talks.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. # -*- coding: utf-8 -*-
  2. """
  3. Manage talks scheduling in a semantic way
  4. """
  5. from __future__ import print_function
  6. import os
  7. import io
  8. from functools import wraps
  9. import logging
  10. import re
  11. import datetime
  12. import shutil
  13. from copy import copy
  14. import locale
  15. from contextlib import contextmanager
  16. import inspect
  17. from babel.dates import format_date, format_datetime, format_time
  18. from markdown import markdown
  19. from docutils import nodes
  20. from docutils.parsers.rst import directives, Directive
  21. import six
  22. from pelican import signals, generators
  23. import jinja2
  24. try:
  25. import ics
  26. except ImportError:
  27. ICS_ENABLED = False
  28. else:
  29. ICS_ENABLED = True
  30. import unidecode
  31. import dateutil
  32. pelican = None # This will be set during register()
  33. def memoize(function):
  34. """decorators to cache"""
  35. memo = {}
  36. @wraps(function)
  37. def wrapper(*args):
  38. if args in memo:
  39. return memo[args]
  40. else:
  41. rv = function(*args)
  42. memo[args] = rv
  43. return rv
  44. return wrapper
  45. @contextmanager
  46. def setlocale(name):
  47. saved = locale.setlocale(locale.LC_ALL)
  48. try:
  49. yield locale.setlocale(locale.LC_ALL, name)
  50. finally:
  51. locale.setlocale(locale.LC_ALL, saved)
  52. @memoize
  53. def get_talk_names():
  54. names = [
  55. name
  56. for name in os.listdir(pelican.settings["TALKS_PATH"])
  57. if not name.startswith("_") and get_talk_data(name) is not None
  58. ]
  59. names.sort()
  60. return names
  61. def all_talks():
  62. return [get_talk_data(tn) for tn in get_talk_names()]
  63. def unique_attr(iterable, attr):
  64. return {x[attr] for x in iterable if attr in x}
  65. @memoize
  66. def get_global_data():
  67. fname = os.path.join(pelican.settings["TALKS_PATH"], "meta.yaml")
  68. if not os.path.isfile(fname):
  69. return None
  70. with io.open(fname, encoding="utf8") as buf:
  71. try:
  72. data = yaml.load(buf)
  73. except Exception:
  74. logging.exception("Syntax error reading %s; skipping", fname)
  75. return None
  76. if data is None:
  77. return None
  78. if "startdate" not in data:
  79. logging.error("Missing startdate in global data")
  80. data["startdate"] = datetime.datetime.now()
  81. if "rooms" not in data:
  82. data["rooms"] = {}
  83. return data
  84. def _get_time_shift(timestring):
  85. """ Il problema che abbiamo è che vogliamo dire che le 2 di notte del sabato sono in realtà "parte" del
  86. venerdì. Per farlo accettiamo orari che superano le 24, ad esempio 25.30 vuol dire 1.30.
  87. Questa funzione ritorna una timedelta in base alla stringa passata
  88. """
  89. timeparts = re.findall(r"\d+", timestring)
  90. if not timeparts or len(timeparts) > 2:
  91. raise ValueError("Malformed time %s" % timestring)
  92. timeparts += [0, 0] # "padding" per essere sicuro ci siano anche [1] e [2]
  93. duration = datetime.timedelta(
  94. hours=int(timeparts[0]), minutes=int(timeparts[1]), seconds=int(timeparts[2])
  95. )
  96. if duration.total_seconds() > 3600 * 31 or duration.total_seconds() < 0:
  97. raise ValueError("Sforamento eccessivo: %d" % duration.hours)
  98. return duration
  99. @memoize
  100. def get_talk_data(talkname):
  101. fname = os.path.join(pelican.settings["TALKS_PATH"], talkname, "meta.yaml")
  102. if not os.path.isfile(fname):
  103. return None
  104. with io.open(fname, encoding="utf8") as buf:
  105. try:
  106. data = yaml.load(buf)
  107. except Exception:
  108. logging.exception("Syntax error reading %s; skipping", fname)
  109. return None
  110. if data is None:
  111. return None
  112. try:
  113. gridstep = pelican.settings["TALKS_GRID_STEP"]
  114. data.setdefault("nooverlap", [])
  115. if "title" not in data:
  116. logging.warn("Talk <{}> has no `title` field".format(talkname))
  117. data["title"] = six.text_type(talkname)
  118. else:
  119. data["title"] = six.text_type(data["title"])
  120. if "text" not in data:
  121. logging.warn("Talk <{}> has no `text` field".format(talkname))
  122. data["text"] = ""
  123. else:
  124. data["text"] = six.text_type(data["text"])
  125. if "duration" not in data:
  126. logging.info(
  127. "Talk <{}> has no `duration` field (50min used)".format(talkname)
  128. )
  129. data["duration"] = 50
  130. data["duration"] = int(data["duration"])
  131. if data["duration"] < gridstep:
  132. logging.info(
  133. "Talk <{}> lasts only {} minutes; changing to {}".format(
  134. talkname, data["duration"], gridstep
  135. )
  136. )
  137. data["duration"] = gridstep
  138. if "links" not in data or not data["links"]:
  139. data["links"] = []
  140. if "contacts" not in data or not data["contacts"]:
  141. data["contacts"] = []
  142. if "needs" not in data or not data["needs"]:
  143. data["needs"] = []
  144. if "room" not in data:
  145. logging.warn("Talk <{}> has no `room` field".format(talkname))
  146. else:
  147. if data["room"] in get_global_data()["rooms"]:
  148. data["room"] = get_global_data()["rooms"][data["room"]]
  149. if "time" not in data or "day" not in data:
  150. logging.warn("Talk <{}> has no `time` or `day`".format(talkname))
  151. if "time" in data:
  152. del data["time"]
  153. if "day" in data:
  154. del data["day"]
  155. else:
  156. data["day"] = get_global_data()["startdate"] + datetime.timedelta(
  157. days=data["day"]
  158. )
  159. try:
  160. shift = _get_time_shift(str(data["time"]))
  161. except ValueError:
  162. logging.error("Talk <%s> has malformed `time`", talkname)
  163. data["delta"] = shift
  164. data["time"] = datetime.datetime.combine(
  165. data["day"], datetime.time(0, 0, 0)
  166. )
  167. data["time"] += shift
  168. data["time"] = data["time"].replace(tzinfo=dateutil.tz.gettz("Europe/Rome"))
  169. data["id"] = talkname
  170. resdir = os.path.join(
  171. pelican.settings["TALKS_PATH"],
  172. talkname,
  173. pelican.settings["TALKS_ATTACHMENT_PATH"],
  174. )
  175. if os.path.isdir(resdir) and os.listdir(resdir):
  176. data["resources"] = resdir
  177. return data
  178. except Exception:
  179. logging.exception("Error on talk %s", talkname)
  180. raise
  181. def overlap(interval_a, interval_b):
  182. """how many minutes do they overlap?"""
  183. return max(0, min(interval_a[1], interval_b[1]) - max(interval_a[0], interval_b[0]))
  184. def get_talk_overlaps(name):
  185. data = get_talk_data(name)
  186. overlapping_talks = set()
  187. if "time" not in data:
  188. return overlapping_talks
  189. start = int(data["time"].strftime("%s"))
  190. end = start + data["duration"] * 60
  191. for other in get_talk_names():
  192. if other == name:
  193. continue
  194. if "time" not in get_talk_data(other):
  195. continue
  196. other_start = int(get_talk_data(other)["time"].strftime("%s"))
  197. other_end = other_start + get_talk_data(other)["duration"] * 60
  198. minutes = overlap((start, end), (other_start, other_end))
  199. if minutes > 0:
  200. overlapping_talks.add(other)
  201. return overlapping_talks
  202. @memoize
  203. def check_overlaps():
  204. for t in get_talk_names():
  205. over = get_talk_overlaps(t)
  206. noover = get_talk_data(t)["nooverlap"]
  207. contacts = set(get_talk_data(t)["contacts"])
  208. for overlapping in over:
  209. if overlapping in noover or set(
  210. get_talk_data(overlapping)["contacts"]
  211. ).intersection(contacts):
  212. logging.warning("Talk %s overlaps with %s" % (t, overlapping))
  213. @memoize
  214. def jinja_env():
  215. env = jinja2.Environment(
  216. loader=jinja2.FileSystemLoader(
  217. os.path.join(pelican.settings["TALKS_PATH"], "_templates")
  218. ),
  219. autoescape=True,
  220. )
  221. env.filters["markdown"] = lambda text: jinja2.Markup(markdown(text))
  222. env.filters["dateformat"] = format_date
  223. env.filters["datetimeformat"] = format_datetime
  224. env.filters["timeformat"] = format_time
  225. return env
  226. @memoize
  227. def get_css():
  228. plugindir = os.path.dirname(
  229. os.path.abspath(inspect.getfile(inspect.currentframe()))
  230. )
  231. with open(os.path.join(plugindir, "style.css")) as buf:
  232. return buf.read()
  233. class TalkListDirective(Directive):
  234. final_argument_whitespace = True
  235. has_content = True
  236. option_spec = {"lang": directives.unchanged}
  237. def run(self):
  238. lang = self.options.get("lang", "C")
  239. tmpl = jinja_env().get_template("talk.html")
  240. def _sort_date(name):
  241. """
  242. This function is a helper to sort talks by start date
  243. When no date is available, put at the beginning
  244. """
  245. d = get_talk_data(name)
  246. room = d.get("room", "")
  247. time = d.get(
  248. "time",
  249. datetime.datetime(1, 1, 1).replace(
  250. tzinfo=dateutil.tz.gettz("Europe/Rome")
  251. ),
  252. )
  253. title = d.get("title", "")
  254. return (time, room, title)
  255. return [
  256. nodes.raw("", tmpl.render(lang=lang, **get_talk_data(n)), format="html")
  257. for n in sorted(get_talk_names(), key=_sort_date)
  258. ]
  259. class TalkDirective(Directive):
  260. required_arguments = 1
  261. final_argument_whitespace = True
  262. has_content = True
  263. option_spec = {"lang": directives.unchanged}
  264. def run(self):
  265. lang = self.options.get("lang", "C")
  266. tmpl = jinja_env().get_template("talk.html")
  267. data = get_talk_data(self.arguments[0])
  268. if data is None:
  269. return []
  270. return [nodes.raw("", tmpl.render(lang=lang, **data), format="html")]
  271. def _delta_to_position(delta):
  272. gridstep = pelican.settings["TALKS_GRID_STEP"]
  273. sec = delta.total_seconds() // gridstep * gridstep
  274. return int("%2d%02d" % (sec // 3600, (sec % 3600) // 60))
  275. def _delta_inc_position(delta, i):
  276. gridstep = pelican.settings["TALKS_GRID_STEP"]
  277. delta = delta + datetime.timedelta(minutes=i * gridstep)
  278. sec = delta.total_seconds() // gridstep * gridstep
  279. return int("%2d%02d" % (sec // 3600, (sec % 3600) // 60))
  280. def _approx_timestr(timestr):
  281. gridstep = pelican.settings["TALKS_GRID_STEP"]
  282. t = str(timestr)
  283. minutes = int(t[-2:])
  284. hours = t[:-2]
  285. minutes = minutes // gridstep * gridstep
  286. return int("%s%02d" % (hours, minutes))
  287. class TalkGridDirective(Directive):
  288. """A complete grid"""
  289. final_argument_whitespace = True
  290. has_content = True
  291. option_spec = {"lang": directives.unchanged}
  292. def run(self):
  293. try:
  294. lang = self.options.get("lang", "C")
  295. tmpl = jinja_env().get_template("grid.html")
  296. output = []
  297. days = unique_attr(all_talks(), "day")
  298. gridstep = pelican.settings["TALKS_GRID_STEP"]
  299. for day in sorted(days):
  300. talks = {
  301. talk["id"]
  302. for talk in all_talks()
  303. if talk.get("day", None) == day
  304. and "time" in talk
  305. and "room" in talk
  306. }
  307. if not talks:
  308. continue
  309. talks = [get_talk_data(t) for t in talks]
  310. rooms = set()
  311. for t in talks:
  312. if type(t["room"]) is list:
  313. for r in t["room"]:
  314. rooms.add(r)
  315. else:
  316. rooms.add(t["room"])
  317. # TODO: ordina in base a qualcosa nel meta.yaml globale
  318. rooms = list(sorted(rooms))
  319. # room=* is not a real room.
  320. # Remove it unless that day only has special rooms
  321. if "*" in rooms and len(rooms) > 1:
  322. del rooms[rooms.index("*")]
  323. mintimedelta = min({talk["delta"] for talk in talks})
  324. maxtimedelta = max(
  325. {
  326. talk["delta"] + datetime.timedelta(minutes=talk["duration"])
  327. for talk in talks
  328. }
  329. )
  330. mintime = _delta_to_position(mintimedelta)
  331. maxtime = _delta_to_position(maxtimedelta)
  332. times = {}
  333. t = mintimedelta
  334. while t <= maxtimedelta:
  335. times[_delta_to_position(t)] = [None] * len(rooms)
  336. t += datetime.timedelta(minutes=gridstep)
  337. for talk in sorted(talks, key=lambda x: x["delta"]):
  338. talktime = _delta_to_position(talk["delta"])
  339. position = _approx_timestr(talktime)
  340. assert position in times, "pos=%d,time=%d" % (position, talktime)
  341. if talk["room"] == "*":
  342. roomnums = range(len(rooms))
  343. elif type(talk["room"]) is list:
  344. roomnums = [rooms.index(r) for r in talk["room"]]
  345. else:
  346. roomnums = [rooms.index(talk["room"])]
  347. for roomnum in roomnums:
  348. if times[position][roomnum] is not None:
  349. logging.error(
  350. "Talk %s and %s overlap! (room %s)",
  351. times[position][roomnum]["id"],
  352. talk["id"],
  353. rooms[roomnum],
  354. )
  355. continue
  356. times[position][roomnum] = copy(talk)
  357. times[position][roomnum]["skip"] = False
  358. for i in range(1, talk["duration"] // gridstep):
  359. p = _approx_timestr(_delta_inc_position(talk["delta"], i))
  360. times[p][roomnum] = copy(talk)
  361. times[p][roomnum]["skip"] = True
  362. render = tmpl.render(
  363. times=times,
  364. rooms=rooms,
  365. mintime=mintime,
  366. maxtime=maxtime,
  367. timestep=gridstep,
  368. lang=lang,
  369. )
  370. output.append(
  371. nodes.raw(
  372. "",
  373. u"<h4>%s</h4>" % format_date(day, format="full", locale=lang),
  374. format="html",
  375. )
  376. )
  377. output.append(nodes.raw("", render, format="html"))
  378. except:
  379. logging.exception("Error on talk grid")
  380. import traceback
  381. traceback.print_exc()
  382. return []
  383. css = get_css()
  384. if css:
  385. output.insert(
  386. 0,
  387. nodes.raw("", '<style type="text/css">%s</style>' % css, format="html"),
  388. )
  389. return output
  390. def talks_to_ics():
  391. c = ics.Calendar()
  392. c.creator = u"pelican"
  393. for t in all_talks():
  394. e = talk_to_ics(t)
  395. if e is not None:
  396. c.events.add(e)
  397. return six.text_type(c)
  398. def talk_to_ics(talk):
  399. def _decode(s):
  400. if six.PY2:
  401. return unidecode.unidecode(s)
  402. else:
  403. return s
  404. if "time" not in talk or "duration" not in talk:
  405. return None
  406. e = ics.Event(
  407. uid="%s@%d.hackmeeting.org" % (talk["id"], get_global_data()["startdate"].year),
  408. name=_decode(talk["title"]),
  409. begin=talk["time"],
  410. duration=datetime.timedelta(minutes=talk["duration"]),
  411. transparent=True,
  412. )
  413. # ics.py has some problems with unicode
  414. # unidecode replaces letters with their most similar ASCII counterparts
  415. # (ie: accents get stripped)
  416. if "text" in talk:
  417. e.description = _decode(talk["text"])
  418. e.url = pelican.settings["SCHEDULEURL"] + "#talk-" + talk["id"]
  419. if "room" in talk:
  420. e.location = talk["room"]
  421. return e
  422. class TalksGenerator(generators.Generator):
  423. def __init__(self, *args, **kwargs):
  424. self.talks = []
  425. super(TalksGenerator, self).__init__(*args, **kwargs)
  426. def generate_context(self):
  427. self.talks = {n: get_talk_data(n) for n in get_talk_names()}
  428. self._update_context(("talks",))
  429. check_overlaps()
  430. def generate_output(self, writer=None):
  431. for talkname in sorted(self.talks):
  432. if "resources" in self.talks[talkname]:
  433. outdir = os.path.join(
  434. self.output_path,
  435. pelican.settings["TALKS_PATH"],
  436. talkname,
  437. pelican.settings["TALKS_ATTACHMENT_PATH"],
  438. )
  439. if os.path.isdir(outdir):
  440. shutil.rmtree(outdir)
  441. shutil.copytree(self.talks[talkname]["resources"], outdir)
  442. if ICS_ENABLED:
  443. with io.open(
  444. os.path.join(self.output_path, pelican.settings.get("TALKS_ICS")),
  445. "w",
  446. encoding="utf8",
  447. ) as buf:
  448. buf.write(talks_to_ics())
  449. else:
  450. logging.warning(
  451. "module `ics` not found. " "ICS calendar will not be generated"
  452. )
  453. def add_talks_option_defaults(pelican):
  454. pelican.settings.setdefault("TALKS_PATH", "talks")
  455. pelican.settings.setdefault("TALKS_ATTACHMENT_PATH", "res")
  456. pelican.settings.setdefault("TALKS_ICS", "schedule.ics")
  457. pelican.settings.setdefault("TALKS_GRID_STEP", 30)
  458. def get_generators(gen):
  459. return TalksGenerator
  460. def pelican_init(pelicanobj):
  461. global pelican
  462. pelican = pelicanobj
  463. try:
  464. import yaml
  465. except ImportError:
  466. print("ERROR: yaml not found. Talks plugins will be disabled")
  467. def register():
  468. pass
  469. else:
  470. def register():
  471. signals.initialized.connect(pelican_init)
  472. signals.get_generators.connect(get_generators)
  473. signals.initialized.connect(add_talks_option_defaults)
  474. directives.register_directive("talklist", TalkListDirective)
  475. directives.register_directive("talk", TalkDirective)
  476. directives.register_directive("talkgrid", TalkGridDirective)