app.py 17.3 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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
            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)
            # Next we need to originate a call to the other side
            logging.info('Will now connect {} to {}'.format(self.caller, self.callee,))
            payload = {}
            payload['app'] = 'piphone'
            payload['api_key'] = ':'.join([login_ari, token_ari])
            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)
            # And now, just need to add the channel to the bridge
            payload = {}
            payload['app'] = 'piphone'
            payload['api_key'] = ':'.join([login_ari, token_ari])
            payload['channel'] = '{}-{}'.format(self.id, sanitize_phonenumber(self.callee),)
            r = requests.post('http://185.34.33.12:8088/ari/bridges/{}/addChannel'.format(self.id,), data=payload)
okhin's avatar
okhin committed
147
        except AssertionError as e:
148
            logging.error("Received a DTMF sequence out le being in  a '{}' state, ignoring: {}".format(self.state(), event['digit']))
okhin's avatar
okhin committed
149

150
151
152
153
    def change(self, event):
        '''
        Let's change the state of the call
        '''
154
        self.update((':'.join([event['channel']['state'], event['channel']['id'].split('-')[-1]]), event['timestamp'],))
okhin's avatar
okhin committed
155
156
157
        logging.info("New state for call {}: {}".format(event['channel']['id'], event['channel']['state']))
        # We now need to take action according to our new state
        if event['channel']['state'] == 'Up':
158
159
160
161
            # Are we the caller orthe callee?
            if event['channel']['id'].endswith(self.callee):
                # Callee side, let's just move
                return
okhin's avatar
okhin committed
162
163
164
165
166
167
168
169
170
171
172
            # Call is being picked up, we want to play a song
            payload = {}
            try:
                results = self.db.execute('SELECT login_ari, pass_ari FROM users WHERE api = ?', (self.owner,))
                login_ari, token_ari = results.fetchone()
                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
173
                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
174
175
                logging.debug("Now playing a sound on channel {}".format(self.id))
            except Exception as e:
176
                logging.exception(e)
okhin's avatar
okhin committed
177
                raise e
178
179

    def call_caller(self, event):
180
        '''
181
182
183
184
185
186
187
        We want to call the caller. Which needs to be done via a bridge.
        Fisrt we set-up a bridge, then we originate a channel, postfixing the bridge id
        with the caller number.

        And then we connect the caller to the bridge.

        The bridge is a mixed one.
188
        '''
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
        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])
        # Let's establish a bridge over the Kwai River
        try:
            payload['type'] = 'mixing'
            logging.debug("Initiating a bridge for call {}".format(self.id,))
            r = requests.post('http://185.34.33.12:8088/ari/bridges/{}'.format(self.id,), data=payload)
        except Exception as e:
            logging.exception(e)
            raise e

        # Now, let's create the channel
        payload = {}
        payload['app'] = 'piphone'
        payload['api_key'] = ':'.join([login_ari, token_ari])
208
209
210
        try:
            payload['endpoint'] = 'SIP/' + sanitize_phonenumber(self.caller) + '@forfait-kwaoo'
            logging.debug('Preparing to send a request to the ARI with payload {}'.format(payload,))
211
            r = requests.post('http://185.34.33.12:8088/ari/channels/{}-{}'.format(self.id, sanitize_phonenumber(self.caller),), data=payload)
212
        except Exception as e:
213
214
215
216
217
218
219
220
221
222
223
224
            logging.exception(e)
            raise e
        # Let's connect the channel to the bridge.
        payload = {}
        payload['app'] = 'piphone'
        payload['api_key'] = ':'.join([login_ari, token_ari])
        try:
            payload['channel'] = '{}-{}'.format(self.id, sanitize_phonenumber(self.caller),)
            logging.debug("Connection the channel to the bridge for call {}".format(self.id,))
            r = requests.post('http://185.34.33.12:8088/ari/bridges/{}/addChannel'.format(self.id,), data=payload)
        except Exception as e:
            logging.exception(e)
225
226
227
            raise e

    def save(self):
228
229
230
        '''
        Save the Call to database.
        '''
231
232
233
234
235
236
237
        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:
238
            logging.exception(e)
239
            raise e
240

okhin's avatar
okhin committed
241
def authenticated(f):
okhin's avatar
okhin committed
242
243
244
245
246
247
248
249
    '''
    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
250
251
    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
252
        logging.debug("Authetication: {}".format([':'.join([key, request.params[key]]) for key in request.params],))
okhin's avatar
okhin committed
253
        if 'token' not in request.params:
okhin's avatar
okhin committed
254
            logging.error("No token found in the params")
okhin's avatar
okhin committed
255
            abort(401, "No token found in the query")
okhin's avatar
okhin committed
256
257
        # We want the api id in the params to.
        if 'api' not in request.params:
okhin's avatar
okhin committed
258
            logging.error("No api id found in the params")
okhin's avatar
okhin committed
259
            abort(401, "No api id found in the params")
okhin's avatar
okhin committed
260
261
262
263
264
265
266
        # 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
267
268
            for key in auth_token:
                request.params[key] = auth_token[key]
okhin's avatar
okhin committed
269
        except (jwt.exceptions.InvalidTokenError, AssertionError) as e:
okhin's avatar
okhin committed
270
            logging.error("Access refused")
271
            logging.exception(e)
okhin's avatar
okhin committed
272
273
274
275
276
277
            abort(403, e)
        except Exception as e:
            abort(500, e)
        return f(db, *args, **kwargs)
    return wrapped

278
279
280
281
282
283
284
285
286
287
288
289
290
291
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
292
        self.logger = logging.getLogger('server')
293
294
        if debug:
            self.logger.setLevel(logging.DEBUG)
okhin's avatar
okhin committed
295
        self.logger.addHandler(logging.FileHandler('app.log'))
296
297
298
299
300
301
302
        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
303
304
305
        ws_logger = logging.getLogger('websockets')
        ws_logger.setLevel(logging.DEBUG)
        ws_logger.addHandler(logging.FileHandler('app.log'))
306
307
        async with websockets.connect('ws://185.34.33.12:8088/ari/events?app=piphone&api_key=piphone:passpiphone') as websocket:
            while self.running == True:
okhin's avatar
okhin committed
308
                ws_logger.info("Waiting for events on websocket")
309
310
311
312
313
314
315
316
317
318
319
                event = await websocket.recv()
                # Let's call the applications function
                await self.dispatch(json.loads(event))
                # This is now where I want to create callbacks from events

    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,))
320
        # Let's get the call ID, the call id isthe channel id minus the last -part.
321
322
323
        if 'channel' not in event:
            self.logger.debug('Not a channel event, skip')
            return
324
325
        call_id = re.sub('-\d+$', '', event['channel']['id'])
        call = Call.load(call_id, self.db)
326
        call.event_handler(event)
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342

    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)
        
343
@app.get('/calls/<callid>')
344
@app.get('/calls/')
okhin's avatar
okhin committed
345
@authenticated
346
def calls(db, callid=None):
okhin's avatar
okhin committed
347
348
349
350
    """
    Return the list of calls associated to the connected user.
    The call has a status, caller, callee and history (status change+timestamp)
    """
351
352
353
354
355
356
357
358
359
360
361
362
    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:
363
            logging.exception(e)
364
365
366
367
368
369
370
371
372
373
374
375
            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
376
        logging.debug("Not exactly one results found, this is an issue")
377
378
379
380
381
382
383
384
385
        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>')
386
@authenticated
387
388
389
390
391
392
393
394
395
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()
396
397
            , 'user': request.params['api']
            , 'hits': 1}
398
399
400
        return {'header': head, 'data': call}
    except Exception as e:
        logging.debug("Missing params : {}".format([p for p in request.params],))
401
        logging.exception(e)
402
        abort(400, "Missing or incorrect fields, the call cannot be processed")
403
404
405
406
407
408
409
410
411

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:
412
        logging.exception(e)
413
414
        server.stop()
        raise e