forked from Dpeta/pesterchum-alt-servers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataobjs.py
636 lines (584 loc) · 22.6 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
import logging
import ostools
PchumLog = logging.getLogger("pchumLogger")
try:
from PyQt6 import QtGui
except ImportError:
print("PyQt5 fallback (dataobjs.py)")
from PyQt5 import QtGui
from datetime import datetime
import re
import random
from mood import Mood
from parsetools import (
timeDifference,
convertTags,
lexMessage,
parseRegexpFunctions,
smiledict,
)
from mispeller import mispeller
_urlre = re.compile(r"(?i)(?:^|(?<=\s))(?:(?:https?|ftp)://|magnet:)[^\s]+")
# _url2re = re.compile(r"(?i)(?<!//)\bwww\.[^\s]+?\.")
_groupre = re.compile(r"\\([0-9]+)")
_upperre = re.compile(r"upper\(([\w<>\\]+)\)")
_lowerre = re.compile(r"lower\(([\w<>\\]+)\)")
_scramblere = re.compile(r"scramble\(([\w<>\\]+)\)")
_reversere = re.compile(r"reverse\(([\w<>\\]+)\)")
_ctagre = re.compile("(</?c=?.*?>)", re.I)
_smilere = re.compile("|".join(list(smiledict.keys())))
_memore = re.compile(r"(\s|^)(#[A-Za-z0-9_]+)")
_handlere = re.compile(r"(\s|^)(@[A-Za-z0-9_]+)")
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"]
if "on" not in self.quirk:
self.quirk["on"] = True
self.on = self.quirk["on"]
if "group" not in self.quirk:
self.quirk["group"] = "Miscellaneous"
self.group = self.quirk["group"]
try:
self.checkstate = self.quirk["checkstate"]
except KeyError:
pass
def apply(self, string, first=False, last=False):
if not self.on:
return string
elif 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
to = self.quirk["to"]
pt = parseRegexpFunctions(to)
return re.sub(fr, pt.expand, 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"])
pt = parseRegexpFunctions(choice)
return pt.expand(mo)
return re.sub(self.quirk["from"], randomrep, string)
elif self.type == "spelling":
percentage = self.quirk["percentage"] / 100.0
words = string.split(" ")
newl = []
ctag = re.compile("(</?c=?.*?>)", re.I)
for w in words:
p = random.random()
if not ctag.search(w) and p < percentage:
newl.append(mispeller(w))
elif p < percentage:
split = ctag.split(w)
tmp = []
for s in split:
if s and not ctag.search(s):
tmp.append(mispeller(s))
else:
tmp.append(s)
newl.append("".join(tmp))
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"],
[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"]
newlist = []
for (i, o) in enumerate(lexed):
if type(o) not in [str, str]:
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 q in self.quirklist:
try:
checkstate = int(q.checkstate)
except Exception:
checkstate = 0
# Exclude option is checked
if checkstate == 2:
# Check for substring that should be excluded.
excludes = list()
# Check for links, store in list.
for match in re.finditer(_urlre, string):
excludes.append(match)
# Check for smilies, store in list.
for match in re.finditer(_smilere, string):
excludes.append(match)
# Check for @handles, store in list.
for match in re.finditer(_handlere, string):
excludes.append(match)
# Check for #memos, store in list.
for match in re.finditer(_memore, string):
excludes.append(match)
if len(excludes) >= 1:
# SORT !!!
excludes.sort(key=lambda exclude: exclude.start())
# Recursion check.
# Strings like http://:3: require this.
for n in range(0, len(excludes) - 1):
if excludes[n].end() > excludes[n + 1].start():
excludes.pop(n)
# Seperate parts to be quirked.
sendparts = list()
# Add string until start of exclude at index 0.
until = excludes[0].start()
sendparts.append(string[:until])
# Add strings between excludes.
for part in range(1, len(excludes)):
after = excludes[part - 1].end()
until = excludes[part].start()
sendparts.append(string[after:until])
# Add string after exclude at last index.
after = excludes[-1].end()
sendparts.append(string[after:])
# Quirk to-be-quirked parts.
recvparts = list()
for part in sendparts:
# No split, apply like normal.
if q.type == "regexp" or q.type == "random":
recvparts.append(
q.apply(part, first=(i == 0), last=lastStr)
)
elif q.type == "prefix" and i == 0:
recvparts.append(q.apply(part))
elif q.type == "suffix" and lastStr:
recvparts.append(q.apply(part))
else:
recvparts.append(q.apply(part))
# Reconstruct and update string.
string = ""
# print("excludes: " + str(excludes))
# print("sendparts: " + str(sendparts))
# print("recvparts: " + str(recvparts))
for part in range(0, len(excludes)):
string += recvparts[part]
string += excludes[part].group()
string += recvparts[-1]
else:
# No split, apply like normal.
if q.type != "prefix" and q.type != "suffix":
if q.type == "regexp" or q.type == "random":
string = q.apply(string, first=(i == 0), last=lastStr)
else:
string = q.apply(string)
elif q.type == "prefix" and i == 0:
string = q.apply(string)
elif q.type == "suffix" and lastStr:
string = q.apply(string)
else:
# No split, apply like normal.
if q.type != "prefix" and q.type != "suffix":
if q.type == "regexp" or q.type == "random":
string = q.apply(string, first=(i == 0), last=lastStr)
else:
string = q.apply(string)
elif q.type == "prefix" and i == 0:
string = q.apply(string)
elif q.type == "suffix" and lastStr:
string = q.apply(string)
newlist.append(string)
final = []
for n in newlist:
if type(n) in [str, str]:
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"),
group=None,
notes="",
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
if group is None:
if chumdb:
group = chumdb.getGroup(handle, "Chums")
else:
group = "Chums"
self.group = group
self.notes = notes
def initials(self, time=None):
handle = self.handle
caps = [l for l in handle if l.isupper()]
if not caps:
caps = [""]
PchumLog.debug("handle = " + str(handle))
PchumLog.debug("caps = " + str(caps))
# Fallback for invalid string
try:
initials = (handle[0] + caps[0]).upper()
except:
PchumLog.exception("")
initials = "XX"
PchumLog.debug("initials = " + str(initials))
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 initials
def colorhtml(self):
if self.color:
return self.color.name()
else:
return "#000000"
def colorcmd(self):
if self.color:
(r, g, b, _) = 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": str(self.color.name()),
"group": str(self.group),
"notes": str(self.notes),
},
)
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 --</c>" % (
syscolor.name(),
self.handle,
self.colorhtml(),
self.initials(),
verb,
)
def memoclosemsg(self, syscolor, initials, verb):
if type(initials) == type(list()):
return "<c=%s><c=%s>%s</c> %s.</c>" % (
syscolor.name(),
self.colorhtml(),
", ".join(initials),
verb,
)
else:
return "<c=%s><c=%s>%s%s%s</c> %s.</c>" % (
syscolor.name(),
self.colorhtml(),
initials.pcf,
self.initials(),
initials.number,
verb,
)
def memonetsplitmsg(self, syscolor, initials):
if len(initials) <= 0:
return "<c=%s>Netsplit quits: <c=black>None</c></c>" % (syscolor.name())
else:
return "<c=%s>Netsplit quits: <c=black>%s</c></c>" % (
syscolor.name(),
", ".join(initials),
)
def memoopenmsg(self, syscolor, td, timeGrammar, verb, channel):
"""timeGrammar.temporal and timeGrammar.when are unused"""
timetext = timeDifference(td)
PchumLog.debug("pre pcf+self.initials()")
initials = timeGrammar.pcf + self.initials()
PchumLog.debug("post 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, initials, reason):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
if type(initials) == type(list()):
if opchum.handle == reason:
return "<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo." % (
opchum.colorhtml(),
opinit,
self.colorhtml(),
", ".join(initials),
)
else:
return (
"<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo: <c=black>[%s]</c>."
% (
opchum.colorhtml(),
opinit,
self.colorhtml(),
", ".join(initials),
str(reason),
)
)
else:
# Is timeGrammar defined? Not sure if this works as intented, added try except block to be safe.
try:
initials = timeGrammar.pcf + self.initials() + timeGrammar.number
if opchum.handle == reason:
return (
"<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo."
% (opchum.colorhtml(), opinit, self.colorhtml(), initials)
)
else:
return (
"<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo: <c=black>[%s]</c>."
% (
opchum.colorhtml(),
opinit,
self.colorhtml(),
initials,
str(reason),
)
)
except:
PchumLog.exception("")
initials = self.initials()
if opchum.handle == reason:
return (
"<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo."
% (opchum.colorhtml(), opinit, self.colorhtml(), initials)
)
else:
return (
"<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo: <c=black>[%s]</c>."
% (
opchum.colorhtml(),
opinit,
self.colorhtml(),
initials,
str(reason),
)
)
# As far as I'm aware, there's no IRC reply for this, this seems impossible to check for in practice.
def memopermabanmsg(self, opchum, opgrammar, syscolor, timeGrammar):
initials = timeGrammar.pcf + self.initials() + timeGrammar.number
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s>%s</c> permabanned <c=%s>%s</c> from the 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 = timeGrammar.pcf + self.initials() + timeGrammar.number
return "<c=%s><c=%s>%s %s [%s]</c> %s %s.</c>" % (
syscolor.name(),
self.colorhtml(),
timeGrammar.temporal,
self.handle,
initials,
timetext,
verb,
)
def memoopmsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s>%s</c> made <c=%s>%s</c> an OP." % (
opchum.colorhtml(),
opinit,
self.colorhtml(),
self.initials(),
)
def memodeopmsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s>%s</c> took away <c=%s>%s</c>'s OP powers." % (
opchum.colorhtml(),
opinit,
self.colorhtml(),
self.initials(),
)
def memovoicemsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s>%s</c> gave <c=%s>%s</c> voice." % (
opchum.colorhtml(),
opinit,
self.colorhtml(),
self.initials(),
)
def memodevoicemsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s>%s</c> took away <c=%s>%s</c>'s voice." % (
opchum.colorhtml(),
opinit,
self.colorhtml(),
self.initials(),
)
def memomodemsg(self, opchum, opgrammar, syscolor, modeverb, modeon):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
if modeon:
modeon = "now"
else:
modeon = "no longer"
return "<c=%s>Memo is %s <c=black>%s</c> by <c=%s>%s</c></c>" % (
syscolor.name(),
modeon,
modeverb,
opchum.colorhtml(),
opinit,
)
def memoquirkkillmsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s><c=%s>%s</c> turned off your quirk.</c>" % (
syscolor.name(),
opchum.colorhtml(),
opinit,
)
@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:
return (False, "Must have exactly 1 uppercase letter")
if handle[0].isupper():
return (False, "Cannot start with uppercase letter")
if re.search("[^A-Za-z0-9]", handle) is not None:
return (False, "Only alphanumeric characters allowed")
if handle[0].isnumeric(): # IRC doesn't allow this
return (False, "Handles may not start with a number")
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()