admin.py 16 KB

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