My static website generator using poole https://www.xythobuz.de
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

macros.py 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  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. order = p.get("sort-order", "date")
  214. if order == "position":
  215. subpages.sort(key=lambda p: p["position"])
  216. else:
  217. subpages.sort(key=lambda p: p["date"], reverse = True)
  218. if len(subpages) > 0:
  219. print("<ul>")
  220. for sp in subpages:
  221. printMenuItem(sp, False, True, True, False, "0", "", False, True)
  222. print("</ul>")
  223. # slect pages with a date
  224. dpages = [p for p in enpages if p.get("date", "") != ""]
  225. # only those that have a parent in ['projects', 'stuff']
  226. mpages = [p for p in dpages if any(x in p.get("parent", "") for x in [ 'projects', 'stuff' ])]
  227. # sort by date
  228. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  229. # print all pages
  230. lastyear = "0"
  231. for p in mpages:
  232. lastyear = printMenuItem(p, True, True, False, False, lastyear)
  233. # print subpages for these top-level items
  234. subpages = [sub for sub in enpages if sub.get("parent", "none") == p.get("child-id", "unknown")]
  235. order = p.get("sort-order", "date")
  236. if order == "position":
  237. subpages.sort(key=lambda p: p["position"])
  238. else:
  239. subpages.sort(key=lambda p: p["date"], reverse = True)
  240. if len(subpages) > 0:
  241. print("<ul>")
  242. for sp in subpages:
  243. printMenuItem(sp, False, True, True, False, "0", "", False, True)
  244. print("</ul>")
  245. print("</ul>")
  246. def printMenuGeneric(mpages = None, sortKey = None, sortReverse = True):
  247. if mpages == None:
  248. mpages = [p for p in pages if p.get("parent", "__none__") == page["child-id"] and p.lang == "en"]
  249. if sortKey != None:
  250. mpages.sort(key = sortKey, reverse = sortReverse)
  251. if len(mpages) > 0:
  252. print("<ul id='menulist'>")
  253. for p in mpages:
  254. printMenuItem(p, False, True, True)
  255. print("</ul>")
  256. def printMenuDate(mpages = None, sortReverse = True):
  257. sortKey = lambda p: p["date"]
  258. printMenuGeneric(mpages, sortKey, sortReverse)
  259. def printMenuPositional(mpages = None):
  260. printMenuGeneric(mpages, lambda p: int(p["position"]), False)
  261. def printMenu(mpages = None):
  262. order = page.get("sort-order", "date")
  263. if order == "position":
  264. printMenuPositional(mpages)
  265. else:
  266. printMenuDate(mpages)
  267. def printRobotMenuEnglish():
  268. mpages = [p for p in pages if p.get("parent", "") == "xyrobot" and p.lang == "en"]
  269. mpages.sort(key=lambda p: int(p["position"]))
  270. print("<ul id='menulist'>")
  271. for p in mpages:
  272. printMenuItem(p)
  273. print("</ul>")
  274. def printRobotMenuDeutsch():
  275. mpages = [p for p in pages if p.get("parent", "") == "xyrobot" and p.lang == "de"]
  276. mpages.sort(key=lambda p: int(p["position"]))
  277. print("<ul id='menulist'>")
  278. for p in mpages:
  279. printMenuItem(p, False, False, False, False, "0", "de")
  280. print("</ul>")
  281. def printSteamMenuEnglish():
  282. mpages = [p for p in pages if p.get("parent", "") == "steam" and p.lang == "en"]
  283. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  284. print("<ul id='menulist'>")
  285. for p in mpages:
  286. printMenuItem(p, False, False, False, True)
  287. print("</ul>")
  288. def printSteamMenuDeutsch():
  289. # TODO show german pages, or english pages when german not available
  290. printSteamMenuEnglish()
  291. # -----------------------------------------------------------------------------
  292. # lightgallery helper macro
  293. # -----------------------------------------------------------------------------
  294. # call this macro like this:
  295. # lightgallery([
  296. # [ "image-link", "description" ],
  297. # [ "image-link", "thumbnail-link", "description" ],
  298. # [ "youtube-link", "thumbnail-link", "description" ],
  299. # [ "video-link", "mime", "thumbnail-link", "image-link", "description" ],
  300. # [ "video-link", "mime", "", "", "description" ],
  301. # ])
  302. # it will also auto-generate thumbnails and resize and strip EXIF from images
  303. # using the included web-image-resize script.
  304. # and it can generate video thumbnails and posters with the video-thumb script.
  305. def lightgallery_check_thumbnail(link, thumb):
  306. # only check local image links
  307. if not link.startswith('img/'):
  308. return
  309. # generate thumbnail filename web-image-resize will create
  310. x = link.rfind('.')
  311. img = link[:x] + '_small' + link[x:]
  312. # only run when desired thumb path matches calculated ones
  313. if thumb != img:
  314. return
  315. # generate fs path to images
  316. path = os.path.join(os.getcwd(), 'static', link)
  317. img = os.path.join(os.getcwd(), 'static', thumb)
  318. # no need to generate thumb again
  319. if os.path.exists(img):
  320. return
  321. # run web-image-resize to generate thumbnail
  322. script = os.path.join(os.getcwd(), 'web-image-resize')
  323. os.system(script + ' ' + path)
  324. def lightgallery_check_thumbnail_video(link, thumb, poster):
  325. # only check local image links
  326. if not link.startswith('img/'):
  327. return
  328. # generate thumbnail filenames video-thumb will create
  329. x = link.rfind('.')
  330. thumb_l = link[:x] + '_thumb.png'
  331. poster_l = link[:x] + '_poster.png'
  332. # only run when desired thumb path matches calculated ones
  333. if (thumb_l != thumb) or (poster_l != poster):
  334. return
  335. # generate fs path to images
  336. path = os.path.join(os.getcwd(), 'static', link)
  337. thumb_p = os.path.join(os.getcwd(), 'static', thumb)
  338. poster_p = os.path.join(os.getcwd(), 'static', poster)
  339. # no need to generate thumb again
  340. if os.path.exists(thumb_p) or os.path.exists(poster_p):
  341. return
  342. # run video-thumb to generate thumbnail
  343. script = os.path.join(os.getcwd(), 'video-thumb')
  344. os.system(script + ' ' + path)
  345. def lightgallery(links):
  346. global v_ii
  347. try:
  348. v_ii += 1
  349. except NameError:
  350. v_ii = 0
  351. videos = [l for l in links if len(l) == 5]
  352. v_i = -1
  353. for v in videos:
  354. link, mime, thumb, poster, alt = v
  355. v_i += 1
  356. print('<div style="display:none;" id="video' + str(v_i) + '_' + str(v_ii) + '">')
  357. print('<video class="lg-video-object lg-html5" controls preload="none">')
  358. print('<source src="' + link + '" type="' + mime + '">')
  359. print('<a href="' + link + '">' + alt + '</a>')
  360. print('</video>')
  361. print('</div>')
  362. print('<div class="lightgallery">')
  363. v_i = -1
  364. for l in links:
  365. if (len(l) == 3) or (len(l) == 2):
  366. link = img = alt = ""
  367. style = img2 = ""
  368. if len(l) == 3:
  369. link, img, alt = l
  370. else:
  371. link, alt = l
  372. if "youtube.com" in link:
  373. img = "https://img.youtube.com/vi/"
  374. img += urlparse_foo(link)
  375. img += "/0.jpg" # full size preview
  376. #img += "/default.jpg" # default thumbnail
  377. style = ' style="width:300px;"'
  378. img2 = '<img src="lg/video-play.png" class="picthumb">'
  379. else:
  380. x = link.rfind('.')
  381. img = link[:x] + '_small' + link[x:]
  382. lightgallery_check_thumbnail(link, img)
  383. print('<div class="border" style="position:relative;" data-src="' + link + '"><a href="' + link + '"><img class="pic" src="' + img + '" alt="' + alt + '"' + style + '>' + img2 + '</a></div>')
  384. elif len(l) == 5:
  385. v_i += 1
  386. link, mime, thumb, poster, alt = videos[v_i]
  387. if len(thumb) <= 0:
  388. x = link.rfind('.')
  389. thumb = link[:x] + '_thumb.png'
  390. if len(poster) <= 0:
  391. x = link.rfind('.')
  392. poster = link[:x] + '_poster.png'
  393. lightgallery_check_thumbnail_video(link, thumb, poster)
  394. 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>')
  395. else:
  396. raise NameError('Invalid number of arguments for lightgallery')
  397. print('</div>')
  398. # -----------------------------------------------------------------------------
  399. # github helper macros
  400. # -----------------------------------------------------------------------------
  401. import json, sys
  402. def restRequest(url):
  403. response = urllib.request.urlopen(url) if PY3 else urllib.urlopen(url)
  404. if response.getcode() != 200:
  405. sys.stderr.write("\n")
  406. sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
  407. sys.stderr.write("!!!!!!! WARNING !!!!!\n")
  408. sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
  409. sys.stderr.write("invalid response code: " + str(response.getcode()) + "\n")
  410. sys.stderr.write("url: \"" + url + "\"\n")
  411. sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
  412. sys.stderr.write("!!!!!!! WARNING !!!!!\n")
  413. sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
  414. sys.stderr.write("\n")
  415. return ""
  416. data = json.loads(response.read().decode("utf-8"))
  417. return data
  418. def restReleases(user, repo):
  419. s = "https://api.github.com/repos/"
  420. s += user
  421. s += "/"
  422. s += repo
  423. s += "/releases"
  424. return restRequest(s)
  425. def printLatestRelease(user, repo):
  426. repo_url = "https://github.com/" + user + "/" + repo
  427. print("<div class=\"releasecard\">")
  428. print("Release builds for " + repo + " are <a href=\"" + repo_url + "/releases\">available on GitHub</a>.<br>\n")
  429. releases = restReleases(user, repo)
  430. if len(releases) <= 0:
  431. print("No release has been published on GitHub yet.")
  432. print("</div>")
  433. return
  434. releases.sort(key=lambda x: x["published_at"], reverse=True)
  435. r = releases[0]
  436. release_url = r["html_url"]
  437. 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")
  438. if len(r["assets"]) <= 0:
  439. print("<br>No release assets have been published on GitHub for that.")
  440. print("</div>")
  441. return
  442. print("<ul>")
  443. print("Release Assets:")
  444. for a in r["assets"]:
  445. size = int(a["size"])
  446. ss = " "
  447. if size >= (1024 * 1024):
  448. ss += "(%.1f MiB)" % (size / (1024.0 * 1024.0))
  449. elif size >= 1024:
  450. ss += "(%d KiB)" % (size // 1024)
  451. else:
  452. ss += "(%d Byte)" % (size)
  453. print("<li><a href=\"" + a["browser_download_url"] + "\">" + a["name"] + "</a>" + ss)
  454. print("</ul></div>")
  455. def include_url(url):
  456. response = urllib.request.urlopen(url) if PY3 else urllib.urlopen(url)
  457. if response.getcode() != 200:
  458. raise Exception("invalid response code", response.getcode())
  459. data = response.read().decode("utf-8")
  460. print(data, end="")
  461. # -----------------------------------------------------------------------------
  462. # preconvert hooks
  463. # -----------------------------------------------------------------------------
  464. # -----------------------------------------------------------------------------
  465. # multi language support
  466. # -----------------------------------------------------------------------------
  467. def hook_preconvert_anotherlang():
  468. MKD_PATT = r'\.(?:md|mkd|mdown|markdown)$'
  469. _re_lang = re.compile(r'^[\s+]?lang[\s+]?[:=]((?:.|\n )*)', re.MULTILINE)
  470. vpages = [] # Set of all virtual pages
  471. for p in pages:
  472. current_lang = DEFAULT_LANG # Default language
  473. langs = [] # List of languages for the current page
  474. page_vpages = {} # Set of virtual pages for the current page
  475. text_lang = re.split(_re_lang, p.source)
  476. text_grouped = dict(zip([current_lang,] + \
  477. [lang.strip() for lang in text_lang[1::2]], \
  478. text_lang[::2]))
  479. for lang, text in (iter(text_grouped.items()) if PY3 else text_grouped.iteritems()):
  480. spath = p.fname.split(os.path.sep)
  481. langs.append(lang)
  482. if lang == "en":
  483. filename = re.sub(MKD_PATT, r"%s\g<0>" % "", p.fname).split(os.path.sep)[-1]
  484. else:
  485. filename = re.sub(MKD_PATT, r".%s\g<0>" % lang, p.fname).split(os.path.sep)[-1]
  486. vp = Page(filename, virtual=text)
  487. # Copy real page attributes to the virtual page
  488. for attr in p:
  489. if not ((attr in vp) if PY3 else vp.has_key(attr)):
  490. vp[attr] = p[attr]
  491. # Define a title in the proper language
  492. vp["title"] = p["title_%s" % lang] \
  493. if ((("title_%s" % lang) in p) if PY3 else p.has_key("title_%s" % lang)) \
  494. else p["title"]
  495. # Keep track of the current lang of the virtual page
  496. vp["lang"] = lang
  497. page_vpages[lang] = vp
  498. # Each virtual page has to know about its sister vpages
  499. for lang, vpage in (iter(page_vpages.items()) if PY3 else page_vpages.iteritems()):
  500. vpage["lang_links"] = dict([(l, v["url"]) for l, v in (iter(page_vpages.items()) if PY3 else page_vpages.iteritems())])
  501. vpage["other_lang"] = langs # set other langs and link
  502. vpages += page_vpages.values()
  503. pages[:] = vpages
  504. # -----------------------------------------------------------------------------
  505. # compatibility redirect for old website URLs
  506. # -----------------------------------------------------------------------------
  507. _COMPAT = """ case "%s":
  508. $loc = "%s/%s";
  509. break;
  510. """
  511. _COMPAT_404 = """ default:
  512. $loc = "%s";
  513. break;
  514. """
  515. def hook_preconvert_compat():
  516. fp = open(os.path.join(options.project, "output", "index.php"), 'w')
  517. fp.write("<?\n")
  518. fp.write("// Auto generated xyCMS compatibility index.php\n")
  519. fp.write("$loc = '" + get_conf("base_url") + "/index.de.html';\n")
  520. fp.write("if (isset($_GET['p'])) {\n")
  521. fp.write(" if (isset($_GET['lang'])) {\n")
  522. fp.write(" $_GET['p'] .= 'EN';\n")
  523. fp.write(" }\n")
  524. fp.write(" switch($_GET['p']) {\n")
  525. for p in pages:
  526. if p.get("compat", "") != "":
  527. tmp = p["compat"]
  528. if p.get("lang", DEFAULT_LANG) == DEFAULT_LANG:
  529. tmp = tmp + "EN"
  530. fp.write(_COMPAT % (tmp, get_conf("base_url"), p.url))
  531. fp.write("\n")
  532. fp.write(_COMPAT_404 % "/404.html")
  533. fp.write(" }\n")
  534. fp.write("}\n")
  535. fp.write("if ($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {\n")
  536. fp.write(" if (php_sapi_name() == 'cgi') {\n")
  537. fp.write(" header('Status: 301 Moved Permanently');\n")
  538. fp.write(" } else {\n")
  539. fp.write(" header('HTTP/1.1 301 Moved Permanently');\n")
  540. fp.write(" }\n")
  541. fp.write("}\n");
  542. fp.write("header('Location: '.$loc);\n")
  543. fp.write("?>")
  544. fp.close()
  545. # -----------------------------------------------------------------------------
  546. # sitemap generation
  547. # -----------------------------------------------------------------------------
  548. _SITEMAP = """<?xml version="1.0" encoding="UTF-8"?>
  549. <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  550. %s
  551. </urlset>
  552. """
  553. _SITEMAP_URL = """
  554. <url>
  555. <loc>%s/%s</loc>
  556. <lastmod>%s</lastmod>
  557. <changefreq>%s</changefreq>
  558. <priority>%s</priority>
  559. </url>
  560. """
  561. def hook_preconvert_sitemap():
  562. date = datetime.strftime(datetime.now(), "%Y-%m-%d")
  563. urls = []
  564. for p in pages:
  565. urls.append(_SITEMAP_URL % (BASE_URL, p.url, date, p.get("changefreq", "monthly"), p.get("priority", "0.5")))
  566. fname = os.path.join(options.project, "output", "sitemap.xml")
  567. fp = open(fname, 'w')
  568. fp.write(_SITEMAP % "".join(urls))
  569. fp.close()
  570. # -----------------------------------------------------------------------------
  571. # postconvert hooks
  572. # -----------------------------------------------------------------------------
  573. # -----------------------------------------------------------------------------
  574. # rss feed generation
  575. # -----------------------------------------------------------------------------
  576. _RSS = """<?xml version="1.0" encoding="UTF-8"?>
  577. <?xml-stylesheet href="%s" type="text/xsl"?>
  578. <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  579. <channel>
  580. <title>%s</title>
  581. <link>%s</link>
  582. <atom:link href="%s" rel="self" type="application/rss+xml" />
  583. <description>%s</description>
  584. <language>en-us</language>
  585. <pubDate>%s</pubDate>
  586. <lastBuildDate>%s</lastBuildDate>
  587. <docs>http://blogs.law.harvard.edu/tech/rss</docs>
  588. <generator>Poole</generator>
  589. <ttl>720</ttl>
  590. %s
  591. </channel>
  592. </rss>
  593. """
  594. _RSS_ITEM = """
  595. <item>
  596. <title>%s</title>
  597. <link>%s</link>
  598. <description>%s</description>
  599. <pubDate>%s</pubDate>
  600. <atom:updated>%s</atom:updated>
  601. <guid>%s</guid>
  602. </item>
  603. """
  604. def hook_postconvert_rss():
  605. items = []
  606. # all pages with "date" get put into feed
  607. posts = [p for p in pages if "date" in p]
  608. # sort by update if available, date else
  609. posts.sort(key=lambda p: p.get("update", p.date), reverse=True)
  610. # only put 20 most recent items in feed
  611. posts = posts[:20]
  612. for p in posts:
  613. title = p.title
  614. if "post" in p:
  615. title = p.post
  616. link = "%s/%s" % (BASE_URL, p.url)
  617. desc = p.html.replace("href=\"img", "%s%s%s" % ("href=\"", BASE_URL, "/img"))
  618. desc = desc.replace("src=\"img", "%s%s%s" % ("src=\"", BASE_URL, "/img"))
  619. desc = desc.replace("href=\"/img", "%s%s%s" % ("href=\"", BASE_URL, "/img"))
  620. desc = desc.replace("src=\"/img", "%s%s%s" % ("src=\"", BASE_URL, "/img"))
  621. desc = htmlspecialchars(desc)
  622. date = time.mktime(time.strptime("%s 12" % p.date, "%Y-%m-%d %H"))
  623. date = email.utils.formatdate(date)
  624. update = time.mktime(time.strptime("%s 12" % p.get("update", p.date), "%Y-%m-%d %H"))
  625. update = email.utils.formatdate(update)
  626. items.append(_RSS_ITEM % (title, link, desc, date, update, link))
  627. items = "".join(items)
  628. style = "/css/rss.xsl"
  629. title = "xythobuz.de Blog"
  630. link = "%s" % BASE_URL
  631. feed = "%s/rss.xml" % BASE_URL
  632. desc = htmlspecialchars("xythobuz Electronics & Software Projects")
  633. date = email.utils.formatdate()
  634. rss = _RSS % (style, title, link, feed, desc, date, date, items)
  635. fp = codecs.open(os.path.join(output, "rss.xml"), "w", "utf-8")
  636. fp.write(rss)
  637. fp.close()
  638. # -----------------------------------------------------------------------------
  639. # compatibility redirect for old mobile pages
  640. # -----------------------------------------------------------------------------
  641. _COMPAT_MOB = """ case "%s":
  642. $loc = "%s/%s";
  643. break;
  644. """
  645. _COMPAT_404_MOB = """ default:
  646. $loc = "%s";
  647. break;
  648. """
  649. def hook_postconvert_mobilecompat():
  650. directory = os.path.join(output, "mobile")
  651. if not os.path.exists(directory):
  652. os.makedirs(directory)
  653. fp = codecs.open(os.path.join(directory, "index.php"), "w", "utf-8")
  654. fp.write("<?\n")
  655. fp.write("// Auto generated xyCMS compatibility mobile/index.php\n")
  656. fp.write("$loc = '" + get_conf("base_url") + "/index.de.html';\n")
  657. fp.write("if (isset($_GET['p'])) {\n")
  658. fp.write(" if (isset($_GET['lang'])) {\n")
  659. fp.write(" $_GET['p'] .= 'EN';\n")
  660. fp.write(" }\n")
  661. fp.write(" switch($_GET['p']) {\n")
  662. for p in pages:
  663. if p.get("compat", "") != "":
  664. tmp = p["compat"]
  665. if p.get("lang", DEFAULT_LANG) == DEFAULT_LANG:
  666. tmp = tmp + "EN"
  667. fp.write(_COMPAT_MOB % (tmp, get_conf("base_url"), re.sub(".html", ".html", p.url)))
  668. fp.write("\n")
  669. fp.write(_COMPAT_404_MOB % "/404.mob.html")
  670. fp.write(" }\n")
  671. fp.write("}\n")
  672. fp.write("if ($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {\n")
  673. fp.write(" if (php_sapi_name() == 'cgi') {\n")
  674. fp.write(" header('Status: 301 Moved Permanently');\n")
  675. fp.write(" } else {\n")
  676. fp.write(" header('HTTP/1.1 301 Moved Permanently');\n")
  677. fp.write(" }\n")
  678. fp.write("}\n");
  679. fp.write("header('Location: '.$loc);\n")
  680. fp.write("?>")
  681. fp.close()
  682. # -----------------------------------------------------------------------------
  683. # displaying filesize for download links
  684. # -----------------------------------------------------------------------------
  685. def hook_postconvert_size():
  686. file_ext = '|'.join(['pdf', 'zip', 'rar', 'ods', 'odt', 'odp', 'doc', 'xls', 'ppt', 'docx', 'xlsx', 'pptx', 'exe', 'brd', 'plist'])
  687. def matched_link(matchobj):
  688. try:
  689. path = matchobj.group(1)
  690. if path.startswith("http") or path.startswith("//") or path.startswith("ftp"):
  691. return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
  692. elif path.startswith("/"):
  693. path = path.strip("/")
  694. path = os.path.join("static/", path)
  695. size = os.path.getsize(path)
  696. if size >= (1024 * 1024):
  697. return "<a href=\"%s\">%s</a>&nbsp;(%.1f MiB)" % (matchobj.group(1), matchobj.group(3), size / (1024.0 * 1024.0))
  698. elif size >= 1024:
  699. return "<a href=\"%s\">%s</a>&nbsp;(%d KiB)" % (matchobj.group(1), matchobj.group(3), size // 1024)
  700. else:
  701. return "<a href=\"%s\">%s</a>&nbsp;(%d Byte)" % (matchobj.group(1), matchobj.group(3), size)
  702. except:
  703. print("Unable to estimate file size for %s" % matchobj.group(1))
  704. return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
  705. _re_url = r'<a href=\"([^\"]*?\.(%s))\">(.*?)<\/a>' % file_ext
  706. for p in pages:
  707. p.html = re.sub(_re_url, matched_link, p.html)