Controling console.log client side - javascript

I'm working on a site that takes fairly long to build/deploy. I sometimes need information that is only available server-side for debugging. Using console.log is annoying since adding a console.log in the code and building takes too long.
But I also don't want the site to always log that information to the console.
My plan was to have a wrapper function for console.log, that checks if there is e.g dev_config set in localStorage.
For example to activate certain verbose levels that then show respective logs, or log only in certain sections.
Would this have a significant impact on performance of the site?
For instance something like this:
const devLog = (message) => {
devConfig = JSON.parse(localStorage.getItem('dev_config'))
if (devConfig != null) {
// ...
// other checks (set devMode to true)
// ...
if (devMode === true) {
const now = new Date()
const hours = now.getHours()
const min = (now.getMinutes() + '').padStart(2, '0')
const sec = (now.getSeconds() + '').padStart(2, '0')
console.log(`[${hours}:${min}:${sec}] `, message)
}
}
}
PS: I am aware of the built-in browser dev tools and I am using them in most cases. But since the information in my current problem is server side, I don't think I can get with the dev tools what I need.

You could overwrite console.log but that could annoy you later on. I prefer to have my own logger like your devLog function. It's more explicit.
As #Barmar suggested in the comments you could instead check the localStorage on load instead of on every call. I have something similar to the below in a few projects of mine:
{
let devConfig = JSON.parse(localStorage.getItem('dev_config'));
devLog = (...args) => {
if (devConfig) {
const time = new Date().toLocaleTimeString()
console.log(`[${time}] `, ...args)
}
};
devLog.activate = () => {
devConfig = true;
localStorage.setItem('dev_config', true)
}
devLog.deactivate = () => {
devConfig = false;
localStorage.setItem('dev_config', false)
}
devLog.toggle = () => {
if ( devConfig ) {
devLog.deactivate()
} else {
devLog.activate()
}
}
}
Since when you're reading dev_config from the localStorage for the first time you'll get null it will start off deactivated - which seems like a good default to me.

Related

ANTLR4 Javascript get tree

Currently I am busy with parsers and tried ANTLR. I understand the grammar so far and now I wanted to implement it in javascript.
Here is a small but important snippet of my code.
if (selected == "Funktionen") {
console.log("You selected functions")
const chars = new antlr4.InputStream(data.stringToLex);
const lexer = new FunktionLexer(chars);
const tokens = new antlr4.CommonTokenStream(lexer);
const parser = new FunktionParser(tokens);
parser.buildParseTrees = true;
const tree = parser.start();
tree.accept(new Visitor());
}
My visitor looks like this
class Visitor {
visitChildren(ctx) {
if (!ctx) {
return;
}
if (ctx.children) {
return ctx.children.map(child => {
if (child.children && child.children.length != 0) {
return child.accept(this);
} else {
return child.getText();
}
});
}
}
}
I have oriented myself to this tutorial and everything works.
https://github.com/antlr/antlr4/blob/master/doc/javascript-target.md
http://lab.antlr.org/ Just hit on start and u will see what I mean.
The object of my tree I get back from my start() function with a right input looks like this:
The big problem is, I want to get the Tree and output it (at least in console log), like on the official ANTLR lab website.
The big problem is, I want to get the Tree and output it
The object returned by parser.start() is the tree of your parsed input. You don't need a visitor for this.
What you mean by "and output it", I do not know. Just print it to your console? That can be done by doing:
const tree = parser.start();
console.log(tree.toStringTree(parser));
// or if the line above doesn't work, try:
// console.log(tree.toStringTree());

(Edited) I am having an issue with my application not giving in-game currency

[Edited - Last time I forgot to add the code]
So i'm having an issue with my code not adding in-game currency to the user after they buy a product. All the internal testing and money work is well- the purchase goes through and the money is received. There is just an issue with adding the currency, which are in this case emblems, to the user. Unfortunately my friend wrote this code who no longer works on the project and I'm not very familiar with any of this, as I normally do UI stuff. Please let me know if I should upload any other images or provide any further information.
I'm not sure how far along it gets in the code before it breaks, but what I do know is using a button for testing and adding the same asyncstorage.getitem and setitem works when an onpress for a button. Again, I am very unfamiliar with all of this stuff so let me know what I need to provide to help.
This code works:
AsyncStorage.getItem('emblems').then(value =>{AsyncStorage.setItem('emblems', '10')})
This code doesn't work
<BuyBox Price='$0.99' EN='1 Emblem' onPress={async () => {
if (this.state.offerings != null) {
const pkg = this.state.offerings.emblems.availablePackages.find(offering => offering.identifier === 'ispy_1_emblems');
if (pkg) {
const {customerInfo, productIdentifier} = await Purchases.purchasePackage(pkg);
if (typeof customerInfo.entitlements.active.my_entitlement_identifier !== "undefined") {
console.log("purchase successful")
AsyncStorage.getItem('emblems').then(value => {
if (value == null){
AsyncStorage.setItem('emblems', '1');
} else {
AsyncStorage.setItem('emblems', (Number(value) + 1).toString());
}
})
}
}
}
}}/>
You forget to mention which library you using.
I'm guessing you're using Revenuecat react-native-purchases, you can print pkg in console to see many details including currency
const {customerInfo, productIdentifier} = await Purchases.purchasePackage(pkg);
use try to test it, I think it will giving error for the first time when there's no value on emblems
try {
const value = await AsyncStorage.getItem("emblems");
if (value !== null) {
AsyncStorage.setItem("emblems", (Number(value) + 1).toString());
} else {
//first time in
await AsyncStorage.setItem("emblems", "1"); //Set 1
}
} catch (e) {
// error reading value
await AsyncStorage.setItem("emblems", "1");
}

Google Cloud Function delete Firestore document

I tested my javascript on local emulator. There are 2 actions, if Timestamp is over 7 days delete the document (this is working like a charm <3) but the else is he should check the "img" its a normal url if this return 404 then delete like on the first action, this is ONLY working on local emulator, when i deploy it to Cloud function its not working anymore and just says e.g "Function execution took 7957 ms, finished with status: 'ok'" BUT on local it works as expected.
exports.removeExpiredDocuments = functions.region('europe-west1').runWith({ memory: "256MB" }).pubsub.schedule("every 1 hours").onRun(async (context) => {
const db = admin.firestore();
const now = firestore.Timestamp.now();
const ts = firestore.Timestamp.fromMillis(now.toMillis() - 604800000); // 168 hours in milliseconds = 604800000
const snaps = await db.collection("products").get();
let promises = [];
snaps.forEach((snap) => {
// functions.logger.info("forEachSnap");
if (snap.data().created_time < ts) {
promises.push(snap.ref.delete());
functions.logger.info('[Time] older than 7 Days ' + snap.data().name, { structuredData: true });
} else {
requesth(snap.data().img, function (error, response) {
functions.logger.info('[img] error: ' + error, { structuredData: true });
if (response.statusCode == 404) {
promises.push(snap.ref.delete());
functions.logger.info('[img] not found ' + snap.data().name, { structuredData: true });
}
});
}
});
return Promise.all(promises);
});
Working on local emulator (with same url as in firebase) and i expect that its working on cloud aswell
firestore.Timestamp.now() does not return a value that can be correctly compared to other Timestamps with < and > comparisons. That means this line of code doesn't do what you think:
if (snap.data().created_time < ts)
If you want to compare two Timestamp objects with each other, you must take another approach. One way is to convert them both to milliseconds with toMillis() and compare those integers with each other. Or convert them to Date and compare them with the appropriate object method.

Script runs smoothly from start to finish, but the expected result doesn't happen

The project aims to study a new social media:
https://booyah.live/
My needs are:
1 - Collect data from profiles that follow a specific profile.
2 - My account use this data to follow the collected profiles.
3 - Among other possible options, also unfollow the profiles I follow.
The problem found in the current script:
The profile data in theory is being collected, the script runs perfectly until the end, but for some reason I can't specify, instead of following all the collected profiles, it only follows the base profile.
For example:
I want to follow all 250 profiles that follow the ID 123456
I activate the booyahGetAccounts(123456); script
In theory the end result would be my account following 250 profiles
But the end result I end up following only the 123456 profile, so the count of people I'm following is 1
Complete Project Script:
const csrf = 'MY_CSRF_TOKEN';
async function booyahGetAccounts(uid, type = 'followers', follow = 1) {
if (typeof uid !== 'undefined' && !isNaN(uid)) {
const loggedInUserID = window.localStorage?.loggedUID;
if (uid === 0) uid = loggedInUserID;
const unfollow = follow === -1;
if (unfollow) follow = 1;
if (loggedInUserID) {
if (csrf) {
async function getUserData(uid) {
const response = await fetch(`https://booyah.live/api/v3/users/${uid}`),
data = await response.json();
return data.user;
}
const loggedInUserData = await getUserData(loggedInUserID),
targetUserData = await getUserData(uid),
followUser = uid => fetch(`https://booyah.live/api/v3/users/${loggedInUserID}/followings`, { method: (unfollow ? 'DELETE' : 'POST'), headers: { 'X-CSRF-Token': csrf }, body: JSON.stringify({ followee_uid: uid, source: 43 }) }),
logSep = (data = '', usePad = 0) => typeof data === 'string' && usePad ? console.log((data ? data + ' ' : '').padEnd(50, '━')) : console.log('━'.repeat(50),data,'━'.repeat(50));
async function getList(uid, type, follow) {
const isLoggedInUser = uid === loggedInUserID;
if (isLoggedInUser && follow && !unfollow && type === 'followings') {
follow = 0;
console.warn('You alredy follow your followings. `follow` mode switched to `false`. Followings will be retrieved instead of followed.');
}
const userData = await getUserData(uid),
totalCount = userData[type.slice(0,-1)+'_count'] || 0,
totalCountStrLength = totalCount.toString().length;
if (totalCount) {
let userIDsLength = 0;
const userIDs = [],
nickname = userData.nickname,
nicknameStr = `${nickname ? ` of ${nickname}'s ${type}` : ''}`,
alreadyFollowedStr = uid => `User ID ${uid} already followed by ${loggedInUserData.nickname} (Account #${loggedInUserID})`;
async function followerFetch(cursor = 0) {
const fetched = [];
await fetch(`https://booyah.live/api/v3/users/${uid}/${type}?cursor=${cursor}&count=100`).then(res => res.json()).then(data => {
const list = data[type.slice(0,-1)+'_list'];
if (list?.length) fetched.push(...list.map(e => e.uid));
if (fetched.length) {
userIDs.push(...fetched);
userIDsLength += fetched.length;
if (follow) followUser(uid);
console.log(`${userIDsLength.toString().padStart(totalCountStrLength)} (${(userIDsLength / totalCount * 100).toFixed(4)}%)${nicknameStr} ${follow ? 'followed' : 'retrieved'}`);
if (fetched.length === 100) {
followerFetch(data.cursor);
} else {
console.log(`END REACHED. ${userIDsLength} accounts ${follow ? 'followed' : 'retrieved'}.`);
if (!follow) logSep(targetList);
}
}
});
}
await followerFetch();
return userIDs;
} else {
console.log(`This account has no ${type}.`);
}
}
logSep(`${follow ? 'Following' : 'Retrieving'} ${targetUserData.nickname}'s ${type}`, 1);
const targetList = await getList(uid, type, follow);
} else {
console.error('Missing CSRF token. Retrieve your CSRF token from the Network tab in your inspector by clicking into the Network tab item named "bug-report-claims" and then scrolling down in the associated details window to where you see "x-csrf-token". Copy its value and store it into a variable named "csrf" which this function will reference when you execute it.');
}
} else {
console.error('You do not appear to be logged in. Please log in and try again.');
}
} else {
console.error('UID not passed. Pass the UID of the profile you are targeting to this function.');
}
}
This current question is a continuation of that answer from the link:
Collect the full list of buttons to follow without having to scroll the page (DevTools Google Chrome)
Since I can't offer more bounty on that question, I created this one to offer the new bounty to anyone who can fix the bug and make the script work.
Access account on Booyah website to use for tests:
Access by google:
User: teststackoverflowbooyah#gmail.com
Password: quartodemilha
I have to admit that it is really hard to read your code, I spent a lesser amount of time rewriting everything from scratch.
Stated that we need a code piece to be cut/pasted in the JavaScript console of web browsers able to store some data (i.e. expiration of followings and permanent followings) we need some considerations.
We can consider expiration of followings as volatile data: something that if lost can be reset to 1 day later from when we loose this data. window.localStorage is a perfect candidate to store these kind of data. If we change web browser the only drawback is that we loose the expiration of followings and we can tolerate to reset them to 1 day later from when we change browser.
While to store the list of permanent followings we need a permanent store even if we change web browser. The best idea that came to my mind is to create an alternative account with which to follow the users we never want to stop following. In my code I used uid 3186068 (a random user), once you have created your own alternative account, just replace the first line of the code block with its uid.
Another thing we need to take care is error handling: API could always have errors. The approach I chosen is to write myFetch which, in case of errors, retries twice the same call; if the error persists, probably we are facing a temporary booyah.live outage. Probably we just need to retry a bit later.
To try to provide a comfortable interface, the code blocks gathers the uid from window.location: to follow the followers of users, just cut/paste the code block on tabs opened on their profiles. For example I run the code from a tab open on https://booyah.live/studio/123456?source=44.
Last, to unfollow users the clean function is called 5 minutes later we paste the code (to not conflict with calls to follow followers) and than is executed one hour later it finishes its job. It is written to access the localStorage in an atomic way, so you can have many of them running simultaneously on different tabs of the same browser, you can not care about it. The only thing you need to take care it that when the window.location changes, all the JavaScript events in the tab are reset; so I suggest to keep a tab open on the home page, paste the code block on it, and forget about this tab; it will be the tab responsible of unfollowing users. Then open other tabs to do what you need, when you hit a user you want to follow the followers, paste the block on it, wait the job is finished and continue to use the tab normally.
// The account we use to store followings
const followingsUID = 3186068;
// Gather the loggedUID from window.localStorage
const { loggedUID } = window.localStorage;
// Gather the CSRF-Token from the cookies
const csrf = document.cookie.split("; ").reduce((ret, _) => (_.startsWith("session_key=") ? _.substr(12) : ret), null);
// APIs could have errors, let's do some retries
async function myFetch(url, options, attempt = 0) {
try {
const res = await fetch("https://booyah.live/api/v3/" + url, options);
const ret = await res.json();
return ret;
} catch(e) {
// After too many consecutive errors, let's abort: we need to retry later
if(attempt === 3) throw e;
return myFetch(url, option, attempt + 1);
}
}
function expire(uid, add = true) {
const { followingsExpire } = window.localStorage;
let expires = {};
try {
// Get and parse followingsExpire from localStorage
expires = JSON.parse(followingsExpire);
} catch(e) {
// In case of error (ex. new browsers) simply init to empty
window.localStorage.followingsExpire = "{}";
}
if(! uid) return expires;
// Set expire after 1 day
if(add) expires[uid] = new Date().getTime() + 3600 * 24 * 1000;
else delete expires[uid];
window.localStorage.followingsExpire = JSON.stringify(expires);
}
async function clean() {
try {
const expires = expire();
const now = new Date().getTime();
for(const uid in expires) {
if(expires[uid] < now) {
await followUser(parseInt(uid), false);
expire(uid, false);
}
}
} catch(e) {}
// Repeat clean in an hour
window.setTimeout(clean, 3600 * 1000);
}
async function fetchFollow(uid, type = "followers", from = 0) {
const { cursor, follower_list, following_list } = await myFetch(`users/${uid}/${type}?cursor=${from}&count=50`);
const got = (type === "followers" ? follower_list : following_list).map(_ => _.uid);
const others = cursor ? await fetchFollow(uid, type, cursor) : [];
return [...got, ...others];
}
async function followUser(uid, follow = true) {
console.log(`${follow ? "F" : "Unf"}ollowing ${uid}...`);
return myFetch(`users/${loggedUID}/followings`, {
method: follow ? "POST" : "DELETE",
headers: { "X-CSRF-Token": csrf },
body: JSON.stringify({ followee_uid: uid, source: 43 })
});
}
async function doAll() {
if(! loggedUID) throw new Error("Can't get 'loggedUID' from localStorage: try to login again");
if(! csrf) throw new Error("Can't get session token from cookies: try to login again");
console.log("Fetching current followings...");
const currentFollowings = await fetchFollow(loggedUID, "followings");
console.log("Fetching permanent followings...");
const permanentFollowings = await fetchFollow(followingsUID, "followings");
console.log("Syncing permanent followings...");
for(const uid of permanentFollowings) {
expire(uid, false);
if(currentFollowings.indexOf(uid) === -1) {
await followUser(uid);
currentFollowings.push(uid);
}
}
// Sync followingsExpire in localStorage
for(const uid of currentFollowings) if(permanentFollowings.indexOf(uid) === -1) expire(uid);
// Call first clean task in 5 minutes
window.setTimeout(clean, 300 * 1000);
// Gather uid from window.location
const match = /\/studio\/(\d+)/.exec(window.location.pathname);
if(match) {
console.log("Fetching this user followers...");
const followings = await fetchFollow(parseInt(match[1]));
for(const uid of followings) {
if(currentFollowings.indexOf(uid) === -1) {
await followUser(uid);
expire(uid);
}
}
}
return "Done";
}
await doAll();
The problem: I strongly suspect a booyah.live API bug
To test my code I run it from https://booyah.live/studio/123456?source=44.
If I run it multiple times I continue to get following output:
Fetching current followings...
Fetching permanent followings...
Syncing permanent followings...
Following 1801775...
Following 143823...
Following 137017...
Fetching this user followers...
Following 16884042...
Following 16166724...
There is bug somewhere! The expected output for subsequent executions in the same tab would be:
Fetching current followings...
Fetching permanent followings...
Syncing permanent followings...
Fetching this user followers...
After seeking the bug in my code without success, I checked booyah.live APIs: if I navigate following URLs (the uids are the ones the code continue to follow in subsequent executions)
https://booyah.live/studio/1801775
https://booyah.live/studio/143823
https://booyah.live/studio/137017
https://booyah.live/studio/16884042
https://booyah.live/studio/16166724
I can clearly see I follow them, but if I navigate https://booyah.live/following (the list of users I follow) I can't find them, neither if I scroll the page till the end.
Since I do exactly the same calls the website does, I strongly suspect the bug is in booyah.live APIs, exactly in the way they handle the cursor parameter.
I suggest you to open a support ticket to booyah.live support team. You could use the test account you provided us: I already provided you the details to do that. ;)

ShowOpenDialog not working on recent versions of electron-js

I'm new on electronjs and developing a small application that reads a json file and build a small html form and return the values entered by the user.
So I've developed small scripts in javascript that link to html 'button' tags to call dialogs so that a user can enter directories, files and save the final form. Everything works nicely... on electronjs "^3.1.13". But if I'm updating to a recent version of the lib ("^8.2.5"), then all my cool ShowOpenDialog don't work at all. Any clue of what happens?
Here is the script to open a folder if it helps:
{
let myName = document.currentScript.getAttribute('name');
const ipc = require('electron').ipcRenderer;
let asyncBtn = document.querySelector('#folder-selector-'+myName);
let replyField = document.querySelector('#folder-selector-content-'+myName);
let onButtonClick = function() {
const { dialog } = require('electron').remote;
let dialogOptions = {
title: "Choisir un dossier:",
properties: ['openDirectory','promptToCreate'],
};
dialog.showOpenDialog(
dialogOptions,
fileNames => {
if (fileNames === undefined) {
console.log("No file selected");
} else {
console.log('file:', fileNames[0]);
replyField.value = fileNames[0];
}
})
};
asyncBtn.addEventListener("click", onButtonClick);
}
Thanks a lot for any help.
Apart from the fact that the call to dialog.showOpenDialog has indeed been updated in recent versions of Electron, and returns a promise instead of making use of a callback function, there is another flaw in your updated code: reading the above-mentioned documentation page shows that getCurrentWindow() is not a method of dialog; it can be obtained from remote instead, so you have to add it explicitely:
const { dialog, getCurrentWindow } = require('electron').remote;
then simply call it from inside dialog.showOpenDialog:
dialog.showOpenDialog( getCurrentWindow(), dialogOptions).then(result => {
but this is an error you could have caught yourself by looking at the DevTools's console, which would display:
TypeError: dialog.getCurrentWindow is not a function
Recent version of showOpenDialog receives two arguments: optional BrowserWindow, and options as second argument. It returns promise and not requires callback.
https://github.com/electron/electron/blob/8-x-y/docs/api/dialog.md#dialogshowopendialogbrowserwindow-options
So you need to change you callback logic to promises.
let onButtonClick = function() {
const { dialog } = require('electron').remote;
let dialogOptions = {
title: "Choisir un dossier:",
properties: ['openDirectory','promptToCreate'],
};
dialog.showOpenDialog(
dialogOptions
).then((fileNames)=>{
if (fileNames === undefined) {
console.log("No file selected");
} else {
console.log('file:', fileNames[0]);
replyField.value = fileNames[0];
}
}).catch(err=>console.log('Handle Error',err))
};
asyncBtn.addEventListener("click", onButtonClick);
thanks a lot Vladimir. So I've tried to update my code as explained, updating electron package to version 8.2.5 and modifying the script as you explained but it's not going any better. If I got it well, this code should be correct, but doesn't work on electron 8.2.5. Any error you still see on this?
{
let myName = document.currentScript.getAttribute('name');
const ipc = require('electron').ipcRenderer;
let asyncBtn = document.querySelector('#folder-selector-'+myName);
let replyField = document.querySelector('#folder-selector-content-'+myName);
let onButtonClick = function() {
const { dialog } = require('electron').remote;
let dialogOptions = {
title: "Choisir un dossier:",
properties: ['openDirectory','promptToCreate']
};
dialog.showOpenDialog( dialog.getCurrentWindow(), dialogOptions).then(result => {
if(!result.canceled) {
replyField.value = result.filePaths[0];
}
}).catch(err => {
console.log(err)
})
};
asyncBtn.addEventListener("click", onButtonClick);
}
Ok, finally got it. Apart from the most appreciated help I had, I missed
"webPreferences": {
nodeIntegration: true
}
in the main.js to make it work.
The discovering of the Developer Tools were of great help as well :)
Now everything is fine again. Thanks a lot!

Categories