|
| 1 | +import datetime |
| 2 | + |
| 3 | +from collections import defaultdict |
| 4 | +from pathlib import Path |
| 5 | +from typing import List |
| 6 | + |
| 7 | +from django.contrib.admin.sites import AdminSite |
| 8 | +from django.http import Http404, FileResponse |
| 9 | +from django.shortcuts import resolve_url |
| 10 | +from django.views.generic import TemplateView |
| 11 | + |
| 12 | +from swp.models import Publication |
| 13 | +from swp.utils.admin import admin_url |
| 14 | +from swp.utils.spooling import iter_files, State, get_date |
| 15 | + |
| 16 | +SPOOLING_STATES: List[State] = [ |
| 17 | + 'error', |
| 18 | + 'todo', |
| 19 | + 'lost', |
| 20 | + 'done', |
| 21 | +] |
| 22 | + |
| 23 | + |
| 24 | +class SpoolingView(TemplateView): |
| 25 | + template_name = 'admin/spooling.html' |
| 26 | + |
| 27 | + site: AdminSite = None |
| 28 | + directory: Path = None |
| 29 | + |
| 30 | + def get_context_data(self, **kwargs): |
| 31 | + kwargs['title'] = 'Spooling' |
| 32 | + kwargs['files'] = {state: self.get_state_info(state) for state in SPOOLING_STATES} |
| 33 | + |
| 34 | + return TemplateView.get_context_data(self, **kwargs) |
| 35 | + |
| 36 | + def get_state_info(self, state: State): |
| 37 | + dates = defaultdict(list) |
| 38 | + |
| 39 | + for publication_id, filepath in iter_files(self.directory, state): |
| 40 | + filename = filepath.name |
| 41 | + date = filepath.parent.name |
| 42 | + |
| 43 | + publication_url = admin_url(Publication, 'change', publication_id, site=self.site) |
| 44 | + download_url = resolve_url('admin:spooling', state=state, date=date, filename=filename) |
| 45 | + |
| 46 | + info = publication_url, download_url, filename |
| 47 | + |
| 48 | + dates[date].append(info) |
| 49 | + |
| 50 | + return dict(dates) |
| 51 | + |
| 52 | + @staticmethod |
| 53 | + def file_response(directory: Path, state: State, date: datetime.date, filename: str): |
| 54 | + filepath = directory / state / get_date(date) / filename |
| 55 | + |
| 56 | + try: |
| 57 | + fp = open(filepath, 'rb') |
| 58 | + except FileNotFoundError as error: |
| 59 | + raise Http404 from error |
| 60 | + |
| 61 | + return FileResponse(fp, filename=filename) |
0 commit comments