Real time chat with nodejs and mongodb - javascript

So, I have created a simple chat system which consists of nodeJS and mongodb. I currently 'host' it on apache, and it works perfectly on my computer, but if someone else connects to my site on the local network, then the chat doesnt work as intended. The send message and show message function breaks.
Ps: The code is from phpacademy, so cudos to them.
Here's the code I used:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>ChattSystem</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="chat">
<input type="text" class="chat-name" placeholder="Enter your name">
<div class="chat-messages"></div>
<textarea placeholder="Type your message"></textarea>
<div class="chat-status">Status: <span>Idle</span></div>
</div>
<script src="http://127.0.0.1:8080/socket.io/socket.io.js"></script>
<script>
(function() {
var getNode = function(s) {
return document.querySelector(s);
},
// Get required nodes
status = getNode('.chat-status span'),
messages = getNode('.chat-messages'),
textarea = getNode('.chat textarea'),
chatName = getNode('.chat-name');
statusDefault = status.textContent,
setStatus = function(s) {
status.textContent = s;
if(s !== statusDefault) {
var delay = setTimeout(function() {
setStatus(statusDefault);
clearInterval(delay);
}, 3000);
}
};
try {
var socket = io.connect('http://127.0.0.1:8080');
} catch(e) {
// Set status to warn user
}
if(socket !== undefined) {
// Listen for output
socket.on('output', function(data) {
if(data.length) {
// Loop through results
for(var x = 0; x < data.length; x = x + 1) {
var message = document.createElement('div');
message.setAttribute('class', 'chat-message');
message.textContent = data[x].name + ': ' + data[x].message;
// Append
messages.appendChild(message);
messages.insertBefore(message, messages.firstChild);
}
}
});
// Listen for a status
socket.on('status', function(data) {
setStatus((typeof data === 'object') ? data.message : data);
if(data.clear === true) {
textarea.value = '';
}
});
// Listen for keydown
textarea.addEventListener('keydown', function(event) {
var self = this,
name = chatName.value;
if(event.which);if(event.which == 13 && event.shiftKey === false) {
socket.emit('input', {
name: name,
message: self.value
});
event.preventDefault();
}
});
}
})();
</script>
</body>
</html>
Server.js
var mongo = require('mongodb').MongoClient,
client = require('socket.io').listen(8080).sockets;
mongo.connect('mongodb://127.0.0.1/chat', function(err, db) {
if(err) throw err;
client.on('connection', function(socket) {
var col = db.collection('messages'),
sendStatus = function(s) {
socket.emit('status', s);
};
// Emit all messages
col.find().limit(100).sort({_id: 1}).toArray(function(err, res) {
if(err) throw err;
socket.emit('output', res);
});
// Wait for input
socket.on('input', function(data) {
var name = data.name,
message = data.message,
whitespacePattern = /^\s*$/;
if(whitespacePattern.test(name) || whitespacePattern.test(message)) {
sendStatus('Name and message is required.');
} else {
col.insert({name: name, message: message}, function() {
// Emit latest message to ALL qclients
client.emit('output', [data]);
sendStatus({
message: "Message sent",
clear: true
});
});
}
});
});
});

In your JS from client side, change the IP to your server IP..
You script has currently the same local IP, thats mean what is always in localhost...
Find your IP and put it:
HTML (JS client side)
try {
var socket = io.connect('http://192.168.x.x:8080');
} catch(e) {
// Set status to warn user
}

Related

How to create a secured node websocket client (unable to verify the first certificate problem)

What is working
I created a node https/websocket server using WebSocket-Node. Here a snippet on how I add key/cert :
import WebSockerServer from "websocket";
import fs from "fs";
const httpsSignalServer = https.createServer(
{
key: fs.readFileSync("./server.private.key"),
cert: fs.readFileSync("./server.crt"),
},
(req, res) => {
console.log("signal server : we have received a request");
}
);
const signalWebsocket = new WebSockerServer.server({
httpServer: httpsSignalServer,
});
signalWebsocket.on("request", (request) => onRequest(request));
httpsSignalServer.listen(8080, () => console.log("My signal server is listening"));
I have a React html web page that sends data to server above with WebSocket web api via wss :
new WebSocket("wss://192.168.230.138:8081");
My react app runs in an https server. So far everything works.
What is not working
The problem is my little node websocket client. I am still using WebSocket-Node. The client documentation shows a tlsOptions to be given to the constructor.
Client code snippet:
var WebSocketClient = require("websocket").client;
var fs = require("fs");
const tlsOptions = {
key: "./server.private.key",
cert: "./server.crt",
};
var client = new WebSocketClient({
key: fs.readFileSync(tlsOptions.key),
cert: fs.readFileSync(tlsOptions.cert),
});
.
.
.
client.connect("wss://localhost:8080/", "");
The client returns the message :
Error: unable to verify the first certificate
Is there anyone out there who knows how to do the client setup with the tlsOptions?
Thank you
I wrote a perfectly functional simple chat script which is using secured connection. I added a couple of simple chat commands to enable or disable the chat from entering commands in chat.You could use this if you like or parts of it or even just see how I did it. Hope you find some use for it.
var maxLength = 100; // chars per chat
const port = 1441;
var JoinLeaveMsg = 1
var fs = require('fs');
const HTTPS = require('https');
const WebSocket = require('ws');
const server = new HTTPS.createServer({
cert: fs.readFileSync('C:/Certbot/live/MyDomain.com/cert.pem'),
key: fs.readFileSync('C:/Certbot/live/MyDomain.com/privkey.pem')
});
const wss = new WebSocket.Server({ server })
wss.on('connection', function connection(ws) {
const now = new Date();
const tDate = now.toDateString();
const date = new Date(now);
const currentDate = date.toLocaleTimeString();
console.log(tDate + ' - ' + currentDate + " - New User Connected");
ws.send(JSON.stringify(
{
name: "welcome",
message: "wanna chat?"
}
));
ws.on('message', function(message){
message = JSON.parse(message);
const createDOMPurify = require('dompurify');
const { JSDOM } = require('jsdom');
const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window);
// START CONNECT
if(message.type == "name"){
// START CHECKS FOR DOUBLE LOGIN
var dirty = message.data;
const ConnectingUser = DOMPurify.sanitize(dirty);
if (ConnectingUser != ''){
wss.clients.forEach(function e(client) {
var ConnectedUser = client.personName;
if(ConnectedUser == ConnectingUser) {
client.send(JSON.stringify(
{
name: "***Server***",
message: "***We do not allow double logins!"
}
));
client.send(JSON.stringify(
{
name: "***Server***",
message: "🔴 Disconnected..."
}
));
client.close();
}
});
}
// END CHECKS FOR DOUBLE LOGIN
ws.personName = ConnectingUser;
memberJoinedChatMsg(ws, ConnectingUser);
return;
}
// START INPUT DATA
if(message.type == "message"){
var ConnectedUser = ws.personName;
if (ConnectedUser != ''){
var dirty = message.message;
const Message = DOMPurify.sanitize(dirty);
var string = Message;
var temp = string.split(" ");
var CommandOne = temp[0];
var CommandTwo = temp[1];
var CommandThree = temp.slice(2).join(" ");
// lets process the messages and send to users
if((Message) != "") {
// START COMMANDS
// Do join/leave msg disable--------------------------------------------------------------------
if((CommandOne) == "/jpenable" || (CommandOne) == "!jpenable"){
JoinLeaveMsg = "1";
Msg ='***Join/Part message has been Enabled!';
sendMsgToAll(Msg)
MessageString ="";
}
// Do join/leave msg enable--------------------------------------------------------------------
if((CommandOne) == "/jpdisable" || (CommandOne) == "!jpdisable"){
JoinLeaveMsg = "0";
Msg ='***Join/Part message has been Disabled!';
sendMsgToAll(Msg)
MessageString ="";
}
// END COMMANDS
if ((Message).length < maxLength) {
wss.clients.forEach(function e(client) {
client.send(JSON.stringify(
{
name: ConnectedUser,
message: Message
}
));
console.log("Sent: "+ConnectedUser+" "+Message);
});
}else{
wss.clients.forEach(function e(client) {
if(client === ws)
client.send(JSON.stringify(
{
name: '***Server***',
message: "*** Your message exceeds "+maxLength+" characters!"
}
));
});
};
}else{
// dont process if empty line entered
};
}
}
// END INPUT DATA
})
ws.on('close', function(message) {
if(ws.personName){
memberLeftChatMsg(ws);
}
ws.close();
//console.log("Client Disconnected");
});
// END CONNECT
})
server.listen(port, function() {
console.log(`Server is listening on ${port}!`)
})
// FUNCTIONS
// complete Send Message To All
function sendMsgToAll(Msg){
wss.clients.forEach(function e(client) {
client.send(JSON.stringify(
{
name: "Server",
message: Msg
}
));
});
};
// complete
function memberJoinedChatMsg(ws, ConnectingUser) {
if(JoinLeaveMsg != "0"){
wss.clients.forEach(function e(client) {
client.send(JSON.stringify(
{
name: "***Server***",
message: "🟢 <<b>"+ConnectingUser+"</b>> has entered chat!"
}
));
});
}
};
// complete
function memberLeftChatMsg(ws) {
if(JoinLeaveMsg != "0"){
wss.clients.forEach(function e(client) {
client.send(JSON.stringify(
{
name: "***Server***",
message: "🔴 <<b>"+ws.personName+"</b>> has left chat!"
}
));
});
}
};
I also have Dompurify installed using npm to help prevent entities being posted. Remember to open the port in your firewall or change the port number in the script. If you need the client side script including the html, .css let me know, I can upload those too :)
CLIENT SCRIPT:
(function() {
const sendBtn = document.querySelector('#send');
const messages = document.querySelector('#messages');
const messageBox = document.querySelector('#messageBox');
var ws;
var text = "Server: Server Offline!";
var sName = name;
function updateChat(element) {
var name = element[0];
var message = element[1];
const now = new Date();
const tDate = now.toDateString();
const date = new Date(now);
const currentDate = date.toLocaleTimeString();
if(sName == name){
$('.responsive-html5-chat' + ' div.messages').append( '<div class="message"><div class="myMessage"><p>' + message + "</p><date>" + name + " " + currentDate + "</date></div></div>" );
}else{
$('.responsive-html5-chat' + ' div.messages').append( '<div class="message"><div class="fromThem"><p>' + message + "</p><date>" + currentDate + " " + name + "</date></div></div>" );
}
setTimeout(function () { $('.responsive-html5-chat' + ' > span').addClass("spinner"); }, 100);
setTimeout(function () { $('.responsive-html5-chat' + ' > span').removeClass("spinner"); }, 2000);
$(".messages").scrollTop(function() { return this.scrollHeight; });
}
function responsiveChat(element) {
$(element).html('<form class="chat"><span></span><div class="messages"></div><input type="text" id="msg" placeholder="Your message" autocomplete="off"><input id="send" type="submit" value="Send"></form>');
}
responsiveChat('.responsive-html5-chat');
function init() {
if (ws) {
ws.onerror = ws.onopen = ws.onclose = null;
ws.close();
}
ws = new WebSocket('wss://MyDomain.com:1441');
ws.onopen = function() {
if(name) {
ws.send(JSON.stringify({
type: "name",
data: name
}));
}else{
const dat = ['', 'Please Login to chat!'];
updateChat(dat);
ws = null;
return ;
}
}
// START RECIEVED FROM SERVER
ws.onmessage = function(event){
var json = JSON.parse(event.data);
var Name = json.name;
var Message = json.message;
if(name) {
if (Name === "***Server***"){
const dat = ['***Server***', Message];
updateChat(dat);
}else if(Name === "welcome" && name != '') {
Message = 'Hi ' + name + ' ' + Message;
const dat = ['', Message];
updateChat(dat);
}else{
const dat = [Name, Message];
updateChat(dat);
}
}
}
// END RECIEVED FROM SERVER
ws.onclose = function(event) {
if (event.wasClean) {
ws = null;
} else {
const dat = ['', 'Server Offline!'];
updateChat(dat);
ws = null;
}
};
}
// START SEND TO SERVER
send.onclick = function (event){
event.preventDefault();
if(name) {
if (!ws) {
const dat = ['', 'You are not connected... :('];
updateChat(dat);
ws = null;
return ;
}
var messages = document.getElementById("msg").value;
document.getElementById("msg").value = ''; // empty msg box
ws.send(JSON.stringify({
type: "message",
data: name,
message: messages
}));
}else{
const dat = ['', 'Please Login to chat!'];
updateChat(dat);
ws = null;
return ;
}
};
init();
})();

Problems converting JavaScript to GopherJs

I am trying to convert this whole section of code from Javascript to GopherJs.
So far i have not been able to do event listeners as i am still a newbie to Javascript.
This is the JavaScript
window.addEventListener("load", function(evt) {
var output = document.getElementById("output");
var input = document.getElementById("input");
var ws;
var print = function(message) {
var d = document.createElement("div");
d.innerHTML = message;
output.appendChild(d);
};
document.getElementById("open").onclick = function(evt) {
if (ws) {
return false;
}
ws = new WebSocket("{{.}}");
ws.onopen = function(evt) {
print("OPEN");
}
ws.onclose = function(evt) {
print("CLOSE");
ws = null;
}
ws.onmessage = function(evt) {
print("RESPONSE: " + evt.data);
}
ws.onerror = function(evt) {
print("ERROR: " + evt.data);
}
return false;
};
document.getElementById("send").onclick = function(evt) {
if (!ws) {
return false;
}
print("SEND: " + input.value);
ws.send(input.value);
return false;
};
document.getElementById("close").onclick = function(evt) {
if (!ws) {
return false;
}
ws.close();
return false;
};
});
I have gone through a few iterations of attempts but it is still not working.
Below is a snippet of my last attempt.
var ws *websocketjs.WebSocket
var err error
//js.Global.Get("document").Call("write", "Hello world!")
js.Global.Call("addEventListener", "load", func(ev *js.Object) {
//js.Global.Get("document").Get("open") = func(ev *js.Object){
onOpen := func(ev *js.Object) {
if ws == nil {
ws, err = websocketjs.New("ws://localhost:8000/ws") // Does not block.
if err != nil {
println(err)
}
}
fmt.Println("we are past the ws part")
js.Global.Get("document").Call("write", "It is opened!")
/////////////////////////////////////////////////
err = ws.Send("Hello Websockets!") // Send a text frame.
if err != nil {
fmt.Println(err)
}
println("it is open now")
}
ws.AddEventListener("open", false, onOpen)
//}
})
//ws.AddEventListener("open", false, onOpen)
//ws.AddEventListener("message", false, onMessage)
//ws.AddEventListener("close", false, onClose)
//ws.AddEventListener("error", false, onError)
err = ws.Close()
I would atleast like to see the first 2 parts done correctly. I can finish the rest with a good example.
Thanks
To obtain the DOM i used "honnef.co/go/js/dom" library.
Everything else was step by step as in Javascript.
Example:
package main
import "honnef.co/go/js/dom"
func main() {
d := dom.GetWindow().Document()
h := d.GetElementByID("foo")
h.SetInnerHTML("Hello World")
}

Return text when checkbox selected

In my site, I have a form that users can click on a checkbox to select "available". I want to have "Yes" or "No" returned in the displayArticle function based on whether the box is checked or not. Right now it returns True or False, which is not optimal. How can I code this?
Here is my entire JS code:
App = {
web3Provider: null,
contracts: {},
account: 0x0,
loading: false,
init: function() {
return App.initWeb3();
},
initWeb3: function() {
// initialize web3
if(typeof web3 !== 'undefined') {
//reuse the provider of the Web3 object injected by Metamask
App.web3Provider = web3.currentProvider;
} else {
//create a new provider and plug it directly into our local node
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
}
web3 = new Web3(App.web3Provider);
App.displayAccountInfo();
return App.initContract();
},
displayAccountInfo: function() {
web3.eth.getCoinbase(function(err, account) {
if(err === null) {
App.account = account;
$('#account').text(account);
web3.eth.getBalance(account, function(err, balance) {
if(err === null) {
$('#accountBalance').text(web3.fromWei(balance, "ether") + " ETH");
}
})
}
});
},
initContract: function() {
$.getJSON('RentalContract.json', function(chainListArtifact) {
//added May24 to json file name
// get the contract artifact file and use it to instantiate a truffle contract abstraction
App.contracts.RentalContract = TruffleContract(chainListArtifact);
// set the provider for our contracts
App.contracts.RentalContract.setProvider(App.web3Provider);
// listen to events
App.listenToEvents();
// retrieve the article from the contract
return App.reloadArticles();
});
},
reloadArticles: function() {
//avoid reentry bugs
if(App.loading){
return;
}
App.loading = true;
// refresh account information because the balance might have changed
App.displayAccountInfo();
var chainListInstance;
App.contracts.RentalContract.deployed().then(function(instance) {
chainListInstance = instance;
return chainListInstance.getArticlesForSale();
}).then(function(articlesIds) {
// retrieve the article placeholder and clear it
$('#articlesRow').empty();
for(var i = 0; i < articlesIds.length; i++){
var articleId = articlesIds[i];
chainListInstance.articles(articleId.toNumber()).then(function(article){
App.displayArticle(article[0], article[1], article[3], article[4], article[5], article[6], article[7]);
});
}
App.loading = false;
}).catch(function(err) {
console.error(err.message);
App.loading = false;
});
},
//displayArticle: function(id, seller, beds, baths, propaddress, rental_price, property_type, description, available, contact_email) {
displayArticle: function(id, seller, propaddress, rental_price, description, available, contact) {
var articlesRow = $('#articlesRow');
//var etherPrice = web3.fromWei(price, "ether");
var articleTemplate = $("#articleTemplate");
//articleTemplate.find('.panel-title').text(propaddress);
//articleTemplate.find('.beds').text(beds);
//articleTemplate.find('.baths').text(baths);
articleTemplate.find('.propaddress').text(propaddress);
articleTemplate.find('.rental_price').text('$' + rental_price);
//articleTemplate.find('.property_type').text(property_type);
articleTemplate.find('.description').text(description);
articleTemplate.find('.available').text(available);
articleTemplate.find('.contact').text(contact);
// articleTemplate.find('.article_price').text(etherPrice + " ETH");
articleTemplate.find('.btn-buy').attr('data-id', id);
// articleTemplate.find('.btn-buy').attr('data-value', etherPrice);
//seller
if(seller == App.account){
articleTemplate.find('.article-seller').text("You");
articleTemplate.find('.btn-buy').hide();
}else{
articleTemplate.find('.article-seller').text(seller);
articleTemplate.find('.btn-buy').show();
}
//add this new article
articlesRow.append(articleTemplate.html());
},
sellArticle: function() {
// retrieve the detail of the article
// var _article_name = $('#article_name').val();
var _description = $('#description').val();
//var _beds = $('#beds').val();
//var _baths = $('#baths').val();
var _propaddress = $('#propaddress').val();
var _rental_price = $('#rental_price').val();
//var _property_type = $('#property_type').val();
var _available = $('#available').val();
var _contact = $('#contact').val();
// var _article_price = $('#article_price').val();
// var _price = web3.toWei(parseFloat($('#article_price').val() || 0), "ether");
// if((_description.trim() == '') || (rental_price == 0)) {
// nothing to sell
// return false;
// }
App.contracts.RentalContract.deployed().then(function(instance) {
//return instance.sellArticle(_description, _beds, _baths, _propaddress, _rental_price, _property_type, _available, _contact_email, {
return instance.sellArticle(_propaddress, _rental_price, _description, _available, _contact,{
from: App.account,
gas: 500000
});
}).then(function(result) {
}).catch(function(err) {
console.error(err);
});
},
// listen to events triggered by the contract
listenToEvents: function() {
App.contracts.RentalContract.deployed().then(function(instance) {
instance.LogSellArticle({}, {}).watch(function(error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._propaddress + ' is now for sale</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
instance.LogBuyArticle({}, {}).watch(function(error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._buyer + ' bought ' + event.args._propaddress + '</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
});
},
buyArticle: function() {
event.preventDefault();
// retrieve the article price and data
var _articleId = $(event.target).data('id');
var _price = parseFloat($(event.target).data('value'));
App.contracts.RentalContract.deployed().then(function(instance){
return instance.buyArticle(_articleId, {
from: App.account,
value: web3.toWei(_price, "ether"),
gas: 500000
});
}).catch(function(error) {
console.error(error);
});
}
};
$(function() {
$(window).load(function() {
App.init();
});
});
If I understand what you're trying to do, perhaps this will work for you.
var isChecked = '';
if (articleTemplate.find('.available').checked === true)
{ isChecked = 'yes'} else
{ isChecked = 'no'}
.
.
.
return isChecked;
Do this:
articleTemplate.find( '.available' ).text( available ? 'Yes' : 'No' );
Example:
function returnValue() {
$( '#val' ).text( $( '#chk' ).is( ':checked' ) ? 'Yes' : 'No' )
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="chk" onclick="returnValue()" />
<label for="chk">Available</label>
<h2 id="val"></h2>

Chromecast web app: using js to send multiple urls to a chromecast

I'm trying to write a javascript file which will be able to cast images to a chromecast. There will be multiple buttons on an html page. Depending on the button the user clicks, a url will be sent to the chromecast. I have the names of the files stored in a JSON file called videoNames.json, which I loop over to get the names. At the moment all the files to be casted are images. When I run the code the screen remains blank and no buttons show up. Here is my code:
<!doctype html>
<html>
<head>
<title>Casting</title>
<script type="text/javascript" src="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<SCRIPT language= "Javascript">
var session = null;
$( document ).ready(function(){
var loadCastInterval = setInterval(function(){
if (chrome.cast.isAvailable) {
console.log('Cast has loaded.');
clearInterval(loadCastInterval);
initializeCastApi();
} else {
console.log('Unavailable');
}
}, 1000);
});
function initializeCastApi() {
var applicationID = chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID;
var sessionRequest = new chrome.cast.SessionRequest(applicationID);
var apiConfig = new chrome.cast.ApiConfig(sessionRequest,
sessionListener,
receiverListener);
chrome.cast.initialize(apiConfig, onInitSuccess, onInitError);
};
function sessionListener(e) {
session = e;
console.log('New session');
if (session.media.length != 0) {
console.log('Found ' + session.media.length + ' sessions.');
}
}
function receiverListener(e) {
if( e === 'available' ) {
console.log("Chromecast was found on the network.");
}
else {
console.log("There are no Chromecasts available.");
}
}
function onInitSuccess() {
console.log("Initialization succeeded");
}
function onInitError() {
console.log("Initialization failed");
}
function getArray(){
return $.getJSON('./videoNames.json');
}
getArray().done( function(json) {
//console.log(json); // show the json data in console
//var len = json.length;
var fixture;
//loop through json and match today's date with match-date
for (var i in json) {
fixture = json[i];
document.write(fixture.name);
var butt = document.createElement("button");
var text = document.createTextNode("Click to cast");
butt.appendChild(text);
butt.id = i;
var nameArray[i] = fixture.name;
document.body.appendChild(butt);
}
});
$(#i).click(function(nameArray[i]){
launchApp(nameArray[i]);
});
function getFileNameExtension(filename){
return filename.split('.').pop();
}
function launchApp(nameArray[i]) {
console.log("Launching the Chromecast App...");
chrome.cast.requestSession(onRequestSessionSuccess(nameArray[i]), onLaunchError);
}
function onRequestSessionSuccess(e) {
console.log("Successfully created session: " + e.sessionId);
session = e;
}
function onLaunchError() {
console.log("Error connecting to the Chromecast.");
}
function onRequestSessionSuccess(e, nameArray[i]) {
console.log("Successfully created session: " + e.sessionId);
session = e;
loadMedia(nameArray[i]);
}
function loadMedia(nameArray[i]) {
if (!session) {
console.log("No session.");
return;
}
var mediaInfo = new
chrome.cast.media.MediaInfo('http://52.60.153.189/video_files/' + nameArray[i]);
mediaInfo.contentType = 'image/' + getFileNameExtension(nameArray[i]);
var request = new chrome.cast.media.LoadRequest(mediaInfo);
request.autoplay = true;
session.loadMedia(request, onLoadSuccess, onLoadError);
}
function onLoadSuccess() {
console.log('Successfully loaded image.');
}
function onLoadError() {
console.log('Failed to load image.');
}
$('#stop').click(function(){
stopApp();
});
function stopApp() {
session.stop(onStopAppSuccess, onStopAppError);
}
function onStopAppSuccess() {
console.log('Successfully stopped app.');
}
function onStopAppError() {
console.log('Error stopping app.');
}
</SCRIPT>
</body>
</html>
Any help is appreciated. Thanks!

Add Mute Button in my PeerJS Application

I'm trying to keep Mute Button that will act like Push to talk
This App.js file (main file)
navigator.getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
//get browser cmopt
var me = {};
var myStream;
var peers = {};
init();
function init() {
if (!navigator.getUserMedia) return unsupported();
getLocalAudioStream(function(err, stream) {
if (err || !stream) return;
connectToPeerJS(function(err) {
if (err) return;
registerIdWithServer(me.id);
if (call.peers.length) callPeers();
else displayShareMessage();
});
});
} // initialization
function connectToPeerJS(cb) {
display('Connecting to PeerJS...');
//me = new Peer({key: API_KEY});
me = new Peer({ host:'rapidserver.herokuapp.com', secure:true, port:443, key: 'peerjs', debug: 3})
me.on('call', handleIncomingCall);
me.on('open', function() {
display('Connected.');
display('ID: ' + me.id);
cb && cb(null, me);
});// connect to peerJs Server and get ID From the Server
me.on('error', function(err) {
display(err);
cb && cb(err);
});
}
function registerIdWithServer() {
display('Registering ID with server...');
$.post('/' + call.id + '/addpeer/' + me.id);
} // Add our ID to the list of PeerJS IDs for this call
function unregisterIdWithServer() {
$.post('/' + call.id + '/removepeer/' + me.id);
}
function callPeers() {
call.peers.forEach(callPeer);
}
function callPeer(peerId) {
display('Calling ' + peerId + '...');
var peer = getPeer(peerId);
peer.outgoing = me.call(peerId, myStream);
peer.outgoing.on('error', function(err) {
display(err);
});
peer.outgoing.on('stream', function(stream) {
display('Connected to ' + peerId + '.');
addIncomingStream(peer, stream);
});
}
function handleIncomingCall(incoming) {
display('Answering incoming call from ' + incoming.peer);
var peer = getPeer(incoming.peer);
peer.incoming = incoming;
incoming.answer(myStream);
peer.incoming.on('stream', function(stream) {
addIncomingStream(peer, stream);
});
}// When someone initiates a call via PeerJS
// Add the new audio stream. Either from an incoming call, or from the response to one of our outgoing calls
function addIncomingStream(peer, stream) {
display('Adding incoming stream from .... ' + peer.id);
peer.incomingStream = stream;
playStream(stream);
}
function playStream(stream) {
var audio = $('<audio autoplay />').appendTo('body');
audio[0].src = (URL || webkitURL || mozURL).createObjectURL(stream);
}
function getLocalAudioStream(cb) {
display('Trying to access your microphone. Please click "Allow".');
navigator.getUserMedia (
{video: false, audio: true},
function success(audioStream) {
display('Microphone is open.');
myStream = audioStream;
if (cb) cb(null, myStream);
},
function error(err) {
display('Couldn\'t connect to microphone. Reload the page to try again.');
if (cb) cb(err);
}
);
}
function getPeer(peerId) {
return peers[peerId] || (peers[peerId] = {id: peerId});
}
function displayShareMessage() {
display('Give someone this URL to chat.');
display('<input type="text" value="' + location.href + '" readonly>');
$('#display input').click(function() {
this.select();
});
}
function unsupported() {
display("Your browser doesn't support getUserMedia.");
}
function display(message) {
$('<div />').html(message).appendTo('#display');
}
And this is my index.ejs (html index file)
<body>
<div class="wrapper">
<div id="display"></div>
</div>
<footer>
<div class="wrapper">
~~~~~Start another call~~~~~~~
</div>
</footer>
<script type="text/javascript">
window.API_KEY = "<%= apiKey %>";
window.call = <%- JSON.stringify(call, null, 2) %>;
</script>
</script>
I'm thinking to add something like mute button or toggle button but i am not sure how do i make it happen with call and with each peer can mute and unmute the call.
Please help me. It would be great help. Thanks in Advance.
I Tried Using this.
<input type="button" name="button" id="mute"> Mute </input>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.js">
$(document).ready(function(){ function Mute() { var button = document.createElement("button"); button.appendChild(document.createTextNode("Toggle Hold"));
button.onclick = function(){ mediaStream.use getAudioTracks()()[0].enabled =!(mediaStream.use getAudioTracks()()[0].enabled);
} }
$("#mute").click(Mute);
});

Categories