question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to correctly load sesion?

See original GitHub issue

Hi, I have tried to write a script to save and load sesions, but I have checked in the app the open sesions and it keeps creating new sesions, this is my code:

const { IgApiClient } = require('/home/pi/node_modules/instagram-private-api');
const { readFile } = require('fs');
const { DateTime, Duration } = require('/home/pi/node_modules/luxon');

const { StickerBuilder } = require('/home/pi/node_modules/instagram-private-api/dist/sticker-builder');
const { promisify } = require('util');
const readFileAsync = promisify(readFile);

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

const IG_USERNAME= process.argv[2];
const IG_PASSWORD= process.argv[3];
var val= process.argv[4];
var comment= process.argv[5];
var mediapp= process.argv[6];
var comentid= process.argv[7];
console.log(IG_USERNAME);

const ig = new IgApiClient();
(async () => {
  //**        hier beginnt die  LOGIN    **
  const ig = new IgApiClient();
  ig.state.generateDevice(IG_USERNAME);
  ig.request.end$.subscribe(async () => {
    const serialized = await ig.state.serialize();
    delete serialized.constants;
    const data = JSON.stringify(serialized); 
    fakeSave(data);
  });
  if (fakeExists(IG_USERNAME)) {
    await ig.state.deserialize(fakeLoad(IG_USERNAME));
  }
  //await ig.qe.syncLoginExperiments(); // this will get the encryption key
  // This call will provoke request.end$ stream
  await ig.account.login(IG_USERNAME, IG_PASSWORD); 
  //**        hier endet die LOGIN    **
})();

function fakeSave(data) {
  console.log(IG_USERNAME);
  fs.writeFile(`/home/pi/js/cookies/${IG_USERNAME}.json`, data, function(err, result)
    {
     if(err) console.log('error', err);
   });
  //return data;
};

function fakeExists(IG_USERNAME) {
  var myLog = (`/home/pi/js/cookies/${IG_USERNAME}.json`);
  if(fs.existsSync(myLog)){
    console.log('The file exists');
    return true;
  }
  else{
    console.log(myLog);
    console.log('The file does not exist');
    return false;
  }
}
function fakeLoad(IG_USERNAME) {
  var json = require(`/home/pi/js/cookies/${IG_USERNAME}.json`); //(with path)
  return json;
}

What do you think I am missing?

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:1
  • Comments:17

github_iconTop GitHub Comments

5reactions
Nerixyzcommented, Aug 10, 2021

Use fs/promises instead of fs

So you’d import the functions like this: const { readFile, writeFile, access } = require('fs/promises').

For the R/W functions

Tip: Use promises.

Save

/** 
 * @param {string} state The stringified state
 */
function save(state) {
  // you _can_ do some error handling but make sure to attach a catch handler
  writeFile(MY_PATH, state).catch(console.error);
}

Load

async function load() {
  const rawState = await readFile(MY_PATH);
  // you might want to wrap this in a try-catch since this can throw
  return JSON.parse(rawState);
}

Exists

function exists() {
  return access(MY_PATH).then(() => true).catch(() => false);
}

You’d then do it like this:

ig.request.end$.subscribe(async () => {
  const serialized = await ig.state.serialize();
  delete serialized.constants;
  const data = JSON.stringify(serialized);
  save(data);
});
if (await exists()) {
  await ig.state.deserialize(await load());
}

You will always login after loading the state.

Do something like this

/**
 * @returns {boolean} `true` if the session is valid/exists - `false` if the session is invalid
 */
async function tryLoadSession() {
  if (await exists()) {
    try {
      await ig.state.deserialize(await load());
      // try any request to check if the session is still valid
      await ig.account.currentUser();
      return true;
    } catch (e) {
      return false;
    }
  }
  return true;
}

// in your main function
if(!(await tryLoadSession())) {
  await ig.account.login(IG_USERNAME, IG_PASSWORD);
}

Some other things

  • Avoid doing something like this: require('/home/pi/node_modules/instagram-private-api'). You should instead do require('instagram-private-api'). Node will automatically resolve the location of the module (starting from your package.json and going to the global node_modules.
  • Avoid doing require(/home/pi/js/cookies/${IG_USERNAME}.json). This will load the json once and then cache it. So it will never observe changes to the file.
2reactions
omidh28commented, Sep 29, 2021

@OmkoBass what are the definitions of loadPassword and compare functions?

It does not really matter, It just checks if Instagram account’s password has been changed or not.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How To Play Session ( Complete Tutorial ) - YouTube
This is a complete in depth tutorial on how to play Session and customize your gameplay settings. Video is separated into chapters for...
Read more >
How to Use Sessions and Session Variables in PHP - Code
Session handling is a key concept in PHP that enables user information to be persisted across all the pages of a website or...
Read more >
How to load Rails Session from session_id? - Stack Overflow
Just do request.session_options[:id] = "whatever you want" in a before_action filter and Rails will use that session_id to load the Session ...
Read more >
What is Session Stickiness | Pros and Cons of Using ... - Imperva
With sticky sessions, a load balancer assigns an identifying attribute to a user, typically by issuing a cookie or by tracking their IP...
Read more >
Different between session.get() and session.load()
1. session.load() · It will always return a “proxy” (Hibernate term) without hitting the database. In Hibernate, proxy is an object with the ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found