facebook connections | ,connect on facebook | Cell 5 | Search

This code automates the process of finding new Facebook friends from scraped posts and connecting with them using Selenium.

Run example

npm run import -- "connect add friends facebook"

connect add friends facebook

var importer = require('../Core');
var glob = require('glob');
var path = require('path');
var fs = require('fs');
var runSeleniumCell = importer.import("run selenium cell");

var PROFILE_PATH = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
var project = PROFILE_PATH + '/Conversations';

var regexToArray = (ex, str, i = 0) => {
    var co = []; var m;
    while ((m = ex.exec(str)) && co.push(m[i])) ;
    return co;
}
                                         
function loadNewConnections() {
    // search posts
    if(fs.existsSync(path.join(project, 'new-friends.json'))) {
        return JSON.parse(fs.readFileSync(path.join(project, 'new-friends.json')).toString());
    }
    var posts = glob.sync('**/*-posts-*', {cwd: project})
        .map(f => path.join(project, f));
    var friends = posts.reduce((acc, p) => {
        importer.streamJson(p, [true, {emitPath: true}], (match) => {
            [].concat(match.value).forEach(m => {
                const url = regexToArray(/facebook.com\/.*/ig, m);
                if(url && url[0]) {
                    acc.push(url[0].replace(/\?fref.*|\?ref.*|\?rc=.*|\?hc_location.*/ig, ''));
                }
            })
        });
        return acc;
    }, []);
    var unique = [];
    for(let i = 0; i < friends.length / 1000; i++) {
        unique = unique.concat(friends.slice(i * 1000, i * 1000 + 1000).filter((u, i, arr) => arr.indexOf(u) === i))
    }
    fs.writeFileSync(path.join(project, 'new-friends.json'), JSON.stringify(unique, null, 4));
    // TODO: diff file-system (abstract better?, code reuse?), selenium connect
    return unique;
}

var friendsOnFacebook, loginFacebook;
function addFacebookFriends() {
    var pages = loadNewConnections();
    console.log(pages.length);
    console.log(pages.slice(0, 30))
    return runSeleniumCell(['log in facebook', 'connect on facebook'])
        .then(r => {
            loginFacebook = r.loginFacebook;
            friendsOnFacebook = r.friendsOnFacebook;
            return loginFacebook();
        })
        .then(() => {
            const rand = Math.round(pages.length / 30 * Math.random()) * 30;
            console.log(pages.slice(rand, rand + 30));
            return importer.runAllPromises(pages.slice(rand, rand + 30).map(page => resolve => {
                console.log(page);
                return friendsOnFacebook(page, true)
                    .then(r => resolve(r))
                    .catch(e => resolve(e))
            }))
        })
}
module.exports = addFacebookFriends;

What the code could have been:

// Import required modules
const importer = require('../Core');
const glob = require('glob');
const path = require('path');
const fs = require('fs');
const runSeleniumCell = importer.import('run selenium cell');

// Define constants
const PROFILE_PATH = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
const PROJECT_DIR = path.join(PROFILE_PATH, 'Conversations');

// Regular expression to extract Facebook URLs
const FACEBOOK_URL_REGEX = /facebook\.com\/.*/ig;

// Function to convert regex matches to array
const regexToArray = (ex, str, i = 0) => {
    const matches = [];
    let match;
    while ((match = ex.exec(str)) && matches.push(match[i])) ;
    return matches;
}

// Function to load new connections from files
const loadNewConnections = async () => {
    // Check if new friends file exists
    if (fs.existsSync(path.join(PROJECT_DIR, 'new-friends.json'))) {
        return JSON.parse(fs.readFileSync(path.join(PROJECT_DIR, 'new-friends.json')).toString());
    }

    // Find posts files
    const posts = glob.sync('**/*-posts-*', { cwd: PROJECT_DIR })
       .map(file => path.join(PROJECT_DIR, file));

    // Load friends from posts files
    const friends = await Promise.all(posts.map(async file => {
        const matches = await importer.streamJson(file, [true, { emitPath: true }]);
        return regexToArray(FACEBOOK_URL_REGEX, matches.value).map(url => url.replace(/\?fref.*|\?ref.*|\?rc=.*|\?hc_location.*/ig, ''));
    }));

    // Remove duplicates and write to file
    const uniqueFriends = [...new Set(friends.flat())];
    fs.writeFileSync(path.join(PROJECT_DIR, 'new-friends.json'), JSON.stringify(uniqueFriends, null, 4));
    return uniqueFriends;
}

// Function to add Facebook friends
const addFacebookFriends = async () => {
    const pages = await loadNewConnections();
    console.log(pages.length);
    console.log(pages.slice(0, 30));

    // Run Selenium commands
    const { loginFacebook, friendsOnFacebook } = await runSeleniumCell(['log in facebook', 'connect on facebook']);
    loginFacebook = await loginFacebook();

    // Connect to Facebook friends in batches
    const batchSize = 30;
    const batches = Math.ceil(pages.length / batchSize);
    for (let i = 0; i < batches; i++) {
        const batch = pages.slice(i * batchSize, i * batchSize + batchSize);
        await importer.runAllPromises(batch.map(page => resolve => {
            console.log(page);
            return friendsOnFacebook(page, true)
               .then(r => resolve(r))
               .catch(e => resolve(e))
        }));
    }

    return pages;
}

module.exports = addFacebookFriends;

This code snippet appears to be part of a larger project designed to automate friend connections on Facebook.

Here's a breakdown:

  1. Dependencies:

  2. Variables:

  3. Functions:

Overall Purpose:

The code snippet automates the process of finding new Facebook friends from scraped posts and connecting with them using Selenium.

Let me know if you have any more questions or would like me to elaborate on any specific part of the code!