]>
gitweb.pimeys.fr Git - today.git/blob - today.py
b05a4553128043c6db87bd367aba7be8f0293779
2 # -*- encoding: utf-8 -*-
5 script qui affiche des trucs à penser, des J-n des conneries
6 or that kind of stuff"""
14 os
.chdir('/home/vincent/scripts/today/')
17 # Import de la configuration
20 if "--color" in sys
.argv
:
21 sys
.argv
.remove("--color")
23 elif sys
.stdout
.isatty():
28 config
= config
.Config(color
=color
)
30 def print_date(timestamp
=None,color
=True):
31 """Afficher la date"""
33 timestamp
= time
.time()
34 return time
.strftime(" "*30 + config
.blue
+"%d/%m/%Y %H:%M:%S"+config
.endcolor
+ "\n",
35 time
.localtime(timestamp
))
37 def add_title(titre
, texte
):
38 """Ajoute un titre à la partie si il y a quelque chose dedans"""
40 texte
= u
" %s%s :%s\n" % (config
.green
, titre
, config
.endcolor
) + texte
+ "\n"
44 """Obtenir la date actuelle sous le bon format"""
45 timestamp
= time
.time()
46 now
= datetime
.datetime(*time
.localtime(timestamp
)[:7])
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())
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
))
78 def parse_datefile(namefile
):
79 """Ouvre et parse un fichier avec des lignes de la forme
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() == '']
86 date
, truc
= l
.split("\t",1)
87 date
= datetime
.datetime(*time
.strptime(date
, "%d/%m/%Y")[:7])
88 data
.append([date
, truc
])
93 """Obtenir la liste des évènements à venir (J-n)"""
95 data
= parse_datefile(config
.timers_file
)
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
)
106 def get_birthdays(*search
):
107 """Obtenir la liste des anniversaires à venir,
108 ou la liste des anniversaires correspondants à une recherche"""
110 liste
= parse_datefile(config
.birthdays_file
)
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
""])
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
137 birthdays
.append([u
"", u
"%s a eu %s ans" % (nom
, age
), -delta
.days
, ""])
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
)
148 """Renvoie la liste des fêtes contenue dans un jour"""
155 ll
.append(["St ", st
[1:]])
157 ll
.append(["Ste ", st
[1:]])
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
]
167 """Renvoie la liste des fêtes à souhaiter aujourd'hui et demain"""
168 sourcesaints
= json
.load(open(config
.saints_file
))
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])
177 saints
["tomorrow"] = _parse_saint(sourcesaints
[now
.month
][0])
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
)
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
)
196 def check_birthdays():
197 """Compte combien il y a d'anniversaires à afficher"""
198 birthdays
= get_birthdays()
200 n
= birthdays
.count(u
"\n") - 1
206 """Compte combien il y a de fêtes à afficher"""
207 saints
= get_saints()
208 return len(re
.findall("\nSt", saints
))
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
])
216 """Récupère les quotes DTC non lues"""
218 last_dtc
= get_last_seen().get("dtc", 0)
219 cmd
= "~/bin/dtc %s + --json" % (last_dtc
+1,)
221 cmd
= "~/bin/dtc %s --json" % args
[0]
223 cmd
= "~/bin/dtc %s %s --json" % (args
[0], args
[1])
226 proc
= subprocess
.Popen(["ssh", "-4", config
.distant_server
, cmd
], stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
227 out
, err
= proc
.communicate()
229 quotes
= json
.loads(out
)
231 last_id
= max([q
["id"] for q
in quotes
])
232 update_last_seen({"dtc" : last_id
})
233 textquotes
= format_quotes(quotes
)
236 def update_xkcd(newid
):
237 update_last_seen({"xkcd" : newid
})
239 def update_xantah(newid
):
240 update_last_seen({"xantah" : newid
})
242 def update_visiteur(newid
):
243 update_last_seen({"visiteur" : newid
})
245 def update_noob(newid
):
246 update_last_seen({"noob" : newid
})
248 def update_warpzone(newid
):
249 update_last_seen({"warpzone" : newid
})
251 def update_hugo(newid
):
252 update_last_seen({"hugo" : newid
})
254 def update_norman(newid
):
255 update_last_seen({"norman" : newid
})
257 def update_cyprien(newid
):
258 update_last_seen({"cyprien" : newid
})
260 def update_grenier(newid
):
261 update_last_seen({"grenier" : newid
})
263 def update_jl8(newid
):
264 update_last_seen({"dc" : newid
})
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
)
276 """Vérifie si il y a des derniers trucs non lus/vus."""
278 seen
= get_last_seen()
280 length
= max([len(thing
) for thing
in news
.keys()])
281 for (thing
, lastid
) in news
.items():
282 n
= lastid
- seen
.get(thing
, 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
)
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
])
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"
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
)))
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()
314 lasttime
= datetime
.datetime(*time
.localtime(float(lasttime
))[:7])
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())))
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.
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
)
335 return u
"You have something in %stoday%s" % (config
.red
, config
.endcolor
)
337 return u
"Nothing in today"
339 if _is_there_something_in_today():
340 return u
"You have something in %stoday%s" % (config
.red
, config
.endcolor
)
343 """Action par défaut, affiche toutes les infos."""
345 out
+= get_everything()
346 _there_is_something_in_today(False)
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(),
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")
362 f
= open(namefile
, "w")
363 f
.write(contents
[ifile
].encode("utf-8"))
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
,
374 lasts_raw
= json
.dumps(lasts
)
375 proc
.stdin
.write(lasts_raw
)
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")
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
,
392 #: Les actions qu'on peut effectuer en rajoutant des paramètres
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
,
413 #: Les actions qui nécessitent un accès au serveur distant
414 REMOTE_ACTIONS
= ["check", "sync"]
416 #: Toutes les actions
417 ACTIONS
= dict(AUTOMATED_ACTIONS
)
418 ACTIONS
.update(OTHER_ACTIONS
)
420 ACTIONS
[None] = affiche
# action par défaut
422 if __name__
== "__main__":
424 if "--no-color" in sys
.argv
:
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:
432 output
= ACTIONS
[None]()
434 commande
= sys
.argv
[1]
435 args
= [s
.decode("utf-8") for s
in sys
.argv
[2:]]
436 output
= ACTIONS
[commande
](*args
)
438 print output
.encode("utf-8")