admin.py 20 KB

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