-
Notifications
You must be signed in to change notification settings - Fork 13
/
sip-settings
executable file
·380 lines (336 loc) · 14.4 KB
/
sip-settings
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
#!/usr/bin/env python2
import fcntl
import re
import struct
import sys
import termios
from collections import deque
from optparse import OptionParser
from sipsimple.account import Account, BonjourAccount, AccountManager
from sipsimple.application import SIPApplication
from sipsimple.configuration import ConfigurationError, ConfigurationManager, DefaultValue, Setting, SettingsGroupMeta
from sipsimple.configuration.datatypes import List, STUNServerAddress
from sipsimple.configuration.settings import SIPSimpleSettings
from sipsimple.storage import FileStorage
from sipsimple.threading import ThreadManager
from sipclient.configuration import config_directory
from sipclient.configuration.account import AccountExtension
from sipclient.configuration.settings import SIPSimpleSettingsExtension
def format_child(obj, attrname, maxchars):
linebuf = attrname
if isinstance(getattr(type(obj), attrname, None), Setting):
attr = getattr(obj, attrname)
if isinstance(attr, unicode):
string = attr.encode(sys.getfilesystemencoding())
else:
string = str(attr)
if maxchars is not None:
maxchars -= len(attrname)+4
if len(string) > maxchars:
string = string[:maxchars-3]+'...'
linebuf += ' = ' + string
return linebuf
def display_object(obj, name):
# get terminal width
if sys.stdout.isatty():
width = struct.unpack('HHHH', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, struct.pack('HHHH', 0, 0, 0, 0)))[1]
else:
width = None
children = deque([child for child in dir(type(obj)) if isinstance(getattr(type(obj), child, None), Setting)] + \
[child for child in dir(type(obj)) if isinstance(getattr(type(obj), child, None), SettingsGroupMeta)])
# display first line
linebuf = ' '*(len(name)+3) + '+'
if children:
linebuf += '-- ' + format_child(obj, children.popleft(), width-(len(name)+7) if width is not None else None)
print linebuf
# display second line
linebuf = name + ' --|'
if children:
linebuf += '-- ' + format_child(obj, children.popleft(), width-(len(name)+7) if width is not None else None)
print linebuf
# display the rest of the lines
if children:
while children:
child = children.popleft()
linebuf = ' '*(len(name)+3) + ('|' if children else '+') + '-- ' + format_child(obj, child, width-(len(name)+7) if width is not None else None)
print linebuf
else:
linebuf = ' '*(len(name)+3) + '+'
print linebuf
print
[display_object(getattr(obj, child), child) for child in dir(type(obj)) if isinstance(getattr(type(obj), child, None), SettingsGroupMeta)]
class SettingsParser(object):
@classmethod
def parse_default(cls, type, value):
if issubclass(type, List):
values = re.split(r'\s*,\s*', value)
return values
elif issubclass(type, bool):
if value.lower() == 'true':
return True
else:
return False
elif issubclass(type, unicode):
if isinstance(value, str):
return value.decode(sys.getfilesystemencoding())
return value
else:
return value
@classmethod
def parse_MSRPRelayAddress(cls, type, value):
return type.from_description(value)
@classmethod
def parse_SIPProxyAddress(cls, type, value):
return type.from_description(value)
@classmethod
def parse_STUNServerAddress(cls, type, value):
return type.from_description(value)
@classmethod
def parse_STUNServerAddressList(cls, type, value):
values = re.split(r'\s*,\s*', value)
return [STUNServerAddress.from_description(v) for v in values]
@classmethod
def parse_PortRange(cls, type, value):
return type(*value.split(':', 1))
@classmethod
def parse_Resolution(cls, type, value):
return type(*value.split('x', 1))
@classmethod
def parse_SoundFile(cls, type, value):
if ',' in value:
path, volume = value.split(',', 1)
else:
path, volume = value, 100
return type(path, volume)
@classmethod
def parse_AccountSoundFile(cls, type, value):
if ',' in value:
path, volume = value.split(',', 1)
else:
path, volume = value, 100
return type(path, volume)
@classmethod
def parse(cls, type, value):
if value == 'None':
return None
if value == 'DEFAULT':
return DefaultValue
parser = getattr(cls, 'parse_%s' % type.__name__, cls.parse_default)
return parser(type, value)
class AccountConfigurator(object):
def __init__(self):
Account.register_extension(AccountExtension)
BonjourAccount.register_extension(AccountExtension)
self.configuration_manager = ConfigurationManager()
self.configuration_manager.start()
self.account_manager = AccountManager()
self.account_manager.load()
def list(self):
print 'Accounts:'
bonjour_account = BonjourAccount()
accounts = [account for account in self.account_manager.get_accounts() if account.id != bonjour_account.id]
accounts.sort(cmp=lambda a, b: cmp(a.id, b.id))
accounts.append(bonjour_account)
for account in accounts:
print ' %s (%s)%s' % (account.id, 'enabled' if account.enabled else 'disabled', ' - default_account' if account is self.account_manager.default_account else '')
def add(self, sip_address, password):
if self.account_manager.has_account(sip_address):
print 'Account %s already exists' % sip_address
return
try:
account = Account(sip_address)
except ValueError, e:
print 'Cannot add SIP account: %s' % str(e)
return
account.auth.password = password
account.enabled = True
account.save()
print 'Account added'
def delete(self, sip_address):
if sip_address != 'ALL':
possible_accounts = [account for account in self.account_manager.iter_accounts() if sip_address in account.id]
if len(possible_accounts) > 1:
print "More than one account exists which matches %s: %s" % (sip_address, ", ".join(sorted(account.id for account in possible_accounts)))
return
if len(possible_accounts) == 0:
print 'Account %s does not exist' % sip_address
return
account = possible_accounts[0]
if account == BonjourAccount():
print 'Cannot delete bonjour account'
return
account.delete()
print 'Account deleted'
else:
for account in self.account_manager.get_accounts():
account.delete()
print 'Accounts deleted'
def show(self, sip_address=None):
if sip_address is None:
accounts = [self.account_manager.default_account]
if accounts[0] is None:
print "No accounts configured"
return
else:
if sip_address != 'ALL':
accounts = [account for account in self.account_manager.iter_accounts() if sip_address in account.id]
else:
accounts = self.account_manager.get_accounts()
if not accounts:
print 'No accounts which match %s' % sip_address
return
for account in accounts:
print 'Account %s:' % account.id
display_object(account, 'account')
def set(self, *args):
if not args:
raise TypeError("set must receive at least one argument")
if '=' in args[0]:
accounts = [self.account_manager.default_account]
if accounts[0] is None:
print "No accounts configured"
return
else:
sip_address = args[0]
args = args[1:]
if sip_address != 'ALL':
accounts = [account for account in self.account_manager.iter_accounts() if sip_address in account.id]
else:
accounts = self.account_manager.get_accounts()
if not accounts:
print 'No accounts which match %s' % sip_address
return
try:
settings = dict(arg.split('=', 1) for arg in args)
except ValueError:
print 'Illegal arguments: %s' % ' '.join(args)
return
for account in accounts:
for attrname, value in settings.iteritems():
object = account
name = attrname
while '.' in name:
local_name, name = name.split('.', 1)
try:
object = getattr(object, local_name)
except AttributeError:
print 'Unknown setting: %s' % attrname
object = None
break
if object is not None:
try:
attribute = getattr(type(object), name)
value = SettingsParser.parse(attribute.type, value)
setattr(object, name, value)
except AttributeError:
print 'Unknown setting: %s' % attrname
except ValueError, e:
print '%s: %s' % (attrname, str(e))
account.save()
print 'Account%s updated' % ('s' if len(accounts) > 1 else '')
def default(self, sip_address):
possible_accounts = [account for account in self.account_manager.iter_accounts() if sip_address in account.id]
if len(possible_accounts) > 1:
print "More than one account exists which matches %s: %s" % (sip_address, ", ".join(sorted(account.id for account in possible_accounts)))
return
if len(possible_accounts) == 0:
print 'Account %s does not exist' % sip_address
return
account = possible_accounts[0]
try:
self.account_manager.default_account = account
except ValueError, e:
print str(e)
return
print 'Account %s is now default account' % account.id
class SIPSimpleConfigurator(object):
def __init__(self):
SIPSimpleSettings.register_extension(SIPSimpleSettingsExtension)
self.configuration_manager = ConfigurationManager()
self.configuration_manager.start()
SIPSimpleSettings()
def show(self):
print 'SIP SIMPLE settings:'
display_object(SIPSimpleSettings(), 'SIP SIMPLE')
def set(self, *args):
sipsimple_settings = SIPSimpleSettings()
try:
settings = dict(arg.split('=', 1) for arg in args)
except ValueError:
print 'Illegal arguments: %s' % ' '.join(args)
return
for attrname, value in settings.iteritems():
object = sipsimple_settings
name = attrname
while '.' in name:
local_name, name = name.split('.', 1)
try:
object = getattr(object, local_name)
except AttributeError:
print 'Unknown setting: %s' % attrname
object = None
break
if object is not None:
try:
attribute = getattr(type(object), name)
value = SettingsParser.parse(attribute.type, value)
setattr(object, name, value)
except AttributeError:
print 'Unknown setting: %s' % attrname
except ValueError, e:
print '%s: %s' % (attrname, str(e))
sipsimple_settings.save()
print 'SIP SIMPLE general settings updated'
if __name__ == '__main__':
description = "This script manages the SIP SIMPLE client SDK settings."
usage = """%prog [--general|--account] [options] command [arguments]
%prog --general show
%prog --general set key1=value1 [key2=value2 ...]
%prog --account list
%prog --account add user@domain password
%prog --account delete user@domain|ALL
%prog --account show [user@domain|ALL]
%prog --account set [user@domain|ALL] key1=value1|DEFAULT [key2=value2|DEFAULT ...]
%prog --account default user@domain"""
parser = OptionParser(usage=usage, description=description)
parser.print_usage = parser.print_help
parser.add_option('-c', '--config-directory', type='string', dest='config_directory', help='The configuration directory to use. This overrides the default location.')
parser.add_option("-a", "--account", action="store_true", dest="account", help="Manage SIP accounts' settings")
parser.add_option("-g", "--general", action="store_true", dest="general", help="Manage general SIP SIMPLE middleware settings")
options, args = parser.parse_args()
# exactly one of -a or -g must be specified
if (not (options.account or options.general)) or (options.account and options.general):
parser.print_usage()
sys.exit(1)
# there must be at least one command
if not args:
sys.stderr.write("Error: no command specified\n")
parser.print_usage()
sys.exit(1)
SIPApplication.storage = FileStorage(options.config_directory or config_directory)
thread_manager = ThreadManager()
thread_manager.start()
# execute the handlers
try:
if options.account:
object = AccountConfigurator()
else:
object = SIPSimpleConfigurator()
except ConfigurationError, e:
sys.stderr.write("Failed to load sipclient's configuration: %s\n" % str(e))
sys.stderr.write("If an old configuration file is in place, delete it or move it and recreate the configuration using the sip_settings script.\n")
else:
command, args = args[0], args[1:]
handler = getattr(object, command, None)
if handler is None or not callable(handler):
sys.stderr.write("Error: illegal command: %s\n" % command)
parser.print_usage()
sys.exit(1)
try:
handler(*args)
except TypeError:
sys.stderr.write("Error: illegal usage of command %s\n" % command)
parser.print_usage()
sys.exit(1)
finally:
thread_manager.stop()