admin.py 22 KB

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