libby_lib_old.html


001| '''Libby Timeline and Tags JSON File Processors.
001| 
001| Classes:
001|     libbytag        (object)        Libby JSON Tags File class.
001|     libbytimeline   (libbytag)      Libby JSON Timeline File class.
001|     libbybook       (object)        Libby Book JSON Object class.
001|     libbyevent      (libbybook)     Libby Event JSON Object class (used in Timeline).
001|     libbyrecord     (object)        Book Record class for Event Timeline.
001| 
001| Libby Timeline Tags JSON:
001| =========================
001| "timeline": [item, item, item,...]
001| 
001|     item :=
001|         "author", "publisher", "isbn", "timestamp",
001|         "activity", "details",
001|         "cover": {"contentType", "url", "title", "color", "format"}
001|         "title": {"text", "url", "titleId"}
001|         "library": {"text", "url", "key"}
001| 
001| Libby Queue Tags JSON:
001| ======================
001| "titles": [item, item, item,...]
001| 
001|     item :=
001|         "author", "publisher", "isbn", "timestamp",
001|         "cover": {"contentType", "url", "title", "color", "format"}
001|         "title": {"text", "url", "titleId"}
001|         "library": {"text", "url", "key"}
001| 
001| '''

002| ####################################################################################################
003| from os import path
004| from datetime import datetime
005| from json import load
006| from dates import CST
007| from htget import htget
008| from webpage import KWARG, WebPage
009| from goodies import plural, combine
010| ####################################################################################################
011| JsonPath = r'C:\CJS\www\_dat'
012| HtmlPath = r'C:\CJS\www\root\cjs'
013| 
014| Files = {
015|     'timeline': {
016|         'title': 'Libby Timeline',
017|         #'url': r'https://share.libbyapp.com/data/5e5f64d8-c443-4ac1-8705-87ea4124a2f5/libbytimeline-activities.json',
018|         'url': r'https://share.libbyapp.com/data/4d163f2e-f6de-4181-ab34-efa6d198bd09/libbytimeline-all-loans.json',
019|         'iname': r'libbytimeline-all.json',
020|         'oname': r'libby-timeline.html',
021|         'ipath': JsonPath,
022|         'opath': HtmlPath,
023|         'format': 'timeline',
024|     },
025|     'queue': {
026|         'title': 'Libby Queue',
027|         'url': r'https://share.libbyapp.com/data/80d50410-1e44-4ec7-94d8-b3f3388cb62b/libbytag-queue.json',
028|         'iname': r'queue.json',
029|         'oname': r'libby-queue.html',
030|         'ipath': JsonPath,
031|         'opath': HtmlPath,
032|         'format': 'tags',
033|     },
034|     'wanttoread': {
035|         'title': 'Libby Want to Read',
036|         'url': r'https://share.libbyapp.com/data/c7b65934-f8db-4ff4-ba72-2994ab236a4c/libbytag-want+to+read.json',
037|         'iname': r'want-to-read.json',
038|         'oname': r'libby-want-to-read.html',
039|         'ipath': JsonPath,
040|         'opath': HtmlPath,
041|         'format': 'tags',
042|     },
043|     'possibles': {
044|         'title': 'Libby Possibles',
045|         'url': r'https://share.libbyapp.com/data/f5b786a1-1cda-497b-95b1-8dbcc6c89e6a/libbytag-possibles.json',
046|         'iname': r'possibles.json',
047|         'oname': r'libby-possibles.html',
048|         'ipath': JsonPath,
049|         'opath': HtmlPath,
050|         'format': 'tags',
051|     },
052| }
053| 
054| TSDT = lambda ts:datetime.fromtimestamp((ts if ts else 0)/1000.0, tz=CST())
055| S42 = lambda s:(('%.39s...'%s) if 42<len(s) else (s))
056| TDS = lambda td:('%s day%s, %.2f hours' % (td.days, plural(td.days), td.seconds/3600.0))
057| 
058| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
059| class libbybook (object):
060|     '''Libby Book JSON Object class.'''
061|     def __init__ (self, json_text):
062|         self.title = json_text['title']['text']
063|         self.url = json_text['title']['url']
064|         cover = json_text['cover']
065|         self.cover = cover['url'] if 'url' in cover else ''
066|         self.color = cover['color'] if 'color' in cover else ''
067|         self.author = json_text['author'] if 'author' in json_text else ''
068|         self.publisher = json_text['publisher'] if 'publisher' in json_text else ''
069|         self.isbn = json_text['isbn'] if 'isbn' in json_text else ''
070|         self.dt = TSDT(json_text['timestamp'])
071|         self.dts = self.dt.strftime('%a %b %d, %Y %I:%M %p %Z')
072| 
073|     def __str__ (self):
074|         return '%s, by %s' % (self.title, self.author)
075| 
076|     def html (self):
077|         return '<strong>%s</strong><br><em>%s</em>' % (S42(self.title), S42(self.author))
078| 
079|     def ISBN (self):
080|         s0 = self.isbn[0:3]
081|         s1 = self.isbn[3:4]
082|         s2 = self.isbn[4:6]
083|         s3 = self.isbn[6:12]
084|         s4 = self.isbn[12:13]
085|         return '%s-%s-%s-%s-%s' % (s0,s1,s2,s3,s4)
086| 
087| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
088| class libbyevent (libbybook):
089|     '''Libby Event JSON Object class (used in Timeline).'''
090|     def __init__ (self, json_text):
091|         super().__init__(json_text)
092|         self.event = json_text['activity'].strip() if 'activity' in json_text else ''
093|         self.details = json_text['details'].strip() if 'details' in json_text else ''
094| 
095| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
096| class libbyrecord (object):
097|     '''Book Record class for Event Timeline.'''
098|     def __init__ (self, libby_book):
099|         self.title = libby_book.title
100|         self.author = libby_book.author
101|         self.cover = libby_book.cover
102|         self.color = libby_book.color
103|         self.isbn = libby_book.isbn
104|         self.onhold = []
105|         self.borrowed = []
106|         self.returned = []
107|         self.note = ''
108| 
109|     def __str__ (self):
110|         return '<strong>%s</strong><br><em>%s</em>' % (S42(self.title), S42(self.author))
111| 
112| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
113| class libbytag (object):
114|     '''Libby JSON Tags File class.'''
115|     table_css = r'color:#000000;background-color:#efefef;font-size:9pt;border-spacing:6px 4px;padding:0;border:1px solid black;margin:0 0 12pt 0;'
116|     tcapt_css = r'font-size:12pt;font-weight:bold;padding:5px;'
117|     thead_css = r'color:#dfdfdf;background-color:#000000;'
118|     index_css = r'font-size:8pt;text-align:right;vertical-align:middle;padding:4px;border-right:1px solid black;'
119|     title_css = r'font-size:10pt;vertical-align:top;padding:2px 6px 2px 3px;'
120|     digit_css = r'white-space:nowrap;font-family:monospace;font-size:8pt;vertical-align:top;padding:2px 5px;'
121|     diffs_css = r'white-space:nowrap;font-size:8pt;font-style:italic;padding:2px 5px;'
122|     small_css = r'font-size:8pt;padding:2px;'
123|     tnote_css = r'font-size:7pt;font-style:italic;padding:2px 9px;border-top:1px solid black;'
124| 
125|     def __init__ (self, tagname, **kwargs):
126|         self.tag = tagname
127|         self.url = Files[tagname]['url']
128|         self.title = KWARG('title', Files[tagname]['title'], str, kwargs)
129|         self.ipath = KWARG('ipath', Files[tagname]['ipath'], str, kwargs)
130|         self.iname = KWARG('iname', Files[tagname]['iname'], str, kwargs)
131|         self.opath = KWARG('opath', Files[tagname]['opath'], str, kwargs)
132|         self.oname = KWARG('oname', Files[tagname]['oname'], str, kwargs)
133|         self.json_file = path.join(self.ipath, self.iname)
134|         self.html_file = path.join(self.opath, self.oname)
135|         self.log = kwargs['log'] if 'log' in kwargs else None
136|         self.books = []
137|         self.page = WebPage(self.title, css=['/basic.css'])
138| 
139|     def __call__ (self, get_json=False):
140|         self.load(get_json=get_json)
141|         self.parse()
142|         self.generate()
143|         self.save()
144| 
145|     def __str__ (self):
146|         return self.title
147| 
148|     def load (self, get_json=False):
149|         '''Load JSON (w/ optional GET).'''
150|         # Get JSON from server (if needed or forced)...
151|         if get_json or not path.exists(self.json_file):
152|             rqst = htget(self.url)
153|             rqst.save(self.json_file)
154|             if self.log:self.log.info('downloaded: %s' % self.json_file)
155|         # Read JSON input file...
156|         fp = open(self.json_file, mode='r', encoding='utf-8')
157|         try:
158|             self.json_data = load(fp)
159|             if self.log:self.log.info('loaded: %s' % self.json_file)
160|         except:
161|             raise
162|         finally:
163|             fp.close()
164| 
165|     def save (self):
166|         '''Write HTML file.'''
167|         # Get the webpage content...
168|         html_text = self.page.content()
169|         # Save it to an HTML file...
170|         fp = open(self.html_file, mode='w', encoding='utf-8')
171|         try:
172|             fp.write(html_text)
173|             if self.log:self.log.info('wrote: %s' % self.html_file)
174|         except:
175|             raise
176|         finally:
177|             fp.close()
178| 
179|     def parse (self):
180|         '''Process JSON data into something more useful.'''
181|         # Pull out general properties...
182|         self.file_version = self.json_data['version']
183|         assert self.file_version == 1
184|         self.ftag_name = self.json_data['tag']['name']
185|         self.ftag_uuid = self.json_data['tag']['UUID']
186|         self.ftag_date = TSDT(self.json_data['tag']['timestamp'])
187|         # Convert array of JSON book objects into libbybook objects...
188|         for item in self.json_data['titles']:
189|             self.books.append(libbybook(item))
190|         # Sort them by date (most recent first)...
191|         self.books = sorted(self.books, key=lambda x:x.dt, reverse=True)
192| 
193|     def generate (self):
194|         '''Generate the HTML webpage.'''
195|         self.page.add('<table style="%s">' % self.table_css)
196|         self.page.add('<thead style="%s">' % self.thead_css)
197|         self.page.add('<tr>')
198|         self.page.add('<th colspan="2">Title/Author</th>')
199|         self.page.add('<th>&nbsp;</th>')
200|         self.page.add('<th>Added</th>')
201|         self.page.add('<th>&nbsp;</th>')
202|         self.page.add('</tr>')
203|         self.page.add('</thead>')
204|         self.page.add('<tbody>')
205|         for ix,book in enumerate(self.books):
206|             self.page.add('<tr>')
207|             self.page.add('<td style="%s">%d</td>' % (self.index_css, ix+1))
208|             self.page.add('<td style="%s">%s</td>' % (self.title_css, book.html()))
209|             self.page.add('<td style="background-color:%s;%s">&nbsp;</td>' % (book.color, self.small_css))
210|             self.page.add('<td style="%s">%s<br><a href="%s" target="_blank">%s</a></td>' % (self.digit_css, book.dts, book.url, book.ISBN()))
211|             self.page.add('<td style="background-color:%s;%s">&nbsp;</td>' % (book.color, self.small_css))
212|             self.page.add('</tr>')
213|         self.page.add('<tr>')
214|         self.page.add('<td colspan="5" style="%s">List created on %s</td>' % (self.tnote_css, self.ftag_date.strftime('%a %b %d, %Y %I:%M %p %Z')))
215|         self.page.add('</tr>')
216|         self.page.add('</tbody>')
217|         self.page.add('</table>')
218|         self.page.add('')
219|         self.page.add('<div style="padding-top:24pt;">&nbsp;</div>')
220| 
221| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
222| class libbytimeline (libbytag):
223|     '''Libby JSON Timeline File class.'''
224|     def __init__ (self, **kwargs):
225|         super().__init__('timeline', **kwargs)
226|         self.timeline = {}
227| 
228|     def parse (self):
229|         '''Process JSON data into something more useful.'''
230|         # Pull out general properties...
231|         self.file_version = self.json_data['version']
232|         assert self.file_version == 1
233|         # Convert array of JSON book objects into list of libbybook objects...
234|         for item in self.json_data['timeline']:
235|             self.books.append(libbyevent(item))
236|         # Convert list into timeline...
237|         for book in sorted(self.books, key=lambda rcd:rcd.dt, reverse=True):
238|             if book.title not in self.timeline:
239|                 self.timeline[book.title] = libbyrecord(book)
240|             rcd = self.timeline[book.title]
241|             if book.event == 'Placed on hold':
242|                 if 0 < len(rcd.onhold):
243|                     if self.log:self.log.info('Duplicate Hold: %s' % book)
244|                 rcd.onhold.append(book.dt)
245|             if book.event == 'Borrowed':
246|                 if 0 < len(rcd.borrowed):
247|                     if self.log:self.log.info('Duplicate Borrow: %s' % book)
248|                 rcd.borrowed.append(book.dt)
249|             if book.event == 'Returned':
250|                 if 0 < len(rcd.returned):
251|                     if self.log:self.log.info('Duplicate Return: %s' % book)
252|                 rcd.returned.append(book.dt)
253|                 rcd.note = book.details
254| 
255|     def generate (self):
256|         '''Generate the HTML webpage.'''
257|         # On Hold...
258|         self.page.add('<table style="%s">' % self.table_css)
259|         self.page.add('<caption style="%s">On Hold</caption>' % self.tcapt_css)
260|         self.page.add('<thead style="%s">' % self.thead_css)
261|         self.page.add('<tr>')
262|         self.page.add('<th colspan="2">Title/Author</th>')
263|         self.page.add('<th>&nbsp;</th>')
264|         self.page.add('<th>On Hold</th>')
265|         self.page.add('<th>Elapsed</th>')
266|         self.page.add('<th>&nbsp;</th>')
267|         self.page.add('</tr>')
268|         self.page.add('</thead>')
269|         self.page.add('<tbody>')
270|         now = datetime.now(tz=CST())
271|         rcds = [rcd for rcd in self.timeline.values() if len(rcd.onhold) and not len(rcd.borrowed)]
272|         for ix,rcd in enumerate(sorted(rcds, key=lambda x:x.onhold[0], reverse=False)):
273|             for onhld in rcd.onhold:
274|                 dts = onhld.strftime('%b %d, %Y')
275|                 diff = TDS(now-onhld)
276|                 self.page.add('<tr>')
277|                 self.page.add('<td style="%s">%d</td>' % (self.index_css, ix+1))
278|                 self.page.add('<td style="%s">%s</td>' % (self.title_css, rcd))
279|                 self.page.add('<td style="background-color:%s;%s">&nbsp;</td>' % (rcd.color, self.small_css))
280|                 self.page.add('<td style="%s">%s</td>' % (self.digit_css, dts))
281|                 self.page.add('<td style="%s">%s</td>' % (self.diffs_css, diff))
282|                 self.page.add('<td style="background-color:%s;%s">&nbsp;</td>' % (rcd.color, self.small_css))
283|                 self.page.add('</tr>')
284|         self.page.add('</tbody>')
285|         self.page.add('</table>')
286|         self.page.add('')
287| 
288|         # Timeline...
289|         self.page.add('<table style="%s">' % self.table_css)
290|         self.page.add('<caption style="%s">Timeline</caption>' % self.tcapt_css)
291|         self.page.add('<thead style="%s">' % self.thead_css)
292|         self.page.add('<tr>')
293|         self.page.add('<th colspan="2">Title/Author</th>')
294|         self.page.add('<th>Loan Dates</th>')
295|         self.page.add('<th>Loan Period</th>')
296|         self.page.add('</tr>')
297|         self.page.add('</thead>')
298|         self.page.add('<tbody>')
299|         rcds = [rcd for rcd in self.timeline.values() if len(rcd.returned)]
300|         for ix,rcd in enumerate(sorted(rcds, key=lambda x:x.returned[0], reverse=True)):
301|             for bor,ret in combine(rcd.borrowed, rcd.returned, fill=None):
302|                 dts1 = bor.strftime('%b %d, %Y') if bor else '-'
303|                 dts2 = ret.strftime('%b %d, %Y') if ret else '-'
304|                 diff = TDS(ret-bor) if (ret and bor) else '?'
305|                 self.page.add('<tr>')
306|                 self.page.add('<td style="%s">%d</td>' % (self.index_css, ix+1))
307|                 self.page.add('<td style="%s">%s</td>' % (self.title_css, rcd))
308|                 self.page.add('<td style="%s">%s<br>%s</td>' % (self.digit_css, dts2, dts1))
309|                 self.page.add('<td style="%s">%s<br>%s</td>' % (self.diffs_css, diff, rcd.note))
310|                 self.page.add('</tr>')
311|         self.page.add('</tbody>')
312|         self.page.add('</table>')
313|         self.page.add('')
314|         self.page.add('<div style="padding-top:24pt;">&nbsp;</div>')
315| 
316| 
317| ####################################################################################################
318| '''eof'''
319|