Duplicate data google apps script and javascript on upload files - javascript

I have a web app with GAS that create folders, upload files, set permissions and save the registers on a sheet.
Ocassionally the app duplicate files when the functions finished and duplicate a register in the google sheet. I don't know how to avoid this error, and the console does not show the error either.
What could be happening? How can I prevent this problem?
This is my code for server side functions:
function fileExists(idfileexist,folderId) {
var consulta = DriveApp.getFileById(idfileexist).getName()
var files = DriveApp.getFilesByName(consulta);
while (files.hasNext()) {
var file = files.next();
var folders = file.getParents();
if (folders.hasNext()) {
var folder = folders.next();
if (folder.getId() == folderId) {
return true;
}
}
}
return false;
}
function removepermission(id, user){
DriveApp.getFileById(id).removeEditor(user)
}
function appendrow(idfile,sheet,numsip,rut,timestamp,user,idfolder,input,ticket){
var values = SpreadsheetApp.openById(idfile);
var ss= values.getSheetByName(sheet);
ss.appendRow([numsip,rut,timestamp,user,idfolder,input,ticket])
}
function setpermisoswriter(id,array){
var file = DriveApp.getFileById(id)
var editors = file.getEditors();
if (editors.length > 0) {
for (var i = 0; i < array.length; i++) {
Drive.Permissions.insert({'role': 'writer','type': 'user','value': array[i]},id,{'sendNotificationEmails': 'false' });};};
}
function setpermisosreader(id,array){
var file = DriveApp.getFileById(id)
var editors = file.getEditors();
if (editors.length > 0) {
for (var i = 0; i < array.length; i++) {
Drive.Permissions.insert({'role': 'reader','type': 'user','value': array[i]},id,{'sendNotificationEmails': 'false' });};};
}
function setownerid(id,user){
Drive.Permissions.insert({'role': 'owner','type': 'user','value': user},id,{'sendNotificationEmails': 'false'})
}
function setpermisoread(id,user){
Drive.Permissions.insert({'role': 'reader','type': 'user','value': user},id,{'sendNotificationEmails': 'false'})
}
function setpermisowrite(id,user){
Drive.Permissions.insert({'role': 'writer','type': 'user','value': user},id,{'sendNotificationEmails': 'false' })
}
function permissionstotal(){
var parentFolderId = "parentFolderId";
var idfilesheet="idfilesheet";
var useractive = Session.getActiveUser().getEmail();
var jefes = ["EMAIL#EMAIL.COM","EMAIL#EMAIL.COM", "EMAIL#EMAIL.COM","EMAIL#EMAIL.COM"]
var userviewer="EMAIL#EMAIL.COM"
setpermisosreader(parentFolderId,jefes)
setpermisosreader(idfilesheet,jefes)
setpermisoread(idfilesheet,useractive)
removepermission(parentFolderId,useractive)
setpermisoread(parentFolderId, useractive)
//setpermisowrite(idfilesheet,userviewer)
//setpermisoread(parentFolderId,userviewer)
}
function addNewRow(array,obj) {
var admin ="ADMIN"
var useractive = Session.getActiveUser().getEmail();
var timestamp = new Date();
var sheet="DATA"
var jefes = ["EMAIL#EMAIL.COM","EMAIL#EMAIL.COM", "EMAIL#EMAIL.COM","EMAIL#EMAIL.COM"]
var userviewer="EMAIL#EMAIL.COM"
var parentFolderId = "parentFolderId";
var idfile="idfile"
var parentFolder = DriveApp.getFolderById(parentFolderId);
setpermisowrite(parentFolderId,useractive)
setpermisowrite(idfile,useractive)
var folderName = "SIP "+array.numsip+"/"+array.rut;
var foldercreated = parentFolder.getFoldersByName(folderName);
foldercreated = foldercreated.hasNext() ? foldercreated.next() : parentFolder.createFolder(folderName);
var idfolder= foldercreated.getId()
appendrow(idfile,sheet,array.numsip,array.rut,timestamp,useractive,idfolder,array.input,array.ticket)
setownerid(idfolder,admin)
setpermisosreader(idfolder,jefes)
//setpermisoread(idfolder,userviewer)
return obj.map(({fileName, mimeType, data}) => {
var blob = Utilities.newBlob(Utilities.base64Decode(data), mimeType, fileName);
var foldercode = foldercreated.createFile(blob).getId();
var archivo = fileExists(foldercode,idfolder);
if (archivo==false){
console.log("archivo ya existe")
}
else{
setpermisosreader(foldercode,jefes)
//setpermisoread(foldercode,userviewer)
setownerid(foldercode,admin)
removepermission(foldercode,useractive)
setpermisoread(foldercode,useractive)
removepermission(idfolder,useractive)
setpermisoread(idfolder,useractive)
console.log("archivo creado")
return foldercode
}
});
}
function getsip(sipCode){
//var sipCode= "123"
var url ="URL SHEET";
var ss2= SpreadsheetApp.openByUrl(url);
var ws2= ss2.getSheetByName("DATA")
var data2 = ws2.getRange(2, 1, ws2.getLastRow(), 2).getDisplayValues()
var idList = data2.map(function(r) {return r[0];});
var position = idList.indexOf(sipCode)
if (position >-1){
console.log (idList[position])
return "REPETIDO";
} else{
console.log ("2")
return "NOREPETIDO"
}
}
This is the Javascript code:
function enviardatosvalidados(){
var validacion=document.getElementById("sipcode").value
if(validacion=="REPETIDO"){
$('#modal2').modal('hide')
$('#modalval').modal('show')
}
else{
try{
enviardatos()
$("#generar").attr("disabled", true)
google.script.run.permissionstotal()
setTimeout(function(){
$("#generar").attr("disabled", false) ; }, 25000)
window.reloadTheWebApp = function() {
console.log('reloadTheWebApp ran');
var linkTag = document.getElementById('testLink');
linkTag.click();
}
} catch(error){
alert("Hubo un error.")
alert(error)
}
}
}
function enviardatos(){
if(validate()){
var sip = document.getElementById("numsip")
var rut = document.getElementById("rut")
var input = document.getElementById("input")
var ticket = document.getElementById("ticket")
var array ={numsip: sip.value,rut: rut.value, input:input.value,ticket:ticket.value}
const f = document.getElementById('files');
Promise.all([...f.files].map((file, i) => {
const fr = new FileReader();
return new Promise((r, rj) => {
fr.onload = (e) => {
const data = e.target.result.split(",");
r({fileName: f.files[i].name, mimeType: data[0].match(/:(\w.+);/)[1], data: data[1]});
}
fr.onerror = (e) => rj(e);
fr.readAsDataURL(file);
});
}))
.then(obj => google.script.run.withSuccessHandler(console.log).addNewRow(array, obj))
.catch(err => alert(err));
$('#modal2').modal('hide')
successnotification2()
setTimeout(function(){
$(':input').val('');
$("#modalcarpeta").modal('show'); }, 25000);
;
}
else{
$('#modal2').modal('hide')
}
}
function validate(){
var fieldsToValidate = document.querySelectorAll("#userform input, #userform select");
Array.prototype.forEach.call(fieldsToValidate, function(el){
if(el.checkValidity()){
el.classList.remove("is-invalid");
}else{
el.classList.add("is-invalid");
}
});
return Array.prototype.every.call(fieldsToValidate, function(el){
return el.checkValidity();
});
}
function checkRut(rut) {
// Despejar Puntos
var valor = rut.value.replace('.','');
// Despejar Guión
valor = valor.replace('-','');
// Aislar Cuerpo y Dígito Verificador
cuerpo = valor.slice(0,-1);
dv = valor.slice(-1).toUpperCase();
// Formatear RUN
rut.value = cuerpo + '-'+ dv
// Si no cumple con el mínimo ej. (n.nnn.nnn)
if(cuerpo.length < 7) { rut.setCustomValidity("RUT Incompleto"); return false;}
// Calcular Dígito Verificador
suma = 0;
multiplo = 2;
// Para cada dígito del Cuerpo
for(i=1;i<=cuerpo.length;i++) {
// Obtener su Producto con el Múltiplo Correspondiente
index = multiplo * valor.charAt(cuerpo.length - i);
// Sumar al Contador General
suma = suma + index;
// Consolidar Múltiplo dentro del rango [2,7]
if(multiplo < 7) { multiplo = multiplo + 1; } else { multiplo = 2; }
}
// Calcular Dígito Verificador en base al Módulo 11
dvEsperado = 11 - (suma % 11);
// Casos Especiales (0 y K)
dv = (dv == 'K')?10:dv;
dv = (dv == 0)?11:dv;
// Validar DV
if(dvEsperado != dv) { rut.setCustomValidity("RUT Inválido"); return false; }
// Validación
rut.setCustomValidity('');
}
function successnotification2(){
document.getElementById("save-success2").classList.remove("invisible");
setTimeout(function(){
document.getElementById("save-success2").classList.add("invisible")
},25000);
}
function getSip(){
var sipCode = document.getElementById("numsip").value;
google.script.run.withSuccessHandler(updatesipcode).getsip(sipCode);
}
function updatesipcode(sipCode){
document.getElementById("sipcode").value = sipCode;
}
document.getElementById("numsip").addEventListener("input",getSip)
Greetings and Thank You!

My old method it was very "heavy". When i set the permission to the folder and files, i had to call a lot of times the Driver API and the services. Other problem it was that the parent folder had a lot of folders and many files which made it take a long time to set the permissions to the user or revocate permissions.
My new method was create a folder with edit permission for the users and move the files and folder to the destiny folder for other users. My objetive was set the correct permissions for final users.This is my new code. The javascript's code doesn't have problems:
function moveFiles(sourceFileId, targetFolderId) {
var file = DriveApp.getFileById(sourceFileId);
file.getParents().next().removeFile(file);
DriveApp.getFolderById(targetFolderId).addFile(file);
}
function fileExists(idfileexist,folderId) {
var consulta = DriveApp.getFileById(idfileexist).getName()
var files = DriveApp.getFilesByName(consulta);
while (files.hasNext()) {
var file = files.next();
var folders = file.getParents();
if (folders.hasNext()) {
var folder = folders.next();
if (folder.getId() == folderId) {
return true;
}
}
}
return false;
}
function removepermission(id, user){
DriveApp.getFileById(id).removeEditor(user)
}
function appendrow(idfile,sheet,numsip,rut,timestamp,user,idfolder,exedoc,ticket){
var values = SpreadsheetApp.openById(idfile);
var ss= values.getSheetByName(sheet);
ss.appendRow([numsip,rut,timestamp,user,idfolder,exedoc,ticket])
}
function setpermisoswriter(id,array){
var file = DriveApp.getFileById(id)
var editors = file.getEditors();
if (editors.length > 0) {
for (var i = 0; i < array.length; i++) {
Drive.Permissions.insert({'role': 'writer','type': 'user','value': array[i]},id,{'sendNotificationEmails': 'false' });};};
}
function setpermisosreader(id,array){
var file = DriveApp.getFileById(id)
var editors = file.getEditors();
if (editors.length > 0) {
for (var i = 0; i < array.length; i++) {
Drive.Permissions.insert({'role': 'reader','type': 'user','value': array[i]},id,{'sendNotificationEmails': 'false' });};};
}
function setownerid(id,user){
Drive.Permissions.insert({'role': 'owner','type': 'user','value': user},id,{'sendNotificationEmails': 'false'})
}
function setpermisoread(id,user){
Drive.Permissions.insert({'role': 'reader','type': 'user','value': user},id,{'sendNotificationEmails': 'false'})
}
function setpermisowrite(id,user){
Drive.Permissions.insert({'role': 'writer','type': 'user','value': user},id,{'sendNotificationEmails': 'false' })
}
function addNewRow(array,obj) {
var admin ="ADMIN"
var useractive = Session.getActiveUser().getEmail();
var timestamp = new Date();
var sheet="DATA"
var parentFolderIdorigen ="PARENT FOLDER"
var idfile="IDSHEET"
var parentFolderorigen = DriveApp.getFolderById(parentFolderIdorigen)
var parentFolderIddestino = "ID"
setpermisowrite(idfile,useractive)
var folderName = "SIP "+array.numsip+"/"+array.rut;
var foldercreated = parentFolderorigen.getFoldersByName(folderName);
foldercreated = foldercreated.hasNext() ? foldercreated.next() : parentFolderorigen.createFolder(folderName);
var idfolder= foldercreated.getId()
appendrow(idfile,sheet,array.numsip,array.rut,timestamp,useractive,idfolder,array.input,array.ticket)
setownerid(idfolder,admin)
return obj.map(({fileName, mimeType, data}) => {
var blob = Utilities.newBlob(Utilities.base64Decode(data), mimeType, fileName);
var foldercode = foldercreated.createFile(blob).getId();
var archivo = fileExists(foldercode,idfolder);
if (archivo==false){
console.log("archivo ya existe")
}
else{
setownerid(foldercode,admin)
moveFiles(idfolder,parentFolderIddestino)
moveFiles(foldercode,idfolder)
console.log("archivo creado")
return foldercode
}
});
}
function getsip(sipCode){
var url ="URLSHEET";
var ss2= SpreadsheetApp.openByUrl(url);
var ws2= ss2.getSheetByName("DATA")
var data2 = ws2.getRange(2, 1, ws2.getLastRow(), 2).getDisplayValues()
var idList = data2.map(function(r) {return r[0];});
var position = idList.indexOf(sipCode)
if (position >-1){
console.log (idList[position])
return "REPETIDO";
} else{
console.log ("2")
return "NOREPETIDO"
}
}
Thanks to #Cooper and #ziganotschka for their comments.

Related

Error with setTimeout() function in for loop

I have the following script that I need to adjust so that each iteration has a one second pause before or after it executes the loop (it doesn't really matter which as long as the lag is there). I tried to add the setTimeout() function into the Try section of my code but it is still consistently failing. I also have tried to use "let" instead of "var" in the for loop but that failed as well. Any advice on how to add it in would be very appreciated. I'm having trouble finding an example of a similar setTimeout() function within a for loop online.
var ZB_DataExtension = 'C7_Unsubscribe_Response';
var ZB_DataExtension_Response = 'C7_Unsubscribe_Response';
var ZB_DataExtension_Logs = 'C7_CustUnsubscribe_Logs';
//Endpoint
var zeroBounceFullUrl = 'https://api.commerce7.com/v1//customer/CUST_ID';
//Extract results from Data Extension using DE key
var results = DataExtension.Init(ZB_DataExtension).Rows.Retrieve();
var updateDE_ZB = DataExtension.Init(ZB_DataExtension_Response);
var logsDE_ZB = DataExtension.Init(ZB_DataExtension_Logs);
var today = Format(Now(), "YYYY-MM-DD ");
for (var i = 0; i < results.length; i++ ) {
var item = results[i];
var zeroBounceUrlItem = "";
var ZB_Status = "";
var currentDateTime = Now();
try{
setTimeout(() => (
zeroBounceUrlItem = String(zeroBounceFullUrl).split("CUST_ID").join(String(item.C7_CustID));
var req = new Script.Util.HttpRequest(zeroBounceUrlItem);
req.emptyContentHandling = 0;
req.retries = 3;
req.continueOnError = true;
req.contentType = "application/json";
req.method = "PUT";
var payload='{"emailMarketingStatus": "Unsubscribed"}'
req.postData = payload ;
var resp = req.send();
var returnStatus= resp.returnStatus;
updateDE_ZB.Rows.Update({C7_API_Answer:String(returnStatus),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
if (returnStatus==0) {
updateDE_ZB.Rows.Update({C7_API_Answer:String("Success"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
}
else {
//ZB_Status = String("ERRO ZB API Call");
//var responseJson = Platform.Function.ParseJSON(String(resp.content));
updateDE_ZB.Rows.Update({C7_API_Answer:String("Failure"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
}
var randomID = Platform.Function.GUID();
logsDE_ZB.Rows.Add({log_guid:String(randomID),C7_CustID:String(item.C7_CustID),Status:String("Success"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem)});
), 1000*i}
catch (err) {
var randomID = Platform.Function.GUID();
ZB_Status = String("ERRO AMPScript");
logsDE_ZB.Rows.Add({log_guid:String(randomID),C7_CustID:String(item.C7_CustID),Status:String("Failure"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem)});
}
}
</script>
Your loop will execute the right number of times and at the right interval, but the value of the variable item inside the timeout might not be what you expect.
Try this:
for (var i = 0; i < results.length; i++ ) {
(function(i){
setTimeout(function(){
var item = results[i];
var zeroBounceUrlItem = "";
var ZB_Status = "";
var currentDateTime = Now();
try{
zeroBounceUrlItem = String(zeroBounceFullUrl).split("CUST_ID").join(String(item.C7_CustID));
var req = new Script.Util.HttpRequest(zeroBounceUrlItem);
req.emptyContentHandling = 0;
req.retries = 3;
req.continueOnError = true;
req.contentType = "application/json";
req.method = "PUT";
var payload='{"emailMarketingStatus": "Unsubscribed"}'
req.postData = payload ;
var resp = req.send();
var returnStatus= resp.returnStatus;
updateDE_ZB.Rows.Update({C7_API_Answer:String(returnStatus),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
if (returnStatus==0) {
updateDE_ZB.Rows.Update({C7_API_Answer:String("Success"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
}
else {
//ZB_Status = String("ERRO ZB API Call");
//var responseJson = Platform.Function.ParseJSON(String(resp.content));
updateDE_ZB.Rows.Update({C7_API_Answer:String("Failure"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
}
var randomID = Platform.Function.GUID();
logsDE_ZB.Rows.Add({log_guid:String(randomID),C7_CustID:String(item.C7_CustID),Status:String("Success"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem)});
catch (err) {
var randomID = Platform.Function.GUID();
ZB_Status = String("ERRO AMPScript");
logsDE_ZB.Rows.Add({log_guid:String(randomID),C7_CustID:String(item.C7_CustID),Status:String("Failure"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem)});
}
}, i*1000);
})(i);
}

Load Array with Excel Data and Return it

Can anyone assist me with loading an array with excel data and returning it as a function? This is my initial code:
var excel = require('exceljs');
var wb = new excel.Workbook();
var path = require('path');
var filePath = path.resolve(__dirname,'data.xlsx');
function signIn(){
var SignIn = [];
wb.xlsx.readFile(filePath).then(function(){
var sh = wb.getWorksheet("Sheet1");
for(var i = 1; i < 3; i++){
SignIn.push(sh.getRow(i).getCell(2).value);
}
});
return SignIn
}
Workbook.readFile is aynchronous, you need to use either a callback or promise type approach. Using promises we can try:
var excel = require('exceljs');
var wb = new excel.Workbook();
var path = require('path');
var filePath = path.resolve(__dirname,'data.xlsx');
function signIn() {
var SignIn = [];
return wb.xlsx.readFile(filePath).then( () => {
var sh = wb.getWorksheet("Sheet1");
for(var i = 1; i < 3; i++){
SignIn.push(sh.getRow(i).getCell(2).value);
}
return SignIn;
});
}
async function testReadData() {
try {
let data = await signIn();
console.log('testReadData: Loaded data: ', data);
} catch (error) {
console.error('testReadData: Error occurred: ', error);
}
}
testReadData();
Or you can use a callback type approach:
function signInWithCallback(callback) {
var SignIn = [];
wb.xlsx.readFile(filePath).then(function(){
var sh = wb.getWorksheet("Sheet1");
for(var i = 1; i < 3; i++){
SignIn.push(sh.getRow(i).getCell(2).value);
}
callback(SignIn);
});
}
signInWithCallback((data) => console.log('Callback: Data: ', data));

How do I call a vendor library from my main.js?

I have a basic electron app where I am trying to use vendor supplied js library. The example they supplied provides a static html page which includes their custom library and an example js file. This is the html
<HTML>
<HEAD>
<TITLE> MWD Library </TITLE>
</HEAD>
<BODY>
<h2>MWD Library Example</h2>
<input id="authAndConnect" type="button" value="authenticate and connect to stream" onclick="authenticateAndConnectToStream()" /></br></br>
<input id="clickMe" type="button" value="place position" onclick="placePosition()" /></br></br>
<input id="unsubscribeMe" type="button" value="unsubscribe" onclick="unsubscribe()" />
<input id="streamError" type="button" value="reconn to stream" onclick="reconnectToStream()" />
<input id="historicalData" type="button" value="historical data for GOLD" onclick="getHistoricalData()" />
<input id="goldExpiries" type="button" value="expiries for GOLD" onclick="getCurrentGoldExpiries()" /></br></br>
<input id="userTrades" type="button" value="active&completed trades" onclick="getUserTrades()" />
</BODY>
<SCRIPT SRC="jquery.ajax.js"></SCRIPT>
<SCRIPT SRC="mwdlib.js"></SCRIPT>
<SCRIPT SRC="app.js"></SCRIPT>
</HTML>
In the example above the button click calls authenticateAndConnectToStream in their example apps.js
//DEMO
//provide API key
MWDLibrary.config("dwR4jXn9ng9U2TbaPG2TzP1FTMqWMOuSrCWSK5vRIW7N9hefYEapvkXuYfVhzmdyFypxdayfkUT07HltIs4pwT0FIqEJ6PyzUz0mIqGj1GtmAlyeuVmSC5IcjO4gz14q");
//authenticate on MarketsWorld
var getAuthTokenParams = {email:"rtmarchionne#gmail.com", password:"Pitts4318AEM"};
var authenticateAndConnectToStream = function(){
MWDLibrary.getAuthDetails(getAuthTokenParams, function(authDetails) {
//optional: get older data
var marketsToSubscribeTo = ['GOLD', 'AUDNZD'];
for (var i = 0; i < marketsToSubscribeTo.length; i++){
MWDLibrary.getHistoricalData(marketsToSubscribeTo[i], function(response) {
console.log(response);
}, function(errorMessage) {
console.log(errorMessage);
});
}
//now you can connect to stream
MWDLibrary.connect(marketsToSubscribeTo, function() {
addMarketsListeners();
}, function(errorMessage) {
console.log(errorMessage);
});
}, function(errorMessage) {
console.log(errorMessage);
});
};
I want to call the same methods that start with MWDLibrary. from my main js like MWDLibrary.config("dwR4jXn9")
My main.js:
const electron = require('electron')
var path = require('path');
var countdown = require(path.resolve( __dirname, "./tradescaler.js" ) );
var mwd = require(path.resolve( __dirname, "./mwdlib.js" ) );
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const ipc = electron.ipcMain
let mainWindow
app.on('ready', _ => {
mainWindow = new BrowserWindow({
height: 360,
width: 700,
title: "TradeScaler Beta - Creative Solutions",
//frame: false,
alwaysOnTop: true,
autoHideMenuBar: true,
backgroundColor: "#FF7E47",
})
mainWindow.loadURL('file://' + __dirname + '/tradescaler.html')
mainWindow
//mainWindow.setAlwaysOnTop(true, 'screen');
mainWindow.on('closed', _ => {
mainWindow = null
})
})
ipc.on('countdown-start', _ => {
console.log('caught it!');
MWDLibrary.config();
countdown(count => {
mainWindow.webContents.send('countdown', count)
})
})
In my main.js above I get an error that says MWDLibrary is not defined.
Is it the structure of the library that is the problem? do i have to pass a window or modify the library?
Here is the library I'm trying to use:
(function(window){
'use strict';
function init(){
var MWDLibrary = {};
var transferProtocol = "https://"
var streamTransferProtocol = "https://"
var baseTLD = "www.marketsworld.com"
var basePort = ""
var streamBaseTLD = "www.marketsworld.com"
var streamPort = ""
var authToken = "";
var publicId = "";
var userLevel = "user";
var apiKey = "-";
var streamUrl = "";
var streamToken = "";
var subscribedChannels = [];
var streamEvents = {};
var offersWithExpiries = [];
var filteredExpiries = {};
var positions = {};
var evtSource;
MWDLibrary.config = function(apiUserKey){
apiKey = apiUserKey;
}
MWDLibrary.expiries = function(market){
return filteredExpiries[market];
}
MWDLibrary.connect = function(channelsToSubscribeTo, successHandler, errorHandler){
//console.log("Connecting...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
var dispatchUrl = streamTransferProtocol+streamBaseTLD+streamPort+'/api/dispatcher';
getJSON(dispatchUrl, apiKey, authToken, function(data){
var data_from_json = JSON.parse(data);
if(data_from_json.url){
var url = data_from_json.url+'/announce?callback=__callback&publicToken='+publicId+'&userLevel='+userLevel+'&_='+(new Date().getTime() / 1000);
getJSON(url, apiKey, authToken, function(data) {
var data_from_json = JSON.parse(data);
if(data_from_json.url){
streamUrl = data_from_json.url.substring(0,data_from_json.url.lastIndexOf("/user"));
streamToken = data_from_json.url.split("token=")[1];
MWDLibrary.subscribe(channelsToSubscribeTo, function(subscribeResponseData) {
evtSource = new EventSource(streamTransferProtocol+data_from_json.url);
evtSource.onopen = sseOpen;
evtSource.onmessage = sseMessage;
evtSource.onerror = sseError;
successHandler('connected');
return;
}, function(errorMessage) {
errorHandler(errorMessage);
return;
});
}
else{
//console.log(data);
errorHandler('Something went wrong.');
return;
}
}, function(status) {
//console.log(status);
errorHandler(status);
return;
});
}
else{
//console.log(data);
errorHandler('Something went wrong.');
return;
}
}, function(status) {
//console.log(status);
errorHandler(status);
return;
});
}
MWDLibrary.subscribe = function(channelsToSubscribeTo, successHandler, errorHandler){
//console.log("Subscribing...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
var channels = 'ALL|TEST|private.'+publicId;
if (channelsToSubscribeTo.length > 0){
var auxChannels = '';
if(subscribedChannels.length > 0){
channels = subscribedChannels[0];
for(var j = 1; j < subscribedChannels.length; j++){
channels = channels +'|'+subscribedChannels[j];
}
}
for(var i = 0; i < channelsToSubscribeTo.length; i++)
{
if(subscribedChannels.indexOf(channelsToSubscribeTo[i])==-1){
auxChannels = auxChannels+'|'+channelsToSubscribeTo[i]+'|'+channelsToSubscribeTo[i]+'.game#1';
}
}
channels = channels+auxChannels;
}
else{
if (subscribedChannels.length == 0)
{
channels = channels+'|GOLD|GOLD.game#1';
}
else{
channels = subscribedChannels[0];
for (var j = 1; j < subscribedChannels.length; j++){
channels = channels + '|' + subscribedChannels[j];
}
}
}
var subscribeUrl = streamTransferProtocol+streamUrl+'/user/stream/subscribe?callback=__callback&token='+streamToken+'&channels='+escape(channels)+'&_='+(new Date().getTime() / 1000);
//subscribe to channels
getJSON(subscribeUrl, apiKey, authToken, function(subscribeData) {
var subscribeData_from_json = JSON.parse(subscribeData);
subscribedChannels = subscribeData_from_json.channels;
//console.log(subscribedChannels);
for (var i = 0; i < subscribedChannels.length; i++)
{
if (subscribedChannels[i] == 'ALL')
{
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['heartbeat'] = new CustomEvent('ALL.heartbeat', {'detail':'-'});
streamEvents[subscribedChannels[i]]['status'] = new CustomEvent('ALL.status', {'detail':'-'});
continue;
}
if (subscribedChannels[i].lastIndexOf('private') > -1)
{
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['positions'] = new CustomEvent('PRIVATE.positions', {'detail':'-'});
streamEvents[subscribedChannels[i]]['balance'] = new CustomEvent('PRIVATE.balance', {'detail':'-'});
continue;
}
if (subscribedChannels[i].lastIndexOf('game') > -1)
{
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['expiry'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.expiry', {'detail':'-'});
streamEvents[subscribedChannels[i]]['spread'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.spread', {'detail':'-'});
streamEvents[subscribedChannels[i]]['payout'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.payout', {'detail':'-'});
streamEvents[subscribedChannels[i]]['offer'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.offer', {'detail':'-'});
continue;
}
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['value'] = new CustomEvent(subscribedChannels[i]+'.value', {'detail':'-'});
}
successHandler(subscribeData_from_json);
}, function(status) {
errorHandler(status);
});
}
MWDLibrary.unsubscribe = function(channelsToUnsubscribeFrom, successHandler, errorHandler){
//console.log("Unsubscribing...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
if(channelsToUnsubscribeFrom.length == 0){
errorHandler("Please select markets to unsubscribe from.");
return;
}
var channels = channelsToUnsubscribeFrom[0]+'|'+channelsToUnsubscribeFrom[0]+'.game#1';
for(var i = 1; i < channelsToUnsubscribeFrom.length; i++)
{
channels = channels+'|'+channelsToUnsubscribeFrom[i]+'|'+channelsToUnsubscribeFrom[i]+'.game#1';
}
var subscribeUrl = streamTransferProtocol+streamUrl+'/user/stream/unsubscribe?callback=__callback&token='+streamToken+'&channels='+escape(channels)+'&_='+(new Date().getTime() / 1000);
//subscribe to channels
getJSON(subscribeUrl, apiKey, authToken, function(unsubscribeData) {
var unsubscribeData_from_json = JSON.parse(unsubscribeData);
var unsubscribedChannels = unsubscribeData_from_json.channels;
for(var i = 0; i < unsubscribedChannels.length; i++)
{
var index = subscribedChannels.indexOf(unsubscribedChannels[i]);
if(index != -1) {
subscribedChannels.splice(index, 1);
}
}
//console.log(subscribedChannels);
successHandler(unsubscribeData_from_json);
}, function(status) {
errorHandler(status);
});
}
MWDLibrary.getAuthDetails = function(params, successHandler, errorHandler){
//console.log("getting auth token...");
var url = transferProtocol+baseTLD+basePort+'/api/v2/sessions';
postJSON(url, apiKey, authToken, params, function(data) {
var data_from_json = JSON.parse(data);
if (!data_from_json.error){
authToken = data_from_json.api_session_token.token;
publicId = data_from_json.api_session_token.user.public_id;
successHandler(data_from_json.api_session_token);
return;
}
else{
errorHandler(data_from_json.error);
return;
}
}, function(status) {
errorHandler(status);
return;
});
}
MWDLibrary.placePosition = function(params, successHandler, errorHandler){
//console.log("placing a position...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
var url = transferProtocol+baseTLD+basePort+'/api/v2/positions';
if(params.market == ''){
errorHandler('Market code is missing.');
return;
}
var position = positions[params.market];
if(!position || position.market_value <= 0){
errorHandler('No data for this market.');
return;
}
if(!params.offer_id || params.offer_id == ''){
errorHandler('Offer id is missing.');
return;
}
if(!params.resolution_at || params.resolution_at <= 0){
errorHandler('Expiry time is missing.');
return;
}
if(!params.type || params.type == ''){
errorHandler('Position type is missing.');
return;
}
if(!params.wager || params.wager <= 0){
errorHandler('Wager is missing.');
return;
}
position.offer_id = params.offer_id;
position.resolution_at = params.resolution_at;
position.type = params.type;
position.wager = params.wager;
//console.log(position);
postJSON(url, apiKey, authToken, position, function(data) {
var data_from_json = JSON.parse(data);
if (!data_from_json.error){
successHandler(data_from_json);
return;
}
else{
errorHandler(data_from_json.error);
return;
}
}, function(status) {
errorHandler(status+' - make sure all parameters are set correctly and wait 10 seconds between bets');
return;
});
}
MWDLibrary.getMarkets = function(successHandler, errorHandler){
//console.log("getting markets list...");
getJSON(transferProtocol+baseTLD+basePort+'/api/v2/markets.json', apiKey, authToken, function(data) {
var data_from_json = JSON.parse(data);
for (var i = 0; i < data_from_json.length; i++) {
var status = "closed";
if (data_from_json[i].market.next_open_time > data_from_json[i].market.next_close_time)
{
status = "open";
}
data_from_json[i].market.status = status;
}
successHandler(data_from_json);
}, function(status) {
errorHandler(status);
});
}
var sortedOffersWithExpiries = offers.sort(compareOffersBtOrder);
for (var i=0; i<sortedOffersWithExpiries.length;i++)
{
expiryValue = 0;
expiryResult = 0;
var expiriesCopy = sortedOffersWithExpiries[i].expiries;
for (var index = 0; index<expiriesCopy.length;index++)
{
expiryValue = expiriesCopy[index]
if (expiryValue > lastExpiry)
{
expiryResult = expiryValue
break
}
}
if (expiryResult != 0)
{
var tuple = {};
tuple.timestamp = expiryValue/1000;
tuple.offerId = sortedOffersWithExpiries[i].offer;
tuple.cutout = sortedOffersWithExpiries[i].cutout;
expiriesFinalList.push(tuple);
lastExpiry = expiryValue
}
}
return expiriesFinalList;
}
function compareOffersBtOrder(a,b) {
if (a.order < b.order)
return -1;
if (a.order > b.order)
return 1;
return 0;
}
})/*(window)-->*/;
You're missing the .js file extension at the end of mwdlib
And you may need to require it using the full system path, instead of a relative one.
var mwd = require(path.resolve( __dirname, "./mwdlib.js" ) );

Wait Callback and our result data to take another proccess out of this function

i have this class (product).
var Product = function () {
this.products = [];
this.priceFrom = null;
this.priceTo = null;
this.countDone = 0;
};
Product.prototype = {
constructor: Product,
getProductsByPriceRange: function (priceFrom, priceTo) {
var xhrUrl = "<?= base_url('market/products/xhr_product_price_range') ?>";
var xhrData = {price_from: priceFrom, price_to: priceTo};
var xhrType = "json";
var UtilsClass = new Utils();
UtilsClass.xhrConnection(xhrUrl, xhrData, xhrType, function (data) {
/* MY DATA IS HERE */
});
},
buildList:function (products) {
for (var i = 0; i < products.length; i++) {
var product = products[i];
console.log("product");
}
},
buildOne: function (product) {
}
};
/*....more classes */
And another piece of code (out of product class):
var fromPrice = data.from;
var toPrice = data.to;
var ProductClass = new Product();
var lastCountDone = ProductClass.countDone;
ProductClass.priceFrom = fromPrice;
ProductClass.priceTo = toPrice;
var myProducts = ProductClass.getProductsByPriceRange(ProductClass.priceFrom, ProductClass.priceTo);
My question is... can i wait callback of UtilsClass.xhrConnection (in first piece) and use generated data of callback in second piece of code (out of first piece).
Any ideas would be very valuable to me. Thank you!
var Product = function () {
this.products = [];
this.priceFrom = null;
this.priceTo = null;
this.countDone = 0;
};
Product.prototype = {
constructor: Product,
getProductsByPriceRange: function (priceFrom, priceTo) {
var xhrUrl = "<?= base_url('market/products/xhr_product_price_range') ?>";
var xhrData = {price_from: priceFrom, price_to: priceTo};
var xhrType = "json";
var UtilsClass = new Utils();
return new Promise(function(resolve, reject){
UtilsClass.xhrConnection(xhrUrl, xhrData, xhrType, function (data) {
/* MY DATA IS HERE */
resolve(data)
});
});
},
buildList:function (products) {
for (var i = 0; i < products.length; i++) {
var product = products[i];
console.log("product");
}
},
buildOne: function (product) {
}
};
While calling,
var fromPrice = data.from;
var toPrice = data.to;
var ProductClass = new Product();
var lastCountDone = ProductClass.countDone;
ProductClass.priceFrom = fromPrice;
ProductClass.priceTo = toPrice;
var myProducts = ProductClass.getProductsByPriceRange(ProductClass.priceFrom, ProductClass.priceTo).then(function(data){%your data will be available here%});

how to run at command through chrome serial api

i want to run at command at my hardware thorugh crome serial api
I use this Opensource code
https://github.com/GoogleChrome/chrome-app-samples/tree/master/servo
this working only for only integer
i want to pass string in the serial port my code is like following
var connectionId = -1;
function setPosition(position) {
var buffer = new ArrayBuffer(1);
var uint8View = new Uint8Array(buffer);
uint8View[0] = '0'.charCodeAt(0) + position;
chrome.serial.write(connectionId, buffer, function() {});
};
function setTxt(data) {
// document.getElementById('txt').innerHTML = data;
var bf = str2ab(data)
chrome.serial.write(connectionId, bf, function() {});
};
function str2ab(str) {
len = str.length;
var buf = new ArrayBuffer(len*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
function onRead(readInfo) {
var uint8View = new Uint8Array(readInfo.data);
var value1 = String.fromCharCode(uint8View[0])
var value = uint8View[0] - '0'.charCodeAt(0);
var rotation = value * 18.0;
// var dataarr = String.fromCharCode.apply(null, new Uint16Array(readInfo.data));
//alert(rotation);
if(uint8View[0])
document.getElementById('txt').innerHTML = document.getElementById('txt').innerHTML + value1;
document.getElementById('image').style.webkitTransform =
'rotateZ(' + rotation + 'deg)';
// document.getElementById('txt').innerHTML=uint8View[0];
// Keep on reading.
chrome.serial.read(connectionId, 1, onRead);
};
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
function onOpen(openInfo) {
connectionId = openInfo.connectionId;
if (connectionId == -1) {
setStatus('Could not open');
return;
}
setStatus('Connected');
setPosition(0);
chrome.serial.read(connectionId, 1, onRead);
};
function setStatus(status) {
document.getElementById('status').innerText = status;
}
function buildPortPicker(ports) {
var eligiblePorts = ports.filter(function(port) {
return !port.match(/[Bb]luetooth/);
});
var portPicker = document.getElementById('port-picker');
eligiblePorts.forEach(function(port) {
var portOption = document.createElement('option');
portOption.value = portOption.innerText = port;
portPicker.appendChild(portOption);
});
portPicker.onchange = function() {
if (connectionId != -1) {
chrome.serial.close(connectionId, openSelectedPort);
return;
}
openSelectedPort();
};
}
function openSelectedPort() {
var portPicker = document.getElementById('port-picker');
var selectedPort = portPicker.options[portPicker.selectedIndex].value;
chrome.serial.open(selectedPort, onOpen);
}
onload = function() {
var tv = document.getElementById('tv');
navigator.webkitGetUserMedia(
{video: true},
function(stream) {
tv.classList.add('working');
document.getElementById('camera-output').src =
webkitURL.createObjectURL(stream);
},
function() {
tv.classList.add('broken');
});
document.getElementById('position-input').onchange = function() {
setPosition(parseInt(this.value, 10));
};
document.getElementById('txt-input').onchange = function() {
setTxt(this.value);
// document.getElementById('txt').innerHTML = this.value;
};
chrome.serial.getPorts(function(ports) {
buildPortPicker(ports)
openSelectedPort();
});
};
string is the passing through serial but this command not run without enter press how to do it any one know
thanks in advance :)
need a \n at the end of string
example:
writeSerial( '#;Bit_Test;*;1;' + '\n' );
take a look at this project http://www.dataino.it/help/document_tutorial.php?id=13

Categories

Resources