Building a Simple Video Chatroom with Sinatra and OpenTok

This tutorial will show you how to create a simple, yet functional video chatroom using the OpenTok API and Sinatra. Sinatra is a Ruby framework which allows you to quickly create web apps.

The App

The app we’ll be creating will be a simple website which will allow you to instantly create a video chatroom.

Setup

So, let’s get started! First of all, you’ll need to install Sinatra. To do this, type the following command in the terminal:
[code]
gem install sinatra
[/code]
Then, create a new folder and inside, make a new file called app.rb.

In app.rb:

[ruby]
require ‘rubygems’
require ‘sinatra’
[/ruby]

Here we’re importing Sinatra and Ruby gems into our project. We now have to install the OpenTok Ruby SDK by running the following command:

[ruby]
gem install opentok
[/ruby]

Now, import the OpenTokSDK and include your API information.
Your new app.rb file should look like this:

[ruby]
require ‘rubygems’
require ‘sinatra’
require ‘opentok’

API_KEY = "" # Replace with your OpenTok API key.
API_SECRET = "" # Replace with your OpenTok API secret.
OTSDK = OpenTok::OpenTokSDK.new API_KEY, API_SECRET

[/ruby]

Now, we have to add some basic url routing. When a user first goes to the site, he should be redirected to a new chatroom. In OpenTok, chatrooms are represented by sessions, each of which has a session_id. This chatroom url for this app will be based off of an OpenTok Session ID. This createSession function returns the id of the newly created session.

[ruby]
get ‘/’ do
sessionId = OTSDK.createSession()
[/ruby]

Next, we need a function which allows us to enter a chatroom by using the Session ID part of the url. So, we will route all urls with Session IDs (like http://domain.com/session_id) to a new function.

[ruby]
get ‘/:session_id’ do
@sessionId = params[:session_id]
@token = OTSDK.generateToken :session_id => @sessionId
erb :chat
end
[/ruby]

In this method, we will create a new token for anyone visiting a specific chatroom. Tokens are like a key to a chatroom, where the session is the room. Each person that connects to an OpenTok Session has a unique token which serves as his or her key to the chatroom. We then call the erb command to render the template found in views/chat.erb, which contains the front-end chat UI.

Now, in the first function, we have to add the actual redirecting part of the code. The function should now look like this:

[ruby]
get ‘/’ do
sessionId = OTSDK.createSession()
url = "/#{sessionId}"
redirect url
end
[/ruby]

Now, anyone that goes to the index page gets sent to a new chat room by creating an OpenTok Session and redirecting to a url based on the Session ID.

That’s it for the Sinatra side of the app!

For the front end part of this, read our excellent Javascript Hello World Tutorial.

You can view a live demo of the Sinatra Chatroom App here.
You can also view the full source code of the project here.