admin.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. @admin.register(Snapshot, site=archivebox_admin)
  127. class SnapshotAdmin(SearchResultsAdminMixin, admin.ModelAdmin):
  128. list_display = ('added', 'title_str', 'files', 'size', 'url_str')
  129. sort_fields = ('title_str', 'url_str', 'added', 'files')
  130. readonly_fields = ('info', 'pk', 'uuid', 'abid', 'calculate_abid', 'bookmarked', 'added', 'updated')
  131. search_fields = ('id', 'url', 'timestamp', 'title', 'tags__name')
  132. fields = ('timestamp', 'url', 'title', 'tags', *readonly_fields)
  133. list_filter = ('added', 'updated', 'tags', 'archiveresult__status')
  134. ordering = ['-added']
  135. actions = ['add_tags', 'remove_tags', 'update_titles', 'update_snapshots', 'resnapshot_snapshot', 'overwrite_snapshots', 'delete_snapshots']
  136. autocomplete_fields = ['tags']
  137. inlines = [ArchiveResultInline]
  138. list_per_page = SNAPSHOTS_PER_PAGE
  139. action_form = SnapshotActionForm
  140. def changelist_view(self, request, extra_context=None):
  141. extra_context = extra_context or {}
  142. return super().changelist_view(request, extra_context | GLOBAL_CONTEXT)
  143. def get_urls(self):
  144. urls = super().get_urls()
  145. custom_urls = [
  146. path('grid/', self.admin_site.admin_view(self.grid_view), name='grid')
  147. ]
  148. return custom_urls + urls
  149. def get_queryset(self, request):
  150. self.request = request
  151. return super().get_queryset(request).prefetch_related('tags').annotate(archiveresult_count=Count('archiveresult'))
  152. def tag_list(self, obj):
  153. return ', '.join(obj.tags.values_list('name', flat=True))
  154. # TODO: figure out a different way to do this, you cant nest forms so this doenst work
  155. # def action(self, obj):
  156. # # csrfmiddlewaretoken: Wa8UcQ4fD3FJibzxqHN3IYrrjLo4VguWynmbzzcPYoebfVUnDovon7GEMYFRgsh0
  157. # # action: update_snapshots
  158. # # select_across: 0
  159. # # _selected_action: 76d29b26-2a88-439e-877c-a7cca1b72bb3
  160. # return format_html(
  161. # '''
  162. # <form action="/admin/core/snapshot/" method="post" onsubmit="e => e.stopPropagation()">
  163. # <input type="hidden" name="csrfmiddlewaretoken" value="{}">
  164. # <input type="hidden" name="_selected_action" value="{}">
  165. # <button name="update_snapshots">Check</button>
  166. # <button name="update_titles">Pull title + favicon</button>
  167. # <button name="update_snapshots">Update</button>
  168. # <button name="overwrite_snapshots">Re-Archive (overwrite)</button>
  169. # <button name="delete_snapshots">Permanently delete</button>
  170. # </form>
  171. # ''',
  172. # csrf.get_token(self.request),
  173. # obj.pk,
  174. # )
  175. def info(self, obj):
  176. return format_html(
  177. '''
  178. PK: <code style="font-size: 10px; user-select: all">{}</code> &nbsp; &nbsp;
  179. ABID: <code style="font-size: 10px; user-select: all">{}</code> &nbsp; &nbsp;
  180. UUID: <code style="font-size: 10px; user-select: all">{}</code> &nbsp; &nbsp;
  181. Timestamp: <code style="font-size: 10px; user-select: all">{}</code> &nbsp; &nbsp;
  182. URL Hash: <code style="font-size: 10px; user-select: all">{}</code><br/>
  183. Archived: {} ({} files {}) &nbsp; &nbsp;
  184. Favicon: <img src="{}" style="height: 20px"/> &nbsp; &nbsp;
  185. Status code: {} &nbsp; &nbsp;
  186. Server: {} &nbsp; &nbsp;
  187. Content type: {} &nbsp; &nbsp;
  188. Extension: {} &nbsp; &nbsp;
  189. <br/><br/>
  190. <a href="/archive/{}">View Snapshot index ➡️</a> &nbsp; &nbsp;
  191. <a href="/admin/core/snapshot/?uuid__exact={}">View actions ⚙️</a>
  192. ''',
  193. obj.pk,
  194. obj.ABID,
  195. obj.uuid,
  196. obj.timestamp,
  197. obj.url_hash,
  198. '✅' if obj.is_archived else '❌',
  199. obj.num_outputs,
  200. self.size(obj),
  201. f'/archive/{obj.timestamp}/favicon.ico',
  202. obj.status_code or '?',
  203. obj.headers and obj.headers.get('Server') or '?',
  204. obj.headers and obj.headers.get('Content-Type') or '?',
  205. obj.extension or '?',
  206. obj.timestamp,
  207. obj.uuid,
  208. )
  209. @admin.display(
  210. description='Title',
  211. ordering='title',
  212. )
  213. def title_str(self, obj):
  214. canon = obj.as_link().canonical_outputs()
  215. tags = ''.join(
  216. format_html('<a href="/admin/core/snapshot/?tags__id__exact={}"><span class="tag">{}</span></a> ', tag.id, tag)
  217. for tag in obj.tags.all()
  218. if str(tag).strip()
  219. )
  220. return format_html(
  221. '<a href="/{}">'
  222. '<img src="/{}/{}" class="favicon" onerror="this.remove()">'
  223. '</a>'
  224. '<a href="/{}/index.html">'
  225. '<b class="status-{}">{}</b>'
  226. '</a>',
  227. obj.archive_path,
  228. obj.archive_path, canon['favicon_path'],
  229. obj.archive_path,
  230. 'fetched' if obj.latest_title or obj.title else 'pending',
  231. urldecode(htmldecode(obj.latest_title or obj.title or ''))[:128] or 'Pending...'
  232. ) + mark_safe(f' <span class="tags">{tags}</span>')
  233. @admin.display(
  234. description='Files Saved',
  235. ordering='archiveresult_count',
  236. )
  237. def files(self, obj):
  238. return snapshot_icons(obj)
  239. @admin.display(
  240. ordering='archiveresult_count'
  241. )
  242. def size(self, obj):
  243. archive_size = (Path(obj.link_dir) / 'index.html').exists() and obj.archive_size
  244. if archive_size:
  245. size_txt = printable_filesize(archive_size)
  246. if archive_size > 52428800:
  247. size_txt = mark_safe(f'<b>{size_txt}</b>')
  248. else:
  249. size_txt = mark_safe('<span style="opacity: 0.3">...</span>')
  250. return format_html(
  251. '<a href="/{}" title="View all files">{}</a>',
  252. obj.archive_path,
  253. size_txt,
  254. )
  255. @admin.display(
  256. description='Original URL',
  257. ordering='url',
  258. )
  259. def url_str(self, obj):
  260. return format_html(
  261. '<a href="{}"><code style="user-select: all;">{}</code></a>',
  262. obj.url,
  263. obj.url,
  264. )
  265. def grid_view(self, request, extra_context=None):
  266. # cl = self.get_changelist_instance(request)
  267. # Save before monkey patching to restore for changelist list view
  268. saved_change_list_template = self.change_list_template
  269. saved_list_per_page = self.list_per_page
  270. saved_list_max_show_all = self.list_max_show_all
  271. # Monkey patch here plus core_tags.py
  272. self.change_list_template = 'private_index_grid.html'
  273. self.list_per_page = SNAPSHOTS_PER_PAGE
  274. self.list_max_show_all = self.list_per_page
  275. # Call monkey patched view
  276. rendered_response = self.changelist_view(request, extra_context=extra_context)
  277. # Restore values
  278. self.change_list_template = saved_change_list_template
  279. self.list_per_page = saved_list_per_page
  280. self.list_max_show_all = saved_list_max_show_all
  281. return rendered_response
  282. # for debugging, uncomment this to print all requests:
  283. # def changelist_view(self, request, extra_context=None):
  284. # print('[*] Got request', request.method, request.POST)
  285. # return super().changelist_view(request, extra_context=None)
  286. @admin.action(
  287. description="Pull"
  288. )
  289. def update_snapshots(self, request, queryset):
  290. archive_links([
  291. snapshot.as_link()
  292. for snapshot in queryset
  293. ], out_dir=OUTPUT_DIR)
  294. @admin.action(
  295. description="⬇️ Title"
  296. )
  297. def update_titles(self, request, queryset):
  298. archive_links([
  299. snapshot.as_link()
  300. for snapshot in queryset
  301. ], overwrite=True, methods=('title','favicon'), out_dir=OUTPUT_DIR)
  302. @admin.action(
  303. description="Re-Snapshot"
  304. )
  305. def resnapshot_snapshot(self, request, queryset):
  306. for snapshot in queryset:
  307. timestamp = datetime.now(timezone.utc).isoformat('T', 'seconds')
  308. new_url = snapshot.url.split('#')[0] + f'#{timestamp}'
  309. add(new_url, tag=snapshot.tags_str())
  310. @admin.action(
  311. description="Reset"
  312. )
  313. def overwrite_snapshots(self, request, queryset):
  314. archive_links([
  315. snapshot.as_link()
  316. for snapshot in queryset
  317. ], overwrite=True, out_dir=OUTPUT_DIR)
  318. @admin.action(
  319. description="Delete"
  320. )
  321. def delete_snapshots(self, request, queryset):
  322. remove(snapshots=queryset, yes=True, delete=True, out_dir=OUTPUT_DIR)
  323. @admin.action(
  324. description="+"
  325. )
  326. def add_tags(self, request, queryset):
  327. tags = request.POST.getlist('tags')
  328. print('[+] Adding tags', tags, 'to Snapshots', queryset)
  329. for obj in queryset:
  330. obj.tags.add(*tags)
  331. @admin.action(
  332. description="–"
  333. )
  334. def remove_tags(self, request, queryset):
  335. tags = request.POST.getlist('tags')
  336. print('[-] Removing tags', tags, 'to Snapshots', queryset)
  337. for obj in queryset:
  338. obj.tags.remove(*tags)
  339. @admin.register(Tag, site=archivebox_admin)
  340. class TagAdmin(admin.ModelAdmin):
  341. list_display = ('slug', 'name', 'num_snapshots', 'snapshots', 'id')
  342. sort_fields = ('id', 'name', 'slug')
  343. readonly_fields = ('id', 'pk', 'abid', 'calculate_abid', 'num_snapshots', 'snapshots')
  344. search_fields = ('id', 'name', 'slug')
  345. fields = (*readonly_fields, 'name', 'slug')
  346. actions = ['delete_selected']
  347. ordering = ['-id']
  348. def num_snapshots(self, tag):
  349. return format_html(
  350. '<a href="/admin/core/snapshot/?tags__id__exact={}">{} total</a>',
  351. tag.id,
  352. tag.snapshot_set.count(),
  353. )
  354. def snapshots(self, tag):
  355. total_count = tag.snapshot_set.count()
  356. return mark_safe('<br/>'.join(
  357. format_html(
  358. '{} <code><a href="/admin/core/snapshot/{}/change"><b>[{}]</b></a> {}</code>',
  359. snap.updated.strftime('%Y-%m-%d %H:%M') if snap.updated else 'pending...',
  360. snap.pk,
  361. snap.abid,
  362. snap.url,
  363. )
  364. for snap in tag.snapshot_set.order_by('-updated')[:10]
  365. ) + (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 ''))
  366. @admin.register(ArchiveResult, site=archivebox_admin)
  367. class ArchiveResultAdmin(admin.ModelAdmin):
  368. list_display = ('id', 'start_ts', 'extractor', 'snapshot_str', 'tags_str', 'cmd_str', 'status', 'output_str')
  369. sort_fields = ('start_ts', 'extractor', 'status')
  370. readonly_fields = ('id', 'ABID', 'snapshot_str', 'tags_str')
  371. search_fields = ('id', 'uuid', 'snapshot__url', 'extractor', 'output', 'cmd_version', 'cmd', 'snapshot__timestamp')
  372. fields = (*readonly_fields, 'snapshot', 'extractor', 'status', 'start_ts', 'end_ts', 'output', 'pwd', 'cmd', 'cmd_version')
  373. autocomplete_fields = ['snapshot']
  374. list_filter = ('status', 'extractor', 'start_ts', 'cmd_version')
  375. ordering = ['-start_ts']
  376. list_per_page = SNAPSHOTS_PER_PAGE
  377. @admin.display(
  378. description='snapshot'
  379. )
  380. def snapshot_str(self, result):
  381. return format_html(
  382. '<a href="/archive/{}/index.html"><b><code>[{}]</code></b></a><br/>'
  383. '<small>{}</small>',
  384. result.snapshot.timestamp,
  385. result.snapshot.timestamp,
  386. result.snapshot.url[:128],
  387. )
  388. @admin.display(
  389. description='tags'
  390. )
  391. def tags_str(self, result):
  392. return result.snapshot.tags_str()
  393. def cmd_str(self, result):
  394. return format_html(
  395. '<pre>{}</pre>',
  396. ' '.join(result.cmd) if isinstance(result.cmd, list) else str(result.cmd),
  397. )
  398. def output_str(self, result):
  399. return format_html(
  400. '<a href="/archive/{}/{}" class="output-link">↗️</a><pre>{}</pre>',
  401. result.snapshot.timestamp,
  402. result.output if (result.status == 'succeeded') and result.extractor not in ('title', 'archive_org') else 'index.html',
  403. result.output,
  404. )