app.py 15.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
10
import logging
import concurrent.futures
import asyncio
from wsgiref.simple_server import make_server
okhin's avatar
okhin committed
11
from operator import itemgetter
okhin's avatar
okhin committed
12

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

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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:
35
            return json.JSONEncoder.default(self, obj)
okhin's avatar
okhin committed
36

okhin's avatar
okhin committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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

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

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

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

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

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

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

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

okhin's avatar
okhin committed
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
    def dtmf(self, event):
        '''
        We received a DTMF sequence
        '''
        try:
            assert self.state() == 'Up'
            # The only thing we want to do is to call the callee if we press 1
            if event['digit'] == '1':
                # 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 starting a 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(self.id), data=payload)
                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/forfait-kwaoo/' + sanitize_phonenumber(self.callee)
                r = requests.post('http://185.34.33.12:8088/ari/channels/{}/redirect'.format(self.id), data=payload)
        except AssertionError as e:
            logging.debug("Received a DTMF sequence out le being in  a '{}' state, ignoring: {}".format(self.state(), event['digit']))

140
141
142
143
144
    def change(self, event):
        '''
        Let's change the state of the call
        '''
        self.update((event['channel']['state'], event['timestamp'],))
okhin's avatar
okhin committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
        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':
            # 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
                r = requests.post('http://185.34.33.12:8088/ari/channels/{0}/play/{0}'.format(self.id), data=payload)
                logging.debug("Now playing a sound on channel {}".format(self.id))
            except Exception as e:
                logging.debug("Exception raised in change(): {} - event was {}".format(e, event,))
                raise e
164
165

    def call_caller(self, event):
166
167
168
        '''
        Let's do a request on the ARI system
        '''
169
        self.update((event['type'], event['timestamp'],))
170
        try:
171
            results = self.db.execute('SELECT login_ari, pass_ari FROM users WHERE api = ?', (self.owner,))
172
173
174
175
176
177
            login_ari, token_ari = results.fetchone()
            payload = {}
            payload['app'] = 'piphone'
            payload['api_key'] = ':'.join([login_ari, token_ari])
            payload['endpoint'] = 'SIP/' + sanitize_phonenumber(self.caller) + '@forfait-kwaoo'
            logging.debug('Preparing to send a request to the ARI with payload {}'.format(payload,))
178
            r = requests.post('http://185.34.33.12:8088/ari/channels/{}'.format(self.id), data=payload)
179
180
            logging.debug('Requests sent, got response: {}'.format(r,))
        except Exception as e:
okhin's avatar
okhin committed
181
            logging.debug("Exception raised in call_caller(): {}".format(e,))
182
183
184
            raise e

    def save(self):
185
186
187
        '''
        Save the Call to database.
        '''
188
189
190
191
192
193
194
195
196
        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:
            logging.debug("Got Exception: {}".format(e,))
            raise e
197

okhin's avatar
okhin committed
198
def authenticated(f):
okhin's avatar
okhin committed
199
200
201
202
203
204
205
206
    '''
    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
207
208
    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
209
        logging.debug("Authetication: {}".format([':'.join([key, request.params[key]]) for key in request.params],))
okhin's avatar
okhin committed
210
        if 'token' not in request.params:
okhin's avatar
okhin committed
211
            logging.error("No token found in the params")
okhin's avatar
okhin committed
212
            abort(401, "No token found in the query")
okhin's avatar
okhin committed
213
214
        # We want the api id in the params to.
        if 'api' not in request.params:
okhin's avatar
okhin committed
215
            logging.error("No api id found in the params")
okhin's avatar
okhin committed
216
            abort(401, "No api id found in the params")
okhin's avatar
okhin committed
217
218
219
220
221
222
223
        # 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
224
225
            for key in auth_token:
                request.params[key] = auth_token[key]
okhin's avatar
okhin committed
226
        except (jwt.exceptions.InvalidTokenError, AssertionError) as e:
okhin's avatar
okhin committed
227
228
            logging.error("Access refused")
            logging.debug("InvalidTokenError: {}".format(e))
okhin's avatar
okhin committed
229
230
231
232
233
234
            abort(403, e)
        except Exception as e:
            abort(500, e)
        return f(db, *args, **kwargs)
    return wrapped

235
236
237
238
239
240
241
242
243
244
245
246
247
248
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
249
        self.logger = logging.getLogger('server')
250
251
        if debug:
            self.logger.setLevel(logging.DEBUG)
okhin's avatar
okhin committed
252
        self.logger.addHandler(logging.FileHandler('app.log'))
253
254
255
256
257
258
259
        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
260
261
262
        ws_logger = logging.getLogger('websockets')
        ws_logger.setLevel(logging.DEBUG)
        ws_logger.addHandler(logging.FileHandler('app.log'))
263
264
        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
265
                ws_logger.info("Waiting for events on websocket")
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
                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,))
        # Let's get the call ID
        if 'channel' not in event:
            self.logger.debug('Not a channel event, skip')
            return
        call = Call.load(event['channel']['id'], self.db)
282
        call.event_handler(event)
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298

    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)
        
299
@app.get('/calls/<callid>')
300
@app.get('/calls/')
okhin's avatar
okhin committed
301
@authenticated
302
def calls(db, callid=None):
okhin's avatar
okhin committed
303
304
305
306
    """
    Return the list of calls associated to the connected user.
    The call has a status, caller, callee and history (status change+timestamp)
    """
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
    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:
            logging.error("Got exception: {}".format(e,))
            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
332
        logging.debug("Not exactly one results found, this is an issue")
333
334
335
336
337
338
339
340
341
        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>')
342
@authenticated
343
344
345
346
347
348
349
350
351
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()
352
353
            , 'user': request.params['api']
            , 'hits': 1}
354
355
356
357
358
        return {'header': head, 'data': call}
    except Exception as e:
        logging.debug("Missing params : {}".format([p for p in request.params],))
        logging.debug("Exception catched: {}".format(e,))
        abort(400, "Missing or incorrect fields, the call cannot be processed")
359
360
361
362
363
364
365
366
367
368
369
370

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:
        logging.error(e)
        server.stop()
        raise e