app.html


001| '''Libby Timeline and Tags HTML Pages.
001| 
001| JSON Timeline Structure:
001|   listof:
001|     author: <text>
001|     publisher: <text>
001|     isbn: 9781453223727
001|     timestamp: 1714709045948,
001|     activity: Borrowed
001|     details:  "21 days"
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| JSON Tag Queue Structure:
001|   listof:
001|     author: <text>
001|     publisher: <text>
001|     isbn: 9781453223727
001|     timestamp: 1714709045948,
001|     cover:
001|         (s/a above)
001|     title:
001|         (s/a above)
001|     library:
001|         (s/a above)
001| 
001| Commands:
001|     line            do_timeline
001|     tag             do_libby_tag
001|     jget            do_get_json
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, typename, makefilename
009| from dates import CST
010| import files
011| import htget
012| ####################################################################################################
013| BasePath = r'C:\CJS\prj\Python\ws\libby'
014| DataPath = BasePath
015| JsonPath = r'C:\CJS\www\_dat'
016| HtmlPath = r'C:\CJS\www\root\cjs'
017| 
018| 
019| UrlAllRetns  = 'https://share.libbyapp.com/data/08073891-3dd6-4bc1-8439-e29750edd658/libbytimeline-all-returns.json'
020| UrlAllLoans  = 'https://share.libbyapp.com/data/4d163f2e-f6de-4181-ab34-efa6d198bd09/libbytimeline-all-loans.json'
021| UrlAllAll    = 'https://share.libbyapp.com/data/54a8b374-2887-494c-8023-be3f6bdc1786/libbytimeline-all-all.json'
022| UrlTimeline  = 'https://share.libbyapp.com/data/fff28a75-2878-4213-a4f7-9ae592e380f4/libbytimeline-timeline.json'
023| 
024| UrlWant2Read = 'https://share.libbyapp.com/data/c7b65934-f8db-4ff4-ba72-2994ab236a4c/libbytag-want+to+read.json'
025| UrlQueue     = 'https://share.libbyapp.com/data/80d50410-1e44-4ec7-94d8-b3f3388cb62b/libbytag-queue.json'
026| UrlPossibles = 'https://share.libbyapp.com/data/f5b786a1-1cda-497b-95b1-8dbcc6c89e6a/libbytag-possibles.json'
027| UrlNotify    = 'https://share.libbyapp.com/data/9d835357-c60e-4ca2-a2b1-b5f856f744cf/libbytag-%F0%9F%94%94.json'
028| UrlTest      = 'https://sonnack.com/web/info.json'
029| 
030| Log = logger('Libby')
031| 
032| CMND = ''
033| ARGS = {
034|     #'url': UrlTimeline,
035|     #'fname': 'timeline.json',
036|     #'fpath': BasePath,
037|     'tag': 'eof',
038| }
039| 
040| ##------------------------------------------------------------------------------------------------##
041| TSDT = lambda ts:datetime.fromtimestamp((ts if ts else 0)/1000.0, tz=CST())
042| 
043| 
044| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
045| class libbyevent:
046|     '''Libby Timeline Event. (Always Borrowed now.)'''
047| 
048|     def __init__ (self, json_recd:dict):
049|         '''New instance.'''
050|         self.author    = json_recd.get('author', '')
051|         self.publisher = json_recd.get('publisher', '')
052|         self.isbn      = json_recd.get('isbn', '')
053|         self.ts        = json_recd.get('timestamp', '')
054|         self.activity  = json_recd.get('activity', '')
055|         self.note      = json_recd.get('details', '')
056| 
057|         # Title...
058|         title = json_recd.get('title', '<null>')
059|         self.title    = title.get('text', '???')
060|         self.titleId  = title.get('titleId', '###')
061|         self.titleUrl = title.get('url', '')
062| 
063|         # Cover...
064|         cover = json_recd['cover']
065|         self.cover = cover.get('url', '')
066|         self.color = cover.get('color', '#ffffff')
067| 
068|         # Library...
069|         lib = json_recd['library']
070|         self.library    = lib.get('text', '')
071|         self.libraryUrl = lib.get('url', '')
072| 
073|         # Convert timestamp...
074|         if self.ts:
075|             self.ts = TSDT(self.ts)
076|             self.dts = self.ts.strftime('%a %b %d, %Y %I:%M %p %Z')
077|         else:
078|             Log.warn(f'No timestamp!')
079|             self.dts = ''
080| 
081| 
082|     def __repr__ (self):
083|         '''Debug string.'''
084|         return f'<{typename(self)} @{id(self):012x}>'
085| 
086|     def __str__ (self):
087|         '''Print string.'''
088|         return f'{self.dts}: {self.title}; {self.author}; {self.ISBN}'
089| 
090|     @property
091|     def ISBN (self):
092|         '''ISBN property.'''
093|         if not self.isbn:
094|             return ''
095| 
096|         s0 = self.isbn[0:3]
097|         s1 = self.isbn[3:4]
098|         s2 = self.isbn[4:6]
099|         s3 = self.isbn[6:12]
100|         s4 = self.isbn[12:13]
101|         return f'{s0}-{s1}-{s2}-{s3}-{s4}'
102| 
103| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
104| class libbytimeline (list):
105|     '''Libby Timeline. Now just a bunch of borrowed events.'''
106| 
107|     def __init__ (self, filename):
108|         '''New instance.'''
109|         super().__init__()
110| 
111|         self.filename = filename
112|         self.load()
113| 
114|     def __repr__ (self):
115|         '''Debug string.'''
116|         return f'<{typename(self)} @{id(self):012x}>'
117| 
118|     def __str__ (self):
119|         '''Print string.'''
120|         return f'{self.filename} [{len(self)} records]'
121| 
122|     def load (self):
123|         '''Load JSON timeline file.'''
124|         fn = self.filename
125|         Log.info(f'open: {fn}')
126| 
127|         # Load JSON file...
128|         jdat = files.jsonfile(fn)
129|         jdat.load()
130|         Log.info(f'loaded: {path.basename(fn)} (records: {len(jdat)})')
131|         Log.info()
132| 
133|         for ix,rcd in enumerate(jdat['timeline'], start=1):
134|             Log.trace(f'{ix:3d}: {rcd["title"]["text"]}')
135|             self.append(libbyevent(rcd))
136|         Log.trace()
137| 
138| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
139| class libbytag (list):
140|     '''Libby Tag. (Just different enough to be a pain.)'''
141| 
142|     def __init__ (self, filename):
143|         '''New instance.'''
144|         super().__init__()
145| 
146|         self.filename = filename
147|         self.load()
148| 
149|     def __repr__ (self):
150|         '''Debug string.'''
151|         return f'<{typename(self)} @{id(self):012x}>'
152| 
153|     def __str__ (self):
154|         '''Print string.'''
155|         return f'{self.filename} [{len(self)} records]'
156| 
157|     def load (self):
158|         '''Load JSON tag file.'''
159|         fn = self.filename
160|         Log.info(f'open: {fn}')
161| 
162|         # Load JSON file...
163|         jdat = files.jsonfile(fn)
164|         jdat.load()
165|         Log.info(f'loaded: {path.basename(fn)} (records: {len(jdat)})')
166|         Log.info()
167| 
168|         tag = jdat['tag']
169|         self.tagname = tag.get('name', '<none>')
170|         self.tagdesc = tag.get('description', '')
171|         self.tagtime = tag.get('timestamp', '')
172|         self.taguuid = tag.get('UUID', '')
173| 
174|         for ix,rcd in enumerate(jdat['titles'], start=1):
175|             Log.trace(f'{ix:3d}: {rcd["title"]["text"]}')
176|             self.append(libbyevent(rcd))
177|         Log.trace()
178| 
179| 
180| ##================================================================================================##
181| def do_timeline (**kwargs):
182|     '''Generate HTML from Libby Timeline JSON.'''
183|     fpath = KWARG('fpath', BasePath, str, kwargs)
184|     fname = KWARG('fname', 'timeline.json', str, kwargs)
185|     Log.info(f'libby-timeline:: {list(kwargs.keys())}')
186|     Log.info(f'fpath="{fpath}"')
187|     Log.info(f'fname="{fname}"')
188|     Log.info()
189|     filename = makefilename(fpath, fname)
190| 
191|     timeline = libbytimeline(filename)
192|     Log.info(timeline)
193|     Log.info()
194| 
195|     opath,oname = path.split(filename)
196|     name,ext = path.splitext(oname)
197|     outfilename = makefilename(opath, f'{name}.list')
198|     Log.debug(f'{outfilename=}')
199|     Log.debug()
200| 
201|     with open(outfilename, mode='w', encoding='utf-8') as fout:
202| 
203|         for ix,book in enumerate(timeline, start=1):
204|             txt = f'{book.ts:%Y-%m-%d %H:%M} {book.title}; {book.author}; {book.ISBN}'
205|             print(txt, file=fout)
206|             Log.debug(f'{ix:3d}: {txt}')
207| 
208|         print(file=fout)
209|         Log.debug()
210| 
211|     Log.info(f'wrote: {outfilename}')
212|     Log.info()
213|     return 'Done'
214| 
215| ##================================================================================================##
216| def do_libby_tag (**kwargs):
217|     '''Generate HTML from Libby Tag JSON.'''
218|     fpath = KWARG('fpath', BasePath, str, kwargs)
219|     fname = KWARG('fname', 'queue.json', str, kwargs)
220|     Log.info(f'libby-tag:: {list(kwargs.keys())}')
221|     Log.info(f'fpath="{fpath}"')
222|     Log.info(f'fname="{fname}"')
223|     Log.info()
224|     filename = makefilename(fpath, fname)
225| 
226|     queue = libbytag(filename)
227|     Log.info(queue)
228|     Log.info()
229| 
230|     opath,oname = path.split(filename)
231|     name,ext = path.splitext(oname)
232|     outfilename = makefilename(opath, f'{name}.list')
233|     Log.debug(f'{outfilename=}')
234|     Log.debug()
235| 
236|     with open(outfilename, mode='w', encoding='utf-8') as fout:
237| 
238|         for book in queue:
239|             txt = f'{book.title}; {book.author}; {book.ISBN}'
240|             print(txt, file=fout)
241|             Log.info(txt)
242| 
243|         print(file=fout)
244|         Log.info()
245| 
246|     Log.info(f'wrote: {outfilename}')
247|     Log.info()
248|     return 'Done'
249| 
250| ##================================================================================================##
251| def do_get_json (**kwargs):
252|     '''CMND: Get an online JSON file and save it.'''
253|     fpath = KWARG('fpath', BasePath, str, kwargs)
254|     fname = KWARG('fname', 'timeline.json', str, kwargs)
255|     url = KWARG('url', UrlAllLoans, str, kwargs)
256|     Log.info(f'get-json:: {list(kwargs.keys())}')
257|     Log.info(f'fpath="{fpath}"')
258|     Log.info(f'fname="{fname}"')
259|     Log.info()
260|     filename = makefilename(fpath, fname)
261| 
262|     data = htget.json_get(url)
263|     Log.info(data.link)
264|     Log.info(data.status)
265|     Log.info()
266| 
267|     Log.info('Response Headers:')
268|     for name,value in data.headers:
269|         Log.info(f'{name}: "{value}"')
270|     Log.info()
271| 
272|     version = data['version']
273|     Log.info(f'JSON version: {version}')
274|     Log.info()
275| 
276|     data.save(filename)
277|     Log.info(f'wrote: {filename}')
278| 
279|     Log.info()
280|     return 'Done'
281| 
282| ##================================================================================================##
283| def do_test (**kwargs):
284|     '''CMND: Do a Test.'''
285|     fpath = KWARG('fpath', BasePath, str, kwargs)
286|     fname = KWARG('fname', 'test.out', str, kwargs)
287|     url = KWARG('url', UrlAllLoans, str, kwargs)
288|     Log.info(f'test:: {list(kwargs.keys())}')
289|     Log.info(f'fpath="{fpath}"')
290|     Log.info(f'fname="{fname}"')
291|     Log.info()
292|     filename = makefilename(fpath, fname)
293|     Log.info()
294|     return 'Done'
295| ####################################################################################################
296| def dispatch (cmd, **kwargs):
297|     """Dispatch to a module function based on CMD."""
298|     Log.info(f'CMD: {cmd}')
299|     for kw in kwargs:
300|         Log.debug(f'argument[{kw}]: {kwargs[kw]}')
301|     Log.info()
302|     if cmd == 'line': return do_timeline(**kwargs)
303|     if cmd == 'tag': return do_libby_tag(**kwargs)
304|     if cmd == 'jget': return do_get_json(**kwargs)
305|     if cmd == 'test': return do_test(**kwargs)
306|     return 'Nothing to do!'
307| ####################################################################################################
308| if __name__ == '__main__':
309|     print(f'autorun: {argv[0]}')
310|     Log.start(path.join(BasePath,'libby.log'))
311|     Log.level(trace())
312|     Log.info(argv[0])
313|     Log.info()
314|     cmd = argv[1] if 1 < len(argv) else CMND
315|     kwargs = ARGS
316|     for a in argv[2:]:
317|         nv = a.split('=', 1)
318|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
319|         Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
320|     try:
321|         print(f'CMD: {cmd}')
322|         print()
323|         kwargs['log'] = Log
324|         obj = dispatch(cmd, **kwargs)
325|         print()
326|         print(obj)
327|         Log.info()
328|         Log.info(obj)
329|     except:
330|         etype, evalue, tb = exc_info()
331|         ts = extract_tb(tb)
332|         Log.error()
333|         Log.error(f'{etype.__name__}: {str(evalue)}')
334|         Log.error()
335|         for t in ts[-5:]:
336|             Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
337|             Log.error(f' {t[3]}')
338|             Log.error()
339|         raise
340|     finally:
341|         Log.end()
342| ####################################################################################################
343| '''eof'''
344|