text: import igprivateapi from 'instagram-private-api';
  import { readFile } from 'fs';
  import { promisify } from 'util';
  import { sleep, log } from './utils.js';
  
  const readFileAsync = promisify(readFile);
  
  const { IgApiClient } = igprivateapi;
  const client = new IgApiClient();
  
  /**
   * Login insta client
   */
  export const login = async() => {
      client.state.generateDevice(process.env.insta_username);
      await client.simulate.preLoginFlow();
      await client.account.login(process.env.insta_username, process.env.insta_password);
      process.nextTick(async () => await client.simulate.postLoginFlow());
  }
  
  const createCaption = (caption, post) => {
      return caption.replaceAll(':title:',post.title).replaceAll(':subreddit:', ).replaceAll(':author:', post.author).replaceAll(':link:', post.link).replaceAll(':upvotes:',post.ups).replaceAll(':ratio:',post.ratio).replaceAll('\r\n','\n');
  }
  
  /**
   * Post a video on the client's insta page
   * @param {Object} post The reddit post data
   * @returns result of upload
   */
  export const postVideo = async(post, _caption) => {
      // take a randomized break before upload, because insta will throw 400
      await sleep( Math.random() * 30_000 );
      
      log('instagram',`Attempting to upload '${post.title}'. |Path: '${post.download.path}' |Thumbnail path: ${post.download.thumbnail_path}`);
  
      const caption = createCaption(_caption, post);
  
      try {
          await client.publish.video({
              // read the file into a Buffer
              video: await readFileAsync(post.download.path),
              coverImage: await readFileAsync(post.download.thumbnail_path),
              caption: caption
          });
  
          return true;
      } catch (e) {
          log('instagram',e);
  
          return false;
      }
  }
  
  /**
   * Post a photo on the client's insta page
   * @param {Object} post The reddit post data
   * @returns result of upload
   */
  export const postPhoto = async(post, _caption) => {
      // take a randomized break before upload, because insta will throw 400
      await sleep( Math.random() * 60_000 );
      log('instagram',`Attempting to upload '${post.title}'. |Path: '${post.download.path}' `);
  
      const caption = createCaption(_caption, post);
  
      try {
          await client.publish.photo({
              // read the file into a Buffer
              file: await readFileAsync(post.download.path),
              // optional, default ''
              caption: caption
          });
  
          return true;
      } catch (e) {
          log('instagram',e);
          return false;
      }    
  }
  