asterisk.py 11.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#!/usr/bin/env python
# -*- coding: utf-8 -
# liste d'event http://www.voip-info.org/wiki/view/asterisk+manager+events
# liste d'action http://www.voip-info.org/wiki/view/Asterisk+manager+API
import os
import sys
import time
import errno
import shutil
import syslog
import socket
import base64
import psycopg2
from datetime import datetime

sys.path.append('/usr/scripts/')
import lc_ldap.shortcuts

class NullRecv(EnvironmentError):
    pass
    
22 23 24
class AsteriskError(ValueError):
    pass

25
class Profile(object):
Valentin Samir's avatar
Valentin Samir committed
26
    def __init__(self, sql_params=None, database=None):
27 28 29 30 31 32 33 34 35 36
        self.sql_params = sql_params
        self.database =database
        
    def update_pin(self, num, pin):
        conn = psycopg2.connect(self.sql_params)
        cur = conn.cursor()
        cur.execute("UPDATE %s SET voicemail_password=%%s WHERE num=%%s" % self.database, (pin, num))
        conn.commit()
        cur.close()
        conn.close()
Valentin Samir's avatar
Valentin Samir committed
37 38 39 40 41 42 43 44 45 46 47

    def alias_to_num(self, alias):
        try:
            conn=lc_ldap.shortcuts.lc_ldap_readonly()
            ret=conn.search(u"(|(uid=%(alias)s)(mailAlias=%(alias)s@crans.org)(canonicalAlias=%(alias)s@crans.org))" % {'alias' : alias})
            if len(ret) == 1:
                return "1" + str(ret[0]['aid'][0])
            else:
                return "NONE"
        except:
            return "NONE"
48 49 50 51 52 53 54 55 56 57 58
        
    def num_to_callerid(self, num):
        try:
            conn = psycopg2.connect(self.sql_params)
            cur = conn.cursor()
            cur.execute("SELECT caller_id from %s WHERE num=%%s" % self.database, (num,))
            caller_id = cur.fetchall()[0][0]
            cur.close()
            conn.close()
            
            if caller_id == 'full_name' or caller_id == 'both':
59
                conn=lc_ldap.shortcuts.lc_ldap_readonly()
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
                aid=int(num[1:])
                adh=conn.search(u'aid=%s' % aid)[0]
                return '%s %s' % (adh['prenom'][0],adh['nom'][0])
            else:
                return num
        except:
            return num

class Sms(object):
    def __init__(self,sms_dir):
        self.sms_dir=sms_dir

    def sms_daemon(self, server,port,user,password, timeout=360):
        manager = Manager(user, password, server=server, event=True, auto_connect=False, timeout=timeout)
        manager.register_events_callback('PeerStatus', self._send_sms)
        while True:
            manager.connect()
            try:
                while True:
                    manager.process_events()
            except (socket.error, asterisk.NullRecv):
                pass
                
Valentin Samir's avatar
Valentin Samir committed
83
    def _mkdirs(self, path):
84 85 86 87 88 89 90 91 92 93
        try:
            os.makedirs(path)
        except OSError as exc:
            if exc.errno == errno.EEXIST and os.path.isdir(path):
                pass
            else: raise
                
    def sms_delay(self, src, dst, body, user, body_type='str'):
        if not body_type in ["str", "base64"]:
            raise EnvironmentError("body_type sould be 'str' ou 'base64' not %r" % body_type)
Valentin Samir's avatar
Valentin Samir committed
94 95 96 97 98 99 100 101 102 103
        date = datetime.now().strftime('%Y%m%d%H%M%S.%f')
        path = self.sms_dir + user + '/' + date + '/'
        self._mkdirs(path)
        with open(path + 'from', 'w') as f:
            f.write(src)
        with open(path + 'to', 'w') as f:
            f.write(dst)
        with open(path + 'body', 'w') as f:
            if body_type=='str':
                f.write(base64.encodestring(body).strip())
104 105
            elif body_type=='base64':
                f.write(body)
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
            
            

    def _send_sms(self, manager, params):
        if params['PeerStatus'] in ['Reachable','Registered']:
            num = params['Peer'].split('/')[1]
            if os.path.isdir(self.sms_dir + '/' + num + '/'):
                dir=os.listdir(self.sms_dir + '/' + num + '/')
                dir.sort()
                for sms in dir:
                    sms_path=self.sms_dir + '/' + num + '/' + sms + '/'
                    if os.path.isfile(sms_path + 'from') and os.path.isfile(sms_path + 'to') and os.path.isfile(sms_path + 'body'):
                        sms_from=open(sms_path + 'from').read()
                        sms_to=open(sms_path + 'to').read()
                        sms_body=open(sms_path + 'body').read()
                        status, params = manager.messageSend(sms_from, sms_to, sms_body, body_type='base64')
                        if status == 'Success':
                            syslog.syslog("Message from %s successfully delivered to %s" % (sms_from, sms_to))
                            shutil.rmtree(sms_path)
                            try:
                                os.rmdir(self.sms_dir + '/' + num + '/')
                            except OSError:
                                pass
                        elif status == 'Error':
                            syslog.syslog("Message from %s to %s : %s" % (sms_from, sms_to, params['Message']))

class History(object):
    def __init__(self, sql_params, database, quota_limit):
        self.sql_params = sql_params
        self.database =database
        self.quota_limit = quota_limit

    def add(self, id, src, dst):
        conn = psycopg2.connect(self.sql_params)
        cur = conn.cursor()
        cur.execute("INSERT INTO %s (uniq_id,src,dst) VALUES (%%s, %%s, %%s)" % self.database, (id, src, dst))
        conn.commit()
        cur.close()
        conn.close()
        
    def delete(self, id):
        conn = psycopg2.connect(self.sql_params)
        cur = conn.cursor()
        cur.execute("DELETE FROM %s WHERE uniq_id=%%s" % self.database, (id,))
        conn.commit()
        cur.close()
        conn.close()
        
    def update(self, id, duration):
        conn = psycopg2.connect(self.sql_params)
        cur = conn.cursor()
        cur.execute("UPDATE %s SET duration=%%s WHERE uniq_id=%%s" % self.database, (int(duration), id))
        conn.commit()
        cur.close()
        conn.close()
        
    def quota(self, number):
        allowed = False
        try:
            conn = psycopg2.connect(self.sql_params)
            cur = conn.cursor()
            cur.execute("SELECT count(DISTINCT dst) FROM %s WHERE date>='%s' AND dst LIKE '+%%'" % (self.database, time.strftime('%Y-%m-01')))
            outgoing_call_num = cur.fetchall()[0][0]
            if outgoing_call_num >= self.quota_limit:
                cur.execute("SELECT count(dst)>0 FROM %s WHERE date>'%s' AND dst=%%s" % (self.database, time.strftime('%Y-%m-01')), (number,))
                allowed = cur.fetchall()[0][0]
            else:
                allowed = True
            cur.close()
            conn.close()
        except:
            pass
        sys.stdout.write('ALLOWED' if allowed  else 'DENY')

class Manager(object):
    
    def __init__(self, username, password, timeout=10, server='asterisk.adm.crans.org', port=5038, debug=False, event=False, auto_connect=True):
        self.timeout = timeout
        self.server = server
        self.port = port
        self.socket = None
        self.debug = debug
        self.event = event
        self._pending_action=[]
        self._response={}
        self._event=[]
        self._event_callback = {}
        self._toread = ""
194
        self.fullybooted = False
195 196 197 198 199 200 201 202 203
        
        self.username = username
        self.password = password
        
        self.register_events_callback('FullyBooted', self._FullyBooted)
        if auto_connect:
            self.connect()
            
    def _FullyBooted(self, manager, params):
204
        manager.fullybooted = True
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
        
    def _recv(self):
        data = self.socket.recv(1024)
        if len(data) == 0:
            raise NullRecv("Got null response")
        self._toread += data
        self._toread = self._toread.split('\r\n\r\n')
        for msg in self._toread[:-1]:
            if self.debug:
                print msg + "\n"
            self._parse_msg(msg)
        self._toread=self._toread[-1]
        
    def _send(self, str):
        if self.debug:
            print str
        self.socket.send ('%s\r\n' % (str))
        
    def _parse_msg(self, msg):
        msg = msg.strip().split('\r\n')
        type, value = msg[0].split(': ', 1)
        params = dict([line.split(': ', 1) for line in msg[1:]])
        handler = getattr(self, "_do_"+type, None)
        handler(value, params)
        
    def _do_Response(self, status, params):
        id = params['ActionID']
        del(params['ActionID'])
        self._response[id] = (status, params)
        
    def _do_Event(self, type, params):
        self._event.append((type, params))

        
    def _gen_actionID(self):
        id=time.time()
        while id in self._pending_action:
            id=id+1
        return str(id)
        
    def _action(self, name, params):
        self._send ('ACTION: %s' % name.upper())
        for (key, value) in params.items():
            self._send ('%s: %s' % (key.upper(), value))
        id=self._gen_actionID()
        self._send ('ActionID: %s' % id)
        self._pending_action.append(id)
        self._send ('')
        
        while not id in self._response.keys():
            self._recv()
        
        response = self._response[id]
        del(self._response[id])
        self._pending_action.remove(id)
        if response[0] == 'Error':
261
            raise AsteriskError('%s. Action:%s params:%s' % (response[1]['Message'], name, params))
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
        return response
        
    def action(self, name, **params):
        return self._action(name, params)
        
    def connect(self):
        sock = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
        sock.settimeout(self.timeout)
        sock.connect ( ( self.server, self.port ) )
        self.socket=sock
        msg = self.socket.recv(1024).strip().split('\r\n', 1)
        self.version = msg[0]
        if len(msg)>1:
            self._toread += msg[1]
        self.login()
277 278
        while not self.fullybooted:
            self.process_events()
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
        self.events(self.event)
            
    def register_events_callback(self, event, func):
        self._event_callback[event] = self._event_callback.get(event, []) + [func]
        
    def process_events(self):
        if not self._event:
            try: self._recv()
            except socket.timeout: pass
        for event in self._event:
            (type, params) = event
            for func in self._event_callback.get(type, []):
                func(self, params)
        self._event=[]
        
        
    def login(self, username=None, secret=None):
        """Login Manager"""
        if username is None: username = self.username
        if secret is None: secret = self.password
        return self.action('login', username=username, secret=secret)
        
    def logoff(self):
        """ Logoff Manager"""
303 304 305
        response = self.action('logoff')
        if response[0] == 'Goodbye':
            self.fullybooted = False
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
        
    def events(self, param):
        """Control Event Flow
        params should be a boolean or a list among system,call,log,verbose,command,agent,user to select
        which flags events should have to be sent."""
        if isinstance(param, list):
            eventmask = ','.join(param)
        elif isinstance(param, bool):
            eventmask = 'on' if param else 'off'
        else:
            raise EnvironmentError("%r should be a list or a bool" % param)
        return self.action('events',  eventmask=eventmask)
        
    def reload(self, module):
        """Synopsis: Send a reload event
            Privilege: system,config,all"""
        privilege = ['system', 'config', 'all']
        return self.action('reload', module=module)
        
    def messageSend(self, src, dst, body, body_type="str"):
        if not body_type in ["str", "base64"]:
            raise EnvironmentError("body_type sould be 'str' ou 'base64' not %r" % body_type)
        if body_type == "str":
329
            body = base64.b64encode(body).strip()
330
        return self._action('messageSend', {'to':dst, 'from':src, 'base64body':body})