admin.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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, SnapshotTag
  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. fk_name = 'snapshot'
  100. class TagInline(admin.TabularInline):
  101. model = Snapshot.tags.through
  102. # fk_name = 'snapshottag'
  103. def identifiers(self, obj):
  104. return '-'
  105. from django.contrib.admin.helpers import ActionForm
  106. from django.contrib.admin.widgets import AutocompleteSelectMultiple
  107. class AutocompleteTags:
  108. model = Tag
  109. search_fields = ['name']
  110. name = 'tags'
  111. remote_field = TagInline
  112. class AutocompleteTagsAdminStub:
  113. name = 'admin'
  114. class SnapshotActionForm(ActionForm):
  115. tags = forms.ModelMultipleChoiceField(
  116. queryset=Tag.objects.all(),
  117. required=False,
  118. widget=AutocompleteSelectMultiple(
  119. AutocompleteTags(),
  120. AutocompleteTagsAdminStub(),
  121. ),
  122. )
  123. # TODO: allow selecting actions for specific extractors? is this useful?
  124. # EXTRACTOR_CHOICES = [
  125. # (name, name.title())
  126. # for name, _, _ in get_default_archive_methods()
  127. # ]
  128. # extractor = forms.ChoiceField(
  129. # choices=EXTRACTOR_CHOICES,
  130. # required=False,
  131. # widget=forms.MultileChoiceField(attrs={'class': "form-control"})
  132. # )
  133. def get_abid_info(self, obj):
  134. return format_html(
  135. # URL Hash: <code style="font-size: 10px; user-select: all">{}</code><br/>
  136. '''
  137. &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/>
  138. &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/>
  139. &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/>
  140. <br/>
  141. <div style="opacity: 0.8">
  142. &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/>
  143. &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/>
  144. &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/>
  145. &nbsp; &nbsp; &nbsp; &nbsp; SUBTYPE: &nbsp; &nbsp; &nbsp; <code style="font-size: 10px; user-select: all"><b>{}</b></code> ({}) &nbsp; &nbsp;
  146. &nbsp; RAND: &nbsp; <code style="font-size: 10px; user-select: all"><b>{}</b></code> ({}) &nbsp; &nbsp;
  147. &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>
  148. <br/><hr/>
  149. &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/>
  150. &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/>
  151. </div>
  152. ''',
  153. obj.pk,
  154. getattr(obj, 'id', str(getattr(obj, 'old_id', '')) + ' (.old_id)'),
  155. getattr(obj, 'uuid', str(getattr(obj, 'id', '')) +' (.id)'),
  156. *obj.abid.split('_', 1), obj.api_url, obj.api_docs_url,
  157. obj.ABID.ts, obj.abid_values['ts'].isoformat() if isinstance(obj.abid_values['ts'], datetime) else obj.abid_values['ts'],
  158. obj.ABID.uri, str(obj.abid_values['uri']),
  159. obj.ABID.subtype, str(obj.abid_values['subtype']),
  160. obj.ABID.rand, str(obj.abid_values['rand'])[-7:],
  161. obj.ABID.uri_salt,
  162. obj.ABID.ulid,
  163. obj.ABID.uuid,
  164. )
  165. @admin.register(Snapshot, site=archivebox_admin)
  166. class SnapshotAdmin(SearchResultsAdminMixin, admin.ModelAdmin):
  167. list_display = ('added', 'title_str', 'files', 'size', 'url_str')
  168. sort_fields = ('title_str', 'url_str', 'added', 'files')
  169. readonly_fields = ('admin_actions', 'status_info', 'bookmarked', 'added', 'updated', 'created', 'modified', 'identifiers')
  170. search_fields = ('id', 'url', 'abid', 'uuid', 'timestamp', 'title', 'tags__name')
  171. list_filter = ('added', 'updated', 'tags', 'archiveresult__status', 'created_by')
  172. fields = ('url', 'timestamp', 'created_by', 'tags', 'title', *readonly_fields)
  173. ordering = ['-added']
  174. actions = ['add_tags', 'remove_tags', 'update_titles', 'update_snapshots', 'resnapshot_snapshot', 'overwrite_snapshots', 'delete_snapshots']
  175. autocomplete_fields = ['tags']
  176. inlines = [ArchiveResultInline]
  177. list_per_page = SNAPSHOTS_PER_PAGE
  178. action_form = SnapshotActionForm
  179. def changelist_view(self, request, extra_context=None):
  180. extra_context = extra_context or {}
  181. return super().changelist_view(request, extra_context | GLOBAL_CONTEXT)
  182. def get_urls(self):
  183. urls = super().get_urls()
  184. custom_urls = [
  185. path('grid/', self.admin_site.admin_view(self.grid_view), name='grid')
  186. ]
  187. return custom_urls + urls
  188. def get_queryset(self, request):
  189. self.request = request
  190. return super().get_queryset(request).prefetch_related('tags').annotate(archiveresult_count=Count('archiveresult'))
  191. def tag_list(self, obj):
  192. return ', '.join(obj.tags.values_list('name', flat=True))
  193. # TODO: figure out a different way to do this, you cant nest forms so this doenst work
  194. # def action(self, obj):
  195. # # csrfmiddlewaretoken: Wa8UcQ4fD3FJibzxqHN3IYrrjLo4VguWynmbzzcPYoebfVUnDovon7GEMYFRgsh0
  196. # # action: update_snapshots
  197. # # select_across: 0
  198. # # _selected_action: 76d29b26-2a88-439e-877c-a7cca1b72bb3
  199. # return format_html(
  200. # '''
  201. # <form action="/admin/core/snapshot/" method="post" onsubmit="e => e.stopPropagation()">
  202. # <input type="hidden" name="csrfmiddlewaretoken" value="{}">
  203. # <input type="hidden" name="_selected_action" value="{}">
  204. # <button name="update_snapshots">Check</button>
  205. # <button name="update_titles">Pull title + favicon</button>
  206. # <button name="update_snapshots">Update</button>
  207. # <button name="overwrite_snapshots">Re-Archive (overwrite)</button>
  208. # <button name="delete_snapshots">Permanently delete</button>
  209. # </form>
  210. # ''',
  211. # csrf.get_token(self.request),
  212. # obj.pk,
  213. # )
  214. def admin_actions(self, obj):
  215. return format_html(
  216. # URL Hash: <code style="font-size: 10px; user-select: all">{}</code><br/>
  217. '''
  218. <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;
  219. <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;
  220. <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>
  221. ''',
  222. obj.timestamp,
  223. obj.timestamp,
  224. obj.pk,
  225. )
  226. def status_info(self, obj):
  227. return format_html(
  228. # URL Hash: <code style="font-size: 10px; user-select: all">{}</code><br/>
  229. '''
  230. Archived: {} ({} files {}) &nbsp; &nbsp;
  231. Favicon: <img src="{}" style="height: 20px"/> &nbsp; &nbsp;
  232. Status code: {} &nbsp; &nbsp;<br/>
  233. Server: {} &nbsp; &nbsp;
  234. Content type: {} &nbsp; &nbsp;
  235. Extension: {} &nbsp; &nbsp;
  236. ''',
  237. '✅' if obj.is_archived else '❌',
  238. obj.num_outputs,
  239. self.size(obj) or '0kb',
  240. f'/archive/{obj.timestamp}/favicon.ico',
  241. obj.status_code or '-',
  242. obj.headers and obj.headers.get('Server') or '-',
  243. obj.headers and obj.headers.get('Content-Type') or '-',
  244. obj.extension or '-',
  245. )
  246. def identifiers(self, obj):
  247. return get_abid_info(self, obj)
  248. @admin.display(
  249. description='Title',
  250. ordering='title',
  251. )
  252. def title_str(self, obj):
  253. canon = obj.as_link().canonical_outputs()
  254. tags = ''.join(
  255. format_html('<a href="/admin/core/snapshot/?tags__id__exact={}"><span class="tag">{}</span></a> ', tag.id, tag)
  256. for tag in obj.tags.all()
  257. if str(tag).strip()
  258. )
  259. return format_html(
  260. '<a href="/{}">'
  261. '<img src="/{}/{}" class="favicon" onerror="this.remove()">'
  262. '</a>'
  263. '<a href="/{}/index.html">'
  264. '<b class="status-{}">{}</b>'
  265. '</a>',
  266. obj.archive_path,
  267. obj.archive_path, canon['favicon_path'],
  268. obj.archive_path,
  269. 'fetched' if obj.latest_title or obj.title else 'pending',
  270. urldecode(htmldecode(obj.latest_title or obj.title or ''))[:128] or 'Pending...'
  271. ) + mark_safe(f' <span class="tags">{tags}</span>')
  272. @admin.display(
  273. description='Files Saved',
  274. ordering='archiveresult_count',
  275. )
  276. def files(self, obj):
  277. return snapshot_icons(obj)
  278. @admin.display(
  279. ordering='archiveresult_count'
  280. )
  281. def size(self, obj):
  282. archive_size = (Path(obj.link_dir) / 'index.html').exists() and obj.archive_size
  283. if archive_size:
  284. size_txt = printable_filesize(archive_size)
  285. if archive_size > 52428800:
  286. size_txt = mark_safe(f'<b>{size_txt}</b>')
  287. else:
  288. size_txt = mark_safe('<span style="opacity: 0.3">...</span>')
  289. return format_html(
  290. '<a href="/{}" title="View all files">{}</a>',
  291. obj.archive_path,
  292. size_txt,
  293. )
  294. @admin.display(
  295. description='Original URL',
  296. ordering='url',
  297. )
  298. def url_str(self, obj):
  299. return format_html(
  300. '<a href="{}"><code style="user-select: all;">{}</code></a>',
  301. obj.url,
  302. obj.url[:128],
  303. )
  304. def grid_view(self, request, extra_context=None):
  305. # cl = self.get_changelist_instance(request)
  306. # Save before monkey patching to restore for changelist list view
  307. saved_change_list_template = self.change_list_template
  308. saved_list_per_page = self.list_per_page
  309. saved_list_max_show_all = self.list_max_show_all
  310. # Monkey patch here plus core_tags.py
  311. self.change_list_template = 'private_index_grid.html'
  312. self.list_per_page = SNAPSHOTS_PER_PAGE
  313. self.list_max_show_all = self.list_per_page
  314. # Call monkey patched view
  315. rendered_response = self.changelist_view(request, extra_context=extra_context)
  316. # Restore values
  317. self.change_list_template = saved_change_list_template
  318. self.list_per_page = saved_list_per_page
  319. self.list_max_show_all = saved_list_max_show_all
  320. return rendered_response
  321. # for debugging, uncomment this to print all requests:
  322. # def changelist_view(self, request, extra_context=None):
  323. # print('[*] Got request', request.method, request.POST)
  324. # return super().changelist_view(request, extra_context=None)
  325. @admin.action(
  326. description="Pull"
  327. )
  328. def update_snapshots(self, request, queryset):
  329. archive_links([
  330. snapshot.as_link()
  331. for snapshot in queryset
  332. ], out_dir=OUTPUT_DIR)
  333. @admin.action(
  334. description="⬇️ Title"
  335. )
  336. def update_titles(self, request, queryset):
  337. archive_links([
  338. snapshot.as_link()
  339. for snapshot in queryset
  340. ], overwrite=True, methods=('title','favicon'), out_dir=OUTPUT_DIR)
  341. @admin.action(
  342. description="Re-Snapshot"
  343. )
  344. def resnapshot_snapshot(self, request, queryset):
  345. for snapshot in queryset:
  346. timestamp = datetime.now(timezone.utc).isoformat('T', 'seconds')
  347. new_url = snapshot.url.split('#')[0] + f'#{timestamp}'
  348. add(new_url, tag=snapshot.tags_str())
  349. @admin.action(
  350. description="Reset"
  351. )
  352. def overwrite_snapshots(self, request, queryset):
  353. archive_links([
  354. snapshot.as_link()
  355. for snapshot in queryset
  356. ], overwrite=True, out_dir=OUTPUT_DIR)
  357. @admin.action(
  358. description="Delete"
  359. )
  360. def delete_snapshots(self, request, queryset):
  361. remove(snapshots=queryset, yes=True, delete=True, out_dir=OUTPUT_DIR)
  362. @admin.action(
  363. description="+"
  364. )
  365. def add_tags(self, request, queryset):
  366. tags = request.POST.getlist('tags')
  367. print('[+] Adding tags', tags, 'to Snapshots', queryset)
  368. for obj in queryset:
  369. obj.tags.add(*tags)
  370. @admin.action(
  371. description="–"
  372. )
  373. def remove_tags(self, request, queryset):
  374. tags = request.POST.getlist('tags')
  375. print('[-] Removing tags', tags, 'to Snapshots', queryset)
  376. for obj in queryset:
  377. obj.tags.remove(*tags)
  378. # @admin.register(SnapshotTag, site=archivebox_admin)
  379. # class SnapshotTagAdmin(admin.ModelAdmin):
  380. # list_display = ('id', 'snapshot', 'tag')
  381. # sort_fields = ('id', 'snapshot', 'tag')
  382. # search_fields = ('id', 'snapshot_id', 'tag_id')
  383. # fields = ('snapshot', 'id')
  384. # actions = ['delete_selected']
  385. # ordering = ['-id']
  386. # def identifiers(self, obj):
  387. # return get_abid_info(self, obj)
  388. @admin.register(Tag, site=archivebox_admin)
  389. class TagAdmin(admin.ModelAdmin):
  390. list_display = ('slug', 'name', 'num_snapshots', 'snapshots', 'abid')
  391. sort_fields = ('id', 'name', 'slug', 'abid')
  392. readonly_fields = ('created', 'modified', 'identifiers', 'num_snapshots', 'snapshots')
  393. search_fields = ('id', 'abid', 'uuid', 'name', 'slug')
  394. fields = ('name', 'slug', 'created_by', *readonly_fields, )
  395. actions = ['delete_selected']
  396. ordering = ['-id']
  397. def identifiers(self, obj):
  398. return get_abid_info(self, obj)
  399. def num_snapshots(self, tag):
  400. return format_html(
  401. '<a href="/admin/core/snapshot/?tags__id__exact={}">{} total</a>',
  402. tag.id,
  403. tag.snapshot_set.count(),
  404. )
  405. def snapshots(self, tag):
  406. total_count = tag.snapshot_set.count()
  407. return mark_safe('<br/>'.join(
  408. format_html(
  409. '{} <code><a href="/admin/core/snapshot/{}/change"><b>[{}]</b></a> {}</code>',
  410. snap.updated.strftime('%Y-%m-%d %H:%M') if snap.updated else 'pending...',
  411. snap.pk,
  412. snap.abid,
  413. snap.url,
  414. )
  415. for snap in tag.snapshot_set.order_by('-updated')[:10]
  416. ) + (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 ''))
  417. @admin.register(ArchiveResult, site=archivebox_admin)
  418. class ArchiveResultAdmin(admin.ModelAdmin):
  419. list_display = ('start_ts', 'snapshot_info', 'tags_str', 'extractor', 'cmd_str', 'status', 'output_str')
  420. sort_fields = ('start_ts', 'extractor', 'status')
  421. readonly_fields = ('snapshot_info', 'tags_str', 'created_by', 'created', 'modified', 'identifiers')
  422. search_fields = ('id', 'uuid', 'abid', 'snapshot__url', 'extractor', 'output', 'cmd_version', 'cmd', 'snapshot__timestamp')
  423. fields = ('snapshot', 'extractor', 'status', 'output', 'pwd', 'cmd', 'start_ts', 'end_ts', 'cmd_version', *readonly_fields)
  424. autocomplete_fields = ['snapshot']
  425. list_filter = ('status', 'extractor', 'start_ts', 'cmd_version')
  426. ordering = ['-start_ts']
  427. list_per_page = SNAPSHOTS_PER_PAGE
  428. @admin.display(
  429. description='Snapshot Info'
  430. )
  431. def snapshot_info(self, result):
  432. return format_html(
  433. '<a href="/archive/{}/index.html"><b><code>[{}]</code></b> &nbsp; {} &nbsp; {}</a><br/>',
  434. result.snapshot.timestamp,
  435. result.snapshot.abid,
  436. result.snapshot.added.strftime('%Y-%m-%d %H:%M'),
  437. result.snapshot.url[:128],
  438. )
  439. def identifiers(self, obj):
  440. try:
  441. return get_abid_info(self, obj)
  442. except Exception as e:
  443. return str(e)
  444. @admin.display(
  445. description='Snapshot Tags'
  446. )
  447. def tags_str(self, result):
  448. return result.snapshot.tags_str()
  449. def cmd_str(self, result):
  450. return format_html(
  451. '<pre>{}</pre>',
  452. ' '.join(result.cmd) if isinstance(result.cmd, list) else str(result.cmd),
  453. )
  454. def output_str(self, result):
  455. return format_html(
  456. '<a href="/archive/{}/{}" class="output-link">↗️</a><pre>{}</pre>',
  457. result.snapshot.timestamp,
  458. result.output if (result.status == 'succeeded') and result.extractor not in ('title', 'archive_org') else 'index.html',
  459. result.output,
  460. )