admin.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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 core.models import Snapshot
  12. from core.forms import AddLinkForm, TagField
  13. from core.utils import get_icons
  14. from util import htmldecode, urldecode, ansi_to_html
  15. from logging_util import printable_filesize
  16. from main import add, remove
  17. from config import OUTPUT_DIR
  18. from extractors import archive_links
  19. # TODO: https://stackoverflow.com/questions/40760880/add-custom-button-to-django-admin-panel
  20. def update_snapshots(modeladmin, request, queryset):
  21. archive_links([
  22. snapshot.as_link()
  23. for snapshot in queryset
  24. ], out_dir=OUTPUT_DIR)
  25. update_snapshots.short_description = "Archive"
  26. def update_titles(modeladmin, request, queryset):
  27. archive_links([
  28. snapshot.as_link()
  29. for snapshot in queryset
  30. ], overwrite=True, methods=('title','favicon'), out_dir=OUTPUT_DIR)
  31. update_titles.short_description = "Pull title"
  32. def overwrite_snapshots(modeladmin, request, queryset):
  33. archive_links([
  34. snapshot.as_link()
  35. for snapshot in queryset
  36. ], overwrite=True, out_dir=OUTPUT_DIR)
  37. overwrite_snapshots.short_description = "Re-archive (overwrite)"
  38. def verify_snapshots(modeladmin, request, queryset):
  39. for snapshot in queryset:
  40. print(snapshot.timestamp, snapshot.url, snapshot.is_archived, snapshot.archive_size, len(snapshot.history))
  41. verify_snapshots.short_description = "Check"
  42. def delete_snapshots(modeladmin, request, queryset):
  43. remove(snapshots=queryset, yes=True, delete=True, out_dir=OUTPUT_DIR)
  44. delete_snapshots.short_description = "Delete"
  45. class SnapshotAdminForm(forms.ModelForm):
  46. tags = TagField(required=False)
  47. class Meta:
  48. model = Snapshot
  49. fields = "__all__"
  50. def save(self, commit=True):
  51. # Based on: https://stackoverflow.com/a/49933068/3509554
  52. # Get the unsave instance
  53. instance = forms.ModelForm.save(self, False)
  54. tags = self.cleaned_data.pop("tags")
  55. #update save_m2m
  56. def new_save_m2m():
  57. instance.save_tags(tags)
  58. # Do we need to save all changes now?
  59. self.save_m2m = new_save_m2m
  60. if commit:
  61. instance.save()
  62. return instance
  63. class SnapshotAdmin(admin.ModelAdmin):
  64. list_display = ('added', 'title_str', 'url_str', 'files', 'size')
  65. sort_fields = ('title_str', 'url_str', 'added')
  66. readonly_fields = ('id', 'url', 'timestamp', 'num_outputs', 'is_archived', 'url_hash', 'added', 'updated')
  67. search_fields = ('url', 'timestamp', 'title', 'tags')
  68. fields = (*readonly_fields, 'title', 'tags')
  69. list_filter = ('added', 'updated', 'tags')
  70. ordering = ['-added']
  71. actions = [delete_snapshots, overwrite_snapshots, update_snapshots, update_titles, verify_snapshots]
  72. actions_template = 'admin/actions_as_select.html'
  73. form = SnapshotAdminForm
  74. def get_queryset(self, request):
  75. return super().get_queryset(request).prefetch_related('tags')
  76. def tag_list(self, obj):
  77. return ', '.join(obj.tags.values_list('name', flat=True))
  78. def id_str(self, obj):
  79. return format_html(
  80. '<code style="font-size: 10px">{}</code>',
  81. obj.url_hash[:8],
  82. )
  83. def title_str(self, obj):
  84. canon = obj.as_link().canonical_outputs()
  85. tags = ''.join(
  86. format_html(' <a href="/admin/core/snapshot/?tags__id__exact={}"><span class="tag">{}</span></a> ', tag.id, tag)
  87. for tag in obj.tags.all()
  88. )
  89. return format_html(
  90. '<a href="/{}">'
  91. '<img src="/{}/{}" class="favicon" onerror="this.remove()">'
  92. '</a>'
  93. '<a href="/{}/index.html">'
  94. '<b class="status-{}">{}</b>'
  95. '</a>',
  96. obj.archive_path,
  97. obj.archive_path, canon['favicon_path'],
  98. obj.archive_path,
  99. 'fetched' if obj.latest_title or obj.title else 'pending',
  100. urldecode(htmldecode(obj.latest_title or obj.title or ''))[:128] or 'Pending...'
  101. ) + mark_safe(f'<span class="tags">{tags}</span>')
  102. def files(self, obj):
  103. return get_icons(obj)
  104. def size(self, obj):
  105. return format_html(
  106. '<a href="/{}" title="View all files">{}</a>',
  107. obj.archive_path,
  108. printable_filesize(obj.archive_size) if obj.archive_size else 'pending',
  109. )
  110. def url_str(self, obj):
  111. return format_html(
  112. '<a href="{}">{}</a>',
  113. obj.url,
  114. obj.url.split('://www.', 1)[-1].split('://', 1)[-1][:64],
  115. )
  116. id_str.short_description = 'ID'
  117. title_str.short_description = 'Title'
  118. url_str.short_description = 'Original URL'
  119. id_str.admin_order_field = 'id'
  120. title_str.admin_order_field = 'title'
  121. url_str.admin_order_field = 'url'
  122. class ArchiveBoxAdmin(admin.AdminSite):
  123. site_header = 'ArchiveBox'
  124. index_title = 'Links'
  125. site_title = 'Index'
  126. def get_urls(self):
  127. return [
  128. path('core/snapshot/add/', self.add_view, name='Add'),
  129. ] + super().get_urls()
  130. def add_view(self, request):
  131. if not request.user.is_authenticated:
  132. return redirect(f'/admin/login/?next={request.path}')
  133. request.current_app = self.name
  134. context = {
  135. **self.each_context(request),
  136. 'title': 'Add URLs',
  137. }
  138. if request.method == 'GET':
  139. context['form'] = AddLinkForm()
  140. elif request.method == 'POST':
  141. form = AddLinkForm(request.POST)
  142. if form.is_valid():
  143. url = form.cleaned_data["url"]
  144. print(f'[+] Adding URL: {url}')
  145. depth = 0 if form.cleaned_data["depth"] == "0" else 1
  146. input_kwargs = {
  147. "urls": url,
  148. "depth": depth,
  149. "update_all": False,
  150. "out_dir": OUTPUT_DIR,
  151. }
  152. add_stdout = StringIO()
  153. with redirect_stdout(add_stdout):
  154. add(**input_kwargs)
  155. print(add_stdout.getvalue())
  156. context.update({
  157. "stdout": ansi_to_html(add_stdout.getvalue().strip()),
  158. "form": AddLinkForm()
  159. })
  160. else:
  161. context["form"] = form
  162. return render(template_name='add_links.html', request=request, context=context)
  163. admin.site = ArchiveBoxAdmin()
  164. admin.site.register(get_user_model())
  165. admin.site.register(Snapshot, SnapshotAdmin)
  166. admin.site.disable_action('delete_selected')