admin.py 19 KB

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