]> gitweb.pimeys.fr Git - today.git/blobdiff - today.py
Revert "pimeys est temporairement down" : Il l'est plus \o/
[today.git] / today.py
index be2c99ced41786d02de202a9725d98091a20a0c2..e430fd881a3030ab8768ced77b3ca24f4ae4366d 100755 (executable)
--- a/today.py
+++ b/today.py
@@ -9,7 +9,6 @@ import time, datetime
 import re
 import os
 import sys
-import urllib
 import subprocess
 import json
 os.chdir('/home/vincent/scripts/today/')
@@ -18,13 +17,34 @@ 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 = "\e[0m"
-            self.blue = "\e[1;36m"
-            self.red = "\e[1;31m"
-            self.green = "\e[1;32m"
-        else:
-            self.endcolor=self.blue=self.red=self.green=""
+        self.endcolor = u"\e[0m"
+        self.blue = u"\e[1;36m"
+        self.red = u"\e[1;31m"
+        self.green = u"\e[1;32m"
+        if not color:
+            self.nocolor()
+        #: Faut-il contacter le serveur distant
+        self.do_remote = True
+        #: 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.json"
+        #: 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"
+    
+    def nocolor(self):
+        """Passe en mode sans couleur."""
+        self.endcolor = self.blue = self.red = self.green = u""
 
 if "--color" in sys.argv:
     sys.argv.remove("--color")
@@ -46,7 +66,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():
@@ -55,56 +75,51 @@ def get_now():
     now = datetime.datetime(*time.localtime(timestamp)[:7])
     return now
 
-def get_lasts():
+def get_last_seen():
     """Récupère la liste des derniers trucs vus/lus"""
-    with open("lasts") as f:
+    with open(config.last_seen_file) as f:
         return json.loads(f.read())
     
-def update_lasts(what, value):
+def update_last_seen(newdict):
     """Met à jour un des derniers trucs vus/lus"""
-    lasts = get_lasts()
-    if not what in lasts.keys():
-        print """%r n'est pas un "truc vu/lu" valide""" % (what,)
-        return
-    lasts[what] = value
-    with open("lasts", "w") as f:
+    lasts = get_last_seen()
+    lasts.update(newdict)
+    with open(config.last_seen_file, "w") as f:
         f.write(json.dumps(lasts))
 
+def parse_datefile(namefile):
+    """Ouvre et parse un fichier avec des lignes de la forme
+       jj/mm/aaaa      Truc
+       """
+    with open(namefile) as f:
+        rawdata = [l.strip().decode("utf8") for l in f.readlines()[1:] if not l.strip().startswith("#") and not l.strip() == '']
+    data = []
+    for l in rawdata:
+        date, truc = l.split("\t",1)
+        date = datetime.datetime(*time.strptime(date, "%d/%m/%Y")[:7])
+        data.append([date, truc])
+    return data
+
+
 def get_timers():
     """Obtenir la liste des évènements à venir (J-n)"""
     now = get_now()
-    f=open("timers.txt", "r")
-    data = [l.strip("\n").decode("utf8") for l in f.readlines()[1:]]
-    f.close()
+    data = parse_datefile(config.timers_file)
     timers = []
-    for l in data:
-        date, event = l.split("\t",1)
-        date = datetime.datetime(*time.strptime(date,"%d/%m/%Y")[:7])
+    for [date, event] in data:
         delta = date - now + datetime.timedelta(1)
         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"""
     now = get_now()
-    text = open("birthdays.txt","r").readlines()
-    liste = [l.decode("utf8").split() for l in text if not l.startswith("#")]
-    liste = [[l[0], " ".join(l[1:])] for l in liste if l!=[]]
-    liste = [ [datetime.datetime(*time.strptime(l[0],"%d/%m/%Y")[:7]),
-               l[1]]
-            for l in liste]
+    liste = parse_datefile(config.birthdays_file)
     birthdays = []
     if len(search) == 0:
         # Simple demande d'anniversaires courants
@@ -114,130 +129,220 @@ 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])
+                    birthdays.append([config.red, u"%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,""])
+                    birthdays.append([u"", u"%s va avoir %s ans" % (nom, age), -delta.days, u""])
                 elif datetime.timedelta(30-4) < delta < datetime.timedelta(30+4):
-                    birthdays.append(["","%s va avoir %s ans"%(nom,age),-delta.days,""])
+                    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(",")
+    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 = (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):
     """Récupère les quotes DTC non lues"""
     if len(args) == 0:
-        cmd = "~/bin/dtc last"
+        last_dtc = get_last_seen().get("dtc", 0)
+        cmd = "~/bin/dtc %s + --json" % (last_dtc+1,)
     elif len(args) == 1:
-        cmd = "~/bin/dtc %s" % args[0]
+        cmd = "~/bin/dtc %s --json" % args[0]
     elif len(args) == 2:
-        cmd = "~/bin/dtc %s %s" % (args[0], args[1])
+        cmd = "~/bin/dtc %s %s --json" % (args[0], args[1])
     else:
         return None
-    proc = subprocess.Popen(["ssh", "pimeys", 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
-    return out.decode("UTF-8")
+    quotes = json.loads(out)
+    if quotes:
+        last_id = max([q["id"] for q in quotes])
+        update_last_seen({"dtc" : last_id})
+    textquotes = format_quotes(quotes)
+    return textquotes
 
-def check_dtc():
-    """Vérifie si il y a des quotes DTC non lues"""
-    cmd = "~/bin/dtc check"
-    proc = subprocess.Popen(["ssh", "pimeys", cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
-    out, err = proc.communicate()
-    out += err
-    if err:
-        return err
-    n = int(out)
-    return n
+def update_xkcd(newid):
+    update_last_seen({"xkcd" : int(newid)})
 
-def check_xkcd():
-    last_read = get_lasts()["xkcd"]
-    try:
-        p = urllib.urlopen("http://xkcd.com")
-    except IOError:
-        return "Impossible de se connecter à xkcd"
-    t = p.read()
-    current_id = int(re.findall("Permanent link to this comic: http://xkcd.com/(.*?)/", t)[0])
-    return current_id - last_read
+def update_xantah(newid):
+    update_last_seen({"xantah" : int(newid)})
+
+def update_visiteur(newid):
+    update_last_seen({"visiteur" : int(newid)})
+
+def update_noob(newid):
+    update_last_seen({"noob" : int(newid)})
+
+def update_warpzone(newid):
+    update_last_seen({"warpzone" : int(newid)})
+
+def update_hugo(newid):
+    update_last_seen({"hugo" : int(newid)})
+
+def update_norman(newid):
+    update_last_seen({"norman" : int(newid)})
+
+def update_cyprien(newid):
+    update_last_seen({"cyprien" : int(newid)})
+
+def update_grenier(newid):
+    update_last_seen({"grenier" : int(newid)})
 
-def update_xkcd(newid):
-    update_lasts("xkcd", int(newid))
 
+THINGS = {
+          "dtc" : u"Quotes DTC",
+          "xkcd" : u"Épisodes de XKCD",
+          "xantah" : u"Épisodes de La Légende de Xantah",
+          "visiteur" : u"Épisodes du Visiteur du Futur",
+          "noob" : u"Épisodes de NOOB",
+          "warpzone" : u"Épisodes de WARPZONE PROJECT",
+          "hugo" : u"Vidéos de Hugo Tout Seul",
+          "norman" : u"Vidéos de Norman",
+          "cyprien" : u"Vidéos de Cyprien",
+          "grenier" : u"Épisodes du joueur du grenier",
+
+          "birthdays" : u"Anniversaires à souhaiter",
+          "saints" : u"Fêtes à souhaiter",
+         }
 
 def check_all():
-    n_birth = check_birthdays()
-    n_dtc = check_dtc()
-    n_xkcd = check_xkcd()
-    l = [["Anniversaires", n_birth],
-         ["Quotes DTC", n_dtc],
-         ["XKCD non lus", n_xkcd]]
+    """Vérifie si il y a des derniers trucs non lus/vus."""
+    cmd = "%s whatsup" % (config.path_today_server,)
+    proc = subprocess.Popen(["ssh", "-4", config.distant_server, cmd], stdout=subprocess.PIPE)
+    out, err = proc.communicate()
+    news = json.loads(out)
+    seen = get_last_seen()
+    news["birthdays"] = check_birthdays()
+    news["saints"] = check_saints()
     checks = []
-    for (text, n) in l:
+    for (thing, comm) in THINGS.iteritems():
+        n = news[thing] - 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 (last : %s)" % (comm, 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():
     """Teste si il y a des choses non lue dans le today"""
-    return open(".something", "r").read() == "True"
+    return open(config.something_file, "r").read() == "True"
 
 def _there_is_something_in_today(something):
     """Met à jour le something"""
-    f = open(".something", "w")
+    f = open(config.something_file, "w")
     f.write(str(bool(something)))
     f.close()
 
 def _get_lasttime():
     """Récupère la dernière fois que today a été exécuté"""
-    lasttime = open(".lasttime", "r").read()
+    if os.path.isfile(config.lasttime_file):
+        lasttime = open(config.lasttime_file, "r").read()
+    else:
+        lasttime = 0
     lasttime = datetime.datetime(*time.localtime(float(lasttime))[:7])
     return lasttime
 
 def _update_lasttime(when):
     """Met à jour le timestamp de dernière exécution de today"""
-    f = open(".lasttime", "w")
+    f = open(config.lasttime_file, "w")
     f.write(str(time.mktime(when.timetuple())))
     f.close()
 
 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()):
@@ -246,35 +351,86 @@ 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)
     return out
 
+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 = [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 (u"%s exists, skipping." % (namefile,)).encode("utf-8")
+        else:
+            f = open(namefile, "w")
+            f.write(contents[ifile].encode("utf-8"))
+            f.close()
+
+def sync():
+    """Synchronise les last_seen avec le serveur distant qui en garde une copie,
+       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", "-4", config.distant_server, cmd],
+                            stdin = subprocess.PIPE, stdout=subprocess.PIPE,
+                            close_fds = True)
+    lasts_raw = json.dumps(lasts)
+    proc.stdin.write(lasts_raw)
+    proc.stdin.close()
+    out = proc.stdout.read()
+    newdict = json.loads(out)
+    update_last_seen(newdict)
+    print (u"Nouvel état : %r" % newdict).encode("utf-8")
+    
+    
+
 #: Les actions effectuées lors d'un appel sans paramètres
 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,
+           "xantah" : update_xantah,
+           "visiteur" : update_visiteur,
+           "noob" : update_noob,
+           "warpzone" : update_warpzone,
+           "hugo" : update_hugo,
+           "norman" : update_norman,
+           "cyprien" : update_cyprien,
+           "grenier" : update_grenier,
+           
            "dtc" : get_dtc,
            "ping" : ping,
            "show" : affiche,
+           "sync" : sync,
+           
+           "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)
@@ -284,7 +440,11 @@ 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")
     if len(sys.argv) == 1:
         # Juste un today
         output = ACTIONS[None]()