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/.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..387ffc3 --- /dev/null +++ b/.github/workflows/ruby.yml @@ -0,0 +1,43 @@ +name: Ruby + +on: + push: + branches: [ master, next ] + pull_request: + branches: [ master, next ] + +jobs: + build: + + runs-on: ${{ matrix.os }} + + strategy: + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + ruby: [ '2.6.x' ] + + steps: + - 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 diff --git a/.gitignore b/.gitignore index 6fa723e..0fa30a3 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,5 @@ /pkg /doc/api /Gemfile.lock +/vendor/bundle +.tool-versions diff --git a/.mergify.yml b/.mergify.yml new file mode 100644 index 0000000..ea3da49 --- /dev/null +++ b/.mergify.yml @@ -0,0 +1,10 @@ +pull_request_rules: + - name: automatic merge for Dependabot pull requests + conditions: + - author=dependabot-preview[bot] + - 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/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/Dockerfile b/Dockerfile new file mode 100644 index 0000000..ebb316f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,15 @@ +FROM ruby:2.6 + +WORKDIR /usr/src/app + +COPY Gemfile ./ + +COPY Makefile ./ + +RUN make install + +COPY . . + +EXPOSE 4567 + +CMD ["make", "serve"] 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/Makefile b/Makefile new file mode 100644 index 0000000..c4a34cd --- /dev/null +++ b/Makefile @@ -0,0 +1,7 @@ +.PHONY: install serve + +install: + bundle install + +serve: + bundle exec ruby app.rb -o 0.0.0.0 diff --git a/README.md b/README.md index 28c367d..57a6c64 100644 --- a/README.md +++ b/README.md @@ -1,65 +1,131 @@ # Twilio Client Quickstart for Ruby -> 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: +> 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). -| Config Value | Description | +## 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 | | :------------- |:------------- | -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). + +### Local development + +1. Clone this repo. -## Setting Up The Ruby (Sinatra) Application + ```bash + git clone https://github.com/TwilioDevEd/client-quickstart-ruby.git + cd client-quickstart-ruby + ``` -1. Create a configuration file for your application: +2. 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: +3. 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. + +4. 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). +5. Navigate to [http://localhost:4567](http://localhost:4567). -6. [Download and install ngrok](https://ngrok.com/download) - -7. Run ngrok: +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 ``` -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. +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. -9. [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:  -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. + +  - +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 +bundle exec rspec +``` + +### 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/) | [](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 +[MIT](http://www.opensource.org/licenses/mit-license.html) + +## Disclaimer + +No warranty expressed or implied. Software is as is. + +[twilio]: https://www.twilio.com 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/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" 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 @@
- - + +