admin.py 8.4 KB

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