2019-04-17 07:49:18 +00:00
|
|
|
__package__ = 'archivebox.core'
|
|
|
|
|
2021-04-10 08:13:43 +00:00
|
|
|
|
2024-08-21 01:31:21 +00:00
|
|
|
from typing import Optional, List, Dict, Iterable
|
2024-05-13 09:37:48 +00:00
|
|
|
from django_stubs_ext.db.models import TypedModelMeta
|
|
|
|
|
2021-04-10 08:13:43 +00:00
|
|
|
import json
|
|
|
|
|
|
|
|
from pathlib import Path
|
2019-04-17 07:49:18 +00:00
|
|
|
|
2021-03-27 05:50:26 +00:00
|
|
|
from django.db import models
|
2024-08-28 10:02:37 +00:00
|
|
|
from django.utils import timezone
|
2020-06-30 10:41:48 +00:00
|
|
|
from django.utils.functional import cached_property
|
2020-10-12 18:47:03 +00:00
|
|
|
from django.utils.text import slugify
|
2021-02-16 20:49:29 +00:00
|
|
|
from django.core.cache import cache
|
2024-08-18 04:56:23 +00:00
|
|
|
from django.urls import reverse, reverse_lazy
|
2020-11-23 18:04:38 +00:00
|
|
|
from django.db.models import Case, When, Value, IntegerField
|
2024-09-05 06:42:36 +00:00
|
|
|
from django.contrib import admin
|
2024-08-21 01:31:21 +00:00
|
|
|
from django.conf import settings
|
2020-09-21 16:50:26 +00:00
|
|
|
|
2024-09-05 06:42:36 +00:00
|
|
|
from abid_utils.models import ABIDModel, ABIDField, AutoDateTimeField
|
2024-05-13 09:37:48 +00:00
|
|
|
|
2021-02-16 20:49:29 +00:00
|
|
|
from ..system import get_dir_size
|
2024-05-13 09:37:48 +00:00
|
|
|
from ..util import parse_date, base_url
|
2019-04-27 21:26:24 +00:00
|
|
|
from ..index.schema import Link
|
2021-04-01 06:22:15 +00:00
|
|
|
from ..index.html import snapshot_icons
|
2024-05-13 09:37:48 +00:00
|
|
|
from ..extractors import ARCHIVE_METHODS_INDEXING_PRECEDENCE, EXTRACTORS
|
|
|
|
|
2020-11-04 12:28:02 +00:00
|
|
|
|
2019-04-17 07:49:18 +00:00
|
|
|
|
2024-05-13 09:37:48 +00:00
|
|
|
# class BaseModel(models.Model):
|
|
|
|
# # TODO: migrate all models to a shared base class with all our standard fields and helpers:
|
2024-09-05 06:42:36 +00:00
|
|
|
# # ulid/created_at/modified_at/created_by/is_deleted/as_json/from_json/etc.
|
2024-05-13 09:37:48 +00:00
|
|
|
# #
|
|
|
|
# # id = models.AutoField(primary_key=True, serialize=False, verbose_name='ID')
|
|
|
|
# # ulid = models.CharField(max_length=26, null=True, blank=True, db_index=True, unique=True)
|
2024-05-12 11:45:34 +00:00
|
|
|
|
2024-05-13 09:37:48 +00:00
|
|
|
# class Meta(TypedModelMeta):
|
|
|
|
# abstract = True
|
2024-05-12 11:45:34 +00:00
|
|
|
|
2024-05-13 09:37:48 +00:00
|
|
|
|
2024-08-20 08:58:19 +00:00
|
|
|
|
|
|
|
|
2024-05-13 09:37:48 +00:00
|
|
|
class Tag(ABIDModel):
|
2020-10-12 18:47:03 +00:00
|
|
|
"""
|
2024-05-15 01:46:38 +00:00
|
|
|
Based on django-taggit model + ABID base.
|
2020-10-12 18:47:03 +00:00
|
|
|
"""
|
2024-05-13 09:37:48 +00:00
|
|
|
abid_prefix = 'tag_'
|
2024-09-05 06:42:36 +00:00
|
|
|
abid_ts_src = 'self.created_at'
|
2024-08-20 08:58:19 +00:00
|
|
|
abid_uri_src = 'self.slug'
|
2024-05-13 09:37:48 +00:00
|
|
|
abid_subtype_src = '"03"'
|
2024-09-04 23:40:15 +00:00
|
|
|
abid_rand_src = 'self.id'
|
2024-09-05 06:42:36 +00:00
|
|
|
abid_drift_allowed = True
|
2024-08-20 08:58:19 +00:00
|
|
|
|
2024-09-04 23:40:15 +00:00
|
|
|
id = models.UUIDField(primary_key=True, default=None, null=False, editable=False, unique=True, verbose_name='ID')
|
2024-05-13 12:12:12 +00:00
|
|
|
abid = ABIDField(prefix=abid_prefix)
|
2021-04-10 11:22:20 +00:00
|
|
|
|
2024-09-04 23:40:15 +00:00
|
|
|
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, null=False, related_name='tag_set')
|
2024-09-05 06:42:36 +00:00
|
|
|
created_at = AutoDateTimeField(default=None, null=False, db_index=True)
|
|
|
|
modified_at = models.DateTimeField(auto_now=True)
|
2024-09-04 23:40:15 +00:00
|
|
|
|
2024-05-13 14:50:07 +00:00
|
|
|
name = models.CharField(unique=True, blank=False, max_length=100)
|
2024-08-20 08:58:19 +00:00
|
|
|
slug = models.SlugField(unique=True, blank=False, max_length=100, editable=False)
|
2024-05-13 14:50:07 +00:00
|
|
|
# slug is autoset on save from name, never set it manually
|
2020-09-21 16:50:26 +00:00
|
|
|
|
2024-08-21 01:31:21 +00:00
|
|
|
snapshot_set: models.Manager['Snapshot']
|
2021-03-27 07:57:05 +00:00
|
|
|
|
2024-05-13 09:37:48 +00:00
|
|
|
class Meta(TypedModelMeta):
|
2020-09-21 16:50:26 +00:00
|
|
|
verbose_name = "Tag"
|
|
|
|
verbose_name_plural = "Tags"
|
|
|
|
|
2020-10-12 18:47:03 +00:00
|
|
|
def __str__(self):
|
|
|
|
return self.name
|
|
|
|
|
|
|
|
def slugify(self, tag, i=None):
|
|
|
|
slug = slugify(tag)
|
|
|
|
if i is not None:
|
|
|
|
slug += "_%d" % i
|
|
|
|
return slug
|
|
|
|
|
|
|
|
def save(self, *args, **kwargs):
|
|
|
|
if self._state.adding and not self.slug:
|
|
|
|
self.slug = self.slugify(self.name)
|
|
|
|
|
2021-03-01 03:54:04 +00:00
|
|
|
# if name is different but slug conficts with another tags slug, append a counter
|
|
|
|
# with transaction.atomic():
|
|
|
|
slugs = set(
|
|
|
|
type(self)
|
|
|
|
._default_manager.filter(slug__startswith=self.slug)
|
|
|
|
.values_list("slug", flat=True)
|
|
|
|
)
|
|
|
|
|
|
|
|
i = None
|
|
|
|
while True:
|
|
|
|
slug = self.slugify(self.name, i)
|
|
|
|
if slug not in slugs:
|
|
|
|
self.slug = slug
|
|
|
|
return super().save(*args, **kwargs)
|
|
|
|
i = 1 if i is None else i+1
|
2020-10-12 18:47:03 +00:00
|
|
|
else:
|
|
|
|
return super().save(*args, **kwargs)
|
2024-08-18 04:56:23 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def api_url(self) -> str:
|
|
|
|
# /api/v1/core/snapshot/{uulid}
|
2024-09-05 10:36:18 +00:00
|
|
|
return reverse_lazy('api-1:get_tag', args=[self.abid]) # + f'?api_key={get_or_create_api_token(request.user)}'
|
2024-08-18 04:56:23 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def api_docs_url(self) -> str:
|
|
|
|
return f'/api/v1/docs#/Core%20Models/api_v1_core_get_tag'
|
2020-10-12 18:47:03 +00:00
|
|
|
|
2024-08-18 07:24:38 +00:00
|
|
|
class SnapshotTag(models.Model):
|
2024-08-20 01:36:20 +00:00
|
|
|
id = models.AutoField(primary_key=True)
|
|
|
|
|
2024-08-20 02:42:25 +00:00
|
|
|
snapshot = models.ForeignKey('Snapshot', db_column='snapshot_id', on_delete=models.CASCADE, to_field='id')
|
|
|
|
tag = models.ForeignKey(Tag, db_column='tag_id', on_delete=models.CASCADE, to_field='id')
|
2020-12-06 17:23:02 +00:00
|
|
|
|
2024-08-20 01:36:20 +00:00
|
|
|
class Meta:
|
|
|
|
db_table = 'core_snapshot_tags'
|
|
|
|
unique_together = [('snapshot', 'tag')]
|
|
|
|
|
2024-08-27 03:16:43 +00:00
|
|
|
|
|
|
|
class SnapshotManager(models.Manager):
|
|
|
|
def get_queryset(self):
|
|
|
|
return super().get_queryset().prefetch_related('tags', 'archiveresult_set') # .annotate(archiveresult_count=models.Count('archiveresult')).distinct()
|
|
|
|
|
|
|
|
|
2024-05-13 09:37:48 +00:00
|
|
|
class Snapshot(ABIDModel):
|
|
|
|
abid_prefix = 'snp_'
|
2024-09-05 06:42:36 +00:00
|
|
|
abid_ts_src = 'self.created_at'
|
2024-05-13 09:37:48 +00:00
|
|
|
abid_uri_src = 'self.url'
|
|
|
|
abid_subtype_src = '"01"'
|
2024-09-04 23:40:15 +00:00
|
|
|
abid_rand_src = 'self.id'
|
2024-09-05 06:42:36 +00:00
|
|
|
abid_drift_allowed = False
|
2024-05-13 09:37:48 +00:00
|
|
|
|
2024-09-04 23:40:15 +00:00
|
|
|
id = models.UUIDField(primary_key=True, default=None, null=False, editable=False, unique=True, verbose_name='ID')
|
2024-05-13 12:12:12 +00:00
|
|
|
abid = ABIDField(prefix=abid_prefix)
|
2019-04-17 07:49:18 +00:00
|
|
|
|
2024-09-04 23:40:15 +00:00
|
|
|
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, null=False, related_name='snapshot_set')
|
2024-09-05 06:42:36 +00:00
|
|
|
created_at = AutoDateTimeField(default=None, null=False, db_index=True) # loaded from self._init_timestamp
|
|
|
|
modified_at = models.DateTimeField(auto_now=True)
|
2019-04-17 07:49:18 +00:00
|
|
|
|
2024-09-04 00:11:10 +00:00
|
|
|
# legacy ts fields
|
2024-09-05 06:42:36 +00:00
|
|
|
bookmarked_at = AutoDateTimeField(default=None, null=False, editable=True, db_index=True)
|
|
|
|
downloaded_at = models.DateTimeField(default=None, null=True, editable=False, db_index=True, blank=True)
|
2019-04-17 07:49:18 +00:00
|
|
|
|
2024-09-04 00:11:10 +00:00
|
|
|
url = models.URLField(unique=True, db_index=True)
|
|
|
|
timestamp = models.CharField(max_length=32, unique=True, db_index=True, editable=False)
|
|
|
|
tags = models.ManyToManyField(Tag, blank=True, through=SnapshotTag, related_name='snapshot_set', through_fields=('snapshot', 'tag'))
|
|
|
|
title = models.CharField(max_length=512, null=True, blank=True, db_index=True)
|
|
|
|
|
2024-09-05 06:42:36 +00:00
|
|
|
keys = ('url', 'timestamp', 'title', 'tags', 'downloaded_at')
|
2019-04-17 07:49:18 +00:00
|
|
|
|
2024-08-21 01:31:21 +00:00
|
|
|
archiveresult_set: models.Manager['ArchiveResult']
|
|
|
|
|
2024-08-27 03:16:43 +00:00
|
|
|
objects = SnapshotManager()
|
|
|
|
|
2024-09-05 06:42:36 +00:00
|
|
|
def save(self, *args, **kwargs):
|
|
|
|
if not self.bookmarked_at:
|
|
|
|
self.bookmarked_at = self.created_at or self._init_timestamp
|
|
|
|
|
|
|
|
super().save(*args, **kwargs)
|
|
|
|
|
|
|
|
|
2019-04-22 17:20:19 +00:00
|
|
|
def __repr__(self) -> str:
|
2024-08-20 08:58:19 +00:00
|
|
|
title = (self.title_stripped or '-')[:64]
|
|
|
|
return f'[{self.timestamp}] {self.url[:64]} ({title})'
|
2019-04-22 17:20:19 +00:00
|
|
|
|
|
|
|
def __str__(self) -> str:
|
2024-08-20 08:58:19 +00:00
|
|
|
title = (self.title_stripped or '-')[:64]
|
|
|
|
return f'[{self.timestamp}] {self.url[:64]} ({title})'
|
2019-04-22 17:20:19 +00:00
|
|
|
|
2019-04-17 07:49:18 +00:00
|
|
|
@classmethod
|
|
|
|
def from_json(cls, info: dict):
|
2019-04-17 07:50:41 +00:00
|
|
|
info = {k: v for k, v in info.items() if k in cls.keys}
|
2019-04-17 07:49:18 +00:00
|
|
|
return cls(**info)
|
|
|
|
|
|
|
|
def as_json(self, *args) -> dict:
|
2019-04-17 07:50:41 +00:00
|
|
|
args = args or self.keys
|
2019-04-17 07:49:18 +00:00
|
|
|
return {
|
2024-08-27 03:16:43 +00:00
|
|
|
key: getattr(self, key) if key != 'tags' else self.tags_str(nocache=False)
|
2020-11-23 18:04:38 +00:00
|
|
|
for key in args
|
2019-04-17 07:49:18 +00:00
|
|
|
}
|
2019-04-22 17:20:19 +00:00
|
|
|
|
|
|
|
def as_link(self) -> Link:
|
|
|
|
return Link.from_json(self.as_json())
|
|
|
|
|
2020-08-28 16:08:03 +00:00
|
|
|
def as_link_with_details(self) -> Link:
|
|
|
|
from ..index import load_link_details
|
|
|
|
return load_link_details(self.as_link())
|
2020-11-23 18:04:38 +00:00
|
|
|
|
2024-09-05 06:42:36 +00:00
|
|
|
@admin.display(description='Tags')
|
2024-05-13 09:37:48 +00:00
|
|
|
def tags_str(self, nocache=True) -> str | None:
|
2024-08-27 03:16:43 +00:00
|
|
|
calc_tags_str = lambda: ','.join(sorted(tag.name for tag in self.tags.all()))
|
2024-09-05 06:42:36 +00:00
|
|
|
cache_key = f'{self.pk}-{(self.downloaded_at or self.bookmarked_at).timestamp()}-tags'
|
2024-08-27 03:16:43 +00:00
|
|
|
|
|
|
|
if hasattr(self, '_prefetched_objects_cache') and 'tags' in self._prefetched_objects_cache:
|
|
|
|
# tags are pre-fetched already, use them directly (best because db is always freshest)
|
|
|
|
tags_str = calc_tags_str()
|
|
|
|
return tags_str
|
|
|
|
|
2021-03-27 08:30:15 +00:00
|
|
|
if nocache:
|
|
|
|
tags_str = calc_tags_str()
|
|
|
|
cache.set(cache_key, tags_str)
|
|
|
|
return tags_str
|
2021-02-16 20:49:29 +00:00
|
|
|
return cache.get_or_set(cache_key, calc_tags_str)
|
2020-08-28 16:08:03 +00:00
|
|
|
|
2021-04-01 06:22:15 +00:00
|
|
|
def icons(self) -> str:
|
|
|
|
return snapshot_icons(self)
|
2024-08-18 04:56:23 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def api_url(self) -> str:
|
|
|
|
# /api/v1/core/snapshot/{uulid}
|
2024-09-05 10:36:18 +00:00
|
|
|
return reverse_lazy('api-1:get_snapshot', args=[self.abid]) # + f'?api_key={get_or_create_api_token(request.user)}'
|
2024-08-18 04:56:23 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def api_docs_url(self) -> str:
|
|
|
|
return f'/api/v1/docs#/Core%20Models/api_v1_core_get_snapshot'
|
2024-08-20 08:58:36 +00:00
|
|
|
|
2024-09-05 10:36:18 +00:00
|
|
|
def get_absolute_url(self):
|
|
|
|
return f'/{self.archive_path}'
|
|
|
|
|
2024-08-20 08:58:36 +00:00
|
|
|
@cached_property
|
|
|
|
def title_stripped(self) -> str:
|
|
|
|
return (self.title or '').replace("\n", " ").replace("\r", "")
|
2021-04-01 06:22:15 +00:00
|
|
|
|
2021-04-10 08:13:43 +00:00
|
|
|
@cached_property
|
|
|
|
def extension(self) -> str:
|
|
|
|
from ..util import extension
|
|
|
|
return extension(self.url)
|
|
|
|
|
2020-06-30 10:41:48 +00:00
|
|
|
@cached_property
|
2019-04-23 01:40:42 +00:00
|
|
|
def bookmarked(self):
|
|
|
|
return parse_date(self.timestamp)
|
|
|
|
|
2021-02-16 01:44:08 +00:00
|
|
|
@cached_property
|
|
|
|
def bookmarked_date(self):
|
|
|
|
# TODO: remove this
|
|
|
|
return self.bookmarked
|
|
|
|
|
2020-06-30 10:41:48 +00:00
|
|
|
@cached_property
|
2019-04-22 17:20:19 +00:00
|
|
|
def is_archived(self):
|
|
|
|
return self.as_link().is_archived
|
|
|
|
|
2020-06-30 10:41:48 +00:00
|
|
|
@cached_property
|
2024-05-13 09:37:48 +00:00
|
|
|
def num_outputs(self) -> int:
|
2024-08-27 03:16:43 +00:00
|
|
|
# DONT DO THIS: it will trigger a separate query for every snapshot
|
|
|
|
# return self.archiveresult_set.filter(status='succeeded').count()
|
|
|
|
# this is better:
|
|
|
|
return sum((1 for result in self.archiveresult_set.all() if result.status == 'succeeded'))
|
2019-04-22 17:20:19 +00:00
|
|
|
|
2020-06-30 10:41:48 +00:00
|
|
|
@cached_property
|
2019-04-22 17:20:19 +00:00
|
|
|
def base_url(self):
|
2021-02-16 01:44:08 +00:00
|
|
|
return base_url(self.url)
|
2019-05-01 03:13:04 +00:00
|
|
|
|
2020-06-30 10:41:48 +00:00
|
|
|
@cached_property
|
2019-05-01 03:13:04 +00:00
|
|
|
def link_dir(self):
|
2024-08-21 01:31:21 +00:00
|
|
|
return str(settings.CONFIG.ARCHIVE_DIR / self.timestamp)
|
2020-06-26 03:32:01 +00:00
|
|
|
|
2020-06-30 10:41:48 +00:00
|
|
|
@cached_property
|
2020-06-26 03:32:01 +00:00
|
|
|
def archive_path(self):
|
2024-08-21 01:31:21 +00:00
|
|
|
return '{}/{}'.format(settings.CONFIG.ARCHIVE_DIR_NAME, self.timestamp)
|
2020-06-26 03:32:01 +00:00
|
|
|
|
2020-06-30 10:41:48 +00:00
|
|
|
@cached_property
|
2020-06-26 03:32:01 +00:00
|
|
|
def archive_size(self):
|
2024-09-05 06:42:36 +00:00
|
|
|
cache_key = f'{str(self.pk)[:12]}-{(self.downloaded_at or self.bookmarked_at).timestamp()}-size'
|
2021-02-16 20:49:29 +00:00
|
|
|
|
|
|
|
def calc_dir_size():
|
|
|
|
try:
|
|
|
|
return get_dir_size(self.link_dir)[0]
|
|
|
|
except Exception:
|
|
|
|
return 0
|
|
|
|
|
|
|
|
return cache.get_or_set(cache_key, calc_dir_size)
|
2020-06-30 10:41:48 +00:00
|
|
|
|
|
|
|
@cached_property
|
2021-04-10 08:13:43 +00:00
|
|
|
def thumbnail_url(self) -> Optional[str]:
|
2024-08-27 03:16:43 +00:00
|
|
|
if hasattr(self, '_prefetched_objects_cache') and 'archiveresult_set' in self._prefetched_objects_cache:
|
|
|
|
result = (sorted(
|
|
|
|
(
|
|
|
|
result
|
|
|
|
for result in self.archiveresult_set.all()
|
|
|
|
if result.extractor == 'screenshot' and result.status =='succeeded' and result.output
|
|
|
|
),
|
2024-09-05 06:42:36 +00:00
|
|
|
key=lambda result: result.created_at,
|
2024-08-27 03:16:43 +00:00
|
|
|
) or [None])[-1]
|
|
|
|
else:
|
|
|
|
result = self.archiveresult_set.filter(
|
|
|
|
extractor='screenshot',
|
|
|
|
status='succeeded'
|
|
|
|
).only('output').last()
|
|
|
|
|
2021-04-10 08:13:43 +00:00
|
|
|
if result:
|
|
|
|
return reverse('Snapshot', args=[f'{str(self.timestamp)}/{result.output}'])
|
|
|
|
return None
|
|
|
|
|
|
|
|
@cached_property
|
2024-05-13 09:37:48 +00:00
|
|
|
def headers(self) -> Optional[Dict[str, str]]:
|
2021-04-10 08:13:43 +00:00
|
|
|
try:
|
2021-04-10 11:22:32 +00:00
|
|
|
return json.loads((Path(self.link_dir) / 'headers.json').read_text(encoding='utf-8').strip())
|
2021-04-10 08:13:43 +00:00
|
|
|
except Exception:
|
|
|
|
pass
|
|
|
|
return None
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def status_code(self) -> Optional[str]:
|
2024-08-21 01:31:21 +00:00
|
|
|
return self.headers.get('Status-Code') if self.headers else None
|
2021-04-10 08:13:43 +00:00
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def history(self) -> dict:
|
2020-11-28 06:05:53 +00:00
|
|
|
# TODO: use ArchiveResult for this instead of json
|
2020-11-28 06:14:45 +00:00
|
|
|
return self.as_link_with_details().history
|
2020-06-30 10:41:48 +00:00
|
|
|
|
|
|
|
@cached_property
|
2021-04-10 08:13:43 +00:00
|
|
|
def latest_title(self) -> Optional[str]:
|
2021-02-16 20:49:53 +00:00
|
|
|
if self.title:
|
2021-02-18 07:33:28 +00:00
|
|
|
return self.title # whoopdedoo that was easy
|
2021-02-16 20:49:53 +00:00
|
|
|
|
2024-08-27 03:16:43 +00:00
|
|
|
# check if ArchiveResult set has already been prefetched, if so use it instead of fetching it from db again
|
|
|
|
if hasattr(self, '_prefetched_objects_cache') and 'archiveresult_set' in self._prefetched_objects_cache:
|
|
|
|
try:
|
|
|
|
return (sorted(
|
|
|
|
(
|
|
|
|
result.output.strip()
|
|
|
|
for result in self.archiveresult_set.all()
|
|
|
|
if result.extractor == 'title' and result.status =='succeeded' and result.output
|
|
|
|
),
|
|
|
|
key=lambda title: len(title),
|
|
|
|
) or [None])[-1]
|
|
|
|
except IndexError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2021-02-16 20:49:53 +00:00
|
|
|
try:
|
2021-02-18 07:33:28 +00:00
|
|
|
# take longest successful title from ArchiveResult db history
|
|
|
|
return sorted(
|
|
|
|
self.archiveresult_set\
|
|
|
|
.filter(extractor='title', status='succeeded', output__isnull=False)\
|
|
|
|
.values_list('output', flat=True),
|
|
|
|
key=lambda r: len(r),
|
|
|
|
)[-1]
|
|
|
|
except IndexError:
|
2021-02-16 20:49:53 +00:00
|
|
|
pass
|
|
|
|
|
2021-02-18 07:33:28 +00:00
|
|
|
try:
|
|
|
|
# take longest successful title from Link json index file history
|
|
|
|
return sorted(
|
|
|
|
(
|
|
|
|
result.output.strip()
|
|
|
|
for result in self.history['title']
|
|
|
|
if result.status == 'succeeded' and result.output.strip()
|
|
|
|
),
|
|
|
|
key=lambda r: len(r),
|
|
|
|
)[-1]
|
|
|
|
except (KeyError, IndexError):
|
|
|
|
pass
|
2021-02-16 20:49:53 +00:00
|
|
|
|
2020-06-30 10:41:48 +00:00
|
|
|
return None
|
2020-10-12 18:47:03 +00:00
|
|
|
|
2024-08-21 01:31:21 +00:00
|
|
|
def save_tags(self, tags: Iterable[str]=()) -> None:
|
2020-10-12 18:47:03 +00:00
|
|
|
tags_id = []
|
|
|
|
for tag in tags:
|
2021-02-18 07:33:42 +00:00
|
|
|
if tag.strip():
|
2024-05-13 12:12:12 +00:00
|
|
|
tags_id.append(Tag.objects.get_or_create(name=tag)[0].pk)
|
2020-10-12 18:47:03 +00:00
|
|
|
self.tags.clear()
|
|
|
|
self.tags.add(*tags_id)
|
2020-11-03 14:54:02 +00:00
|
|
|
|
2020-12-06 17:23:02 +00:00
|
|
|
|
2024-05-13 09:37:48 +00:00
|
|
|
# def get_storage_dir(self, create=True, symlink=True) -> Path:
|
2024-09-05 06:42:36 +00:00
|
|
|
# date_str = self.bookmarked_at.strftime('%Y%m%d')
|
2024-05-13 09:37:48 +00:00
|
|
|
# domain_str = domain(self.url)
|
2024-08-21 01:31:21 +00:00
|
|
|
# abs_storage_dir = Path(settings.CONFIG.ARCHIVE_DIR) / 'snapshots' / date_str / domain_str / str(self.ulid)
|
2024-05-12 12:21:58 +00:00
|
|
|
|
2024-05-13 09:37:48 +00:00
|
|
|
# if create and not abs_storage_dir.is_dir():
|
|
|
|
# abs_storage_dir.mkdir(parents=True, exist_ok=True)
|
2024-05-12 12:21:58 +00:00
|
|
|
|
2024-05-13 09:37:48 +00:00
|
|
|
# if symlink:
|
|
|
|
# LINK_PATHS = [
|
2024-08-21 01:31:21 +00:00
|
|
|
# Path(settings.CONFIG.ARCHIVE_DIR).parent / 'index' / 'all_by_id' / str(self.ulid),
|
|
|
|
# # Path(settings.CONFIG.ARCHIVE_DIR).parent / 'index' / 'snapshots_by_id' / str(self.ulid),
|
|
|
|
# Path(settings.CONFIG.ARCHIVE_DIR).parent / 'index' / 'snapshots_by_date' / date_str / domain_str / str(self.ulid),
|
|
|
|
# Path(settings.CONFIG.ARCHIVE_DIR).parent / 'index' / 'snapshots_by_domain' / domain_str / date_str / str(self.ulid),
|
2024-05-13 09:37:48 +00:00
|
|
|
# ]
|
|
|
|
# for link_path in LINK_PATHS:
|
|
|
|
# link_path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
# try:
|
|
|
|
# link_path.symlink_to(abs_storage_dir)
|
|
|
|
# except FileExistsError:
|
|
|
|
# link_path.unlink()
|
|
|
|
# link_path.symlink_to(abs_storage_dir)
|
|
|
|
|
|
|
|
# return abs_storage_dir
|
2024-05-12 12:21:58 +00:00
|
|
|
|
|
|
|
|
2020-11-23 18:04:38 +00:00
|
|
|
class ArchiveResultManager(models.Manager):
|
|
|
|
def indexable(self, sorted: bool = True):
|
2024-08-27 03:16:43 +00:00
|
|
|
"""Return only ArchiveResults containing text suitable for full-text search (sorted in order of typical result quality)"""
|
|
|
|
|
2020-11-23 18:04:38 +00:00
|
|
|
INDEXABLE_METHODS = [ r[0] for r in ARCHIVE_METHODS_INDEXING_PRECEDENCE ]
|
2024-08-27 03:16:43 +00:00
|
|
|
qs = self.get_queryset().filter(extractor__in=INDEXABLE_METHODS, status='succeeded')
|
2020-11-03 14:54:02 +00:00
|
|
|
|
2020-11-23 18:04:38 +00:00
|
|
|
if sorted:
|
2024-08-27 03:16:43 +00:00
|
|
|
precedence = [
|
|
|
|
When(extractor=method, then=Value(precedence))
|
|
|
|
for method, precedence in ARCHIVE_METHODS_INDEXING_PRECEDENCE
|
|
|
|
]
|
|
|
|
qs = qs.annotate(
|
|
|
|
indexing_precedence=Case(
|
|
|
|
*precedence,
|
|
|
|
default=Value(1000),
|
|
|
|
output_field=IntegerField()
|
|
|
|
)
|
|
|
|
).order_by('indexing_precedence')
|
2020-11-23 18:04:38 +00:00
|
|
|
return qs
|
2020-12-06 17:23:02 +00:00
|
|
|
|
2024-05-13 09:37:48 +00:00
|
|
|
class ArchiveResult(ABIDModel):
|
|
|
|
abid_prefix = 'res_'
|
2024-09-05 06:42:36 +00:00
|
|
|
abid_ts_src = 'self.snapshot.created_at'
|
2024-05-13 09:37:48 +00:00
|
|
|
abid_uri_src = 'self.snapshot.url'
|
|
|
|
abid_subtype_src = 'self.extractor'
|
2024-09-04 23:40:15 +00:00
|
|
|
abid_rand_src = 'self.id'
|
2024-09-05 06:42:36 +00:00
|
|
|
abid_drift_allowed = True
|
2024-08-22 22:36:02 +00:00
|
|
|
|
|
|
|
EXTRACTOR_CHOICES = (
|
|
|
|
('htmltotext', 'htmltotext'),
|
|
|
|
('git', 'git'),
|
|
|
|
('singlefile', 'singlefile'),
|
|
|
|
('media', 'media'),
|
|
|
|
('archive_org', 'archive_org'),
|
|
|
|
('readability', 'readability'),
|
|
|
|
('mercury', 'mercury'),
|
|
|
|
('favicon', 'favicon'),
|
|
|
|
('pdf', 'pdf'),
|
|
|
|
('headers', 'headers'),
|
|
|
|
('screenshot', 'screenshot'),
|
|
|
|
('dom', 'dom'),
|
|
|
|
('title', 'title'),
|
|
|
|
('wget', 'wget'),
|
|
|
|
)
|
|
|
|
STATUS_CHOICES = [
|
|
|
|
("succeeded", "succeeded"),
|
|
|
|
("failed", "failed"),
|
|
|
|
("skipped", "skipped")
|
|
|
|
]
|
2024-05-12 05:28:59 +00:00
|
|
|
|
2024-09-04 23:40:15 +00:00
|
|
|
id = models.UUIDField(primary_key=True, default=None, null=False, editable=False, unique=True, verbose_name='ID')
|
2024-05-13 12:12:12 +00:00
|
|
|
abid = ABIDField(prefix=abid_prefix)
|
2021-02-16 20:54:27 +00:00
|
|
|
|
2024-09-04 23:40:15 +00:00
|
|
|
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, null=False, related_name='archiveresult_set')
|
2024-09-05 06:42:36 +00:00
|
|
|
created_at = AutoDateTimeField(default=None, null=False, db_index=True)
|
|
|
|
modified_at = models.DateTimeField(auto_now=True)
|
2024-09-04 00:11:10 +00:00
|
|
|
|
2024-08-18 08:07:21 +00:00
|
|
|
snapshot = models.ForeignKey(Snapshot, on_delete=models.CASCADE, to_field='id', db_column='snapshot_id')
|
2024-08-18 07:24:38 +00:00
|
|
|
|
2024-05-12 05:28:59 +00:00
|
|
|
extractor = models.CharField(choices=EXTRACTOR_CHOICES, max_length=32)
|
2024-05-13 09:37:48 +00:00
|
|
|
cmd = models.JSONField()
|
2020-11-27 05:01:34 +00:00
|
|
|
pwd = models.CharField(max_length=256)
|
2021-02-16 20:54:27 +00:00
|
|
|
cmd_version = models.CharField(max_length=128, default=None, null=True, blank=True)
|
|
|
|
output = models.CharField(max_length=1024)
|
|
|
|
start_ts = models.DateTimeField(db_index=True)
|
2020-11-04 12:28:02 +00:00
|
|
|
end_ts = models.DateTimeField()
|
2020-11-23 23:28:43 +00:00
|
|
|
status = models.CharField(max_length=16, choices=STATUS_CHOICES)
|
2020-11-04 15:31:20 +00:00
|
|
|
|
2020-11-23 18:04:38 +00:00
|
|
|
objects = ArchiveResultManager()
|
|
|
|
|
2024-05-13 09:37:48 +00:00
|
|
|
class Meta(TypedModelMeta):
|
2024-08-20 08:58:19 +00:00
|
|
|
verbose_name = 'Archive Result'
|
|
|
|
verbose_name_plural = 'Archive Results Log'
|
2024-08-18 05:58:35 +00:00
|
|
|
|
2024-05-13 09:37:48 +00:00
|
|
|
|
2020-11-04 15:31:20 +00:00
|
|
|
def __str__(self):
|
2024-09-05 06:42:36 +00:00
|
|
|
# return f'[{self.abid}] 📅 {self.start_ts.strftime("%Y-%m-%d %H:%M")} 📄 {self.extractor} {self.snapshot.url}'
|
2020-11-04 15:31:20 +00:00
|
|
|
return self.extractor
|
2024-05-12 05:28:59 +00:00
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def snapshot_dir(self):
|
|
|
|
return Path(self.snapshot.link_dir)
|
|
|
|
|
2024-08-18 04:56:23 +00:00
|
|
|
@property
|
|
|
|
def api_url(self) -> str:
|
|
|
|
# /api/v1/core/archiveresult/{uulid}
|
2024-09-05 10:36:18 +00:00
|
|
|
return reverse_lazy('api-1:get_archiveresult', args=[self.abid]) # + f'?api_key={get_or_create_api_token(request.user)}'
|
2024-08-18 04:56:23 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def api_docs_url(self) -> str:
|
|
|
|
return f'/api/v1/docs#/Core%20Models/api_v1_core_get_archiveresult'
|
2024-09-05 10:36:18 +00:00
|
|
|
|
|
|
|
def get_absolute_url(self):
|
|
|
|
return f'/{self.snapshot.archive_path}/{self.output_path()}'
|
2024-05-12 05:28:59 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def extractor_module(self):
|
|
|
|
return EXTRACTORS[self.extractor]
|
|
|
|
|
|
|
|
def output_path(self) -> str:
|
|
|
|
"""return the canonical output filename or directory name within the snapshot dir"""
|
|
|
|
return self.extractor_module.get_output_path()
|
|
|
|
|
|
|
|
def embed_path(self) -> str:
|
|
|
|
"""
|
|
|
|
return the actual runtime-calculated path to the file on-disk that
|
|
|
|
should be used for user-facing iframe embeds of this result
|
|
|
|
"""
|
|
|
|
|
2024-08-21 01:31:21 +00:00
|
|
|
if get_embed_path_func := getattr(self.extractor_module, 'get_embed_path', None):
|
|
|
|
return get_embed_path_func(self)
|
2024-05-12 05:28:59 +00:00
|
|
|
|
|
|
|
return self.extractor_module.get_output_path()
|
|
|
|
|
|
|
|
def legacy_output_path(self):
|
|
|
|
link = self.snapshot.as_link()
|
|
|
|
return link.canonical_outputs().get(f'{self.extractor}_path')
|
|
|
|
|
|
|
|
def output_exists(self) -> bool:
|
|
|
|
return Path(self.output_path()).exists()
|
2024-05-12 12:21:58 +00:00
|
|
|
|
|
|
|
|
2024-05-13 09:37:48 +00:00
|
|
|
# def get_storage_dir(self, create=True, symlink=True):
|
2024-09-05 06:42:36 +00:00
|
|
|
# date_str = self.snapshot.bookmarked_at.strftime('%Y%m%d')
|
2024-05-13 09:37:48 +00:00
|
|
|
# domain_str = domain(self.snapshot.url)
|
2024-08-21 01:31:21 +00:00
|
|
|
# abs_storage_dir = Path(settings.CONFIG.ARCHIVE_DIR) / 'results' / date_str / domain_str / self.extractor / str(self.ulid)
|
2024-05-13 09:37:48 +00:00
|
|
|
|
|
|
|
# if create and not abs_storage_dir.is_dir():
|
|
|
|
# abs_storage_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
|
|
# if symlink:
|
|
|
|
# LINK_PATHS = [
|
2024-08-21 01:31:21 +00:00
|
|
|
# Path(settings.CONFIG.ARCHIVE_DIR).parent / 'index' / 'all_by_id' / str(self.ulid),
|
|
|
|
# # Path(settings.CONFIG.ARCHIVE_DIR).parent / 'index' / 'results_by_id' / str(self.ulid),
|
|
|
|
# # Path(settings.CONFIG.ARCHIVE_DIR).parent / 'index' / 'results_by_date' / date_str / domain_str / self.extractor / str(self.ulid),
|
|
|
|
# Path(settings.CONFIG.ARCHIVE_DIR).parent / 'index' / 'results_by_domain' / domain_str / date_str / self.extractor / str(self.ulid),
|
|
|
|
# Path(settings.CONFIG.ARCHIVE_DIR).parent / 'index' / 'results_by_type' / self.extractor / date_str / domain_str / str(self.ulid),
|
2024-05-13 09:37:48 +00:00
|
|
|
# ]
|
|
|
|
# for link_path in LINK_PATHS:
|
|
|
|
# link_path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
# try:
|
|
|
|
# link_path.symlink_to(abs_storage_dir)
|
|
|
|
# except FileExistsError:
|
|
|
|
# link_path.unlink()
|
|
|
|
# link_path.symlink_to(abs_storage_dir)
|
|
|
|
|
|
|
|
# return abs_storage_dir
|
|
|
|
|
|
|
|
# def symlink_index(self, create=True):
|
|
|
|
# abs_result_dir = self.get_storage_dir(create=create)
|