This repository was archived by the owner on Apr 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathopds2_import.py
More file actions
871 lines (692 loc) · 28.6 KB
/
opds2_import.py
File metadata and controls
871 lines (692 loc) · 28.6 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
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
import logging
import webpub_manifest_parser.opds2.ast as opds2_ast
from flask_babel import lazy_gettext as _
from io import StringIO
from urllib.parse import urljoin, urlparse
from webpub_manifest_parser.errors import BaseError
from webpub_manifest_parser.opds2.parsers import OPDS2DocumentParserFactory
from webpub_manifest_parser.opds2.registry import (
OPDS2LinkRelationsRegistry,
OPDS2MediaTypesRegistry,
)
from webpub_manifest_parser.utils import encode, first_or_default
from .metadata_layer import (
CirculationData,
ContributorData,
FormatData,
IdentifierData,
LinkData,
Metadata,
SubjectData,
)
from .model import (
Contributor,
DeliveryMechanism,
Edition,
ExternalIntegration,
Hyperlink,
Identifier,
LicensePool,
LinkRelations,
MediaTypes,
Representation,
RightsStatus,
Subject,
)
from .opds_import import OPDSImporter, OPDSImportMonitor
from .util.http import BadResponseException
from .util.opds_writer import OPDSFeed
def parse_feed(feed, silent=True):
"""Parses the feed into OPDS2Feed object.
:param feed: OPDS 2.0 feed
:type feed: Union[str, opds2_ast.OPDS2Feed]
:param silent: Boolean value indicating whether to raise
:type silent: bool
:return: Parsed OPDS 2.0 feed
:rtype: opds2_ast.OPDS2Feed
"""
parsed_feed = None
if isinstance(feed, str):
try:
input_stream = StringIO(feed)
parser_factory = OPDS2DocumentParserFactory()
parser = parser_factory.create()
parsed_feed = parser.parse_stream(input_stream)
except BaseError:
logging.exception("Failed to parse the OPDS 2.0 feed")
if not silent:
raise
elif isinstance(feed, dict):
try:
parser_factory = OPDS2DocumentParserFactory()
parser = parser_factory.create()
parsed_feed = parser.parse_json(feed)
except BaseError:
logging.exception("Failed to parse the OPDS 2.0 feed")
if not silent:
raise
elif isinstance(feed, opds2_ast.OPDS2Feed):
parsed_feed = feed
else:
raise ValueError(
"Argument 'feed' must be either a string or instance of {0} class".format(opds2_ast.OPDS2Feed)
)
return parsed_feed
class OPDS2Importer(OPDSImporter):
"""Imports editions and license pools from an OPDS 2.0 feed."""
NAME = ExternalIntegration.OPDS2_IMPORT
DESCRIPTION = _("Import books from a publicly-accessible OPDS 2.0 feed.")
NEXT_LINK_RELATION = "next"
def __init__(
self,
db,
collection,
data_source_name=None,
identifier_mapping=None,
http_get=None,
metadata_client=None,
content_modifier=None,
map_from_collection=None,
mirrors=None,
):
"""Initialize a new instance of OPDS2Importer class.
:param db: Database session
:type db: sqlalchemy.orm.session.Session
:param collection: Circulation Manager's collection.
LicensePools created by this OPDS2Import class will be associated with the given Collection.
If this is None, no LicensePools will be created -- only Editions.
:type collection: Collection
:param data_source_name: Name of the source of this OPDS feed.
All Editions created by this import will be associated with this DataSource.
If there is no DataSource with this name, one will be created.
NOTE: If `collection` is provided, its .data_source will take precedence over any value provided here.
This is only for use when you are importing OPDS metadata without any particular Collection in mind.
:type data_source_name: str
:param identifier_mapping: Dictionary used for mapping external identifiers into a set of internal ones
:type identifier_mapping: Dict
:param metadata_client: A SimplifiedOPDSLookup object that is used to fill in missing metadata
:type metadata_client: SimplifiedOPDSLookup
:param content_modifier: A function that may modify-in-place representations (such as images and EPUB documents)
as they come in from the network.
:type content_modifier: Callable
:param map_from_collection: Identifier mapping
:type map_from_collection: Dict
:param mirrors: A dictionary of different MirrorUploader objects for different purposes
:type mirrors: Dict[MirrorUploader]
"""
super(OPDS2Importer, self).__init__(
db,
collection,
data_source_name,
identifier_mapping,
http_get,
metadata_client,
content_modifier,
map_from_collection,
mirrors,
)
self._logger = logging.getLogger(__name__)
def _extract_subjects(self, subjects):
"""Extract a list of SubjectData objects from the webpub-manifest-parser's subject.
:param subjects: Parsed subject object
:type subjects: List[core_ast.Subject]
:return: List of subjects metadata
:rtype: List[SubjectMetadata]
"""
self._logger.debug("Started extracting subjects metadata")
subject_metadata_list = []
for subject in subjects:
self._logger.debug(
"Started extracting subject metadata from {0}".format(encode(subject))
)
scheme = subject.scheme
subject_type = Subject.by_uri.get(scheme)
if not subject_type:
# We can't represent this subject because we don't
# know its scheme. Just treat it as a tag.
subject_type = Subject.TAG
subject_metadata = SubjectData(
type=subject_type, identifier=subject.code, name=subject.name, weight=1
)
subject_metadata_list.append(subject_metadata)
self._logger.debug(
"Finished extracting subject metadata from {0}: {1}".format(
encode(subject), encode(subject_metadata)
)
)
self._logger.debug(
"Finished extracting subjects metadata: {0}".format(
encode(subject_metadata_list)
)
)
return subject_metadata_list
def _extract_contributors(self, contributors, default_role=Contributor.AUTHOR_ROLE):
"""Extract a list of ContributorData objects from the webpub-manifest-parser's contributor.
:param contributors: Parsed contributor object
:type contributors: List[core_ast.Contributor]
:param default_role: Default role
:type default_role: Optional[str]
:return: List of contributors metadata
:rtype: List[ContributorData]
"""
self._logger.debug("Started extracting contributors metadata")
contributor_metadata_list = []
for contributor in contributors:
self._logger.debug(
"Started extracting contributor metadata from {0}".format(
encode(contributor)
)
)
contributor_metadata = ContributorData(
sort_name=contributor.sort_as,
display_name=contributor.name,
family_name=None,
wikipedia_name=None,
roles=contributor.roles if contributor.roles else default_role,
)
self._logger.debug(
"Finished extracting contributor metadata from {0}: {1}".format(
encode(contributor), encode(contributor_metadata)
)
)
contributor_metadata_list.append(contributor_metadata)
self._logger.debug(
"Finished extracting contributors metadata: {0}".format(
encode(contributor_metadata_list)
)
)
return contributor_metadata_list
def _extract_link(self, link, feed_self_url, default_link_rel=None):
"""Extract a LinkData object from webpub-manifest-parser's link.
:param link: webpub-manifest-parser's link
:type link: ast_core.Link
:param feed_self_url: Feed's self URL
:type feed_self_url: str
:param default_link_rel: Default link's relation
:type default_link_rel: Optional[str]
:return: Link metadata
:rtype: LinkData
"""
self._logger.debug(
"Started extracting link metadata from {0}".format(encode(link))
)
# FIXME: It seems that OPDS 2.0 spec doesn't contain information about rights so we use the default one.
rights_uri = RightsStatus.rights_uri_from_string("")
rel = first_or_default(link.rels, default_link_rel)
media_type = link.type
href = link.href
if feed_self_url and not urlparse(href).netloc:
# This link is relative, so we need to get the absolute url
href = urljoin(feed_self_url, href)
link_metadata = LinkData(
rel=rel,
href=href,
media_type=media_type,
rights_uri=rights_uri,
content=None,
)
self._logger.debug(
"Finished extracting link metadata from {0}: {1}".format(
encode(link), encode(link_metadata)
)
)
return link_metadata
def _extract_description_link(self, publication):
"""Extract description from the publication object and create a Hyperlink.DESCRIPTION link containing it.
:param publication: Publication object
:type publication: opds2_ast.Publication
:return: LinkData object containing publication's description
:rtype: LinkData
"""
self._logger.debug(
"Started extracting a description link from {0}".format(
encode(publication.metadata.description)
)
)
description_link = None
if publication.metadata.description:
description_link = LinkData(
rel=Hyperlink.DESCRIPTION,
media_type=MediaTypes.TEXT_PLAIN,
content=publication.metadata.description,
)
self._logger.debug(
"Finished extracting a description link from {0}: {1}".format(
encode(publication.metadata.description), encode(description_link)
)
)
return description_link
def _extract_image_links(self, publication, feed_self_url):
"""Extracts a list of LinkData objects containing information about artwork.
:param publication: Publication object
:type publication: ast_core.Publication
:param feed_self_url: Feed's self URL
:type feed_self_url: str
:return: List of links metadata
:rtype: List[LinkData]
"""
self._logger.debug(
"Started extracting image links from {0}".format(
encode(publication.images)
)
)
# FIXME: This code most likely will not work in general.
# There's no guarantee that these images have the same media type,
# or that the second-largest image isn't far too large to use as a thumbnail.
# Instead of using the second-largest image as a thumbnail,
# find the image that would make the best thumbnail
# because of its dimensions, media type, and aspect ratio:
# IDEAL_COVER_ASPECT_RATIO = 2.0/3
# IDEAL_IMAGE_HEIGHT = 240
# IDEAL_IMAGE_WIDTH = 160
sorted_raw_image_links = list(
reversed(
sorted(
publication.images.links, key=lambda link: (link.width or 0, link.height or 0)
)
)
)
image_links = []
if len(sorted_raw_image_links) > 0:
cover_link = self._extract_link(
sorted_raw_image_links[0],
feed_self_url,
default_link_rel=Hyperlink.IMAGE,
)
image_links.append(cover_link)
if len(sorted_raw_image_links) > 1:
cover_link = self._extract_link(
sorted_raw_image_links[1],
feed_self_url,
default_link_rel=Hyperlink.THUMBNAIL_IMAGE,
)
image_links.append(cover_link)
self._logger.debug(
"Finished extracting image links from {0}: {1}".format(
encode(publication.images), encode(image_links)
)
)
return image_links
def _extract_links(self, publication, feed_self_url):
"""Extract a list of LinkData objects from a list of webpub-manifest-parser links.
:param publication: Publication object
:type publication: ast_core.Publication
:param feed_self_url: Feed's self URL
:type feed_self_url: str
:return: List of links metadata
:rtype: List[LinkData]
"""
self._logger.debug(
"Started extracting links from {0}".format(encode(publication.links))
)
links = []
for link in publication.links:
link_metadata = self._extract_link(link, feed_self_url)
links.append(link_metadata)
description_link = self._extract_description_link(publication)
if description_link:
links.append(description_link)
image_links = self._extract_image_links(publication, feed_self_url)
if image_links:
links.extend(image_links)
self._logger.debug(
"Finished extracting links from {0}: {1}".format(
encode(publication.links), encode(links)
)
)
return links
def _extract_media_types_and_drm_scheme_from_link(self, link):
"""Extract information about content's media type and used DRM schema from the link.
:param link: Link object
:type link: ast_core.Link
:return: 2-tuple containing information about the content's media type and its DRM schema
:rtype: List[Tuple[str, str]]
"""
self._logger.debug(
"Started extracting media types and a DRM scheme from {0}".format(
encode(link)
)
)
media_types_and_drm_scheme = []
if link.properties:
if (
not link.properties.availability
or link.properties.availability.state
== opds2_ast.OPDS2AvailabilityType.AVAILABLE.value
):
for acquisition_object in link.properties.indirect_acquisition:
nested_acquisition_object = acquisition_object
while nested_acquisition_object.child:
nested_acquisition_object = first_or_default(
acquisition_object.child
)
drm_scheme = (
acquisition_object.type
if acquisition_object.type in DeliveryMechanism.KNOWN_DRM_TYPES
else DeliveryMechanism.NO_DRM
)
media_types_and_drm_scheme.append(
(nested_acquisition_object.type, drm_scheme)
)
else:
if (
link.type in MediaTypes.BOOK_MEDIA_TYPES
or link.type in MediaTypes.AUDIOBOOK_MEDIA_TYPES
):
media_types_and_drm_scheme.append((link.type, DeliveryMechanism.NO_DRM))
self._logger.debug(
"Finished extracting media types and a DRM scheme from {0}: {1}".format(
encode(link), encode(media_types_and_drm_scheme)
)
)
return media_types_and_drm_scheme
def _extract_medium_from_links(self, links):
"""Extract the publication's medium from its links.
:param links: List of links
:type links: ast_core.LinkList
:return: Publication's medium
:rtype: Optional[str]
"""
derived = None
for link in links:
if not link.rels or not link.type or not self._is_acquisition_link(link):
continue
link_media_type, _ = first_or_default(
self._extract_media_types_and_drm_scheme_from_link(link),
default=(None, None),
)
derived = Edition.medium_from_media_type(link_media_type)
if derived:
break
return derived
@staticmethod
def _extract_medium(publication, default_medium=Edition.BOOK_MEDIUM):
"""Extract the publication's medium from its metadata.
:param publication: Publication object
:type publication: opds2_core.OPDS2Publication
:return: Publication's medium
:rtype: str
"""
medium = default_medium
if publication.metadata.type:
medium = Edition.additional_type_to_medium.get(
publication.metadata.type, default_medium
)
return medium
def _extract_identifier(self, publication):
"""Extract the publication's identifier from its metadata.
:param publication: Publication object
:type publication: opds2_core.OPDS2Publication
:return: Identifier object
:rtype: Identifier
"""
return self._parse_identifier(publication.metadata.identifier)
def _extract_publication_metadata(self, feed, publication, data_source_name):
"""Extract a Metadata object from webpub-manifest-parser's publication.
:param publication: Feed object
:type publication: opds2_ast.OPDS2Feed
:param publication: Publication object
:type publication: opds2_ast.OPDS2Publication
:param data_source_name: Data source's name
:type data_source_name: str
:return: Publication's metadata
:rtype: Metadata
"""
self._logger.debug(
"Started extracting metadata from publication {0}".format(
encode(publication)
)
)
title = publication.metadata.title
if title == OPDSFeed.NO_TITLE:
title = None
subtitle = publication.metadata.subtitle
languages = first_or_default(publication.metadata.languages)
derived_medium = self._extract_medium_from_links(publication.links)
medium = self._extract_medium(publication, derived_medium)
publisher = first_or_default(publication.metadata.publishers)
if publisher:
publisher = publisher.name
imprint = first_or_default(publication.metadata.imprints)
if imprint:
imprint = imprint.name
published = publication.metadata.published
subjects = self._extract_subjects(publication.metadata.subjects)
contributors = (
self._extract_contributors(
publication.metadata.authors, Contributor.AUTHOR_ROLE
)
+ self._extract_contributors(
publication.metadata.translators, Contributor.TRANSLATOR_ROLE
)
+ self._extract_contributors(
publication.metadata.editors, Contributor.EDITOR_ROLE
)
+ self._extract_contributors(
publication.metadata.artists, Contributor.ARTIST_ROLE
)
+ self._extract_contributors(
publication.metadata.illustrators, Contributor.ILLUSTRATOR_ROLE
)
+ self._extract_contributors(
publication.metadata.letterers, Contributor.LETTERER_ROLE
)
+ self._extract_contributors(
publication.metadata.pencilers, Contributor.PENCILER_ROLE
)
+ self._extract_contributors(
publication.metadata.colorists, Contributor.COLORIST_ROLE
)
+ self._extract_contributors(
publication.metadata.inkers, Contributor.INKER_ROLE
)
+ self._extract_contributors(
publication.metadata.narrators, Contributor.NARRATOR_ROLE
)
+ self._extract_contributors(
publication.metadata.contributors, Contributor.CONTRIBUTOR_ROLE
)
)
feed_self_url = first_or_default(
feed.links.get_by_rel(OPDS2LinkRelationsRegistry.SELF.key)
).href
links = self._extract_links(publication, feed_self_url)
last_opds_update = publication.metadata.modified
identifier = self._extract_identifier(publication)
identifier_data = IdentifierData(
type=identifier.type, identifier=identifier.identifier
)
# FIXME: There are no measurements in OPDS 2.0
measurements = []
# FIXME: There is no series information in OPDS 2.0
series = None
series_position = None
# FIXME: It seems that OPDS 2.0 spec doesn't contain information about rights so we use the default one
rights_uri = RightsStatus.rights_uri_from_string("")
circulation_data = CirculationData(
default_rights_uri=rights_uri,
data_source=data_source_name,
primary_identifier=identifier_data,
links=links,
licenses_owned=LicensePool.UNLIMITED_ACCESS,
licenses_available=LicensePool.UNLIMITED_ACCESS,
licenses_reserved=0,
patrons_in_hold_queue=0,
formats=[],
)
formats = self._find_formats_in_non_open_access_acquisition_links(
publication.links, links, rights_uri, circulation_data
)
circulation_data.formats.extend(formats)
metadata = Metadata(
data_source=data_source_name,
title=title,
subtitle=subtitle,
language=languages,
medium=medium,
publisher=publisher,
published=published,
imprint=imprint,
primary_identifier=identifier_data,
subjects=subjects,
contributors=contributors,
measurements=measurements,
series=series,
series_position=series_position,
links=links,
data_source_last_updated=last_opds_update,
circulation=circulation_data,
)
self._logger.debug(
"Finished extracting metadata from publication {0}: {1}".format(
encode(publication), encode(metadata)
)
)
return metadata
def _find_formats_in_non_open_access_acquisition_links(
self, ast_link_list, link_data_list, rights_uri, circulation_data
):
"""Find circulation formats in non open-access acquisition links.
:param ast_link_list: List of Link objects
:type ast_link_list: List[ast_core.Link]
:param link_data_list: List of LinkData objects
:type link_data_list: List[LinkData]
:param rights_uri: Rights URI
:type rights_uri: str
:param circulation_data: Circulation data
:type circulation_data: CirculationData
:return: List of additional circulation formats found in non-open access links
:rtype: List[FormatData]
"""
formats = []
for ast_link, parsed_link in zip(ast_link_list, link_data_list):
if not self._is_acquisition_link(ast_link):
continue
if self._is_open_access_link_(parsed_link, circulation_data):
continue
for (
content_type,
drm_scheme,
) in self._extract_media_types_and_drm_scheme_from_link(ast_link):
formats.append(
FormatData(
content_type=content_type,
drm_scheme=drm_scheme,
link=parsed_link,
rights_uri=rights_uri,
)
)
return formats
@staticmethod
def _get_publications(feed):
"""Return all the publications in the feed.
:param feed: OPDS 2.0 feed
:type feed: opds2_ast.OPDS2Feed
:return: An iterable list of publications containing in the feed
:rtype: Iterable[opds2_ast.OPDS2Publication]
"""
if feed.publications:
for publication in feed.publications:
yield publication
if feed.groups:
for group in feed.groups:
if group.publications:
for publication in group.publications:
yield publication
@staticmethod
def _is_acquisition_link(link):
"""Return a boolean value indicating whether a link can be considered an acquisition link.
:param link: Link object
:type link: ast_core.Link
:return: Boolean value indicating whether a link can be considered an acquisition link
:rtype: bool
"""
return any(
[rel for rel in link.rels if rel in LinkRelations.CIRCULATION_ALLOWED]
)
@staticmethod
def _is_open_access_link_(link_data, circulation_data):
"""Return a boolean value indicating whether the specified LinkData object describes an open-access link.
:param link_data: LinkData object
:type link_data: LinkData
:param circulation_data: CirculationData object
:type circulation_data: CirculationData
"""
open_access_link = (
link_data.rel == Hyperlink.OPEN_ACCESS_DOWNLOAD and link_data.href
)
if open_access_link:
return True
# Try to deduce if the ast_link is open-access, even if it doesn't explicitly say it is
rights_uri = link_data.rights_uri or circulation_data.default_rights_uri
open_access_rights_link = (
link_data.media_type in Representation.BOOK_MEDIA_TYPES
and link_data.href
and rights_uri in RightsStatus.OPEN_ACCESS
)
return open_access_rights_link
def extract_next_links(self, feed):
"""Extracts "next" links from the feed.
:param feed: OPDS 2.0 feed
:type feed: Union[str, opds2_ast.OPDS2Feed]
:return: List of "next" links
:rtype: List[str]
"""
parsed_feed = parse_feed(feed)
if not parsed_feed:
return []
next_links = parsed_feed.links.get_by_rel(self.NEXT_LINK_RELATION)
next_links = [next_link.href for next_link in next_links]
return next_links
def extract_last_update_dates(self, feed):
"""Extract last update date of the feed.
:param feed: OPDS 2.0 feed
:type feed: Union[str, opds2_ast.OPDS2Feed]
:return: A list of 2-tuples containing publication's identifiers and their last modified dates
:rtype: List[Tuple[str, datetime.datetime]]
"""
parsed_feed = parse_feed(feed)
if not parsed_feed:
return []
dates = [
(publication.metadata.identifier, publication.metadata.modified)
for publication in self._get_publications(parsed_feed)
if publication.metadata.modified
]
return dates
def extract_feed_data(self, feed, feed_url=None):
"""Turn an OPDS 2.0 feed into lists of Metadata and CirculationData objects.
:param feed: OPDS 2.0 feed
:type feed: Union[str, opds2_ast.OPDS2Feed]
:param feed_url: Feed URL used to resolve relative links
:type feed_url: Optional[str]f
"""
feed = parse_feed(feed, silent=False)
publication_metadata_dictionary = {}
failures = {}
for publication in self._get_publications(feed):
publication_metadata = self._extract_publication_metadata(
feed, publication, self.data_source_name
)
publication_metadata_dictionary[
publication_metadata.primary_identifier.identifier
] = publication_metadata
return publication_metadata_dictionary, failures
class OPDS2ImportMonitor(OPDSImportMonitor):
PROTOCOL = ExternalIntegration.OPDS2_IMPORT
MEDIA_TYPE = OPDS2MediaTypesRegistry.OPDS_FEED.key, "application/json"
def _verify_media_type(self, url, status_code, headers, feed):
# Make sure we got an OPDS feed, and not an error page that was
# sent with a 200 status code.
media_type = headers.get("content-type")
if not media_type or not any(x in media_type for x in self.MEDIA_TYPE):
message = "Expected {0} OPDS 2.0 feed, got {1}".format(
self.MEDIA_TYPE, media_type
)
raise BadResponseException(
url, message=message, debug_message=feed, status_code=status_code
)
def _get_accept_header(self):
return "{0}, {1};q=0.9, */*;q=0.1".format(
OPDS2MediaTypesRegistry.OPDS_FEED.key, "application/json"
)