Use headless chrome to automate Facebook posts - facebook

Is it possible to post on a facebook group using Headless Chrome? I need this to automate posting some messages on a group.
I managed to login in to facebook but I'm stuck at this point...
const CDP = require('chrome-remote-interface');
CDP((protocol) => {
const {Page, Runtime} = protocol;
Promise.all([
Page.enable(),
Runtime.enable()
]).then(() => {
Page.navigate({url: 'https://www.facebook.com'});
Page.loadEventFired(() => {
const js = 'document.getElementById("email").value="my_email";document.getElementById("pass").value="SlidSelfby92";document.getElementById("loginbutton").click()';
Runtime.evaluate({expression: js}).then(result => {
console.log(result);
setTimeout(function () {
Runtime.evaluate({expression: "document.getElementsByClassName('_2s25')[0].href"}).then(result => {
Page.navigate({url: result.result.value});
})
},5000)
});
});
});
}).on('error', (err) => {
console.error(err);
});
If this is not possible, then does anyone know how can I post to facebook using an API Call?

Related

How to properly setup socket io in MERN app?

I am new to socket.io. I have basic understanding of how it works, but I am struggling to find proper setup for it within MERN app. If there is any article, or guidance that you can give me, I would appretiate it. I am building social network app, and I need to have live notifications and messages. So I am not sure how to setup socket.io client in react. Should I instanciate it in helper file, like mongoose in express, or is there any other way? Thanks
Install socket.io for server app
Install socket.io - client for client app
import socket.io in server page
const express = require('express');
const http = require('http');
const socketio = require('socket.io');
const cors = require('cors');
const app = express();
const server = http.createServer(app)
const io = socketio(server, { cors: { origin: '*' } }) //for omit cors error
const PORT = 2900;
app.use(express.json());
app.use(cors());
io.on('connect', (socket) => {
console.log("user connected")
socket.on('valor', ({ id, name, }, callback) => {
console.log('data::', id, name)
socket.emit('receiveGreet', { data: 'This message from server' }, (error) => {
console.log('error::', error)
})
callback()
})
socket.on('disconnect', () => {
console.log('user disconnected')
})
})
app.get('/', (req, res) => {
res.json('api running')
})
server.listen(PORT, console.log(`server running in node on port ${PORT}`));
Client side Code May look like this
import io from 'socket.io-client';
let socket: any;
const serverUrl = 'http://localhost:2900';
const MyComponent = () => {
useEffect(() => {
socket = io(serverUrl);
socket.on('receiveGreet', (data) => {
console.log('data::', data);
});
}, []);
return () => {
socket.disconnect();
socket.off();
};
};

HTTP .get() method does not respond with anything

I am trying to use Express + MongoDB building React app.
I was able to post some documents to MongoDB and delete them. Currently, I'm trying to figure out how to get them using HTTP .get() method.
I have these routes:
router.post('/totalbalance', (request, response) => {
const totalBalance = new TotalBalanceModelTemplate({
totalBalance:request.body.totalBalance,
});
totalBalance.save()
.then(data => {
response.json(data);
})
.catch(error => {
response.json(error);
});
});
router.get('/totalbalance', (request, response) => {
console.log("Response ", response);
});
This is axios request:
useEffect(() => {
console.log("Using get() method here");
axios.get('http://localhost:4000/app/totalbalance')
}, []);
However, it does not return anything (only 'Using get() method here' gets printed out to the console).
What am I missing here?
Thanks in advance!

Mongoose not fetching data until I refresh the database connection

I am trying to re-fetch the data from MongoDB using mongoose whenever a user reloads the page. However, the old data stays there and the new data doesn't get fetched until I restart the server.
Here is the router:
router.post("/dashboard", (req, res) => {
const userId = req.body.userId;
User.findOne({ _id: userId }, (err, users) => {
if (err) {
console.log(err);
res.status(500).send();
} else {
router.get("/dashboard", (req, res, next) => {
const leagues = [users.leagues.premium, users.leagues.free];
if (err) return next(err);
res.status(200).send(leagues);
});
}
});
});
And here is the Actions (Redux):
export const fetchLeagues = userId => dispatch => {
axios.post("/api/leagues/dashboard", userId).then(
setTimeout(function() {
axios.get("/api/leagues/dashboard").then(leagues => {
dispatch({
type: GET_LEAGUES,
payload: leagues
});
});
}, 50)
);
};
The data must be fetched from a specific user, so that's why I am posting the user Id, then getting the data back. Not sure if this is the best way of doing this.
Just to clarify, I am using the MERN stack with redux and axios to execute this. I tried to use this: MongoDB does not refresh data automatically?, but I still can't get this thing to refresh/re-fetch the data when the router is called again. Thanks.
Doing a POST request then a GET request seems unnecessary here as you can just return the data in a single request.
The reason why the data is being persisted is because when you declare the router.get('/dashboard') route you are permanently hardcoding that route to have the values from the first request.
It's probably best to use a GET request, as that is what you are trying to do.
e.g.
router.get("/dashboard/:userId", (req, res) => {
const userId = req.params.userId;
User.findOne({ _id: userId }, (err, users) => {
if (err) {
console.log(err);
res.status(500).send();
} else {
const leagues = [users.leagues.premium, users.leagues.free];
if (err) return next(err);
res.status(200).send(leagues);
}
});
});
// Where userId is now a string
export const fetchLeagues = userId => dispatch => {
axios.get(`/api/leagues/dashboard/${userId}`).then(leagues => {
dispatch({
type: GET_LEAGUES,
payload: leagues
});
});
};

Using koa-jwt with koa-router

I am implementing the a Nextjs service with koa, koa-router and kow-jwt, but I'm confused with the routing setting with them.
My project have 2 pages, one is dashboard and the other is login. The dashboard need to pass the verification and the login not. If the auth failed, then redirect user to login page.
I've search on the Internet, and found some examples as following, none of them chain them together.
Nextjs custom server
kow-jwt
Please give me some advice to make them work well together.
const app = next({dev});
const handle = app.getRequestHandler();
app.prepare()
.then(() => {
const server = new koa();
const router = new koaRouter();
router.get('/login', async ctx => {
await app.render(ctx.req, ctx.res, '/login', ctx.query);
ctx.respond = false;
});
router.get('/dashboard',
jwt({
secret: config.graphqlSecret
}),
async ctx => {
await app.render(ctx.req, ctx.res, '/dashboard', ctx.query);
ctx.respond = false;
}
);
// what is the purpose of this route?
router.get('*', async ctx => {
await handle(ctx.req, ctx.res);
ctx.respond = false;
});
server.use(async (ctx, next) => {
try {
await next();
} catch (err) {
if (err.statusCode === 401) {
ctx.redirect('/login');
}
}
});
server.use(router.routes());
server.use(router.allowedMethods());
server.listen(3000);
});
with the code above, the behavior is
If I link to dashboard with and without jwt token, it always redirect to login page.
If I link to dashboard from menu (implement with <Link> in Nextjs), it shows the content of dashboard.
Thank you for your help.
You need to include the jwt part in your server.use, not within the router. Make two different routers, one with the open routes and one with the protected ones. Then set open routes, set jwt middleware and then set protected routes:
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare()
.then(() => {
const server = new Koa()
const router = new Router()
router.get('/login', async ctx => {
await app.render(ctx.req, ctx.res, '/login', ctx.query);
ctx.respond = false;
});
router.get('/dashboard', async ctx => {
await app.render(ctx.req, ctx.res, '/dashboard', ctx.query);
ctx.respond = false;
});
router.get('*', async ctx => {
await handle(ctx.req, ctx.res)
ctx.respond = false
})
// this will keep redirecting user to login until is logged in
// if you remove it, will get an auth error unless you go manually
// to the login path
server.use(async (ctx, next) => {
try {
await next();
} catch (err) {
if (err.statusCode === 401) {
ctx.redirect('/login');
}
}
});
// we need to do it this way because of the way nextjs works with '*' path
// Middleware below this line is only reached if JWT token is valid
server.use(jwt({ secret: 'shared-secret' }).unless({ path: [/^\/b/] }));
// specify in unless the unprotected path
server.use(jwt({secret: config.graphqlSecret}).unless({ path: [/^\/login/] })).use(router.allowedMethods());
// every route protected by default
server.use(router.routes())
server.listen(3000);
})

How to change default language of facebook login dialog in ionic?

I am trying to implement login using fb in my ionic app. I am new to both ionic and facebook api.
My problem is when I login using facebook login I see the dialog for facebook login in a different language. as displayed in the image.
But, what I want is load this dialog in English by default. How to do it?
.
here is my code for login in login.ts:
loginFb() {
this.fb.login(['public_profile', 'user_friends', 'email'])
.then(res => {
if(res.status === "connected") {
this.isLoggedIn = true;
this.getFbUserDetail(res.authResponse.userID);
} else {
this.isLoggedIn = false;
}
})
.catch(e => console.log('Error logging into Facebook', e));
}
getFbUserDetail(userid) {
this.fb.api("/"+userid+"/?fields=id,email,name,picture,gender",["public_profile"])
.then(res => {
console.log(res);
this.users = res;
console.log('name',this.users.name);
console.log('gender',this.users.gender);
})
.catch(e => {
console.log(e);
});
}
I have followed this link to connecct facebook with ionic app.