├── .gitignore ├── LICENSE ├── README.md ├── dialpad-functions ├── .env.sample ├── .nvmrc ├── functions │ ├── external-transfer │ │ ├── add-conference-participant.js │ │ ├── get-call-properties.js │ │ ├── hold-conference-participant.js │ │ ├── remove-conference-participant.js │ │ └── update-conference-participant.js │ └── outbound-dialing │ │ ├── callHandlerTwiml.protected.js │ │ ├── callStatusUpdateHandler.protected.js │ │ ├── callTreatment.js │ │ ├── endCall.js │ │ ├── forceUpdateSyncDoc.js │ │ ├── invokeOutboundCall.protected.js │ │ └── makeCall.js ├── package-lock.json └── package.json ├── package-lock.json ├── package.json ├── public ├── appConfig.example.js ├── index.html ├── plugins.json └── plugins.local.build.json ├── screenshot ├── create-activity.png ├── dialpad.gif ├── dialpad.png ├── external-conference-warm-transfer-demo.gif └── workflow-config.png └── src ├── OutboundDialingWithConferencePlugin.js ├── components ├── dialpad │ ├── DialPad.js │ ├── DialPadLauncher.js │ └── index.js └── external-transfer │ ├── ConferenceButton.js │ ├── ConferenceDialog.js │ ├── ConferenceMonitor.js │ ├── ParticipantActionsButtons.js │ ├── ParticipantName.js │ ├── ParticipantStatus.js │ ├── ParticipantStatusContainer.js │ └── index.js ├── eventListeners ├── actionsFramework │ ├── acceptTask.js │ ├── holdParticipant.js │ ├── index.js │ ├── kickParticipant.js │ ├── monitorCall.js │ └── unholdParticipant.js └── workerClient │ └── reservationCreated.js ├── index.js ├── notifications └── CustomNotifications.js └── utilities ├── ConferenceService.js └── DialPadUtil.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | .DS_Store 8 | 9 | # Runtime data 10 | pids 11 | *.pid 12 | *.seed 13 | *.pid.lock 14 | 15 | # Directory for instrumented libs generated by jscoverage/JSCover 16 | lib-cov 17 | 18 | # Coverage directory used by tools like istanbul 19 | coverage 20 | 21 | # nyc test coverage 22 | .nyc_output 23 | 24 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 25 | .grunt 26 | 27 | # Bower dependency directory (https://bower.io/) 28 | bower_components 29 | 30 | # node-waf configuration 31 | .lock-wscript 32 | 33 | # Compiled binary addons (https://nodejs.org/api/addons.html) 34 | build/Release 35 | 36 | # Dependency directories 37 | node_modules/ 38 | jspm_packages/ 39 | 40 | # TypeScript v1 declaration files 41 | typings/ 42 | 43 | # Optional npm cache directory 44 | .npm 45 | 46 | # Optional eslint cache 47 | .eslintcache 48 | 49 | # Optional REPL history 50 | .node_repl_history 51 | 52 | # Output of 'npm pack' 53 | *.tgz 54 | 55 | # Yarn Integrity file 56 | .yarn-integrity 57 | 58 | # dotenv environment variables file 59 | .env 60 | 61 | # next.js build output 62 | .next 63 | 64 | # Flex related ignore 65 | appConfig.js 66 | build/ 67 | 68 | # serverless cli functions 69 | .twilio-functions 70 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # plugin-flex-outbound-dialpad 2 | 3 | This plugin is intended to demonstrate how to make outbound calls from [Twilio Flex](https://www.twilio.com/flex) that use the native call orchestration so the inbound call features such as supervisor monitoring as well as cold and warm transfer, also work for outbound calls. This plugin also provides the ability to perform external conferencing which leverages the work on [this project](https://github.com/trogers-twilio/plugin-external-conference-warm-transfer) 4 | 5 | ### How It Works 6 | 7 | This plugin uses a series of twilio functions to create an outbound call, listen for updates to that call and push the updates to the flex users via a sync document. When the call is answered, the worker goes available in Flex to recieve the call via a task router task. The front end puts the agent in a busy state while waiting for the task to arrive so that no other tasks are recieved. To avoid a race condition, when the agent does go available, any tasks that are not the outbound call are auto rejected. The worker goes into a busy state to avoid excessive reservation rejections. 8 | 9 | ### Dialpad 10 | 11 | 12 | 13 | ## Task Router Dependencies 14 | 15 | ### Workflow 16 | 17 | Before using this plugin you must first create a dedicated TaskRouter workflow for outbound calls. You can do this [here](https://www.twilio.com/console/taskrouter/dashboard). Make sure it is part of your **Flex Task Assignment** workspace. 18 | 19 | * Ensure there is the following matching workers expression for the only filter on the workspace. 20 | * `task.targetWorker === worker.contact_uri` 21 | * Ensure the **priorty** of the filter is set to **1000** (or at least the highest in the system). 22 | * Make sure the filter matches to a queue with Everyone on it. The default Everyone queue will work but if you want to seperate real time reporting for outbound calls, you should make a dedicated queue for it with a queue expression. 23 | * `1 === 1` 24 | 25 | ### Activities 26 | 27 | This plugin forces the agent into an offline state to block calls while dialing out and an online state to accept the outbound call thats been placed. You must ensure these are agent activity states are available for this plugin to work. For both offline and available, two possible activities have been programmed, the plugin will try one of the activities and if its not available, try the other, if thats not available it will fail. You can either provision one of the states or update the code to switch to an equivalent activity that you do have configured in Task Router. 28 | 29 | Available states programmed by default (One of these must be configured in Task Router): 30 | * Available 31 | * Idle 32 | 33 | Unavailable states programmed by default (One of these must be configured in Task Router): 34 | * Outbound Calls 35 | * Offline 36 | 37 | 38 | 39 | ## Twilio Serverless Dependency 40 | 41 | You will need the [twilio CLI](https://www.twilio.com/docs/twilio-cli/quickstart) and the [serverless plugin](https://www.twilio.com/docs/labs/serverless-toolkit/getting-started) to deploy the functions you can install with the following commands 42 | 43 | `npm install twilio-cli -g` 44 | 45 | and then 46 | 47 | `twilio plugins:install @twilio-labs/plugin-serverless` 48 | 49 | ## How To Use 50 | 51 | 1. Setup dependencies above, The workflow and the outbound calls worker activity. 52 | 2. Clone the repository. 53 | 3. Copy `./public/appConfig.example.js` to `./public/appConfig.js` and set your account sid. 54 | 4. Run `npm install`. 55 | 5. Copy `./dialpad-functions/.env.sample` to `./dialpad-functions/.env` and populate the appropriate SIDs. The workflow sid should be the workflow dependency described above. 56 | 6. CD into `./dialpad-functions/` then run `npm install` and then `twilio serverless:deploy` (optionally you can run locally with `twilio serverless:start --ngrok=""`. 57 | 7. Take note of the domain of where they deployed and update `FUNCTIONS_HOSTNAME` in [./src/OutboundDialingWithConferencePlugin.js](./blob/master/src/OutboundDialingWithConferencePlugin.js). 58 | 7. Update the `DEFAULT_FROM_NUMBER` in [./src/OutboundDialingWithConferencePlugin.js](./blob/master/src/OutboundDialingWithConferencePlugin.js) to a twilio number or a verified number associated with your account. 59 | 8. CD back to the root folder and run `npm start` to run locally or `npm run-script build` and deploy the generated `./build/plugin-outbound-dialing-with-conference.js` to [Twilio Assests](https://www.twilio.com/console/assets/public) to include plugin with hosted Flex. 60 | 61 | ## Important Notes 62 | 63 | * The plugin assumes an activity of `Outbound Calls` or `Offline` is configured for making the worker automatically unavailable, if these are not worker activity states that are available, you can either add them or update the code to change to a different state. The same is true for ensuring an available activity of `Available` or `Idle` is in the system. 64 | * This plugin is not compatible with the dialpad plugin that is listed as an `Experimental feature` - the expiremental feature or more recently, the `Pre Release` feature must be turned off. 65 | * If you place a `phone` attribute on the worker and assign it a twilio or verified number, the call will be placed from that number instead of the default number. 66 | * This solution doesnt support and is not suitable for direct agent to agent dialing. 67 | * Since the call is routed to the agent only after the call is answered, there can be a perceived delay, typically less than a second, of the agent and the customer connecting on the conference. It is adviced to configure the hold music for the outbound call to be silence, this creates a smoother experience for the person being dialed. 68 | 69 | ## TODOs 70 | 71 | 1. Improve styling to better match base palette. 72 | 2. Add in improved text box for entering numbers with country code drop down. 73 | 3. Introduce callback task for making outbound calls from a callback . 74 | 4. Update plugin builder to use serverless:cli for plugin asset deployment and align functions hostname automatically. 75 | 76 | ## Changelog 77 | 78 | v1.3 - Moved dialpad to main header to avoid the responsive rendering of the side nav unmounting when resizing the canvas. 79 | 80 | v1.2 - converted plugin to use Twilio functions and sync docs to manage state. Also merged in external transfer features. 81 | 82 | v1.1 - added ringtone when dialing, DTMF tones while on a call and better state management. 83 | 84 | - breaking change to url, must align with backend 85 | 86 | v1.0 - initial release 87 | 88 | ## Code of Conduct 89 | 90 | Please be aware that this project has a [Code of Conduct](https://github.com/twilio-labs/.github/blob/master/CODE_OF_CONDUCT.md). The tldr; is to just be excellent to each other ❤️ 91 | -------------------------------------------------------------------------------- /dialpad-functions/.env.sample: -------------------------------------------------------------------------------- 1 | ACCOUNT_SID=AC... 2 | AUTH_TOKEN=... 3 | TWILIO_WORKFLOW_SID=WW... 4 | TWILIO_WORKSPACE_SID=WS... 5 | TWILIO_SYNC_SERVICE_SID=IS... 6 | ACCOUNT_SID_X=AC... 7 | ACCOUNT_SID_Y=AC... -------------------------------------------------------------------------------- /dialpad-functions/.nvmrc: -------------------------------------------------------------------------------- 1 | 8.10.0 -------------------------------------------------------------------------------- /dialpad-functions/functions/external-transfer/add-conference-participant.js: -------------------------------------------------------------------------------- 1 | const nodeFetch = require('node-fetch'); 2 | const TokenValidator = require('twilio-flex-token-validator').functionValidator; 3 | 4 | exports.handler = TokenValidator(async function (context, event, callback) { 5 | const response = new Twilio.Response(); 6 | response.appendHeader('Access-Control-Allow-Origin', '*'); 7 | response.appendHeader('Access-Control-Allow-Methods', 'OPTIONS POST'); 8 | response.appendHeader('Content-Type', 'application/json'); 9 | response.appendHeader('Access-Control-Allow-Headers', 'Content-Type'); 10 | 11 | console.log('add-conference-participant parameters:'); 12 | Object.keys(event).forEach(key => { 13 | if (key !== "token" || key !== "Token") { 14 | console.log(`${key}: ${event[key]}`); 15 | } 16 | }); 17 | 18 | if (Object.keys(event).length === 0) { 19 | console.log('Empty event object, likely an OPTIONS request'); 20 | return callback(null, response); 21 | } 22 | 23 | const { 24 | taskSid, 25 | to, 26 | from 27 | } = event; 28 | 29 | console.log(`Adding ${to} to named conference ${taskSid}`); 30 | const client = context.getTwilioClient(); 31 | const participantsResponse = await client 32 | .conferences(taskSid) 33 | .participants 34 | .create({ 35 | to, 36 | from, 37 | earlyMedia: true, 38 | endConferenceOnExit: false 39 | }); 40 | console.log('Participant response properties:'); 41 | Object.keys(participantsResponse).forEach(key => { 42 | console.log(`${key}: ${participantsResponse[key]}`); 43 | }); 44 | response.setBody({ 45 | ...participantsResponse, 46 | status: 200, 47 | _version: undefined 48 | }); 49 | 50 | return callback(null, response); 51 | }); 52 | -------------------------------------------------------------------------------- /dialpad-functions/functions/external-transfer/get-call-properties.js: -------------------------------------------------------------------------------- 1 | const nodeFetch = require('node-fetch'); 2 | const TokenValidator = require('twilio-flex-token-validator').functionValidator; 3 | 4 | exports.handler = TokenValidator(async function (context, event, callback) { 5 | const response = new Twilio.Response(); 6 | response.appendHeader('Access-Control-Allow-Origin', '*'); 7 | response.appendHeader('Access-Control-Allow-Methods', 'OPTIONS POST'); 8 | response.appendHeader('Content-Type', 'application/json'); 9 | response.appendHeader('Access-Control-Allow-Headers', 'Content-Type'); 10 | 11 | console.log('get-call-properties parameters:'); 12 | Object.keys(event).forEach(key => { 13 | if (key !== "token" || key !== "Token") { 14 | console.log(`${key}: ${event[key]}`); 15 | } 16 | }); 17 | 18 | if (Object.keys(event).length === 0) { 19 | console.log('Empty event object, likely an OPTIONS request'); 20 | return callback(null, response); 21 | } 22 | 23 | const { 24 | callSid, 25 | } = event; 26 | 27 | console.log(`Getting properties for call SID ${callSid}`); 28 | const client = context.getTwilioClient(); 29 | const callProperties = await client 30 | .calls(callSid) 31 | .fetch(); 32 | console.log('Call properties:'); 33 | Object.keys(callProperties).forEach(key => { 34 | console.log(`${key}: ${callProperties[key]}`); 35 | }); 36 | 37 | response.setBody({ 38 | ...callProperties, 39 | _version: undefined 40 | }); 41 | 42 | return callback(null, response); 43 | }); 44 | -------------------------------------------------------------------------------- /dialpad-functions/functions/external-transfer/hold-conference-participant.js: -------------------------------------------------------------------------------- 1 | const nodeFetch = require('node-fetch'); 2 | const TokenValidator = require('twilio-flex-token-validator').functionValidator; 3 | 4 | exports.handler = TokenValidator(async function (context, event, callback) { 5 | const response = new Twilio.Response(); 6 | response.appendHeader('Access-Control-Allow-Origin', '*'); 7 | response.appendHeader('Access-Control-Allow-Methods', 'OPTIONS POST'); 8 | response.appendHeader('Content-Type', 'application/json'); 9 | response.appendHeader('Access-Control-Allow-Headers', 'Content-Type'); 10 | 11 | console.log('hold-conference-participant parameters:'); 12 | Object.keys(event).forEach(key => { 13 | if (key !== "token" || key !== "Token") { 14 | console.log(`${key}: ${event[key]}`); 15 | } 16 | }); 17 | 18 | if (Object.keys(event).length === 0) { 19 | console.log('Empty event object, likely an OPTIONS request'); 20 | return callback(null, response); 21 | } 22 | 23 | const { 24 | conference, 25 | participant, 26 | hold 27 | } = event; 28 | 29 | console.log(`${hold ? 'Holding' : 'Unholding'} participant ${participant} ` 30 | + `in conference ${conference}`); 31 | const client = context.getTwilioClient(); 32 | const participantsResponse = await client.conferences(conference) 33 | .participants(participant) 34 | .update({ 35 | hold, 36 | }); 37 | 38 | 39 | response.setBody({ 40 | ...participantsResponse, 41 | status: 200, 42 | _version: undefined 43 | }); 44 | 45 | console.log(`Participant ${participant} updated in conference \ 46 | ${conference}. Participant response properties:`); 47 | 48 | Object.keys(response.body).forEach(key => { 49 | console.log(` ${key}:`, response.body[key]); 50 | }); 51 | 52 | return callback(null, response); 53 | }); 54 | -------------------------------------------------------------------------------- /dialpad-functions/functions/external-transfer/remove-conference-participant.js: -------------------------------------------------------------------------------- 1 | const nodeFetch = require('node-fetch'); 2 | const TokenValidator = require('twilio-flex-token-validator').functionValidator; 3 | 4 | exports.handler = TokenValidator(async function (context, event, callback) { 5 | const response = new Twilio.Response(); 6 | response.appendHeader('Access-Control-Allow-Origin', '*'); 7 | response.appendHeader('Access-Control-Allow-Methods', 'OPTIONS POST'); 8 | response.appendHeader('Content-Type', 'application/json'); 9 | response.appendHeader('Access-Control-Allow-Headers', 'Content-Type'); 10 | 11 | console.log('remove-conference-participant parameters:'); 12 | Object.keys(event).forEach(key => { 13 | if (key !== "token" || key !== "Token") { 14 | console.log(`${key}: ${event[key]}`); 15 | } 16 | }); 17 | 18 | if (Object.keys(event).length === 0) { 19 | console.log('Empty event object, likely an OPTIONS request'); 20 | return callback(null, response); 21 | } 22 | 23 | const { 24 | conference, 25 | participant 26 | } = event; 27 | 28 | console.log(`Removing participant ${participant} from conference ${conference}`); 29 | const client = context.getTwilioClient(); 30 | const participantResponse = await client 31 | .conferences(conference) 32 | .participants(participant) 33 | .remove(); 34 | console.log('Participant response properties:'); 35 | Object.keys(participantResponse).forEach(key => { 36 | console.log(`${key}: ${participantResponse[key]}`); 37 | }); 38 | 39 | return callback(null, response); 40 | }); 41 | -------------------------------------------------------------------------------- /dialpad-functions/functions/external-transfer/update-conference-participant.js: -------------------------------------------------------------------------------- 1 | const nodeFetch = require('node-fetch'); 2 | const TokenValidator = require('twilio-flex-token-validator').functionValidator; 3 | 4 | exports.handler = TokenValidator(async function (context, event, callback) { 5 | const response = new Twilio.Response(); 6 | response.appendHeader('Access-Control-Allow-Origin', '*'); 7 | response.appendHeader('Access-Control-Allow-Methods', 'OPTIONS POST'); 8 | response.appendHeader('Content-Type', 'application/json'); 9 | response.appendHeader('Access-Control-Allow-Headers', 'Content-Type'); 10 | 11 | console.log('update-conference-participant parameters:'); 12 | Object.keys(event).forEach(key => { 13 | if (key !== "token" || key !== "Token") { 14 | console.log(`${key}: ${event[key]}`); 15 | } 16 | }); 17 | 18 | if (Object.keys(event).length === 0) { 19 | console.log('Empty event object, likely an OPTIONS request'); 20 | return callback(null, response); 21 | } 22 | 23 | const { 24 | conference, 25 | participant, 26 | endConferenceOnExit 27 | } = event; 28 | 29 | console.log(`Updating participant ${participant} in conference ${conference}`); 30 | const client = context.getTwilioClient(); 31 | const participantResponse = await client 32 | .conferences(conference) 33 | .participants(participant) 34 | .update({ 35 | endConferenceOnExit 36 | }).catch(e => { 37 | console.error(e); 38 | return {}; 39 | }); 40 | console.log('Participant response properties:'); 41 | Object.keys(participantResponse).forEach(key => { 42 | console.log(`${key}: ${participantResponse[key]}`); 43 | }); 44 | 45 | response.setBody({ 46 | status: 200 47 | }); 48 | 49 | return callback(null, response); 50 | }); 51 | -------------------------------------------------------------------------------- /dialpad-functions/functions/outbound-dialing/callHandlerTwiml.protected.js: -------------------------------------------------------------------------------- 1 | exports.handler = async function (context, event, callback) { 2 | 3 | console.log("callhandler for: ", event.CallSid); 4 | console.log("worker:", event.workerContactUri); 5 | console.log("to:", event.To); 6 | console.log("workflowSid:", context.TWILIO_WORKFLOW_SID); 7 | 8 | var taskAttributes = { 9 | targetWorker: event.workerContactUri, 10 | autoAnswer: "true", 11 | type: "outbound", 12 | direction: "outbound", 13 | name: event.To 14 | }; 15 | 16 | let twiml = new Twilio.twiml.VoiceResponse(); 17 | 18 | var enqueue = twiml.enqueue({ 19 | workflowSid: `${context.TWILIO_WORKFLOW_SID}` 20 | }); 21 | 22 | enqueue.task(JSON.stringify(taskAttributes)); 23 | callback(null, twiml); 24 | } 25 | 26 | -------------------------------------------------------------------------------- /dialpad-functions/functions/outbound-dialing/callStatusUpdateHandler.protected.js: -------------------------------------------------------------------------------- 1 | /* 2 | Function for recieving call status updates and pushing them into 3 | a sync document monitored by the worker. This allows the front end 4 | to recognize when the call is queued, ringing, answered and for 5 | the front end to recieve the task 6 | */ 7 | 8 | const updateSyncDoc = (context, event) => { 9 | const client = context.getTwilioClient(); 10 | const syncService = client.sync.services(context.TWILIO_SYNC_SERVICE_SID); 11 | 12 | return new Promise(function (resolve, reject) { 13 | syncService.documents(event.workerSyncDoc) 14 | .update({ 15 | data: { 16 | autoDial: false, 17 | call: { 18 | callSid: event.CallSid, 19 | callStatus: event.CallStatus 20 | } 21 | } 22 | }) 23 | .then(() => resolve()) 24 | .catch(error => { 25 | console.log("ERROR updating sync map: ", error); 26 | resolve(); 27 | }) 28 | }) 29 | } 30 | 31 | exports.handler = async function (context, event, callback) { 32 | 33 | console.log("callback for: ", event.CallSid); 34 | console.log("status: ", event.CallStatus); 35 | console.log("workerSyncDoc: ", event.workerSyncDoc); 36 | console.log("workerSid: ", event.workerSid); 37 | 38 | const response = new Twilio.Response(); 39 | 40 | response.appendHeader('Access-Control-Allow-Origin', '*'); 41 | response.appendHeader('Access-Control-Allow-Methods', 'OPTIONS POST'); 42 | response.appendHeader('Content-Type', 'application/json'); 43 | response.appendHeader('Access-Control-Allow-Headers', 'Content-Type'); 44 | 45 | // We dont need to know about calls that are completed as this is the natural part of the life cycle after the call has been answered 46 | if (event.CallStatus !== "completed") { 47 | updateSyncDoc(context, event).then(() => callback(null, response)) 48 | } else { 49 | callback(null, response) 50 | } 51 | 52 | }; 53 | 54 | 55 | -------------------------------------------------------------------------------- /dialpad-functions/functions/outbound-dialing/callTreatment.js: -------------------------------------------------------------------------------- 1 | const nodeFetch = require('node-fetch'); 2 | const TokenValidator = require('twilio-flex-token-validator').functionValidator; 3 | 4 | exports.handler = TokenValidator(async function (context, event, callback) { 5 | 6 | console.log("callTreament: callTreament event parameters"); 7 | console.log("callTreament: To: ", event.To); 8 | 9 | const response = new Twilio.Response(); 10 | 11 | response.appendHeader('Access-Control-Allow-Origin', '*'); 12 | response.appendHeader('Access-Control-Allow-Methods', 'OPTIONS POST'); 13 | response.appendHeader('Content-Type', 'application/json'); 14 | response.appendHeader('Access-Control-Allow-Headers', 'Content-Type'); 15 | 16 | // Add Environment variables to distinquish accounts 17 | if (context.ACCOUNT_SID == context.ACCOUNT_SID_Y) { 18 | //apply call treatments for this account 19 | response.setBody({ To: event.To }); 20 | } 21 | else { 22 | response.setBody({ To: event.To }); 23 | } 24 | 25 | callback(null, response); 26 | 27 | }); -------------------------------------------------------------------------------- /dialpad-functions/functions/outbound-dialing/endCall.js: -------------------------------------------------------------------------------- 1 | const nodeFetch = require('node-fetch'); 2 | const TokenValidator = require('twilio-flex-token-validator').functionValidator; 3 | 4 | function hangupCall(context, event) { 5 | 6 | const client = context.getTwilioClient(); 7 | return new Promise(function (resolve, reject) { 8 | client 9 | .calls(event.CallSid) 10 | .update({ status: "completed" }) 11 | .then(call => { 12 | console.log("terminated call: ", call.sid); 13 | resolve({ call: { callStatus: call.status, callSid: call.sid }, error: null }); 14 | }) 15 | .catch(error => { 16 | console.log("Failed to terminate call: ", data.callSid); 17 | resolve({ call: null, error }); 18 | }); 19 | }); 20 | } 21 | 22 | exports.handler = TokenValidator(async function (context, event, callback) { 23 | 24 | console.log("endCall for: ", event.CallSid); 25 | 26 | const response = new Twilio.Response(); 27 | 28 | response.appendHeader('Access-Control-Allow-Origin', '*'); 29 | response.appendHeader('Access-Control-Allow-Methods', 'OPTIONS POST'); 30 | response.appendHeader('Content-Type', 'application/json'); 31 | response.appendHeader('Access-Control-Allow-Headers', 'Content-Type'); 32 | 33 | const hangupCallResult = await hangupCall(context, event) 34 | if (hangupCallResult.error) { 35 | response.setStatusCode(hangupCallResult.error.status) 36 | } 37 | response.setBody(hangupCallResult); 38 | 39 | callback(null, response); 40 | 41 | }); -------------------------------------------------------------------------------- /dialpad-functions/functions/outbound-dialing/forceUpdateSyncDoc.js: -------------------------------------------------------------------------------- 1 | const nodeFetch = require('node-fetch'); 2 | const TokenValidator = require('twilio-flex-token-validator').functionValidator; 3 | 4 | const updateSyncDoc = (context, event) => { 5 | 6 | const client = context.getTwilioClient(); 7 | const syncService = client.sync.services(context.TWILIO_SYNC_SERVICE_SID); 8 | 9 | return new Promise(function (resolve, reject) { 10 | 11 | client.calls(event.callSid) 12 | .fetch() 13 | .then(call => { 14 | 15 | syncService.documents(event.syncDocName) 16 | .update({ 17 | data: { 18 | autoDial: false, 19 | call: { 20 | callSid: call.sid, 21 | callStatus: call.status 22 | } 23 | } 24 | }) 25 | .then(() => resolve()) 26 | .catch(error => { 27 | console.log("ERROR updating sync map: ", error); 28 | resolve(); 29 | }) 30 | }) 31 | .catch(error => { 32 | console.log("Unable to retrieve call for sid:", event.callSid); 33 | resolve() 34 | }) 35 | }) 36 | } 37 | 38 | exports.handler = TokenValidator(async function (context, event, callback) { 39 | 40 | console.log("forceUpdateSyncDoc request parameters:"); 41 | console.log("callSid:", event.callSid); 42 | console.log("syncDocName: ", event.syncDocName); 43 | 44 | const response = new Twilio.Response(); 45 | 46 | response.appendHeader('Access-Control-Allow-Origin', '*'); 47 | response.appendHeader('Access-Control-Allow-Methods', 'OPTIONS POST'); 48 | response.appendHeader('Content-Type', 'application/json'); 49 | response.appendHeader('Access-Control-Allow-Headers', 'Content-Type'); 50 | 51 | await updateSyncDoc(context, event) 52 | 53 | callback(null, response); 54 | 55 | }); -------------------------------------------------------------------------------- /dialpad-functions/functions/outbound-dialing/invokeOutboundCall.protected.js: -------------------------------------------------------------------------------- 1 | /* 2 | Function for triggering an outbound call from a third part application 3 | */ 4 | exports.handler = async function (context, event, callback) { 5 | 6 | console.log("number to dial: ", event.To); 7 | console.log("workerContactUri:", event.workerContactUri); 8 | 9 | const response = new Twilio.Response(); 10 | 11 | response.appendHeader('Access-Control-Allow-Origin', '*'); 12 | response.appendHeader('Access-Control-Allow-Methods', 'OPTIONS POST'); 13 | response.appendHeader('Content-Type', 'application/json'); 14 | response.appendHeader('Access-Control-Allow-Headers', 'Content-Type'); 15 | 16 | const client = context.getTwilioClient(); 17 | const syncService = client.sync.services(context.TWILIO_SYNC_SERVICE_SID); 18 | 19 | syncService.documents(event.workerContactUri + ".outbound-call") 20 | .update({ 21 | data: { 22 | autoDial: true, 23 | numberToDial: event.To, 24 | } 25 | }).then(newDoc => { 26 | callback(null, response); 27 | }) 28 | }; -------------------------------------------------------------------------------- /dialpad-functions/functions/outbound-dialing/makeCall.js: -------------------------------------------------------------------------------- 1 | const nodeFetch = require('node-fetch'); 2 | const TokenValidator = require('twilio-flex-token-validator').functionValidator; 3 | 4 | async function getCallTreatment(context, event) { 5 | 6 | console.log('makeCall: Getting Call Treatment'); 7 | 8 | const callTreatmentUrl = encodeURI( 9 | "https://" + 10 | event.functionsDomain + 11 | "/outbound-dialing/callTreatment?Token=" + 12 | event.Token + 13 | "&To=" + 14 | event.To 15 | ); 16 | 17 | const fetchResponse = await nodeFetch(callTreatmentUrl, { 18 | method: 'POST', 19 | headers: { 20 | 'Content-Type': 'application/json', 21 | }, 22 | body: JSON.stringify({ 23 | To: event.To 24 | }) 25 | }); 26 | 27 | const callTreatmentResponse = await fetchResponse.json(); 28 | console.log('makeCall: CallTreatmentResponse: ', callTreatmentResponse) 29 | return callTreatmentResponse.To; 30 | 31 | } 32 | 33 | function makeOutboundCall(context, event) { 34 | const client = context.getTwilioClient(); 35 | 36 | return new Promise(async function (resolve, reject) { 37 | const callHandlerCallbackURL = encodeURI( 38 | "https://" + 39 | event.functionsDomain + 40 | "/outbound-dialing/callHandlerTwiml?workerContactUri=" + 41 | event.workerContactUri 42 | ); 43 | 44 | const statusCallbackURL = encodeURI( 45 | "https://" + 46 | event.functionsDomain + 47 | "/outbound-dialing/callStatusUpdateHandler?workerSyncDoc=" + 48 | event.workerContactUri + 49 | ".outbound-call" + 50 | "&workerSid=" + 51 | event.workerSid 52 | ); 53 | 54 | const to = await getCallTreatment(context, event); 55 | 56 | client.calls 57 | .create({ 58 | url: callHandlerCallbackURL, 59 | to: to, 60 | from: event.From, 61 | statusCallback: statusCallbackURL, 62 | statusCallbackEvent: ["ringing", "answered", "completed"] 63 | }) 64 | .then(call => { 65 | console.log("makeCall: call created: ", call.sid); 66 | resolve({ call: call, error: null }); 67 | }) 68 | .catch(error => { 69 | console.log("makeCall: call creation failed"); 70 | resolve({ call: null, error }); 71 | }); 72 | }); 73 | } 74 | 75 | exports.handler = TokenValidator(async function (context, event, callback) { 76 | 77 | console.log("makeCall: makeCall request parameters:"); 78 | console.log("makeCall: to:", event.To); 79 | console.log("makeCall: from:", event.From); 80 | console.log("makeCall: workerContactUri:", event.workerContactUri); 81 | console.log("makeCall: callbackDomain:", event.functionsDomain); 82 | console.log("makeCall: workerSid", event.workerSid); 83 | 84 | const response = new Twilio.Response(); 85 | 86 | response.appendHeader('Access-Control-Allow-Origin', '*'); 87 | response.appendHeader('Access-Control-Allow-Methods', 'OPTIONS POST'); 88 | response.appendHeader('Content-Type', 'application/json'); 89 | response.appendHeader('Access-Control-Allow-Headers', 'Content-Type'); 90 | 91 | const makeCallResult = await makeOutboundCall(context, event) 92 | if (makeCallResult.error) { 93 | response.setStatusCode(makeCallResult.error.status) 94 | } 95 | response.setBody(makeCallResult); 96 | 97 | callback(null, response); 98 | 99 | }); -------------------------------------------------------------------------------- /dialpad-functions/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "dialpad-functions", 3 | "version": "0.0.0", 4 | "private": true, 5 | "scripts": { 6 | "test": "echo \"Error: no test specified\" && exit 1", 7 | "start": "twilio-run --env" 8 | }, 9 | "devDependencies": { 10 | "twilio-run": "^2.0.0" 11 | }, 12 | "engines": { 13 | "node": "8.10.0" 14 | }, 15 | "dependencies": { 16 | "node-fetch": "^2.6.0", 17 | "twilio-flex-token-validator": "^1.5.1" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "plugin-outbound-dialing-with-conference", 3 | "description": "Example front end implementation of a dialpad that creates outbound calls via a voice sdk and sends call to worker via task router", 4 | "version": "1.3.0", 5 | "author": "Jared Hunter ", 6 | "private": true, 7 | "scripts": { 8 | "postinstall": "flex-check-start", 9 | "prestart": "flex-check-start", 10 | "start": "react-app-rewired start", 11 | "build": "react-app-rewired build", 12 | "test": "react-app-rewired test --env=jsdom", 13 | "eject": "react-app-rewired eject" 14 | }, 15 | "devDependencies": { 16 | "@twilio/flex-ui": "^1.14.1", 17 | "react-app-rewire-flex-plugin": "^1", 18 | "react-app-rewired": "^1.6.2" 19 | }, 20 | "dependencies": { 21 | "flex-plugin": "1.3.4", 22 | "react": "16.5.2", 23 | "react-click-n-hold": "^1.0.7", 24 | "react-dom": "16.5.2", 25 | "react-scripts": "1.1.5" 26 | }, 27 | "config-overrides-path": "node_modules/react-app-rewire-flex-plugin" 28 | } 29 | -------------------------------------------------------------------------------- /public/appConfig.example.js: -------------------------------------------------------------------------------- 1 | // your account sid 2 | var accountSid = 'accountSid'; 3 | 4 | // set to /plugins.json for local dev 5 | // set to /plugins.local.build.json for testing your build 6 | // set to "" for the default live plugin loader 7 | var pluginServiceUrl = '/plugins.json'; 8 | 9 | var appConfig = { 10 | pluginService: { 11 | enabled: true, 12 | url: pluginServiceUrl, 13 | }, 14 | sso: { 15 | accountSid: accountSid 16 | }, 17 | ytica: false, 18 | logLevel: 'info', 19 | showSupervisorDesktopView: true, 20 | }; 21 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Twilio Flex 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /public/plugins.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "OutboundDialingWithConferencePlugin", 4 | "version": "1.3.0", 5 | "class": "OutboundDialingWithConferencePlugin", 6 | "requires": [ 7 | { 8 | "@twilio/flex-ui": "^1" 9 | } 10 | ], 11 | "src": "http://localhost:8080/plugin-outbound-dialing-with-conference.js" 12 | } 13 | ] -------------------------------------------------------------------------------- /public/plugins.local.build.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "OutboundDialingWithConferencePlugin", 4 | "version": "1.3.0", 5 | "class": "OutboundDialingWithConferencePlugin", 6 | "requires": [ 7 | { 8 | "@twilio/flex-ui": "^1" 9 | } 10 | ], 11 | "src": "http://127.0.0.1:8085" 12 | } 13 | ] -------------------------------------------------------------------------------- /screenshot/create-activity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twilio-labs/plugin-flex-outbound-dialpad/cae957bacc9d46f333cfae7c77e0eb665a8a14ff/screenshot/create-activity.png -------------------------------------------------------------------------------- /screenshot/dialpad.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twilio-labs/plugin-flex-outbound-dialpad/cae957bacc9d46f333cfae7c77e0eb665a8a14ff/screenshot/dialpad.gif -------------------------------------------------------------------------------- /screenshot/dialpad.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twilio-labs/plugin-flex-outbound-dialpad/cae957bacc9d46f333cfae7c77e0eb665a8a14ff/screenshot/dialpad.png -------------------------------------------------------------------------------- /screenshot/external-conference-warm-transfer-demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twilio-labs/plugin-flex-outbound-dialpad/cae957bacc9d46f333cfae7c77e0eb665a8a14ff/screenshot/external-conference-warm-transfer-demo.gif -------------------------------------------------------------------------------- /screenshot/workflow-config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twilio-labs/plugin-flex-outbound-dialpad/cae957bacc9d46f333cfae7c77e0eb665a8a14ff/screenshot/workflow-config.png -------------------------------------------------------------------------------- /src/OutboundDialingWithConferencePlugin.js: -------------------------------------------------------------------------------- 1 | import { FlexPlugin } from "flex-plugin"; 2 | import { SyncClient } from "twilio-sync"; 3 | import { Manager } from "@twilio/flex-ui"; 4 | 5 | //independent features 6 | import { loadDialPadInterface } from "./components/dialpad" 7 | import { loadExternalTransferInterface } from "./components/external-transfer" 8 | 9 | // common libraries 10 | import { registerReservationCreatedExtensions } from "./eventListeners/workerClient/reservationCreated"; 11 | import { registerActionExtensions } from "./eventListeners/actionsFramework" 12 | 13 | import "./notifications/CustomNotifications"; 14 | 15 | const PLUGIN_NAME = "OutboundDialingWithConferencePlugin"; 16 | 17 | export const FUNCTIONS_HOSTNAME = ''; 18 | export const DEFAULT_FROM_NUMBER = ""; // twilio account or verified number 19 | export const SYNC_CLIENT = new SyncClient(Manager.getInstance().user.token); 20 | 21 | function tokenUpdateHandler() { 22 | 23 | console.log("OUTBOUND DIALPAD: Refreshing SYNC_CLIENT Token"); 24 | 25 | const loginHandler = Manager.getInstance().store.getState().flex.session.loginHandler; 26 | 27 | const tokenInfo = loginHandler.getTokenInfo(); 28 | const accessToken = tokenInfo.token; 29 | 30 | SYNC_CLIENT.updateToken(accessToken); 31 | } 32 | 33 | 34 | export default class OutboundDialingWithConferencePlugin extends FlexPlugin { 35 | 36 | 37 | constructor() { 38 | super(PLUGIN_NAME); 39 | 40 | } 41 | 42 | 43 | /** 44 | * This code is run when your plugin is being started 45 | * Use this to modify any UI components or attach to the actions framework 46 | * 47 | * @param flex { typeof import('@twilio/flex-ui') } 48 | * @param manager { import('@twilio/flex-ui').Manager } 49 | */ 50 | init(flex, manager) { 51 | 52 | var translationStrings = { 53 | DIALPADExternalTransferHoverOver: "Add Conference Participant", 54 | DIALPADExternalTransferPhoneNumberPopupHeader: "Enter phone number to add to the conference", 55 | DIALPADExternalTransferPhoneNumberPopupTitle: "Phone Number", 56 | DIALPADExternalTransferPhoneNumberPopupCancel: "Cancel", 57 | DIALPADExternalTransferPhoneNumberPopupDial: "Dial" 58 | } 59 | 60 | //add translationStrings into manager.strings, preserving anything thats already there - this allows language to be updated outside of updating this plugin 61 | manager.strings = { ...translationStrings, ...manager.strings } 62 | 63 | //Add listener to loginHandler to refresh token when it expires 64 | manager.store.getState().flex.session.loginHandler.on("tokenUpdated", tokenUpdateHandler); 65 | // Add custom extensions 66 | loadDialPadInterface.bind(this)(flex, manager); 67 | loadExternalTransferInterface.bind(this)(flex, manager) 68 | registerReservationCreatedExtensions(manager); 69 | registerActionExtensions(); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/components/dialpad/DialPad.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { Actions, Manager, Notifications } from "@twilio/flex-ui"; 3 | import { 4 | withStyles, 5 | MuiThemeProvider, 6 | createMuiTheme 7 | } from "@material-ui/core/styles"; 8 | import Phone from "@material-ui/icons/Phone"; 9 | import CallEnd from "@material-ui/icons/CallEnd"; 10 | import ClickNHold from "react-click-n-hold"; 11 | import Card from "@material-ui/core/Card"; 12 | import CardContent from "@material-ui/core/CardContent"; 13 | import { green, red } from "@material-ui/core/colors"; 14 | import Button from "@material-ui/core/Button"; 15 | import Backspace from "@material-ui/icons/Backspace"; 16 | 17 | import classNames from "classnames"; 18 | import { connect } from "react-redux"; 19 | 20 | 21 | import { blockForOutboundCall } from "../../eventListeners/workerClient/reservationCreated"; 22 | import { CallControls, CallStatus, RingingService, DialpadSyncDoc } from '../../utilities/DialPadUtil' 23 | 24 | 25 | 26 | const styles = theme => ({ 27 | main: { 28 | width: "100%", 29 | height: "100%", 30 | display: "flex", 31 | justifyContent: "center", 32 | alignItems: "center" 33 | }, 34 | dialpad: { 35 | width: "100%", 36 | maxHeight: "700px", 37 | maxWidth: "400px", 38 | backgroundColor: theme.SideNav.Container.background 39 | }, 40 | headerInputContainer: { 41 | display: "flex", 42 | justifyContent: "stretch", 43 | alignItems: "center", 44 | marginBottom: "25px", 45 | marginLeft: "30px" 46 | }, 47 | headerInput: { 48 | minHeight: "40px", 49 | maxHeight: "40px", 50 | borderBottom: "2px solid white", 51 | display: "flex", 52 | justifyContent: "flex-start", 53 | alignItems: "center", 54 | borderRadius: theme.shape.borderRadius, 55 | fontSize: "1.5em", 56 | padding: theme.spacing.unit, 57 | flexGrow: 1, 58 | marginRight: "5px", 59 | color: "white" 60 | }, 61 | backspaceButton: { 62 | cursor: "pointer", 63 | color: theme.palette.grey[100], 64 | "&:hover": { 65 | opacity: ".4" 66 | } 67 | }, 68 | numpadContainer: { 69 | margin: theme.spacing.unit 70 | }, 71 | numpadRowContainer: { 72 | display: "flex", 73 | marginBottom: "15px", 74 | justifyContent: "center" 75 | }, 76 | numberButtonContainer: { 77 | width: "33%" 78 | }, 79 | numberButton: { 80 | display: "block", 81 | margin: theme.spacing.unit, 82 | width: "60px", 83 | height: "60px", 84 | borderRadius: "100%", 85 | paddingBottom: "20%", 86 | fontSize: "1.2em", 87 | fontWeight: "700", 88 | textAlign: "center" 89 | }, 90 | functionButton: { 91 | paddingBottom: "0%" 92 | }, 93 | hide: { 94 | visibility: "hidden" 95 | } 96 | }); 97 | 98 | const greenButton = createMuiTheme({ 99 | palette: { 100 | primary: green 101 | }, 102 | typography: { 103 | useNextVariants: true 104 | } 105 | }); 106 | 107 | const redButton = createMuiTheme({ 108 | palette: { 109 | primary: red 110 | }, 111 | typography: { 112 | useNextVariants: true 113 | } 114 | }); 115 | 116 | export class DialPad extends React.Component { 117 | constructor(props) { 118 | super(props); 119 | 120 | this.token = Manager.getInstance().user.token; 121 | this.syncDocName = `${this.props.workerContactUri}.outbound-call`; 122 | } 123 | 124 | buttons = [ 125 | [ 126 | { 127 | value: "1", 128 | letters: "" 129 | }, 130 | { 131 | value: "2", 132 | letters: "abc" 133 | }, 134 | { 135 | value: "3", 136 | letters: "def" 137 | } 138 | ], 139 | [ 140 | { 141 | value: "4", 142 | letters: "ghi" 143 | }, 144 | { 145 | value: "5", 146 | letters: "jkl" 147 | }, 148 | { 149 | value: "6", 150 | letters: "mno" 151 | } 152 | ], 153 | [ 154 | { 155 | value: "7", 156 | letters: "pqrs" 157 | }, 158 | { 159 | value: "8", 160 | letters: "tuv" 161 | }, 162 | { 163 | value: "9", 164 | letters: "wxyz" 165 | } 166 | ], 167 | [ 168 | { 169 | value: "*", 170 | letters: " " 171 | }, 172 | { 173 | value: "0", 174 | letters: "+" 175 | }, 176 | { 177 | value: "#", 178 | letters: " " 179 | } 180 | ] 181 | ]; 182 | 183 | numpad = this.buttons.map((rowItem, rowIndex) => { 184 | const { classes } = this.props; 185 | 186 | return ( 187 |
188 | {rowItem.map((item, itemIndex) => { 189 | return ( 190 |
191 | {item.value !== "0" 192 | ? this.standardNumberButton(item) 193 | : this.clickNHoldButton(item)} 194 |
195 | ); 196 | })} 197 |
198 | ); 199 | }); 200 | 201 | standardNumberButton(item) { 202 | const { classes } = this.props; 203 | return ( 204 | 223 | ); 224 | } 225 | 226 | clickNHoldButton(item) { 227 | const { classes } = this.props; 228 | return ( 229 | this.buttonPlusPress(e, item)} 232 | onEnd={(e, threshold) => this.buttonZeroPress(e, threshold, item)} 233 | > 234 | 252 | 253 | ); 254 | } 255 | 256 | functionButtons() { 257 | const { classes, call, activeCall } = this.props; 258 | 259 | return ( 260 |
261 | {CallStatus.showGreenButton(call, activeCall) ? ( 262 |
263 | 264 | 279 | 280 |
281 | ) : ( 282 |
283 | )} 284 | {CallStatus.showRedButton(call) ? ( 285 |
286 | 287 | 300 | 301 |
302 | ) : ( 303 |
304 | )} 305 |
306 | ); 307 | } 308 | 309 | componentDidMount() { 310 | console.log("OUTBOUND DIALPAD: Mounting Dialpad Popup"); 311 | 312 | this.props.setInitialActivity(Manager.getInstance().workerClient.activity.name) 313 | 314 | document.addEventListener("keydown", this.eventkeydownListener, false); 315 | document.addEventListener("keyup", this.eventListener, false); 316 | document.addEventListener("paste", this.pasteListener, false); 317 | 318 | blockForOutboundCall(); 319 | this.setAgentUnavailable(); 320 | 321 | 322 | // As this is only checked when the dialpad is mounted 323 | // auto dial only works when the dialpad is closed 324 | if (this.props.autoDial) { 325 | console.log("OUTBOUND DIALPAD: Auto Dial triggered"); 326 | this.pressDial(); 327 | } 328 | } 329 | 330 | componentWillUnmount() { 331 | console.log("OUTBOUND DIALPAD: Unmounting Dialpad Popup"); 332 | 333 | 334 | DialpadSyncDoc.clearSyncDoc(); 335 | document.removeEventListener("keydown", this.eventkeydownListener, false); 336 | document.removeEventListener("keyup", this.eventListener, false); 337 | document.removeEventListener("paste", this.pasteListener, false); 338 | 339 | // make sure dialpad always stops ringing if its closed 340 | RingingService.stopRinging(); 341 | } 342 | 343 | setAgentUnavailable() { 344 | return new Promise((resolve, reject) => { 345 | 346 | Actions.invokeAction("SetActivity", { 347 | activityName: "Outbound Calls" 348 | }) 349 | .then(() => { 350 | console.log("OUTBOUND DIALPAD: Agent is now on Outbound Calls"); 351 | resolve(); 352 | }) 353 | .catch(error => { 354 | Actions.invokeAction("SetActivity", { 355 | activityName: "Offline" 356 | }) 357 | .then(() => { 358 | console.log("OUTBOUND DIALPAD: Agent is now Offline"); 359 | resolve(); 360 | }) 361 | .catch(() => { 362 | Notifications.showNotification("ActivityStateUnavailable", { 363 | state1: "Outbound Calls", 364 | state2: "Offline" 365 | }); 366 | reject(); 367 | }); 368 | }); 369 | }) 370 | } 371 | 372 | noVoiceTasksOpen() { 373 | const { tasks } = this.props; 374 | 375 | var response = true; 376 | tasks.forEach(value => { 377 | if (value.channelType === "voice") { 378 | console.warn("OUTBOUND DIALPAD: Voice task is still open, probably in wrap up, canceling dial"); 379 | response = false; 380 | } 381 | }) 382 | 383 | return response; 384 | }; 385 | 386 | pressDial() { 387 | console.log("OUTBOUND DIALPAD: Dial Button Pressed"); 388 | 389 | const { call } = this.props; 390 | 391 | if ( 392 | this.noVoiceTasksOpen() && 393 | this.props.number !== "" && 394 | CallStatus.canDial(call) && 395 | this.props.activeCall === "" 396 | ) { 397 | this.orchestrateMakeCall() 398 | 399 | } else { 400 | Notifications.showNotification("CantDialOut"); 401 | } 402 | } 403 | 404 | orchestrateMakeCall() { 405 | console.log("OUTBOUND DIALPAD: Orhcestrating call"); 406 | 407 | const { setCallState } = this.props; 408 | 409 | // setup an interim callStatus of dialing, while we make the backend call 410 | // this will block any other calls being made 411 | setCallState({ callSid: "", callStatus: "dialing" }) 412 | 413 | CallControls.makeCall(this.props.number) 414 | .then(response => { 415 | 416 | if (response.error) { 417 | const { message } = response.error 418 | console.error("OUTBOUND DIALPAD: failure placing call", message); 419 | 420 | Notifications.showNotification("BackendError", { 421 | message: message 422 | }); 423 | 424 | // reset the "dialing" status the blocked further calls 425 | setCallState({ callSid: "", callStatus: "" }) 426 | } else { 427 | console.log("OUTBOUND DIALPAD: call succesfully placed"); 428 | } 429 | }) 430 | .catch(error => { 431 | console.error("OUTBOUND DIALPAD: failure placing call", error); 432 | Notifications.showNotification("BackendError", { 433 | message: error.error.message 434 | }); 435 | 436 | // reset the "dialing" status the blocked further calls 437 | setCallState({ callSid: "", callStatus: "" }) 438 | }) 439 | 440 | } 441 | 442 | 443 | pressHangup(callSid) { 444 | // if hangup occurs while queued, twilio fails and also fails 445 | // to handle future hang up requests 446 | if (this.props.call.callStatus !== "queued") { 447 | 448 | CallControls.hangupCall(callSid) 449 | .then(response => { 450 | const { call, error } = response; 451 | if (error) { 452 | console.error("OUTBOUND DIALPAD: Issue when hanging up call, ", response.error.message); 453 | Notifications.showNotification("BackendError", { 454 | message: response.error.message 455 | }); 456 | } 457 | if (CallStatus.isTerminalState(call)) { 458 | DialpadSyncDoc.clearSyncDoc(); 459 | RingingService.stopRinging(); 460 | } 461 | }) 462 | .catch(error => { 463 | console.error("OUTBOUND DIALPAD: Unknown issue calling hangup, ", error); 464 | Notifications.showNotification("BackendError", { 465 | message: error 466 | }); 467 | }) 468 | } 469 | } 470 | 471 | eventListener = e => this.keyPressListener(e); 472 | 473 | eventkeydownListener = e => this.keydownListener(e); 474 | 475 | pasteListener = e => { 476 | const paste = (e.clipboardData || window.clipboardData) 477 | .getData("text") 478 | .replace(/\D/g, ""); //strip all non numeric characters from paste 479 | for (var i = 0; i < paste.length; i++) { 480 | this.buttonPress(paste.charAt(i)); 481 | } 482 | }; 483 | 484 | keydownListener(e) { 485 | if (e.keyCode === 8) { 486 | e.preventDefault(); 487 | e.stopPropagation(); 488 | this.backspace(); 489 | } 490 | } 491 | 492 | keyPressListener(e) { 493 | const { call } = this.props 494 | e.preventDefault(); 495 | e.stopPropagation(); 496 | if ((e.keyCode > 47 && e.keyCode < 58) || (e.keyCode >= 96 && e.keyCode <= 105) || e.keyCode === 187 || e.keyCode === 107) { 497 | //listen to 0-9 & + 498 | this.buttonPress(e.key); 499 | } else if (e.keyCode === 13) { 500 | //listen for enter 501 | if (CallStatus.isRinging(call)) { 502 | this.pressHangup(this.props.call.callSid); 503 | } else if ( 504 | call.callStatus === "" || 505 | CallStatus.isTerminalState(call) 506 | ) { 507 | this.pressDial(); 508 | } 509 | } 510 | } 511 | 512 | backspaceAll() { 513 | this.props.setNumberState(""); 514 | } 515 | 516 | backspace() { 517 | this.props.setNumberState(this.props.number.substring(0, this.props.number.length - 1)); 518 | } 519 | 520 | buttonPress(value) { 521 | const activeCall = this.props.activeCall; 522 | 523 | if (activeCall === "") { 524 | // e.164 max langh is 15 + 1 for the addition symbol 525 | if (this.props.number.length < 16) { 526 | this.props.setNumberState(this.props.number + value); 527 | } 528 | } else { 529 | activeCall.sendDigits(value); 530 | } 531 | } 532 | 533 | buttonPlusPress(e, item) { 534 | this.buttonPress(item.letters); 535 | } 536 | 537 | buttonZeroPress(e, threshold, item) { 538 | e.preventDefault(); 539 | e.stopPropagation(); 540 | if (!threshold) { 541 | this.buttonPress(item.value); 542 | } 543 | } 544 | 545 | render() { 546 | const { classes } = this.props; 547 | 548 | return ( 549 |
550 | 551 | 552 |
553 |
{this.props.number}
554 | 559 | 560 | 561 |
562 |
563 | {this.numpad.map(button => button)} 564 | {this.functionButtons()} 565 |
566 |
567 |
568 |
569 | ); 570 | } 571 | } 572 | 573 | const mapStateToProps = state => { 574 | return { 575 | tasks: state.flex.worker.tasks, 576 | phoneNumber: state.flex.worker.attributes.phone, 577 | workerContactUri: state.flex.worker.attributes.contact_uri, 578 | activeCall: 579 | typeof state.flex.phone.connection === "undefined" 580 | ? "" 581 | : state.flex.phone.connection.source, 582 | available: state.flex.worker.activity.available 583 | }; 584 | }; 585 | 586 | export default connect(mapStateToProps)(withStyles(styles)(DialPad)); 587 | -------------------------------------------------------------------------------- /src/components/dialpad/DialPadLauncher.js: -------------------------------------------------------------------------------- 1 | import * as React from "react"; 2 | 3 | import { IconButton, Notifications, Actions } from "@twilio/flex-ui"; 4 | import Dialog from "@material-ui/core/Dialog"; 5 | import PropTypes from "prop-types"; 6 | import DialPad from "./DialPad"; 7 | import Close from "@material-ui/icons/Close"; 8 | import styled from "react-emotion"; 9 | import { withStyles } from "@material-ui/core/styles"; 10 | import { CallStatus, RingingService, DialpadSyncDoc } from '../../utilities/DialPadUtil' 11 | import { unblockForOutBoundCall } from "../../eventListeners/workerClient/reservationCreated"; 12 | 13 | const StyledDialog = withStyles({ 14 | root: { 15 | width: "100%" 16 | } 17 | })(({ classes, ...other }) => ); 18 | 19 | 20 | class DialPadDialog extends React.Component { 21 | 22 | constructor(props) { 23 | super(props); 24 | 25 | this.state = { 26 | autoDial: false, 27 | numberToDial: "", 28 | call: { callSid: "", callStatus: "" } 29 | }; 30 | 31 | this.setCallState = this.setCallState.bind(this); 32 | this.setNumberState = this.setNumberState.bind(this); 33 | this.setInitialActivity = this.setInitialActivity.bind(this); 34 | } 35 | 36 | 37 | 38 | componentDidMount() { 39 | console.log("OUTBOUND DIALPAD: Mounting DialPadLauncher v1.3.0"); 40 | this.initSyncListener(); 41 | } 42 | 43 | componentWillUnmount() { 44 | console.log("OUTBOUND DIALPAD: Unmounting DialPadLauncher"); 45 | } 46 | 47 | setInitialActivity(activity) { 48 | this.initialActivity = activity 49 | console.log("OUTBOUND DIALPAD: Initial activity when dialpad launched", this.initialActivity); 50 | } 51 | 52 | initSyncListener() { 53 | 54 | const { openDialpad } = this.props; 55 | 56 | DialpadSyncDoc.getDialpadSyncDoc() 57 | .then(doc => { 58 | 59 | console.log("OUTBOUND DIALPAD: Initial Sync Doc State: ", doc.value); 60 | 61 | //forcing update incase call status event callback has somehow 62 | //failed to update sync doc 63 | if (doc.value && doc.value.call && doc.value.call.callSid) { 64 | console.log("OUTBOUND DIALPAD: forcing update of sync doc for initial setup"); 65 | DialpadSyncDoc.forceUpdateStatus(doc.value.call.callSid); 66 | } 67 | 68 | // map and respond to sync doc state upon load 69 | this.setState(doc.value) 70 | this.processCallStatus() 71 | 72 | //add listener and handler for doc changes 73 | doc.on("updated", updatedDoc => { 74 | console.log("OUTBOUND DIALPAD: Sync Doc Update Recieved: ", updatedDoc.value); 75 | this.setState(updatedDoc.value) 76 | if (updatedDoc.value.autoDial) { 77 | openDialpad(); 78 | } 79 | this.processCallStatus(); 80 | 81 | }) 82 | 83 | }) 84 | } 85 | 86 | setAgentAvailable() { 87 | return new Promise((resolve, reject) => { 88 | 89 | Actions.invokeAction("SetActivity", { 90 | activityName: "Available" 91 | }) 92 | .then(() => { 93 | console.log("OUTBOUND DIALPAD: Agent is now Available"); 94 | resolve(); 95 | }) 96 | .catch(error => { 97 | Actions.invokeAction("SetActivity", { 98 | activityName: "Idle" 99 | }) 100 | .then(() => { 101 | console.log("OUTBOUND DIALPAD: Agent is now Idle"); 102 | resolve(); 103 | }) 104 | .catch(() => { 105 | Notifications.showNotification("ActivityStateUnavailable", { 106 | state1: "Available", 107 | state2: "Idle" 108 | }); 109 | reject(); 110 | }); 111 | }); 112 | }) 113 | } 114 | 115 | processCallStatus() { 116 | const { call } = this.state; 117 | const { openDialpad, closeDialpad } = this.props; 118 | 119 | if (CallStatus.isRinging(call)) { 120 | console.log("OUTBOUND DIALPAD: Call Status Update Ringing State"); 121 | // this ensures the dialpad is opened if the page is refreshed 122 | openDialpad(); 123 | RingingService.startRinging(); 124 | } else if (CallStatus.isAnswered(call)) { 125 | console.log("OUTBOUND DIALPAD: Call Status Update Answered State"); 126 | // The agent will be pushed into available 127 | // by function handling the call status change 128 | // "in-progress" - this is just to reset the sync doc 129 | RingingService.stopRinging(); 130 | // sets agent availble and closes dialpad without resetting state for blocking inbound calls - this will be hanlded by the reservationCreated event handler 131 | this.setAgentAvailable().then(() => closeDialpad()).catch(() => closeDialpad()); 132 | } else if (CallStatus.isTerminalState(call)) { 133 | console.log("OUTBOUND DIALPAD: Call Status Update Terminal State"); 134 | if (CallStatus.isExceptionState(call)) { 135 | Notifications.showNotification("UnableToConnect", { 136 | message: call.callStatus 137 | }); 138 | } 139 | // any termination state will reset the sync doc 140 | // and make sure the dialpad isnt ringing 141 | RingingService.stopRinging(); 142 | DialpadSyncDoc.clearSyncDoc(); 143 | 144 | } 145 | } 146 | 147 | // used to ensure dialpad popup can't be closed while making 148 | // an outbound call and when manually closed (instead of auto answering 149 | // call, the user returns to their previous activity 150 | handleClose() { 151 | const { call } = this.state; 152 | const { closeDialpad } = this.props; 153 | 154 | if (CallStatus.isCloseable(call)) { 155 | console.log("OUTBOUND DIALPAD: Returning to initial activity when dialpad launched", this.initialActivity); 156 | Actions.invokeAction("SetActivity", { 157 | activityName: this.initialActivity 158 | }) 159 | unblockForOutBoundCall(); 160 | closeDialpad(); 161 | } else { 162 | Notifications.showNotification("CantCloseDialpad"); 163 | } 164 | }; 165 | 166 | // used to allow state updated from child component 167 | setCallState(callUpdate) { 168 | console.log("OUTBOUND DIALPAD: Call State updated from Dialpad Popup:", callUpdate.callStatus); 169 | 170 | this.setState({ call: callUpdate }); 171 | }; 172 | 173 | // used to allow state updated from child component 174 | setNumberState(numberUpdate) { 175 | console.log("OUTBOUND DIALPAD: Number State updated from Dialpad Popup"); 176 | this.setState({ numberToDial: numberUpdate }); 177 | }; 178 | 179 | render() { 180 | const { classes, onClose, ...other } = this.props; 181 | 182 | return ( 183 | 191 | 192 | {""} 193 | { 195 | this.handleClose(); 196 | }} 197 | /> 198 | {""} 199 | 200 | 210 | 211 | ); 212 | } 213 | } 214 | 215 | DialPadDialog.propTypes = { 216 | isOpen: PropTypes.bool.isRequired, 217 | openDialpad: PropTypes.func.isRequired, 218 | closeDialpad: PropTypes.func.isRequired, 219 | }; 220 | 221 | 222 | 223 | const CloseButton = styled("div")` 224 | cursor: pointer; 225 | position: absolute; 226 | top: 10px; 227 | left: 5px; 228 | color: white; 229 | `; 230 | 231 | export default class DialPadLauncher extends React.Component { 232 | state = { 233 | isOpen: false 234 | }; 235 | 236 | openDialpad = () => { 237 | this.setState({ 238 | isOpen: true 239 | }); 240 | }; 241 | 242 | closeDialpad = () => { 243 | this.setState({ isOpen: false }); 244 | }; 245 | 246 | render() { 247 | return ( 248 | 249 | this.openDialpad()} 254 | > 255 | Dialpad 256 | 257 | 262 | 263 | ); 264 | } 265 | } 266 | -------------------------------------------------------------------------------- /src/components/dialpad/index.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import DialPadLauncher from "./DialPadLauncher"; 3 | 4 | export function loadDialPadInterface(flex, manager) { 5 | 6 | flex.MainHeader.Content.add( 7 | , 10 | { 11 | sortOrder: 0, 12 | align: "end" 13 | } 14 | ) 15 | 16 | 17 | } -------------------------------------------------------------------------------- /src/components/external-transfer/ConferenceButton.js: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { 3 | Actions, 4 | IconButton, 5 | TaskHelper, 6 | withTheme, 7 | Manager 8 | } from '@twilio/flex-ui'; 9 | 10 | class ConferenceButton extends React.PureComponent { 11 | handleClick = () => { 12 | Actions.invokeAction('SetComponentState', { 13 | name: 'ConferenceDialog', 14 | state: { isOpen: true } 15 | }); 16 | } 17 | 18 | render() { 19 | const isLiveCall = TaskHelper.isLiveCall(this.props.task); 20 | 21 | return ( 22 | 23 | 30 | 31 | ); 32 | } 33 | } 34 | 35 | export default withTheme(ConferenceButton); 36 | -------------------------------------------------------------------------------- /src/components/external-transfer/ConferenceDialog.js: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { connect } from 'react-redux'; 3 | import { Actions, withTheme, Manager } from '@twilio/flex-ui'; 4 | import Button from '@material-ui/core/Button'; 5 | import Dialog from '@material-ui/core/Dialog'; 6 | import DialogActions from '@material-ui/core/DialogActions'; 7 | import DialogContent from '@material-ui/core/DialogContent'; 8 | import DialogContentText from '@material-ui/core/DialogContentText'; 9 | import TextField from '@material-ui/core/TextField'; 10 | import ConferenceService from '../../utilities/ConferenceService'; 11 | 12 | import { DEFAULT_FROM_NUMBER } from "../../OutboundDialingWithConferencePlugin" 13 | 14 | class ConferenceDialog extends React.Component { 15 | state = { 16 | conferenceTo: '' 17 | } 18 | 19 | handleClose = () => { 20 | this.closeDialog(); 21 | } 22 | 23 | closeDialog = () => { 24 | Actions.invokeAction('SetComponentState', { 25 | name: 'ConferenceDialog', 26 | state: { isOpen: false } 27 | }); 28 | } 29 | 30 | handleKeyPress = e => { 31 | const key = e.key; 32 | 33 | if (key === 'Enter') { 34 | this.addConferenceParticipant(); 35 | this.closeDialog(); 36 | } 37 | } 38 | 39 | handleChange = e => { 40 | const value = e.target.value; 41 | this.setState({ conferenceTo: value }); 42 | } 43 | 44 | handleDialButton = () => { 45 | this.addConferenceParticipant(); 46 | this.closeDialog(); 47 | } 48 | 49 | addConferenceParticipant = async () => { 50 | const to = this.state.conferenceTo; 51 | const { task, task: { taskSid } } = this.props; 52 | const conference = task && (task.conference || {}); 53 | const { conferenceSid } = conference; 54 | 55 | let from; 56 | if (this.props.phoneNumber) { 57 | from = this.props.phoneNumber 58 | } else { 59 | from = DEFAULT_FROM_NUMBER; 60 | } 61 | 62 | // Adding entered number to the conference 63 | console.log(`Adding ${to} to conference`); 64 | let participantCallSid; 65 | try { 66 | participantCallSid = await ConferenceService.addParticipant(taskSid, from, to); 67 | ConferenceService.addConnectingParticipant(conferenceSid, participantCallSid, 'unknown'); 68 | } catch (error) { 69 | console.error('Error adding conference participant:', error); 70 | } 71 | this.setState({ conferenceTo: '' }); 72 | } 73 | 74 | render() { 75 | return ( 76 | 80 | 81 | 82 | {Manager.getInstance().strings.DIALPADExternalTransferPhoneNumberPopupHeader} 83 | 84 | 94 | 95 | 96 | 102 | 108 | 109 | 110 | ); 111 | } 112 | } 113 | 114 | const mapStateToProps = state => { 115 | const componentViewStates = state.flex.view.componentViewStates; 116 | const conferenceDialogState = componentViewStates && componentViewStates.ConferenceDialog; 117 | const isOpen = conferenceDialogState && conferenceDialogState.isOpen; 118 | return { 119 | isOpen, 120 | phoneNumber: state.flex.worker.attributes.phone 121 | }; 122 | }; 123 | 124 | export default connect(mapStateToProps)(withTheme(ConferenceDialog)); 125 | -------------------------------------------------------------------------------- /src/components/external-transfer/ConferenceMonitor.js: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import ConferenceService from '../../utilities/ConferenceService'; 3 | 4 | class ConferenceMonitor extends React.Component { 5 | state = { 6 | liveParticipantCount: 0 7 | } 8 | 9 | componentDidUpdate() { 10 | const { task } = this.props; 11 | const conference = task && (task.conference || {}); 12 | const { 13 | conferenceSid, 14 | liveParticipantCount, 15 | participants = [] 16 | } = conference; 17 | const liveParticipants = participants.filter(p => p.status === 'joined'); 18 | 19 | if (liveParticipantCount > 2 && this.state.liveParticipantCount <= 2) { 20 | this.handleMoreThanTwoParticipants(conferenceSid, liveParticipants); 21 | } else if (liveParticipantCount <= 2 && this.state.liveParticipantCount > 2) { 22 | this.handleOnlyTwoParticipants(conferenceSid, liveParticipants); 23 | } 24 | 25 | if (liveParticipantCount !== this.state.liveParticipantCount) { 26 | this.setState({ liveParticipantCount }); 27 | } 28 | } 29 | 30 | handleMoreThanTwoParticipants = (conferenceSid, participants) => { 31 | console.log('More than two conference participants. Setting endConferenceOnExit to false for all participants.'); 32 | this.setEndConferenceOnExit(conferenceSid, participants, false); 33 | } 34 | 35 | handleOnlyTwoParticipants = (conferenceSid, participants) => { 36 | console.log('Conference participants dropped to two. Setting endConferenceOnExit to true for all participants.'); 37 | this.setEndConferenceOnExit(conferenceSid, participants, true); 38 | } 39 | 40 | setEndConferenceOnExit = async (conferenceSid, participants, endConferenceOnExit) => { 41 | const promises = []; 42 | participants.forEach(p => { 43 | console.log(`setting endConferenceOnExit = ${endConferenceOnExit} for callSid: ${p.callSid} status: ${p.status}`); 44 | if (p.connecting) { return } //skip setting end conference on connecting parties as it will fail 45 | promises.push( 46 | ConferenceService.setEndConferenceOnExit(conferenceSid, p.callSid, endConferenceOnExit) 47 | ); 48 | }); 49 | 50 | try { 51 | await Promise.all(promises); 52 | console.log(`endConferenceOnExit set to ${endConferenceOnExit} for all participants`); 53 | } catch (error) { 54 | console.error(`Error setting endConferenceOnExit to ${endConferenceOnExit} for all participants\r\n`, error); 55 | } 56 | } 57 | 58 | render() { 59 | // This is a Renderless Component, only used for monitoring and taking action on conferences 60 | return null; 61 | } 62 | } 63 | 64 | export default ConferenceMonitor; 65 | -------------------------------------------------------------------------------- /src/components/external-transfer/ParticipantActionsButtons.js: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { connect } from 'react-redux'; 3 | import styled from 'react-emotion'; 4 | import { 5 | Actions, 6 | IconButton, 7 | TaskHelper, 8 | VERSION as FlexVersion, 9 | withTheme 10 | } from '@twilio/flex-ui'; 11 | 12 | const ActionsContainer = styled('div')` 13 | margin-top: 10px; 14 | button { 15 | width: 36px; 16 | height: 36px; 17 | margin-left: 6px; 18 | margin-right: 6px; 19 | } 20 | `; 21 | 22 | const ActionsContainerListItem = styled('div')` 23 | button { 24 | width: 32px; 25 | height: 32px; 26 | margin-left: 6px; 27 | margin-right: 6px; 28 | } 29 | `; 30 | 31 | class ParticipantActionsButtons extends React.Component { 32 | componentWillUnmount() { 33 | const { participant } = this.props; 34 | if (participant.status === 'recently_left') { 35 | this.props.clearParticipantComponentState(); 36 | } 37 | } 38 | 39 | showKickConfirmation = () => this.props.setShowKickConfirmation(true); 40 | 41 | hideKickConfirmation = () => this.props.setShowKickConfirmation(false); 42 | 43 | onHoldParticipantClick = () => { 44 | const { participant, task } = this.props; 45 | const { callSid, workerSid } = participant; 46 | const participantType = participant.participantType; 47 | Actions.invokeAction(participant.onHold ? 'UnholdParticipant' : 'HoldParticipant', { 48 | participantType, 49 | task, 50 | targetSid: participantType === 'worker' ? workerSid : callSid 51 | }); 52 | }; 53 | 54 | onKickParticipantConfirmClick = () => { 55 | const { participant, task } = this.props; 56 | const { callSid, workerSid } = participant; 57 | const { participantType } = participant; 58 | Actions.invokeAction('KickParticipant', { 59 | participantType, 60 | task, 61 | targetSid: participantType === 'worker' ? workerSid : callSid 62 | }); 63 | this.hideKickConfirmation(); 64 | }; 65 | 66 | renderKickConfirmation() { 67 | return ( 68 | 69 | 75 | 81 | 82 | ); 83 | } 84 | 85 | renderActions() { 86 | const { participant, theme, task } = this.props; 87 | 88 | const holdParticipantTooltip = participant.onHold 89 | ? 'Hold Participant' : 'Unhold Participant'; 90 | const kickParticipantTooltip = 'Remove Participant'; 91 | 92 | // The name of the hold icons changed in Flex 1.11.0 to HoldOff. 93 | // Since the minimum requirement is 1.10.0 and there is no version between 94 | // 1.10.0 and 1.11.0, the check is only needed for version 1.10.0. 95 | const holdIcon = FlexVersion === '1.10.0' ? 'HoldLarge' : 'Hold'; 96 | const unholdIcon = FlexVersion === '1.10.0' ? 'HoldLargeBold' : 'HoldOff'; 97 | 98 | return ( 99 | 100 | 108 | 115 | 116 | ); 117 | } 118 | 119 | render() { 120 | return this.props.listMode 121 | ? ( 122 | 123 | {this.props.showKickConfirmation 124 | ? this.renderKickConfirmation() 125 | : this.renderActions() 126 | } 127 | 128 | ) : ( 129 | 130 | {this.props.showKickConfirmation 131 | ? this.renderKickConfirmation() 132 | : this.renderActions() 133 | } 134 | 135 | ); 136 | } 137 | } 138 | 139 | const mapStateToProps = (state, ownProps) => { 140 | const { participant } = ownProps; 141 | const componentViewStates = state.flex.view.componentViewStates; 142 | const customParticipants = componentViewStates.customParticipants || {}; 143 | const participantState = customParticipants[participant.callSid] || {}; 144 | const customParticipantsState = {}; 145 | 146 | return { 147 | showKickConfirmation: participantState.showKickConfirmation, 148 | setShowKickConfirmation: value => { 149 | customParticipantsState[participant.callSid] = { 150 | ...participantState, 151 | showKickConfirmation: value 152 | }; 153 | Actions.invokeAction('SetComponentState', { 154 | name: 'customParticipants', 155 | state: customParticipantsState 156 | }); 157 | }, 158 | clearParticipantComponentState: () => { 159 | customParticipantsState[participant.callSid] = undefined; 160 | Actions.invokeAction('SetComponentState', { 161 | name: 'customParticipants', 162 | state: customParticipantsState 163 | }); 164 | } 165 | }; 166 | }; 167 | 168 | export default connect(mapStateToProps)(withTheme(ParticipantActionsButtons)); 169 | -------------------------------------------------------------------------------- /src/components/external-transfer/ParticipantName.js: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { connect } from 'react-redux'; 3 | import styled from 'react-emotion'; 4 | import { Manager, withTheme } from '@twilio/flex-ui'; 5 | import { FUNCTIONS_HOSTNAME } from "../../OutboundDialingWithConferencePlugin"; 6 | 7 | const Name = styled('div')` 8 | font-size: 14px; 9 | font-weight: bold; 10 | margin-top: 10px; 11 | margin-bottom: 4px; 12 | white-space: nowrap; 13 | overflow: hidden; 14 | text-overflow: ellipsis; 15 | `; 16 | 17 | const NameListItem = styled('div')` 18 | font-size: 12px; 19 | font-weight: bold; 20 | white-space: nowrap; 21 | text-overflow: ellipsis; 22 | overflow: hidden; 23 | `; 24 | 25 | class ParticipantName extends React.Component { 26 | state = { 27 | name: '' 28 | }; 29 | 30 | componentDidMount() { 31 | const { participant, task } = this.props; 32 | const { callSid } = participant; 33 | 34 | if (participant.participantType === 'customer') { 35 | this.setState({ name: task.attributes.name }); 36 | return; 37 | } 38 | 39 | const manager = Manager.getInstance(); 40 | const token = manager.user.token; 41 | 42 | const getCallPropertiesUrl = ( 43 | `https://${FUNCTIONS_HOSTNAME}/external-transfer/get-call-properties` 44 | ); 45 | fetch(getCallPropertiesUrl, { 46 | headers: { 47 | 'Content-Type': 'application/x-www-form-urlencoded' 48 | }, 49 | method: 'POST', 50 | body: ( 51 | `Token=${encodeURIComponent(token)}` 52 | + `&callSid=${encodeURIComponent(callSid)}` 53 | ) 54 | }).then(response => response.json()) 55 | .then(json => { 56 | if (json) { 57 | const name = (json && json.to) || ''; 58 | this.setState({ name }); 59 | } 60 | }); 61 | } 62 | 63 | render() { 64 | return this.props.listMode 65 | ? ( 66 | 67 | {this.state.name} 68 | 69 | ) : ( 70 | 71 | {this.state.name} 72 | 73 | ); 74 | } 75 | } 76 | 77 | const mapStateToProps = state => { 78 | const { serviceBaseUrl } = state.flex.config; 79 | 80 | return { 81 | serviceBaseUrl, 82 | }; 83 | }; 84 | 85 | export default connect(mapStateToProps)(withTheme(ParticipantName)); 86 | -------------------------------------------------------------------------------- /src/components/external-transfer/ParticipantStatus.js: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { connect } from 'react-redux'; 3 | import styled from 'react-emotion'; 4 | import { 5 | withTheme, 6 | templates, 7 | Template 8 | } from '@twilio/flex-ui'; 9 | 10 | const Status = styled('div')` 11 | font-size: 12px; 12 | `; 13 | 14 | const StatusListItem = styled('div')` 15 | font-size: 10px; 16 | `; 17 | 18 | class ParticipantStatus extends React.PureComponent { 19 | render() { 20 | const { participant } = this.props; 21 | let statusTemplate = templates.CallParticipantStatusLive; 22 | 23 | if (participant.onHold) { 24 | statusTemplate = templates.CallParticipantStatusOnHold; 25 | } 26 | if (participant.status === 'recently_left') { 27 | statusTemplate = templates.CallParticipantStatusLeft; 28 | } 29 | if (participant.connecting) { 30 | statusTemplate = templates.CallParticipantStatusConnecting; 31 | } 32 | if (this.props.showKickConfirmation) { 33 | statusTemplate = templates.CallParticipantStatusKickConfirmation; 34 | } 35 | 36 | return this.props.listMode 37 | ? ( 38 | 39 |