Esempio n. 1
0
File: PBX.py Progetto: calston/tums
    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, ';')
Esempio n. 2
0
File: PBX.py Progetto: calston/tums
    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)