Skip to content

Commit

Permalink
async/await and minor improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
Matthias Damm committed Jan 26, 2020
1 parent 36f095c commit 9bdf628
Showing 1 changed file with 95 additions and 214 deletions.
309 changes: 95 additions & 214 deletions controllers/setup.js
Original file line number Diff line number Diff line change
@@ -1,240 +1,121 @@
const Twilio = require('twilio')
const async = require('async')

const client = new Twilio(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_AUTH_TOKEN)

module.exports.get = function (req, res) {
res.status(200).json(req.configuration)
}

module.exports.update = function (req, res) {
let config = req.body.configuration

async.waterfall([

function (callback) {

module.exports.createOrUpdateApplication(config, req, function (err, application) {
if (err) {
console.log('Setup Failure: Error setting up Twilio client application.')
callback(err)
} else {
config.twilio.applicationSid = application.sid

callback(null, config)
}
})

}, function (config, callback) {

module.exports.updateMessagingService(req, config, function (err) {
if (err) {
console.log('Setup Failure: Error updating messaging service.')
callback(err)
} else {
callback(null, config)
}
})

}, function (config, callback) {

module.exports.syncQueues(config, function (err) {
if (err) {
console.log('Setup Failure: Error establishing queues.')
callback(err)
} else {
callback(null, config)
}
})

}, function (config, callback) {
let workflowConfiguration = { task_routing: { filters: [] }}

for (let i = 0; i < config.queues.length; i++) {
let target = {
queue: config.queues[i].taskQueueSid
}

if (config.queues[i].targetWorkerExpression) {
target.expression = config.queues[i].targetWorkerExpression
}

let item = {
targets: [target],
expression: config.queues[i].expression,
filterFriendlyName: config.queues[i].filterFriendlyName
}

workflowConfiguration.task_routing.filters.push(item)
}

const workflow = {
sid: config.twilio.workflowSid,
friendlyName: 'Twilio Contact Center Workflow',
taskReservationTimeout: 1200,
configuration: JSON.stringify(workflowConfiguration)
}
const twilio = require('twilio');

module.exports.createOrUpdateWorkflow(workflow, function (err, workflow) {
const client = twilio(process.env.TWILIO_API_KEY_SID, process.env.TWILIO_API_KEY_SECRET, {
accountSid: process.env.TWILIO_ACCOUNT_SID
});

if (err) {
console.log('Setup Failure: Error setting up workflows.')
callback(err)
} else {
config.twilio.workflowSid = workflow.sid
callback(null, config)
}
})
module.exports.get = (req, res) => {
res.status(200).json(req.configuration);
};

}, function (config, callback) {
module.exports.update = async (req, res) => {
let configuration = req.body.configuration;

req.util.setConfiguration(config, function (err) {
if (err) {
callback(err)
} else {
callback()
}
})

}
], function (err) {
if (err) {
res.status(500).send(res.convertErrorToJSON(err))
return
}
try {
const { sid: applicationSid } = await createOrUpdateApplication(configuration.twilio.applicationSid, req);

res.status(200).end()
})
configuration.twilio.applicationSid = applicationSid;

}
await updateChatService(req);
await syncQueues(configuration);

module.exports.syncQueues = function (config, callback) {
let queues = config.queues
const { sid: workflowSid } = await createOrUpdateWorkflow(
configuration.twilio.workflowSid,
configuration.queues
);

/* create queues */
async.eachSeries(queues, function (queue, next) {
let queueForSync = {
sid: queue.taskQueueSid,
friendlyName: queue.friendlyName,
reservationActivitySid: config.twilio.workerReservationActivitySid,
assignmentActivitySid: config.twilio.workerAssignmentActivitySid,
targetWorkers: 'channels HAS "' + queue.id + '"'
}
configuration.twilio.workflowSid = workflowSid;

module.exports.createOrUpdateQueue(queueForSync, function (err, queueFromApi) {
if (err) {
console.log('Queue Setup Failure: Problem setting up specific queue.')
callback(err)
req.util.setConfiguration(configuration, (error) => {
if (error) {
throw error;
} else {
queue.taskQueueSid = queueFromApi.sid
next()
res.status(200).end();
}
});
} catch (error) {
res.status(500).send(res.convertErrorToJSON(error));
}
};

const syncQueues = async (configuration) => {
return Promise.all(
configuration.queues.map(async (queue) => {
let payload = {
sid: queue.taskQueueSid,
friendlyName: queue.friendlyName,
targetWorkers: `channels HAS "${queue.id}"`
};

const { sid } = await createOrUpdateQueue(payload);
queue.taskQueueSid = sid;
})
}, function () {
callback(null, config)
})
}
);
};

module.exports.createOrUpdateQueue = function (queue, callback) {
const createOrUpdateQueue = async (queue) => {
if (queue.sid) {

client.taskrouter.workspaces(process.env.TWILIO_WORKSPACE_SID).taskQueues(queue.sid).update(queue, function (err) {
if (err) {
callback(err)
} else {
callback(null, queue)
}
})

} else {

client.taskrouter.workspaces(process.env.TWILIO_WORKSPACE_SID).taskQueues.create(queue, function (err, queueFromApi) {
if (err) {
callback(err)
} else {
queue.sid = queueFromApi.sid
callback(null, queue)
}
})
return client.taskrouter.workspaces(process.env.TWILIO_WORKSPACE_SID).taskQueues(queue.sid).update(queue);
} else {
return client.taskrouter.workspaces(process.env.TWILIO_WORKSPACE_SID).taskQueues.create(queue);
}
}
};

module.exports.createOrUpdateWorkflow = function (workflow, callback) {
if (workflow.sid) {
const createOrUpdateWorkflow = async (sid, queues) => {
let workflow = { task_routing: { filters: [] } };

client.taskrouter.workspaces(process.env.TWILIO_WORKSPACE_SID).workflows(workflow.sid).update(workflow, function (err) {
if (err) {
callback(err)
} else {
callback(null, workflow)
}
})
for (let i = 0; i < queues.length; i++) {
let target = {
queue: queues[i].taskQueueSid
};

} else {
if (queues[i].targetWorkerExpression) {
target.expression = queues[i].targetWorkerExpression;
}

client.taskrouter.workspaces(process.env.TWILIO_WORKSPACE_SID).workflows.create(workflow, function (err, workflowFromApi) {
if (err) {
callback(err)
} else {
workflow.sid = workflowFromApi.sid
callback(null, workflow)
}
})
let item = {
targets: [ target ],
expression: queues[i].expression,
filterFriendlyName: queues[i].filterFriendlyName
};

workflow.task_routing.filters.push(item);
}
}

module.exports.createOrUpdateApplication = function (configuration, req, callback) {
const url = req.protocol + '://' + req.hostname + '/api/phone/call'

if (configuration.twilio.applicationSid) {

client.applications(configuration.twilio.applicationSid).update({
friendlyName: 'Twilio Contact Center Demo',
voiceUrl: url,
voiceMethod: 'POST'
}, function (err, application) {
if (err) {
callback(err)
} else {
callback(null, application)
}
})

} else {

client.applications.create({
friendlyName: 'Twilio Contact Center Demo',
voiceUrl: url,
voiceMethod: 'POST'
}, function (err, application) {
if (err) {
callback(err)
} else {
callback(null, application)
}
})

const payload = {
sid: sid,
friendlyName: 'Twilio Contact Center Workflow',
taskReservationTimeout: 1200,
configuration: JSON.stringify(workflow)
};

if (sid) {
return client.taskrouter.workspaces(process.env.TWILIO_WORKSPACE_SID).workflows(sid).update(payload);
} else {
return client.taskrouter.workspaces(process.env.TWILIO_WORKSPACE_SID).workflows.create(payload);
}
}

module.exports.updateMessagingService = function (req, config, callback) {
const url = req.protocol + '://' + req.hostname + '/api/messaging-adapter/outbound'

let webhooks = {}
};

const createOrUpdateApplication = async (sid, req) => {
const payload = {
friendlyName: 'Twilio Contact Center Demo',
voiceUrl: `${req.protocol}://${req.hostname}/api/phone/call`,
voiceMethod: 'POST'
};

if (sid) {
return client.applications(sid).update(payload);
} else {
return client.applications.create(payload);
}
};

webhooks.postWebhookUrl = url
webhooks.webhookFilters = 'onMessageSent'
webhooks.webhookMethod = 'POST'
const updateChatService = async (req) => {
let webhooks = {};

client.chat.services(process.env.TWILIO_CHAT_SERVICE_SID).update(webhooks)
.then(function (res) {
callback(null)
}).catch(function (err) {
console.log(err)
callback(err)
})
webhooks.postWebhookUrl = `${req.protocol}://${req.hostname}/api/messaging-adapter/outbound`;
webhooks.webhookFilters = 'onMessageSent';
webhooks.webhookMethod = 'POST';

}
return client.chat.services(process.env.TWILIO_CHAT_SERVICE_SID).update(webhooks);
};

0 comments on commit 9bdf628

Please sign in to comment.