forked from hackyourlife/lima-gold
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·1830 lines (1690 loc) · 54.3 KB
/
main.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
#!/bin/python
# -*- coding: utf-8 -*-
# vim:set ts=8 sts=8 sw=8 tw=80 noet cc=80:
import sys
import os
import configparser
import logging
import readline
import re
import hashlib
import rl
import rp
import json
import rot
import morse
import random_quote
from optparse import OptionParser
from getpass import getpass
from random import randint, shuffle
from client import Client
from api import noshow, help, get_help
import datetime
_TIME_FORMAT = '%Y%m%dT%H:%M:%S'
_PRINT_FORMAT = '%H:%M:%S'
def time(at=None):
"""Stringify time in ISO 8601 format."""
if not at:
at = utcnow()
if type(at) == float:
at = datetime.datetime.fromtimestamp(at)
st = at.strftime(_TIME_FORMAT)
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
st += ('Z' if tz == 'UTC' else tz)
return st
def localtime(at=None):
if not at:
at = now()
if type(at) == float:
at = datetime.datetime.fromtimestamp(at)
st = at.strftime(_PRINT_FORMAT)
return st
def utcnow():
return datetime.datetime.utcnow()
def now():
return datetime.datetime.now()
logger = logging.getLogger(__name__)
PROMPT = '%s%s '
mode = '>'
enable_bell = False
no_colors = False
show_timestamps = True
decode_caesar = False
caesar_lang = None
msg_decode = False
espeak_voice = None
PLAIN = '>'
STEALTH = '$'
GOLD = '#'
xmpp = None
encrypted_message_info = "[Diese Nachricht ist nur für Lima-Gold-Mitglieder " \
"lesbar. Mehr auf lima-city.de/gold]"
encrypted_link_info = "[Dieser Link ist nur für Lima-Gold-Mitglieder lesbar. " \
"Mehr auf lima-city.de/gold]"
encrypted_section_info = "[Dieser Teil der Nachricht ist nur für " \
"Lima-Gold-Mitglieder lesbar. Mehr auf lima-city.de/gold]"
url_regex = re.compile(r'(https?|ftps?|ssh|sftp|irc|xmpp)://([a-zA-Z0-9]+)')
jid_regex = re.compile(r'[a-zA-Z0-9]+@(?:[a-zA-Z0-9]+\.)+[a-zA-Z0-9]+(?:/.*)?')
longest = 0
rpad = False
color_sequences = re.compile('\033\\[[^m]+?m')
COLORS = [ "[31m", "[32m", "[33m", "[34m", "[35m", "[36m", "[37m" ]
MENTION_COLOR = "[93m"
INPUT_COLOR = "[36m"
STEALTH_COLOR = "[96m"
ENCRYPTED_COLOR = "[33m" # "gold"
def get_nick_color(nick):
md5 = hashlib.md5(nick.encode())
return COLORS[md5.digest()[0] % len(COLORS) ]
def prompt():
global xmpp
return PROMPT % (xmpp.nick, mode)
def escape_vt(text):
# for now, just remove ESC and CSI chars
return text.replace("\033", "^[").replace("\x9b", "CSI")
def show_raw(raw):
if no_colors:
raw = color_sequences.sub('', raw)
rl.echo(raw)
else:
rl.echo("\033[0m%s" % raw, prompt_prefix="\033%s" % INPUT_COLOR)
def show(msg):
show_raw(escape_vt(msg))
def show_input(msg):
show_raw("\033%s%s %s%s\033[0m" % (INPUT_COLOR, localtime(),
escape_vt(prompt()), escape_vt(msg)))
class Help(object):
def __init__(self, synopsis=None, description=None, args={}, info=None,
see=[], topic=None):
self.iscommand = synopsis is not None
self.synopsis = synopsis
self.description = description
self.args = args
self.info = info
self.see = see
self.topic = topic
online_help = {
"/macro": Help("/macro text = replacement", "define a new "
"macro. They are evaluated on the input text "
"and can therefore invoke any command. However,"
" you cannot override any command for "
"manipulating macros.",
see=["/dmacro", "/macros"]),
"/dmacro": Help("/dmacro macro", "delete a macro.",
see=["/macro", "/macros"]),
"/macros": Help("/macros", "list all currently defined macros.",
see=["/macro", "/dmacro"]),
"/def": Help("/def text = replacement", "substitute all "
"occurences of \"text\" by \"replacement\". "
"This is similar to a macro, but more flexible,"
" since it operates on substrings.",
see=["/undef", "/defs"]),
"/undef": Help("/undef def", "delete a definition.",
see=["/def", "/defs"]),
"/defs": Help("/defs", "lists all currently defined "
"definitions.", see=["/def", "/undef"]),
"modes": Help(topic="Modes", info="There exist 3 different "
"modes of operation: plaintext, encrypted and "
"stealth mode. They influence how messages are "
"sent and if a regular client can see and/or "
"read them. The current mode is indicated by "
"the last character of the prompt.\n"
"> = plaintext, # = encrypted, $ = stealth",
see=["/plain", "/encrypt", "/stealth",
"/status"]),
"config": Help(topic="Configuration file", info="This clinet "
"can be configured with a configuration file "
"called xmpp.cfg and located in the current "
"directory. The syntax is like a plain ini "
"file: there are multiple sections, wich are "
"started with a \"[section]\" and multiple "
"values inside a section, one key/value pair "
"per line.\n"
"\n"
"The full list of all configurable options:\n"
"[xmpp]\n"
"jid = [email protected]\n"
"password = secret\n"
"room = [email protected]\n"
"nick = Me\n"
"key = secret\n"
"\n"
"[client]\n"
"bell = False\n"
"history = True\n"
"mode = plain\n"
"logfile = xmpp.log\n"
"\n"
"[ui]\n"
"rpadnicks = False\n"
"colors = True\n"
"timestamps = True\n"
"\n"
"The options have the following meaning:\n"
"jid: the jid of the jabber account.\n"
"password: the account's password. This is "
"optional. If it is missing, the client will "
"ask on startup.\n"
"room: the jid of the MUC room to join.\n"
"nick: the nick you would like to use in the "
"room.\n"
"key: the encryption key for all the encrypted "
"messages.\n"
"bell: if this is enabled, the client will "
"output a bell character each time a new "
"message is received.\n"
"history: if this is enabled, the client will "
"try to get 20 lines of history after joining "
"the room.\n"
"mode: the default mode. It can be \"plain\", "
"\"encrypt\" or \"stealth\". This has the same "
"effect as if you enter a /plain, /encrypt or "
"/stealth command by hand at each start.\n"
"logfile: the log file for history logging.\n"
"rpadnicks: pad nicks, such that all messages "
"are aligned\n"
"colors: enable coloring of messages\n"
"timestamps: show timestamps"),
"about": Help(topic="About", info="This client was written to "
"allow private group chats in public muc "
"rooms. The encrypted mode was invented to "
"show other participants, that a conversation "
"is going on, and to show them, that they "
"have no chance to participate. The stealth "
"mode was invented to hide the fact, that there"
" is a conversation at all. To make this "
"possible, the XMPP protocol was extended, "
"such that regular clients silently ignore the "
"stealth messages, but the conference server "
"still distributes them to all clients.")
}
def print_help():
commands = " ".join(sorted([ key for key in online_help.keys() \
if online_help[key].iscommand ]))
topics = " ".join(sorted([ key for key in online_help.keys() \
if not online_help[key].iscommand ]))
show("commands: %s\nhelp topics: %s\nFor more information, type /help "
"<command|topic>" % (commands, topics))
def show_help(subject):
if subject in online_help:
hlp = online_help[subject]
if hlp.iscommand:
text = "SYNOPSIS\n %s\n\nDESCRIPTION\n %s" % \
(hlp.synopsis, hlp.description)
if len(hlp.args) > 0:
a = "\n\n".join([ " %s\n %s" % \
(arg, hlp.args[arg])
for arg in hlp.args ])
text += "\n\nARGUMENTS:\n%s" % a
else:
text = "TOPIC: %s\n\n%s" % (hlp.topic, hlp.info)
if len(hlp.see) > 0:
text += "\n\nSEE ALSO\n %s" % ", ".join(hlp.see)
show(text)
else:
show("no help entry found")
class NickCompleter(object):
def __init__(self, xmpp):
self.xmpp = xmpp
def complete(self, text, state):
if state == 0: # first time for this text: find nicks
if text:
participants = self.xmpp.get_participants()
self.matches = [ participants[jid]["nick"] for \
jid in participants if \
participants[jid]["nick"] \
.startswith(text) ]
else:
self.matches = []
try:
return self.matches[state]
except IndexError:
return None
commands = {}
def add_command(name, callback):
commands[name] = callback
help_data = get_help(callback)
if help_data is not None:
online_help["/%s" % name] = Help(**help_data)
def parse_args(line, count=None):
whitespace = [ "\t", "\r", "\n", " " ]
args = []
s = 0
a = ""
for i in range(len(line)):
if count is not None and len(args) >= count:
if len(line) > i:
args += [ line[i:] ]
break
c = line[i]
if s == 0: # init
if c == '"':
s = 3
elif c == "'":
s = 4
elif c not in whitespace:
s = 1
a += c
elif s == 1: # normal
if c in whitespace:
if len(a) > 0:
args += [ a ]
a = ""
s = 2
else:
a += c
elif s == 2: # whitespace
if c == '"':
s = 3
elif c == "'":
s = 4
elif c not in whitespace:
s = 1
a += c
elif s == 3: # "quote"
if c == '"':
s = 1
elif c == "\\":
s = 5
else:
a += c
elif s == 4: # 'quote'
if c == "'":
s = 1
elif c == "\\":
s = 6
else:
a += c
elif s == 5: # "quote": escape
a += c
s = 3
elif s == 6: # 'quote': escape
a += c
s = 4
else:
raise Exception("unknown state!")
if len(a) > 0:
args += [ a ]
return args
def execute_command(line):
line = line.strip()
if len(line) == 0:
return False
cmd = line.split(" ")[0]
args = line[len(cmd) + 1:].strip()
if len(args) == 0:
args = None
if cmd[0] != "/":
return False
cmd = cmd[1:]
try:
c = commands[cmd]
if not hasattr(c, "noshow") or not c.noshow:
show_input(line)
if args is None:
c()
else:
nargs = c.__code__.co_argcount
args = parse_args(args, nargs - 1)
c(*args)
except KeyError:
show('unknown command: "/%s"' % cmd)
return (cmd, args)
except TypeError:
show("argument error")
return True
xmpp = None
if __name__ == "__main__":
logging.basicConfig(level=logging.ERROR,
format="%(levelname)-8s %(message)s")
parser = OptionParser()
parser.add_option("-f", "--file", dest="file", help="Config file path")
parser.add_option("-j", "--jid", dest="jid", help="JID")
parser.add_option("-p", "--password", dest="password", help="Password")
parser.add_option("-r", "--room", dest="room", help="Conference room")
parser.add_option("-n", "--nick", dest="nick", help="Nick")
parser.add_option("-k", "--key", dest="key", help="Encryption key")
parser.add_option("-l", "--log", dest="log", help="Log file path")
parser.add_option("-D", "--no-decode", dest="msgdecode", default=True,
action="store_false", help="Disable message decoding")
parser.add_option("-b", "--bell", dest="bell",
action="store_true", help="Enable bell")
parser.add_option("-B", "--no-bell", dest="bell",
action="store_false", help="Disable bell")
parser.add_option("-m", "--mode", dest="mode", help="Default mode")
parser.add_option("-i", "--history", dest="history",
action="store_true", help="Disable history on connect")
parser.add_option("-H", "--no-history", dest="history",
action="store_false", help="Disable history on connect")
parser.add_option("-a", "--rpad", dest="rpad",
action="store_true", help="rpad nicks")
parser.add_option("-A", "--no-rpad", dest="rpad",
action="store_false", help="Do not rpad nicks")
parser.add_option("-c", "--colors", dest="colors",
action="store_true", help="Disable colors")
parser.add_option("-C", "--no-colors", dest="colors",
action="store_false", help="Disable colors")
parser.add_option("-t", "--timestamps", dest="Enable timestamps",
action="store_true", help="Disable timestamps")
parser.add_option("-T", "--no-timestamps", dest="timestamps",
action="store_false", help="Disable timestamps")
parser.add_option("-E", "--encrypted", dest="encrypted",
help="Replacement text for encrypted messages")
parser.add_option("-L", "--link", dest="link",
help="Replacement text for encrypted links")
parser.add_option("-S", "--section", dest="section",
help="Replacement text for encrypted sections")
parser.add_option("-J", "--no-join-log", dest="joinlog",
action="store_false",
help="Disable join-time join messages")
parser.add_option("-V", "--voice", dest="voice", help="Voice name")
parser.add_option("--ipv4", action="store_false", dest="ipv6", help="Use IPv4 only")
(options, args) = parser.parse_args()
xdg_dirs = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config"))
filenames = [ "/etc/limagold.conf",
os.path.expanduser("~/.limagoldrc") ]
for xdg_dir in xdg_dirs.split(":"):
filenames += [ "%s/limagold.conf" % xdg_dir ]
filenames += [ "xmpp.cfg" ]
if options.file is not None:
filenames += [ options.file ]
config = configparser.SafeConfigParser()
cfgfiles = config.read(filenames)
for section in [ "xmpp", "client", "ui", "messages", "random_quote" ]:
if not config.has_section(section):
config.add_section(section)
if options.jid is not None:
config.set("xmpp", "jid", options.jid)
if options.password is not None:
config.set("xmpp", "password", options.password)
if options.room is not None:
config.set("xmpp", "room", options.room)
if options.nick is not None:
config.set("xmpp", "nick", options.nick)
if options.key is not None:
config.set("xmpp", "key", options.key)
if options.ipv6 is not None:
config.set("client", "ipv6", str(options.ipv6))
if options.log is not None:
config.set("client", "logfile", options.log)
if options.bell is not None:
config.set("client", "bell", str(options.bell))
if options.mode is not None:
config.set("client", "mode", options.mode)
if options.history is not None:
config.set("client", "history", str(options.history))
if options.joinlog is not None:
config.set("client", "joinlog", str(options.joinlog))
if options.rpad is not None:
config.set("ui", "rpadnicks", str(options.rpad))
if options.colors is not None:
config.set("ui", "colors", str(options.colors))
if options.timestamps is not None:
config.set("ui", "timestamps", str(options.timestamps))
if options.encrypted is not None:
config.set("messages", "encrypted", options.encrypted)
if options.link is not None:
config.set("messages", "encrypted_link", options.link)
if options.section is not None:
config.set("messages", "encrypted_section", options.section)
if len(config.options("random_quote")) == 0:
if os.path.isfile("/usr/share/lima-gold/bofh_excuses.txt"):
config.set("random_quote", "bofh",
'"/usr/share/lima-gold/'
'bofh_excuses.txt"')
elif os.path.isfile("./bofh_excuses.txt"):
config.set("random_quote", "bofh",
'"./bofh_excuses.txt"')
msg_decode = options.msgdecode
espeak_voice = options.voice
if espeak_voice is not None:
import struct
from pyaudio import PyAudio
import espeak
rate = espeak.initialize(espeak.AUDIO_OUTPUT_SYNCHRONOUS)
espeak.set_voice(espeak_voice)
pa = PyAudio()
snd = pa.open(format=pa.get_format_from_width(2), channels=1,
rate=rate, output=True)
snd.start_stream()
def synth_cb(samples, nsamples, events):
result = bytes()
for sample in samples[:nsamples]:
result += struct.pack("=h", sample)
snd.write(result)
return 0
espeak.set_synth_callback(synth_cb)
if config.has_section("random_quote"):
random_quote.init(config)
jid = config.get("xmpp", "jid")
try:
password = config.get("xmpp", "password")
except:
password = getpass("Password: ")
room = config.get("xmpp", "room")
nick = config.get("xmpp", "nick")
key = config.get("xmpp", "key", fallback=None)
logfile_name = os.path.expanduser(config.get("client", "logfile",
fallback="xmpp.log"))
enable_bell = config.getboolean("client", "bell", fallback=False)
ipv6 = config.getboolean("client", "ipv6", fallback=True)
default_mode = config.get("client", "mode", fallback="plain")
history = config.getboolean("client", "history", fallback=True)
join_log = config.getboolean("client", "joinlog", fallback=True)
rpad = config.getboolean("ui", "rpadnicks", fallback=False)
no_colors = not config.getboolean("ui", "colors", fallback=True)
show_timestamps = config.getboolean("ui", "timestamps", fallback=True)
decode_caesar = config.getboolean("ui", "caesar", fallback=False)
caesar_lang = config.get("ui", "caesar_lang", fallback="en")
encrypted_message_info = config.get("messages", "encrypted",
fallback=encrypted_message_info)
encrypted_link_info = config.get("messages", "encrypted_link",
fallback=encrypted_link_info)
encrypted_section_info = config.get("messages", "encrypted_section",
fallback=encrypted_section_info)
MENTION_COLOR = config.get("colors", "mention", fallback=MENTION_COLOR)
INPUT_COLOR = config.get("colors", "input", fallback=INPUT_COLOR)
STEALTH_COLOR = config.get("colors", "stealth", fallback=STEALTH_COLOR)
ENCRYPTED_COLOR = config.get("colors", "encrypted",
fallback=ENCRYPTED_COLOR)
mode = GOLD if key is not None else PLAIN
if not rot.is_supported(caesar_lang):
caesar_lang = "en"
xmpp = Client(jid, password, room, nick, key, history=history,
encrypted_msg_info=encrypted_message_info, ipv6=ipv6)
xmpp.register_plugin("xep_0030") # Service Discovery
xmpp.register_plugin("xep_0045") # Multi-User Chat
xmpp.register_plugin("xep_0199") # XMPP Ping
xmpp.register_plugin("encrypt-im") # encrypted stealth MUC
macros = {}
if config.has_section("macros"):
keys = config.options("macros")
for macro in keys:
macros[macro] = config.get("macros", macro)
definitions = {}
if config.has_section("definitions"):
keys = config.options("definitions")
for definition in keys:
definitions[definition] = config.get("definitions",
definition)
regex_program = []
if config.has_section("regex_programs"):
program = config.get("regex_programs", "default", fallback=None)
if program is not None:
regex_program = json.loads(program)
regex_default_program = rp.compile(regex_program)
if default_mode == "plain" or key is None:
xmpp.encrypt = False
mode = PLAIN
elif default_mode == "gold" or default_mode == "encrypt":
xmpp.encrypt = True
mode = GOLD
elif default_mode == "stealth":
xmpp.encrypt = False
mode = STEALTH
logfile = open(logfile_name, "a")
def log_msg(msgtype, msg, nick):
t = time()
lines = msg.count("\n")
line = "%sR %s %03d <%s> %s" % (msgtype, t, lines, nick, msg)
try:
logfile.write("%s\n" % line)
logfile.flush()
except Exception as e:
show("exception while writing log: %s" % e)
def log_privmsg(msg, jid):
t = time()
lines = msg.count("\n")
line = "PR %s %03d <%s> %s" % (t, lines, jid, msg)
try:
logfile.write("%s\n" % line)
logfile.flush()
except Exception as e:
show("exception while writing log: %s" % e)
def log_privmsg_send(msg, jid):
t = time()
lines = msg.count("\n")
line = "PS %s %03d <%s> %s" % (t, lines, jid, msg)
try:
logfile.write("%s\n" % line)
logfile.flush()
except Exception as e:
show("exception while writing log: %s" % e)
def log_status(info):
t = time()
lines = info.count("\n")
line = "MI %s %03d %s" % (t, lines, info)
try:
logfile.write("%s\n" % line)
logfile.flush()
except Exception as e:
show("exception while writing log: %s" % e)
def get_formatted_nick(nick):
global longest
global rpad
if rpad and len(nick) > longest:
longest = len(nick)
return nick if not rpad else nick.rjust(longest, ' ')
bits_regex = re.compile(r"^[01\s]+$")
lulu_regex = re.compile(r"^[lu\s]+$")
hex_regex = re.compile(r"^[0-9a-fA-F]+$")
morse_regex = re.compile(r"^[\s−·\.-]+$")
strip_regex = re.compile(r"[:\s-]")
is_printable = lambda x: x >= 32
printable = lambda x: ord(".") if x < 32 else x
get_bytes = lambda s: bytes([ ord(x) for x in s ])
to_utf8 = lambda s: get_bytes(s).decode("utf-8")
bits2s = lambda b: to_utf8("".join(chr(printable(int("".join(x), 2))) \
for x in zip(*[iter(b)]*8)))
hex2s = lambda b: to_utf8("".join(chr(printable(int("".join(x), 16))) \
for x in zip(*[iter(b)]*2)))
bits2p = lambda b: sum([ 1 for x in zip(*[iter(b)]*8) \
if not is_printable(int("".join(x), 2)) ])
def get_mode_name(msgtype):
if msgtype == xmpp.STEALTH:
return "stealth"
elif msgtype == xmpp.ENCRYPTED:
return "gold"
else:
return None
def decode_msg(msg, nick, msgtype=None):
msgmode = "" if msgtype is None or msgtype is xmpp.PLAIN else \
"%s: " % get_mode_name(msgtype)
if not msg_decode:
if espeak_voice is not None:
espeak.say("%s%s: %s" % (msgmode, nick, msg))
return
last = msg
while True:
stripped = strip_regex.sub("", msg)
if morse_regex.match(msg) is not None:
if morse.valid(msg):
tmp = morse.decode(msg)
msg = tmp.lower()
show("morse: %s" % msg)
stripped = strip_regex.sub("", msg)
if bits_regex.match(stripped) is not None \
and len(stripped) % 8 == 0:
try:
msg = bits2s(stripped)
show("binary: %s" % msg)
stripped = strip_regex.sub("", msg)
except:
pass # decoding error
if len(set(stripped)) == 2 and len(stripped) % 8 == 0 \
and caesar_lang is not None:
letters = list(set(stripped))
lstr = "".join(letters)
binary1 = stripped.translate(str \
.maketrans(lstr, "01"))
binary2 = stripped.translate(str \
.maketrans(lstr, "10"))
b1 = bits2p(binary1)
b2 = bits2p(binary2)
candidate1, candidate2 = [], []
try:
candidate1 = bits2s(binary1)
except UnicodeDecodeError:
pass
try:
candidate2 = bits2s(binary2)
except UnicodeDecodeError:
pass
freq = rot.default_frequencies(caesar_lang)
l1 = sum([ 1 for x in set(candidate1) \
if x in freq ])
l2 = sum([ 1 for x in set(candidate2) \
if x in freq ])
c1 = rot.cost(candidate1, freq) if l1 > 0 \
else None
c2 = rot.cost(candidate2, freq) if l2 > 0 \
else None
if b1 < b2 and c1 is not None:
c2 = None
elif b2 < b1 and c2 is not None:
c1 = None
if not (c1 is None and c2 is None):
if c1 is None:
c1 = c2 + 1
elif c2 is None:
c2 = c1 + 1
msg = candidate1 if c1 < c2 \
else candidate2
l = "%s%s" % ((letters[0], letters[1]) \
if c1 < c2 else
(letters[1], letters[0]))
show("bin(%s): %s" % (l, msg))
stripped = strip_regex.sub("", msg)
if hex_regex.match(stripped) is not None \
and len(stripped) % 2 == 0:
if caesar_lang is not None:
try:
tmp = hex2s(stripped)
freq = rot.default_frequencies(caesar_lang)
l = sum([ 1 for x in set(tmp) \
if x in freq ])
if l != 0:
msg = tmp
show("hex: %s" % msg)
except UnicodeDecodeError:
pass
else:
try:
msg = hex2s(stripped)
show("hex: %s" % msg)
except UnicodeDecodeError:
pass
if last == msg:
break
last = msg
if decode_caesar:
match = url_regex.search(msg)
if match is None:
try:
result = rot.crackx(msg, caesar_lang,
True)
if result.text != msg:
show("rot(%d): %s" % (result.n,
result.text))
msg = result.text
except:
pass
# do not speak an url
match = url_regex.search(msg)
if match is not None and match.start() == 0:
return
if espeak_voice is not None:
espeak.say("%s%s: %s" % (msgmode, nick, msg))
def muc_msg(msg, nick, jid, role, affiliation, msgtype, echo):
nick = get_formatted_nick(nick);
if enable_bell and not echo:
sys.stdout.write("\007")
color = INPUT_COLOR if echo else get_nick_color(nick)
normal_color = INPUT_COLOR if echo else "[0m"
t = localtime()
timestamp = "%s " % t if show_timestamps else ""
timestamp_nos = "%s" % t if show_timestamps else ""
if msgtype == xmpp.STEALTH:
if msg.startswith("/me "):
show_raw("\033%s%s$\033%s*** %s\033%s %s" %
(STEALTH_COLOR, timestamp_nos,
color, escape_vt(nick),
normal_color,
escape_vt(msg[4:])))
else:
show_raw("\033%s%s$\033%s<%s>\033%s %s" %
(STEALTH_COLOR, timestamp_nos,
color, escape_vt(nick),
normal_color,
escape_vt(msg)))
log_msg("Q", msg, nick)
elif msgtype == xmpp.ENCRYPTED:
if msg.startswith("/me "):
show_raw("\033%s%s#\033%s*** %s\033%s %s" %
(ENCRYPTED_COLOR, timestamp_nos,
color, escape_vt(nick),
normal_color,
escape_vt(msg[4:])))
else:
show_raw("\033%s%s#\033%s<%s>\033%s %s" %
(ENCRYPTED_COLOR, timestamp_nos,
color, escape_vt(nick),
normal_color,
escape_vt(msg)))
log_msg("E", msg, nick)
else:
if msg.startswith("/me "):
show_raw("\033%s%s\033%s*** %s\033%s %s" %
(normal_color, timestamp, color,
escape_vt(nick),
normal_color,
escape_vt(msg[4:])))
else:
show_raw("\033%s%s\033%s<%s>\033%s %s" %
(normal_color, timestamp,
color, escape_vt(nick),
normal_color, escape_vt(msg)))
log_msg("M", msg, nick)
decode_msg(msg, nick, msgtype)
def muc_mention(msg, nick, jid, role, affiliation, msgtype, echo, body):
nick = get_formatted_nick(nick);
if enable_bell and not echo:
sys.stdout.write("\007")
color = get_nick_color(nick)
msgcolor = INPUT_COLOR if echo else MENTION_COLOR
timestamp = "\033%s%s " % (MENTION_COLOR, localtime()) if \
show_timestamps else ""
timestamp_nos = "\033%s%s" % (MENTION_COLOR, localtime()) if \
show_timestamps else ""
if msgtype == xmpp.STEALTH:
show_raw("%s\033%s$\033%s<<<%s>>>\033%s " "%s\033[0m" %
(timestamp_nos, msgcolor, color,
escape_vt(nick), msgcolor,
escape_vt(msg)))
log_msg("Q", body, nick)
elif msgtype == xmpp.ENCRYPTED:
show_raw("%s\033%s#\033%s<<<%s>>>\033%s " "%s\033[0m" %
(timestamp_nos, msgcolor, color,
escape_vt(nick), msgcolor,
escape_vt(msg)))
log_msg("E", body, nick)
else:
show_raw("%s\033%s<<<%s>>>\033%s %s\033[0m" %
(timestamp, color, escape_vt(nick),
msgcolor, escape_vt(msg)))
log_msg("M", body, nick)
decode_msg(msg, nick, msgtype)
def priv_msg(msg, jid):
if enable_bell:
sys.stdout.write("\007")
timestamp = "%s " % localtime() if show_timestamps else ""
show_raw("\033%s%s<PRIV#%s> %s\033[0m" % (MENTION_COLOR,
timestamp, escape_vt(jid), escape_vt(msg)))
log_privmsg(msg, jid)
def muc_online(jid, nick, role, affiliation, localjid, info):
global longest
if history or not info:
timestamp = "%s " % localtime() if show_timestamps \
else ""
show("%s*** online: %s (%s; %s)" % (timestamp, nick,
jid, role))
if not info or join_log:
log_status("%s <%s> has joined" % (nick, jid))
if len(nick) > longest:
longest = len(nick)
def muc_offline(jid, nick):
timestamp = "%s " % localtime() if show_timestamps else ""
show("%s*** offline: %s" % (timestamp, nick))
log_status("%s has left" % nick)
def muc_joined():
log_status('You have joined as "%s"' % xmpp.nick)
show('You have joined as "%s"' % xmpp.nick)
def save_config():
if len(cfgfiles) == 0:
show("no config file")
return
cfgfile = cfgfiles[-1]
cfg = configparser.SafeConfigParser()
cfg.read(cfgfile)
str_mode = "plain" if mode == PLAIN else "encrypt" \
if mode == GOLD else "stealth"
newcfg = {
"client": {
"mode": str_mode,
"bell": str(enable_bell) },
"ui": {
"caesar": str(decode_caesar),
"caesar_lang": str(caesar_lang) }
}
for section in newcfg:
if not cfg.has_section(section):
cfg.add_section(section)
for option in newcfg[section]:
cfg.set(section, option,
newcfg[section][option])
if not cfg.has_section("macros"):
cfg.add_section("macros")
for macro in cfg.options("macros"):
cfg.remove_option("macros", macro)
for macro in macros:
cfg.set("macros", macro, macros[macro])
if len(cfg.options("macros")) == 0:
cfg.remove_section("macros")
if not cfg.has_section("definitions"):
cfg.add_section("definitions")
for definition in cfg.options("definitions"):
cfg.remove_option("definitions", definition)
for definition in definitions:
cfg.set("definitions", definition,
definitions[definition])
if len(cfg.options("definitions")) == 0:
cfg.remove_section("definitions")
if not cfg.has_section("regex_programs"):
cfg.add_section("regex_programs")
for regex in cfg.options("regex_programs"):
cfg.remove_option("regex_programs", regex)
if len(regex_program) != 0:
cfg.set("regex_programs", "default",
json.dumps(regex_program))
if len(cfg.options("regex_programs")) == 0:
cfg.remove_section("regex_programs")
try:
with open(cfgfile, "w") as f:
cfg.write(f, True)
show('wrote config to "%s"' % cfgfile)
except Exception as e:
show("exception: %s" % e)
def send(msg):
if mode == STEALTH:
xmpp.muc_send(msg, stealth=True)
else:
xmpp.muc_send(msg)
def send_mode(m, text):
if m == "p":
xmpp.muc_send(text, enc=False)
elif m == "e":
if xmpp.key is None:
show("error: no key set")
else:
try:
xmpp.muc_send(text, enc=True)
except Exception as e:
show("exception: %s" % e)
elif m == "q":
if xmpp.key is None:
print("error: no key set")
else:
try:
xmpp.muc_send(text,
stealth=True)
except Exception as e:
show("exception: %s" % e)
else:
show("invalid argument: \"%s\"" % m)
pass
@help(synopsis="help [command|topic]",
description="Shows help texts.",
args={ "command": "a command you want to know something about",
"topic": "a help topic"})
def _help(topic=None):
if topic is None:
print_help()
else:
show_help(topic)
@help(synopsis="encrypt", description="Switch to encrypted (gold) "
"mode. Everyone will see, that there was a message, but"
" only users with the key can read them",
see=["/plain", "/stealth", "/status", "modes"])
def _encrypt():
global mode
if xmpp.key is None:
show("no encryption key set")
else:
xmpp.encrypt = True
mode = GOLD
@help(synopsis="plain", description="Switch to plaintext mode. This is "
"the mode, every XMPP client supports.",
see=["/encrypt", "/stealth", "/status", "modes"])
def _plain():
global mode
xmpp.encrypt = False
mode = PLAIN