-
Notifications
You must be signed in to change notification settings - Fork 47
/
wechatircd.py
executable file
·2004 lines (1743 loc) · 73.8 KB
/
wechatircd.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 python3
from configargparse import ArgParser, Namespace
#from ipdb import set_trace as bp
from collections import deque
from datetime import datetime, timezone
from itertools import chain
import aiohttp.web, async_timeout, asyncio, base64, inspect, json, logging.handlers, os, pprint, random, re, \
signal, socket, ssl, string, sys, time, traceback, uuid, weakref
logger = logging.getLogger('wechatircd')
im_name = 'WeChat'
capabilities = set(['draft/message-tags', 'echo-message', 'multi-prefix', 'sasl', 'server-time']) # http://ircv3.net/irc/
options = None
server = None
web = None
def debug(msg, *args):
logger.debug(msg, *args)
def info(msg, *args):
logger.info(msg, *args)
def warning(msg, *args):
logger.warning(msg, *args)
def error(msg, *args):
logger.error(msg, *args)
class ExceptionHook(object):
instance = None
def __call__(self, *args, **kwargs):
if self.instance is None:
from IPython.core import ultratb
self.instance = ultratb.VerboseTB(call_pdb=True)
return self.instance(*args, **kwargs)
### HTTP serving js & WebSocket server
class Web(object):
def __init__(self, tls):
global web
web = self
self.tls = tls
self.id2media = {}
self.id2message = {}
self.recent_messages = deque()
self.ws = weakref.WeakSet()
async def handle_index(self, request):
with open(os.path.join(options.http_root, 'index.html'), 'rb') as f:
return aiohttp.web.Response(body=f.read())
async def handle_index_js(self, request):
try:
with open(os.path.join(options.http_root, 'index.js'), 'rb') as f:
return aiohttp.web.Response(body=f.read(),
headers={'Content-Type': 'application/javascript; charset=UTF-8',
'Access-Control-Allow-Origin': '*'})
except FileNotFoundError:
return aiohttp.web.Response(status=404, text='Not Found')
async def handle_injector_js(self, request):
try:
with open(os.path.join(options.http_root, 'injector.js'), 'rb') as f:
return aiohttp.web.Response(
body=f.read().replace(b'@WEBSOCKET_URL', 'wss://{}/ws'.format(request.headers['Host']).encode()),
headers={'Content-Type': 'application/javascript; charset=UTF-8',
'Access-Control-Allow-Origin': '*'})
except FileNotFoundError:
return aiohttp.web.Response(status=404, text='Not Found. Wrong --http-root ?')
except KeyError:
return aiohttp.web.Response(status=400, text='Missing Host:')
async def handle_media(self, request):
id = re.sub(r'\..*', '', request.match_info.get('id'))
if id not in self.id2media:
return aiohttp.web.Response(status=404, text='Not Found')
try:
media = self.id2media[id]
with async_timeout.timeout(30, loop=server.loop):
async with aiohttp.ClientSession() as session:
async with session.get(media['url'], headers={'Cookie': media['cookie']}) as resp:
response = aiohttp.web.StreamResponse(status=resp.status, reason=resp.reason, headers={'Content-Type': resp.headers.get('content-type', 'application/octet-stream')})
await response.prepare(request)
while True:
chunk = await resp.content.readany()
if not chunk:
await response.write_eof()
break
await response.write(chunk)
await response.drain()
return response
except asyncio.TimeoutError:
return aiohttp.web.Response(status=504, text='I used to live in 504A')
except Exception as ex:
return aiohttp.web.Response(status=500, text=str(ex))
async def handle_web_socket(self, request):
ws = aiohttp.web.WebSocketResponse(heartbeat=options.heartbeat)
self.ws.add(ws)
peername = request.transport.get_extra_info('peername')
info('WebSocket client connected from %r', peername)
await ws.prepare(request)
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
try:
data = json.loads(msg.data)
server.on_websocket(data)
except AssertionError:
info('WebSocket client error')
break
except:
raise
elif msg.type == aiohttp.WSMsgType.CLOSE:
info('WebSocket client close')
break
info('WebSocket client disconnected from %r', peername)
server.on_websocket_close(peername)
self.ws.remove(ws)
return ws
def start(self, listens, port, loop):
self.loop = loop
self.app = aiohttp.web.Application()
self.app.router.add_route('GET', '/', self.handle_index)
self.app.router.add_route('GET', '/index.js', self.handle_index_js)
self.app.router.add_route('GET', '/injector.js', self.handle_injector_js)
self.app.router.add_route('GET', '/media/{id}', self.handle_media)
self.app.router.add_route('GET', '/ws', self.handle_web_socket)
self.handler = self.app.make_handler()
self.srv = []
for i in listens:
self.srv.append(loop.run_until_complete(
loop.create_server(self.handler, i, port, ssl=self.tls)))
def stop(self):
for i in self.srv:
i.close()
self.loop.run_until_complete(i.wait_closed())
self.loop.run_until_complete(self.app.shutdown())
self.loop.run_until_complete(self.handler.finish_connections(0))
self.loop.run_until_complete(self.app.cleanup())
def append_history(self, data):
if len(self.recent_messages) >= 10000:
msg = self.recent_messages.popleft()
del self.id2message[msg['id']]
self.recent_messages.append(data)
self.id2message[data['id']] = data
def send_command(self, data):
for ws in web.ws:
try:
self.loop.create_task(ws.send_str(json.dumps(data)))
except:
pass
break
def logout(self):
self.send_command({'command': 'logout'})
def reload(self):
self.send_command({'command': 'reload'})
def send_file(self, receiver, filename, body):
self.send_command({
'command': 'send_file',
'receiver': receiver,
'filename': filename,
'body': body.decode('latin-1'),
})
def send_text_message(self, client, receiver, msg):
self.send_command({
'command': 'send_text_message',
'client': client.nick,
'receiver': receiver,
'text': msg,
})
def add_friend(self, username, message):
self.send_command({
'command': 'add_friend',
'user': username,
'text': message,
})
def add_member(self, roomname, username):
self.send_command({
'command': 'add_member',
'room': roomname,
'user': username,
})
def del_member(self, roomname, username):
self.send_command({
'command': 'del_member',
'room': roomname,
'user': username,
})
def mod_topic(self, roomname, topic):
self.send_command({
'command': 'mod_topic',
'room': roomname,
'topic': topic,
})
def reload_contact(self, who):
self.send_command({
'command': 'reload_contact',
'name': who,
})
def web_eval(self, expr):
self.send_command({
'command': 'eval',
'expr': expr,
})
### IRC utilities
def irc_lower(s):
irc_trans = str.maketrans(string.ascii_uppercase + '[]\\^',
string.ascii_lowercase + '{}|~')
return s.translate(irc_trans)
# loose
def irc_escape(s):
s = re.sub(r',', '.', s) # `,` is used as seprator in IRC messages
s = re.sub(r'&?', '', s) # chatroom name may include `&`
s = re.sub(r'<[^>]*>', '', s) # remove emoji
return re.sub(r'[^-\w$%^*()=./]', '', s)
def irc_escape_nick(s):
return re.sub('^[&#!+:]*', '', irc_escape(s))
def process_text(to, text):
# !m
# @(\d\d)(\d\d)(\d\d)?
reply = None
multiline = False
while 1:
cont = False
match = re.match(r'@(\d\d)(\d\d)(\d\d)? ', text)
if match:
cont = True
text = text[match.end():]
HH, MM, SS = int(match.group(1)), int(match.group(2)), match.group(3)
if SS is not None:
SS = int(SS)
for msg in reversed(web.recent_messages):
if msg['to'] == to.username:
dt = datetime.fromtimestamp(msg['time'])
if dt.hour == HH and dt.minute == MM and (SS is None or dt.second == SS):
reply = msg
break
match = re.match(r'@(\d{1,2}) ', text)
if match:
cont = True
text = text[match.end():]
which = int(match.group(1))
in_channel = isinstance(to, SpecialChannel)
if which > 0:
for msg in reversed(web.recent_messages):
if in_channel and msg['to'] == to.username and msg['from'] != server or \
not in_channel and msg['from'] == to and msg['to'] == server.username:
which -= len(msg['text'].splitlines())
if which <= 0:
reply = msg
break
if text.startswith('!m '):
cont = True
text = text[3:]
multiline = True
if not cont: break
if multiline:
text = text.replace('\\n', '\n')
# nick: -> @Group Alias or SpecialUser#name
at = ''
i = 0
while i < len(text) and text[i] != ' ':
j = text.find(': ', i)
if j == -1: break
nick = text[i:j]
if not server.has_special_user(nick): break
user = server.get_special_user(nick)
if to in user.channel2nick:
at += '@{} '.format(user.channel2nick[to] or server.get_special_user(nick).alias())
else:
at += '@{} '.format(server.get_special_user(nick).alias())
i = j+2
text = at+text[i:]
if reply:
refer_text = reply['text'].replace('\n', '\\n')
if len(refer_text) > 8:
refer_text = refer_text[:8]+'...'
refer_from = reply['from']
if refer_from == server:
text = '「Re: {}」{}'.format(refer_text, text)
else:
if to in refer_from.channel2nick:
refer_from = refer_from.channel2nick[to] or refer_from.alias()
else:
refer_from = refer_from.alias()
text = '「Re {}: {}」{}'.format(refer_from, refer_text, text)
return text
def irc_log(where, peer, local_time, sender, line):
if options.logger_mask is None:
return
for regex in options.logger_ignore or []:
if re.search(regex, peer.name):
return
filename = local_time.strftime(options.logger_mask.replace('$channel', peer.nick))
time_str = local_time.strftime(options.logger_time_format.replace('$channel', peer.nick))
if where.log_file is None or where.log_file.name != filename:
if where.log_file is not None:
where.log_file.close()
os.makedirs(os.path.dirname(filename), exist_ok=True)
where.log_file = open(filename, 'a')
where.log_file.write('{}\t{}\t{}\n'.format(
time_str, sender.nick,
re.sub(r'\x03\d+(,\d+)?|[\x02\x0f\x1d\x1f\x16]', '', line)))
where.log_file.flush()
def irc_privmsg(client, command, to, text):
if command == 'PRIVMSG' and client.ctcp(to, text):
return
def send():
web.send_text_message(client, to.username, to.privmsg_text)
to.privmsg_text = ''
async def wait(seq):
await asyncio.sleep(options.paste_wait)
if to.privmsg_seq == seq:
send()
text = process_text(to, text)
to.privmsg_seq = to.privmsg_seq+1
if len(to.privmsg_text):
to.privmsg_text += '\n'
to.privmsg_text += text
server.loop.create_task(wait(to.privmsg_seq))
### Commands
cmd_use_case = {}
def registered(v):
def wrapped(fn):
cmd_use_case[fn.__name__] = v
return fn
return wrapped
class Command:
@staticmethod
@registered(3)
def authenticate(client, arg):
if arg.upper() == 'PLAIN':
client.write('AUTHENTICATE +')
return
if not (client.nick and client.user):
return
try:
if base64.b64decode(arg).split(b'\0')[2].decode() == options.sasl_password:
client.authenticated = True
client.reply('900 {} {} {} :You are now logged in as {}', client.nick, client.user, client.nick, client.nick)
client.reply('903 {} :SASL authentication successful', client.nick)
client.register()
else:
client.reply('904 {} :SASL authentication failed', client.nick)
except Exception as ex:
client.reply('904 {} :SASL authentication failed', client.nick)
@staticmethod
def away(client):
pass
@staticmethod
@registered(3)
def cap(client, *args):
if not args: return
comm = args[0].lower()
if comm == 'list':
client.reply('CAP * LIST :{}', ' '.join(client.capabilities))
elif comm == 'ls':
client.reply('CAP * LS :{}', ' '.join(capabilities))
elif comm == 'req':
enabled, disabled = set(), set()
for name in args[1].split():
if name.startswith('-'):
disabled.add(name[1:])
else:
enabled.add(name)
client.capabilities = (capabilities & enabled) - disabled
client.reply('CAP * ACK :{}', ' '.join(client.capabilities))
@staticmethod
def info(client):
client.rpl_info('{} users', len(server.nicks))
client.rpl_info('{} {} users', im_name, len(client.nick2special_user))
client.rpl_info('{} {} rooms', im_name, len(client.name2special_room))
@staticmethod
def invite(client, nick, channelname):
if client.is_in_channel(channelname):
server.get_channel(channelname).on_invite(client, nick)
else:
client.err_notonchannel(channelname)
@staticmethod
def ison(client, *nicks):
client.reply('303 {} :{}', client.nick,
' '.join(nick for nick in nicks
if server.has_nick(nick)))
@staticmethod
def join(client, *args):
if not args:
self.err_needmoreparams('JOIN')
else:
arg = args[0]
if arg == '0':
channels = list(client.channels.values())
for channel in channels:
channel.on_part(client, channel.name)
else:
for channelname in arg.split(','):
if server.has_special_room(channelname):
server.get_special_room(channelname).on_join(client)
else:
try:
server.ensure_channel(channelname).on_join(client)
except ValueError:
client.err_nosuchchannel(channelname)
@staticmethod
def kick(client, channelname, nick, reason=None):
if client.is_in_channel(channelname):
server.get_channel(channelname).on_kick(client, nick, reason)
else:
client.err_notonchannel(channelname)
@staticmethod
def kill(client, nick, reason=None):
if not server.has_nick(nick):
client.err_nosuchnick(nick)
return
user = server.get_nick(nick)
if not isinstance(user, Client) or user == client:
client.err_nosuchnick(nick)
return
user.disconnect(reason)
@staticmethod
def list(client, arg=None):
if arg:
channels = []
for channelname in arg.split(','):
if server.has_channel(channelname):
channels.append(server.get_channel(channelname))
else:
channels = set(server.channels.values())
channels.update(server.name2special_room.values())
channels = list(channels)
channels.sort(key=lambda ch: ch.name)
for channel in channels:
client.reply('322 {} {} {} :{}', client.nick, channel.name,
channel.n_members(client), channel.topic)
client.reply('323 {} :End of LIST', client.nick)
@staticmethod
def lusers(client):
client.reply('251 :There are {} users and {} {} users on 1 server',
len(server.nicks),
len(server.nick2special_user),
im_name
)
@staticmethod
def mode(client, target, *args):
if server.has_nick(target):
if args:
client.err_umodeunknownflag()
else:
client.rpl_umodeis(server.get_nick(target).mode)
elif server.has_channel(target):
server.get_channel(target).on_mode(client, *args)
else:
client.err_nosuchchannel(target)
@staticmethod
def motd(client):
async def do():
try:
async with aiohttp.ClientSession() as session:
async with session.get('https://api.github.com/repos/MaskRay/wechatircd/commits') as resp:
client.reply('375 {} :- {} Message of the Day -', client.nick, server.name)
data = await resp.json()
for x in data[:5]:
client.reply('372 {} :- {} {} {}'.format(client.nick, x['sha'][:7], x['commit']['committer']['date'][:10], x['commit']['message'].replace('\n', '\\n')))
client.reply('376 {} :End of /MOTD command.', client.nick)
except:
pass
server.loop.create_task(do())
@staticmethod
def names(client, target):
if not client.is_in_channel(target):
client.err_notonchannel(target)
return
server.get_channel(target).on_names(client)
@staticmethod
@registered(3)
def nick(client, *args):
if len(options.irc_password) and not client.authenticated:
client.err_passwdmismatch('NICK')
return
if not args:
client.err_nonicknamegiven()
return
server.change_nick(client, args[0])
@staticmethod
def notice(client, *args):
Command.notice_or_privmsg(client, 'NOTICE', *args)
@staticmethod
def part(client, arg, *args):
partmsg = args[0] if args else None
for channelname in arg.split(','):
if client.is_in_channel(channelname):
server.get_channel(channelname).on_part(client, partmsg)
else:
client.err_notonchannel(channelname)
@staticmethod
@registered(1)
def pass_(client, password):
if len(options.irc_password) and password == options.irc_password:
client.authenticated = True
client.register()
@staticmethod
@registered(3)
def ping(client, *args):
if not args:
client.err_noorigin()
return
client.reply('PONG {} :{}', server.name, args[0])
@staticmethod
@registered(3)
def pong(client, *args):
pass
@staticmethod
def privmsg(client, *args):
Command.notice_or_privmsg(client, 'PRIVMSG', *args)
@staticmethod
def quit(client, *args):
client.disconnect(args[0] if args else client.prefix)
@staticmethod
def squit(client, *args):
web.logout()
@staticmethod
def stats(client, query):
if len(query) == 1:
if query == 'u':
td = datetime.now() - server._boot
client.reply('242 {} :Server Up {} days {}:{:02}:{:02}',
client.nick, td.days, td.seconds // 3600,
td.seconds // 60 % 60, td.seconds % 60)
client.reply('219 {} {} :End of STATS report', client.nick, query)
@staticmethod
def summon(client, nick, msg):
if server.has_special_user(nick):
web.add_friend(server.get_special_user(nick).username, msg)
else:
client.err_nologin(nick)
@staticmethod
def time(client):
client.reply('391 {} {} :{}Z', client.nick, server.name,
datetime.utcnow().isoformat())
@staticmethod
def topic(client, channelname, new=None):
if not client.is_in_channel(channelname):
client.err_notonchannel(channelname)
return
server.get_channel(channelname).on_topic(client, new)
@staticmethod
def who(client, target):
if server.has_channel(target):
server.get_channel(target).on_who(client)
elif server.has_nick(target):
server.get_nick(target).on_who_member(client, server)
client.reply('315 {} {} :End of WHO list', client.nick, target)
@staticmethod
def whois(client, *args):
if not args:
client.err_nonicknamegiven()
return
elif len(args) == 1:
target = args[0]
else:
target = args[1]
if server.has_nick(target):
server.get_nick(target).on_whois(client)
else:
client.err_nosuchnick(target)
return
client.reply('318 {} {} :End of WHOIS list', client.nick, target)
@classmethod
def notice_or_privmsg(cls, client, command, *args):
if not args:
client.err_norecipient(command)
return
if len(args) == 1:
client.err_notexttosend()
return
target = args[0]
msg = args[1]
# on name conflict, prefer to resolve user first
if server.has_nick(target):
user = server.get_nick(target)
if isinstance(user, Client):
user.write(':{} PRIVMSG {} :{}'.format(client.prefix, user.nick, msg))
elif user.is_friend:
user.on_notice_or_privmsg(client, command, msg)
elif command == 'PRIVMSG':
client.err_nosuchnick(target)
# IRC channel or special chatroom
elif client.is_in_channel(target):
server.get_channel(target).on_notice_or_privmsg(
client, command, msg)
elif command == 'PRIVMSG':
client.err_nosuchnick(target)
@staticmethod
@registered(1)
def user(client, user, mode, _, realname):
if len(options.irc_password) and not client.authenticated:
client.err_passwdmismatch('USER')
return
client.user = user
client.realname = realname
client.register()
class SpecialCommands:
@staticmethod
def add_friend_ack(data):
nick = server.username2special_user[data['user']].nick
for client in server.auth_clients():
client.reply('342 {} {} :Summoning user to IRC', client.nick, nick)
@staticmethod
def add_friend_nak(data):
nick = server.username2special_user[data['user']].nick
for client in server.auth_clients():
client.status('Friend request to {} failed'.format(nick))
@staticmethod
def contact(data):
friend = data['friend']
record = data['record']
debug('{}: '.format('friend' if friend else 'room_contact') + ', '.join([k + ':' + repr(record.get(k)) for k in ['Alias', 'Nick', 'UserName']]))
server.ensure_special_user(record, 1 if friend else -1)
@staticmethod
def delete_contact(data):
username = data['username']
# FIXME user
if username in server.username2special_room:
server.username2special_room[username].on_delete()
@staticmethod
def message(data):
if data['id'] in web.id2message:
return
if data['from'] == 'BrandServ':
if options.ignore_brand: return
sender = BrandServ()
else:
sender = server.ensure_special_user(data['from'])
sender_client_nick = data['client']
if data.get('type') == 'room':
to = server.ensure_special_room(data['to'])
else:
to = server.ensure_special_user(data['to'])
data['from'] = sender
data['to'] = to.username
web.append_history(data)
if data.get('media'):
media_id = str(len(web.id2media))
if options.http_url:
web.id2media[media_id] = {'url': data['text'], 'cookie': data['cookie']}
if data['media'] in ('图片', '动画表情'):
media_id += '.jpg'
elif data['media'] == '语音':
media_id += '.mp3'
elif data['media'] in ('视频', '小视频'):
media_id += '.mp4'
text = '[{}] {}/media/{}'.format(data['media'], options.http_url, media_id)
else:
text = '[{}] {}'.format(data['media'], data['text'])
else:
text = data['text']
for line in text.splitlines():
if to == server or sender == server:
client = server.preferred_client()
if client:
where = sender if to == server else to
irc_log(where, client if where == server else where, datetime.fromtimestamp(data['time']), client if sender == server else sender, line)
else:
irc_log(to, to, datetime.fromtimestamp(data['time']), sender, line)
if isinstance(to, SpecialChannel):
for c in server.auth_clients():
if c not in to.joined and 'm' not in to.mode:
if options.join == 'auto' and c not in to.explicit_parted or options.join == 'new':
c.auto_join(to)
for client in server.auth_clients():
if (isinstance(to, Channel) and client not in to.joined) or (
'echo-message' not in client.capabilities and
client.nick == sender_client_nick):
continue
sender_prefix = client.prefix if sender == server else sender.prefix
to_nick = client.nick if to == server else to.nick
msg = ':{} PRIVMSG {} :{}'.format(sender_prefix, to_nick, line)
tags = []
if 'draft/message-tags' in client.capabilities:
tags.append('draft/msgid={}'.format(data['id']))
if 'server-time' in client.capabilities:
tags.append('time={}Z'.format(datetime.fromtimestamp(
data['time'], timezone.utc).strftime('%FT%T.%f')[:23]))
if tags:
msg = '@{} {}'.format(';'.join(tags), msg)
client.write(msg)
@staticmethod
def room(data):
record = data['record']
debug('room: ' + ', '.join(k + ':' + repr(record.get(k)) for k in ['Nick', 'UserName']))
server.ensure_special_room(record).update_detail(record)
@staticmethod
def self(data):
server.username = data['username']
@staticmethod
def send_file_message_nak(data):
receiver = data['receiver']
filename = data['filename']
if server.has_special_room(receiver):
room = server.get_special_room(receiver)
for client in server.auth_clients():
client.write(':{} PRIVMSG {} :[文件发送失败] {}'.format(
client.prefix, room.nick, filename))
elif server.has_special_user(receiver):
user = server.get_special_user(receiver)
for client in server.auth_clients():
client.write(':{} PRIVMSG {} :[文件发送失败] {}'.format(
client.prefix, user.nick, filename))
@staticmethod
def send_text_message_nak(data):
receiver = data['receiver']
msg = data['text']
if server.has_special_room(receiver):
room = server.get_special_room(receiver)
for client in server.auth_clients():
client.write(':{} PRIVMSG {} :[文字发送失败] {}'.format(
client.prefix, room.nick, msg))
elif server.has_special_user(receiver):
user = server.get_special_user(receiver)
for client in server.auth_clients():
client.write(':{} PRIVMSG {} :[文字发送失败] {}'.format(
client.prefix, user.nick, msg))
@staticmethod
def web_debug(data):
debug('web_debug: ' + repr(data))
### Channels: StandardChannel, StatusChannel, SpecialChannel
class Channel:
def __init__(self, name):
self.name = name
self.topic = ''
self.mode = 'n'
self.members = {}
def __repr__(self):
return repr({k: v for k, v in self.__dict__.items() if k in ('name',)})
@property
def prefix(self):
return self.name
def log(self, source, fmt, *args):
info('%s %s '+fmt, self.name, source.nick, *args)
def multicast_group(self, source):
return self.members.keys()
def n_members(self, client):
return len(self.members)
def event(self, source, command, fmt, *args, include_source=True):
line = fmt.format(*args) if args else fmt
for client in self.multicast_group(source):
if client != source or include_source:
client.write(':{} {} {}'.format(source.prefix, command, line))
def dehalfop_event(self, user):
self.event(self, 'MODE', '{} -h {}', self.name, user.nick)
def deop_event(self, user):
self.event(self, 'MODE', '{} -o {}', self.name, user.nick)
def devoice_event(self, user):
self.event(self, 'MODE', '{} -v {}', self.name, user.nick)
def halfop_event(self, user):
self.event(self, 'MODE', '{} +h {}', self.name, user.nick)
def nick_event(self, user, new):
self.event(user, 'NICK', new)
def join_event(self, user):
self.event(user, 'JOIN', self.name)
def kick_event(self, kicker, channel, kicked, reason=None):
if reason:
self.event(kicker, 'KICK', '{} {}: {}', channel.name, kicked.nick, reason)
else:
self.event(kicker, 'KICK', '{} {}', channel.name, kicked.nick)
self.log(kicker, 'kicked %s', kicked.prefix)
def op_event(self, user):
self.event(self, 'MODE', '{} +o {}', self.name, user.nick)
def part_event(self, user, partmsg):
if partmsg:
self.event(user, 'PART', '{} :{}', self.name, partmsg)
else:
self.event(user, 'PART', self.name)
def voice_event(self, user):
self.event(user, 'MODE', '{} +v {}', self.name, user.nick)
def on_invite(self, client, nick):
# TODO
client.err_chanoprivsneeded(self.name)
# subclasses should return True if succeeded to join
def on_join(self, client):
client.enter(self)
self.join_event(client)
self.on_topic(client)
self.on_names(client)
def on_kick(self, client, nick, reason):
client.err_chanoprivsneeded(self.name)
def on_mode(self, client):
client.rpl_channelmodeis(self.name, self.mode)
def on_names(self, client):
self.on_names_impl(client, self.members.items())
def on_names_impl(self, client, items):
names = []
for u, mode in items:
nick = u.nick
prefix = ''
while 1:
if 'o' in mode:
prefix += '@'
if 'multi-prefix' not in client.capabilities:
break
if 'h' in mode:
prefix += '%'
if 'multi-prefix' not in client.capabilities:
break
if 'v' in mode:
prefix += '+'
if 'multi-prefix' not in client.capabilities:
break
break
names.append(prefix+nick)
buf = ''
bytelen = 0
maxlen = 510-1-len(server.name)-5-len(client.nick.encode())-3-len(self.name.encode())-2
for name in names:
if bytelen+1+len(name.encode()) > maxlen:
client.reply('353 {} = {} :{}', client.nick, self.name, buf)
buf = ''
bytelen = 0
if buf:
buf += ' '
bytelen += 1
buf += name
bytelen += len(name.encode())
if buf:
client.reply('353 {} = {} :{}', client.nick, self.name, buf)
client.reply('366 {} {} :End of NAMES list', client.nick, self.name)
def on_topic(self, client, new=None):
if new:
client.err_nochanmodes(self.name)
else:
if self.topic:
client.reply('332 {} {} :{}', client.nick, self.name, self.topic)
else:
client.reply('331 {} {} :No topic is set', client.nick, self.name)
class StandardChannel(Channel):
def __init__(self, name):
super().__init__(name)
def on_notice_or_privmsg(self, client, command, msg):
self.event(client, command, '{} :{}', self.name, msg, include_source=False)
def on_join(self, client):
if client in self.members:
return False
# first user becomes op
self.members[client] = 'o' if not self.members else ''
super().on_join(client)
return True
def on_kick(self, client, nick, reason):
if 'o' not in self.members[client]:
client.err_chanoprivsneeded(self.name)
elif not server.has_nick(nick):
client.err_usernotinchannel(nick, self.name)
else:
user = server.get_nick(nick)
if user not in self.members:
client.err_usernotinchannel(nick, self.name)
elif client != user:
self.kick_event(client, self, user, reason)
self.on_part(user, None)
def on_part(self, client, msg=None):
if client not in self.members:
client.err_notonchannel(self.name)
return False
if msg: # explicit PART, not disconnection
self.part_event(client, msg)
if len(self.members) == 1:
server.remove_channel(self.name)
elif 'o' in self.members.pop(client):
user = next(iter(self.members))
self.members[user] += 'o'
self.op_event(user)
client.leave(self)
return True
def on_topic(self, client, new=None):
if new:
self.log(client, 'set topic %r', new)
self.topic = new
self.event(client, 'TOPIC', '{} :{}', self.name, new)
else:
super().on_topic(client, new)
def on_who(self, client):