admin.py 15 KB

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