def genSnomFkeys(self, fkeys, type="320", useblf=True): """Generates function keys for each user""" output = [] ext = 0 for k, butNum in enumerate( self.butMat.get(type, self.butMat['320'])[ext]): buttonText = 'fkey%s' % butNum if k < len(fkeys): key = fkeys[k] else: key = None dial = "" keyDet = PBXUtils.resolveKeyNumber(key) butType = "dest" pickup = "" if keyDet: dial = keyDet[0] if 'ext/' == key[0:4] and useblf: pickup = "|*8" butType = "blf" if dial: output.append('%s: %s <sip:%s@%s>%s' % (buttonText, butType, dial, self.lanIP, pickup)) else: butdata = '' if type in self.butMat.get('defaults', {}): if k < len(self.butMat['defaults'][type]): butdata = self.butMat['defaults'][type][k] output.append('%s: %s' % (buttonText, butdata)) return str.join('\n', output)
def writeConfig(self, *a): """Writes the configuration files for zaptel to load at boot time""" if not PBXUtils.enabled(): print "PBX System is not enabled" return if not self.checkModules(): if not self.installModules(): print "No automatic kernel support for zaptel detected please manually install Zaptel drivers ..." return try: module_config = open(self.modulesconfigfile, 'r') missing_modules = [] missing_modules += self.kernelModules file_lines = module_config.readlines() for module in file_lines: module = module.rstrip() if module in missing_modules: #If the module is in the config remove it from the missing_modules list missing_modules.remove(module) module_config.close() if len(missing_modules) > 0: #If missing_modules has elements we need to add it to the /etc/modules file file_lines = [line.rstrip() for line in file_lines] file_lines += ["","#Generated by vulani configurator"] file_lines += missing_modules module_config = open(self.modulesconfigfile,'wt') module_config.write(str.join('\n', file_lines)) module_config.close() #Load modules self.loadModules() except Exception, _e: print "Error loading config file %s, %s" % (self.modulesconfigfile, str(_e))
def genSnomFkeys(self, fkeys, type="360", ext=0): """Generates function keys for each user""" output = [] #for k, user in enumerate(fkeys): for k, butNum in enumerate(self.butMat[type][ext]): buttonText = 'fkey%s' % butNum if k < len(fkeys): key = fkeys[k] else: key = None dial = "" keyDet = PBXUtils.resolveKeyNumber(key) butType = "dest" pickup = "" if keyDet: dial = keyDet[0] if 'ext/' == key[0:4]: pickup = "|*8" butType = "blf" if dial: output.append('%s: %s <sip:%s@%s>%s' % (buttonText, butType, dial, self.lanIP, pickup)) else: output.append('%s: ' % buttonText) return str.join('\n', output)
def __init__(self): """Check if we have all the files required before we update the config""" if PBXUtils.enabled( ): #Please leave this in here and enable at own risk self.iaxRegistrations = [] if os.path.exists('/etc/asterisk/peers') and os.path.exists( '/etc/asterisk/extensions') and os.path.exists( '/etc/asterisk/VULANI'): pass else: self.prepareAsterisk()
def telDBPerformRout(telDB): """Perform routine queries Telephone CDR""" return #Disable if not PBXUtils.enabled(): print "PBX is not enabled" return #else: #print "Performing Routine Queries on Telephone DB" def handSuc(_): #print _ pass #print str(_) def handFal(_): print "Failure, %s" % _ try: fulDevList = PBXUtils.getAllExtenDevs() except Exception, _exp: fulDevList = {} print "While trying to perform TelDB Routines got exception, %s" % _exp
def writeConfig(self, *a): """Write the configuration files""" if PBXUtils.enabled(): # Write PBX Hardware self.PBXHardware = PBXUtils.PBXHardware() self.PBXHardware.save() # Do incremental configs first self.writeProviders() # write the static files self.writeStatics() # Write Sip Config self.writeSipConf() # Write IAX Config self.writeIaxConf() # Write Indications self.writeIndications() # Write HoldMusic self.writeMusicOnHold() # Write Queues self.writeQueues() # Write Binding Extensions self.writeExtensions() # Write Voicemail Settings self.writeVoiceMail() # Create CDR DB self.createCDRDB()
def writeQueues(self): """Generate the queue file""" queues = {} #Start by collecting setting for the queues for queueName, queueData in config.PBX.get('queues', {}).items(): queues[queueName] = queueData queues[queueName]['members'] = [] #Merge members into the dict entry for each queue for user, extension in config.PBXExtensions.items(): for queue in extension.get('queues', []): if queue in queues: queues[queue]['members'].extend([ PBXUtils.resolveDevice(dev) for dev in extension['devices'] ]) queueComp = "" #Loop through the queues and add members for queue, qDet in queues.items(): members = "" for member in qDet['members']: members = members + """ member => %s\n""" % member queueComp = queueComp + """ [%(name)s] strategy=%(strategy)s timeout=%(timeout)s announce-frequency=%(ann-freq)s announce-holdtime=%(ann-holdtime)s maxlen=0 leavewhenempty=yes eventwhencalled=yes retry=5 music=default %(members)s """ % { 'name': queue, 'strategy': qDet.get('strategy', 'ringall'), 'timeout': qDet.get('timeout', '0'), 'ann-freq': qDet['announce'] and '30' or '0', 'ann-holdtime': qDet['announce'] and 'yes' or 'no', 'members': members, } queueData = self.configContent['queues'] % {'queues': queueComp} self.writeFile('/etc/asterisk/queues.conf', queueData, ';')
def render_editContent(self, ctx, data): if not self.avatarId.checkDomainPermissions(self.domain): return ctx.tag["Nice try"] if Settings.sambaDN and self.domain == Settings.defaultDomain: sambaGroups = tags.a( _class="noUnderline", href=url.root.child("Users").child('Groups').child( self.domain).child(self.cid))[ tags.img(src="/images/groupsm.png", align="absmiddle"), self.text.userLinkEditMembership] PBXTab = PBXUtils.enabled() else: sambaGroups = "" PBXTab = False notice = "" if self.cid == "root" and Settings.sambaDN: notice = tags.strong[tags.p( style="color:#f00")[self.text.userWarningEditRoot]] if self.returns == 'Completed': notice = tags.img(src='/images/modsuccess.png') elif self.returns == 'Failed': notice = tags.h1['Edit Failed!'] tabs = [(self.text.userTabSettings, 'editForm-userSettings'), (self.text.userTabPermissions, 'editForm-userPermissions'), (self.text.userTabMail, 'editForm-mailSettings'), (self.text.userTabAccess, 'editForm-userAccess')] if PBXTab: tabs.append( (self.text.userFormUserExtension, 'editForm-userExtension')) tabs.append((self.text.userFormUserFKeys, 'editForm-userFKeys')) return ctx.tag[ notice, tags.h3[self.text.userHeadingEditUser, self.cid], tags.a(_class="noUnderline", href=url.root.child('Users').child('Delete'). child(str(self.domain)).child(str(self.cid)), onclick="return confirm('%s');" % self.text.userConfirmDelete)[ tags.img(src="/images/ex-wbg.png", align="absmiddle"), self.text.userLinkDeleteUser], sambaGroups, PageHelpers.TabSwitcher(tabs), tags.directive('form editForm'), PageHelpers.LoadTabSwitcher()]
def cleanupPBXUser(self, username): def restartDevs(res): for dev in devs: Asterisk.restartSnom(dev.split("/")[-1]) ext = {} if PBXUtils.enabled(): ext = self.sysconf.PBXExtensions devs = [] for k, i in ext.items(): search = "ext/" + username if search in i.get("fkeys", []): for idx, val in enumerate(i["fkeys"]): if search == val: ext[k]["fkeys"][idx] = None if username in ext: devs = ext[username]["devices"] del ext[username] self.sysconf.PBXExtensions = ext return restartAsterisk().addBoth(restartDevs)
from Core import PBXUtils from PBXHardwarePlugins import ZaptelCards """ Provides ISDN card implementation of card entity for the zaptel hardware plugin """ priConfig = PBXUtils.PBXCardPortConfig( 'priconfig', #Config Entity "PRI Config", #Title "Please select a configuration profile", #Description { #Options 'za': "South Africa(Telkom, Neotel)(E1)", 'de': "Germany (E1)", 'uk': "United Kingdom (E1)", 'usa': "United States (T1)", #'t1cbank': "T1 Channelbank", #'e1cbank': "E1 ChannelBank", }, "za" #Future default will be set to the country ) briConfig = PBXUtils.PBXCardPortConfig( 'briconfig', #Config Entity "BRI Config", #Title "Please select a configuration profile", #Description { #Options 'za': "South Africa(Telkom, Neotel)(BRI)", 'de': "Germany (BRI)", 'uk': "United Kingdom (BRI)", }, "za" #Future default will be set to the country
def writeSipConf(self): """Writes the sip.conf file""" content = self.configContent['sip'] % { 'codec': str.join("\n ", self.colapseData(self.codecs)), 'domain': config.Domain, 'context': 'default' } self.writeFile('/etc/asterisk/sip.conf', content, ';') # Create sip peers for handsets phones = config.PBX.get('phones', {}) for exten, conf in phones.items(): phDevString = "Phone/" + conf['username'] conf['context'] = "" conf['voicemail'] = '' conf['append'] = '' ext = PBXUtils.getDeviceExtension(phDevString) if ext: if ext[1]['enabled']: conf['extname'] = ext[0] conf[ 'context'] = "context = " + PBXUtils.getExtensionContext( ext[1]) if 'fullcallerID' in ext[1]: conf['callerid'] = ext[1]['fullcallerID'] if ext[1].get('voiceMail', False): conf['voicemail'] = 'mailbox=' + str( ext[1]['extensions'][0]) conf['append'] = """callgroup=0 accountcode=%(extname)s pickupgroup=0 vmexten=*96 %(voicemail)s """ % conf block = """[%(username)s] type=peer %(context)s callerid=%(callerid)s username=%(username)s host=dynamic notifyringing=yes nat=yes notifyhold=yes limitonpeers=yes call-limit=99 canreinvite=no qualify=5000 dtmfmode=rfc2833 %(append)s """ % conf if conf.get('call-limit', 0): block += "call-limit=%s\n" % conf['call-limit'] ph = open('/etc/asterisk/peers/sip/%s.conf' % exten, 'wt') ph.write(self.stripBlock(block)) ph.close()
def writeExtensions(self): #def cmpRoutExp(a,b): def compareNumExp(a, b): """Compares the number expresion priority and makes certain that when sort is applied that the values are in the correct order Highest value first""" #normalise try: vala = a[4] except: vala = 0 if not vala: vala = 0 try: valb = b[4] except: valb = 0 if not valb: valb = 0 if vala < valb: return 1 if vala == valb: return 0 else: return -1 def clr(val): if not val: return "" else: return str(val) # Write Router Context #Create base routers for providers userRouters = {} routerContextNames = {} providerResolvedDevices = {} voipTypeResolve = { 'vulani': 'IAX2', 'iax2': 'IAX2', 'sip': 'SIP', } #Resolve provider routing endpoints for providerName, provider in config.PBXProviders.items(): if provider['type'] != 'hardware': ro = voipTypeResolve[provider['type']] + '/' + providerName providerResolvedDevices[providerName] = [ro] continue devDict = PBXUtils.resolveProviderDevice(provider) for dev in provider['device']: if dev in devDict: if providerName not in providerResolvedDevices: providerResolvedDevices[providerName] = [] providerResolvedDevices[providerName].append(devDict[dev]) routerFile = """ //PBX Router Extension Contexts""" for Router, routerConfig in config.PBXRouters.items(): routerContextNames[Router] = "router-" + Router.replace(' ', '_') routerContent = {} routerConfig.sort(compareNumExp) numberExpresion = [] for num in routerConfig: if num[1] not in config.PBXProviders: print "Invalid provider specified in Router Config %s" % str( num) continue if num[1] not in providerResolvedDevices: print "No availible resolved devices for provider %s" % num[ 1] continue devs = providerResolvedDevices[num[1]] #Pad devs for pos in range(len(devs), 6): devs.append("") content = """&route-provider(%(prefix)s${EXTEN%(ltrim)s},%(dev0)s,%(dev1)s,%(dev2)s,%(dev3)s,%(dev4)s,%(dev5)s,%(provider)s,%(monitor)s,,);""" % { 'num': clr(num[0]), 'prefix': clr(num[2]), 'provider': clr(num[1]), 'ltrim': clr(num[3]), 'dev0': devs[0], 'dev1': devs[1], 'dev2': devs[2], 'dev3': devs[3], 'dev4': devs[4], 'dev5': devs[5], 'monitor': config.PBX.get('recordAll', True) and '1' or '', } if num[0] not in routerContent: routerContent[num[0]] = [] numberExpresion.append(num[0]) routerContent[num[0]].append(content) compiledContext = "" for numExp in numberExpresion: expHandlers = routerContent[numExp] if len(expHandlers) == 1: compiledContext = compiledContext + """ %s => %s""" % (numExp, expHandlers[0]) else: compiledContext = compiledContext + """ %s => { %s };""" % (numExp, str.join('\n ', expHandlers)) routerFile += """ context %s { %s };""" % (routerContextNames[Router], compiledContext) self.writeFile( '/etc/asterisk/extensions/routing/vulaniProviderRouting.ael', routerFile, '//', 12) # Prepare User Contexts userContexts = "" contextSets = {} for user, userDet in config.PBXExtensions.items(): userDet['outbound'].sort() kn = str.join('-', userDet['outbound']) if kn not in contextSets: contextSets[kn] = { 'context': 'userProv-' + kn, 'userList': [user], 'includeList': [ 'userHints', 'userExtensions', 'systemExtensions', 'featureExtensions', 'customExtensions', ], 'providers': userDet['outbound'] } else: contextSets[kn]['userList'].append(user) # Write User Contexts for contextSet, data in contextSets.items(): includeList = data['includeList'] for provider in data['providers']: if provider in routerContextNames: includeList.append(routerContextNames[provider]) data['compiledIncludeContexts'] = "" for context in includeList: data['compiledIncludeContexts'] = data[ 'compiledIncludeContexts'] + '\n %s;' % context userContexts = userContexts + """ context %(context)s { includes { %(compiledIncludeContexts)s }; };""" % data self.writeFile( '/etc/asterisk/extensions/routing/userProviderContexts.ael', userContexts, '//', 12) # Write User Extensions userHints = "" userExtensions = "" userExtensionCompiled = "" userHintsCompiled = "" for user, userExt in config.PBXExtensions.items(): if not userExt['enabled']: continue devSet = str.join( '&', [PBXUtils.resolveDevice(dev) for dev in userExt['devices']]) hintDev = [ PBXUtils.resolveDevice(dev) for dev in userExt['devices'] ][0] for extension in userExt['extensions']: userExtensionCompiled = userExtensionCompiled + """ hint(%(dev)s) %(exten)s => &std-exten(%(mailboxname)s,%(dev)s,%(user)s,%(monitor)s,,%(fwdVoiceMail)i,);""" % { 'exten': extension, 'mailboxname': userExt['extensions'][0], 'dev': devSet, 'fwdVoiceMail': userExt['voiceMail'], 'user': user, 'monitor': config.PBX.get('recordAll', True) and '1' or '', } userExtensions = """ context userExtensions {%s }; """ % userExtensionCompiled self.writeFile('/etc/asterisk/extensions/userExtensions.ael', userExtensions, '//', 12) #Compile systemExt systemExt = [] ivrExtensions = "" for ivrName, ivrDet in config.PBX.get('ivr', {}).items(): welcomePlayback = "Playback(%s);" % ivrDet['prompt'][0].split( '.')[0] prompts = [] for prompt in ivrDet['prompt'][1:]: if prompt: prompts.append(prompt.split('.')[0]) if prompts: optionsPlayback = "Background(" + str.join('&', prompts) + ");" else: optionsPlayback = "" ivrItems = [] for k, option in enumerate(ivrDet['options']): if option: res = PBXUtils.resolveKeyNumber(option) if res: ivrItems.append('%s => Dial(Local/%s@default);' % (k, res[0])) timeoutEntry = "goto s|menuOptions;" if ivrDet.get('timeout-option', False): res = PBXUtils.resolveKeyNumber(ivrDet['timeout-option']) if res: timeoutEntry = 'Dial(Local/%s@default);' % res[0] ivrCompiled = str.join('\n ', ivrItems) for extNum in ivrDet['extensions']: systemExt.append('%s => jump s@ivr-%s;' % (extNum, ivrName)) ivrExtensions += """ context ivr-%(name)s { s => { Answer; Set(TIMEOUT(digit)=5); Set(TIMEOUT(response)=%(timeout)s); %(welcomePlayback)s menuOptions: %(optionsPlayback)s WaitExten(); %(timeoutEntry)s }; %(ivrContent)s t => { hangup;}; i => { Playback(option-is-invalid) ; goto s|menuOptions;};//This will change if default timeout is specified }; """ % { 'name': ivrName, 'timeout': ivrDet['timeout'], 'ivrContent': ivrCompiled, 'optionsPlayback': optionsPlayback, 'welcomePlayback': welcomePlayback, 'timeoutEntry': timeoutEntry } self.writeFile('/etc/asterisk/extensions/ivrContexts.ael', ivrExtensions, '//', 12) #compiling queues for qName, qDet in config.PBX.get('queues', {}).items(): if 'extensions' in qDet: systemExt.append( "hint(DS/%(exten)s) %(exten)s => &queue-exten(%(exten)s,%(queue-name)s,);" % { 'queue-name': qName, 'exten': qDet['extensions'][0], }) systemCompiled = str.join('\n ', systemExt) # Write System Extensions systemExt = """ context systemExtensions { %s }; context featureExtensions { *60 => jump s@recorder-menu; _*61XX => { Answer(); Wait(0.5); Record(custom/${EXTEN:3}.gsm); Wait(1); Playback(custom/${EXTEN:3}); Hangup; }; *96 => VoiceMailMain(${CALLERID(num)}); *8 => Pickup(0); _*8. => { DPickup(${EXTEN:2}@PICKUPMARK); }; }; """ % systemCompiled self.writeFile('/etc/asterisk/extensions/system.ael', systemExt, '//', 12) incomingContext = """ context incomming { includes { preCustomIncomming; userHints; userExtensions; systemExtensions; postCustomIncomming; }; }; context default { includes { incomming; }; }; """ self.writeFile('/etc/asterisk/extensions/incoming.ael', incomingContext, '//', 12)
def form_editForm(self, data): domains = [] if self.avatarId.isAdmin: for i in self.flatFil: thisdom = i.split('dm=')[-1].split(',')[0] if not thisdom in domains: domains.append(thisdom) # Form population userData = self.lc.getUser(self.cid) devList = [] #extList = [] rouList = [] UserExtForm = [] fkeyForm = [] if Settings.sambaDN and self.domain==Settings.defaultDomain and PBXUtils.enabled(): includeList = [] includeList = self.sysconf.PBXExtensions.get(userData['uid'][0], {'extensions':[]})['extensions'] extList = PBXUtils.getAvaExtenNumSelect(True, includeList) #for ext in PBXUtils.getAvailibleExtensions(): # extList.append((str(ext), str(ext))) for dev in PBXUtils.getAllAvaExtDeviceEndPoints(): devList.append((str(dev), str(dev))) queueList = [(queue, queue) for queue in self.sysconf.PBX.get('queues', {}).keys()] rouList = self.sysconf.PBXRouters.keys() extensionWidget = formal.widgetFactory(formal.SelectChoice, options = extList) deviceWidget = formal.widgetFactory(formal.SelectChoice, options = devList) #queueWidget = formal.widgetFactory(formal.SelectChoice, options = queueList) userExtensions = PBXUtils.getExtensionSelect() fKeyOptions = formal.widgetFactory(formal.SelectChoice, options = userExtensions) fKeys = [] maxKeys = 11 for i in range(maxKeys): fKeys.append(formal.Field('fkeys%s' % i, formal.String(), fKeyOptions, label = "Key %s" % i)) fKeys.append(formal.Field('fkeys%s'%maxKeys, formal.String(), fKeyOptions, label = "Key %s"%maxKeys, description = "Select the extensions for the function keys above")) UserExtForm = formal.Group('userExtension')[ formal.Field('userExtEnabled', formal.Boolean(), label = self.text.userFormLabelExtEnabled), formal.Field('userExtOutbound', formal.Sequence(formal.String()), formal.widgetFactory(formal.CheckboxMultiChoice, options=[(i,i) for i in rouList]), label = self.text.userFormLabelOutbound, description = self.text.userFormDescOutbound), formal.Field('userExtQueues', formal.Sequence(formal.String()), formal.widgetFactory(formal.CheckboxMultiChoice, options = queueList), label = self.text.userFormLabelQueues, description = self.text.userFormDescQueues), formal.Field('userExtCallerID', formal.String(), label = self.text.userFormLabelCallID), formal.Field('userExtNumber0', formal.String(), extensionWidget, label = self.text.userFormLabelExtNumber), formal.Field('userExtNumber1', formal.String(), extensionWidget,label = ""), formal.Field('userExtNumber2', formal.String(), extensionWidget,label = ""), formal.Field('userExtNumber3', formal.String(), extensionWidget,label = ""), formal.Field('userExtNumber4', formal.String(), extensionWidget,label = ""), formal.Field('userExtNumber5', formal.String(), extensionWidget,label = ""), formal.Field('userExtNumber6', formal.String(), extensionWidget,label = ""), formal.Field('userExtNumber7', formal.String(), extensionWidget,label = ""), formal.Field('userExtNumber8', formal.String(), extensionWidget,label = ""), formal.Field('userExtNumber9', formal.String(), extensionWidget,label = ""), tags.div(_class="userLine")[tags.a(href="#", onclick="addExten();")[self.text.userFormLabelAddExt]], formal.Field('userExtFwdUA', formal.String(), label = self.text.userFormLabelRedNoAnswer, description = self.text.userFormDescRedNoAnswer), formal.Field('userExtDev0', formal.String(), deviceWidget,label = self.text.userFormLabelDev), formal.Field('userExtDev1', formal.String(), deviceWidget,label = ""), formal.Field('userExtDev2', formal.String(), deviceWidget,label = ""), formal.Field('userExtDev3', formal.String(), deviceWidget,label = ""), formal.Field('userExtDev4', formal.String(), deviceWidget,label = ""), formal.Field('userExtDev5', formal.String(), deviceWidget,label = ""), formal.Field('userExtDev6', formal.String(), deviceWidget,label = ""), formal.Field('userExtDev7', formal.String(), deviceWidget,label = ""), formal.Field('userExtDev8', formal.String(), deviceWidget,label = ""), formal.Field('userExtDev9', formal.String(), deviceWidget,label = ""), tags.div(_class="userLine")[tags.a(href="#", onclick="addExtDev();")[self.text.userFormLabelAddDev]], formal.Field('userExtVoiceMail', formal.Boolean(), label = self.text.userFormLabelVoiceMail), formal.Field('userExtVoiceMailPin', formal.String(), label = self.text.userFormLabelVoiceMailPin), ] fkeyForm = formal.Group('userFKeys')[fKeys] form = formal.Form(self.submitForm)[ formal.Group('userSettings')[ tags.div(_class="field")[ tags.label[self.text.userFormLabelEmailAddress], tags.div(id="emailAd", _class="inputs")[ "%s@%s"% (self.cid, self.domain) ] ], formal.Field('uid', formal.String(required=True), label = self.text.userFormLabelUsername), formal.Field('givenName', formal.String(required=True), label = self.text.userFormLabelName), formal.Field('sn', formal.String(), label = self.text.userFormLabelSurname), formal.Field('userPassword', formal.String(), formal.CheckedPassword, label= self.text.userFormLabelPass), ], formal.Group('mailSettings')[ formal.Field('mailForwardingAddress0', formal.String(), label=self.text.userFormLabelForward), formal.Field('mailForwardingAddress1', formal.String(), label=""), formal.Field('mailForwardingAddress2', formal.String(), label=""), formal.Field('mailForwardingAddress3', formal.String(), label=""), formal.Field('mailForwardingAddress4', formal.String(), label=""), formal.Field('mailForwardingAddress5', formal.String(), label=""), formal.Field('mailForwardingAddress6', formal.String(), label=""), formal.Field('mailForwardingAddress7', formal.String(), label=""), formal.Field('mailForwardingAddress8', formal.String(), label=""), formal.Field('mailForwardingAddress9', formal.String(), label=""), tags.div(_class="userLine")[tags.a(href="#", onclick="addForward();")[self.text.userFormLabelAddline]], formal.Field('mailAlternateAddress0', formal.String(), label=self.text.userFormLabelAlias), formal.Field('mailAlternateAddress1', formal.String(), label=""), formal.Field('mailAlternateAddress2', formal.String(), label=""), formal.Field('mailAlternateAddress3', formal.String(), label=""), formal.Field('mailAlternateAddress4', formal.String(), label=""), formal.Field('mailAlternateAddress5', formal.String(), label=""), formal.Field('mailAlternateAddress6', formal.String(), label=""), formal.Field('mailAlternateAddress7', formal.String(), label=""), formal.Field('mailAlternateAddress8', formal.String(), label=""), formal.Field('mailAlternateAddress9', formal.String(), label=""), tags.div(_class="userLine")[tags.a(href="#", onclick="addAlias();")[self.text.userFormLabelAddline]], formal.Field('vacen', formal.Boolean(), label = self.text.userFormLabelVacationActive, description=self.text.userFormTextVacationNote), formal.Field('vacation', formal.String(), formal.TextArea, label=self.text.userFormLabelVacation), formal.Field('vacvalidity', formal.Date(), label = "Valid until", description="Disable the vacation note automatically on this date") ], formal.Group('userPermissions')[ formal.Field('employeeType', formal.Boolean(), label = self.text.userFormLabelWeb), formal.Field('accountStatus', formal.Boolean(), label = self.text.userFormLabelEmail), formal.Field('tumsAdmin', formal.Boolean(), label = self.text.userFormLabelAdmin), formal.Field('tumsUser', formal.Sequence(formal.String()), formal.widgetFactory(formal.CheckboxMultiChoice, [(i,i) for i in domains]), label = self.text.userFormLabelDomainAdmin), formal.Field('tumsReports', formal.Boolean(), label = self.text.userFormLabelReports), formal.Field('copyto', formal.String(), label = self.text.userFormLabelCopy, description = self.text.userFormTextCopy) ], formal.Group('userAccess')[ formal.Field('vpnEnabled', formal.Boolean(), label = self.text.userFormLabelVPN, description = self.text.userFormTextVPN), formal.Field('ftpEnabled', formal.Boolean(), label = self.text.userFormLabelFTP, description = self.text.userFormTextFTP), formal.Field('ftpGlobal', formal.Boolean(), label = self.text.userFormLabelGlobalFTP, description = self.text.userFormTextGlobal) ], UserExtForm, fkeyForm ] form.addAction(self.submitForm) tData = copy.deepcopy(userData) tData['userSettings.uid'] = tData['uid'][0] tData['userSettings.givenName'] = tData.get('givenName', [""])[0] tData['userSettings.sn'] = tData.get('sn', [""])[0] if tData.get('loginShell'): if '/bin/bash' in tData['loginShell']: tData['userAccess.ftpEnabled'] = True if self.sysconf.FTP.get('globals'): if tData['uid'][0] in self.sysconf.FTP['globals']: tData['userAccess.ftpGlobal'] = True tData['userSettings.userPassword'] = '' # Strip password address = "%s@%s" % (tData['uid'][0], self.domain) for i in os.listdir('/etc/openvpn/keys/'): if "%s.%s" % (self.cid, self.domain) in i and "key" in i: tData['userAccess.vpnEnabled'] = True if self.sysconf.Mail.get('copys', []): for addr, dest in self.sysconf.Mail['copys']: if addr == address: tData['userPermissions.copyto'] = dest if userData.get('accountStatus', False): tData['userPermissions.accountStatus'] = True else: tData['userPermissions.accountStatus'] = False if userData.get('mailForwardingAddress', False): for cnt,address in enumerate(userData['mailForwardingAddress']): tData['mailSettings.mailForwardingAddress%s' % cnt] = address if userData.get('mailAlternateAddress', False): for cnt,address in enumerate(userData['mailAlternateAddress']): tData['mailSettings.mailAlternateAddress%s' % cnt] = address emp = userData.get('employeeType', [False]) if 'squid' in emp: tData['userPermissions.employeeType'] = True else: tData['userPermissions.employeeType'] = False if 'tumsAdmin' in emp: tData['userPermissions.tumsAdmin'] = True else: tData['userPermissions.tumsAdmin'] = False if 'tumsReports' in emp: tData['userPermissions.tumsReports'] = True else: tData['userPermissions.tumsReports'] = False if emp[0]: for i in emp: if 'tumsUser[' in i: tData['userPermissions.tumsUser'] = i.split('[')[-1].split(']')[0].split(',') try: vac = open("/var/spool/mail/vacation/%s@%s.txt" % (self.cid, self.domain), 'r') tData['mailSettings.vacation'] = vac.read() tData['mailSettings.vacen'] = True except: pass # No vacation note try: vac = open("/var/spool/mail/vacation/DISABLED%s@%s.txt" % (self.cid, self.domain), 'r') tData['mailSettings.vacation'] = vac.read() tData['mailSettings.vacen'] = False except: pass # No disabled note either. if os.path.exists('/var/spool/mail/vacation/%s@%s.validity' % (self.cid, self.domain)): n = open('/var/spool/mail/vacation/%s@%s.validity'% (self.cid, self.domain)).read().strip('\n') d = datetime.date(*[int(i) for i in n.split('-')]) tData['mailSettings.vacvalidity'] = d #Populate Userextension Data if PBXUtils.enabled(): ext = self.sysconf.PBXExtensions.get(tData['uid'][0], { 'enabled': False, 'outbound': [], 'callerID': "", 'voiceMail': False, 'voiceMailPin': '', 'fkeys': [], 'extensions': [], 'devices': [], 'queues': [] }) tData['userExtension.userExtEnabled'] = ext['enabled'] tData['userExtension.userExtOutbound'] = ext['outbound'] tData['userExtension.userExtQueues'] = ext.get('queues', []) tData['userExtension.userExtCallerID'] = ext['callerID'] tData['userExtension.userExtVoiceMail'] = ext['voiceMail'] tData['userExtension.userExtVoiceMailPin'] = ext['voiceMailPin'] for i in range(0,9): try: tData['userExtension.userExtNumber%s'%i]=ext['extensions'][i] except: pass try: tData['userExtension.userExtDev%s'%i]=ext['devices'][i] except: pass for i in range(12): try: tData['userFKeys.fkeys%s'%i] = ext['fkeys'][i] except: pass form.data = tData return form
def generateHandsetConfig(self, macAddr): """Generates the handset config from the mac address""" #snomMAC = self.sysconf.PBX.get('snomMAC', []) #if macAddr not in snomMAC: # snomMAC.append(macAddr) #So it shows in the interface # PBX = self.sysconf.PBX # PBX['snomMAC'] = snomMAC # self.sysconf.PBX = PBX phoneEnt = self.getPhoneEntry(macAddr) d = None data = {} def returnEntry(ret=None): print data if data: return stan.raw(snomDevConf % data) return "" if not phoneEnt: #Generate a blank Phone entry PBX = self.sysconf.PBX phones = PBX.get('phones', {}) cblock = { 'callerid': macAddr, 'username': macAddr, 'fullcallerid': macAddr, 'phone': { 'type': 'Snom ' + self.phoneVer[0], 'fkeys': [], 'mac': macAddr, 'autogen': True, #This was autogenerated }, 'secret': GenPasswd2(), 'outgoinglimit': 1 } phones[macAddr] = cblock PBX['phones'] = phones self.sysconf.PBX = PBX d = Asterisk.restartAsterisk() phoneEnt = self.getPhoneEntry(macAddr) print phoneEnt if phoneEnt: type = phoneEnt['phone']['type'].lower().split()[1] ptype = phoneEnt['phone']['type'].lower().split()[0] if self.phoneVer[0]: type = self.phoneVer[0].lower() if ptype == 'snom': ext = PBXUtils.getDeviceExtension('Phone/' + phoneEnt['username']) callerid = phoneEnt['username'] displayName = phoneEnt['username'] fkeys = self.genSnomFkeys([], type, self.phoneVer[1][0] == 7) if type == '300': displayName = displayName[ 2:] #Strip out the first two '0' chars if ext: #If there is a user extension bound to this phone then we need to work out a few things if ext[1]['enabled']: callerid = ext[1].get( 'fullcallerID', ext[1].get('callerID', 'Unknown')) displayName = "%s-%s" % (ext[1].get( 'callerID', 'Unknown'), ext[0]) if 'fkeys' in ext[1]: #Resolve Function Keys fkeys = self.genSnomFkeys(ext[1]['fkeys'], type) fwurl = 'firmware_status: http://%s:9682/snom/snom-firmware.htm' % self.lanIP if self.phoneVer[0] not in self.firmware.keys(): autoVer = "v%s" % self.phoneVer[1][0] print "Snom of type %s requested firmware for version %s, I don't know this type sending it to snom url(%s)" % ( self.phoneVer[0], str.join('.', self.phoneVer[1]), self.firmware[autoVer], ) if autoVer in self.firmware: fwurl = "firmware_status: %s%s" % ( self.firmware[autoVer], str(time.time())) data = { 'fkeys': fkeys, 'user': phoneEnt['username'], 'user_realname': callerid, 'user_idletext': displayName, 'password': phoneEnt['secret'], 'firmwareurl': fwurl, } if d: #If there is a defer then lets wait for it to end return d.addBoth(returnEntry) else: return returnEntry()
def form_editForm(self, data): domains = [] if self.avatarId.isAdmin: for i in self.flatFil: thisdom = i.split('dm=')[-1].split(',')[0] if not thisdom in domains: domains.append(thisdom) # Form population userData = self.lc.getUser(self.cid) devList = [] #extList = [] rouList = [] UserExtForm = [] fkeyForm = [] if Settings.sambaDN and self.domain == Settings.defaultDomain and PBXUtils.enabled( ): includeList = [] includeList = self.sysconf.PBXExtensions.get( userData['uid'][0], {'extensions': []})['extensions'] devIncList = self.sysconf.PBXExtensions.get( userData['uid'][0], {'devices': []})['devices'] extList = PBXUtils.getAvaExtenNumSelect(True, includeList) #for ext in PBXUtils.getAvailibleExtensions(): # extList.append((str(ext), str(ext))) for dev in PBXUtils.getAllAvaExtDeviceEndPoints(devIncList): devList.append((str(dev), str(dev))) queueList = [ (queue, queue) for queue in self.sysconf.PBX.get('queues', {}).keys() ] rouList = self.sysconf.PBXRouters.keys() extensionWidget = formal.widgetFactory(formal.SelectChoice, options=extList) deviceWidget = formal.widgetFactory(formal.SelectChoice, options=devList) #queueWidget = formal.widgetFactory(formal.SelectChoice, options = queueList) userExtensions = PBXUtils.getExtensionSelect() queueOptions = formal.widgetFactory(formal.SelectChoice, options=[(1, "Level 1 Member"), (2, "Level 2 Member"), (3, "Level 3 Member") ]) queues = [] for queue in self.sysconf.PBX.get('queues', {}).keys()[0:-1]: queues.append( formal.Field('queue%s' % queue, formal.Integer(), queueOptions, label="Queue %s" % queue)) try: queue = self.sysconf.PBX.get('queues', {}).keys()[-1] except: queue = None if queue: queues.append( formal.Field( 'queue%s' % queue, formal.Integer(), queueOptions, label="Queue %s" % queue, description= "Each extension may be part of many queues, each queue membersip has a specific weighting. The weighting determines the order in which calls may be seeded. Level 2 members only get calls seeded to them once Level 1 has been saturated etc." )) fKeyOptions = formal.widgetFactory(formal.SelectChoice, options=userExtensions) fKeys = [] maxKeys = 54 for i in range(maxKeys): fKeys.append( formal.Field('fkeys%s' % i, formal.String(), fKeyOptions, label="Key %s" % i)) fKeys.append( formal.Field( 'fkeys%s' % maxKeys, formal.String(), fKeyOptions, label="Key %s" % maxKeys, description= "Select the extensions for the function keys above")) userExtFormContent = [ formal.Field('userExtEnabled', formal.Boolean(), label=self.text.userFormLabelExtEnabled), formal.Field('userExtOutbound', formal.Sequence(formal.String()), formal.widgetFactory(formal.CheckboxMultiChoice, options=[(i, i) for i in rouList]), label=self.text.userFormLabelOutbound, description=self.text.userFormDescOutbound), #formal.Field('userExtQueues', formal.Sequence(formal.String()), # formal.widgetFactory(formal.CheckboxMultiChoice, # options = queueList), # label = self.text.userFormLabelQueues, # description = self.text.userFormDescQueues), ] userExtFormContent.extend(queues) userExtFormContent.extend([ formal.Field( 'userLowBW', formal.Boolean(), label="Low Bandwidth", description= 'Indicates that the devices(if applicable) should use a low bandwidth codec' ), formal.Field( 'userExtTimeout', formal.Integer(), label="Timeout", description= "How many seconds should we wait before giving up on this extension, note that setting this to 0 will force the extension to use the default timeout" ), formal.Field( 'userExtqTimeout', formal.Integer(), label="Queue Timeout", description= "How many seconds should we wait before giving up on this queue member, 0 will indicate to use the default" ), formal.Field('userExtCallerID', formal.String(), label=self.text.userFormLabelCallID), formal.Field('userExtNumber0', formal.String(), extensionWidget, label=self.text.userFormLabelExtNumber), formal.Field('userExtNumber1', formal.String(), extensionWidget, label=""), formal.Field('userExtNumber2', formal.String(), extensionWidget, label=""), formal.Field('userExtNumber3', formal.String(), extensionWidget, label=""), formal.Field('userExtNumber4', formal.String(), extensionWidget, label=""), formal.Field('userExtNumber5', formal.String(), extensionWidget, label=""), formal.Field('userExtNumber6', formal.String(), extensionWidget, label=""), formal.Field('userExtNumber7', formal.String(), extensionWidget, label=""), formal.Field('userExtNumber8', formal.String(), extensionWidget, label=""), formal.Field('userExtNumber9', formal.String(), extensionWidget, label=""), tags.div(_class="userLine")[tags.a( href="#", onclick="addExten();")[self.text.userFormLabelAddExt]], #formal.Field('userExtFwdUA', formal.String(), label = self.text.userFormLabelRedNoAnswer, # description = self.text.userFormDescRedNoAnswer), formal.Field('userExtDev0', formal.String(), deviceWidget, label=self.text.userFormLabelDev), formal.Field('userExtDev1', formal.String(), deviceWidget, label=""), formal.Field('userExtDev2', formal.String(), deviceWidget, label=""), formal.Field('userExtDev3', formal.String(), deviceWidget, label=""), formal.Field('userExtDev4', formal.String(), deviceWidget, label=""), formal.Field('userExtDev5', formal.String(), deviceWidget, label=""), formal.Field('userExtDev6', formal.String(), deviceWidget, label=""), formal.Field('userExtDev7', formal.String(), deviceWidget, label=""), formal.Field('userExtDev8', formal.String(), deviceWidget, label=""), formal.Field('userExtDev9', formal.String(), deviceWidget, label=""), tags.div(_class="userLine")[tags.a( href="#", onclick="addExtDev();")[self.text.userFormLabelAddDev]], formal.Field('userExtVoiceMail', formal.Boolean(), label=self.text.userFormLabelVoiceMail), formal.Field('userExtVoiceMailPin', formal.String(), label=self.text.userFormLabelVoiceMailPin), ]) UserExtForm = formal.Group('userExtension')[userExtFormContent] fkeyForm = formal.Group('userFKeys')[fKeys] form = formal.Form( self.submitForm )[formal.Group('userSettings')[tags.div(_class="field")[ tags.label[self.text.userFormLabelEmailAddress], tags.div(id="emailAd", _class="inputs")["%s@%s" % (self.cid, self.domain)]], formal.Field('uid', formal .String(required=True, validators=Base .UserNameValidators), label=self.text. userFormLabelUsername), formal.Field('givenName', formal.String( required=True), label=self.text. userFormLabelName), formal.Field('sn', formal.String(), label=self.text. userFormLabelSurname), formal.Field('userPassword', formal.String(), formal.CheckedPassword, label=self.text. userFormLabelPass), ], formal.Group('mailSettings') [formal.Field('mailForwardingAddress0', formal.String(), label=self. text.userFormLabelForward), formal.Field('mailForwardingAddress1', formal.String(), label=""), formal.Field('mailForwardingAddress2', formal.String(), label=""), formal.Field('mailForwardingAddress3', formal.String(), label=""), formal.Field('mailForwardingAddress4', formal.String(), label=""), formal.Field('mailForwardingAddress5', formal.String(), label=""), formal.Field('mailForwardingAddress6', formal.String(), label=""), formal.Field('mailForwardingAddress7', formal.String(), label=""), formal.Field('mailForwardingAddress8', formal.String(), label=""), formal.Field('mailForwardingAddress9', formal.String(), label=""), tags.div( _class="userLine")[tags.a(href="#", onclick="addForward();" )[self.text.userFormLabelAddline]], formal.Field('mailAlternateAddress0', formal.String(), label=self.text.userFormLabelAlias), formal.Field('mailAlternateAddress1', formal.String(), label=""), formal.Field('mailAlternateAddress2', formal.String(), label=""), formal.Field('mailAlternateAddress3', formal.String(), label=""), formal.Field('mailAlternateAddress4', formal.String(), label=""), formal.Field('mailAlternateAddress5', formal.String(), label=""), formal.Field('mailAlternateAddress6', formal.String(), label=""), formal.Field('mailAlternateAddress7', formal.String(), label=""), formal.Field('mailAlternateAddress8', formal.String(), label=""), formal.Field('mailAlternateAddress9', formal.String(), label=""), tags.div( _class="userLine")[tags.a(href="#", onclick="addAlias();" )[self.text.userFormLabelAddline]], formal.Field('vacen', formal.Boolean(), label=self.text.userFormLabelVacationActive, description=self.text.userFormTextVacationNote), formal.Field('vacation', formal.String(), formal.TextArea, label=self.text.userFormLabelVacation), formal.Field('vacvalidity', formal.Date(), label="Valid until", description= "Disable the vacation note automatically on this date" )], formal.Group('userPermissions')[ formal.Field('employeeType', formal.Boolean(), label=self.text.userFormLabelWeb), formal.Field('accountStatus', formal.Boolean(), label=self.text.userFormLabelEmail), formal.Field('tumsAdmin', formal.Boolean(), label=self.text.userFormLabelAdmin), formal.Field('tumsUser', formal.Sequence(formal.String()), formal.widgetFactory(formal.CheckboxMultiChoice, [( i, i) for i in domains]), label=self.text.userFormLabelDomainAdmin), formal.Field('tumsReports', formal.Boolean(), label=self.text.userFormLabelReports), formal.Field('copyto', formal.String(), label=self.text.userFormLabelCopy, description=self.text.userFormTextCopy)], formal.Group('userAccess')[ formal.Field('vpnEnabled', formal.Boolean(), label=self.text.userFormLabelVPN, description=self.text.userFormTextVPN), formal.Field('ftpEnabled', formal.Boolean(), label=self.text.userFormLabelFTP, description=self.text.userFormTextFTP), formal.Field('ftpGlobal', formal.Boolean(), label=self.text.userFormLabelGlobalFTP, description=self.text.userFormTextGlobal)], UserExtForm, fkeyForm] form.addAction(self.submitForm) tData = copy.deepcopy(userData) tData['userSettings.uid'] = tData['uid'][0] tData['userSettings.givenName'] = tData.get('givenName', [""])[0] tData['userSettings.sn'] = tData.get('sn', [""])[0] if tData.get('loginShell'): if '/bin/bash' in tData['loginShell']: tData['userAccess.ftpEnabled'] = True if self.sysconf.FTP.get('globals'): if tData['uid'][0] in self.sysconf.FTP['globals']: tData['userAccess.ftpGlobal'] = True tData['userSettings.userPassword'] = '' # Strip password address = "%s@%s" % (tData['uid'][0], self.domain) for i in os.listdir('/etc/openvpn/keys/'): if "%s.%s" % (self.cid, self.domain) in i and "key" in i: tData['userAccess.vpnEnabled'] = True if self.sysconf.Mail.get('copys', []): for addr, dest in self.sysconf.Mail['copys']: if addr == address: tData['userPermissions.copyto'] = dest if userData.get('accountStatus', False): tData['userPermissions.accountStatus'] = True else: tData['userPermissions.accountStatus'] = False if userData.get('mailForwardingAddress', False): for cnt, address in enumerate(userData['mailForwardingAddress']): tData['mailSettings.mailForwardingAddress%s' % cnt] = address if userData.get('mailAlternateAddress', False): for cnt, address in enumerate(userData['mailAlternateAddress']): tData['mailSettings.mailAlternateAddress%s' % cnt] = address emp = userData.get('employeeType', [False]) if 'squid' in emp: tData['userPermissions.employeeType'] = True else: tData['userPermissions.employeeType'] = False if 'tumsAdmin' in emp: tData['userPermissions.tumsAdmin'] = True else: tData['userPermissions.tumsAdmin'] = False if 'tumsReports' in emp: tData['userPermissions.tumsReports'] = True else: tData['userPermissions.tumsReports'] = False if emp[0]: for i in emp: if 'tumsUser[' in i: tData['userPermissions.tumsUser'] = i.split('[')[-1].split( ']')[0].split(',') try: vac = open( "/var/spool/mail/vacation/%s@%s.txt" % (self.cid, self.domain), 'r') tData['mailSettings.vacation'] = vac.read() tData['mailSettings.vacen'] = True except: pass # No vacation note try: vac = open( "/var/spool/mail/vacation/DISABLED%s@%s.txt" % (self.cid, self.domain), 'r') tData['mailSettings.vacation'] = vac.read() tData['mailSettings.vacen'] = False except: pass # No disabled note either. if os.path.exists('/var/spool/mail/vacation/%s@%s.validity' % (self.cid, self.domain)): n = open('/var/spool/mail/vacation/%s@%s.validity' % (self.cid, self.domain)).read().strip('\n') d = datetime.date(*[int(i) for i in n.split('-')]) tData['mailSettings.vacvalidity'] = d #Populate Userextension Data if PBXUtils.enabled(): ext = self.sysconf.PBXExtensions.get( tData['uid'][0], { 'enabled': False, 'lowbw': False, 'outbound': [], 'callerID': "", 'voiceMail': False, 'voiceMailPin': '', 'fkeys': [], 'extensions': [], 'devices': [], 'queues': {} }) tData['userExtension.userExtEnabled'] = ext['enabled'] tData['userExtension.userExtOutbound'] = ext['outbound'] tData['userExtension.userExtTimeout'] = ext.get('timeout', 0) tData['userExtension.userExtqTimeout'] = ext.get('qtimeout', 0) #tData['userExtension.userExtQueues'] = ext.get('queues', []) queueSettings = ext.get('queues', {}) if type(queueSettings) == list: n = {} for queue in queueSettings: n[queue] = 1 queueSettings = n for queue in self.sysconf.PBX.get('queues', {}).keys(): tData['userExtension.queue%s' % queue] = queueSettings.get( queue, None) tData['userExtension.userExtCallerID'] = ext['callerID'] tData['userExtension.userExtVoiceMail'] = ext['voiceMail'] tData['userExtension.userExtVoiceMailPin'] = ext['voiceMailPin'] tData['userExtension.userLowBW'] = ext.get('lowbw', False) for i in range(0, 9): try: tData['userExtension.userExtNumber%s' % i] = ext['extensions'][i] except: pass try: tData['userExtension.userExtDev%s' % i] = ext['devices'][i] except: pass for i in range(54): try: tData['userFKeys.fkeys%s' % i] = ext['fkeys'][i] except: pass form.data = tData return form
class Plugin(object): parameterHook = "--debzaptel" parameterDescription = "Install Zaptel Drivers" parameterArgs = "" autoRun = False required = "debian" configFiles = [] kernelModules = [ "zaphfc", "qozap", "ztgsm", "wctdm", "wctdm24xxp", "wcfxo", "wcfxs", "pciradio", "tor2", "torisa", "wct1xxp", "wct4xxp", "wcte11xp", "wanpipe", "wcusb", "xpp_usb" ] zaptelbasename = "zaptel-modules" modulesDir = "/lib/modules" zaptelModuleDirectory = "/misc" zaptelaptpkg = "" kernelVersion = "" modulesconfigfile = "/etc/modules" def reloadServices(self): self.loadModules() if(os.path.exists("/etc/zaptel.conf")): os.system('/etc/init.d/zaptel restart') os.system('/sbin/ztcfg -vv') def writeConfig(self, *a): """Writes the configuration files for zaptel to load at boot time""" if not PBXUtils.enabled(): print "PBX System is not enabled" return if not self.checkModules(): if not self.installModules(): print "No automatic kernel support for zaptel detected please manually install Zaptel drivers ..." return try: module_config = open(self.modulesconfigfile, 'r') missing_modules = [] missing_modules += self.kernelModules file_lines = module_config.readlines() for module in file_lines: module = module.rstrip() if module in missing_modules: #If the module is in the config remove it from the missing_modules list missing_modules.remove(module) module_config.close() if len(missing_modules) > 0: #If missing_modules has elements we need to add it to the /etc/modules file file_lines = [line.rstrip() for line in file_lines] file_lines += ["","#Generated by vulani configurator"] file_lines += missing_modules module_config = open(self.modulesconfigfile,'wt') module_config.write(str.join('\n', file_lines)) module_config.close() #Load modules self.loadModules() except Exception, _e: print "Error loading config file %s, %s" % (self.modulesconfigfile, str(_e)) try: hardware = PBXUtils.PBXHardware() if "zaptel" in hardware.plugins.keys(): hardware.plugins["zaptel"].save() self.reloadServices() except Exception, _e: print "Error while applying configuration settings", str(_e)
class MultiPort(ZaptelCards.CardEntity): """Sangoma and Digium multiport analog card support""" name = "Analog Multiport" description = "Digium and Sangoma Multiport analog cards" cardParam = [] portParam = [ PBXUtils.PBXCardPortConfig( 'type', "Port Type", "Each analogue port can be either Active(FXS) or Passive(FXO). FXS ports produce a dialtone and therefore a telephone can be plugged into it, where as the FXO does not. It is important to realise that you should never plug two FXS ports into each other as this will likely result in damage", { 'na': 'Empty', 'fxs': 'Active(FXS)', 'fxo': 'Passive(FXO)' }, "na"), PBXUtils.PBXCardPortConfig('signalling', "Port Signalling", "", { 'ks': 'Kewl Start', 'ls': 'Loop Start', 'gs': 'Ground Start' }, 'ks').advanced() ] useSpanHeader = False pluginObject = None def getZaptelConf(self): """Returns a textual representation of the zaptel.conf lines""" output = [] for portInd, portLine in enumerate(self.portLines): if self[portInd]['type'] != 'na': values = self[portInd] values['type'] = values[ 'type'] == 'fxs' and "fxo" or 'fxs' #Hmm crazy zaptel idea that your fxo is your fxs in zapata but the correct way around in zaptel output.append("%(type)s%(signalling)s=" % self[portInd] + str(portLine[0])) return output def getZapataConf(self): """Returns a textual representation of the zapata.conf for Asterisk""" #cProf = briProfiles[self['briconfig']] #Grab the config profile #output = self.mergeConfigList(cProf, briConfigList) output = [] for portInd, portLine in enumerate(self.portLines[:-1]): if self[portInd]['type'] == 'na': continue signalling = str.join( '_', (self[portInd]['type'], self[portInd]['signalling'])) output.append( "group = " + str.join(', ', self.pluginEntity.getPortGroup(portLine[1]))) #Get CallerID output.append("callerid = " + self[portInd]['callerid']) #Get PickupGroup output.append("callgroup = " + self[portInd]['callgroup']) output.append("pickupgroup = " + self[portInd]['pickupgroup']) #Context Bindings output.append("context = " + self[portInd]['context']) output.append("signalling = " + signalling) output.append("channel = " + str(portLine[0])) return output def checkStatus(self): """Card type does not have a status without opening /dev/zap/ctl""" return None def getPortList(self): """ Returns a list object of tuples containing details of the port ('name', state, 'status text'), the index reflects the port number, the state is the current status -1 for error, 0 for normal/idle/inactive, 1 raised state indicates that the port is in use or active """ return [(portDetail[1], "In Use" in str(portDetail[2]) and int(1) or int(0), portDetail[2], portDetail[0]) for portDetail in self.portLines]
def commitUserExtensions(self, form, data): if Settings.sambaDN and self.domain==Settings.defaultDomain and PBXUtils.enabled(): user = data['userSettings.uid'].encode('ascii', 'replace').lower() ext = self.sysconf.PBXExtensions.get(user, { 'enabled': False, 'outbound': [], 'callerID': "", 'voiceMail': False, 'voiceMailPin': '', 'fkeys': [], 'extensions': [], 'devices': [], 'queues': [] }) ext['enabled'] = data['userExtension.userExtEnabled'] ext['outbound'] = [ i.encode('ascii', 'replace') for i in data['userExtension.userExtOutbound'] ] ext['queues'] = [ i.encode('ascii', 'replace') for i in data['userExtension.userExtQueues'] ] if data['userExtension.userExtCallerID']: ext['callerID'] = data['userExtension.userExtCallerID'].encode('ascii', 'replace') else: ext['callerID'] = data['userExtension.userExtNumber0'].encode('ascii', 'replace') oldFullCID = self.sysconf.PBXExtensions.get(user, {'fullcallerID': ""}) ext['fullcallerID'] = """"%s" <%s>""" % (data['cn'][0].encode('ascii','replace'), ext['callerID']) ext['voiceMail'] = data['userExtension.userExtVoiceMail'] if data['userExtension.userExtVoiceMailPin']: ext['voiceMailPin'] = data['userExtension.userExtVoiceMailPin'].encode('ascii', 'replace') else: ext['voiceMailPin'] = '' ext['extensions'] = [] ext['devices'] = [] oldDev = self.sysconf.PBXExtensions.get(user, {'devices':[]})['devices'] for i in range(0,9): if data['userExtension.userExtNumber%s'%i]: ext['extensions'].append(data['userExtension.userExtNumber%s'%i].encode('ascii', 'replace')) if data['userExtension.userExtDev%s'%i]: ext['devices'].append(data['userExtension.userExtDev%s'%i].encode('ascii', 'replace')) restartPhone = False fkeys = [] for i in range(12): fkeys.append(data['userFKeys.fkeys%s'%i]) if 'fkeys' in ext: if ext['fkeys'] != fkeys: restartPhone = True ext['fkeys'] = fkeys for k, devname in enumerate(oldDev): if k < len(ext['devices']): if devname != ext['devices'][k]: restartPhone = True if oldFullCID != ext['fullcallerID']: restartPhone = True if restartPhone: for devname in ext['devices']: dev = devname.split('/') if dev[0] == 'Phone': Asterisk.restartSnom(dev[1]) EXT = self.sysconf.PBXExtensions EXT[user] = ext self.sysconf.PBXExtensions = EXT return True
def commitUserExtensions(self, form, data): def cAscii(val): if type(val) == str: return val.encode('ascii', 'replace') return val if Settings.sambaDN and self.domain == Settings.defaultDomain and PBXUtils.enabled( ): user = data['userSettings.uid'].encode('ascii', 'replace').lower() ext = self.sysconf.PBXExtensions.get( user, { 'enabled': False, 'lowbw': False, 'outbound': [], 'callerID': "", 'voiceMail': False, 'voiceMailPin': '', 'fkeys': [], 'extensions': [], 'devices': [], 'queues': {} }) ext['enabled'] = data['userExtension.userExtEnabled'] if data['userExtension.userExtOutbound']: ext['outbound'] = [ cAscii(i) for i in data['userExtension.userExtOutbound'] ] #if data['userExtension.userExtQueues']: # ext['queues'] = [ # cAscii(i) # for i in data['userExtension.userExtQueues'] # ] #else: # ext['queues'] = [] userQueues = {} for queue in self.sysconf.PBX.get('queues', {}).keys(): penalty = data.get("userExtension.queue%s" % queue, None) if penalty: userQueues[queue.encode('ascii', 'replace')] = penalty ext['queues'] = userQueues if data['userExtension.userExtCallerID']: ext['callerID'] = cAscii(data['userExtension.userExtCallerID']) else: ext['callerID'] = cAscii(data['userExtension.userExtNumber0']) if data['userExtension.userExtTimeout'] > 0: ext['timeout'] = cAscii(data['userExtension.userExtTimeout']) else: if 'timeout' in ext: del ext['timeout'] if data['userExtension.userExtqTimeout'] > 0: ext['qtimeout'] = cAscii(data['userExtension.userExtqTimeout']) else: if 'qtimeout' in ext: del ext['qtimeout'] oldFullCID = self.sysconf.PBXExtensions.get( user, {'fullcallerID': ""}) ext['lowbw'] = data['userExtension.userLowBW'] ext['fullcallerID'] = """"%s" <%s>""" % (data['cn'][0].encode( 'ascii', 'replace'), ext['callerID']) ext['voiceMail'] = data['userExtension.userExtVoiceMail'] if data['userExtension.userExtVoiceMailPin']: ext['voiceMailPin'] = data[ 'userExtension.userExtVoiceMailPin'].encode( 'ascii', 'replace') else: ext['voiceMailPin'] = '' ext['extensions'] = [] ext['devices'] = [] oldDev = self.sysconf.PBXExtensions.get(user, {'devices': []})['devices'] for i in range(0, 9): if data['userExtension.userExtNumber%s' % i]: ext['extensions'].append( cAscii(data['userExtension.userExtNumber%s' % i])) if data['userExtension.userExtDev%s' % i]: ext['devices'].append( cAscii(data['userExtension.userExtDev%s' % i])) restartPhone = False fkeys = [] for i in range(54): fkeys.append(data['userFKeys.fkeys%s' % i]) if 'fkeys' in ext: if ext['fkeys'] != fkeys: restartPhone = True ext['fkeys'] = fkeys for k, devname in enumerate(oldDev): if k < len(ext['devices']): if devname != ext['devices'][k]: restartPhone = True if oldFullCID != ext['fullcallerID']: restartPhone = True if restartPhone: for devname in ext['devices']: dev = devname.split('/') if dev[0] == 'Phone': Asterisk.restartSnom(dev[1]) EXT = self.sysconf.PBXExtensions EXT[user] = ext self.sysconf.PBXExtensions = EXT return True