forked from illuminatedwax/pesterchum
/
dataobjs.py
291 lines (276 loc) · 12 KB
/
dataobjs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
from PyQt4 import QtGui, QtCore
from datetime import *
import re
import random
from generic import PesterIcon
from parsetools import timeDifference, convertTags, lexMessage
from mispeller import mispeller
_upperre = re.compile(r"upper\(([\w\\]+)\)")
class Mood(object):
moods = ["chummy", "rancorous", "offline", "pleasant", "distraught",
"pranky", "smooth", "ecstatic", "relaxed", "discontent",
"devious", "sleek", "detestful", "mirthful", "manipulative",
"vigorous", "perky", "acceptant", "protective", "mystified",
"amazed", "insolent", "bemused" ]
moodcats = ["chums", "trolls", "other"]
revmoodcats = {'discontent': 'trolls', 'insolent': 'chums', 'rancorous': 'chums', 'sleek': 'trolls', 'bemused': 'chums', 'mystified': 'chums', 'pranky': 'chums', 'distraught': 'chums', 'offline': 'chums', 'chummy': 'chums', 'protective': 'other', 'vigorous': 'trolls', 'ecstatic': 'trolls', 'relaxed': 'trolls', 'pleasant': 'chums', 'manipulative': 'trolls', 'detestful': 'trolls', 'smooth': 'chums', 'mirthful': 'trolls', 'acceptant': 'trolls', 'perky': 'trolls', 'devious': 'trolls', 'amazed': 'chums'}
def __init__(self, mood):
if type(mood) is int:
self.mood = mood
else:
self.mood = self.moods.index(mood)
def value(self):
return self.mood
def name(self):
try:
name = self.moods[self.mood]
except IndexError:
name = "chummy"
return name
def icon(self, theme):
try:
f = theme["main/chums/moods"][self.name()]["icon"]
except KeyError:
return PesterIcon(theme["main/chums/moods/chummy/icon"])
return PesterIcon(f)
class pesterQuirk(object):
def __init__(self, quirk):
if type(quirk) != dict:
raise ValueError("Quirks must be given a dictionary")
self.quirk = quirk
self.type = self.quirk["type"]
def apply(self, string, first=False, last=False):
if self.type == "prefix":
return self.quirk["value"] + string
elif self.type == "suffix":
return string + self.quirk["value"]
elif self.type == "replace":
return string.replace(self.quirk["from"], self.quirk["to"])
elif self.type == "regexp":
fr = self.quirk["from"]
if not first and len(fr) > 0 and fr[0] == "^":
return string
if not last and len(fr) > 0 and fr[len(fr)-1] == "$":
return string
def regexprep(mo):
to = self.quirk["to"]
def upperrep(m):
return mo.expand(m.group(1)).upper()
to = _upperre.sub(upperrep, to)
return mo.expand(to)
return re.sub(fr, regexprep, string)
elif self.type == "random":
if len(self.quirk["randomlist"]) == 0:
return string
fr = self.quirk["from"]
if not first and len(fr) > 0 and fr[0] == "^":
return string
if not last and len(fr) > 0 and fr[len(fr)-1] == "$":
return string
def randomrep(mo):
choice = random.choice(self.quirk["randomlist"])
def upperrep(m):
return mo.expand(m.group(1)).upper()
choice = _upperre.sub(upperrep, choice)
return mo.expand(choice)
return re.sub(self.quirk["from"], randomrep, string)
elif self.type == "spelling":
percentage = self.quirk["percentage"]/100.0
words = string.split(" ")
newl = []
for w in words:
p = random.random()
if p < percentage:
newl.append(mispeller(w))
else:
newl.append(w)
return " ".join(newl)
def __str__(self):
if self.type == "prefix":
return "BEGIN WITH: %s" % (self.quirk["value"])
elif self.type == "suffix":
return "END WITH: %s" % (self.quirk["value"])
elif self.type == "replace":
return "REPLACE %s WITH %s" % (self.quirk["from"], self.quirk["to"])
elif self.type == "regexp":
return "REGEXP: %s REPLACED WITH %s" % (self.quirk["from"], self.quirk["to"])
elif self.type == "random":
return "REGEXP: %s RANDOMLY REPLACED WITH %s" % (self.quirk["from"], [str(r) for r in self.quirk["randomlist"]])
elif self.type == "spelling":
return "MISPELLER: %d%%" % (self.quirk["percentage"])
class pesterQuirks(object):
def __init__(self, quirklist):
self.quirklist = []
for q in quirklist:
self.addQuirk(q)
def plainList(self):
return [q.quirk for q in self.quirklist]
def addQuirk(self, q):
if type(q) == dict:
self.quirklist.append(pesterQuirk(q))
elif type(q) == pesterQuirk:
self.quirklist.append(q)
def apply(self, lexed, first=False, last=False):
prefix = [q for q in self.quirklist if q.type=='prefix']
suffix = [q for q in self.quirklist if q.type=='suffix']
replace = [q for q in self.quirklist if
q.type=='replace' or q.type=='regexp']
randomrep = [q for q in self.quirklist if q.type=='random']
spelling = [q for q in self.quirklist if q.type=='spelling']
newlist = []
for (i, o) in enumerate(lexed):
if type(o) not in [str, unicode]:
if i == 0:
string = " "
for p in prefix:
string += p.apply(string)
newlist.append(string)
newlist.append(o)
continue
lastStr = (i == len(lexed)-1)
string = o
for s in spelling:
string = s.apply(string)
for r in randomrep:
string = r.apply(string, first=(i==0), last=lastStr)
for r in replace:
string = r.apply(string, first=(i==0), last=lastStr)
if i == 0:
if len(prefix) >= 1:
myprefix = random.choice(prefix)
string = myprefix.apply(string)
if lastStr:
if len(suffix) >= 1:
mysuffix = random.choice(suffix)
string = mysuffix.apply(string)
newlist.append(string)
final = []
for n in newlist:
if type(n) in [str, unicode]:
final.extend(lexMessage(n))
else:
final.append(n)
return final
def __iter__(self):
for q in self.quirklist:
yield q
class PesterProfile(object):
def __init__(self, handle, color=None, mood=Mood("offline"), chumdb=None):
self.handle = handle
if color is None:
if chumdb:
color = chumdb.getColor(handle, QtGui.QColor("black"))
else:
color = QtGui.QColor("black")
self.color = color
self.mood = mood
def initials(self, time=None):
handle = self.handle
caps = [l for l in handle if l.isupper()]
if not caps:
caps = [""]
initials = (handle[0]+caps[0]).upper()
if hasattr(self, 'time') and time:
if self.time > time:
return "F"+initials
elif self.time < time:
return "P"+initials
else:
return "C"+initials
else:
return (handle[0]+caps[0]).upper()
def colorhtml(self):
if self.color:
return self.color.name()
else:
return "#000000"
def colorcmd(self):
if self.color:
(r, g, b, a) = self.color.getRgb()
return "%d,%d,%d" % (r,g,b)
else:
return "0,0,0"
def plaindict(self):
return (self.handle, {"handle": self.handle,
"mood": self.mood.name(),
"color": unicode(self.color.name())})
def blocked(self, config):
return self.handle in config.getBlocklist()
def memsg(self, syscolor, lexmsg, time=None):
suffix = lexmsg[0].suffix
msg = convertTags(lexmsg[1:], "text")
uppersuffix = suffix.upper()
if time is not None:
handle = "%s %s" % (time.temporal, self.handle)
initials = time.pcf+self.initials()+time.number+uppersuffix
else:
handle = self.handle
initials = self.initials()+uppersuffix
return "<c=%s>-- %s%s <c=%s>[%s]</c> %s --</c>" % (syscolor.name(), handle, suffix, self.colorhtml(), initials, msg)
def pestermsg(self, otherchum, syscolor, verb):
return "<c=%s>-- %s <c=%s>[%s]</c> %s %s <c=%s>[%s]</c> at %s --</c>" % (syscolor.name(), self.handle, self.colorhtml(), self.initials(), verb, otherchum.handle, otherchum.colorhtml(), otherchum.initials(), datetime.now().strftime("%H:%M"))
def moodmsg(self, mood, syscolor, theme):
return "<c=%s>-- %s <c=%s>[%s]</c> changed their mood to %s <img src='%s' /> --</c>" % (syscolor.name(), self.handle, self.colorhtml(), self.initials(), mood.name().upper(), theme["main/chums/moods"][mood.name()]["icon"])
def idlemsg(self, syscolor, verb):
return "<c=%s>-- %s <c=%s>[%s]</c> %s --" % (syscolor.name(), self.handle, self.colorhtml(), self.initials(), verb)
def memoclosemsg(self, syscolor, timeGrammar, verb):
return "<c=%s><c=%s>%s%s%s</c> %s.</c>" % (syscolor.name(), self.colorhtml(), timeGrammar.pcf, self.initials(), timeGrammar.number, verb)
def memoopenmsg(self, syscolor, td, timeGrammar, verb, channel):
(temporal, pcf, when) = (timeGrammar.temporal, timeGrammar.pcf, timeGrammar.when)
timetext = timeDifference(td)
initials = pcf+self.initials()
return "<c=%s><c=%s>%s</c> %s %s %s.</c>" % \
(syscolor.name(), self.colorhtml(), initials, timetext, verb, channel[1:].upper().replace("_", " "))
def memobanmsg(self, opchum, opgrammar, syscolor, timeGrammar):
initials = timeGrammar.pcf+self.initials()+timeGrammar.number
opinit = opgrammar.pcf+opchum.initials()+opgrammar.number
return "<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo." % \
(opchum.colorhtml(), opinit, self.colorhtml(), initials)
def memojoinmsg(self, syscolor, td, timeGrammar, verb):
(temporal, pcf, when) = (timeGrammar.temporal, timeGrammar.pcf, timeGrammar.when)
timetext = timeDifference(td)
initials = pcf+self.initials()+timeGrammar.number
return "<c=%s><c=%s>%s %s [%s]</c> %s %s." % \
(syscolor.name(), self.colorhtml(), temporal, self.handle,
initials, timetext, verb)
@staticmethod
def checkLength(handle):
return len(handle) <= 256
@staticmethod
def checkValid(handle):
caps = [l for l in handle if l.isupper()]
if len(caps) != 1 or handle[0].isupper():
return False
if re.search("[^A-Za-z0-9]", handle) is not None:
return False
return True
class PesterHistory(object):
def __init__(self):
self.history = []
self.current = 0
self.saved = None
def next(self, text):
if self.current == 0:
return None
if self.current == len(self.history):
self.save(text)
self.current -= 1
text = self.history[self.current]
return text
def prev(self):
self.current += 1
if self.current >= len(self.history):
self.current = len(self.history)
return self.retrieve()
return self.history[self.current]
def reset(self):
self.current = len(self.history)
self.saved = None
def save(self, text):
self.saved = text
def retrieve(self):
return self.saved
def add(self, text):
if len(self.history) == 0 or text != self.history[len(self.history)-1]:
self.history.append(text)
self.reset()