2
0

admin.py 16 KB

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