diff --git a/app/library/models.py b/app/library/models.py
index 63b68f0..77cb216 100644
--- a/app/library/models.py
+++ b/app/library/models.py
@@ -202,13 +202,14 @@ class Work(models.Model):
def folder(self):
return f"{slugify(self.composer)}/{slugify(self.name)}-{self.pk:04d}"
- def extract(self, *tags):
-
+ def tagged_sections(self, *tags):
qs = self.docs.filter(sections__tag__in=tags)
qs = qs.annotate(Count('sections'), end=Min('sections__end'), start=Max('sections__start')) \
.filter(sections__count=len(tags))
-
- return list(qs.values_list('upload', 'start', 'end'))
+ return qs
+
+ def list_sections(self, *tags):
+ return list(self.tagged_sections(*tags).values_list('upload', 'start', 'end'))
@property
def digital_parts(self):
@@ -276,6 +277,14 @@ class Work(models.Model):
assigned = set(self.assigned_instruments())
return [ x for x in self.orchestration.as_list() if not x[0] in assigned ]
+ def music_tags(self):
+ tags = dict(self.orchestration.as_list())
+ for section in Section.objects.filter(doc__work_id=self.pk):
+ tags.setdefault(section.tag, section.name)
+
+ return tags.items()
+
+
def __str__(self):
return f"{self.name} ({self.composer})"
diff --git a/app/library/pdf_utils.py b/app/library/pdf_utils.py
index c0e5b67..a9eec64 100644
--- a/app/library/pdf_utils.py
+++ b/app/library/pdf_utils.py
@@ -24,12 +24,12 @@ def extract_and_concat(items):
if count == 0:
continue
- if start is None:
+ if not start:
sections.append(source)
else:
- if end is None:
+ if not end:
end = start
dest = os.path.join(d.name, f'section_{i}.pdf')
diff --git a/app/library/templates/library/document_annotate.html b/app/library/templates/library/document_annotate.html
index 2cf3fba..78bd13b 100644
--- a/app/library/templates/library/document_annotate.html
+++ b/app/library/templates/library/document_annotate.html
@@ -75,7 +75,7 @@
- {% for tag, inst in document.work.unassigned_instruments %}
+ {% for tag, inst in document.work.music_tags %}
- {{ inst }}
{% endfor %}
- Add instrument
diff --git a/app/library/templates/library/work_detail.html b/app/library/templates/library/work_detail.html
index afc392e..ff49a66 100644
--- a/app/library/templates/library/work_detail.html
+++ b/app/library/templates/library/work_detail.html
@@ -87,15 +87,18 @@
Digital Parts
diff --git a/app/library/tests.py b/app/library/tests.py
index b6c6a1a..3063ca0 100644
--- a/app/library/tests.py
+++ b/app/library/tests.py
@@ -162,15 +162,15 @@ class LibraryTestCase(AccessTestCase):
doc.sections.create(tag=g)
# no tags - get nothing (should it be everything?)
- self.assertEqual(work.extract(), [])
+ self.assertEqual(work.list_sections(), [])
# single tag - should get just that range
- self.assertEqual(work.extract('vl-1'), [('sel/beethoven/some_quartet/some_quartet_vl-1.pdf', None, None)])
+ self.assertEqual(work.list_sections('vl-1'), [('sel/beethoven/some_quartet/some_quartet_vl-1.pdf', None, None)])
# single tag - returns all documents with that range
- result = work.extract('mvmt-2')
+ result = work.list_sections('mvmt-2')
self.assertEqual(len(result), 4)
# multiple tags - returns the overlapping portion of all documents that have all tags
- self.assertEqual(work.extract('vl-1', 'mvmt-2'), [('sel/beethoven/some_quartet/some_quartet_vl-1.pdf', 4, 8)])
- self.assertEqual(work.extract('vl-1', 'vl-2'), [])
\ No newline at end of file
+ self.assertEqual(work.list_sections('vl-1', 'mvmt-2'), [('sel/beethoven/some_quartet/some_quartet_vl-1.pdf', 4, 8)])
+ self.assertEqual(work.list_sections('vl-1', 'vl-2'), [])
\ No newline at end of file
diff --git a/app/library/urls.py b/app/library/urls.py
index 431b577..f816add 100644
--- a/app/library/urls.py
+++ b/app/library/urls.py
@@ -27,6 +27,7 @@ urlpatterns = [
path('collections//works//partset', views.WorkPartSetView.as_view(), name="work_partset"),
path('collections//works//add_to_project', views.WorkAddToProject.as_view(), name="work_add_to_project"),
path('collections//works//upload', views.WorkAddDocumentView.as_view(), name="document_add"),
+ path('collections//works//download', views.WorkDownloadView.as_view(), name="work_download"),
path('collections//docs//delete', views.DocumentDeleteView.as_view(), name="document_delete"),
path('collections//docs//download', views.DocumentDownloadView.as_view(), name="document_download"),
diff --git a/app/library/views/__init__.py b/app/library/views/__init__.py
index 7af3ddb..ed9dc15 100644
--- a/app/library/views/__init__.py
+++ b/app/library/views/__init__.py
@@ -19,7 +19,7 @@ import re
from interface.views import EnsembleMixin, ProjectMixin, AuthorizedResourceMixin
from interface.models import Project
from library.models import Collection, Work, Document, Section
-from library.music_tags import MUSIC_TAGS, MUSIC_TAG_BY_NAME
+from library.music_tags import MUSIC_TAGS, MUSIC_TAG_BY_NAME, MusicTag
from library import forms, models
from library.pdf_utils import extract_pages, extract_and_concat
@@ -308,6 +308,38 @@ class WorkPartSetView(CollectionMixin, DetailView):
works = works.filter(collection__allowed_ensembles__ensemble=self.request.ensemble_id)
return works
+class WorkDownloadView(CollectionMixin, SingleObjectMixin, View):
+ model = models.Work
+
+ def get(self, request, *args, **kwargs):
+ self.object = self.get_object()
+
+ tags = request.GET.getlist('tag')
+
+ if not tags:
+ raise Http404("No tags given")
+
+ sections = list(self.object.tagged_sections(*tags))
+ print(sections)
+
+ if len(sections) == 0:
+ raise Http404("No matching sections")
+
+ if len(sections) == 1 and sections[0].start == 0:
+ # bypass extraction and redirect to the url
+ logger.debug("Redirecting to url")
+ return redirect(sections[0].upload.url)
+
+ result = extract_and_concat([ (s.upload.path, s.upload.name, s.start, s.end, 1) for s in sections ])
+
+ tag_names = " - ".join([ str(MusicTag.from_tag(tag)) for tag in tags ])
+
+ download_name = f'{self.object.name} - {tag_names}.pdf'
+
+ response = FileResponse(result, content_type="application/pdf")
+ response['Content-Disposition'] = f'inline; filename="{download_name}"'
+ return response
+
class WorkAddDocumentView(CollectionMixin, CreateView):
template_name = "interface/default_form.html"
model = Document
diff --git a/app/library/views/api.py b/app/library/views/api.py
index fa1b2b5..596a2d1 100644
--- a/app/library/views/api.py
+++ b/app/library/views/api.py
@@ -35,6 +35,7 @@ class WorkExportView(EnsembleMixin, WorkMixin, View):
from interface.views import AuthorizedResourceMixin
from rest_framework import routers, serializers, viewsets
+from rest_framework.exceptions import APIException
from library.models import Collection, Work, Document, Section, WorkMeta
@@ -72,14 +73,12 @@ class SectionSerializer(serializers.ModelSerializer):
def to_internal_value(self, data):
tag, start, end = data.split(":")
- try:
- start = int(start)
- except:
- start = 0
- try:
- end = int(end)
- except:
- end = 0
+ start = int(start)
+ end = int(end)
+ if start < 1:
+ start = None
+ if end < 1:
+ end = None
return super().to_internal_value({'tag': tag, 'start': start, 'end': end})
class DocumentSerializer(serializers.ModelSerializer):
@@ -139,7 +138,9 @@ class WorkSerializer(serializers.ModelSerializer):
filename = os.path.basename(url.path)
r = requests.get(d['upload'], stream=True)
- f = TemporaryUploadedFile(filename, r.headers['content-type'], r.headers['content-length'], r.encoding)
+ if r.status_code != 200:
+ raise APIException("Failed to download file")
+ f = TemporaryUploadedFile(filename, r.headers['content-type'], r.headers.get('content-length'), r.encoding)
shutil.copyfileobj(r.raw, f.file)
r.close()
d['upload'] = f