From 262da1edaca1e82c0776e4bcebf4cb81907f4b3f Mon Sep 17 00:00:00 2001 From: Angela Rojas Date: Tue, 21 Apr 2020 14:28:30 -0500 Subject: [PATCH 1/7] Resolves #5 --- .env.example | 16 ++++- .github/workflows/ruby.yml | 34 ++++++++++ .gitignore | 1 + .mergify.yml | 13 ++++ CODE_OF_CONDUCT.md | 73 ++++++++++++++++++++ CONTRIBUTING.md | 3 + Gemfile | 15 +++-- LICENSE | 14 ++-- README.md | 25 +++++-- app.rb | 41 ++++++++---- public/index.html | 4 +- public/quickstart.js | 134 ++++++++++++++++++++++--------------- spec/app_spec.rb | 56 ++++++++++++++++ spec/spec_helper.rb | 17 +++++ 14 files changed, 359 insertions(+), 87 deletions(-) create mode 100644 .github/workflows/ruby.yml create mode 100644 .mergify.yml create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 spec/app_spec.rb create mode 100644 spec/spec_helper.rb diff --git a/.env.example b/.env.example index 8be7812..d50afed 100644 --- a/.env.example +++ b/.env.example @@ -1,4 +1,16 @@ TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX -TWILIO_AUTH_TOKEN=your_auth_token -TWILIO_TWIML_APP_SID=APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX TWILIO_CALLER_ID=+1XXXYYYZZZZ + +# SID of your TwiML Application +# https://www.twilio.com/console/voice/twiml/apps +# OR +# twilio api:core:applications:create --friendly-name=voice-client-javascript +TWILIO_TWIML_APP_SID=APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + +# Your REST API Key information +# https://www.twilio.com/console/project/api-keys +# OR +# twilio api:core:keys:create --friendly-name=voice-client-javascript -o json +# NOTE: Make sure to copy the secret, it'll will only be displayed once +API_KEY=SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX +API_SECRET=XXXXXXXXXXXXXXXXX diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml new file mode 100644 index 0000000..c4a6512 --- /dev/null +++ b/.github/workflows/ruby.yml @@ -0,0 +1,34 @@ +name: Ruby + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - name: Setup System + run: | + sudo apt-get install libsqlite3-dev + - name: Set up Ruby 2.6 + uses: actions/setup-ruby@v1 + with: + ruby-version: 2.6.x + - name: Build and test with minitest + run: | + gem install bundler + bundle install --jobs 4 --retry 3 + - name: Test + run: bundle exec rspec + env: + TWILIO_ACCOUNT_SID: ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + TWILIO_CALLER_ID: +1XXXYYYZZZZ + TWILIO_TWIML_APP_SID: APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + API_KEY: SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + API_SECRET: XXXXXXXXXXXXXXXXX diff --git a/.gitignore b/.gitignore index 6fa723e..3a9a19b 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ /pkg /doc/api /Gemfile.lock +/vendor/bundle diff --git a/.mergify.yml b/.mergify.yml new file mode 100644 index 0000000..0433495 --- /dev/null +++ b/.mergify.yml @@ -0,0 +1,13 @@ +pull_request_rules: + - name: automatic merge for Dependabot pull requests + conditions: + - author=dependabot-preview[bot] + - status-success=build (macos-latest, 10) + - status-success=build (macos-latest, 12) + - status-success=build (windows-latest, 10) + - status-success=build (windows-latest, 12) + - status-success=build (ubuntu-latest, 10) + - status-success=build (ubuntu-latest, 12) + actions: + merge: + method: squash diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..2f0727e --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,73 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +- The use of sexualized language or imagery and unwelcome sexual attention or + advances +- Trolling, insulting/derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or electronic + address, without explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at open-source@twilio.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..ad3257e --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,3 @@ +# Contributing to Twilio + +All third party contributors acknowledge that any contributions they provide will be made under the same open source license that the open source project is provided under. diff --git a/Gemfile b/Gemfile index c94bd55..6dcc236 100644 --- a/Gemfile +++ b/Gemfile @@ -1,6 +1,11 @@ source 'https://rubygems.org' -gem 'dotenv' -gem 'faker' -gem 'sinatra' -gem 'sinatra-contrib' -gem 'twilio-ruby', '~> 5.28.0' +gem 'dotenv', '~>2.7.5' +gem 'faker', '~>2.11.0' +gem 'sinatra', '~>2.0.8' +gem 'sinatra-contrib', '~>2.0.8' +gem 'twilio-ruby', '~> 5.33.1' + +group :test do + gem 'rack-test' + gem 'rspec' +end diff --git a/LICENSE b/LICENSE index 4bcc4c2..48bedc4 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,6 @@ -Copyright (c) 2015 Twilio Inc. +MIT License + +Copyright (c) 2020 Twilio Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -7,13 +9,13 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 28c367d..852dae5 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,19 @@ # Twilio Client Quickstart for Ruby +![](https://github.com/TwilioDevEd/client-quickstart-ruby/workflows/Ruby/badge.svg) + > We are currently in the process of updating this sample template. If you are encountering any issues with the sample, please open an issue at [github.com/twilio-labs/code-exchange/issues](https://github.com/twilio-labs/code-exchange/issues) and we'll try to help you. This application should give you a ready-made starting point for writing your own voice apps with Twilio Client. Before we begin, we need to collect all the config values we need to run the application: -| Config Value | Description | +| Config Value | Description | | :------------- |:------------- | -Account SID | Your primary Twilio account identifier - find this [in the console here](https://www.twilio.com/console). -Auth Token | Used to authenticate - [just like the above, you'll find this here](https://www.twilio.com/console). -TwiML App SID | The TwiML application with a voice URL configured to access your server running this app - create one [in the console here](https://www.twilio.com//console/phone-numbers/dev-tools/twiml-apps). Also, you will need to configure the Voice "REQUEST URL" on the TwiML app once you've got your server up and running. -Twilio Phone # | A Twilio phone number in [E.164 format](https://en.wikipedia.org/wiki/E.164) - you can [get one here](https://www.twilio.com/console/phone-numbers/incoming) +`TWILIO_ACCOUNT_SID` | Your primary Twilio account identifier - find this [in the console here](https://www.twilio.com/console). +`TWILIO_TWIML_APP_SID` | The TwiML application with a voice URL configured to access your server running this app - create one [in the console here](https://www.twilio.com/console/voice/twiml/apps). Also, you will need to configure the Voice "REQUEST URL" on the TwiML app once you've got your server up and running. +`TWILIO_CALLER_ID` | A Twilio phone number in [E.164 format](https://en.wikipedia.org/wiki/E.164) - you can [get one here](https://www.twilio.com/console/phone-numbers/incoming) +`API_KEY` / `API_SECRET` | Your REST API Key information needed to create an [Access Token](https://www.twilio.com/docs/iam/access-tokens) - create [one here](https://www.twilio.com/console/project/api-keys). ## Setting Up The Ruby (Sinatra) Application @@ -60,6 +62,15 @@ We'd recommend Google Chrome or Mozilla Firefox instead. ![screenshot of phone app](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/TwilioClientQuickstart.original.png) -## License +### Run tests + +```bash +bundle exec rspec +``` + +## Meta -MIT +* No warranty expressed or implied. Software is as is. Diggity. +* The CodeExchange repository can be found [here](https://github.com/twilio-labs/code-exchange/). +* [MIT License](http://www.opensource.org/licenses/mit-license.html) +* Lovingly crafted by Twilio Developer Education. diff --git a/app.rb b/app.rb index 83db57b..8f8a4e8 100644 --- a/app.rb +++ b/app.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'twilio-ruby' require 'sinatra' require 'sinatra/json' @@ -14,36 +16,51 @@ # Generate a token for use in our Video application get '/token' do + # Required for any Twilio Access Token + account_sid = ENV['TWILIO_ACCOUNT_SID'] + api_key = ENV['API_KEY'] + api_secret = ENV['API_SECRET'] + + # Required for Voice + outgoing_application_sid = ENV['TWILIO_TWIML_APP_SID'] + # Create a random username for the client identity = Faker::Internet.user_name.gsub(/[^0-9a-z_]/i, '') - capability = Twilio::JWT::ClientCapability.new ENV['TWILIO_ACCOUNT_SID'], - ENV['TWILIO_AUTH_TOKEN'] - # Create an application sid at - # twilio.com/console/phone-numbers/dev-tools/twiml-apps and use it here - outgoing_scope = Twilio::JWT::ClientCapability::OutgoingClientScope.new(ENV['TWILIO_TWIML_APP_SID']) - incoming_scope = Twilio::JWT::ClientCapability::IncomingClientScope.new('test-client-name') - capability.add_scope(outgoing_scope) - capability.add_scope(incoming_scope) + # Create Voice grant for our token + grant = Twilio::JWT::AccessToken::VoiceGrant.new + grant.outgoing_application_sid = outgoing_application_sid + + # Optional: add to allow incoming calls + grant.incoming_allow = true + + # Create an Access Token + token = Twilio::JWT::AccessToken.new( + account_sid, + api_key, + api_secret, + [grant], + identity: identity + ) # Generate the token and send to client - json :identity => identity, :token => capability.to_jwt + json :identity => identity, :token => token.to_jwt end post '/voice' do twiml = Twilio::TwiML::VoiceResponse.new do |r| - if params['To'] and params['To'] != '' + if params['To'] && params['To'] != '' r.dial(caller_id: ENV['TWILIO_CALLER_ID']) do |d| # wrap the phone number or client name in the appropriate TwiML verb # by checking if the number given has only digits and format symbols if params['To'] =~ /^[\d\+\-\(\) ]+$/ d.number(params['To']) else - d.client(params['To']) + d.client identity: params['To'] end end else - r.say("Thanks for calling!") + r.say(message: "Thanks for calling!") end end diff --git a/public/index.html b/public/index.html index 7611685..31215ae 100644 --- a/public/index.html +++ b/public/index.html @@ -32,8 +32,8 @@
- - + + diff --git a/public/quickstart.js b/public/quickstart.js index 74c8a9f..cfe3376 100644 --- a/public/quickstart.js +++ b/public/quickstart.js @@ -5,46 +5,63 @@ var inputVolumeBar = document.getElementById('input-volume'); var volumeIndicators = document.getElementById('volume-indicators'); - log('Requesting Capability Token...'); + var device; + + log('Requesting Access Token...'); $.getJSON('/token') - .done(function (data) { - log('Got a token.'); - console.log('Token: ' + data.token); + .then(function (data) { + log("Got a token."); + console.log("Token: " + data.token); // Setup Twilio.Device - Twilio.Device.setup(data.token); + device = new Twilio.Device(data.token, { + // Set Opus as our preferred codec. Opus generally performs better, requiring less bandwidth and + // providing better audio quality in restrained network conditions. Opus will be default in 2.0. + codecPreferences: ["opus", "pcmu"], + // Use fake DTMF tones client-side. Real tones are still sent to the other end of the call, + // but the client-side DTMF tones are fake. This prevents the local mic capturing the DTMF tone + // a second time and sending the tone twice. This will be default in 2.0. + fakeLocalDTMF: true, + // Use `enableRingingState` to enable the device to emit the `ringing` + // state. The TwiML backend also needs to have the attribute + // `answerOnBridge` also set to true in the `Dial` verb. This option + // changes the behavior of the SDK to consider a call `ringing` starting + // from the connection to the TwiML backend to when the recipient of + // the `Dial` verb answers. + enableRingingState: true + }); - Twilio.Device.ready(function (device) { - log('Twilio.Device Ready!'); - document.getElementById('call-controls').style.display = 'block'; + device.on("ready", function(device) { + log("Twilio.Device Ready!"); + document.getElementById("call-controls").style.display = "block"; }); - Twilio.Device.error(function (error) { - log('Twilio.Device Error: ' + error.message); + device.on("error", function(error) { + log("Twilio.Device Error: " + error.message); }); - Twilio.Device.connect(function (conn) { - log('Successfully established call!'); - document.getElementById('button-call').style.display = 'none'; - document.getElementById('button-hangup').style.display = 'inline'; - volumeIndicators.style.display = 'block'; + device.on("connect", function(conn) { + log("Successfully established call!"); + document.getElementById("button-call").style.display = "none"; + document.getElementById("button-hangup").style.display = "inline"; + volumeIndicators.style.display = "block"; bindVolumeIndicators(conn); }); - Twilio.Device.disconnect(function (conn) { - log('Call ended.'); - document.getElementById('button-call').style.display = 'inline'; - document.getElementById('button-hangup').style.display = 'none'; - volumeIndicators.style.display = 'none'; + device.on("disconnect", function(conn) { + log("Call ended."); + document.getElementById("button-call").style.display = "inline"; + document.getElementById("button-hangup").style.display = "none"; + volumeIndicators.style.display = "none"; }); - Twilio.Device.incoming(function (conn) { - log('Incoming connection from ' + conn.parameters.From); - var archEnemyPhoneNumber = '+12099517118'; + device.on("incoming", function(conn) { + log("Incoming connection from " + conn.parameters.From); + var archEnemyPhoneNumber = "+12093373517"; if (conn.parameters.From === archEnemyPhoneNumber) { conn.reject(); - log('It\'s your nemesis. Rejected call.'); + log("It's your nemesis. Rejected call."); } else { // accept the incoming connection and start two-way audio conn.accept(); @@ -60,25 +77,33 @@ document.getElementById('output-selection').style.display = 'block'; } }) - .fail(function () { - log('Could not get a token from server!'); + .catch(function (err) { + console.log(err); + log("Could not get a token from server!"); }); // Bind button to make call - document.getElementById('button-call').onclick = function () { + document.getElementById("button-call").onclick = function() { // get the phone number to connect the call to var params = { - To: document.getElementById('phone-number').value + To: document.getElementById("phone-number").value }; - console.log('Calling ' + params.To + '...'); - Twilio.Device.connect(params); + console.log("Calling " + params.To + "..."); + if (device) { + var outgoingConnection = device.connect(params); + outgoingConnection.on("ringing", function() { + log("Ringing..."); + }); + } }; // Bind button to hangup call - document.getElementById('button-hangup').onclick = function () { - log('Hanging up...'); - Twilio.Device.disconnectAll(); + document.getElementById("button-hangup").onclick = function() { + log("Hanging up..."); + if (device) { + device.disconnectAll(); + } }; document.getElementById('get-devices').onclick = function() { @@ -103,25 +128,25 @@ }); function bindVolumeIndicators(connection) { - connection.volume(function(inputVolume, outputVolume) { - var inputColor = 'red'; - if (inputVolume < .50) { - inputColor = 'green'; - } else if (inputVolume < .75) { - inputColor = 'yellow'; + connection.on("volume", function(inputVolume, outputVolume) { + var inputColor = "red"; + if (inputVolume < 0.5) { + inputColor = "green"; + } else if (inputVolume < 0.75) { + inputColor = "yellow"; } - inputVolumeBar.style.width = Math.floor(inputVolume * 300) + 'px'; + inputVolumeBar.style.width = Math.floor(inputVolume * 300) + "px"; inputVolumeBar.style.background = inputColor; - var outputColor = 'red'; - if (outputVolume < .50) { - outputColor = 'green'; - } else if (outputVolume < .75) { - outputColor = 'yellow'; + var outputColor = "red"; + if (outputVolume < 0.5) { + outputColor = "green"; + } else if (outputVolume < 0.75) { + outputColor = "yellow"; } - outputVolumeBar.style.width = Math.floor(outputVolume * 300) + 'px'; + outputVolumeBar.style.width = Math.floor(outputVolume * 300) + "px"; outputVolumeBar.style.background = outputColor; }); } @@ -134,18 +159,21 @@ // Update the available ringtone and speaker devices function updateDevices(selectEl, selectedDevices) { - selectEl.innerHTML = ''; - Twilio.Device.audio.availableOutputDevices.forEach(function(device, id) { - var isActive = (selectedDevices.size === 0 && id === 'default'); + selectEl.innerHTML = ""; + + device.audio.availableOutputDevices.forEach(function(device, id) { + var isActive = selectedDevices.size === 0 && id === "default"; selectedDevices.forEach(function(device) { - if (device.deviceId === id) { isActive = true; } + if (device.deviceId === id) { + isActive = true; + } }); - var option = document.createElement('option'); + var option = document.createElement("option"); option.label = device.label; - option.setAttribute('data-id', id); + option.setAttribute("data-id", id); if (isActive) { - option.setAttribute('selected', 'selected'); + option.setAttribute("selected", "selected"); } selectEl.appendChild(option); }); diff --git a/spec/app_spec.rb b/spec/app_spec.rb new file mode 100644 index 0000000..02ec39c --- /dev/null +++ b/spec/app_spec.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +require File.expand_path('spec_helper.rb', __dir__) + +describe 'app' do + describe 'get /' do + it 'renders index.html page' do + twilio_sdk = '' + jquery_script = '' + + get '/' + expect(last_response).to be_ok + expect(last_response.body).to include('id="ringtone-devices"') + expect(last_response.body).to include('id="speaker-devices"') + expect(last_response.body).to include('id="get-devices"') + expect(last_response.body).to include('') + expect(last_response.body).to include('') + expect(last_response.body).to include('
') + expect(last_response.body).to include(jquery_script) + expect(last_response.body).to include(twilio_sdk) + end + end + + describe 'get /token' do + it 'generates a token' do + get '/token' + expect(JSON.parse(last_response.body).keys).to contain_exactly('identity', 'token') + end + end + + describe 'post /voice' do + context 'when a phone number is sent' do + it 'responds with Number tag' do + post '/voice', To: '+1234567890' + expect(last_response.body).to include('+1234567890') + end + end + + context 'when a string is sent ' do + it 'responds with Number tag' do + post '/voice', To: 'client' + expect(last_response.body).to include('client') + end + end + + context 'when no parameter is sent ' do + it 'responds with Number tag' do + post '/voice' + expect(last_response.body).to include('Thanks for calling!') + end + end + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..e1002fc --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +require 'rack/test' +require 'rspec' + +ENV['RACK_ENV'] = 'test' + +require File.expand_path('../app.rb', __dir__) + +module RSpecMixin + include Rack::Test::Methods + def app + Sinatra::Application + end +end + +RSpec.configure { |c| c.include RSpecMixin } From ca736903e8a45f3de3c02acd810143ff2a6a56dc Mon Sep 17 00:00:00 2001 From: Angela Rojas Date: Thu, 14 May 2020 10:23:11 -0500 Subject: [PATCH 2/7] Create makefile and update readme file --- Makefile | 5 +++ README.md | 97 ++++++++++++++++++++++++++++++++++++++++--------------- 2 files changed, 76 insertions(+), 26 deletions(-) create mode 100644 Makefile diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..e59ba36 --- /dev/null +++ b/Makefile @@ -0,0 +1,5 @@ +install: + bundle install + +serve: + bundle exec ruby app.rb diff --git a/README.md b/README.md index 852dae5..22ef44d 100644 --- a/README.md +++ b/README.md @@ -4,53 +4,75 @@ > We are currently in the process of updating this sample template. If you are encountering any issues with the sample, please open an issue at [github.com/twilio-labs/code-exchange/issues](https://github.com/twilio-labs/code-exchange/issues) and we'll try to help you. -This application should give you a ready-made starting point for writing your -own voice apps with Twilio Client. Before we begin, we need to collect -all the config values we need to run the application: +## About + +This application should give you a ready-made starting point for writing your own voice apps with Twilio Client. This application use [Sinatra](http://sinatrarb.com/documentation.html). + + +Implementations in other languages: + +| .NET | Java | Python | PHP | Node | +| :--- | :--- | :----- | :-- | :--- | +| [Done](https://github.com/TwilioDevEd/client-quickstart-csharp) | [Done](https://github.com/TwilioDevEd/client-quickstart-java) | [Done](https://github.com/TwilioDevEd/client-quickstart-python) | [Done](https://github.com/TwilioDevEd/client-quickstart-php) | [Done](https://github.com/TwilioDevEd/client-quickstart-node) | + +## Set up + +### Requirements + +- [Ruby](https://www.ruby-lang.org/) **2.6.x** version + +### Twilio Account Settings + +This application should give you a ready-made starting point for writing your own application. +Before we begin, we need to collect all the config values we need to run the application: | Config Value | Description | | :------------- |:------------- | `TWILIO_ACCOUNT_SID` | Your primary Twilio account identifier - find this [in the console here](https://www.twilio.com/console). `TWILIO_TWIML_APP_SID` | The TwiML application with a voice URL configured to access your server running this app - create one [in the console here](https://www.twilio.com/console/voice/twiml/apps). Also, you will need to configure the Voice "REQUEST URL" on the TwiML app once you've got your server up and running. -`TWILIO_CALLER_ID` | A Twilio phone number in [E.164 format](https://en.wikipedia.org/wiki/E.164) - you can [get one here](https://www.twilio.com/console/phone-numbers/incoming) +`TWILIO_CALLER_ID` | A Twilio phone number in [E.164 format](https://en.wikipedia.org/wiki/E.164) - you can get one [here](https://www.twilio.com/console/phone-numbers/incoming) `API_KEY` / `API_SECRET` | Your REST API Key information needed to create an [Access Token](https://www.twilio.com/docs/iam/access-tokens) - create [one here](https://www.twilio.com/console/project/api-keys). -## Setting Up The Ruby (Sinatra) Application +### Local development + +1. Clone this repo. + + ```bash + git clone https://github.com/TwilioDevEd/client-quickstart-ruby.git + cd client-quickstart-ruby + ``` -1. Create a configuration file for your application: +1. Install depenedencies. ```bash - cp .env.example .env + make install ``` -2. Edit `.env` with the four configuration parameters we gathered from above. - -3. Next, we need to install our depenedencies: +1. Set your environment variables. ```bash - bundle install + cp .env.example .env ``` -4. Run the application using the `ruby` command. + See [Twilio Account Settings](#twilio-account-settings) to locate the necessary environment variables. + +1. Start the server. ```bash - bundle exec ruby app.rb + make serve ``` -5. Your application should now be running at [http://localhost:4567](http://localhost:4567). - -6. [Download and install ngrok](https://ngrok.com/download) +1. Navigate to [http://localhost:4567](http://localhost:4567). -7. Run ngrok: +1. Expose your application to the wider internet using ngrok. You can click [here](https://www.twilio.com/blog/2015/09/6-awesome-reasons-to-use-ngrok-when-testing-webhooks.html) for more details. This step **is important** because the application won't work as expected if you run it through localhost. ```bash ngrok http 4567 ``` -8. When ngrok starts up, it will assign a unique URL to your tunnel. -It might be something like `https://asdf456.ngrok.io`. Take note of this. +1. Once ngrok is running, it will assign a unique URL to your tunnel. It might be something like `https://asdf456.ngrok.io`. Take note of this. -9. [Configure your TwiML app](https://www.twilio.com//console/phone-numbers/dev-tools/twiml-apps)'s +1. [Configure your TwiML app](https://www.twilio.com//console/phone-numbers/dev-tools/twiml-apps)'s Voice "REQUEST URL" to be your ngrok URL plus `/voice`. For example: ![screenshot of twiml app](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/TwilioClientRequestUrl.original.png) @@ -62,15 +84,38 @@ We'd recommend Google Chrome or Mozilla Firefox instead. ![screenshot of phone app](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/TwilioClientQuickstart.original.png) -### Run tests +That's it! + +### Tests ```bash bundle exec rspec ``` -## Meta +### Cloud deployment + +Additionally to trying out this application locally, you can deploy it to a variety of host services. Here is a small selection of them. + +Please be aware that some of these might charge you for the usage or might make the source code for this application visible to the public. When in doubt research the respective hosting service first. + +| Service | | +| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| [Heroku](https://www.heroku.com/) | [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy) | + +## Resources + +- The CodeExchange repository can be found [here](https://github.com/twilio-labs/code-exchange/). + +## Contributing + +This template is open source and welcomes contributions. All contributions are subject to our [Code of Conduct](https://github.com/twilio-labs/.github/blob/master/CODE_OF_CONDUCT.md). + +## License + +[MIT](http://www.opensource.org/licenses/mit-license.html) + +## Disclaimer + +No warranty expressed or implied. Software is as is. -* No warranty expressed or implied. Software is as is. Diggity. -* The CodeExchange repository can be found [here](https://github.com/twilio-labs/code-exchange/). -* [MIT License](http://www.opensource.org/licenses/mit-license.html) -* Lovingly crafted by Twilio Developer Education. +[twilio]: https://www.twilio.com From ad90a010763b4034544ffeebaec6c77bca0fb32b Mon Sep 17 00:00:00 2001 From: Angela Rojas Date: Mon, 1 Jun 2020 15:19:54 -0500 Subject: [PATCH 3/7] Add next branch --- .github/workflows/ruby.yml | 4 ++-- .gitignore | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml index c4a6512..8b6c85b 100644 --- a/.github/workflows/ruby.yml +++ b/.github/workflows/ruby.yml @@ -2,9 +2,9 @@ name: Ruby on: push: - branches: [ master ] + branches: [ master, next ] pull_request: - branches: [ master ] + branches: [ master, next ] jobs: build: diff --git a/.gitignore b/.gitignore index 3a9a19b..0fa30a3 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ /doc/api /Gemfile.lock /vendor/bundle +.tool-versions From c784e56e6d50cd9fbd47e6431a23e1e8c243ab3d Mon Sep 17 00:00:00 2001 From: Angela Rojas Date: Thu, 11 Jun 2020 16:33:07 -0500 Subject: [PATCH 4/7] Dockerizing the app --- .dockerignore | 1 + Dockerfile | 19 +++++++++++++++++++ Makefile | 2 +- README.md | 34 ++++++++++++++++++++++------------ docker-compose.yml | 7 +++++++ 5 files changed, 50 insertions(+), 13 deletions(-) create mode 100644 .dockerignore create mode 100644 Dockerfile create mode 100644 docker-compose.yml diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..b844b14 --- /dev/null +++ b/.dockerignore @@ -0,0 +1 @@ +Gemfile.lock diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..3ac1005 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,19 @@ +FROM ruby:2.6 + +WORKDIR /usr/src/app + +COPY Gemfile ./ + +COPY Makefile ./ + +RUN make install + +COPY . . + +# Install a Javascript environment in the container to avoid ExecJS::RuntimeUnavailable +RUN curl -sL https://deb.nodesource.com/setup_10.x | bash - \ + && apt install -y nodejs + +EXPOSE 4567 + +CMD ["make", "serve"] diff --git a/Makefile b/Makefile index e59ba36..ec9abfb 100644 --- a/Makefile +++ b/Makefile @@ -2,4 +2,4 @@ install: bundle install serve: - bundle exec ruby app.rb + bundle exec ruby app.rb -o 0.0.0.0 diff --git a/README.md b/README.md index 22ef44d..efebe59 100644 --- a/README.md +++ b/README.md @@ -42,13 +42,13 @@ Before we begin, we need to collect all the config values we need to run the app cd client-quickstart-ruby ``` -1. Install depenedencies. +2. Install depenedencies. ```bash make install ``` -1. Set your environment variables. +3. Set your environment variables. ```bash cp .env.example .env @@ -56,36 +56,46 @@ Before we begin, we need to collect all the config values we need to run the app See [Twilio Account Settings](#twilio-account-settings) to locate the necessary environment variables. -1. Start the server. +4. Start the server. ```bash make serve ``` -1. Navigate to [http://localhost:4567](http://localhost:4567). +5. Navigate to [http://localhost:4567](http://localhost:4567). -1. Expose your application to the wider internet using ngrok. You can click [here](https://www.twilio.com/blog/2015/09/6-awesome-reasons-to-use-ngrok-when-testing-webhooks.html) for more details. This step **is important** because the application won't work as expected if you run it through localhost. +6. Expose your application to the wider internet using [ngrok](https://ngrok.com/). You can click [here](https://www.twilio.com/blog/2015/09/6-awesome-reasons-to-use-ngrok-when-testing-webhooks.html) for more details. This step **is important** because the application won't work as expected if you run it through localhost. ```bash ngrok http 4567 ``` -1. Once ngrok is running, it will assign a unique URL to your tunnel. It might be something like `https://asdf456.ngrok.io`. Take note of this. +7. Once ngrok is running, it will assign a unique URL to your tunnel. It might be something like `https://asdf456.ngrok.io`. Take note of this. -1. [Configure your TwiML app](https://www.twilio.com//console/phone-numbers/dev-tools/twiml-apps)'s +8. [Configure your TwiML app](https://www.twilio.com//console/phone-numbers/dev-tools/twiml-apps)'s Voice "REQUEST URL" to be your ngrok URL plus `/voice`. For example: ![screenshot of twiml app](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/TwilioClientRequestUrl.original.png) -You should now be ready to rock! Make some phone calls. -Open it on another device and call yourself. Note that Twilio Client requires -WebRTC enabled browsers, so Edge and Internet Explorer will not work for testing. -We'd recommend Google Chrome or Mozilla Firefox instead. + You should now be ready to rock! Make some phone calls. + Open it on another device and call yourself. Note that Twilio Client requires + WebRTC enabled browsers, so Edge and Internet Explorer will not work for testing. + We'd recommend Google Chrome or Mozilla Firefox instead. -![screenshot of phone app](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/TwilioClientQuickstart.original.png) + ![screenshot of phone app](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/TwilioClientQuickstart.original.png) That's it! +### Docker + +If you have [Docker](https://www.docker.com/) already installed on your machine, you can use our `docker-compose.yml` to setup your project. + +1. Make sure you have the project cloned. +2. Setup the `.env` file as outlined in the [Local Development](#local-development) steps. +3. Run `docker-compose up`. +4. Follow the steps in [Local Development](#local-development) on how to expose your port to Twilio using a tool like [ngrok](https://ngrok.com/) and configure the remaining parts of your application. + + ### Tests ```bash diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..f579dd6 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,7 @@ +version: "3.8" +services: + app: + restart: always + build: . + ports: + - "4567:4567" From 34144eb26223ba51583f11802d3b7960b14dd039 Mon Sep 17 00:00:00 2001 From: Angela Rojas Date: Thu, 11 Jun 2020 16:44:26 -0500 Subject: [PATCH 5/7] Remove node install step --- Dockerfile | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Dockerfile b/Dockerfile index 3ac1005..ebb316f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,10 +10,6 @@ RUN make install COPY . . -# Install a Javascript environment in the container to avoid ExecJS::RuntimeUnavailable -RUN curl -sL https://deb.nodesource.com/setup_10.x | bash - \ - && apt install -y nodejs - EXPOSE 4567 CMD ["make", "serve"] From 30f9535345b529cda916ee55ac982ff7280d858f Mon Sep 17 00:00:00 2001 From: Angela Rojas Date: Thu, 18 Jun 2020 08:02:14 -0500 Subject: [PATCH 6/7] Add Windows and Macos platforms --- .github/workflows/ruby.yml | 51 ++++++++++++++++++++++---------------- .mergify.yml | 9 +++---- Makefile | 2 ++ 3 files changed, 35 insertions(+), 27 deletions(-) diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml index 8b6c85b..f36a4e4 100644 --- a/.github/workflows/ruby.yml +++ b/.github/workflows/ruby.yml @@ -9,26 +9,35 @@ on: jobs: build: - runs-on: ubuntu-latest + runs-on: ${{ matrix.os }} + + strategy: + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + ruby: [ '2.6.x' ] steps: - - uses: actions/checkout@v2 - - name: Setup System - run: | - sudo apt-get install libsqlite3-dev - - name: Set up Ruby 2.6 - uses: actions/setup-ruby@v1 - with: - ruby-version: 2.6.x - - name: Build and test with minitest - run: | - gem install bundler - bundle install --jobs 4 --retry 3 - - name: Test - run: bundle exec rspec - env: - TWILIO_ACCOUNT_SID: ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX - TWILIO_CALLER_ID: +1XXXYYYZZZZ - TWILIO_TWIML_APP_SID: APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX - API_KEY: SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX - API_SECRET: XXXXXXXXXXXXXXXXX + - name: Checkout code + uses: actions/checkout@v2 + - name: Setup Ruby ${{ matrix.ruby }} + uses: actions/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + - name: Ruby gem cache + uses: actions/cache@v1 + with: + path: vendor/bundle + key: ${{ runner.os }}-gems-${{ hashFiles('**/Gemfile.lock') }} + restore-keys: | + ${{ runner.os }}-gems- + - name: Install gems + run: | + gem install bundler + bundle config path vendor/bundle + bundle install --jobs 4 --retry 3 + - name: Run tests + run: | + cp .env.example .env + bundle exec rspec + env: + RAILS_ENV: test \ No newline at end of file diff --git a/.mergify.yml b/.mergify.yml index 0433495..ea3da49 100644 --- a/.mergify.yml +++ b/.mergify.yml @@ -2,12 +2,9 @@ pull_request_rules: - name: automatic merge for Dependabot pull requests conditions: - author=dependabot-preview[bot] - - status-success=build (macos-latest, 10) - - status-success=build (macos-latest, 12) - - status-success=build (windows-latest, 10) - - status-success=build (windows-latest, 12) - - status-success=build (ubuntu-latest, 10) - - status-success=build (ubuntu-latest, 12) + - status-success=build (ubuntu-latest, 2.6.x) + - status-success=build (macos-latest, 2.6.x) + - status-success=build (windows-latest, 2.6.x) actions: merge: method: squash diff --git a/Makefile b/Makefile index ec9abfb..c4a34cd 100644 --- a/Makefile +++ b/Makefile @@ -1,3 +1,5 @@ +.PHONY: install serve + install: bundle install From a52bd5fde5f123e9ca699ffcac0dcc369ec2e396 Mon Sep 17 00:00:00 2001 From: Angela Rojas Date: Thu, 18 Jun 2020 08:19:13 -0500 Subject: [PATCH 7/7] Modify text and EOL --- .github/workflows/ruby.yml | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml index f36a4e4..387ffc3 100644 --- a/.github/workflows/ruby.yml +++ b/.github/workflows/ruby.yml @@ -40,4 +40,4 @@ jobs: cp .env.example .env bundle exec rspec env: - RAILS_ENV: test \ No newline at end of file + RAILS_ENV: test diff --git a/README.md b/README.md index efebe59..57a6c64 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ![](https://github.com/TwilioDevEd/client-quickstart-ruby/workflows/Ruby/badge.svg) -> We are currently in the process of updating this sample template. If you are encountering any issues with the sample, please open an issue at [github.com/twilio-labs/code-exchange/issues](https://github.com/twilio-labs/code-exchange/issues) and we'll try to help you. +> This template is part of Twilio CodeExchange. If you encounter any issues with this code, please open an issue at [github.com/twilio-labs/code-exchange/issues](https://github.com/twilio-labs/code-exchange/issues). ## About