2
0

admin.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. __package__ = 'archivebox.core'
  2. from io import StringIO
  3. from contextlib import redirect_stdout
  4. from pathlib import Path
  5. from django.contrib import admin
  6. from django.urls import path
  7. from django.utils.html import format_html
  8. from django.utils.safestring import mark_safe
  9. from django.shortcuts import render, redirect
  10. from django.contrib.auth import get_user_model
  11. from core.models import Snapshot
  12. from core.forms import AddLinkForm
  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 SnapshotAdmin(admin.ModelAdmin):
  46. list_display = ('added', 'title_str', 'url_str', 'files', 'size')
  47. sort_fields = ('title_str', 'url_str', 'added')
  48. readonly_fields = ('id', 'url', 'timestamp', 'num_outputs', 'is_archived', 'url_hash', 'added', 'updated')
  49. search_fields = ('url', 'timestamp', 'title', 'tags')
  50. fields = (*readonly_fields, 'title', 'tags')
  51. list_filter = ('added', 'updated', 'tags')
  52. ordering = ['-added']
  53. actions = [delete_snapshots, overwrite_snapshots, update_snapshots, update_titles, verify_snapshots]
  54. actions_template = 'admin/actions_as_select.html'
  55. def id_str(self, obj):
  56. return format_html(
  57. '<code style="font-size: 10px">{}</code>',
  58. obj.url_hash[:8],
  59. )
  60. def title_str(self, obj):
  61. canon = obj.as_link().canonical_outputs()
  62. tags = ''.join(
  63. format_html('<span>{}</span>', tag.strip())
  64. for tag in obj.tags.split(',')
  65. ) if obj.tags else ''
  66. return format_html(
  67. '<a href="/{}">'
  68. '<img src="/{}/{}" class="favicon" onerror="this.remove()">'
  69. '</a>'
  70. '<a href="/{}/index.html">'
  71. '<b class="status-{}">{}</b>'
  72. '</a>',
  73. obj.archive_path,
  74. obj.archive_path, canon['favicon_path'],
  75. obj.archive_path,
  76. 'fetched' if obj.latest_title or obj.title else 'pending',
  77. urldecode(htmldecode(obj.latest_title or obj.title or ''))[:128] or 'Pending...'
  78. ) + mark_safe(f'<span class="tags">{tags}</span>')
  79. def files(self, obj):
  80. return get_icons(obj)
  81. def size(self, obj):
  82. return format_html(
  83. '<a href="/{}" title="View all files">{}</a>',
  84. obj.archive_path,
  85. printable_filesize(obj.archive_size) if obj.archive_size else 'pending',
  86. )
  87. def url_str(self, obj):
  88. return format_html(
  89. '<a href="{}">{}</a>',
  90. obj.url,
  91. obj.url.split('://www.', 1)[-1].split('://', 1)[-1][:64],
  92. )
  93. id_str.short_description = 'ID'
  94. title_str.short_description = 'Title'
  95. url_str.short_description = 'Original URL'
  96. id_str.admin_order_field = 'id'
  97. title_str.admin_order_field = 'title'
  98. url_str.admin_order_field = 'url'
  99. class ArchiveBoxAdmin(admin.AdminSite):
  100. site_header = 'ArchiveBox'
  101. index_title = 'Links'
  102. site_title = 'Index'
  103. def get_urls(self):
  104. return [
  105. path('core/snapshot/add/', self.add_view, name='Add'),
  106. ] + super().get_urls()
  107. def add_view(self, request):
  108. if not request.user.is_authenticated:
  109. return redirect(f'/admin/login/?next={request.path}')
  110. request.current_app = self.name
  111. context = {
  112. **self.each_context(request),
  113. 'title': 'Add URLs',
  114. }
  115. if request.method == 'GET':
  116. context['form'] = AddLinkForm()
  117. elif request.method == 'POST':
  118. form = AddLinkForm(request.POST)
  119. if form.is_valid():
  120. url = form.cleaned_data["url"]
  121. print(f'[+] Adding URL: {url}')
  122. depth = 0 if form.cleaned_data["depth"] == "0" else 1
  123. input_kwargs = {
  124. "urls": url,
  125. "depth": depth,
  126. "update_all": False,
  127. "out_dir": OUTPUT_DIR,
  128. }
  129. add_stdout = StringIO()
  130. with redirect_stdout(add_stdout):
  131. add(**input_kwargs)
  132. print(add_stdout.getvalue())
  133. context.update({
  134. "stdout": ansi_to_html(add_stdout.getvalue().strip()),
  135. "form": AddLinkForm()
  136. })
  137. else:
  138. context["form"] = form
  139. return render(template_name='add_links.html', request=request, context=context)
  140. admin.site = ArchiveBoxAdmin()
  141. admin.site.register(get_user_model())
  142. admin.site.register(Snapshot, SnapshotAdmin)
  143. admin.site.disable_action('delete_selected')