admin.py 23 KB

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