-
Notifications
You must be signed in to change notification settings - Fork 19
/
overdrive.py
1484 lines (1287 loc) · 58.1 KB
/
overdrive.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
import datetime
import dateutil
import json
import pytz
import re
import requests
import flask
import urlparse
from flask_babel import lazy_gettext as _
from sqlalchemy.orm import contains_eager
from circulation import (
DeliveryMechanismInfo,
LoanInfo,
HoldInfo,
FulfillmentInfo,
BaseCirculationAPI,
)
from selftest import (
HasSelfTests,
SelfTestResult,
)
from core.overdrive import (
OverdriveAPI as BaseOverdriveAPI,
OverdriveRepresentationExtractor,
OverdriveBibliographicCoverageProvider,
MockOverdriveAPI as BaseMockOverdriveAPI,
)
from core.model import (
CirculationEvent,
Collection,
Credential,
DataSource,
DeliveryMechanism,
Edition,
ExternalIntegration,
Hold,
Identifier,
LicensePool,
Loan,
MediaTypes,
Representation,
Session,
)
from core.monitor import (
CollectionMonitor,
IdentifierSweepMonitor,
TimelineMonitor,
)
from core.util.http import HTTP
from core.metadata_layer import ReplacementPolicy
from core.scripts import Script
from circulation_exceptions import *
from core.analytics import Analytics
class OverdriveAPI(BaseOverdriveAPI, BaseCirculationAPI, HasSelfTests):
NAME = ExternalIntegration.OVERDRIVE
DESCRIPTION = _("Integrate an Overdrive collection. For an Overdrive Advantage collection, select the consortium's Overdrive collection as the parent.")
SETTINGS = [
{ "key": Collection.EXTERNAL_ACCOUNT_ID_KEY, "label": _("Library ID"), "required": True },
{ "key": BaseOverdriveAPI.WEBSITE_ID, "label": _("Website ID"), "required": True },
{ "key": ExternalIntegration.USERNAME, "label": _("Client Key"), "required": True },
{ "key": ExternalIntegration.PASSWORD, "label": _("Client Secret"), "required": True },
{
"key": BaseOverdriveAPI.SERVER_NICKNAME,
"label": _("Server family"),
"description": _("Unless you hear otherwise from Overdrive, your integration should use their production servers."),
"type": "select",
"options": [
dict(
label=_("Production"),
key=BaseOverdriveAPI.PRODUCTION_SERVERS
),
dict(
label=_("Testing"),
key=BaseOverdriveAPI.TESTING_SERVERS,
)
],
"default": BaseOverdriveAPI.PRODUCTION_SERVERS,
},
] + BaseCirculationAPI.SETTINGS
LIBRARY_SETTINGS = BaseCirculationAPI.LIBRARY_SETTINGS + [
{ "key": BaseOverdriveAPI.ILS_NAME_KEY, "label": _("ILS Name"),
"default": BaseOverdriveAPI.ILS_NAME_DEFAULT,
"description": _("When multiple libraries share an Overdrive account, Overdrive uses a setting called 'ILS Name' to determine which ILS to check when validating a given patron."),
},
BaseCirculationAPI.DEFAULT_LOAN_DURATION_SETTING
]
# An Overdrive Advantage collection inherits everything except the library id
# from its parent.
CHILD_SETTINGS = [
{ "key": Collection.EXTERNAL_ACCOUNT_ID_KEY, "label": _("Library ID"), "required": True },
]
SET_DELIVERY_MECHANISM_AT = BaseCirculationAPI.FULFILL_STEP
# Create a lookup table between common DeliveryMechanism identifiers
# and Overdrive format types.
epub = Representation.EPUB_MEDIA_TYPE
pdf = Representation.PDF_MEDIA_TYPE
adobe_drm = DeliveryMechanism.ADOBE_DRM
no_drm = DeliveryMechanism.NO_DRM
streaming_drm = DeliveryMechanism.STREAMING_DRM
streaming_text = DeliveryMechanism.STREAMING_TEXT_CONTENT_TYPE
streaming_audio = DeliveryMechanism.STREAMING_AUDIO_CONTENT_TYPE
overdrive_audiobook_manifest = MediaTypes.OVERDRIVE_AUDIOBOOK_MANIFEST_MEDIA_TYPE
libby_drm = DeliveryMechanism.LIBBY_DRM
# These are not real Overdrive formats; we use them internally so
# we can distinguish between (e.g.) using "audiobook-overdrive"
# to get into Overdrive Read, and using it to get a link to a
# manifest file.
MANIFEST_INTERNAL_FORMATS = set(
['audiobook-overdrive-manifest', 'ebook-overdrive-manifest']
)
# When a request comes in for a given DeliveryMechanism, what
# do we tell Overdrive?
delivery_mechanism_to_internal_format = {
(epub, no_drm): 'ebook-epub-open',
(epub, adobe_drm): 'ebook-epub-adobe',
(pdf, no_drm): 'ebook-pdf-open',
(pdf, adobe_drm): 'ebook-pdf-adobe',
(streaming_text, streaming_drm): 'ebook-overdrive',
(streaming_audio, streaming_drm): 'audiobook-overdrive',
(overdrive_audiobook_manifest, libby_drm): 'audiobook-overdrive-manifest'
}
# These formats can be delivered either as manifest files or as
# links to websites that stream the content.
STREAMING_FORMATS = [
'ebook-overdrive',
'audiobook-overdrive',
]
# Once you choose a non-streaming format you're locked into it and can't
# use other formats.
LOCK_IN_FORMATS = [
x for x in BaseOverdriveAPI.FORMATS
if x not in STREAMING_FORMATS
and x not in MANIFEST_INTERNAL_FORMATS
]
# TODO: This is a terrible choice but this URL should never be
# displayed to a patron, so it doesn't matter much.
DEFAULT_ERROR_URL = "http://librarysimplified.org/"
# Map Overdrive's error messages to standard circulation manager
# exceptions.
ERROR_MESSAGE_TO_EXCEPTION = {
"PatronHasExceededCheckoutLimit": PatronLoanLimitReached,
"PatronHasExceededCheckoutLimit_ForCPC": PatronLoanLimitReached,
}
def __init__(self, _db, collection):
super(OverdriveAPI, self).__init__(_db, collection)
self.overdrive_bibliographic_coverage_provider = (
OverdriveBibliographicCoverageProvider(
collection, api_class=self
)
)
def external_integration(self, _db):
return self.collection.external_integration
def _run_self_tests(self, _db):
result = self.run_test(
"Checking global Client Authentication privileges",
self.check_creds, force_refresh=True
)
yield result
if not result.success:
# There is no point in running the other tests if we
# can't even get a token.
return
def _count_advantage():
"""Count the Overdrive Advantage accounts"""
accounts = list(self.get_advantage_accounts())
return "Found %d Overdrive Advantage account(s)." % len(accounts)
yield self.run_test(
"Looking up Overdrive Advantage accounts",
_count_advantage
)
def _count_books():
"""Count the titles in the collection."""
url = self._all_products_link
status, headers, body = self.get(url, {})
body = json.loads(body)
return "%d item(s) in collection" % body['totalItems']
yield self.run_test(
"Counting size of collection", _count_books
)
default_patrons = []
for result in self.default_patrons(self.collection):
if isinstance(result, SelfTestResult):
yield result
continue
library, patron, pin = result
task = "Checking Patron Authentication privileges, using test patron for library %s" % library.name
yield self.run_test(
task, self.get_patron_credential, patron, pin
)
def patron_request(self, patron, pin, url, extra_headers={}, data=None,
exception_on_401=False, method=None):
"""Make an HTTP request on behalf of a patron.
The results are never cached.
"""
patron_credential = self.get_patron_credential(patron, pin)
headers = dict(Authorization="Bearer %s" % patron_credential.credential)
headers.update(extra_headers)
if method and method.lower() in ('get', 'post', 'put', 'delete'):
method = method.lower()
else:
if data:
method = 'post'
else:
method = 'get'
url = self.endpoint(url)
response = HTTP.request_with_timeout(
method, url, headers=headers, data=data
)
if response.status_code == 401:
if exception_on_401:
# This is our second try. Give up.
raise IntegrationException(
"Something's wrong with the patron OAuth Bearer Token!"
)
else:
# Refresh the token and try again.
self.refresh_patron_access_token(
patron_credential, patron, pin)
return self.patron_request(
patron, pin, url, extra_headers, data, True)
else:
# This is commented out because it may expose patron
# information.
#
# self.log.debug("%s: %s", url, response.status_code)
return response
def get_patron_credential(self, patron, pin):
"""Create an OAuth token for the given patron."""
def refresh(credential):
return self.refresh_patron_access_token(
credential, patron, pin)
return Credential.lookup(
self._db, DataSource.OVERDRIVE, "OAuth Token", patron, refresh,
collection=self.collection
)
def scope_string(self, library):
"""Create the Overdrive scope string for the given library.
This is used when setting up Patron Authentication, and when
generating the X-Overdrive-Scope header used by SimplyE to set up
its own Patron Authentication.
"""
return "websiteid:%s authorizationname:%s" % (
self.website_id, self.ils_name(library)
)
def refresh_patron_access_token(self, credential, patron, pin):
"""Request an OAuth bearer token that allows us to act on
behalf of a specific patron.
Documentation: https://developer.overdrive.com/apis/patron-auth
"""
payload = dict(
grant_type="password",
username=patron.authorization_identifier,
scope=self.scope_string(patron.library)
)
if pin:
# A PIN was provided.
payload['password'] = pin
else:
# No PIN was provided. Depending on the library,
# this might be fine. If it's not fine, Overdrive will
# refuse to issue a token.
payload['password_required'] = 'false'
payload['password'] = '[ignore]'
response = self.token_post(self.PATRON_TOKEN_ENDPOINT, payload)
if response.status_code == 200:
self._update_credential(credential, response.json())
elif response.status_code == 400:
response = response.json()
message = response['error']
error = response.get('error_description')
if error:
message += '/' + error
diagnostic = None
debug = message
if error == 'Requested record not found':
debug = "The patron failed Overdrive's cross-check against the library's ILS."
raise PatronAuthorizationFailedException(message, debug)
return credential
def checkout(self, patron, pin, licensepool, internal_format):
"""Check out a book on behalf of a patron.
:param patron: a Patron object for the patron who wants
to check out the book.
:param pin: The patron's alleged password.
:param licensepool: Identifier of the book to be checked out is
attached to this licensepool.
:param internal_format: Represents the patron's desired book format.
:return: a LoanInfo object.
"""
identifier = licensepool.identifier
overdrive_id=identifier.identifier
headers = {"Content-Type": "application/json"}
payload = dict(fields=[dict(name="reserveId", value=overdrive_id)])
payload = json.dumps(payload)
response = self.patron_request(
patron, pin, self.CHECKOUTS_ENDPOINT, extra_headers=headers,
data=payload
)
data = response.json()
if response.status_code == 400:
return self._process_checkout_error(patron, pin, licensepool, data)
else:
# Try to extract the expiration date from the response.
expires = self.extract_expiration_date(data)
# Create the loan info.
loan = LoanInfo(
licensepool.collection,
licensepool.data_source.name,
licensepool.identifier.type,
licensepool.identifier.identifier,
None,
expires,
None,
)
return loan
def _process_checkout_error(self, patron, pin, licensepool, error):
"""Handle an error received by the API checkout endpoint.
:param patron: The Patron who tried to check out the book.
:param pin: The Patron's PIN; used in case follow-up
API requests are necessary.
:param licensepool: LicensePool for the book that was to be borrowed.
:param error: A dictionary representing the error response, parsed as JSON.
"""
code = "Unknown Error"
identifier = licensepool.identifier
if isinstance(error, dict):
code = error.get('errorCode', code)
if code == 'NoCopiesAvailable':
# Clearly our info is out of date.
self.update_licensepool(identifier.identifier)
raise NoAvailableCopies()
if code == 'TitleAlreadyCheckedOut':
# Client should have used a fulfill link instead, but
# we can handle it.
#
# NOTE: It's very unlikely this will happen, but it could
# happen if the patron borrows a book through Libby and
# then immediately borrows the same book through SimplyE.
loan = self.get_loan(patron, pin, identifier.identifier)
expires = self.extract_expiration_date(loan)
return LoanInfo(
licensepool.collection,
licensepool.data_source.name,
identifier.type,
identifier.identifier,
None,
expires,
None
)
if code in self.ERROR_MESSAGE_TO_EXCEPTION:
exc_class = self.ERROR_MESSAGE_TO_EXCEPTION[code]
raise exc_class()
# All-purpose fallback
raise CannotLoan(code)
def checkin(self, patron, pin, licensepool):
# Get the loan for this patron to see whether or not they
# have a delivery mechanism recorded.
loan = None
loans = [l for l in patron.loans if l.license_pool == licensepool]
if loans:
loan = loans[0]
if (loan and loan.fulfillment
and loan.fulfillment.delivery_mechanism
and loan.fulfillment.delivery_mechanism.drm_scheme
== DeliveryMechanism.NO_DRM):
# This patron fulfilled this loan without DRM. That means we
# should be able to find a loanEarlyReturnURL and hit it.
if self.perform_early_return(patron, pin, loan):
# No need for the fallback strategy.
return
# Our fallback strategy is to DELETE the checkout endpoint.
# We do this if no loan can be found, no delivery mechanism is
# recorded, the delivery mechanism uses DRM, we are unable to
# locate the return URL, or we encounter a problem using the
# return URL.
#
# The only case where this is likely to work is when the
# loan exists but has not been locked to a delivery mechanism.
overdrive_id = licensepool.identifier.identifier
url = self.endpoint(self.CHECKOUT_ENDPOINT, overdrive_id=overdrive_id)
return self.patron_request(patron, pin, url, method='DELETE')
def perform_early_return(self, patron, pin, loan, http_get=None):
"""Ask Overdrive for a loanEarlyReturnURL for the given loan
and try to hit that URL.
:param patron: A Patron
:param pin: Authorization PIN for the patron
:param loan: A Loan object corresponding to the title on loan.
:param http_get: You may pass in a mock of HTTP.get_with_timeout
for use in tests.
"""
mechanism = loan.fulfillment.delivery_mechanism
internal_format = self.delivery_mechanism_to_internal_format.get(
(mechanism.content_type, mechanism.drm_scheme)
)
if not internal_format:
# Something's wrong in general, but in particular we don't know
# which fulfillment link to ask for. Bail out.
return False
# Ask Overdrive for a link that can be used to fulfill the book
# (but which may also contain an early return URL).
url, media_type = self.get_fulfillment_link(
patron, pin, loan.license_pool.identifier.identifier,
internal_format
)
# The URL comes from Overdrive, so it probably doesn't need
# interpolation, but just in case.
url = self.endpoint(url)
# Make a regular, non-authenticated request to the fulfillment link.
http_get = http_get or HTTP.get_with_timeout
response = http_get(url, allow_redirects=False)
location = response.headers.get('location')
# Try to find an early return URL in the Location header
# sent from the fulfillment request.
early_return_url = self._extract_early_return_url(location)
if early_return_url:
response = http_get(early_return_url)
if response.status_code == 200:
return True
return False
@classmethod
def _extract_early_return_url(cls, location):
"""Extract an early return URL from the URL Overdrive sends to
fulfill a non-DRMed book.
:param location: A URL found in a Location header.
"""
if not location:
return None
parsed = urlparse.urlparse(location)
query = urlparse.parse_qs(parsed.query)
urls = query.get('loanEarlyReturnUrl')
if urls:
return urls[0]
def fill_out_form(self, **values):
fields = []
for k, v in values.items():
fields.append(dict(name=k, value=v))
headers = {"Content-Type": "application/json; charset=utf-8"}
return headers, json.dumps(dict(fields=fields))
error_to_exception = {
"TitleNotCheckedOut" : NoActiveLoan,
}
def raise_exception_on_error(self, data, custom_error_to_exception={}):
if not 'errorCode' in data:
return
error = data['errorCode']
message = data.get('message') or ''
for d in custom_error_to_exception, self.error_to_exception:
if error in d:
raise d[error](message)
def get_loan(self, patron, pin, overdrive_id):
url = self.CHECKOUTS_ENDPOINT + "/" + overdrive_id.upper()
data = self.patron_request(patron, pin, url).json()
self.raise_exception_on_error(data)
return data
def get_hold(self, patron, pin, overdrive_id):
url = self.endpoint(
self.HOLD_ENDPOINT, product_id=overdrive_id.upper()
)
data = self.patron_request(patron, pin, url).json()
self.raise_exception_on_error(data)
return data
def get_loans(self, patron, pin):
"""Get a JSON structure describing all of a patron's outstanding
loans."""
data = self.patron_request(patron, pin, self.CHECKOUTS_ENDPOINT).json()
self.raise_exception_on_error(data)
return data
def fulfill(self, patron, pin, licensepool, internal_format, **kwargs):
"""Get the actual resource file to the patron.
:param kwargs: A container for arguments to fulfill()
which are not relevant to this vendor.
:return: a FulfillmentInfo object.
"""
try:
result = self.get_fulfillment_link(
patron, pin, licensepool.identifier.identifier, internal_format
)
if isinstance(result, FulfillmentInfo):
# The fulfillment process was short-circuited, probably
# by the creation of an OverdriveManifestFulfillmentInfo.
return result
url, media_type = result
if internal_format in self.STREAMING_FORMATS:
media_type += DeliveryMechanism.STREAMING_PROFILE
except FormatNotAvailable, e:
# It's possible the available formats for this book have changed and we
# have an inaccurate delivery mechanism. Try to update the formats, but
# reraise the error regardless.
self.log.info("Overdrive id %s was not available as %s, getting updated formats" % (licensepool.identifier.identifier, internal_format))
try:
self.update_formats(licensepool)
except Exception, e2:
self.log.error("Could not update formats for Overdrive ID %s" % licensepool.identifier.identifier)
raise e
return FulfillmentInfo(
licensepool.collection,
licensepool.data_source.name,
licensepool.identifier.type,
licensepool.identifier.identifier,
content_link=url,
content_type=media_type,
content=None,
content_expires=None
)
def get_fulfillment_link(self, patron, pin, overdrive_id, format_type):
"""Get the link to the ACSM or manifest for an existing loan.
"""
loan = self.get_loan(patron, pin, overdrive_id)
if not loan:
raise NoActiveLoan("Could not find active loan for %s" % overdrive_id)
download_link = None
if (not loan.get('isFormatLockedIn')
and format_type in self.LOCK_IN_FORMATS):
# The format is not locked in. Lock it in.
# This will happen the first time someone tries to fulfill
# a loan with a lock-in format (basically Adobe-gated formats)
response = self.lock_in_format(
patron, pin, overdrive_id, format_type)
if response.status_code not in (201, 200):
if response.status_code == 400:
message = response.json().get("message")
if message == "The selected format may not be available for this title.":
raise FormatNotAvailable("This book is not available in the format you requested.")
else:
raise CannotFulfill("Could not lock in format %s" % format_type)
response = response.json()
try:
download_link = self.extract_download_link(
response, self.DEFAULT_ERROR_URL)
except IOError, e:
# Get the loan fresh and see if that solves the problem.
loan = self.get_loan(patron, pin, overdrive_id)
# TODO: Verify that the asked-for format type is the same as the
# one in the loan.
if format_type and not download_link:
download_link = self.get_download_link(
loan, format_type, self.DEFAULT_ERROR_URL
)
if not download_link:
raise CannotFulfill(
"No download link for %s, format %s" % (
overdrive_id, format_type))
if download_link:
if format_type in self.MANIFEST_INTERNAL_FORMATS:
# The client must authenticate using its own
# credentials to fulfill this URL; we can't do it.
scope_string = self.scope_string(patron.library)
return OverdriveManifestFulfillmentInfo(
self.collection, download_link,
overdrive_id, scope_string
)
return self.get_fulfillment_link_from_download_link(
patron, pin, download_link)
raise CannotFulfill("Cannot obtain a download link for patron[%r], overdrive_id[%s], format_type[%s].", patron, overdrive_id, format_type)
def get_fulfillment_link_from_download_link(self, patron, pin, download_link, fulfill_url=None):
# If this for Overdrive's streaming reader, and the link expires,
# the patron can go back to the circulation manager fulfill url
# again to get a new one.
if not fulfill_url and flask.request:
fulfill_url = flask.request.url
else:
fulfill_url=""
download_link = download_link.replace("{odreadauthurl}", fulfill_url)
download_response = self.patron_request(patron, pin, download_link)
return self.extract_content_link(download_response.json())
def extract_content_link(self, content_link_gateway_json):
link = content_link_gateway_json['links']['contentlink']
return link['href'], link['type']
def lock_in_format(self, patron, pin, overdrive_id, format_type):
overdrive_id = overdrive_id.upper()
headers, document = self.fill_out_form(
reserveId=overdrive_id, formatType=format_type)
url = self.endpoint(
self.FORMATS_ENDPOINT, overdrive_id=overdrive_id
)
return self.patron_request(patron, pin, url, headers, document)
@classmethod
def extract_data_from_checkout_response(cls, checkout_response_json,
format_type, error_url):
expires = cls.extract_expiration_date(checkout_response_json)
return expires, cls.get_download_link(
checkout_response_json, format_type, error_url)
@classmethod
def extract_data_from_hold_response(cls, hold_response_json):
position = hold_response_json['holdListPosition']
placed = cls._extract_date(hold_response_json, 'holdPlacedDate')
return position, placed
@classmethod
def extract_expiration_date(cls, data):
return cls._extract_date(data, 'expires')
@classmethod
def _extract_date(cls, data, field_name):
if not isinstance(data, dict):
return None
if not field_name in data:
return None
try:
return datetime.datetime.strptime(
data[field_name], cls.TIME_FORMAT
)
except ValueError, e:
# Wrong format
return None
def get_patron_information(self, patron, pin):
data = self.patron_request(patron, pin, self.ME_ENDPOINT).json()
self.raise_exception_on_error(data)
return data
def get_patron_checkouts(self, patron, pin):
data = self.patron_request(patron, pin, self.CHECKOUTS_ENDPOINT).json()
self.raise_exception_on_error(data)
return data
def get_patron_holds(self, patron, pin):
data = self.patron_request(patron, pin, self.HOLDS_ENDPOINT).json()
self.raise_exception_on_error(data)
return data
@classmethod
def _pd(cls, d):
"""Stupid method to parse a date."""
if not d:
return d
return datetime.datetime.strptime(d, cls.TIME_FORMAT)
def patron_activity(self, patron, pin):
try:
loans = self.get_patron_checkouts(patron, pin)
holds = self.get_patron_holds(patron, pin)
except PatronAuthorizationFailedException, e:
# This frequently happens because Overdrive performs
# checks for blocked or expired accounts upon initial
# authorization, where the circulation manager would let
# the 'authorization' part succeed and block the patron's
# access afterwards.
#
# It's common enough that it's hardly worth mentioning, but it
# could theoretically be the sign of a larger problem.
self.log.info(
"Overdrive authentication failed, assuming no loans.",
exc_info=e
)
loans = {}
holds = {}
for checkout in loans.get('checkouts', []):
loan_info = self.process_checkout_data(checkout, self.collection)
yield loan_info
for hold in holds.get('holds', []):
overdrive_identifier = hold['reserveId'].lower()
start = self._pd(hold.get('holdPlacedDate'))
end = self._pd(hold.get('holdExpires'))
position = hold.get('holdListPosition')
if position is not None:
position = int(position)
if 'checkout' in hold.get('actions', {}):
# This patron needs to decide whether to check the
# book out. By our reckoning, the patron's position is
# 0, not whatever position Overdrive had for them.
position = 0
yield HoldInfo(
self.collection,
DataSource.OVERDRIVE,
Identifier.OVERDRIVE_ID,
overdrive_identifier,
start_date=start,
end_date=end,
hold_position=position
)
@classmethod
def process_checkout_data(cls, checkout, collection):
"""Convert one checkout from Overdrive's list of checkouts
into a LoanInfo object.
:return: A LoanInfo object if the book can be fulfilled
by the default Library Simplified client, and None otherwise.
"""
overdrive_identifier = checkout['reserveId'].lower()
start = cls._pd(checkout.get('checkoutDate'))
end = cls._pd(checkout.get('expires'))
usable_formats = []
# If a format is already locked in, it will be in formats.
for format in checkout.get('formats', []):
format_type = format.get('formatType')
if format_type in cls.FORMATS:
usable_formats.append(format_type)
# If a format hasn't been selected yet, available formats are in actions.
actions = checkout.get('actions', {})
format_action = actions.get('format', {})
format_fields = format_action.get('fields', [])
for field in format_fields:
if field.get('name', "") == "formatType":
format_options = field.get("options", [])
for format_type in format_options:
if format_type in cls.FORMATS:
usable_formats.append(format_type)
if not usable_formats:
# Either this book is not available in any format readable
# by the default client, or the patron previously chose to
# fulfill it in a format not readable by the default
# client. Either way, we cannot fulfill this loan and we
# shouldn't show it in the list.
return None
locked_to = None
if len(usable_formats) == 1:
# Either the book has been locked into a specific format,
# or only one usable format is available. We don't know
# which case we're looking at, but for our purposes the
# book is locked -- unless, of course, what Overdrive
# considers "one format" corresponds to more than one
# format on our side.
[overdrive_format] = usable_formats
internal_formats = list(
OverdriveRepresentationExtractor.internal_formats(
overdrive_format
)
)
if len(internal_formats) == 1:
[(media_type, drm_scheme)] = internal_formats
# Make it clear that Overdrive will only deliver the content
# in one specific media type.
locked_to = DeliveryMechanismInfo(
content_type=media_type,
drm_scheme=drm_scheme
)
return LoanInfo(
collection,
DataSource.OVERDRIVE,
Identifier.OVERDRIVE_ID,
overdrive_identifier,
start_date=start,
end_date=end,
locked_to=locked_to
)
def default_notification_email_address(self, patron, pin):
"""Find the email address this patron wants to use for hold
notifications.
:return: The email address Overdrive has on record for
this patron's hold notifications, or None if there is
no such address.
"""
# We're calling the superclass implementation, but we have no
# intention of actually using the result. This is a
# per-library default that trashes all of its input, and
# Overdrive has a better solution.
trash_everything_address = super(
OverdriveAPI, self
).default_notification_email_address(patron, pin)
# Instead, we will ask _Overdrive_ if this patron has a
# preferred email address for notifications.
address = None
response = self.patron_request(
patron, pin, self.PATRON_INFORMATION_ENDPOINT
)
if response.status_code == 200:
data = response.json()
address = data.get('lastHoldEmail')
# Great! Except, it's possible that this address is the
# 'trash everything' address, because we _used_ to send
# that address to Overdrive. If so, ignore it.
if address == trash_everything_address:
address = None
else:
self.log.error(
"Unable to get patron information for %s: %s",
patron.authorization_identifier,
response.content
)
return address
def place_hold(self, patron, pin, licensepool, notification_email_address):
"""Place a book on hold.
:return: A HoldData object, if a hold was successfully placed,
or the book was already on hold.
:raise: A CirculationException explaining why no hold
could be placed.
"""
if not notification_email_address:
notification_email_address = self.default_notification_email_address(
patron, pin
)
overdrive_id = licensepool.identifier.identifier
form_fields = dict(reserveId=overdrive_id)
if notification_email_address:
form_fields['emailAddress'] = notification_email_address
else:
form_fields['ignoreHoldEmail'] = True
headers, document = self.fill_out_form(**form_fields)
response = self.patron_request(
patron, pin, self.HOLDS_ENDPOINT, headers,
document
)
return self.process_place_hold_response(
response, patron, pin, licensepool
)
def process_place_hold_response(self, response, patron, pin, licensepool):
"""Process the response to a HOLDS_ENDPOINT request.
:return: A HoldData object, if a hold was successfully placed,
or the book was already on hold.
:raise: A CirculationException explaining why no hold
could be placed.
"""
def make_holdinfo(hold_response):
# Create a HoldInfo object by combining data passed into
# the enclosing method with the data from a hold response
# (either creating a new hold or fetching an existing
# one).
position, start_date = self.extract_data_from_hold_response(
hold_response
)
return HoldInfo(
licensepool.collection,
licensepool.data_source.name,
licensepool.identifier.type,
licensepool.identifier.identifier,
start_date=start_date,
end_date=None,
hold_position=position
)
family = response.status_code // 100
if family == 4:
error = response.json()
if not error or not 'errorCode' in error:
raise CannotHold()
code = error['errorCode']
if code == 'AlreadyOnWaitList':
# The book is already on hold, so this isn't an exceptional
# condition. Refresh the queue info and act as though the
# request was successful.
hold = self.get_hold(
patron, pin, licensepool.identifier.identifier
)
return make_holdinfo(hold)
elif code == 'NotWithinRenewalWindow':
# The patron has this book checked out and cannot yet
# renew their loan.
raise CannotRenew()
elif code == 'PatronExceededHoldLimit':
raise PatronHoldLimitReached()
else:
raise CannotHold(code)
elif family == 2:
# The book was successfuly placed on hold. Return an
# appropriate HoldInfo.
data = response.json()
return make_holdinfo(data)
else:
# Some other problem happened -- we don't know what. It's
# not a 5xx error because the HTTP client would have been
# turned that into a RemoteIntegrationException.
raise CannotHold()
def release_hold(self, patron, pin, licensepool):
"""Release a patron's hold on a book.
:raises CannotReleaseHold: If there is an error communicating
with Overdrive, or Overdrive refuses to release the hold for
any reason.
"""
url = self.endpoint(
self.HOLD_ENDPOINT,
product_id=licensepool.identifier.identifier
)
response = self.patron_request(patron, pin, url, method='DELETE')
if response.status_code // 100 == 2 or response.status_code == 404:
return True
if not response.content:
raise CannotReleaseHold()
data = response.json()
if not 'errorCode' in data:
raise CannotReleaseHold()
if data['errorCode'] == 'PatronDoesntHaveTitleOnHold':
# There was never a hold to begin with, so we're fine.
return True
raise CannotReleaseHold(response.content)
def circulation_lookup(self, book):
if isinstance(book, basestring):
book_id = book
circulation_link = self.endpoint(
self.AVAILABILITY_ENDPOINT,
collection_token=self.collection_token,
product_id=book_id
)
book = dict(id=book_id)
else:
book_id = book['id']
circulation_link = book['availability_link']
return book, self.get(circulation_link, {})
def update_formats(self, licensepool):
"""Update the format information for a single book.