-
Notifications
You must be signed in to change notification settings - Fork 0
/
MySTConnection.py
executable file
·234 lines (185 loc) · 7.01 KB
/
MySTConnection.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
This file is part of MyServerTalks.
MyServerTalks 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 2 of the License, or
(at your option) any later version.
MyServerTalks 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 MyServerTalks; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
'''
from idlelib.IOBinding import encoding
import xmpp
import os
import sys
import locale
from MySTParser import *
from MySTContactManager import *
from MySTFormatReply import *
from MySTLog import *
from MySTModuleAutoload import *
class MySTConnection:
def __init__(self, module_manager):
self.user = ''
self.password = ''
self.server = ''
self.parser = MySTParser()
self.module_manager = module_manager
self.roster = None
# Connect to jabber
def connect(self, user, password):
# set the user and pass for atributes
self.user = user
self.password = password
self.jid = xmpp.JID(self.user)
self.user, self.server, self.password = self.jid.getNode(), self.jid.getDomain(), self.password
# Enable all debug flags
flags = ['nodebuilder', 'dispatcher', 'gen_auth', 'SASL_auth', 'bind', 'socket', 'CONNECTproxy', 'TLS', 'roster', 'browser', 'ibb']
self.jabber = xmpp.Client(self.server, debug=[]) # to enable debug replace debug=[] with debug=flags
self.config = MySTConfig()
# try to get information about different server to connect
host = self.config.get('config', 'server', 'host')
port = self.config.get('config', 'server', 'port')
# info about server (tuple)
server = ()
if (host != '' and port != ''): server = (host, int(port))
# try to get information proxy
proxy_host = self.config.get('config', 'proxy', 'host')
proxy_port = self.config.get('config', 'proxy', 'port')
proxy_user = self.config.get('config', 'proxy', 'user')
proxy_pass = self.config.get('config', 'proxy', 'pass')
# info about proxy (dict)
proxy = {}
if (proxy_host != ''): proxy['host'] = proxy_host
if (proxy_port != ''): proxy['port'] = int(proxy_port)
if (proxy_user != ''): proxy['user'] = proxy_user
if (proxy_pass != ''): proxy['password'] = proxy_pass
# try connect
if (len(server) > 0 or len(proxy) > 0):
# use a different server or a proxy to connect
self.conn = self.jabber.connect(server, proxy)
else:
self.conn = self.jabber.connect()
# Check the connection
if not self.conn:
print 'Unable to connect to server %s' % self.server
sys.exit(1)
# Check TLS connection
if (self.conn != 'tls'):
print 'Warning: Unable to estabilish secure connection, TLS failed.'
self.auth = self.jabber.auth(self.user, self.password, 'myservertalks')
# Check if user is authenticated
if not self.auth:
print 'Unable to authorize on %s - check login/password.' % self.server
sys.exit(1)
# Check if SASL it's possible
if (self.auth != 'sasl'):
print 'Warning: Unable to perform SASL auth os %s. Old authentication method used.' % self.server
self.jabber.RegisterHandler('message', self.messageHandler)
self.jabber.RegisterHandler('presence', self.presenceHandler)
self.jabber.sendInitPresence()
self.roster = self.jabber.getRoster()
self.module_manager.getUserHandler().setContactHandler(MySTContactManager(self.roster))
self.user_handler = self.module_manager.getUserHandler()
# Autoload modules
MySTModuleAutoload(self.config, self.jabber, self.user_handler)
# Disconnect from jabber
def disconnect(self):
self.jabber.disconnect()
def presenceHandler(self, conn, presence):
source = presence.getFrom()
try:
contact, resource = source.__str__().split('/')
except Exception:
contact, resource = source.__str__(), ''
# When get user status "unavailable" the system cleans user environment
if (presence.getType() == 'unavailable'):
self.module_manager.getUserHandler().cleanUserEnvironment(contact.lower())
return
if presence.getErrorCode():
MySTLog.log("Error in presence with exit code: "+presence.getErrorCode())
return
show = ''
status = ''
escope = self.module_manager.getUserHandler().getUserEscope(contact).lower()
if (escope == 'user'):
custom_message = self.config.get('config', 'status', 'dnd')
show = 'dnd'
if (custom_message != None and custom_message != ''):
status = custom_message.strip()
else:
status = 'Do not disturb'
elif (escope == 'super'):
custom_message = self.config.get('config', 'status', 'avail')
show = 'avail'
if (custom_message != None and custom_message != ''):
status = custom_message.strip()
else:
status = 'Available'
else:
return
new_presence = xmpp.Presence(to=source, show=show, priority=5, status=status)
self.jabber.send(new_presence)
# Send a message
def messageSend(self, to, message):
# try to get the default local language and encoding
try:
language, encoding = locale.getdefaultlocale()
except:
language, encoding = ['en', 'utf-8']
# decode the message
message = message.decode(encoding)
# send the message
self.jabber.send(xmpp.Message(to, message))
# Message handler for received messages
def messageHandler(self, conn, message):
print message
text = message.getBody()
instruct = MySTParser.parse(text)
print 'message: ', text
print 'instruct: ', instruct
if (instruct == None): return False
# Get the contact sending the message
from_contact = message.getFrom().__str__()
if (from_contact.find('/') >= 0):
contact, resource = message.getFrom().__str__().split('/')
else:
contact, resource = from_contact, ''
print 'contact: ', contact, 'resource: ', resource
# Set contact
instruct.setContact(contact.lower())
# User escope
escope = self.module_manager.getUserHandler().getUserEscope(contact.lower())
escope = escope.lower()
# Set the escope
instruct.setEscope(escope)
# Reply to contact
# VERY IMPORTANT
reply = self.module_manager.execute(instruct)
# Format to send the reply
output_format = self.module_manager.getUserHandler().getUserEnvironment('display')
# Get the output format
output = MySTFormatReply.getOutput(output_format, reply)
if (output.strip() != ''):
presence = xmpp.Presence()
presence.setFrom(message.getFrom())
self.presenceHandler(conn, presence)
# Send the reply
self.messageSend(message.getFrom(), output)
# Loop for process and connection status check
def loop(self):
while True:
try:
# Check if is connected, if not try reconnect
if not (self.jabber.isConnected()):
print "Disconnected... Trying to reconnect now...\n"
self.jabber.reconnectAndReauth()
self.jabber.Process(1)
except KeyboardInterrupt:
break