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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. # -*- coding: utf-8 -*-
  2. from __future__ import print_function
  3. import sys
  4. import re
  5. import itertools
  6. import email.utils
  7. import os.path
  8. import time
  9. import codecs
  10. from datetime import datetime
  11. DEFAULT_LANG = "en"
  12. BASE_URL = "https://www.xythobuz.de"
  13. # =============================================================================
  14. # Python 2/3 hacks
  15. # =============================================================================
  16. PY3 = sys.version_info[0] == 3
  17. if PY3:
  18. import urllib
  19. import urllib.request
  20. def urlparse_foo(link):
  21. return urllib.parse.parse_qs(urllib.parse.urlparse(link).query)['v'][0]
  22. else:
  23. import urllib
  24. import urlparse
  25. def urlparse_foo(link):
  26. return urlparse.parse_qs(urlparse.urlparse(link).query)['v'][0]
  27. # -----------------------------------------------------------------------------
  28. # sub page helper macro
  29. # -----------------------------------------------------------------------------
  30. def backToParent():
  31. # check for special parent cases
  32. posts = []
  33. if page.get("show_in_quadcopters", "false") == "true":
  34. posts = [p for p in pages if p.url == "quadcopters.html"]
  35. # if not, check for actual parent
  36. if len(posts) == 0:
  37. url = page.get("parent", "") + ".html"
  38. posts = [p for p in pages if p.url == url]
  39. # print if any parent link found
  40. if len(posts) > 0:
  41. p = posts[0]
  42. print('<span class="listdesc">[...back to ' + p.title + ' overview](' + p.url + ')</span>')
  43. # -----------------------------------------------------------------------------
  44. # table helper macro
  45. # -----------------------------------------------------------------------------
  46. def tableHelper(style, header, content):
  47. print("<table>")
  48. if (header != None) and (len(header) == len(style)):
  49. print("<tr>")
  50. for h in header:
  51. print("<th>" + h + "</th>")
  52. print("</tr>")
  53. for ci in range(0, len(content)):
  54. if len(content[ci]) != len(style):
  55. # invalid call of table helper!
  56. continue
  57. print("<tr>")
  58. for i in range(0, len(style)):
  59. s = style[i]
  60. td_style = ""
  61. if "monospaced" in s:
  62. td_style += " font-family: monospace;"
  63. if "align-last-right" in s:
  64. if ci == (len(content) - 1):
  65. td_style += " text-align: right;"
  66. else:
  67. if "align-center" in s:
  68. td_style += " text-align: center;"
  69. elif "align-right" in s:
  70. td_style += " text-align: right;"
  71. elif "align-center" in s:
  72. td_style += " text-align: center;"
  73. td_args = ""
  74. if td_style != "":
  75. td_args = " style=\"" + td_style + "\""
  76. print("<td" + td_args + ">")
  77. if isinstance(content[ci][i], tuple):
  78. text, link = content[ci][i]
  79. print("<a href=\"" + link + "\">" + text + "</a>")
  80. else:
  81. text = content[ci][i]
  82. print(text)
  83. print("</td>")
  84. print("</tr>")
  85. print("</table>")
  86. # -----------------------------------------------------------------------------
  87. # menu helper macro
  88. # -----------------------------------------------------------------------------
  89. def githubCommitBadge(p, showInline = False):
  90. ret = ""
  91. if p.get("github", "") != "":
  92. link = p.get("git", p.github)
  93. linkParts = p.github.split("/")
  94. if len(linkParts) >= 5:
  95. ret += "<a href=\"" + link + "\"><img "
  96. if showInline:
  97. ret += "style =\"vertical-align: middle; padding-bottom: 0.25em;\" "
  98. ret += "src=\"https://img.shields.io/github/last-commit/"
  99. ret += linkParts[3] + "/" + linkParts[4]
  100. ret += ".svg?logo=git&style=flat\" /></a>"
  101. return ret
  102. def printMenuItem(p, yearsAsHeading = False, showDateSpan = False, showOnlyStartDate = False, nicelyFormatFullDate = False, lastyear = "0", lang = "", showLastCommit = True):
  103. title = p.title
  104. if lang != "":
  105. if p.get("title_" + lang, "") != "":
  106. title = p.get("title_" + lang, "")
  107. if title == "Blog":
  108. title = p.post
  109. year = p.get("date", "")[0:4]
  110. if year != lastyear:
  111. lastyear = year
  112. if yearsAsHeading:
  113. print("\n\n#### %s\n" % (year))
  114. dateto = ""
  115. if p.get("date", "" != ""):
  116. year = p.get("date", "")[0:4]
  117. if showOnlyStartDate:
  118. dateto = " (%s)" % (year)
  119. if p.get("update", "") != "" and p.get("update", "")[0:4] != year:
  120. if showDateSpan:
  121. dateto = " (%s - %s)" % (year, p.get("update", "")[0:4])
  122. if nicelyFormatFullDate:
  123. dateto = " - " + datetime.strptime(p.get("update", p.date), "%Y-%m-%d").strftime("%B %d, %Y")
  124. print(" * **[%s](%s)**%s" % (title, p.url, dateto))
  125. if p.get("description", "") != "":
  126. description = p.get("description", "")
  127. if lang != "":
  128. if p.get("description_" + lang, "") != "":
  129. description = p.get("description_" + lang, "")
  130. print("<br><span class=\"listdesc\">" + description + "</span>")
  131. if showLastCommit:
  132. link = githubCommitBadge(p)
  133. if len(link) > 0:
  134. print("<br>" + link)
  135. return lastyear
  136. def printRecentMenu(count = 5):
  137. posts = [p for p in pages if "date" in p and p.lang == "en"]
  138. posts.sort(key=lambda p: p.get("update", p.get("date")), reverse=True)
  139. if count > 0:
  140. posts = posts[0:count]
  141. for p in posts:
  142. printMenuItem(p, False, False, False, True, "0", "", False)
  143. def printBlogMenu():
  144. posts = [p for p in pages if "post" in p and p.lang == "en"]
  145. posts.sort(key=lambda p: p.get("date", "9999-01-01"), reverse=True)
  146. lastyear = "0"
  147. for p in posts:
  148. lastyear = printMenuItem(p, True, False, False, True, lastyear)
  149. def printProjectsMenu():
  150. # prints all pages with parent 'projects' or 'stuff'.
  151. # first the ones without date, sorted by position.
  152. # then afterwards those with date, split by year.
  153. # also supports blog posts with parent.
  154. enpages = [p for p in pages if p.lang == "en"]
  155. dpages = [p for p in enpages if p.get("date", "") == ""]
  156. mpages = [p for p in dpages if any(x in p.get("parent", "") for x in [ 'projects', 'stuff' ])]
  157. mpages.sort(key=lambda p: [int(p.get("position", "999"))])
  158. for p in mpages:
  159. printMenuItem(p)
  160. dpages = [p for p in enpages if p.get("date", "") != ""]
  161. mpages = [p for p in dpages if any(x in p.get("parent", "") for x in [ 'projects', 'stuff' ])]
  162. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  163. lastyear = "0"
  164. for p in mpages:
  165. lastyear = printMenuItem(p, True, True, False, False, lastyear)
  166. def print3DPrintingMenu():
  167. mpages = [p for p in pages if p.get("parent", "") == "3d-printing" and p.lang == "en"]
  168. mpages.sort(key=lambda p: int(p["position"]))
  169. for p in mpages:
  170. printMenuItem(p, False, True, True)
  171. def printInputDevicesMenu():
  172. mpages = [p for p in pages if p.get("parent", "") == "input_devices" and p.lang == "en"]
  173. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  174. for p in mpages:
  175. printMenuItem(p, False, True, True)
  176. def printInputDevicesRelatedMenu():
  177. mpages = [p for p in pages if p.get("show_in_input_devices", "false") == "true"]
  178. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  179. for p in mpages:
  180. printMenuItem(p, False, True, True)
  181. def printSmarthomeMenu():
  182. mpages = [p for p in pages if p.get("parent", "") == "smarthome" and p.lang == "en"]
  183. mpages.sort(key=lambda p: int(p["position"]))
  184. for p in mpages:
  185. printMenuItem(p, False, True, True)
  186. def printQuadcopterMenu():
  187. mpages = [p for p in pages if p.get("parent", "") == "quadcopters" and p.lang == "en"]
  188. mpages.sort(key=lambda p: int(p["position"]))
  189. for p in mpages:
  190. printMenuItem(p, False, True, True)
  191. def printQuadcopterRelatedMenu():
  192. mpages = [p for p in pages if p.get("show_in_quadcopters", "false") == "true"]
  193. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  194. for p in mpages:
  195. printMenuItem(p, False, True, True)
  196. def printRobotMenuEnglish():
  197. mpages = [p for p in pages if p.get("parent", "") == "xyrobot" and p.lang == "en"]
  198. mpages.sort(key=lambda p: int(p["position"]))
  199. for p in mpages:
  200. printMenuItem(p)
  201. def printRobotMenuDeutsch():
  202. mpages = [p for p in pages if p.get("parent", "") == "xyrobot" and p.lang == "de"]
  203. mpages.sort(key=lambda p: int(p["position"]))
  204. for p in mpages:
  205. printMenuItem(p, False, False, False, False, "0", "de")
  206. def printSteamMenuEnglish():
  207. mpages = [p for p in pages if p.get("parent", "") == "steam" and p.lang == "en"]
  208. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  209. for p in mpages:
  210. printMenuItem(p, False, False, False, True)
  211. def printSteamMenuDeutsch():
  212. # TODO show german pages, or english pages when german not available
  213. printSteamMenuEnglish()
  214. # -----------------------------------------------------------------------------
  215. # lightgallery helper macro
  216. # -----------------------------------------------------------------------------
  217. # call this macro like this:
  218. # lightgallery([
  219. # [ "image-link", "description" ],
  220. # [ "image-link", "thumbnail-link", "description" ],
  221. # [ "youtube-link", "thumbnail-link", "description" ],
  222. # [ "video-link", "mime", "thumbnail-link", "image-link", "description" ],
  223. # [ "video-link", "mime", "", "", "description" ],
  224. # ])
  225. # it will also auto-generate thumbnails and resize and strip EXIF from images
  226. # using the included web-image-resize script.
  227. # and it can generate video thumbnails and posters with the video-thumb script.
  228. def lightgallery_check_thumbnail(link, thumb):
  229. # only check local image links
  230. if not link.startswith('img/'):
  231. return
  232. # generate thumbnail filename web-image-resize will create
  233. x = link.rfind('.')
  234. img = link[:x] + '_small' + link[x:]
  235. # only run when desired thumb path matches calculated ones
  236. if thumb != img:
  237. return
  238. # generate fs path to images
  239. path = os.path.join(os.getcwd(), 'static', link)
  240. img = os.path.join(os.getcwd(), 'static', thumb)
  241. # no need to generate thumb again
  242. if os.path.exists(img):
  243. return
  244. # run web-image-resize to generate thumbnail
  245. script = os.path.join(os.getcwd(), 'web-image-resize')
  246. os.system(script + ' ' + path)
  247. def lightgallery_check_thumbnail_video(link, thumb, poster):
  248. # only check local image links
  249. if not link.startswith('img/'):
  250. return
  251. # generate thumbnail filenames video-thumb will create
  252. x = link.rfind('.')
  253. thumb_l = link[:x] + '_thumb.png'
  254. poster_l = link[:x] + '_poster.png'
  255. # only run when desired thumb path matches calculated ones
  256. if (thumb_l != thumb) or (poster_l != poster):
  257. return
  258. # generate fs path to images
  259. path = os.path.join(os.getcwd(), 'static', link)
  260. thumb_p = os.path.join(os.getcwd(), 'static', thumb)
  261. poster_p = os.path.join(os.getcwd(), 'static', poster)
  262. # no need to generate thumb again
  263. if os.path.exists(thumb_p) or os.path.exists(poster_p):
  264. return
  265. # run video-thumb to generate thumbnail
  266. script = os.path.join(os.getcwd(), 'video-thumb')
  267. os.system(script + ' ' + path)
  268. def lightgallery(links):
  269. global v_ii
  270. try:
  271. v_ii += 1
  272. except NameError:
  273. v_ii = 0
  274. videos = [l for l in links if len(l) == 5]
  275. v_i = -1
  276. for v in videos:
  277. link, mime, thumb, poster, alt = v
  278. v_i += 1
  279. print('<div style="display:none;" id="video' + str(v_i) + '_' + str(v_ii) + '">')
  280. print('<video class="lg-video-object lg-html5" controls preload="none">')
  281. print('<source src="' + link + '" type="' + mime + '">')
  282. print('<a href="' + link + '">' + alt + '</a>')
  283. print('</video>')
  284. print('</div>')
  285. print('<div class="lightgallery">')
  286. v_i = -1
  287. for l in links:
  288. if (len(l) == 3) or (len(l) == 2):
  289. link = img = alt = ""
  290. style = img2 = ""
  291. if len(l) == 3:
  292. link, img, alt = l
  293. else:
  294. link, alt = l
  295. if "youtube.com" in link:
  296. img = "https://img.youtube.com/vi/"
  297. img += urlparse_foo(link)
  298. img += "/0.jpg" # full size preview
  299. #img += "/default.jpg" # default thumbnail
  300. style = ' style="width:300px;"'
  301. img2 = '<img src="lg/video-play.png" class="picthumb">'
  302. else:
  303. x = link.rfind('.')
  304. img = link[:x] + '_small' + link[x:]
  305. lightgallery_check_thumbnail(link, img)
  306. print('<div class="border" style="position:relative;" data-src="' + link + '"><a href="' + link + '"><img class="pic" src="' + img + '" alt="' + alt + '"' + style + '>' + img2 + '</a></div>')
  307. elif len(l) == 5:
  308. v_i += 1
  309. link, mime, thumb, poster, alt = videos[v_i]
  310. if len(thumb) <= 0:
  311. x = link.rfind('.')
  312. thumb = link[:x] + '_thumb.png'
  313. if len(poster) <= 0:
  314. x = link.rfind('.')
  315. poster = link[:x] + '_poster.png'
  316. lightgallery_check_thumbnail_video(link, thumb, poster)
  317. print('<div class="border" data-poster="' + poster + '" data-sub-html="' + alt + '" data-html="#video' + str(v_i) + '_' + str(v_ii) + '"><a href="' + link + '"><img class="pic" src="' + thumb + '"></a></div>')
  318. else:
  319. raise NameError('Invalid number of arguments for lightgallery')
  320. print('</div>')
  321. # -----------------------------------------------------------------------------
  322. # github helper macros
  323. # -----------------------------------------------------------------------------
  324. import json, sys
  325. def restRequest(url):
  326. response = urllib.request.urlopen(url) if PY3 else urllib.urlopen(url)
  327. if response.getcode() != 200:
  328. sys.stderr.write("\n")
  329. sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
  330. sys.stderr.write("!!!!!!! WARNING !!!!!\n")
  331. sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
  332. sys.stderr.write("invalid response code: " + str(response.getcode()) + "\n")
  333. sys.stderr.write("url: \"" + url + "\"\n")
  334. sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
  335. sys.stderr.write("!!!!!!! WARNING !!!!!\n")
  336. sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
  337. sys.stderr.write("\n")
  338. return ""
  339. data = json.loads(response.read().decode("utf-8"))
  340. return data
  341. def restReleases(user, repo):
  342. s = "https://api.github.com/repos/"
  343. s += user
  344. s += "/"
  345. s += repo
  346. s += "/releases"
  347. return restRequest(s)
  348. def printLatestRelease(user, repo):
  349. repo_url = "https://github.com/" + user + "/" + repo
  350. print("<div class=\"releasecard\">")
  351. print("Release builds for " + repo + " are <a href=\"" + repo_url + "/releases\">available on GitHub</a>.<br>\n")
  352. releases = restReleases(user, repo)
  353. if len(releases) <= 0:
  354. print("No release has been published on GitHub yet.")
  355. print("</div>")
  356. return
  357. releases.sort(key=lambda x: x["published_at"], reverse=True)
  358. r = releases[0]
  359. release_url = r["html_url"]
  360. 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")
  361. if len(r["assets"]) <= 0:
  362. print("<br>No release assets have been published on GitHub for that.")
  363. print("</div>")
  364. return
  365. print("<ul>")
  366. print("Release Assets:")
  367. for a in r["assets"]:
  368. size = int(a["size"])
  369. ss = " "
  370. if size >= (1024 * 1024):
  371. ss += "(%.1f MiB)" % (size / (1024.0 * 1024.0))
  372. elif size >= 1024:
  373. ss += "(%d KiB)" % (size // 1024)
  374. else:
  375. ss += "(%d Byte)" % (size)
  376. print("<li><a href=\"" + a["browser_download_url"] + "\">" + a["name"] + "</a>" + ss)
  377. print("</ul></div>")
  378. def include_url(url):
  379. response = urllib.request.urlopen(url) if PY3 else urllib.urlopen(url)
  380. if response.getcode() != 200:
  381. raise Exception("invalid response code", response.getcode())
  382. data = response.read().decode("utf-8")
  383. print(data, end="")
  384. # -----------------------------------------------------------------------------
  385. # preconvert hooks
  386. # -----------------------------------------------------------------------------
  387. # -----------------------------------------------------------------------------
  388. # multi language support
  389. # -----------------------------------------------------------------------------
  390. def hook_preconvert_anotherlang():
  391. MKD_PATT = r'\.(?:md|mkd|mdown|markdown)$'
  392. _re_lang = re.compile(r'^[\s+]?lang[\s+]?[:=]((?:.|\n )*)', re.MULTILINE)
  393. vpages = [] # Set of all virtual pages
  394. for p in pages:
  395. current_lang = DEFAULT_LANG # Default language
  396. langs = [] # List of languages for the current page
  397. page_vpages = {} # Set of virtual pages for the current page
  398. text_lang = re.split(_re_lang, p.source)
  399. text_grouped = dict(zip([current_lang,] + \
  400. [lang.strip() for lang in text_lang[1::2]], \
  401. text_lang[::2]))
  402. for lang, text in (iter(text_grouped.items()) if PY3 else text_grouped.iteritems()):
  403. spath = p.fname.split(os.path.sep)
  404. langs.append(lang)
  405. if lang == "en":
  406. filename = re.sub(MKD_PATT, "%s\g<0>" % "", p.fname).split(os.path.sep)[-1]
  407. else:
  408. filename = re.sub(MKD_PATT, ".%s\g<0>" % lang, p.fname).split(os.path.sep)[-1]
  409. vp = Page(filename, virtual=text)
  410. # Copy real page attributes to the virtual page
  411. for attr in p:
  412. if not ((attr in vp) if PY3 else vp.has_key(attr)):
  413. vp[attr] = p[attr]
  414. # Define a title in the proper language
  415. vp["title"] = p["title_%s" % lang] \
  416. if ((("title_%s" % lang) in p) if PY3 else p.has_key("title_%s" % lang)) \
  417. else p["title"]
  418. # Keep track of the current lang of the virtual page
  419. vp["lang"] = lang
  420. page_vpages[lang] = vp
  421. # Each virtual page has to know about its sister vpages
  422. for lang, vpage in (iter(page_vpages.items()) if PY3 else page_vpages.iteritems()):
  423. vpage["lang_links"] = dict([(l, v["url"]) for l, v in (iter(page_vpages.items()) if PY3 else page_vpages.iteritems())])
  424. vpage["other_lang"] = langs # set other langs and link
  425. vpages += page_vpages.values()
  426. pages[:] = vpages
  427. # -----------------------------------------------------------------------------
  428. # compatibility redirect for old website URLs
  429. # -----------------------------------------------------------------------------
  430. _COMPAT = """ case "%s":
  431. $loc = "%s/%s";
  432. break;
  433. """
  434. _COMPAT_404 = """ default:
  435. $loc = "%s";
  436. break;
  437. """
  438. def hook_preconvert_compat():
  439. fp = open(os.path.join(options.project, "output", "index.php"), 'w')
  440. fp.write("<?\n")
  441. fp.write("// Auto generated xyCMS compatibility index.php\n")
  442. fp.write("$loc = 'https://www.xythobuz.de/index.de.html';\n")
  443. fp.write("if (isset($_GET['p'])) {\n")
  444. fp.write(" if (isset($_GET['lang'])) {\n")
  445. fp.write(" $_GET['p'] .= 'EN';\n")
  446. fp.write(" }\n")
  447. fp.write(" switch($_GET['p']) {\n")
  448. for p in pages:
  449. if p.get("compat", "") != "":
  450. tmp = p["compat"]
  451. if p.get("lang", DEFAULT_LANG) == DEFAULT_LANG:
  452. tmp = tmp + "EN"
  453. fp.write(_COMPAT % (tmp, "https://www.xythobuz.de", p.url))
  454. fp.write("\n")
  455. fp.write(_COMPAT_404 % "/404.html")
  456. fp.write(" }\n")
  457. fp.write("}\n")
  458. fp.write("if ($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {\n")
  459. fp.write(" if (php_sapi_name() == 'cgi') {\n")
  460. fp.write(" header('Status: 301 Moved Permanently');\n")
  461. fp.write(" } else {\n")
  462. fp.write(" header('HTTP/1.1 301 Moved Permanently');\n")
  463. fp.write(" }\n")
  464. fp.write("}\n");
  465. fp.write("header('Location: '.$loc);\n")
  466. fp.write("?>")
  467. fp.close()
  468. # -----------------------------------------------------------------------------
  469. # sitemap generation
  470. # -----------------------------------------------------------------------------
  471. _SITEMAP = """<?xml version="1.0" encoding="UTF-8"?>
  472. <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  473. %s
  474. </urlset>
  475. """
  476. _SITEMAP_URL = """
  477. <url>
  478. <loc>%s/%s</loc>
  479. <lastmod>%s</lastmod>
  480. <changefreq>%s</changefreq>
  481. <priority>%s</priority>
  482. </url>
  483. """
  484. def hook_preconvert_sitemap():
  485. date = datetime.strftime(datetime.now(), "%Y-%m-%d")
  486. urls = []
  487. for p in pages:
  488. urls.append(_SITEMAP_URL % (BASE_URL, p.url, date, p.get("changefreq", "monthly"), p.get("priority", "0.5")))
  489. fname = os.path.join(options.project, "output", "sitemap.xml")
  490. fp = open(fname, 'w')
  491. fp.write(_SITEMAP % "".join(urls))
  492. fp.close()
  493. # -----------------------------------------------------------------------------
  494. # postconvert hooks
  495. # -----------------------------------------------------------------------------
  496. # -----------------------------------------------------------------------------
  497. # rss feed generation
  498. # -----------------------------------------------------------------------------
  499. _RSS = """<?xml version="1.0" encoding="UTF-8"?>
  500. <?xml-stylesheet href="%s" type="text/xsl"?>
  501. <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  502. <channel>
  503. <title>%s</title>
  504. <link>%s</link>
  505. <atom:link href="%s" rel="self" type="application/rss+xml" />
  506. <description>%s</description>
  507. <language>en-us</language>
  508. <pubDate>%s</pubDate>
  509. <lastBuildDate>%s</lastBuildDate>
  510. <docs>http://blogs.law.harvard.edu/tech/rss</docs>
  511. <generator>Poole</generator>
  512. <ttl>720</ttl>
  513. %s
  514. </channel>
  515. </rss>
  516. """
  517. _RSS_ITEM = """
  518. <item>
  519. <title>%s</title>
  520. <link>%s</link>
  521. <description>%s</description>
  522. <pubDate>%s</pubDate>
  523. <atom:updated>%s</atom:updated>
  524. <guid>%s</guid>
  525. </item>
  526. """
  527. def hook_postconvert_rss():
  528. items = []
  529. # all pages with "date" get put into feed
  530. posts = [p for p in pages if "date" in p]
  531. # sort by update if available, date else
  532. posts.sort(key=lambda p: p.get("update", p.date), reverse=True)
  533. # only put 20 most recent items in feed
  534. posts = posts[:20]
  535. for p in posts:
  536. title = p.title
  537. if "post" in p:
  538. title = p.post
  539. link = "%s/%s" % (BASE_URL, p.url)
  540. desc = p.html.replace("href=\"img", "%s%s%s" % ("href=\"", BASE_URL, "/img"))
  541. desc = desc.replace("src=\"img", "%s%s%s" % ("src=\"", BASE_URL, "/img"))
  542. desc = desc.replace("href=\"/img", "%s%s%s" % ("href=\"", BASE_URL, "/img"))
  543. desc = desc.replace("src=\"/img", "%s%s%s" % ("src=\"", BASE_URL, "/img"))
  544. desc = htmlspecialchars(desc)
  545. date = time.mktime(time.strptime("%s 12" % p.date, "%Y-%m-%d %H"))
  546. date = email.utils.formatdate(date)
  547. update = time.mktime(time.strptime("%s 12" % p.get("update", p.date), "%Y-%m-%d %H"))
  548. update = email.utils.formatdate(update)
  549. items.append(_RSS_ITEM % (title, link, desc, date, update, link))
  550. items = "".join(items)
  551. style = "/css/rss.xsl"
  552. title = "xythobuz.de Blog"
  553. link = "%s" % BASE_URL
  554. feed = "%s/rss.xml" % BASE_URL
  555. desc = htmlspecialchars("xythobuz Electronics & Software Projects")
  556. date = email.utils.formatdate()
  557. rss = _RSS % (style, title, link, feed, desc, date, date, items)
  558. fp = codecs.open(os.path.join(output, "rss.xml"), "w", "utf-8")
  559. fp.write(rss)
  560. fp.close()
  561. # -----------------------------------------------------------------------------
  562. # compatibility redirect for old mobile pages
  563. # -----------------------------------------------------------------------------
  564. _COMPAT_MOB = """ case "%s":
  565. $loc = "%s/%s";
  566. break;
  567. """
  568. _COMPAT_404_MOB = """ default:
  569. $loc = "%s";
  570. break;
  571. """
  572. def hook_postconvert_mobilecompat():
  573. directory = os.path.join(output, "mobile")
  574. if not os.path.exists(directory):
  575. os.makedirs(directory)
  576. fp = codecs.open(os.path.join(directory, "index.php"), "w", "utf-8")
  577. fp.write("<?\n")
  578. fp.write("// Auto generated xyCMS compatibility mobile/index.php\n")
  579. fp.write("$loc = 'https://www.xythobuz.de/index.de.html';\n")
  580. fp.write("if (isset($_GET['p'])) {\n")
  581. fp.write(" if (isset($_GET['lang'])) {\n")
  582. fp.write(" $_GET['p'] .= 'EN';\n")
  583. fp.write(" }\n")
  584. fp.write(" switch($_GET['p']) {\n")
  585. for p in pages:
  586. if p.get("compat", "") != "":
  587. tmp = p["compat"]
  588. if p.get("lang", DEFAULT_LANG) == DEFAULT_LANG:
  589. tmp = tmp + "EN"
  590. fp.write(_COMPAT_MOB % (tmp, "https://www.xythobuz.de", re.sub(".html", ".html", p.url)))
  591. fp.write("\n")
  592. fp.write(_COMPAT_404_MOB % "/404.mob.html")
  593. fp.write(" }\n")
  594. fp.write("}\n")
  595. fp.write("if ($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {\n")
  596. fp.write(" if (php_sapi_name() == 'cgi') {\n")
  597. fp.write(" header('Status: 301 Moved Permanently');\n")
  598. fp.write(" } else {\n")
  599. fp.write(" header('HTTP/1.1 301 Moved Permanently');\n")
  600. fp.write(" }\n")
  601. fp.write("}\n");
  602. fp.write("header('Location: '.$loc);\n")
  603. fp.write("?>")
  604. fp.close()
  605. # -----------------------------------------------------------------------------
  606. # displaying filesize for download links
  607. # -----------------------------------------------------------------------------
  608. def hook_postconvert_size():
  609. file_ext = '|'.join(['pdf', 'zip', 'rar', 'ods', 'odt', 'odp', 'doc', 'xls', 'ppt', 'docx', 'xlsx', 'pptx', 'exe', 'brd', 'plist'])
  610. def matched_link(matchobj):
  611. try:
  612. path = matchobj.group(1)
  613. if path.startswith("http") or path.startswith("//") or path.startswith("ftp"):
  614. return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
  615. elif path.startswith("/"):
  616. path = path.strip("/")
  617. path = os.path.join("static/", path)
  618. size = os.path.getsize(path)
  619. if size >= (1024 * 1024):
  620. return "<a href=\"%s\">%s</a>&nbsp;(%.1f MiB)" % (matchobj.group(1), matchobj.group(3), size / (1024.0 * 1024.0))
  621. elif size >= 1024:
  622. return "<a href=\"%s\">%s</a>&nbsp;(%d KiB)" % (matchobj.group(1), matchobj.group(3), size // 1024)
  623. else:
  624. return "<a href=\"%s\">%s</a>&nbsp;(%d Byte)" % (matchobj.group(1), matchobj.group(3), size)
  625. except:
  626. print("Unable to estimate file size for %s" % matchobj.group(1))
  627. return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
  628. _re_url = '<a href=\"([^\"]*?\.(%s))\">(.*?)<\/a>' % file_ext
  629. for p in pages:
  630. p.html = re.sub(_re_url, matched_link, p.html)