]> gitweb.pimeys.fr Git - today.git/blob - today.py
[saints] échec de .split si y'a pas de saint ce jour-là
[today.git] / today.py
1 #!/usr/bin/python
2 # -*- encoding: utf-8 -*-
3
4 """ Codé par 20-100
5 script qui affiche des trucs à penser, des J-n des conneries
6 or that kind of stuff"""
7
8 import time, datetime
9 import re
10 import os
11 import sys
12 import subprocess
13 import json
14 os.chdir('/home/vincent/scripts/today/')
15
16
17 class Config(object):
18 """Configuration (pas de couleurs si on n'output pas dans un terminal"""
19 def __init__(self, color=True):
20 self.endcolor = u"\e[0m"
21 self.blue = u"\e[1;36m"
22 self.red = u"\e[1;31m"
23 self.green = u"\e[1;32m"
24 if not color:
25 self.nocolor()
26 #: Faut-il contacter le serveur distant
27 self.do_remote = True
28 #: Serveur distant où aller récupérer les checks
29 self.distant_server = "pimeys"
30 #: path de today-server.py sur le serveur distant
31 self.path_today_server = "/home/vincent/scripts/today/today_server.py"
32 #: Fichier contenant les anniversaires
33 self.birthdays_file = "birthdays.txt"
34 #: Fichier contenant les évènements à venir
35 self.timers_file = "timers.txt"
36 #: Fichier contenant les fêtes à souhaiter
37 self.saints_file = "saints.json"
38 #: Fichier contenant les ids des derniers trucs vus/lus
39 self.last_seen_file = "lasts"
40 #: Fichier contenant le timestamp de dernière exécution
41 self.lasttime_file = ".lasttime"
42 #: Fichier contenant un booléen mémorisant si il y a quelquechose dans le today du jour et qu'il n'a pas encore été regardé
43 self.something_file = ".something"
44
45 def nocolor(self):
46 """Passe en mode sans couleur."""
47 self.endcolor = self.blue = self.red = self.green = u""
48
49 if "--color" in sys.argv:
50 sys.argv.remove("--color")
51 color = True
52 elif sys.stdout.isatty():
53 color = True
54 else:
55 color = False
56
57 config = Config(color=color)
58
59 def print_date(timestamp=None,color=True):
60 """Afficher la date"""
61 if timestamp == None:
62 timestamp = time.time()
63 return time.strftime(" "*30 + config.blue+"%d/%m/%Y %H:%M:%S"+config.endcolor + "\n",
64 time.localtime(timestamp))
65
66 def add_title(titre, texte):
67 """Ajoute un titre à la partie si il y a quelque chose dedans"""
68 if texte:
69 texte = u" %s%s :%s\n" % (config.green, titre, config.endcolor) + texte + "\n"
70 return texte
71
72 def get_now():
73 """Obtenir la date actuelle sous le bon format"""
74 timestamp = time.time()
75 now = datetime.datetime(*time.localtime(timestamp)[:7])
76 return now
77
78 def get_last_seen():
79 """Récupère la liste des derniers trucs vus/lus"""
80 with open(config.last_seen_file) as f:
81 return json.loads(f.read())
82
83 def update_last_seen(newdict):
84 """Met à jour un des derniers trucs vus/lus"""
85 lasts = get_last_seen()
86 lasts.update(newdict)
87 with open(config.last_seen_file, "w") as f:
88 f.write(json.dumps(lasts))
89
90 def parse_datefile(namefile):
91 """Ouvre et parse un fichier avec des lignes de la forme
92 jj/mm/aaaa Truc
93 """
94 with open(namefile) as f:
95 rawdata = [l.strip().decode("utf8") for l in f.readlines()[1:] if not l.strip().startswith("#") and not l.strip() == '']
96 data = []
97 for l in rawdata:
98 date, truc = l.split("\t",1)
99 date = datetime.datetime(*time.strptime(date, "%d/%m/%Y")[:7])
100 data.append([date, truc])
101 return data
102
103
104 def get_timers():
105 """Obtenir la liste des évènements à venir (J-n)"""
106 now = get_now()
107 data = parse_datefile(config.timers_file)
108 timers = []
109 for [date, event] in data:
110 delta = date - now + datetime.timedelta(1)
111 if delta > datetime.timedelta(0):
112 timers.append([event,delta.days])
113 eventsize = max([0]+[len(l[0]) for l in timers])
114 timers = u"\n".join([(u"%%-%ss J-%%s" % eventsize) % (event, timer) for event,timer in timers])
115 timers = add_title(u"Timers", timers)
116 return timers
117
118 def get_birthdays(*search):
119 """Obtenir la liste des anniversaires à venir,
120 ou la liste des anniversaires correspondants à une recherche"""
121 now = get_now()
122 liste = parse_datefile(config.birthdays_file)
123 birthdays = []
124 if len(search) == 0:
125 # Simple demande d'anniversaires courants
126 for date, nom in liste:
127 thisyeardate = datetime.datetime(now.year, date.month, date.day)
128 delta = thisyeardate - now + datetime.timedelta(1)
129 if delta > datetime.timedelta(0):
130 age = now.year - date.year
131 if abs(delta) < datetime.timedelta(1):
132 birthdays.append([config.red, u"%s a %s ans AUJOURD'HUI !" % (nom, age), 0, config.endcolor])
133 elif delta < datetime.timedelta(7):
134 birthdays.append([config.red, u"%s va avoir %s ans" % (nom, age), -delta.days, config.endcolor])
135 elif delta < datetime.timedelta(14):
136 birthdays.append([u"", u"%s va avoir %s ans" % (nom, age), -delta.days, u""])
137 elif datetime.timedelta(30-4) < delta < datetime.timedelta(30+4):
138 birthdays.append([u"", u"%s va avoir %s ans" % (nom, age), -delta.days, u""])
139 else:
140 # Recherche spécifique
141 search = [i.lower() for i in search]
142 tous = ("--all" in search)
143 for date, nom in liste:
144 if tous or any([term.lower() in nom.lower() for term in search]):
145 thisyeardate = datetime.datetime(now.year, date.month, date.day)
146 delta = thisyeardate - now + datetime.timedelta(1)
147 age = now.year - date.year
148 if delta.days<0:
149 birthdays.append([u"", u"%s a eu %s ans" % (nom, age), -delta.days, ""])
150 else:
151 birthdays.append([u"", u"%s va avoir %s ans" % (nom, age), -delta.days, ""])
152 birthdays.sort(lambda x,y: -cmp(x[2], y[2]))
153 eventsize = max([0]+[len(l[1]) for l in birthdays])
154 template = (u"%%s%%-%ss J%%+d%%s" % eventsize)
155 birthdays = u"\n".join([template % tuple(tup) for tup in birthdays])
156 birthdays = add_title(u"Anniversaires", birthdays)
157 return birthdays
158
159 def _parse_saint(s):
160 """Renvoie la liste des fêtes contenue dans un jour"""
161 l = s.split(",")
162 if l == [""]:
163 l = []
164 ll = []
165 for st in l:
166 if st[0] == "&":
167 ll.append(["St ", st[1:]])
168 elif st[0] == "!":
169 ll.append(["Ste ", st[1:]])
170 return ll
171
172 def _get_firstnames():
173 """Récupère la liste des noms des gens connus"""
174 birthdays = parse_datefile(config.birthdays_file)
175 firstnames = [b[1].split()[0] for b in birthdays]
176 return firstnames
177
178 def get_saints():
179 """Renvoie la liste des fêtes à souhaiter aujourd'hui et demain"""
180 sourcesaints = json.load(open(config.saints_file))
181 now = get_now()
182 saints = {}
183 saints["today"] = _parse_saint(sourcesaints[now.month - 1][now.day - 1])
184 nbdays = len(sourcesaints[now.month - 1])
185 if now.day == nbdays: # il faut regarder le mois suivant
186 if now.month == 12: # il faut regarder l'année suivante
187 saints["tomorrow"] = _parse_saint(sourcesaints[0][0])
188 else:
189 saints["tomorrow"] = _parse_saint(sourcesaints[now.month][0])
190 else:
191 saints["tomorrow"] = _parse_saint(sourcesaints[now.month - 1][now.day])
192 firstnames = _get_firstnames()
193 towish = {"today" : [], "tomorrow" : []}
194 for day in ["today", "tomorrow"]:
195 ssaints = saints[day]
196 for (sexe, saint) in ssaints:
197 if any([firstname.lower() in saint.lower().split() for firstname in firstnames]):
198 towish[day].append(sexe + saint)
199 ttowish = []
200 if towish["today"]:
201 ttowish.append(u"Aujourd'hui :\n" + "\n".join(towish["today"]))
202 if towish["tomorrow"]:
203 ttowish.append(u"Demain :\n" + "\n".join(towish["tomorrow"]))
204 saints = "\n".join(ttowish)
205 saints = add_title(u"Fêtes à souhaiter", saints)
206 return saints
207
208 def check_birthdays():
209 """Compte combien il y a d'anniversaires à afficher"""
210 birthdays = get_birthdays()
211 if birthdays:
212 n = birthdays.count(u"\n") - 1
213 else:
214 n = 0
215 return n
216
217 def check_saints():
218 """Compte combien il y a de fêtes à afficher"""
219 saints = get_saints()
220 return len(re.findall("\nSt", saints))
221
222 def format_quotes(liste):
223 """Formate les quotes de dicos à texte"""
224 t = (u"\n" + u"_"*80 + u"\n").join([u"%(id)s (%(date)s)\n%(quote)s" % q for q in liste])
225 return t
226
227 def get_dtc(*args):
228 """Récupère les quotes DTC non lues"""
229 if len(args) == 0:
230 last_dtc = get_last_seen().get("dtc", 0)
231 cmd = "~/bin/dtc %s + --json" % (last_dtc+1,)
232 elif len(args) == 1:
233 cmd = "~/bin/dtc %s --json" % args[0]
234 elif len(args) == 2:
235 cmd = "~/bin/dtc %s %s --json" % (args[0], args[1])
236 else:
237 return None
238 proc = subprocess.Popen(["ssh", "-4", config.distant_server, cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
239 out, err = proc.communicate()
240 out += err
241 quotes = json.loads(out)
242 if quotes:
243 last_id = max([q["id"] for q in quotes])
244 update_last_seen({"dtc" : last_id})
245 textquotes = format_quotes(quotes)
246 return textquotes
247
248 def update_xkcd(newid):
249 update_last_seen({"xkcd" : int(newid)})
250
251 def update_xantah(newid):
252 update_last_seen({"xantah" : int(newid)})
253
254 def update_visiteur(newid):
255 update_last_seen({"visiteur" : int(newid)})
256
257 def update_noob(newid):
258 update_last_seen({"noob" : int(newid)})
259
260 def update_warpzone(newid):
261 update_last_seen({"warpzone" : int(newid)})
262
263 def update_hugo(newid):
264 update_last_seen({"hugo" : int(newid)})
265
266 def update_norman(newid):
267 update_last_seen({"norman" : int(newid)})
268
269 def update_cyprien(newid):
270 update_last_seen({"cyprien" : int(newid)})
271
272 def update_grenier(newid):
273 update_last_seen({"grenier" : int(newid)})
274
275 def update_jl8(newid):
276 update_last_seen({"dc" : int(newid)})
277
278
279 THINGS = {
280 "dtc" : u"Quotes DTC",
281 "xkcd" : u"Épisodes de XKCD",
282 "xantah" : u"Épisodes de La Légende de Xantah",
283 "visiteur" : u"Épisodes du Visiteur du Futur",
284 "noob" : u"Épisodes de NOOB",
285 "warpzone" : u"Épisodes de WARPZONE PROJECT",
286 "hugo" : u"Vidéos de Hugo Tout Seul",
287 "norman" : u"Vidéos de Norman",
288 "cyprien" : u"Vidéos de Cyprien",
289 "grenier" : u"Épisodes du joueur du grenier",
290 "dc" : u"Épisodes de la BD youngDC",
291
292 "birthdays" : u"Anniversaires à souhaiter",
293 "saints" : u"Fêtes à souhaiter",
294 }
295
296 def check_all():
297 """Vérifie si il y a des derniers trucs non lus/vus."""
298 cmd = "%s whatsup" % (config.path_today_server,)
299 proc = subprocess.Popen(["ssh", "-4", config.distant_server, cmd], stdout=subprocess.PIPE)
300 out, err = proc.communicate()
301 news = json.loads(out)
302 seen = get_last_seen()
303 news["birthdays"] = check_birthdays()
304 news["saints"] = check_saints()
305 checks = []
306 for (thing, comm) in THINGS.iteritems():
307 n = news[thing] - seen.get(thing, 0)
308 if type(n) != int:
309 print n
310 elif n > 0:
311 checks.append("%s : %s (last : %s)" % (comm, n, news[thing]))
312 checks = u"\n".join(checks)
313 checks = add_title(u"Checks", checks)
314 return checks
315
316 def get_everything():
317 """Récupère toutes les infos."""
318 work = [action() for (keyword, action) in AUTOMATED_ACTIONS.iteritems()
319 if (config.do_remote or not keyword in REMOTE_ACTIONS)]
320 chain = u"\n\n".join([result for result in work if result])
321 return chain
322
323 def _is_there_something_in_today():
324 """Teste si il y a des choses non lue dans le today"""
325 return open(config.something_file, "r").read() == "True"
326
327 def _there_is_something_in_today(something):
328 """Met à jour le something"""
329 f = open(config.something_file, "w")
330 f.write(str(bool(something)))
331 f.close()
332
333 def _get_lasttime():
334 """Récupère la dernière fois que today a été exécuté"""
335 if os.path.isfile(config.lasttime_file):
336 lasttime = open(config.lasttime_file, "r").read()
337 else:
338 lasttime = 0
339 lasttime = datetime.datetime(*time.localtime(float(lasttime))[:7])
340 return lasttime
341
342 def _update_lasttime(when):
343 """Met à jour le timestamp de dernière exécution de today"""
344 f = open(config.lasttime_file, "w")
345 f.write(str(time.mktime(when.timetuple())))
346 f.close()
347
348 def ping():
349 """Dit juste si il y a quelque chose à voir.
350 La première exécution de la journée peut être lente parce qu'elle va bosser avant de répondre.
351 """
352 now = get_now()
353 lasttime = _get_lasttime()
354 if (lasttime.date() < now.date()):
355 # On a changé de jour
356 _update_lasttime(now)
357 something = get_everything()
358 _there_is_something_in_today(something)
359 if something:
360 return u"You have something in %stoday%s" % (config.red, config.endcolor)
361 else:
362 return u"Nothing in today"
363 else:
364 if _is_there_something_in_today():
365 return u"You have something in %stoday%s" % (config.red, config.endcolor)
366
367 def affiche():
368 """Action par défaut, affiche toutes les infos."""
369 out = print_date()
370 out += get_everything()
371 _there_is_something_in_today(False)
372 return out
373
374 def initialize():
375 """Crée les fichiers (vides) nécessaires au fonctionnement du script"""
376 files = [config.birthdays_file, config.timers_file, config.saints_file,
377 config.last_seen_file]
378 contents = [u"# Anniversaires\n#jj/mm/aaaa Prénom Nom\n",
379 u"# Évènements à venir\n#jj/mm/aaaa Évènement\n",
380 json.dumps([[""]*31]*12).decode(),
381 u"{}"]
382 for ifile in range(len(files)):
383 namefile = files[ifile]
384 if os.path.isfile(namefile):
385 print (u"%s exists, skipping." % (namefile,)).encode("utf-8")
386 else:
387 f = open(namefile, "w")
388 f.write(contents[ifile].encode("utf-8"))
389 f.close()
390
391 def sync():
392 """Synchronise les last_seen avec le serveur distant qui en garde une copie,
393 le maximum de chaque truc vu est gardé des deux côtés."""
394 lasts = get_last_seen()
395 cmd = "%s sync" % (config.path_today_server,)
396 proc = subprocess.Popen(["ssh", "-4", config.distant_server, cmd],
397 stdin = subprocess.PIPE, stdout=subprocess.PIPE,
398 close_fds = True)
399 lasts_raw = json.dumps(lasts)
400 proc.stdin.write(lasts_raw)
401 proc.stdin.close()
402 out = proc.stdout.read()
403 newdict = json.loads(out)
404 update_last_seen(newdict)
405 print (u"Nouvel état : %r" % newdict).encode("utf-8")
406
407
408
409 #: Les actions effectuées lors d'un appel sans paramètres
410 AUTOMATED_ACTIONS = {
411 "timers" : get_timers,
412 "birth" : get_birthdays,
413 "saints" : get_saints,
414 "check" : check_all,
415 }
416
417 #: Les actions qu'on peut effectuer en rajoutant des paramètres
418 OTHER_ACTIONS = {
419 "xkcd" : update_xkcd,
420 "xantah" : update_xantah,
421 "visiteur" : update_visiteur,
422 "noob" : update_noob,
423 "warpzone" : update_warpzone,
424 "hugo" : update_hugo,
425 "norman" : update_norman,
426 "cyprien" : update_cyprien,
427 "grenier" : update_grenier,
428 "dc" : update_jl8,
429
430 "dtc" : get_dtc,
431 "ping" : ping,
432 "show" : affiche,
433 "sync" : sync,
434
435 "init" : initialize,
436 }
437
438 #: Les actions qui nécessitent un accès au serveur distant
439 REMOTE_ACTIONS = ["check", "sync"]
440
441 #: Toutes les actions
442 ACTIONS = dict(AUTOMATED_ACTIONS)
443 ACTIONS.update(OTHER_ACTIONS)
444
445 ACTIONS[None] = affiche # action par défaut
446
447 if __name__ == "__main__":
448 import sys
449 if "--no-color" in sys.argv:
450 config.nocolor()
451 sys.argv.remove("--no-color")
452 if "--no-remote" in sys.argv:
453 config.do_remote = False
454 sys.argv.remove("--no-remote")
455 if len(sys.argv) == 1:
456 # Juste un today
457 output = ACTIONS[None]()
458 else:
459 commande = sys.argv[1]
460 args = [s.decode("utf-8") for s in sys.argv[2:]]
461 output = ACTIONS[commande](*args)
462 if output:
463 print output.encode("utf-8")