-
Notifications
You must be signed in to change notification settings - Fork 50
/
profile.py
663 lines (642 loc) · 23.5 KB
/
profile.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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
import logging
import os
from string import Template
import json
import re
import codecs
import platform
from datetime import *
from time import strftime, time
from PyQt5 import QtGui, QtCore, QtWidgets
import ostools
from mood import Mood
from dataobjs import PesterProfile, pesterQuirk, pesterQuirks
from parsetools import convertTags, addTimeInitial, themeChecker, ThemeException
_datadir = ostools.getDataDir()
class PesterLog(object):
def __init__(self, handle, parent=None):
global _datadir
self.parent = parent
self.handle = handle
self.convos = {}
self.logpath = _datadir+"logs"
def log(self, handle, msg):
if self.parent.config.time12Format():
time = strftime("[%I:%M")
else:
time = strftime("[%H:%M")
if self.parent.config.showSeconds():
time += strftime(":%S] ")
else:
time += "] "
if handle[0] == '#':
if not self.parent.config.logMemos() & self.parent.config.LOG: return
if not self.parent.config.logMemos() & self.parent.config.STAMP:
time = ""
else:
if not self.parent.config.logPesters() & self.parent.config.LOG: return
if not self.parent.config.logPesters() & self.parent.config.STAMP:
time = ""
if str(handle).upper() == "NICKSERV": return
#watch out for illegal characters
handle = re.sub(r'[<>:"/\\|?*]', "_", handle)
bbcodemsg = time + convertTags(msg, "bbcode")
html = time + convertTags(msg, "html")+"<br />"
msg = time +convertTags(msg, "text")
modes = {"bbcode": bbcodemsg, "html": html, "text": msg}
if handle not in self.convos:
time = datetime.now().strftime("%Y-%m-%d.%H.%M")
self.convos[handle] = {}
for (format, t) in modes.items():
if not os.path.exists("%s/%s/%s/%s" % (self.logpath, self.handle, handle, format)):
os.makedirs("%s/%s/%s/%s" % (self.logpath, self.handle, handle, format))
try:
fp = codecs.open("%s/%s/%s/%s/%s.%s.txt" % (self.logpath, self.handle, handle, format, handle, time), encoding='utf-8', mode='a')
except IOError:
errmsg = QtWidgets.QMessageBox(self)
errmsg.setText("Warning: Pesterchum could not open the log file for %s!" % (handle))
errmsg.setInformativeText("Your log for %s will not be saved because something went wrong. We suggest restarting Pesterchum. Sorry :(" % (handle))
errmsg.show()
continue
self.convos[handle][format] = fp
for (format, t) in modes.items():
f = self.convos[handle][format]
if platform.system() == "Windows":
f.write(t+"\r\n")
else:
f.write(t+"\r\n")
f.flush()
def finish(self, handle):
if handle not in self.convos:
return
for f in list(self.convos[handle].values()):
f.close()
del self.convos[handle]
def close(self):
for h in list(self.convos.keys()):
for f in list(self.convos[h].values()):
f.close()
class userConfig(object):
def __init__(self, parent):
self.parent = parent
# Use for bit flag log setting
self.LOG = 1
self.STAMP = 2
# Use for bit flag blink
self.PBLINK = 1
self.MBLINK = 2
# Use for bit flag notfications
self.SIGNIN = 1
self.SIGNOUT = 2
self.NEWMSG = 4
self.NEWCONVO = 8
self.INITIALS = 16
self.filename = _datadir+"pesterchum.js"
fp = open(self.filename)
self.config = json.load(fp)
fp.close()
if "defaultprofile" in self.config:
self.userprofile = userProfile(self.config["defaultprofile"])
else:
self.userprofile = None
self.logpath = _datadir+"logs"
if not os.path.exists(self.logpath):
os.makedirs(self.logpath)
try:
fp = open("%s/groups.js" % (self.logpath), 'r')
self.groups = json.load(fp)
fp.close()
except IOError:
self.groups = {}
fp = open("%s/groups.js" % (self.logpath), 'w')
json.dump(self.groups, fp)
fp.close()
except ValueError:
self.groups = {}
fp = open("%s/groups.js" % (self.logpath), 'w')
json.dump(self.groups, fp)
fp.close()
def chums(self):
if 'chums' not in self.config:
self.set("chums", [])
return self.config.get('chums', [])
def setChums(self, newchums):
fp = open(self.filename) # what if we have two clients open??
newconfig = json.load(fp)
fp.close()
oldchums = newconfig['chums']
# Time to merge these two! :OOO
for c in list(set(oldchums) - set(newchums)):
newchums.append(c)
self.set("chums", newchums)
def hideOfflineChums(self):
return self.config.get('hideOfflineChums', False)
def defaultprofile(self):
try:
return self.config['defaultprofile']
except KeyError:
return None
def tabs(self):
return self.config.get("tabs", True)
def tabMemos(self):
if 'tabmemos' not in self.config:
self.set("tabmemos", self.tabs())
return self.config.get("tabmemos", True)
def showTimeStamps(self):
if 'showTimeStamps' not in self.config:
self.set("showTimeStamps", True)
return self.config.get('showTimeStamps', True)
def time12Format(self):
if 'time12Format' not in self.config:
self.set("time12Format", True)
return self.config.get('time12Format', True)
def showSeconds(self):
if 'showSeconds' not in self.config:
self.set("showSeconds", False)
return self.config.get('showSeconds', False)
def sortMethod(self):
return self.config.get('sortMethod', 0)
def useGroups(self):
return self.config.get('useGroups', False)
def openDefaultGroup(self):
groups = self.getGroups()
for g in groups:
if g[0] == "Chums":
return g[1]
return True
def showEmptyGroups(self):
if 'emptyGroups' not in self.config:
self.set("emptyGroups", False)
return self.config.get('emptyGroups', False)
def showOnlineNumbers(self):
if 'onlineNumbers' not in self.config:
self.set("onlineNumbers", False)
return self.config.get('onlineNumbers', False)
def logPesters(self):
return self.config.get('logPesters', self.LOG | self.STAMP)
def logMemos(self):
return self.config.get('logMemos', self.LOG)
def disableUserLinks(self):
return not self.config.get('userLinks', True)
def idleTime(self):
return self.config.get('idleTime', 10)
def minimizeAction(self):
return self.config.get('miniAction', 0)
def closeAction(self):
return self.config.get('closeAction', 1)
def opvoiceMessages(self):
return self.config.get('opvMessages', True)
def animations(self):
return self.config.get('animations', True)
def checkForUpdates(self):
u = self.config.get('checkUpdates', 0)
if type(u) == type(bool()):
if u: u = 2
else: u = 3
return u
# Once a day
# Once a week
# Only on start
# Never
def lastUCheck(self):
return self.config.get('lastUCheck', 0)
def checkMSPA(self):
return self.config.get('mspa', False)
def blink(self):
return self.config.get('blink', self.PBLINK | self.MBLINK)
def notify(self):
return self.config.get('notify', True)
def notifyType(self):
return self.config.get('notifyType', "default")
def notifyOptions(self):
return self.config.get('notifyOptions', self.SIGNIN | self.NEWMSG | self.NEWCONVO | self.INITIALS)
def lowBandwidth(self):
return self.config.get('lowBandwidth', False)
def ghostchum(self):
return self.config.get('ghostchum', False)
def addChum(self, chum):
if chum.handle not in self.chums():
fp = open(self.filename) # what if we have two clients open??
newconfig = json.load(fp)
fp.close()
newchums = newconfig['chums'] + [chum.handle]
self.set("chums", newchums)
def removeChum(self, chum):
if type(chum) is PesterProfile:
handle = chum.handle
else:
handle = chum
newchums = [c for c in self.config['chums'] if c != handle]
self.set("chums", newchums)
def getBlocklist(self):
if 'block' not in self.config:
self.set('block', [])
return self.config['block']
def addBlocklist(self, handle):
l = self.getBlocklist()
if handle not in l:
l.append(handle)
self.set('block', l)
def delBlocklist(self, handle):
l = self.getBlocklist()
l.pop(l.index(handle))
self.set('block', l)
def getGroups(self):
if 'groups' not in self.groups:
self.saveGroups([["Chums", True]])
return self.groups.get('groups', [["Chums", True]])
def addGroup(self, group, open=True):
l = self.getGroups()
exists = False
for g in l:
if g[0] == group:
exists = True
break
if not exists:
l.append([group,open])
l.sort()
self.saveGroups(l)
def delGroup(self, group):
l = self.getGroups()
i = 0
for g in l:
if g[0] == group: break
i = i+1
l.pop(i)
l.sort()
self.saveGroups(l)
def expandGroup(self, group, open=True):
l = self.getGroups()
for g in l:
if g[0] == group:
g[1] = open
break
self.saveGroups(l)
def saveGroups(self, groups):
self.groups['groups'] = groups
try:
jsonoutput = json.dumps(self.groups)
except ValueError as e:
raise e
fp = open("%s/groups.js" % (self.logpath), 'w')
fp.write(jsonoutput)
fp.close()
def server(self):
if hasattr(self.parent, 'serverOverride'):
return self.parent.serverOverride
return self.config.get('server', 'irc.mindfang.org')
def port(self):
if hasattr(self.parent, 'portOverride'):
return self.parent.portOverride
return self.config.get('port', '6667')
def soundOn(self):
if 'soundon' not in self.config:
self.set('soundon', True)
return self.config['soundon']
def chatSound(self):
return self.config.get('chatSound', True)
def memoSound(self):
return self.config.get('memoSound', True)
def memoPing(self):
return self.config.get('pingSound', True)
def nameSound(self):
return self.config.get('nameSound', True)
def volume(self):
return self.config.get('volume', 100)
def trayMessage(self):
return self.config.get('traymsg', True)
def set(self, item, setting):
self.config[item] = setting
try:
jsonoutput = json.dumps(self.config)
except ValueError as e:
raise e
fp = open(self.filename, 'w')
fp.write(jsonoutput)
fp.close()
def availableThemes(self):
themes = []
# Load user themes.
for dirname, dirnames, filenames in os.walk(_datadir+'themes'):
for d in dirnames:
themes.append(d)
# Also load embedded themes.
if _datadir:
for dirname, dirnames, filenames in os.walk('themes'):
for d in dirnames:
if d not in themes:
themes.append(d)
themes.sort()
return themes
def availableProfiles(self):
profs = []
profileloc = _datadir+'profiles'
for dirname, dirnames, filenames in os.walk(profileloc):
for filename in filenames:
l = len(filename)
if filename[l-3:l] == ".js":
profs.append(filename[0:l-3])
profs.sort()
return [userProfile(p) for p in profs]
class userProfile(object):
def __init__(self, user):
self.profiledir = _datadir+"profiles"
if type(user) is PesterProfile:
self.chat = user
self.userprofile = {"handle":user.handle,
"color": str(user.color.name()),
"quirks": [],
"theme": "pesterchum"}
self.theme = pesterTheme("pesterchum")
self.chat.mood = Mood(self.theme["main/defaultmood"])
self.lastmood = self.chat.mood.value()
self.quirks = pesterQuirks([])
self.randoms = False
initials = self.chat.initials()
if len(initials) >= 2:
initials = (initials, "%s%s" % (initials[0].lower(), initials[1]), "%s%s" % (initials[0], initials[1].lower()))
self.mentions = [r"\b(%s)\b" % ("|".join(initials))]
else:
self.mentions = []
self.autojoins = []
else:
fp = open("%s/%s.js" % (self.profiledir, user))
self.userprofile = json.load(fp)
fp.close()
try:
self.theme = pesterTheme(self.userprofile["theme"])
except ValueError as e:
self.theme = pesterTheme("pesterchum")
self.lastmood = self.userprofile.get('lastmood', self.theme["main/defaultmood"])
self.chat = PesterProfile(self.userprofile["handle"],
QtGui.QColor(self.userprofile["color"]),
Mood(self.lastmood))
self.quirks = pesterQuirks(self.userprofile["quirks"])
if "randoms" not in self.userprofile:
self.userprofile["randoms"] = False
self.randoms = self.userprofile["randoms"]
if "mentions" not in self.userprofile:
initials = self.chat.initials()
if len(initials) >= 2:
initials = (initials, "%s%s" % (initials[0].lower(), initials[1]), "%s%s" % (initials[0], initials[1].lower()))
self.userprofile["mentions"] = [r"\b(%s)\b" % ("|".join(initials))]
else:
self.userprofile["mentions"] = []
self.mentions = self.userprofile["mentions"]
if "autojoins" not in self.userprofile:
self.userprofile["autojoins"] = []
self.autojoins = self.userprofile["autojoins"]
try:
with open(_datadir+"passwd.js") as fp:
self.passwd = json.load(fp)
except Exception as e:
self.passwd = {}
self.autoidentify = False
self.nickservpass = ""
if self.chat.handle in self.passwd:
self.autoidentify = self.passwd[self.chat.handle]["auto"]
self.nickservpass = self.passwd[self.chat.handle]["pw"]
def setMood(self, mood):
self.chat.mood = mood
def setTheme(self, theme):
self.theme = theme
self.userprofile["theme"] = theme.name
self.save()
def setColor(self, color):
self.chat.color = color
self.userprofile["color"] = str(color.name())
self.save()
def setQuirks(self, quirks):
self.quirks = quirks
self.userprofile["quirks"] = self.quirks.plainList()
self.save()
def getRandom(self):
return self.randoms
def setRandom(self, random):
self.randoms = random
self.userprofile["randoms"] = random
self.save()
def getMentions(self):
return self.mentions
def setMentions(self, mentions):
try:
for (i,m) in enumerate(mentions):
re.compile(m)
except re.error as e:
logging.error("#%s Not a valid regular expression: %s" % (i, e))
else:
self.mentions = mentions
self.userprofile["mentions"] = mentions
self.save()
def getLastMood(self):
return self.lastmood
def setLastMood(self, mood):
self.lastmood = mood.value()
self.userprofile["lastmood"] = self.lastmood
self.save()
def getTheme(self):
return self.theme
def getAutoIdentify(self):
return self.autoidentify
def setAutoIdentify(self, b):
self.autoidentify = b
if self.chat.handle not in self.passwd:
self.passwd[self.chat.handle] = {}
self.passwd[self.chat.handle]["auto"] = b
self.saveNickServPass()
def getNickServPass(self):
return self.nickservpass
def setNickServPass(self, pw):
self.nickservpass = pw
if self.chat.handle not in self.passwd:
self.passwd[self.chat.handle] = {}
self.passwd[self.chat.handle]["pw"] = pw
self.saveNickServPass()
def getAutoJoins(self):
return self.autojoins
def setAutoJoins(self, autojoins):
self.autojoins = autojoins
self.userprofile["autojoins"] = self.autojoins
self.save()
def save(self):
handle = self.chat.handle
if handle[0:12] == "pesterClient":
# dont save temp profiles
return
try:
jsonoutput = json.dumps(self.userprofile)
except ValueError as e:
raise e
fp = open("%s/%s.js" % (self.profiledir, handle), 'w')
fp.write(jsonoutput)
fp.close()
def saveNickServPass(self):
# remove profiles with no passwords
for h,t in list(self.passwd.items()):
if "auto" not in t or "pw" not in t or t["pw"] == "":
del self.passwd[h]
try:
jsonoutput = json.dumps(self.passwd, indent=4)
except ValueError as e:
raise e
with open(_datadir+"passwd.js", 'w') as fp:
fp.write(jsonoutput)
@staticmethod
def newUserProfile(chatprofile):
if os.path.exists("%s/%s.js" % (_datadir+"profiles", chatprofile.handle)):
newprofile = userProfile(chatprofile.handle)
else:
newprofile = userProfile(chatprofile)
newprofile.save()
return newprofile
class PesterProfileDB(dict):
def __init__(self):
self.logpath = _datadir+"logs"
if not os.path.exists(self.logpath):
os.makedirs(self.logpath)
try:
fp = open("%s/chums.js" % (self.logpath), 'r')
chumdict = json.load(fp)
fp.close()
except IOError:
chumdict = {}
fp = open("%s/chums.js" % (self.logpath), 'w')
json.dump(chumdict, fp)
fp.close()
except ValueError:
chumdict = {}
fp = open("%s/chums.js" % (self.logpath), 'w')
json.dump(chumdict, fp)
fp.close()
u = []
for (handle, c) in chumdict.items():
options = dict()
if 'group' in c:
options['group'] = c['group']
if 'notes' in c:
options['notes'] = c['notes']
if 'color' not in c:
c['color'] = "#000000"
if 'mood' not in c:
c['mood'] = "offline"
u.append((handle, PesterProfile(handle, color=QtGui.QColor(c['color']), mood=Mood(c['mood']), **options)))
converted = dict(u)
self.update(converted)
def save(self):
try:
fp = open("%s/chums.js" % (self.logpath), 'w')
chumdict = dict([p.plaindict() for p in self.values()])
json.dump(chumdict, fp)
fp.close()
except Exception as e:
raise e
def getColor(self, handle, default=None):
if handle not in self:
return default
else:
return self[handle].color
def setColor(self, handle, color):
if handle in self:
self[handle].color = color
else:
self[handle] = PesterProfile(handle, color)
def getGroup(self, handle, default="Chums"):
if handle not in self:
return default
else:
return self[handle].group
def setGroup(self, handle, theGroup):
if handle in self:
self[handle].group = theGroup
else:
self[handle] = PesterProfile(handle, group=theGroup)
self.save()
def getNotes(self, handle, default=""):
if handle not in self:
return default
else:
return self[handle].notes
def setNotes(self, handle, notes):
if handle in self:
self[handle].notes = notes
else:
self[handle] = PesterProfile(handle, notes=notes)
self.save()
def __setitem__(self, key, val):
dict.__setitem__(self, key, val)
self.save()
class pesterTheme(dict):
def __init__(self, name, default=False):
possiblepaths = (_datadir+"themes/%s" % (name),
"themes/%s" % (name),
_datadir+"themes/pesterchum",
"themes/pesterchum")
self.path = "themes/pesterchum"
for p in possiblepaths:
if os.path.exists(p):
self.path = p
break
self.name = name
try:
fp = open(self.path+"/style.js")
theme = json.load(fp, object_hook=self.pathHook)
fp.close()
except IOError:
theme = json.loads("{}")
self.update(theme)
if "inherits" in self:
self.inheritedTheme = pesterTheme(self["inherits"])
if not default:
self.defaultTheme = pesterTheme("pesterchum", default=True)
def __getitem__(self, key):
keys = key.split("/")
try:
v = dict.__getitem__(self, keys.pop(0))
except KeyError as e:
if hasattr(self, 'inheritedTheme'):
return self.inheritedTheme[key]
if hasattr(self, 'defaultTheme'):
return self.defaultTheme[key]
else:
raise e
for k in keys:
try:
v = v[k]
except KeyError as e:
if hasattr(self, 'inheritedTheme'):
return self.inheritedTheme[key]
if hasattr(self, 'defaultTheme'):
return self.defaultTheme[key]
else:
raise e
return v
def pathHook(self, d):
for (k, v) in d.items():
if type(v) is str:
s = Template(v)
d[k] = s.safe_substitute(path=self.path)
return d
def get(self, key, default):
keys = key.split("/")
try:
v = dict.__getitem__(self, keys.pop(0))
for k in keys:
v = v[k]
return default if v is None else v
except KeyError:
if hasattr(self, 'inheritedTheme'):
return self.inheritedTheme.get(key, default)
else:
return default
def has_key(self, key):
keys = key.split("/")
try:
v = dict.__getitem__(self, keys.pop(0))
for k in keys:
v = v[k]
return False if v is None else True
except KeyError:
if hasattr(self, 'inheritedTheme'):
return key in self.inheritedTheme
else:
return False