Skip to content

Commit

Permalink
Merge pull request twilio#4 from TwilioDevEd/migrate-ip-messaging
Browse files Browse the repository at this point in the history
Fix IP-Messaging snippets and meta.json
  • Loading branch information
mcelicalderon committed Apr 15, 2016
2 parents 50dd889 + bddb22b commit 85f571b
Show file tree
Hide file tree
Showing 31 changed files with 313 additions and 44 deletions.
4 changes: 4 additions & 0 deletions ip-messaging/channels/accept-invite/meta.json
@@ -0,0 +1,4 @@
{
"title": "Accepting an Invite",
"type": "mobile"
}
4 changes: 4 additions & 0 deletions ip-messaging/channels/create-channel/meta.json
@@ -0,0 +1,4 @@
{
"title": "Create a Channel",
"type": "mobile"
}
4 changes: 4 additions & 0 deletions ip-messaging/channels/delete-a-channel/meta.json
@@ -0,0 +1,4 @@
{
"title": "Delete a Channel",
"type": "mobile"
}
4 changes: 4 additions & 0 deletions ip-messaging/channels/detect-channel-states/meta.json
@@ -0,0 +1,4 @@
{
"title": "Handle Channel Events",
"type": "mobile"
}
16 changes: 16 additions & 0 deletions ip-messaging/channels/detect-member-states/detect-member-states.js
@@ -0,0 +1,16 @@
// Listen for members joining a channel
myChannel.on('memberJoined', function(member) {
console.log(member.identity + 'has joined the channel.');
});
// Listen for members joining a channel
myChannel.on('memberLeft', function(member) {
console.log(member.identity + 'has left the channel.');
});
// Listen for members typing
myChannel.on('typingStarted', function(member) {
console.log(member.identity + 'is currently typing.');
});
// Listen for members typing
myChannel.on('typingEnded', function(member) {
console.log(member.identity + 'has stopped typing.');
});
4 changes: 4 additions & 0 deletions ip-messaging/channels/detect-member-states/meta.json
@@ -0,0 +1,4 @@
{
"title": "Handle Member Events",
"type": "mobile"
}
4 changes: 4 additions & 0 deletions ip-messaging/channels/get-messages/meta.json
@@ -0,0 +1,4 @@
{
"title": "Receiving Messages",
"type": "mobile"
}
4 changes: 4 additions & 0 deletions ip-messaging/channels/join-a-channel/meta.json
@@ -0,0 +1,4 @@
{
"title": "Join a Channel",
"type": "mobile"
}
4 changes: 4 additions & 0 deletions ip-messaging/channels/message-added/meta.json
@@ -0,0 +1,4 @@
{
"title": "Listening for New Messages",
"type": "server"
}
4 changes: 4 additions & 0 deletions ip-messaging/channels/retrieve-channels/meta.json
@@ -0,0 +1,4 @@
{
"title": "Retrieve Channels",
"type": "mobile"
}
4 changes: 4 additions & 0 deletions ip-messaging/channels/send-invite/meta.json
@@ -0,0 +1,4 @@
{
"title": "Sending an Invite",
"type": "mobile"
}
4 changes: 4 additions & 0 deletions ip-messaging/channels/send-messages/meta.json
@@ -0,0 +1,4 @@
{
"title": "Sending Messages",
"type": "mobile"
}
4 changes: 4 additions & 0 deletions ip-messaging/consumption/consumption-report/meta.json
@@ -0,0 +1,4 @@
{
"title": "Sending a Consumption Report",
"type": "mobile"
}
4 changes: 4 additions & 0 deletions ip-messaging/consumption/message-read-status/meta.json
@@ -0,0 +1,4 @@
{
"title": "Updating Member Read Status in Realtime",
"type": "mobile"
}
@@ -0,0 +1,4 @@
{
"title": "Displaying a Typing Indicator Message",
"type": "mobile"
}
4 changes: 4 additions & 0 deletions ip-messaging/typing-indicator/typing-indicator-send/meta.json
@@ -0,0 +1,4 @@
{
"title": "Sending the Typing Indicator",
"type": "mobile"
}
4 changes: 4 additions & 0 deletions ip-messaging/users/client-initialization/meta.json
@@ -0,0 +1,4 @@
{
"title": "Initializing the client",
"type": "mobile"
}
4 changes: 4 additions & 0 deletions ip-messaging/users/token-generation-server/meta.json
@@ -0,0 +1,4 @@
{
"title": "Creating an Access Token on the Server",
"type": "mobile"
}
@@ -0,0 +1,63 @@
import com.github.javafaker.Faker;
import com.google.gson.Gson;
import com.twilio.sdk.auth.AccessToken;
import com.twilio.sdk.auth.IpMessagingGrant;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import static spark.Spark.get;
import static spark.Spark.staticFileLocation;

public class WebApp {

public static void main(String[] args) {
// Serve static files from src/main/resources/public
staticFileLocation("/public");

// Create a Faker instance to generate a random username for the connecting user
Faker faker = new Faker();

// Create an access token using our Twilio credentials
get("/token", "application/json", (request, response) -> {
// Generate a random username for the connecting client
String identity = faker.name().firstName() + faker.name().lastName() + faker.address().zipCode();

// Create an endpoint ID which uniquely identifies the user on their current device
String appName = "TwilioChatDemo";
String endpointId = appName + ":" + identity + ":" + request.params("device");

// Fetch environment info
Map<String, String> env = new HashMap<String, String>();
Path path = Paths.get(".env");
Files.lines(path).forEach(s -> {
String[] keyVal = s.split("=");
String key = keyVal[0];
String val = keyVal[1];
env.put(key, val);
});

// Create IP messaging grant
IpMessagingGrant grant = new IpMessagingGrant();
grant.setEndpointId(endpointId);
grant.setServiceSid(env.get("TWILIO_IPM_SERVICE_SID"));

// Create access token
AccessToken token =
new AccessToken.Builder(env.get("TWILIO_ACCOUNT_SID"), env.get("TWILIO_API_KEY"),
env.get("TWILIO_API_SECRET")).identity(identity).grant(grant).build();

// create JSON response payload
HashMap<String, String> json = new HashMap<String, String>();
json.put("identity", identity);
json.put("token", token.toJWT());

// Render JSON response
Gson gson = new Gson();
return gson.toJson(json);
});
}
}
@@ -0,0 +1,53 @@
require('dotenv').load();
var http = require('http');
var path = require('path');
var AccessToken = require('twilio').AccessToken;
var IpMessagingGrant = AccessToken.IpMessagingGrant;
var express = require('express');
// Create Express webapp
var app = express();
app.use(express.static(path.join(__dirname, 'public')));

/*
Generate an Access Token for a chat application user - it generates a random
username for the client requesting a token, and takes a device ID as a query
parameter.
*/
app.get('/token', function(request, response) {
var appName = 'TwilioChatDemo';
var identity = "John Doe";
var deviceId = request.query.device;

// Create a unique ID for the client on their current device
var endpointId = appName + ':' + identity + ':' + deviceId;

// Create a "grant" which enables a client to use IPM as a given user,
// on a given device
var ipmGrant = new IpMessagingGrant({
serviceSid: process.env.TWILIO_IPM_SERVICE_SID,
endpointId: endpointId
});

// Create an access token which we will sign and return to the client,
// containing the grant we just created
var token = new AccessToken(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_API_KEY,
process.env.TWILIO_API_SECRET
);
token.addGrant(ipmGrant);
token.identity = identity;

// Serialize the token to a JWT string and include it in a JSON response
response.send({
identity: identity,
token: token.toJwt()
});
});

// Create http server and run it
var server = http.createServer(app);
var port = process.env.PORT || 3000;
server.listen(port, function() {
console.log('Express server running on *:' + port);
});
@@ -0,0 +1,35 @@
<?php

require_once('./twilio-php/Services/Twilio.php');
require_once('./config.php');

// An identifier for your app - can be anything you'd like
$appName = 'TwilioChatDemo';
// choose a random username for the connecting user
$identity = "John Doe";
// A device ID should be passed as a query string parameter to this script
$deviceId = empty($_GET['device']) ? "unknown" : $_GET['device'];
// The endpoint ID is a combination of the above
$endpointId = $appName . ':' . $identity . ':' . $deviceId;
// Create access token, which we will serialize and send to the client
$token = new Services_Twilio_AccessToken(
$TWILIO_ACCOUNT_SID,
$TWILIO_API_KEY,
$TWILIO_API_SECRET,
3600,
$identity
);

// Create IP Messaging grant
$ipmGrant = new Services_Twilio_Auth_IpMessagingGrant();
$ipmGrant->setServiceSid($TWILIO_IPM_SERVICE_SID);
$ipmGrant->setEndpointId($endpointId);

// Add grant to token
$token->addGrant($ipmGrant);

// return serialized token and the user's randomly generated ID
echo json_encode(array(
'identity' => $identity,
'token' => $token->toJWT(),
));
@@ -0,0 +1,39 @@
import os
from flask import Flask, jsonify, request
from faker import Factory
from twilio.access_token import AccessToken, IpMessagingGrant

app = Flask(__name__)
fake = Factory.create()

@app.route('/')
def index():
return app.send_static_file('index.html')

@app.route('/token')
def token():
# get credentials for environment variables
account_sid = os.environ['TWILIO_ACCOUNT_SID']
api_key = os.environ['TWILIO_API_KEY']
api_secret = os.environ['TWILIO_API_SECRET']
service_sid = os.environ['TWILIO_IPM_SERVICE_SID']

# create a randomly generated username for the client
identity = fake.user_name()

# Create a unique endpoint ID for the
device_id = request.args.get('device')
endpoint = "TwilioChatDemo:{0}:{1}".format(identity, device_id)

# Create access token with credentials
token = AccessToken(account_sid, api_key, api_secret, identity)

# Create an IP Messaging grant and add to token
ipm_grant = IpMessagingGrant(endpoint_id=endpoint, service_sid=service_sid)
token.add_grant(ipm_grant)

# Return token info as JSON
return jsonify(identity=identity, token=token.to_jwt())

if __name__ == '__main__':
app.run(debug=True)
@@ -0,0 +1,38 @@
require 'twilio-ruby'
require 'sinatra'
require 'sinatra/json'
require 'dotenv'
require 'faker'

# Load environment configuration
Dotenv.load

# Render home page
get '/' do
File.read(File.join('public', 'index.html'))
end

# Generate a token for use in our IP Messaging application
get '/token' do
# Get the user-provided ID for the connecting device
device_id = params['device']

# Create a random username for the client
identity = Faker::Internet.user_name

# Create a unique ID for the currently connecting device
endpoint_id = "TwilioDemoApp:#{identity}:#{device_id}"

# Create an Access Token for IP messaging usage
token = Twilio::Util::AccessToken.new ENV['TWILIO_ACCOUNT_SID'],
ENV['TWILIO_API_KEY'], ENV['TWILIO_API_SECRET'], 3600, identity

# Create IP Messaging grant for our token
grant = Twilio::Util::AccessToken::IpMessagingGrant.new
grant.service_sid = ENV['TWILIO_IPM_SERVICE_SID']
grant.endpoint_id = endpoint_id
token.add_grant grant

# Generate the token and send to client
json :identity => identity, :token => token.to_jwt
end
2 changes: 1 addition & 1 deletion lookups/lookup-get-basic-example-1/meta.json
@@ -1,4 +1,4 @@
{
"title": "Lookup with E.164 formatted number",
"type": "server"
}
}

0 comments on commit 85f571b

Please sign in to comment.