admin.py 16 KB

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