]> gitweb.pimeys.fr Git - today.git/blob - today.py
Meilleure gestion des fichiers.
[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 urllib
13 import subprocess
14 import json
15 os.chdir('/home/vincent/scripts/today/')
16
17
18 class Config(object):
19 """Configuration (pas de couleurs si on n'output pas dans un terminal"""
20 def __init__(self, color=True):
21 if color:
22 self.endcolor = "\e[0m"
23 self.blue = "\e[1;36m"
24 self.red = "\e[1;31m"
25 self.green = "\e[1;32m"
26 else:
27 self.endcolor=self.blue=self.red=self.green=""
28 #: Fichier contenant les anniversaires
29 self.birthdays_file = "birthdays.txt"
30 #: Fichier contenant les évènements à venir
31 self.timers_file = "timers.txt"
32 #: Fichier contenant les fêtes à souhaiter
33 self.saints_file = "saints.txt"
34 #: Fichier contenant les ids des derniers trucs vus/lus
35 self.last_seen_file = "lasts"
36
37 if "--color" in sys.argv:
38 sys.argv.remove("--color")
39 color = True
40 elif sys.stdout.isatty():
41 color = True
42 else:
43 color = False
44
45 config = Config(color=color)
46
47 def print_date(timestamp=None,color=True):
48 """Afficher la date"""
49 if timestamp == None:
50 timestamp = time.time()
51 return time.strftime(" "*30 + config.blue+"%d/%m/%Y %H:%M:%S"+config.endcolor + "\n",
52 time.localtime(timestamp))
53
54 def add_title(titre, texte):
55 """Ajoute un titre à la partie si il y a quelque chose dedans"""
56 if texte:
57 texte = " %s%s :%s\n" % (config.green, titre, config.endcolor) + texte + "\n"
58 return texte
59
60 def get_now():
61 """Obtenir la date actuelle sous le bon format"""
62 timestamp = time.time()
63 now = datetime.datetime(*time.localtime(timestamp)[:7])
64 return now
65
66 def get_last_seen():
67 """Récupère la liste des derniers trucs vus/lus"""
68 with open(config.last_seen_file) as f:
69 return json.loads(f.read())
70
71 def update_last_seen(what, value):
72 """Met à jour un des derniers trucs vus/lus"""
73 lasts = get_last_seen()
74 if not what in lasts.keys():
75 print """%r n'est pas un "truc vu/lu" valide""" % (what,)
76 return
77 lasts[what] = value
78 with open(config.last_seen_file, "w") as f:
79 f.write(json.dumps(lasts))
80
81 def parse_datefile(namefile):
82 """Ouvre et parse un fichier avec des lignes de la forme
83 jj/mm/aaaa Truc
84 """
85 with open(namefile) as f:
86 rawdata = [l.strip().decode("utf8") for l in f.readlines()[1:] if not l.strip().startswith("#")]
87 data = []
88 for l in rawdata:
89 date, truc = l.split("\t",1)
90 date = datetime.datetime(*time.strptime(date,"%d/%m/%Y")[:7])
91 data.append([date, truc])
92 return data
93
94
95 def get_timers():
96 """Obtenir la liste des évènements à venir (J-n)"""
97 now = get_now()
98 data = parse_datefile(config.timers_file)
99 timers = []
100 for [date, event] in data:
101 delta = date - now + datetime.timedelta(1)
102 if delta > datetime.timedelta(0):
103 timers.append([event,delta.days])
104 eventsize = max([0]+[len(l[0]) for l in timers])
105 timers = "\n".join([("%%-%ss J-%%s" % eventsize) % (event, timer) for event,timer in timers])
106 timers = add_title("Timers", timers)
107 return timers
108
109 def exists(l):
110 """Renvoie True si au moins un élément de l est vrai"""
111 for i in l:
112 if i:
113 return True
114 return False
115
116 def get_birthdays(*search):
117 """Obtenir la liste des anniversaires à venir,
118 ou la liste des anniversaires correspondants à une recherche"""
119 now = get_now()
120 liste = parse_datefile(config.birthdays_file)
121 birthdays = []
122 if len(search) == 0:
123 # Simple demande d'anniversaires courants
124 for date, nom in liste:
125 thisyeardate = datetime.datetime(now.year, date.month, date.day)
126 delta = thisyeardate - now + datetime.timedelta(1)
127 if delta > datetime.timedelta(0):
128 age = now.year - date.year
129 if abs(delta) < datetime.timedelta(1):
130 birthdays.append([config.red,"%s a %s ans AUJOURD'HUI !"%(nom,age),0,config.endcolor])
131 elif delta < datetime.timedelta(7):
132 birthdays.append([config.red,"%s va avoir %s ans"%(nom,age),-delta.days,config.endcolor])
133 elif delta < datetime.timedelta(14):
134 birthdays.append(["","%s va avoir %s ans"%(nom,age),-delta.days,""])
135 elif datetime.timedelta(30-4) < delta < datetime.timedelta(30+4):
136 birthdays.append(["","%s va avoir %s ans"%(nom,age),-delta.days,""])
137 else:
138 # Recherche spécifique
139 search = [i.lower() for i in search]
140 tous = ("--all" in search)
141 for date, nom in liste:
142 if tous or exists([term.lower() in nom.lower() for term in search]):
143 thisyeardate = datetime.datetime(now.year, date.month, date.day)
144 delta = thisyeardate - now + datetime.timedelta(1)
145 age = now.year - date.year
146 if delta.days<0:
147 birthdays.append(["", "%s a eu %s ans"%(nom,age), -delta.days, ""])
148 else:
149 birthdays.append(["", "%s va avoir %s ans"%(nom,age), -delta.days, ""])
150 birthdays.sort(lambda x,y: -cmp(x[2], y[2]))
151 eventsize = max([0]+[len(l[1]) for l in birthdays])
152 template = ("%%s%%-%ss J%%+d%%s" % eventsize)
153 birthdays = "\n".join([template % tuple(tup) for tup in birthdays])
154 birthdays = add_title("Anniversaires", birthdays)
155 return birthdays
156
157 def check_birthdays():
158 """Compte combien il y a d'anniversaires à afficher"""
159 birthdays = get_birthdays()
160 if birthdays:
161 n = birthdays.count("\n") - 1
162 else:
163 n = 0
164 return n
165
166 def format_quotes(liste):
167 """Formate les quotes de dicos à texte"""
168 t = ("\n" + "_"*80 + "\n").join(["%(id)s (%(date)s)\n%(quote)s" % q for q in liste])
169 return t
170
171 def get_dtc(*args):
172 """Récupère les quotes DTC non lues"""
173 if len(args) == 0:
174 last_dtc = get_last_seen().get("dtc", 0)
175 cmd = "~/bin/dtc %s + --json" % (last_dtc+1,)
176 elif len(args) == 1:
177 cmd = "~/bin/dtc %s --json" % args[0]
178 elif len(args) == 2:
179 cmd = "~/bin/dtc %s %s --json" % (args[0], args[1])
180 else:
181 return None
182 proc = subprocess.Popen(["ssh", "pimeys", cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
183 out, err = proc.communicate()
184 out += err
185 quotes = json.loads(out)
186 if quotes:
187 last_id = max([q["id"] for q in quotes])
188 update_lasts("dtc", last_id)
189 textquotes = format_quotes(quotes)
190 return textquotes
191
192 def update_xkcd(newid):
193 update_last_seen("xkcd", int(newid))
194
195
196 def check_all():
197 """Vérifie si il y a des derniers trucs non lus/vus."""
198 cmd = "/home/vincent/scripts/today/today-server.py whatsup"
199 proc = subprocess.Popen(["ssh", "pimeys", cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
200 out, err = proc.communicate()
201 news = json.loads(out)
202 seen = get_last_seen()
203 n_birth = check_birthdays()
204 n_dtc = news["dtc"] - seen.get("dtc", 0)
205 n_xkcd = news["xkcd"] - seen.get("xkcd", 0)
206 l = [["Anniversaires", n_birth],
207 ["Quotes DTC", n_dtc],
208 ["XKCD non lus", n_xkcd]]
209 checks = []
210 for (text, n) in l:
211 if type(n) != int:
212 print n
213 elif n > 0:
214 checks.append("%s : %s" % (text, n))
215 checks = "\n".join(checks)
216 checks = add_title("Checks", checks)
217 return checks
218
219 def get_everything():
220 """Récupère toutes les infos"""
221 work = [action() for action in AUTOMATED_ACTIONS.values()]
222 chain = "\n\n".join([result for result in work if result])
223 return chain
224
225 def _is_there_something_in_today():
226 """Teste si il y a des choses non lue dans le today"""
227 return open(".something", "r").read() == "True"
228
229 def _there_is_something_in_today(something):
230 """Met à jour le something"""
231 f = open(".something", "w")
232 f.write(str(bool(something)))
233 f.close()
234
235 def _get_lasttime():
236 """Récupère la dernière fois que today a été exécuté"""
237 lasttime = open(".lasttime", "r").read()
238 lasttime = datetime.datetime(*time.localtime(float(lasttime))[:7])
239 return lasttime
240
241 def _update_lasttime(when):
242 """Met à jour le timestamp de dernière exécution de today"""
243 f = open(".lasttime", "w")
244 f.write(str(time.mktime(when.timetuple())))
245 f.close()
246
247 def ping():
248 """Dit juste si il y a quelque chose à voir.
249 La première exécution de la journée peut être lente parce qu'elle va bosser avnt de répondre."""
250 now = get_now()
251 lasttime = _get_lasttime()
252 if (lasttime.date() < now.date()):
253 # On a changé de jour
254 _update_lasttime(now)
255 something = get_everything()
256 _there_is_something_in_today(something)
257 if something:
258 return "You have something in %stoday%s" % (config.red, config.endcolor)
259 else:
260 return "Nothing in today"
261 else:
262 if _is_there_something_in_today():
263 return "You have something in %stoday%s" % (config.red, config.endcolor)
264
265 def affiche():
266 """Action par défaut, affiche toutes les infos"""
267 out = print_date()
268 out += get_everything()
269 _there_is_something_in_today(False)
270 return out
271
272 def initialize():
273 """Crée les fichiers (vides) nécessaires au fonctionnement du script"""
274 files = [config.birthdays_file, config.timers_file, config.saints_file,
275 config.last_seen_file]
276 contents = ["# Anniversaires\n#jj/mm/aaaa Prénom Nom\n",
277 "# Évènements à venir\n#jj/mm/aaaa Évènement\n",
278 "# Fêtes\n#jj/mm/aaaa Saint\n",
279 "{}"]
280 for ifile in range(len(files)):
281 namefile = files[ifile]
282 if os.path.isfile(namefile):
283 print "%s exists, skipping." % (namefile,)
284 else:
285 f = open(namefile, "w")
286 f.write(contents[ifile])
287 f.close()
288
289
290 #: Les actions effectuées lors d'un appel sans paramètres
291 AUTOMATED_ACTIONS = {
292 "timers" : get_timers,
293 "birth" : get_birthdays,
294 "check" : check_all,
295 }
296
297 #: Les actions qu'on peut effectuer en rajoutant des paramètres
298 OTHER_ACTIONS = {
299 "xkcd" : update_xkcd,
300 "dtc" : get_dtc,
301 "ping" : ping,
302 "show" : affiche,
303
304 "init" : initialize,
305 }
306
307 #: Toutes les actions
308 ACTIONS = dict(AUTOMATED_ACTIONS)
309 ACTIONS.update(OTHER_ACTIONS)
310
311 ACTIONS[None] = affiche # action par défaut
312
313 if __name__ == "__main__":
314 import sys
315 if "--no-color" in sys.argv:
316 config.endcolor, config.red, config.blue = "","",""
317 if len(sys.argv) == 1:
318 # Juste un today
319 output = ACTIONS[None]()
320 else:
321 commande = sys.argv[1]
322 args = sys.argv[2:]
323 output = ACTIONS[commande](*args)
324 if output:
325 print output.encode("utf-8")