I am developping an hybrid app (JQM 1.4 + Phonegap 3.6.3).
I have a function populateImagesUrlsLocalAndServer that checks if an image file exists on my server, but I can't use this function because it makes my app crash on Phonegap...
I can't find why.
Can you help me fix this issue so I can use this feature in my app again ?
Thank
function populateImagesUrlsLocalAndServer(str, baseUrl, type) {
if (connectionStatus == "online") {
if (UrlExists('./'+baseUrl+str)) { //local file
imagesUrls[str] = './'+baseUrl+str;
} else if (isPhoneGap && UrlExists('http://boardlineapp.com/app/'+baseUrl+str)) { //server file....we exclude this for desktop browser because of cross domain error
console.log('retrieving '+'http://boardlineapp.com/app/'+baseUrl+str+' on server')
imagesUrls[str] = 'http://boardlineapp.com/app/'+baseUrl+str;
} else {
imagesUrls[str] = './'+baseUrl+'default.png';
}
} else { //offline
if (UrlExists('./'+baseUrl+str)) { //local file
imagesUrls[str] = './'+baseUrl+str;
} else {
imagesUrls[str] = './'+baseUrl+'default.png';
}
}
imagesUrls[str+'type'] = type;
}
instead, for now I am using :
function populateImagesUrls(str, baseUrl, type) {
if ( str == 'byrne-ow-fender.png'
|| str == 'ci-tacogrinder.png'
|| str == 'noamizuno.png'
|| str == 'brendanmargieson.png'
|| str == 'kaihing.png'
|| str == 'dustinhollick.png'
|| str == 'dhd-thetwin.png'
) {
//console.log(str);
//console.log(baseUrl);
imagesUrls[str] = './'+baseUrl+'default.png';
} else {
imagesUrls[str] = './'+baseUrl+str;
}
imagesUrls[str+'type'] = type;
}
the function that calls it is the following:
function checkIfImagesExistAllAtOnce() {
var prodataTemp = [];
prodataTemp = prodata.slice();
prodataTemp.shift();
prodataTemp.sort(sort_by('brand', 'name', 'model'));
var strBrandDone;
var strNameDone;
var strModelDone;
for (i = 1; i < prodataTemp.length; ++i) {
//check brand
var str = prodataTemp[i]['brand'].replace(/\s+/g, '').toLowerCase();
str = str+'.png';
if (str != strBrandDone) {
var baseUrl = "images/brands/";
strBrandDone = str;
var type = "brand";
populateImagesUrls(str, baseUrl, type);
//populateImagesUrlsLocalAndServer(str, baseUrl, type);
}
//check pro image
var str = prodataTemp[i]['name'].replace(/\s+/g, '').toLowerCase();
str = str+'.png';
if (str != strNameDone) {
var baseUrl = "images/pros/";
strNameDone = str;
var type = "pro";
populateImagesUrls(str, baseUrl, type);
//populateImagesUrlsLocalAndServer(str, baseUrl, type);
}
//check board image
var str = prodataTemp[i]['imageName'];
if (str != strModelDone) {
var baseUrl = "images/boards/";
strModelDone = str;
var type = "board";
populateImagesUrls(str, baseUrl, type);
//populateImagesUrlsLocalAndServer(str, baseUrl, type);
}
}
prodataTemp = null;
}
Related
I need to send data from a custom form to Zoho. I'm looking at the native javascript request in their documentation here.
https://www.zoho.com/crm/developer/docs/api/v2/insert-records.html
var listener = 0;
class InsertRecordsAPI {
async insertRecords() {
var url = "https://www.zohoapis.com/crm/v2/Leads"
var parameters = new Map()
var headers = new Map()
var token = {
clientId:"1000.NPY9M1V0XXXXXXXXXXXXXXXXXXXF7H",
redirectUrl:"http://127.0.0.1:5500/redirect.html",
scope:"ZohoCRM.users.ALL,ZohoCRM.bulk.read,ZohoCRM.modules.ALL,ZohoCRM.settings.ALL,Aaaserver.profile.Read,ZohoCRM.org.ALL,profile.userphoto.READ,ZohoFiles.files.ALL,ZohoCRM.bulk.ALL,ZohoCRM.settings.variable_groups.ALL"
}
var accesstoken = await new InsertRecordsAPI().getToken(token)
headers.set("Authorization", "Zoho-oauthtoken " + accesstoken)
var requestMethod = "POST"
var reqBody = {"data":[{"Last_Name":"Lead_changed","Email":"newcrmapi#zoho.com","Company":"abc","Lead_Status":"Contacted"},{"Last_Name":"New Lead","Email":"newlead#zoho.com","Company":"abc","Lead_Status":"Contacted"}],"trigger":["approval","workflow","blueprint"]}
var params = "";
parameters.forEach(function(value, key) {
if (parameters.has(key)) {
if (params) {
params = params + key + '=' + value + '&';
}
else {
params = key + '=' + value + '&';
}
}
});
var apiHeaders = {};
if(headers) {
headers.forEach(function(value, key) {
apiHeaders[key] = value;
});
}
if (params.length > 0){
url = url + '?' + params.substring(0, params.length - 1);
}
var requestObj = {
uri : url,
method : requestMethod,
headers : apiHeaders,
body : JSON.stringify(reqBody),
encoding: "utf8",
allowGetBody : true,
throwHttpErrors : false
};
var result = await new InsertRecordsAPI().makeAPICall(requestObj);
console.log(result.status)
console.log(result.response)
}
async getToken(token) {
if(listener == 0) {
window.addEventListener("storage", function(reponse) {
if(reponse.key === "access_token" && (reponse.oldValue != reponse.newValue || reponse.oldValue == null)){
location.reload();
}
if(reponse.key === "access_token"){
sessionStorage.removeItem("__auth_process");
}
}, false);
listener = 1;
if(sessionStorage.getItem("__auth_process")) {
sessionStorage.removeItem("__auth_process");
}
}
["granted_for_session", "access_token","expires_in","expires_in_sec","location","api_domain","state","__token_init","__auth_process"].forEach(function (k) {
var isKeyExists = localStorage.hasOwnProperty(k);
if(isKeyExists) {
sessionStorage.setItem(k, localStorage[k]);
}
localStorage.removeItem(k);
});
var valueInStore = sessionStorage.getItem("access_token");
var tokenInit = sessionStorage.getItem("__token_init");
if(tokenInit != null && valueInStore != null && Date.now() >= parseInt(tokenInit) + 59 * 60 * 1000){ // check after 59th minute
valueInStore = null;
sessionStorage.removeItem("access_token");
}
var auth_process = sessionStorage.getItem("__auth_process");
if ((valueInStore == null && auth_process == null) || (valueInStore == 'undefined' && (auth_process == null || auth_process == "true"))) {
var accountsUrl = "https://accounts.zoho.com/oauth/v2/auth"
var clientId;
var scope;
var redirectUrl;
if(token != null) {
clientId = token.clientId;
scope = token.scope;
redirectUrl = token.redirectUrl;
}
var fullGrant = sessionStorage.getItem("full_grant");
var grantedForSession = sessionStorage.getItem("granted_for_session");
if(sessionStorage.getItem("__token_init") != null && ((fullGrant != null && "true" == full_grant) || (grantedForSession != null && "true" == grantedForSession))) {
accountsUrl += '/refresh';
}
if (clientId && scope) {
sessionStorage.setItem("__token_init", Date.now());
sessionStorage.removeItem("access_token");
sessionStorage.setItem("__auth_process", "true");
window.open(accountsUrl + "?" + "scope" + "=" + scope + "&"+ "client_id" +"=" + clientId + "&response_type=token&state=zohocrmclient&redirect_uri=" + redirectUrl);
["granted_for_session", "access_token","expires_in","expires_in_sec","location","api_domain","state","__token_init","__auth_process"].forEach(function (k) {
var isKeyExists = localStorage.hasOwnProperty(k);
if(isKeyExists){
sessionStorage.setItem(k, localStorage[k]);
}
localStorage.removeItem(k);
});
valueInStore = sessionStorage.getItem("access_token");
}
}
if(token != null && valueInStore != 'undefined'){
token.accessToken = valueInStore;
}
return token.accessToken;
}
async makeAPICall(requestDetails) {
return new Promise(function (resolve, reject) {
var body, xhr, i;
body = requestDetails.body || null;
xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open(requestDetails.method, requestDetails.uri, true);
for (i in requestDetails.headers) {
xhr.setRequestHeader(i, requestDetails.headers[i]);
}
xhr.send(body);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
resolve(xhr);
}
}
})
}
}
I need to send dynamic data and I'm a little fuzzy on how to use the async functions and populate the reqBody variable.
I have tried things like
makeAPICall(myjson);
.then((data) => { console.log(data)})
But I'm not getting anything returned. Any response is welcome. My thanks in advance.
I am trying to fix this script to automatically connect people you may know on Linkedin based on User roles (CEO e.t.c), Can someone help me fix this, Below is my code; I have tried the script on almost all browsers, Somebody help fix this.
var userRole = [
"CEO",
"CIO"
];
var inviter = {} || inviter;
inviter.userList = [];
inviter.className = 'button-secondary-small';
inviter.refresh = function () {
window.scrollTo(0, document.body.scrollHeight);
window.scrollTo(document.body.scrollHeight, 0);
window.scrollTo(0, document.body.scrollHeight);
};
inviter.initiate = function()
{
inviter.refresh();
var connectBtns = $(".button-secondary-small:visible");
//
if (connectBtns == null) {var connectBtns = inviter.initiate();}
return connectBtns;
};
inviter.invite = function () {
var connectBtns = inviter.initiate();
var buttonLength = connectBtns.length;
for (var i = 0; i < buttonLength; i++) {
if (connectBtns != null && connectBtns[i] != null) {inviter.handleRepeat(connectBtns[i]);}
//if there is a connect button and there is at least one that has not been pushed, repeat
if (i == buttonLength - 1) {
console.log("done: " + i);
inviter.refresh();
}
}
};
inviter.handleRepeat = function(button)
{
var nameValue = button.children[1].textContent
var name = nameValue.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
function hasRole(role){
for(var i = 0; i < role.length; i++) {
// cannot read children of undefined
var position = button.parentNode.parentNode.children[1].children[1].children[0].children[3].textContent;
var formatedPosition = position.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var hasRole = formatedPosition.indexOf(role[i]) == -1 ? false : true;
console.log('Has role: ' + role[i] + ' -> ' + hasRole);
if (hasRole) {
return hasRole;
}
}
return false;
}
if(inviter.arrayContains(name))
{
console.log("canceled");
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else if (hasRole(userRole) == false) {
console.log("cancel");
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else if (button.textContent.indexOf("Connect")<0){
console.log("skipped");
inviter.userList.push(name); // it's likely that this person didn't join linkedin in the meantime, so we'll ignore them
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else {
console.log("added");
inviter.userList.push(name);
button.click();
}
};
inviter.arrayContains = function(item)
{
return (inviter.userList.indexOf(item) > -1);
};
inviter.usersJson = {};
inviter.loadResult = function()
{
var retrievedObject = localStorage.getItem('inviterList');
var temp = JSON.stringify(retrievedObject);
inviter.userList = JSON.parse(temp);
};
inviter.saveResult = function()
{
inviter.usersJson = JSON.stringify(inviter.userList);
localStorage.setItem('inviterList', inviter.usersJson);
};
setInterval(function () { inviter.invite(); }, 5000);
`
When I try executing this, I get the following error:
VM288:49 Uncaught TypeError: Cannot read property 'children' of undefined
at hasRole (<anonymous>:49:71)
at Object.inviter.handleRepeat (<anonymous>:66:11)
at Object.inviter.invite (<anonymous>:30:69)
at <anonymous>:108:35
Any ideas as to how to fix it?
I'm trying to setup a file upload through rest for large files. The function below is taking care of chunking but I need to be able to recognize the last chunk because my rest call changes to /finishUpload() in order to commit the save.
Right now I'm only able to figure out when the blob is empty but I can't figure out how to determine the last iteration before the blob is empty.
This is the script I'm using below to parse my files.
export default function parseFile(file, options) {
var opts = typeof options === 'undefined' ? {} : options;
var fileSize = file.size;
var chunkSize = typeof opts['chunk_size'] === 'undefined' ? 64 * 1024 : parseInt(opts['chunk_size']);
var binary = typeof opts['binary'] === 'undefined' ? false : opts['binary'] == true;
var offset = 0;
var self = this; // we need a reference to the current object
var readBlock = null;
var chunkReadCallback = typeof opts['chunk_read_callback'] === 'function' ? opts['chunk_read_callback'] : function() {};
var chunkErrorCallback = typeof opts['error_callback'] === 'function' ? opts['error_callback'] : function() {};
var success = typeof opts['success'] === 'function' ? opts['success'] : function() {};
var onLoadHandler = function(evt) {
if (evt.target.result == "") {
console.log('Chunk empty, call finish');
success(file);
return;
}
if (evt.target.error == null) {
chunkReadCallback(evt.target.result, offset).then(function() {
offset += evt.target.result.length;
readBlock(offset, chunkSize, file);
});
} else {
chunkErrorCallback(evt.target.error);
return;
}
if (offset >= fileSize) {
success(file);
return;
}
}
readBlock = function(_offset, _chunkSize, _file) {
var r = new FileReader();
var blob = _file.slice(_offset, _chunkSize + _offset);
console.log("blob size:", blob.size, "offset:", _offset, "C+S:",_chunkSize + _offset)
r.onload = onLoadHandler;
if (binary) {
r.readAsArrayBuffer(blob);
} else {
r.readAsText(blob);
}
}
readBlock(offset, chunkSize, file);
}
Codepen
Why not rely on the filesize, i.e. check the condition _chunkSize + _offset >= fileSize?
You can use progress, loadend events to process File object one byte at a time; define a variable where processing should be paused or stopped at nth byte, every nth byte, or any byte during processing of file.
var str = "abcdefghijklmnopqrstuvwxyz";
var type = "application/octet-stream";
var data = new Blob([], {
type: type
});
var filename = "file.txt";
var reader = new FileReader();
var complete = false;
var beforeEnd = false;
var stopAt = str.length - 1;
function handleFile(e) {
data = new File([data.slice()
, str.slice(data.size, data.size + 1)]
, filename, {
type: type,
lastModifiedDate: new Date()
});
}
function handleRead(e) {
if (data.size <= str.length && !complete) {
if (data.size === stopAt && !beforeEnd) {
beforeEnd = true;
var r = new FileReader();
r.onloadend = function() {
alert(`stopAt: ${stopAt}\n`
+`data.size: ${data.size}\n`
+`result at stopAt: ${r.result[stopAt -1]}`);
reader.readAsArrayBuffer(data);
}
r.readAsText(data);
} else {
reader.readAsArrayBuffer(data)
}
} else {
console.log("complete")
}
}
function handleProgress(e) {
if (data.size <= str.length && !complete) {
var read = new FileReader();
read.onload = function() {
if (!complete) {
console.log(read.result);
if (read.result.length === str.length) {
complete = true;
console.log(data);
}
}
}
read.readAsText(data);
}
}
reader.addEventListener("load", handleFile);
reader.addEventListener("loadend", handleRead);
reader.addEventListener("progress", handleProgress);
reader.readAsArrayBuffer(data);
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);
}
How can I check if cookies are being blocked using JavaScript?
Write a cookie and then read it...
for example:
function readCookie(cname) {
a = trim(document.cookie);
res = '';
while(a != '') {
cookiename = a.substring(0,a.search('='));
cookiewert = a.substring(a.search('=')+1,a.search(';'));
if(cookiewert == '' || a.search(';')==-1) {
cookiewert = a.substring(a.search('=')+1,a.length);
} else {
cookiewert = a.substring(a.search('=')+1,a.search(';'));
}
if(cname == trim(cookiename)){
res = cookiewert;
return (res);
}
i = a.search(';')+1;
if(i == 0){i = a.length}
a = a.substring(i,a.length);
}
return(res)
}
function checkSessionCookie() {
//write cookie
document.cookie = 'sessioncookieallowed=true;';
var check = readCookie('sessioncookieallowed');
}
call function checkSessionCookie();