This repository has been archived by the owner on Dec 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
opds.py
2078 lines (1785 loc) · 73.4 KB
/
opds.py
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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import logging
from collections import defaultdict
from urllib.parse import quote
from lxml import etree
from sqlalchemy.orm.session import Session
from .cdn import cdnify
from .classifier import Classifier
from .entrypoint import EntryPoint
from .facets import FacetConstants
from .lane import (
Facets,
FacetsWithEntryPoint,
FeaturedFacets,
Lane,
Pagination,
SearchFacets,
)
from .model import (
CachedFeed,
Contributor,
DataSource,
Edition,
Hyperlink,
Identifier,
Measurement,
PresentationCalculationPolicy,
Subject,
Work,
)
from .util.datetime_helpers import utc_now
from .util.flask_util import OPDSEntryResponse, OPDSFeedResponse
from .util.opds_writer import AtomFeed, OPDSFeed, OPDSMessage
class UnfulfillableWork(Exception):
"""Raise this exception when it turns out a Work currently cannot be
fulfilled through any means, *and* this is a problem sufficient to
cancel the creation of an <entry> for the Work.
For commercial works, this might be because the collection
contains no licenses. For open-access works, it might be because
none of the delivery mechanisms could be mirrored.
"""
class Annotator(object):
"""The Annotator knows how to present an OPDS feed in a specific
application context.
"""
opds_cache_field = Work.simple_opds_entry.name
def is_work_entry_solo(self, work):
"""Return a boolean value indicating whether the work's OPDS catalog entry is served by itself,
rather than as a part of the feed.
:param work: Work object
:type work: core.model.work.Work
:return: Boolean value indicating whether the work's OPDS catalog entry is served by itself,
rather than as a part of the feed
:rtype: bool
"""
return False
def annotate_work_entry(
self, work, active_license_pool, edition, identifier, feed, entry, updated=None
):
"""Make any custom modifications necessary to integrate this
OPDS entry into the application's workflow.
:work: The Work whose OPDS entry is being annotated.
:active_license_pool: Of all the LicensePools associated with this
Work, the client has expressed interest in this one.
:edition: The Edition to use when associating bibliographic
metadata with this entry. You will probably not need to use
this, because bibliographic metadata was associated with
the entry when it was created.
:identifier: Of all the Identifiers associated with this
Work, the client has expressed interest in this one.
:param feed: An OPDSFeed -- the feed in which this entry will be
situated.
:param entry: An lxml Element object, the entry that will be added
to the feed.
"""
# First, try really hard to find an Identifier that we can
# use to make the <id> tag.
if not identifier:
if active_license_pool:
identifier = active_license_pool.identifier
elif edition:
identifier = edition.primary_identifier
if identifier:
entry.append(AtomFeed.id(identifier.urn))
# Add a permalink if one is available.
permalink_uri, permalink_type = self.permalink_for(
work, active_license_pool, identifier
)
if permalink_uri:
OPDSFeed.add_link_to_entry(
entry, rel="alternate", href=permalink_uri, type=permalink_type
)
if self.is_work_entry_solo(work):
OPDSFeed.add_link_to_entry(
entry, rel="self", href=permalink_uri, type=permalink_type
)
if active_license_pool:
data_source = active_license_pool.data_source.name
if data_source != DataSource.INTERNAL_PROCESSING:
# INTERNAL_PROCESSING indicates a dummy LicensePool
# created as a stand-in, e.g. by the metadata wrangler.
# This component is not actually distributing the book,
# so it should not have a bibframe:distribution tag.
provider_name_attr = "{%s}ProviderName" % AtomFeed.BIBFRAME_NS
kwargs = {provider_name_attr: data_source}
data_source_tag = AtomFeed.makeelement(
"{%s}distribution" % AtomFeed.BIBFRAME_NS, **kwargs
)
entry.extend([data_source_tag])
# We use Atom 'published' for the date the book first became
# available to people using this application.
avail = active_license_pool.availability_time
if avail:
now = utc_now()
today = datetime.date.today()
if isinstance(avail, datetime.datetime):
avail = avail.date()
if avail <= today: # Avoid obviously wrong values.
availability_tag = AtomFeed.makeelement("published")
# TODO: convert to local timezone.
availability_tag.text = AtomFeed._strftime(avail)
entry.extend([availability_tag])
# If this OPDS entry is being used as part of a grouped feed
# (which is up to the Annotator subclass), we need to add a
# group link.
group_uri, group_title = self.group_uri(work, active_license_pool, identifier)
if group_uri:
OPDSFeed.add_link_to_entry(
entry, rel=OPDSFeed.GROUP_REL, href=group_uri, title=str(group_title)
)
if not updated and work.last_update_time:
# NOTE: This is a default that works in most cases. When
# ordering ElasticSearch results by last update time,
# `work` is a WorkSearchResult object containing a more
# reliable value that you can use if you want.
updated = work.last_update_time
if updated:
entry.extend([AtomFeed.updated(AtomFeed._strftime(updated))])
@classmethod
def annotate_feed(cls, feed, lane, list=None):
"""Make any custom modifications necessary to integrate this
OPDS feed into the application's workflow.
"""
pass
@classmethod
def group_uri(cls, work, license_pool, identifier):
"""The URI to be associated with this Work when making it part of
a grouped feed.
By default, this does nothing. See circulation/LibraryAnnotator
for a subclass that does something.
:return: A 2-tuple (URI, title)
"""
return None, ""
@classmethod
def rating_tag(cls, type_uri, value):
"""Generate a schema:Rating tag for the given type and value."""
rating_tag = AtomFeed.makeelement(AtomFeed.schema_("Rating"))
value_key = AtomFeed.schema_("ratingValue")
rating_tag.set(value_key, "%.4f" % value)
if type_uri:
type_key = AtomFeed.schema_("additionalType")
rating_tag.set(type_key, type_uri)
return rating_tag
@classmethod
def cover_links(cls, work):
"""Return all links to be used as cover links for this work.
In a distribution application, each work will have only one
link. In a content server-type application, each work may have
a large number of links.
:return: A 2-tuple (thumbnail_links, full_links)
"""
thumbnails = []
full = []
if work:
_db = Session.object_session(work)
if work.cover_thumbnail_url:
thumbnails = [cdnify(work.cover_thumbnail_url)]
if work.cover_full_url:
full = [cdnify(work.cover_full_url)]
return thumbnails, full
@classmethod
def categories(cls, work):
"""Return all relevant classifications of this work.
:return: A dictionary mapping 'scheme' URLs to dictionaries of
attribute-value pairs.
Notable attributes: 'term', 'label', 'http://schema.org/ratingValue'
"""
if not work:
return {}
categories = {}
fiction_term = None
if work.fiction == True:
fiction_term = "Fiction"
elif work.fiction == False:
fiction_term = "Nonfiction"
if fiction_term:
fiction_scheme = Subject.SIMPLIFIED_FICTION_STATUS
categories[fiction_scheme] = [
dict(term=fiction_scheme + fiction_term, label=fiction_term)
]
simplified_genres = []
for wg in work.work_genres:
simplified_genres.append(wg.genre.name)
if simplified_genres:
categories[Subject.SIMPLIFIED_GENRE] = [
dict(term=Subject.SIMPLIFIED_GENRE + quote(x), label=x)
for x in simplified_genres
]
# Add the appeals as a category of schema
# http://librarysimplified.org/terms/appeal
schema_url = AtomFeed.SIMPLIFIED_NS + "appeals/"
appeals = []
categories[schema_url] = appeals
for name, value in (
(Work.CHARACTER_APPEAL, work.appeal_character),
(Work.LANGUAGE_APPEAL, work.appeal_language),
(Work.SETTING_APPEAL, work.appeal_setting),
(Work.STORY_APPEAL, work.appeal_story),
):
if value:
appeal = dict(term=schema_url + name, label=name)
weight_field = AtomFeed.schema_("ratingValue")
appeal[weight_field] = value
appeals.append(appeal)
# Add the audience as a category of schema
# http://schema.org/audience
if work.audience:
audience_uri = AtomFeed.SCHEMA_NS + "audience"
categories[audience_uri] = [dict(term=work.audience, label=work.audience)]
# Any book can have a target age, but the target age
# is only relevant for childrens' and YA books.
audiences_with_target_age = (
Classifier.AUDIENCE_CHILDREN,
Classifier.AUDIENCE_YOUNG_ADULT,
)
if work.target_age and work.audience in audiences_with_target_age:
uri = Subject.uri_lookup[Subject.AGE_RANGE]
target_age = work.target_age_string
if target_age:
categories[uri] = [dict(term=target_age, label=target_age)]
return categories
@classmethod
def authors(cls, work, edition):
"""Create one or more <author> and <contributor> tags for the given
Work.
:param work: The Work under consideration.
:param edition: The Edition to use as a reference
for bibliographic information, including the list of
Contributions.
"""
authors = list()
state = defaultdict(set)
for contribution in edition.contributions:
tag = cls.contributor_tag(contribution, state)
if tag is None:
# contributor_tag decided that this contribution doesn't
# need a tag.
continue
authors.append(tag)
if authors:
return authors
# We have no author information, so we add empty <author> tag
# to avoid the implication (per RFC 4287 4.2.1) that this book
# was written by whoever wrote the OPDS feed.
return [AtomFeed.author(AtomFeed.name(""))]
@classmethod
def contributor_tag(cls, contribution, state):
"""Build an <author> or <contributor> tag for a Contribution.
:param contribution: A Contribution.
:param state: A defaultdict of sets, which may be used to keep
track of what happened during previous calls to
contributor_tag for a given Work.
:return: A Tag, or None if creating a Tag for this Contribution
would be redundant or of low value.
"""
contributor = contribution.contributor
role = contribution.role
if role in Contributor.AUTHOR_ROLES:
tag_f = AtomFeed.author
marc_role = None
else:
tag_f = AtomFeed.contributor
marc_role = Contributor.MARC_ROLE_CODES.get(role)
if not marc_role:
# This contribution is not one that we publish as
# a <atom:contributor> tag. Skip it.
return None
name = contributor.display_name or contributor.sort_name
name_key = name.lower()
if name_key in state[marc_role]:
# We've already credited this person with this
# MARC role. Returning a tag would be redundant.
return None
# Okay, we're creating a tag.
properties = dict()
if marc_role:
properties["{%s}role" % AtomFeed.OPF_NS] = marc_role
tag = tag_f(AtomFeed.name(name), **properties)
# Record the fact that we credited this person with this role,
# so that we don't do it again on a subsequent call.
state[marc_role].add(name_key)
return tag
@classmethod
def series(cls, series_name, series_position):
"""Generate a schema:Series tag for the given name and position."""
if not series_name:
return None
series_details = dict()
series_details["name"] = series_name
if series_position != None:
series_details[AtomFeed.schema_("position")] = str(series_position)
series_tag = AtomFeed.makeelement(AtomFeed.schema_("Series"), **series_details)
return series_tag
@classmethod
def content(cls, work):
"""Return an HTML summary of this work."""
summary = ""
if work:
if work.summary_text != None:
summary = work.summary_text
elif work.summary and work.summary.content:
work.summary_text = work.summary.content
summary = work.summary_text
return summary
@classmethod
def lane_id(cls, lane):
return cls.featured_feed_url(lane)
@classmethod
def work_id(cls, work):
return work.presentation_edition.primary_identifier.urn
@classmethod
def permalink_for(cls, work, license_pool, identifier):
"""Generate a permanent link a client can follow for information about
this entry, and only this entry.
Note that permalink is distinct from the Atom <id>,
which is always the identifier's URN.
:return: A 2-tuple (URL, media type). If a single value is
returned, the media type will be presumed to be that of an
OPDS entry.
"""
# In the absence of any specific controllers, there is no
# permalink. This method must be defined in a subclass.
return None, None
@classmethod
def lane_url(cls, lane, facets=None):
raise NotImplementedError()
@classmethod
def feed_url(cls, lane, facets=None, pagination=None):
raise NotImplementedError()
@classmethod
def groups_url(cls, lane, facets=None):
raise NotImplementedError()
@classmethod
def search_url(cls, lane, query, pagination, facets=None):
raise NotImplementedError()
@classmethod
def default_lane_url(cls):
raise NotImplementedError()
@classmethod
def featured_feed_url(cls, lane, order=None, facets=None):
raise NotImplementedError()
@classmethod
def facet_url(cls, facets, facet=None):
return None
@classmethod
def navigation_url(cls, lane):
raise NotImplementedError()
@classmethod
def active_licensepool_for(cls, work):
"""Which license pool would be/has been used to issue a license for
this work?
"""
if not work:
return None
return work.active_license_pool()
def sort_works_for_groups_feed(self, works, **kwargs):
return works
class VerboseAnnotator(Annotator):
"""The default Annotator for machine-to-machine integration.
This Annotator describes all categories and authors for the book
in great detail.
"""
opds_cache_field = Work.verbose_opds_entry.name
def annotate_work_entry(
self, work, active_license_pool, edition, identifier, feed, entry
):
super(VerboseAnnotator, self).annotate_work_entry(
work, active_license_pool, edition, identifier, feed, entry
)
self.add_ratings(work, entry)
@classmethod
def add_ratings(cls, work, entry):
"""Add a quality rating to the work."""
for type_uri, value in [
(Measurement.QUALITY, work.quality),
(None, work.rating),
(Measurement.POPULARITY, work.popularity),
]:
if value:
entry.append(cls.rating_tag(type_uri, value))
@classmethod
def categories(cls, work, policy=None):
"""Send out _all_ categories for the work.
(So long as the category type has a URI associated with it in
Subject.uri_lookup.)
:param policy: A PresentationCalculationPolicy to
use when deciding how deep to go when finding equivalent
identifiers for the work.
"""
policy = policy or PresentationCalculationPolicy(
equivalent_identifier_cutoff=100
)
_db = Session.object_session(work)
by_scheme_and_term = dict()
identifier_ids = work.all_identifier_ids(policy=policy)
classifications = Identifier.classifications_for_identifier_ids(
_db, identifier_ids
)
for c in classifications:
subject = c.subject
if subject.type in Subject.uri_lookup:
scheme = Subject.uri_lookup[subject.type]
term = subject.identifier
weight_field = AtomFeed.schema_("ratingValue")
key = (scheme, term)
if not key in by_scheme_and_term:
value = dict(term=subject.identifier)
if subject.name:
value["label"] = subject.name
value[weight_field] = 0
by_scheme_and_term[key] = value
by_scheme_and_term[key][weight_field] += c.weight
# Collapse by_scheme_and_term to by_scheme
by_scheme = defaultdict(list)
for (scheme, term), value in list(by_scheme_and_term.items()):
by_scheme[scheme].append(value)
by_scheme.update(super(VerboseAnnotator, cls).categories(work))
return by_scheme
@classmethod
def authors(cls, work, edition):
"""Create a detailed <author> tag for each author."""
return [cls.detailed_author(author) for author in edition.author_contributors]
@classmethod
def detailed_author(cls, contributor):
"""Turn a Contributor into a detailed <author> tag."""
children = []
children.append(AtomFeed.name(contributor.display_name or ""))
sort_name = AtomFeed.makeelement("{%s}sort_name" % AtomFeed.SIMPLIFIED_NS)
sort_name.text = contributor.sort_name
children.append(sort_name)
if contributor.family_name:
family_name = AtomFeed.makeelement(AtomFeed.schema_("family_name"))
family_name.text = contributor.family_name
children.append(family_name)
if contributor.wikipedia_name:
wikipedia_name = AtomFeed.makeelement(
"{%s}wikipedia_name" % AtomFeed.SIMPLIFIED_NS
)
wikipedia_name.text = contributor.wikipedia_name
children.append(wikipedia_name)
if contributor.viaf:
viaf_tag = AtomFeed.makeelement(AtomFeed.schema_("sameas"))
viaf_tag.text = "http://viaf.org/viaf/%s" % contributor.viaf
children.append(viaf_tag)
if contributor.lc:
lc_tag = AtomFeed.makeelement(AtomFeed.schema_("sameas"))
lc_tag.text = "http://id.loc.gov/authorities/names/%s" % contributor.lc
children.append(lc_tag)
return AtomFeed.author(*children)
class AcquisitionFeed(OPDSFeed):
FACET_REL = "http://opds-spec.org/facet"
@classmethod
def groups(
cls,
_db,
title,
url,
worklist,
annotator,
pagination=None,
facets=None,
max_age=None,
search_engine=None,
search_debug=False,
**response_kwargs
):
"""The acquisition feed for 'featured' items from a given lane's
sublanes, organized into per-lane groups.
NOTE: If the lane has no sublanes, a grouped feed will
probably be unsatisfying. Call page() instead with an
appropriate Facets object.
:param pagination: A Pagination object. No single child of this lane
will contain more than `pagination.size` items.
:param facets: A GroupsFacet object.
:param response_kwargs: Extra keyword arguments to pass into
the OPDSFeedResponse constructor.
:return: An OPDSFeedResponse containing the feed.
"""
annotator = cls._make_annotator(annotator)
facets = facets or FeaturedFacets.default(worklist.get_library(_db))
def refresh():
return cls._generate_groups(
_db=_db,
title=title,
url=url,
worklist=worklist,
annotator=annotator,
pagination=pagination,
facets=facets,
search_engine=search_engine,
search_debug=search_debug,
)
return CachedFeed.fetch(
_db=_db,
worklist=worklist,
pagination=pagination,
facets=facets,
refresher_method=refresh,
max_age=max_age,
**response_kwargs
)
@classmethod
def _generate_groups(
cls,
_db,
title,
url,
worklist,
annotator,
pagination,
facets,
search_engine,
search_debug,
):
"""Internal method called by groups() when a grouped feed
must be regenerated.
"""
# Try to get a set of (Work, WorkList) 2-tuples
# to make a normal grouped feed.
works_and_lanes = [
x
for x in worklist.groups(
_db=_db,
pagination=pagination,
facets=facets,
search_engine=search_engine,
debug=search_debug,
)
]
# Make a typical grouped feed.
all_works = []
for work, sublane in works_and_lanes:
if sublane == worklist:
# We are looking at the groups feed for (e.g.)
# "Science Fiction", and we're seeing a book
# that is featured within "Science Fiction" itself
# rather than one of the sublanes.
#
# We want to assign this work to a group called "All
# Science Fiction" and point its 'group URI' to
# the linear feed of the "Science Fiction" lane
# (as opposed to the groups feed, which is where we
# are now).
v = dict(
lane=worklist,
label=worklist.display_name_for_all,
link_to_list_feed=True,
)
else:
# We are looking at the groups feed for (e.g.)
# "Science Fiction", and we're seeing a book
# that is featured within one of its sublanes,
# such as "Space Opera".
#
# We want to assign this work to a group derived
# from the sublane.
v = dict(lane=sublane)
annotator.lanes_by_work[work].append(v)
all_works.append(work)
all_works = annotator.sort_works_for_groups_feed(all_works)
feed = AcquisitionFeed(_db, title, url, all_works, annotator)
# Regardless of whether or not the entries in feed can be
# grouped together, we want to apply certain feed-level
# annotations.
# A grouped feed may link to alternate entry points into
# the data.
entrypoints = facets.selectable_entrypoints(worklist)
if entrypoints:
def make_link(ep):
return annotator.groups_url(
worklist, facets=facets.navigate(entrypoint=ep)
)
cls.add_entrypoint_links(feed, make_link, entrypoints, facets.entrypoint)
# A grouped feed may have breadcrumb links.
feed.add_breadcrumb_links(worklist, facets.entrypoint)
# Miscellaneous.
annotator.annotate_feed(feed, worklist)
return feed
@classmethod
def page(
cls,
_db,
title,
url,
worklist,
annotator,
facets=None,
pagination=None,
max_age=None,
search_engine=None,
search_debug=False,
**response_kwargs
):
"""Create a feed representing one page of works from a given lane.
:param response_kwargs: Extra keyword arguments to pass into
the OPDSFeedResponse constructor.
:return: An OPDSFeedResponse containing the feed.
"""
library = worklist.get_library(_db)
facets = facets or Facets.default(library)
pagination = pagination or Pagination.default()
annotator = cls._make_annotator(annotator)
def refresh():
return cls._generate_page(
_db,
title,
url,
worklist,
annotator,
facets,
pagination,
search_engine,
search_debug,
)
response_kwargs.setdefault("max_age", max_age)
return CachedFeed.fetch(
_db,
worklist=worklist,
pagination=pagination,
facets=facets,
refresher_method=refresh,
**response_kwargs
)
@classmethod
def _generate_page(
cls,
_db,
title,
url,
lane,
annotator,
facets,
pagination,
search_engine,
search_debug,
):
"""Internal method called by page() when a cached feed
must be regenerated.
"""
works = lane.works(
_db,
pagination=pagination,
facets=facets,
search_engine=search_engine,
debug=search_debug,
)
if not isinstance(works, list):
# It's possible that works() returned a database query or
# other generator-like object, but at this point we want
# an actual list of Work objects.
works = [x for x in works]
if not pagination.page_has_loaded:
# Depending on how the works were obtained,
# Pagination.page_loaded may or may not have been called
# yet.
pagination.page_loaded(works)
feed = cls(_db, title, url, works, annotator)
entrypoints = facets.selectable_entrypoints(lane)
if entrypoints:
# A paginated feed may have multiple entry points into the
# same dataset.
def make_link(ep):
return annotator.feed_url(lane, facets=facets.navigate(entrypoint=ep))
cls.add_entrypoint_links(feed, make_link, entrypoints, facets.entrypoint)
# Add URLs to change faceted views of the collection.
for args in cls.facet_links(annotator, facets):
OPDSFeed.add_link_to_feed(feed=feed.feed, **args)
if len(works) > 0 and pagination.has_next_page:
# There are works in this list. Add a 'next' link.
OPDSFeed.add_link_to_feed(
feed=feed.feed,
rel="next",
href=annotator.feed_url(lane, facets, pagination.next_page),
)
if pagination.offset > 0:
OPDSFeed.add_link_to_feed(
feed=feed.feed,
rel="first",
href=annotator.feed_url(lane, facets, pagination.first_page),
)
previous_page = pagination.previous_page
if previous_page:
OPDSFeed.add_link_to_feed(
feed=feed.feed,
rel="previous",
href=annotator.feed_url(lane, facets, previous_page),
)
if isinstance(facets, FacetsWithEntryPoint):
feed.add_breadcrumb_links(lane, facets.entrypoint)
annotator.annotate_feed(feed, lane)
return feed
@classmethod
def from_query(cls, query, _db, feed_name, url, pagination, url_fn, annotator):
"""Build a feed representing one page of a given list. Currently used for
creating an OPDS feed for a custom list and not cached.
TODO: This is used by the circulation manager admin interface.
Investigate changing the code that uses this to use the search
index -- this is inefficient and creates an alternate code path
that may harbor bugs.
TODO: This cannot currently return OPDSFeedResponse because the
admin interface modifies the feed after it's generated.
"""
page_of_works = pagination.modify_database_query(_db, query)
pagination.total_size = int(query.count())
feed = cls(_db, feed_name, url, page_of_works, annotator)
if pagination.total_size > 0 and pagination.has_next_page:
OPDSFeed.add_link_to_feed(
feed=feed.feed, rel="next", href=url_fn(pagination.next_page.offset)
)
if pagination.offset > 0:
OPDSFeed.add_link_to_feed(
feed=feed.feed, rel="first", href=url_fn(pagination.first_page.offset)
)
if pagination.previous_page:
OPDSFeed.add_link_to_feed(
feed=feed.feed,
rel="previous",
href=url_fn(pagination.previous_page.offset),
)
return feed
def as_response(self, **kwargs):
"""Convert this feed into an OPDSFEedResponse."""
return OPDSFeedResponse(self, **kwargs)
def as_error_response(self, **kwargs):
"""Convert this feed into an OPDSFEedResponse that should be treated
by intermediaries as an error -- that is, treated as private
and not cached.
"""
kwargs["max_age"] = 0
kwargs["private"] = True
return self.as_response(**kwargs)
@classmethod
def _make_annotator(cls, annotator):
"""Helper method to make sure there's some kind of Annotator."""
if not annotator:
annotator = Annotator
if callable(annotator):
annotator = annotator()
return annotator
@classmethod
def facet_link(cls, href, title, facet_group_name, is_active):
"""Build a set of attributes for a facet link.
:param href: Destination of the link.
:param title: Human-readable description of the facet.
:param facet_group_name: The facet group to which the facet belongs,
e.g. "Sort By".
:param is_active: True if this is the client's currently
selected facet.
:return: A dictionary of attributes, suitable for passing as
keyword arguments into OPDSFeed.add_link_to_feed.
"""
args = dict(href=href, title=title)
args["rel"] = cls.FACET_REL
args["{%s}facetGroup" % AtomFeed.OPDS_NS] = facet_group_name
if is_active:
args["{%s}activeFacet" % AtomFeed.OPDS_NS] = "true"
return args
@classmethod
def add_entrypoint_links(
cls, feed, url_generator, entrypoints, selected_entrypoint, group_name="Formats"
):
"""Add links to a feed forming an OPDS facet group for a set of
EntryPoints.
:param feed: A lxml Tag object.
:param url_generator: A callable that returns the entry point
URL when passed an EntryPoint.
:param entrypoints: A list of all EntryPoints in the facet group.
:param selected_entrypoint: The current EntryPoint, if selected.
"""
if len(entrypoints) == 1 and selected_entrypoint in (None, entrypoints[0]):
# There is only one entry point. Unless the currently
# selected entry point is somehow different, there's no
# need to put any links at all here -- a facet group with
# one one facet might as well not be there.
return
is_default = True
for entrypoint in entrypoints:
link = cls._entrypoint_link(
url_generator, entrypoint, selected_entrypoint, is_default, group_name
)
if link is not None:
cls.add_link_to_feed(feed.feed, **link)
is_default = False
@classmethod
def _entrypoint_link(
cls, url_generator, entrypoint, selected_entrypoint, is_default, group_name
):
"""Create arguments for add_link_to_feed for a link that navigates
between EntryPoints.
"""
display_title = EntryPoint.DISPLAY_TITLES.get(entrypoint)
if not display_title:
# Shouldn't happen.
return
url = url_generator(entrypoint)
is_selected = entrypoint is selected_entrypoint
link = cls.facet_link(url, display_title, group_name, is_selected)
# Unlike a normal facet group, every link in this facet
# group has an additional attribute marking it as an entry
# point.
#
# In OPDS 2 this can become an additional rel value,
# removing the need for a custom attribute.
link[
"{%s}facetGroupType" % AtomFeed.SIMPLIFIED_NS
] = FacetConstants.ENTRY_POINT_REL
return link
def add_breadcrumb_links(self, lane, entrypoint=None):
"""Add information necessary to find your current place in the
site's navigation.
A link with rel="start" points to the start of the site
A <simplified:entrypoint> section describes the current entry point.
A <simplified:breadcrumbs> section contains a sequence of
breadcrumb links.
"""
# Add the top-level link with rel='start'
xml = self.feed
annotator = self.annotator
top_level_title = annotator.top_level_title() or "Collection Home"
self.add_link_to_feed(
feed=xml,
rel="start",
href=annotator.default_lane_url(),
title=top_level_title,
)
# Add a link to the direct parent with rel="up".
#
# TODO: the 'direct parent' may be the same lane but without
# the entry point specified. Fixing this would also be a good
# opportunity to refactor the code for figuring out parent and
# parent_title.