tasks.html


001| '''Substack Tasks.
001| 
001| Classes:
001|     dbSubscribers (dbTable)                 - Subscribers database.
001|     charfilter (dict)                       - Character Filter for email addresses.
001| 
001| Data:
001|     MarkerChars                             - List of chars we allow in email addresses.
001| 
001| Commands:
001|     c.subs      do_subscribers_chart        - Subscribers chart.
001|     c.fols      do_followers_chart          - Followers chart.
001|     p.subs      do_subscriptions            - All subscribers HTML page.
001|     scansubs    do_subscription_scan        - Scan and report on subscription files.
001| 
001|     db.make     do_dbsubs_make              - Create the Subscriptions database from file(s).
001|     db.list     do_dbsubs_list              - List all records in Subscriptions database.
001| 
001|     test        do_test                     - Test.
001| '''

002| ####################################################################################################
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| from datetime import date, datetime, timedelta
007| import matplotlib.pyplot as plt
008| import matplotlib.ticker as mlticks
009| import matplotlib.dates as mldates
010| from logger import logger,info,debug,trace, LogFilenameTimestamp
011| from goodies import KWARG, typename, plural
012| from files import linefile, csvfile, tabfile
013| from dbsql import dbTable
014| from mlchart import mlchart
015| from webpage import WebPage
016| ####################################################################################################
017| BlogBase = r'C:\CJS\prj\Python\blog'
018| BasePath = path.join(BlogBase, 'substack')
019| DataPath = path.join(BasePath, 'dat')
020| HtmlBase = r'C:\CJS\www\root\cjs\blog'
021| Log = logger('substack')
022| 
023| CMND = ''
024| ARGS = {
025|     #'fname': 'tasks.out',
026|     #'fpath': BasePath,
027|     #'dname': 'posts.tab',
028|     #'dpath': DataPath,
029| }
030| 
031| ##------------------------------------------------------------------------------------------------##
032| ChartSubsFileName    = 'data_subscribers_2026-03-31.csv'
033| ChartFollowsFileName = 'data_followers_2026-03-31.csv'
034| 
035| SubscriptionFileNames = [
036|     'subs_2024-08-01.csv',
037|     'subs_2024-09-10.csv',
038|     'subs_2024-10-01.csv',
039|     'subs_2024-12-03.csv',
040|     'subs_2024-12-28.csv',
041|     'subs_2025-01-20.csv',
042|     'subs_2025-02-28.csv',
043|     'subs_2025-03-28.csv',
044|     'subs_2025-04-24.csv',
045|     'subs_2025-05-30.csv',
046|     'subs_2025-06-24.csv',
047|     'subs_2025-07-30.csv',
048|     'subs_2025-08-27.csv',
049|     'subs_2025-09-27.csv',
050|     'subs_2025-10-27.csv',
051|     'subs_2025-12-01.csv',
052|     'subs_2025-12-30.csv',
053|     'subs_2026-01-31.csv',
054|     'subs_2026-03-31.csv',
055| ]
056| 
057| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
058| class charfilter (dict):
059|     '''Character Filter class for str.translate.'''
060| 
061|     def __getitem__ (self, key):
062|         if 0 < key < 256:
063|             return key
064|         return super().__getitem__(key)
065| 
066|     def __missing__ (self, key):
067|         return '?'
068| 
069| ##------------------------------------------------------------------------------------------------##
070| MarkerChars = '!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
071| 
072| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
073| class dbSubscribers (dbTable):
074|     '''Subscribers Database class.'''
075|     dbName = 'subscribers.sqlite'
076|     dataPath = DataPath
077|     tabName = 'subscribers'
078|     tabCols = ['"Email" TEXT NOT NULL UNIQUE'
079|               ,'"Name" TEXT DEFAULT NULL'
080|               ,'"Subscription type" TEXT NOT NULL'
081|               ,'"Activity" INTEGER NOT NULL'
082|               ,'"Subscription date" TEXT NOT NULL'
083|               ,'"Revenue" TEXT NOT NULL'
084|               ,'"Comments" INTEGER NOT NULL'
085|               ,'"Comments (7 days)" INTEGER NOT NULL'
086|               ,'"Comments (30 days)" INTEGER NOT NULL'
087|               ,'"Shares" INTEGER NOT NULL'
088|               ,'"Shares (7 days)" INTEGER NOT NULL'
089|               ,'"Shares (30 days)" INTEGER NOT NULL'
090|               ,'"Subscriber country" TEXT DEFAULT NULL'
091|               ,'"Email receives (last 6 mons)" INTEGER NOT NULL'
092|               ,'"Email drops (last 6 mons)" INTEGER NOT NULL'
093|               ,'"Emails opened (last 6 mons)" INTEGER NOT NULL'
094|               ,'"Email opens (last 6 mons)" INTEGER NOT NULL'
095|               ,'"Email opens (last 7 days)" INTEGER NOT NULL'
096|               ,'"Email opens (last 30 days)" INTEGER NOT NULL'
097|               ,'"Email last opened at" TEXT DEFAULT NULL'
098|               ,'"Link clicks" INTEGER NOT NULL'
099|               ,'"Last clicked at" TEXT DEFAULT NULL'
100|               ,'"Unique emails seen (last 6 mons)" INTEGER NOT NULL'
101|               ,'"Unique emails seen (last 7 days)" INTEGER NOT NULL'
102|               ,'"Unique emails seen (last 30 days)" INTEGER NOT NULL'
103|               ,'"Post views (6 mons)" INTEGER NOT NULL'
104|               ,'"Post views (7 days)" INTEGER NOT NULL'
105|               ,'"Post views (30 days)" INTEGER NOT NULL'
106|               ,'"Unique posts seen" INTEGER NOT NULL'
107|               ,'"Unique posts seen (7 days)" INTEGER NOT NULL'
108|               ,'"Unique posts seen (30 days)" INTEGER NOT NULL'
109|               ,'"Subscriptions gifted" INTEGER NOT NULL'
110|               ,'"Expires at" TEXT DEFAULT NULL'
111|               ,'"Subscription source (free)" TEXT DEFAULT NULL'
112|               ,'"Subscription source (paid)" TEXT DEFAULT NULL'
113|               ,'"Days active (30 days)" INTEGER NOT NULL'
114|               ,'"First payment at" TEXT DEFAULT NULL'
115|               ,'"Paid upgrade date" TEXT DEFAULT NULL'
116|               ,'"Cancel date" TEXT DEFAULT NULL'
117|               ,'"Receiving emails for" TEXT DEFAULT NULL'
118|               ,'"Is Bestseller" TEXT DEFAULT NULL'
119|               ,'"Stripe plan nickname" TEXT DEFAULT NULL'
120|               ]
121|     tabData = []
122| 
123|     def __init__(self):
124|         super().__init__(path.join(self.dataPath,self.dbName), self.tabName, self.tabCols)
125| 
126|     def create_table (self):
127|         super().create_table('Create Subscribers Table')
128|         self.load_records()
129| 
130|     def destroy_table (self):
131|         super().destroy_table('Destroy Subscribers Table')
132| 
133|     def load_records (self):
134|         Log.info('Load Records')
135|         # Load subscription files...
136|         filelist = [csvfile(path.join(self.dataPath,fn),log=Log) for fn in SubscriptionFileNames]
137|         subs = {}
138|         # For each file in the list...
139|         for fin in filelist:
140|             fin.load()
141|             # For each record in the file...
142|             for rcd in fin:
143|                 email = rcd[0]
144|                 subs[email] = rcd+['']
145| 
146|         self.tabData = list(subs.values())
147|         self.db_insert_many(self.tabData)
148| 
149|     def list_records (self, fname='subscribers.list', fpath=dataPath):
150|         self.Log.debug('db[%s] ListToFile' % self.name)
151|         sql = 'SELECT * FROM "%s" ORDER BY name,email' % self.name
152|         fn = path.join(fpath, fname) if fpath else fname
153|         fp = open(fn, mode='w', encoding='utf-8')
154|         try:
155|             rs = self.db_query(sql)
156|             if not rs: Log.warn('No data!'); return []
157|             for r in rs:
158|                 print(r, file=fp)
159|             print(file=fp)
160|             self.Log.info('wrote: %s' % fn)
161|         except:
162|             raise
163|         finally:
164|             fp.close()
165| 
166| 
167| ##================================================================================================##
168| def do_subscribers_chart (**kwargs):
169|     """CMND: Create a chart of subscribers."""
170|     fpath = KWARG('fpath', HtmlBase, str, kwargs)
171|     fname = KWARG('fname', 'subscribers.png', str, kwargs)
172|     dpath = KWARG('dpath', DataPath, str, kwargs)
173|     dname = KWARG('dname', ChartSubsFileName, str, kwargs)
174|     Log.info('chart-subscribers:: %s' % str(list(kwargs.keys())))
175|     Log.debug(f'{fpath=}')
176|     Log.debug(f'{fname=}')
177|     Log.debug(f'{dpath=}')
178|     Log.debug(f'{dname=}')
179|     Log.info()
180| 
181|     class subs_chart (mlchart):
182|         '''Subscribers Chart class.'''
183| 
184|         def __init__ (self, data):
185|             '''New chart instance.'''
186|             super().__init__((8.8, 5.0))
187|             self.data = data
188|             self.fpath = fpath
189|             self.fname = fname
190|             self.margins = dict(left=0.08, right=0.99, bottom=0.18, top=0.92)
191|             self.title = f'Logos con Carne Subscribers ({(self.data[-1][1])})'
192|             self.x_title = 'Date'
193|             self.y_title = 'Subscribers'
194|             self.x_limit = (self.data[0][0]-timedelta(1), self.data[-1][0]+timedelta(5))
195|             self.y_limit = (0, +300)
196|             self.x_grids = (None, None)
197|             self.y_grids = (50, 10)
198|             self.x_tickf = '%b %d'
199|             self.y_tickf = '%d'
200|             self.x_tickr = True
201|             self.x_dates = False
202|             self.title_kw['fontsize'] = 18
203|             self.title_kw['fontweight'] = 'bold'
204|             self.x_title_kw['fontsize'] = 14
205|             self.y_title_kw['fontsize'] = 14
206| 
207|         def make_x_axis_spcl (self):
208|             self.ax.xaxis_date()
209|             self.ax.xaxis.set_major_locator(mldates.MonthLocator())
210|             self.ax.xaxis.set_major_formatter(mldates.DateFormatter(self.x_tickf))
211|             self.ax.xaxis.set_minor_locator(mldates.DayLocator(bymonthday=[7,14,21,28]))
212|             self.ax.xaxis.set_minor_formatter(mlticks.NullFormatter())
213| 
214|         def plotter (self):
215|             """Plot something!"""
216|             xs = [t[0] for t in self.data]
217|             ys = [t[1] for t in self.data]
218|             self.ax.plot(xs,ys, color='#ff5f1f', lw=3.0, ms=0, alpha=0.85, zorder=11)
219| 
220|     datefunc = lambda s: datetime.strptime(s,'%Y/%m/%d').date()
221| 
222|     Log.debug('Load file data.')
223|     fn = path.join(dpath,dname) if dpath else dname
224|     fo = csvfile(fn)
225|     fo.load()
226|     data = [(datefunc(t[0]),int(t[1])) for t in fo]
227| 
228|     Log.debug('Make chart.')
229|     cht = subs_chart(data)
230|     cht.make()
231|     Log.info(f'wrote: {path.join(cht.fpath,cht.fname)}')
232| 
233|     Log.info()
234|     return 'Done'
235| 
236| ##================================================================================================##
237| def do_followers_chart (**kwargs):
238|     """CMND: Create a chart of followers."""
239|     fpath = KWARG('fpath', HtmlBase, str, kwargs)
240|     fname = KWARG('fname', 'followers.png', str, kwargs)
241|     dpath = KWARG('dpath', DataPath, str, kwargs)
242|     dname = KWARG('dname', ChartFollowsFileName, str, kwargs)
243|     Log.info('chart-followers:: %s' % str(list(kwargs.keys())))
244|     Log.debug(f'{fpath=}')
245|     Log.debug(f'{fname=}')
246|     Log.debug(f'{dpath=}')
247|     Log.debug(f'{dname=}')
248|     Log.info()
249| 
250|     class followers_chart (mlchart):
251|         '''Followers Chart class.'''
252| 
253|         def __init__ (self, data):
254|             '''New chart instance.'''
255|             super().__init__((8.8, 5.0))
256|             self.data = data
257|             self.fpath = fpath
258|             self.fname = fname
259|             self.margins = dict(left=0.08, right=0.99, bottom=0.18, top=0.92)
260|             self.title = f'Logos con Carne Followers ({(self.data[-1][1])})'
261|             self.x_title = 'Date'
262|             self.y_title = 'Followers'
263|             self.x_limit = (self.data[0][0]-timedelta(1), self.data[-1][0]+timedelta(5))
264|             self.y_limit = (0, +1000)
265|             self.x_grids = (None, None)
266|             self.y_grids = (100, 25)
267|             self.x_tickf = '%b %d'
268|             self.y_tickf = '%d'
269|             self.x_tickr = True
270|             self.x_dates = False
271|             self.title_kw['fontsize'] = 18
272|             self.title_kw['fontweight'] = 'bold'
273|             self.x_title_kw['fontsize'] = 14
274|             self.y_title_kw['fontsize'] = 14
275| 
276|         def make_x_axis_spcl (self):
277|             self.ax.xaxis_date()
278|             self.ax.xaxis.set_major_locator(mldates.MonthLocator())
279|             self.ax.xaxis.set_major_formatter(mldates.DateFormatter(self.x_tickf))
280|             self.ax.xaxis.set_minor_locator(mldates.DayLocator(bymonthday=[7,14,21,28]))
281|             self.ax.xaxis.set_minor_formatter(mlticks.NullFormatter())
282| 
283|         def plotter (self):
284|             """Plot something!"""
285|             xs = [t[0] for t in self.data]
286|             ys = [t[1] for t in self.data]
287|             self.ax.plot(xs,ys, color='#1f5fff', lw=3.0, ms=0, alpha=0.85, zorder=11)
288| 
289|     datefunc = lambda s: datetime.strptime(s,'%Y/%m/%d').date()
290| 
291|     Log.debug('Load file data.')
292|     fn = path.join(dpath,dname) if dpath else dname
293|     fo = csvfile(fn)
294|     fo.load()
295|     data = [(datefunc(t[0]),int(t[1])) for t in fo]
296| 
297|     Log.debug('Make chart.')
298|     cht = followers_chart(data)
299|     cht.make()
300|     Log.info(f'wrote: {path.join(cht.fpath,cht.fname)}')
301| 
302|     Log.info()
303|     return 'Done'
304| 
305| ##================================================================================================##
306| def do_subscriptions (**kwargs):
307|     """CMND: Create an HTML page of all subscribers active and retired."""
308|     fpath = KWARG('fpath', HtmlBase, str, kwargs)
309|     fname = KWARG('fname', 'stacksubs.html', str, kwargs)
310|     dpath = KWARG('dpath', DataPath, str, kwargs)
311|     dname = KWARG('dname', 'subs_%s.csv', str, kwargs)
312|     Log.info('subscriptions:: %s' % str(list(kwargs.keys())))
313|     Log.debug(f'{fpath=}')
314|     Log.debug(f'{fname=}')
315|     Log.debug(f'{dpath=}')
316|     Log.debug(f'{dname=}')
317|     Log.info()
318|     props = {'h1':'Substack', 'h2':'Subscriptions', 'h3':'', 'css':['http://localhost/basic.css']}
319|     css0 = 'font-family:monospace; font-size:10pt;'
320|     css1 = 'font-size:11pt; font-weight:bold;'
321|     css2 = 'font-size:11pt;'
322|     css3 = 'font-family:monospace; font-size:13pt; font-weight:bold;'
323| 
324|     # Create a list of csvfile objects (subscription files)...
325|     filelist = [csvfile(path.join(dpath,fn),log=Log) for fn in SubscriptionFileNames]
326| 
327|     # Load subscription files...
328|     for fin in filelist:
329|         fin.load()
330|     Log.info()
331| 
332|     # For each file...
333|     CF = charfilter()
334|     subs = {}
335|     for fx,fin in enumerate(filelist, start=1):
336|         Log.trace(fin)
337|         Log.trace(fin.hdrs)
338| 
339|         # Get column indexes of the columns we'll use...
340|         cx_email = fin.hdrs.index('Email')
341|         cx_name  = fin.hdrs.index('Name')
342|         cx_date  = fin.hdrs.index('Start date') if 'Start date' in fin.hdrs else fin.hdrs.index('Subscription date')
343| 
344|         # For each record in the file...
345|         for rcd in fin:
346|             email = rcd[cx_email]
347|             name  = rcd[cx_name].translate(CF)
348|             added = datetime.fromisoformat(rcd[cx_date][0:-1])
349| 
350|             if email not in subs:
351|                 Log.trace(f'add: {name} ({email})')
352|                 subs[email] = [name, email, [fx], added, 1]
353|             else:
354|                 Log.trace(f'found: {name} ({email})')
355|                 subs[email][2].append(fx)
356|                 subs[email][4] += 1
357| 
358|         Log.trace()
359|     Log.trace()
360| 
361|     # Find current and retired subscribers...
362|     m = len(filelist)
363|     current = [rcd for rcd in sorted(subs.values()) if rcd[2][-1]==m]
364|     retired = [rcd for rcd in sorted(subs.values()) if rcd[2][-1]<m]
365|     Log.info(f'Subs: {len(subs)}, Active: {len(current)}, Retired: {len(retired)}')
366|     Log.info()
367| 
368|     Log.info('Retired Subscribers:')
369|     for rcd in retired:
370|         Log.info(f'[added {rcd[3]:%Y-%m-%d}] {rcd[0]} <{rcd[1]}>')
371|     Log.info()
372| 
373|     # Report...
374|     pag = WebPage('Subscriptions', **props)
375|     pag.add(f'<h3>Substack Subscriptions ({len(current)} active, {len(retired)} retired)</h3>')
376|     pag.add()
377|     pag.add('<table style="font-size:13px;border-spacing:9px 1px;padding:0;border:0;margin:13px;">')
378|     pag.add('<tbody>')
379| 
380|     for ix,rcd in enumerate(sorted(subs.values()),start=1):
381|         name = rcd[0]
382|         email = rcd[1]
383|         marks = rcd[2]
384|         flags = [MarkerChars[ix] if ix in marks else '.' for ix in range(1,len(filelist)+1)]
385|         clr = 'color:red;' if marks[-1] < len(filelist) else ''
386|         pag.add('<tr>')
387|         pag.add(f'<td style="{css0}">{ix}</td>')
388|         pag.add(f'<td style="{css1}{clr}">{name}</td>')
389|         pag.add(f'<td style="{css2}{clr}">{email}</td>')
390|         pag.add(f'<td style="{css3}{clr}">{"".join(flags)}</td>')
391|         pag.add('</tr>')
392| 
393|     pag.add()
394|     pag.add('</tbody>')
395|     pag.add('</table>')
396| 
397|     pag.add('<div style="font-family:monospace; margin-top:20px;">')
398|     for fx,fin in enumerate(filelist, start=1):
399|         pag.add(f'<div>[{MarkerChars[fx]}] {fin.name}</div>')
400|     pag.add('</div>')
401|     pag.add('')
402| 
403|     fn = path.join(fpath, fname) if fpath else fname
404|     pag.save(fn, log=Log)
405| 
406|     Log.info()
407|     return 'Done'
408| 
409| ##================================================================================================##
410| def do_subscription_scan (**kwargs):
411|     """CMND: Scan the subcription files and report."""
412|     fpath = KWARG('fpath', BasePath, str, kwargs)
413|     fname = KWARG('fname', 'scans_subs.out', str, kwargs)
414|     dpath = KWARG('dpath', DataPath, str, kwargs)
415|     dname = KWARG('dname', 'subs_%s.csv', str, kwargs)
416|     Log.info('subscription-scan:: %s' % str(list(kwargs.keys())))
417|     Log.debug(f'{fpath=}')
418|     Log.debug(f'{fname=}')
419|     Log.debug(f'{dpath=}')
420|     Log.debug(f'{dname=}')
421|     Log.info()
422| 
423|     # Create a list of csvfile objects (subscription files)...
424|     filelist = [csvfile(path.join(dpath,fn)) for fn in SubscriptionFileNames]
425| 
426|     # Load subscription files...
427|     for fin in filelist:
428|         fin.load()
429|     Log.info()
430| 
431|     # For each file...
432|     CF = charfilter()
433|     subs = {}
434|     for fx,fin in enumerate(filelist, start=1):
435|         Log.trace(fin)
436|         Log.trace(fin.hdrs)
437| 
438|         # Get column indexes of the columns we'll use...
439|         cx_email = fin.hdrs.index('Email')
440|         cx_name  = fin.hdrs.index('Name')
441|         cx_date  = fin.hdrs.index('Start date') if 'Start date' in fin.hdrs else fin.hdrs.index('Subscription date')
442| 
443|         # For each record in the file...
444|         for rcd in fin:
445|             email = rcd[cx_email]
446|             name  = rcd[cx_name].translate(CF)
447|             added = datetime.fromisoformat(rcd[cx_date][0:-1])
448| 
449|             if email not in subs:
450|                 Log.trace(f'add: {name} ({email})')
451|                 subs[email] = [name, email, [], added, 0]
452|             subs[email][2].append(fx)
453| 
454|     m = len(filelist)
455|     current = [rcd for rcd in sorted(subs.values()) if rcd[2][-1]==m]
456|     retired = [rcd for rcd in sorted(subs.values()) if rcd[2][-1]<m]
457|     Log.info(f'Subs: {len(subs)}, Active: {len(current)}, Retired: {len(retired)}')
458|     Log.info()
459| 
460|     for fx,fin in enumerate(filelist, start=1):
461|         fin.newsubs = []
462|         fin.retired = []
463| 
464|         for rcd in sorted(subs.values(), key=lambda v:(v[0],v[1])):
465|             if (rcd[4]==0) and (fx in rcd[2]):
466|                 rcd[4] = 1
467|                 fin.newsubs.append(rcd)
468|                 continue
469|             if (rcd[4]==1) and (fx not in rcd[2]) and (rcd[3] < fin.created):
470|                 rcd[4] = 2
471|                 fin.retired.append(rcd)
472|                 continue
473| 
474|     fn = path.join(fpath,fname) if fpath else fname
475|     fo = linefile(fn)
476| 
477|     for fx,fin in enumerate(filelist, start=1):
478|         s = f'{fin.filename}'
479|         Log.debug(s)
480|         fo.add(s)
481| 
482|         for rcd in fin.newsubs:
483|             s = f'+ [{rcd[3]:%Y-%m-%d}] {rcd[0]} <{rcd[1]}>'
484|             Log.debug(s)
485|             fo.add(s)
486| 
487|         for rcd in fin.retired:
488|             s = f'- [{rcd[3]:%Y-%m-%d}] {rcd[0]} <{rcd[1]}>'
489|             Log.debug(s)
490|             fo.add(s)
491| 
492|         Log.debug()
493|         fo.add()
494|     Log.debug()
495|     fo.add()
496| 
497|     fo.save()
498| 
499|     Log.info()
500|     return 'Done'
501| 
502| ##================================================================================================##
503| def do_dbsubs_make (**kwargs):
504|     """CMND: Create the Subscriptions database from file(s)."""
505|     fpath = KWARG('fpath', BasePath, str, kwargs)
506|     fname = KWARG('fname', 'subscriptions.out', str, kwargs)
507|     dpath = KWARG('dpath', DataPath, str, kwargs)
508|     dname = KWARG('dname', 'posts.tab', str, kwargs)
509|     Log.info('dbsubs-make:: %s' % str(list(kwargs.keys())))
510|     Log.debug(f'{fpath=}')
511|     Log.debug(f'{fname=}')
512|     Log.debug(f'{dpath=}')
513|     Log.debug(f'{dname=}')
514|     Log.info()
515|     db = dbSubscribers()
516|     db.create_table()
517|     Log.info()
518|     return 'Done'
519| 
520| ##================================================================================================##
521| def do_dbsubs_list (**kwargs):
522|     """CMND: List all records in Subscriptions database."""
523|     fpath = KWARG('fpath', BasePath, str, kwargs)
524|     fname = KWARG('fname', 'subscriptions.list', str, kwargs)
525|     dpath = KWARG('dpath', DataPath, str, kwargs)
526|     dname = KWARG('dname', 'posts.tab', str, kwargs)
527|     Log.info('dbsubs-list:: %s' % str(list(kwargs.keys())))
528|     Log.debug(f'{fpath=}')
529|     Log.debug(f'{fname=}')
530|     Log.debug(f'{dpath=}')
531|     Log.debug(f'{dname=}')
532|     Log.info()
533|     db = dbSubscribers()
534|     db.list_records()
535|     Log.info()
536|     return 'Done'
537| 
538| ##================================================================================================##
539| def do_test (**kwargs):
540|     """CMND: Do a test."""
541|     fpath = KWARG('fpath', BasePath, str, kwargs)
542|     fname = KWARG('fname', 'All-Posts.png', str, kwargs)
543|     dpath = KWARG('dpath', DataPath, str, kwargs)
544|     dname = KWARG('dname', 'posts.tab', str, kwargs)
545|     Log.info('test:: %s' % str(list(kwargs.keys())))
546|     Log.debug(f'{fpath=}')
547|     Log.debug(f'{fname=}')
548|     Log.debug(f'{dpath=}')
549|     Log.debug(f'{dname=}')
550|     Log.info()
551|     Log.info()
552|     Log.info()
553|     return 'Done'
554| ####################################################################################################
555| def dispatch (cmd, **kwargs):
556|     """Dispatch to a module function based on CMD."""
557|     Log.info(f'CMD: {cmd}')
558|     for kw in kwargs:
559|         Log.debug(f'argument[{kw}]: {kwargs[kw]}')
560|     Log.info()
561|     if cmd == 'c.subs':     return do_subscribers_chart(**kwargs)
562|     if cmd == 'c.fols':     return do_followers_chart(**kwargs)
563|     if cmd == 'p.subs':     return do_subscriptions(**kwargs)
564|     if cmd == 'scansubs':   return do_subscription_scan(**kwargs)
565|     if cmd == 'db.make':    return do_dbsubs_make(**kwargs)
566|     if cmd == 'db.list':    return do_dbsubs_list(**kwargs)
567|     if cmd == 'test':       return do_test(**kwargs)
568|     return 'Nothing to do!'
569| ####################################################################################################
570| if __name__ == '__main__':
571|     print('autorun: %s' % argv[0])
572|     Log.start(path.join(BasePath,'tasks.log'))
573|     Log.level(trace())
574|     Log.info(argv[0])
575|     Log.info()
576|     cmd = argv[1] if 1 < len(argv) else CMND
577|     kwargs = ARGS
578|     for a in argv[2:]:
579|         nv = a.split('=', 1)
580|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
581|         Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
582|     try:
583|         print(f'CMD: {cmd}')
584|         print()
585|         obj = dispatch(cmd, **kwargs)
586|         print()
587|         print(obj)
588|         Log.info()
589|         Log.info(obj)
590|     except:
591|         etype, evalue, tb = exc_info()
592|         ts = extract_tb(tb)
593|         Log.error()
594|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
595|         Log.error()
596|         for t in ts[-5:]:
597|             Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
598|             Log.error(' %s' % t[3])
599|             Log.error()
600|         raise
601|     finally:
602|         Log.end()
603| ####################################################################################################
604| '''eof'''
605|