-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtinychat.py
3356 lines (2817 loc) · 97 KB
/
tinychat.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
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# Coded in Sublime Text 3 beta, latest.
from rtmp import rtmp_protocol
import requests # http://www.python-requests.org/
try:
requests.packages.urllib3.disable_warnings() # For python < 2.7.9
except:
pass
import random
import os, sys, signal
import traceback # https://docs.python.org/2/library/traceback.html
import time
time.mstime = lambda: int(round(time.time() * 1000)) # Get current time in milliseconds.
from urllib import quote, quote_plus # Handles URLs.
import json
import re
# Handle linux SIGTERM; cleanup.
def signalHandler(signum, frame):
print "Signal handler called with signal "+str(signum)+"."
# Print all queued messages. Cleanup properly.
try:
room = ROOMS[0] # Only main room.
room._chatlogFlush()
room.disconnect()
except:
pass
SETTINGS["Run"] = False
sys.exit()
signal.signal(signal.SIGTERM, signalHandler)
# Windows console fix, not necessary for everyone.
try:
import codecs
codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
except:
pass
import socket # https://docs.python.org/2/library/socket.html
import socks # https://github.com/Anorov/PySocks 1.5.4
import threading
ROOMS = [] # First room should always be the main room & thread.
# Operation variables.
try:
LOCAL_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), "")
except:
LOCAL_DIRECTORY = ""
# Holds further private modules and settings files.
SETTINGS_DIRECTORY = os.path.join(LOCAL_DIRECTORY, "settings", "")
SETTINGS_FILE = False # Default to no settings file.
# Delay before any (re)connection.
DELAY = 10
# Returns a new internet socket().
# Optionally reusable.
def getSocket(reusable=False, keepalive=True):
s = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM) # Default values.
# Looks like TC uses some MQTT thing. No idea.
# if keepalive:
# s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
# # Linux only.
# try:
# # Activate after seconds idle.
# # Overrides value shown by sysctl net.ipv4.tcp_keepalive_time.
# s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 15) # socket.IPPROTO_TCP
# # Ping interval.
# # Overrides value shown by sysctl net.ipv4.tcp_keepalive_intvl.
# s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 15) # socket.IPPROTO_TCP
# # Max fails.
# # Overrides value shown by sysctl net.ipv4.tcp_keepalive_probes.
# s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, 4) # socket.IPPROTO_TCP
# except:
# pass
if reusable:
# The SO_REUSEADDR flag tells the kernel to reuse a local socket
# in TIME_WAIT state, without waiting for its natural timeout to expire.
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return s
# Global bot settings.
# This includes everything from the settings file!
SETTINGS = {
# Client controls.
"Run": True, # Let a thread ask to exit process loop.
"ReconnectOnBan": False, # Reconnect when banned.
"DebugConsole": False,
"DebugLog": False,
"ChatLog": True,
"ChatConsole": True,
"LastPM": None, # The nickname that last got a msg PM from bot.
"IP": None,
"PORT": None,
"PROXY": None, # Optional proxy option to use, proxy or "list".
"SOCK": getSocket(), # Connection socket used for all actions.
"Recaptcha": "", # The text file holding recaptcha info.
"NoRecaptcha": False, # Don't bother with reCaptcha.
"ReceiveCams": False, # Whether to receive webcam streams from other users.
"SCKey": None,
"YTKey": None,
# Optional event handling extensions, for bots.
"onJoinExtend": None,
"onJoinsdoneExtend": None,
"onQuitExtend": None,
"onNoticeExtend": None,
"onMessageExtend": None,
"onPMExtend": None,
"onNickChangeExtend": None,
"onUserinfoReceivedExtend": None,
"onBanlistExtend": None,
"onBroadcastExtend": None,
"disconnectExtend": None,
# Thread control.
"LastRoomID": 0,
"SendCommands": True, # Disable sending messages to room.
"KeepAlive": None, # The keepalive thread.
# Input control.
"RunningOnWindows": False,
"InteractiveConsole": True, # Has interactive console for user input.
"UserInput": None, # None means msvcrt() lib isn't loaded.
"UserInputLast": "",
# Extra settings.
"BanNewusers": False,
"MaxCharsMsg": 110,
"MaxCharsPM": 90,
"MaxCharsNotice": 160, # 360 total max per /notice.
"Instructions": False # Execute module at joinsdone().
}
# The Login and RTMP connections arguments.
CONN_ARGS = {
"room": "",
"nickname": "",
"username": "",
"password": ""
}
# Get connection arguments from command-line arguments.
try:
if len(sys.argv) == 1:
raise Exception("No arguments given to tinychat module...\n")
# Each item is a word, unless surrounded by "quotes".
for item in sys.argv:
parts = item.split("=", 1)
try:
# All names are lower-case.
name = parts[0].lower()
except:
# Must have a name.
continue
try:
val = parts[1]
except:
# Value can be empty.
val = ""
if name == "room":
CONN_ARGS["room"] = val
elif name in {"nick", "nickname"}:
CONN_ARGS["nickname"] = val
elif name in {"user", "username"}:
CONN_ARGS["username"] = val
elif name in {"pass", "password"}:
CONN_ARGS["password"] = val
# Using an interactive console or not, like command prompt.
elif name == "interactive":
try:
SETTINGS["InteractiveConsole"] = bool(int(val))
except:
print("Argument INTERACTIVE must be 0 or 1, only.")
# Override main room IP.
elif name == "ip":
SETTINGS["IP"] = val
# Override main room PORT.
elif name == "port":
try:
SETTINGS["PORT"] = int(val)
except:
print("Argument PORT must be an integer number.")
# All the module's connections go through proxy.
elif name == "proxy":
SETTINGS["PROXY"] = val
# Reconnect on ban.
elif name == "reonban":
try:
SETTINGS["ReconnectOnBan"] = bool(int(val))
except:
print("Argument REONBAN must be 0 or 1, only.")
elif name == "norecaptcha":
try:
SETTINGS["NoRecaptcha"] = bool(int(val))
except:
print("Argument NORECAPTCHA must be 0 or 1, only.")
elif name == "instructions":
try:
SETTINGS["Instructions"] = int(val)
except:
print("Argument INSTRUCTIONS must be an integer number.")
elif name == "settings":
try:
SETTINGS_FILE = bool(int(val))
except:
SETTINGS_FILE = val
print("Settings file set: "+str(SETTINGS_FILE))
except Exception as e:
print(e)
# If command-line argument for settings is True, try to find by room name.
if SETTINGS_FILE is True:
s = "settings_"+CONN_ARGS["room"]+".txt"
if os.path.isfile(LOCAL_DIRECTORY + s):
SETTINGS_FILE = s
# Append and override further settings from file.
# Supports unicode.
try:
if type(SETTINGS_FILE) not in {str, unicode}:
raise Exception()
with open(LOCAL_DIRECTORY + SETTINGS_FILE) as f:
data = f.read().splitlines()
# Handle unicode.
try:
lines = data.decode("utf-8", "replace")
except:
pass
# Convert to dict{}.
d = {}
for line in data:
# Remove trailing whitespaces.
line = line.strip()
# Skip comments and empty lines.
if line.startswith("//") or line == "":
continue
words = line.split()
name = words.pop(0)
value = " ".join(words)
# Optionally parse True/False.
if value == "True":
value = True
elif value == "False":
value = False
# Optionally parse as number.
elif value.startswith("###"):
try:
value = float(value)
except:
pass
elif value.startswith("##"):
try:
value = int(value)
except:
pass
# Optional CONN_ARGS. Doesn't override command-line arguments.
if name in CONN_ARGS and not CONN_ARGS[name] and name != "room":
CONN_ARGS[name] = value
else:
# Override into SETTINGS.
d[name] = value
# Apply.
SETTINGS.update(d)
except Exception as e:
if str(e):
print "Failed to load SETTINGS from "+SETTINGS_FILE+"!"
print str(e)
# Media handling - audio & video streams.
try:
from settings import media as MEDIA
except:
MEDIA = None
# Access bypass.
try:
from settings import bypassAccess as BYPASS_ACCESS
except:
BYPASS_ACCESS = None
# Captcha bypass.
try:
from settings import bypass_captcha as BYPASS_CAPTCHA
except:
BYPASS_CAPTCHA = None
# Proxy module.
try:
from settings import proxy as PROXY_MODULE
except:
PROXY_MODULE = None
PROXY = None
# Instructions module.
try:
import instructions as INSTRUCTIONS
doInstructions = INSTRUCTIONS.do
except:
# traceback.print_exc()
INSTRUCTIONS = None
# Get latest flash client version, for connection arguments.
try:
r = requests.get("http://www.tinychat.com/embed/chat.js", timeout=10)
t = r.text
# Make sure result variable is str().
FLASH_VER = str(t.split("Tinychat-")[1].split(".swf")[0]) # '11.1-1.0.0.0660'
FLASH_MVER = str(FLASH_VER.split("-")[1]) # '1.0.0.0660'
FLASH_SWFNAME = str("Tinychat-"+FLASH_VER+".swf") # 'Tinychat-11.1-1.0.0.0660.swf'
except Exception as e:
FLASH_VER = '11.1-1.0.0.0660'
FLASH_MVER = str(FLASH_VER.split("-")[1])
FLASH_SWFNAME = str("Tinychat-"+FLASH_VER+".swf")
print "Failed to get Flash Client version from Tinychat, using default values!"
print str(e)
# Running on a Windows machine, or otherwise.
if os.name == "nt":
SETTINGS["RunningOnWindows"] = True
# Console input control.
if SETTINGS["RunningOnWindows"]:
try:
import msvcrt # https://docs.python.org/2/library/msvcrt.html#console-i-o
SETTINGS["UserInput"] = []
except:
pass
else:
# For linux...
pass
# Time formats.
get_current_time = lambda: time.strftime("%H.%M.%S")
current_date = time.strftime("%d.%m.%Y")
# Logging.
try:
LOG_BASE_DIRECTORY = os.environ["OPENSHIFT_LOG_DIR"] + "room_logs/"
except:
LOG_BASE_DIRECTORY = "logs/"
LOG_FILENAME_POSTFIX = current_date + "_" + time.strftime("%H.%M.%S") + ".log"
TINYCHAT_COLORS = {
'blue' : '#1965b6',
'cyan' : '#32a5d9',
'lightgreen' : '#7db257',
'yellow' : '#a78901',
'pink' : '#9d5bb5',
'purple' : '#5c1a7a',
'red' : '#c53332',
'darkred' : '#821615',
'green' : '#487d21',
'lightpink' : '#c356a3',
'lightblue' : '#1d82eb',
'turquoise' : '#a990',
'skinpink' : '#b9807f',
'leafgreen' : '#7bb224',
# Non-official TC colors...
'black' : '#0',
# Pro colors...
'brightred' : '#e62430',
'orange' : '#fba91a'
}
# Handle tracking videos and songs.
YTqueue = {
"history": [], # Videos played by bot, only.
"current": "", # Currently tracked video, not only from bot.
# Track the last played (or playing) video.
"start": 0, # The time() when started.
"length": 0, # The length of the video in seconds.
"skip": 0, # The skip amount in seconds.
"paused": 0 # The time() when paused.
}
SCqueue = {
"history": [], # Tracks played by bot, only.
"current": "", # Currently tracked track, not only from bot.
# Track the last played (or playing) video.
"start": 0, # The time() when started.
"length": 0, # The length of the video in seconds.
"skip": 0, # The skip amount in seconds.
"paused": 0 # The time() when paused.
}
# Proxies for spoofing the connection - requests and RTMP. Optional.
# Turns PROXY into an object with methods, or to None on failure.
try:
# Need both module and a proxy or list.
if not PROXY_MODULE or not SETTINGS["PROXY"]:
raise Exception()
# Either a given .txt file, single proxy, or nothing.
if SETTINGS["PROXY"].endswith(".txt"):
# List of proxies.
try:
with open(SETTINGS_DIRECTORY + SETTINGS["PROXY"]) as f:
d = f.read().splitlines()
except:
raise Exception("Failed to open proxies list from "+SETTINGS["PROXY"]+"...")
proxies = filter(lambda x: x.strip() and not x.startswith("//"), d)
elif SETTINGS["PROXY"]:
# Single proxy.
proxies = SETTINGS["PROXY"]
# Set as object from class. Proxies are shuffled, and made a tuple (not list!)
l = threading.Lock()
PROXY = PROXY_MODULE.proxy(proxies, requests, getSocket, l, loopOver=True)
# Invalid single proxy.
if not PROXY.proxies:
raise Exception("Proxy "+SETTINGS["PROXY"]+" is not a valid proxy format! "+
"Using local connection...")
except Exception as e:
PROXY = None
if str(e):
print str(e)
# Format Room and PM messages.
class TinychatMessage():
def __init__(self, msg, nick, user=None, recipient=None, color=None, pm=False):
self.msg = msg
self.nick = nick
self.user = user
self.recipient = recipient
self.color = color
self.pm = pm
def printFormatted(self):
if self.pm:
pm = "(PM) "
else:
pm = ""
print(pm + self.recipient + ": " + self.nick + ": " + self.msg)
# User properties object.
class TinychatUser():
def __init__(self, userID=0, nick="", color=""):
self.joinTime = time.time()
self.nick = nick
self.id = userID # int()
self.color = color
self.lastMsg = ""
self.mod = False
self.admin = False
self.account = ""
self.broadcasting = False # Can't tell if stopped broadcasting, unless closed by mod.
self.device = "" # Tinychat identifies Android & iPhone users.
self.pro = False # User is on a Pro account.
# self.btype = '' # 'android', 'ios', '' is computer user.
# self.stype = 0 # 10 is PRO, 20 is EXTREME, 0 is normal user.
self.lurking = False # User is on "guest" mode, and can't send anything to room.
self.gp = 0 # Giftpoints. int()
self.alevel = "" # Gifts Achievement level (image url: http://tinychat.com/gifts/images/achievement/new/star_y_32.png)
# A single room connection.
class TinychatRoom():
# self.sock is None if using a bad socket().
# Each connection has its own room() with socket(), by design.
def __init__(self, room, nick=None, username=None, passwd=None, roomPassword=None,
instructions=None, printOverride=None, doConnect=None,
replaceIndex=None, autoBot=None, noRecaptcha=None):
# Put reference to room, in the list.
if replaceIndex is not None:
ROOMS.insert(replaceIndex, self)
else:
ROOMS.append(self)
self.autoBot = autoBot
self.noRecaptcha = SETTINGS["NoRecaptcha"]
# Optional room type for RTMP connect().
if room.find("*") >= 0:
parts = room.split("*")
self.site = parts[0]
self.room = parts[1]
elif room.find("^") >= 0:
# Command-line argument can't use ^, so optional check.
parts = room.split("^")
self.site = parts[0]
self.room = parts[1]
else:
self.site = "tinychat"
self.room = room
self.type = "show" # Default, but also check in API.
self.cookies = {} # Holds requests session cookies.
if username == None:
self.username = ""
else:
self.username = username
self.nick = nick
self.passwd = passwd
self.roomPassword = roomPassword
self.connected = False
self.reconnecting = False
SETTINGS["LastRoomID"] += 1
self.roomID = SETTINGS["LastRoomID"]
self.chatVerbose = SETTINGS["ChatConsole"]
self.chatLogging = SETTINGS["ChatLog"]
self.chatlogQueue = []
# Optionally filled in getRTMPInfo().
self.bpass = None
self.greenroom = False
self.timecookie = None
# Each room() has its own socket(), representing an IP address.
self.sock = None
self.proxies = None
self.proxy = None
self.PROXY = PROXY # Modular access.
self.getSocket = getSocket # ...
self.setSocket() # Sets the above variables, or not on failure.
try:
if not self.sock:
raise Exception("Bad socket from setSocket()...")
self.s = requests.session()
self.authHTTP()
self.tcurl = self.getRTMPInfo()
self.doTimestampRecaptcha() # Sets self.timecookie, as well.
except:
# traceback.print_exc()
# Failed socket. Probably bad proxy.
self.reconnect()
return
# Work bot - advertising.
self.instructions = instructions
# Connect immediately, after initialization.
self.doConnect = doConnect
# Ignore print queueing, and print immediately.
self.printOverride = printOverride
tcurlsplits = self.tcurl.split("/tinyconf") # >>['rtmp://127.0.0.1:1936', '']
tcurlsplits1 = self.tcurl.split("/") # >>['rtmp:', '', '127.0.0.1:1936', 'tinyconf']
tcurlsplits2 = self.tcurl.split(":") # >>['rtmp', '//127.0.0.1', '1936/tinyconf']
tcurlsplits3 = tcurlsplits1[2].split(":") # >>[127.0.0.1', '1936']
self.url = tcurlsplits[0] # Defining Full RTMP URL "rtmp://127.0.0.1:1936"
self.protocol = tcurlsplits2[0] # Defining RTMP Type [RTMP/RTMPE,etc]
self.ip = tcurlsplits3[0] # Defining RTMP Server IP
self.port = int(tcurlsplits3[1])
self.app = tcurlsplits1[3] # Defining Tinychat FMS App
self.pageurl = "http://tinychat.com/"+room # Definging Tinychat's Room HTTP URL
self.swfurl = "http://tinychat.com/embed/"+FLASH_SWFNAME+"?version="+FLASH_MVER+"/[[DYNAMIC]]/8" #static
self.flashVer = "WIN 20,0,0,267" # static
self.pc = "Desktop "+FLASH_MVER
# Overrides.
if SETTINGS["IP"]:
self.ip = SETTINGS["IP"]
if SETTINGS["PORT"]:
self.port = int(SETTINGS["PORT"])
self.color = TINYCHAT_COLORS["black"]
self.topic = ""
self.users = {} # self.users[NICK] = USER OBJECT
self.user = None # Holds the bot's user object.
self.nextFails = 0 # Count .next() failures, to avoid infinite loop.
self.banlist = []
self.forgives = []
self.onCam = False
self.keepAlive = True # Toggles on disconnect() and connect().
# Avoid sending more than 10 msgs per 1 second.
self.limitMsgs = {
"msgs": 0,
"first": time.time()
}
# Connect immediately, after finishing initialization.
if self.doConnect:
self.connect()
# Core connectivity functions.
def connect(self, force=None):
self._chatlog("Connecting to "+self.room+"...", True)
if not self.connected or force:
try:
self.connection = rtmp_protocol.RtmpClient(self.ip, self.port, self.tcurl,
self.pageurl, self.swfurl, self.app, self.flashVer, self.sock,
self.username, self.site, self.room, self.pc, self.type, self.timecookie)
self.connection.connect()
self.connected = True
self.keepAlive = True
SETTINGS["Reconnecting"] = False
if self.proxy:
if type(PROXY.proxies) is tuple:
p = self.proxy+" ("+PROXY.getCountString(self.proxyIndex)+")"
else:
p = self.proxy
else:
p = ""
self._chatlog("== Connected "+(self.nick if self.nick else "bot")+" == "+p)
printFile(self.room+".connected", "connected", local=True)
# Start listening to server.
self._listen()
except Exception as e:
# traceback.print_exc()
self.connected = False
self._chatlog("Failed to connect! Reconnecting...", True)
self.reconnect()
def _listen(self):
while self.connected and not self.reconnecting:
# Read next possible packet.
try:
msg = self.connection.reader.next()
except socket.timeout:
# Only applies for the connect() attempt.
self.disconnect()
self._chatlog("Socket().timeout! Reconnecting...", True)
self.reconnect()
break
except:
self.nextFails += 1
self._chatlog("Failed to read next() packet...", True)
# Kill after consecutive fails.
if self.nextFails == 5:
self.disconnect()
self._chatlog("Can't read next()! Reconnecting...", True)
self.reconnect()
break
# Otherwise, skip it.
# traceback.print_exc()
continue
else:
# Reset count on success.
self.nextFails = 0
# Handle RTMP packets.
try:
if msg['msg'] == rtmp_protocol.DataTypes.USER_CONTROL:
# Ping, normally.
# self._chatlog("USER CONTROL: "+str(msg['event_type'])+", "+str(msg['event_data'])+".", True)
return
elif msg['msg'] == rtmp_protocol.DataTypes.SHARED_OBJECT:
# Useless.
# self._chatlog("SHARED OBJECT: "+str(msg['obj_name'])+", "+str(msg['curr_version'])+
# ", "+msg['flags']+", "+msg['events']+".", True)
return
elif msg['msg'] == rtmp_protocol.DataTypes.DATA_MESSAGE:
# Useless.
# self._chatlog("DATA MESSAGE: "+str(msg['event_data'])+".", True)
return
elif msg['msg'] == rtmp_protocol.DataTypes.VIDEO_MESSAGE:
try:
pass
# self.videoDatas[msg['streamid']].append(msg['control'], msg['video'])
except:
pass
elif msg['msg'] == rtmp_protocol.DataTypes.COMMAND:
pars = msg['command']
cmd = pars[0].encode("ascii", "ignore").lower() # pars[0].encode("ascii", "ignore").lower()
if len(pars) > 3:
pars = pars[3:]
else:
pars = []
# for i in range(len(pars)):
# if type(pars[i]) == str: pars[i] = pars[i].encode("ascii", "ignore")
# Incoming RTMP event.
if cmd == "privmsg":
recipient = pars[0]
message = pars[1]
color = pars[2].lower().split(",")[0]
nick = pars[3]
# Ignore empty messages.
if not message:
continue
m = self._decodeMessage(message)
if len(m) > 0:
if recipient[0] == "#":
recipient = "^".join(recipient.split("^")[1:])
else:
recipient = "-".join(recipient.split("-")[1:])
user = self._getUser(nick)
if not user:
print("< Caught empty user at privmsg: "+nick+" >")
print str(message)
continue
message = TinychatMessage(m, nick, user, recipient, color)
user.lastMsg = message
user.color = color
if recipient == self.nick:
message.pm = True
if message.msg.startswith("/msg ") and len(message.msg.split(" ")) >= 2:
message.msg = " ".join(message.msg.split(" ")[2:])
self.onPM(user, message)
else:
self.onMessage(user, message)
continue
# Event for self joining?
if cmd == "registered":
u = pars[0]
# Get my user object.
self.onJoin(u, myself=True)
continue
if cmd == "join":
u = pars[0]
self.onJoin(u)
continue
if cmd == "topic":
topic = pars[0]
if not self.topic:
# On join.
msg = "Topic: "
else:
msg = "Topic set as: "
self.topic = topic
self._chatlog(msg + self.topic, True)
continue
if cmd == "joins":
for u in pars:
self.onJoin(u, joins=True)
continue
if cmd == "joinsdone":
self.onJoinsdone()
continue
if cmd == "deop":
userid = int(pars[0])
nick = pars[1]
user = self._getUser(userid)
user.mod = False
self._chatlog(user.nick + " have lost their oper.", True)
continue
if cmd == "nick":
old = pars[0]
new = pars[1]
userid = int(pars[2])
# Replaces reference in room object, and handles event.
self.onNickChange(old, new, userid)
continue
if cmd == "notice":
event = pars[0]
if event == "avon":
userid = pars[1]
nick = pars[2]
self.onBroadcast(nick, userid)
continue
if cmd == "avons":
# First item is None.
pars = pars[1:]
# Empty.
if not pars:
continue
for i in range(0, len(pars), 2):
userid = pars[i]
nick = pars[i+1]
self.onBroadcast(nick, userid)
continue
if cmd == "quit":
nick = pars[0]
userid = int(pars[1])
self.onQuit(nick, userid)
continue
if cmd == "kick":
userID = pars[0]
nick = pars[1]
self.onBanned(userID, nick)
continue
if cmd == "banlist":
self.onBanlist(pars)
continue
if cmd == "banned":
self.onBanned(bot=True)
continue
if cmd == "doublesignon":
try:
self._chatlog("The account "+self.user.account+
" is already being used by: ["+pars[1]+","+pars[0]+"].", True)
except:
self._chatlog("The account "+self.user.account+
" is already being used in this room.", True)
continue
if cmd == "nickinuse":
self._chatlog("The nickname "+self.nick+" is already being used. Adding X.", True)
self.setNick(self.nick+"X")
continue
if cmd == "from_owner":
# Format: noticeword%20word
# or _closebob
s = pars[0]
# A notice message.
if s.startswith("notice"):
notice = pars[0][len("notice"):].replace("%20", " ")
self.onNotice(notice)
# Someone was uncammed.
elif s.startswith("_close"):
target = s[len("_close"):]
self.onCamClosed(target)
else:
self._chatlog("UNHANDLED from_owner: "+str(pars), True)
continue
if cmd == "_error":
self._chatlog(str(pars), True)
continue
if cmd == "_result":
pars = msg['command'][1:]
# self._chatlog("_result: "+str(pars))
localStreamID = pars[0]
remoteStreamID = pars[2]
try:
self.onResult(localStreamID, remoteStreamID)
except:
pass
continue
if cmd == "onstatus":
# self._chatlog("onstatus: "+str(pars), True)
statusObj = pars[0]
try:
self.onStatus(statusObj)
except:
pass
continue
if cmd == "gift":
self._chatlog("Gift: " + str(pars))
continue
# Uncaught command! Ignore commands I don't care about.
if cmd not in {"onbwdone", "startbanlist", "owner"}:
self._chatlog("UNHANDLED COMMAND: " + str(cmd) + " " + str(pars), True)
except:
self._chatlog("Error handling incoming packet...", True)
traceback.print_exc()
def disconnect(self):
# Delete recaptcha file, in case closed during wait loop.
printFile(SETTINGS["Recaptcha"], local=True)
# Delete connection file.
printFile(self.room+".connected", local=True)
if self.connected:
self.connected = False
# Flush all chat messages in backlog.
self._chatlogFlush()
try:
self.connection.socket.shutdown(1)
self.connection.socket.close()
except:
self._chatlog("Failed to gracefully disconnect...", True)
self._chatlog("=== Disconnected ===", True)
# Instructions or further handling.
if SETTINGS['disconnectExtend']:
try:
SETTINGS['disconnectExtend'](self)
except:
traceback.print_exc()
# diconnect() and make a new connection at the same ROOMS index.
def reconnect(self):
# Setup new repeat connection.
SETTINGS["Reconnecting"] = True
self.keepAlive = False
# Keep to index in ROOMS.
try:
i = ROOMS.index(self)
except:
i = None
# Close previous connection.
self.disconnect()
# Remove room from list.
ROOMS.remove(self)
try:
nick = self.user.nick
except:
nick = self.nick
# Make new room with new proxy, with a new socket().
t = threading.Thread(target=makeRoom, args=(nick, i,))
t.daemon = True
t.start()
# Sets a local or proxified socket, or None.
# Sets: self.sock. Optionally: self.proxies, self.proxy.
def setSocket(self):
self.sock = getSocket()
# Makes a new user from userid, and adds it to self.users.
# Return the new user object.
def _makeUser(self, userid):
user = TinychatUser(userID=userid)
self.users[userid] = user
return user
# Gets an existing user by userid or nickname,
# or optionally by account name.
# Return False if not found.
def _getUser(self, identifier, account=False):
# By account name.
if account:
for user in self.users.values():
if user.account == identifier:
return user
else:
if type(identifier) is int:
# By userid.
try:
user = self.users[identifier]
return user
except:
pass
else:
# By nickname.
for user in self.users.values():
if user.nick == identifier:
return user