admin.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. __package__ = 'archivebox.core'
  2. from io import StringIO
  3. from contextlib import redirect_stdout
  4. from django.contrib import admin
  5. from django.urls import path
  6. from django.utils.html import format_html
  7. from django.utils.safestring import mark_safe
  8. from django.shortcuts import render, redirect
  9. from django.contrib.auth import get_user_model
  10. from django import forms
  11. from ..util import htmldecode, urldecode, ansi_to_html
  12. from core.models import Snapshot, Tag
  13. from core.forms import AddLinkForm, TagField
  14. from core.mixins import SearchResultsAdminMixin
  15. from index.html import snapshot_icons
  16. from logging_util import printable_filesize
  17. from main import add, remove
  18. from config import OUTPUT_DIR
  19. from extractors import archive_links
  20. # Admin URLs
  21. # /admin/
  22. # /admin/login/
  23. # /admin/core/
  24. # /admin/core/snapshot/
  25. # /admin/core/snapshot/:uuid/
  26. # /admin/core/tag/
  27. # /admin/core/tag/:uuid/
  28. # TODO: https://stackoverflow.com/questions/40760880/add-custom-button-to-django-admin-panel
  29. def update_snapshots(modeladmin, request, queryset):
  30. archive_links([
  31. snapshot.as_link()
  32. for snapshot in queryset
  33. ], out_dir=OUTPUT_DIR)
  34. update_snapshots.short_description = "Archive"
  35. def update_titles(modeladmin, request, queryset):
  36. archive_links([
  37. snapshot.as_link()
  38. for snapshot in queryset
  39. ], overwrite=True, methods=('title','favicon'), out_dir=OUTPUT_DIR)
  40. update_titles.short_description = "Pull title"
  41. def overwrite_snapshots(modeladmin, request, queryset):
  42. archive_links([
  43. snapshot.as_link()
  44. for snapshot in queryset
  45. ], overwrite=True, out_dir=OUTPUT_DIR)
  46. overwrite_snapshots.short_description = "Re-archive (overwrite)"
  47. def verify_snapshots(modeladmin, request, queryset):
  48. for snapshot in queryset:
  49. print(snapshot.timestamp, snapshot.url, snapshot.is_archived, snapshot.archive_size, len(snapshot.history))
  50. verify_snapshots.short_description = "Check"
  51. def delete_snapshots(modeladmin, request, queryset):
  52. remove(snapshots=queryset, yes=True, delete=True, out_dir=OUTPUT_DIR)
  53. delete_snapshots.short_description = "Delete"
  54. class SnapshotAdminForm(forms.ModelForm):
  55. tags = TagField(required=False)
  56. class Meta:
  57. model = Snapshot
  58. fields = "__all__"
  59. def save(self, commit=True):
  60. # Based on: https://stackoverflow.com/a/49933068/3509554
  61. # Get the unsave instance
  62. instance = forms.ModelForm.save(self, False)
  63. tags = self.cleaned_data.pop("tags")
  64. #update save_m2m
  65. def new_save_m2m():
  66. instance.save_tags(tags)
  67. # Do we need to save all changes now?
  68. self.save_m2m = new_save_m2m
  69. if commit:
  70. instance.save()
  71. return instance
  72. class SnapshotAdmin(SearchResultsAdminMixin, admin.ModelAdmin):
  73. list_display = ('added', 'title_str', 'url_str', 'files', 'size')
  74. sort_fields = ('title_str', 'url_str', 'added')
  75. readonly_fields = ('id', 'url', 'timestamp', 'num_outputs', 'is_archived', 'url_hash', 'added', 'updated')
  76. search_fields = ['url', 'timestamp', 'title', 'tags__name']
  77. fields = (*readonly_fields, 'title', 'tags')
  78. list_filter = ('added', 'updated', 'tags')
  79. ordering = ['-added']
  80. actions = [delete_snapshots, overwrite_snapshots, update_snapshots, update_titles, verify_snapshots]
  81. actions_template = 'admin/actions_as_select.html'
  82. form = SnapshotAdminForm
  83. def get_urls(self):
  84. urls = super().get_urls()
  85. custom_urls = [
  86. path('grid/', self.admin_site.admin_view(self.grid_view),name='grid')
  87. ]
  88. return custom_urls + urls
  89. def get_queryset(self, request):
  90. return super().get_queryset(request).prefetch_related('tags')
  91. def tag_list(self, obj):
  92. return ', '.join(obj.tags.values_list('name', flat=True))
  93. def id_str(self, obj):
  94. return format_html(
  95. '<code style="font-size: 10px">{}</code>',
  96. obj.url_hash[:8],
  97. )
  98. def title_str(self, obj):
  99. canon = obj.as_link().canonical_outputs()
  100. tags = ''.join(
  101. format_html('<a href="/admin/core/snapshot/?tags__id__exact={}"><span class="tag">{}</span></a> ', tag.id, tag)
  102. for tag in obj.tags.all()
  103. if str(tag).strip()
  104. )
  105. return format_html(
  106. '<a href="/{}">'
  107. '<img src="/{}/{}" class="favicon" onerror="this.remove()">'
  108. '</a>'
  109. '<a href="/{}/index.html">'
  110. '<b class="status-{}">{}</b>'
  111. '</a>',
  112. obj.archive_path,
  113. obj.archive_path, canon['favicon_path'],
  114. obj.archive_path,
  115. 'fetched' if obj.latest_title or obj.title else 'pending',
  116. urldecode(htmldecode(obj.latest_title or obj.title or ''))[:128] or 'Pending...'
  117. ) + mark_safe(f' <span class="tags">{tags}</span>')
  118. def files(self, obj):
  119. return snapshot_icons(obj)
  120. def size(self, obj):
  121. archive_size = obj.archive_size
  122. if archive_size:
  123. size_txt = printable_filesize(archive_size)
  124. if archive_size > 52428800:
  125. size_txt = mark_safe(f'<b>{size_txt}</b>')
  126. else:
  127. size_txt = mark_safe('<span style="opacity: 0.3">...</span>')
  128. return format_html(
  129. '<a href="/{}" title="View all files">{}</a>',
  130. obj.archive_path,
  131. size_txt,
  132. )
  133. def url_str(self, obj):
  134. return format_html(
  135. '<a href="{}"><code>{}</code></a>',
  136. obj.url,
  137. obj.url.split('://www.', 1)[-1].split('://', 1)[-1][:64],
  138. )
  139. def grid_view(self, request):
  140. # cl = self.get_changelist_instance(request)
  141. # Save before monkey patching to restore for changelist list view
  142. saved_change_list_template = self.change_list_template
  143. saved_list_per_page = self.list_per_page
  144. saved_list_max_show_all = self.list_max_show_all
  145. # Monkey patch here plus core_tags.py
  146. self.change_list_template = 'private_index_grid.html'
  147. self.list_per_page = 20
  148. self.list_max_show_all = self.list_per_page
  149. # Call monkey patched view
  150. rendered_response = self.changelist_view(request)
  151. # Restore values
  152. self.change_list_template = saved_change_list_template
  153. self.list_per_page = saved_list_per_page
  154. self.list_max_show_all = saved_list_max_show_all
  155. return rendered_response
  156. id_str.short_description = 'ID'
  157. title_str.short_description = 'Title'
  158. url_str.short_description = 'Original URL'
  159. id_str.admin_order_field = 'id'
  160. title_str.admin_order_field = 'title'
  161. url_str.admin_order_field = 'url'
  162. class TagAdmin(admin.ModelAdmin):
  163. list_display = ('slug', 'name', 'id')
  164. sort_fields = ('id', 'name', 'slug')
  165. readonly_fields = ('id',)
  166. search_fields = ('id', 'name', 'slug')
  167. fields = (*readonly_fields, 'name', 'slug')
  168. class ArchiveBoxAdmin(admin.AdminSite):
  169. site_header = 'ArchiveBox'
  170. index_title = 'Links'
  171. site_title = 'Index'
  172. def get_urls(self):
  173. return [
  174. path('core/snapshot/add/', self.add_view, name='Add'),
  175. ] + super().get_urls()
  176. def add_view(self, request):
  177. if not request.user.is_authenticated:
  178. return redirect(f'/admin/login/?next={request.path}')
  179. request.current_app = self.name
  180. context = {
  181. **self.each_context(request),
  182. 'title': 'Add URLs',
  183. }
  184. if request.method == 'GET':
  185. context['form'] = AddLinkForm()
  186. elif request.method == 'POST':
  187. form = AddLinkForm(request.POST)
  188. if form.is_valid():
  189. url = form.cleaned_data["url"]
  190. print(f'[+] Adding URL: {url}')
  191. depth = 0 if form.cleaned_data["depth"] == "0" else 1
  192. input_kwargs = {
  193. "urls": url,
  194. "depth": depth,
  195. "update_all": False,
  196. "out_dir": OUTPUT_DIR,
  197. }
  198. add_stdout = StringIO()
  199. with redirect_stdout(add_stdout):
  200. add(**input_kwargs)
  201. print(add_stdout.getvalue())
  202. context.update({
  203. "stdout": ansi_to_html(add_stdout.getvalue().strip()),
  204. "form": AddLinkForm()
  205. })
  206. else:
  207. context["form"] = form
  208. return render(template_name='add.html', request=request, context=context)
  209. admin.site = ArchiveBoxAdmin()
  210. admin.site.register(get_user_model())
  211. admin.site.register(Snapshot, SnapshotAdmin)
  212. admin.site.register(Tag, TagAdmin)
  213. admin.site.disable_action('delete_selected')