HTML5 audio not playing with Handlebars templated src attribute - node.js

I'm trying to play mp3's that I am streaming out of a Mongo GridFSBucket. The root of my issue is that I set the src attribute of my audio tag with my handlebars template to the URL that my stream should be headed to but the player is unresponsive.
If I don't feed this URL to my the audio tag and I remove the handlebars code, my browser (Chrome) creates a video tag that blacks out the window and superimposes HTML media player controls in the center and plays the track without issue.
How should I specify to the player that whatever it is streaming to the video tag it is creating should instead go to the audio player?
list.handlebars
<script src="../index.js" ></script>
<title>CRATE</title>
</head>
<body>
<div>tracks displayed below</div>
<div>{{userNameId}}'s Tracks</div>
{{#each tracks}}
<div class="row">
<div class="col-md-12">
<form id="trackSelection" method="GET" action="/play">
<input type="hidden" name="bytes" value="{{length}}">
<button class="playButton" type="submit" name="id" value=" .
{{_id}}">{{filename}}</button>
</form>
</div>
</div>
{{/each}}
<audio id="playback" src="{{sourceUrl}}" type="audio/mpeg" controls>
</audio>
</body>
</html>
index.js
app.get('/play', urlEditor, function(req, res, next) {
var db = req.db // => Db object
var size = sanitizer.escape(req.query.bytes);
var sanitizedTrackId = sanitizer.escape(req.query.id);
var username = 'ross';
var protocol = req.protocol;
var originalUrl = req.originalUrl;
// var sourceUrl = protocol + '://' + hosted + originalUrl;
var sourceUrl = protocol + '://' + req.get('host') + originalUrl;
console.log("sourceUrl", sourceUrl)
console.log("type", typeof sourceUrl)
if (username) {
const collection = db.collection(username + ".files");
var userNameId = collection.s.name;
console.log(userNameId);
const tracks = new Promise(function(resolve, reject) {
resolve(collection.find({}).toArray(function(err, tracks) {
assert.equal(err, null);
// return tracks;
finishPage(tracks);
}))
})
} else {
console.log('waiting')
}
function finishPage(tracks) {
try {
console.log("SID", sanitizedTrackId);
var trackID = new ObjectID(sanitizedTrackId);
} catch (err) {
return res.status(400).json({ message: "Invalid trackID in URL parameter. Must be a single String of 12 bytes or a string of 24 hex characters" });
}
let playEngine = new mongo.GridFSBucket(db, {
bucketName: username
});
var downloadStream = playEngine.openDownloadStream(trackID);
downloadStream.pipe(res);
console.log('success');
console.log("___________________");
var head = {
'Accept-Ranges': 'bytes',
'Content-Length': size,
'Content-Type': 'audio/mp3',
}
// res.render("list");
// res.set({ 'content-type': 'audio/mp3', 'accept-ranges': 'bytes', 'content-length': size }).render("list", { tracks: tracks, userNameId: userNameId, sourceUrl: sourceUrl });
res.status(206, head).render("list", { tracks: tracks, userNameId: userNameId, sourceUrl: sourceUrl });
}

Related

Is there a way to increase recording quality with the Web Audio API in Safari?

I'm using WebRTC along with WebAudioRecorder.js and the Web Audio API to record microphone input from the user for audio recognition with the audD API (similar to Shazam). This is working fine in Chrome and Firefox and it seems the quality of the recording is fairly solid. However, audD is not able to recognize the blob/file being sent from my recording in Safari (11.1.2) because of what I'm guessing is low audio quality (the playback is almost inaudible). The only audio format that both Safari and audD are compatible with is mp3, so that's how I've been encoding the file.
Javascript:
// to be set to a WebAudioRecorder.js recorder instance
let recorder;
// to be set to the stream resulting from getUserMedia()
let gumStream;
function beginRecording() {
if (navigator.mediaDevices.getUserMedia) {
console.log('starting the recording');
navigator.mediaDevices.getUserMedia({ 'audio': true })
.then(function(stream) {
let AudioContext = window.AudioContext // Default
|| window.webkitAudioContext // Safari and old versions of Chrome
|| false;
if (AudioContext) {
let audioCtx = new AudioContext;
gumStream = stream;
let source = audioCtx.createMediaStreamSource(stream);
recorder = new WebAudioRecorder(source, {
workerDir: 'web-audio-recorder-js/lib/',
encoding: 'mp3'
});
} else {
alert('The Web Audio API is not supported.');
}
recorder.setOptions({
timeLimit: 120,
encodeAfterRecord: true,
ogg: {quality: 0.9},
mp3: {bitRate: 320},
});
recorder.startRecording();
recorder.onComplete = function(recorder, blob) {
createAudioPlayback(blob);
POSTreq(blob);
}
recorder.onError = function(recorder, err) {
console.error(err);
}
})
.catch(function(err) {
console.error(err);
})
}
}
function stopRecording() {
console.log('stopping the recording');
let recordingTime = recorder.recordingTime();
console.log(recordingTime);
let audioTrack = gumStream.getAudioTracks()[0];
console.log(audioTrack);
audioTrack.stop();
recorder.finishRecording();
$('#msg_box').text(`Recorded for ${Math.round(recordingTime)} seconds`);
console.log('recording stopped');
}
function createAudioPlayback(blobData) {
let url = URL.createObjectURL(blobData);
$('body').append(`<audio controls src="${url}"></audio>`);
}
function POSTreq (blobData) {
let xhr = new XMLHttpRequest();
let fd = new FormData();
fd.append('api_token', '');
fd.append('file', blobData);
fd.append('method', 'recognize');
fd.append('return_itunes_audios', true);
fd.append('itunes_country', 'us');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
parseRetrievedData(xhr.response);
}
}
xhr.open('POST', 'https://api.audd.io/');
xhr.responseType = 'json';
xhr.send(fd);
}
function parseRetrievedData(parseData) {
console.log('the data from the audD api is: ', parseData);
}
$(function() {
$('#start-button').click(function(e) {
beginRecording();
$('#stop-button').prop('hidden', false);
});
$('#stop-button').click(function(e) {
stopRecording();
});
});
HTML:
<div class="recorder_wrapper">
<div class="recorder">
<button id="start-button">Start</button>
<button id="stop-button">Stop</button>
<p id="msg_box"></p>
<section class="auth-links-region" role="region">
Signup
Login
</section>
<section class="authentication-region" role="region" hidden>
<p class="authentication-text"></p>
My Searches
Logout
</section>
</div>
</div>

Cannot connect mongodb and socket.io using node

I'm following this tutorial to make a basic socket.io chatroom connected to mongodb. Here is the code:
const mongo = require('mongodb').MongoClient;
const client = require('socket.io').listen(3000).sockets;
// Connect to mongo
mongo.connect('mongodb://127.0.0.1/mongochat', function(err, db){
if(err){
throw err;
}
console.log('MongoDB connected...');
// Connect to Socket.io
client.on('connection', function(socket){
let chat = db.collection('chats');
// Create function to send status
sendStatus = function(s){
socket.emit('status', s);
}
// Get chats from mongo collection
chat.find().limit(100).sort({_id:1}).toArray(function(err, res){
if(err){
throw err;
}
// Emit the messages
socket.emit('output', res);
});
// Handle input events
socket.on('input', function(data){
let name = data.name;
let message = data.message;
// Check for name and message
if(name == '' || message == ''){
// Send error status
sendStatus('Please enter a name and message');
} else {
// Insert message
chat.insert({name: name, message: message}, function(){
client.emit('output', [data]);
// Send status object
sendStatus({
message: 'Message sent',
clear: true
});
});
}
});
// Handle clear
socket.on('clear', function(data){
// Remove all chats from collection
chat.remove({}, function(){
// Emit cleared
socket.emit('cleared');
});
});
});
});
The code runs and I get
(node:31737) DeprecationWarning: current URL string parser is
deprecated, and will be removed in a future version. To use the new
parser, pass option { useNewUrlParser: true } to MongoClient.connect.
MongoDB connected...
But when I try to get the html page in browser I get This 127.0.0.1 page can’t be found instead.
Here is the index.html page on the same folder as server.js that is supposed to be rendered but it does not:
<!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">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<title>MongoChat</title>
<style>
#messages{height:300px;}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3 col-sm-12">
<h1 class="text-center">
MongoChat
<button id="clear" class="btn btn-danger">Clear</button>
</h1>
<div id="status"></div>
<div id="chat">
<input type="text" id="username" class="form-control" placeholder="Enter name...">
<br>
<div class="card">
<div id="messages" class="card-block">
</div>
</div>
<br>
<textarea id="textarea" class="form-control" placeholder="Enter message..."></textarea>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script>
(function(){
var element = function(id){
return document.getElementById(id);
}
// Get Elements
var status = element('status');
var messages = element('messages');
var textarea = element('textarea');
var username = element('username');
var clearBtn = element('clear');
// Set default status
var statusDefault = status.textContent;
var setStatus = function(s){
// Set status
status.textContent = s;
if(s !== statusDefault){
var delay = setTimeout(function(){
setStatus(statusDefault);
}, 4000);
}
}
// Connect to socket.io
var socket = io.connect('http://127.0.0.1:4000');
// Check for connection
if(socket !== undefined){
console.log('Connected to socket...');
// Handle Output
socket.on('output', function(data){
//console.log(data);
if(data.length){
for(var x = 0;x < data.length;x++){
// Build out message div
var message = document.createElement('div');
message.setAttribute('class', 'chat-message');
message.textContent = data[x].name+": "+data[x].message;
messages.appendChild(message);
messages.insertBefore(message, messages.firstChild);
}
}
});
// Get Status From Server
socket.on('status', function(data){
// get message status
setStatus((typeof data === 'object')? data.message : data);
// If status is clear, clear text
if(data.clear){
textarea.value = '';
}
});
// Handle Input
textarea.addEventListener('keydown', function(event){
if(event.which === 13 && event.shiftKey == false){
// Emit to server input
socket.emit('input', {
name:username.value,
message:textarea.value
});
event.preventDefault();
}
})
// Handle Chat Clear
clearBtn.addEventListener('click', function(){
socket.emit('clear');
});
// Clear Message
socket.on('cleared', function(){
messages.textContent = '';
});
}
})();
</script>
</body>
</html>
mongodb driver "mongodb": "^3.1.0-beta4",
mongodb database version v3.2.20
"socket.io": "^2.1.1"`
This problem bugs me for hours and I have no clues. So apprecite your help.

socket.io, webrtc, nodejs video chat app getting errors over https: ERR_SSL_PROTOCOL_ERROR, 404 (Not Found), and ERR_CONNECTION_TIMED_OUT

I have put together a video chat app using socket.io, webrtc, nodejs from this online tutorial from github but now I am getting errors when converting it to be used over https:
Request URL:https://telemed.caduceususa.com/socket.io/?EIO=3&transport=polling&t=1479396416422-0
Request Method:GET
Status Code:404 Not Found
Remote Address:10.9.2.169:443
Other errors I have gotten in this process are as follows:
When I try to declare a different PORT I get - ERR_SSL_PROTOCOL_ERROR,
When I try to declare port 80 or 8080 i get: ERR_CONNECTION_TIMED_OUT
Something is going wrong on this line inside socket.io.js:
xhr.send(this.data);
I am running a node.js server on Windows Server 2012 and I have set up IIS to serve up the server on PORT 80. I have created the subdomain https://telemed.caduceususa.com in DNS and have purchased a trusted SSL cert to run the site over HTTPS.
Here is the excerpt of code from the dev tools that contains the above line that is causing the error as well as my other code:
/**
* Creates the XHR object and sends the request.
*
* #api private
*/
Request.prototype.create = function(){
var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
// SSL options for Node.js client
opts.pfx = this.pfx;
opts.key = this.key;
opts.passphrase = this.passphrase;
opts.cert = this.cert;
opts.ca = this.ca;
opts.ciphers = this.ciphers;
opts.rejectUnauthorized = this.rejectUnauthorized;
var xhr = this.xhr = new XMLHttpRequest(opts);
var self = this;
try {
debug('xhr open %s: %s', this.method, this.uri);
xhr.open(this.method, this.uri, this.async);
if (this.supportsBinary) {
// This has to be done after open because Firefox is stupid
// https://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
xhr.responseType = 'arraybuffer';
}
if ('POST' == this.method) {
try {
if (this.isBinary) {
xhr.setRequestHeader('Content-type', 'application/octet-stream');
} else {
xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
}
} catch (e) {}
}
// ie6 check
if ('withCredentials' in xhr) {
xhr.withCredentials = true;
}
if (this.hasXDR()) {
xhr.onload = function(){
self.onLoad();
};
xhr.onerror = function(){
self.onError(xhr.responseText);
};
} else {
xhr.onreadystatechange = function(){
if (4 != xhr.readyState) return;
if (200 == xhr.status || 1223 == xhr.status) {
self.onLoad();
} else {
// make sure the `error` event handler that's user-set
// does not throw in the same tick and gets caught here
setTimeout(function(){
self.onError(xhr.status);
}, 0);
}
};
}
debug('xhr data %s', this.data);
xhr.send(this.data);
}
Here is the server.js file:
var fs = require('fs');
var hskey = fs.readFileSync('ssl/telemed_internal_server.key');
var hscert = fs.readFileSync('ssl/telemed_internal_cert.pem');
var ca = fs.readFileSync('ssl/telemed_internal_key.pem');
var credentials = {
ca: ca,
key: hskey,
cert: hscert
};
var static = require('node-static');
var https = require('https');
var util = require('util');
var file = new(static.Server)();
var app = https.createServer(credentials, function (req, res) {
file.serve(req, res);
}).listen(process.env.PORT || 80);
var io = require('socket.io').listen(app);
io.sockets.on('connection', function (socket){
// convenience function to log server messages on the client
function log(){
var array = [">>> Message from server: "];
for (var i = 0; i < arguments.length; i++) {
array.push(arguments[i]);
}
socket.emit('log', array);
}
// when receive sdp, broadcast sdp to other user
socket.on('sdp', function(data){
console.log('Received SDP from ' + socket.id);
socket.to(data.room).emit('sdp received', data.sdp);
});
// when receive ice candidate, broadcast sdp to other user
socket.on('ice candidate', function(data){
console.log('Received ICE candidate from ' + socket.id + ' ' + data.candidate);
socket.to(data.room).emit('ice candidate received', data.candidate);
});
socket.on('message', function (message) {
log('Got message:', message);
// for a real app, would be room only (not broadcast)
socket.broadcast.emit('message', message);
});
socket.on('create or join', function (room) {
// join room
var existingRoom = io.sockets.adapter.rooms[room];
var clients = [];
if(existingRoom){
clients = Object.keys(existingRoom);
}
if(clients.length == 0){
socket.join(room);
io.to(room).emit('empty', room);
}
else if(clients.length == 1){
socket.join(room);
socket.to(room).emit('joined', room, clients.length + 1);
}
// only allow 2 users max per room
else{
socket.emit('full', room);
}
});
socket.on('error', function(error){
console.error(error);
})
});
Here is the main.js (config) file:
//my signalling server
var serverIP = "https://telemed.caduceususa.com/";
// RTCPeerConnection Options
var server = {
// Uses Google's STUN server
iceServers: [{
"url": "stun:stun4.l.google.com:19302"
},
{
url: 'turn:numb.viagenie.ca',
credential: 'muazkh',
username: 'webrtc#live.com'
}]
};
// various other development IPs
// var serverIP = "https://192.168.43.241:2013";
// var serverIP = "https://10.0.11.196:2013";
var localPeerConnection, signallingServer;
var btnSend = document.getElementById('btn-send');
var btnVideoStop = document.getElementById('btn-video-stop');
var btnVideoStart = document.getElementById('btn-video-start');
var btnVideoJoin = document.getElementById('btn-video-join');
var localVideo = document.getElementById('local-video');
var remoteVideo = document.getElementById('remote-video');
var inputRoomName = document.getElementById('room-name');
var localStream, localIsCaller;
btnVideoStop.onclick = function(e) {
e.preventDefault();
// stop video stream
if (localStream != null) {
localStream.stop();
}
// kill all connections
if (localPeerConnection != null) {
localPeerConnection.removeStream(localStream);
localPeerConnection.close();
signallingServer.close();
localVideo.src = "";
remoteVideo.src = "";
}
btnVideoStart.disabled = false;
btnVideoJoin.disabled = false;
btnVideoStop.disabled = true;
}
btnVideoStart.onclick = function(e) {
e.preventDefault();
// is starting the call
localIsCaller = true;
initConnection();
}
btnVideoJoin.onclick = function(e) {
e.preventDefault();
// just joining a call, not offering
localIsCaller = false;
initConnection();
}
function initConnection() {
var room = inputRoomName.value;
if (room == undefined || room.length <= 0) {
alert('Please enter room name');
return;
}
// start connection!
connect(room);
btnVideoStart.disabled = true;
btnVideoJoin.disabled = true;
btnVideoStop.disabled = false;
}
// WEBRTC STUFF STARTS HERE
// Set objects as most are currently prefixed
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection ||
window.webkitRTCPeerConnection || window.msRTCPeerConnection;
window.RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription ||
window.webkitRTCSessionDescription || window.msRTCSessionDescription;
navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia ||
navigator.webkitGetUserMedia || navigator.msGetUserMedia;
window.SignallingServer = window.SignallingServer;
var sdpConstraints = {
optional: [],
mandatory: {
OfferToReceiveVideo: true,
}
}
function connect(room) {
// create peer connection
localPeerConnection = new RTCPeerConnection(server);
// create local data channel, send it to remote
navigator.getUserMedia({
video: true,
audio: true
}, function(stream) {
// get and save local stream
trace('Got stream, saving it now and starting RTC conn');
// must add before calling setRemoteDescription() because then
// it triggers 'addstream' event
localPeerConnection.addStream(stream);
localStream = stream;
// show local video
localVideo.src = window.URL.createObjectURL(stream);
// can start once have gotten local video
establishRTCConnection(room);
}, errorHandler)
}
function establishRTCConnection(room) {
// create signalling server
signallingServer = new SignallingServer(room, serverIP);
signallingServer.connect();
// a remote peer has joined room, initiate sdp exchange
signallingServer.onGuestJoined = function() {
trace('guest joined!')
// set local description and send to remote
localPeerConnection.createOffer(function(sessionDescription) {
trace('set local session desc with offer');
localPeerConnection.setLocalDescription(sessionDescription);
// send local sdp to remote
signallingServer.sendSDP(sessionDescription);
});
}
// got sdp from remote
signallingServer.onReceiveSdp = function(sdp) {
// get stream again
localPeerConnection.addStream(localStream);
trace(localStream)
// if local was the caller, set remote desc
if (localIsCaller) {
trace('is caller');
trace('set remote session desc with answer');
localPeerConnection.setRemoteDescription(new RTCSessionDescription(
sdp));
}
// if local is joining a call, set remote sdp and create answer
else {
trace('set remote session desc with offer');
localPeerConnection.setRemoteDescription(new RTCSessionDescription(
sdp), function() {
trace('make answer')
localPeerConnection.createAnswer(function(
sessionDescription) {
// set local description
trace('set local session desc with answer');
localPeerConnection.setLocalDescription(
sessionDescription);
// send local sdp to remote too
signallingServer.sendSDP(sessionDescription);
});
});
}
}
// when received ICE candidate
signallingServer.onReceiveICECandidate = function(candidate) {
trace('Set remote ice candidate');
localPeerConnection.addIceCandidate(new RTCIceCandidate(candidate));
}
// when room is full, alert user
signallingServer.onRoomFull = function(room) {
window.alert('Room "' + room +
'"" is full! Please join or create another room');
}
// get ice candidates and send them over
// wont get called unless SDP has been exchanged
localPeerConnection.onicecandidate = function(event) {
if (event.candidate) {
//!!! send ice candidate over via signalling channel
trace("Sending candidate");
signallingServer.sendICECandidate(event.candidate);
}
}
// when stream is added to connection, put it in video src
localPeerConnection.onaddstream = function(data) {
remoteVideo.src = window.URL.createObjectURL(data.stream);
}
}
function errorHandler(error) {
console.error('Something went wrong!');
console.error(error);
}
function trace(text) {
console.info(text);
}
Here is the signalling server:
function trace(text){
console.info(text);
}
// Connects to signalling server with given room and IP
// has methods to exchange SDP and ICE candidates
var SignallingServer = function(room, socketServer){
this.room = room;
this.socket = io.connect(socketServer);
this.socket.on('full', function (room){
trace('Room ' + room + ' is full');
this.onRoomFull(room);
}.bind(this));
this.socket.on('empty', function (room){
this.isInitiator = true;
trace('Room ' + room + ' is empty');
});
this.socket.on('join', function (room){
trace('Making request to join room ' + room);
});
this.socket.on('joined', function (room, numClients){
trace('New user has joined ' + room);
trace('Room has ' + numClients + ' clients');
//ask host to initiate sdp transfer
this.onGuestJoined();
}.bind(this));
this.socket.on('sdp received', function(sdp){
trace('Received SDP ');
trace(sdp);
this.onReceiveSdp(sdp);
}.bind(this));
this.socket.on('ice candidate received', function(candidate){
trace('Received ICE candidate ');
trace(candidate);
this.onReceiveICECandidate(candidate);
}.bind(this));
this.socket.on('log', function (array){
console.log.apply(console, array);
});
}
SignallingServer.prototype = {
connect: function(){
if (this.room !== '') {
trace('Joining room ' + this.room);
this.socket.emit('create or join', this.room);
}
},
close: function(){
trace('Disconnecting')
this.socket.disconnect();
},
sendSDP: function(sdp){
trace('sending sdp')
this.socket.emit('sdp', {
room: this.room,
sdp: sdp
});
},
sendICECandidate: function(candidate){
trace('sending ice candidate');
this.socket.emit('ice candidate', {
room: this.room,
candidate: candidate
});
},
onReceiveSdp: function(sdp){
trace('Placeholder function: Received SDP')
},
onGuestJoined: function(){
trace('Placeholder function: Guest joined room')
},
onReceiveICECandidate: function(candidate){
trace('Placeholder function: Received ICE candidate')
},
onRoomFull: function(room){
trace('Placeholder function: Room is full!');
}
}
window.SignallingServer = SignallingServer;
AND FINALLY THE HTML (CAN SOMEONE ALSO EXPLAIN WHAT LIVERELOAD.JS IS?):
<!doctype html>
<!--[if lt IE 7]>
<html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="">
<![endif]-->
<!--[if IE 7]>
<html class="no-js lt-ie9 lt-ie8" lang="">
<![endif]-->
<!--[if IE 8]>
<html class="no-js lt-ie9" lang="">
<![endif]-->
<!--[if gt IE 8]>
<!-->
<html class="no-js" lang="">
<!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<style>
body {
padding-top: 50px;
padding-bottom: 20px;
}
</style>
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">
You are using an <strong>outdated</strong>
browser. Please
upgrade your browser
to improve your experience.
</p>
<![endif]-->
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">WebRTC Video Chat</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<!-- chatroom name form -->
<form class="navbar-form navbar-right form-inline">
<div class="form-group">
<input class="form-control" type="text" id="room-name" placeholder="Room name"/>
</div>
<button class="btn btn-primary" id="btn-video-start">Start</button>
<button class="btn btn-default" id="btn-video-join">Join</button>
<button class="btn btn-default" disabled id="btn-video-stop">Stop</button>
</form>
</div>
<!--/.navbar-collapse --> </div>
</nav>
<div class="container main">
<div class="row videos">
<div class="remote-video">
<video width="280" height="250" autoplay id="remote-video"></video>
</div>
<div class="local-video">
<video width="280" height="250" autoplay id="local-video" muted></video>
</div>
</div>
</div>
</div>
<!-- /container -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.2.min.js"><\/script>')</script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/vendor/socket.io.js"></script>
<script src="js/main.js"></script>
<script src="js/signalling.js"></script>
<script src="//localhost:9010/livereload.js"></script>
</body>
</html>

I want to display some query mongoose result data using Angular on an html page

I have a little problem, I want to display some mongoose query result data using Angular on on an html page.
I don't know how to send data to the angular $scope.
app.js:
User.find({ Code: doc.Code}, function (err, data){
var users = [];
var userswithsamecode = '';
data.forEach(function(d){
console.log(d.nom + " " + d.prenom);
users.push(d);
userswithsamecode += "<li>" + d.nom +" "+ d.prenom + '</li><br>';
How can I send this result to the angular $scope,
collegues.html
<html data-ng-app="demo">
<div data-ng-controller="simple">
Name:
<br/>
<input type="text" data-ng-model="name" />
<br/>
<ul>
<li data-ng-repeat="collegue in collegues |filter:name">{{}} </li>
</ul>
</div>
<script src="angular.min.js"></script>
<script>
var demo=angular.module('demo', []);
function simple($scope){
$scope.collegues=
];}
demo.controller('simple', simple);
</script>'
Thanks for your help!
First you need to create a model for mongo. An example
var Example = mongoose.model('ExampleCollection'{
name:String,
description: String
});
//posting to a mongodb
var example = new Example (
app.post("/add-something-to-mongo", function(req, res) {
name: req.body.name,
description: req.body.description
});
listing.save(function(err) {
if(err) {
console.log("Error! ", err);
}else
{
console.log("Saved!"
};
});
});
});
The angular code would look something like this.
var app = this;
var url = "heroku_url or localhost url";
app.save = function(Example) {
// create a new object
var newExample = {
"name": $scope.name
"description": $scope.description
};
$http.post(url + "/routefromserver", newExample).success(function() {
console.log("posting");
})
};
And lastly the HTML
<input id="name" type="text" ng-model="name" />
<input id="city" type="text" ng-model="description"/>
<button ng-click="app.save()">Save Me</button>

display messages on page refresh using nowjs

from the nowjs.org example, i have this code:
var server = require('http').createServer(function(req, res){
res.end(html);
});
server.listen(9080);
console.log("This server's process pid is: " + process.pid);
var nowjs = require("now");
var everyone = nowjs.initialize(server);
var MESSAGE_BACKLOG = 200,
SESSION_TIMEOUT = 60 * 1000;
function updateRSS () {
var bytes = parseInt(rss);
if (bytes) {
var megabytes = bytes / (1024*1024);
megabytes = Math.round(megabytes*10)/10;
$("#rss").text(megabytes.toString());
}
}
var mem = process.memoryUsage();
var rss;
setInterval(function () {
mem = process.memoryUsage();
}, 10*1000);
var messages = [];
var rss = updateRSS();
everyone.now.distributeMessage = function(message){
var messagetime = (new Date()).getTime();
// var mem = process.memoryUsage();
console.log(mem);
console.log(rss);
console.log('User '+this.now.name+' added message ' +message + messagetime + ' ' + mem + ' mem: ' + rss);
everyone.now.receiveMessage(this.now.name, message, messagetime);
messages.push([this.now.name, message, messagetime]);
console.log(messages);
};
i am pushing the messages into the messages = [], as per line:
messages.push([this.now.name, message, messagetime]);
here is the html file, i am using:
<script type="text/javascript" src="http://127.0.0.1:9080/nowjs/now.js"></script>
<script type="text/javascript">
$(function(){
//submit new messages when the user hits enter if the message isnt blank
now.receiveMessage = function(name, message, messagetime){
$("#messages").append('<br />' + '' + name + '' + ': ' + message +messagetime);
}
$("#text-input").keypress(function (e) {
if (e.keyCode != 13 /* Return */) return;
now.distributeMessage($("#text-input").val());
$("#text-input").attr("value", ""); // clear the entry field.
});
$("#send-button").click(function(){
now.distributeMessage($("#text-input").val());
$("#text-input").val("");
});
now.name = "${user}";
});
</script>
<div id="chat">
<div id="log"></div>
<div id="messages"></div>
<input type="text" id="text-input" />
<input type="button" value="Send" id="send-button" />
</div>
<ul id="status">
<li><a id="usersLink" href="#">5 users</a></li>
<li>uptime: <span id="uptime">?</span></li>
<li>memory: <span id="rss">?</span>mb RSS</li>
</ul>
but i dont see how to redisplay the already posted messages back, when the user refreshes the page?
any advice much appreciated.

Resources