admin.py 15 KB

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