forked from NYPL-Simplified/circulation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscripts.py
1882 lines (1608 loc) · 67.3 KB
/
scripts.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
import argparse
import csv
import logging
import os
import sys
import time
from io import StringIO
from datetime import (
datetime,
timedelta,
)
from enum import Enum
from sqlalchemy import (
or_,
)
from api.adobe_vendor_id import (
AuthdataUtility,
)
from api.bibliotheca import (
BibliothecaCirculationSweep
)
from api.config import (
CannotLoadConfiguration,
Configuration,
)
from api.controller import CirculationManager
from api.lanes import create_default_lanes
from api.local_analytics_exporter import LocalAnalyticsExporter
from api.marc import LibraryAnnotator as MARCLibraryAnnotator
from api.novelist import (
NoveListAPI
)
from api.nyt import NYTBestSellerAPI
from api.odl import (
ODLImporter,
ODLImportMonitor,
SharedODLImporter,
SharedODLImportMonitor,
)
from api.onix import ONIXExtractor
from api.opds_for_distributors import (
OPDSForDistributorsImporter,
OPDSForDistributorsImportMonitor,
OPDSForDistributorsReaperMonitor,
)
from api.overdrive import (
OverdriveAPI,
)
from core.entrypoint import EntryPoint
from core.external_list import CustomListFromCSV
from core.external_search import ExternalSearchIndex
from core.lane import Lane
from core.lane import (
Pagination,
Facets,
FeaturedFacets,
)
from core.marc import MARCExporter
from core.metadata_layer import (
CirculationData,
FormatData,
ReplacementPolicy,
LinkData,
)
from core.metadata_layer import MARCExtractor
from core.mirror import MirrorUploader
from core.model import (
CachedMARCFile,
CirculationEvent,
Collection,
ConfigurationSetting,
Contribution,
CustomList,
DataSource,
DeliveryMechanism,
Edition,
ExternalIntegration,
get_one,
Hold,
Hyperlink,
Identifier,
LicensePool,
Loan,
Representation,
RightsStatus,
SessionManager,
Subject,
Timestamp,
Work,
EditionConstants)
from core.model.configuration import ExternalIntegrationLink
from core.opds import (
AcquisitionFeed,
)
from core.opds_import import (
MetadataWranglerOPDSLookup,
OPDSImporter,
)
from core.scripts import OPDSImportScript, CollectionType
from core.scripts import (
Script as CoreScript,
DatabaseMigrationInitializationScript,
IdentifierInputScript,
LaneSweeperScript,
LibraryInputScript,
PatronInputScript,
TimestampScript,
)
from core.util import LanguageCodes
from core.util.opds_writer import (
OPDSFeed,
)
from core.util.datetime_helpers import utc_now
class Script(CoreScript):
def load_config(self):
if not Configuration.instance:
Configuration.load(self._db)
class CreateWorksForIdentifiersScript(Script):
"""Do the bare minimum to associate each Identifier with an Edition
with title and author, so that we can calculate a permanent work
ID.
"""
to_check = [Identifier.OVERDRIVE_ID, Identifier.THREEM_ID,
Identifier.GUTENBERG_ID]
BATCH_SIZE = 100
name = "Create works for identifiers"
def __init__(self, metadata_web_app_url=None):
if metadata_web_app_url:
self.lookup = MetadataWranglerOPDSLookup(metadata_web_app_url)
else:
self.lookup = MetadataWranglerOPDSLookup.from_config(_db)
def run(self):
# We will try to fill in Editions that are missing
# title/author and as such have no permanent work ID.
#
# We will also try to create Editions for Identifiers that
# have no Edition.
either_title_or_author_missing = or_(
Edition.title == None,
Edition.sort_author == None,
)
edition_missing_title_or_author = self._db.query(Identifier).join(
Identifier.primarily_identifies).filter(
either_title_or_author_missing)
no_edition = self._db.query(Identifier).filter(
Identifier.primarily_identifies==None).filter(
Identifier.type.in_(self.to_check))
for q, descr in (
(edition_missing_title_or_author,
"identifiers whose edition is missing title or author"),
(no_edition, "identifiers with no edition")):
batch = []
self.log.debug("Trying to fix %d %s", q.count(), descr)
for i in q:
batch.append(i)
if len(batch) >= self.BATCH_SIZE:
self.process_batch(batch)
batch = []
def process_batch(self, batch):
response = self.lookup.lookup(batch)
if response.status_code != 200:
raise Exception(response.text)
content_type = response.headers['content-type']
if content_type != OPDSFeed.ACQUISITION_FEED_TYPE:
raise Exception("Wrong media type: %s" % content_type)
importer = OPDSImporter(
self._db, response.text,
overwrite_rels=[Hyperlink.DESCRIPTION, Hyperlink.IMAGE])
imported, messages_by_id = importer.import_from_feed()
self.log.info("%d successes, %d failures.",
len(imported), len(messages_by_id))
self._db.commit()
class MetadataCalculationScript(Script):
"""Force calculate_presentation() to be called on some set of Editions.
This assumes that the metadata is in already in the database and
will fall into place if we just call
Edition.calculate_presentation() and Edition.calculate_work() and
Work.calculate_presentation().
Most of these will be data repair scripts that do not need to be run
regularly.
"""
name = "Metadata calculation script"
def q(self):
raise NotImplementedError()
def run(self):
q = self.q()
search_index_client = ExternalSearchIndex(self._db)
self.log.info("Attempting to repair metadata for %d works" % q.count())
success = 0
failure = 0
also_created_work = 0
def checkpoint():
self._db.commit()
self.log.info("%d successes, %d failures, %d new works.",
success, failure, also_created_work)
i = 0
for edition in q:
edition.calculate_presentation()
if edition.sort_author:
success += 1
work, is_new = edition.license_pool.calculate_work(
search_index_client=search_index_client)
if work:
work.calculate_presentation()
if is_new:
also_created_work += 1
else:
failure += 1
i += 1
if not i % 1000:
checkpoint()
checkpoint()
class FillInAuthorScript(MetadataCalculationScript):
"""Fill in Edition.sort_author for Editions that have a list of
Contributors, but no .sort_author.
This is a data repair script that should not need to be run
regularly.
"""
name = "Fill in missing authors"
def q(self):
return self._db.query(Edition).join(
Edition.contributions).join(Contribution.contributor).filter(
Edition.sort_author==None)
class UpdateStaffPicksScript(Script):
DEFAULT_URL_TEMPLATE = "https://docs.google.com/spreadsheets/d/%s/export?format=csv"
def run(self):
inp = self.open()
tag_fields = {
'tags': Subject.NYPL_APPEAL,
}
integ = Configuration.integration(Configuration.STAFF_PICKS_INTEGRATION)
fields = integ.get(Configuration.LIST_FIELDS, {})
importer = CustomListFromCSV(
DataSource.LIBRARY_STAFF, CustomList.STAFF_PICKS_NAME,
**fields
)
reader = csv.DictReader(inp, dialect='excel-tab')
importer.to_customlist(self._db, reader)
self._db.commit()
def open(self):
if len(sys.argv) > 1:
return open(sys.argv[1])
url = Configuration.integration_url(
Configuration.STAFF_PICKS_INTEGRATION, True
)
if not url.startswith('https://') or url.startswith('http://'):
url = self.DEFAULT_URL_TEMPLATE % url
self.log.info("Retrieving %s", url)
representation, cached = Representation.get(
self._db, url, do_get=Representation.browser_http_get,
accept="text/csv", max_age=timedelta(days=1))
if representation.status_code != 200:
raise ValueError("Unexpected status code %s" %
representation.status_code)
if not representation.media_type.startswith("text/csv"):
raise ValueError("Unexpected media type %s" %
representation.media_type)
return StringIO(representation.content)
class CacheRepresentationPerLane(TimestampScript, LaneSweeperScript):
name = "Cache one representation per lane"
@classmethod
def arg_parser(cls, _db):
parser = LaneSweeperScript.arg_parser(_db)
parser.add_argument(
'--language',
help='Process only lanes that include books in this language.',
action='append'
)
parser.add_argument(
'--max-depth',
help='Stop processing lanes once you reach this depth.',
type=int,
default=None
)
parser.add_argument(
'--min-depth',
help='Start processing lanes once you reach this depth.',
type=int,
default=1
)
return parser
def __init__(self, _db=None, cmd_args=None, testing=False, manager=None,
*args, **kwargs):
"""Constructor.
:param _db: A database connection.
:param cmd_args: A mock set of command-line arguments, to use instead
of looking at the actual command line.
:param testing: If this method creates a CirculationManager object,
this value will be passed in to its constructor as its value for
`testing`.
:param manager: A mock CirculationManager object, to use instead
of creating a new one (creating a CirculationManager object is
very time-consuming).
:param *args: Positional arguments to pass to the superconstructor.
:param **kwargs: Keyword arguments to pass to the superconstructor.
"""
super(CacheRepresentationPerLane, self).__init__(_db, *args, **kwargs)
self.parse_args(cmd_args)
if not manager:
manager = CirculationManager(self._db, testing=testing)
from api.app import app
app.manager = manager
self.app = app
self.base_url = ConfigurationSetting.sitewide(self._db, Configuration.BASE_URL_KEY).value
def parse_args(self, cmd_args=None):
parser = self.arg_parser(self._db)
parsed = parser.parse_args(cmd_args)
self.languages = []
if parsed.language:
for language in parsed.language:
alpha = LanguageCodes.string_to_alpha_3(language)
if alpha:
self.languages.append(alpha)
else:
self.log.warn("Ignored unrecognized language code %s", alpha)
self.max_depth = parsed.max_depth
self.min_depth = parsed.min_depth
# Return the parsed arguments in case a subclass needs to
# process more args.
return parsed
def should_process_lane(self, lane):
if not isinstance(lane, Lane):
return False
language_ok = False
if not self.languages:
# We are considering lanes for every single language.
language_ok = True
if not lane.languages:
# The lane has no language restrictions.
language_ok = True
for language in self.languages:
if language in lane.languages:
language_ok = True
break
if not language_ok:
return False
if self.max_depth is not None and lane.depth > self.max_depth:
return False
if self.min_depth is not None and lane.depth < self.min_depth:
return False
return True
def cache_url(self, annotator, lane, languages):
raise NotImplementedError()
def generate_representation(self, *args, **kwargs):
raise NotImplementedError()
# The generated document will probably be an OPDS acquisition
# feed.
ACCEPT_HEADER = OPDSFeed.ACQUISITION_FEED_TYPE
cache_url_method = None
def process_library(self, library):
begin = time.time()
client = self.app.test_client()
ctx = self.app.test_request_context(base_url=self.base_url)
ctx.push()
super(CacheRepresentationPerLane, self).process_library(library)
ctx.pop()
end = time.time()
self.log.info(
"Processed library %s in %.2fsec", library.short_name, end-begin
)
def process_lane(self, lane):
"""Generate a number of feeds for this lane.
One feed will be generated for each combination of Facets and
Pagination objects returned by facets() and pagination().
"""
cached_feeds = []
for facets in self.facets(lane):
for pagination in self.pagination(lane):
extra_description = ""
if facets:
extra_description += " Facets: %s." % facets.query_string
if pagination:
extra_description += " Pagination: %s." % pagination.query_string
self.log.info(
"Generating feed for %s.%s", lane.full_identifier,
extra_description
)
a = time.time()
feed = self.do_generate(lane, facets, pagination)
b = time.time()
if feed:
cached_feeds.append(feed)
self.log.info(
"Took %.2f sec to make %d bytes.", (b-a),
len(feed.data)
)
total_size = sum(len(x.data) for x in cached_feeds)
return cached_feeds
def facets(self, lane):
"""Yield a Facets object for each set of facets this
script is expected to handle.
:param lane: The lane under consideration. (Different lanes may have
different available facets.)
:yield: A sequence of Facets objects.
"""
yield None
def pagination(self, lane):
"""Yield a Pagination object for each page of a feed this
script is expected to handle.
:param lane: The lane under consideration. (Different lanes may have
different pagination rules.)
:yield: A sequence of Pagination objects.
"""
yield None
class CacheFacetListsPerLane(CacheRepresentationPerLane):
"""Cache the first two pages of every relevant facet list for this lane."""
name = "Cache paginated OPDS feed for each lane"
@classmethod
def arg_parser(cls, _db):
parser = CacheRepresentationPerLane.arg_parser(_db)
available = Facets.DEFAULT_ENABLED_FACETS[Facets.ORDER_FACET_GROUP_NAME]
order_help = 'Generate feeds for this ordering. Possible values: %s.' % (
", ".join(available)
)
parser.add_argument(
'--order',
help=order_help,
action='append',
default=[],
)
available = Facets.DEFAULT_ENABLED_FACETS[Facets.AVAILABILITY_FACET_GROUP_NAME]
availability_help = 'Generate feeds for this availability setting. Possible values: %s.' % (
", ".join(available)
)
parser.add_argument(
'--availability',
help=availability_help,
action='append',
default=[],
)
available = Facets.DEFAULT_ENABLED_FACETS[Facets.COLLECTION_FACET_GROUP_NAME]
collection_help = 'Generate feeds for this collection within each lane. Possible values: %s.' % (
", ".join(available)
)
parser.add_argument(
'--collection',
help=collection_help,
action='append',
default=[],
)
available = [x.INTERNAL_NAME for x in EntryPoint.ENTRY_POINTS]
entrypoint_help = 'Generate feeds for this entry point within each lane. Possible values: %s.' % (
", ".join(available)
)
parser.add_argument(
'--entrypoint',
help=entrypoint_help,
action='append',
default=[],
)
default_pages = 2
parser.add_argument(
'--pages',
help="Number of pages to cache for each facet. Default: %d" % default_pages,
type=int,
default=default_pages
)
return parser
def parse_args(self, cmd_args=None):
parsed = super(CacheFacetListsPerLane, self).parse_args(cmd_args)
self.orders = parsed.order
self.availabilities = parsed.availability
self.collections = parsed.collection
self.entrypoints = parsed.entrypoint
self.pages = parsed.pages
return parsed
def facets(self, lane):
"""This script covers a user-specified combination of facets, but it
defaults to using every combination of available facets for
the given lane with a certain sort order.
This means every combination of availability, collection, and
entry point.
That's a whole lot of feeds, which is why this script isn't
actually used -- by the time we generate all of then, they've
expired.
"""
library = lane.get_library(self._db)
default_order = library.default_facet(Facets.ORDER_FACET_GROUP_NAME)
allowed_orders = library.enabled_facets(Facets.ORDER_FACET_GROUP_NAME)
chosen_orders = self.orders or [default_order]
allowed_entrypoint_names = [
x.INTERNAL_NAME for x in library.entrypoints
]
default_entrypoint_name = None
if allowed_entrypoint_names:
default_entrypoint_name = allowed_entrypoint_names[0]
chosen_entrypoints = self.entrypoints or allowed_entrypoint_names
default_availability = library.default_facet(
Facets.AVAILABILITY_FACET_GROUP_NAME
)
allowed_availabilities = library.enabled_facets(
Facets.AVAILABILITY_FACET_GROUP_NAME
)
chosen_availabilities = self.availabilities or [default_availability]
default_collection = library.default_facet(
Facets.COLLECTION_FACET_GROUP_NAME
)
allowed_collections = library.enabled_facets(
Facets.COLLECTION_FACET_GROUP_NAME
)
chosen_collections = self.collections or [default_collection]
top_level = (lane.parent is None)
for entrypoint_name in chosen_entrypoints:
entrypoint = EntryPoint.BY_INTERNAL_NAME.get(entrypoint_name)
if not entrypoint:
logging.warn("Ignoring unknown entry point %s" % entrypoint_name)
continue
if not entrypoint_name in allowed_entrypoint_names:
logging.warn("Ignoring disabled entry point %s" % entrypoint_name)
continue
for order in chosen_orders:
if order not in allowed_orders:
logging.warn("Ignoring unsupported ordering %s" % order)
continue
for availability in chosen_availabilities:
if availability not in allowed_availabilities:
logging.warn("Ignoring unsupported availability %s" % availability)
continue
for collection in chosen_collections:
if collection not in allowed_collections:
logging.warn("Ignoring unsupported collection %s" % collection)
continue
facets = Facets(
library=library, collection=collection,
availability=availability,
entrypoint=entrypoint,
entrypoint_is_default=(
top_level and
entrypoint.INTERNAL_NAME == default_entrypoint_name
),
order=order, order_ascending=True
)
yield facets
def pagination(self, lane):
"""This script covers a user-specified number of pages."""
page = Pagination.default()
for pagenum in range(0, self.pages):
yield page
page = page.next_page
if not page:
# There aren't enough books to fill `self.pages`
# pages. Stop working.
break
def do_generate(self, lane, facets, pagination, feed_class=None):
feeds = []
title = lane.display_name
library = lane.get_library(self._db)
annotator = self.app.manager.annotator(lane, facets=facets)
url = annotator.feed_url(lane, facets=facets, pagination=pagination)
feed_class = feed_class or AcquisitionFeed
return feed_class.page(
_db=self._db, title=title, url=url, worklist=lane,
annotator=annotator, facets=facets, pagination=pagination,
max_age=0
)
class CacheOPDSGroupFeedPerLane(CacheRepresentationPerLane):
name = "Cache OPDS grouped feed for each lane"
def should_process_lane(self, lane):
# OPDS grouped feeds are only generated for lanes that have sublanes.
if not lane.children:
return False
if self.max_depth is not None and lane.depth > self.max_depth:
return False
return True
def do_generate(self, lane, facets, pagination, feed_class=None):
title = lane.display_name
annotator = self.app.manager.annotator(lane, facets=facets)
url = annotator.groups_url(lane, facets)
feed_class = feed_class or AcquisitionFeed
# Since grouped feeds are only cached for lanes that have sublanes,
# there's no need to consider the case of a lane with no sublanes,
# unlike the corresponding code in OPDSFeedController.groups()
return feed_class.groups(
_db=self._db, title=title, url=url, worklist=lane,
annotator=annotator, max_age=0, facets=facets
)
def facets(self, lane):
"""Generate a Facets object for each of the library's enabled
entrypoints.
This is the only way grouped feeds are ever generated, so there is
no way to override this.
"""
top_level = (lane.parent is None)
library = lane.get_library(self._db)
# If the WorkList has explicitly defined EntryPoints, we want to
# create a grouped feed for each EntryPoint. Otherwise, we want
# to create a single grouped feed with no particular EntryPoint.
#
# We use library.entrypoints instead of lane.entrypoints
# because WorkList.entrypoints controls which entry points you
# can *switch to* from a given WorkList. We're handling the
# case where you switched further up the hierarchy and now
# you're navigating downwards.
entrypoints = list(library.entrypoints) or [None]
default_entrypoint = entrypoints[0]
for entrypoint in entrypoints:
facets = FeaturedFacets(
minimum_featured_quality=library.minimum_featured_quality,
uses_customlists=lane.uses_customlists,
entrypoint=entrypoint,
entrypoint_is_default=(
top_level and entrypoint is default_entrypoint
)
)
yield facets
class CacheMARCFiles(LaneSweeperScript):
"""Generate and cache MARC files for each input library."""
name = "Cache MARC files"
@classmethod
def arg_parser(cls, _db):
parser = LaneSweeperScript.arg_parser(_db)
parser.add_argument(
'--max-depth',
help='Stop processing lanes once you reach this depth.',
type=int,
default=0,
)
parser.add_argument(
'--force',
help="Generate new MARC files even if MARC files have already been generated recently enough",
dest='force', action='store_true',
)
return parser
def __init__(self, _db=None, cmd_args=None, *args, **kwargs):
super(CacheMARCFiles, self).__init__(_db, *args, **kwargs)
self.parse_args(cmd_args)
def parse_args(self, cmd_args=None):
parser = self.arg_parser(self._db)
parsed = parser.parse_args(cmd_args)
self.max_depth = parsed.max_depth
self.force = parsed.force
return parsed
def should_process_library(self, library):
integration = ExternalIntegration.lookup(
self._db, ExternalIntegration.MARC_EXPORT,
ExternalIntegration.CATALOG_GOAL, library)
return (integration is not None)
def process_library(self, library):
if self.should_process_library(library):
super(CacheMARCFiles, self).process_library(library)
self.log.info("Processed library %s" % library.name)
def should_process_lane(self, lane):
if isinstance(lane, Lane):
if self.max_depth is not None and lane.depth > self.max_depth:
return False
if lane.size == 0:
return False
return True
def process_lane(self, lane, exporter=None):
# Generate a MARC file for this lane, if one has not been generated recently enough.
if isinstance(lane, Lane):
library = lane.library
else:
library = lane.get_library(self._db)
annotator = MARCLibraryAnnotator(library)
exporter = exporter or MARCExporter.from_config(library)
update_frequency = ConfigurationSetting.for_library_and_externalintegration(
self._db, MARCExporter.UPDATE_FREQUENCY, library, exporter.integration
).int_value
if update_frequency is None:
update_frequency = MARCExporter.DEFAULT_UPDATE_FREQUENCY
last_update = None
files_q = self._db.query(CachedMARCFile).filter(
CachedMARCFile.library==library
).filter(
CachedMARCFile.lane==(lane if isinstance(lane, Lane) else None),
).order_by(CachedMARCFile.end_time.desc())
if files_q.count() > 0:
last_update = files_q.first().end_time
if not self.force and last_update and (last_update > utc_now() - timedelta(days=update_frequency)):
self.log.info("Skipping lane %s because last update was less than %d days ago" % (lane.display_name, update_frequency))
return
# To find the storage integration for the exporter, first find the
# external integration link associated with the exporter's external
# integration.
integration_link = get_one(
self._db, ExternalIntegrationLink,
external_integration_id=exporter.integration.id,
purpose=ExternalIntegrationLink.MARC
)
# Then use the "other" integration value to find the storage integration.
storage_integration = get_one(self._db, ExternalIntegration,
id=integration_link.other_integration_id
)
if not storage_integration:
self.log.info("No storage External Integration was found.")
return
# First update the file with ALL the records.
records = exporter.records(
lane, annotator, storage_integration
)
# Then create a new file with changes since the last update.
start_time = None
if last_update:
# Allow one day of overlap to ensure we don't miss anything due to script timing.
start_time = last_update - timedelta(days=1)
records = exporter.records(
lane, annotator, storage_integration, start_time=start_time
)
class AdobeAccountIDResetScript(PatronInputScript):
@classmethod
def arg_parser(cls, _db):
parser = super(AdobeAccountIDResetScript, cls).arg_parser(_db)
parser.add_argument(
'--delete',
help="Actually delete credentials as opposed to showing what would happen.",
action='store_true'
)
return parser
def do_run(self, *args, **kwargs):
parsed = self.parse_command_line(self._db, *args, **kwargs)
patrons = parsed.patrons
self.delete = parsed.delete
if not self.delete:
self.log.info(
"This is a dry run. Nothing will actually change in the database."
)
self.log.info(
"Run with --delete to change the database."
)
if patrons and self.delete:
self.log.warn(
"""This is not a drill.
Running this script will permanently disconnect %d patron(s) from their Adobe account IDs.
They will be unable to fulfill any existing loans that involve Adobe-encrypted files.
Sleeping for five seconds to give you a chance to back out.
You'll get another chance to back out before the database session is committed.""",
len(patrons)
)
time.sleep(5)
self.process_patrons(patrons)
if self.delete:
self.log.warn("All done. Sleeping for five seconds before committing.")
time.sleep(5)
self._db.commit()
def process_patron(self, patron):
"""Delete all of a patron's Credentials that contain an Adobe account
ID _or_ connect the patron to a DelegatedPatronIdentifier that
contains an Adobe account ID.
"""
self.log.info(
'Processing patron "%s"',
patron.authorization_identifier or patron.username
or patron.external_identifier
)
for credential in AuthdataUtility.adobe_relevant_credentials(patron):
self.log.info(
' Deleting "%s" credential "%s"',
credential.type, credential.credential
)
if self.delete:
self._db.delete(credential)
class AvailabilityRefreshScript(IdentifierInputScript):
"""Refresh the availability information for a LicensePool, direct from the
license source.
"""
def do_run(self):
args = self.parse_command_line(self._db)
if not args.identifiers:
raise Exception(
"You must specify at least one identifier to refresh."
)
# We don't know exactly how big to make these batches, but 10 is
# always safe.
start = 0
size = 10
while start < len(args.identifiers):
batch = args.identifiers[start:start+size]
self.refresh_availability(batch)
self._db.commit()
start += size
def refresh_availability(self, identifiers):
provider = None
identifier = identifiers[0]
if identifier.type==Identifier.THREEM_ID:
sweeper = BibliothecaCirculationSweep(self._db)
sweeper.process_batch(identifiers)
elif identifier.type==Identifier.OVERDRIVE_ID:
api = OverdriveAPI(self._db)
for identifier in identifiers:
api.update_licensepool(identifier.identifier)
elif identifier.type==Identifier.AXIS_360_ID:
provider = Axis360BibliographicCoverageProvider(self._db)
provider.process_batch(identifiers)
else:
self.log.warn("Cannot update coverage for %r" % identifier.type)
class LanguageListScript(LibraryInputScript):
"""List all the languages with at least one non-open access work
in the collection.
"""
def process_library(self, library):
print(library.short_name)
for item in self.languages(library):
print(item)
def languages(self, library):
":yield: A list of output lines, one per language."
for abbreviation, count in library.estimated_holdings_by_language(
include_open_access=False
).most_common():
display_name = LanguageCodes.name_for_languageset(abbreviation)
yield "%s %i (%s)" % (abbreviation, count, display_name)
class CompileTranslationsScript(Script):
"""A script to combine translation files for circulation, core
and the admin interface, and compile the result to be used by the
app. The combination step is necessary because Flask-Babel does not
support multiple domains yet.
"""
def run(self):
languages = Configuration.localization_languages()
for language in languages:
base_path = "translations/%s/LC_MESSAGES" % language
if not os.path.exists(base_path):
logging.warn("No translations for configured language %s" % language)
continue
os.system("rm %(path)s/messages.po" % dict(path=base_path))
os.system("cat %(path)s/*.po > %(path)s/messages.po" % dict(path=base_path))
os.system("pybabel compile -f -d translations")
class InstanceInitializationScript(TimestampScript):
"""An idempotent script to initialize an instance of the Circulation Manager.
This script is intended for use in servers, Docker containers, etc,
when the Circulation Manager app is being installed. It initializes
the database and sets an appropriate alias on the ElasticSearch index.
Because it's currently run every time a container is started, it must
remain idempotent.
"""
name = "Instance initialization"
TEST_SQL = "select * from timestamps limit 1"
def run(self, *args, **kwargs):
# Create a special database session that doesn't initialize
# the ORM -- this could be fatal if there are migration
# scripts that haven't run yet.
#
# In fact, we don't even initialize the database schema,
# because that's the thing we're trying to check for.
url = Configuration.database_url()
_db = SessionManager.session(
url, initialize_data=False, initialize_schema=False
)
results = None
try:
# We need to check for the existence of a known table --
# this will demonstrate that this script has been run before --
# but we don't need to actually look at what we get from the
# database.
#
# Basically, if this succeeds, we can bail out and not run
# the rest of the script.
results = list(_db.execute(self.TEST_SQL))
except Exception as e:
# This did _not_ succeed, so the schema is probably not
# initialized and we do need to run this script.. This
# database session is useless now, but we'll create a new
# one during the super() call, and use that one to do the
# work.
_db.close()
if results is None:
super(InstanceInitializationScript, self).run(*args, **kwargs)
else:
self.log.error("I think this site has already been initialized; doing nothing.")
def do_run(self, ignore_search=False):
# Creates a "-current" alias on the Elasticsearch client.
if not ignore_search:
try:
search_client = ExternalSearchIndex(self._db)
except CannotLoadConfiguration as e:
# Elasticsearch isn't configured, so do nothing.
pass