]> gitweb.pimeys.fr Git - bots/parrot.git/blob - quotes.py
fa9ac0afdedf3c8dfc6b945150d46533b4b03f72
[bots/parrot.git] / quotes.py
1 #!/usr/bin/env python
2 # -*- encoding: utf-8 -*-
3
4 """ Gestion des quotes """
5
6 import datetime
7 import time
8 import re
9 import json
10 import random
11
12 import config
13
14 quote_matcher = re.compile(config.quote_regexp, flags=re.UNICODE)
15 quote_matcher_with_timestamp = re.compile(config.quote_regexp_with_timestamp, flags=re.UNICODE)
16
17 def get_now():
18 """ Renvoie la date actuelle """
19 return datetime.datetime(*time.localtime()[:6])
20
21 class Quote(object):
22 """ Une citation """
23 def __init__(self, author, content, timestamp=None):
24 if timestamp is None:
25 timestamp = get_now()
26 elif isinstance(timestamp, basestring):
27 timestamp = datetime.datetime(*time.strptime(timestamp, u"%Y-%m-%d_%H:%M:%S")[:6])
28 self.author = author
29 self.content = content
30 self.timestamp = timestamp
31
32 def jsonize(self):
33 d = {"author" : self.author, "content" : self.content,
34 "timestamp" : self.timestamp.strftime(u"%F_%T")}
35 return d
36
37 def __unicode__(self):
38 """ Retourne la quote affichable """
39 return config.quote_template % self.__dict__
40 def __str__(self):
41 return unicode(self).encode("utf-8")
42
43 def __eq__(self, otherquote):
44 """ Vérifie si cette phrase n'a pas déjà été dite par la même personne.
45 Indépendamment de la date. """
46 return [self.author, self.content] == [otherquote.author, otherquote.content]
47
48
49 def parse(text, date=None):
50 """ Parse le ``text`` et renvoie une quote ou None. """
51 if date == None:
52 date = get_now()
53 get = quote_matcher.match(text)
54 if not get is None:
55 d = get.groupdict()
56 return Quote(d["author"], d["content"], date)
57
58 def load_file(filename):
59 """ Récupère les quotes depuis le fichier """
60 with open(filename) as f:
61 jsonquotes = json.load(f)
62 quotes = [Quote(**q) for q in jsonquotes]
63 return quotes
64
65 def save_file(quotes, filename):
66 """ Enregistre les quotes dans le fichier """
67 with open(filename, "w") as f:
68 raws = [q.jsonize() for q in quotes]
69 json.dump(raws, f)
70
71 class QuoteDB(object):
72 """ Stocke et distribue des quotes. """
73 def __init__(self):
74 self.quotelist = []
75
76 def load(self):
77 """ Charge le fichier de quotes dans la DB """
78 self.quotelist = load_file(config.quote_file)
79
80 def save(self):
81 """ Sauvegarde la DB dans le fichier de quotes """
82 save_file(self.quotelist, config.quote_file)
83
84 def store(self, author, content, timestamp=None):
85 """ Enregistre une nouvelle quote, sauf si elle existe déjà.
86 Renvoie ``True`` si elle a été ajoutée, ``False`` si elle existait. """
87 newquote = Quote(author, content, timestamp)
88 if not newquote in self.quotelist:
89 self.quotelist.append(newquote)
90 return True
91 return False
92
93 def __repr__(self):
94 return repr(self.quotelist)
95
96 def random(self):
97 """ Sort une quote aléatoire """
98 return random.choice(self.quotelist)
99 def randomfrom(self, author):
100 """ Sort une quote aléatoire de ``author`` """
101 return random.choice([q for q in self.quotelist if q.author == author])
102
103 def search(self, inquote=None, author=None, regexp=False):
104 """Fait une recherche dans les quotes."""
105 if regexp:
106 if inquote is None:
107 inquote = ".*"
108 if author is None:
109 author = ".*"
110 qreg = re.compile(inquote, flags=re.UNICODE)
111 areg = re.compile(author, flags=re.UNICODE)
112 l = [q for q in self.quotelist if qreg.match(q.content) and areg.match(q.author)]
113 else:
114 if inquote is None:
115 inquote = ""
116 if author is None:
117 author = ""
118 l = [q for q in self.quotelist if inquote in q.content and author in q.author]
119 return l
120
121 def search_authors(self, author=None, regexp=False):
122 """Renvoie la liste des auteurs contenant ``author`` ou qui matchent la regexp."""
123 if regexp:
124 if author is None:
125 author = ".*"
126 areg = re.compile(author, flags=re.UNICODE)
127 l = list(set([q.author for q in self.quotelist if areg.match(q.author)]))
128 else:
129 if author is None:
130 author = ""
131 l = list(set([q.author for q in self.quotelist if author in q.author]))
132 return l
133
134 def dump(quotedb, dump_file=None):
135 """Pour exporter les quotes dans un format readable vers un fichier."""
136 if dump_file is None:
137 dump_file = config.quote_dump_file
138 t = "\n".join(["%s %s" % (q.timestamp.strftime("%F_%T"), q) for q in quotedb.quotelist]) + "\n"
139 with open(dump_file, "w") as f:
140 f.write(t)
141
142 def restore(dump_file=None):
143 """Crée un DB de quotes en parsant le contenu d'un fichier de dump."""
144 if dump_file is None:
145 dump_file = config.quote_dump_file
146 with open(dump_file) as f:
147 t = f.read()
148 t = t.decode("utf-8") # Oui, ça peut fail, mais on ne doit alors pas continuer
149 l = [m.groupdict() for m in quote_matcher_with_timestamp.finditer(t)]
150 # On instancie les quotes grâce aux dicos qui ont déjà la bonne tronche
151 l = [Quote(**q) for q in l]
152 newquotedb = QuoteDB()
153 newquotedb.quotelist = l
154 return newquotedb