My static website generator using poole https://www.xythobuz.de
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

macros.py 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. # -*- coding: utf-8 -*-
  2. import re
  3. import itertools
  4. import email.utils
  5. import os.path
  6. import time
  7. import codecs
  8. from datetime import datetime
  9. DEFAULT_LANG = "en"
  10. BASE_URL = "https://www.xythobuz.de"
  11. # -----------------------------------------------------------------------------
  12. # sub page helper macro
  13. # -----------------------------------------------------------------------------
  14. def backToParent():
  15. url = page.get("parent", "") + ".html"
  16. posts = [p for p in pages if p.url == url]
  17. if len(posts) > 0:
  18. p = posts[0]
  19. print '<span class="listdesc">[...back to ' + p.title + ' overview](' + p.url + ')</span>'
  20. # -----------------------------------------------------------------------------
  21. # table helper macro
  22. # -----------------------------------------------------------------------------
  23. def tableHelper(style, header, content):
  24. print "<table>"
  25. if (header != None) and (len(header) == len(style)):
  26. print "<tr>"
  27. for h in header:
  28. print "<th>" + h + "</th>"
  29. print "</tr>"
  30. for ci in range(0, len(content)):
  31. if len(content[ci]) != len(style):
  32. # invalid call of table helper!
  33. continue
  34. print "<tr>"
  35. for i in range(0, len(style)):
  36. s = style[i]
  37. if "align-last-right" in s:
  38. if ci == (len(content) - 1):
  39. print "<td style=\"text-align: right;\">"
  40. else:
  41. if "align-center" in s:
  42. print "<td style=\"text-align: center;\">"
  43. else:
  44. print "<td>"
  45. elif "align-right" in s:
  46. print "<td style=\"text-align: right;\">"
  47. elif "align-center" in s:
  48. print "<td style=\"text-align: center;\">"
  49. else:
  50. print "<td>"
  51. if isinstance(content[ci][i], tuple):
  52. text, link = content[ci][i]
  53. print "<a href=\"" + link + "\">" + text + "</a>"
  54. else:
  55. text = content[ci][i]
  56. print text
  57. print "</td>"
  58. print "</tr>"
  59. print "</table>"
  60. # -----------------------------------------------------------------------------
  61. # menu helper macro
  62. # -----------------------------------------------------------------------------
  63. def printMenuItem(p, yearsAsHeading = False, showDateSpan = False, showOnlyStartDate = False, nicelyFormatFullDate = False, lastyear = "0", lang = ""):
  64. title = p.title
  65. if lang != "":
  66. if p.get("title_" + lang, "") != "":
  67. title = p.get("title_" + lang, "")
  68. if p.title == "Blog":
  69. title = p.post
  70. year = p.get("date", "")[0:4]
  71. if year != lastyear:
  72. lastyear = year
  73. if yearsAsHeading:
  74. print "\n\n#### %s\n" % (year)
  75. dateto = ""
  76. if p.get("date", "" != ""):
  77. year = p.get("date", "")[0:4]
  78. if showOnlyStartDate:
  79. dateto = " (%s)" % (year)
  80. if p.get("update", "") != "" and p.get("update", "")[0:4] != year:
  81. if showDateSpan:
  82. dateto = " (%s - %s)" % (year, p.get("update", "")[0:4])
  83. if nicelyFormatFullDate:
  84. dateto = " - " + datetime.strptime(p.date, "%Y-%m-%d").strftime("%B %d, %Y")
  85. print " * **[%s](%s)**%s" % (title, p.url, dateto)
  86. if p.get("description", "") != "":
  87. description = p.get("description", "")
  88. if lang != "":
  89. if p.get("description_" + lang, "") != "":
  90. description = p.get("description_" + lang, "")
  91. print "<br><span class=\"listdesc\">" + description + "</span>"
  92. return lastyear
  93. def printRecentMenu(count = 5):
  94. posts = [p for p in pages if "date" in p]
  95. posts.sort(key=lambda p: p.get("date"), reverse=True)
  96. for p in posts[0:count]:
  97. printMenuItem(p, False, False, False, True)
  98. def printBlogMenu():
  99. posts = [p for p in pages if "post" in p]
  100. posts.sort(key=lambda p: p.get("date", "9999-01-01"), reverse=True)
  101. lastyear = "0"
  102. for p in posts:
  103. lastyear = printMenuItem(p, True, False, False, True, lastyear)
  104. def printProjectsMenu():
  105. # prints all pages with parent 'projects' or 'stuff'.
  106. # first the ones without date, sorted by position.
  107. # then afterwards those with date, split by year.
  108. # also supports blog posts with parent.
  109. enpages = [p for p in pages if p.lang == "en"]
  110. dpages = [p for p in enpages if p.get("date", "") == ""]
  111. mpages = [p for p in dpages if any(x in p.get("parent", "") for x in [ 'projects', 'stuff' ])]
  112. mpages.sort(key=lambda p: [int(p.get("position", "999"))])
  113. for p in mpages:
  114. printMenuItem(p)
  115. dpages = [p for p in enpages if p.get("date", "") != ""]
  116. mpages = [p for p in dpages if any(x in p.get("parent", "") for x in [ 'projects', 'stuff' ])]
  117. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  118. lastyear = "0"
  119. for p in mpages:
  120. lastyear = printMenuItem(p, True, True, False, False, lastyear)
  121. def print3DPrintingMenu():
  122. mpages = [p for p in pages if p.get("parent", "") == "3d-printing" and p.lang == "en"]
  123. mpages.sort(key=lambda p: int(p["position"]))
  124. for p in mpages:
  125. printMenuItem(p, False, True, True)
  126. def printQuadcopterMenu():
  127. mpages = [p for p in pages if p.get("parent", "") == "quadcopters" and p.lang == "en"]
  128. mpages.sort(key=lambda p: int(p["position"]))
  129. for p in mpages:
  130. printMenuItem(p, False, True, True)
  131. def printQuadcopterRelatedMenu():
  132. mpages = [p for p in pages if p.get("show_in_quadcopters", "false") == "true"]
  133. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  134. for p in mpages:
  135. printMenuItem(p, False, True, True)
  136. def printRobotMenuEnglish():
  137. mpages = [p for p in pages if p.get("parent", "") == "xyrobot" and p.lang == "en"]
  138. mpages.sort(key=lambda p: int(p["position"]))
  139. for p in mpages:
  140. printMenuItem(p)
  141. def printRobotMenuDeutsch():
  142. mpages = [p for p in pages if p.get("parent", "") == "xyrobot" and p.lang == "de"]
  143. mpages.sort(key=lambda p: int(p["position"]))
  144. for p in mpages:
  145. printMenuItem(p, False, False, False, False, "0", "de")
  146. # -----------------------------------------------------------------------------
  147. # lightgallery helper macro
  148. # -----------------------------------------------------------------------------
  149. # call this macro like this
  150. # lightgallery([
  151. # [ "image-link", "description" ],
  152. # [ "image-link", "thumbnail-link", "description" ],
  153. # [ "youtube-link", "thumbnail-link", "description" ],
  154. # [ "video-link", "mime", "thumbnail-link", "image-link", "description" ]
  155. # ])
  156. def lightgallery(links):
  157. videos = [l for l in links if len(l) == 5]
  158. v_i = 0
  159. for v in videos:
  160. link, mime, thumb, poster, alt = v
  161. v_i += 1
  162. print '<div style="display:none;" id="video' + str(v_i) + '">'
  163. print '<video class="lg-video-object lg-html5" controls preload="none">'
  164. print '<source src="' + link + '" type="' + mime + '">'
  165. print 'Your browser does not support HTML5 video.'
  166. print '</video>'
  167. print '</div>'
  168. print '<div class="lightgallery">'
  169. v_i = 0
  170. for l in links:
  171. if (len(l) == 3) or (len(l) == 2):
  172. link = img = alt = ""
  173. if len(l) == 3:
  174. link, img, alt = l
  175. else:
  176. link, alt = l
  177. x = link.rfind('.')
  178. img = link[:x] + '_small' + link[x:]
  179. print '<div class="border" data-src="' + link + '"><a href="' + link + '"><img class="pic" src="' + img + '" alt="' + alt + '"></a></div>'
  180. elif len(l) == 5:
  181. v_i += 1
  182. link, mime, thumb, poster, alt = v
  183. print '<div class="border" data-poster="' + poster + '" data-sub-html="' + alt + '" data-html="#video' + str(v_i) + '"><a href="' + link + '"><img class="pic" src="' + thumb + '"></a></div>'
  184. else:
  185. raise NameError('Invalid number of arguments for lightgallery')
  186. print '</div>'
  187. # -----------------------------------------------------------------------------
  188. # github helper macros
  189. # -----------------------------------------------------------------------------
  190. import urllib, json
  191. def restRequest(url):
  192. response = urllib.urlopen(url)
  193. data = json.loads(response.read())
  194. return data
  195. def restReleases(user, repo):
  196. s = "https://api.github.com/repos/"
  197. s += user
  198. s += "/"
  199. s += repo
  200. s += "/releases"
  201. return restRequest(s)
  202. def printLatestRelease(user, repo):
  203. repo_url = "https://github.com/" + user + "/" + repo
  204. print("<div class=\"releasecard\">")
  205. print("Release builds for " + repo + " are <a href=\"" + repo_url + "/releases\">available on GitHub</a>.<br>\n")
  206. releases = restReleases(user, repo)
  207. if len(releases) <= 0:
  208. print("No release has been published on GitHub yet.")
  209. print("</div>")
  210. return
  211. releases.sort(key=lambda x: x["published_at"], reverse=True)
  212. r = releases[0]
  213. release_url = r["html_url"]
  214. print("Latest release of <a href=\"" + repo_url + "\">" + repo + "</a>, at the time of this writing: <a href=\"" + release_url + "\">" + r["name"] + "</a> (" + datetime.strptime(r["published_at"], "%Y-%m-%dT%H:%M:%SZ").strftime("%Y-%m-%d %H:%M:%S") + ")\n")
  215. if len(r["assets"]) <= 0:
  216. print("<br>No release assets have been published on GitHub for that.")
  217. print("</div>")
  218. return
  219. print("<ul>")
  220. print("Release Assets:")
  221. for a in r["assets"]:
  222. size = int(a["size"])
  223. ss = " "
  224. if size >= (1024 * 1024):
  225. ss += "(%.1f MiB)" % (size / (1024.0 * 1024.0))
  226. elif size >= 1024:
  227. ss += "(%d KiB)" % (size // 1024)
  228. else:
  229. ss += "(%d Byte)" % (size)
  230. print("<li><a href=\"" + a["browser_download_url"] + "\">" + a["name"] + "</a>" + ss)
  231. print("</ul></div>")
  232. # -----------------------------------------------------------------------------
  233. # preconvert hooks
  234. # -----------------------------------------------------------------------------
  235. def hook_preconvert_anotherlang():
  236. MKD_PATT = r'\.(?:md|mkd|mdown|markdown)$'
  237. _re_lang = re.compile(r'^[\s+]?lang[\s+]?[:=]((?:.|\n )*)', re.MULTILINE)
  238. vpages = [] # Set of all virtual pages
  239. for p in pages:
  240. current_lang = DEFAULT_LANG # Default language
  241. langs = [] # List of languages for the current page
  242. page_vpages = {} # Set of virtual pages for the current page
  243. text_lang = re.split(_re_lang, p.source)
  244. text_grouped = dict(zip([current_lang,] + \
  245. [lang.strip() for lang in text_lang[1::2]], \
  246. text_lang[::2]))
  247. for lang, text in text_grouped.iteritems():
  248. spath = p.fname.split(os.path.sep)
  249. langs.append(lang)
  250. if lang == "en":
  251. filename = re.sub(MKD_PATT, "%s\g<0>" % "", p.fname).split(os.path.sep)[-1]
  252. else:
  253. filename = re.sub(MKD_PATT, ".%s\g<0>" % lang, p.fname).split(os.path.sep)[-1]
  254. vp = Page(filename, virtual=text)
  255. # Copy real page attributes to the virtual page
  256. for attr in p:
  257. if not vp.has_key(attr):
  258. vp[attr] = p[attr]
  259. # Define a title in the proper language
  260. vp["title"] = p["title_%s" % lang] \
  261. if p.has_key("title_%s" % lang) \
  262. else p["title"]
  263. # Keep track of the current lang of the virtual page
  264. vp["lang"] = lang
  265. # Fix post name if exists
  266. if vp.has_key("post"):
  267. if lang == "en":
  268. vp["post"] = vp["post"][:]
  269. else:
  270. vp["post"] = vp["post"][:-len(lang) - 1]
  271. page_vpages[lang] = vp
  272. # Each virtual page has to know about its sister vpages
  273. for lang, vpage in page_vpages.iteritems():
  274. vpage["lang_links"] = dict([(l, v["url"]) for l, v in page_vpages.iteritems()])
  275. vpage["other_lang"] = langs # set other langs and link
  276. vpages += page_vpages.values()
  277. pages[:] = vpages
  278. _COMPAT = """ case "%s":
  279. $loc = "%s/%s";
  280. break;
  281. """
  282. _COMPAT_404 = """ default:
  283. $loc = "%s";
  284. break;
  285. """
  286. def hook_preconvert_compat():
  287. fp = open(os.path.join(options.project, "output", "index.php"), 'w')
  288. fp.write("<?\n")
  289. fp.write("// Auto generated xyCMS compatibility index.php\n")
  290. fp.write("$loc = 'https://www.xythobuz.de/index.de.html';\n")
  291. fp.write("if (isset($_GET['p'])) {\n")
  292. fp.write(" if (isset($_GET['lang'])) {\n")
  293. fp.write(" $_GET['p'] .= 'EN';\n")
  294. fp.write(" }\n")
  295. fp.write(" switch($_GET['p']) {\n")
  296. for p in pages:
  297. if p.get("compat", "") != "":
  298. tmp = p["compat"]
  299. if p.get("lang", DEFAULT_LANG) == DEFAULT_LANG:
  300. tmp = tmp + "EN"
  301. fp.write(_COMPAT % (tmp, "https://www.xythobuz.de", p.url))
  302. fp.write("\n")
  303. fp.write(_COMPAT_404 % "/404.html")
  304. fp.write(" }\n")
  305. fp.write("}\n")
  306. fp.write("if ($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {\n")
  307. fp.write(" if (php_sapi_name() == 'cgi') {\n")
  308. fp.write(" header('Status: 301 Moved Permanently');\n")
  309. fp.write(" } else {\n")
  310. fp.write(" header('HTTP/1.1 301 Moved Permanently');\n")
  311. fp.write(" }\n")
  312. fp.write("}\n");
  313. fp.write("header('Location: '.$loc);\n")
  314. fp.write("?>")
  315. fp.close()
  316. _SITEMAP = """<?xml version="1.0" encoding="UTF-8"?>
  317. <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  318. %s
  319. </urlset>
  320. """
  321. _SITEMAP_URL = """
  322. <url>
  323. <loc>%s/%s</loc>
  324. <lastmod>%s</lastmod>
  325. <changefreq>%s</changefreq>
  326. <priority>%s</priority>
  327. </url>
  328. """
  329. def hook_preconvert_sitemap():
  330. date = datetime.strftime(datetime.now(), "%Y-%m-%d")
  331. urls = []
  332. for p in pages:
  333. urls.append(_SITEMAP_URL % (BASE_URL, p.url, date, p.get("changefreq", "monthly"), p.get("priority", "0.5")))
  334. fname = os.path.join(options.project, "output", "sitemap.xml")
  335. fp = open(fname, 'w')
  336. fp.write(_SITEMAP % "".join(urls))
  337. fp.close()
  338. # -----------------------------------------------------------------------------
  339. # postconvert hooks
  340. # -----------------------------------------------------------------------------
  341. _RSS = """<?xml version="1.0"?>
  342. <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  343. <channel>
  344. <title>%s</title>
  345. <link>%s</link>
  346. <atom:link href="%s" rel="self" type="application/rss+xml" />
  347. <description>%s</description>
  348. <language>en-us</language>
  349. <pubDate>%s</pubDate>
  350. <lastBuildDate>%s</lastBuildDate>
  351. <docs>http://blogs.law.harvard.edu/tech/rss</docs>
  352. <generator>Poole</generator>
  353. %s
  354. </channel>
  355. </rss>
  356. """
  357. _RSS_ITEM = """
  358. <item>
  359. <title>%s</title>
  360. <link>%s</link>
  361. <description>%s</description>
  362. <pubDate>%s</pubDate>
  363. <guid>%s</guid>
  364. </item>
  365. """
  366. def hook_postconvert_rss():
  367. items = []
  368. posts = [p for p in pages if "date" in p]
  369. posts.sort(key=lambda p: p.date, reverse=True)
  370. posts = posts[:10]
  371. for p in posts:
  372. title = p.title
  373. if "post" in p:
  374. title = p.post
  375. link = "%s/%s" % (BASE_URL, p.url)
  376. desc = p.html.replace("href=\"img", "%s%s%s" % ("href=\"", BASE_URL, "/img"))
  377. desc = desc.replace("src=\"img", "%s%s%s" % ("src=\"", BASE_URL, "/img"))
  378. desc = desc.replace("href=\"/img", "%s%s%s" % ("href=\"", BASE_URL, "/img"))
  379. desc = desc.replace("src=\"/img", "%s%s%s" % ("src=\"", BASE_URL, "/img"))
  380. desc = htmlspecialchars(desc)
  381. date = time.mktime(time.strptime("%s 12" % p.date, "%Y-%m-%d %H"))
  382. date = email.utils.formatdate(date)
  383. items.append(_RSS_ITEM % (title, link, desc, date, link))
  384. items = "".join(items)
  385. title = "xythobuz.de Blog"
  386. link = "%s" % BASE_URL
  387. feed = "%s/rss.xml" % BASE_URL
  388. desc = htmlspecialchars("xythobuz Electronics & Software Projects")
  389. date = email.utils.formatdate()
  390. rss = _RSS % (title, link, feed, desc, date, date, items)
  391. fp = codecs.open(os.path.join(output, "rss.xml"), "w", "utf-8")
  392. fp.write(rss)
  393. fp.close()
  394. _COMPAT_MOB = """ case "%s":
  395. $loc = "%s/%s";
  396. break;
  397. """
  398. _COMPAT_404_MOB = """ default:
  399. $loc = "%s";
  400. break;
  401. """
  402. def hook_postconvert_mobilecompat():
  403. directory = os.path.join(output, "mobile")
  404. if not os.path.exists(directory):
  405. os.makedirs(directory)
  406. fp = codecs.open(os.path.join(directory, "index.php"), "w", "utf-8")
  407. fp.write("<?\n")
  408. fp.write("// Auto generated xyCMS compatibility mobile/index.php\n")
  409. fp.write("$loc = 'https://www.xythobuz.de/index.de.html';\n")
  410. fp.write("if (isset($_GET['p'])) {\n")
  411. fp.write(" if (isset($_GET['lang'])) {\n")
  412. fp.write(" $_GET['p'] .= 'EN';\n")
  413. fp.write(" }\n")
  414. fp.write(" switch($_GET['p']) {\n")
  415. for p in pages:
  416. if p.get("compat", "") != "":
  417. tmp = p["compat"]
  418. if p.get("lang", DEFAULT_LANG) == DEFAULT_LANG:
  419. tmp = tmp + "EN"
  420. fp.write(_COMPAT_MOB % (tmp, "https://www.xythobuz.de", re.sub(".html", ".html", p.url)))
  421. fp.write("\n")
  422. fp.write(_COMPAT_404_MOB % "/404.mob.html")
  423. fp.write(" }\n")
  424. fp.write("}\n")
  425. fp.write("if ($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {\n")
  426. fp.write(" if (php_sapi_name() == 'cgi') {\n")
  427. fp.write(" header('Status: 301 Moved Permanently');\n")
  428. fp.write(" } else {\n")
  429. fp.write(" header('HTTP/1.1 301 Moved Permanently');\n")
  430. fp.write(" }\n")
  431. fp.write("}\n");
  432. fp.write("header('Location: '.$loc);\n")
  433. fp.write("?>")
  434. fp.close()
  435. def hook_postconvert_size():
  436. file_ext = '|'.join(['pdf', 'zip', 'rar', 'ods', 'odt', 'odp', 'doc', 'xls', 'ppt', 'docx', 'xlsx', 'pptx', 'exe', 'brd', 'mp3', 'mp4', 'plist'])
  437. def matched_link(matchobj):
  438. try:
  439. path = matchobj.group(1)
  440. if path.startswith("http") or path.startswith("//") or path.startswith("ftp"):
  441. return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
  442. elif path.startswith("/"):
  443. path = path.strip("/")
  444. path = os.path.join("static/", path)
  445. size = os.path.getsize(path)
  446. if size >= (1024 * 1024):
  447. return "<a href=\"%s\">%s</a>&nbsp;(%.1f MiB)" % (matchobj.group(1), matchobj.group(3), size / (1024.0 * 1024.0))
  448. elif size >= 1024:
  449. return "<a href=\"%s\">%s</a>&nbsp;(%d KiB)" % (matchobj.group(1), matchobj.group(3), size // 1024)
  450. else:
  451. return "<a href=\"%s\">%s</a>&nbsp;(%d Byte)" % (matchobj.group(1), matchobj.group(3), size)
  452. except:
  453. print "Unable to estimate file size for %s" % matchobj.group(1)
  454. return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
  455. _re_url = '<a href=\"([^\"]*?\.(%s))\">(.*?)<\/a>' % file_ext
  456. for p in pages:
  457. p.html = re.sub(_re_url, matched_link, p.html)