microblog.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. import sys, os, traceback
  2. import dateutil.parser
  3. # returns html-formatted string
  4. def make_buttons(btn_dict, msg_id):
  5. buttons = "<div class=\"buttons\">"
  6. fmt = "<a href=\"%s\">[%s]</a>"
  7. for key in btn_dict:
  8. url = btn_dict[key]
  9. if url[-1] == '=':
  10. # then interpret it as a query string
  11. url += str(msg_id)
  12. buttons += fmt % (url,key)
  13. buttons += "</div>"
  14. return buttons
  15. # apply div classes for use with .css
  16. def make_post(num, timestamp, conf, msg):
  17. fmt = conf["format"]
  18. if "buttons" in conf:
  19. b = make_buttons(conf["buttons"], num)
  20. else:
  21. b = ""
  22. return fmt.format(
  23. __timestamp__=timestamp, __num__=num, __msg__=msg, __btn__=b)
  24. def make_gallery(indices, w, conf=None):
  25. tag = []
  26. if indices == []:
  27. return tag
  28. template = '''
  29. <div class=\"panel\">
  30. <a href=\"%s\"><img src=\"%s\" class=\"embed\"></a>
  31. </div>
  32. '''
  33. tag.append("<div class=\"gallery\">")
  34. for index in reversed(indices):
  35. image = w.pop(index)
  36. is_path = image[0] == '.' or image[0] == '/'
  37. if conf and not is_path:
  38. thumb = "%s/%s" % (conf["path_to_thumb"], image)
  39. full = "%s/%s" % (conf["path_to_fullsize"], image)
  40. tag.append(template % (full,thumb))
  41. continue
  42. elif not conf and not is_path:
  43. msg = ("Warning: no path defined for image %s!" % image)
  44. print(msg,file=sys.stderr)
  45. else:
  46. pass
  47. tag.append(template % (image, image))
  48. tag.append("</div>")
  49. return tag
  50. def markup(message, config):
  51. def is_image(s, image_formats):
  52. l = s.rsplit('.', maxsplit=1)
  53. if len(l) < 2:
  54. return False
  55. # Python 3.10.5
  56. # example result that had to be filtered:
  57. # string: started.
  58. # result: ['started', '']
  59. if l[1] == str(''):
  60. return False
  61. #print(s, l, file=sys.stderr)
  62. if l[1] in image_formats:
  63. return True
  64. return False
  65. result = 0
  66. tagged = ""
  67. # support multiple images (gallery style)
  68. tags = [] # list of strings
  69. output = []
  70. gallery = []
  71. ptags = config["tag_paragraphs"]
  72. sep = ""
  73. if "line_separator" in config:
  74. sep = config["line_separator"]
  75. for line in message:
  76. images = [] # list of integers
  77. words = line.split()
  78. for i in range(len(words)):
  79. word = words[i]
  80. # don't help people click http
  81. if word.find("src=") == 0 or word.find("href=") == 0:
  82. continue
  83. elif word.find("https://") != -1:
  84. w = escape(word)
  85. new_word = ("<a href=\"%s\">%s</a>") % (w, w)
  86. words[i] = new_word
  87. elif word.find("#") != -1 and len(word) > 1:
  88. # split by unicode blank character if present
  89. # allows tagging such as #fanfic|tion
  90. w = word.split(chr(8206))
  91. # w[0] is the portion closest to the #
  92. tags.append(w[0])
  93. new_word = "<span class=\"hashtag\">%s</span>" % (w[0])
  94. if len(w) > 1:
  95. new_word += w[1]
  96. words[i] = new_word
  97. elif is_image(word, config["accepted_images"]):
  98. images.append(i)
  99. if len(images) > 0:
  100. # function invokes pop() which modifies list 'words'
  101. gc = config["gallery"] if "gallery" in config else None
  102. gallery = make_gallery(images, words, gc)
  103. if ptags and len(words) > 0:
  104. words.insert(0,"<p>")
  105. words.append("</p>")
  106. output.append(" ".join(words))
  107. # avoid paragraph with an image gallery
  108. if len(gallery) > 0:
  109. output.append("".join(gallery))
  110. gallery = []
  111. return sep.join(output), tags
  112. # apply basic HTML formatting - only div class here is gallery
  113. from html import escape
  114. class Post:
  115. def __init__(self, ts, msg):
  116. self.timestamp = ts.strip() # string
  117. self.message = msg # list
  118. # format used for sorting
  119. def get_epoch_time(self):
  120. t = dateutil.parser.parse(self.timestamp)
  121. return int(t.timestamp())
  122. # format used for display
  123. def get_short_time(self):
  124. t = dateutil.parser.parse(self.timestamp)
  125. return t.strftime("%y %b %d")
  126. def parse_txt(filename):
  127. content = []
  128. with open(filename, 'r') as f:
  129. content = f.readlines()
  130. posts = [] # list of posts - same order as file
  131. message = [] # list of lines
  132. # {-1 = init;; 0 = timestamp is next, 1 = message is next}
  133. state = -1
  134. timestamp = ""
  135. for line in content:
  136. if state == -1:
  137. state = 0
  138. continue
  139. elif state == 0:
  140. timestamp = line
  141. state = 1
  142. elif state == 1:
  143. if len(line) > 1:
  144. message.append(line)
  145. else:
  146. p = Post(timestamp, message)
  147. posts.append(p)
  148. # reset
  149. message = []
  150. state = 0
  151. return posts
  152. def get_posts(filename, config):
  153. posts = parse_txt(filename)
  154. taginfos = []
  155. tagcloud = dict() # (tag, count)
  156. tagged = dict() # (tag, index of message)
  157. total = len(posts)
  158. count = total
  159. index = count # - 1
  160. timeline = []
  161. btns = None
  162. for post in posts:
  163. markedup, tags = markup(post.message, config)
  164. count -= 1
  165. index -= 1
  166. timeline.append(
  167. make_post(count, post.get_short_time(), config, markedup)
  168. )
  169. for tag in tags:
  170. if tagcloud.get(tag) == None:
  171. tagcloud[tag] = 0
  172. tagcloud[tag] += 1
  173. if tagged.get(tag) == None:
  174. tagged[tag] = []
  175. tagged[tag].append(index)
  176. return timeline, tagcloud, tagged
  177. def make_tagcloud(d, rell):
  178. sorted_d = {k: v for k,
  179. v in sorted(d.items(),
  180. key=lambda item: -item[1])}
  181. output = []
  182. fmt = "<span class=\"hashtag\"><a href=\"%s\">%s(%i)</a></span>"
  183. #fmt = "<span class=\"hashtag\">%s(%i)</span>"
  184. for key in d.keys():
  185. link = rell % key[1:]
  186. output.append(fmt % (link, key, d[key]))
  187. return output
  188. class Paginator:
  189. def __init__(self, post_count, ppp, loc=None):
  190. if post_count <= 0:
  191. raise Exception
  192. if not loc:
  193. loc = "pages"
  194. if loc and not os.path.exists(loc):
  195. os.mkdir(loc)
  196. self.TOTAL_POSTS = post_count
  197. self.PPP = ppp
  198. self.TOTAL_PAGES = int(post_count/self.PPP)
  199. self.SUBDIR = loc
  200. self.FILENAME = "%i.html"
  201. self.written = []
  202. def toc(self, current_page=None, path=None): #style 1
  203. if self.TOTAL_PAGES < 1:
  204. return "[no pages]"
  205. if path == None:
  206. path = self.SUBDIR
  207. # For page 'n' do not create an anchor tag
  208. fmt = "<a href=\"%s\">[%i]</a>" #(filename, page number)
  209. anchors = []
  210. for i in reversed(range(self.TOTAL_PAGES)):
  211. if i != current_page:
  212. x = path + "/" + (self.FILENAME % i)
  213. anchors.append(fmt % (x, i))
  214. else:
  215. anchors.append("<b>[%i]</b>" % i)
  216. return "\n".join(anchors)
  217. # makes one page
  218. def singlepage(self, template, tagcloud, timeline_, i=None, p=None):
  219. tc = "\n".join(tagcloud)
  220. tl = "\n\n".join(timeline_)
  221. toc = self.toc(i, p)
  222. return template.format(
  223. postcount=self.TOTAL_POSTS, tags=tc, pages=toc, timeline=tl
  224. )
  225. def paginate(self, template, tagcloud, timeline, is_tagline=False):
  226. outfile = "%s/%s" % (self.SUBDIR, self.FILENAME)
  227. timeline.reverse() # reorder from oldest to newest
  228. start = 0
  229. for i in range(start, self.TOTAL_PAGES):
  230. fn = outfile % i
  231. with open(fn, 'w') as f:
  232. self.written.append(fn)
  233. prev = self.PPP * i
  234. curr = self.PPP * (i+1)
  235. sliced = timeline[prev:curr]
  236. sliced.reverse()
  237. f.write(self.singlepage(template, tagcloud, sliced, i, "."))
  238. return
  239. import argparse
  240. if __name__ == "__main__":
  241. def sort(filename):
  242. def export(new_content, new_filename):
  243. with open(new_filename, 'w') as f:
  244. print(file=f)
  245. for post in new_content:
  246. print(post.timestamp, file=f)
  247. print("".join(post.message), file=f)
  248. return
  249. posts = parse_txt(filename)
  250. posts.sort(key=lambda e: e.get_epoch_time())
  251. outfile = ("%s.sorted" % filename)
  252. print("Sorted text written to ", outfile)
  253. export(reversed(posts), outfile)
  254. def get_args():
  255. p = argparse.ArgumentParser()
  256. p.add_argument("template", help="an html template file")
  257. p.add_argument("content", help="text file for microblog content")
  258. p.add_argument("--sort", \
  259. help="sorts content from oldest to newest"
  260. " (this is a separate operation from page generation)", \
  261. action="store_true")
  262. args = p.parse_args()
  263. if args.sort:
  264. sort(args.content)
  265. exit()
  266. return args.template, args.content
  267. # assume relative path
  268. def demote_css(template, css_list, level=1):
  269. prepend = ""
  270. if level == 1:
  271. prepend = '.'
  272. else:
  273. for i in range(level):
  274. prepend = ("../%s" % prepend)
  275. tpl = template
  276. for css in css_list:
  277. tpl = tpl.replace(css, ("%s%s" % (prepend, css) ))
  278. return tpl
  279. # needs review / clean-up
  280. # ideally relate 'lvl' with sub dir instead of hardcoding
  281. def writepage(template, timeline, tagcloud, config, subdir = None):
  282. html = ""
  283. with open(template,'r') as f:
  284. html = f.read()
  285. try:
  286. count = len(timeline)
  287. p = config["postsperpage"]
  288. pagectrl = Paginator(count, p, subdir)
  289. except ZeroDivisionError as e:
  290. print("error: ",e, ". check 'postsperpage' in config", file=sys.stderr)
  291. exit()
  292. except Exception as e:
  293. print("error: ",e, ("(number of posts = %i)" % count), file=sys.stderr)
  294. exit()
  295. latest = timeline if count <= pagectrl.PPP else timeline[:pagectrl.PPP]
  296. if subdir == None: # if top level page
  297. lvl = 1
  298. tcloud = make_tagcloud(tagcloud, "./tags/%s/latest.html")
  299. print(pagectrl.singlepage(html, tcloud, latest))
  300. tcloud = make_tagcloud(tagcloud, "../tags/%s/latest.html")
  301. pagectrl.paginate(
  302. demote_css(html, config["relative_css"], lvl),
  303. tcloud, timeline
  304. )
  305. else: # if timelines per tag
  306. is_tagline = True
  307. lvl = 2
  308. newhtml = demote_css(html, config["relative_css"], lvl)
  309. tcloud = make_tagcloud(tagcloud, "../%s/latest.html")
  310. fn = "%s/latest.html" % subdir
  311. with open(fn, 'w') as f:
  312. pagectrl.written.append(fn)
  313. f.write(
  314. pagectrl.singlepage(newhtml, tcloud, latest, p=".")
  315. )
  316. pagectrl.paginate(newhtml, tcloud, timeline, is_tagline)
  317. return pagectrl.written
  318. import toml
  319. def load_settings():
  320. s = dict()
  321. filename = "settings.toml"
  322. if os.path.exists(filename):
  323. with open(filename, 'r') as f:
  324. s = toml.loads(f.read())
  325. else:
  326. s = None
  327. return s
  328. def main():
  329. tpl, content = get_args()
  330. cfg = load_settings()
  331. if cfg == None:
  332. print("exit: no settings.toml found.", file=sys.stderr)
  333. return
  334. if "post" not in cfg:
  335. print("exit: table 'post' absent in settings.toml", file=sys.stderr)
  336. return
  337. if "page" not in cfg:
  338. print("exit: table 'page' absent in settings.toml", file=sys.stderr)
  339. return
  340. tl, tc, tg = get_posts(content, cfg["post"])
  341. if tl == []:
  342. return
  343. # main timeline
  344. updated = []
  345. updated += writepage(tpl, tl, tc, cfg["page"])
  346. # timeline per tag
  347. if tc != dict() and tg != dict():
  348. if not os.path.exists("tags"):
  349. os.mkdir("tags")
  350. for key in tg.keys():
  351. tagline = []
  352. for index in tg[key]:
  353. tagline.append(tl[index])
  354. # [1:] means to omit hashtag from dir name
  355. updated += writepage(
  356. tpl, tagline, tc, cfg["page"], \
  357. subdir="tags/%s" % key[1:] \
  358. )
  359. with open("updatedfiles.txt", 'w') as f:
  360. for filename in updated:
  361. print(filename, file=f) # sys.stderr)
  362. if "latestpage" in cfg:
  363. print(cfg["latestpage"], file=f)
  364. try:
  365. main()
  366. except KeyError as e:
  367. traceback.print_exc()
  368. print("\n\tA key may be missing from your settings file.", file=sys.stderr)
  369. except dateutil.parser._parser.ParserError as e:
  370. traceback.print_exc()
  371. print("\n\tFailed to interpret a date from string..",
  372. "\n\tYour file of posts may be malformed.",
  373. "\n\tCheck if your file starts with a line break.", file=sys.stderr)