node.js / firebase functions) I’m having a hard time comparing the two times

I used ‘firebase functions’ to create a schedule function that periodically calls and deletes files in storage when they are old.
I want to compare the file’s ‘timeCreated’ with the current time and make it delete after 10 minutes more since the file was created.
The following is part of my code.

functions/index.js

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const firebase = admin.initializeApp();

exports.scheduledFunction = functions
  .region("asia-northeast3")
  .pubsub.schedule("every 1 minutes")
  .onRun(async (context) => {
    try {
      const bucket = firebase.storage().bucket();

      // get files
      const [filesArray] = await bucket.getFiles({
        prefix: "chat/files", // storage file path
      });

      const TIMESTAMP_AGO = Date.now() - 600000; // before 10min 
      const DELETE_OPTIONS = { ignoreNotFound: true }; // ??
.
.
      filesArray.map(async (file) => {
        let metadata;

        try {
          // metadata
          [metadata] = await file.getMetadata();
          const { temporaryHold, eventBasedHold, timeCreated } = metadata;

          const dispose = timeCreated < TIMESTAMP_AGO; // is file older check

           if (dispose) {
              await file.delete(DELETE_OPTIONS); 
              console.log("delete file");
            }
        }
  }
}

I would like to check if the creation time is more than 10 minutes by comparing the time below.
However, ‘dispose’ is always returned as false.

const TIMESTAMP_AGO = Date.now() - 600000;
const dispose = timeCreated < TIMESTAMP_AGO; // always false

The following is the log output from the firebase functions console.

timeCreated: 2022-05-10T14:46:08.014Z, TIMESTAMP_AGO: 1652196423265 

What should I do to compare the time correctly?

Is there a way to get conditional formatting rules set in a sheet in the apps script console?

I have a sheet that have some conditional formatting rules that I set manually, the thing is this sheet is created by a script, so I want it to have these rules on creation and I don’t want to make a template sheet that holds these rules for performance reasons, so Here is an image of a rule:

image of a conditional formatting rule

so I need a way to get the range and rule as text so I can rebuild them programmatically using apps script, so I built this code:

function getConditionalFormatting(){
  sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheetName");
  rules = sheet.getConditionalFormatRules();
  for(var i = 0; i < rules.length; i++){
      console.log(rules[i].toString());
  }
}

and this is the output I get instead of the rule itself:
output from the code embedded above

so anyone got an idea on how can I get them as the rule itslef in the first image instead of “ConditionalFormatRule”.

Electron – ContextBridge passthrough not working inside react

I’ve been digging through questions, gh issues and articles for the last couple of days to no avail; so hopefully someone can help.

The project is an old-ish electron app that I’m not familiar with at all, and I’ve been scratching my head trying to get contextIsolation working. Relevant snippets below (some have been adjusted to remove useless/identifying elements):

main.js

mainWindow = new BrowserWindow({
    width: 1280,
    height: 800,
    minWidth: 1280,
    minHeight: 800,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
      nodeIntegration: false,
      contextIsolation: true,
      enableRemoteModule: true
    },
    autoHideMenuBar: true
  });

preload.js

const { ipcRenderer, contextBridge } = require("electron");

contextBridge.exposeInMainWorld("test_api", {
  send: (channel, data) => {
    ipcRenderer.send(channel, data);
  },
  receive: (channel, func) => {
    ipcRenderer.on(channel, (event, ...args) => func(...args));
  }
});

src/index.js

import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { Routes } from "./react/router";
import store from "./react/store";

import "./react/assets/scss/app.scss";
import "react-toastify/dist/ReactToastify.min.css";

// Needed for bootstrap dropdown button seen in
// Export as... button on survey page
import "bootstrap";
import "bootstrap/dist/js/bootstrap.js";

ReactDOM.render(
  <Provider store={store}>
    <Routes />
  </Provider>,
  document.getElementById("root")
);

src/react/App.js

import React, { useEffect, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";

...

const App = ({ children }) => {
  const location = useLocation();

  const appRef = useRef();
  const dispatch = useDispatch();

  const visibleDropZone = useSelector(state => state.app.showDropZone);

  useEffect(() => {
    dispatch(getSettings()); // <breakpoint here>
  }, [dispatch, location]);

  return (
    <div className="app-wrapper">
       ...
    </div>
  );
};
export default App;

getSettings()

export const getSettings = () => dispatch => {
  dispatch({ type: setting_types.GET_SETTINGS_REQUEST });
  test_api.send("test", "hello");
  window.test_api.send("test", "hello");
};

When I hit the breakpoint marked, I can’t access test_api or window.test_api; and likewise getSettings() errors appropriately without the breakpoint.

I can share any other required snippets, but I can’t publish the full repo so please understand that 🙂

Best approach to list all images from a specific directory and send to renderer process using Electron

I have a function in the main process that read all images that are in a directory and send it to the renderer process as a base64string. I have around 20 images each one with 15kb approximately however it is taking a lot to load them all (6seconds~7seconds) I wonder what are the best approaches to read multiple images and send to the renderer process.

The following code promisify the readFile method from node’s fs.

const readFromFile = (filePath) => {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, (err, data) => {
      if (err) {
        console.log(err);
        reject(err);
      } else {
        resolve(data.toString("base64"));
      }
    });
  });
};

and then I wait till all images are read to send it back to the renderer process after adding the images to an array of objects.

return Promise.all(videoThumbPromises.concat(dataThumbPromises)).then(
    (result) => {
      let amountOfImages = dataThumbPromises.length;
      for (let i = 0; i < dataThumbPromises.length; i++) {
        readyToUploadClips[i].thumbnail_video = result[i];
        readyToUploadClips[i].thumbnail_data = result[i + amountOfImages];
      }
      return readyToUploadClips;
    }
  );

The videoThumbPromises and dataThumbPromises are arrays of Promises generated by the readFromFile function.

disabled browser back button google chrome and edge

window.history.pushState(null, null, location.href);

        window.addEventListener('popstate', () => {
            history.go(1);
            alert('Back button is not allowed.');
        });

Show message when browser back button clicked on chrome and edge latest version above code snippet is not working.

On Firefox it works perfectly.

Please suggest any workaround.

Thanks.

Math problem trying to convert from java to node Js

What would the syntax be to write the following php code in node?

public class RSAKey
{
    static BigInteger applyToValue (BigInteger value, String key_part1, String key_part2)
    {
        BigInteger result = BigInteger.ZERO;
        BigInteger part1 = new BigInteger (key_part1, 16);
        BigInteger part2 = new BigInteger (key_part2, 16);
 
        if (part1.equals (BigInteger.ZERO) || part2.equals (BigInteger.ZERO)
             || value.compareTo (BigInteger.ZERO) <= 0)
            return result;
 
        while (! value.equals (BigInteger.ZERO))
        {
            result = result.multiply (part2);
            BigInteger[] div = value.divideAndRemainder (part2);
            value = div[0];
            result = result.add (div[1].modPow (part1, part2));
        }
 
        return result;
    }
}

I’ve gotten this far declaring everything but don’t know how to add the while loop and array

 var result = 0n;
       const part1 =  BigInt(key_part1, 16);
        const part2 = BigInt(key_part2, 16);
        var value = BigInt('0x736968746b63617263726576656e6c6c6977736c6f6f66756f7937342d35392d62332d31392d61312d3237');
 
           result = result * part2;
            var remainder = BigInt(value % part2);
            var modded = 0n;
            modded = bigInt(remainder).modPow(part1, part2);
            result = bigInt(result) + bigInt(modded);```

Problem using useRoutes when redirecting with params

I am trying to set up my project for the first time using useRoutes and lazy loading with children. But I am having a problem that it won’t load the children when redirected to that site? The Home page works perfectly fine.

https://codesandbox.io/s/great-rgb-ippuob?file=/src/Page/Home/index.js
Home path=”/”

import React from "react";
import { Link } from "react-router-dom";
const Home = () => {
  return (
    <>
      <h1>Hello Welcome to my beauty page</h1>
      <Link to="/1">click me</Link>
    </>
  );
};
export default Home;

Children:

import React from "react";
import { useParams } from "react-router-dom";
const Id = () => {
  const { id: loadingId } = useParams();
  return <h1>Right now you are on the side of: {loadingId}</h1>;
};
export default Id;

App.js:

import "./styles.css";
import Route from "./Routes";
import { Suspense } from "react";
export default function App() {
  return (
    <>
      <div className="App">
        <Suspense fallback={<p>Loading...</p>}>
          <Route />
        </Suspense>
      </div>
    </>
  );
}

Routes:

import { useRoutes } from "react-router-dom";
import React from "react";
export default function Router() {
  return useRoutes([
    {
      path: "/",
      element: <Home />,
      children: [{ path: "/:id", element: <Id /> }]
    }
  ]);
}
const Home = React.lazy(() => import("./Page/Home"));
const Id = React.lazy(() => import("./Page/Id"));

And in Index I have

<BrowserRouter>
      <App />
    </BrowserRouter>

How to get a response from nodemailer using netlify functions?

I am using netlify functions to send an email from the frontend and it works fine… as in it does send the email.

However on the clientside (browser) I can’t get any response. I need a basic response that would allow me to do a if (status==="success") displayMessage() but I can’t seem to get any response on the browser.

I get this message Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data However on sending the request via POSTMAN I get a response ‘Email Sent Succesfully’ which is the body part of the callback response.

Here’s the function that I am using at .netlify/functions/sendMail

const nodemailer = require("nodemailer");

exports.handler = function (event, context, callback) {
  const mailConfig = {
    host: "smtp.mailgun.org",
    port: 465,
    secure: true,
    auth: {
      user: process.env.MAILGUN_USER,
      pass: process.env.MAILGUN_PASSWORD,
    },
  };
  const transporter = nodemailer.createTransport(mailConfig);

  transporter.verify((error, success) => {
    if (error) {
      console.log(error);
    } else {
      console.log("Ready to send emails");
    }
  });

  const messageData = JSON.parse(event.body);

  const { email, name, mobile, message, subject, recipient } = messageData;

  console.log(messageData);

  const mailOptions = {
    from: email,
    to: recipient,
    subject: subject,
    text: message,
  };

  transporter.sendMail(mailOptions, (error, success) => {
    if (error) {
      console.log(error);
      callback(error);
    } else {
      console.log("email sent");
      callback(null, {
        statusCode: 200,
        body: "Email sent successfully",
      });
    }
  });
};


and on the client side I have this

const form = document.querySelector("#message");

const submitMessage = (event) => {
  event.preventDefault();

  const formData = new FormData(form);

  formData.append("recipient", "[email protected]");
  formData.append("subject", "Submission from website");

  const messageData = Object.fromEntries(formData);

  console.log(messageData);

  const url = ".netlify/functions/sendMail";
  const options = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(messageData),
  };

  fetch(url, options)
    .then((response) => response.json())
    .then((data) => console.log(data));
};

form.addEventListener("submit", submitMessage);

in the fetch request, I expected data to give me a response so I could trigger some action to display a success message..

Can someone advise me what I am doing wrong here?

How to send AES encrypted form data from postman?

I have two fields in my postman raw(json) i.e. username & password.

But the server only accepts AES encrypted data.

How can I send both fields encrypted.

Here is my postman pre-request script which I found from an blog although he is not using any fields which is why I’m confused.

postman pre-request Script

var CryptoJS = require("crypto-js");

// Generate random 16 bytes to use as IV
var IV = CryptoJS.lib.WordArray.random(16);

var keyString = 'TyJk8w3KsvKEekRs'
// finds the SHA-256 hash for the keyString
var Key = CryptoJS.SHA256(keyString);

function encrypt(data) {
    var val = CryptoJS.enc.Utf8.parse(JSON.stringify(data));
    var encrypted = CryptoJS.AES.encrypt(val, Key, { iv: IV }).toString();
    var b64 = CryptoJS.enc.Base64.parse(encrypted).toString(CryptoJS.enc.Hex);
    return b64;
}

var data = {"data": "how to send encrypted data"};

// Set local variables to postman
pm.variables.set("encrypted", encrypt(data));
pm.variables.set("IV", IV.toString());

Here is my postman form raw body

enter image description here

connect react with express

I am trying to connect an express backend with an react frontend as follows:

express code:

const app = express();
const port = 4000;
var router = express.Router();

app.use(bodyParser.urlencoded({ extended: false }));

app.listen(port, () => {
  //...
});

router.get('/handle',(request,response) => {
  response.send("...");
});
app.use("/", router);
module.exports = router;

React Code (inside a on-click function):

var myRequest = new XMLHttpRequest(),
  method = 'GET',
  url = 'http://127.0.0.1:4000';

  myRequest.open(method, url, true);
  
  myRequest.onerror = function() { 
    alert(`Network Error`);
  };
  myRequest.send();
  myRequest.onload = function() {
    alert(`success`);
  };

When i type http://127.0.0.1/handle into the browser, i get the correct response – so the express server is working. However, when i try to do the request with the react code, i always get “network error”. I really have no idea how to fix this, could anyone give me a hint? (React app is also running on localhost)

Query in mysql and express does not return what is expected

I have this query using express and mysql, the query in the database works and returns a column with the title “total” and a row with the sum of several expenses. I need to get the number that appears in the row to later show it on the screen with an ajax query, but with the code like this if I enter the link it does not return anything. What can I do? thanks

// GET total spended
router.get('/total', (req, res) => {
  mysqlConnection.query("SELECT (CTE.INCOME - CTE.OUTCOME) AS TOTAL FROM ( SELECT SUM(CASE WHEN operaciones.Tipo= 'Ingreso' THEN COALESCE(operaciones.Monto,0) ELSE 0 END) AS INCOME, SUM(CASE WHEN operaciones.Tipo='gasto' THEN COALESCE(operaciones.Monto,0) ELSE 0 END) AS OUTCOME FROM operaciones ) CTE;", (err, rows, fields) => {
                    
  if (!err) {
    res.json(rows);
  } else {
    console.log(err);
  }
  });
});

d3 zoom wheel scroll – How much a point moved on wheel scroll?

I wanted to know how much a point on svg moved when the user uses the wheel scroll to zoom in/out at a certain point in the svg.

for ex:

https://bl.ocks.org/mbostock/2206340

In my case, I need to track how much the center of the SVG moved(in both X and Y direction) when user uses d3 zoom scroll wheel to zoom in/out at a particular point considering the scale .