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