This repository has been archived by the owner on Mar 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ch.py
2394 lines (2080 loc) · 60 KB
/
ch.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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
################################################################
# Imports
################################################################
import socket
import threading
import time
import random
import re
import sys
import select
################################################################
# Debug stuff
################################################################
debug = False
################################################################
# Python 2 compatibility
################################################################
if sys.version_info[0] < 3:
class urllib:
parse = __import__("urllib")
request = __import__("urllib2")
input = raw_input
import codecs
import Queue as queue
else:
import queue
import urllib.request
import urllib.parse
################################################################
# Constants
################################################################
Userlist_Recent = 0
Userlist_All = 1
BigMessage_Multiple = 0
BigMessage_Cut = 1
# minimum of 1 thread needed
Number_of_Threads = 1
################################################################
# Struct class
################################################################
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
################################################################
# Tagserver stuff
################################################################
specials = {'mitvcanal': 56, 'animeultimacom': 34, 'cricket365live': 21, 'pokemonepisodeorg': 22, 'animelinkz': 20, 'sport24lt': 56, 'narutowire': 10, 'watchanimeonn': 22, 'cricvid-hitcric-': 51, 'narutochatt': 70, 'leeplarp': 27, 'stream2watch3': 56, 'ttvsports': 56, 'ver-anime': 8, 'vipstand': 21, 'eafangames': 56, 'soccerjumbo': 21, 'myfoxdfw': 67, 'kiiiikiii': 21, 'de-livechat': 5, 'rgsmotrisport': 51, 'dbzepisodeorg': 10, 'watch-dragonball': 8, 'peliculas-flv': 69, 'tvanimefreak': 54, 'tvtvanimefreak': 54}
tsweights = [['5', 75], ['6', 75], ['7', 75], ['8', 75], ['16', 75], ['17', 75], ['18', 75], ['9', 95], ['11', 95], ['12', 95], ['13', 95], ['14', 95], ['15', 95], ['19', 110], ['23', 110], ['24', 110], ['25', 110], ['26', 110], ['28', 104], ['29', 104], ['30', 104], ['31', 104], ['32', 104], ['33', 104], ['35', 101], ['36', 101], ['37', 101], ['38', 101], ['39', 101], ['40', 101], ['41', 101], ['42', 101], ['43', 101], ['44', 101], ['45', 101], ['46', 101], ['47', 101], ['48', 101], ['49', 101], ['50', 101], ['52', 110], ['53', 110], ['55', 110], ['57', 110], ['58', 110], ['59', 110], ['60', 110], ['61', 110], ['62', 110], ['63', 110], ['64', 110], ['65', 110], ['66', 110], ['68', 95], ['71', 116], ['72', 116], ['73', 116], ['74', 116], ['75', 116], ['76', 116], ['77', 116], ['78', 116], ['79', 116], ['80', 116], ['81', 116], ['82', 116], ['83', 116], ['84', 116]]
def getServer(group):
"""
Get the server host for a certain room.
@type group: str
@param group: room name
@rtype: str
@return: the server's hostname
"""
try:
sn = specials[group]
except KeyError:
group = group.replace("_", "q")
group = group.replace("-", "q")
fnv = float(int(group[0:min(5, len(group))], 36))
lnv = group[6: (6 + min(3, len(group) - 5))]
if(lnv):
lnv = float(int(lnv, 36))
lnv = max(lnv,1000)
else:
lnv = 1000
num = (fnv % lnv) / lnv
maxnum = sum(map(lambda x: x[1], tsweights))
cumfreq = 0
sn = 0
for wgt in tsweights:
cumfreq += float(wgt[1]) / maxnum
if(num <= cumfreq):
sn = int(wgt[0])
break
return "s" + str(sn) + ".chatango.com"
################################################################
# Uid
################################################################
def _genUid():
"""
generate a uid
"""
return str(random.randrange(10 ** 15, 10 ** 16))
################################################################
# Message stuff
################################################################
def _clean_message(msg):
"""
Clean a message and return the message, n tag and f tag.
@type msg: str
@param msg: the message
@rtype: str, str, str
@returns: cleaned message, n tag contents, f tag contents
"""
n = re.search("<n(.*?)/>", msg)
if n: n = n.group(1)
f = re.search("<f(.*?)>", msg)
if f: f = f.group(1)
msg = re.sub("<n.*?/>", "", msg)
msg = re.sub("<f.*?>", "", msg)
msg = _strip_html(msg)
msg = msg.replace("<", "<")
msg = msg.replace(">", ">")
msg = msg.replace(""", "\"")
msg = msg.replace("'", "'")
msg = msg.replace("&", "&")
return msg, n, f
def _strip_html(msg):
"""Strip HTML."""
li = msg.split("<")
if len(li) == 1:
return li[0]
else:
ret = list()
for data in li:
data = data.split(">", 1)
if len(data) == 1:
ret.append(data[0])
elif len(data) == 2:
ret.append(data[1])
return "".join(ret)
def _parseNameColor(n):
"""This just returns its argument, should return the name color."""
#probably is already the name
return n
def _parseFont(f):
"""Parses the contents of a f tag and returns color, face and size."""
#' xSZCOL="FONT"'
try: #TODO: remove quick hack
sizecolor, fontface = f.split("=", 1)
sizecolor = sizecolor.strip()
size = int(sizecolor[1:3])
col = sizecolor[3:6]
if col == "": col = None
face = f.split("\"", 2)[1]
return col, face, size
except:
return None, None, None
################################################################
# Anon id
################################################################
def _getAnonId(n, ssid):
"""Gets the anon's id."""
if n == None: n = "5504"
try:
return "".join(list(
map(lambda x: str(x[0] + x[1])[-1], list(zip(
list(map(lambda x: int(x), n)),
list(map(lambda x: int(x), ssid[4:]))
)))
))
except ValueError:
return "NNNN"
################################################################
# ANON PM class
################################################################
class _ANON_PM_OBJECT:
"""Manages connection with Chatango anon PM."""
def __init__(self, mgr, name):
self._connected = False
self._mgr = mgr
self._wlock = False
self._firstCommand = True
self._wbuf = b""
self._wlockbuf = b""
self._rbuf = b""
self._pingTask = None
self._name = name
def _auth(self):
self._sendCommand("mhs","mini","unknown","%s" % (self._name))
self._setWriteLock(True)
return True
def disconnect(self):
"""Disconnect the bot from PM"""
self._disconnect()
self._callEvent("onAnonPMDisconnect", User(self._name))
def _disconnect(self):
self._connected = False
self._sock.close()
self._sock = None
def ping(self):
"""send a ping"""
self._sendCommand("")
self._callEvent("onPMPing")
def message(self, user, msg):
"""send a pm to a user"""
if msg!=None:
self._sendCommand("msg", user.name, msg)
####
# Feed
####
def _feed(self, data):
"""
Feed data to the connection.
@type data: bytes
@param data: data to be fed
"""
self._rbuf += data
while self._rbuf.find(b"\x00") != -1:
data = self._rbuf.split(b"\x00")
for food in data[:-1]:
self._process(food.decode(errors="replace").rstrip("\r\n"))
self._rbuf = data[-1]
def _process(self, data):
"""
Process a command string.
@type data: str
@param data: the command string
"""
self._callEvent("onRaw", data)
data = data.split(":")
cmd, args = data[0], data[1:]
func = "_rcmd_" + cmd
if hasattr(self, func):
getattr(self, func)(args)
else:
if debug:
print("unknown data: "+str(data))
def _getManager(self): return self._mgr
mgr = property(_getManager)
####
# Received Commands
####
def _rcmd_mhs(self, args):
"""
note to future maintainers
args[1] is ether "online" or "offline"
"""
self._connected = True
self._setWriteLock(False)
def _rcmd_msg(self, args):
user = User(args[0])
body = _strip_html(":".join(args[5:]))
self._callEvent("onPMMessage", user, body)
####
# Util
####
def _callEvent(self, evt, *args, **kw):
getattr(self.mgr, evt)(self, *args, **kw)
self.mgr.onEventCalled(self, evt, *args, **kw)
def _write(self, data):
if self._wlock:
self._wlockbuf += data
else:
self.mgr._write(self, data)
def _setWriteLock(self, lock):
self._wlock = lock
if self._wlock == False:
self._write(self._wlockbuf)
self._wlockbuf = b""
def _sendCommand(self, *args):
"""
Send a command.
@type args: [str, str, ...]
@param args: command and list of arguments
"""
if self._firstCommand:
terminator = b"\x00"
self._firstCommand = False
else:
terminator = b"\r\n\x00"
self._write(":".join(args).encode() + terminator)
class ANON_PM:
"""Comparable wrapper for anon Chatango PM"""
####
# Init
####
def __init__(self, mgr):
self._mgr = mgr
self._wlock = False
self._firstCommand = True
self._persons = dict()
self._wlockbuf = b""
self._pingTask = None
####
# Connections
####
def _connect(self,name):
self._persons[name] = _ANON_PM_OBJECT(self._mgr,name)
sock = socket.socket()
sock.connect((self._mgr._anonPMHost, self._mgr._PMPort))
sock.setblocking(False)
self._persons[name]._sock = sock
if not self._persons[name]._auth(): return
self._persons[name]._pingTask = self._mgr.setInterval(self._mgr._pingDelay, self._persons[name].ping)
self._persons[name]._connected = True
def message(self, user, msg):
"""send a pm to a user"""
if not user.name in self._persons:
self._connect(user.name)
self._persons[user.name].message(user,msg)
def getConnections(self):
return list(self._persons.values())
################################################################
# PM class
################################################################
class PM:
"""Manages a connection with Chatango PM."""
####
# Init
####
def __init__(self, mgr):
self._auth_re = re.compile(r"auth\.chatango\.com ?= ?([^;]*)", re.IGNORECASE)
self._connected = False
self._mgr = mgr
self._auid = None
self._blocklist = set()
self._contacts = set()
self._status = dict()
self._wlock = False
self._firstCommand = True
self._wbuf = b""
self._wlockbuf = b""
self._rbuf = b""
self._pingTask = None
self._connect()
####
# Connections
####
def _connect(self):
self._wbuf = b""
self._sock = socket.socket()
self._sock.connect((self._mgr._PMHost, self._mgr._PMPort))
self._sock.setblocking(False)
self._firstCommand = True
if not self._auth(): return
self._pingTask = self.mgr.setInterval(self._mgr._pingDelay, self.ping)
self._connected = True
def _getAuth(self, name, password):
"""
Request an auid using name and password.
@type name: str
@param name: name
@type password: str
@param password: password
@rtype: str
@return: auid
"""
data = urllib.parse.urlencode({
"user_id": name,
"password": password,
"storecookie": "on",
"checkerrors": "yes"
}).encode()
try:
resp = urllib.request.urlopen("http://chatango.com/login", data)
headers = resp.headers
except Exception:
return None
for header, value in headers.items():
if header.lower() == "set-cookie":
m = self._auth_re.search(value)
if m:
auth = m.group(1)
if auth == "":
return None
return auth
return None
def _auth(self):
self._auid = self._getAuth(self._mgr.name, self._mgr.password)
if self._auid == None:
self._sock.close()
self._callEvent("onLoginFail")
self._sock = None
return False
self._sendCommand("tlogin", self._auid, "2")
self._setWriteLock(True)
return True
def disconnect(self):
"""Disconnect the bot from PM"""
self._disconnect()
self._callEvent("onPMDisconnect")
def _disconnect(self):
self._connected = False
self._sock.close()
self._sock = None
####
# Feed
####
def _feed(self, data):
"""
Feed data to the connection.
@type data: bytes
@param data: data to be fed
"""
self._rbuf += data
while self._rbuf.find(b"\x00") != -1:
data = self._rbuf.split(b"\x00")
for food in data[:-1]:
self._process(food.decode(errors="replace").rstrip("\r\n"))
self._rbuf = data[-1]
def _process(self, data):
"""
Process a command string.
@type data: str
@param data: the command string
"""
self._callEvent("onRaw", data)
data = data.split(":")
cmd, args = data[0], data[1:]
func = "_rcmd_" + cmd
if hasattr(self, func):
getattr(self, func)(args)
else:
if debug:
print("unknown data: "+str(data))
####
# Properties
####
def _getManager(self): return self._mgr
def _getContacts(self): return self._contacts
def _getBlocklist(self): return self._blocklist
mgr = property(_getManager)
contacts = property(_getContacts)
blocklist = property(_getBlocklist)
####
# Received Commands
####
def _rcmd_OK(self, args):
self._setWriteLock(False)
self._sendCommand("wl")
self._sendCommand("getblock")
self._callEvent("onPMConnect")
def _rcmd_wl(self, args):
self._contacts = set()
for i in range(len(args) // 4):
name, last_on, is_on, idle = args[i * 4: i * 4 + 4]
user = User(name)
if last_on=="None":pass#in case chatango gives a "None" as data argument
elif not is_on == "on": self._status[user] = [int(last_on), False, 0]
elif idle == '0': self._status[user] = [int(last_on), True, 0]
else: self._status[user] = [int(last_on), True, time.time() - int(idle) * 60]
self._contacts.add(user)
self._callEvent("onPMContactlistReceive")
def _rcmd_block_list(self, args):
self._blocklist = set()
for name in args:
if name == "": continue
self._blocklist.add(User(name))
def _rcmd_idleupdate(self, args):
user = User(args[0])
last_on, is_on, idle = self._status[user]
if args[1] == '1':
self._status[user] = [last_on, is_on, 0]
else:
self._status[user] = [last_on, is_on, time.time()]
def _rcmd_track(self, args):
user = User(args[0])
if user in self._status:
last_on = self._status[user][0]
else:
last_on = 0
if args[1] == '0':
idle = 0
else:
idle = time.time() - int(args[1]) * 60
if args[2] == "online":
is_on = True
else:
is_on = False
self._status[user] = [last_on, is_on, idle]
def _rcmd_DENIED(self, args):
self._disconnect()
self._callEvent("onLoginFail")
def _rcmd_msg(self, args):
user = User(args[0])
body = _strip_html(":".join(args[5:]))
self._callEvent("onPMMessage", user, body)
def _rcmd_msgoff(self, args):
user = User(args[0])
body = _strip_html(":".join(args[5:]))
self._callEvent("onPMOfflineMessage", user, body)
def _rcmd_wlonline(self, args):
user = User(args[0])
last_on = float(args[1])
self._status[user] = [last_on,True,last_on]
self._callEvent("onPMContactOnline", user)
def _rcmd_wloffline(self, args):
user = User(args[0])
last_on = float(args[1])
self._status[user] = [last_on,False,0]
self._callEvent("onPMContactOffline", user)
def _rcmd_kickingoff(self, args):
self.disconnect()
def _rcmd_toofast(self, args):
self.disconnect()
def _rcmd_unblocked(self, user):
"""call when successfully unblocked"""
if user in self._blocklist:
self._blocklist.remove(user)
self._callEvent("onPMUnblock", user)
####
# Commands
####
def ping(self):
"""send a ping"""
self._sendCommand("")
self._callEvent("onPMPing")
def message(self, user, msg):
"""send a pm to a user"""
if msg!=None:
self._sendCommand("msg", user.name, msg)
def addContact(self, user):
"""add contact"""
if user not in self._contacts:
self._sendCommand("wladd", user.name)
self._contacts.add(user)
self._callEvent("onPMContactAdd", user)
def removeContact(self, user):
"""remove contact"""
if user in self._contacts:
self._sendCommand("wldelete", user.name)
self._contacts.remove(user)
self._callEvent("onPMContactRemove", user)
def block(self, user):
"""block a person"""
if user not in self._blocklist:
self._sendCommand("block", user.name, user.name, "S")
self._blocklist.add(user)
self._callEvent("onPMBlock", user)
def unblock(self, user):
"""unblock a person"""
if user in self._blocklist:
self._sendCommand("unblock", user.name)
def track(self, user):
"""get and store status of person for future use"""
self._sendCommand("track", user.name)
def checkOnline(self, user):
"""return True if online, False if offline, None if unknown"""
if user in self._status:
return self._status[user][1]
else:
return None
def getIdle(self, user):
"""return last active time, time.time() if isn't idle, 0 if offline, None if unknown"""
if not user in self._status: return None
if not self._status[user][1]: return 0
if not self._status[user][2]: return time.time()
else: return self._status[user][2]
####
# Util
####
def _callEvent(self, evt, *args, **kw):
getattr(self.mgr, evt)(self, *args, **kw)
self.mgr.onEventCalled(self, evt, *args, **kw)
def _write(self, data):
if self._wlock:
self._wlockbuf += data
else:
self.mgr._write(self, data)
def _setWriteLock(self, lock):
self._wlock = lock
if self._wlock == False:
self._write(self._wlockbuf)
self._wlockbuf = b""
def _sendCommand(self, *args):
"""
Send a command.
@type args: [str, str, ...]
@param args: command and list of arguments
"""
if self._firstCommand:
terminator = b"\x00"
self._firstCommand = False
else:
terminator = b"\r\n\x00"
self._write(":".join(args).encode() + terminator)
def getConnections(self):
return [self]
################################################################
# Room class
################################################################
class Room:
"""Manages a connection with a Chatango room."""
####
# Init
####
def __init__(self, room, uid = None, server = None, port = None, mgr = None):
"""init, don't overwrite"""
# Basic stuff
self._name = room
self._server = server or getServer(room)
self._port = port or 443
self._mgr = mgr
# Under the hood
self._connected = False
self._reconnecting = False
self._uid = uid or _genUid()
self._rbuf = b""
self._wbuf = b""
self._wlockbuf = b""
self._owner = None
self._mods = set()
self._mqueue = dict()
self._history = list()
self._userlist = list()
self._firstCommand = True
self._connectAmmount = 0
self._premium = False
self._userCount = 0
self._pingTask = None
self._botname = None
self._currentname = None
self._users = dict()
self._msgs = dict()
self._wlock = False
self._silent = False
self._banlist = dict()
self._unbanlist = dict()
# Inited vars
if self._mgr: self._connect()
####
# Connect/disconnect
####
def _connect(self):
"""Connect to the server."""
self._sock = socket.socket()
self._sock.connect((self._server, self._port))
self._sock.setblocking(False)
self._firstCommand = True
self._wbuf = b""
self._auth()
self._pingTask = self.mgr.setInterval(self.mgr._pingDelay, self.ping)
if not self._reconnecting: self.connected = True
def reconnect(self):
"""Reconnect."""
self._reconnect()
def _reconnect(self):
"""Reconnect."""
self._reconnecting = True
if self.connected:
self._disconnect()
self._uid = _genUid()
self._connect()
self._reconnecting = False
def disconnect(self):
"""Disconnect."""
self._disconnect()
self._callEvent("onDisconnect")
def _disconnect(self):
"""Disconnect from the server."""
if not self._reconnecting: self.connected = False
for user in self._userlist:
user.clearSessionIds(self)
self._userlist = list()
self._pingTask.cancel()
self._sock.close()
if not self._reconnecting: del self.mgr._rooms[self.name]
def _auth(self):
"""Authenticate."""
# login as name with password
if self.mgr.name and self.mgr.password:
self._sendCommand("bauth", self.name, self._uid, self.mgr.name, self.mgr.password)
self._currentname = self.mgr.name
# login as anon
else:
self._sendCommand("bauth", self.name)
self._setWriteLock(True)
####
# Properties
####
def _getName(self): return self._name
def _getBotName(self):
if self.mgr.name and self.mgr.password:
return self.mgr.name
elif self.mgr.name and self.mgr.password == None:
return "#" + self.mgr.name
elif self.mgr.name == None:
return self._botname
def _getCurrentname(self): return self._currentname
def _getManager(self): return self._mgr
def _getUserlist(self, mode = None, unique = None, memory = None):
ul = None
if mode == None: mode = self.mgr._userlistMode
if unique == None: unique = self.mgr._userlistUnique
if memory == None: memory = self.mgr._userlistMemory
if mode == Userlist_Recent:
ul = map(lambda x: x.user, self._history[-memory:])
elif mode == Userlist_All:
ul = self._userlist
if unique:
return list(set(ul))
else:
return ul
def _getUserNames(self):
ul = self.userlist
return list(map(lambda x: x.name, ul))
def _getUser(self): return self.mgr.user
def _getOwner(self): return self._owner
def _getOwnerName(self): return self._owner.name
def _getMods(self):
newset = set()
for mod in self._mods:
newset.add(mod)
return newset
def _getModNames(self):
mods = self._getMods()
return [x.name for x in mods]
def _getUserCount(self): return self._userCount
def _getSilent(self): return self._silent
def _setSilent(self, val): self._silent = val
def _getBanlist(self): return list(self._banlist.keys())
def _getUnBanlist(self): return [[record["target"], record["src"]] for record in self._unbanlist.values()]
name = property(_getName)
botname = property(_getBotName)
currentname = property(_getCurrentname)
mgr = property(_getManager)
userlist = property(_getUserlist)
usernames = property(_getUserNames)
user = property(_getUser)
owner = property(_getOwner)
ownername = property(_getOwnerName)
mods = property(_getMods)
modnames = property(_getModNames)
usercount = property(_getUserCount)
silent = property(_getSilent, _setSilent)
banlist = property(_getBanlist)
unbanlist = property(_getUnBanlist)
####
# Feed/process
####
def _feed(self, data):
"""
Feed data to the connection.
@type data: bytes
@param data: data to be fed
"""
self._rbuf += data
while self._rbuf.find(b"\x00") != -1:
data = self._rbuf.split(b"\x00")
for food in data[:-1]:
self._process(food.decode(errors="replace").rstrip("\r\n"))
self._rbuf = data[-1]
def _process(self, data):
"""
Process a command string.
@type data: str
@param data: the command string
"""
self._callEvent("onRaw", data)
data = data.split(":")
cmd, args = data[0], data[1:]
func = "_rcmd_" + cmd
if hasattr(self, func):
getattr(self, func)(args)
else:
if debug:
print("unknown data: "+str(data))
####
# Received Commands
####
def _rcmd_ok(self, args):
# if no name, join room as anon and no password
if args[2] == "N" and self.mgr.password == None and self.mgr.name == None:
n = args[4].rsplit('.', 1)[0]
n = n[-4:]
aid = args[1][0:8]
pid = "!anon" + _getAnonId(n, aid)
self._botname = pid
self._currentname = pid
self.user._nameColor = n
# if got name, join room as name and no password
elif args[2] == "N" and self.mgr.password == None:
self._sendCommand("blogin", self.mgr.name)
self._currentname = self.mgr.name
# if got password but fail to login
elif args[2] != "M": #unsuccesful login
self._callEvent("onLoginFail")
self.disconnect()
self._owner = User(args[0])
self._uid = args[1]
self._aid = args[1][4:8]
self._mods = set(map(lambda x: User(x.split(",")[0]), args[6].split(";")))
self._i_log = list()
def _rcmd_denied(self, args):
self._disconnect()
self._callEvent("onConnectFail")
def _rcmd_inited(self, args):
self._sendCommand("g_participants", "start")
self._sendCommand("getpremium", "1")
self.requestBanlist()
self.requestUnBanlist()
if self._connectAmmount == 0:
self._callEvent("onConnect")
for msg in reversed(self._i_log):
user = msg.user
self._callEvent("onHistoryMessage", user, msg)
self._addHistory(msg)
del self._i_log
else:
self._callEvent("onReconnect")
self._connectAmmount += 1
self._setWriteLock(False)
def _rcmd_premium(self, args):
if float(args[1]) > time.time():
self._premium = True
if self.user._mbg: self.setBgMode(1)
if self.user._mrec: self.setRecordingMode(1)
else:
self._premium = False
def _rcmd_mods(self, args):
modnames = args
mods = set(map(lambda x: User(x.split(",")[0]), modnames))
premods = self._mods
for user in mods - premods: #modded
self._mods.add(user)
self._callEvent("onModAdd", user)
for user in premods - mods: #demodded
self._mods.remove(user)
self._callEvent("onModRemove", user)
self._callEvent("onModChange")
def _rcmd_b(self, args):
mtime = float(args[0])
puid = args[3]
ip = args[6]
name = args[1]
rawmsg = ":".join(args[9:])
msg, n, f = _clean_message(rawmsg)
if name == "":
nameColor = None
name = "#" + args[2]
if name == "#":
name = "!anon" + _getAnonId(n, puid)
else:
if n: nameColor = _parseNameColor(n)
else: nameColor = None
i = args[5]
unid = args[4]
user = User(name)
#Create an anonymous message and queue it because msgid is unknown.
if f: fontColor, fontFace, fontSize = _parseFont(f)
else: fontColor, fontFace, fontSize = None, None, None
msg = Message(
time = mtime,
user = user,
body = msg,
raw = rawmsg,
ip = ip,
nameColor = nameColor,
fontColor = fontColor,
fontFace = fontFace,
fontSize = fontSize,
unid = unid,
puid = puid,
room = self
)
self._mqueue[i] = msg
def _rcmd_u(self, args):
temp = Struct(**self._mqueue)
if hasattr(temp, args[0]):
msg = getattr(temp, args[0])
if msg.user != self.user:
msg.user._fontColor = msg.fontColor
msg.user._fontFace = msg.fontFace
msg.user._fontSize = msg.fontSize
msg.user._nameColor = msg.nameColor
del self._mqueue[args[0]]
msg.attach(self, args[1])
self._addHistory(msg)
self._callEvent("onMessage", msg.user, msg)
def _rcmd_i(self, args):
mtime = float(args[0])
puid = args[3]
ip = args[6]
name = args[1]
rawmsg = ":".join(args[9:])
msg, n, f = _clean_message(rawmsg)
if name == "":
nameColor = None
name = "#" + args[2]
if name == "#":
name = "!anon" + _getAnonId(n, puid)
else:
if n: nameColor = _parseNameColor(n)
else: nameColor = None
i = args[5]
unid = args[4]
user = User(name)
#Create an anonymous message and queue it because msgid is unknown.
if f: fontColor, fontFace, fontSize = _parseFont(f)
else: fontColor, fontFace, fontSize = None, None, None
msg = Message(
time = mtime,
user = user,
body = msg,
raw = rawmsg,