admin.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. __package__ = 'archivebox.core'
  2. from io import StringIO
  3. from pathlib import Path
  4. from contextlib import redirect_stdout
  5. from datetime import datetime, timezone
  6. from django.contrib import admin
  7. from django.db.models import Count
  8. from django.urls import path
  9. from django.utils.html import format_html
  10. from django.utils.safestring import mark_safe
  11. from django.shortcuts import render, redirect
  12. from django.contrib.auth import get_user_model
  13. from django import forms
  14. from signal_webhooks.admin import WebhookAdmin, get_webhook_model
  15. # from plugantic.admin import CustomPlugin
  16. from ..util import htmldecode, urldecode, ansi_to_html
  17. from core.models import Snapshot, ArchiveResult, Tag
  18. from core.forms import AddLinkForm
  19. from core.mixins import SearchResultsAdminMixin
  20. from api.models import APIToken
  21. from index.html import snapshot_icons
  22. from logging_util import printable_filesize
  23. from main import add, remove
  24. from extractors import archive_links
  25. from config import (
  26. OUTPUT_DIR,
  27. SNAPSHOTS_PER_PAGE,
  28. VERSION,
  29. VERSIONS_AVAILABLE,
  30. CAN_UPGRADE
  31. )
  32. GLOBAL_CONTEXT = {'VERSION': VERSION, 'VERSIONS_AVAILABLE': VERSIONS_AVAILABLE, 'CAN_UPGRADE': CAN_UPGRADE}
  33. # Admin URLs
  34. # /admin/
  35. # /admin/login/
  36. # /admin/core/
  37. # /admin/core/snapshot/
  38. # /admin/core/snapshot/:uuid/
  39. # /admin/core/tag/
  40. # /admin/core/tag/:uuid/
  41. # TODO: https://stackoverflow.com/questions/40760880/add-custom-button-to-django-admin-panel
  42. class ArchiveBoxAdmin(admin.AdminSite):
  43. site_header = 'ArchiveBox'
  44. index_title = 'Links'
  45. site_title = 'Index'
  46. namespace = 'admin'
  47. def get_urls(self):
  48. return [
  49. path('core/snapshot/add/', self.add_view, name='Add'),
  50. ] + super().get_urls()
  51. def add_view(self, request):
  52. if not request.user.is_authenticated:
  53. return redirect(f'/admin/login/?next={request.path}')
  54. request.current_app = self.name
  55. context = {
  56. **self.each_context(request),
  57. 'title': 'Add URLs',
  58. }
  59. if request.method == 'GET':
  60. context['form'] = AddLinkForm()
  61. elif request.method == 'POST':
  62. form = AddLinkForm(request.POST)
  63. if form.is_valid():
  64. url = form.cleaned_data["url"]
  65. print(f'[+] Adding URL: {url}')
  66. depth = 0 if form.cleaned_data["depth"] == "0" else 1
  67. input_kwargs = {
  68. "urls": url,
  69. "depth": depth,
  70. "update_all": False,
  71. "out_dir": OUTPUT_DIR,
  72. }
  73. add_stdout = StringIO()
  74. with redirect_stdout(add_stdout):
  75. add(**input_kwargs)
  76. print(add_stdout.getvalue())
  77. context.update({
  78. "stdout": ansi_to_html(add_stdout.getvalue().strip()),
  79. "form": AddLinkForm()
  80. })
  81. else:
  82. context["form"] = form
  83. return render(template_name='add.html', request=request, context=context)
  84. archivebox_admin = ArchiveBoxAdmin()
  85. archivebox_admin.register(get_user_model())
  86. archivebox_admin.register(APIToken)
  87. archivebox_admin.register(get_webhook_model(), WebhookAdmin)
  88. archivebox_admin.disable_action('delete_selected')
  89. # archivebox_admin.register(CustomPlugin)
  90. # patch admin with methods to add data views (implemented by admin_data_views package)
  91. ############### Additional sections are defined in settings.ADMIN_DATA_VIEWS #########
  92. from admin_data_views.admin import get_app_list, admin_data_index_view, get_admin_data_urls, get_urls
  93. archivebox_admin.get_app_list = get_app_list.__get__(archivebox_admin, ArchiveBoxAdmin)
  94. archivebox_admin.admin_data_index_view = admin_data_index_view.__get__(archivebox_admin, ArchiveBoxAdmin)
  95. archivebox_admin.get_admin_data_urls = get_admin_data_urls.__get__(archivebox_admin, ArchiveBoxAdmin)
  96. archivebox_admin.get_urls = get_urls(archivebox_admin.get_urls).__get__(archivebox_admin, ArchiveBoxAdmin)
  97. class ArchiveResultInline(admin.TabularInline):
  98. model = ArchiveResult
  99. class TagInline(admin.TabularInline):
  100. model = Snapshot.tags.through
  101. from django.contrib.admin.helpers import ActionForm
  102. from django.contrib.admin.widgets import AutocompleteSelectMultiple
  103. class AutocompleteTags:
  104. model = Tag
  105. search_fields = ['name']
  106. name = 'tags'
  107. remote_field = TagInline
  108. class AutocompleteTagsAdminStub:
  109. name = 'admin'
  110. class SnapshotActionForm(ActionForm):
  111. tags = forms.ModelMultipleChoiceField(
  112. queryset=Tag.objects.all(),
  113. required=False,
  114. widget=AutocompleteSelectMultiple(
  115. AutocompleteTags(),
  116. AutocompleteTagsAdminStub(),
  117. ),
  118. )
  119. # TODO: allow selecting actions for specific extractors? is this useful?
  120. # EXTRACTOR_CHOICES = [
  121. # (name, name.title())
  122. # for name, _, _ in get_default_archive_methods()
  123. # ]
  124. # extractor = forms.ChoiceField(
  125. # choices=EXTRACTOR_CHOICES,
  126. # required=False,
  127. # widget=forms.MultileChoiceField(attrs={'class': "form-control"})
  128. # )
  129. def get_abid_info(self, obj):
  130. return format_html(
  131. # URL Hash: <code style="font-size: 10px; user-select: all">{}</code><br/>
  132. '''
  133. &nbsp; &nbsp; DB ID:&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; <code style="font-size: 16px; user-select: all; border-radius: 8px; background-color: #fdd; padding: 1px 4px; border: 1px solid #aaa; margin-bottom: 8px; display: inline-block; vertical-align: top;"><b>{}</b></code><br/>
  134. &nbsp; &nbsp; &nbsp; &nbsp;.id: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; <code style="font-size: 10px; user-select: all">{}</code> &nbsp; &nbsp;<br/>
  135. &nbsp; &nbsp; &nbsp; &nbsp;.uuid: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<code style="font-size: 10px; user-select: all">{}</code> &nbsp; &nbsp;<br/>
  136. <br/>
  137. <div style="opacity: 0.8">
  138. &nbsp; &nbsp; ABID: &nbsp; &nbsp; &nbsp; &nbsp; <small style="opacity: 0.5">{}_</small><code style="font-size: 16px; user-select: all; border-radius: 8px; background-color: #ddf; padding: 1px 4px; border: 1px solid #aaa; margin-bottom: 8px; display: inline-block; vertical-align: top;"><b>{}</b></code> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; <a href="{}" style="font-size: 1.5em; font-family: monospace;">/api/v1 GET JSON</a> &nbsp; &nbsp; <a href="{}" style="color: limegreen; font-size: 1.2em; vertical-align: 1px; font-family: monospace;">API DOCS</a><br/>
  139. &nbsp; &nbsp; &nbsp; &nbsp; TS: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<code style="font-size: 10px; user-select: all"><b>{}</b></code> &nbsp; &nbsp; &nbsp;&nbsp; ({})<br/>
  140. &nbsp; &nbsp; &nbsp; &nbsp; URI: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <code style="font-size: 10px; user-select: all"><b>{}</b></code> &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; (<span style="display:inline-block; vertical-align: -4px; user-select: all; width: 230px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{}</span>)<br/>
  141. &nbsp; &nbsp; &nbsp; &nbsp; SUBTYPE: &nbsp; &nbsp; &nbsp; <code style="font-size: 10px; user-select: all"><b>{}</b></code> ({}) &nbsp; &nbsp;
  142. &nbsp; RAND: &nbsp; <code style="font-size: 10px; user-select: all"><b>{}</b></code> ({}) &nbsp; &nbsp;
  143. &nbsp; SALT: &nbsp; <code style="font-size: 10px; user-select: all"><b style="display:inline-block; user-select: all; width: 50px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{}</b></code>
  144. <br/><hr/>
  145. &nbsp; &nbsp; &nbsp; &nbsp; <small style="opacity: 0.8">.ulid: &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <code style="font-size: 10px; user-select: all">{}</code></small><br/>
  146. &nbsp; &nbsp; &nbsp; &nbsp; <small style="opacity: 0.8">.uuid: &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<code style="font-size: 10px; user-select: all">{}</code></small><br/><br/>
  147. </div>
  148. ''',
  149. obj.pk,
  150. getattr(obj, 'id', str(getattr(obj, 'old_id', '')) + ' (.old_id)'),
  151. getattr(obj, 'uuid', str(getattr(obj, 'id', '')) +' (.id)'),
  152. *obj.abid.split('_', 1), obj.api_url, obj.api_docs_url,
  153. obj.ABID.ts, obj.abid_values['ts'].isoformat() if isinstance(obj.abid_values['ts'], datetime) else obj.abid_values['ts'],
  154. obj.ABID.uri, str(obj.abid_values['uri']),
  155. obj.ABID.subtype, str(obj.abid_values['subtype']),
  156. obj.ABID.rand, str(obj.abid_values['rand'])[-7:],
  157. obj.ABID.uri_salt,
  158. obj.ABID.ulid,
  159. obj.ABID.uuid,
  160. )
  161. @admin.register(Snapshot, site=archivebox_admin)
  162. class SnapshotAdmin(SearchResultsAdminMixin, admin.ModelAdmin):
  163. list_display = ('added', 'title_str', 'files', 'size', 'url_str')
  164. sort_fields = ('title_str', 'url_str', 'added', 'files')
  165. readonly_fields = ('admin_actions', 'status_info', 'bookmarked', 'added', 'updated', 'created', 'modified', 'identifiers')
  166. search_fields = ('id', 'url', 'abid', 'uuid', 'timestamp', 'title', 'tags__name')
  167. list_filter = ('added', 'updated', 'tags', 'archiveresult__status', 'created_by')
  168. fields = ('url', 'timestamp', 'created_by', 'tags', 'title', *readonly_fields)
  169. ordering = ['-added']
  170. actions = ['add_tags', 'remove_tags', 'update_titles', 'update_snapshots', 'resnapshot_snapshot', 'overwrite_snapshots', 'delete_snapshots']
  171. autocomplete_fields = ['tags']
  172. inlines = [ArchiveResultInline]
  173. list_per_page = SNAPSHOTS_PER_PAGE
  174. action_form = SnapshotActionForm
  175. def changelist_view(self, request, extra_context=None):
  176. extra_context = extra_context or {}
  177. return super().changelist_view(request, extra_context | GLOBAL_CONTEXT)
  178. def get_urls(self):
  179. urls = super().get_urls()
  180. custom_urls = [
  181. path('grid/', self.admin_site.admin_view(self.grid_view), name='grid')
  182. ]
  183. return custom_urls + urls
  184. def get_queryset(self, request):
  185. self.request = request
  186. return super().get_queryset(request).prefetch_related('tags').annotate(archiveresult_count=Count('archiveresult'))
  187. def tag_list(self, obj):
  188. return ', '.join(obj.tags.values_list('name', flat=True))
  189. # TODO: figure out a different way to do this, you cant nest forms so this doenst work
  190. # def action(self, obj):
  191. # # csrfmiddlewaretoken: Wa8UcQ4fD3FJibzxqHN3IYrrjLo4VguWynmbzzcPYoebfVUnDovon7GEMYFRgsh0
  192. # # action: update_snapshots
  193. # # select_across: 0
  194. # # _selected_action: 76d29b26-2a88-439e-877c-a7cca1b72bb3
  195. # return format_html(
  196. # '''
  197. # <form action="/admin/core/snapshot/" method="post" onsubmit="e => e.stopPropagation()">
  198. # <input type="hidden" name="csrfmiddlewaretoken" value="{}">
  199. # <input type="hidden" name="_selected_action" value="{}">
  200. # <button name="update_snapshots">Check</button>
  201. # <button name="update_titles">Pull title + favicon</button>
  202. # <button name="update_snapshots">Update</button>
  203. # <button name="overwrite_snapshots">Re-Archive (overwrite)</button>
  204. # <button name="delete_snapshots">Permanently delete</button>
  205. # </form>
  206. # ''',
  207. # csrf.get_token(self.request),
  208. # obj.pk,
  209. # )
  210. def admin_actions(self, obj):
  211. return format_html(
  212. # URL Hash: <code style="font-size: 10px; user-select: all">{}</code><br/>
  213. '''
  214. <a class="btn" style="font-size: 18px; display: inline-block; border-radius: 10px; border: 3px solid #eee; padding: 4px 8px" href="/archive/{}">Summary page ➡️</a> &nbsp; &nbsp;
  215. <a class="btn" style="font-size: 18px; display: inline-block; border-radius: 10px; border: 3px solid #eee; padding: 4px 8px" href="/archive/{}/index.html#all">Result files 📑</a> &nbsp; &nbsp;
  216. <a class="btn" style="font-size: 18px; display: inline-block; border-radius: 10px; border: 3px solid #eee; padding: 4px 8px" href="/admin/core/snapshot/?id__exact={}">Admin actions ⚙️</a>
  217. ''',
  218. obj.timestamp,
  219. obj.timestamp,
  220. obj.pk,
  221. )
  222. def status_info(self, obj):
  223. return format_html(
  224. # URL Hash: <code style="font-size: 10px; user-select: all">{}</code><br/>
  225. '''
  226. Archived: {} ({} files {}) &nbsp; &nbsp;
  227. Favicon: <img src="{}" style="height: 20px"/> &nbsp; &nbsp;
  228. Status code: {} &nbsp; &nbsp;<br/>
  229. Server: {} &nbsp; &nbsp;
  230. Content type: {} &nbsp; &nbsp;
  231. Extension: {} &nbsp; &nbsp;
  232. ''',
  233. '✅' if obj.is_archived else '❌',
  234. obj.num_outputs,
  235. self.size(obj) or '0kb',
  236. f'/archive/{obj.timestamp}/favicon.ico',
  237. obj.status_code or '-',
  238. obj.headers and obj.headers.get('Server') or '-',
  239. obj.headers and obj.headers.get('Content-Type') or '-',
  240. obj.extension or '-',
  241. )
  242. def identifiers(self, obj):
  243. return get_abid_info(self, obj)
  244. @admin.display(
  245. description='Title',
  246. ordering='title',
  247. )
  248. def title_str(self, obj):
  249. canon = obj.as_link().canonical_outputs()
  250. tags = ''.join(
  251. format_html('<a href="/admin/core/snapshot/?tags__id__exact={}"><span class="tag">{}</span></a> ', tag.id, tag)
  252. for tag in obj.tags.all()
  253. if str(tag).strip()
  254. )
  255. return format_html(
  256. '<a href="/{}">'
  257. '<img src="/{}/{}" class="favicon" onerror="this.remove()">'
  258. '</a>'
  259. '<a href="/{}/index.html">'
  260. '<b class="status-{}">{}</b>'
  261. '</a>',
  262. obj.archive_path,
  263. obj.archive_path, canon['favicon_path'],
  264. obj.archive_path,
  265. 'fetched' if obj.latest_title or obj.title else 'pending',
  266. urldecode(htmldecode(obj.latest_title or obj.title or ''))[:128] or 'Pending...'
  267. ) + mark_safe(f' <span class="tags">{tags}</span>')
  268. @admin.display(
  269. description='Files Saved',
  270. ordering='archiveresult_count',
  271. )
  272. def files(self, obj):
  273. return snapshot_icons(obj)
  274. @admin.display(
  275. ordering='archiveresult_count'
  276. )
  277. def size(self, obj):
  278. archive_size = (Path(obj.link_dir) / 'index.html').exists() and obj.archive_size
  279. if archive_size:
  280. size_txt = printable_filesize(archive_size)
  281. if archive_size > 52428800:
  282. size_txt = mark_safe(f'<b>{size_txt}</b>')
  283. else:
  284. size_txt = mark_safe('<span style="opacity: 0.3">...</span>')
  285. return format_html(
  286. '<a href="/{}" title="View all files">{}</a>',
  287. obj.archive_path,
  288. size_txt,
  289. )
  290. @admin.display(
  291. description='Original URL',
  292. ordering='url',
  293. )
  294. def url_str(self, obj):
  295. return format_html(
  296. '<a href="{}"><code style="user-select: all;">{}</code></a>',
  297. obj.url,
  298. obj.url[:128],
  299. )
  300. def grid_view(self, request, extra_context=None):
  301. # cl = self.get_changelist_instance(request)
  302. # Save before monkey patching to restore for changelist list view
  303. saved_change_list_template = self.change_list_template
  304. saved_list_per_page = self.list_per_page
  305. saved_list_max_show_all = self.list_max_show_all
  306. # Monkey patch here plus core_tags.py
  307. self.change_list_template = 'private_index_grid.html'
  308. self.list_per_page = SNAPSHOTS_PER_PAGE
  309. self.list_max_show_all = self.list_per_page
  310. # Call monkey patched view
  311. rendered_response = self.changelist_view(request, extra_context=extra_context)
  312. # Restore values
  313. self.change_list_template = saved_change_list_template
  314. self.list_per_page = saved_list_per_page
  315. self.list_max_show_all = saved_list_max_show_all
  316. return rendered_response
  317. # for debugging, uncomment this to print all requests:
  318. # def changelist_view(self, request, extra_context=None):
  319. # print('[*] Got request', request.method, request.POST)
  320. # return super().changelist_view(request, extra_context=None)
  321. @admin.action(
  322. description="Pull"
  323. )
  324. def update_snapshots(self, request, queryset):
  325. archive_links([
  326. snapshot.as_link()
  327. for snapshot in queryset
  328. ], out_dir=OUTPUT_DIR)
  329. @admin.action(
  330. description="⬇️ Title"
  331. )
  332. def update_titles(self, request, queryset):
  333. archive_links([
  334. snapshot.as_link()
  335. for snapshot in queryset
  336. ], overwrite=True, methods=('title','favicon'), out_dir=OUTPUT_DIR)
  337. @admin.action(
  338. description="Re-Snapshot"
  339. )
  340. def resnapshot_snapshot(self, request, queryset):
  341. for snapshot in queryset:
  342. timestamp = datetime.now(timezone.utc).isoformat('T', 'seconds')
  343. new_url = snapshot.url.split('#')[0] + f'#{timestamp}'
  344. add(new_url, tag=snapshot.tags_str())
  345. @admin.action(
  346. description="Reset"
  347. )
  348. def overwrite_snapshots(self, request, queryset):
  349. archive_links([
  350. snapshot.as_link()
  351. for snapshot in queryset
  352. ], overwrite=True, out_dir=OUTPUT_DIR)
  353. @admin.action(
  354. description="Delete"
  355. )
  356. def delete_snapshots(self, request, queryset):
  357. remove(snapshots=queryset, yes=True, delete=True, out_dir=OUTPUT_DIR)
  358. @admin.action(
  359. description="+"
  360. )
  361. def add_tags(self, request, queryset):
  362. tags = request.POST.getlist('tags')
  363. print('[+] Adding tags', tags, 'to Snapshots', queryset)
  364. for obj in queryset:
  365. obj.tags.add(*tags)
  366. @admin.action(
  367. description="–"
  368. )
  369. def remove_tags(self, request, queryset):
  370. tags = request.POST.getlist('tags')
  371. print('[-] Removing tags', tags, 'to Snapshots', queryset)
  372. for obj in queryset:
  373. obj.tags.remove(*tags)
  374. @admin.register(Tag, site=archivebox_admin)
  375. class TagAdmin(admin.ModelAdmin):
  376. list_display = ('slug', 'name', 'num_snapshots', 'snapshots', 'abid')
  377. sort_fields = ('id', 'name', 'slug', 'abid')
  378. readonly_fields = ('created', 'modified', 'identifiers', 'num_snapshots', 'snapshots')
  379. search_fields = ('id', 'abid', 'uuid', 'name', 'slug')
  380. fields = ('name', 'slug', 'created_by', *readonly_fields, )
  381. actions = ['delete_selected']
  382. ordering = ['-id']
  383. def identifiers(self, obj):
  384. return get_abid_info(self, obj)
  385. def num_snapshots(self, tag):
  386. return format_html(
  387. '<a href="/admin/core/snapshot/?tags__id__exact={}">{} total</a>',
  388. tag.id,
  389. tag.snapshot_set.count(),
  390. )
  391. def snapshots(self, tag):
  392. total_count = tag.snapshot_set.count()
  393. return mark_safe('<br/>'.join(
  394. format_html(
  395. '{} <code><a href="/admin/core/snapshot/{}/change"><b>[{}]</b></a> {}</code>',
  396. snap.updated.strftime('%Y-%m-%d %H:%M') if snap.updated else 'pending...',
  397. snap.pk,
  398. snap.abid,
  399. snap.url,
  400. )
  401. for snap in tag.snapshot_set.order_by('-updated')[:10]
  402. ) + (f'<br/><a href="/admin/core/snapshot/?tags__id__exact={tag.id}">and {total_count-10} more...<a>' if tag.snapshot_set.count() > 10 else ''))
  403. @admin.register(ArchiveResult, site=archivebox_admin)
  404. class ArchiveResultAdmin(admin.ModelAdmin):
  405. list_display = ('start_ts', 'snapshot_info', 'tags_str', 'extractor', 'cmd_str', 'status', 'output_str')
  406. sort_fields = ('start_ts', 'extractor', 'status')
  407. readonly_fields = ('snapshot_info', 'tags_str', 'created_by', 'created', 'modified', 'identifiers')
  408. search_fields = ('id', 'uuid', 'abid', 'snapshot__url', 'extractor', 'output', 'cmd_version', 'cmd', 'snapshot__timestamp')
  409. fields = ('snapshot', 'extractor', 'status', 'output', 'pwd', 'cmd', 'start_ts', 'end_ts', 'cmd_version', *readonly_fields)
  410. autocomplete_fields = ['snapshot']
  411. list_filter = ('status', 'extractor', 'start_ts', 'cmd_version')
  412. ordering = ['-start_ts']
  413. list_per_page = SNAPSHOTS_PER_PAGE
  414. @admin.display(
  415. description='Snapshot Info'
  416. )
  417. def snapshot_info(self, result):
  418. return format_html(
  419. '<a href="/archive/{}/index.html"><b><code>[{}]</code></b> &nbsp; {} &nbsp; {}</a><br/>',
  420. result.snapshot.timestamp,
  421. result.snapshot.abid,
  422. result.snapshot.added.strftime('%Y-%m-%d %H:%M'),
  423. result.snapshot.url[:128],
  424. )
  425. def identifiers(self, obj):
  426. try:
  427. return get_abid_info(self, obj)
  428. except Exception as e:
  429. return str(e)
  430. @admin.display(
  431. description='Snapshot Tags'
  432. )
  433. def tags_str(self, result):
  434. return result.snapshot.tags_str()
  435. def cmd_str(self, result):
  436. return format_html(
  437. '<pre>{}</pre>',
  438. ' '.join(result.cmd) if isinstance(result.cmd, list) else str(result.cmd),
  439. )
  440. def output_str(self, result):
  441. return format_html(
  442. '<a href="/archive/{}/{}" class="output-link">↗️</a><pre>{}</pre>',
  443. result.snapshot.timestamp,
  444. result.output if (result.status == 'succeeded') and result.extractor not in ('title', 'archive_org') else 'index.html',
  445. result.output,
  446. )