]> gitweb.pimeys.fr Git - bots/parrot.git/blobdiff - quotes.py
On droppe les espaces insécables dans les auteurs
[bots/parrot.git] / quotes.py
index 73f711c08b5dc6de3143f4d84802f24ad403c27e..08cac11f11368a8dec06db4f2bce6cd1ae0d8e54 100644 (file)
--- a/quotes.py
+++ b/quotes.py
@@ -11,10 +11,18 @@ import random
 
 import config
 
+quote_matcher = re.compile(config.quote_regexp, flags=re.UNICODE)
+quote_matcher_with_timestamp = re.compile(config.quote_regexp_with_timestamp, flags=re.UNICODE)
+spaces_matcher = re.compile(u"\s", flags=re.U)
+
 def get_now():
     """ Renvoie la date actuelle """
     return datetime.datetime(*time.localtime()[:6])
 
+def sanitize_author(raw):
+    """Proprifie l'auteur : enlève les espaces insécables."""
+    return spaces_matcher.sub(u" ", raw)
+
 class Quote(object):
     """ Une citation """
     def __init__(self, author, content, timestamp=None):
@@ -22,7 +30,7 @@ class Quote(object):
             timestamp = get_now()
         elif isinstance(timestamp, basestring):
             timestamp = datetime.datetime(*time.strptime(timestamp, u"%Y-%m-%d_%H:%M:%S")[:6])
-        self.author = author
+        self.author = sanitize_author(author)
         self.content = content
         self.timestamp = timestamp
     
@@ -42,7 +50,6 @@ class Quote(object):
             Indépendamment de la date. """
         return [self.author, self.content] == [otherquote.author, otherquote.content]
 
-quote_matcher = re.compile(config.quote_regexp)
 
 def parse(text, date=None):
     """ Parse le ``text`` et renvoie une quote ou None. """
@@ -97,3 +104,56 @@ class QuoteDB(object):
     def randomfrom(self, author):
         """ Sort une quote aléatoire de ``author`` """
         return random.choice([q for q in self.quotelist if q.author == author])
+    
+    def search(self, inquote=None, author=None, regexp=False):
+        """Fait une recherche dans les quotes."""
+        if regexp:
+            if inquote is None:
+                inquote = ".*"
+            if author is None:
+                author = ".*"
+            qreg = re.compile(inquote, flags=re.UNICODE)
+            areg = re.compile(author, flags=re.UNICODE)
+            l = [q for q in self.quotelist if qreg.match(q.content) and areg.match(q.author)]
+        else:
+            if inquote is None:
+                inquote = ""
+            if author is None:
+                author = ""
+            l = [q for q in self.quotelist if inquote in q.content and author in q.author]
+        return l
+
+    def search_authors(self, author=None, regexp=False):
+        """Renvoie la liste des auteurs contenant ``author`` ou qui matchent la regexp."""
+        if regexp:
+            if author is None:
+                author = ".*"
+            areg = re.compile(author, flags=re.UNICODE)
+            l = list(set([q.author for q in self.quotelist if areg.match(q.author)]))
+        else:
+            if author is None:
+                author = ""
+            l = list(set([q.author for q in self.quotelist if author in q.author]))
+        return l
+
+def dump(quotedb, dump_file=None):
+    """Pour exporter les quotes dans un format readable vers un fichier."""
+    if dump_file is None:
+        dump_file = config.quote_dump_file
+    t = "\n".join(["%s %s" % (q.timestamp.strftime("%F_%T"), q) for q in quotedb.quotelist]) + "\n"
+    with open(dump_file, "w") as f:
+        f.write(t)
+
+def restore(dump_file=None):
+    """Crée un DB de quotes en parsant le contenu d'un fichier de dump."""
+    if dump_file is None:
+        dump_file = config.quote_dump_file
+    with open(dump_file) as f:
+        t = f.read()
+    t = t.decode("utf-8") # Oui, ça peut fail, mais on ne doit alors pas continuer
+    l = [m.groupdict() for m in quote_matcher_with_timestamp.finditer(t)]
+    # On instancie les quotes grâce aux dicos qui ont déjà la bonne tronche
+    l = [Quote(**q) for q in l]
+    newquotedb = QuoteDB()
+    newquotedb.quotelist = l
+    return newquotedb