wordpress.html
001| '''WordPress Blog classes.
001|
001| Classes:
001| XmlWordpress (XmlHandlerMain)
001| XmlHandlerPageDB (XmlHandlerMain)
001| XmlHandlerCategoryIndex (XmlHandlerPageDB)
001| XmlHandlerPostsByTag (XmlHandlerPageDB)
001| XmlHandlerPostsByMonth (XmlHandlerPageDB)
001| XmlHandlerPostIdList (XmlHandlerPageDB)
001| XmlHandlerPgDbTest (XmlHandlerPageDB)
001|
001| WordPressItem (object) Blog XML Record
001| RealCategoryData (object) Categories from Blog Admin Page
001| BlogPageHitsData (object) PageHits/Year
001| SelectedPosts (object) Selected Posts Dataset
001|
001| BlogPostWebPage (WebPage)
001| HtmlPageCategoryList (WebPage)
001| HtmlPageCategoryIndex (WebPage)
001| HtmlPagePostsByTag (WebPage)
001| HtmlPagePostsByMonth (WebPage)
001| BlogStatsPage (WebPage) Blog Stats
001| BlogPageHitsPage (WebPage) PageHits/Year
001|
001| dbBaseTable (dbTable)
001| dbPostsTable (dbBaseTable)
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| import xml.sax.handler as saxhandler
008| import xml.sax.xmlreader as saxreader
009| from xml.sax.saxutils import unescape
010| from urllib.parse import quote_plus, unquote_plus
011| from dates import UTC, CST
012| from files import EOL, tabfile,csvfile
013| from goodies import safediv, add_commas
014| from dbsql import dbTable
015| from xml_sax import XmlHandlerMain, parse_xml_file
016| from webpage import KWARG, WebPage
017| from logger import logger
018|
019| Log = logger('WP')
020|
021| HtmlH1 ='Logos Con Carne'
022| HtmlH2 = 'Blog Stats'
023| CssFiles = ['/basic.css', '/cjs/blog/wordpress.css', 'local.css', 'stats.css']
024|
025|
026| class WordPressItem (object):
027| '''Blog XML Record class.'''
028| FieldNames = [
029| ('recid' , 'rec_nmbr' , 'wp:post_id' ),
030| ('rectype' , 'rec_type' , 'wp:post_type' ),
031| ('date' , 'rec_date' , 'wp:post_date_gmt' ),
032| ('status' , 'rec_status' , 'wp:status' ),
033| ('name' , 'name' , 'wp:post_name' ),
034| ('title' , 'title' , 'title' ),
035| ('category' , 'category' , 'category' ),
036| ('url' , 'url' , 'guid' ),
037| ('link' , 'link' , 'link' ),
038| ('content' , 'content' , 'content:encoded' )]
039|
040| def __init__ (self):
041| self.objnames = [t[0] for t in WordPressItem.FieldNames]
042| self.rcdnames = [t[1] for t in WordPressItem.FieldNames]
043| self.xmlnames = [t[2] for t in WordPressItem.FieldNames]
044| self.recid = 0
045| self.rectype = ''
046| self.status = ''
047| self.date = ''
048| self.name = ''
049| self.title = ''
050| self.category = ''
051| self.url = ''
052| self.link = ''
053| self.content = ''
054|
055| def rname (self, name):
056| '''Return index of a record field name.'''
057| if name in self.rcdnames:
058| return self.rcdnames.index(name)
059| return -1
060|
061| def xname (self, name):
062| '''Return index of an XML field name.'''
063| if name in self.xmlnames:
064| return self.xmlnames.index(name)
065| return -1
066|
067| def pairs (self):
068| '''Record as name:value pairs. Uses DB field names.'''
069| buf = {}
070| for r,n in zip(self.rcdnames, self.objnames):
071| buf[r] = self.__dict__[n]
072| return buf
073|
074| def record (self):
075| '''Record for SQLite database. Synchronize!'''
076| rcd = [self.__dict__[n] for n in self.objnames]
077| return tuple(rcd)
078|
079| def __call__ (self, which, value):
080| '''Set new value; return old value. Use index or any field name.'''
081| name = self.objnames[which] if isinstance(which,int) else str(which)
082|
083| if name not in self.objnames:
084|
085| if name in self.rcdnames:
086| ix = self.rcdnames.index(name)
087| name = self.objnames[ix]
088| else:
089|
090| if name in self.xmlnames:
091| ix = self.xmlnames.index(name)
092| name = self.objnames[ix]
093| else:
094| raise ValueError('Sorry! No field "%s"!' % name)
095|
096| old_value = self.__dict__[name]
097| self.__dict__[name] = value
098| return old_value
099|
100| def __bool__ (self): return (0 < len(self.objnames))
101| def __len__ (self): return len(self.objnames)
102|
103| def __getitem__ (self, ix):
104| name = self.objnames[ix]
105| return self.__dict__[name]
106|
107| def __setitem__ (self, ix, value):
108| name = self.objnames[ix]
109| if name == 'category':
110| curr = self.category
111| if len(curr):
112| self.category = '%s,%s' % (curr,value)
113| else:
114| self.category = value
115| return
116| self.__dict__[name] = value
117|
118| def __delitem__ (self, ix):
119| print('delitem')
120| raise RuntimeError('Not allowed to delete fields.')
121|
122| def __str__ (self):
123| t = (self.recid, self.rectype, self.date, self.link)
124| s = '%d[%s] %s %s'
125| return s % t
126|
127| def __repr__ (self):
128| t = (self.recid, self.rectype, self.date, self.status, self.link)
129| s = '{wp_item:{id:%s, type:%s, date:%s, status:%s, link:%s}}'
130| return s % t
131|
132|
133| class XmlWordpress (XmlHandlerMain):
134| '''Parse WordPress Extract XML file.'''
135|
136| def __init__ (self, fname, fpath=None, log=None):
137| super().__init__(fname, log=log)
138| self.filename = fname if fpath is None else path.join(fpath,fname)
139| self.fsize = path.getsize(self.filename)
140| self.dcr = datetime.fromtimestamp(path.getctime(self.filename), CST())
141| self.dlm = datetime.fromtimestamp(path.getmtime(self.filename), CST())
142| self.state = 0
143| self.records = []
144| self.current = WordPressItem()
145|
146| parse_xml_file(self.filename, self)
147|
148| def __bool__ (self): return (0 < len(self.records))
149| def __len__ (self): return len(self.records)
150| def __iter__ (self): return iter(self.records)
151| def __getitem__ (self, ix): return self.records[ix]
152| def __setitem__ (self, ix, value): self.records[ix] = value
153| def __delitem__ (self, ix): del self.records[ix]
154|
155|
156| def startElement (self, name, attrs):
157| '''XML Element'''
158|
159| super().startElement(name, attrs)
160|
161|
162| if (self.state == 0) and (name == 'rss'):
163| self.state = 1
164| if self.log: self.log.trace('xmlState[0] -> %d <%s>' % (self.state,name))
165|
166|
167| elif (self.state == 1) and (name == 'channel'):
168| self.state = 2
169| if self.log: self.log.trace('xmlState[1] -> %d <%s>' % (self.state,name))
170|
171|
172| elif (self.state == 2) and (name == 'item'):
173| self.current = WordPressItem()
174| self.state = 3
175| if self.log: self.log.trace('xmlState[2] -> %d <%s>' % (self.state,name))
176|
177|
178| elif (self.state == 3):
179| ix = self.current.xname(name)
180| if 0 <= ix:
181| self.state = 301 + ix
182| if self.log: self.log.trace('xmlState[3] -> %d <%s>' % (self.state,name))
183|
184| def endElement (self, name):
185| txt = self.buff.strip()
186|
187|
188| if (self.state == 1) and (name == 'rss'):
189| self.state = 0
190| if self.log: self.log.trace('xmlState[1] -> %d <%s>' % (self.state,name))
191|
192|
193| elif (self.state == 2) and (name == 'channel'):
194| self.state = 1
195| if self.log: self.log.trace('xmlState[2] -> %d <%s>' % (self.state,name))
196|
197|
198| elif (self.state == 3) and (name == 'item'):
199| rcd = self.current.record()
200| self.records.append(rcd)
201| if self.log: self.log.debug('xmlData[%d] %s' % (len(self.records),rcd))
202| self.state = 2
203| if self.log: self.log.trace('xmlState[3] -> %d <%s>' % (self.state,name))
204|
205|
206| elif (301 <= self.state <= 399):
207| ix = self.state - 301
208| assert ix == self.current.xname(name)
209| self.current[ix] = txt
210| self.state = 3
211| if self.log: self.log.trace('xmlState[3xx] -> %d <%s> "%s"' % (self.state,name,txt))
212|
213|
214| super().endElement(name)
215|
216|
217| class dbBaseTable (dbTable):
218| '''Base class for Wordpress tables.'''
219|
220| dbName = 'blog.sqlite'
221| dbPath = r'C:\Users\Bentley\proj\blog\data'
222| xmlName = 'blog.xml'
223| xmlPath = r'C:\Users\Bentley\www\root\blog\data'
224|
225| def __init__(self, tab_name, tab_cols):
226| super().__init__(path.join(self.dbPath,self.dbName), tab_name, tab_cols)
227|
228|
229| class dbPostsTable (dbBaseTable):
230| """Wordpress POSTS Table class."""
231| tabName = 'posts'
232| tabCols = ['"post_id" INTEGER NOT NULL UNIQUE'
233| ,'"post_type" TEXT NOT NULL'
234| ,'"post_date" TEXT NOT NULL'
235| ,'"post_status" TEXT NOT NULL'
236| ,'"post_name" TEXT NOT NULL'
237| ,'"post_title" TEXT NOT NULL'
238| ,'"category" TEXT NOT NULL'
239| ,'"url" TEXT NOT NULL'
240| ,'"link" TEXT NOT NULL'
241| ,'"content" TEXT NOT NULL'
242| ]
243|
244| def __init__(self):
245| super().__init__(self.tabName, self.tabCols)
246| self.Log.info('Database[%s]: %s' % (self.name,self.dbname))
247|
248| def create_table (self):
249| """Create POSTS Table."""
250| self.Log.info('Create Posts Table')
251| self.db_create()
252| self.load_records()
253|
254| def destroy_table (self):
255| """Destroy POSTS Table."""
256| super().destroy_table('Destroy Posts Table')
257|
258| def load_records (self):
259| """Load records from XML into database."""
260| xml = XmlWordpress(self.xmlName, fpath=self.xmlPath, log=self.Log)
261| for rcd in xml.records:
262| self.Log.debug(rcd)
263| self.Log.debug()
264| self.db_insert_many(xml.records)
265|
266| def list_to_file (self, sql, fname=None, fpath=None):
267| """List all records in POSTS table."""
268| self.Log.debug('db[%s] ListToFile' % self.name)
269| self.Log.trace('db[%s] %s' % (self.name,sql))
270| rs = self.db_query(sql)
271| if not rs:
272| self.Log.info('No data!')
273| return
274| xn = 'blog-db.tab' if fname is None else fname
275| xp = self.dbPath if fpath is None else fpath
276| fn = path.join(xp, xn)
277| fo = tabfile(fn, log=self.Log)
278| fo.hdrs = [hdr.replace('"','') for hdr in self.col_names]
279| fo.data = [[str(f) for f in r] for r in rs]
280| fo.save()
281|
282|
283|
284|
285| class XmlHandlerPageDB (XmlHandlerMain):
286| '''Parse Wordpress PGDB XML class.'''
287| S_NULL = 0
288| S_START = 1
289| S_RECORD = 2
290| S_FIELD = 3
291| S_ITEM = 4
292|
293| def __init__ (self, filename, fout, log=None):
294| self.setDocumentLocator(saxreader.Locator())
295| self.name = filename
296| self.out = fout
297| self.log = log
298| self.depth = 0
299| self.state = 0
300| self.buff = ''
301| self.record_ct = 0
302| self.record_id = -1
303| self.field_name = ''
304| self.item_name = ''
305| self.fields = {}
306|
307| def get_attribute (self, attrs, name):
308| return attrs[name] if name in attrs else ''
309|
310| def startDocument (self):
311| if self.log: self.log.info('document: START <%s>' % self.name)
312| self.depth = 0
313| self.state = 0
314| self.buff = ''
315| def endDocument (self):
316| if self.log: self.log.info('document: END')
317| if self.depth:
318| raise SyntaxError('Element Nesting Error!')
319|
320| def characters (self, content):
321| if self.log: self.log.debug('content: %s' % content)
322| self.buff += content
323|
324| def print_record (self):
325| t = (self.record_id, int(self.fields['pid']), self.fields['date'][0:10], self.fields['name'])
326| s = '%6d %5d %s %s'
327| print(s%t, file=self.out)
328|
329| def startElement (self, name, attrs):
330| if self.state == self.S_NULL:
331| if name == 'Records':
332| self.record_ct = int(self.get_attribute(attrs,'count'))
333| if self.log: self.log.trace('Records: %d' % self.record_ct)
334| self.state = self.S_START;
335|
336| if self.state == self.S_START:
337| if name == 'Record':
338| self.record_id = int(self.get_attribute(attrs,'rid'))
339| self.fields = {}
340| if self.log: self.log.trace('Record: %d' % self.record_id)
341| self.state = self.S_RECORD;
342|
343| if self.state == self.S_RECORD:
344| if name == 'Field':
345| self.field_name = self.get_attribute(attrs,'fid')
346| if self.field_name in ['cats', 'tags']:
347| self.fields[self.field_name] = []
348| self.state = self.S_FIELD;
349|
350| if self.state == self.S_FIELD:
351| if name == 'Item':
352| self.item_name = self.get_attribute(attrs,'name')
353| self.state = self.S_ITEM;
354|
355| if self.log: self.log.debug('element: %s' % name)
356| self.depth += 1
357| self.buff = ''
358|
359| def endElement (self, name):
360| if self.state == self.S_ITEM:
361| if name == 'Item':
362| txt = unescape(self.buff)
363| self.fields[self.field_name].append(txt)
364| if self.log: self.log.trace('Item: "%s"' % txt)
365| self.state = self.S_FIELD;
366|
367| if self.state == self.S_FIELD:
368| if name == 'Field':
369| if self.field_name in ['cats', 'tags']:
370| if self.log: self.log.trace('Field[%s] ^' % self.field_name)
371| else:
372| txt = unescape(self.buff)
373| self.fields[self.field_name] = txt
374| if self.log: self.log.trace('Field[%s]: "%s"' % (self.field_name, txt))
375| self.state = self.S_RECORD;
376|
377| if self.state == self.S_RECORD:
378| if name == 'Record':
379| self.print_record()
380| self.state = self.S_START;
381|
382| if self.state == self.S_START:
383| if name == 'Records':
384| if self.log: self.log.trace('Exit Records.')
385| self.state = self.S_NULL;
386|
387| self.depth -= 1
388| if self.depth < 0:
389| raise SyntaxError('Element Nesting Error!')
390| self.buff = ''
391|
392|
393|
394|
395|
396| BlogPostCss = '''\
396| #PageBody {
396| padding-right: 8px;
396| }
396| #PageBody #PostInfoPane {
396| float: right;
396| width: 220px;
396| background-color: #ffffef;
396| padding: 0;
396| border: 3px solid black;
396| margin: 0 0 20px 30px;
396| }
396| #PageBody #PostInfoDate {
396| font-size: 13px;
396| font-weight: bold;
396| text-align: right;
396| margin: 3px 5px 8px 5px;
396| }
396| #PageBody #PostInfoName {
396| font-size: 10px;
396| margin: 3px 5px;
396| }
396| #PageBody #PostInfoPID {
396| font-size: 12px;
396| margin: 3px 5px;
396| }
396| #PageBody #PostInfoTags {
396| font-size: 12px;
396| margin: 4px 5px;
396| }
396| #PageBody #PostInfoLink {
396| margin: 10px 5px;
396| }
396| #PageBody #BlogPost {
396| width: 500px;
396| font-size: 12px;
396| }
396| #PageBody #BlogPost .caption {
396| font-size: 11px;
396| }
396| '''
397|
398| def parse_caption (s):
399| '''Parse the WP [caption {params}]{content}[/caption] inserts.'''
400| args = {}
401| state = 0
402| name = []
403| value = []
404| for ch in s:
405|
406| if state == 0:
407| if ch == ' ':
408| continue
409| name = [ch]
410| state = 1
411| continue
412|
413| if state == 1:
414| if ch == '=':
415| state = 2
416| continue
417| name.append(ch)
418| continue
419|
420| if state == 2:
421| assert ch=='"'
422| value = []
423| state = 3
424| continue
425|
426| if state == 3:
427| if ch == '"':
428| nm = ''.join(name)
429| val = ''.join(value)
430| if nm == 'width':
431| val = int(val)
432| args[nm] = val
433| state = 0
434| value.append(ch)
435| continue
436| raise RuntimeError('Invalid State: %s' % str(state))
437|
438| return args
439|
440| class BlogPostWebPage (WebPage):
441| '''Makes a webpage containing a blog post or page.'''
442| def __init__ (self, pid, db_record, h1, h2):
443| self.pid = pid
444| post_date = datetime.fromisoformat(db_record[0])
445| post_name = db_record[1]
446| post_title = db_record[2]
447| post_tags = db_record[3].replace(',', ', ')
448| post_url = db_record[4]
449| post_lines = db_record[5].splitlines()
450| super().__init__(post_title, h1=h1, h2=h2, h3='', css=CssFiles)
451| self.csstxt = BlogPostCss
452|
453| self.add('<div id="PostInfoPane">')
454| self.add('<div id="PostInfoDate">%s</div>' % post_date.strftime('%a %b %d, %Y'))
455| self.add('<div id="PostInfoPID" >pgid: <strong>%d</strong></div>' % pid)
456| self.add('<div id="PostInfoTags">tags: <em>%s</em></div>' % post_tags)
457| self.add('<div id="PostInfoName">slug: %s</div>' % post_name)
458| self.add('<div id="PostInfoLink"><a href="%s" target="_blank">[WP Link]</a></div>' % post_url)
459| self.add('</div>')
460| self.add('<h3>%s</h3>' % post_title)
461| self.add('<div id="BlogPost">')
462|
463| def strip_latex_params (txt):
464| s,fg,bg = 0, '00007f', 'ffffff'
465| Log.trace(txt)
466| ix = txt.rfind('&s=')
467| if 0 <= ix:
468| t = txt[ix+7:ix+8]
469| if t in ['+', '-']:
470| t = txt[ix+7:ix+9]
471| s = int(t)
472| txt = txt[0:ix]+txt[ix+8:]
473|
474| ix = txt.rfind('&fg=')
475| if 0 <= ix:
476| fg = txt[ix+8:ix+14]
477| txt = txt[0:ix]+txt[ix+14:]
478|
479| ix = txt.rfind('&bg=')
480| if 0 <= ix:
481| bg = txt[ix+8:ix+14]
482| txt = txt[0:ix]+txt[ix+14:]
483|
484| Log.trace(txt)
485| return (txt, s, fg, bg)
486|
487| blockquote_flag = False
488| list_flag = False
489| pre_flag = False
490| div_flag = False
491| for line in post_lines:
492|
493| if '$latex ' in line:
494| url = r'<img src="https://s0.wp.com/latex.php?latex=%s&s=%d&fg=%s&bg=%s&c=20201002">'
495| ix0 = line.index('$latex ')
496| ix1 = line.index('$', ix0+7)
497|
498| code,s,fg,bg = strip_latex_params(line[ix0+7:ix1])
499| code = code.replace('&', '%26')
500| image = url % (code, s, fg, bg)
501|
502| if ix0 == 0:
503| line = '<p style="margin-left:20px;">%s%s</p>' % (image, line[ix1+1:])
504| else:
505| line = '%s%s%s' % (line[0:ix0], image, line[ix1+1:])
506|
507|
508| if '[caption ' in line:
509| ix0 = line.index('[caption ')
510| ix1 = line.index(']', ix0+9)
511| if line[ix1+1:].startswith('<img '):
512| ix2 = line.index('>', ix1+1)
513| elif line[ix1+1:].startswith('<a '):
514| ix2 = 5 + line.index('/></a>', ix1+1)
515|
516| else:
517| raise RuntimeError(f'Unexpected [caption] element: "{line}"')
518| ix3 = line.index('[/caption]', ix2+1)
519| img = line[ix1+1:ix2+1]
520| txt = line[ix2+2:ix3]
521| args = parse_caption(line[ix0+9:ix1])
522|
523| if args['align'] == 'aligncenter':
524| line = f'<div class="caption" style="text-align:center;margin:10px 0 15px 0;">{img}<div>{txt}</div></div>'
525| self.add(line)
526| continue
527|
528| if args['align'] == 'alignleft':
529| line = f'<div class="caption" style="width:{args["width"]}px;float:left;text-align:left;margin:0 10px 20px 0;">{img}<div>{txt}</div></div>'
530| self.add(line)
531| continue
532|
533| if args['align'] == 'alignright':
534| line = f'<div class="caption" style="width{args["width"]}:%dpx;float:right;text-align:left;margin:0 0 20px 10px;">{img}<div>{txt}</div></div>'
535| self.add(line)
536| continue
537|
538|
539| if line[0:3] in ['<ol','<ul','<dl']:
540| list_flag = True
541| self.add(line)
542| continue
543| if list_flag:
544| if line[0:4] in ['</ol','</ul','</dl']:
545| list_flag = False
546| self.add(line)
547| continue
548|
549|
550| if line.startswith('<pre'):
551| if '</pre>' not in line:
552| pre_flag = True
553| self.add(line)
554| continue
555| if pre_flag:
556| if '</pre>' in line:
557| pre_flag = False
558| self.add(line)
559| continue
560|
561|
562| if line.startswith('<blockquote'):
563| if line.endswith('</blockquote>'):
564| self.add(line)
565| continue
566| blockquote_flag = True
567| self.add('%s<br>' % line)
568| continue
569| if blockquote_flag:
570| if line.endswith('</blockquote>'):
571| blockquote_flag = False
572| self.add(line)
573| continue
574| self.add('%s<br>' % line)
575| continue
576|
577|
578| if line.startswith('<div'):
579| if line.endswith('</div>'):
580| self.add(line)
581| continue
582| div_flag = True
583| self.add('%s<br>' % line)
584| continue
585| if div_flag:
586| if line.endswith('</div>'):
587| div_flag = False
588| self.add(line)
589| continue
590| self.add('%s<br>' % line)
591| continue
592|
593|
594| if line.startswith('<t') or line.startswith('</t'):
595| self.add(line)
596| continue
597|
598|
599| if line.startswith('<p'):
600| self.add(line)
601| continue
602|
603|
604| if line == '<!--more-->':
605| continue
606|
607| if len(line) == 0:
608| continue
609|
610| self.add('<p>%s</p>' % line)
611|
612| self.add('</div>')
613| self.add('')
614|
615| def save (self, fname, fpath=None):
616| fn = path.join(fpath, fname) if fpath else fname
617| fp = open(fn, mode='w', encoding='utf-8')
618| try:
619| self.write(fp)
620| except:
621| raise
622| finally:
623| fp.close()
624| Log.info('wrote: %s' % fn)
625|
626|
627|
628|
629| class XmlHandlerCategoryIndex (XmlHandlerPageDB):
630| '''Parse Wordpress PGDB XML File - Category Index class.'''
631| def __init__ (self, filename, fout, log=None):
632| super().__init__(filename, fout, log)
633| self.categories = {}
634| parse_xml_file(filename, self)
635|
636| def endElement (self, name):
637| if self.state == self.S_ITEM:
638|
639| if (self.field_name == 'cats') and (name == 'Item'):
640| cat_txt = unescape(self.buff)
641| if self.item_name not in self.categories:
642| self.categories[self.item_name] = [cat_txt, 0]
643| t = (self.fields['pid'], self.fields['name'], self.fields['url'], self.fields['date'])
644| self.categories[self.item_name].append(t)
645| self.categories[self.item_name][1] += 1
646| super().endElement(name)
647|
648| class HtmlPageCategoryList (WebPage):
649| '''Category List HTML Page class.'''
650| html_row = '<tr><td class="C1"><a target="_top" href="cat_%s.html">%s</a></td><td class="C2"><a target="_blank" href="https://logosconcarne.com/category/%s">%s</a></td><td class="C3">%d</td><td class="C3">%d</td><td class="C4" style="color:%s;">%+d</td></tr>'
651| html_foot = '<tr><th class="C1" colspan="2">(total)</th><td class="C3">%d</td><td class="C3">%d</td></tr>'
652| PageProps = {
653| 'h1': 'Logos Con Carne',
654| 'h2': 'Stats',
655| 'h3': 'Posts by Category',
656| 'css': ['/basic.css', 'cat_index.css']
657| }
658| def __init__ (self, data, rdata):
659| super().__init__('Categories', **HtmlPageCategoryList.PageProps)
660| self.data = data
661| self.rdata = rdata
662| self.total = 0
663| self.rtotal = rdata.tpages
664| self._build()
665|
666| def _build (self):
667| self.add()
668| self.add('<table class="CategoryList">')
669| self.add('<thead><tr>')
670| self.add('<th class="C1">category</th>')
671| self.add('<th class="C2">slug</th>')
672| self.add('<th class="C3">posts</th>')
673| self.add('<th class="C3">real</th>')
674| self.add('<th class="C3">diff</th>')
675| self.add('</tr></thead><tbody>')
676| for cat in sorted(self.data.categories):
677| lst = self.data.categories[cat]
678| nam = lst[0]
679| nbr = int(lst[1])
680| rnbr = self.rdata.xref[nam]
681| dif = rnbr - nbr
682| c = '#ff0000' if dif < 0 else ('#009900' if 0 < dif else '#cccccc')
683| self.add(self.html_row % (cat,nam, cat,cat, nbr, rnbr, c, dif))
684| self.total += nbr
685| self.add(self.html_foot % (self.total, self.rtotal))
686| self.add('</tbody></table>')
687| self.add()
688|
689| class HtmlPageCategoryIndex (WebPage):
690| '''Category Index HTML Page class.'''
691| def __init__ (self, data):
692| '''New Category Index page. data=[name,count,post1,post2,..]'''
693| self.post_list = data
694| self.cat_name = self.post_list.pop(0)
695| self.count = self.post_list.pop(0)
696| props = {
697| 'h1': 'Logos Con Carne',
698| 'h2': 'Category Index',
699| 'h3': 'Pages posted under "%s" (%d posts)' % (self.cat_name, self.count),
700| 'css': ['/basic.css', 'cat_index.css']
701| }
702| super().__init__(self.cat_name, **props)
703| self._build()
704|
705| def _build (self):
706| self.add()
707| self.add('<table class="CategoryIndex">')
708| self.add('<thead><tr>')
709| self.add('<th class="C1">#</th>')
710| self.add('<th class="C2">id</th>')
711| self.add('<th class="C3">date</th>')
712| self.add('<th class="C4">post</th>')
713| self.add('</tr></thead><tbody>')
714| Log.debug('CATEGORY: "%s" (%d)' % (self.cat_name, self.count))
715| for ix,t in enumerate(self.post_list):
716| pid,nam,url,dt = t
717| post = 'posts/post_%06d.html' % int(pid)
718| self.add('<tr>')
719| self.add('<td class="C1">%d</td>' % (1+ix))
720| self.add('<td class="C2"><a target=_blank href="%s">%s</a></td>' % (url,pid))
721| self.add('<td class="C3">%s</td>' % dt)
722| self.add('<td class="C4"><a target=_blank href="%s">%s</a></td>' % (post,nam))
723| self.add('</tr>')
724| self.add('</tbody></table>')
725| self.add()
726|
727| class RealCategoryData (object):
728| '''Categories TAB File class.'''
729| def __init__ (self, fname='categories.tab', fpath=None):
730| self.filename = fname if fpath is None else path.join(fpath,fname)
731| ftab = tabfile(self.filename)
732| ftab.load()
733| self.hdrs = ftab.hdrs
734| self.rcds = [(t[0], t[1], t[2], int(t[3])) for t in ftab.data]
735| self.cats = [r[0] for r in self.rcds]
736| self.hits = [r[3] for r in self.rcds]
737| self.tpages = sum(self.hits)
738| self.xref = dict(zip(self.cats, self.hits))
739|
740| def __len__ (self):
741| return len(self.rcds)
742| def __getitem__ (self, ix):
743| return self.rcds[ix]
744| def __iter__ (self):
745| return iter(self.rcds)
746|
747| def __str__ (self):
748| return '%s\n[%d Categories, %d Pages]' % (self.filename, len(self), self.tpages)
749|
750|
751|
752|
753| class XmlHandlerPostsByTag (XmlHandlerPageDB):
754| '''Parse Wordpress PGDB XML File - Tag Index class.'''
755| def __init__ (self, filename, fout, log=None):
756| super().__init__(filename, fout, log)
757| self.tags = {}
758| parse_xml_file(filename, self)
759|
760| def print_record (self):
761| pass
762|
763| def endElement (self, name):
764| super().endElement(name)
765| if name != 'Record':
766| return
767| for c in self.fields['tags']:
768| if c not in self.tags:
769| self.tags[c] = 0
770| self.tags[c] += 1
771|
772| class HtmlPagePostsByTag (WebPage):
773| '''Tag Index HTML Page class.'''
774| html_row = '<tr><th>%d</th><td class="C1">%s</td><td class="C2">%d</td><td class="Link">%s</td></tr>'
775| PageProps = {
776| 'h1': 'Logos Con Carne',
777| 'h2': 'Stats',
778| 'h3': 'Posts by Tag',
779| 'css': ['/basic.css','stats.css']
780| }
781| def __init__ (self, data):
782| super().__init__('Posts by Tag', **HtmlPagePostsByTag.PageProps)
783| self.data = data
784| self.total = 0
785| self._build()
786|
787| def _build (self):
788| self.add()
789| self.add('<table class="StatsTable">')
790| self.add('<thead><tr>')
791| self.add('<th class="C1">#</th>')
792| self.add('<th class="C2">tag</th>')
793| self.add('<th class="C2">posts</th>')
794| self.add('<th class="C0">link</th>')
795| self.add('</tr></thead><tbody>')
796| ds = self.data.tags.items()
797| ds = sorted(ds, key=lambda x:x[0].lower())
798| ds = sorted(ds, key=lambda x:x[1], reverse=True)
799| for dx,dt in enumerate(ds):
800| tag, hits = dt
801| url = 'https://logosconcarne.com/tag/%s/' % tag.lower().replace(' ','-')
802| link = '<a href="%s" target="_blank" rel="noopener">%s</a>' % (url,url)
803| self.add(self.html_row % (dx+1, tag, hits, link))
804| self.total += hits
805| self.add(self.html_row % (0, '(total)', self.total, ''))
806| self.add('</tbody></table>')
807| self.add()
808|
809|
810|
811|
812| class XmlHandlerPostsByMonth (XmlHandlerPageDB):
813| '''Parse Wordpress PGDB XML File - Posts-by-Month class.'''
814| def __init__ (self, filename, fout, log=None):
815| super().__init__(filename, fout, log)
816| self.stats = {}
817| parse_xml_file(filename, self)
818|
819| def print_record (self):
820| pass
821|
822| def endElement (self, name):
823| super().endElement(name)
824| if name != 'Record':
825| return
826| s = self.fields['date']
827| dt_yr = int(s[0:4])
828| dt_mo = int(s[5:7])
829| if dt_yr not in self.stats:
830| self.stats[dt_yr] = [0] * 12
831| self.stats[dt_yr][dt_mo-1] += 1
832|
833| class HtmlPagePostsByMonth (WebPage):
834| '''Posts-by-Month HTML Page class.'''
835| PageProps = {
836| 'h1': 'Logos Con Carne',
837| 'h2': 'Stats',
838| 'h3': 'Posts by Month',
839| 'css': ['/basic.css','stats.css']
840| }
841| def __init__ (self, data):
842| super().__init__('Posts by Month', **HtmlPagePostsByMonth.PageProps)
843| self.data = data
844| self._build()
845|
846| def _build (self):
847| months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
848| self.add('')
849| self.add('<table class="StatsTable">')
850| self.add('<thead>')
851| self.add('<tr>')
852| self.add('<th class="C1">year</th>')
853| for mo in range(12):
854| self.add('<th class="C2">%s</th>' % months[mo])
855| self.add('<th class="C3">tot</th>')
856| self.add('</tr>')
857| self.add('</thead>')
858| self.add('<tbody>')
859| for yr in sorted(self.data.stats):
860| self.add('<tr>')
861| self.add('<th style="font-weight:bold;">%d</th>' % yr)
862| total = 0
863| for mo in range(12):
864| n = self.data.stats[yr][mo]
865| self.add('<td class="C3">%d</td>' % n)
866| total += n
867| self.add('<td class="C2">%d</td>' % total)
868| self.add('</tr>')
869| self.add('</tbody>')
870| self.add('</table>')
871| self.add('<div style="margin-top:24pt;">')
872| self.add('<img src="charts/posts-per-month.png" alt="[posts-per-month.png]" width="700">')
873| self.add('</div>')
874| self.add('<p style="font-family:sans-serif;font-size:8pt;margin-top:24pt;">')
875| self.add('Note: Table data includes pages; chart data is posts only.')
876| self.add('</p>')
877|
878|
879|
880|
881| class XmlHandlerPostIdList (XmlHandlerPageDB):
882| '''Parse Wordpress PGDB XML File - Post IDs List class.'''
883| def __init__ (self, filename, post_type, fout, log=None):
884| super().__init__(filename, fout, log)
885| self.post_type = post_type
886| parse_xml_file(filename, self)
887|
888| def print_record (self):
889| if self.fields['post-type'] == self.post_type:
890| t = (int(self.fields['pid']), self.fields['name'])
891| s = '%d %s'
892| x = s % t
893| print(x, file=self.out)
894|
895| def startElement (self, name, attrs):
896| super().startElement(name, attrs)
897| if (name == 'Field') and (self.field_name == 'pid'):
898| self.fields['post-type'] = self.get_attribute(attrs,'post-type')
899| if self.log: self.log.trace('post-type: "%s"' % self.fields['post-type'])
900|
901|
902|
903|
904| class BlogPageHitsData (object):
905| '''Blog Page Hits Data. Data form: page-name:[tot-hits,[(year,hits),..]]'''
906| def __init__ (self, filelist, fpath=None):
907| self.files = filelist
908| self.fpath = fpath
909| self.data = {}
910| self.total_hits = 0
911| self._load()
912| Log.trace(self)
913| Log.trace()
914|
915| def __len__ (self): return len(self.data)
916| def __getitem__ (self, k): return self.data[k]
917| def __iter__ (self): return iter(self.data)
918|
919| def __str__ (self):
920| s = 'Blog Hits: %d pages, %d hits total, %d years'
921| t = (len(self), self.total_hits, len(self.files))
922| return s%t
923|
924| def names (self): return list(self.data.keys())
925| def items (self): return list(self.data.items())
926|
927| def _load (self):
928| """Load hit data CSV files."""
929| for fx,t in enumerate(self.files):
930| yr, nm = t
931| fn = nm if self.fpath is None else path.join(self.fpath,nm)
932| Log.debug('FILE #%d [%d]: {%s}' % (1+fx, yr, nm))
933| try:
934| fobj = csvfile(fn, headers=False)
935| fobj.load()
936|
937| for dx,d in enumerate(fobj.data):
938| Log.trace(d)
939| title = d[0]
940| hits = int(d[1])
941| link = d[2] if 2<len(d) else ''
942| Log.trace('hit-datum: %d/%d: (%d) "%s" %s' % (yr,dx,hits,title,link))
943|
944| if 0 <= title.find('""'):
945| title = title.replace('""','"')
946|
947| if title not in self.data:
948| self.data[title] = [link, 0, []]
949| if 0 < len(link):
950| if 0 < len(self.data[title][0]):
951| if link != self.data[title][0]:
952| Log.warn('%d/%d: Link Conflict: "%s" v %s"' % (yr,dx,link,self.data[title][0]))
953| else:
954| self.data[title][0] = link
955|
956| self.data[title][1] += hits
957| self.data[title][2].append((yr, hits))
958| self.total_hits += hits
959| except:
960| raise
961| Log.debug()
962|
963|
964| class BlogPageHitsPage (WebPage):
965| """Page Hits HTML webpage class."""
966| Params = dict(h1=HtmlH1, h2=HtmlH2, h3='Page Hits by Year', css=CssFiles)
967|
968| def __init__ (self, stats_files, year_zero, year_curr, fpath=None):
969| super().__init__('Page Hits by Year', **self.Params)
970|
971| self.data_obj = BlogPageHitsData(stats_files, fpath=fpath)
972| self.data = self.data_obj.items()
973|
974| yrs = list(range(year_zero, year_curr+1))
975| tot_years = {}
976| for yr in yrs: tot_years[yr] = 0
977| tot_reads = 0
978| self.add('')
979| self.add('<table class="StatsTable">')
980| self.add('<thead>')
981| self.add('<tr>')
982| self.add('<th class="C0">Rank</th>')
983| self.add('<th class="C1">Post Title</th>')
984| self.add('<th class="C2">Reads</th>')
985| for yr in yrs: self.add('<th class="C3">%d</th>' % yr)
986| self.add('</tr>')
987| self.add('</thead>')
988| self.add('<tbody>')
989|
990| html_tr = '<tr><th>%d</th> <td class="C1">%s</td> <td class="C2">%d</td> %s</tr>'
991| html_td = '<td class="C3"%s>%d</td>\n'
992| html_a = '<a href="%s">%s</a>'
993| for ix,t2 in enumerate(sorted(self.data, key=lambda x:(x[1][1],x[0]), reverse=True)):
994| title, stats = t2
995| link = html_a % (stats[0], title)
996| total = stats[1]
997|
998| if title.startswith('reblog'):
999| Log.trace('SKIP: %s (%d)' % (title, total))
1000| continue
1001|
1002| subs = ''
1003| for yr in yrs:
1004| n = 0
1005| ss = [s for s in stats[2] if s[0]==yr]
1006| if ss:
1007| n = ss[0][1]
1008| c = '' if n else ' style="color:#dfdfdf;"'
1009| subs += (html_td % (c,n))
1010| tot_years[yr] += n
1011|
1012| tot_reads += total
1013| self.add(html_tr % (ix, link, total, subs))
1014|
1015| subs = ''
1016| for yr in yrs:
1017| n = tot_years[yr]
1018| subs += (html_td % (' style="background-color:#ffffbf;font-weight:bold;"',n))
1019| self.add(html_tr % (0, 'totals', tot_reads, subs))
1020| self.add('</tbody>')
1021| self.add('</table>')
1022| self.add('')
1023| Log.trace()
1024|
1025| def save (self, fname, fpath=None):
1026| fn = fname if fpath is None else path.join(fpath,fname)
1027| fp = open(fn, mode='w', encoding='utf-8')
1028| try:
1029| self.write(fp)
1030| except:
1031| raise
1032| finally:
1033| fp.close()
1034| Log.info('wrote: %s' % fn)
1035|
1036|
1037|
1038|
1039| class BlogStatsPage (WebPage):
1040| """Blog Stats HTML webpage class."""
1041| Params = dict(h1=HtmlH1, h2=HtmlH2, h3='Post Stats by Year', css=CssFiles)
1042|
1043| def __init__ (self, data, hdrs, cols):
1044| super().__init__('Post Stats by Year', **self.Params)
1045| self.data = data
1046| self.hdrs = hdrs
1047| self.cols = cols
1048| self.totals = [0]*len(self.hdrs)
1049| self.stats = []
1050|
1051| Log.trace('[%s]' % ', '.join(self.hdrs))
1052| for row in self.data:
1053| Log.trace(row)
1054| Log.trace()
1055|
1056| self._process()
1057|
1058| self._build()
1059|
1060| def _process (self):
1061| '''Process stats data into totals and averages.'''
1062|
1063| for row in self.data:
1064| for ix in range(1,len(row)):
1065| self.totals[ix] += row[ix]
1066| row.append(row[1]/12.0)
1067|
1068| self.tposts = self.totals[1]
1069| self.tcmmts = self.totals[2]
1070| self.tlikes = self.totals[4]
1071| self.twords = self.totals[6]
1072|
1073|
1074| self.nbr_yrs = float(len(self.data))
1075|
1076|
1077| self.stats.append('Table Totals:')
1078| self.stats.append('')
1079| for lbl,typ,dat in zip(self.hdrs, self.cols, self.totals):
1080| if typ == 0:
1081| continue
1082| if typ == 1:
1083| self.stats.append(f'{lbl}: {dat:,}')
1084| continue
1085| self.stats.append(f'{lbl}: {dat}')
1086| self.stats.append('')
1087| self.stats.append('')
1088| self.stats.append('Yearly Averages:')
1089| self.stats.append('')
1090| for lbl,typ,dat in zip(self.hdrs, self.cols, self.totals):
1091| if typ == 0:
1092| continue
1093| if typ == 1:
1094| self.stats.append(f'{lbl}: {dat/self.nbr_yrs:,.1f}')
1095| continue
1096| self.stats.append(f'{lbl}: {dat}')
1097| self.stats.append('')
1098| self.stats.append('')
1099| self.stats.append('Stats:')
1100| self.stats.append('')
1101| self.stats.append(f'Total-Posts: {self.tposts:,}')
1102| self.stats.append(f'Total-Likes: {self.tlikes:,}')
1103| self.stats.append(f'Total-Cmmts: {self.tcmmts:,}')
1104| self.stats.append(f'Total-Words: {self.twords:,}')
1105| self.stats.append('')
1106| self.stats.append(f'Avg-Words-per-Post: {safediv(self.twords,self.tposts):.2f}')
1107| self.stats.append(f'Avg-Likes-per-Post: {safediv(self.tlikes,self.tposts):.2f}')
1108| self.stats.append(f'Avg-Cmmts-per-Post: {safediv(self.tcmmts,self.tposts):.2f}')
1109| self.stats.append('')
1110|
1111| def _build (self):
1112| '''Build HTML content.'''
1113| self.add('')
1114|
1115| self.add('<ul>')
1116| self.add('<li>Total Posts: %s</li>' % add_commas(self.tposts))
1117| self.add('<li>Posts per Year: %.2f</li>' % safediv(self.tposts,len(self.data)-1))
1118| self.add('<li>Total Words: %s</li>' % add_commas(self.twords))
1119| self.add('<li>Words per Post: %.2f</li>' % safediv(self.twords,self.tposts))
1120| self.add('</ul>')
1121| self.add('')
1122|
1123| self.add('<table class="StatsTable">')
1124| self.add('<thead>')
1125| self.add('<tr>')
1126| for col in self.hdrs:
1127| colstyle = ''
1128| self.add('<th style="%s">%s</th>' % (colstyle,col))
1129| self.add('</tr>')
1130| self.add('</thead>')
1131| self.add('<tbody>')
1132| for row in self.data:
1133| self.add('<tr>')
1134| self.add('<th style="">%d</th>' % row[0])
1135| for dat,typ in zip(row[1:], self.cols[1:]):
1136| css = 'text-align:right;'
1137| txt = (('%.2f' if typ==2 else '%d') % dat)
1138| self.add('<td style="%s">%s</td>' % (css,txt))
1139| self.add('</tr>')
1140| self.add('</tbody>')
1141| self.add('</table>')
1142| self.add('')
1143| self.add('<div style="padding:0;margin:24pt 12pt;">')
1144| self.add('<img src="charts/posts-per-year.png" alt="[Posts per Year]" width="300">')
1145| self.add('<img src="charts/words-per-post.png" alt="[Words per Post]" width="300">')
1146| self.add('</div>')
1147| self.add('')
1148| self.add('')
1149|
1150| def save (self, fname, fpath=None):
1151| '''Save HTML page.'''
1152| fn = fname if fpath is None else path.join(fpath,fname)
1153| fp = open(fn, mode='w', encoding='utf-8')
1154| try:
1155| self.write(fp)
1156| except:
1157| raise
1158| finally:
1159| fp.close()
1160| Log.info('wrote: %s' % fn)
1161|
1162| def stats_save (self, fname='stats.txt', fpath=None):
1163| '''Save stats to file.'''
1164| fn = fname if fpath is None else path.join(fpath,fname)
1165| fp = open(fn, mode='w', encoding='utf-8')
1166| try:
1167| for stat in self.stats:
1168| fp.write(stat)
1169| fp.write(EOL)
1170| except:
1171| raise
1172| finally:
1173| fp.close()
1174| Log.info('wrote: %s' % fn)
1175|
1176|
1177|
1178| class SelectedPosts (object):
1179| """Selected Posts Dataset class."""
1180| FileName = 'selected-posts.list'
1181|
1182| class PostHits (object):
1183| """Post Hits Data class."""
1184| def __init__ (self, name):
1185| self.name = name
1186| self.pid = None
1187| self.url = ''
1188| self.hits = []
1189| self.total = 0
1190| self.rank = 0
1191| self.rank_year = 0
1192| self.chart_max = 0
1193| def years_list (self):
1194| return [yr[0] for yr in self.hits]
1195| def years_total (self):
1196| return sum([yr[1] for yr in self.hits])
1197| def months_total (self, year):
1198| g = self.years_list()
1199| if year not in g:
1200| return -1
1201| ix = g.index(year)
1202| return sum(self.hits[ix][2])
1203| def _add_links (self, txt):
1204| parts = txt.split(',')
1205| assert len(parts)==2, RuntimeError(f'Too many ID fields: "{txt}"')
1206| self.pid = int(parts[0].strip())
1207| self.url = parts[1].strip()
1208| def _add_stats (self, txt):
1209| parts = txt.split(',')
1210| assert len(parts)==4, RuntimeError(f'Too many stat fields: "{txt}"')
1211| self.rank = int(parts[0].strip())
1212| self.rank_year = int(parts[1].strip())
1213| self.total = int(parts[2].strip())
1214| self.chart_max = int(parts[3].strip())
1215| def _add_year (self, txt):
1216| a = [int(_.strip()) for _ in txt.split(',')]
1217| t = (a[0], a[-1], a[1:-1])
1218| self.hits.append(t)
1219| def __eq__ (self, other): return (self.rank == other.rank)
1220| def __ne__ (self, other): return (self.rank != other.rank)
1221| def __lt__ (self, other): return (self.rank < other.rank)
1222| def __le__ (self, other): return (self.rank <= other.rank)
1223| def __gt__ (self, other): return (self.rank > other.rank)
1224| def __ge__ (self, other): return (self.rank >= other.rank)
1225| def __hash__ (self): return hash(self.name, self.url)
1226| def __bool__ (self): return True
1227| def __str__ (self):
1228| s = '[%d,%d] %s (%d) #%d'
1229| t = (self.rank, self.rank_year, self.name, self.total, self.pid)
1230| return s%t
1231| def __repr__ (self):
1232| s = '{PostHits:{name:"%s", pid:%d, total:%d, rank:%d, ymax:%d, id:%08x}}'
1233| t = (self.name, self.pid, self.total, self.rank, self.chart_max, id(self))
1234| return s%t
1235|
1236| def __init__ (self, fname=FileName, fpath=None, exclude=None):
1237| self.filename = fname if fpath is None else path.join(fpath,fname)
1238| self.exclude = '__' if exclude is None else exclude
1239| self.data = []
1240| self.posts = []
1241| self.errs = []
1242| self._load()
1243| self._process()
1244| self._test()
1245|
1246| def save (self, fname=FileName, fpath=None):
1247| '''Write posts data to an output file.'''
1248| fn = fname if fpath is None else path.join(fpath,fname)
1249| fp = open(fn, mode='w', encoding='utf-8')
1250| try:
1251| for p in sorted(self.posts, key=lambda g:g.rank):
1252| print(p, file=fp)
1253| for y in p.hits:
1254| print(y, file=fp)
1255| print(file=fp)
1256| print(file=fp)
1257| except:
1258| raise
1259| finally:
1260| fp.close()
1261| Log.info('wrote: %s' % fn)
1262|
1263| def __len__ (self):
1264| return len(self.posts)
1265|
1266| def __getitem__ (self, ix):
1267| return self.posts[ix]
1268|
1269| def __iter__ (self):
1270| return iter(self.posts)
1271|
1272| def __call__ (self, name=None, pid=None):
1273| if pid is not None:
1274| for p in self.posts:
1275| if p.pid == pid:
1276| return p
1277| return None
1278| if name is not None:
1279| s = name.lower()
1280| ns = [(p.name.lower(), p) for p in self.posts]
1281| for n,p in ns:
1282| if n == s:
1283| return p
1284| for n,p in ns:
1285| if n.startswith(s):
1286| return p
1287| for n,p in ns:
1288| if s in n:
1289| return p
1290| return None
1291| raise RuntimeError('A Name or a PID is required.')
1292|
1293| def __str__ (self):
1294| s = 'posts: %d, lines: %d, errs: %d'
1295| t = (len(self), len(self.data), len(self.errs))
1296| return s%t
1297|
1298| def __repr__ (self):
1299| s = '{SelectedPosts:{fname:"%s", posts:%d, id:%08x}}'
1300| t = (self.filename, len(self), id(self))
1301| return s%t
1302|
1303| def _load (self):
1304| '''Load the input data from a file.'''
1305| fp = open(self.filename, 'r', encoding='utf-8')
1306| try:
1307| self.data = fp.readlines()
1308| except:
1309| raise
1310| finally:
1311| fp.close()
1312| Log.info('read: %s' % self.filename)
1313|
1314| def _process (self):
1315| '''Parse input data into posts data.'''
1316| state = 0
1317| linenbr = 0
1318| obj = None
1319| for txt in self.data:
1320| linenbr += 1
1321| txt = txt.strip()
1322| if txt == '':
1323| continue
1324| if state == 0:
1325| if txt.startswith('===='):
1326| state = 1
1327| continue
1328| raise RuntimeError('Illegal Syntax[%d]: %s' % (linenbr, txt))
1329| if state == 1:
1330| obj = SelectedPosts.PostHits(txt)
1331| state = 2
1332| continue
1333| if state == 2:
1334| obj._add_links(txt)
1335| state = 3
1336| continue
1337| if state == 3:
1338| obj._add_stats(txt)
1339| state = 4
1340| continue
1341| if state == 4:
1342| if txt.startswith('----'):
1343| state = 5
1344| continue
1345| raise RuntimeError('Illegal Syntax[%d]: %s' % (linenbr, txt))
1346| if state == 5:
1347| if txt[0:4].isdigit():
1348| obj._add_year(txt)
1349| continue
1350| if txt.startswith('----'):
1351| if self.exclude is not None:
1352| if not obj.name.startswith(self.exclude):
1353| self.posts.append(obj)
1354| obj = None
1355| state = 0
1356| continue
1357| raise RuntimeError('Illegal Syntax[%d]: %s' % (linenbr, txt))
1358|
1359| def _test (self):
1360| '''Test. (Check errs for results; empty means okay.)'''
1361| for p in self.posts:
1362| tot = 0
1363| for yr,stot,hitz in p.hits:
1364| htot = sum(hitz)
1365| if htot != stot:
1366| self.errs.append('Year: %d<>%d %s' % (stot,htot,p.name))
1367| tot += stot
1368| if tot != p.total:
1369| self.errs.append('Total: %d<>%d %s' % (p.total,tot,p.name))
1370|
1371|
1372|
1373|
1374| '''eof'''
1375|