]>
gitweb.pimeys.fr Git - today.git/blob - today.py
2 # -*- encoding: utf-8 -*-
5 script qui affiche des trucs à penser, des J-n des conneries
6 or that kind of stuff"""
15 os
.chdir('/home/vincent/scripts/today/')
19 """Configuration (pas de couleurs si on n'output pas dans un terminal"""
20 def __init__(self
, color
=True):
22 self
.endcolor
= "\e[0m"
23 self
.blue
= "\e[1;36m"
25 self
.green
= "\e[1;32m"
27 self
.endcolor
=self
.blue
=self
.red
=self
.green
=""
29 if "--color" in sys
.argv
:
30 sys
.argv
.remove("--color")
32 elif sys
.stdout
.isatty():
37 config
= Config(color
=color
)
39 def print_date(timestamp
=None,color
=True):
40 """Afficher la date"""
42 timestamp
= time
.time()
43 return time
.strftime(" "*30 + config
.blue
+"%d/%m/%Y %H:%M:%S"+config
.endcolor
+ "\n",
44 time
.localtime(timestamp
))
46 def add_title(titre
, texte
):
47 """Ajoute un titre à la partie si il y a quelque chose dedans"""
49 texte
= " %s%s :%s\n" % (config
.green
, titre
, config
.endcolor
) + texte
+ "\n"
53 """Obtenir la date actuelle sous le bon format"""
54 timestamp
= time
.time()
55 now
= datetime
.datetime(*time
.localtime(timestamp
)[:7])
59 """Récupère la liste des derniers trucs vus/lus"""
60 with
open("lasts") as f
:
61 return json
.loads(f
.read())
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
,)
70 with
open("lasts", "w") as f
:
71 f
.write(json
.dumps(lasts
))
74 """Obtenir la liste des évènements à venir (J-n)"""
76 f
=open("timers.txt", "r")
77 data
= [l
.strip("\n").decode("utf8") for l
in f
.readlines()[1:]]
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
)
92 """Renvoie True si au moins un élément de l est vrai"""
98 def get_birthdays(*search
):
99 """Obtenir la liste des anniversaires à venir,
100 ou la liste des anniversaires correspondants à une recherche"""
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]),
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
,""])
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
134 birthdays
.append(["", "%s a eu %s ans"%(nom
,age
), -delta
.days
, ""])
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
)
144 def check_birthdays():
145 """Compte combien il y a d'anniversaires à afficher"""
146 birthdays
= get_birthdays()
148 n
= birthdays
.count("\n") - 1
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
])
159 """Récupère les quotes DTC non lues"""
161 last_dtc
= get_last_seen()["dtc"]
162 cmd
= "~/bin/dtc %s + --json" % (last_dtc
+1,)
164 cmd
= "~/bin/dtc %s --json" % args
[0]
166 cmd
= "~/bin/dtc %s %s --json" % (args
[0], args
[1])
169 proc
= subprocess
.Popen(["ssh", "pimeys", cmd
], stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
170 out
, err
= proc
.communicate()
172 quotes
= json
.loads(out
)
174 last_id
= max([q
["id"] for q
in quotes
])
175 update_lasts("dtc", last_id
)
176 textquotes
= format_quotes(quotes
)
179 def update_xkcd(newid
):
180 update_lasts("xkcd", int(newid
))
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
]]
201 checks
.append("%s : %s" % (text
, n
))
202 checks
= "\n".join(checks
)
203 checks
= add_title("Checks", checks
)
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
])
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"
216 def _there_is_something_in_today(something
):
217 """Met à jour le something"""
218 f
= open(".something", "w")
219 f
.write(str(bool(something
)))
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])
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())))
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."""
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
)
245 return "You have something in %stoday%s" % (config
.red
, config
.endcolor
)
247 return "Nothing in today"
249 if _is_there_something_in_today():
250 return "You have something in %stoday%s" % (config
.red
, config
.endcolor
)
253 """Action par défaut, affiche toutes les infos"""
255 out
+= get_everything()
256 _there_is_something_in_today(False)
259 #: Les actions effectuées lors d'un appel sans paramètres
260 AUTOMATED_ACTIONS
= {
261 "timers" : get_timers
,
262 "birth" : get_birthdays
,
266 #: Les actions qu'on peut effectuer en rajoutant des paramètres
268 "xkcd" : update_xkcd
,
274 #: Toutes les actions
275 ACTIONS
= dict(AUTOMATED_ACTIONS
)
276 ACTIONS
.update(OTHER_ACTIONS
)
278 ACTIONS
[None] = affiche
# action par défaut
280 if __name__
== "__main__":
282 if "--no-color" in sys
.argv
:
283 config
.endcolor
, config
.red
, config
.blue
= "","",""
284 if len(sys
.argv
) == 1:
286 output
= ACTIONS
[None]()
288 commande
= sys
.argv
[1]
290 output
= ACTIONS
[commande
](*args
)
292 print output
.encode("utf-8")