I'm trying to place OpenTok video calls within my website. How do I notify a particular user for video chat?
var apiKey = "447302";
var sessionId = "1_MX40NDczMDE5Mn5";
var token = "T1==cGFydG5lcl9pZD00NDczMDE5MiZzZGtfdmVyc2l";
// Initialize session, set up event listeners, and connect
var session = TB.initSession(sessionId);
session.addEventListener('sessionConnected', sessionConnectedHandler);
session.connect(apiKey, token);
function sessionConnectedHandler(event) {
var publisher = TB.initPublisher(apiKey, 'myPublisherDiv');
session.publish(publisher);
}
session.on("streamCreated", function(e) {
for (var i = 0; i < e.streams.length; i++) {
var div = document.createElement('div');
div.setAttribute('id', 'stream' + e.streams[i].streamId);
document.getElementById('chatDiv').appendChild(div);
session.subscribe(e.streams[i], e.streams[i].streamId);
}
});
OpenTok's API does not provide any notification logic. You can notify users by playing a sound or sending alert messages.
When a new person joins your session, you will get a connectionCreated event. You can throw a notification on your connectionCreated handler.
Related
I'm working on a website that plays a text to speech message,
but I want to be able to change the message with a Google document.
My question:
is it possible to make a js variable with the text in a Google Docs document?
This is my code so far:
const message = '' // Try edit me
// Update header text
document.querySelector('#header').innerHTML = message
// Log to console
console.log(message)
//message
var inter = message
//my scripts
if (inter.length===0){
location.reload();
} else{
var audio = new Audio('notif.mp3');
audio.play();
var msg = new SpeechSynthesisUtterance();
msg.text = inter;
window.speechSynthesis.speak(msg);
setTimeout(function() {
location.reload();
}, 30000);
}
My web page has
var bc = new BroadcastChannel('Consumer');
bc.onmessage = function(event) {
alert("a");
}
bc.postMessage("hello");
It broadcasts a message, and the page is also required to receive the same message.
However it doesn't work. Did I miss anything?
You can create two instances of BroadcastChannel on your page. One can act as a broadcaster for messages, the other one for receiving messages.
var broadcaster = new BroadcastChannel('Consumer');
var messageReceiver= new BroadcastChannel('Consumer');
messageReceiver.onmessage = function(event) {
alert(event.data);
}
broadcaster.postMessage("hello");
See this in action: https://jsfiddle.net/h56d3y27/
Or wrapped in a reusable class:
(note: class is not supported by all browsers. See : https://caniuse.com/#search=class for browser compatibility)
class AllInclusiveBroadcaster {
constructor(listener, channelName) {
if (!channelName) channelName = "channel";
this.broadcaster = new BroadcastChannel(channelName);
this.messageReceiver = new BroadcastChannel(channelName);
this.messageReceiver.onmessage = (event) => {
listener(event.data);
}
}
postmessage(data) {
this.broadcaster.postMessage(data);
}
}
var broadcaster = new AllInclusiveBroadcaster((data) => alert(data));
broadcaster.postmessage("Hello BroadcastChannel");
See this also in action a JSFiddle
You could dispatch an event (call it what you like) to, say, document, with the same data ... then have a single handler that listens for BroadcastChannel messages and to the event name you created above
in the following, the code creates and listens for fakeBroadcastMessage
created a function to send both the bc message and the "local" message
var bc = new BroadcastChannel('Consumer');
function handleBroadcastMessage(event) {
// do things here
}
bc.addEventHandler('message', handleBroadcastMessage);
document.addEventListener('fakeBroadcastMessage', handleBroadcastMessage);
function sendMessage(data) {
bc.postMessage(data);
var ev = new Event('fakeBroadcastMessage');
ev.data = data;
document.dispatchEvent(ev);
}
sendMessage('hello');
I want to get the access token in order to diaply the images of an account. So I display a pop up where the user can connect. The pop up works but it redirects to instagram site, with the user connected instead of send me the code. The link to the connection is something like :
https://www.instagram.com/accounts/login/?force_classic_login=&next=/oauth/authorize/%3Fclient_id=aaaaaaaa&redirect_uri=url&response_type=token
I log in and then, it redirects me to :
https://www.instagram.com/oauth/authorize/?client_id=aaaaaaa&redirect_uri=url&response_type=token
I don't understand how I can get the code. And I also used the exact same code as : https://github.com/radykal/instagram-popup-login
Can someone help me please ?
EDIT
var loc = window.location.host+window.location.pathname;
var accessToken = null; //the access token is required to make any endpoint calls, http://instagram.com/developer/endpoints/
var authenticateInstagram = function(instagramClientId, instagramRedirectUri, callback) {
//the pop-up window size, change if you want
var popupWidth = 700,
popupHeight = 500,
popupLeft = (window.screen.width - popupWidth) / 2,
popupTop = (window.screen.height - popupHeight) / 2;
//the url needs to point to instagram_auth.php
var popup = window.open('instagram_auth.php', '', 'width='+popupWidth+',height='+popupHeight+',left='+popupLeft+',top='+popupTop+'');
popup.onload = function() {
//open authorize url in pop-up
if(window.location.hash.length == 0) {
popup.open('https://instagram.com/oauth/authorize/?client_id='+instagramClientId+'&redirect_uri='+instagramRedirectUri+'&response_type=token', '_self');
}
//an interval runs to get the access token from the pop-up
var interval = setInterval(function() {
try {
console.log(window.location);
//check if hash exists
if(popup.location.hash.length) {
//hash found, that includes the access token
clearInterval(interval);
accessToken = popup.location.hash.slice(14); //slice #access_token= from string
popup.close();
if(callback != undefined && typeof callback == 'function') callback();
}
}
catch(evt) {
//permission denied
console.log("error");
}
}, 100);
}
};
function login_callback() {
alert("You are successfully logged in! Access Token: "+accessToken);
}
function login() {
authenticateInstagram(
'16edb5c3bc05437594d69178f2aa646a', //instagram client ID
'localhost/facebook', //instagram redirect URI
login_callback //optional - a callback function
);
return false;
}
The code is ok, I think it is a problem with your app settings: Login to Instagram Developer, go to "Manage Client" and the "security" tab an disable "Implicit OAuth".
Within IBM bluemix, my node clients keep having their websocket connections closed even though my server code does not initiate any closures.
My server side code is as follows:
app.ws('/problemUpdate', function(ws, req) {
// if we have the maximum number of clients, remove the oldest
if (clients.length>MAX_CLIENTS){
ws=clients.pop();
ws.close();
}
clients.unshift(ws);
ws.on('close', function(msg) {
// on close, remove clients
for (var i = 0; i < clients.length; i++) {
if(clients[i]==ws){
console.log("removing");
clients.splice(i,1);
}
}
});
ws.on('message', function(msg) {
if (readyToSend(ws)){
ws.send(ws);
}
});
// listen the event
eventEmitter.on('updateProblem', function(updatedProblem){
//Broadcast to all clients
console.log("Total Clients: "+clients.length);
for (var i = 0; i < clients.length; i++) {
var client = clients[i];
if (readyToSend(client)){
client.send(updatedProblem);
}
}
});
});
My client side websocket related code is as follows:
updateWebsocket(webSocketProblemUpdate);
function updateWebsocket(socket){
socket.onopen = function(){
console.log("Connection Opened");
}
socket.onclose = function(){
}
socket.onerror = function(evt){
console.log("The following error occurred: " + evt.data);
}
socket.onmessage = function(evt){
var jsonProblem = JSON.parse(evt.data);
var problemName = jsonProblem.envelope.problemName;
delete jsonProblem["envelope"];
var option = document.createElement('option');
option.text=problemName;
option.value=problemName;
var alreadyAdded=false;
[].forEach.call( document.getElementById('problems') , function(elm){
if(elm.value==option.value && elm.text==option.text){
//if(elm.text==option.text){
alreadyAdded=true;
// update the content of an already added scenario
accumulatedJsonProblems[problemName]=JSON.stringify(jsonProblem);
$('.problems').change();
}
})
if (!alreadyAdded){
accumulatedJsonProblems[problemName]=JSON.stringify(jsonProblem);
var select = $("#problems")[0];
select.add(option,$('#problems').children('option').length);
document.getElementById('problems').value=problemName;
$('.problems').change();
console.log("The following data was received:" + JSON.stringify(jsonProblem));
}
}
}
Any clues as to what is closing my web sockets?
Thanks,
Aaron
After some research, I found that IBM bluemix closes connections every 2 minutes. A security standard was implemented. To solve the problem, I reopen the websocket from the client every 5 minutes and catch an client side closures with a reopen.
//refresh the websocket every 5 minutes
setInterval(function() {
console.log("Interval expired, refreshing websocket");
// only closing because the on close method automatically opens a new websocket
webSocketProblemUpdate.close();
}, 300000);
socket.onclose = function(){
console.log("Connection Closed");
window.WebSocket = window.WebSocket || window.MozWebSocket;
webSocketProblemUpdate = new WebSocket("ws://"+window.document.location.host+"/problemUpdate");
updateWebsocket(webSocketProblemUpdate);
}
Cheers,
Aaron
I'm getting more into JS development on my own personal time and for this created a sort of SDK to log into openID connect implementation ( very basic, only implicit flow and code flow). This post is about the client side JS for the implicit flow.
I have successfully created a small SDK that allows me to launch the login request and monitor the pop up for the finished log in (or window close). In the end I now want to add a custom event so that other code can subscribe and be notified when this happens. I have been unable to get this to work. So my question is, how can I do it given the code posted, and of course if you have any suggestions on bettering my code, I'll gladly accept them.
Here is the code:
var mysystemID = {
authorizationURL:"MYRUL_TO_SERVER/oauth/v2/authorize",
client_id:"MYCLIENTID",
redirect_uri:window.location.protocol+"//"+window.location.host+"/callback",
response_type:"id_token token",
windowref : undefined,
intervalID : null,
access_token:"",
id_token:"null",
parser:document.createElement('a'),
checkLogin : function(){
if (this.windowref==undefined){
return false;
}
if (this.windowref.closed){
console.log("window closed")
clearInterval(this.intervalID)
this.intervalID=null
}
try{
this.parser.href = this.windowref.location.href;
if((this.parser.protocol + "//" +this.parser.host + this.parser.pathname) == this.redirect_uri)
{
console.log("login detected")
clearInterval(this.intervalID)
this.intervalID=null
this.windowref.close()
var obj = {}
var str = this.parser.hash.substring(1)
$.each(str.split("&"),function(index,value){
var pieces = value.split("=")
obj[pieces[0]] = pieces[1]
})
console.log(obj)
this.access_token = obj.token
this.id_token = JSON.parse(atob(obj.id_token.split(".")[1]))
// var event = new CustomEvent("my_login", {"detail":{"access_token":this.id_token}});
// this.dispatchEvent(event);
console.log(this.id_token)
}
}catch(e){
//do nothing
}
}
}
mysystemID.login_process = function(){
var scope = $('#scope').val() ||"openid"
var uri = this.authorizationURL+"?response_type="+encodeURIComponent(this.response_type)
+"&client_id=" + this.client_id +"&redirect_uri="+encodeURIComponent(this.redirect_uri)
+"&scope="+encodeURIComponent(scope)+"&nonce="+Math.floor( Math.random()*99999);
console.log(uri)
this.windowref = window.open(uri,
"login with mysystem
ID","width=400, height=600")
if (this.windowref!=null){
this.intervalID = setInterval(this.checkLogin.bind(mysystemID),500)
}
}.bind(mysystemID)
mysystemID.logout = function(){
this.access_token = ""
this.id_token = ""
}.bind(mysystemID)
mysystemID.isLoggedIn = function(){
return this.access_token!=""
}.bind(mysystemID)
A few notes, I rely on jQuery for some things,
and I instantiate it like so:
$(document).ready(function(){
$('a#login_push').on("click",mysystemID.login_process)
});
Within the code you can see my attempt at the event:
// var event = new CustomEvent("my_login", {"detail":{"access_token":this.id_token}});
// this.dispatchEvent(event);
the listener had been chained to the
$(document).ready(function(){
$('a#login_push').on("click",mysystemID.login_process).on("my_login",function(e,data){console.log('logged in fired')});
});