Skip to content

Commit 68d9278

Browse files
committed
adds HelloWorld sample app, fixes #16
1 parent c4d3e42 commit 68d9278

File tree

7 files changed

+210
-50
lines changed

7 files changed

+210
-50
lines changed

.gitignore

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,5 @@ coverage.xml
4141
# Sphinx documentation
4242
docs/_build/
4343

44-
# introduced by virtualenv
45-
.Python
46-
include/
47-
man/
44+
# Virtual env
45+
venv/

sample/HelloWorld/README.md

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
# OpenTok Hello World Python
2+
3+
This is a simple demo app that shows how you can use the OpenTok-Python-SDK to create Sessions,
4+
generate Tokens with those Sessions, and then pass these values to a JavaScript client that can
5+
connect and conduct a group chat.
6+
7+
## Running the App
8+
9+
First, we highly recommend setting up a [virtualenv](http://www.virtualenv.org/en/latest/).
10+
11+
```
12+
$ virtualenv venv
13+
$ source venv/bin/activate
14+
```
15+
16+
Next, download the dependencies using [Pip](http://www.pip-installer.org/en/latest/), from the
17+
current directory:
18+
19+
```
20+
(venv)$ pip install -r requirements.txt
21+
```
22+
23+
Then add your own API Key and API Secret to the environment variables. There are a few ways to do
24+
this but the simplest would be to do it right in your shell.
25+
26+
```
27+
(venv)$ export API_KEY=0000000
28+
(venv)$ export API_SECRET=abcdef1234567890abcdef01234567890abcdef
29+
```
30+
31+
Finally, start the server.
32+
33+
```
34+
(venv)$ python helloworld.py
35+
```
36+
37+
Visit <http://127.0.0.1:5000/> in your browser. Open it again in a second window. Smile! You've just
38+
set up a group chat.
39+
40+
## Walkthrough
41+
42+
This demo application uses the [Flask web microframework](http://flask.pocoo.org/). It is similar to
43+
many other popular web frameworks. We are only covering the very basics of the framework, but you can
44+
learn more by following the links above.
45+
46+
### Main Application (helloworld.py)
47+
48+
The first thing done in this file is to import the dependencies we will be using. In this case that
49+
is the Flask web framework, the os module, and most importantly the OpenTok SDK.
50+
51+
```python
52+
from flask import Flask, render_template
53+
from opentok import OpenTok
54+
import os
55+
```
56+
57+
Next this file performs some basic checks on the environment. If it cannot find the `API_KEY`and
58+
`API_SECRET` environment variables, there is no point in continuing.
59+
60+
The object `app` is our application and its initialized by instantiating an object from Flask.
61+
Then we initialize an instance of OpenTok as `opentok`. If this file is run as the main file,
62+
we should start running the app.
63+
64+
```python
65+
app = Flask(__name__)
66+
opentok = OpenTok(api_key, api_secret)
67+
68+
# ...
69+
70+
if __name__ == "__main__":
71+
app.run()
72+
```
73+
74+
Now, lets discuss the Hello World application's functionality. We want to set up a group chat so
75+
that any client that visits a page will connect to the same OpenTok Session. Once they are connected
76+
they can Publish a Stream and Subscribe to all the other streams in that Session. So we just need
77+
one Session object, and it needs to be accessible every time a request is made. On the next line we
78+
simply call the `OpenTok` instance's `create_session` method to get a Session and store it in the
79+
`session` variable. Alternatively, `session_id`s are commonly stored in databses for applications
80+
that have many of them.
81+
82+
```python
83+
session = opentok.create_session()
84+
```
85+
86+
We only need one page, so we create one route handler for any HTTP GET requests to trigger.
87+
88+
```python
89+
@app.route("/")
90+
def hello():
91+
# ...
92+
```
93+
94+
Now all we have to do is serve a page with the three values the client will need to connect to the
95+
session: `api_key`, `session_id`, and `token`. The `api_key` is available in the outer scope so we
96+
can just assign it. The `session_id` is available as the `session.session_id` attribute. The `token`
97+
is generated freshly on this request by calling the `generate_token` method of the `opentok`
98+
instance, and passing in the `session_id`. This is because a Token is a piece of information that
99+
carries a specific client's permissions in a certain Session. Ideally, as we've done here, you
100+
generate a unique token for each client that will connect.
101+
102+
```python
103+
key = api_key
104+
session_id = session.session_id
105+
token = opentok.generate_token(session_id)
106+
```
107+
108+
Now all we have to do is serve a page with those three values. Lets call our `render_template`
109+
helper that will pick up a template called `index.html` from the `templates/` directory in our
110+
application and pass in the variables for it to include on the page.
111+
112+
```python
113+
return render_template('index.html', api_key=key, session_id=session_id, token=token)
114+
```
115+
116+
### Main Template (templates/index.html)
117+
118+
This file simply sets up the HTML page for the JavaScript application to run, imports the
119+
JavaScript library, and passes the values created by the server into the JavaScript application
120+
inside `public/js/helloworld.js`
121+
122+
### JavaScript Applicaton (static/js/helloworld.js)
123+
124+
The group chat is mostly implemented in this file. At a high level, we connect to the given
125+
Session, publish a stream from our webcam, and listen for new streams from other clients to
126+
subscribe to.
127+
128+
For more details, read the comments in the file or go to the
129+
[JavaScript Client Library](http://tokbox.com/opentok/libraries/client/js/) for a full reference.

sample/HelloWorld/helloworld.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from flask import Flask, render_template
2+
from opentok import OpenTok
3+
import os
4+
5+
try:
6+
api_key = os.environ['API_KEY']
7+
api_secret = os.environ['API_SECRET']
8+
except Exception:
9+
raise Exception('You must define API_KEY and API_SECRET environment variables')
10+
11+
app = Flask(__name__)
12+
opentok = OpenTok(api_key, api_secret)
13+
session = opentok.create_session()
14+
15+
@app.route("/")
16+
def hello():
17+
key = api_key
18+
session_id = session.session_id
19+
token = opentok.generate_token(session_id)
20+
return render_template('index.html', api_key=key, session_id=session_id, token=token)
21+
22+
if __name__ == "__main__":
23+
app.debug = True
24+
app.run()

sample/HelloWorld/requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Flask
2+
-e ./../..
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Initialize an OpenTok Session object
2+
var session = TB.initSession(sessionId);
3+
4+
// Initialize a Publisher, and place it into the element with id="publisher"
5+
var publisher = TB.initPublisher(apiKey, 'publisher');
6+
7+
// Attach event handlers
8+
session.on({
9+
10+
// This function runs when session.connect() asynchronously completes
11+
sessionConnected: function(event) {
12+
// Publish the publisher we initialzed earlier (this will trigger 'streamCreated' on other
13+
// clients)
14+
session.publish(publisher);
15+
},
16+
17+
// This function runs when another client publishes a stream (eg. session.publish())
18+
streamCreated: function(event) {
19+
// Create a container for a new Subscriber, assign it an id using the streamId, put it inside
20+
// the element with id="subscribers"
21+
var subContainer = document.createElement('div');
22+
subContainer.id = 'stream-' + event.stream.streamId;
23+
document.getElementById('subscribers').appendChild(subContainer);
24+
25+
// Subscribe to the stream that caused this event, put it inside the container we just made
26+
session.subscribe(event.stream, subContainer);
27+
}
28+
29+
});
30+
31+
// Connect to the Session using the 'apiKey' of the application and a 'token' for permission
32+
session.connect(apiKey, token);
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="utf-8" />
5+
<title>OpenTok Hello World</title>
6+
<script src="//static.opentok.com/webrtc/v2.2/js/TB.min.js"></script>
7+
<script type="text/javascript">
8+
var apiKey = '{{ api_key }}';
9+
var sessionId = '{{ session_id }}';
10+
var token = '{{ token }}';
11+
</script>
12+
<script src="{{ url_for('static', filename='js/helloworld.js') }}"></script>
13+
</head>
14+
<body>
15+
<h2>Hello, World!</h2>
16+
17+
<div id="publisher"></div>
18+
19+
<div id="subscribers"></div>
20+
</body>
21+
</html>

sample/sample.py

Lines changed: 0 additions & 46 deletions
This file was deleted.

0 commit comments

Comments
 (0)