admin.py 16 KB

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