Introduction


Twilio is a cloud communications platform as a service company based in San Francisco, California. Twilio allows software developers to programmatically make and receive phone calls, send and receive text messages, and perform other communication functions using its web service APIs.

Programmable Video

Programmable Video is the service provided by Twilio, Connect multiple users (limited) in a single video Conference, so that those users can interact with each other with the live conference or run-time video chat.
Step 1 - Build Node.Js application
Node js code is used for API calls, to authenticate the user and in return will get token of the user. After getting various user-specific tokens, we can connect to the same room created by Twilio to make a video conference.
  1. require('dotenv').load()
  2. const express = require('express')
  3. const app = express()
  4. var AccessToken = require("twilio").jwt.AccessToken;
  5. var VideoGrant = AccessToken.VideoGrant;
  6. app.get('/token/:identity', function (req, res) {
  7. const identity = req.params.identity;
  8. // Create an access token which we will sign and return to the client,
  9. // containing the grant we just created
  10. var token = new AccessToken(
  11. process.env.TWILIO_ACCOUNT_SID,
  12. process.env.TWILIO_API_KEY,
  13. process.env.TWILIO_API_SECRET
  14. );
  15. // Assign the generated identity to the token
  16. token.identity = identity;
  17. const grant = new VideoGrant();
  18. // Grant token access to the Video API features
  19. token.addGrant(grant);
  20. // Serialize the token to a JWT string and include it in a JSON response
  21. res.send({
  22. identity: identity,
  23. jwt: token.toJwt()
  24. })
  25. })
  26. app.listen(3001, function () {
  27. console.log('Programmable Video Chat token server listening on port 3001!')
  28. })
Step 2 - Build React.Js application
Configured basic ReactJs application using the create-react-app command. Using this command will get the default well-structured application of React.

Step 3 - Twilio Configuration
If you do not have an account on Twilio, you can sign up (Register), then configure your account.

You can get your configuration key(s) from:
  • TWILIO_ACCOUNT_SID: Get you to TWILIO_ACCOUNT_SID from the Twilio account dashboard.

  • Let’s make our .env file and add the following code to it, replacing each key and token with the one found in our Twilio console.

Twilio Code - Predefined Functions(App.js)

Twilio API provided predefined functions to get connected with different users. Provided we get token, create a room, join a room, attachTracks, attachParticipants, detachTracks, etc.. with the use of predefined function we can get connect with different users and make a track of each user who is connected or who is not.
  1. import React, { Component } from 'react'
  2. import Video from 'twilio-video';
  3. import axios from 'axios';
  4. import './global.css';
  5. import { ToastsContainer, ToastsStore } from 'react-toasts';
  6. import "react-loader-spinner/dist/loader/css/react-spinner-loader.css";
  7. import Loader from 'react-loader-spinner';
  8. class App extends Component {
  9. constructor(props) {
  10. super(props);
  11. this.state = {
  12. userName: "",
  13. identity: null,
  14. peerUserId: 0,
  15. peerIdentity: "",
  16. roomName: '*****', // Room Name
  17. roomNameErr: false, // Track error for room name TextField
  18. previewTracks: null,
  19. localMediaAvailable: false,
  20. hasJoinedRoom: false,
  21. hasParticipantsJoinedRoom: false,
  22. activeRoom: '', // Track the current active room
  23. jwt: ''
  24. }
  25. this.joinRoom = this.joinRoom.bind(this);
  26. this.roomJoined = this.roomJoined.bind(this);
  27. this.leaveRoom = this.leaveRoom.bind(this);
  28. this.detachTracks = this.detachTracks.bind(this);
  29. this.detachParticipantTracks = this.detachParticipantTracks.bind(this);
  30. }
  31. getTwillioToken = () => {
  32. const currentUserName = this.refs["yourname"].value;
  33. if (currentUserName.length === 0) {
  34. ToastsStore.error("Please enter the username!");
  35. return;
  36. }
  37. axios.get('/token/' + currentUserName).then(results => {
  38. const { identity, jwt } = results.data;
  39. this.setState(
  40. {
  41. identity,
  42. jwt
  43. }, () => {
  44. if (jwt.length === 0 || identity.length === 0) {
  45. ToastsStore.error("Issue to fetch token!");
  46. } else {
  47. this.setState({ userName: currentUserName });
  48. this.joinRoom();
  49. }
  50. });
  51. });
  52. }
  53. joinRoom() {
  54. if (!this.state.roomName.trim()) {
  55. this.setState({ roomNameErr: true });
  56. return;
  57. }
  58. console.log("Joining room '" + this.state.roomName + "'...");
  59. let connectOptions = {
  60. name: this.state.roomName
  61. };
  62. if (this.state.previewTracks) {
  63. connectOptions.tracks = this.state.previewTracks;
  64. }
  65. // Join the Room with the token from the server and the
  66. // LocalParticipant's Tracks.
  67. Video.connect(this.state.jwt, connectOptions).then(this.roomJoined, error => {
  68. ToastsStore.error('Please verify your connection of webcam!');
  69. ToastsStore.error('Webcam-Video permission should not block!');
  70. });
  71. }
  72. attachTracks(tracks, container) {
  73. tracks.forEach(track => {
  74. container.appendChild(track.attach());
  75. });
  76. }
  77. // Attaches a track to a specified DOM container
  78. attachParticipantTracks(participant, container) {
  79. var tracks = Array.from(participant.tracks.values());
  80. this.attachTracks(tracks, container);
  81. }
  82. detachTracks(tracks) {
  83. tracks.forEach(track => {
  84. track.detach().forEach(detachedElement => {
  85. detachedElement.remove();
  86. });
  87. });
  88. }
  89. detachParticipantTracks(participant) {
  90. var tracks = Array.from(participant.tracks.values());
  91. this.detachTracks(tracks);
  92. }
  93. roomJoined(room) {
  94. // Called when a participant joins a room
  95. console.log("Joined as '" + this.state.identity + "'");
  96. this.setState({
  97. activeRoom: room,
  98. localMediaAvailable: true,
  99. hasJoinedRoom: true
  100. });
  101. // Attach LocalParticipant's Tracks, if not already attached.
  102. var previewContainer = this.refs.groupChat_localMedia;
  103. console.log('previewContainer.querySelector(video)', previewContainer.querySelector('.video'));
  104. if (!previewContainer.querySelector('.video')) {
  105. this.attachParticipantTracks(room.localParticipant, this.refs.groupChat_localMedia);
  106. }
  107. // Attach the Tracks of the Room's Participants.
  108. room.participants.forEach(participant => {
  109. console.log("Already in Room: '" + participant.identity + "'");
  110. this.setState({
  111. peerIdentity: participant.identity
  112. })
  113. var previewContainer = this.refs.remoteMedia;
  114. this.attachParticipantTracks(participant, previewContainer);
  115. });
  116. // When a Participant joins the Room, log the event.
  117. room.on('participantConnected', participant => {
  118. console.log("Joining: '" + participant.identity + "'");
  119. this.setState({
  120. peerIdentity: participant.identity,
  121. partnerConnected: true
  122. })
  123. });
  124. // When a Participant adds a Track, attach it to the DOM.
  125. room.on('trackAdded', (track, participant) => {
  126. console.log(participant.identity + ' added track: ' + track.kind);
  127. var previewContainer = this.refs.remoteMedia;
  128. this.attachTracks([track], previewContainer);
  129. });
  130. // When a Participant removes a Track, detach it from the DOM.
  131. room.on('trackRemoved', (track, participant) => {
  132. console.log(participant.identity + ' removed track: ' + track.kind);
  133. this.detachTracks([track]);
  134. });
  135. // When a Participant leaves the Room, detach its Tracks.
  136. room.on('participantDisconnected', participant => {
  137. console.log("Participant '" + participant.identity + "' left the room");
  138. this.detachParticipantTracks(participant);
  139. });
  140. // Once the LocalParticipant leaves the room, detach the Tracks
  141. // of all Participants, including that of the LocalParticipant.
  142. room.on('disconnected', () => {
  143. if (this.state.previewTracks) {
  144. this.state.previewTracks.forEach(track => {
  145. track.stop();
  146. });
  147. }
  148. this.detachParticipantTracks(room.localParticipant);
  149. room.participants.forEach(this.detachParticipantTracks);
  150. this.state.activeRoom = null;
  151. this.setState({ hasJoinedRoom: false, localMediaAvailable: false });
  152. });
  153. }
  154. leaveRoom() {
  155. this.state.activeRoom.disconnect();
  156. this.setState({ hasJoinedRoom: false, localMediaAvailable: false, peerIdentity: '' });
  157. }
  158. render() {
  159. /* Hide 'Join Room' button if user has already joined a room */
  160. let joinOrLeaveRoomButton = this.state.hasJoinedRoom ? (
  161. <button className="btn btn-warning" onClick={this.leaveRoom} > Leave Room</button>
  162. ) : (
  163. <button className="btn btn-success ml-2" onClick={this.getTwillioToken} >Join Room</button>
  164. );
  165. /** */
  166. return (
  167. <React.Fragment>
  168. <div className="container">
  169. <div className="row mt-3">
  170. <div className="col-6">
  171. <div className="card">
  172. <div className="card-body">
  173. <div ref="groupChat_localMedia"></div>
  174. <div className="text-center">
  175. {!this.state.hasJoinedRoom && <Loader type="Puff" color="#00BFFF" />}
  176. </div>
  177. </div>
  178. <div className="card-footer">{this.state.hasJoinedRoom ? <button className="btn btn-warning" onClick={this.leaveRoom} > Leave Room</button> : <span> </span>}</div>
  179. </div>
  180. </div>
  181. <div className="col-6">
  182. <div className="card">
  183. <div className="card-body">
  184. <div ref="remoteMedia"></div>
  185. <div className="text-center">
  186. {!this.state.hasParticipantsJoinedRoom && !this.state.peerIdentity && <Loader type="Puff" color="#00BFFF" />}
  187. </div>
  188. </div>
  189. <div className="card-footer text-center">
  190. {(!this.state.hasParticipantsJoinedRoom && !this.state.peerIdentity) ? <span>Wait for peer user to connect channel !!!</span> : <span>Peer User Name : {`${this.state.peerIdentity}`}</span >}
  191. </div>
  192. </div>
  193. </div>
  194. </div>
  195. </div>
  196. <ToastsContainer store={ToastsStore} />
  197. </React.Fragment>
  198. )
  199. }
  200. }
  201. export default App;
TwilioProgrammableVideo.gif
For More Details:
GitHub Repository