This repository has been archived by the owner on Apr 11, 2022. It is now read-only.
/
opds_import.py
2014 lines (1727 loc) · 75.7 KB
/
opds_import.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
from nose.tools import set_trace
from io import (
StringIO,
BytesIO,
)
from collections import (
defaultdict,
Counter,
)
import datetime
import dateutil
import feedparser
import logging
import traceback
import urllib
from urlparse import urlparse, urljoin
from sqlalchemy.orm import aliased
from sqlalchemy.orm.session import Session
from flask_babel import lazy_gettext as _
from lxml import etree
from monitor import CollectionMonitor
from util import LanguageCodes
from util.xmlparser import XMLParser
from config import (
CannotLoadConfiguration,
Configuration,
IntegrationException,
)
from metadata_layer import (
CirculationData,
Metadata,
IdentifierData,
ContributorData,
LinkData,
MeasurementData,
SubjectData,
ReplacementPolicy,
TimestampData,
)
from model import (
Collection,
CoverageRecord,
DataSource,
Edition,
Equivalency,
ExternalIntegration,
Hyperlink,
Identifier,
LicensePool,
Measurement,
Representation,
RightsStatus,
Subject,
get_one,
)
from model.configuration import ExternalIntegrationLink
from model.constants import MediaTypes
from coverage import CoverageFailure
from util.http import (
BadResponseException,
HTTP,
)
from util.opds_writer import (
OPDSFeed,
OPDSMessage,
)
from util.string_helpers import base64
from mirror import MirrorUploader
from selftest import (
HasSelfTests,
SelfTestResult,
)
class AccessNotAuthenticated(Exception):
"""No authentication is configured for this service"""
pass
class SimplifiedOPDSLookup(object):
"""Tiny integration class for the Simplified 'lookup' protocol."""
LOOKUP_ENDPOINT = "lookup"
@classmethod
def check_content_type(cls, response):
content_type = response.headers.get('content-type')
if content_type != OPDSFeed.ACQUISITION_FEED_TYPE:
raise BadResponseException.from_response(
response.url,
"Wrong media type: %s" % content_type,
response
)
@classmethod
def from_protocol(cls, _db, protocol,
goal=ExternalIntegration.LICENSE_GOAL, library=None
):
integration = ExternalIntegration.lookup(
_db, protocol, goal, library=library
)
if not integration or not integration.url:
return None
return cls(integration.url)
def __init__(self, base_url):
if not base_url.endswith('/'):
base_url += "/"
self.base_url = base_url
@property
def lookup_endpoint(self):
return self.LOOKUP_ENDPOINT
def _get(self, url, **kwargs):
"""Make an HTTP request. This method is overridden in the mock class."""
kwargs['timeout'] = kwargs.get('timeout', 300)
kwargs['allowed_response_codes'] = kwargs.get('allowed_response_codes', [])
kwargs['allowed_response_codes'] += ['2xx', '3xx']
return HTTP.get_with_timeout(url, **kwargs)
def urn_args(self, identifiers):
return "&".join(set("urn=%s" % i.urn for i in identifiers))
def lookup(self, identifiers):
"""Retrieve an OPDS feed with metadata for the given identifiers."""
args = self.urn_args(identifiers)
url = self.base_url + self.lookup_endpoint + "?" + args
logging.info("Lookup URL: %s", url)
return self._get(url)
class MetadataWranglerOPDSLookup(SimplifiedOPDSLookup, HasSelfTests):
PROTOCOL = ExternalIntegration.METADATA_WRANGLER
NAME = _("Library Simplified Metadata Wrangler")
CARDINALITY = 1
SETTINGS = [
{ "key": ExternalIntegration.URL,
"label": _("URL"),
"default": "http://metadata.librarysimplified.org/",
"required": True,
"format": "url",
},
]
SITEWIDE = True
ADD_ENDPOINT = 'add'
ADD_WITH_METADATA_ENDPOINT = 'add_with_metadata'
METADATA_NEEDED_ENDPOINT = 'metadata_needed'
REMOVE_ENDPOINT = 'remove'
UPDATES_ENDPOINT = 'updates'
CANONICALIZE_ENDPOINT = 'canonical-author-name'
@classmethod
def from_config(cls, _db, collection=None):
integration = ExternalIntegration.lookup(
_db, ExternalIntegration.METADATA_WRANGLER,
ExternalIntegration.METADATA_GOAL
)
if not integration:
raise CannotLoadConfiguration(
"No ExternalIntegration found for the Metadata Wrangler.")
if not integration.url:
raise CannotLoadConfiguration("Metadata Wrangler improperly configured.")
return cls(
integration.url, shared_secret=integration.password,
collection=collection
)
@classmethod
def external_integration(cls, _db):
return ExternalIntegration.lookup(
_db, ExternalIntegration.METADATA_WRANGLER,
ExternalIntegration.METADATA_GOAL
)
def _run_self_tests(self, _db, lookup_class=None):
"""Run self-tests on every eligible Collection.
:param _db: A database connection.
:param lookup_class: Pass in a mock class to instantiate that
class as needed instead of MetadataWranglerOPDSLookup.
:return: A dictionary mapping Collection objects to lists of
SelfTestResult objects.
"""
lookup_class = lookup_class or MetadataWranglerOPDSLookup
results = dict()
# Find all eligible Collections on the system, instantiate a
# _new_ MetadataWranglerOPDSLookup for each, and call
# its _run_collection_self_tests method.
for c in _db.query(Collection):
try:
metadata_identifier = c.metadata_identifier
except ValueError, e:
continue
lookup = lookup_class.from_config(_db, c)
for i in lookup._run_collection_self_tests():
yield i
def _run_collection_self_tests(self):
"""Run the self-test suite on the Collection associated with this
MetadataWranglerOPDSLookup.
"""
if not self.collection:
return
metadata_identifier = None
try:
metadata_identifier = self.collection.metadata_identifier
except ValueError, e:
# This collection has no metadata identifier. It's
# probably a "Manual intervention" collection. It cannot
# interact with the metadata wrangler and there's no need
# to test it.
return
# Check various endpoints that yield OPDS feeds.
one_day_ago = datetime.datetime.utcnow() - datetime.timedelta(days=1)
for title, m, args in (
(
"Metadata updates in last 24 hours",
self.updates, [one_day_ago]
),
(
"Titles where we could (but haven't) provide information to the metadata wrangler",
self.metadata_needed, []
)
):
yield self._feed_self_test(title, m, *args)
def _feed_self_test(self, name, method, *args):
"""Retrieve a feed from the metadata wrangler and
turn it into a SelfTestResult.
"""
result = SelfTestResult(name)
result.collection = self.collection
# If the server returns a 500 error we don't want to raise an
# exception -- we want to record it as part of the test
# result.
kwargs = dict(allowed_response_codes=['%sxx' % f for f in range(1,6)])
response = method(*args, **kwargs)
self._annotate_feed_response(result, response)
# We're all done.
result.end = datetime.datetime.utcnow()
return result
@classmethod
def _annotate_feed_response(cls, result, response):
"""Parse an OPDS feed and annotate a SelfTestResult with some
information about it:
* How the feed was requested.
* What the response code was.
* The number of items on the first page.
* The title of each item on the page, if any.
* The total number of items in the feed, if available.
:param result: A SelfTestResult object.
:param response: A requests Response object.
"""
lines = []
lines.append("Request URL: %s" % response.url)
lines.append(
"Request authorization: %s" %
response.request.headers.get('Authorization')
)
lines.append("Status code: %d" % response.status_code)
result.success = response.status_code == 200
if result.success:
feed = feedparser.parse(response.content)
total_results = feed['feed'].get('opensearch_totalresults')
if total_results is not None:
lines.append(
"Total identifiers registered with this collection: %s" % (
total_results
)
)
lines.append("Entries on this page: %d" % len(feed['entries']))
for i in feed['entries']:
lines.append(" " + i['title'])
result.result = lines
def __init__(self, url, shared_secret=None, collection=None):
super(MetadataWranglerOPDSLookup, self).__init__(url)
self.shared_secret = shared_secret
self.collection = collection
@property
def authenticated(self):
return bool(self.shared_secret)
@property
def authorization(self):
if self.authenticated:
token = 'Bearer ' + base64.b64encode(self.shared_secret)
return { 'Authorization' : token }
return None
@property
def lookup_endpoint(self):
if not (self.authenticated and self.collection):
return self.LOOKUP_ENDPOINT
return self.collection.metadata_identifier + '/' + self.LOOKUP_ENDPOINT
def _get(self, url, **kwargs):
if self.authenticated:
headers = kwargs.get('headers', {})
headers.update(self.authorization)
kwargs['headers'] = headers
return super(MetadataWranglerOPDSLookup, self)._get(url, **kwargs)
def _post(self, url, data="", **kwargs):
"""Make an HTTP request. This method is overridden in the mock class."""
if self.authenticated:
headers = kwargs.get('headers', {})
headers.update(self.authorization)
kwargs['headers'] = headers
kwargs['timeout'] = kwargs.get('timeout', 120)
kwargs['allowed_response_codes'] = kwargs.get('allowed_response_codes', [])
kwargs['allowed_response_codes'] += ['2xx', '3xx']
return HTTP.post_with_timeout(url, data, **kwargs)
def add_args(self, url, arg_string):
joiner = '?'
if joiner in url:
# This URL already has an argument (namely: data_source), so
# append the new arguments.
joiner = '&'
return url + joiner + arg_string
def get_collection_url(self, endpoint):
if not self.authenticated:
raise AccessNotAuthenticated("Metadata Wrangler access not authenticated.")
if not self.collection:
raise ValueError("No Collection provided.")
data_source = ''
if self.collection.protocol == ExternalIntegration.OPDS_IMPORT:
# Open access OPDS_IMPORT collections need to send a DataSource to
# allow OPDS lookups on the Metadata Wrangler.
data_source = '?data_source=' + urllib.quote(self.collection.data_source.name)
return (self.base_url
+ self.collection.metadata_identifier
+ '/' + endpoint + data_source)
def add(self, identifiers):
"""Add items to an authenticated Metadata Wrangler Collection"""
add_url = self.get_collection_url(self.ADD_ENDPOINT)
url = self.add_args(add_url, self.urn_args(identifiers))
logging.info("Metadata Wrangler Collection Addition URL: %s", url)
return self._post(url)
def add_with_metadata(self, feed):
"""Add a feed of items with metadata to an authenticated Metadata Wrangler Collection."""
add_with_metadata_url = self.get_collection_url(self.ADD_WITH_METADATA_ENDPOINT)
return self._post(add_with_metadata_url, unicode(feed))
def metadata_needed(self, **kwargs):
"""Get a feed of items that need additional metadata to be processed
by the Metadata Wrangler.
"""
metadata_needed_url = self.get_collection_url(
self.METADATA_NEEDED_ENDPOINT
)
return self._get(metadata_needed_url, **kwargs)
def remove(self, identifiers):
"""Remove items from an authenticated Metadata Wrangler Collection"""
remove_url = self.get_collection_url(self.REMOVE_ENDPOINT)
url = self.add_args(remove_url, self.urn_args(identifiers))
logging.info("Metadata Wrangler Collection Removal URL: %s", url)
return self._post(url)
def updates(self, last_update_time, **kwargs):
"""Retrieve updated items from an authenticated Metadata
Wrangler Collection
:param last_update_time: DateTime representing the last time
an update was fetched. May be None.
"""
url = self.get_collection_url(self.UPDATES_ENDPOINT)
if last_update_time:
formatted_time = last_update_time.strftime('%Y-%m-%dT%H:%M:%SZ')
url = self.add_args(url, ('last_update_time='+formatted_time))
logging.info("Metadata Wrangler Collection Updates URL: %s", url)
return self._get(url, **kwargs)
def canonicalize_author_name(self, identifier, working_display_name):
"""Attempt to find the canonical name for the author of a book.
:param identifier: an ISBN-type Identifier.
:param working_display_name: The display name of the author
(i.e. the name format human being used as opposed to the name
that goes into library records).
"""
args = "display_name=%s" % (
urllib.quote(working_display_name.encode("utf8"))
)
if identifier:
args += "&urn=%s" % urllib.quote(identifier.urn)
url = self.base_url + self.CANONICALIZE_ENDPOINT + "?" + args
logging.info("GET %s", url)
return self._get(url)
class MockSimplifiedOPDSLookup(SimplifiedOPDSLookup):
def __init__(self, *args, **kwargs):
self.requests = []
self.responses = []
super(MockSimplifiedOPDSLookup, self).__init__(*args, **kwargs)
def queue_response(self, status_code, headers={}, content=None):
from testing import MockRequestsResponse
self.responses.insert(
0, MockRequestsResponse(status_code, headers, content)
)
def _get(self, url, *args, **kwargs):
self.requests.append((url, args, kwargs))
response = self.responses.pop()
return HTTP._process_response(
url, response, kwargs.get('allowed_response_codes'),
kwargs.get('disallowed_response_codes')
)
class MockMetadataWranglerOPDSLookup(MockSimplifiedOPDSLookup, MetadataWranglerOPDSLookup):
def _post(self, url, *args, **kwargs):
self.requests.append((url, args, kwargs))
response = self.responses.pop()
return HTTP._process_response(
url, response, kwargs.get('allowed_response_codes'),
kwargs.get('disallowed_response_codes')
)
class OPDSXMLParser(XMLParser):
NAMESPACES = { "simplified": "http://librarysimplified.org/terms/",
"app" : "http://www.w3.org/2007/app",
"dcterms" : "http://purl.org/dc/terms/",
"dc" : "http://purl.org/dc/elements/1.1/",
"opds": "http://opds-spec.org/2010/catalog",
"schema" : "http://schema.org/",
"atom" : "http://www.w3.org/2005/Atom",
"drm": "http://librarysimplified.org/terms/drm",
}
class OPDSImporter(object):
""" Imports editions and license pools from an OPDS feed.
Creates Edition, LicensePool and Work rows in the database, if those
don't already exist.
Should be used when a circulation server asks for data from
our internal content server, and also when our content server asks for data
from external content servers.
"""
COULD_NOT_CREATE_LICENSE_POOL = (
"No existing license pool for this identifier and no way of creating one.")
NAME = ExternalIntegration.OPDS_IMPORT
DESCRIPTION = _("Import books from a publicly-accessible OPDS feed.")
# These settings are used by all OPDS-derived import methods.
BASE_SETTINGS = [
{
"key": Collection.EXTERNAL_ACCOUNT_ID_KEY,
"label": _("URL"),
"required": True,
"format": "url"
},
{
"key": Collection.DATA_SOURCE_NAME_SETTING,
"label": _("Data source name"),
"required": True,
},
]
# These settings are used by 'regular' OPDS but not by OPDS For
# Distributors, which has its own way of doing authentication.
SETTINGS = BASE_SETTINGS + [
{
"key": ExternalIntegration.USERNAME,
"label": _("Username"),
"description": _("If HTTP Basic authentication is required to access the OPDS feed (it usually isn't), enter the username here."),
},
{
"key": ExternalIntegration.PASSWORD,
"label": _("Password"),
"description": _("If HTTP Basic authentication is required to access the OPDS feed (it usually isn't), enter the password here."),
},
]
# Subclasses of OPDSImporter may define a different parser class that's
# a subclass of OPDSXMLParser. For example, a subclass may want to use
# tags from an additional namespace.
PARSER_CLASS = OPDSXMLParser
# Subclasses of OPDSImporter may define a list of status codes
# that should be treated as indicating success, rather than failure,
# when they show up in <simplified:message> tags.
SUCCESS_STATUS_CODES = None
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
):
""":param collection: LicensePools created by this OPDS import
will be associated with the given Collection. If this is None,
no LicensePools will be created -- only Editions.
: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.
:param mirrors: A dictionary of different MirrorUploader objects for
different purposes.
:param http_get: Use this method to make an HTTP GET request. This
can be replaced with a stub method for testing purposes.
:param metadata_client: A SimplifiedOPDSLookup object that is used
to fill in missing metadata.
:param content_modifier: A function that may modify-in-place
representations (such as images and EPUB documents) as they
come in from the network.
"""
self._db = _db
self.log = logging.getLogger("OPDS Importer")
self.collection = collection
if self.collection and not data_source_name:
# Use the Collection data_source for OPDS import.
data_source = self.collection.data_source
if data_source:
data_source_name = data_source.name
else:
raise ValueError(
"Cannot perform an OPDS import on a Collection that has no associated DataSource!"
)
else:
# Use the given data_source or default to the Metadata
# Wrangler.
data_source_name = data_source_name or DataSource.METADATA_WRANGLER
self.data_source_name = data_source_name
self.identifier_mapping = identifier_mapping
try:
self.metadata_client = metadata_client or MetadataWranglerOPDSLookup.from_config(_db, collection=collection)
except CannotLoadConfiguration, e:
# The Metadata Wrangler isn't configured, but we can import without it.
self.log.warn("Metadata Wrangler integration couldn't be loaded, importing without it.")
self.metadata_client = None
# Check to see if a mirror for each purpose was passed in.
# If not, then attempt to create one.
covers_mirror = mirrors.get(ExternalIntegrationLink.COVERS, None) if mirrors else None
books_mirror = mirrors.get(ExternalIntegrationLink.OPEN_ACCESS_BOOKS, None) if mirrors else None
if collection:
if not covers_mirror:
# If this Collection is configured to mirror the assets it
# discovers, this will create a MirrorUploader for that
# Collection for its purpose. Otherwise, this will return None.
covers_mirror = MirrorUploader.for_collection(
collection, ExternalIntegrationLink.COVERS
)
if not books_mirror:
books_mirror = MirrorUploader.for_collection(
collection, ExternalIntegrationLink.OPEN_ACCESS_BOOKS
)
self.mirrors = dict(covers_mirror=covers_mirror, books_mirror=books_mirror)
self.content_modifier = content_modifier
# In general, we are cautious when mirroring resources so that
# we don't, e.g. accidentally get our IP banned from
# gutenberg.org.
self.http_get = http_get or Representation.cautious_http_get
self.map_from_collection = map_from_collection
@property
def data_source(self):
"""Look up or create a DataSource object representing the
source of this OPDS feed.
"""
offers_licenses = (self.collection is not None)
return DataSource.lookup(
self._db, self.data_source_name, autocreate=True,
offers_licenses = offers_licenses
)
def assert_importable_content(self, feed, feed_url, max_get_attempts=5):
"""Raise an exception if the given feed contains nothing that can,
even theoretically, be turned into a LicensePool.
By default, this means the feed must link to open-access content
that can actually be retrieved.
"""
metadata, failures = self.extract_feed_data(feed, feed_url)
get_attempts = 0
# Find an open-access link, and try to GET it just to make
# sure OPDS feed isn't hiding non-open-access stuff behind an
# open-access link.
#
# To avoid taking forever or antagonizing API providers, we'll
# give up after `max_get_attempts` failures.
for link in self._open_access_links(metadata.values()):
url = link.href
success = self._is_open_access_link(url, link.media_type)
if success:
return success
get_attempts += 1
if get_attempts >= max_get_attempts:
error = "Was unable to GET supposedly open-access content such as %s (tried %s times)" % (
url, get_attempts
)
explanation = "This might be an OPDS For Distributors feed, or it might require different authentication credentials."
raise IntegrationException(error, explanation)
raise IntegrationException(
"No open-access links were found in the OPDS feed.",
"This might be an OPDS for Distributors feed."
)
@classmethod
def _open_access_links(cls, metadatas):
"""Find all open-access links in a list of Metadata objects.
:param metadatas: A list of Metadata objects.
:yield: A sequence of `LinkData` objects.
"""
for item in metadatas:
if not item.circulation:
continue
for link in item.circulation.links:
if link.rel == Hyperlink.OPEN_ACCESS_DOWNLOAD:
yield link
def _is_open_access_link(self, url, type):
"""Is `url` really an open-access link?
That is, can we make a normal GET request and get something
that looks like a book?
"""
headers = {}
if type:
headers["Accept"] = type
status, headers, body = self.http_get(url, headers=headers)
if status == 200 and len(body) > 1024 * 10:
# We could also check the media types, but this is good
# enough for now.
return "Found a book-like thing at %s" % url
self.log.error(
"Supposedly open-access link %s didn't give us a book. Status=%s, body length=%s",
url, status, len(body)
)
return False
def import_from_feed(self, feed, feed_url=None):
# Keep track of editions that were imported. Pools and works
# for those editions may be looked up or created.
imported_editions = {}
pools = {}
works = {}
# CoverageFailures that note business logic errors and non-success download statuses
failures = {}
# If parsing the overall feed throws an exception, we should address that before
# moving on. Let the exception propagate.
metadata_objs, failures = self.extract_feed_data(feed, feed_url)
# make editions. if have problem, make sure associated pool and work aren't created.
for key, metadata in metadata_objs.iteritems():
# key is identifier.urn here
# If there's a status message about this item, don't try to import it.
if key in failures.keys():
continue
try:
# Create an edition. This will also create a pool if there's circulation data.
edition = self.import_edition_from_metadata(metadata)
if edition:
imported_editions[key] = edition
except Exception, e:
# Rather than scratch the whole import, treat this as a failure that only applies
# to this item.
self.log.error("Error importing an OPDS item", exc_info=e)
identifier, ignore = Identifier.parse_urn(self._db, key)
data_source = self.data_source
failure = CoverageFailure(identifier, traceback.format_exc(), data_source=data_source, transient=False)
failures[key] = failure
# clean up any edition might have created
if key in imported_editions:
del imported_editions[key]
# Move on to the next item, don't create a work.
continue
try:
pool, work = self.update_work_for_edition(edition)
if pool:
pools[key] = pool
if work:
works[key] = work
except Exception, e:
identifier, ignore = Identifier.parse_urn(self._db, key)
data_source = self.data_source
failure = CoverageFailure(identifier, traceback.format_exc(), data_source=data_source, transient=False)
failures[key] = failure
return imported_editions.values(), pools.values(), works.values(), failures
def import_edition_from_metadata(
self, metadata
):
""" For the passed-in Metadata object, see if can find or create an Edition
in the database. Also create a LicensePool if the Metadata has
CirculationData in it.
"""
# Locate or create an Edition for this book.
edition, is_new_edition = metadata.edition(self._db)
policy = ReplacementPolicy(
subjects=True,
links=True,
contributions=True,
rights=True,
link_content=True,
even_if_not_apparently_updated=True,
mirrors=self.mirrors,
content_modifier=self.content_modifier,
http_get=self.http_get,
)
metadata.apply(
edition=edition, collection=self.collection,
metadata_client=self.metadata_client, replace=policy
)
return edition
def update_work_for_edition(self, edition):
"""If possible, ensure that there is a presentation-ready Work for the
given edition's primary identifier.
"""
work = None
# Find a LicensePool for the primary identifier. Any LicensePool will
# do--the collection doesn't have to match, since all
# LicensePools for a given identifier have the same Work.
#
# If we have CirculationData, a pool was created when we
# imported the edition. If there was already a pool from a
# different data source or a different collection, that's fine
# too.
pool = get_one(
self._db, LicensePool, identifier=edition.primary_identifier,
on_multiple='interchangeable'
)
if pool:
if not pool.work or not pool.work.presentation_ready:
# There is no presentation-ready Work for this
# LicensePool. Try to create one.
work, ignore = pool.calculate_work()
else:
# There is a presentation-ready Work for this LicensePool.
# Use it.
work = pool.work
# If a presentation-ready Work already exists, there's no
# rush. We might have new metadata that will change the Work's
# presentation, but when we called Metadata.apply() the work
# was set up to have its presentation recalculated in the
# background, and that's good enough.
return pool, work
@classmethod
def extract_next_links(self, feed):
if isinstance(feed, basestring):
parsed = feedparser.parse(feed)
else:
parsed = feed
feed = parsed['feed']
next_links = []
if feed and 'links' in feed:
next_links = [
link['href'] for link in feed['links']
if link['rel'] == 'next'
]
return next_links
@classmethod
def extract_last_update_dates(cls, feed):
if isinstance(feed, basestring):
parsed_feed = feedparser.parse(feed)
else:
parsed_feed = feed
dates = [
cls.last_update_date_for_feedparser_entry(entry)
for entry in parsed_feed['entries']
]
return [x for x in dates if x and x[1]]
def build_identifier_mapping(self, external_urns):
"""Uses the given Collection and a list of URNs to reverse
engineer an identifier mapping.
NOTE: It would be better if .identifier_mapping weren't
instance data, since a single OPDSImporter might import
multiple pages of a feed. However, the code as written should
work.
"""
if not self.collection:
return
mapping = dict()
identifiers_by_urn, failures = Identifier.parse_urns(
self._db, external_urns, autocreate=False
)
external_identifiers = identifiers_by_urn.values()
internal_identifier = aliased(Identifier)
qu = self._db.query(Identifier, internal_identifier)\
.join(Identifier.inbound_equivalencies)\
.join(internal_identifier, Equivalency.input)\
.join(internal_identifier.licensed_through)\
.filter(
Identifier.id.in_([x.id for x in external_identifiers]),
LicensePool.collection==self.collection
)
for external_identifier, internal_identifier in qu:
mapping[external_identifier] = internal_identifier
self.identifier_mapping = mapping
def extract_feed_data(self, feed, feed_url=None):
"""Turn an OPDS feed into lists of Metadata and CirculationData objects,
with associated messages and next_links.
"""
data_source = self.data_source
fp_metadata, fp_failures = self.extract_data_from_feedparser(feed=feed, data_source=data_source)
# gets: medium, measurements, links, contributors, etc.
xml_data_meta, xml_failures = self.extract_metadata_from_elementtree(
feed, data_source=data_source, feed_url=feed_url, do_get=self.http_get
)
if self.map_from_collection:
# Build the identifier_mapping based on the Collection.
self.build_identifier_mapping(fp_metadata.keys() + fp_failures.keys())
# translate the id in failures to identifier.urn
identified_failures = {}
for urn, failure in fp_failures.items() + xml_failures.items():
identifier, failure = self.handle_failure(urn, failure)
identified_failures[identifier.urn] = failure
# Use one loop for both, since the id will be the same for both dictionaries.
metadata = {}
circulationdata = {}
for id, m_data_dict in fp_metadata.items():
external_identifier, ignore = Identifier.parse_urn(self._db, id)
if self.identifier_mapping:
internal_identifier = self.identifier_mapping.get(
external_identifier, external_identifier)
else:
internal_identifier = external_identifier
# Don't process this item if there was already an error
if internal_identifier.urn in identified_failures.keys():
continue
identifier_obj = IdentifierData(
type=internal_identifier.type,
identifier=internal_identifier.identifier
)
# form the Metadata object
xml_data_dict = xml_data_meta.get(id, {})
combined_meta = self.combine(m_data_dict, xml_data_dict)
if combined_meta.get('data_source') is None:
combined_meta['data_source'] = self.data_source_name
combined_meta['primary_identifier'] = identifier_obj
metadata[internal_identifier.urn] = Metadata(**combined_meta)
# Form the CirculationData that would correspond to this Metadata,
# assuming there is a Collection to hold the LicensePool that
# would result.
c_data_dict = None
if self.collection:
c_circulation_dict = m_data_dict.get('circulation')
xml_circulation_dict = xml_data_dict.get('circulation', {})
c_data_dict = self.combine(c_circulation_dict, xml_circulation_dict)
# Unless there's something useful in c_data_dict, we're
# not going to put anything under metadata.circulation,
# and any partial data that got added to
# metadata.circulation is going to be removed.
metadata[internal_identifier.urn].circulation = None
if c_data_dict:
circ_links_dict = {}
# extract just the links to pass to CirculationData constructor
if 'links' in xml_data_dict:
circ_links_dict['links'] = xml_data_dict['links']
combined_circ = self.combine(c_data_dict, circ_links_dict)
if combined_circ.get('data_source') is None:
combined_circ['data_source'] = self.data_source_name
combined_circ['primary_identifier'] = identifier_obj
circulation = CirculationData(**combined_circ)
self._add_format_data(circulation)
if circulation.formats:
metadata[internal_identifier.urn].circulation = circulation
else:
# If the CirculationData has no formats, it
# doesn't really offer any way to actually get the
# book, and we don't want to create a
# LicensePool. All the circulation data is
# useless.
#
# TODO: This will need to be revisited when we add
# ODL support.
pass
return metadata, identified_failures
def handle_failure(self, urn, failure):
"""Convert a URN and a failure message that came in through
an OPDS feed into an Identifier and a CoverageFailure object.
The Identifier may not be the one designated by `urn` (if it's
found in self.identifier_mapping) and the 'failure' may turn out not
to be a CoverageFailure at all -- if it's an Identifier, that means
that what a normal OPDSImporter would consider 'failure' is
considered success.
"""
external_identifier, ignore = Identifier.parse_urn(self._db, urn)
if self.identifier_mapping:
# The identifier found in the OPDS feed is different from
# the identifier we want to export.
internal_identifier = self.identifier_mapping.get(
external_identifier, external_identifier)
else:
internal_identifier = external_identifier
if isinstance(failure, Identifier):
# The OPDSImporter does not actually consider this a
# failure. Signal success by returning the internal
# identifier as the 'failure' object.
failure = internal_identifier
else:
# This really is a failure. Associate the internal
# identifier with the CoverageFailure object.
failure.obj = internal_identifier
return internal_identifier, failure
@classmethod
def _add_format_data(cls, circulation):
"""Subclasses that specialize OPDS Import can implement this
method to add formats to a CirculationData object with
information that allows a patron to actually get a book
that's not open access.
"""
pass
@classmethod
def combine(self, d1, d2):
"""Combine two dictionaries that can be used as keyword arguments to
the Metadata constructor.
"""
if not d1 and not d2: