libby_old.html
001| """LIBBY TIMELINE.
001|
001| https://share.libbyapp.com/data/4d163f2e-f6de-4181-ab34-efa6d198bd09/libbytimeline-all-loans.json
001| https://share.libbyapp.com/data/fff28a75-2878-4213-a4f7-9ae592e380f4/libbytimeline-timeline.json
001|
001| JSON structure:
001| author: <text>
001| publisher: <text>
001| timestamp: 1714709045948,
001| activity: Returned,
001| details: <text>
001| cover:
001| contentType: image/jpeg
001| url: https://...
001| title: <text>
001| color: #xxxxxx
001| format: ebook
001| title:
001| text: <text>
001| url: https://...
001| titleId: <number>
001| library:
001| text: <text>
001| url: https://...
001| key: <text>
001|
001| Classes:
001| libbyevent
001| libbyloan
001| libbytimeline
001|
001| Commands:
001| list do_listing
001| page do_titles_webpage
001| auth do_authors_webpage
001| test do_test
001|
001| """
002|
003| from sys import argv, stdout, exc_info
004| from traceback import extract_tb
005| from os import path
006| from datetime import datetime
007| from logger import logger, info, debug, trace
008| from goodies import KWARG
009| from dates import CST
010| from files import linefile, jsonfile
011| from webpage import WebPage
012| from libby import libbytag, libbytimeline
013|
014| BasePath = r'C:\CJS\prj\Python\ws'
015| DataPath = path.join(BasePath, 'dat')
016| HtmlPath = r'C:\CJS\www\root\cjs'
017| JsonPath = r'C:\CJS\www\_dat'
018| FileName = path.join(JsonPath, 'libbytimeline-all.json')
019| Log = logger('Libby')
020|
021| CMND = ''
022| ARGS = {
023|
024|
025| }
026|
027| TSDT = lambda ts:datetime.fromtimestamp((ts if ts else 0)/1000.0, tz=CST())
028|
029|
030| class libbyevent:
031| '''Libby Event: Placed on Hold, Borrowed, Returned.'''
032| def __init__ (self, json_recd):
033| title = json_recd['title']
034| cover = json_recd['cover']
035| self.activity = json_recd['activity']
036| self.ts = TSDT(json_recd['timestamp'])
037| self.note = json_recd['details'] if 'details' in json_recd else '---'
038| self.author = json_recd['author'] if 'author' in json_recd else ''
039| self.title = title['text'] if 'text' in title else '???'
040| self.titleId = title['titleId'] if 'titleId' in title else '###'
041| self.url = title['url'] if 'url' in title else ''
042| self.cover = cover['url'] if 'url' in cover else ''
043| self.color = cover['color'] if 'color' in cover else '#ffffff'
044|
045| def __str__ (self):
046| return f'{self.ts:%b %d, %Y %H:%M} [{self.activity}] {self.title} ({self.titleId})'
047|
048| def __repr__ (self):
049| t = (self.ts, self.activity, self.titleId, self.title, self.author)
050| s = '{libbyevent:{ts:"%s", act:"%s", id:"%s", title:"%s", author:"%s"}}'
051| return s % t
052|
053|
054| class libbyloan:
055| def __init__ (self, retn, loan=None, hold=None):
056| self.ts = retn.ts
057| self.titleId = retn.titleId
058| self.title = retn.title
059| self.author = retn.author
060| self.url = retn.url
061| self.cover = retn.cover
062| self.retn:libbyevent = retn
063| self.loan:libbyevent = loan
064| self.hold:libbyevent = hold
065|
066| def __str__ (self):
067| s1 = self.hold.ts.strftime('%m-%d-%y') if self.hold else '--------'
068| s2 = self.loan.ts.strftime('%m-%d-%y') if self.loan else '--------'
069| s3 = self.retn.ts.strftime('%m-%d-%y') if self.retn else '--------'
070| return f'[{s1}][{s2}][{s3}] {self.title[0:20]}, {self.author[0:20]}'
071|
072| def __repr__ (self):
073| t = (self.titleId, self.title, self.author)
074| s = '{libbyloan:{id:"%s", title:"%s", author:"%s", H:0, B:0, R:0}}'
075| return s % t
076|
077|
078| class libbytimeline (jsonfile):
079| '''Libby Timeline.'''
080|
081| def __init__ (self, filename):
082| super().__init__(filename)
083| self.load()
084| self.ver = self.data['version']
085| self.events = [libbyevent(rcd) for rcd in self.data['timeline']]
086| self.events = list(sorted(self.events, key=lambda r:r.ts, reverse=True))
087| self.queue = list(self.events)
088| self.timeline = {}
089|
090| def get_next_record (rcds:list, act_type:str='Returned', tid=None):
091| for ix,r in enumerate(rcds):
092| if r.activity == act_type:
093| if tid is None:
094| return (ix,r)
095| if tid == r.titleId:
096| return (ix,r)
097| return (-1,None)
098|
099| while 0 < len(self.queue):
100|
101| rx,rcd1 = get_next_record(self.queue)
102| if rx < 0:
103| Log.debug('No more returned books found in queue.')
104| break
105|
106|
107| del self.queue[rx]
108| Log.trace(f'Return: {rcd1!s}')
109|
110|
111| rx,rcd2 = get_next_record(self.queue, 'Borrowed', rcd1.titleId)
112| if rx < 0:
113| Log.trace(f'No borrow event for "{rcd1.title}"')
114| else:
115| if rcd1.ts < rcd2.ts:
116| Log.warn(f'Borrow is after return: {rcd2!s}')
117| break
118| if 90 < (rcd1.ts - rcd2.ts).days:
119| Log.warn(f'Borrow occurs too early: {rcd2!s}')
120| break
121|
122| del self.queue[rx]
123| Log.trace(f'Borrow: {rcd2!s} ({(rcd1.ts-rcd2.ts).days} days)')
124|
125|
126| rx,rcd3 = get_next_record(self.queue, 'Placed on hold', rcd1.titleId)
127| if rx < 0:
128| Log.trace(f'No hold event for "{rcd1.title}"')
129| else:
130| if rcd1.ts < rcd2.ts:
131| Log.warn(f'Borrow is after return: {rcd2!s}')
132| break
133|
134| del self.queue[rx]
135| Log.trace(f'Holding: {rcd3!s} ({(rcd1.ts-rcd3.ts).days} days)')
136|
137|
138| loan = libbyloan(rcd1, rcd2, rcd3)
139| self.timeline[loan.ts] = loan
140| Log.trace(loan)
141|
142| def __iter__ (self): return iter(self.events)
143| def __len__ (self): return len(self.events)
144| def __getitem__ (self, ix): return self.events[ix]
145|
146| def __str__ (self):
147| return f'{self.name} ({len(self)} titles)'
148|
149| def __repr__ (self):
150| t = (self.ver, self.name, len(self))
151| s = '{libbytimeline:{ver:%d, name:"%s", len:%d}}'
152| return s % t
153|
154| def travel_timeline (self, func, reverse=True):
155| for ix,ts in enumerate(sorted(self.timeline, reverse=reverse)):
156| func(ix, self.timeline[ts])
157|
158| def search (self, pattern, field):
159| return [evt for evt in self.events if getattr(evt,field)==pattern]
160|
161| def dump (self, limit=0, file=stdout):
162| for ix,d in enumerate(self):
163| if limit and (limit <= ix):
164| break
165| print(d, file=file)
166| print(file=file)
167|
168|
169|
170| TitlesCSS = '''\
170| #PageBody table.timeline {
170| font-family: serif;
170| font-size: 15px;
170| cell-spacing: 0;
170| padding: 0;
170| border-top: 1px solid black;
170| border-right: 1px solid black;
170| border-bottom: 1px solid black;
170| margin: 9px;
170| }
170| #PageBody table.timeline thead th {
170| background-color: #000000;
170| color: #ffffff;
170| }
170| #PageBody table.timeline tbody td.ix {
170| background-color: #000000;
170| color: #ffffff;
170| font-family: monospace;
170| font-weight: bold;
170| text-align: center;
170| vertical-align: top;
170| padding: 1px 3px;
170| border-right: 1px solid black;
170| }
170| #PageBody table.timeline tbody td.title {
170| background-color: #f0f8ff;
170| font-weight: bold;
170| padding: 1px 9px 1px 6px;
170| border-top: 1px solid black;
170| }
170| #PageBody table.timeline tbody td.author {
170| font-style: italic;
170| padding: 1px 9px 1px 6px;
170| }
170| #PageBody table.timeline tbody td.return {
170| background-color: #c0ffff;
170| font-family: monospace;
170| padding: 1px 9px;
170| border-top: 1px solid black;
170| }
170| #PageBody table.timeline tbody td.loan {
170| background-color: #c0ffc0;
170| font-family: monospace;
170| padding: 1px 9px;
170| }
170| #PageBody table.timeline tbody td.hold {
170| background-color: #ffffa0;
170| font-family: monospace;
170| padding: 1px 9px;
170| }
170| #PageBody table.timeline tbody td.note {
170| background-color: #f0f8ff;
170| font-style: italic;
170| padding: 1px 9px;
170| border-top: 1px solid black;
170| }
170| #PageBody table.timeline tbody td.dspan {
170| background-color: #f0f8ff;
170| font-style: italic;
170| padding: 1px 9px;
170| border-top: 1px solid black;
170| }
170| #PageBody table.timeline tbody td.hspan {
170| background-color: #fff8f0;
170| padding: 1px 9px;
170| font-style: italic;
170| }
170|
170| '''
171|
172| AuthorsCSS = '''\
172| #PageBody table.authors {
172| font-family: serif;
172| font-size: 18px;
172| cell-spacing: 0;
172| padding: 0;
172| border-top: 1px solid black;
172| border-right: 1px solid black;
172| border-bottom: 1px solid black;
172| margin: 9px;
172| }
172| #PageBody table.authors thead th {
172| background-color: #000000;
172| color: #ffffff;
172| }
172| #PageBody table.authors tbody td.ix {
172| background-color: #000000;
172| color: #ffffff;
172| font-family: monospace;
172| font-weight: bold;
172| text-align: center;
172| vertical-align: top;
172| padding: 2px 5px;
172| }
172| #PageBody table.authors tbody td.author {
172| font-family: sans-serif;
172| text-align: left;
172| vertical-align: top;
172| padding: 2px 9px 3px 6px;
172| border-top: 1px solid black;
172| }
172| #PageBody table.authors tbody td.title {
172| font-weight: normal;
172| padding: 1px 9px 1px 6px;
172| border-left: 1px solid black;
172| }
172| '''
173|
174|
175| def do_titles_webpage (**kwargs):
176| '''CMND: Generate a timeline webpage.'''
177| fpath = KWARG('fpath', HtmlPath, str, kwargs)
178| fname = KWARG('fname', 'libbytimeline.html', str, kwargs)
179| Log.info('make-titles-webpage:: %s' % str(list(kwargs.keys())))
180| Log.info('fpath="%s"' % fpath)
181| Log.info('fname="%s"' % fname)
182| Log.info()
183|
184| def cb_webrecord (ix:int, rcd:libbyloan):
185| pg.add('<tr>')
186| pg.add(f'<td rowspan="2" class="ix">{ix+1}</td>')
187| pg.add(f'<td class="title">{rcd.title}</td>')
188| pg.add(f'<td class="return">{rcd.retn.ts:%m-%d-%y}</td>')
189| pg.add(f'<td class="note">{rcd.retn.note}</td>')
190| if rcd.loan is None:
191| pg.add(f'<td class="dspan"></td>')
192| else:
193| span = rcd.retn.ts - rcd.loan.ts
194| pg.add(f'<td class="dspan">{span.days} days {span.seconds/3600:.1f} hours</td>')
195| pg.add('</tr>')
196|
197| pg.add('<tr>')
198| pg.add(f'<td class="author">{rcd.author}</td>')
199| pg.add(f'<td class="loan">{rcd.loan.ts:%m-%d-%y}</td>' if rcd.loan else '<td></td>')
200| pg.add(f'<td class="hold">{rcd.hold.ts:%m-%d-%y}</td>' if rcd.hold else '<td></td>')
201| if (rcd.loan is None) or (rcd.hold is None):
202| pg.add(f'<td class="hspan"></td>')
203| else:
204| span = rcd.loan.ts-rcd.hold.ts
205| pg.add(f'<td class="hspan">{span.days} days {span.seconds/3600:.1f} hours</td>')
206| pg.add('</tr>')
207|
208| props = dict(h1='Python Applications', h2='Libby', csstxt=TitlesCSS)
209| pg = WebPage('Libby Timeline', **props)
210| pg.add('<table class="timeline">')
211| pg.add('<thead>')
212| pg.add('<tr>')
213| pg.add('<th>#</th>')
214| pg.add('<th>Title/Author</th>')
215| pg.add('<th>Loan/Retn</th>')
216| pg.add('<th>Hold</th>')
217| pg.add('<th>Timespans</th>')
218| pg.add('</tr>')
219| pg.add('</thead>')
220| pg.add('<tbody>')
221|
222| library_books = libbytimeline(FileName)
223| library_books.travel_timeline(cb_webrecord)
224|
225| pg.add('</tbody>')
226| pg.add('</table>')
227|
228| fn = path.join(fpath, fname)
229| pg.save(fn)
230|
231| Log.info()
232| return 'Done'
233|
234|
235| def do_authors_webpage (**kwargs):
236| '''CMND: Generate an authors webpage.'''
237| fpath = KWARG('fpath', HtmlPath, str, kwargs)
238| fname = KWARG('fname', 'libbyauthors.html', str, kwargs)
239| Log.info('make-authors-webpage:: %s' % str(list(kwargs.keys())))
240| Log.info('fpath="%s"' % fpath)
241| Log.info('fname="%s"' % fname)
242| Log.info()
243| authors = {}
244|
245| def cb_authors (ix:int, rcd:libbyloan):
246| author = rcd.retn.author
247| title = rcd.retn.title
248| Log.debug(f'{author}, {title}')
249| if author not in authors:
250| authors[author] = {}
251| if title not in authors[author]:
252| authors[author][title] = 0
253| authors[author][title] += 1
254|
255| library_books = libbytimeline(FileName)
256| library_books.travel_timeline(cb_authors)
257|
258| props = dict(h1='Python Applications', h2='Libby', csstxt=AuthorsCSS)
259| pg = WebPage('Libby Timeline Authors', **props)
260|
261|
262| most_read_author = None
263| most_read_times = 0
264| for author in sorted(authors):
265| curr_author = authors[author]
266| if most_read_times < len(curr_author):
267| most_read_author = author
268| most_read_times = len(curr_author)
269|
270| pg.add(f'<p>Number of Authors: {len(authors)}<br>')
271| pg.add(f'Most Read Author: {most_read_author} ({most_read_times})</p>')
272| pg.add()
273|
274| pg.add('<table class="authors">')
275| pg.add('<thead>')
276| pg.add('<tr>')
277| pg.add('<th>#</th>')
278| pg.add('<th>Author</th>')
279| pg.add('<th>Title</th>')
280| pg.add('</tr>')
281| pg.add('</thead>')
282| pg.add('<tbody>')
283|
284| for ax,author in enumerate(sorted(authors)):
285| curr_author = authors[author]
286| nrows = len(curr_author)
287| atag = f'<br>({nrows})' if 1 < nrows else ''
288| pg.add(f'<tr>')
289| pg.add(f'<td rowspan="{nrows}" class="ix">{ax+1}</td>')
290| pg.add(f'<td rowspan="{nrows}" class="author""><strong>{author}</strong>{atag}</td>')
291| for tx,title in enumerate(sorted(curr_author)):
292| ntitles = curr_author[title]
293| ttag = f' ({ntitles})' if 1 < ntitles else ''
294| if tx == 0:
295| css = 'border-top: 1px solid black;'
296| pg.add(f'<td class="title" style="{css}">{title}{ttag}</td>')
297| else:
298| pg.add(f'<tr><td class="title">{title}{ttag}</td>')
299| pg.add(f'</tr>')
300|
301| pg.add('</tbody>')
302| pg.add('</table>')
303|
304| fn = path.join(fpath, fname)
305| pg.save(fn)
306|
307| Log.info()
308| return 'Done'
309|
310|
311| def do_listing (**kwargs):
312| '''CMND: Generate a timeline listing.'''
313| fpath = KWARG('fpath', BasePath, str, kwargs)
314| fname = KWARG('fname', 'libbytimeline.out', str, kwargs)
315| Log.info('make-listing:: %s' % str(list(kwargs.keys())))
316| Log.info('fpath="%s"' % fpath)
317| Log.info('fname="%s"' % fname)
318| Log.info()
319| library_books = libbytimeline(FileName)
320|
321| fn = path.join(fpath, fname) if fpath else fname
322| fo = linefile(fn)
323| fo.add('Libby Timeline')
324| fo.add()
325| fo.add('Queue:')
326| for evt in library_books.queue:
327| fo.add(str(evt))
328| fo.add()
329|
330| fo.add('Oddballs:')
331| duds = library_books.search('Hold expired', 'activity')
332| for dud in duds:
333| fo.add(str(dud))
334| fo.add()
335|
336| fo.add('Activities:')
337| activities = {event.activity for event in library_books}
338| stats = {act:0 for act in activities}
339|
340| for event in library_books:
341| stats[event.activity] += 1
342| for act,stat in sorted(stats.items(), key=lambda t:t[0], reverse=True):
343| fo.add(f'{act}: {stat}')
344| fo.add()
345| fo.add()
346|
347|
348| fo.add('Timeline:')
349| def cb_timeline (ix:int, rcd:libbyloan):
350| fo.add(f'{ix:3d} {rcd!s}')
351|
352| library_books.travel_timeline(cb_timeline)
353| fo.add()
354| fo.save()
355|
356| Log.info()
357| return 'Done'
358|
359|
360| def do_tags (**kwargs):
361| '''Generate HTML from Libby Tags JSON.'''
362| get_json = KWARG('get', 0, int, kwargs)
363| Log.info('test:: %s' % str(list(kwargs.keys())))
364| Log.info('get-json="%s"' % get_json)
365| Log.info()
366|
367|
368| tagnames = [k for k,v in kwargs.items() if v == '']
369|
370| for ix,tagname in enumerate(tagnames):
371| Log.info('%d: "%s"' % (ix+1, tagname))
372|
373| obj = libbytag(tagname, **kwargs)
374| obj(get_json=get_json)
375| Log.info()
376|
377| Log.info()
378| return 'Done'
379|
380|
381| def do_test_libbyqueue (**kwargs):
382| '''Test queue.json and the libbyqueue class.'''
383|
384| class libbyqueue (files.jsonfile):
385| fn = r"C:\CJS\prj\Python\app\dat\queue.json"
386|
387| def __init__ (self):
388| super().__init__(libbyqueue.fn)
389| self.load()
390| self.ver = self.data['version']
391| self.ts = self.data['tag']['timestamp']
392| self.name = self.data['tag']['name']
393| self.uuid = self.data['tag']['UUID']
394| self.rcds = self.data['titles']
395|
396| def __len__ (self): return len(self.rcds)
397| def __iter__ (self): return iter(self.rcds)
398| def __getitem__ (self, ix): return self.rcds[ix]
399|
400| def __str__ (self): return '%s (%d titles)' % (self.name,len(self))
401| def __repr__ (self):
402| t = (self.ts, self.name, self.uuid, len(self))
403| s = '{libbyqueue:{ts:%s, name:%s, uuid:%s, len:%d}}'
404| return s % t
405|
406| q = libbyqueue()
407| Log.info(q)
408| Log.info()
409|
410| for ttl in q:
411| Log.info(ttl['title']['text'])
412| Log.info()
413| return 'Done'
414|
415|
416| def do_test (**kwargs):
417| '''CMND: Do a Test.'''
418| fpath = KWARG('fpath', BasePath, str, kwargs)
419| fname = KWARG('fname', 'test.out', str, kwargs)
420| get_json = KWARG('get', False, int, kwargs)
421| Log.info('test:: %s' % str(list(kwargs.keys())))
422| Log.info('fpath="%s"' % fpath)
423| Log.info('fname="%s"' % fname)
424| Log.info()
425| from json import load
426| from libby import TSDT, libbybook
427|
428| """
428| F0 - 1111.0000 - .x000
428| 9F - 1001.1111 - 01.1111
428| A7 - 1010.0111 - 10.0111
428| BE - 1011.1110 - 11.1110
428|
428| x0.0001:1111.1001.1111.1110
428| 1 F 9 F E
428| """
429| json_url = 'https://share.libbyapp.com/data/ff762c24-35a7-4cb1-a62a-3f22a6487b48/libbytag-%F0%9F%A7%BE.json'
430| json_file = r"C:\Users\chris\Downloads\libbytag-WTF.json"
431|
432|
433| fp = open(json_file, mode='r', encoding='utf-8')
434| try:
435| json_data = load(fp)
436| Log.info('loaded: %s' % json_file)
437| Log.info()
438| except:
439| raise
440| finally:
441| fp.close()
442|
443|
444| file_version = json_data['version']
445| assert file_version == 1
446| ftag_name = json_data['tag']['name']
447| ftag_uuid = json_data['tag']['UUID']
448| ftag_date = TSDT(json_data['tag']['timestamp'])
449|
450|
451| books = []
452| for item in json_data['titles']:
453| books.append(libbybook(item))
454|
455|
456| books = sorted(books, key=lambda x:x.dt, reverse=True)
457|
458|
459| for ix,book in enumerate(books):
460| Log.info('%3d: %s' % (ix+1,book))
461|
462| Log.info()
463| return 'Done'
464|
465| def dispatch (cmd, **kwargs):
466| """Dispatch to a module function based on CMD."""
467| Log.info('CMD: %s' % cmd)
468| for kw in kwargs:
469| Log.debug('argument[%s]: %s' % (kw,kwargs[kw]))
470| Log.info()
471| if cmd == 'time': return do_timeline(**kwargs)
472| if cmd == 'list': return do_listing(**kwargs)
473| if cmd == 'page': return do_titles_webpage(**kwargs)
474| if cmd == 'auth': return do_authors_webpage(**kwargs)
475| if cmd == 'tags': return do_tags(**kwargs)
476| if cmd == 'lque': return do_test_libbyqueue(**kwargs)
477| if cmd == 'test': return do_test(**kwargs)
478| return 'Nothing to do!'
479|
480| if __name__ == '__main__':
481| print('autorun: %s' % argv[0])
482| Log.start(path.join(BasePath,'libbytimeline.log'))
483| Log.level(debug())
484| Log.info(argv[0])
485| Log.info()
486| cmd = argv[1] if 1 < len(argv) else CMND
487| kwargs = ARGS
488| for a in argv[2:]:
489| nv = a.split('=', 1)
490| kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
491| Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
492| try:
493| print('CMD: %s' % cmd)
494| print()
495| obj = dispatch(cmd, **kwargs)
496| print()
497| print(obj)
498| Log.info()
499| Log.info(obj)
500| except:
501| etype, evalue, tb = exc_info()
502| ts = extract_tb(tb)
503| Log.error()
504| Log.error('%s: %s' % (etype.__name__,str(evalue)))
505| Log.error()
506| for t in ts[-5:]:
507| Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
508| Log.error(' %s' % t[3])
509| Log.error()
510| raise
511| finally:
512| Log.end()
513|
514| '''eof'''
515|