multi-account-post-schedule.../routes/index.js

379 lines
10 KiB
JavaScript
Raw Normal View History

2022-07-07 18:23:44 +02:00
var express = require('express');
var router = express.Router();
2022-07-07 19:03:04 +02:00
var sqlite3 = require('sqlite3');
2022-07-10 23:02:32 +02:00
var Masto = require('mastodon');
const accounts_to_select = [
{
label: "tykayn",
value: "tykayn"
},
{
label: "modominem",
value: "modominem"
},
2022-07-11 17:04:46 +02:00
{
label: "qzine",
value: "qzine"
},
{
label: "curator",
value: "curator"
},
{
label: "kurator",
value: "kurator"
},
{
label: "voix du nucléaire",
value: "voixdunucleaire"
},
{
label: "The greatest Meme",
value: "meme"
},
{
label: "cil de gometz",
value: "cil_gometz"
},
2022-07-10 23:02:32 +02:00
]
2022-07-11 17:04:46 +02:00
const default_times = ['08:02:00', '08:42:00', '09:10:00', '09:15:00', '10:22:00', '12:22:00']
2022-07-07 19:03:04 +02:00
const database_masto = "mastodon_multi_accounts.db"
2022-07-07 18:23:44 +02:00
/* GET home page. */
2022-07-11 17:04:46 +02:00
let schedule_time = '';
2022-07-07 19:03:04 +02:00
router.get('/', function (req, res, next) {
2022-07-11 17:04:46 +02:00
if (!req.body.schedule_time) {
schedule_time = default_times[Math.floor(Math.random() * default_times.length)];
}
res.render('index', {accounts_to_select, reqBody: req.body, schedule_time});
2022-07-07 18:23:44 +02:00
});
2022-07-07 18:23:44 +02:00
// publier un message avec un certain compte
2022-07-07 19:03:04 +02:00
router.get('/publish', function (req, res, next) {
res.render('index', {title: 'Express'});
2022-07-07 18:23:44 +02:00
});
2022-07-07 19:03:04 +02:00
const connect = require('@databases/sqlite');
const {sql} = require('@databases/sqlite');
2022-07-07 23:39:28 +02:00
const {runOnChangeOnly} = require("nodemon/lib/config/defaults");
const fs = require("fs");
2022-07-07 19:03:04 +02:00
const db = connect(database_masto);
2022-07-07 19:16:56 +02:00
2022-07-07 18:23:44 +02:00
function createDatabase() {
2022-07-07 19:03:04 +02:00
var newdb = new sqlite3.Database(database_masto, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, (err) => {
2022-07-07 18:23:44 +02:00
createTables(newdb);
2022-07-07 19:03:04 +02:00
})
2022-07-07 18:23:44 +02:00
}
2022-07-07 19:03:04 +02:00
2022-07-07 18:23:44 +02:00
function createTables(newdb) {
2022-07-07 19:16:56 +02:00
async function prepare() {
await db.query(sql`
create table posts_scheduled
(
action_id integer
2022-07-07 19:16:56 +02:00
constraint posts_scheduled_pk
primary key autoincrement,
post_username varchar not null,
content varchar not null,
medias varchar,
datetime datetime
2022-07-07 19:16:56 +02:00
);
create unique index posts_scheduled_action_id_uindex
on posts_scheduled (action_id);
insert into posts_scheduled
2022-07-07 19:28:40 +02:00
values (NULL, "modominem", "un message d'example", NULL);
2022-07-07 19:16:56 +02:00
2022-07-07 19:28:40 +02:00
`);
2022-07-07 19:16:56 +02:00
console.log('requête de création faite')
}
2022-07-07 19:28:40 +02:00
2022-07-07 19:16:56 +02:00
const prepared = prepare();
2022-07-07 18:23:44 +02:00
}
// ajouter un message à la file d'attente avec un certain compte
router.post('/add-to-queue', function (req, res, next) {
// get account
// get content*
// add to sql DB
// insert into posts_scheduled
// values (NULL, "modominem", "un message d'example", NULL);
var db = new sqlite3.Database(database_masto, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, (err) => {
}
)
db.serialize(() => {
db.run('INSERT INTO posts_scheduled VALUES(?,?,?,?,?)', [null, req.body.author, req.body.message, req.body.fichier, null], function (err) {
if (err) {
return console.log(err.message);
2022-07-10 23:02:32 +02:00
res.render('index', {message: 'erreur ' + err.message});
}
console.log("nouveau post ajouté", req.body.author, req.body.message);
res.render('index', {message: 'message ajouté OK'});
});
});
});
2022-07-07 18:23:44 +02:00
function getAllPosts(db) {
2022-07-07 19:28:40 +02:00
return db.query(sql`SELECT *
2022-07-07 23:39:28 +02:00
FROM posts_scheduled
ORDER BY action_id DESC LIMIT 15;`)
2022-07-07 18:23:44 +02:00
}
2022-07-07 19:03:04 +02:00
router.get('/init-db', function (req, res, next) {
var db = new sqlite3.Database(database_masto, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, (err) => {
2022-07-07 19:28:40 +02:00
console.log('got to create db')
createDatabase()
2022-07-07 19:03:04 +02:00
}
)
res.render('created_db', {});
2022-07-07 18:23:44 +02:00
});
2022-07-07 19:03:04 +02:00
router.get('/list', function (req, res, next) {
2022-07-07 19:28:40 +02:00
// let posts_list = [{
// action_id: 1,
// post_username: "modominem",
// content: "demo post list",
// medias: "media file name from assets folder",
// date_schedule: "2022-07-07 "
// }]
2022-07-07 23:39:28 +02:00
getAllPosts(db).then(
2022-07-07 19:28:40 +02:00
(results) => {
2022-07-07 23:39:28 +02:00
console.log("liste de posts ", results)
2022-07-07 19:28:40 +02:00
res.render('database', {posts_list: results});
},
(err) => console.error(err),
);
2022-07-07 18:23:44 +02:00
});
2022-07-07 19:33:11 +02:00
router.get('/add-example', function (req, res, next) {
2022-07-07 23:39:28 +02:00
// let db = connect(database_masto);
2022-07-07 19:03:04 +02:00
2022-07-07 19:28:40 +02:00
async function prepare() {
await db.query(sql`
2022-07-07 19:03:04 +02:00
insert into posts_scheduled
2022-07-07 23:39:28 +02:00
values (NULL, "modominem", "un message d'example", "image.jpg", NULL)
2022-07-07 19:03:04 +02:00
;
2022-07-07 19:28:40 +02:00
`).then(resp => {
console.log(resp)
let posts_list = []
2022-07-07 19:33:11 +02:00
res.redirect('/list')
2022-07-07 19:28:40 +02:00
},
err => {
console.log(err)
});
}
2022-07-07 19:33:11 +02:00
2022-07-07 23:39:28 +02:00
const prepared = prepare();
2022-07-07 19:33:11 +02:00
2022-07-07 19:28:40 +02:00
}
);
2022-07-07 19:03:04 +02:00
2022-07-07 23:39:28 +02:00
require('dotenv').config();
2022-07-07 18:23:44 +02:00
// publier le message en db dans la file
2022-07-07 19:03:04 +02:00
router.get('/publish-last-entry', function (req, res, next) {
2022-07-07 23:39:28 +02:00
var OAuth2 = require('oauth').OAuth2;
// console.log('process.env' , process.env)
var oauth = new OAuth2(process.env.APP_ID, process.env.SECRET, process.env.INSTANCE_MASTODON, null, '/oauth/token');
var url = oauth.getAuthorizeUrl({
redirect_uri: 'urn:ietf:wg:oauth:2.0:oob',
response_type: 'code',
scope: 'read write follow'
});
console.log('url ', url)
let status = "#mastoart of @tykayn"
let visibility = "unlisted" // public, unlisted, private, direct.
let media_filename = "colline.JPG"
2022-07-07 23:39:28 +02:00
let file_path = "assets/not_published/" + media_filename
let accessToken = process.env.TOKEN
let sensitive = false;
2022-07-07 23:39:28 +02:00
let scheduled_at = "2022-07-07T21:36:29.100Z";
let account_id = "2974"; // curator bliss
let language = "fr";
let enable_post = false;
// Get the user to open up the url in their browser and get the code
// oauth.getOAuthAccessToken('code from the authorization page that user should paste into your app',
// {grant_type: 'authorization_code', redirect_uri: 'urn:ietf:wg:oauth:2.0:oob'},
// function (err, accessToken, refreshToken, res) {
//
// console.log(err, accessToken, refreshToken , res);
const masto = new Masto({
access_token: accessToken,
api_url: process.env.INSTANCE_MASTODON + '/api/v1/',
});
2022-07-07 23:39:28 +02:00
if (enable_post) {
2022-07-07 23:39:28 +02:00
masto.post('media', {file: fs.createReadStream(file_path)}).then(resp => {
id = resp.data.id;
// doc https://docs.joinmastodon.org/methods/statuses/
2022-07-07 23:39:28 +02:00
console.log('media id ', resp.data.id)
console.log(resp.data)
masto.post('statuses', {
status: status,
media_ids: [id],
account_id,
visibility,
language,
sensitive
}).then(resp => {
2022-07-07 23:39:28 +02:00
// succès, marquer le post comme fait en BDD
console.log(resp)
var oldPath = file_path
var newPath = 'assets/published/' + media_filename
2022-07-07 23:39:28 +02:00
fs.rename(oldPath, newPath, function (err) {
if (err) throw err
console.log('Successfully renamed - AKA moved!')
})
2022-07-07 23:39:28 +02:00
},
err => {
2022-07-07 23:39:28 +02:00
console.error(err)
})
})
}
//
// if (!file) {
// return masto.post('statuses', {
// status,
// visibility,
// });
// }
// const response = await masto.post('media', {
// file: {
// value: file,
// options: {
// filename: 'assets/test.png',
// contentType: 'image/png',
// },
// },
// });
//
// return masto.post('statuses', {
// status,
// visibility,
// media_ids: [response.data.id],
// });
// })
2022-07-07 23:39:28 +02:00
res.render('index', {});
//
// getAllPosts(db).then(
// (results) => {
// console.log( "publier le premier message de la file d'attente" ,results[0])
// res.render('publish', {p: results[0]});
// },
// (err) => console.error(err),
// );
2022-07-07 19:41:44 +02:00
2022-07-07 18:23:44 +02:00
});
2022-07-07 19:41:44 +02:00
// répartir les publications dans le temps
// TODO
2022-07-07 23:39:28 +02:00
const limit_posts_per_day = 10
2022-07-07 19:41:44 +02:00
router.get('/dispatch-publication-in-time', function (req, res, next) {
2022-07-07 23:39:28 +02:00
2022-07-07 19:41:44 +02:00
getAllPosts(db).then(
(results) => {
2022-07-07 23:39:28 +02:00
console.log("répartir", results[0])
2022-07-07 19:41:44 +02:00
// on compte les posts et quel intervalle de temps mettre entre chaque pour tenir le rythme de X posts par jour
2022-07-07 23:39:28 +02:00
res.render('index', {p: results[0]});
2022-07-07 19:41:44 +02:00
},
(err) => console.error(err),
);
});
2022-07-11 17:04:46 +02:00
router.post('/direct-post', function (req, res, next) {
if (process.env['TOKEN_' + req.body.author]) {
let visibility = 'public';
let language = 'fr';
let sensitive = false;
2022-07-11 17:45:28 +02:00
2022-07-11 17:04:46 +02:00
let accessToken = process.env['TOKEN_' + req.body.author]
console.log('accessToken', accessToken)
const masto = new Masto({
access_token: accessToken,
api_url: process.env.INSTANCE_MASTODON + '/api/v1/',
});
let params = {
status: req.body.message,
visibility,
language,
sensitive
}
if (req.body.cw) {
params['spoiler_text'] = req.body.cw
}
if (req.body.scheduled_at && req.body.scheduled_at_bool) {
let dateschedule = new Date(req.body.scheduled_at)
params['scheduled_at'] = dateschedule.toISOString()
}
console.log(req.body)
if (!req.body.fichier) {
masto.post('statuses', params).then(rep => {
console.log('rep', rep)
}, err => {
console.error(err)
})
res.render('index', {bodyReq: req.body})
}
// if (req.body.fichier) {
//
// masto.post('statuses', params).then(rep => {
// console.log('rep', rep)
// }, err => {
// console.error(err)
// })
// res.render('index', {bodyReq: req.body})
// }
} else {
console.error('pas de token pour ' + req.body.author)
}
})
2022-07-07 18:23:44 +02:00
module.exports = router;