My static website generator using poole https://www.xythobuz.de
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

macros.py 31KB

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