Peer to peer reworking for conference, WebRTC - javascript

I have to ask the question again today.
I am in the course of processing a code to connect to one to one to the code allowing for a group conversation. Without beating around the bush, I have this code:
CallToUsers = function(connection) {
var connection = connection;
var isChannelReady;
var isInitiator = false;
var isStarted = false;
var servers = null;
var localStream = connection.getStream();
var localStreams = [];
var localConnection;
var turnReady;
var remoteStreams = [];
var remoteStream;
var pcConfig = {
'iceServers': [{
'url': 'stun:stun.l.google.com:19302'
}]
};
var pcConstraints = {
'optional': [{
'DtlsSrtpKeyAgreement': true
}]
};
var sdpConstraints = {
'mandatory': {
'OfferToReceiveAudio': true,
'OfferToReceiveVideo': true
}
};
var room;
var socket = io.connect();
var divElement = document.createElement('div');
divElement.setAttribute('id', 'remotesVideo');
document.body.appendChild(divElement);
var createRoom = function(room) {
room = room;
if(room !== '') {
console.log('Create or join to room', room);
socket.emit('create or join', room);
}
socket.on('created', function(room) {
console.log('Created room ' + room);
isInitiator = true;
});
/*socket.on('full', function(room) {
console.log('Room' + room + ' is full');
});*/
socket.on('join', function(room) {
console.log('Another peer made request to join ' + room);
isChannelReady = true;
});
socket.on('joined', function(room) {
console.log('User joined to room ' + room);
isChannelReady = true;
});
socket.on('log', function(array) {
console.log.apply(console, array);
});
};
var sendMessage = function(message) {
console.log('Client sending a message: ', message);
socket.emit('message', message);
};
window.onbeforeunload = function(e){
sendMessage('bye');
};
var startCall = function() {
sendMessage('got user media');
if(isInitiator) {
maybeStart();
}
socket.on('message', function(message) {
console.log('Client received a message: ' + message);
if(message === 'got user media') {
maybeStart();
} else if(message.type === 'offer') {
if(!isInitiator && !isStarted) {
maybeStart();
}
for(var i = 0; i < localStreams.length; i++) {
localStreams[i].setRemoteDescription(new RTCSessionDescription(message));
}
doAnswer();
} else if(message.type === 'answer' && isStarted) {
for(var i = 0; i < localStreams.length; i++) {
localStreams[i].setRemoteDescription(new RTCSessionDescription(message));
}
} else if(message.type === 'candidate' && isStarted) {
var candidate = new RTCIceCandidate({
sdpMLineIndex: message.label,
candidate: message.candidate
});
for(var i = 0; i < localStreams.length; i++) {
localStreams[i].addIceCandidate(candidate);
}
} else if(message === 'bye' && isStarted) {
handleRemoteEndCall();
}
});
//if(location.hostname != 'localhost') {
//requestTurn('https://computeengineondemand.appspot.com/turn?username=41784574&key=4080218913');
//}
};
var maybeStart = function() {
if(!isStarted && typeof localStream != 'undefined' && isChannelReady) {
createPeerConnection();
for(var i = 0; i < localStreams.length; i++) {
localStreams[i].addStream(localStream);
}
isStarted = true;
if(isInitiator) {
doCall();
}
}
};
var createPeerConnection = function() {
try {
localConnection = new RTCPeerConnection(pcConfig, pcConstraints);
localConnection.onicecandidate = handleIceCandidate;
localConnection.onaddstream = handleRemoteStreamAdded;
localConnection.onremovestream = handleRemoteStreamRemoved;
localStreams.push(localConnection);
console.log('Created RTCPeerConnection');
} catch(e) {
console.log('exception ' + e.message);
return;
}
};
var handleIceCandidate = function(event) {
if(event.candidate) {
sendMessage({
type: 'candidate',
label: event.candidate.sdpMLineIndex,
id: event.candidate.sdpMid,
candidate: event.candidate.candidate
});
} else {
console.log('End of candidates');
}
};
var handleRemoteStreamAdded = function(event) {
console.log('Remote stream added');
var newVideo = document.createElement('video');
newVideo.setAttribute('id', Math.floor((Math.random() * 1000) + 1));
newVideo.muted = false;
divElement.appendChild(newVideo);
attachMediaStream(newVideo, event.stream);
remoteStream = event.stream;
remoteStreams.push(remoteStream);
};
var handleRemoteStreamRemoved = function(event) {
console.log('Delete');
};
var handleCreateOfferError = function(event) {
console.log('createOffer() error: ' + e);
}
var setLocalAndSendMessage = function(sessionDescription) {
sessionDescription.sdp = preferOpus(sessionDescription.sdp);
for(var i = 0; i < localStreams.length; i++) {
localStreams[i].setLocalDescription(sessionDescription);
}
sendMessage(sessionDescription);
};
var doCall = function() {
console.log('Start call');
for(var i = 0; i < localStreams.length; i++) {
localStreams[i].createOffer(setLocalAndSendMessage, handleCreateOfferError);
}
};
var doAnswer = function() {
console.log('Sending answer');
for(var i = 0; i < localStreams.length; i++) {
localStreams[i].createAnswer(setLocalAndSendMessage, null, sdpConstraints);
}
};
var endCall = function() {
console.log('Hanging up');
isStarted = false;
for(var i = 0; i < localStreams.length; i++) {
localStreams[i].close();
localStreams[i] = null;
}
sendMessage('bye');
};
var handleRemoteEndCall = function() {
};
var requestTurn = function(turnUrl) {
var turnExists = false;
for(var i in pcConfig.iceServers) {
if(pcConfig.iceServers[i].url.substr(0, 5) === 'turn:') {
turnExists = true;
turnReady = true;
break;
}
}
if(!turnExists) {
console.log('Getting TURN server from ', turnUrl);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
var turnServer = JSON.parse(xhr.responseText);
console.log('Got TURN server: ', turnServer);
pc_config.iceServers.push({
'url': 'turn:' + turnServer.username + '#' + turnServer.turn,
'credential': turnServer.password
});
turnReady = true;
}
};
xhr.open('GET', turnUrl, true);
xhr.send();
}
};
var preferOpus = function(sdp) {
var sdpLines = sdp.split('\r\n');
var mLineIndex;
for(var i = 0; i < sdpLines.length; i++) {
if(sdpLines[i].search('m=audio') !== -1) {
mLineIndex = i;
break;
}
}
if(mLineIndex === null) {
return sdp;
}
for(i = 0; i < sdpLines.length; i++) {
if(sdpLines[i].search('opus/48000') !== -1) {
var opusPayload = extractSdp(sdpLines[i], /:(\d+) opus\/48000/i);
if(opusPayload) {
sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex], opusPayload);
}
break;
}
}
sdpLines = removeCN(sdpLines, mLineIndex);
sdp = sdpLines.join('\r\n');
return sdp;
};
var extractSdp = function(sdpLine, pattern) {
var result = sdpLine.match(pattern);
return result && result.length === 2 ? result[1] : null;
};
var setDefaultCodec = function(mLine, payload) {
var elements = mLine.split(' ');
var newLine = [];
var index = 0;
for(var i = 0; i < elements.length; i++) {
if(index === 3) {
newLine[index++] = payload;
}
if(elements[i] !== payload) {
newLine[index++] = elements[i];
}
}
return newLine.join(' ');
};
var removeCN = function(sdpLines, mLineIndex) {
var mLineElements = sdpLines[mLineIndex].split(' ');
for(var i = sdpLines.length - 1; i >= 0; i--) {
var payload = extractSdp(sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i);
if(payload) {
var cnPos = mLineElements.indexOf(payload);
if(cnPos !== -1) {
mLineElements.splice(cnPos, 1);
}
sdpLines.splice(i, 1);
}
}
sdpLines[mLineIndex] = mLineElements.join(' ');
return sdpLines;
};
return {
startCall: startCall,
endCall: endCall,
createRoom: createRoom
};
};
While the conversation between two users working well, then when adding another member, it no longer connects to the other two peers, although clearly the logs I see that attaches to the same room.
In the console, no errors.
Does anyone would be kind to help?
#edit
I'm adding server code too if needed:
var static = require('node-static');
var http = require('http');
var file = new(static.Server)();
var app = http.createServer(function (req, res) {
file.serve(req, res);
}).listen(2017);
var io = require('socket.io').listen(app);
io.sockets.on('connection', function (socket){
function log(){
var array = [">>> "];
for (var i = 0; i < arguments.length; i++) {
array.push(arguments[i]);
}
socket.emit('log', array);
}
socket.on('message', function (message) {
log('Got message: ', message);
socket.broadcast.emit('message', message); // should be room only
});
socket.on('create or join', function (room) {
var numClients = io.sockets.clients(room).length;
log('Room ' + room + ' has ' + numClients + ' client(s)');
log('Request to create or join room', room);
if (numClients == 0){
socket.join(room);
socket.emit('created', room);
} else {
io.sockets.in(room).emit('join', room);
socket.join(room);
socket.emit('joined', room);
}
socket.emit('emit(): client ' + socket.id + ' joined room ' + room);
socket.broadcast.emit('broadcast(): client ' + socket.id + ' joined room ' + room);
});
});

Finally solved the problem. The general rule of writing conferences, where all peers are connected to is this: each new incoming plays the role of answerer, and after creating a connection with all offers who send him an offer, begins to act as offerer (except the first peer, which is always the offer). #Mert Koksal, thank you for your interest thread.

Related

How to take the actual written value in html js

I am using the following library to implement multilingualism in my test website. However, there are some shortcomings that are difficult to deal with with my little experience.
The script works in such a way that we have a default language, it is written directly to html and dictionaries are made for other languages(they are at the very end of the js code). Everything works fine except for the title. When we want to switch to the default language, the title does not change, only after reloading the page it changes.
Most likely, the matter is in the following piece of code(184-186 line):
if (langDict["Title"] != null) {
document.title = langDict["Title"];
}
I suppose we need to add else and somehow set for it a value that is written in the html itself, but not which js changed in the translation.
var languative;
(function (languative) {
var phraseIdAttr = "data-phrase-id";
languative.ignoreTags = {
img: "<img />",
br: "<br />",
hr: "<hr />"
};
languative.dictonaries = {
html: {
_id: "html",
_name: "HTML"
},
en: {
_id: "en",
_name: "English"
},
ru: {
_id: "ru",
_name: "Русский - Russian"
},
de: {
_id: "de",
_name: "Deutsche - German"
}
};
languative.selectedDictionary = null;
function getDictionary(langKey) {
langKey = langKey.toLowerCase();
if (langKey in languative.dictonaries)
return languative.dictonaries[langKey];
var sep = langKey.indexOf("-");
if (sep > 0)
langKey = langKey.substring(0, sep);
return languative.dictonaries[langKey];
}
languative.getDictionary = getDictionary;
function getPhrase(phraseId) {
var res = findPhrase(phraseId);
if (res)
return res; else
return phraseId;
}
languative.getPhrase = getPhrase;
function findPhrase(phraseId) {
if ((phraseId == null) || (phraseId == ""))
return null;
if ((languative.selectedDictionary != null) && (phraseId in languative.selectedDictionary))
return languative.selectedDictionary[phraseId];
if (phraseId in languative.dictonaries.html)
return languative.dictonaries.html[phraseId];
return null;
}
languative.findPhrase = findPhrase;
function getYesNo(value) {
if (value === undefined)
return getPhrase("undefined"); else if (value)
return getPhrase("yes"); else
return getPhrase("no");
}
languative.getYesNo = getYesNo;
function getAttr(node, attr) {
var result = (node.getAttribute && node.getAttribute(attr)) || null;
if (!result && node.attributes) {
for (var i = 0; i < node.attributes.length; i++) {
var attrNode = node.attributes[i];
if (attrNode.nodeName === attr)
return attrNode.nodeValue;
}
}
return result;
}
function getDictionaryFromHtml() {
function getNodeValue(node) {
var res = null;
if ("innerHTML" in node) {
res = node["innerHTML"];
} else {
res = node.nodeValue;
}
if (res != null) {
res = res.replace(/\s{2,}/g, ' ');
res = res.replace(/^\s+|\s+$/g, '');
}
return res;
}
function getTagPhrase(tag) {
if (tag.childNodes.length > 1) {
var resPhrase = new Array();
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var chName = chNode.nodeName.toLowerCase();
var chValue = null;
if (chName in languative.ignoreTags)
chValue = languative.ignoreTags[chName]; else
chValue = getNodeValue(chNode);
resPhrase.push(chValue);
}
return resPhrase;
} else {
return getNodeValue(tag);
}
}
var tags = getHtmlTags();
var resDict = new Object();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = getTagPhrase(tag);
if ((phraseId in resDict) && (resDict[phraseId] != phraseValue)) {
console.warn("Different phrases with the same data-phrase-id='" + phraseId + "'\n" + " 1: " + JSON.stringify(resDict[phraseId], null, " ") + "\n 2: " + JSON.stringify(phraseValue, null, " "));
} else {
resDict[phraseId] = phraseValue;
}
}
}
return resDict;
}
languative.getDictionaryFromHtml = getDictionaryFromHtml;
function changeLanguage(langKey) {
function setTagPhrase(tag, phrase) {
if (tag.childNodes.length > 1) {
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var nName = chNode.nodeName.toLowerCase();
if (!(nName in languative.ignoreTags)) {
if ("innerHTML" in chNode) {
chNode["innerHTML"] = " " + phrase[ci] + " ";
} else {
chNode.nodeValue = " " + phrase[ci] + " ";
}
}
}
} else {
tag.innerHTML = " " + phrase + " ";
}
}
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
console.warn("Cannot identify dictionary by key '" + langKey + "'. Default dictionary (" + languative.dictonaries.html._id + ": " + languative.dictonaries.html._name + ") used instead.");
langDict = languative.dictonaries.html;
}
languative.selectedDictionary = langDict;
var tags = getHtmlTags();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = languative.getPhrase(phraseId);
if (phraseValue) {
setTagPhrase(tag, phraseValue);
} else {
console.warn("Phrase not definied in dictionary: data-phrase-id='" + phraseId + "'");
}
}
}
if (langDict["Title"] != null) {
document.title = langDict["Title"];
}
}
languative.changeLanguage = changeLanguage;
function getHtmlTags() {
var res = new Array();
var docTags = document.body.getElementsByTagName("*");
for (var i = 0; i < docTags.length; i++) {
var docTag = docTags[i];
var phraseId = getAttr(docTag, phraseIdAttr);
if (phraseId)
res.push(docTag);
}
return res;
}
var initialized = false;
function init() {
if (!initialized) {
initialized = true;
var htmlDict = languative.getDictionaryFromHtml();
for (var dictKey in htmlDict) {
if (!(dictKey in languative.dictonaries.html)) {
languative.dictonaries.html[dictKey] = htmlDict[dictKey];
}
}
var nav = window.navigator;
languative.changeLanguage(nav.userLanguage || nav.language);
}
}
languative.init = init;
function modifyDictionary(langKey, dictModifications) {
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
languative.dictonaries[langKey.toLowerCase()] = dictModifications;
} else {
for (var dictKey in dictModifications) {
langDict[dictKey] = dictModifications[dictKey];
}
}
}
languative.modifyDictionary = modifyDictionary;
})(languative || (languative = {}));
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', languative.init);
if (window.addEventListener) {
window.addEventListener('load', languative.init, false);
} else {
window.attachEvent('onload', languative.init);
}
languative.modifyDictionary("ru", {
Title: "Заголовок",
firstmessage: "ЭТО ЯЗЫК ПО УМОЛЧАНИЮ",
secondmessage: "КАКОЙ ТО ДРУГОЙ ТЕКСТ",
thirdmessage: "ЧТО ТО ЕЩЕ"
});
languative.modifyDictionary("de", {
Title: "Überschrift",
firstmessage: "Dies ist die Standardsprache",
secondmessage: "JEDER ANDERE TEXT",
thirdmessage: "ETWAS ANDERES"
});
<ul>
<li>English</li>
<li>Russian</li>
<li>German</li>
</ul>
<h1 data-phrase-id="firstmessage">THIS IS THE DEFAULT LANGUAGE</h1>
<span data-phrase-id="secondmessage">ANY OTHER TEXT</span>
<p data-phrase-id="thirdmessage">SOMETHING ELSE</p>
Also on my website there is a feedback form. I would like it to be possible to translate the placeholder values. How to do it?
I got it like this, but is this a good way?
if ((localStorage.getItem("lang") == "de") || (window.navigator.userLanguage == "de") || (window.navigator.language) == "de") {
document.querySelector("input[name=name]").placeholder = "Name";
document.querySelector("input[name=subject]").placeholder = "Thema";
document.querySelector("input[name=message]").placeholder = "Brief";
} else if ((localStorage.getItem("lang") == "ru") || (window.navigator.userLanguage == "ru") || (window.navigator.language) == "ru") {
document.querySelector("input[name=name]").placeholder = "Имя";
document.querySelector("input[name=subject]").placeholder = "Тема";
document.querySelector("input[name=message]").placeholder = "Сообщение";
} else {
document.querySelector("input[name=name]").placeholder = "Name";
document.querySelector("input[name=subject]").placeholder = "Subject";
document.querySelector("input[name=message]").placeholder = "Message";
};
document.querySelector('.lang').onclick = function() {
if ((localStorage.getItem("lang") == "de") || (window.navigator.userLanguage == "de") || (window.navigator.language) == "de") {
document.querySelector("input[name=name]").placeholder = "Name";
document.querySelector("input[name=subject]").placeholder = "Thema";
document.querySelector("input[name=message]").placeholder = "Brief";
} else if ((localStorage.getItem("lang") == "ru") || (window.navigator.userLanguage == "ru") || (window.navigator.language) == "ru") {
document.querySelector("input[name=name]").placeholder = "Имя";
document.querySelector("input[name=subject]").placeholder = "Тема";
document.querySelector("input[name=message]").placeholder = "Сообщение";
} else {
document.querySelector("input[name=name]").placeholder = "Name";
document.querySelector("input[name=subject]").placeholder = "Subject";
document.querySelector("input[name=message]").placeholder = "Message";
};
};
var languative;
(function (languative) {
var phraseIdAttr = "data-phrase-id";
languative.ignoreTags = {
img: "<img />",
br: "<br />",
hr: "<hr />"
};
languative.dictonaries = {
html: {
_id: "html",
_name: "HTML"
},
en: {
_id: "en",
_name: "English"
},
ru: {
_id: "ru",
_name: "Русский - Russian"
},
de: {
_id: "de",
_name: "Deutsche - German"
}
};
languative.selectedDictionary = null;
function getDictionary(langKey) {
langKey = langKey.toLowerCase();
if (langKey in languative.dictonaries)
return languative.dictonaries[langKey];
var sep = langKey.indexOf("-");
if (sep > 0)
langKey = langKey.substring(0, sep);
return languative.dictonaries[langKey];
}
languative.getDictionary = getDictionary;
function getPhrase(phraseId) {
var res = findPhrase(phraseId);
if (res)
return res; else
return phraseId;
}
languative.getPhrase = getPhrase;
function findPhrase(phraseId) {
if ((phraseId == null) || (phraseId == ""))
return null;
if ((languative.selectedDictionary != null) && (phraseId in languative.selectedDictionary))
return languative.selectedDictionary[phraseId];
if (phraseId in languative.dictonaries.html)
return languative.dictonaries.html[phraseId];
return null;
}
languative.findPhrase = findPhrase;
function getYesNo(value) {
if (value === undefined)
return getPhrase("undefined"); else if (value)
return getPhrase("yes"); else
return getPhrase("no");
}
languative.getYesNo = getYesNo;
function getAttr(node, attr) {
var result = (node.getAttribute && node.getAttribute(attr)) || null;
if (!result && node.attributes) {
for (var i = 0; i < node.attributes.length; i++) {
var attrNode = node.attributes[i];
if (attrNode.nodeName === attr)
return attrNode.nodeValue;
}
}
return result;
}
function getDictionaryFromHtml() {
function getNodeValue(node) {
var res = null;
if ("innerHTML" in node) {
res = node["innerHTML"];
} else {
res = node.nodeValue;
}
if (res != null) {
res = res.replace(/\s{2,}/g, ' ');
res = res.replace(/^\s+|\s+$/g, '');
}
return res;
}
function getTagPhrase(tag) {
if (tag.childNodes.length > 1) {
var resPhrase = new Array();
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var chName = chNode.nodeName.toLowerCase();
var chValue = null;
if (chName in languative.ignoreTags)
chValue = languative.ignoreTags[chName]; else
chValue = getNodeValue(chNode);
resPhrase.push(chValue);
}
return resPhrase;
} else {
return getNodeValue(tag);
}
}
var tags = getHtmlTags();
var resDict = new Object();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = getTagPhrase(tag);
if ((phraseId in resDict) && (resDict[phraseId] != phraseValue)) {
console.warn("Different phrases with the same data-phrase-id='" + phraseId + "'\n" + " 1: " + JSON.stringify(resDict[phraseId], null, " ") + "\n 2: " + JSON.stringify(phraseValue, null, " "));
} else {
resDict[phraseId] = phraseValue;
}
}
}
return resDict;
}
languative.getDictionaryFromHtml = getDictionaryFromHtml;
function changeLanguage(langKey) {
function setTagPhrase(tag, phrase) {
if (tag.childNodes.length > 1) {
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var nName = chNode.nodeName.toLowerCase();
if (!(nName in languative.ignoreTags)) {
if ("innerHTML" in chNode) {
chNode["innerHTML"] = " " + phrase[ci] + " ";
} else {
chNode.nodeValue = " " + phrase[ci] + " ";
}
}
}
} else {
tag.innerHTML = " " + phrase + " ";
}
}
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
console.warn("Cannot identify dictionary by key '" + langKey + "'. Default dictionary (" + languative.dictonaries.html._id + ": " + languative.dictonaries.html._name + ") used instead.");
langDict = languative.dictonaries.html;
}
languative.selectedDictionary = langDict;
var tags = getHtmlTags();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = languative.getPhrase(phraseId);
if (phraseValue) {
setTagPhrase(tag, phraseValue);
} else {
console.warn("Phrase not definied in dictionary: data-phrase-id='" + phraseId + "'");
}
}
}
if (langDict["Title"] != null) {
document.title = langDict["Title"];
}
}
languative.changeLanguage = changeLanguage;
function getHtmlTags() {
var res = new Array();
var docTags = document.body.getElementsByTagName("*");
for (var i = 0; i < docTags.length; i++) {
var docTag = docTags[i];
var phraseId = getAttr(docTag, phraseIdAttr);
if (phraseId)
res.push(docTag);
}
return res;
}
var initialized = false;
function init() {
if (!initialized) {
initialized = true;
var htmlDict = languative.getDictionaryFromHtml();
for (var dictKey in htmlDict) {
if (!(dictKey in languative.dictonaries.html)) {
languative.dictonaries.html[dictKey] = htmlDict[dictKey];
}
}
var nav = window.navigator;
languative.changeLanguage(nav.userLanguage || nav.language);
}
}
languative.init = init;
function modifyDictionary(langKey, dictModifications) {
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
languative.dictonaries[langKey.toLowerCase()] = dictModifications;
} else {
for (var dictKey in dictModifications) {
langDict[dictKey] = dictModifications[dictKey];
}
}
}
languative.modifyDictionary = modifyDictionary;
})(languative || (languative = {}));
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', languative.init);
if (window.addEventListener) {
window.addEventListener('load', languative.init, false);
} else {
window.attachEvent('onload', languative.init);
}
languative.modifyDictionary("ru", {
name: "Ваше имя",
email: "Ваш email",
send: "Отправить сообщение"
});
languative.modifyDictionary("de", {
name: "Ihr Name",
email: "Deine E-Mail",
send: "Nachricht senden"
});
ul li{
list-style: none;
}
<ul>
<li>English</li>
<li>Russian</li>
<li>German</li>
</ul>
<form>
<input type="text" name="name" data-phrase-id="name" placeholder="Your name">
<input type="text" name="email" data-phrase-id="email" placeholder="Your email">
<input type="submit" data-phrase-id="send" value="Send message">
</form>
For the first snippet you should just add a dictionary for en containing the Title and it will work, like so:
languative.modifyDictionary("en", {
Title: "Caption",
});
For the second one, there is more work because your script change innerHTML, which is not suitable for your feedback form since it contains only input elements which doesn't have innerHTML, so the script should be modified accordingly, like so:
var languative;
(function (languative) {
var phraseIdAttr = "data-phrase-id";
languative.ignoreTags = {
img: "<img />",
br: "<br />",
hr: "<hr />"
};
languative.dictonaries = {
html: {
_id: "html",
_name: "HTML"
},
en: {
_id: "en",
_name: "English"
},
ru: {
_id: "ru",
_name: "Русский - Russian"
},
de: {
_id: "de",
_name: "Deutsche - German"
}
};
languative.selectedDictionary = null;
function getDictionary(langKey) {
langKey = langKey.toLowerCase();
if (langKey in languative.dictonaries)
return languative.dictonaries[langKey];
var sep = langKey.indexOf("-");
if (sep > 0)
langKey = langKey.substring(0, sep);
return languative.dictonaries[langKey];
}
languative.getDictionary = getDictionary;
function getPhrase(phraseId) {
var res = findPhrase(phraseId);
if (res)
return res; else
return phraseId;
}
languative.getPhrase = getPhrase;
function findPhrase(phraseId) {
if ((phraseId == null) || (phraseId == ""))
return null;
if ((languative.selectedDictionary != null) && (phraseId in languative.selectedDictionary))
return languative.selectedDictionary[phraseId];
if (phraseId in languative.dictonaries.html)
return languative.dictonaries.html[phraseId];
return null;
}
languative.findPhrase = findPhrase;
function getYesNo(value) {
if (value === undefined)
return getPhrase("undefined"); else if (value)
return getPhrase("yes"); else
return getPhrase("no");
}
languative.getYesNo = getYesNo;
function getAttr(node, attr) {
var result = (node.getAttribute && node.getAttribute(attr)) || null;
if (!result && node.attributes) {
for (var i = 0; i < node.attributes.length; i++) {
var attrNode = node.attributes[i];
if (attrNode.nodeName === attr)
return attrNode.nodeValue;
}
}
return result;
}
function getDictionaryFromHtml() {
function getNodeValue(node) {
var res = null;
if (node.tagName !== 'INPUT') {
if ("innerHTML" in node) {
res = node["innerHTML"];
} else {
res = node.nodeValue;
}
} else {
res = node.getAttribute("placeholder") || node.value;
}
if (res != null) {
res = res.replace(/\s{2,}/g, ' ');
res = res.replace(/^\s+|\s+$/g, '');
}
return res;
}
function getTagPhrase(tag) {
if (tag.childNodes.length > 1) {
var resPhrase = new Array();
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var chName = chNode.nodeName.toLowerCase();
var chValue = null;
if (chName in languative.ignoreTags)
chValue = languative.ignoreTags[chName]; else
chValue = getNodeValue(chNode);
resPhrase.push(chValue);
}
return resPhrase;
} else {
return getNodeValue(tag);
}
}
var tags = getHtmlTags();
var resDict = new Object();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = getTagPhrase(tag);
if ((phraseId in resDict) && (resDict[phraseId] != phraseValue)) {
console.warn("Different phrases with the same data-phrase-id='" + phraseId + "'\n" + " 1: " + JSON.stringify(resDict[phraseId], null, " ") + "\n 2: " + JSON.stringify(phraseValue, null, " "));
} else {
resDict[phraseId] = phraseValue;
}
}
}
return resDict;
}
languative.getDictionaryFromHtml = getDictionaryFromHtml;
function changeLanguage(langKey) {
function setTagPhrase(tag, phrase) {
if (tag.childNodes.length > 1) {
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var nName = chNode.nodeName.toLowerCase();
if (!(nName in languative.ignoreTags)) {
console.log(chNode.tagName)
if (chNode.tagType !== 'INPUT') {
if ("innerHTML" in chNode) {
chNode["innerHTML"] = " " + phrase[ci] + " ";
} else {
chNode.nodeValue = " " + phrase[ci] + " ";
}
} else {
chNode.hasAttribute("placeholder")
? chNode.setAttribute("placeholder", phrase[ci])
: chNode.value = phrase[ci];
}
}
}
} else {
if (tag.tagName !== 'INPUT') {
tag.innerHTML = " " + phrase + " ";
} else {
tag.hasAttribute("placeholder")
? tag.setAttribute("placeholder", phrase)
: tag.value = phrase;
}
}
}
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
console.warn("Cannot identify dictionary by key '" + langKey + "'. Default dictionary (" + languative.dictonaries.html._id + ": " + languative.dictonaries.html._name + ") used instead.");
langDict = languative.dictonaries.html;
}
languative.selectedDictionary = langDict;
var tags = getHtmlTags();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = languative.getPhrase(phraseId);
if (phraseValue) {
setTagPhrase(tag, phraseValue);
} else {
console.warn("Phrase not definied in dictionary: data-phrase-id='" + phraseId + "'");
}
}
}
if (langDict["Title"] != null) {
document.title = langDict["Title"];
}
}
languative.changeLanguage = changeLanguage;
function getHtmlTags() {
var res = new Array();
var docTags = document.body.getElementsByTagName("*");
for (var i = 0; i < docTags.length; i++) {
var docTag = docTags[i];
var phraseId = getAttr(docTag, phraseIdAttr);
if (phraseId)
res.push(docTag);
}
return res;
}
var initialized = false;
function init() {
if (!initialized) {
initialized = true;
var htmlDict = languative.getDictionaryFromHtml();
for (var dictKey in htmlDict) {
if (!(dictKey in languative.dictonaries.html)) {
languative.dictonaries.html[dictKey] = htmlDict[dictKey];
}
}
var nav = window.navigator;
languative.changeLanguage(nav.userLanguage || nav.language);
}
}
languative.init = init;
function modifyDictionary(langKey, dictModifications) {
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
languative.dictonaries[langKey.toLowerCase()] = dictModifications;
} else {
for (var dictKey in dictModifications) {
langDict[dictKey] = dictModifications[dictKey];
}
}
}
languative.modifyDictionary = modifyDictionary;
})(languative || (languative = {}));
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', languative.init);
if (window.addEventListener) {
window.addEventListener('load', languative.init, false);
} else {
window.attachEvent('onload', languative.init);
}
languative.modifyDictionary("ru", {
name: "Ваше имя",
email: "Ваш email",
send: "Отправить сообщение"
});
languative.modifyDictionary("de", {
name: "Ihr Name",
email: "Deine E-Mail",
send: "Nachricht senden"
});
ul li{
list-style: none;
}
<ul>
<li>English</li>
<li>Russian</li>
<li>German</li>
</ul>
<form>
<input type="text" name="name" data-phrase-id="name" placeholder="Your name">
<input type="text" name="email" data-phrase-id="email" placeholder="Your email">
<input type="submit" data-phrase-id="send" value="Send message">
</form>

Find Email-adresses in the mailbody with Mailparser

I'm quite new to the topic and i'm still having some issues with my mailparser. Though searching and finding emails in the email header (mail.from) does work, it doesn't work in the email body. Does anybody have some experience with that and is willing to help? You can find the function i'm talking about under the "// Check for other addresses in Mail-Body (Doesn't work yet)"-comment. I think, that my Regex is correct. Also if the matchAll-Function give back an array and it can't be saved in the the subscriber.email-object, it shall be at least logged to the console. Also i checked manually in the inbox if there are mails with email adresses in the mail body. There are at least two, which shall be found..
The part of the App.js, that does the mailparsing:
const simpleParser = require('mailparser').simpleParser;
//const htmlparser = require("htmlparser2");
var fs = require('fs');
var config = require('./config');
var Imap = require('imap');
var imap = new Imap(config.imap);
var blacklistString = '';
String.prototype.matchAll = function(regexp) {
var matches = [];
this.replace(regexp, function() {
var arr = ([]).slice.call(arguments, 0);
var extras = arr.splice(-2);
arr.index = extras[0];
arr.input = extras[1];
matches.push(arr);
});
return matches.length ? matches : null;
};
function openInbox(subbox,cb) {
imap.openBox('INBOX.'+subbox, true, cb);
}
function getBoxes(cb) {
imap.getBoxes(cb);
}
function showBoxes(boxes) {
imap.end();
}
function logArrayElements(element) {
if(element[1].indexOf('placeholder.de')==-1){
addToBlacklistString(element[1]);
}
}
function addToBlacklistString(str) {
blacklistString += str+"\n";
}
function writeBlacklistFile() {
fs.appendFile('data/data.csv', blacklistString, function (err) {
if (err) throw err;
console.log('Saved!');
});
}
function search(searchArray, regex){
imap.search(searchArray, function(err, results) {
if (err) throw err;
var temp = 0;
var mailtemp = [];
var f = imap.fetch(results, { bodies: '' });
f.on('message', function(msg, seqno) {
console.log('Message #%d', seqno);
var prefix = '(#' + seqno + ') ';
msg.on('body', function(stream, info) {
simpleParser(stream, (err, mail)=>{
//console.log(temp);
//console.log(mail.subject);
/*fs.writeFile('data/'+seqno+'.txt',mail.text, function(err){
console.log(err);
});*/
//var text = mail.text;
// New Subscriber Object
var subscr = new Subscriber({nr: '', mailIdent: '', from: '', emails: '', text:'', uLink: '', anwalt: false });
subscr.nr = seqno;
//Check for From-Address
if(!!mail.from) {
//console.log(mail.from.value);
for(var i = 0; i < mail.from.value.length; i++) {
mailtemp = mail.from.value[i].address.matchAll(regex);
mailtemp.forEach(function(element){
/*fs.appendFile('data/data.csv', element[0] + "\n", function(error){
console.log(error);
});*/
subscr.from = element[0];
});
if(!!mailtemp) {
mailtemp.forEach(logArrayElements);
}
}
}else{
//console.log(mail.text);
}
// Message-ID
if(!!mail.messageId) {
subscr.mailIdent = mail.messageId;
}
console.log(mail.messageId);
// Check for other addresses in Mail-Body (Doesn't work yet)
var regexEmails = new RegExp('/([\w\.\-\_\#\+]+#[\w\.\-\_äüö]+\.[a-zA-Z]+)/g');
if(!!mail.text){
if(mail.text.matchAll(regexEmails)!=null) {
subscr.emails = mail.text.matchAll(regexEmails);
console.log(subscr.emails);
}
}
/* Split mail.text at substrings in substr-array. Extend if necessary..
*
* Also check for 'Anwalt'-Expression in splitted Substring
*
* If mail.text doesn't exist -> Check for html body and convert it to text-format
*/
//var regexLink = new RegExp('\.de\/(unsubscribe|austragen)\/([^\"]+)');
var regexAnwalt = new RegExp('nwalt|echtsanwalt|rechtlicher');
if(!!mail.text) {
var substr = ["schrieb pplaceholder.de", "Von: \"placeholder.de", "Von: pplaceholder.de", "From: placeholder.de", "Ursprüngliche Nachricht"];
for (var i = 0; i<substr.length; i++) {
if(mail.text.indexOf(substr[i]) > -1) {
var textTemp = mail.text;
var arr = textTemp.split(substr[i]);
if(arr[0].matchAll(regexAnwalt)!=null) {
subscr.anwalt = true;
};
subscr.text = arr[0];
break;
} else {
subscr.text = mail.text;
}
}
//console.log(arr);
}
else
{
var html = mail.html;
var text = htmlToText.fromString(html, {
noLinkBrackets: true,
ignoreImage: true,
uppercaseHeadings: false,
preserveNewlines: false,
wordwrap:130,
format: {
heading: function (node, fn, options) {
var h = fn(node.children, options);
return '\n==== ' + h + ' ====\n\n';
}
}
});
subscr.text = text;
}
mail.headers.forEach(function(value, key) {
//console.log(value);
});
subscr.save();
//console.log(subscr);
temp++;
});
});
msg.once('end', function() {
console.log(prefix + 'Finished');
});
});
f.once('error', function(err) {
console.log('Fetch error: ' + err);
});
f.once('end', function() {
console.log('Done fetching all messages!');
//writeBlacklistFile();
imap.end();
});
});
}
imap.once('ready', function() {
openInbox('Test',function(err, box) {
var searchArray = [['FROM', '#']];
search(searchArray,/([\w\.\-\_\#\+]+#[\w\.\-\_äüö]+\.[a-zA-Z]+)/g);
});
});
imap.once('error', function(err) {
console.log(err);
});
imap.once('end', function() {
console.log('Connection ended');
});
imap.connect();
app.listen(2700, function(){
console.log("Listening on Port 2700")
});
module.exports = app;
subscriber.js
const mongoose = require('mongoose');
var subscriberSchema = mongoose.Schema({
nr: Number,
mailIdent: String,
from: String,
emails: String,
text: String,
uLink: String,
anwalt: Boolean
});
var Subscriber = module.exports = mongoose.model('Subscriber', subscriberSchema);
//get Subscriber
module.exports.getSubscribers = function(callback, limit){
Subscriber.find(callback).limit(limit);
};
module.exports.getSubscriberByID = function(_id, callback){
Subscriber.findById(_id, callback);
};
The Regex for the Emails was a little bit wrong.
Also i didn't noticed that the matchAll-Fct. is giving back a two-dimensional Array. Here is the changed part of the code:
var regexEmails = new RegExp("([\\w\\.\\-\\_\\#\\+]+#[\\w\\.\\-\\_äüö]+\\.[a-zA-Z]+)");
var temp1 = mail.text.matchAll(regexEmails);
if(!!temp1){
//console.log(temp1);
for(var i =0; i<temp1.length; i++) {
if(temp1[0][i]!=='info#service.placeholder.de' && temp1[0][i] !== "info#placeholder.de"){
subscr.emails += temp1[0][i];
}
}
}

NodeJs Proxy Connection

why I cant connect with username and password with SOCKS5 like
username:password#ip:port, i can with HTTP, but cant with SOCKS5
doneusername:password#ip:port, i can with HTTP, but cant with SOCKS5
done
SOCKS5 ; username:password#ip:port
Attempting connection to ws://ip:port
Connecting to: ws://ip:port
net.js:928
throw new RangeError('port should be >= 0 and < 65536: ' + port);
^
RangeError: port should be >= 0 and < 65536: NaN
at lookupAndConnect (net.js:928:13)
at Socket.connect (net.js:905:5)
at Socket.connect (net.js:868:37)
var WebSocket = require('ws');
var valid_player_pos = null;
var reconnect = false;
var suicide_targets = null;
var socket = require('socket.io-client')(config.feederServer);
socket.on('pos', function(data) {
valid_player_pos = data;
//console.log(data);
});
socket.on('cmd', function(data) {
console.log(data);
if (data.name == "split") {
for (bot in bots) {
bots[bot].client.split();
}
} else if (data.name == "eject") {
for (bot in bots) {
bots[bot].client.eject();
}
} else if (data.name == "connect_server") {
if (data.ip == null) {
return;
}
if (data.ip == "") {
return;
}
for (bot in bots) {
bots[bot].client.disconnect();
}
bots = {};
game_server_ip = data.ip;
console.log("client requested bots on: " + game_server_ip);
setTimeout(function() {
startFeederBotOnProxies();
}, 1000);
} else if(data.name == "reconnect_server") {
reconnect = true;
if (data.ip == null) {
return;
}
if (data.ip == "") {
return;
}
for (bot in bots) {
bots[bot].client.disconnect();
}
bots = {};
game_server_ip = data.ip;
console.log("client requested bots on: " + game_server_ip);
}
});
socket.on('force-login', function(data) {
console.log(data);
if (data == "server-booted-up") {
return;
}
socket.emit("login", {
"uuid": config.client_uuid,
"type": "server"
});
});
fs = require('fs');
var HttpsProxyAgent = require('https-proxy-agent');
var Socks = require('socks');
function getRandomLine(filename) {
var fs = require('fs');
var lines = fs.readFileSync(filename).toString().split("\n");
line = lines[Math.floor(Math.random() * lines.length)];
return line
}
//object of bots
var bots = {};
bot_count = 0;
var fs = require('fs');
var lines = fs.readFileSync(config.proxies).toString().split("\n");
var url = require('url');
var game_server_ip = null;
function createAgent(ip,type) {
data = ip.split(":");
return new Socks.Agent({
proxy: {
ipaddress: data[0],
port: parseInt(data[1]),
type: parseInt(type)
}}
);
}
var proxy_mode = "HTTP";
function startFeederBotOnProxies() {
for (proxy_line in lines) {
if(lines[proxy_line].trim() == "#HTTP"){
proxy_mode = "HTTP";
}else if(lines[proxy_line].trim() == "#SOCKS4"){
proxy_mode = "SOCKS4";
}else if(lines[proxy_line].trim() == "#SOCKS5"){
proxy_mode = "SOCKS5";
}
if (lines[proxy_line][0] == "#" || lines[proxy_line].length < 3) {
continue;
}
//usefull for testing single proxies
if (process.argv[3] != null && proxy_line != process.argv[3]) {
continue;
}
proxy = "http://" + lines[proxy_line];
proxy_single = lines[proxy_line];
console.log(proxy_mode + " ; " + proxy_single);
try {
var opts = url.parse(proxy);
if (proxy != null) {
if(proxy_mode=="HTTP"){
agent = HttpsProxyAgent(opts);
}else if(proxy_mode=="SOCKS4"){
agent = createAgent(lines[proxy_line],4);
}else if(proxy_mode=="SOCKS5"){
agent = createAgent(lines[proxy_line],5);
}
} else {
var agent = null;
}
if (lines[proxy_line] == "NOPROXY") {
agent = null;
}
console.log("Attempting connection to " + game_server_ip);
for (i = 0; i < config.botsPerIp; i++) {
if(bot_count<config.maxBots){
bot_count++;
bots[bot_count] = new FeederBot(bot_count, agent, bot_count, game_server_ip);
}
}
} catch (e) {
console.log('Error occured on startup: ' + e);
}
}
}
console.log("ogar-feeder-bot started! Join a game in Chrome with the Userscript installed.");
console.log("Press CTRL + C to stop this script.");
From all of discussions I get that the problem with Your createAgent.
So use this code and be happy (:
function createAgent(connectionString, type) {
var type = parseInt(type || 5);
var ipParts = connectionString.split('#'); // splitting user:pass#host:port
var host, port, username, password;
switch(ipParts.length) {
case 3 : // somebody#somewhere.com:somepassword#proxy.com:1080
var credentials = (ipParts[0]+'#'+ipParts[1]).split(':'); // yusolokuji#leeching.net:luquitas
username = credentials[0]; // somebody#somewhere.com
password = credentials[1]; // somepassword
var hostParts = ipParts[2].split(':'); // proxy.com:1080
host = hostParts[0];
port = hostParts[1] || 1080;
break;
case 2 : // somebody:somepassword#proxy.com:1080
var credentials = ipParts[0].split(':'); // somebody:somepassword
username = credentials[0]; // somebody
password = credentials[1]; // somepassword
var hostParts = ipParts[1].split(':'); // proxy.com:1080
host = hostParts[0];
port = hostParts[1] || 1080;
break;
case 1 : // proxy.com:1080
ipParts = ipParts[0].split(':');
host = ipParts[0];
port = ipParts[1];
break;
}
var config = {
proxy: {
ipaddress: host,
port: parseInt(port),
type: type
}
};
if(type == 5) {
config.proxy.authentication = {
username: username,
password: password
};
}
if(type == 4) {
config.proxy.user_id = username;
}
return new Socks.Agent(config);
}

angularjs-passing data between functions of same controller

I am working on a project in which I have used angularjs and mvc.I am getting my status details data by http post.Now I want to use my this data in my another function of controller.I have passed my data in a scope variable $scope.Statuses and tried to use this scope variable to get data in my another function but its getting null value.Please suggest how to achieve this.
angularjs controller
var myIssuesController = function ($scope, $sce, $http, cfpLoadingBar, deviceDetector, $filter, $modal, $log) {
$("#navMyIssues").addClass("active");
$scope.issueCommnets = null;
$scope.showComments = false;
$scope.Issues = [];
$scope.dateFormat = 'dd-MMM-yyyy';
$scope.dateTimeFormat = 'dd-MMM-yyyy h:mm:ss a';
$scope.selectedIssue = null;
$scope.statusName = null;
$scope.ProjectDetails = [];
$scope.selectedProject = null;
$scope.isVisible = false;
$scope.isVisibleReply = false;
$scope.notifiedMembers = null;
$scope.defaultProfileImagePath = "";
$scope.pendingIssueCount = 0;
$scope.inprogressIssueCount = 0;
$scope.limitationIssueCount = 0;
$scope.needsresearchIssueCount = 0;
$scope.intestingIssueCount = 0;
$scope.Statuses = null;
$scope.issuesLoaded = false;
$scope.issueDetailsLoaded = false;
$scope.modalHeader;
$scope.options;
var selectedTab;
//get all assigned issues
$scope.GetAssignedIssues = function () {
//$scope.issueCount = -1;
$scope.issuesLoaded = false;
$scope.issueDetailsLoaded = false;
$scope.query = "";
var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/GetAllAssignedIssues/';
$http.post(url, []).success(function (data, status, headers, config) {
if (data != '' || data.length == 0) {
$scope.Issues = data;
$scope.Issues = $filter('orderBy')($scope.Issues, 'CreatedOn', true);
$scope.Statuses=$scope.getIssueStatusDetails($scope.Issues[0]);
for (var count = 0; count < $scope.Issues.length; count++) {
if ($scope.Issues[count].StatusName == "Pending") {
$scope.pendingIssueCount = $scope.pendingIssueCount + 1;
}
else if ($scope.Issues[count].StatusName == "In Progress") {
$scope.inprogressIssueCount = $scope.inprogressIssueCount + 1;
}
else if ($scope.Issues[count].StatusName == "Limitation") {
$scope.limitationIssueCount = $scope.limitationIssueCount + 1;
}
else if ($scope.Issues[count].StatusName == "Needs Research") {
$scope.needsresearchIssueCount = $scope.needsresearchIssueCount + 1;
}
else if ($scope.Issues[count].StatusName == "In Testing") {
$scope.intestingIssueCount = $scope.intestingIssueCount + 1;
}
var statusColor = "";
if ( $scope.Statuses[count]["Name"] == $scope.Issues[count].StatusName) {
statusColor = $scope.Statuses[count]["ColorInHexa"];
$scope.Issues[count].IssueStatusStyle = "border-bottom: 4px solid " + statusColor + " !important;padding-bottom: 5px;";
}
}
if (data.length != 0) {
if ($scope.selectedIssue == null) {
$scope.selectedIssue = $scope.Issues[0];
} else {
for (var count = 0; count < $scope.Issues.length;count++)
{
if($scope.Issues[count].Id==$scope.selectedIssue.Id) {
$scope.selectedIssue = $scope.Issues[count];
}
}
}
}
$scope.issuesLoaded = true;
$scope.showIssueDetails($scope.selectedIssue);
}
else {
$scope.errors.push(data.error);
//$scope.issueCount = -1;
}
if ($scope.isVisible == false) {
$("#changedetailsbox").hide();
$scope.isVisible = true;
}
if ($scope.isVisibleReply == false) {
$("#postReplybox").hide();
$scope.isVisibleReply = true;
}
}
);
};
$scope.GetAssignedIssues();
$scope.getIssueStatusDetails = function (issue) {
var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/GetIssueStatusDetails/';
$http.post(url, { ProjectId: issue.ProjectId } ).success(function(data, status, headers, config) {
if (data != '' || data.length != 0) {
$scope.selectedProject = data;
$scope.Statuses = $scope.selectedProject.Statuses;
} else {
$scope.errors.push(data.error);
}
});
};
}
AngularJS Services is your best friend when you need access variables or functions between controllers. Most commonly used services are: 'factory', 'provider', 'service'
"Angular services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app."
More information on AngularJS website
https://docs.angularjs.org/guide/services
Better explanation:
AngularJS: Service vs provider vs factory

Uncaught TypeError: Cannot read property 'options' of null

I cannot figure out why I keep getting this error:
Uncaught TypeError: Cannot read property 'options' of null
getFSREPlist
(anonymous function)
The error is referencing this line of code (21):
document.getElementById(elementidupdate).options.length=0;
What is weird is that it was working prior to this new google map api I just put on. Also, it is pulling the country code "1" and putting it in the drop down, but not the province code "19".
Here is the on page script:
getFSREPlist('1', 'fsrep-search-province', 'CountryID', '19');getFSREPlist('19', 'fsrep-search-city', 'ProvinceID', '3'); request.send(null);
Here is the full file:
function sack(file) {
this.xmlhttp = null;
this.resetData = function () {
this.method = "POST";
this.queryStringSeparator = "?";
this.argumentSeparator = "&";
this.URLString = "";
this.encodeURIString = true;
this.execute = false;
this.element = null;
this.elementObj = null;
this.requestFile = file;
this.vars = new Object();
this.responseStatus = new Array(2);
};
this.resetFunctions = function () {
this.onLoading = function () {};
this.onLoaded = function () {};
this.onInteractive = function () {};
this.onCompletion = function () {};
this.onError = function () {};
this.onFail = function () {};
};
this.reset = function () {
this.resetFunctions();
this.resetData();
};
this.createAJAX = function () {
try {
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
try {
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
this.xmlhttp = null;
}
}
if (!this.xmlhttp) {
if (typeof XMLHttpRequest != "undefined") {
this.xmlhttp = new XMLHttpRequest();
} else {
this.failed = true;
}
}
};
this.setVar = function (name, value) {
this.vars[name] = Array(value, false);
};
this.encVar = function (name, value, returnvars) {
if (true == returnvars) {
return Array(encodeURIComponent(name), encodeURIComponent(value));
} else {
this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
}
}
this.processURLString = function (string, encode) {
encoded = encodeURIComponent(this.argumentSeparator);
regexp = new RegExp(this.argumentSeparator + "|" + encoded);
varArray = string.split(regexp);
for (i = 0; i < varArray.length; i++) {
urlVars = varArray[i].split("=");
if (true == encode) {
this.encVar(urlVars[0], urlVars[1]);
} else {
this.setVar(urlVars[0], urlVars[1]);
}
}
}
this.createURLString = function (urlstring) {
if (this.encodeURIString && this.URLString.length) {
this.processURLString(this.URLString, true);
}
if (urlstring) {
if (this.URLString.length) {
this.URLString += this.argumentSeparator + urlstring;
} else {
this.URLString = urlstring;
}
}
this.setVar("rndval", new Date().getTime());
urlstringtemp = new Array();
for (key in this.vars) {
if (false == this.vars[key][1] && true == this.encodeURIString) {
encoded = this.encVar(key, this.vars[key][0], true);
delete this.vars[key];
this.vars[encoded[0]] = Array(encoded[1], true);
key = encoded[0];
}
urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
}
if (urlstring) {
this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
} else {
this.URLString += urlstringtemp.join(this.argumentSeparator);
}
}
this.runResponse = function () {
eval(this.response);
}
this.runAJAX = function (urlstring) {
if (this.failed) {
this.onFail();
} else {
this.createURLString(urlstring);
if (this.element) {
this.elementObj = document.getElementById(this.element);
}
if (this.xmlhttp) {
var self = this;
if (this.method == "GET") {
totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
this.xmlhttp.open(this.method, totalurlstring, true);
} else {
this.xmlhttp.open(this.method, this.requestFile, true);
try {
this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
} catch (e) {}
}
this.xmlhttp.onreadystatechange = function () {
switch (self.xmlhttp.readyState) {
case 1:
self.onLoading();
break;
case 2:
self.onLoaded();
break;
case 3:
self.onInteractive();
break;
case 4:
self.response = self.xmlhttp.responseText;
self.responseXML = self.xmlhttp.responseXML;
self.responseStatus[0] = self.xmlhttp.status;
self.responseStatus[1] = self.xmlhttp.statusText;
if (self.execute) {
self.runResponse();
}
if (self.elementObj) {
elemNodeName = self.elementObj.nodeName;
elemNodeName.toLowerCase();
if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea") {
self.elementObj.value = self.response;
} else {
self.elementObj.innerHTML = self.response;
}
}
if (self.responseStatus[0] == "200") {
self.onCompletion();
} else {
self.onError();
}
self.URLString = "";
break;
}
};
this.xmlhttp.send(this.URLString);
}
}
};
this.reset();
this.createAJAX();
}
var ajax = new Array();
function getFSREPlist(sel, elementidupdate, fsrepvariable, currentvalue) {
if (sel == '[object]' || sel == '[object HTMLSelectElement]') {
var FSREPID = sel.options[sel.selectedIndex].value;
} else {
var FSREPID = sel;
}
document.getElementById(elementidupdate).options.length = 0;
var index = ajax.length;
ajax[index] = new sack();
ajax[index].requestFile = 'http://www.cabcot.com/wp-content/plugins/firestorm-real-estate-plugin/search.php?' + fsrepvariable + '=' + FSREPID + '&cvalue=' + currentvalue;
ajax[index].onCompletion = function () {
ElementUpdate(index, elementidupdate)
};
ajax[index].runAJAX();
}
function ElementUpdate(index, elementidupdate) {
var obj = document.getElementById(elementidupdate);
eval(ajax[index].response);
}
You should call getFSREPlist when DOM is loaded. I ran
document.getElementById('fsrep-search-province').options.length=0
from chrome´s console. while page was still loading and caused that same error.
http://i.imgur.com/GBFizq1.png

Categories