forked from alafin/dialer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dialer_app.py
352 lines (280 loc) · 11.6 KB
/
dialer_app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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
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
140
141
142
143
144
145
146
147
148
149
150
151
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import functools
from urlparse import urljoin
import asterisk.manager
import eventlet
import requests
from oauthlib.oauth1 import RequestValidator, ResourceEndpoint
from requests_oauthlib import OAuth1
from flask import Flask, request, jsonify, abort, Blueprint
from werkzeug.exceptions import RequestTimeout
import config
eventlet.monkey_patch()
app = Flask(__name__)
app.debug = config.DEBUG
manager = asterisk.manager.Manager()
ami_blueprint = Blueprint('asterisk', __name__)
api_blueprint = Blueprint('api', __name__)
class DialerRequestValidator(RequestValidator):
enforce_ssl = False
client_key_length = 3, 50
access_token_length = 3, 50
def get_client_secret(self, client_key, request):
return None
def get_access_token_secret(self, client_key, resource_owner_key, request):
return unicode(config.RESOURCE_OWNER_SECRET)
def validate_timestamp_and_nonce(
self, client_key, timestamp, nonce, request, request_token=None, access_token=None
):
return True
def validate_client_key(self, client_key, request):
if client_key != 'uaprom':
app.logger.debug('Failed on validate_client_key')
return False
return True
def validate_access_token(self, client_key, token, request):
if token != 'crm':
app.logger.debug('Failed on validate_access_token')
return False
return True
def validate_realms(self, client_key, token, request, uri=None, realms=None):
return True
validator = DialerRequestValidator()
endpoint = ResourceEndpoint(validator)
def oauth_protected(realms=None):
def wrapper(f):
@functools.wraps(f)
def verify_oauth(*args, **kwargs):
app.logger.debug('Start verify request')
app.logger.debug(
'request.url=%s request.method=%s request.data=%s request.headers=%s realms=%s' % (
request.url, request.method, request.form or request.data, request.headers,
realms
)
)
v, r = endpoint.validate_protected_resource_request(
request.url,
http_method=request.method,
body=request.form or request.data,
headers=request.headers,
realms=realms or []
)
if v:
return f(*args, **kwargs)
else:
app.logger.debug('Not valid request.')
return abort(403)
return verify_oauth
return wrapper
SITES = {
'UA': 'https://my.prom.ua/',
'RU': 'https://my.tiu.ru/',
'BY': 'https://my.deal.by/',
'KZ': 'https://my.satu.kz/',
}
def log_action(status, error_msg, action, response):
app.logger.debug(
'Tried to %s status=%s and error=%s and response=%s' % (
action, status, error_msg, response
)
)
def event_callback(event, manager):
app.logger.debug('Handling event - %s\nHeaders - %s' % (event, event.headers))
@ami_blueprint.before_request
# @oauth_protected()
def before_each_dialer_request(*args, **kwargs):
status, response, error_msg = 'success', '', ''
try:
if not manager.connected():
manager.connect(config.ASTERISK_ADDRESS, config.ASTERISK_PORT)
manager.login(config.ASTERISK_LOGIN, config.ASTERISK_PASSWORD)
response = manager.send_action({
'Action': 'Events',
'Events': 'on',
'EventMask': 'cdr',
}).response
manager.register_event('*', event_callback)
except asterisk.manager.ManagerSocketException, (errno, reason):
status = 'failure'
error_msg = 'Error connecting to the manager: %s' % reason
except asterisk.manager.ManagerAuthException, reason:
status = 'failure'
error_msg = 'Error login to the manager: %s' % reason
except asterisk.manager.ManagerException, reason:
status = 'failure'
error_msg = 'Error: %s' % reason
log_action(status, error_msg, 'login-connect-listen_events', response)
@ami_blueprint.route('/call', methods=['POST'])
def call():
app.logger.debug('Start call')
inline = request.form['inline']
exten = request.form['exten']
channel = 'SIP/%s' % inline
status, error_msg, response, action = 'success', '', '', 'call'
try:
response = manager.originate(
channel, exten, caller_id='call_from_CRM <CRM>', async=True
).response
except asterisk.manager.ManagerException, reason:
error_msg = 'Error: %s' % reason
log_action(status, error_msg, action, response)
return jsonify(status=status, error=error_msg, response=response)
@ami_blueprint.route('/show_inuse', methods=['GET'])
def show_inuse():
app.logger.debug('Start show_inuse')
status, error_msg, response, action = 'success', '', '', 'show_inuse'
try:
response = manager.command('sip show inuse').data
except asterisk.manager.ManagerException, reason:
status = 'failure'
error_msg = 'Error: %s' % reason
log_action(status, error_msg, action, response)
return jsonify(status=status, error=error_msg, response=response)
@ami_blueprint.route('/show_channels', methods=['GET'])
def show_channels():
app.logger.debug('Start show_channels')
status, error_msg, response, action = 'success', '', '', 'show_channels'
try:
response = manager.command('core show channels verbose').data
except asterisk.manager.ManagerException, reason:
status = 'failure'
error_msg = 'Error: %s' % reason
log_action(status, error_msg, action, response)
return jsonify(status=status, error=error_msg, response=response)
@ami_blueprint.route('/spy', methods=['POST'])
def spy():
app.logger.debug('Start spy')
inline = request.form['inline']
exten = request.form['exten']
status, error_msg, response, action = 'success', '', '', 'spy'
try:
manager.send_action({
'Action': 'Originate',
'Channel': 'SIP/%s' % inline,
'CallerID': 'Listening...',
'Application': 'ChanSpy',
'Data': 'SIP/%s,q' % exten
}).response
except asterisk.manager.ManagerException, reason:
status = 'failure'
error_msg = 'Error: %s' % reason
log_action(status, error_msg, action, response)
return jsonify(status=status, error=error_msg, response=response)
@ami_blueprint.route('/queue_add', methods=['POST'])
def queue_add():
app.logger.debug('Start queue_add')
queue = request.form['queue']
interface = request.form['interface']
state_interface = request.form['state_interface']
status, error_msg, response, action = 'success', '', '', 'queue_add'
try:
response = manager.send_action({
'Action': 'QueueAdd',
'Queue': queue,
'Interface': interface,
'StateInterface': state_interface,
}).response
except asterisk.manager.ManagerException, reason:
status = 'failure'
error_msg = 'Error: %s' % reason
log_action(status, error_msg, action, response)
return jsonify(status=status, error=error_msg, response=response)
@ami_blueprint.route('/db_get', methods=['GET'])
def db_get():
app.logger.debug('Start db_get')
family = request.args['family']
key = request.args['key']
status, error_msg, response, action = 'success', '', '', 'db_get'
try:
response = manager.command('database get %s %s' % (family, key)).response
except asterisk.manager.ManagerException, reason:
status = 'failure'
error_msg = 'Error: %s' % reason
log_action(status, error_msg, action, response)
return jsonify(status=status, error=error_msg, response=response)
@ami_blueprint.route('/queue_status', methods=['GET'])
def queue_status():
app.logger.debug('Start queue_status')
status, error_msg, response, action = 'success', '', '', 'queue_status'
try:
response = manager.send_action({'Action': 'QueueStatus'}).response
except asterisk.manager.ManagerException, reason:
status = 'failure'
error_msg = 'Error: %s' % reason
log_action(status, error_msg, action, response)
return jsonify(status=status, error=error_msg, response=response)
@ami_blueprint.route('/queue_remove', methods=['POST'])
def queue_remove():
app.logger.debug('Start queue_remove')
queue = request.form['queue']
interface = request.form['interface']
status, error_msg, response, action = 'success', '', '', 'queue_remove'
try:
response = manager.send_action({
'Action': 'QueueRemove',
'Queue': queue,
'Interface': interface,
}).response
except asterisk.manager.ManagerException, reason:
status = 'failure'
error_msg = 'Error: %s' % reason
log_action(status, error_msg, action, response)
return jsonify(status=status, error=error_msg, response=response)
### API ###
def try_remote_request(api_url, payload):
auth = OAuth1(
'dialer',
resource_owner_key=config.RESOURCE_OWNER_KEY,
resource_owner_secret=config.RESOURCE_OWNER_SECRET
)
with eventlet.Timeout(config.API_TIMEOUT, False):
response = requests.get(api_url, params=payload, auth=auth)
if response.status_code == 200:
return response.text
else:
abort(response.status_code)
raise RequestTimeout
@api_blueprint.before_request
def before_each_api_request(*args, **kwargs):
if request.remote_addr not in config.ALLOWED_HOSTS:
abort(403)
@api_blueprint.route('/manager_phone', methods=['GET'])
def manager_phone():
calling_phone = request.args['calling_phone']
country = request.args['country'].upper()
api_url = urljoin(SITES[country], '/agency/api/manager/manager_phone')
payload = {'calling_phone': calling_phone}
return try_remote_request(api_url, payload)
@api_blueprint.route('/manager_phone_for_company', methods=['GET'])
def manager_phone_for_company():
id = request.args['id']
country = request.args['country'].upper()
api_url = urljoin(SITES[country], '/agency/api/manager/manager_phone_for_company')
payload = {'id': id}
return try_remote_request(api_url, payload)
@api_blueprint.route('/show_calling_popup_to_manager', methods=['GET'])
def show_calling_popup_to_manager():
calling_phone = request.args['calling_phone']
inner_number = request.args['inner_number']
country = request.args['country'].upper()
api_url = urljoin(SITES[country], '/agency/api/manager/show_calling_popup_to_manager')
payload = {'calling_phone': calling_phone, 'inner_number': inner_number}
return try_remote_request(api_url, payload)
@api_blueprint.route('/show_calling_review_popup_to_manager', methods=['GET'])
def show_calling_review_popup_to_manager():
inner_number = request.args['inner_number']
review_href = request.args['review_href']
country = request.args['country'].upper()
api_url = urljoin(SITES[country], '/agency/api/manager/show_calling_review_popup_to_manager')
payload = {'inner_number': inner_number, 'review_href': review_href}
return try_remote_request(api_url, payload)
@api_blueprint.route('/manager_call_after_hours', methods=['GET'])
def manager_call_after_hours():
calling_phone = request.args['calling_phone']
country = request.args['country'].upper()
api_url = urljoin(SITES[country], '/agency/api/manager/manager_call_after_hours')
payload = {'calling_phone': calling_phone}
return try_remote_request(api_url, payload)
app.register_blueprint(ami_blueprint)
app.register_blueprint(api_blueprint, url_prefix='/api')
if __name__ == '__main__':
app.run(port=8000)