admin.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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. # monkey patch django-signals-webhooks to change how it shows up in Admin UI
  15. from signal_webhooks.apps import DjangoSignalWebhooksConfig
  16. from signal_webhooks.admin import WebhookAdmin, WebhookModel
  17. from ..util import htmldecode, urldecode, ansi_to_html
  18. from core.models import Snapshot, ArchiveResult, Tag
  19. from core.forms import AddLinkForm
  20. from core.mixins import SearchResultsAdminMixin
  21. from api.models import APIToken
  22. from index.html import snapshot_icons
  23. from logging_util import printable_filesize
  24. from main import add, remove
  25. from extractors import archive_links
  26. from config import (
  27. OUTPUT_DIR,
  28. SNAPSHOTS_PER_PAGE,
  29. VERSION,
  30. VERSIONS_AVAILABLE,
  31. CAN_UPGRADE
  32. )
  33. GLOBAL_CONTEXT = {'VERSION': VERSION, 'VERSIONS_AVAILABLE': VERSIONS_AVAILABLE, 'CAN_UPGRADE': CAN_UPGRADE}
  34. # Admin URLs
  35. # /admin/
  36. # /admin/login/
  37. # /admin/core/
  38. # /admin/core/snapshot/
  39. # /admin/core/snapshot/:uuid/
  40. # /admin/core/tag/
  41. # /admin/core/tag/:uuid/
  42. # TODO: https://stackoverflow.com/questions/40760880/add-custom-button-to-django-admin-panel
  43. class ArchiveBoxAdmin(admin.AdminSite):
  44. site_header = 'ArchiveBox'
  45. index_title = 'Links'
  46. site_title = 'Index'
  47. namespace = 'admin'
  48. def get_urls(self):
  49. return [
  50. path('core/snapshot/add/', self.add_view, name='Add'),
  51. ] + super().get_urls()
  52. def add_view(self, request):
  53. if not request.user.is_authenticated:
  54. return redirect(f'/admin/login/?next={request.path}')
  55. request.current_app = self.name
  56. context = {
  57. **self.each_context(request),
  58. 'title': 'Add URLs',
  59. }
  60. if request.method == 'GET':
  61. context['form'] = AddLinkForm()
  62. elif request.method == 'POST':
  63. form = AddLinkForm(request.POST)
  64. if form.is_valid():
  65. url = form.cleaned_data["url"]
  66. print(f'[+] Adding URL: {url}')
  67. depth = 0 if form.cleaned_data["depth"] == "0" else 1
  68. input_kwargs = {
  69. "urls": url,
  70. "depth": depth,
  71. "update_all": False,
  72. "out_dir": OUTPUT_DIR,
  73. }
  74. add_stdout = StringIO()
  75. with redirect_stdout(add_stdout):
  76. add(**input_kwargs)
  77. print(add_stdout.getvalue())
  78. context.update({
  79. "stdout": ansi_to_html(add_stdout.getvalue().strip()),
  80. "form": AddLinkForm()
  81. })
  82. else:
  83. context["form"] = form
  84. return render(template_name='add.html', request=request, context=context)
  85. # monkey patch django-signals-webhooks to change how it shows up in Admin UI
  86. DjangoSignalWebhooksConfig.verbose_name = 'API'
  87. WebhookModel._meta.get_field('name').help_text = 'Give your webhook a descriptive name (e.g. Notify ACME Slack channel of any new ArchiveResults).'
  88. WebhookModel._meta.get_field('signal').help_text = 'The type of event the webhook should fire for (e.g. Create, Update, Delete).'
  89. WebhookModel._meta.get_field('ref').help_text = 'Dot import notation of the model the webhook should fire for (e.g. core.models.Snapshot or core.models.ArchiveResult).'
  90. WebhookModel._meta.get_field('endpoint').help_text = 'External URL to POST the webhook notification to (e.g. https://someapp.example.com/webhook/some-webhook-receiver).'
  91. WebhookModel._meta.app_label = 'api'
  92. archivebox_admin = ArchiveBoxAdmin()
  93. archivebox_admin.register(get_user_model())
  94. archivebox_admin.register(APIToken)
  95. archivebox_admin.register(WebhookModel, WebhookAdmin)
  96. archivebox_admin.disable_action('delete_selected')
  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. @admin.register(Snapshot, site=archivebox_admin)
  130. class SnapshotAdmin(SearchResultsAdminMixin, admin.ModelAdmin):
  131. list_display = ('added', 'title_str', 'files', 'size', 'url_str')
  132. sort_fields = ('title_str', 'url_str', 'added', 'files')
  133. readonly_fields = ('info', 'bookmarked', 'added', 'updated')
  134. search_fields = ('id', 'url', 'timestamp', 'title', 'tags__name')
  135. fields = ('timestamp', 'url', 'title', 'tags', *readonly_fields)
  136. list_filter = ('added', 'updated', 'tags', 'archiveresult__status')
  137. ordering = ['-added']
  138. actions = ['add_tags', 'remove_tags', 'update_titles', 'update_snapshots', 'resnapshot_snapshot', 'overwrite_snapshots', 'delete_snapshots']
  139. autocomplete_fields = ['tags']
  140. inlines = [ArchiveResultInline]
  141. list_per_page = SNAPSHOTS_PER_PAGE
  142. action_form = SnapshotActionForm
  143. def changelist_view(self, request, extra_context=None):
  144. extra_context = extra_context or {}
  145. return super().changelist_view(request, extra_context | GLOBAL_CONTEXT)
  146. def get_urls(self):
  147. urls = super().get_urls()
  148. custom_urls = [
  149. path('grid/', self.admin_site.admin_view(self.grid_view), name='grid')
  150. ]
  151. return custom_urls + urls
  152. def get_queryset(self, request):
  153. self.request = request
  154. return super().get_queryset(request).prefetch_related('tags').annotate(archiveresult_count=Count('archiveresult'))
  155. def tag_list(self, obj):
  156. return ', '.join(obj.tags.values_list('name', flat=True))
  157. # TODO: figure out a different way to do this, you cant nest forms so this doenst work
  158. # def action(self, obj):
  159. # # csrfmiddlewaretoken: Wa8UcQ4fD3FJibzxqHN3IYrrjLo4VguWynmbzzcPYoebfVUnDovon7GEMYFRgsh0
  160. # # action: update_snapshots
  161. # # select_across: 0
  162. # # _selected_action: 76d29b26-2a88-439e-877c-a7cca1b72bb3
  163. # return format_html(
  164. # '''
  165. # <form action="/admin/core/snapshot/" method="post" onsubmit="e => e.stopPropagation()">
  166. # <input type="hidden" name="csrfmiddlewaretoken" value="{}">
  167. # <input type="hidden" name="_selected_action" value="{}">
  168. # <button name="update_snapshots">Check</button>
  169. # <button name="update_titles">Pull title + favicon</button>
  170. # <button name="update_snapshots">Update</button>
  171. # <button name="overwrite_snapshots">Re-Archive (overwrite)</button>
  172. # <button name="delete_snapshots">Permanently delete</button>
  173. # </form>
  174. # ''',
  175. # csrf.get_token(self.request),
  176. # obj.id,
  177. # )
  178. def info(self, obj):
  179. return format_html(
  180. '''
  181. UUID: <code style="font-size: 10px; user-select: all">{}</code> &nbsp; &nbsp;
  182. Timestamp: <code style="font-size: 10px; user-select: all">{}</code> &nbsp; &nbsp;
  183. URL Hash: <code style="font-size: 10px; user-select: all">{}</code><br/>
  184. Archived: {} ({} files {}) &nbsp; &nbsp;
  185. Favicon: <img src="{}" style="height: 20px"/> &nbsp; &nbsp;
  186. Status code: {} &nbsp; &nbsp;
  187. Server: {} &nbsp; &nbsp;
  188. Content type: {} &nbsp; &nbsp;
  189. Extension: {} &nbsp; &nbsp;
  190. <br/><br/>
  191. <a href="/archive/{}">View Snapshot index ➡️</a> &nbsp; &nbsp;
  192. <a href="/admin/core/snapshot/?id__exact={}">View actions ⚙️</a>
  193. ''',
  194. obj.id,
  195. obj.timestamp,
  196. obj.url_hash,
  197. '✅' if obj.is_archived else '❌',
  198. obj.num_outputs,
  199. self.size(obj),
  200. f'/archive/{obj.timestamp}/favicon.ico',
  201. obj.status_code or '?',
  202. obj.headers and obj.headers.get('Server') or '?',
  203. obj.headers and obj.headers.get('Content-Type') or '?',
  204. obj.extension or '?',
  205. obj.timestamp,
  206. obj.id,
  207. )
  208. @admin.display(
  209. description='Title',
  210. ordering='title',
  211. )
  212. def title_str(self, obj):
  213. canon = obj.as_link().canonical_outputs()
  214. tags = ''.join(
  215. format_html('<a href="/admin/core/snapshot/?tags__id__exact={}"><span class="tag">{}</span></a> ', tag.id, tag)
  216. for tag in obj.tags.all()
  217. if str(tag).strip()
  218. )
  219. return format_html(
  220. '<a href="/{}">'
  221. '<img src="/{}/{}" class="favicon" onerror="this.remove()">'
  222. '</a>'
  223. '<a href="/{}/index.html">'
  224. '<b class="status-{}">{}</b>'
  225. '</a>',
  226. obj.archive_path,
  227. obj.archive_path, canon['favicon_path'],
  228. obj.archive_path,
  229. 'fetched' if obj.latest_title or obj.title else 'pending',
  230. urldecode(htmldecode(obj.latest_title or obj.title or ''))[:128] or 'Pending...'
  231. ) + mark_safe(f' <span class="tags">{tags}</span>')
  232. @admin.display(
  233. description='Files Saved',
  234. ordering='archiveresult_count',
  235. )
  236. def files(self, obj):
  237. return snapshot_icons(obj)
  238. @admin.display(
  239. ordering='archiveresult_count'
  240. )
  241. def size(self, obj):
  242. archive_size = (Path(obj.link_dir) / 'index.html').exists() and obj.archive_size
  243. if archive_size:
  244. size_txt = printable_filesize(archive_size)
  245. if archive_size > 52428800:
  246. size_txt = mark_safe(f'<b>{size_txt}</b>')
  247. else:
  248. size_txt = mark_safe('<span style="opacity: 0.3">...</span>')
  249. return format_html(
  250. '<a href="/{}" title="View all files">{}</a>',
  251. obj.archive_path,
  252. size_txt,
  253. )
  254. @admin.display(
  255. description='Original URL',
  256. ordering='url',
  257. )
  258. def url_str(self, obj):
  259. return format_html(
  260. '<a href="{}"><code style="user-select: all;">{}</code></a>',
  261. obj.url,
  262. obj.url,
  263. )
  264. def grid_view(self, request, extra_context=None):
  265. # cl = self.get_changelist_instance(request)
  266. # Save before monkey patching to restore for changelist list view
  267. saved_change_list_template = self.change_list_template
  268. saved_list_per_page = self.list_per_page
  269. saved_list_max_show_all = self.list_max_show_all
  270. # Monkey patch here plus core_tags.py
  271. self.change_list_template = 'private_index_grid.html'
  272. self.list_per_page = SNAPSHOTS_PER_PAGE
  273. self.list_max_show_all = self.list_per_page
  274. # Call monkey patched view
  275. rendered_response = self.changelist_view(request, extra_context=extra_context)
  276. # Restore values
  277. self.change_list_template = saved_change_list_template
  278. self.list_per_page = saved_list_per_page
  279. self.list_max_show_all = saved_list_max_show_all
  280. return rendered_response
  281. # for debugging, uncomment this to print all requests:
  282. # def changelist_view(self, request, extra_context=None):
  283. # print('[*] Got request', request.method, request.POST)
  284. # return super().changelist_view(request, extra_context=None)
  285. @admin.action(
  286. description="Pull"
  287. )
  288. def update_snapshots(self, request, queryset):
  289. archive_links([
  290. snapshot.as_link()
  291. for snapshot in queryset
  292. ], out_dir=OUTPUT_DIR)
  293. @admin.action(
  294. description="⬇️ Title"
  295. )
  296. def update_titles(self, request, queryset):
  297. archive_links([
  298. snapshot.as_link()
  299. for snapshot in queryset
  300. ], overwrite=True, methods=('title','favicon'), out_dir=OUTPUT_DIR)
  301. @admin.action(
  302. description="Re-Snapshot"
  303. )
  304. def resnapshot_snapshot(self, request, queryset):
  305. for snapshot in queryset:
  306. timestamp = datetime.now(timezone.utc).isoformat('T', 'seconds')
  307. new_url = snapshot.url.split('#')[0] + f'#{timestamp}'
  308. add(new_url, tag=snapshot.tags_str())
  309. @admin.action(
  310. description="Reset"
  311. )
  312. def overwrite_snapshots(self, request, queryset):
  313. archive_links([
  314. snapshot.as_link()
  315. for snapshot in queryset
  316. ], overwrite=True, out_dir=OUTPUT_DIR)
  317. @admin.action(
  318. description="Delete"
  319. )
  320. def delete_snapshots(self, request, queryset):
  321. remove(snapshots=queryset, yes=True, delete=True, out_dir=OUTPUT_DIR)
  322. @admin.action(
  323. description="+"
  324. )
  325. def add_tags(self, request, queryset):
  326. tags = request.POST.getlist('tags')
  327. print('[+] Adding tags', tags, 'to Snapshots', queryset)
  328. for obj in queryset:
  329. obj.tags.add(*tags)
  330. @admin.action(
  331. description="–"
  332. )
  333. def remove_tags(self, request, queryset):
  334. tags = request.POST.getlist('tags')
  335. print('[-] Removing tags', tags, 'to Snapshots', queryset)
  336. for obj in queryset:
  337. obj.tags.remove(*tags)
  338. @admin.register(Tag, site=archivebox_admin)
  339. class TagAdmin(admin.ModelAdmin):
  340. list_display = ('slug', 'name', 'num_snapshots', 'snapshots', 'id')
  341. sort_fields = ('id', 'name', 'slug')
  342. readonly_fields = ('id', 'num_snapshots', 'snapshots')
  343. search_fields = ('id', 'name', 'slug')
  344. fields = (*readonly_fields, 'name', 'slug')
  345. actions = ['delete_selected']
  346. ordering = ['-id']
  347. def num_snapshots(self, obj):
  348. return format_html(
  349. '<a href="/admin/core/snapshot/?tags__id__exact={}">{} total</a>',
  350. obj.id,
  351. obj.snapshot_set.count(),
  352. )
  353. def snapshots(self, obj):
  354. total_count = obj.snapshot_set.count()
  355. return mark_safe('<br/>'.join(
  356. format_html(
  357. '{} <code><a href="/admin/core/snapshot/{}/change"><b>[{}]</b></a> {}</code>',
  358. snap.updated.strftime('%Y-%m-%d %H:%M') if snap.updated else 'pending...',
  359. snap.id,
  360. snap.timestamp,
  361. snap.url,
  362. )
  363. for snap in obj.snapshot_set.order_by('-updated')[:10]
  364. ) + (f'<br/><a href="/admin/core/snapshot/?tags__id__exact={obj.id}">and {total_count-10} more...<a>' if obj.snapshot_set.count() > 10 else ''))
  365. @admin.register(ArchiveResult, site=archivebox_admin)
  366. class ArchiveResultAdmin(admin.ModelAdmin):
  367. list_display = ('id', 'start_ts', 'extractor', 'snapshot_str', 'tags_str', 'cmd_str', 'status', 'output_str')
  368. sort_fields = ('start_ts', 'extractor', 'status')
  369. readonly_fields = ('id', 'uuid', 'snapshot_str', 'tags_str')
  370. search_fields = ('id', 'uuid', 'snapshot__url', 'extractor', 'output', 'cmd_version', 'cmd', 'snapshot__timestamp')
  371. fields = (*readonly_fields, 'snapshot', 'extractor', 'status', 'start_ts', 'end_ts', 'output', 'pwd', 'cmd', 'cmd_version')
  372. autocomplete_fields = ['snapshot']
  373. list_filter = ('status', 'extractor', 'start_ts', 'cmd_version')
  374. ordering = ['-start_ts']
  375. list_per_page = SNAPSHOTS_PER_PAGE
  376. @admin.display(
  377. description='snapshot'
  378. )
  379. def snapshot_str(self, obj):
  380. return format_html(
  381. '<a href="/archive/{}/index.html"><b><code>[{}]</code></b></a><br/>'
  382. '<small>{}</small>',
  383. obj.snapshot.timestamp,
  384. obj.snapshot.timestamp,
  385. obj.snapshot.url[:128],
  386. )
  387. @admin.display(
  388. description='tags'
  389. )
  390. def tags_str(self, obj):
  391. return obj.snapshot.tags_str()
  392. def cmd_str(self, obj):
  393. return format_html(
  394. '<pre>{}</pre>',
  395. ' '.join(obj.cmd) if isinstance(obj.cmd, list) else str(obj.cmd),
  396. )
  397. def output_str(self, obj):
  398. return format_html(
  399. '<a href="/archive/{}/{}" class="output-link">↗️</a><pre>{}</pre>',
  400. obj.snapshot.timestamp,
  401. obj.output if (obj.status == 'succeeded') and obj.extractor not in ('title', 'archive_org') else 'index.html',
  402. obj.output,
  403. )