]> gitweb.pimeys.fr Git - today.git/blob - today.py
[client] BD DC
[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 ll = []
163 for st in l:
164 if st[0] == "&":
165 ll.append(["St ", st[1:]])
166 elif st[0] == "!":
167 ll.append(["Ste ", st[1:]])
168 return ll
169
170 def _get_firstnames():
171 """Récupère la liste des noms des gens connus"""
172 birthdays = parse_datefile(config.birthdays_file)
173 firstnames = [b[1].split()[0] for b in birthdays]
174 return firstnames
175
176 def get_saints():
177 """Renvoie la liste des fêtes à souhaiter aujourd'hui et demain"""
178 sourcesaints = json.load(open(config.saints_file))
179 now = get_now()
180 saints = {}
181 saints["today"] = _parse_saint(sourcesaints[now.month - 1][now.day - 1])
182 nbdays = len(sourcesaints[now.month - 1])
183 if now.day == nbdays: # il faut regarder le mois suivant
184 if now.month == 12: # il faut regarder l'année suivante
185 saints["tomorrow"] = _parse_saint(sourcesaints[0][0])
186 else:
187 saints["tomorrow"] = _parse_saint(sourcesaints[now.month][0])
188 else:
189 saints["tomorrow"] = _parse_saint(sourcesaints[now.month - 1][now.day])
190 firstnames = _get_firstnames()
191 towish = {"today" : [], "tomorrow" : []}
192 for day in ["today", "tomorrow"]:
193 ssaints = saints[day]
194 for (sexe, saint) in ssaints:
195 if any([firstname.lower() in saint.lower().split() for firstname in firstnames]):
196 towish[day].append(sexe + saint)
197 ttowish = []
198 if towish["today"]:
199 ttowish.append(u"Aujourd'hui :\n" + "\n".join(towish["today"]))
200 if towish["tomorrow"]:
201 ttowish.append(u"Demain :\n" + "\n".join(towish["tomorrow"]))
202 saints = "\n".join(ttowish)
203 saints = add_title(u"Fêtes à souhaiter", saints)
204 return saints
205
206 def check_birthdays():
207 """Compte combien il y a d'anniversaires à afficher"""
208 birthdays = get_birthdays()
209 if birthdays:
210 n = birthdays.count(u"\n") - 1
211 else:
212 n = 0
213 return n
214
215 def check_saints():
216 """Compte combien il y a de fêtes à afficher"""
217 saints = get_saints()
218 return len(re.findall("\nSt", saints))
219
220 def format_quotes(liste):
221 """Formate les quotes de dicos à texte"""
222 t = (u"\n" + u"_"*80 + u"\n").join([u"%(id)s (%(date)s)\n%(quote)s" % q for q in liste])
223 return t
224
225 def get_dtc(*args):
226 """Récupère les quotes DTC non lues"""
227 if len(args) == 0:
228 last_dtc = get_last_seen().get("dtc", 0)
229 cmd = "~/bin/dtc %s + --json" % (last_dtc+1,)
230 elif len(args) == 1:
231 cmd = "~/bin/dtc %s --json" % args[0]
232 elif len(args) == 2:
233 cmd = "~/bin/dtc %s %s --json" % (args[0], args[1])
234 else:
235 return None
236 proc = subprocess.Popen(["ssh", "-4", config.distant_server, cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
237 out, err = proc.communicate()
238 out += err
239 quotes = json.loads(out)
240 if quotes:
241 last_id = max([q["id"] for q in quotes])
242 update_last_seen({"dtc" : last_id})
243 textquotes = format_quotes(quotes)
244 return textquotes
245
246 def update_xkcd(newid):
247 update_last_seen({"xkcd" : int(newid)})
248
249 def update_xantah(newid):
250 update_last_seen({"xantah" : int(newid)})
251
252 def update_visiteur(newid):
253 update_last_seen({"visiteur" : int(newid)})
254
255 def update_noob(newid):
256 update_last_seen({"noob" : int(newid)})
257
258 def update_warpzone(newid):
259 update_last_seen({"warpzone" : int(newid)})
260
261 def update_hugo(newid):
262 update_last_seen({"hugo" : int(newid)})
263
264 def update_norman(newid):
265 update_last_seen({"norman" : int(newid)})
266
267 def update_cyprien(newid):
268 update_last_seen({"cyprien" : int(newid)})
269
270 def update_grenier(newid):
271 update_last_seen({"grenier" : int(newid)})
272
273 def update_jl8(newid):
274 update_last_seen({"dc" : int(newid)})
275
276
277 THINGS = {
278 "dtc" : u"Quotes DTC",
279 "xkcd" : u"Épisodes de XKCD",
280 "xantah" : u"Épisodes de La Légende de Xantah",
281 "visiteur" : u"Épisodes du Visiteur du Futur",
282 "noob" : u"Épisodes de NOOB",
283 "warpzone" : u"Épisodes de WARPZONE PROJECT",
284 "hugo" : u"Vidéos de Hugo Tout Seul",
285 "norman" : u"Vidéos de Norman",
286 "cyprien" : u"Vidéos de Cyprien",
287 "grenier" : u"Épisodes du joueur du grenier",
288 "dc" : u"Épisodes de la BD youngDC",
289
290 "birthdays" : u"Anniversaires à souhaiter",
291 "saints" : u"Fêtes à souhaiter",
292 }
293
294 def check_all():
295 """Vérifie si il y a des derniers trucs non lus/vus."""
296 cmd = "%s whatsup" % (config.path_today_server,)
297 proc = subprocess.Popen(["ssh", "-4", config.distant_server, cmd], stdout=subprocess.PIPE)
298 out, err = proc.communicate()
299 news = json.loads(out)
300 seen = get_last_seen()
301 news["birthdays"] = check_birthdays()
302 news["saints"] = check_saints()
303 checks = []
304 for (thing, comm) in THINGS.iteritems():
305 n = news[thing] - seen.get(thing, 0)
306 if type(n) != int:
307 print n
308 elif n > 0:
309 checks.append("%s : %s (last : %s)" % (comm, n, news[thing]))
310 checks = u"\n".join(checks)
311 checks = add_title(u"Checks", checks)
312 return checks
313
314 def get_everything():
315 """Récupère toutes les infos."""
316 work = [action() for (keyword, action) in AUTOMATED_ACTIONS.iteritems()
317 if (config.do_remote or not keyword in REMOTE_ACTIONS)]
318 chain = u"\n\n".join([result for result in work if result])
319 return chain
320
321 def _is_there_something_in_today():
322 """Teste si il y a des choses non lue dans le today"""
323 return open(config.something_file, "r").read() == "True"
324
325 def _there_is_something_in_today(something):
326 """Met à jour le something"""
327 f = open(config.something_file, "w")
328 f.write(str(bool(something)))
329 f.close()
330
331 def _get_lasttime():
332 """Récupère la dernière fois que today a été exécuté"""
333 if os.path.isfile(config.lasttime_file):
334 lasttime = open(config.lasttime_file, "r").read()
335 else:
336 lasttime = 0
337 lasttime = datetime.datetime(*time.localtime(float(lasttime))[:7])
338 return lasttime
339
340 def _update_lasttime(when):
341 """Met à jour le timestamp de dernière exécution de today"""
342 f = open(config.lasttime_file, "w")
343 f.write(str(time.mktime(when.timetuple())))
344 f.close()
345
346 def ping():
347 """Dit juste si il y a quelque chose à voir.
348 La première exécution de la journée peut être lente parce qu'elle va bosser avant de répondre.
349 """
350 now = get_now()
351 lasttime = _get_lasttime()
352 if (lasttime.date() < now.date()):
353 # On a changé de jour
354 _update_lasttime(now)
355 something = get_everything()
356 _there_is_something_in_today(something)
357 if something:
358 return u"You have something in %stoday%s" % (config.red, config.endcolor)
359 else:
360 return u"Nothing in today"
361 else:
362 if _is_there_something_in_today():
363 return u"You have something in %stoday%s" % (config.red, config.endcolor)
364
365 def affiche():
366 """Action par défaut, affiche toutes les infos."""
367 out = print_date()
368 out += get_everything()
369 _there_is_something_in_today(False)
370 return out
371
372 def initialize():
373 """Crée les fichiers (vides) nécessaires au fonctionnement du script"""
374 files = [config.birthdays_file, config.timers_file, config.saints_file,
375 config.last_seen_file]
376 contents = [u"# Anniversaires\n#jj/mm/aaaa Prénom Nom\n",
377 u"# Évènements à venir\n#jj/mm/aaaa Évènement\n",
378 json.dumps([[""]*31]*12).decode(),
379 u"{}"]
380 for ifile in range(len(files)):
381 namefile = files[ifile]
382 if os.path.isfile(namefile):
383 print (u"%s exists, skipping." % (namefile,)).encode("utf-8")
384 else:
385 f = open(namefile, "w")
386 f.write(contents[ifile].encode("utf-8"))
387 f.close()
388
389 def sync():
390 """Synchronise les last_seen avec le serveur distant qui en garde une copie,
391 le maximum de chaque truc vu est gardé des deux côtés."""
392 lasts = get_last_seen()
393 cmd = "%s sync" % (config.path_today_server,)
394 proc = subprocess.Popen(["ssh", "-4", config.distant_server, cmd],
395 stdin = subprocess.PIPE, stdout=subprocess.PIPE,
396 close_fds = True)
397 lasts_raw = json.dumps(lasts)
398 proc.stdin.write(lasts_raw)
399 proc.stdin.close()
400 out = proc.stdout.read()
401 newdict = json.loads(out)
402 update_last_seen(newdict)
403 print (u"Nouvel état : %r" % newdict).encode("utf-8")
404
405
406
407 #: Les actions effectuées lors d'un appel sans paramètres
408 AUTOMATED_ACTIONS = {
409 "timers" : get_timers,
410 "birth" : get_birthdays,
411 "saints" : get_saints,
412 "check" : check_all,
413 }
414
415 #: Les actions qu'on peut effectuer en rajoutant des paramètres
416 OTHER_ACTIONS = {
417 "xkcd" : update_xkcd,
418 "xantah" : update_xantah,
419 "visiteur" : update_visiteur,
420 "noob" : update_noob,
421 "warpzone" : update_warpzone,
422 "hugo" : update_hugo,
423 "norman" : update_norman,
424 "cyprien" : update_cyprien,
425 "grenier" : update_grenier,
426 "dc" : update_jl8,
427
428 "dtc" : get_dtc,
429 "ping" : ping,
430 "show" : affiche,
431 "sync" : sync,
432
433 "init" : initialize,
434 }
435
436 #: Les actions qui nécessitent un accès au serveur distant
437 REMOTE_ACTIONS = ["check", "sync"]
438
439 #: Toutes les actions
440 ACTIONS = dict(AUTOMATED_ACTIONS)
441 ACTIONS.update(OTHER_ACTIONS)
442
443 ACTIONS[None] = affiche # action par défaut
444
445 if __name__ == "__main__":
446 import sys
447 if "--no-color" in sys.argv:
448 config.nocolor()
449 sys.argv.remove("--no-color")
450 if "--no-remote" in sys.argv:
451 config.do_remote = False
452 sys.argv.remove("--no-remote")
453 if len(sys.argv) == 1:
454 # Juste un today
455 output = ACTIONS[None]()
456 else:
457 commande = sys.argv[1]
458 args = [s.decode("utf-8") for s in sys.argv[2:]]
459 output = ACTIONS[commande](*args)
460 if output:
461 print output.encode("utf-8")