forked from datalogics/server_core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
7976 lines (6763 loc) · 296 KB
/
model.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
# encoding: utf-8
from cStringIO import StringIO
from collections import (
Counter,
defaultdict,
)
from lxml import etree
from nose.tools import set_trace
import cairosvg
import bisect
import datetime
import isbnlib
import json
import logging
import md5
import operator
import os
import random
import re
import requests
import time
import traceback
import urllib
import urlparse
import uuid
import warnings
import bcrypt
from PIL import (
Image,
)
from psycopg2.extras import NumericRange
from sqlalchemy.engine.url import URL
from sqlalchemy import exc as sa_exc
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
backref,
defer,
relationship,
sessionmaker,
)
from sqlalchemy import (
func,
or_,
MetaData,
Table,
)
from sqlalchemy.sql import select
from sqlalchemy.orm import (
aliased,
backref,
defer,
contains_eager,
joinedload,
lazyload,
)
from sqlalchemy.orm.exc import (
NoResultFound,
MultipleResultsFound,
)
from sqlalchemy.ext.mutable import (
MutableDict,
)
from sqlalchemy.ext.associationproxy import (
association_proxy,
)
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.sql.functions import func
from sqlalchemy.sql.expression import (
cast,
and_,
or_,
select,
join,
literal_column,
case,
table,
)
from sqlalchemy.exc import (
IntegrityError
)
from sqlalchemy import (
create_engine,
Binary,
Boolean,
Column,
Date,
DateTime,
Enum,
Float,
ForeignKey,
Integer,
Index,
Numeric,
String,
Table,
Unicode,
UniqueConstraint,
)
import log # Make sure logging is set up properly.
from config import Configuration
from external_search import ExternalSearchIndex
import classifier
from classifier import (
Classifier,
Erotica,
COMICS_AND_GRAPHIC_NOVELS,
GenreData,
WorkClassifier,
)
from util import (
LanguageCodes,
MetadataSimilarity,
TitleProcessor,
)
from util.http import (
HTTP,
RemoteIntegrationException,
)
from util.permanent_work_id import WorkIDCalculator
from util.summary import SummaryEvaluator
from sqlalchemy.orm.session import Session
from sqlalchemy.dialects.postgresql import (
ARRAY,
HSTORE,
JSON,
INT4RANGE,
)
from sqlalchemy.orm import sessionmaker
from s3 import S3Uploader
from analytics import Analytics
DEBUG = False
def production_session():
url = Configuration.database_url()
if url.startswith('"'):
url = url[1:]
logging.debug("Database url: %s", url)
return SessionManager.session(url)
class PolicyException(Exception):
pass
class BaseMaterializedWork(object):
"""A mixin class for materialized views that incorporate Work and Edition."""
pass
class SessionManager(object):
# Materialized views need to be created and indexed from SQL
# commands kept in files. This dictionary maps the views to the
# SQL files.
MATERIALIZED_VIEW_WORKS = 'mv_works_editions_datasources_identifiers'
MATERIALIZED_VIEW_WORKS_WORKGENRES = 'mv_works_editions_workgenres_datasources_identifiers'
MATERIALIZED_VIEWS = {
MATERIALIZED_VIEW_WORKS : 'materialized_view_works.sql',
MATERIALIZED_VIEW_WORKS_WORKGENRES : 'materialized_view_works_workgenres.sql',
}
# A function that calculates recursively equivalent identifiers
# is also defined in SQL.
RECURSIVE_EQUIVALENTS_FUNCTION = 'recursive_equivalents.sql'
engine_for_url = {}
@classmethod
def engine(cls, url=None):
url = url or Configuration.database_url()
return create_engine(url, echo=DEBUG)
@classmethod
def sessionmaker(cls, url=None):
engine = cls.engine(url)
return sessionmaker(bind=engine)
@classmethod
def initialize(cls, url):
if url in cls.engine_for_url:
engine = cls.engine_for_url[url]
return engine, engine.connect()
engine = cls.engine(url)
Base.metadata.create_all(engine)
base_path = os.path.split(__file__)[0]
resource_path = os.path.join(base_path, "files")
connection = None
for view_name, filename in cls.MATERIALIZED_VIEWS.items():
if engine.has_table(view_name):
continue
if not connection:
connection = engine.connect()
resource_file = os.path.join(resource_path, filename)
if not os.path.exists(resource_file):
raise IOError("Could not load materialized view from %s: file does not exist." % resource_file)
logging.info(
"Loading materialized view %s from %s.",
view_name, resource_file)
sql = open(resource_file).read()
connection.execute(sql)
if not connection:
connection = engine.connect()
# Check if the recursive equivalents function exists already.
query = select(
[literal_column('proname')]
).select_from(
table('pg_proc')
).where(
literal_column('proname')=='fn_recursive_equivalents'
)
result = connection.execute(query)
result = list(result)
# If it doesn't, create it.
if not result:
resource_file = os.path.join(resource_path, cls.RECURSIVE_EQUIVALENTS_FUNCTION)
if not os.path.exists(resource_file):
raise IOError("Could not load recursive equivalents function from %s: file does not exist." % resource_file)
sql = open(resource_file).read()
connection.execute(sql)
if connection:
connection.close()
class MaterializedWorkWithGenre(Base, BaseMaterializedWork):
__table__ = Table(
cls.MATERIALIZED_VIEW_WORKS_WORKGENRES,
Base.metadata,
Column('works_id', Integer, primary_key=True),
Column('workgenres_id', Integer, primary_key=True),
Column('license_pool_id', Integer, ForeignKey('licensepools.id')),
autoload=True,
autoload_with=engine
)
license_pool = relationship(
LicensePool,
primaryjoin="LicensePool.id==MaterializedWorkWithGenre.license_pool_id",
foreign_keys=LicensePool.id, lazy='joined', uselist=False)
class MaterializedWork(Base, BaseMaterializedWork):
__table__ = Table(
cls.MATERIALIZED_VIEW_WORKS,
Base.metadata,
Column('works_id', Integer, primary_key=True),
Column('license_pool_id', Integer, ForeignKey('licensepools.id')),
autoload=True,
autoload_with=engine
)
license_pool = relationship(
LicensePool,
primaryjoin="LicensePool.id==MaterializedWork.license_pool_id",
foreign_keys=LicensePool.id, lazy='joined', uselist=False)
def __repr__(self):
return (u'%s "%s" (%s) %s' % (
self.works_id, self.sort_title, self.sort_author, self.language,
)).encode("utf8")
globals()['MaterializedWork'] = MaterializedWork
globals()['MaterializedWorkWithGenre'] = MaterializedWorkWithGenre
cls.engine_for_url[url] = engine
return engine, engine.connect()
@classmethod
def refresh_materialized_views(self, _db):
for view_name in self.MATERIALIZED_VIEWS.keys():
_db.execute("refresh materialized view %s;" % view_name)
_db.commit()
@classmethod
def session(cls, url):
engine = connection = 0
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=sa_exc.SAWarning)
engine, connection = cls.initialize(url)
session = Session(connection)
cls.initialize_data(session)
session.commit()
return session
@classmethod
def initialize_data(cls, session):
# Create initial data sources.
list(DataSource.well_known_sources(session))
# Create all genres.
for g in classifier.genres.values():
Genre.lookup(session, g, autocreate=True)
# Make sure that the mechanisms fulfillable by the default
# client are marked as such.
for content_type, drm_scheme in DeliveryMechanism.default_client_can_fulfill_lookup:
mechanism, is_new = DeliveryMechanism.lookup(
session, content_type, drm_scheme
)
mechanism.default_client_can_fulfill = True
session.commit()
def get_one(db, model, on_multiple='error', **kwargs):
q = db.query(model).filter_by(**kwargs)
try:
return q.one()
except MultipleResultsFound, e:
if on_multiple == 'error':
raise e
elif on_multiple == 'interchangeable':
# These records are interchangeable so we can use
# whichever one we want.
#
# This may be a sign of a problem somewhere else. A
# database-level constraint might be useful.
q = q.limit(1)
return q.one()
except NoResultFound:
return None
def get_one_or_create(db, model, create_method='',
create_method_kwargs=None,
**kwargs):
one = get_one(db, model, **kwargs)
if one:
return one, False
else:
__transaction = db.begin_nested()
try:
if 'on_multiple' in kwargs:
# This kwarg is supported by get_one() but not by create().
del kwargs['on_multiple']
obj = create(db, model, create_method, create_method_kwargs, **kwargs)
__transaction.commit()
return obj
except IntegrityError, e:
logging.info(
"INTEGRITY ERROR on %r %r, %r: %r", model, create_method_kwargs,
kwargs, e)
__transaction.rollback()
return db.query(model).filter_by(**kwargs).one(), False
def create(db, model, create_method='',
create_method_kwargs=None,
**kwargs):
kwargs.update(create_method_kwargs or {})
created = getattr(model, create_method, model)(**kwargs)
db.add(created)
db.flush()
return created, True
Base = declarative_base()
class Patron(Base):
__tablename__ = 'patrons'
id = Column(Integer, primary_key=True)
# The patron's permanent unique identifier in an external library
# system, probably never seen by the patron.
#
# This is not stored as a ForeignIdentifier because it corresponds
# to the patron's identifier in the library responsible for the
# Simplified instance, not a third party.
external_identifier = Column(Unicode, unique=True, index=True)
# The patron's account type, as reckoned by an external library
# system. Different account types may be subject to different
# library policies.
#
# Depending on library policy it may be possible to automatically
# derive the patron's account type from their authorization
# identifier.
_external_type = Column(Unicode, index=True, name="external_type")
# An identifier used by the patron that gives them the authority
# to borrow books. This identifier may change over time.
authorization_identifier = Column(Unicode, unique=True, index=True)
# An identifier used by the patron that authenticates them,
# but does not give them the authority to borrow books. i.e. their
# website username.
username = Column(Unicode, unique=True, index=True)
# The last time this record was synced up with an external library
# system.
last_external_sync = Column(DateTime)
# The time, if any, at which the user's authorization to borrow
# books expires.
authorization_expires = Column(Date, index=True)
# Outstanding fines the user has, if any.
fines = Column(Unicode)
loans = relationship('Loan', backref='patron')
holds = relationship('Hold', backref='patron')
annotations = relationship('Annotation', backref='patron', order_by="desc(Annotation.timestamp)")
# One Patron can have many associated Credentials.
credentials = relationship("Credential", backref="patron")
AUDIENCE_RESTRICTION_POLICY = 'audiences'
EXTERNAL_TYPE_REGULAR_EXPRESSION = 'external_type_regular_expression'
def works_on_loan(self):
db = Session.object_session(self)
loans = db.query(Loan).filter(Loan.patron==self)
return [loan.work for loan in self.loans if loan.work]
def works_on_loan_or_on_hold(self):
db = Session.object_session(self)
results = set()
holds = [hold.work for hold in self.holds if hold.work]
loans = self.works_on_loan()
return set(holds + loans)
@property
def external_type(self):
if self.authorization_identifier and not self._external_type:
policy = Configuration.policy(
self.EXTERNAL_TYPE_REGULAR_EXPRESSION)
if policy:
match = re.compile(policy).search(
self.authorization_identifier)
if match:
groups = match.groups()
if groups:
self._external_type = groups[0]
return self._external_type
def can_borrow(self, work, policy):
"""Return true if the given policy allows this patron to borrow the
given work.
This will return False when the policy for this patron's
.external_type prevents access to this book's audience.
"""
if not self.external_type in policy:
return True
if not work:
# Shouldn't happen, but not this method's problem.
return True
p = policy[self.external_type]
if not self.AUDIENCE_RESTRICTION_POLICY in p:
return True
allowed = p[self.AUDIENCE_RESTRICTION_POLICY]
if work.audience in allowed:
return True
return False
@property
def authorization_is_active(self):
# Unlike pretty much every other place in this app, I use
# (server) local time here instead of UTC. This is to make it
# less likely that a patron's authorization will expire before
# they think it should.
if (self.authorization_expires
and self.authorization_expires
< datetime.datetime.now().date()):
return False
return True
class LoanAndHoldMixin(object):
@property
def work(self):
"""Try to find the corresponding work for this Loan/Hold."""
license_pool = self.license_pool
if not license_pool:
return None
if license_pool.work:
return license_pool.work
if license_pool.presentation_edition and license_pool.presentation_edition.work:
return license_pool.presentation_edition.work
return None
class Loan(Base, LoanAndHoldMixin):
__tablename__ = 'loans'
id = Column(Integer, primary_key=True)
patron_id = Column(Integer, ForeignKey('patrons.id'), index=True)
license_pool_id = Column(Integer, ForeignKey('licensepools.id'), index=True)
fulfillment_id = Column(Integer, ForeignKey('licensepooldeliveries.id'))
start = Column(DateTime)
end = Column(DateTime)
__table_args__ = (
UniqueConstraint('patron_id', 'license_pool_id'),
)
def until(self, default_loan_period):
"""Give or estimate the time at which the loan will end."""
if self.end:
return self.end
if default_loan_period is None:
# This loan will last forever.
return None
start = self.start or datetime.datetime.utcnow()
return start + default_loan_period
class Hold(Base, LoanAndHoldMixin):
"""A patron is in line to check out a book.
"""
__tablename__ = 'holds'
id = Column(Integer, primary_key=True)
patron_id = Column(Integer, ForeignKey('patrons.id'), index=True)
license_pool_id = Column(Integer, ForeignKey('licensepools.id'), index=True)
start = Column(DateTime, index=True)
end = Column(DateTime, index=True)
position = Column(Integer, index=True)
@classmethod
def _calculate_until(
self, start, queue_position, total_licenses, default_loan_period,
default_reservation_period):
"""Helper method for `Hold.until` that can be tested independently.
We have to wait for the available licenses to cycle a
certain number of times before we get a turn.
Example: 4 licenses, queue position 21
After 1 cycle: queue position 17
2 : queue position 13
3 : queue position 9
4 : queue position 5
5 : queue position 1
6 : available
The worst-case cycle time is the loan period plus the reservation
period.
"""
if queue_position == 0:
# The book is currently reserved to this patron--they need
# to hurry up and check it out.
return start + default_reservation_period
if total_licenses == 0:
# The book will never be available
return None
# Start with the default loan period to clear out everyone who
# currently has the book checked out.
duration = default_loan_period
if queue_position < total_licenses:
# After that period, the book will be available to this patron.
# Do nothing.
pass
else:
# Otherwise, add a number of cycles in which other people are
# notified that it's their turn.
cycle_period = (default_loan_period + default_reservation_period)
cycles = queue_position / total_licenses
if (total_licenses > 1 and queue_position % total_licenses == 0):
cycles -= 1
duration += (cycle_period * cycles)
return start + duration
def until(self, default_loan_period, default_reservation_period):
"""Give or estimate the time at which the book will be available
to this patron.
This is a *very* rough estimate that should be treated more or
less as a worst case. (Though it could be even worse than
this--the library's license might expire and then you'll
_never_ get the book.)
"""
if self.end:
# Whew, the server provided its own estimate.
return self.end
if default_reservation_period is None:
# This hold has no definite end date.
return None
start = datetime.datetime.utcnow()
licenses_available = self.license_pool.licenses_owned
position = self.position
if not position:
# We don't know where in line we are. Assume we're at the
# end.
position = self.license_pool.patrons_in_hold_queue
return self._calculate_until(
start, position, licenses_available,
default_loan_period, default_reservation_period)
def update(self, start, end, position):
"""When the book becomes available, position will be 0 and end will be
set to the time at which point the patron will lose their place in
line.
Otherwise, end is irrelevant and is set to None.
"""
if start is not None:
self.start = start
if position == 0 and end is not None:
self.end = end
else:
self.end = None
if position is not None:
self.position = position
__table_args__ = (
UniqueConstraint('patron_id', 'license_pool_id'),
)
class Annotation(Base):
LS_NAMESPACE = u"http://librarysimplified.org/terms/annotation/"
IDLING = LS_NAMESPACE + u'idling'
MOTIVATIONS = [
IDLING
]
__tablename__ = 'annotations'
id = Column(Integer, primary_key=True)
patron_id = Column(Integer, ForeignKey('patrons.id'), index=True)
identifier_id = Column(Integer, ForeignKey('identifiers.id'), index=True)
motivation = Column(Unicode, index=True)
timestamp = Column(DateTime, index=True)
active = Column(Boolean, default=True)
content = Column(Unicode)
target = Column(Unicode)
def set_inactive(self):
self.active = False
self.content = None
self.timestamp = datetime.datetime.now()
class DataSource(Base):
"""A source for information about books, and possibly the books themselves."""
GUTENBERG = "Gutenberg"
OVERDRIVE = "Overdrive"
PROJECT_GITENBERG = "Project GITenberg"
STANDARD_EBOOKS = "Standard Ebooks"
UNGLUE_IT = "unglue.it"
BIBLIOTHECA = "Bibliotheca"
OCLC = "OCLC Classify"
OCLC_LINKED_DATA = "OCLC Linked Data"
AMAZON = "Amazon"
XID = "WorldCat xID"
AXIS_360 = "Axis 360"
WEB = "Web"
OPEN_LIBRARY = "Open Library"
CONTENT_CAFE = "Content Cafe"
VIAF = "VIAF"
GUTENBERG_COVER_GENERATOR = "Gutenberg Illustrated"
GUTENBERG_EPUB_GENERATOR = "Project Gutenberg EPUB Generator"
METADATA_WRANGLER = "Library Simplified metadata wrangler"
MANUAL = "Manual intervention"
NOVELIST = "NoveList Select"
NYT = "New York Times"
NYPL_SHADOWCAT = "NYPL Shadowcat"
LIBRARY_STAFF = "Library staff"
ADOBE = "Adobe DRM"
PLYMPTON = "Plympton"
OA_CONTENT_SERVER = "Library Simplified Open Access Content Server"
PRESENTATION_EDITION = "Presentation edition generator"
INTERNAL_PROCESSING = "Library Simplified Internal Process"
THETA = "Theta"
DEPRECATED_NAMES = {
"3M" : BIBLIOTHECA
}
THREEM = BIBLIOTHECA
# Some sources of open-access ebooks are better than others. This
# list shows which sources we prefer, in ascending order of
# priority. unglue.it is lowest priority because it tends to
# aggregate books from other sources. We prefer books from their
# original sources.
OPEN_ACCESS_SOURCE_PRIORITY = [
UNGLUE_IT,
GUTENBERG,
GUTENBERG_EPUB_GENERATOR,
PROJECT_GITENBERG,
PLYMPTON,
STANDARD_EBOOKS,
]
# When we're generating the presentation edition for a
# LicensePool, editions are processed based on their data source,
# in the following order:
#
# [all other sources] < [source of the license pool] < [metadata
# wrangler] < [library staff] < [manual intervention]
#
# This list keeps track of the high-priority portion of that
# ordering.
#
# "LIBRARY_STAFF" comes from the Admin Interface.
# "MANUAL" is not currently used, but will give the option of putting in
# software engineer-created system overrides.
PRESENTATION_EDITION_PRIORITY = [
METADATA_WRANGLER, LIBRARY_STAFF, MANUAL
]
__tablename__ = 'datasources'
id = Column(Integer, primary_key=True)
name = Column(String, unique=True, index=True)
offers_licenses = Column(Boolean, default=False)
primary_identifier_type = Column(String, index=True)
extra = Column(MutableDict.as_mutable(JSON), default={})
# One DataSource can generate many Editions.
editions = relationship("Edition", backref="data_source")
# One DataSource can generate many CoverageRecords.
coverage_records = relationship("CoverageRecord", backref="data_source")
# One DataSource can generate many IDEquivalencies.
id_equivalencies = relationship("Equivalency", backref="data_source")
# One DataSource can grant access to many LicensePools.
license_pools = relationship(
"LicensePool", backref=backref("data_source", lazy='joined'))
# One DataSource can provide many Hyperlinks.
links = relationship("Hyperlink", backref="data_source")
# One DataSource can provide many Resources.
resources = relationship("Resource", backref="data_source")
# One DataSource can generate many Measurements.
measurements = relationship("Measurement", backref="data_source")
# One DataSource can provide many Classifications.
classifications = relationship("Classification", backref="data_source")
# One DataSource can have many associated Credentials.
credentials = relationship("Credential", backref="data_source")
# One DataSource can generate many CustomLists.
custom_lists = relationship("CustomList", backref="data_source")
# One DataSource can have one Collection.
collection = relationship(
"Collection", backref="data_source", uselist=False
)
@classmethod
def lookup(cls, _db, name):
# Turn a deprecated name (e.g. "3M" into the current name
# (e.g. "Bibliotheca").
name = cls.DEPRECATED_NAMES.get(name, name)
return get_one(_db, DataSource, name=name)
URI_PREFIX = "http://librarysimplified.org/terms/sources/"
@classmethod
def name_from_uri(cls, uri):
"""Turn a data source URI into a name suitable for passing
into lookup().
"""
if not uri.startswith(cls.URI_PREFIX):
return None
name = uri[len(cls.URI_PREFIX):]
return urllib.unquote(name)
@classmethod
def from_uri(cls, _db, uri):
return cls.lookup(_db, cls.name_from_uri(uri))
@property
def uri(self):
return self.URI_PREFIX + urllib.quote(self.name)
# These are pretty standard values but each library needs to
# define the policy they've negotiated in their configuration.
default_default_loan_period = datetime.timedelta(days=21)
default_default_reservation_period = datetime.timedelta(days=3)
def _datetime_config_value(self, key, default):
integration = Configuration.integration(self.name)
if not integration:
return default
value = integration.get(key)
if not value:
return default
value = int(value)
return datetime.timedelta(days=value)
@property
def default_loan_period(self):
return self._datetime_config_value(
Configuration.DEFAULT_LOAN_PERIOD,
self.default_default_loan_period
)
@property
def default_reservation_period(self):
return self._datetime_config_value(
Configuration.DEFAULT_RESERVATION_PERIOD,
self.default_default_reservation_period
)
@classmethod
def license_source_for(cls, _db, identifier):
"""Find the one DataSource that provides licenses for books identified
by the given identifier.
If there is no such DataSource, or there is more than one,
raises an exception.
"""
sources = cls.license_sources_for(_db, identifier)
return sources.one()
@classmethod
def license_sources_for(cls, _db, identifier):
"""A query that locates all DataSources that provide licenses for
books identified by the given identifier.
"""
if isinstance(identifier, basestring):
type = identifier
else:
type = identifier.type
q =_db.query(DataSource).filter(DataSource.offers_licenses==True).filter(
DataSource.primary_identifier_type==type)
return q
@classmethod
def metadata_sources_for(cls, _db, identifier):
"""Finds the DataSources that provide metadata for books
identified by the given identifier.
"""
if isinstance(identifier, basestring):
type = identifier
else:
type = identifier.type
if not hasattr(cls, 'metadata_lookups_by_identifier_type'):
# This should only happen during testing.
list(DataSource.well_known_sources(_db))
names = cls.metadata_lookups_by_identifier_type[type]
return _db.query(DataSource).filter(DataSource.name.in_(names)).all()
@classmethod
def well_known_sources(cls, _db):
"""Make sure all the well-known sources exist in the database.
"""
cls.metadata_lookups_by_identifier_type = defaultdict(list)
for (name, offers_licenses, offers_metadata_lookup, primary_identifier_type, refresh_rate) in (
(cls.GUTENBERG, True, False, Identifier.GUTENBERG_ID, None),
(cls.OVERDRIVE, True, False, Identifier.OVERDRIVE_ID, 0),
(cls.THREEM, True, False, Identifier.THREEM_ID, 60*60*6),
(cls.AXIS_360, True, False, Identifier.AXIS_360_ID, 0),
(cls.OCLC, False, False, None, None),
(cls.OCLC_LINKED_DATA, False, False, None, None),
(cls.AMAZON, False, False, None, None),
(cls.OPEN_LIBRARY, False, False, Identifier.OPEN_LIBRARY_ID, None),
(cls.GUTENBERG_COVER_GENERATOR, False, False, Identifier.GUTENBERG_ID, None),
(cls.GUTENBERG_EPUB_GENERATOR, False, False, Identifier.GUTENBERG_ID, None),
(cls.WEB, True, False, Identifier.URI, None),
(cls.VIAF, False, False, None, None),
(cls.CONTENT_CAFE, True, True, Identifier.ISBN, None),
(cls.MANUAL, False, False, None, None),
(cls.NYT, False, False, Identifier.ISBN, None),
(cls.LIBRARY_STAFF, False, False, None, None),
(cls.METADATA_WRANGLER, False, False, None, None),
(cls.PROJECT_GITENBERG, True, False, Identifier.GUTENBERG_ID, None),
(cls.STANDARD_EBOOKS, True, False, Identifier.URI, None),
(cls.UNGLUE_IT, True, False, Identifier.URI, None),
(cls.ADOBE, False, False, None, None),
(cls.PLYMPTON, True, False, Identifier.ISBN, None),
(cls.OA_CONTENT_SERVER, True, False, None, None),
(cls.NOVELIST, False, True, Identifier.NOVELIST_ID, None),
(cls.PRESENTATION_EDITION, False, False, None, None),
(cls.INTERNAL_PROCESSING, True, False, None, None),
(cls.THETA, True, False, Identifier.THETA_ID, 0),
):
extra = dict()
if refresh_rate:
extra['circulation_refresh_rate_seconds'] = refresh_rate
obj, new = get_one_or_create(
_db, DataSource,
name=name,
create_method_kwargs=dict(
offers_licenses=offers_licenses,
primary_identifier_type=primary_identifier_type,
extra=extra,
)
)
if offers_metadata_lookup:
l = cls.metadata_lookups_by_identifier_type[primary_identifier_type]
l.append(obj.name)
yield obj
class BaseCoverageRecord(object):
"""Contains useful constants used by both CoverageRecord and
WorkCoverageRecord.
"""
SUCCESS = 'success'
TRANSIENT_FAILURE = 'transient failure'
PERSISTENT_FAILURE = 'persistent failure'
ALL_STATUSES = [SUCCESS, TRANSIENT_FAILURE, PERSISTENT_FAILURE]
# By default, count coverage as present if it ended in
# success or in persistent failure. Do not count coverage
# as present if it ended in transient failure.
DEFAULT_COUNT_AS_COVERED = [SUCCESS, PERSISTENT_FAILURE]
status_enum = Enum(SUCCESS, TRANSIENT_FAILURE, PERSISTENT_FAILURE,
name='coverage_status')
@classmethod
def not_covered(cls, count_as_covered=None,
count_as_not_covered_if_covered_before=None):
"""Filter a query to find only items without coverage records.
:param count_as_covered: A list of constants that indicate
types of coverage records that should count as 'coverage'
for purposes of this query.
:param count_as_not_covered_if_covered_before: If a coverage record
exists, but is older than the given date, do not count it as
covered.
:return: A clause that can be passed in to Query.filter().
"""
if not count_as_covered:
count_as_covered = cls.DEFAULT_COUNT_AS_COVERED
elif isinstance(count_as_covered, basestring):
count_as_covered = [count_as_covered]
# If there is no coverage record, then of course the item is
# not covered.
missing = cls.id==None
# If we're looking for specific coverage statuses, then a
# record does not count if it has some other status.
missing = or_(
missing, ~cls.status.in_(count_as_covered)
)
# If the record's timestamp is before the cutoff time, we
# don't count it as covered, regardless of which status it
# has.
if count_as_not_covered_if_covered_before:
missing = or_(
missing, cls.timestamp < count_as_not_covered_if_covered_before
)
return missing
class CoverageRecord(Base, BaseCoverageRecord):
"""A record of a Identifier being used as input into some process."""
__tablename__ = 'coveragerecords'
SET_EDITION_METADATA_OPERATION = 'set-edition-metadata'
CHOOSE_COVER_OPERATION = 'choose-cover'
SYNC_OPERATION = 'sync'
REAP_OPERATION = 'reap'
IMPORT_OPERATION = 'import'
RESOLVE_IDENTIFIER_OPERATION = 'resolve-identifier'
id = Column(Integer, primary_key=True)
identifier_id = Column(
Integer, ForeignKey('identifiers.id'), index=True)
# If applicable, this is the ID of the data source that took the
# Identifier as input.
data_source_id = Column(
Integer, ForeignKey('datasources.id')
)
operation = Column(String(255), default=None)
timestamp = Column(DateTime, index=True)
status = Column(BaseCoverageRecord.status_enum, index=True)
exception = Column(Unicode, index=True)
__table_args__ = (
UniqueConstraint('identifier_id', 'data_source_id', 'operation'),
)