Long running process to get ip working async in Angular - javascript

I need to call a javascript program which will get the ip address (from intranet) and send it to node js server where i have to do some calculation!
below is the JS file ipaddress.js:
var myIP = (function () {
return {
getIP: function () {
var ip_dups = {};
//compatibility for firefox and chrome
var RTCPeerConnection = window.RTCPeerConnection
|| window.mozRTCPeerConnection
|| window.webkitRTCPeerConnection;
var useWebKit = !!window.webkitRTCPeerConnection;
//bypass naive webrtc blocking using an iframe
if (!RTCPeerConnection) {
//NOTE: you need to have an iframe in the page right above the script tag
//
//<iframe id="iframe" sandbox="allow-same-origin" style="display: none"></iframe>
//<script>...getIPs called in here...
//
var win = iframe.contentWindow;
RTCPeerConnection = win.RTCPeerConnection
|| win.mozRTCPeerConnection
|| win.webkitRTCPeerConnection;
useWebKit = !!win.webkitRTCPeerConnection;
}
//minimal requirements for data connection
var mediaConstraints = {
optional: [{ RtpDataChannels: true }]
};
var servers = { iceServers: [{ urls: "stun:stun.services.mozilla.com" }] };
//construct a new RTCPeerConnection
var pc = new RTCPeerConnection(servers, mediaConstraints);
function handleCandidate(candidate) {
//match just the IP address
var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
var ip_addr = ip_regex.exec(candidate)[1];
//remove duplicates
if (ip_dups[ip_addr] === undefined)
return (ip_addr);
ip_dups[ip_addr] = true;
}
//listen for candidate events
pc.onicecandidate = function (ice) {
//skip non-candidate events
if (ice.candidate)
handleCandidate(ice.candidate.candidate);
};
//create a bogus data channel
pc.createDataChannel("");
//create an offer sdp
pc.createOffer(function (result) {
//trigger the stun server request
pc.setLocalDescription(result, function () { }, function () { });
}, function () { });
//wait for a while to let everything done
setTimeout(function () {
//read candidate info from local description
var lines = pc.localDescription.sdp.split('\n');
lines.forEach(function (line) {
if (line.indexOf('a=candidate:') === 0)
handleCandidate(line);
});
}, 1000);
}
}
})(myIP() || {})
In angular program app.component.ts file:
import 'ipaddress.js'
declare var myIP;
....
ngOnInit(){
ip = myIP();
console.log(ip);
//send this ip to node server and do the validation!
}
I need myIP() function to return ip and program should wait until myIP() doesnot send result and then only further execution starts.
can anyone help me in this?

Related

Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided

This is the js code for downloading the file and persisting to the database:
<script type="text/javascript">
(function () {
window.indexedDB = window.indexedDB || window.webkitIndexedDB ||
window.mozIndexedDB || window.OIndexedDB ||
window.msIndexedDB;
var IDBTransaction = window.IDBTransaction ||
window.webkitIDBTransaction ||
window.OIDBTransaction ||
window.msIDBTransaction;
var dbVersion = 1.0;
var indexedDB = window.indexedDB;
var dlStatusText = document.getElementById("fetchstatus");
// Create/open database
var request = indexedDB.open("Syafunda_Videos", dbVersion),
db,
createObjectStore = function (dataBase) {
dataBase.createObjectStore("Videos",{ keyPath: "id", autoIncrement:true });
},
getVideoFile = function () {
var xhr = new XMLHttpRequest(),
blob;
// Get the Video file from the server.
xhr.open("GET", "<?php echo $name ?>", true);
xhr.responseType = "blob";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
blob = xhr.response;
addVideoInDb(blob);
dlStatusText.innerHTML = "DOWNLOAD COMPLETE: Video file downloaded.";
}
else {
dlStatusText.innerHTML = "ERROR: Unable to download video.";
}
}, false);
xhr.send();
},
addVideoInDb = function (blob) {
var transaction = db.transaction(["Videos"], "readwrite");
var add = transaction.objectStore("Videos").put(blob);
//console.log(objectStore.autoIncrement);
};
request.onerror = function (event) {
console.log("Error creating/accessing IndexedDB database");
};
request.onsuccess = function (event) {
console.log("Success creating/accessing IndexedDB database");
db = request.result;
db.onerror = function (event) {
console.log("Error creating/accessing IndexedDB database");
};
getVideoFile();
}
// For future use. Currently only in latest Firefox versions
request.onupgradeneeded = function (event) {
createObjectStore(event.target.result);
};
})();</script>
I'm trying to retrieve files from indexedDB. I keep on getting that error in the console:This is the js code for retrieving files from the databas,this is where I am getting the error:
Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
at IDBRequest.transaction.objectStore.get.onsuccess)
Where am I going wrong? Here is a snippet of my JS code. Some pointers would be great:
<script type="text/javascript">
(function () {
// IndexedDB
window.indexedDB = window.indexedDB || window.webkitIndexedDB ||
window.mozIndexedDB || window.OIndexedDB ||
window.msIndexedDB,
IDBTransaction = window.IDBTransaction ||
window.webkitIDBTransaction ||
window.OIDBTransaction || window.msIDBTransaction,
dbVersion = 1.0;
var indexedDB = window.indexedDB;
// Create/open database
var request = indexedDB.open("Syafunda_Videos");
request.onerror = function (event) {
// Failed to Open the indexedDB database
};
request.onsuccess = function (event) {
db = request.result;
// Open a transaction to the database
var transaction = db.transaction(["Videos"], "readwrite");
//Retrieve the video file
transaction.objectStore("Videos").get("2").onsuccess =
function (event) {
var videoFile = event.target.result;
var URL = window.URL || window.webkitURL;
var videoURL = URL.createObjectURL(videoFile);
// Set video src to ObjectURL
var videoElement = document.getElementById("Video");
videoElement.setAttribute("src", videoURL);
var mimeDisplayElement = document.getElementById("vidMimeDisplay");
mimeDisplayElement.innerHTML = videoFile.type;
};
}
})();
</script>
on getting the video,i changed: get("2") to get(2) like so
//Retrieve the video file
transaction.objectStore("Videos").get(2).onsuccess =
function (event) { //code...}

uwsgi-websocket GET /websocket no PONG received in 3 seconds

I am trying to implement websocket through uwsgi Gevent. But, in between 2,3 requests I am always getting no PONG received in 3 seconds error.
Server Side code:
#ws.route('/websocket')
def audio(ws):
first_message = True
total_msg = ""
sample_rate = 0
total_data = []
while True:
msg = ws.receive()
# processing message here and sending response back
ws.send("response")
if __name__ == '__main__':
app.run(https='0.0.0.0:443,{},{}'.format(ssl_cert,ssl_key), port = 5002, gevent=1000)
Client side code:
ws = new WebSocket('wss://ec2-54-72-7-110.eu-west-1.compute.amazonaws.com/websocket');
//ws = new WebSocket('wss://ec2-54-72-7-110.eu-west-1.compute.amazonaws.com:5000/websocket');
ws.onopen = function(evt) {
console.log('Connected to websocket.');
alert("Recording started")
navigator.getUserMedia({audio: true, video: false}, initializeRecorder, function(e) {
console.log('No live audio input: ' + e);
});
}
function initializeRecorder(stream){
audio_context = new AudioContext;
sampleRate = audio_context.sampleRate;
ws.send("sample rate:" + sampleRate);
var audioInput = audio_context.createMediaStreamSource(stream);
console.log("Created media stream.");
var bufferSize = 4096;
// record only 1 channel
recorder = audio_context.createScriptProcessor(bufferSize, 1, 1);
// specify the processing function
recorder.onaudioprocess = recorderProcess;
// connect stream to our recorder
audioInput.connect(recorder);
// connect our recorder to the previous destination
recorder.connect(audio_context.destination);
}
function recorderProcess(e) {
var left = e.inputBuffer.getChannelData(0);
if (ws.readyState === WebSocket.OPEN) {
var view = new Int16Array(convertFloat32ToInt16(left))
console.log(view);
ws.send(view);
}
}
function close_WebSocket(){
console.log("done")
ws.send("done")
ws.onmessage = function(evt) {
console.log(evt.data)
ws.close()
}
audio_context.close();
}
I don't know what is wrong with it?

Overlapping parts while buffering mp3

I am trying to stream MP3 file from a nodeJS server using BinaryJS - http://binaryjs.com/
But, when I am decoding the buffers on the client side they are seems to be overlapping, Meaning that the new chunk of data is being played few milliseconds before the previous one ended, causing the audio to lag.
is there any way to make the client wait until the current buffer is finished before starting the new one?
Server:
var BinaryServer = require('binaryjs').BinaryServer;
var fs = require('fs');
var server = BinaryServer({port: 9000});
server.on('connection', function(client){
var file = fs.createReadStream(__dirname + '/Song.mp3', {
'flags': 'r',
'bufferSize': 4 * 1024
});
});
client.send(file);
});
Client:
var client = new BinaryClient('ws://localhost:9000');
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
client.on('stream', function (stream, meta) {
var parts = [];
var last = 0;
stream.on('data', function (data) {
var source = context.createBufferSource();
context.decodeAudioData(data, function (buf) {
source.buffer = buf;
source.connect(context.destination);
source.loop = false;
source.start(last);
last += buf.duration;
source.onended = function() {
console.log('Your audio has finished playing');
};
},
function (e) {
"Error with decoding audio data" + e.err
});
parts.push(data);
});
stream.on('end', function () {
console.log(parts);
});
});
Not sure about this, but instead of initializing last to 0, you might want to initialize it to context.currentTime.

How do I test my WebSocket which is developed in JavaScript

I have created WebSocket.js but unfortunately I am unable to test it due to unavailability of data. The requirement is the data comes from various sources so I have multiple sockets for that. Note: I want to particularly test my socket.onMessage behaves for different sockets. Please find the code snippet below:
var webSocket;
var txQueue = [];
var defaultReconnectTimeout = 1000; //will be multiplied by 2 and saved into reconnectTimeout on each try
var reconnectTimeout = defaultReconnectTimeout;
var registerWebSocketHandlers = function(webSocket) {
webSocket.onclose = function(){
setTimeout(service.reopen, reconnectTimeout *= 2);
};
webSocket.onopen = function(e) {
reconnectTimeout = defaultReconnectTimeout; //reset this
deferredSend();
};
webSocket.onerror = function(e) {
throw new Error("[WebSocket] An error occured " + e);
};
}
var uniqid = function() {
return (new Date().getTime()).toString(16);
}
var deferredSend = function() {
if(!service.isOpen()) {
$timeout(deferredSend, 100);
return;
}
while(txQueue.length && service.isOpen()) {
var payload = txQueue.shift();
webSocket.send(typeof payload === 'string' ? payload : JSON.stringify(payload));
}
};
var createNewWebSocketInstance = function(apiUrl){
var websocket = new $window.WebSocket(apiUrl);
websocket.id = uniqid();
return websocket;
}
// TODO: this is a bit hacky since we directly bind it to the raw window event
$window.onbeforeunload = function(e) {
service.close();
};
var service = {};
service.setMessageEventHandler = function(name,cb) {
instances[name].onmessage = function(msg) {
if(msg.data.indexOf('Status: connected') === 0)
{
return;
}
var jsonObj = JSON.parse(msg.data);
cb(jsonObj);
};
};
service.isOpen = function() {
return webSocket.readyState === 1;
};
service.send = function(msg) {
txQueue.push(msg);
deferredSend();
};
service.close = function() {
return webSocket.close();
};
service.reopen = function() {
// get old message handler
var msgHandler = webSocket.onmessage;
// try closing the previous WebSocket
service.close();
// open new WebSocket
openConnection();
// re-attach old handler to new WebSocket
webSocket.onmessage = msgHandler;
};
service.getId = function() {
return webSocket.id;
}
// Returns an already existing instance of the socket, if unavailable then creates a new one.
service.getInstance = function(name, config) {
if(!(name in instances)) {
instances[name] = createNewWebSocketInstance(config);
}
registerWebSocketHandlers(instances[name]);
return instances[name];
};
return service;
You can test WebSocket using websocket.html at websocket.org Echo Test Creating your own test
Using a text editor, copy the following code and save it as
websocket.html somewhere on your hard drive. Then simply open it in a browser. The page will automatically connect, send a message,
display the response, and close the connection.
See Linux - WebSocket test error.

How do I code a node.js proxy to use NTLMv2 authentication

I've tried to search through stackoverflow for a similar question but most people are asking about the client-side of the NTLMv2 protocol.
I'm implementing a proxy that is performing the server-side of the protocol to authenticate users connecting to the proxy.
I've coded a lot of the protocol but I'm now stuck because the documentation that should take me further is difficult to understand.
This is the best documentation I've found so far: http://www.innovation.ch/personal/ronald/ntlm.html, but how to deal with the LM and NT responses is oblivious to me.
The proxy is located on an application server. The domain server is a different machine.
Example code for the node proxy:
var http = require('http')
, request = require('request')
, ProxyAuth = require('./proxyAuth');
function handlerProxy(req, res) {
ProxyAuth.authorize(req, res);
var options = {
url: req.url,
method: req.method,
headers: req.headers
}
req.pipe(request(options)).pipe(res)
}
var server = http.createServer(handlerProxy);
server.listen(3000, function(){
console.log('Express server listening on port ' + 3000);
});
ProxyAuth.js code:
ProxyAuth = {
parseType3Msg: function(buf) {
var lmlen = buf.readUInt16LE(12);
var lmoff = buf.readUInt16LE(16);
var ntlen = buf.readUInt16LE(20);
var ntoff = buf.readUInt16LE(24);
var dlen = buf.readUInt16LE(28);
var doff = buf.readUInt16LE(32);
var ulen = buf.readUInt16LE(36);
var uoff = buf.readUInt16LE(40);
var hlen = buf.readUInt16LE(44);
var hoff = buf.readUInt16LE(48);
var domain = buf.slice(doff, doff+dlen).toString('utf8');
var user = buf.slice(uoff, uoff+ulen).toString('utf8');
var host = buf.slice(hoff, hoff+hlen).toString('utf8');
var lmresp = buf.slice(lmoff, lmoff+lmlen).toString('utf8');
var ntresp = buf.slice(ntoff, ntoff+ntlen).toString('utf8');
console.log(user, lmresp, ntresp);
/* NOW WHAT DO I DO? */
},
authorize: function(req, res) {
var auth = req.headers['authorization'];
if (!auth) {
res.writeHead(401, {
'WWW-Authenticate': 'NTLM',
});
res.end('<html><body>Proxy Authentication Required</body></html>');
}
else if(auth) {
var header = auth.split(' ');
var buf = new Buffer(header[1], 'base64');
var msg = buf.toString('utf8');
console.log("Decoded", msg);
if (header[0] == "NTLM") {
if (msg.substring(0,8) != "NTLMSSP\x00") {
res.writeHead(401, {
'WWW-Authenticate': 'NTLM',
});
res.end('<html><body>Header not recognized</body></html>');
}
// Type 1 message
if (msg[8] == "\x01") {
console.log(buf.toString('hex'));
var challenge = require('crypto').randomBytes(8);
var type2msg = "NTLMSSP\x00"+
"\x02\x00\x00\x00"+ // 8 message type
"\x00\x00\x00\x00"+ // 12 target name len/alloc
"\x00\x00\x00\x00"+ // 16 target name offset
"\x01\x82\x00\x00"+ // 20 flags
challenge.toString('utf8')+ // 24 challenge
"\x00\x00\x00\x00\x00\x00\x00\x00"+ // 32 context
"\x00\x00\x00\x00\x00\x00\x00\x00"; // 40 target info len/alloc/offset
type2msg = new Buffer(type2msg).toString('base64');
res.writeHead(401, {
'WWW-Authenticate': 'NTLM '+type2msg.trim(),
});
res.end();
}
else if (msg[8] == "\x03") {
console.log(buf.toString('hex'));
ProxyAuth.parseType3Msg(buf);
/* NOW WHAT DO I DO? */
}
}
else if (header[0] == "Basic") {
}
}
}
};
module.exports = ProxyAuth;
The /* NOW WHAT DO I DO? */ comment specifies where I am stuck.
I hope I put enough information there, but let me know if anything else is needed.

Categories