-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviews.py
More file actions
734 lines (593 loc) · 20.8 KB
/
Copy pathviews.py
File metadata and controls
734 lines (593 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
import csv
import magic
from django.shortcuts import render, get_object_or_404, redirect, HttpResponse
from django.urls import reverse
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib import messages
from django.http import Http404
from django.db.models import Q
from django.utils import timezone
from plugins.books import models, forms, files, logic
from core import files as core_files
from repository import models as repository_models
def index(request, category_slug=None):
category = None
today = timezone.now().date()
books = models.Book.objects.filter(
Q(date_published__lte=today) &
(Q(date_embargo__isnull=True) | Q(date_embargo__lte=today))
).order_by('-date_published')
if category_slug:
category = get_object_or_404(
models.Category,
slug=category_slug,
)
books = books.filter(categories=category)
template = 'books/{}/index.html'.format(request.press.theme)
context = {
'books': books,
'category': category,
'book_settings': logic.get_book_settings(),
}
return render(request, template, context)
def view_book(request, book_id):
book = get_object_or_404(
models.Book,
pk=book_id,
date_published__isnull=False,
)
template = 'books/{}/book.html'.format(request.press.theme)
context = {
'book': book,
'book_settings': logic.get_book_settings(),
}
return render(request, template, context)
def download_format(request, book_id, format_id, mark_download='yes'):
# Forcing a session to be created where people link directly to the book.
request.session.save()
book = get_object_or_404(models.Book, pk=book_id, date_published__isnull=False)
format = get_object_or_404(models.Format, pk=format_id, book=book)
if mark_download == 'yes':
format.add_book_access(request, 'download')
# Handle serving the file here
return files.serve_book_file(format)
def read_epub(request, book_id, format_id):
# Forcing a session to be created where people link directly to the book.
request.session.save()
book = get_object_or_404(models.Book, pk=book_id)
format = get_object_or_404(models.Format, pk=format_id, book=book)
mime = magic.from_file(files.get_file_path(format), mime=True)
if not mime == 'application/epub+zip':
raise Http404
format.add_book_access(request, 'view')
template = 'books/book_epub.html'
context = {
'book': book,
'format': format,
}
return render(request, template, context)
def download_chapter(request, book_id, chapter_id, mark_download='yes'):
# Forcing a session to be created where people link directly to the book.
request.session.save()
book = get_object_or_404(
models.Book,
pk=book_id,
date_published__isnull=False,
)
chapter = get_object_or_404(
models.Chapter,
pk=chapter_id,
book=book,
)
chapter_format = models.ChapterFormat.objects.filter(chapter=chapter).first()
if not chapter_format:
raise Http404
if mark_download == 'yes':
chapter.add_book_access(request, 'download')
return files.serve_chapter_format_file(chapter_format)
def download_chapter_format(request, book_id, chapter_id, chapter_format_id, mark_download='yes'):
request.session.save()
book = get_object_or_404(
models.Book,
pk=book_id,
date_published__isnull=False,
)
chapter = get_object_or_404(
models.Chapter,
pk=chapter_id,
book=book,
)
chapter_format = get_object_or_404(
models.ChapterFormat,
pk=chapter_format_id,
chapter=chapter,
)
if mark_download == 'yes':
chapter.add_book_access(request, 'download')
return files.serve_chapter_format_file(chapter_format)
@staff_member_required
def admin(request):
books = models.Book.objects.all()
template = 'books/admin.html'
context = {
'books': books,
}
return render(request, template, context)
@staff_member_required
def edit_book(request, book_id=None):
book = None
if book_id:
book = get_object_or_404(models.Book, pk=book_id)
form = forms.BookForm(instance=book)
if request.POST:
form = forms.BookForm(request.POST, request.FILES, instance=book)
if form.is_valid():
form.save()
return redirect(reverse('books_admin'))
contributor_links = []
formats = []
chapters = []
if book:
contributor_links = models.ContributorLink.objects.filter(
book=book,
).order_by('order')
formats = models.Format.objects.filter(book=book).order_by('sequence')
chapters = models.Chapter.objects.filter(book=book).order_by('sequence')
template = 'books/edit_book.html'
context = {
'book': book,
'form': form,
'contributor_links': contributor_links,
'formats': formats,
'chapters': chapters,
}
return render(request, template, context)
@staff_member_required()
def edit_contributor(request, book_id, contributor_id=None, chapter_id=None):
contributor = None
book = get_object_or_404(models.Book, pk=book_id)
chapter = None
if chapter_id:
chapter = get_object_or_404(
models.Chapter,
pk=chapter_id,
book=book,
)
if contributor_id:
if chapter:
contributor = get_object_or_404(
models.Contributor,
pk=contributor_id,
contributorlink__chapter=chapter,
)
else:
contributor = get_object_or_404(
models.Contributor,
pk=contributor_id,
contributorlink__book=book,
)
if chapter:
return_url = reverse(
'books_edit_chapter',
kwargs={'book_id': book.pk, 'chapter_id': chapter.pk},
)
else:
return_url = reverse(
'books_edit_book',
kwargs={'book_id': book.pk},
)
form = forms.ContributorForm(instance=contributor)
if request.POST:
if contributor and "delete" in request.POST:
logic.remove_contributor(contributor, book=book, chapter=chapter)
messages.success(request, 'Contributor removed.')
return redirect(return_url)
form = forms.ContributorForm(request.POST, request.FILES, instance=contributor)
if form.is_valid():
form_contributor = form.save()
if not contributor:
# New contributor: link to the chapter when editing in a
# chapter context, otherwise to the book.
if chapter:
models.ContributorLink.objects.create(
contributor=form_contributor,
chapter=chapter,
order=chapter.get_next_contributor_order(),
)
else:
models.ContributorLink.objects.create(
contributor=form_contributor,
book=book,
order=book.get_next_contributor_order(),
)
return redirect(return_url)
template = 'books/edit_contributor.html'
context = {
'book': book,
'chapter': chapter,
'contributor': contributor,
'form': form,
'return_url': return_url,
}
return render(request, template, context)
@staff_member_required
def edit_format(request, book_id, format_id=None):
book_format = None
book = get_object_or_404(
models.Book,
pk=book_id,
)
if format_id:
book_format = get_object_or_404(
models.Format,
pk=format_id,
book=book,
)
form = forms.FormatForm(instance=book_format)
if request.POST:
if book_format and "delete" in request.POST:
book_format.delete()
messages.success(request, 'Format deleted.')
return redirect(
reverse(
'books_edit_book',
kwargs={'book_id': book.pk},
)
)
form = forms.FormatForm(request.POST, request.FILES, instance=book_format)
if form.is_valid():
form_format = form.save(commit=False)
form_format.book = book
form_format.save()
return redirect(reverse('books_edit_book', kwargs={'book_id': book.pk}))
template = 'books/edit_format.html'
context = {
'book': book,
'format': book_format,
'form': form,
}
return render(request, template, context)
@staff_member_required
def edit_chapter_format(request, book_id, chapter_id, chapter_format_id=None):
book = get_object_or_404(models.Book, pk=book_id)
chapter = get_object_or_404(models.Chapter, pk=chapter_id, book=book)
chapter_format = None
if chapter_format_id:
chapter_format = get_object_or_404(
models.ChapterFormat,
pk=chapter_format_id,
chapter=chapter,
)
form = forms.ChapterFormatForm(instance=chapter_format)
if request.POST:
if chapter_format and 'delete' in request.POST:
chapter_format.delete()
messages.success(request, 'Chapter format deleted.')
return redirect(
reverse('books_edit_chapter', kwargs={'book_id': book.pk, 'chapter_id': chapter.pk})
)
form = forms.ChapterFormatForm(request.POST, request.FILES, instance=chapter_format)
if form.is_valid():
saved_format = form.save(commit=False)
saved_format.chapter = chapter
saved_format.save()
messages.success(request, 'Chapter format saved.')
return redirect(
reverse('books_edit_chapter', kwargs={'book_id': book.pk, 'chapter_id': chapter.pk})
)
template = 'books/edit_chapter_format.html'
context = {
'book': book,
'chapter': chapter,
'chapter_format': chapter_format,
'form': form,
}
return render(request, template, context)
@staff_member_required
def import_books_upload(request):
"""
Presents an interface for a CSV file of book metadata to be uploaded for processing.
:param request: HttpRequest object
:return: HttpResponse or HttpRedirect on Post
"""
if request.GET.get('download') == 'true':
# Generates a sample CSV and serves it.
response = HttpResponse(content_type='text/csv')
writer = csv.writer(response)
writer.writerow(files.CSV_HEADERS)
writer.writerow(files.CSV_EXAMPLE)
response['Content-Disposition'] = 'attachment; filename="janeway_book_import_example.csv"'
return response
if request.POST and request.FILES:
temp_file = core_files.save_file_to_temp(request.FILES.get('import'))
return redirect(reverse('books_import_preview', kwargs={'uuid': temp_file[0].split('.')[0]}))
elif request.POST and not request.FILES:
messages.add_message(request, messages.INFO, 'No file provided')
template = 'books/import_books_upload.html'
context = {}
return render(request, template, context)
@staff_member_required
def import_books_preview(request, uuid):
uuid_csv = '{uuid}.csv'.format(uuid=uuid)
try:
has_error, error_message, has_error_lines, error_lines, good_lines = files.verify_upload(uuid_csv)
except Exception as e:
has_error = True
error_message = ['There was a general error processing the uploaded file: {0}.'.format(e)]
if has_error:
return render(request, 'books/import_has_error.html', {'error_message': error_message})
return render(request, 'books/import_verify.html', {'headers': files.CSV_HEADERS,
'good_rows': good_lines,
'has_error_lines': has_error_lines,
'error_lines:': error_lines,
'UUID': uuid})
@staff_member_required
def import_books_process(request, uuid):
uuid = '{uuid}.csv'.format(uuid=uuid)
if request.POST:
files.perform_book_import(uuid)
return redirect(reverse('books_admin'))
else:
messages.add_message(request, messages.INFO, 'Post required')
return redirect(reverse('books_import_preview', kwargs={'uuid': uuid}))
def export_onix_xml(
request,
book_id=None,
):
# Get the books based on the optional book_id parameter
books = models.Book.objects.all() if book_id is None else models.Book.objects.filter(pk=book_id)
# Use an ONIX-compliant XML template
template = 'books/onix.xml'
context = {
'books': books,
'chapters': models.Chapter.objects.filter(book__in=books),
'contributors': models.Contributor.objects.filter(contributorlink__book__in=books).distinct(),
}
xml_content = render(request, template, context).content
return HttpResponse(
xml_content,
content_type='application/xml',
)
@staff_member_required
def book_metrics(request):
"""
Fetches a list of books and displays their metrics between two dates.
:param request: HttpRequest
:return: HttpResponse
"""
start_date, end_date = logic.get_start_and_end_date(request)
date_form = forms.DateForm(
initial={'start_date': start_date, 'end_date': end_date}
)
books = models.Book.objects.filter(date_published__isnull=False)
data = logic.book_metrics_data(books, start_date, end_date)
template = 'books/metrics.html'
context = {
'books': books,
'data': data,
'date_form': date_form,
}
return render(request, template, context)
@staff_member_required
def book_metrics_by_month(request):
"""
Fetches a list of books and displays their usage by month.
:param request: HttpRequest
:return: HttpResponse
"""
start_month, end_month, date_parts = logic.get_start_and_end_months(request)
books = models.Book.objects.all()
month_form = forms.MonthForm(
initial={
'start_month': start_month, 'end_month': end_month,
}
)
data, dates, current_year, previous_year = logic.book_metrics_by_month(
books,
date_parts,
)
if request.method == 'POST':
return logic.export_metrics_by_month(
dates,
data,
)
template = 'books/metrics_by_month.html'
context = {
'month_form': month_form,
'books': books,
'data': data,
'dates': dates,
}
return render(request, template, context)
@staff_member_required
def books_chapter(request, book_id, chapter_id=None):
"""
Allows for creation of new or editing of existing chapters.
:param request: HttpRequest object
:pram book_id: int Book object pk
:param chapter_id: optional int Chapter object pk
:return: HttpResponse or HttpRedirect
"""
book = get_object_or_404(models.Book, pk=book_id)
chapter = None
if chapter_id:
chapter = get_object_or_404(models.Chapter, pk=chapter_id)
form = forms.ChapterForm(
instance=chapter,
items=logic.get_chapter_contributor_items(book),
initial={
'sequence': book.get_next_chapter_sequence() if not chapter else chapter.sequence,
}
)
if request.POST:
if chapter and "delete" in request.POST:
chapter.delete()
messages.success(request, 'Chapter deleted.')
return redirect(
reverse(
'books_edit_book',
kwargs={'book_id': book.pk},
)
)
form = forms.ChapterForm(
request.POST,
request.FILES,
instance=chapter,
items=logic.get_chapter_contributor_items(book),
)
if form.is_valid():
saved_chapter = form.save(book=book)
form.save_chapter_contributors(saved_chapter)
messages.add_message(
request,
messages.SUCCESS,
'Chapter Saved.',
)
return redirect(
reverse(
'books_edit_book',
kwargs={'book_id': book.pk},
)
)
contributor_links = []
chapter_formats = []
if chapter:
contributor_links = models.ContributorLink.objects.filter(
chapter=chapter,
).order_by('order')
chapter_formats = models.ChapterFormat.objects.filter(
chapter=chapter,
).order_by('sequence')
template = 'books/chapter.html'
context = {
'form': form,
'book': book,
'chapter': chapter,
'contributor_links': contributor_links,
'chapter_formats': chapter_formats,
}
return render(request, template, context)
def view_chapter(request, book_id, chapter_id):
"""
Displays details of a chapter.
:param request: HttpRequest object
:param book_id: Book object PK
:param chapter_id: Chapter object PK
:return: HttpResponse
"""
book = get_object_or_404(models.Book, pk=book_id)
chapter = get_object_or_404(models.Chapter, pk=chapter_id)
template = 'books/view_chapter.html'
if request.press.theme == 'OLH':
template = 'books/OLH/view_chapter.html'
context = {
'book': book,
'chapter': chapter,
}
return render(request, template, context)
@staff_member_required
def categories(request, category_id=None):
"""
Lists all categories.
"""
all_categories = models.Category.objects.all()
category, fire_redirect = None, False
if category_id:
category = get_object_or_404(
models.Category,
pk=category_id,
)
form = forms.CategoryForm(instance=category)
if request.POST:
if 'delete' in request.POST:
delete_id = request.POST.get('delete')
get_object_or_404(
models.Category,
pk=delete_id,
).delete()
messages.add_message(
request,
messages.ERROR,
'Category deleted',
)
fire_redirect = True
if 'save' in request.POST:
form = forms.CategoryForm(
request.POST,
instance=category,
)
if form.is_valid():
form.save()
messages.add_message(
request,
messages.SUCCESS,
'Category saved.',
)
fire_redirect = True
if fire_redirect:
return redirect(
reverse(
'books_categories',
)
)
template = 'books/categories.html'
context = {
'categories': all_categories,
'form': form,
}
return render(request, template, context)
@staff_member_required
def book_preprint_management_view(
request,
book_id,
):
"""Manage linked preprints for a given book."""
book = get_object_or_404(
models.Book,
id=book_id,
)
# Fetch linked preprints through the BookPreprint model
linked_preprints = models.BookPreprint.objects.filter(
book=book,
).order_by('order')
# Fetch available preprints that are not already linked
available_preprints = repository_models.Preprint.objects.exclude(
id__in=linked_preprints.values_list('preprint_id', flat=True),
)
# Initialize the form for adding a new preprint
form = forms.PreprintSelectionForm(
request.POST or None,
available_preprints=available_preprints,
)
if request.method == 'POST' and 'preprint_id' in request.POST:
# Handle linking a new preprint
if form.is_valid():
preprint = form.cleaned_data['preprint_id']
# Create a new BookPreprint entry with the next available order
max_order = models.BookPreprint.objects.filter(
book=book,
).count()
models.BookPreprint.objects.create(
book=book,
preprint=preprint,
order=max_order,
)
messages.success(
request,
'Preprint linked to book.',
)
return redirect(
'book_preprint_management',
book_id=book.id,
)
context = {
'book': book,
'linked_preprints': linked_preprints,
'available_preprints': available_preprints,
'form': form,
}
return render(
request,
'books/book_preprint_manager.html',
context,
)