talks.py 15 KB

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