forked from torhve/Weechat-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjabber.py
1664 lines (1530 loc) · 67.8 KB
/
jabber.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 -*-
#
# Copyright (C) 2009-2011 Sebastien Helleu <[email protected]>
# Copyright (C) 2010 xt <[email protected]>
# Copyright (C) 2010 Aleksey V. Zapparov <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
# Jabber/XMPP protocol for WeeChat.
# (this script requires WeeChat 0.3.0 (or newer) and xmpppy library)
#
# For help, see /help jabber
# Happy chat, enjoy :)
#
# History:
# 2011-03-21, Isaac Raway <[email protected]>:
# version 0.8: search chat buffer before opening it
# 2011-02-13, Sebastien Helleu <[email protected]>:
# version 0.7: use new help format for command arguments
# 2010-11-23, xt
# version 0.6: change format of sent ping, to match RFC
# 2010-10-05, xt, <[email protected]>
# version 0.5: no highlight for status/presence messages
# 2010-10-01, xt, <[email protected]>
# version 0.4:
# add kick and invite
# 2010-08-03, Aleksey V. Zapparov <[email protected]>:
# version 0.3:
# add /jabber priority [priority]
# add /jabber status [message]
# add /jabber presence [online|chat|away|xa|dnd]
# 2010-08-02, Aleksey V. Zapparov <[email protected]>:
# version 0.2.1:
# fix prexence is set for current resource instead of sending
# special presences for all buddies
# 2010-08-02, Aleksey V. Zapparov <[email protected]>:
# version 0.2:
# add priority and away_priority of resource
# 2010-08-02, Sebastien Helleu <[email protected]>:
# version 0.1: first official version
# 2010-08-01, ixti <[email protected]>:
# fix bug with non-ascii resources
# 2010-06-09, iiijjjiii <[email protected]>:
# add connect server and port options (required for google talk)
# add private option permitting messages to be displayed in separate
# chat buffers or in a single server buffer
# add jid aliases
# add keepalive ping
# 2010-03-17, xt <[email protected]>:
# add autoreconnect option, autoreconnects on protocol error
# 2010-03-17, xt <[email protected]>:
# add autoconnect option, add new command /jmsg with -server option
# 2009-02-22, Sebastien Helleu <[email protected]>:
# first version (unofficial)
#
SCRIPT_NAME = "jabber"
SCRIPT_AUTHOR = "Sebastien Helleu <[email protected]>"
SCRIPT_VERSION = "0.8"
SCRIPT_LICENSE = "GPL3"
SCRIPT_DESC = "Jabber/XMPP protocol for WeeChat"
SCRIPT_COMMAND = SCRIPT_NAME
import re
import warnings
import_ok = True
try:
import weechat
except:
print "This script must be run under WeeChat."
print "Get WeeChat now at: http://www.weechat.org/"
import_ok = False
# On import, xmpp may produce warnings about using hashlib instead of
# deprecated sha and md5. Since the code producing those warnings is
# outside this script, catch them and ignore.
original_filters = warnings.filters[:]
warnings.filterwarnings("ignore",category=DeprecationWarning)
try:
import xmpp
except:
print "Package python-xmpp (xmpppy) must be installed to use Jabber protocol."
print "Get xmpppy with your package manager, or at this URL: http://xmpppy.sourceforge.net/"
import_ok = False
finally:
warnings.filters = original_filters
# ==============================[ global vars ]===============================
jabber_servers = []
jabber_server_options = {
"jid" : { "type" : "string",
"desc" : "jabber id ([email protected])",
"min" : 0,
"max" : 0,
"string_values": "",
"default" : "",
"value" : "",
"check_cb" : "",
"change_cb" : "",
"delete_cb" : "",
},
"priority" : { "type" : "integer",
"desc" : "Default resource priority",
"min" : 0,
"max" : 65535,
"string_values": "",
"default" : "8",
"value" : "8",
"check_cb" : "",
"change_cb" : "",
"delete_cb" : "",
},
"away_priority": { "type" : "integer",
"desc" : "Resource priority on away",
"min" : 0,
"max" : 65535,
"string_values": "",
"default" : "0",
"value" : "0",
"check_cb" : "",
"change_cb" : "",
"delete_cb" : "",
},
"password" : { "type" : "string",
"desc" : "password for jabber id on server",
"min" : 0,
"max" : 0,
"string_values": "",
"default" : "",
"value" : "",
"check_cb" : "",
"change_cb" : "",
"delete_cb" : "",
},
"server" : { "type" : "string",
"desc" : "connect server host or ip, eg. talk.google.com",
"min" : 0,
"max" : 0,
"string_values": "",
"default" : "",
"value" : "",
"check_cb" : "",
"change_cb" : "",
"delete_cb" : "",
},
"port" : { "type" : "integer",
"desc" : "connect server port, eg. 5223",
"min" : 0,
"max" : 65535,
"string_values": "",
"default" : "5222",
"value" : "5222",
"check_cb" : "",
"change_cb" : "",
"delete_cb" : "",
},
"autoconnect" : { "type" : "boolean",
"desc" : "automatically connect to server when script is starting",
"min" : 0,
"max" : 0,
"string_values": "",
"default" : "off",
"value" : "off",
"check_cb" : "",
"change_cb" : "",
"delete_cb" : "",
},
"autoreconnect": { "type" : "boolean",
"desc" : "automatically reconnect to server when disconnected",
"min" : 0,
"max" : 0,
"string_values": "",
"default" : "off",
"value" : "off",
"check_cb" : "",
"change_cb" : "",
"delete_cb" : "",
},
"private" : { "type" : "boolean",
"desc" : "display messages in separate chat buffers instead of a single server buffer",
"min" : 0,
"max" : 0,
"string_values": "",
"default" : "on",
"value" : "on",
"check_cb" : "",
"change_cb" : "",
"delete_cb" : "",
},
"ping_interval": { "type" : "integer",
"desc" : "Number of seconds between server pings. 0 = disable",
"min" : 0,
"max" : 9999999,
"string_values": "",
"default" : "0",
"value" : "0",
"check_cb" : "ping_interval_check_cb",
"change_cb" : "",
"delete_cb" : "",
},
"ping_timeout" : { "type" : "integer",
"desc" : "Number of seconds to allow ping to respond before timing out",
"min" : 0,
"max" : 9999999,
"string_values": "",
"default" : "10",
"value" : "10",
"check_cb" : "ping_timeout_check_cb",
"change_cb" : "",
"delete_cb" : "",
},
}
jabber_config_file = None
jabber_config_section = {}
jabber_config_option = {}
jabber_jid_aliases = {} # { 'alias1': 'jid1', 'alias2': 'jid2', ... }
# =================================[ config ]=================================
def jabber_config_init():
""" Initialize config file: create sections and options in memory. """
global jabber_config_file, jabber_config_section
jabber_config_file = weechat.config_new("jabber", "jabber_config_reload_cb", "")
if not jabber_config_file:
return
# look
jabber_config_section["look"] = weechat.config_new_section(
jabber_config_file, "look", 0, 0, "", "", "", "", "", "", "", "", "", "")
if not jabber_config_section["look"]:
weechat.config_free(jabber_config_file)
return
jabber_config_option["debug"] = weechat.config_new_option(
jabber_config_file, jabber_config_section["look"],
"debug", "boolean", "display debug messages", "", 0, 0,
"off", "off", 0, "", "", "", "", "", "")
# color
jabber_config_section["color"] = weechat.config_new_section(
jabber_config_file, "color", 0, 0, "", "", "", "", "", "", "", "", "", "")
if not jabber_config_section["color"]:
weechat.config_free(jabber_config_file)
return
jabber_config_option["message_join"] = weechat.config_new_option(
jabber_config_file, jabber_config_section["color"],
"message_join", "color", "color for text in join messages", "", 0, 0,
"green", "green", 0, "", "", "", "", "", "")
jabber_config_option["message_quit"] = weechat.config_new_option(
jabber_config_file, jabber_config_section["color"],
"message_quit", "color", "color for text in quit messages", "", 0, 0,
"red", "red", 0, "", "", "", "", "", "")
# server
jabber_config_section["server"] = weechat.config_new_section(
jabber_config_file, "server", 0, 0,
"jabber_config_server_read_cb", "", "jabber_config_server_write_cb", "",
"", "", "", "", "", "")
if not jabber_config_section["server"]:
weechat.config_free(jabber_config_file)
return
jabber_config_section["jid_aliases"] = weechat.config_new_section(
jabber_config_file, "jid_aliases", 0, 0,
"jabber_config_jid_aliases_read_cb", "",
"jabber_config_jid_aliases_write_cb", "",
"", "", "", "", "", "")
if not jabber_config_section["jid_aliases"]:
weechat.config_free(jabber_config_file)
return
def jabber_config_reload_cb(data, config_file):
""" Reload config file. """
return weechat.WEECHAT_CONFIG_READ_OK
def jabber_config_server_read_cb(data, config_file, section, option_name, value):
""" Read server option in config file. """
global jabber_servers
rc = weechat.WEECHAT_CONFIG_OPTION_SET_ERROR
items = option_name.split(".", 1)
if len(items) == 2:
server = jabber_search_server_by_name(items[0])
if not server:
server = Server(items[0])
jabber_servers.append(server)
if server:
rc = weechat.config_option_set(server.options[items[1]], value, 1)
return rc
def jabber_config_server_write_cb(data, config_file, section_name):
""" Write server section in config file. """
global jabber_servers
weechat.config_write_line(config_file, section_name, "")
for server in jabber_servers:
for name, option in sorted(server.options.iteritems()):
weechat.config_write_option(config_file, option)
return weechat.WEECHAT_RC_OK
def jabber_config_jid_aliases_read_cb(data, config_file, section, option_name, value):
""" Read jid_aliases option in config file. """
global jabber_jid_aliases
jabber_jid_aliases[option_name] = value
option = weechat.config_new_option(
config_file, section,
option_name, "string", "jid alias", "", 0, 0,
"", value, 0, "", "", "", "", "", "")
if not option:
return weechat.WEECHAT_CONFIG_OPTION_SET_ERROR
return weechat.WEECHAT_CONFIG_OPTION_SET_OK_CHANGED
def jabber_config_jid_aliases_write_cb(data, config_file, section_name):
""" Write jid_aliases section in config file. """
global jabber_jid_aliases
weechat.config_write_line(config_file, section_name, "")
for alias, jid in sorted(jabber_jid_aliases.iteritems()):
weechat.config_write_line(config_file, alias, jid)
return weechat.WEECHAT_RC_OK
def jabber_config_read():
""" Read jabber config file (jabber.conf). """
global jabber_config_file
return weechat.config_read(jabber_config_file)
def jabber_config_write():
""" Write jabber config file (jabber.conf). """
global jabber_config_file
return weechat.config_write(jabber_config_file)
def jabber_debug_enabled():
""" Return True if debug is enabled. """
global jabber_config_options
if weechat.config_boolean(jabber_config_option["debug"]):
return True
return False
def jabber_config_color(color):
""" Return color code for a jabber color option. """
global jabber_config_option
if color in jabber_config_option:
return weechat.color(weechat.config_color(jabber_config_option[color]))
return ""
def ping_timeout_check_cb(server_name, option, value):
global jabber_config_file, jabber_config_section
ping_interval_option = weechat.config_search_option(
jabber_config_file,
jabber_config_section["server"],
"%s.ping_interval" % (server_name)
)
ping_interval = weechat.config_integer(ping_interval_option)
if int(ping_interval) and int(value) >= int(ping_interval):
weechat.prnt("", "\njabber: unable to update 'ping_timeout' for server %s" % (server_name))
weechat.prnt("", "jabber: to prevent multiple concurrent pings, ping_interval must be greater than ping_timeout")
return weechat.WEECHAT_CONFIG_OPTION_SET_ERROR
return weechat.WEECHAT_CONFIG_OPTION_SET_OK_CHANGED
def ping_interval_check_cb(server_name, option, value):
global jabber_config_file, jabber_config_section
ping_timeout_option = weechat.config_search_option(
jabber_config_file,
jabber_config_section["server"],
"%s.ping_timeout" % (server_name)
)
ping_timeout = weechat.config_integer(ping_timeout_option)
if int(value) and int(ping_timeout) >= int(value):
weechat.prnt("", "\njabber: unable to update 'ping_interval' for server %s" % (server_name))
weechat.prnt("", "jabber: to prevent multiple concurrent pings, ping_interval must be greater than ping_timeout")
return weechat.WEECHAT_CONFIG_OPTION_SET_ERROR
return weechat.WEECHAT_CONFIG_OPTION_SET_OK_CHANGED
# ================================[ servers ]=================================
class Server:
""" Class to manage a server: buffer, connection, send/recv data. """
def __init__(self, name, **kwargs):
""" Init server """
global jabber_config_file, jabber_config_section, jabber_server_options
self.name = name
# create options (user can set them with /set)
self.options = {}
# if the value is provided, use it, otherwise use the default
values = {}
for option_name, props in jabber_server_options.iteritems():
values[option_name] = props["default"]
values['name'] = name
values.update(**kwargs)
for option_name, props in jabber_server_options.iteritems():
self.options[option_name] = weechat.config_new_option(
jabber_config_file, jabber_config_section["server"],
self.name + "." + option_name, props["type"], props["desc"],
props["string_values"], props["min"], props["max"],
props["default"], values[option_name], 0,
props["check_cb"], self.name, props["change_cb"], "",
props["delete_cb"], "")
# internal data
self.jid = None
self.client = None
self.sock = None
self.hook_fd = None
self.buffer = ""
self.chats = []
self.buddies = []
self.buddy = None
self.ping_timer = None # weechat.hook_timer for sending pings
self.ping_timeout_timer = None # weechat.hook_timer for monitoring ping timeout
self.ping_up = False # Connection status as per pings.
self.presence = xmpp.protocol.Presence()
def option_string(self, option_name):
""" Return a server option, as string. """
return weechat.config_string(self.options[option_name])
def option_boolean(self, option_name):
""" Return a server option, as boolean. """
return weechat.config_boolean(self.options[option_name])
def option_integer(self, option_name):
""" Return a server option, as string. """
return weechat.config_integer(self.options[option_name])
def connect(self):
""" Connect to Jabber server. """
if not self.buffer:
bufname = "%s.server.%s" % (SCRIPT_NAME, self.name)
self.buffer = weechat.buffer_search("python", bufname)
if not self.buffer:
self.buffer = weechat.buffer_new(bufname,
"jabber_buffer_input_cb", "",
"jabber_buffer_close_cb", "")
if self.buffer:
weechat.buffer_set(self.buffer, "short_name", self.name)
weechat.buffer_set(self.buffer, "localvar_set_type", "server")
weechat.buffer_set(self.buffer, "localvar_set_server", self.name)
weechat.buffer_set(self.buffer, "nicklist", "1")
weechat.buffer_set(self.buffer, "nicklist_display_groups", "1")
weechat.buffer_set(self.buffer, "display", "auto")
self.disconnect()
self.buddy = Buddy(jid=self.option_string("jid"), server=self)
server = self.option_string("server")
port = self.option_integer("port")
self.client = xmpp.Client(server=self.buddy.domain, debug=[])
conn = None
server_tuple = None
if server:
if port:
server_tuple = (server, port)
else:
server_tuple = (server)
# self.client.connect() may produce a "socket.ssl() is deprecated"
# warning. Since the code producing the warning is outside this script,
# catch it and ignore.
original_filters = warnings.filters[:]
warnings.filterwarnings("ignore",category=DeprecationWarning)
try:
conn = self.client.connect(server=server_tuple)
finally:
warnings.filters = original_filters
if conn:
weechat.prnt(self.buffer, "jabber: connection ok with %s" % conn)
res = self.buddy.resource
if not res:
res = "WeeChat"
auth = self.client.auth(self.buddy.username,
self.option_string("password"),
res)
if auth:
weechat.prnt(self.buffer, "jabber: authentication ok (using %s)" % auth)
self.client.RegisterHandler("presence", self.presence_handler)
self.client.RegisterHandler("iq", self.iq_handler)
self.client.RegisterHandler("message", self.message_handler)
self.client.sendInitPresence(requestRoster=1)
self.sock = self.client.Connection._sock.fileno()
self.hook_fd = weechat.hook_fd(self.sock, 1, 0, 0, "jabber_fd_cb", "")
weechat.buffer_set(self.buffer, "highlight_words", self.buddy.username)
weechat.buffer_set(self.buffer, "localvar_set_nick", self.buddy.username);
hook_away = weechat.hook_command_run("/away -all*", "jabber_away_command_run_cb", "")
# setting initial presence
priority = weechat.config_integer(self.options['priority'])
self.set_presence(show="",priority=priority)
self.ping_up = True
else:
weechat.prnt(self.buffer, "%sjabber: could not authenticate"
% weechat.prefix("error"))
self.ping_up = False
self.client = None
else:
weechat.prnt(self.buffer, "%sjabber: could not connect"
% weechat.prefix("error"))
self.ping_up = False
self.client = None
return self.is_connected()
def is_connected(self):
"""Return connect status"""
if not self.client or not self.client.isConnected():
return False
else:
return True
def add_chat(self, buddy):
"""Create a chat buffer for a buddy"""
chat = Chat(self, buddy, switch_to_buffer=False)
self.chats.append(chat)
return chat
def add_buddy(self, jid):
""" Add a new buddy """
self.client.Roster.Authorize(jid)
self.client.Roster.Subscribe(jid)
def del_buddy(self, jid):
""" Remove a buddy and/or deny authorization request """
self.client.Roster.Unauthorize(jid)
self.client.Roster.Unsubscribe(jid)
def print_debug_server(self, message):
""" Print debug message on server buffer. """
if jabber_debug_enabled():
weechat.prnt(self.buffer, "%sjabber: %s" % (weechat.prefix("network"), message))
def print_debug_handler(self, handler_name, node):
""" Print debug message for a handler on server buffer. """
self.print_debug_server("%s_handler, xml message:\n%s"
% (handler_name,
node.__str__(fancy=True).encode("utf-8")))
def print_error(self, message):
""" Print error message on server buffer. """
if jabber_debug_enabled():
weechat.prnt(self.buffer, "%sjabber: %s" % (weechat.prefix("error"), message))
def presence_handler(self, conn, node):
self.print_debug_handler("presence", node)
buddy = self.search_buddy_list(node.getFrom().getStripped().encode("utf-8"), by='jid')
if not buddy:
buddy = self.add_buddy(jid=node.getFrom())
action='update'
node_type = node.getType()
if node_type in ["error", "unavailable"]:
action='remove'
if action == 'update':
away = node.getShow() in ["away", "xa"]
status = ''
if node.getStatus():
status = node.getStatus().encode("utf-8")
buddy.set_status(status=status, away=away)
self.update_nicklist(buddy=buddy, action=action)
return
def iq_handler(self, conn, node):
""" Receive iq message. """
self.print_debug_handler("iq", node)
#weechat.prnt(self.buffer, "jabber: iq handler")
if node.getFrom() == self.buddy.domain:
# type='result' => pong from server
# type='error' => error message from server
# The ping_up is set True on an error message to handle cases where
# the ping feature is not implemented on a server. It's a bit of a
# hack, but if we can receive an error from the server, we assume
# the connection to the server is up.
if node.getType() in ['result', 'error']:
self.delete_ping_timeout_timer() # Disable the timeout feature
self.ping_up = True
if not self.client.isConnected() and weechat.config_boolean(self.options['autoreconnect']):
self.connect()
def message_handler(self, conn, node):
""" Receive message. """
self.print_debug_handler("message", node)
node_type = node.getType()
if node_type not in ["message", "chat", None]:
self.print_error("unknown message type: '%s'" % node_type)
return
jid = node.getFrom()
body = node.getBody()
if not jid or not body:
return
buddy = self.search_buddy_list(str(jid).encode("utf-8"), by='jid')
#buddy = self.search_buddy_list(node.getFrom().getStripped().encode("utf-8"), by='jid')
if not buddy:
buddy = self.add_buddy(jid=jid)
# If a chat buffer exists for the buddy, receive the message with that
# buffer even if private is off. The buffer may have been created with
# /jchat.
recv_object = self
if not buddy.chat and weechat.config_boolean(self.options['private']):
self.add_chat(buddy)
if buddy.chat:
recv_object = buddy.chat
recv_object.recv_message(buddy, body.encode("utf-8"))
def recv(self):
""" Receive something from Jabber server. """
if not self.client:
return
try:
self.client.Process(1)
except xmpp.protocol.StreamError, e:
weechat.prnt('', '%s: Error from server: %s' %(SCRIPT_NAME, e))
self.disconnect()
if weechat.config_boolean(self.options['autoreconnect']):
autoreconnect_delay = 30
weechat.command('', '/wait %s /%s connect %s' %(\
autoreconnect_delay, SCRIPT_COMMAND, self.name))
def recv_message(self, buddy, message):
""" Receive a message from buddy. """
weechat.prnt_date_tags(self.buffer, 0, "notify_private",
"%s%s\t%s" % (weechat.color("chat_nick_other"),
buddy.alias,
message))
def print_status(self, nickname, status):
''' Print a status in server window and in chat '''
weechat.prnt_date_tags(self.buffer, 0, 'no_highlight', "%s%s has status %s" % (\
weechat.prefix("action"),
nickname,
status))
for chat in self.chats:
if nickname in chat.buddy.alias:
chat.print_status(status)
break
def send_message(self, buddy, message):
""" Send a message to buddy.
The buddy argument can be either a jid string,
eg [email protected]/resource or a Buddy object instance.
"""
recipient = buddy
if isinstance(buddy, Buddy):
recipient = buddy.jid
if not self.ping_up:
weechat.prnt(self.buffer, "%sjabber: unable to send message, connection is down"
% weechat.prefix("error"))
return
if self.client:
msg = xmpp.protocol.Message(to=recipient, body=message, typ='chat')
self.client.send(msg)
def send_message_from_input(self, input=''):
""" Send a message from input text on server buffer. """
# Input must be of format "name: message" where name is a jid, bare_jid
# or alias. The colon can be replaced with a comma as well.
# Split input into name and message.
if not re.compile(r'.+[:,].+').match(input):
weechat.prnt(self.buffer, "%sjabber: %s" % (weechat.prefix("network"),
"Invalid send format. Use jid: message"
))
return
name, message = re.split('[:,]', input, maxsplit=1)
buddy = self.search_buddy_list(name, by='alias')
if not buddy:
weechat.prnt(self.buffer,
"%sjabber: Invalid jid: %s" % (weechat.prefix("network"),
name))
return
# Send activity indicates user is no longer away, set it so
if self.buddy and self.buddy.away:
self.set_away('')
self.send_message(buddy=buddy, message=message)
try:
sender = self.buddy.alias
except:
sender = self.jid
weechat.prnt(self.buffer, "%s%s\t%s" % (weechat.color("chat_nick_self"),
sender,
message.strip()))
def set_away(self, message):
""" Set/unset away on server.
If a message is provided, status is set to 'away'.
If no message, then status is set to 'online'.
"""
if message:
show = "xa"
status = message
priority = weechat.config_integer(self.options['away_priority'])
self.buddy.set_status(away=True, status=message)
else:
show = ""
status = None
priority = weechat.config_integer(self.options['priority'])
self.buddy.set_status(away=False)
self.set_presence(show, status, priority)
def set_presence(self, show=None, status=None, priority=None):
if not show == None: self.presence.setShow(show)
if not status == None: self.presence.setStatus(status)
if not priority == None: self.presence.setPriority(priority)
self.client.send(self.presence)
def add_buddy(self, jid=None):
buddy = Buddy(jid=jid, server=self)
buddy.resource = buddy.resource.encode("utf-8")
self.buddies.append(buddy)
return buddy
def display_buddies(self):
""" Display buddies. """
weechat.prnt(self.buffer, "")
weechat.prnt(self.buffer, "Buddies:")
len_max = { 'alias': 5, 'jid': 5 }
lines = []
for buddy in sorted(self.buddies, key=lambda x: str(x.jid)):
alias = ''
if buddy.alias != buddy.bare_jid:
alias = buddy.alias
lines.append( {
'jid': str(buddy.jid),
'alias': alias,
'status': buddy.away_string(),
})
if len(alias) > len_max['alias']:
len_max['alias'] = len(alias)
if len(str(buddy.jid)) > len_max['jid']:
len_max['jid'] = len(str(buddy.jid))
prnt_format = " %s%-" + str(len_max['jid']) + "s %-" + str(len_max['alias']) + "s %s"
weechat.prnt(self.buffer, prnt_format % ('', 'JID', 'Alias', 'Status'))
for line in lines:
weechat.prnt(self.buffer, prnt_format % (weechat.color("chat_nick"),
line['jid'],
line['alias'],
line['status'],
))
def stringify_jid(self, jid, wresource=1):
""" Serialise JID into string.
Args:
jid: xmpp.protocol.JID, JID instance to serialize
Notes:
Method is based on original JID.__str__ but with hack to allow
non-ascii in resource names.
"""
if jid.node:
jid_str = jid.node + '@' + jid.domain
else:
jid_str = jid.domain
if wresource and jid.resource:
# concatenate jid with resource delimiter first and encode them
# into utf-8, else it will raise UnicodeException becaouse of
# slash character :((
return (jid_str + '/').encode("utf-8") + jid.resource.encode("utf-8")
return jid_str.encode("utf-8")
def search_buddy_list(self, name, by='jid'):
""" Search for a buddy by name.
Args:
name: string, the buddy name to search, eg the jid or alias
by: string, either 'alias' or 'jid', determines which Buddy
property to match on, default 'jid'
Notes:
If the 'by' parameter is set to 'jid', the search matches on all
Buddy object jid properties, followed by all bare_jid properties.
Once a match is found it is returned.
If the 'by' parameter is set to 'alias', the search matches on all
Buddy object alias properties.
Generally, set the 'by' parameter to 'jid' when the jid is provided
from a server, for example from a received message. Set 'by' to
'alias' when the jid is provided by the user.
"""
if by == 'jid':
for buddy in self.buddies:
if self.stringify_jid(buddy.jid) == name:
return buddy
for buddy in self.buddies:
if buddy.bare_jid == name:
return buddy
else:
for buddy in self.buddies:
if buddy.alias == name:
return buddy
return None
def update_nicklist(self, buddy=None, action=None):
"""Update buddy in nicklist
Args:
buddy: Buddy object instance
action: string, one of 'update' or 'remove'
"""
if not buddy:
return
if not action in ['remove', 'update']:
return
ptr_nick_gui = weechat.nicklist_search_nick(self.buffer, "", buddy.alias)
weechat.nicklist_remove_nick(self.buffer, ptr_nick_gui)
msg = ''
prefix = ''
color = ''
away = ''
if action == 'update':
nick_color = "bar_fg"
if buddy.away:
nick_color = "weechat.color.nicklist_away"
weechat.nicklist_add_nick(self.buffer, "", buddy.alias,
nick_color, "", "", 1)
if not ptr_nick_gui:
msg = 'joined'
prefix = 'join'
color = 'message_join'
away = buddy.away_string()
if action == 'remove':
msg = 'quit'
prefix = 'quit'
color = 'message_quit'
if msg:
weechat.prnt(self.buffer, "%s%s%s%s has %s %s"
% (weechat.prefix(prefix),
weechat.color("chat_nick"),
buddy.alias,
jabber_config_color(color),
msg,
away))
return
def add_ping_timer(self):
if self.ping_timer:
self.delete_ping_timer()
if not self.option_integer('ping_interval'):
return
self.ping_timer = weechat.hook_timer( self.option_integer('ping_interval') * 1000,
0, 0, "jabber_ping_timer", self.name)
return
def delete_ping_timer(self):
if self.ping_timer:
weechat.unhook(self.ping_timer)
self.ping_time = None
return
def add_ping_timeout_timer(self):
if self.ping_timeout_timer:
self.delete_ping_timeout_timer()
if not self.option_integer('ping_timeout'):
return
self.ping_timeout_timer = weechat.hook_timer(
self.option_integer('ping_timeout') * 1000, 0, 1,
"jabber_ping_timeout_timer", self.name)
return
def delete_ping_timeout_timer(self):
if self.ping_timeout_timer:
weechat.unhook(self.ping_timeout_timer)
self.ping_timeout_timer = None
return
def ping(self):
if not self.is_connected():
if not self.connect():
return
iq = xmpp.protocol.Iq(to=self.buddy.domain, typ='get')
iq.addChild( name= "ping", namespace = "urn:xmpp:ping" )
id = self.client.send(iq)
self.print_debug_handler("ping", iq)
self.add_ping_timeout_timer()
return
def ping_time_out(self):
self.delete_ping_timeout_timer()
self.ping_up = False
# A ping timeout indicates a server connection problem. Disconnect
# completely.
try:
self.client.disconnected()
except IOError:
# An IOError is raised by the default DisconnectHandler
pass
self.disconnect()
return
def disconnect(self):
""" Disconnect from Jabber server. """
if self.hook_fd != None:
weechat.unhook(self.hook_fd)
self.hook_fd = None
if self.client != None:
#if self.client.isConnected():
# self.client.disconnect()
self.client = None
self.jid = None
self.sock = None
self.buddy = None
weechat.nicklist_remove_all(self.buffer)
def close_buffer(self):
""" Close server buffer. """
if self.buffer != "":
weechat.buffer_close(self.buffer)
self.buffer = ""
def delete(self):
""" Delete server. """
for chat in self.chats:
chat.delete()
self.delete_ping_timer()
self.delete_ping_timeout_timer()
self.disconnect()
self.close_buffer()
for option in self.options.keys():
weechat.config_option_free(option)
def jabber_search_server_by_name(name):
""" Search a server by name. """
global jabber_servers
for server in jabber_servers:
if server.name == name:
return server
return None
def jabber_search_context(buffer):
""" Search a server / chat for a buffer. """
global jabber_servers
context = { "server": None, "chat": None }
for server in jabber_servers:
if server.buffer == buffer:
context["server"] = server
return context
for chat in server.chats:
if chat.buffer == buffer:
context["server"] = server
context["chat"] = chat
return context
return context
def jabber_search_context_by_name(server_name):
''' Search for buffer given name of server '''
bufname = "%s.server.%s" % (SCRIPT_NAME, server_name)
return jabber_search_context(weechat.buffer_search("python", bufname))
# =================================[ chats ]==================================
class Chat:
""" Class to manage private chat with buddy or MUC. """
def __init__(self, server, buddy, switch_to_buffer):
""" Init chat """
self.server = server
self.buddy = buddy
buddy.chat = self
bufname = "%s.%s.%s" % (SCRIPT_NAME, server.name, self.buddy.alias)
self.buffer = weechat.buffer_search("python", bufname)
if not self.buffer:
self.buffer = weechat.buffer_new(bufname,
"jabber_buffer_input_cb", "",
"jabber_buffer_close_cb", "")
self.buffer_title = self.buddy.alias
if self.buffer:
weechat.buffer_set(self.buffer, "title", self.buffer_title)
weechat.buffer_set(self.buffer, "short_name", self.buddy.alias)
weechat.buffer_set(self.buffer, "localvar_set_type", "private")
weechat.buffer_set(self.buffer, "localvar_set_server", server.name)
weechat.buffer_set(self.buffer, "localvar_set_channel", self.buddy.alias)
weechat.hook_signal_send("logger_backlog",
weechat.WEECHAT_HOOK_SIGNAL_POINTER, self.buffer)
if switch_to_buffer:
weechat.buffer_set(self.buffer, "display", "auto")
def recv_message(self, buddy, message):
""" Receive a message from buddy. """
if buddy.alias != self.buffer_title:
self.buffer_title = buddy.alias
weechat.buffer_set(self.buffer, "title", "%s" % self.buffer_title)
weechat.prnt_date_tags(self.buffer, 0, "notify_private",
"%s%s\t%s" % (weechat.color("chat_nick_other"),
buddy.alias,
message))
def send_message(self, message):
""" Send message to buddy. """
if not self.server.ping_up:
weechat.prnt(self.buffer, "%sjabber: unable to send message, connection is down"
% weechat.prefix("error"))