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