talks.py 17 KB

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