app.py 11.9 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

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

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

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

50
class Call(object):
okhin's avatar
okhin committed
51
52
53
    """
    This Class is used to manage operatiosn on a call, to print it and dump it.
    """
54
    history = []
55
56
    actions = {'Created': 'call_caller'
            , 'ChannelStateChange': 'change'}
57
    def __init__(self, caller, callee, owner, callid=None, db=None):
okhin's avatar
okhin committed
58
59
60
61
        try:
            self.caller = caller
            self.callee = callee
            self.owner = owner
62
            if callid == None:
63
64
65
                self.id = str(uuid.uuid4())
                self.db = db
                self.event_handler({'type': 'Created', 'timestamp': datetime.datetime.now().isoformat()})
66
67
            else:
                self.id = callid
okhin's avatar
okhin committed
68
        except Exception as e:
69
            logging.debug("Exception catched: {}".format(e,))
okhin's avatar
okhin committed
70
71
72
73
74
75
76
            raise e

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

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

90
    def update(self, new_state):
91
        '''
92
        Let's update the state of the call. new_state is a tuple in the form (newstate, timestamp,)
93
94
95
96
        '''
        logging.debug("Got a new state: {}".format(new_state,))
        self.history.append(new_state)
        self.save()
97
98
99
100
101
102

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

106
107
108
109
110
111
112
    def change(self, event):
        '''
        Let's change the state of the call
        '''
        self.update((event['channel']['state'], event['timestamp'],))

    def call_caller(self, event):
113
114
115
        '''
        Let's do a request on the ARI system
        '''
116
        self.update((event['type'], event['timestamp'],))
117
        try:
118
            results = self.db.execute('SELECT login_ari, pass_ari FROM users WHERE api = ?', (self.owner,))
119
120
121
122
123
124
            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,))
125
            r = requests.post('http://185.34.33.12:8088/ari/channels/{}'.format(self.id), data=payload)
126
127
128
129
130
            logging.debug('Requests sent, got response: {}'.format(r,))
        except Exception as e:
            raise e

    def save(self):
131
132
133
        '''
        Save the Call to database.
        '''
134
135
136
137
138
139
140
141
142
        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
143

okhin's avatar
okhin committed
144
145
146
147
148
149
150
151
152
153
# 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.
def authenticated(f):
    def wrapped(db, *args, **kwargs):
        # Let's get the JWT token. It should be a params (from get or post or whatev')
        if 'token' not in request.params:
okhin's avatar
okhin committed
154
            abort(401, "No token found in the query")
okhin's avatar
okhin committed
155
156
        # We want the api id in the params to.
        if 'api' not in request.params:
okhin's avatar
okhin committed
157
            abort(401, "No api id found in the params")
okhin's avatar
okhin committed
158
159
160
161
162
163
164
        # 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
165
166
            for key in auth_token:
                request.params[key] = auth_token[key]
okhin's avatar
okhin committed
167
168
169
170
171
172
173
        except (jwt.exceptions.InvalidTokenError, AssertionError) as e:
            abort(403, e)
        except Exception as e:
            abort(500, e)
        return f(db, *args, **kwargs)
    return wrapped

174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
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
        """
        self.logger = logging.getLogger(__name__)
        if debug:
            self.logger.setLevel(logging.DEBUG)
        self.log_handler = logging.FileHandler('app.log')
        self.logger.addHandler(self.log_handler)
        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):
        logger = logging.getLogger('websockets')
        logger.setLevel(logging.DEBUG)
        logger.addHandler(self.log_handler)
        async with websockets.connect('ws://185.34.33.12:8088/ari/events?app=piphone&api_key=piphone:passpiphone') as websocket:
            while self.running == True:
                logger.debug("Waiting for events")
                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)
222
        call.event_handler(event)
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238

    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)
        
239
@app.get('/calls/<callid>')
240
@app.get('/calls/')
okhin's avatar
okhin committed
241
@authenticated
242
def calls(db, callid=None):
okhin's avatar
okhin committed
243
244
245
246
    """
    Return the list of calls associated to the connected user.
    The call has a status, caller, callee and history (status change+timestamp)
    """
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
    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:
        logging.debg("Not exactly one results found, this is an issue")
        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>')
282
@authenticated
283
284
285
286
287
288
289
290
291
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()
292
293
            , 'user': request.params['api']
            , 'hits': 1}
294
295
296
297
298
        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")
299
300
301
302
303
304
305
306
307
308
309
310
311

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