-
Notifications
You must be signed in to change notification settings - Fork 3
/
pinylib.py
1270 lines (1096 loc) · 49.5 KB
/
pinylib.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
# -*- coding: utf-8 -*-
import logging
import threading
import time
import traceback
from colorama import init, Fore, Style
import config
import user
import apis.tinychat
from rtmplib import rtmp
from page import acc, params
from util import string_util, file_handler
__version__ = '7.0.0'
# Console colors.
COLOR = {
'white': Fore.WHITE,
'green': Fore.GREEN,
'bright_green': Style.BRIGHT + Fore.GREEN,
'yellow': Fore.YELLOW,
'bright_yellow': Style.BRIGHT + Fore.YELLOW,
'cyan': Fore.CYAN,
'bright_cyan': Style.BRIGHT + Fore.CYAN,
'red': Fore.RED,
'bright_red': Style.BRIGHT + Fore.RED,
'magenta': Fore.MAGENTA,
'bright_magenta': Style.BRIGHT + Fore.MAGENTA
}
CONFIG = config
init(autoreset=True)
log = logging.getLogger(__name__)
def write_to_log(msg, room_name):
""" Writes chat events to log.
:param msg: the message to write to the log.
:type msg: str
:param room_name: the room name.
:type room_name: str
"""
d = time.strftime('%Y-%m-%d')
file_name = d + '.log'
path = config.CONFIG_PATH + room_name + '/logs/'
file_handler.file_writer(path, file_name, msg.encode(encoding='UTF-8', errors='ignore'))
class TinychatRTMPClient(object):
"""
Tinychat client responsible for managing the connection and the different
events that may occur in the chat room.
"""
def __init__(self, roomname, nick='', account='', password='', room_pass=None, proxy=None):
""" Create a instance of the TinychatRTMPClient class.
:param roomname: The room name to connect to.(required)
:type roomname: str
:param nick: The nick name to use in the chat room.(optional)
:type nick: str
:param account: Tinychat account name.(optional)
:type account: str
:param password: The password for the tinychat account.(optional)
:type password: str
:param room_pass: The password for the room.(optional)
:type room_pass: str | None
:param proxy: A proxy in the format IP:PORT for the connection to the remote server,
but also for doing the various web requests related to establishing a connection.(optional)
:type proxy: str | None
"""
self.roomname = roomname
self.nickname = nick
self.account = account
self.password = password
self.room_pass = room_pass
self.is_client_mod = False
self.is_client_owner = False
self.connection = None
self.green_connection = None
self.is_connected = False
self.is_green_connected = False
self.users = user.Users()
self.active_user = None
self.param = None
self._proxy = proxy
self._client_id = None
self._bauth_key = None
self._is_reconnected = False
self._reconnect_delay = config.RECONNECT_DELAY
self._init_time = time.time()
def console_write(self, color, message):
""" Writes message to console.
:param color: the colorama color representation.
:param message: str the message to write.
"""
msg_encoded = message.encode('ascii', 'ignore')
if config.USE_24HOUR:
ts = time.strftime('%H:%M:%S')
else:
ts = time.strftime('%I:%M:%S:%p')
if config.CONSOLE_COLORS:
msg = COLOR['white'] + '[' + ts + '] ' + Style.RESET_ALL + color + msg_encoded
else:
msg = '[' + ts + '] ' + msg_encoded
try:
print(msg)
except UnicodeEncodeError as ue:
log.error(ue, exc_info=True)
if config.DEBUG_MODE:
traceback.print_exc()
if config.CHAT_LOGGING:
write_to_log('[' + ts + '] ' + message, self.roomname)
def set_rtmp_parameters(self):
""" Set the RTMP parameters before making a connect. """
self.param = params.Params(room_name=self.roomname, room_pass=self.room_pass,
swf_version=config.SWF_VERSION, proxy=self._proxy)
self.param.get_config()
if self.param.config_status == 3:
if config.DEBUG_MODE:
for k in self.param.config_dict:
self.console_write(COLOR['white'], '%s: %s' % (k, self.param.config_dict[k]))
if self.account:
self.console_write(COLOR['white'], 'Account: %s' % self.account)
return self.param.config_status
def login(self):
""" Login to tinychat.
:return: True if logged in, else False.
:rtype: bool
"""
account = acc.Account(account=self.account, password=self.password, proxy=self._proxy)
if self.account and self.password:
if account.is_logged_in():
return True
account.login()
return account.is_logged_in()
def connect(self):
""" Make a connection with the remote RTMP server. """
if not self.is_connected:
log.info('connecting to: %s' % self.roomname)
try:
self.param.recaptcha()
self.connection = rtmp.RtmpClient(
ip=self.param.ip,
port=self.param.port,
tc_url=self.param.tc_url,
app=self.param.app,
page_url=self.param.embed_url,
swf_url=self.param.swf_url,
proxy=self._proxy,
is_win=True
)
self.connection.connect(
{
'account': self.account,
'type': self.param.roomtype,
'prefix': u'tinychat',
'room': self.roomname,
'version': self.param.desktop_version,
'cookie': self.param.cauth_cookie()
}
)
self.is_connected = True
except Exception as e:
log.critical('connect error: %s' % e, exc_info=True)
self.is_connected = False
self.reconnect()
if config.DEBUG_MODE:
traceback.print_exc()
finally:
if config.RESET_INIT_TIME:
self._init_time = time.time()
if self.param.is_greenroom and not self.is_green_connected:
threading.Thread(target=self.__connect_green).start()
self.__callback()
def __connect_green(self):
""" Make a connection to the greenroom application. """
if not self.is_green_connected:
try:
self.green_connection = rtmp.RtmpClient(
ip=self.param.ip,
port=self.param.port,
tc_url=self.param.tc_url,
app=self.param.app,
page_url=self.param.embed_url,
swf_url=self.param.swf_url,
proxy=self._proxy,
is_win=True
)
self.green_connection.connect(
{
'account': '',
'type': self.param.roomtype,
'prefix': u'greenroom',
'room': self.roomname,
'version': self.param.desktop_version,
'cookie': ''
}
)
self.is_green_connected = True
except Exception as e:
log.critical('greenroom connect error: %s' % e, exc_info=True)
self.is_green_connected = False
self.reconnect(greenroom=True)
if config.DEBUG_MODE:
traceback.print_exc()
finally:
self.__green_callback()
def disconnect(self, greenroom=False):
""" Close the connection with the remote RTMP server.
:param greenroom: True closes the greenroom connection,
else close the normal connection.
:type greenroom: bool
"""
log.info('disconnecting from server.')
try:
if greenroom:
log.info('disconnection from greenroom application')
self.is_green_connected = False
self.green_connection.shutdown()
else:
self.is_connected = False
self._bauth_key = None
self.users.clear()
self.connection.shutdown()
except Exception as e:
log.error('disconnect error, greenroom: %s, error: %s' % (greenroom, e), exc_info=True)
if config.DEBUG_MODE:
traceback.print_exc()
def reconnect(self, greenroom=False):
""" Reconnect to the application.
:param greenroom: True reconnect to the greenroom application else
reconnect to the normal application(room)
:type greenroom: bool
"""
if greenroom:
log.info('reconnecting to the greenroom application.')
self.disconnect(greenroom=True)
time.sleep(config.RECONNECT_DELAY)
self.__connect_green()
else:
reconnect_msg = '============ RECONNECTING IN %s SECONDS ============' % self._reconnect_delay
log.info('reconnecting: %s' % reconnect_msg)
self.console_write(COLOR['bright_cyan'], reconnect_msg)
self._is_reconnected = True
self.disconnect()
time.sleep(self._reconnect_delay)
# increase reconnect_delay after each reconnect.
self._reconnect_delay *= 2
if self._reconnect_delay > 900:
self._reconnect_delay = config.RECONNECT_DELAY
if self.account and self.password:
if not self.login():
self.console_write(COLOR['bright_red'], 'Failed to login.')
else:
self.console_write(COLOR['bright_green'], 'Login okay.')
self.set_rtmp_parameters()
if self.param.config_status == 3:
self.connect()
else:
msg = 'failed to set rtmp parameters, %s' % self.param.config_status
log.error(msg)
if config.DEBUG_MODE:
self.console_write(COLOR['bright_red'], msg)
def __green_callback(self):
""" Read packets from the greenroom RTMP application. """
log.info('starting greenroom callback loop. is_green_connected: %s' % self.is_green_connected)
fails = 0
amf0_data_type = - 1
amf0_data = None
while self.is_green_connected:
try:
amf0_data = self.green_connection.amf()
amf0_data_type = amf0_data['msg']
except rtmp.AmfDataReadError as e:
fails += 1
log.error('greenroom amf read error: %s %s' % (fails, e), exc_info=True)
if fails == 2:
if config.DEBUG_MODE:
traceback.print_exc()
self.reconnect(greenroom=True)
break
else:
fails = 0
try:
if amf0_data_type == rtmp.rtmp_type.DT_COMMAND:
amf0_cmd = amf0_data['command']
cmd = amf0_cmd[0]
if cmd == '_result':
self.on_result(amf0_cmd, greenroom=True)
elif cmd == '_error':
self.on_error(amf0_cmd, greenroom=True)
elif cmd == 'notice':
notice_msg = amf0_cmd[3]
notice_msg_id = amf0_cmd[4]
if notice_msg == 'avon':
avon_name = amf0_cmd[5]
self.on_avon(notice_msg_id, avon_name, greenroom=True)
else:
if config.DEBUG_MODE:
self.console_write(COLOR['white'], 'ignoring greenroom command: %s' % cmd)
except Exception as gge:
log.error('general greenroom callback error: %s' % gge, exc_info=True)
if config.DEBUG_MODE:
traceback.print_exc()
self.reconnect(greenroom=True)
def __callback(self):
""" Read packets from the RTMP application. """
log.info('starting callback loop. is_connected: %s' % self.is_connected)
fails = 0
amf0_data_type = -1
amf0_data = None
while self.is_connected:
try:
amf0_data = self.connection.amf()
amf0_data_type = amf0_data['msg']
except rtmp.AmfDataReadError as e:
fails += 1
log.error('amf data read error count: %s %s' % (fails, e), exc_info=True)
if fails == 2:
if config.DEBUG_MODE:
traceback.print_exc()
self.reconnect()
break
else:
fails = 0
try:
if amf0_data_type == rtmp.rtmp_type.DT_COMMAND:
create_stream_res = self.connection.is_create_stream_response(amf0_data)
if create_stream_res:
msg = 'create stream response, stream_id: %s' % self.connection.stream_id
log.info(msg)
self.connection.publish(self._client_id)
if config.DEBUG_MODE:
self.console_write(COLOR['white'], msg)
continue
amf0_cmd = amf0_data['command']
cmd = amf0_cmd[0]
iparam0 = 0
if cmd == '_result':
self.on_result(amf0_cmd)
elif cmd == '_error':
self.on_error(amf0_cmd)
elif cmd == 'onBWDone':
self.on_bwdone()
elif cmd == 'onStatus':
self.on_status(amf0_cmd)
elif cmd == 'registered':
client_info_dict = amf0_cmd[3]
self.on_registered(client_info_dict)
elif cmd == 'join':
join_info = amf0_cmd[3]
threading.Thread(target=self.on_join, args=(join_info,)).start()
elif cmd == 'joins':
current_room_users_info_list = amf0_cmd[3:]
if len(current_room_users_info_list) is not 0:
while iparam0 < len(current_room_users_info_list):
self.on_joins(current_room_users_info_list[iparam0])
iparam0 += 1
elif cmd == 'joinsdone':
self.on_joinsdone()
elif cmd == 'oper':
oper_id_name = amf0_cmd[3:]
while iparam0 < len(oper_id_name):
oper_id = str(int(oper_id_name[iparam0]))
oper_name = oper_id_name[iparam0 + 1]
if len(oper_id) == 1:
self.on_oper(oper_id[0], oper_name)
iparam0 += 2
elif cmd == 'deop':
deop_id = amf0_cmd[3]
deop_nick = amf0_cmd[4]
self.on_deop(deop_id, deop_nick)
# elif cmd == 'owner':
# self.on_owner()
elif cmd == 'avons':
avons_id_name = amf0_cmd[4:]
if len(avons_id_name) is not 0:
while iparam0 < len(avons_id_name):
avons_id = avons_id_name[iparam0]
avons_name = avons_id_name[iparam0 + 1]
self.on_avon(avons_id, avons_name)
iparam0 += 2
elif cmd == 'pros':
pro_ids = amf0_cmd[4:]
if len(pro_ids) is not 0:
for pro_id in pro_ids:
pro_id = str(int(pro_id))
self.on_pro(pro_id)
elif cmd == 'nick':
old_nick = amf0_cmd[3]
new_nick = amf0_cmd[4]
nick_id = int(amf0_cmd[5])
self.on_nick(old_nick, new_nick, nick_id)
elif cmd == 'nickinuse':
self.on_nickinuse()
elif cmd == 'quit':
quit_name = amf0_cmd[3]
quit_id = amf0_cmd[4]
self.on_quit(quit_id, quit_name)
elif cmd == 'kick':
kick_id = amf0_cmd[3]
kick_name = amf0_cmd[4]
self.on_kick(kick_id, kick_name)
elif cmd == 'banned':
self.on_banned()
elif cmd == 'banlist':
banlist_id_nick = amf0_cmd[3:]
if len(banlist_id_nick) is not 0:
while iparam0 < len(banlist_id_nick):
banned_id = banlist_id_nick[iparam0]
banned_nick = banlist_id_nick[iparam0 + 1]
self.on_banlist(banned_id, banned_nick)
iparam0 += 2
elif cmd == 'startbanlist':
# print(amf0_data)
pass
elif cmd == 'topic':
topic = amf0_cmd[3]
self.on_topic(topic)
elif cmd == 'from_owner':
owner_msg = amf0_cmd[3]
self.on_from_owner(owner_msg)
elif cmd == 'doublesignon':
self.on_doublesignon()
elif cmd == 'privmsg':
raw_msg = amf0_cmd[4]
msg_color = amf0_cmd[5]
msg_sender = amf0_cmd[6]
self.on_privmsg(msg_sender, raw_msg, msg_color)
elif cmd == 'notice':
notice_msg = amf0_cmd[3]
notice_msg_id = amf0_cmd[4]
if notice_msg == 'avon':
avon_name = amf0_cmd[5]
self.on_avon(notice_msg_id, avon_name)
elif notice_msg == 'pro':
self.on_pro(notice_msg_id)
elif cmd == 'gift':
gift_to = amf0_cmd[3]
gift_sender = amf0_data[4]
gift_info = amf0_data[5]
self.on_gift(gift_sender, gift_to, gift_info)
else:
self.console_write(COLOR['bright_red'], 'Unknown command: %s' % cmd)
except Exception as ex:
log.error('general callback error: %s' % ex, exc_info=True)
if config.DEBUG_MODE:
traceback.print_exc()
# Callback Event Methods.
def on_result(self, result_info, greenroom=False):
""" Default NetConnection message containing info about the connection.
:param result_info: Info containing various information.
:type result_info: dict
:param greenroom: True if the info is from the greenroom connection.
:type greenroom: bool
"""
if config.DEBUG_MODE:
if greenroom:
self.console_write(COLOR['white'], '## Greenroom result..')
for list_item in result_info:
if type(list_item) is rtmp.pyamf.ASObject:
for k in list_item:
self.console_write(COLOR['white'], k + ': ' + str(list_item[k]))
else:
self.console_write(COLOR['white'], str(list_item))
def on_error(self, error_info, greenroom=False):
""" Default NetConnection message containing error info about the connection.
:param error_info: Info containing various error information.
:type error_info: dict
:param greenroom: True if the error info is from the greenroom connection.
:type greenroom: bool
"""
if config.DEBUG_MODE:
if greenroom:
self.console_write(COLOR['bright_red'], '## Greenroom error..')
for list_item in error_info:
if type(list_item) is rtmp.pyamf.ASObject:
for k in list_item:
self.console_write(COLOR['bright_red'], k + ': ' + str(list_item[k]))
else:
self.console_write(COLOR['bright_red'], str(list_item))
def on_status(self, status_info):
""" Default NetStream status updates message.
:param status_info: Info containing various information related to a NetStream
:type status_info: dict
"""
if config.DEBUG_MODE:
for list_item in status_info:
if type(list_item) is rtmp.pyamf.ASObject:
for k in list_item:
self.console_write(COLOR['white'], k + ': ' + str(list_item[k]))
else:
self.console_write(COLOR['white'], str(list_item))
def on_bwdone(self):
""" Application specific message. """
if not self._is_reconnected:
if config.ENABLE_AUTO_JOB:
self.start_auto_job_timer()
def on_registered(self, client_info):
""" Application message containing client info.
:param client_info: Info containing client information.
:type client_info: dict
"""
self._client_id = client_info['id']
self.is_client_mod = client_info['mod']
self.is_client_owner = client_info['own']
client = self.users.add(client_info)
client.user_level = 0
self.console_write(COLOR['bright_green'], 'registered with ID: %d' % self._client_id)
key = self.param.get_captcha_key(self._client_id)
if key is None:
self.console_write(COLOR['bright_red'],
'There was a problem obtaining the captcha key. Key=%s' % str(key))
else:
self.console_write(COLOR['bright_green'], 'Captcha key: %s' % key)
self.send_cauth_msg(key)
self.set_nick()
def on_join(self, join_info):
""" Application message received when a user joins the room.
:param join_info: Information about the user joining.
:type join_info: dict
"""
_user = self.users.add(join_info)
if _user is not None:
if _user.account:
tc_info = apis.tinychat.user_info(_user.account)
if tc_info is not None:
_user.tinychat_id = tc_info['tinychat_id']
_user.last_login = tc_info['last_active']
if _user.is_owner:
_user.user_level = 1
self.console_write(COLOR['red'], 'Room Owner %s:%d:%s' %
(_user.nick, _user.id, _user.account))
elif _user.is_mod:
_user.user_level = 3
self.console_write(COLOR['bright_red'], 'Moderator %s:%d:%s' %
(_user.nick, _user.id, _user.account))
else:
self.console_write(COLOR['bright_yellow'], '%s:%d has account: %s' %
(_user.nick, _user.id, _user.account))
else:
if _user.id is not self._client_id:
self.console_write(COLOR['cyan'], '%s:%d joined the room.' % (_user.nick, _user.id))
else:
log.warning('user join: %s' % _user)
def on_joins(self, joins_info):
""" Application message received for every user in the room when the client joins the room.
:param joins_info: Information about a user.
:type joins_info: dict
"""
_user = self.users.add(joins_info)
if _user is not None:
if _user.account:
if _user.is_owner:
_user.user_level = 1
self.console_write(COLOR['red'], 'Joins Room Owner %s:%d:%s' %
(_user.nick, _user.id, _user.account))
elif _user.is_mod:
_user.user_level = 3
self.console_write(COLOR['bright_red'], 'Joins Moderator %s:%d:%s' %
(_user.nick, _user.id, _user.account))
else:
self.console_write(COLOR['bright_yellow'], 'Joins %s:%d:%s' %
(_user.nick, _user.id, _user.account))
else:
if joins_info['id'] is not self._client_id:
self.console_write(COLOR['bright_cyan'], 'Joins %s:%d' % (_user.nick, _user.id))
else:
log.warning('user joins: %s' % _user)
def on_joinsdone(self):
""" Application message received when all room users information have been received. """
if self.is_client_mod:
self.send_banlist_msg()
def on_oper(self, uid, nick):
""" Application message received when a user is oper(moderator)
NOTE: This message is most likely deprecated.
:param uid: str the Id of the oper.
:param nick: str the nick of the user
"""
_user = self.users.search(nick)
_user.is_mod = True
if uid != self._client_id:
self.console_write(COLOR['bright_red'], '%s:%s is moderator.' % (nick, uid))
def on_deop(self, uid, nick):
""" Application message received when a moderator is de-moderated(deop)
NOTE: This message is most likely deprecated.
:param uid: str the Id of the moderator.
:param nick: str the nick of the moderator.
"""
_user = self.users.search(nick)
_user.is_mod = False
self.console_write(COLOR['red'], '%s:%s was deoped.' % (nick, uid))
def on_avon(self, uid, name, greenroom=False):
""" Application message received when a user starts broadcasting.
:param uid: The Id of the user.
:type uid: str
:param name: The nick name of the user.
:type name: str
:param greenroom: True the user is waiting in the greenroom.
:type greenroom: bool
"""
if greenroom:
_user = self.users.search_by_id(name)
if _user is not None:
_user.is_waiting = True
self.console_write(COLOR['bright_yellow'], '%s:%s is waiting in the greenroom' %
(_user.nick, _user.id))
else:
_user = self.users.search(name)
if _user is not None and _user.is_waiting:
_user.is_waiting = False
self.console_write(COLOR['cyan'], '%s:%s is broadcasting.' % (name, uid))
def on_pro(self, uid):
""" Application message received when a user is using a PRO account.
:param uid: The Id of the pro user.
:type uid: str
"""
_user = self.users.search_by_id(uid)
if _user is not None:
self.console_write(COLOR['bright_magenta'], '%s:%s is pro.' % (_user.nick, uid))
else:
self.console_write(COLOR['bright_magenta'], '%s is pro.' % uid)
def on_nick(self, old, new, uid):
""" Application message received when a user changes nick name.
:param old: The old nick name of the user.
:type old: str
:param new: The new nick name of the user
:type new: str
:param uid: The Id of the user.
:type uid: int
"""
if uid == self._client_id:
self.nickname = new
old_info = self.users.search(old)
old_info.nick = new
if not self.users.change(old, new, old_info):
log.error('failed to change nick for user: %s' % new)
self.console_write(COLOR['bright_cyan'], '%s:%s changed nick to: %s' % (old, uid, new))
def on_nickinuse(self):
""" Application message received when the client nick name chosen is already in use."""
self.nickname += string_util.create_random_string(1, 5)
self.console_write(COLOR['white'], 'Nick already taken. Changing nick to: %s' % self.nickname)
self.set_nick()
def on_quit(self, uid, name):
""" Application message received when a user leaves the room.
:param uid: The Id of the user leaving.
:type uid: str
:param name: The nick name of the user leaving.
:type name: str
"""
log.debug('%s:%s left the room' % (name, uid))
if self.users.delete(name):
self.console_write(COLOR['cyan'], '%s:%s left the room.' % (name, uid))
else:
msg = 'failed to delete user: %s' % name
if config.DEBUG_MODE:
self.console_write(COLOR['bright_red'], msg)
log.debug(msg)
def on_kick(self, uid, name):
""" Application message received when a user gets banned.
:param uid: The Id of the user getting banned.
:type uid: str
:param name: The nick name of the user getting banned.
:type name: str
"""
self.console_write(COLOR['bright_red'], '%s:%s was banned.' % (name, uid))
self.send_banlist_msg()
def on_banned(self):
""" Application message received when the client is banned from a room. """
self.console_write(COLOR['red'], 'You are banned from this room.')
def on_banlist(self, uid, nick):
""" Application message containing a user currently on the banlist.
:param uid: Id of the banned user.
:type uid: str
:param nick: nick name of the banned user.
:type nick: str
"""
self.console_write(COLOR['bright_red'], 'Banned user: %s:%s' % (nick, uid))
def on_topic(self, topic):
""" Application message containing the rooms topic(if any)
:param topic: The topic of the room.
:type topic: str
"""
topic_msg = topic.encode('utf-8', 'replace')
self.console_write(COLOR['cyan'], 'room topic: ' + topic_msg)
def on_from_owner(self, owner_msg):
""" Application message received when a user's broadcast gets closed by a moderator.
NOTE: There are other types of this message kind..
:param owner_msg: url encoded string.
:type owner_msg: str
"""
msg = str(owner_msg).replace('notice', '')
msg = string_util.unquote(msg.encode('utf-8'))
self.console_write(COLOR['bright_red'], msg)
def on_doublesignon(self):
""" Application message received when the client account is already in the room. """
self.console_write(COLOR['bright_red'], 'Double account sign on. Aborting!')
self.is_connected = False
def on_reported(self, nick, uid):
""" Application message received when the client gets reported by another user in the room.
:param nick: The nick name of the user reporting the client.
:type nick: str
:param uid: The Id of the user reporting the client.
:type uid: str
"""
self.console_write(COLOR['bright_red'], 'You were reported by: %s:%s' % (nick, uid))
def on_gift(self, gift_sender, gift_receiver, gift_info):
""" Application message received when a user sends another user a gift.
NOTE: This is not fully tested/discovered
:param gift_sender: The gift senders information.
:type gift_sender: dict
:param gift_receiver: The gift receiver information.
:type gift_receiver: dict
:param gift_info: The gift information.
:type gift_info: dict
"""
sender_nick = gift_sender['name']
receiver_nick = gift_receiver['name']
receiver_gp = int(gift_receiver['points'])
gift_name = gift_info['name']
gift_comment = gift_info['comment']
self.console_write(COLOR['bright_magenta'], '%s sent gift %s to %s points: %s, comment: %s' %
(sender_nick, gift_name, receiver_nick, receiver_gp, gift_comment))
def on_privmsg(self, msg_sender, raw_msg, msg_color):
""" Application message received when a user sends a chat message among other.
Several commands are sent through this type of message, this method
sorts the different commands out, and sends them of to the correct event handlers(methods).
:param msg_sender: The nick name of the message sender.
:type msg_sender: str
:param raw_msg: The message as comma seperated decimals.
:type raw_msg: str
:param msg_color: The chat message color.
:type msg_color: str
"""
# Get user info object of the user sending the message..
self.active_user = self.users.search(msg_sender)
# decode the message from comma separated decimal to normal text
decoded_msg = self._decode_msg(u'' + raw_msg)
if decoded_msg.startswith('/'):
msg_cmd = decoded_msg.split(' ')
if msg_cmd[0] == '/msg':
private_msg = ' '.join(msg_cmd[2:])
self.private_message_handler(private_msg.strip())
elif msg_cmd[0] == '/reported':
self.on_reported(self.active_user.nick, self.active_user.id)
elif msg_cmd[0] == '/mbs':
if self.active_user.is_mod:
if len(msg_cmd) == 4:
media_type = msg_cmd[1]
media_id = msg_cmd[2]
threading.Thread(target=self.on_media_broadcast_start,
args=(media_type, media_id, msg_sender,)).start()
elif msg_cmd[0] == '/mbc':
if self.active_user.is_mod:
if len(msg_cmd) == 2:
media_type = msg_cmd[1]
self.on_media_broadcast_close(media_type, msg_sender)
elif msg_cmd[0] == '/mbpa':
if self.active_user.is_mod:
if len(msg_cmd) == 2:
media_type = msg_cmd[1]
self.on_media_broadcast_paused(media_type, msg_sender)
elif msg_cmd[0] == '/mbpl':
if self.active_user.is_mod:
if len(msg_cmd) == 3:
media_type = msg_cmd[1]
time_point = int(msg_cmd[2])
self.on_media_broadcast_play(media_type, time_point, msg_sender)
elif msg_cmd[0] == '/mbsk':
if self.active_user.is_mod:
if len(msg_cmd) == 3:
media_type = msg_cmd[1]
time_point = int(msg_cmd[2])
self.on_media_broadcast_skip(media_type, time_point, msg_sender)
else:
if len(msg_color) == 10:
self.message_handler(decoded_msg.strip())
else:
log.warning('rejecting chat msg from: %s:%s with unusual msg color: %s' %
(self.active_user.nick, self.active_user.id, msg_color))
# Message Handler.
def message_handler(self, decoded_msg):
""" Message handler.
:param decoded_msg: The decoded msg(text).
:type decoded_msg: str
"""
self.console_write(COLOR['green'], '%s: %s ' % (self.active_user.nick, decoded_msg))
# Private Message Handler.
def private_message_handler(self, private_msg):
""" A user private message the client.
:param private_msg: The private message.
:type private_msg: str
"""
self.console_write(COLOR['white'], 'Private message from %s: %s' % (self.active_user.nick, private_msg))
# Media Events Handlers.
def on_media_broadcast_start(self, media_type, video_id, usr_nick):
""" A user started a media broadcast.
:param media_type: The type of media. youTube or soundCloud.
:type media_type: str
:param video_id: The youtube ID or souncloud trackID.
:type video_id: str
:param usr_nick: The user name of the user playing media.
:type usr_nick: str
"""
self.console_write(COLOR['bright_magenta'], '%s is playing %s %s' % (usr_nick, media_type, video_id))
def on_media_broadcast_close(self, media_type, usr_nick):
""" A user closed a media broadcast.
:param media_type: The type of media. youTube or soundCloud.
:type media_type: str
:param usr_nick: The user name of the user closing the media.
:type usr_nick: str
"""
self.console_write(COLOR['bright_magenta'], '%s closed the %s' % (usr_nick, media_type))
def on_media_broadcast_paused(self, media_type, usr_nick):
""" A user paused the media broadcast.
:param media_type: The type of media being paused. youTube or soundCloud.
:type media_type: str
:param usr_nick: The user name of the user pausing the media.
:type usr_nick: str
"""
self.console_write(COLOR['bright_magenta'], '%s paused the %s' % (usr_nick, media_type))
def on_media_broadcast_play(self, media_type, time_point, usr_nick):
""" A user resumed playing a media broadcast.
:param media_type: The media type. youTube or soundCloud.
:type media_type: str
:param time_point: The time point in the tune in milliseconds.
:type time_point: int
:param usr_nick: The user resuming the tune.
:type usr_nick: str
"""
self.console_write(COLOR['bright_magenta'], '%s resumed the %s at: %s' %
(usr_nick, media_type, time_point))
def on_media_broadcast_skip(self, media_type, time_point, usr_nick):
""" A user time searched a tune.
:param media_type: The media type. youTube or soundCloud.
:type media_type: str
:param time_point: The time point in the tune in milliseconds.
:type time_point: int
:param usr_nick: The user time searching the tune.
:type usr_nick: str
"""
self.console_write(COLOR['bright_magenta'], '%s time searched the %s at: %s ' %
(usr_nick, media_type, time_point))
# Message Methods.
def send_bauth_msg(self):
""" Get and send the bauth key needed before we can start a broadcast. """
if self._bauth_key is not None:
self.connection.call('bauth', [u'' + self._bauth_key])
else:
_token = self.param.get_broadcast_token(self.nickname, self._client_id)
if _token != 'PW':
self._bauth_key = _token
self.connection.call('bauth', [u'' + _token])
def send_cauth_msg(self, cauthkey):
""" Send the cauth message, we need to send this before we can chat.
:param cauthkey: The cauth key.
:type cauthkey: str
"""
self.connection.call('cauth', [u'' + cauthkey])
def send_owner_run_msg(self, msg):
""" Send owner run message.
:param msg: The message to send.
:type msg: str
"""
if self.is_client_mod:
msg = string_util.quote_str(msg)
self.connection.call('owner_run', [u'notice' + msg])
def send_cam_approve_msg(self, nick, uid=None):
""" Send cam approval message.
NOTE: if no uid is provided, we try and look up the user by nick.
:param nick: The nick to be approved.