X-Git-Url: http://gitweb.pimeys.fr/?p=today.git;a=blobdiff_plain;f=today.py;h=2fb940e2420faa754cb84446de1d8dfe9b14d944;hp=503cf505ad9f95c23df0ec5a2ab9ea72ae5df7d3;hb=HEAD;hpb=bddd179c766be89b43b9dab27fc76846b5e5d680 diff --git a/today.py b/today.py index 503cf50..2fb940e 100755 --- a/today.py +++ b/today.py @@ -6,6 +6,7 @@ or that kind of stuff""" import time, datetime +import re import os import sys import subprocess @@ -13,32 +14,8 @@ import json os.chdir('/home/vincent/scripts/today/') -class Config(object): - """Configuration (pas de couleurs si on n'output pas dans un terminal""" - def __init__(self, color=True): - if color: - self.endcolor = "" - self.blue = "" - self.red = "" - self.green = "" - else: - self.endcolor=self.blue=self.red=self.green="" - #: Serveur distant où aller récupérer les checks - self.distant_server = "pimeys" - #: path de today-server.py sur le serveur distant - self.path_today_server = "/home/vincent/scripts/today/today-server.py" - #: Fichier contenant les anniversaires - self.birthdays_file = "birthdays.txt" - #: Fichier contenant les évènements à venir - self.timers_file = "timers.txt" - #: Fichier contenant les fêtes à souhaiter - self.saints_file = "saints.txt" - #: Fichier contenant les ids des derniers trucs vus/lus - self.last_seen_file = "lasts" - #: Fichier contenant le timestamp de dernière exécution - self.lasttime_file = ".lasttime" - #: Fichier contenant un booléen mémorisant si il y a quelquechose dans le today du jour et qu'il n'a pas encore été regardé - self.something_file = ".something" +# Import de la configuration +import config if "--color" in sys.argv: sys.argv.remove("--color") @@ -48,7 +25,7 @@ elif sys.stdout.isatty(): else: color = False -config = Config(color=color) +config = config.Config(color=color) def print_date(timestamp=None,color=True): """Afficher la date""" @@ -60,7 +37,7 @@ def print_date(timestamp=None,color=True): def add_title(titre, texte): """Ajoute un titre à la partie si il y a quelque chose dedans""" if texte: - texte = " %s%s :%s\n" % (config.green, titre, config.endcolor) + texte + "\n" + texte = u" %s%s :%s\n" % (config.green, titre, config.endcolor) + texte + "\n" return texte def get_now(): @@ -73,13 +50,32 @@ def get_last_seen(): """Récupère la liste des derniers trucs vus/lus""" with open(config.last_seen_file) as f: return json.loads(f.read()) - -def update_last_seen(newdict): + +def is_int(a): + try: + int(a) + return True + except ValueError: + return False + +def update_last_seen(newdict, lasts_seen=None): """Met à jour un des derniers trucs vus/lus""" - lasts = get_last_seen() - lasts.update(newdict) + if not all([is_int(v) or (v == "last") for v in newdict.values()]): + raise ValueError("Donner un entier ou last") + # Il est possible qu'on ait mis "last" quelque part + if "last" in newdict.values(): + # il faut alors récupérer les derniers pour convertir "last" en + lasts_published = get_whatsup() + for key in [k for (k, v) in newdict.items() if v == "last"]: + newdict[key] = lasts_published[key] + # On convertit les chaînes en entier (pour les il leur arrive rien) + newdict = {k: int(v) for (k,v) in newdict.items()} + if lasts_seen is None: + lasts_seen = get_last_seen() + lasts_seen.update(newdict) with open(config.last_seen_file, "w") as f: - f.write(json.dumps(lasts)) + f.write(json.dumps(lasts_seen)) + return ", ".join(["last %s to %s" % (id, n) for (id, n) in newdict.items()]) def parse_datefile(namefile): """Ouvre et parse un fichier avec des lignes de la forme @@ -90,7 +86,7 @@ def parse_datefile(namefile): data = [] for l in rawdata: date, truc = l.split("\t",1) - date = datetime.datetime(*time.strptime(date,"%d/%m/%Y")[:7]) + date = datetime.datetime(*time.strptime(date, "%d/%m/%Y")[:7]) data.append([date, truc]) return data @@ -105,17 +101,10 @@ def get_timers(): if delta > datetime.timedelta(0): timers.append([event,delta.days]) eventsize = max([0]+[len(l[0]) for l in timers]) - timers = "\n".join([("%%-%ss J-%%s" % eventsize) % (event, timer) for event,timer in timers]) - timers = add_title("Timers", timers) + timers = u"\n".join([(u"%%-%ss J-%%s" % eventsize) % (event, timer) for event,timer in timers]) + timers = add_title(u"Timers", timers) return timers -def exists(l): - """Renvoie True si au moins un élément de l est vrai""" - for i in l: - if i: - return True - return False - def get_birthdays(*search): """Obtenir la liste des anniversaires à venir, ou la liste des anniversaires correspondants à une recherche""" @@ -130,45 +119,97 @@ def get_birthdays(*search): if delta > datetime.timedelta(0): age = now.year - date.year if abs(delta) < datetime.timedelta(1): - birthdays.append([config.red,"%s a %s ans AUJOURD'HUI !"%(nom,age),0,config.endcolor]) + birthdays.append([config.red, u"%s a %s ans AUJOURD'HUI !" % (nom, age), 0, config.endcolor]) elif delta < datetime.timedelta(7): - birthdays.append([config.red,"%s va avoir %s ans"%(nom,age),-delta.days,config.endcolor]) - elif delta < datetime.timedelta(14): - birthdays.append(["","%s va avoir %s ans"%(nom,age),-delta.days,""]) - elif datetime.timedelta(30-4) < delta < datetime.timedelta(30+4): - birthdays.append(["","%s va avoir %s ans"%(nom,age),-delta.days,""]) + birthdays.append([config.red, u"%s va avoir %s ans" % (nom, age), -delta.days, config.endcolor]) + elif delta < datetime.timedelta(30): + birthdays.append([u"", u"%s va avoir %s ans" % (nom, age), -delta.days, u""]) else: # Recherche spécifique search = [i.lower() for i in search] tous = ("--all" in search) for date, nom in liste: - if tous or exists([term.lower() in nom.lower() for term in search]): + if tous or any([term.lower() in nom.lower() for term in search]): thisyeardate = datetime.datetime(now.year, date.month, date.day) delta = thisyeardate - now + datetime.timedelta(1) age = now.year - date.year if delta.days<0: - birthdays.append(["", "%s a eu %s ans"%(nom,age), -delta.days, ""]) + birthdays.append([u"", u"%s a eu %s ans" % (nom, age), -delta.days, ""]) else: - birthdays.append(["", "%s va avoir %s ans"%(nom,age), -delta.days, ""]) + birthdays.append([u"", u"%s va avoir %s ans" % (nom, age), -delta.days, ""]) birthdays.sort(lambda x,y: -cmp(x[2], y[2])) eventsize = max([0]+[len(l[1]) for l in birthdays]) - template = ("%%s%%-%ss J%%+d%%s" % eventsize) - birthdays = "\n".join([template % tuple(tup) for tup in birthdays]) - birthdays = add_title("Anniversaires", birthdays) + template = (u"%%s%%-%ss J%%+d%%s" % eventsize) + birthdays = u"\n".join([template % tuple(tup) for tup in birthdays]) + birthdays = add_title(u"Anniversaires", birthdays) return birthdays +def _parse_saint(s): + """Renvoie la liste des fêtes contenue dans un jour""" + l = s.split(",") + if l == [""]: + l = [] + ll = [] + for st in l: + if st[0] == "&": + ll.append(["St ", st[1:]]) + elif st[0] == "!": + ll.append(["Ste ", st[1:]]) + return ll + +def _get_firstnames(): + """Récupère la liste des noms des gens connus""" + birthdays = parse_datefile(config.birthdays_file) + firstnames = [b[1].split()[0] for b in birthdays] + return firstnames + +def get_saints(): + """Renvoie la liste des fêtes à souhaiter aujourd'hui et demain""" + sourcesaints = json.load(open(config.saints_file)) + now = get_now() + saints = {} + saints["today"] = _parse_saint(sourcesaints[now.month - 1][now.day - 1]) + nbdays = len(sourcesaints[now.month - 1]) + if now.day == nbdays: # il faut regarder le mois suivant + if now.month == 12: # il faut regarder l'année suivante + saints["tomorrow"] = _parse_saint(sourcesaints[0][0]) + else: + saints["tomorrow"] = _parse_saint(sourcesaints[now.month][0]) + else: + saints["tomorrow"] = _parse_saint(sourcesaints[now.month - 1][now.day]) + firstnames = _get_firstnames() + towish = {"today" : [], "tomorrow" : []} + for day in ["today", "tomorrow"]: + ssaints = saints[day] + for (sexe, saint) in ssaints: + if any([firstname.lower() in saint.lower().split() for firstname in firstnames]): + towish[day].append(sexe + saint) + ttowish = [] + if towish["today"]: + ttowish.append(u"Aujourd'hui :\n" + "\n".join(towish["today"])) + if towish["tomorrow"]: + ttowish.append(u"Demain :\n" + "\n".join(towish["tomorrow"])) + saints = "\n".join(ttowish) + saints = add_title(u"Fêtes à souhaiter", saints) + return saints + def check_birthdays(): """Compte combien il y a d'anniversaires à afficher""" birthdays = get_birthdays() if birthdays: - n = birthdays.count("\n") - 1 + n = birthdays.count(u"\n") - 1 else: n = 0 return n +def check_saints(): + """Compte combien il y a de fêtes à afficher""" + saints = get_saints() + return len(re.findall("\nSt", saints)) + def format_quotes(liste): """Formate les quotes de dicos à texte""" - t = ("\n" + "_"*80 + "\n").join(["%(id)s (%(date)s)\n%(quote)s" % q for q in liste]) + t = (u"\n" + u"_"*80 + u"\n").join([u"%(id)s (%(date)s)\n%(quote)s" % q for q in liste]) return t def get_dtc(*args): @@ -182,7 +223,7 @@ def get_dtc(*args): cmd = "~/bin/dtc %s %s --json" % (args[0], args[1]) else: return None - proc = subprocess.Popen(["ssh", config.distant_server, cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + proc = subprocess.Popen(["ssh", "-4", config.distant_server, cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() out += err quotes = json.loads(out) @@ -192,37 +233,36 @@ def get_dtc(*args): textquotes = format_quotes(quotes) return textquotes -def update_xkcd(newid): - update_last_seen({"xkcd" : int(newid)}) - -def check_all(): - """Vérifie si il y a des derniers trucs non lus/vus.""" +def get_whatsup(): + """Récupère sur le serveur les derniers trucs.""" cmd = "%s whatsup" % (config.path_today_server,) - proc = subprocess.Popen(["ssh", config.distant_server, cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + proc = subprocess.Popen(["ssh", "-4", config.distant_server, cmd], stdout=subprocess.PIPE) out, err = proc.communicate() news = json.loads(out) + return news + +def check_all(): + """Vérifie si il y a des derniers trucs non lus/vus.""" + news = get_whatsup() seen = get_last_seen() - n_birth = check_birthdays() - n_dtc = news["dtc"] - seen.get("dtc", 0) - n_xkcd = news["xkcd"] - seen.get("xkcd", 0) - l = [["Anniversaires", n_birth], - ["Quotes DTC", n_dtc], - ["XKCD non lus", n_xkcd]] checks = [] - for (text, n) in l: + length = max([len(thing) for thing in news.keys()]) + for (thing, lastid) in news.items(): + n = lastid - seen.get(thing, 0) if type(n) != int: print n elif n > 0: - checks.append("%s : %s" % (text, n)) - checks = "\n".join(checks) - checks = add_title("Checks", checks) + checks.append("%s :%s%s (last : %s)" % (thing, " " *(length + 1 - len(thing)), n, news[thing])) + checks = u"\n".join(checks) + checks = add_title(u"Checks", checks) return checks def get_everything(): - """Récupère toutes les infos""" - work = [action() for action in AUTOMATED_ACTIONS.values()] - chain = "\n\n".join([result for result in work if result]) + """Récupère toutes les infos.""" + work = [action() for (keyword, action) in AUTOMATED_ACTIONS.iteritems() + if (config.do_remote or not keyword in REMOTE_ACTIONS)] + chain = u"\n\n".join([result for result in work if result]) return chain def _is_there_something_in_today(): @@ -252,7 +292,8 @@ def _update_lasttime(when): def ping(): """Dit juste si il y a quelque chose à voir. - La première exécution de la journée peut être lente parce qu'elle va bosser avnt de répondre.""" + La première exécution de la journée peut être lente parce qu'elle va bosser avant de répondre. + """ now = get_now() lasttime = _get_lasttime() if (lasttime.date() < now.date()): @@ -261,15 +302,15 @@ def ping(): something = get_everything() _there_is_something_in_today(something) if something: - return "You have something in %stoday%s" % (config.red, config.endcolor) + return u"You have something in %stoday%s" % (config.red, config.endcolor) else: - return "Nothing in today" + return u"Nothing in today" else: if _is_there_something_in_today(): - return "You have something in %stoday%s" % (config.red, config.endcolor) + return u"You have something in %stoday%s" % (config.red, config.endcolor) def affiche(): - """Action par défaut, affiche toutes les infos""" + """Action par défaut, affiche toutes les infos.""" out = print_date() out += get_everything() _there_is_something_in_today(False) @@ -279,17 +320,17 @@ def initialize(): """Crée les fichiers (vides) nécessaires au fonctionnement du script""" files = [config.birthdays_file, config.timers_file, config.saints_file, config.last_seen_file] - contents = ["# Anniversaires\n#jj/mm/aaaa Prénom Nom\n", - "# Évènements à venir\n#jj/mm/aaaa Évènement\n", - "# Fêtes\n#jj/mm/aaaa Saint\n", - "{}"] + contents = [u"# Anniversaires\n#jj/mm/aaaa Prénom Nom\n", + u"# Évènements à venir\n#jj/mm/aaaa Évènement\n", + json.dumps([[""]*31]*12).decode(), + u"{}"] for ifile in range(len(files)): namefile = files[ifile] if os.path.isfile(namefile): - print "%s exists, skipping." % (namefile,) + print (u"%s exists, skipping." % (namefile,)).encode("utf-8") else: f = open(namefile, "w") - f.write(contents[ifile]) + f.write(contents[ifile].encode("utf-8")) f.close() def sync(): @@ -297,7 +338,7 @@ def sync(): le maximum de chaque truc vu est gardé des deux côtés.""" lasts = get_last_seen() cmd = "%s sync" % (config.path_today_server,) - proc = subprocess.Popen(["ssh", config.distant_server, cmd], + proc = subprocess.Popen(["ssh", "-4", config.distant_server, cmd], stdin = subprocess.PIPE, stdout=subprocess.PIPE, close_fds = True) lasts_raw = json.dumps(lasts) @@ -306,7 +347,7 @@ def sync(): out = proc.stdout.read() newdict = json.loads(out) update_last_seen(newdict) - print "Nouvel état : %r" % newdict + print (u"Nouvel état : %r" % newdict).encode("utf-8") @@ -314,12 +355,12 @@ def sync(): AUTOMATED_ACTIONS = { "timers" : get_timers, "birth" : get_birthdays, + "saints" : get_saints, "check" : check_all, } #: Les actions qu'on peut effectuer en rajoutant des paramètres OTHER_ACTIONS = { - "xkcd" : update_xkcd, "dtc" : get_dtc, "ping" : ping, "show" : affiche, @@ -328,6 +369,9 @@ OTHER_ACTIONS = { "init" : initialize, } +#: Les actions qui nécessitent un accès au serveur distant +REMOTE_ACTIONS = ["check", "sync"] + #: Toutes les actions ACTIONS = dict(AUTOMATED_ACTIONS) ACTIONS.update(OTHER_ACTIONS) @@ -337,13 +381,25 @@ ACTIONS[None] = affiche # action par défaut if __name__ == "__main__": import sys if "--no-color" in sys.argv: - config.endcolor, config.red, config.blue = "","","" + config.nocolor() + sys.argv.remove("--no-color") + if "--no-remote" in sys.argv: + config.do_remote = False + sys.argv.remove("--no-remote") + output = None if len(sys.argv) == 1: # Juste un today output = ACTIONS[None]() else: commande = sys.argv[1] - args = sys.argv[2:] - output = ACTIONS[commande](*args) + args = [s.decode("utf-8") for s in sys.argv[2:]] + if commande in ACTIONS: + output = ACTIONS[commande](*args) + else: + # on tente un update + lasts_seen = get_last_seen() + if not commande in lasts_seen: + print "Attention : n'existait pas avant." + output = update_last_seen({commande : args[0]}, lasts_seen) if output: print output.encode("utf-8")