add participant for the twilio room - javascript

Twilio Room was created using the below code, but not able to produce any output, it is showing everything is working fine, but not able to know how can i proceed forward so I can add multiple participants and can make a video call for each other. it asks for the camera and mike permission but not able to see the video. thanks in advance if you see any mistake please ignore it
require_once ./vendor/autoload.php;
use Twilio\Rest\Client;
// use Twilio\TwiML\VoiceResponse;
// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = "AC3c0f477f066042308c088574dae7bf9a";
$token = "8c7e575ac24e6e6f924bbaa22c42bbb4";
$twilio = new Client($sid, $token);
$room = $twilio->video->v1->rooms
->create([
"statusCallback" => "http://example.org",
"type" => "peer-to-peer",
"uniqueName" => "DailyStandup227"
]
);
print_r($room);
*After this I generated the access token
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php
require_once './vendor/autoload.php';// Loads the library
use Twilio\Jwt\AccessToken;
use Twilio\Jwt\Grants\ChatGrant;
use Twilio\Jwt\Grants\VideoGrant;
// Required for all Twilio access tokens
$twilioAccountSid = 'AC3c0f477f066042308c088574dae7bf9a';
$twilioApiKey = 'SKb30ca8d445b8bd68479c54c2544fa1b4';
$twilioApiSecret = 'ixmFdysnjHRuXgXCTOQwl4I4OIsPa27l';
// Required for Chat grant
$roomName = 'DailyStandup221';
// choose a random username for the connecting user
$identity = "amirIshaque";
// Create an access token, which we will serialize and send to the client
$token = new AccessToken(
$twilioAccountSid,
$twilioApiKey,
$twilioApiSecret,
3600,
$identity
);
// Create Voice grant
$videoGrant = new VideoGrant();
$videoGrant->setRoom($roomName);
// Add grant to token
$token->addGrant($videoGrant);
// render token to string
echo $token->toJWT();
** then by using the above access token and room **
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My Website</title>
<!-- <link rel="stylesheet" href="./style.css"> -->
<!-- <link rel="icon" href="./favicon.ico" type="image/x-icon"> -->
</head>
<body>
<main>
<h1>Welcome to My Website</h1>
<div id="container"></div>
<Response>
<Dial><Conference>DailyStandup18</Conference></Dial>
<Response>
</main>
<!-- <script src="./twilio-video.min.js"></script> -->
<script src="./twilio-video.min.js"></script>
<script>
const Video = Twilio.Video;
console.log('$TOKEN',Video);
Video.connect('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImN0eSI6InR3aWxpby1mcGE7dj0xIn0.eyJqdGkiOiJTS2IzMGNhOGQ0NDViOGJkNjg0NzljNTRjMjU0NGZhMWI0LTE2NjY0NDcyMDMiLCJpc3MiOiJTS2IzMGNhOGQ0NDViOGJkNjg0NzljNTRjMjU0NGZhMWI0Iiwic3ViIjoiQUMzYzBmNDc3ZjA2NjA0MjMwOGMwODg1NzRkYWU3YmY5YSIsImV4cCI6MTY2NjQ1MDgwMywiZ3JhbnRzIjp7ImlkZW50aXR5IjoiYW1pcklzaGFxdWUiLCJ2aWRlbyI6eyJyb29tIjoiRGFpbHlTdGFuZHVwMjIxIn19fQ.f-yld_8HU_HX6f1NVuwxSOIq3KEcuh6sWWhms6bar14', { name: 'DailyStandup227' }).then(room => {
console.log(room);
console.log('Connected to Room "%s"', room.name);
console.log(room.participants);
room.participants.forEach(participantConnected);
room.on('participantConnected', participantConnected);
room.on('participantDisconnected', participantDisconnected);
room.once('disconnected', error => room.participants.forEach(participantDisconnected));
alert('5');
});
// Twilio.Video
// .createLocalVideoTrack()
// .then(track => {
// const container = document.getElementById('container');
// container.appendChild(track.attach());
// });
function participantConnected(participant) {
console.log('Participant "%s" connected', participant.identity);
alert('1');
const div = document.createElement('div');
div.id = participant.sid;
div.innerText = participant.identity;
participant.on('trackSubscribed', track => trackSubscribed(div, track));
participant.on('trackUnsubscribed', trackUnsubscribed);
participant.tracks.forEach(publication => {
if (publication.isSubscribed) {
trackSubscribed(div, publication.track);
}
});
document.body.appendChild(div);
}
function participantDisconnected(participant) {
alert('2');
console.log('Participant "%s" disconnected', participant.identity);
document.getElementById(participant.sid).remove();
}
function trackSubscribed(div, track) {
alert('3');
div.appendChild(track.attach());
}
function trackUnsubscribed(track) {
alert('4');
track.detach().forEach(element => element.remove());
}
</script>
<!-- <script src="index.js"></script> -->
</body>
</html>

Related

Manage Rcon remote web rust server

I am trying to develop a web application that allows me to type commands in the Rcon console via the web Browser.
The problem is that every time I send a command I get “[Rcon] Failed to parse message, incorrect format”.
Error message rcon
File log server
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket</title>
</head>
<body>
<h1>WebSockets Rust Server</h1>
<input type="button" value="Send" onclick="webSocketTest();">
<script>
function webSocketTest() {
// Create the WebSocket
const rcon = new WebSocket('ws://localhost:28016/1234');
rcon.onopen = function(e) {
// This line causes the problem
rcon.send('status');
}
rcon.onmessage = function(e) {
// Code
}
rcon.onerror = function(e) {
// Code
}
rcon.onclose = function(e) {
// Code
}
}
</script>
</body>
</html>
EDIT:
Finally I fix the problem. I was making the mistake of trying to collect the data in the wrong function.
<<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket</title>
</head>
<body>
<h1>WebSockets Rust Server</h1>
<input type="button" value="Send" id="btnSend"><br>
<textarea id="response" rows="10" cols="60"></textarea>
<script>
const rcon = new WebSocket('ws://localhost:28016/1234');
console.log(rcon);
rcon.onopen = function() {
console.log('Connected');
};
/* In this funcion have the server response */
rcon.onmessage = function(e) {
const msg = JSON.parse(e.data);
document.getElementById('response').innerHTML = msg.Message;
}
rcon.onerror = function (e) {
console.log(e);
}
rcon.onclose = function(e) {
console.log('Connection closed');
console.log(e);
};
/* Click Event on send btn that calls anonymous function to send the data */
const btnSend = document.getElementById("btnSend");
btnSend.addEventListener('click', function() {
/* Data to send */
const data = {
Message: "status", // rcon command
Identifier: 1, // +server.identity
Name: "totalgamer" // +server.hostname
};
/* Need to use JSON.stringify before send the data */
rcon.send(JSON.stringify(data));
});
</script>
</body>
</html>
Now it's works fine.

Inconsistent HTTP trigger behaviour to Firebase Cloud Functions

I'm having trouble reliably triggering a Firebase Cloud Function via the HTTP trigger method. It doesn't work in all browsers, and sometimes only works if you reload the page. The html webpage is hosted with Firebase Hosting.
Premise is simple, main html page has a button which when pressed, sends the HTTP request to the Cloud Function, and then navigates to another page saying done. The Cloud Function sends an FCM notification and works reliably when manually using the HTTP request url.
Is there something wrong with my HTTP request in scripts.js? What would make this very inconsistent behaviour? It works generally in Chrome, not in Firefox, and sometimes in Edge.
index.html looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel=icon href=favicon.ico>
<title>Title</title>
</head>
<body>
<h1>New heading</h1>
<input type="button" value="Send FCM" onclick="doThing()">
<script src="scripts.js"></script>
</body>
</html>
scripts.js looks like this
var request = require('request')
function doThing(){
const url = '<HTTP request URL>';
request(url, function(error, response, body){
if (!error && response.statusCode == 200){
window.location.href = "outro.html";
}
})
}
and outro.html looks like this;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
<body>
<h1>Cya</h1>
</body>
</body>
</html>
For clarity, this is the Cloud Function script:
const functions = require('firebase-functions');
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.https.onRequest((request, response) =>{
var topic = 'all';
var payload = {
notification:{
title: 'Title!',
body: 'Test!'
},
};
return admin.messaging().sendToTopic(topic, payload).then((res) =>{
response.status(200).send("ok");
return console.log("Success:");
}).catch((err) =>{
console.log("Error: ", err);
response.status(500).send("bad");
});
});
All are deployed with firebase deploy.

Checking Login Status , Google oAuth, without rendering button

My Problem
I have a login page that gives the user the option to "Login With Google".
When the user successfully logs in, I am storing their username and Google ID in the Session.
My problem is, on pages OTHER than the login page, I need to check to see if they are logged in. I am having problems getting this to work. If they are not logged in, I need to know that - putting in a simple global page variable for now would be suffice.
This code handles the login: ( the renderButton function is called immediately on page load )
var googleID; // global variable to hold ID
var token; // will hold token ( once I get this working )
// Render Google Sign-in button
function renderButton() {
gapi.signin2.render('gSignIn', {
'scope': 'profile email',
'width': 240,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': onSuccess,
'onfailure': onFailure
});
}
// Sign-in success callback
function onSuccess(googleUser) {
gapi.client.load('oauth2', 'v2', function () {
var request = gapi.client.oauth2.userinfo.get({
'userId': 'me'
});
request.execute(function (resp) {
// GET GOOGLE ID
googleId = resp.id;
});
});
}
// Sign-in failure callback
function onFailure(error) {
alert(error);
}
// Sign out the user
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
loggedIn = false;
});
// Change Link
document.querySelector("#loginNav").innerHTML = "Login";
auth2.disconnect();
}
So this all works great on the login page.
But on my other pages, for instance my index page, how to I check to see if they are logged in?
I am trying this code, but getting NOTHING - no error, no success.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Login</title>
</head>
<body>
<div id="loginStatus">Status</div>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="https://apis.google.com/js/client:platform.js?onload=init" async defer></script>
<script>
var auth2; // Global
var loggedIn;
function init() {
var appStart = function () {
gapi.load('auth2', initSigninV2);
};
}
/**
* Initializes Signin v2 and sets up listeners.
*/
var initSigninV2 = function () {
auth2 = gapi.auth2.init({
client_id: 'MY-CLIENT--ID-HERE',
scope: 'profile'
});
if (auth2.isSignedIn.get() == true) {
alert("Loggin in!");
loggedIn = "LOGGED IN";
} else {
alert("Not Logged IN!!!");
loggedIn = "NOT LOGGED IN";
}
document.getElementById("loginStatus").innerHTML = loggedIn;
}
</script>
</body>
</html>
Can anyone help me get this working?
Thank you.
I found a solution that worked for me.
Once logged in the first time, I simply saved the user credentials in a local storage variable.
Then on subsequent pages, I check that variable.
It's not fool-proof, but for my basic needs it works.

How to Youtube transcript with api (captions.download

I have built a javascript code to be able to read any Youtube video transcript (gapi.client.youtube.captions.download). The auth 2.0 works fine, I run my app in a local web server everything is fine, the problem is that when I run the request I have the error 403: cb=gapi.loaded_0:164 GET https://content.googleapis.com/youtube/v3/captions/My_API_Key 403 I have not found any solution here in StackOverflow.. any idea ?
Here is my js file:
const CLIENT_ID = 'My_Client_ID';
const DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest"];
const SCOPES = 'https://www.googleapis.com/auth/youtube.readonly';
const authorizeButton = document.getElementById('enter-button');
const signoutButton = document.getElementById('exit-button');
const content = document.getElementById('content');
// default youtube channel
const defaultChannel = 'googledevelopers';
// Load auth2 library
function handleClientLoad(){
gapi.load('client:auth2', initClient);
}
// Init API client library and set up sing in listeners
function initClient(){
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(() => {
// Listen for sing state changes
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle initial sign in state
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignouClick;
});
}
// update UI sign in state changes
function updateSigninStatus(isSignedIn){
if(isSignedIn){
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
content.style.display = 'block';
getChannel(defaultChannel);
}else{
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
content.style.display = 'none';
}
}
// Handle Login
function handleAuthClick(){
gapi.auth2.getAuthInstance().signIn();
}
// Handle Logout
function handleSignouClick(){
gapi.auth2.getAuthInstance().signOut();
}
// Display channel Data
function showChannelData(data){
const channelData = document.getElementById('channel-data');
channelData.innerHTML = data;
}
// Get channel from API
function getChannel(channel){
gapi.client.youtube.captions.download({
id: 'guMGyC1tUYAdL3hgBlcGnW4Rt_bBUbtp'
})
.then(response => {
console.log(response);
const channel = response.result.items[0];
})
.catch(err => alert('No Channel By THat Name'));
}
And here is my index.ejs file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Your awesome Youtube search engine</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Awesome videos!" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
</head>
<body>
<header>
<h1 class="w100 text-center">YouTube Viral Search</h1>
</header>
<div class="container">
<p>Login with Google</p>
<button class="btn green" id="enter-button">Log In</button>
<button class="btn green" id="exit-button">Log Out</button>
<br />
<div id="content">
<div class="row">
<div id="channel-data" class="col s12"></div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
<script src="/javascripts/appYT.js"></script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
enter code here
You can use the following code for get the transcript in a given video.
This is the working jsfiddle
N.B here I have the videoId zenMEj0cAC4, but you can change it as you desire.
$.ajax({
type: "GET",
url: "https://video.google.com/timedtext?type=track&v=zenMEj0cAC4&id=0&lang=en",
crossDomain: true,
}).done(function(data) {
console.log(data);
getCaption(data);
});
var parser, xmlDoc;
var HTML_captions = "";
// Parse the AJAX response and get the captions.
function getCaption(ajax_response) {
try {
parser = new DOMParser();
xmlDoc = parser.parseFromString(ajax_response, "text/xml");
//console.log(ajax_response);
//console.log(xmlDoc.getElementsByTagName("transcript").length);
if (xmlDoc.getElementsByTagName("transcript").length > 0) {
// Loop the results of the xmlDoc:
for (var i = 0; i < xmlDoc.getElementsByTagName("transcript")[0].childNodes.length; i++) {
console.log(xmlDoc.getElementsByTagName("transcript")[0].childNodes[i].innerHTML);
HTML_captions += xmlDoc.getElementsByTagName("transcript")[0].childNodes[i].innerHTML + "<br/>";
}
} else {
// Loop the results of the ajax_response;
for (var i = 0; i < ajax_response.getElementsByTagName("transcript")[0].childNodes.length; i++) {
console.log(ajax_response.getElementsByTagName("transcript")[0].childNodes[i].innerHTML);
HTML_captions += ajax_response.getElementsByTagName("transcript")[0].childNodes[i].innerHTML + "<br/>";
}
}
document.getElementById("demo").innerHTML = "<i>Preparing captions...</i>";
setTimeout(fillData(), 2000);
} catch (err) {
console.log(err);
document.getElementById("demo").innerHTML = ('Error at getCaption function - see console form more details.');
alert('Error at getCaption function - see console form more details.');
}
}
// Fill the data "captions" in a HTML "div" control.
function fillData() {
try {
document.getElementById("demo").innerHTML = HTML_captions;
} catch (err) {
console.log(err);
document.getElementById("demo").innerHTML = ('Error at fillData function - see console form more details.');
alert('Error at fillData function - see console form more details.');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="demo"><i>Loading captions...</i></div>
Just in case you need more information about how you can get automatic closed captions, you can refer to these answers in Stack Overflow:
Get closed caption “cc” for Youtube video
Extract automatic captions from YouTube video

podio API javascript

I m trying to connect Podio API with a webpage.
I have this error : "podio.hasAuthError is not a function", but i don t know what to do....
I show you my (basic) code.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="lib/podio-js/dist/podio-js.js"></script>
<script type="text/javascript">
var podio = new PodioJS({ authType: 'client', clientId: 'foo'});
var redirectURL = 'http://foo';
// isAuthenticated either gets the cached accessToken
// or will check whether it is present in the hash fragment
podio.isAuthenticated().then(function(){
// ready to make API calls...
}).catch(function(){
if (podio.hasAuthError()) {
console.log(podio.getAuthError());
} else {
// start authentication via link or redirect
console.log(platform.getAuthorizationURL(redirectURL));
}
});
</script>
</head>
<body>
</body>
</html>

Categories