app.py 18 KB
Newer Older
okhin's avatar
okhin committed
1
2
3
#!/usr/bin/env python

import sqlite3
okhin's avatar
okhin committed
4
5
6
import datetime
import uuid
import json
7
8
9
import logging
import concurrent.futures
import asyncio
10
import re
11
from wsgiref.simple_server import make_server
okhin's avatar
okhin committed
12
from operator import itemgetter
okhin's avatar
okhin committed
13

14
from bottle import request, abort, Bottle, ServerAdapter, JSONPlugin
okhin's avatar
okhin committed
15
16
from bottle_sqlite import SQLitePlugin
import jwt
17
18
import websockets
import requests
okhin's avatar
okhin committed
19

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
logging.basicConfig(filename='app.log', level=logging.DEBUG) 
app = Bottle(autojson=False)

class PiphoneJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        """
        We need to implement this to be able to JSONEncode
        """
        if isinstance(obj, Call):
            return {  'caller': obj.caller
                , 'callee': obj.callee
                , 'callid': obj.id
                , 'url': obj.url()
                , 'history': obj.history
                , 'owner': obj.owner }
        else:
36
            return json.JSONEncoder.default(self, obj)
okhin's avatar
okhin committed
37

okhin's avatar
okhin committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def sanitize_phonenumber(number):
    """
    This function is used to sanitize a phone number.
    If it starts with a +, it will be removed and replaced by 00.
    Any chars who do notbelong to [0-9] will be stripped.
    If the number doesn't starts with 00, a TypeError will be raised
    """
    if number[0] == '+':
        number = '00' + number[1:]
    number = ''.join([c for c in number if c in '0123456789'])
    if not number.startswith('00'):
        raise TypeError('{} is not a valid international number, it should start with 00')
    return number

52
class Call(object):
okhin's avatar
okhin committed
53
54
55
    """
    This Class is used to manage operatiosn on a call, to print it and dump it.
    """
56
    history = []
57
    actions = {'Created': 'call_caller'
okhin's avatar
okhin committed
58
59
60
            , 'ChannelStateChange': 'change'
            , 'ChannelDtmfReceived': 'dtmf'}

61
    def __init__(self, caller, callee, owner, callid=None, db=None):
okhin's avatar
okhin committed
62
63
64
65
        try:
            self.caller = caller
            self.callee = callee
            self.owner = owner
66
            if callid == None:
67
68
                self.id = str(uuid.uuid4())
                self.db = db
69
                self.event_handler({'type': 'Created', 'timestamp': datetime.datetime.now().isoformat(), 'channel': {'id': 'Init'}})
70
71
            else:
                self.id = callid
okhin's avatar
okhin committed
72
        except Exception as e:
73
            logging.exception(e)
okhin's avatar
okhin committed
74
75
76
77
78
            raise e

    def url(self):
        return ''.join(['/calls/', self.id])

okhin's avatar
okhin committed
79
80
81
82
    def state(self):
        sort = sorted(self.history, reverse=True, key=itemgetter(1))
        return sort[0][0]

okhin's avatar
okhin committed
83
84
    @classmethod
    def load(cls, callid, db):
85
        logging.debug("Loading call {}".format(callid,))
okhin's avatar
okhin committed
86
        try:
87
            results = db.execute('SELECT caller, callee, owner, callid, history FROM calls WHERE callid = ?;', (callid,))
okhin's avatar
okhin committed
88
            result = results.fetchone()
89
90
            assert len(result) == 5
            object = cls(result[0], result[1], result[2], result[3])
okhin's avatar
okhin committed
91
            object.history = json.loads(result[4])
92
            object.db = db
okhin's avatar
okhin committed
93
            return object
94
        except Exception as e:
95
            logging.exception(e)
96
            raise e
okhin's avatar
okhin committed
97

98
    def update(self, new_state):
99
        '''
100
        Let's update the state of the call. new_state is a tuple in the form (newstate, timestamp,)
101
102
103
104
        '''
        logging.debug("Got a new state: {}".format(new_state,))
        self.history.append(new_state)
        self.save()
105
106
107
108
109
110

    def event_handler(self, event):
        '''
        There's a new event related to our call
        '''
        state = event['type']
111
        if state in self.actions:
112
            getattr(self, self.actions[state])(event=event)
113

okhin's avatar
okhin committed
114
115
116
117
118
    def dtmf(self, event):
        '''
        We received a DTMF sequence
        '''
        try:
119
            assert self.state().startswith('Up')
okhin's avatar
okhin committed
120
            # The only thing we want to do is to call the callee if we press 1
121
122
123
124
125
126
127
128
129
130
131
132
            if event['digit'] != '1':
                return
            # Now, we're connectig the other side
            # But first we should stop the playback
            results = self.db.execute('SELECT login_ari, pass_ari FROM users WHERE api = ?', (self.owner,))
            login_ari, token_ari = results.fetchone()
            payload = {}
            payload['app'] = 'piphone'
            payload['api_key'] = ':'.join([login_ari, token_ari])
            logging.debug('Stopping the playback currently running'.format(payload,))
            # We're stoping the playback, with the same ID as the channel, to keep track of it
            r = requests.delete('http://185.34.33.12:8088/ari/playbacks/{0}'.format(event['channel']['id']), data=payload)
okhin's avatar
okhin committed
133
134
135
136
            # Now we're moving the channel to the MOH Bridge
            payload['channel'] = event['channel']['id']
            logging.debug('Moving call {} to the garage'.format(payload['channel']))
            r = requests.post('http://185.34.33.12:8088/ari/bridges/piphone-moh/addChannel', data=payload)
137
138
139
140
141
            # Next we need to originate a call to the other side
            logging.info('Will now connect {} to {}'.format(self.caller, self.callee,))
            payload['endpoint'] = 'SIP/' + sanitize_phonenumber(self.callee) + '@forfait-kwaoo'
            logging.debug('Preparing to send a request to the ARI with payload {}'.format(payload,))
            r = requests.post('http://185.34.33.12:8088/ari/channels/{}-{}'.format(self.id, sanitize_phonenumber(self.callee),), data=payload)
okhin's avatar
okhin committed
142
        except AssertionError as e:
143
            logging.error("Received a DTMF sequence out le being in  a '{}' state, ignoring: {}".format(self.state(), event['digit']))
okhin's avatar
okhin committed
144

145
146
147
148
    def change(self, event):
        '''
        Let's change the state of the call
        '''
149
        self.update((':'.join([event['channel']['state'], event['channel']['id'].split('-')[-1]]), event['timestamp'],))
okhin's avatar
okhin committed
150
151
        logging.info("New state for call {}: {}".format(event['channel']['id'], event['channel']['state']))
        # We now need to take action according to our new state
okhin's avatar
okhin committed
152
153
        results = self.db.execute('SELECT login_ari, pass_ari FROM users WHERE api = ?', (self.owner,))
        login_ari, token_ari = results.fetchone()
okhin's avatar
okhin committed
154
        if event['channel']['state'] == 'Up':
155
156
            # Are we the caller orthe callee?
            if event['channel']['id'].endswith(self.callee):
okhin's avatar
okhin committed
157
158
159
160
161
162
163
164
165
166
167
168
                # Step 1 create a bridge
                payload = {}
                payload['app'] = 'piphone'
                payload['api_key'] = ':'.join([login_ari, token_ari])
                payload['type'] = 'mixing'
                logging.debug("Creating a bridges to connect {} to {}".format(self.caller, self.callee,))
                r = requests.post('http://185.34.33.12:8088/ari/bridges/{}'.format(self.id), data=payload)
                # Step 2, moving channels
                payload['channel'] = ",".join([self.id + '-' + self.caller, self.id + '-' + self.callee])
                logging.debug("Moving channels to the created bridge: {}".format(payload['channel']))
                r = requests.post('http://185.34.33.12:8088/ari/bridges/{}/addChannel'.format(self.id), data=payload)
                logging.info("Call now fully connected: {} <-> {}".format(self.caller, self.callee))
169
                return
okhin's avatar
okhin committed
170
171
172
173
174
175
176
177
178
            # Call is being picked up, we want to play a song
            payload = {}
            try:
                payload['app'] = 'piphone'
                payload['api_key'] = ':'.join([login_ari, token_ari])
                payload['media'] = 'sound:mario'
                payload['lang'] = 'en_US'
                logging.debug('Preparing to send a request to the ARI with payload {}'.format(payload,))
                # We're starting a playback, with the same ID as the channel, to keep track of it
179
                r = requests.post('http://185.34.33.12:8088/ari/channels/{0}/play/{0}'.format(event['channel']['id']), data=payload)
okhin's avatar
okhin committed
180
181
                logging.debug("Now playing a sound on channel {}".format(self.id))
            except Exception as e:
182
                logging.exception(e)
okhin's avatar
okhin committed
183
                raise e
184
185

    def call_caller(self, event):
186
        '''
okhin's avatar
okhin committed
187
188
        Let's call the caller. It's a simple originate. We will also check if the MoH bridge is ready,
        because it will be used to store people in it waiting for the callee to pick up the phone.
189

okhin's avatar
okhin committed
190
        The bridge needed to connect the calls together will be created later.
191
        '''
192
193
194
195
196
197
        self.update((':'.join([event['type'], event['channel']['id'].split('-')[-1]]), event['timestamp'],))
        results = self.db.execute('SELECT login_ari, pass_ari FROM users WHERE api = ?', (self.owner,))
        login_ari, token_ari = results.fetchone()
        payload = {}
        payload['app'] = 'piphone'
        payload['api_key'] = ':'.join([login_ari, token_ari])
okhin's avatar
okhin committed
198
        # We want to check if the moh bridge is opened
199
        try:
okhin's avatar
okhin committed
200
201
202
203
204
            r = requests.get('http://185.34.33.12:8088/ari/bridges/{}-moh'.format(payload['app']), data=payload)
            r.raise_for_status()
        except HTTPError as e:
            # The bridge dos not exist
            logging.error("The Hold bridges does not exists")
205
206
207
208
209
210
            raise e

        # Now, let's create the channel
        payload = {}
        payload['app'] = 'piphone'
        payload['api_key'] = ':'.join([login_ari, token_ari])
211
212
213
        try:
            payload['endpoint'] = 'SIP/' + sanitize_phonenumber(self.caller) + '@forfait-kwaoo'
            logging.debug('Preparing to send a request to the ARI with payload {}'.format(payload,))
214
            r = requests.post('http://185.34.33.12:8088/ari/channels/{}-{}'.format(self.id, sanitize_phonenumber(self.caller),), data=payload)
215
        except Exception as e:
216
217
            logging.exception(e)
            raise e
218
219

    def save(self):
220
221
222
        '''
        Save the Call to database.
        '''
223
224
225
226
227
228
229
        logging.debug("Saving call {}: {}".format(self.id, json.dumps(self, cls=PiphoneJSONEncoder)))
        try:
            self.db.execute('''INSERT OR REPLACE INTO calls (caller, callee, owner, callid, history)
                VALUES (?, ?, ?, ?, ?) '''
                , (self.caller, self.callee, self.owner, self.id, json.dumps(self.history)))
            self.db.commit()
        except Exception as e:
230
            logging.exception(e)
231
            raise e
232

okhin's avatar
okhin committed
233
def authenticated(f):
okhin's avatar
okhin committed
234
235
236
237
238
239
240
241
    '''
    We need a decorator to check if our query is authenticated.
    We will store an API key and SECRET in ur database, the client
    needs to have both of them.
    He must then send us a JWT token with an API claim in the payload.
    The JWT token must be encoded and signed with the SECRET. If the
    token is bad, we return a 403.
    '''
okhin's avatar
okhin committed
242
243
    def wrapped(db, *args, **kwargs):
        # Let's get the JWT token. It should be a params (from get or post or whatev')
okhin's avatar
okhin committed
244
        logging.debug("Authetication: {}".format([':'.join([key, request.params[key]]) for key in request.params],))
okhin's avatar
okhin committed
245
        if 'token' not in request.params:
okhin's avatar
okhin committed
246
            logging.error("No token found in the params")
okhin's avatar
okhin committed
247
            abort(401, "No token found in the query")
okhin's avatar
okhin committed
248
249
        # We want the api id in the params to.
        if 'api' not in request.params:
okhin's avatar
okhin committed
250
            logging.error("No api id found in the params")
okhin's avatar
okhin committed
251
            abort(401, "No api id found in the params")
okhin's avatar
okhin committed
252
253
254
255
256
257
258
        # Now, let's get the token on our side
        try:
            results = db.execute('SELECT token FROM users WHERE api = ?', (request.params['api'],)).fetchall()
            assert len(results) == 1
            token = results[0][0]
            auth_token = jwt.decode(request.params['token'], token)
            assert auth_token['api'] == request.params['api']
okhin's avatar
okhin committed
259
260
            for key in auth_token:
                request.params[key] = auth_token[key]
okhin's avatar
okhin committed
261
        except (jwt.exceptions.InvalidTokenError, AssertionError) as e:
okhin's avatar
okhin committed
262
            logging.error("Access refused")
263
            logging.exception(e)
okhin's avatar
okhin committed
264
265
266
267
268
269
            abort(403, e)
        except Exception as e:
            abort(500, e)
        return f(db, *args, **kwargs)
    return wrapped

270
271
272
273
274
275
276
277
278
279
280
281
282
283
class Server(ServerAdapter):
    """
    This class manage all that is needed to run the REST App of the piphone. It is in charge of
    launching an Executor, start the event loop in its own thread and run the bottle app.
    """
    server = None
    running = False
    options = None
    callbacks = {}

    def __init__(self, debug=False, *args, **kwargs):
        """
        We're starting the logger subsytem, create the Thread Pool and stuff
        """
okhin's avatar
okhin committed
284
        self.logger = logging.getLogger('server')
285
286
        if debug:
            self.logger.setLevel(logging.DEBUG)
okhin's avatar
okhin committed
287
        self.logger.addHandler(logging.FileHandler('app.log'))
288
289
290
291
292
293
294
        self.threads = concurrent.futures.ThreadPoolExecutor()
        self.loop = asyncio.get_event_loop()
        self.db = sqlite3.connect('call.db')

        super(Server, self).__init__(*args, **kwargs)

    async def __listen(self):
okhin's avatar
okhin committed
295
296
297
        ws_logger = logging.getLogger('websockets')
        ws_logger.setLevel(logging.DEBUG)
        ws_logger.addHandler(logging.FileHandler('app.log'))
298
        async with websockets.connect('ws://185.34.33.12:8088/ari/events?app=piphone&api_key=piphone:passpiphone') as websocket:
okhin's avatar
okhin committed
299
            await self.hold_bridges()
300
            while self.running == True:
okhin's avatar
okhin committed
301
                ws_logger.info("Waiting for events on websocket")
302
303
304
305
306
307
308
309
310
311
                event = await websocket.recv()
                # Let's call the applications function
                await self.dispatch(json.loads(event))

    async def dispatch(self, event):
        """
        Let's work on our events. Parse them and do request on the ARI API. Event is
        a dict loaded from JSON.
        """
        self.logger.debug('Event received: {}'.format(event,))
312
        # Let's get the call ID, the call id isthe channel id minus the last -part.
313
314
315
        if 'channel' not in event:
            self.logger.debug('Not a channel event, skip')
            return
316
317
        call_id = re.sub('-\d+$', '', event['channel']['id'])
        call = Call.load(call_id, self.db)
318
        call.event_handler(event)
319

okhin's avatar
okhin committed
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
    async def hold_bridges(self):
        '''
        We will create a bridge that will be used to park caller waiting for callee to join.
        It will play a song in a loop.
        '''
        payload = {}
        payload['app'] = 'piphone'
        payload['api_key'] = 'piphone:passpiphone'
        payload['mode'] = 'holding'
        try:
            r = requests.post('http://185.34.33.12:8088/ari/bridges/piphone-moh', data=payload)
            r.raise_for_status()
            payload['mohClass'] = 'piphone'
            r = requests.post('http://185.34.33.12:8088/ari/bridges/piphone-moh/moh', data=payload)
            r.raise_for_status()
        except Exception as e:
            logging.error("Cannot start MOH Bridges")
            logging.exception(e)
            raise e

340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
    def run(self, handler):
        """
        We're starting the REST application, and the launch applications
        """
        self.running = True
        self.server = make_server('127.0.0.1', 8080, handler, **self.options)
        self.threads.submit(self.server.serve_forever)
        self.loop.run_until_complete(self.__listen())

    def stop(self):
        self.running = False
        self.loop.close()
        self.server.shutdown()
        self.threads.shutdown(wait=False)
        
355
@app.get('/calls/<callid>')
356
@app.get('/calls/')
okhin's avatar
okhin committed
357
@authenticated
358
def calls(db, callid=None):
okhin's avatar
okhin committed
359
360
361
362
    """
    Return the list of calls associated to the connected user.
    The call has a status, caller, callee and history (status change+timestamp)
    """
363
364
365
366
367
368
369
370
371
372
373
374
    logging.debug("GET {}".format(request.fullpath))
    if callid == None:
        try:
            results = db.execute('SELECT callid FROM calls WHERE owner = ?;', (request.params['api'],))
            calls = []
            for row in results.fetchall():
                call = Call.load(row[0], db)
                logging.debug("Call fetched: {}".format(json.dumps(call, cls=PiphoneJSONEncoder)))
                calls.append(call)
            head = {'call': request.fullpath, 'user': request.params['api'], 'hits': len(calls)}
            return {'head': head, 'data': calls}
        except Exception as e:
375
            logging.exception(e)
376
377
378
379
380
381
382
383
384
385
386
387
            abort(500, "Exception")
    # We first need to check if we can access the callid we asked for
    try:
        results = db.execute('SELECT callid FROM calls WHERE owner = ? AND callid = ? ;'
                , (request.params['api'], callid,))
        rows = results.fetchall()
        logging.debug("Found {} results: {}".format(len(rows), rows))
        assert len(rows) == 1
        call = Call.load(callid, db)
        head = {'call': call.url(), 'user': request.params['api'], 'hits': 1}
        return {'head': head, 'data': call}
    except AssertionError as e:
okhin's avatar
okhin committed
388
        logging.debug("Not exactly one results found, this is an issue")
389
390
391
392
393
394
395
396
397
        logging.error("Unauthorized access to call {} from user {}".format(callid, request.params['api']))
        abort(403, "You do not have the authorization to get this call")
    except Exception as e:
        logging.debug("Exception catched: {}".format(e,))
        logging.error("Call not found {}".format(callid,))
        abort(404, "This call does not exist")

@app.post('/calls/')
@app.post('/calls/<callid>')
398
@authenticated
399
400
401
402
403
404
405
406
407
def originate(db, callid=None):
    logging.debug("POST {}".format(request.fullpath))
    try:
        if callid is not None:
            call = Call(request.params['caller'], request.params['callee'], request.params['api'], callid=request.params['callid'], db=db)
        else:
            call = Call(request.params['caller'], request.params['callee'], request.params['api'], db=db)
        logging.debug("Originate a call: {}".format(json.dumps(call, cls=PiphoneJSONEncoder)))
        head = {'call': call.url()
408
409
            , 'user': request.params['api']
            , 'hits': 1}
410
411
412
        return {'header': head, 'data': call}
    except Exception as e:
        logging.debug("Missing params : {}".format([p for p in request.params],))
413
        logging.exception(e)
414
        abort(400, "Missing or incorrect fields, the call cannot be processed")
415
416
417
418
419
420
421
422
423

if __name__ == '__main__':
    app.install(SQLitePlugin(dbfile='call.db'))
    app.install(JSONPlugin(json_dumps=lambda s: json.dumps(s, cls=PiphoneJSONEncoder)))

    server=Server()
    try:
        app.run(server=server)
    except Exception as e:
424
        logging.exception(e)
425
426
        server.stop()
        raise e