2
0

admin.py 16 KB

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