app.py 9.16 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
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:
            return json.JSONEncoder.default(self, o)
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
55
56
    history = []
    actions = {'Created': 'call_caller'}
    def __init__(self, caller, callee, owner, callid=None, db=None):
okhin's avatar
okhin committed
57
58
59
60
        try:
            self.caller = caller
            self.callee = callee
            self.owner = owner
61
62
63
64
65
66
            if callid == None:
                self.id = uuid.uuid4()
            else:
                self.id = callid
            self.db = db
            self.change(('Created', datetime.datetime.now().isoformat(),))
okhin's avatar
okhin committed
67
68
69
70
71
72
73
74
        except Exception as e:
            raise e

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

    @classmethod
    def load(cls, callid, db):
75
        results = db.execute('SELECT caller, callee, owner, callid, history FROM calls WHERE callid = ?;', (callid,))
okhin's avatar
okhin committed
76
77
78
79
        try:
            result = results.fetchone()
            object = cls(result[0], result[1], result[2])
            object.id = result[3]
80
            object.db = db
okhin's avatar
okhin committed
81
82
83
84
85
            object.history = json.loads(result[4])
            return object
        except:
            return None

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
    def change(self, new_state):
        '''
        Let's change the state of the call. new_state is a tuple in the form (newstate, timestamp,)
        '''
        logging.debug("Got a new state: {}".format(new_state,))
        self.history.append(new_state)
        self.save()
        state = new_state[0]
        if state in self.actions:
            getattr(self, self.actions[state])()

    def call_caller(self):
        '''
        Let's do a request on the ARI system
        '''
        results = self.db.execute('SELECT login_ari, pass_ari FROM users WHERE api = ?', (self.owner,))
        try:
            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,))
            r = requests.post('http://185.34.33.12:8088/ari/channels', data=payload)
            logging.debug('Requests sent, got response: {}'.format(r,))
        except Exception as e:
            raise e

    def save(self):
115
116
117
        '''
        Save the Call to database.
        '''
118
        self.db.execute('''INSERT OR REPLACE INTO calls (caller, callee, owner, callid, history)
119
                VALUES (?, ?, ?, ?, ?)
120
        ''', (self.caller, self.callee, self.owner, self.id, json.dumps(self.history)))
121

okhin's avatar
okhin committed
122
123
124
125
126
127
128
129
130
131
# 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
132
            abort(401, "No token found in the query")
okhin's avatar
okhin committed
133
134
        # We want the api id in the params to.
        if 'api' not in request.params:
okhin's avatar
okhin committed
135
            abort(401, "No api id found in the params")
okhin's avatar
okhin committed
136
137
138
139
140
141
142
        # 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
143
144
            for key in auth_token:
                request.params[key] = auth_token[key]
okhin's avatar
okhin committed
145
146
147
148
149
150
151
        except (jwt.exceptions.InvalidTokenError, AssertionError) as e:
            abort(403, e)
        except Exception as e:
            abort(500, e)
        return f(db, *args, **kwargs)
    return wrapped

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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
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)
        await call.change((event['channel']['state'], event['channel']['creationtime'],))

    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)
        
@app.get('/calls/')
okhin's avatar
okhin committed
218
@authenticated
okhin's avatar
okhin committed
219
220
221
222
223
def calls(db):
    """
    Return the list of calls associated to the connected user.
    The call has a status, caller, callee and history (status change+timestamp)
    """
224
    logging.debug("/calls/ called")
okhin's avatar
okhin committed
225
226
227
    results = db.execute('SELECT callid FROM calls WHERE owner = ?;', (request.params['api'],))
    calls = []
    for call in results.fetchall():
228
229
        calls.append(Call.load(call[0], db))
    head = {'call': request.fullpath, 'user': request.params['api'], 'hits': len(calls)}
okhin's avatar
okhin committed
230
    return {'head': head, 'data': calls}
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253

@app.post('/calls/<callid>/caller/<caller>/callee/<callee>/')
@authenticated
def originate(db, callid, caller, callee):
    call = Call(caller, callee, request.params['api'], callid, db)
    logging.debug("Originate a call: {}".format(json.dumps(call, cls=PiphoneJSONEncoder)))
    head = {'call': call.url()
            , 'user': request.params['api']
            , 'hits': 1}
    return {'header': head, 'data': call}

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