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 17KB

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