-
Notifications
You must be signed in to change notification settings - Fork 0
/
taskrouter_dashboard.py
277 lines (237 loc) · 11.5 KB
/
taskrouter_dashboard.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
#!/usr/bin/python
import os
from flask import Flask, request, Response, jsonify, send_from_directory, redirect, url_for
# from flask_cors import CORS, cross_origin
import requests
from requests.auth import HTTPBasicAuth
import json
import logging
from twilio.rest import Client
from twilio.jwt.access_token import AccessToken
from twilio.jwt.access_token.grants import SyncGrant
logging.basicConfig(level=logging.DEBUG)
app = Flask(__name__)
#Task to Worker mapping
task_worker = {}
# Task Sid to Recording URls mapping
task_sid_recording_url = {}
# Twilio Settings
twilio_account_sid = os.environ.get("TWILIO_ACCOUNT_SID")
twilio_auth_token = os.environ.get("TWILIO_AUTH_TOKEN")
twilio_api_key = os.environ.get("TWILIO_API_KEY")
twilio_api_secret = os.environ.get("TWILIO_API_SECRET")
twilio_sync_service_id = os.environ.get("TWILIO_SYNC_SERVICE_ID")
twilio_workspace_sid = os.environ.get("TWILIO_WORKSPACE_SID")
twilio_test_call_to = os.environ.get("TWILIO_TEST_CALL_TO_PHONE_NUMBER")
twilio_test_call_from = os.environ.get("TWILIO_TEST_CALL_FROM_PHONE_NUMBER")
twilio_logged_in_worker_contact_uri = os.environ.get('TWILIO_LOGGED_IN_WORKER_CONTACT_URI')
# Create Client to access Twilio resources
# client = Client(twilio_api_key, twilio_api_secret)
@app.route('/sync_taskrouter_statistics', methods=['GET'])
def sync_taskrouter_statistics():
# Get TaskRouter Statistics
stats = {}
# Get Workspace related stats from last 60 minutes
client = Client(twilio_api_key, twilio_api_secret)
statistics = client.taskrouter.workspaces(twilio_workspace_sid).statistics().fetch(minutes=60)
stats['totalTasks'] = statistics.realtime['total_tasks']
stats['totalWorkers'] = statistics.realtime['total_workers']
task_statuses = statistics.realtime['tasks_by_status']
for (k, v) in task_statuses.items():
print(k, v)
task_status = k + 'Tasks'
stats[task_status] = statistics.realtime['tasks_by_status'][k]
for x in statistics.realtime['activity_statistics']:
if (x['friendly_name'] == 'Offline'):
stats['activityOfflineWorkers'] = x['workers']
elif (x['friendly_name'] == 'Idle'):
stats['activityIdleWorkers'] = x['workers']
elif (x['friendly_name'] == 'Reserved'):
stats['activityReservedWorkers'] = x['workers']
elif (x['friendly_name'] == 'Busy'):
stats['activityBusyWorkers'] = x['workers']
stats['avgTaskAcceptanceTime'] = statistics.cumulative["avg_task_acceptance_time"]
stats['startTime'] = statistics.cumulative["start_time"]
stats['endTime'] = statistics.cumulative["end_time"]
new_data = {'Data': json.dumps(stats)}
print('Workspace Statistics: ' + json.dumps(new_data, indent=2))
sync_document = 'SyncTaskRouterStats'
url = 'https://sync.twilio.com/v1/Services/' + twilio_sync_service_id + '/Documents/' + sync_document
response = requests.request("POST", url, data=new_data, auth=HTTPBasicAuth(twilio_api_key, twilio_api_secret))
print(response.text)
return (response.text)
@app.route('/taskrouter_event', methods=['POST'])
def taskrouter_event():
request_dict = {}
request_dict = request.form.to_dict()
# Store the Task to WorkerName mapping in process
if (request_dict['EventType'] == 'reservation.accepted' or request_dict['EventType'] == 'reservation.created'):
task_worker[request_dict['TaskSid']] = request_dict['WorkerName']
if (request_dict['EventType'] == 'task.completed' or request_dict['EventType'] == 'task.canceled') and request_dict['TaskChannelUniqueName'] == 'voice':
attributes = json.loads(request_dict['TaskAttributes'])
call = None
client = Client(twilio_account_sid, twilio_auth_token)
recordingUri = None
try:
recordingUri = attributes.get('conversations').get('segment_link')
except Exception as ex:
print(str(ex))
try:
recordings = client.recordings \
.list(
call_sid=attributes.get('call_sid'),
limit=20
)
recordingUri = 'https://api.twilio.com/2010-04-01/Accounts/{}/Recordings/{}'.format(twilio_account_sid, recordings[0].sid)
# recordingUri = recordings[0].uri
# call = client.calls(attributes.get('call_sid')).fetch()
except Exception as ex:
print(str(ex))
if recordingUri:
try:
url = '{scheme}://{host}/taskrouter_recording_callback'.format(scheme=request.scheme, host=request.host)
response = requests.request("POST", url, data={'TaskSid': request_dict['TaskSid'], 'RecordingUrl': recordingUri}, auth=HTTPBasicAuth(twilio_api_key, twilio_api_secret))
print(response.text)
except Exception as ex:
print(str(ex))
new_data = {'Data': json.dumps(request_dict)}
print(new_data)
sync_document = 'SyncTaskRouterEvents'
url = 'https://sync.twilio.com/v1/Services/' + twilio_sync_service_id + '/Documents/' + sync_document
response = requests.request("POST", url, data=new_data, auth=HTTPBasicAuth(twilio_api_key, twilio_api_secret))
print(response.text)
# Sync all Statistics
sync_taskrouter_statistics()
# Sync all Tasks
sync_taskrouter_tasks()
return 'OK'
@app.route('/taskrouter_tasks', methods=['GET'])
def taskrouter_tasks():
client = Client(twilio_api_key, twilio_api_secret)
current_tasks = client.taskrouter.workspaces(twilio_workspace_sid).tasks.list(ordering='Priority:desc,DateCreated:asc')
task_model = {}
tasks_results = []
for task in current_tasks:
task_model['TaskSid'] = task.sid
task_model['Priority'] = task.priority
task_model['TaskChannelUniqueName'] = task.task_channel_unique_name
task_model['TaskQueueFriendlyName'] = task.task_queue_friendly_name
task_model['Timeout'] = task.timeout
task_model['WorkflowFriendlyName'] = task.workflow_friendly_name
attributes = json.loads(task.attributes)
for (key, value) in attributes.items():
task_model[key] = value
try:
task_model['WorkerName'] = task_worker[task.sid]
except:
task_model['WorkerName'] = ""
# Workaround to Video channel task missing team name
if (task_model.get('channel') == 'video'):
task_model['team'] = 'Support'
elif not task_model.get('team'):
task_model['team'] = 'Support'
# Get previously stored recording url
try:
task_model['RecordingUrl'] = attributes.get('conversations', {}).get('segment_link', None) if attributes.get('conversations', {}).get('segment_link', None) else task_sid_recording_url[task.sid]
task_model['recordingUrl'] = attributes.get('conversations', {}).get('segment_link', None) if attributes.get('conversations', {}).get('segment_link', None) else task_sid_recording_url[task.sid]
# task_model['RecordingUrl'] = task_sid_recording_url[task.sid]
except:
task_model['RecordingUrl'] = ""
task_model['TaskStatus'] = task.assignment_status
tasks_results.append(dict(task_model))
result = json.dumps(tasks_results)
print(result)
return result
@app.route('/sync_taskrouter_tasks', methods=['GET'])
def sync_taskrouter_tasks():
results = json.loads(taskrouter_tasks())
sync_map = 'SyncTaskRouterTasks'
new_data = {}
print(len(results))
print(results)
# Delete the current Sync Map and re-create if we have Tasks
if (len(results) > 0):
# Delete the Sync Map
url = "https://sync.twilio.com/v1/Services/" + twilio_sync_service_id + "/Maps/" + sync_map
response = requests.request("DELETE", url, auth=HTTPBasicAuth(twilio_api_key, twilio_api_secret))
print('Map Deleted')
print(response)
# Re-create the Sync Map
new_data = {'UniqueName': sync_map}
url = 'https://sync.twilio.com/v1/Services/' + twilio_sync_service_id + '/Maps'
response = requests.request("POST", url, data=new_data, auth=HTTPBasicAuth(twilio_api_key, twilio_api_secret))
print('Map Created')
print(response)
for result in results:
item_key = result['TaskSid']
new_data = {'Key': item_key,
'Data': json.dumps(result)}
print(new_data)
# Insert into Sync Map
url = 'https://sync.twilio.com/v1/Services/' + twilio_sync_service_id + '/Maps/' + sync_map + '/Items'
response = requests.request("POST", url, data=new_data, auth=HTTPBasicAuth(twilio_api_key, twilio_api_secret))
print(response.text)
return 'OK'
@app.route('/taskrouter_recording_callback', methods=['POST'])
def taskrouter_recording_callback():
task_sid = request.values.get('TaskSid', '')
request_dict = {}
request_dict = request.form.to_dict()
recording_url = request.values.get('RecordingUrl', '')
# recording_url = request_dict["RecordingUrl"] + ".mp3"
task_sid_recording_url[task_sid] = recording_url
#print(json.dumps(task_sid_recording_url))
return 'OK'
@app.route('/taskrouter_workers', methods=['GET'])
def taskrouter_workers():
client = Client(twilio_api_key, twilio_api_secret)
workers = client.taskrouter.workspaces(twilio_workspace_sid).workers.list()
worker_model = {}
workers_results = []
for worker in workers:
worker_model['worker_sid'] = worker.sid
worker_model['friendly_name'] = worker.friendly_name
worker_model['activity_name'] = worker.activity_name
worker_model['account_sid'] = worker.account_sid
worker_model['workspace_sid'] = worker.workspace_sid
attributes = json.loads(worker.attributes)
for (key, value) in attributes.items():
worker_model[key] = value
print(key, value)
workers_results.append(dict(worker_model))
result = json.dumps(workers_results)
return result
@app.route('/create_test_calls', methods=['GET'])
def create_test_calls():
client = Client(twilio_api_key, twilio_api_secret)
total_inbound_calls = int(request.values.get('calls', '1'))
for x in range(0, total_inbound_calls):
print (x)
url = "http://twimlets.com/holdmusic?Bucket=com.twilio.music.classical&Message=This%20is%20a%20test%20call%20number%20" + str(x) + '&'
call = client.calls.create(to=twilio_test_call_to, from_=twilio_test_call_from, send_digits="ww1", url=url)
print(call.sid)
return "OK"
@app.route('/')
def index():
return send_from_directory('static', 'taskrouter_dashboard.html')
# return redirect("/taskrouter_dashboard.html", code=302)
@app.route('/<path:path>')
def send_js(path):
return send_from_directory('static', path)
def create_sync_map(userid):
client = Client(twilio_api_key, twilio_api_secret)
map_instance = client.sync.services(twilio_sync_service_id).sync_maps.create(unique_name=userid)
return (map_instance.sid)
@app.route('/token')
def token():
# get the userid from the incoming request
identity = request.values.get('identity', None)
# Create access token with credentials
token = AccessToken(twilio_account_sid, twilio_api_key, twilio_api_secret, identity=identity)
# Create a Sync grant and add to token
sync_grant = SyncGrant(service_sid=twilio_sync_service_id)
token.add_grant(sync_grant)
# Return token info as JSON
return jsonify(identity=identity, token=token.to_jwt().decode('utf-8'))
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True, threaded=True)