]> gitweb.pimeys.fr Git - today.git/blob - today.py
partie serveur
[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_lasts():
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_lasts()
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 get_dtc(*args):
154 """Récupère les quotes DTC non lues"""
155 if len(args) == 0:
156 cmd = "~/bin/dtc last"
157 elif len(args) == 1:
158 cmd = "~/bin/dtc %s" % args[0]
159 elif len(args) == 2:
160 cmd = "~/bin/dtc %s %s" % (args[0], args[1])
161 else:
162 return None
163 proc = subprocess.Popen(["ssh", "pimeys", cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
164 out, err = proc.communicate()
165 out += err
166 return out.decode("UTF-8")
167
168 def check_dtc():
169 """Vérifie si il y a des quotes DTC non lues"""
170 cmd = "~/bin/dtc check"
171 proc = subprocess.Popen(["ssh", "pimeys", cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
172 out, err = proc.communicate()
173 out += err
174 if err:
175 return err
176 n = int(out)
177 return n
178
179 def check_xkcd():
180 last_read = get_lasts()["xkcd"]
181 try:
182 p = urllib.urlopen("http://xkcd.com")
183 except IOError:
184 return "Impossible de se connecter à xkcd"
185 t = p.read()
186 current_id = int(re.findall("Permanent link to this comic: http://xkcd.com/(.*?)/", t)[0])
187 return current_id - last_read
188
189 def update_xkcd(newid):
190 update_lasts("xkcd", int(newid))
191
192
193 def check_all():
194 n_birth = check_birthdays()
195 n_dtc = check_dtc()
196 n_xkcd = check_xkcd()
197 l = [["Anniversaires", n_birth],
198 ["Quotes DTC", n_dtc],
199 ["XKCD non lus", n_xkcd]]
200 checks = []
201 for (text, n) in l:
202 if type(n) != int:
203 print n
204 elif n > 0:
205 checks.append("%s : %s" % (text, n))
206 checks = "\n".join(checks)
207 checks = add_title("Checks", checks)
208 return checks
209
210 def get_everything():
211 """Récupère toutes les infos"""
212 work = [action() for action in AUTOMATED_ACTIONS.values()]
213 chain = "\n\n".join([result for result in work if result])
214 return chain
215
216 def _is_there_something_in_today():
217 """Teste si il y a des choses non lue dans le today"""
218 return open(".something", "r").read() == "True"
219
220 def _there_is_something_in_today(something):
221 """Met à jour le something"""
222 f = open(".something", "w")
223 f.write(str(bool(something)))
224 f.close()
225
226 def _get_lasttime():
227 """Récupère la dernière fois que today a été exécuté"""
228 lasttime = open(".lasttime", "r").read()
229 lasttime = datetime.datetime(*time.localtime(float(lasttime))[:7])
230 return lasttime
231
232 def _update_lasttime(when):
233 """Met à jour le timestamp de dernière exécution de today"""
234 f = open(".lasttime", "w")
235 f.write(str(time.mktime(when.timetuple())))
236 f.close()
237
238 def ping():
239 """Dit juste si il y a quelque chose à voir.
240 La première exécution de la journée peut être lente parce qu'elle va bosser avnt de répondre."""
241 now = get_now()
242 lasttime = _get_lasttime()
243 if (lasttime.date() < now.date()):
244 # On a changé de jour
245 _update_lasttime(now)
246 something = get_everything()
247 _there_is_something_in_today(something)
248 if something:
249 return "You have something in %stoday%s" % (config.red, config.endcolor)
250 else:
251 return "Nothing in today"
252 else:
253 if _is_there_something_in_today():
254 return "You have something in %stoday%s" % (config.red, config.endcolor)
255
256 def affiche():
257 """Action par défaut, affiche toutes les infos"""
258 out = print_date()
259 out += get_everything()
260 _there_is_something_in_today(False)
261 return out
262
263 #: Les actions effectuées lors d'un appel sans paramètres
264 AUTOMATED_ACTIONS = {
265 "timers" : get_timers,
266 "birth" : get_birthdays,
267 "check" : check_all,
268 }
269
270 #: Les actions qu'on peut effectuer en rajoutant des paramètres
271 OTHER_ACTIONS = {
272 "xkcd" : update_xkcd,
273 "dtc" : get_dtc,
274 "ping" : ping,
275 "show" : affiche,
276 }
277
278 #: Toutes les actions
279 ACTIONS = dict(AUTOMATED_ACTIONS)
280 ACTIONS.update(OTHER_ACTIONS)
281
282 ACTIONS[None] = affiche # action par défaut
283
284 if __name__ == "__main__":
285 import sys
286 if "--no-color" in sys.argv:
287 config.endcolor, config.red, config.blue = "","",""
288 if len(sys.argv) == 1:
289 # Juste un today
290 output = ACTIONS[None]()
291 else:
292 commande = sys.argv[1]
293 args = sys.argv[2:]
294 output = ACTIONS[commande](*args)
295 if output:
296 print output.encode("utf-8")