Socket IO – appending messages to the correct location

I am creating a real time chat application, where users can chat with other users in real time. All users are stored in my MongoDB Database. I’m using React on the frontend, and node with express on the backend.

When users connect to the socket server, they’re added to the users array stored on the server, like so:

var users = [
   // User objects
   {username: test1, id: 32d2, socketId: ue3e9393kd3},
   {username: test2, id: 322, socketId: ude3e339393kd3},
   {username: test3, id: 333dw2, socketId: ud33e9393kd3},
]

On the frontend, when chatting with a user, they first select the other users name from a messages list, and it redirects to the route chat/otheruserid. So whatever user they want to chat with, the other users id would be stored in the url.

When submitting the message to send, it is received by the server and sent back to the client. I currently use the following code to send message events.

io.to(user.socketId).emit('send message', msg)

This socket id would be obtained by filtering the users array to find a specific user (i.e the one they selected on the frontend to chat with)

The problem I have, is if using the example above, if the user test1 had a chat with test2, and a chat with test3, if both test2 and test3 sent a message to user test1, how would I be able to append the message to the DOM of the correct chat screen.

For example, if test2 and test3 send messages to test1 at approximately the same time, and test1 was on the chat page with test2, then you could append the message from test2 to the current page’s DOM. However if when on the chat page with test2, and test3 sends a message, how would I append the message from test3 to the chat screen located at the path: chat/test3id, so when the user eventually goes to this path, the new message has been appended to the dom? Thanks.

How do I add a event listener for IPCmain.on?

I’m trying to make a button for my app where when you press it, a “note card” pops up. But right now when I’m trying to pass in “event” into one of the parameters for my IPCmain.on it is saying that its deprecated. What should I do?

main.js

const {app, BrowserWindow, ipcMain} = require('electron'); 

let mainWindow

function createWindow() {
  mainWindow = new BrowserWindow({width: 800, height: 600})

  mainWindow.loadFile('index.html')
}

app.whenReady().then(createWindow); 

app.on('window-all-closed', ()=> {
  app.quit();
})

app.on('activate', () => {
  if(BrowserWindow.getAllWindows().length === 0){
    createWindow(); 
  }
}); 

ipcMain.on('createNote', () => {
  const noteText = 'New Note'; 
  mainWindow.webContents.send('noteCreated', noteText);
});

create.js

const { ipcRenderer } = require('electron'); 

document.getElementById('createButton').addEventListener('click', ()=>{
  ipcRenderer.send('createNote'); 
}); 

ipcRenderer.on('noteCreated', (noteText) => {
  const noteContainer = document.getElementById('noteContainer'); 
  const noteCard = document.createElement('div'); 
  noteCard.textContent = noteText; 
  noteContainer.appendChild(noteCard); 
});  

index.html

<!DOCTYPE html>
<html lang="en">
  <head> 
    <meta charset = "UTF-8"> 
    <meta name = "viewport" content="width=device-width, initial-scale=1.0">
    <script src="create.js"> </script>
    <title> ToDo </title>
  </head>

  <body>
    <div id="Header">
      <h1> Header </h1>
      <button id="createButton"> Create </button>
    </div>
    <div id="noteContainer"></div>
  </body>
</html>

I tried to pass in my variable “createNote” from create.js into the parameter, but that didn’t work.

Disparate values, from URL and Javascript, into the Json of Node js Express app

Need help with the values from two separate places to make up the Json in the server.js of the Express app that will perform a PayPal sale.

The first values are from the URL and needs to go into the Json; as id in first entry, shown here as number 113; and name, shown here as rosie.

From the browser URL:

https://mywebsite.com/?id=113&name=daisy

Into the Json of server.js:

const chosenItems = new Map([
  [113, { item: 302, name: "daisy" }]
])

And the second value, shown here as number 302, is from the “item” id generated in a separate javascript, items.js

document.getElementById("item").innerHTML = arr[0].v;

The first id from the URL (113) and the item from the javascript (302) is essential, while the name from the URL will be a bonus.

Is there a simple way to get these values directly into this Json format?

Many thanks

Andi

I tried this for the first values from the URL:

app.get('/', function(req, res) {
  const id = req.query.id;
  const name = req.query.name;

  res.send([
    [ id, { 'name': name }]
  ])
});

which outputs this into the browser:

[["113",{"name":"daisy"}]]

but I can’t get it to only fill the Json in the server.js here:

const chosenItems = new Map([
  [id, { item: 'item', name: 'name' }]
])

to look / function like this

const chosenItems = new Map([
  [113, { item: 302, name: "daisy" }]
])

For the second value, I do not know how to integrate the “item” from the separate javascript, looked into a function for a getElementById but can’t get it to work and now stuck.

Would very much appreciate help!

Cannot handle bad decrypt error when encryption key is wrong node.js

I am creating 2 functions to encrypt / decrypt a file. for now, they work when the password is right (the encryption key is derived with a key derivation function from the password). But when the input password is wrong the function throws an error.

I want that when the password is wrong, the returning function resolves to false, handles the error and doesn’t crash the app.

this is the code:

function decrypt(path: string, password: string): Promise<boolean> {
  let reader = fs.createReadStream(path);
  let salt: Buffer, iv: Buffer;

  return new Promise((res, rej) => {
    reader.on("readable", () => {
      if (!salt) salt = reader.read(SALT_LENGTH);
      if (!iv) iv = reader.read(IV_LENGTH);

      if (salt && iv) {
        reader.close();
      }
    });

    reader.on("close", async () => {
      reader = fs.createReadStream(path, { start: SALT_LENGTH + IV_LENGTH });

      let key = await deriveKey(password, salt.toString("ascii"));
      let decipher = crypto.createDecipheriv("aes-256-cbc", key, iv);

      decipher.on("error", (err) => {
        rej(err);
        res(false);
      });

      let tmpPath = path + ".tmp";
      let writer = fs.createWriteStream(tmpPath);

      reader
        .pipe(decipher)
        .on("error", (err) => {
          rej(err);
          res(false);
        })
        .pipe(writer);

      writer.on("error", (err) => {
        rej(err);
        res(false);
      });

      writer.on("finish", async () => {
        await deleteFile(path);
        await renameFile(tmpPath, path);
        res(true);
      });
    });
  });
}

encrypt("test.txt", "password")
  .then(() => decrypt("test.txt", "passworddd"))
  .then(console.log);

i have tried everything:

  • wrapping the code in a try catch
  • on every pipe function add a error handler
  • add an error handler on the decipher

the example call does not log anyhing. it just crashes.

how can i handle the bad decrypt error?

how to change css file in html page using js if the user has a page width below a certain threshold

I want to change the css file depending on if the user is on mobile or on desktop. I couldnt find anything that actually works so i just restorted to using the js below to redirect the user to a diff html page with a diff css sheet. But i find this super inefficient. Does anyone know how I can make the css stylesheet change depending on the screen width property in the page?

<script type="text/javascript">
<!--
if (screen.width <= 699) {
document.location = "m_index.html";
}
//-->
</script>

       <!-- main css -->
       <link rel="stylesheet" href="master.css">
 
       <!-- CSS with media query -->
       <link rel="stylesheet"
             media="screen and (max-width: 360px)"
             href="small-screen.css">
       <link rel="stylesheet"
             media="screen and (min-width: 360px) and (max-width: 550px)"
             href="large-screen.css">

How to use color palettes for D3.js word cloud generator?

Say I have csv file where each row contains a string and an integer. For strings that are associated with larger numbers, they should be larger in size and have a darker hue in the wordcloud. For strings with smaller numbers, they should be smaller in size and be lighter in hue. However, my color palettes should be composed of multiple colors (e.g., yellow to orange to red). The number of hues for these colors varies on how many integers are in my csv (e.g., 1-100 or 1-1000).

I got stuck trying to create a js function that will alter the words in the wordcloud to have the appropiate size and hue based on a specific color palette that I choose.

Angular: How to extract PDF table into an array using pdfjs-dist

I have a PDF report like in the photo attached.
I am wanting to extract this into an array in my angular application.
Currently I have the following code:

  convertPDFToArray(pdfUrl: string): Promise<any[]> {
    return new Promise((resolve, reject) => {
      const loadingTask = pdfjsLib.getDocument(pdfUrl);
      loadingTask.promise.then((pdfDocument: any) => {
        const numPages = pdfDocument.numPages;
        const promises = [];

        for (let pageNumber = 1; pageNumber <= numPages; pageNumber++) {
          const page = pdfDocument.getPage(pageNumber);
          promises.push(page.then((pdfPage: any) => pdfPage.getTextContent()));
        }

        Promise.all(promises)
          .then((pageContents: any[]) => {
            const textArray = [];

            for (const content of pageContents) {
              for (const item of content.items) {
                textArray.push(item.str);
              }
            }

            resolve(textArray);
          })
          .catch((error) => {
            reject(error);
          });
      });
    });
  }

currently all it does it splits everything into an individual string and presents the array.
I am wanting something more structured so that I can work with it and extract the data properly. Wondering if anyone can help on this.

I have attached a pic of the doc (Apologies for the crossing out, I can’t present that)

example

Thanks

Solve captcha apart

I want to do what 2captcha or services like that do but on my own pc.
Is there any way to grab a captcha from a page from headless browser and display in a new tab, in order to solve it and send the success key back to the headless browser?
How does 2captcha do that?

I searched for some reverse engineering captcha’s guide but couldn’t understand how to detach them from the original site. I think there’s even some cross origin problems.

signInWithRedirect should redirect to a custom url / home url

I am using firebase signInWithRedirect in my react js web app , everything is working fine but when i use google sign in it redirect me again to the sign in page , insted i want it to redirect to the home page or to the original url before login.
for eg: let home url be xyz.com
and sign in page url be xyz.com/login
and when i use google signInWithRedirect it redirect me to xyz.com/login , instead i want it to redirect to xyz.com .

I am using this code for google sign in :

signInWithRedirect(auth, provider);

I also tried this for redirecting but this doesn’t help

signInWithRedirect(auth, provider);
getRedirectResult(auth)
      .then((result) => {
        navigate("/");
})

wrapAll() for each multiple selectors

I have some tabs each one with video player, some of them with chapters and some of them with a playlist.

As I’m not able to change the html structure I use this bit of code to get everything how I need it.

<script>

    jQuery(document).ready(function($){

//Chapters
    
    var chapters = document.querySelectorAll('.chapters');
          
        $(chapters).each(function(){
      
        $("<div class='chapter-title'></div>" ).insertBefore(this);
        });
    
                       
        $('.tab1 .chapter-title, .tab1 .chapters').wrapAll('<div class="chapter_wrapper" />');
                    
        $('.tab2 .chapter-title,.tab2 .chapters').wrapAll('<div class="chapter_wrapper" />');
    
//Playlists
    
    var playlists = document.querySelectorAll('.playlist');
    
    $(playlists).each(function(){
      
            $("<div class='playlist-title'></div>").insertBefore(this);
        });
                     
    $('.tab2 .playlist-title, .tab2 .playlist').wrapAll('<div class="playlist_wrapper" />');
                     
});
    
</script>

As the amount of tabs, players etc. will increase in future, I want to ask if there’s a way to use the wrapAll() method for each multiple selections that I don#t have to use the .tab1, .tab2, .tab3 etc. selectors everytime.

Would appreciate any help.

how to patch the data in mysql using the javasript json

Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!Now that you’re ready to post your question, read through it from start to finish. Does it make sense?

Add any details you missed and read through it again. Now is a good time to make sure that your title still describes the problem!

JS error being captured by something unexpected

I have an error in my code. When i tell my chrome dev tools to pause on uncaught exceptions, i do get a pause:
enter image description here

However, its coming from VM**** and not my file:
enter image description here

Why is my code not pausing here:
enter image description here

My build system is fairly complex, it’s webpack with some custom resolvers. How can i get the dev tools to pause on line 241 in my file not the
VM one.

Inertia.js – “usePage must be used within the Inertia component” error

I’m encountering an issue with Inertia.js where I’m getting the error “usePage must be used within the Inertia component.” I’m using usePage in my translations file (translations.jsx), and it seems to be causing a problem. The error is pointing to line 9 in usePage.ts.

Here’s the simplified snippet of my code:

// app.jsx
import React from "react";
import { createInertiaApp } from "@inertiajs/inertia-react";
import { resolvePageComponent } from "laravel-vite-plugin/inertia-helpers";
import { createRoot } from "react-dom/client";
import { InertiaProgress } from "@inertiajs/progress";
import { __ } from "./Shared/translations";

const appName = window.document.getElementsByTagName('title')[0]?.innerText || 'Laravel';

InertiaProgress.init({
    color: "#5e20d5",
    height: "10px",
    showSpinner: true,
});

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => resolvePageComponent(`./Pages/${name}.jsx`, import.meta.glob('./Pages/**/*.jsx')),
    setup({ el, App, props }) {
        const root = createRoot(el);

        root.render(<App {...props} />);

        window.__ = __;
    },
    progress: {
        color: '#4B5563',
    },
});
// translations.jsx
import { usePage } from "@inertiajs/react";

export function __(key, replace = {}) {
    const { language } = usePage().props;
    if (language && language[key]) {
        let translation = language[key];
        
        Object.keys(replace).forEach(function (key) {
            translation = translation.replace(':' + key, replace[key]);
        });

        return translation;
    } else {
        return key;
    }
}

Can someone please suggest an alternative approach or identify what might be causing this issue?

Any help would be greatly appreciated! Thank you.

Nextjs api try catch error with vercel sql

This is my other api code which works perfectly:

import excuteQuery from "@/lib/db";

const dotenv = require("dotenv");
dotenv.config();

export default async function Check(req, res) {
  try {
    res.json({ message: "Success" });
  } catch (error) {
    console.log(error);
    res.status(500).json({ error: "Internal server error" });
  }
}

But my other api gives error 500 when catch block executes in the end:

export default async function CreateAccount(req, res) {
  try {
    const content = req.body;
    console.log("content", content);

    if (!content) {
      res.status(400).json({ error: "Content cannot be empty." });
      return;
    }

    const email = content.email;
    console.log("email", email);

    const password = content.password;
    console.log("pass", password);

    const encryptedPassword = encryptData(password, secretKey, iv);
    console.log("encryptedPassword", encryptedPassword);

    const fullName = content.firstName + " " + content.lastName;
    console.log("fullName", fullName);

    const result = await excuteQuery({
      query: "INSERT INTO createacc(email, password, username) VALUES(?, ?, ?)",
      values: [email, password, fullName],
    });

    console.log("ttt", result);
    res.json({
      message: content.email,
      name: fullName,
      token: jwt.sign(
        {
          email: content.email,
          name: fullName,
        },
        KEY
      ),
    });
  } catch (error) {
    console.log(error);
    res.status(500).json({ error: "Internal server error" });
  }
}

I have tried many other ways by checking which part is causing the problem using console log and im pretty sure its the query one
I ran the same query with hardcoded values in vercel query section and it works but mine fails each time here is the db.js code :

import { sql } from "@vercel/postgres";
export default async function excuteQuery({ query, values }) {
  try {
    const client = await sql.connect();
    const results = await client.query(query, values);
    client.release(); // Release the connection after use
    return results;
  } catch (error) {
    return { error: "Executing query" };
  }
}