Skip to content
Snippets Groups Projects
Commit e28c5ac4 authored by Guillaume Vagner's avatar Guillaume Vagner
Browse files

save group list

parent 67d9ea68
Branches
No related tags found
No related merge requests found
...@@ -2,4 +2,4 @@ const bot = require('./telegram'); ...@@ -2,4 +2,4 @@ const bot = require('./telegram');
const app = require('./website'); const app = require('./website');
const mongoose = require('./mongoose'); const mongoose = require('./mongoose');
const { sendRequest, getBirthdays } = require('./requests'); const { sendRequest, getBirthdays } = require('./requests');
const Token = require('./models/Token'); const Channel = require('./models/Channel');
const mongoose = require('../mongoose'); const mongoose = require('../mongoose');
const tokenSchema = new mongoose.Schema({ const channelSchema = new mongoose.Schema({
token: String, token: String,
expiration: Date, expiration: Date,
username: String, username: String,
chatId: Number, chatId: Number,
state: String state: String,
groups: [{ id: Number, name: String }]
}) })
module.exports = mongoose.model('Token', tokenSchema); module.exports = mongoose.model('Channel', channelSchema);
\ No newline at end of file \ No newline at end of file
const rp = require('request-promise'); const rp = require('request-promise');
const Token = require('./models/Token'); const Channel = require('./models/Channel');
function sendRequest(req, token, callback) { function sendRequest(req, token) {
const options = { const options = {
headers: { 'Authorization': `Bearer ${token}` }, headers: { 'Authorization': `Bearer ${token}` },
json: true json: true
...@@ -15,7 +15,7 @@ function sendRequest(req, token, callback) { ...@@ -15,7 +15,7 @@ function sendRequest(req, token, callback) {
function getBirthdays(token) { function getBirthdays(token) {
req = 'query getUsersBirthday {users: usersBirthday { ...userData}}fragment userData on User {id firstName lastName roles {sector {composition {association {id}}}}}' const req = 'query getUsersBirthday {users: usersBirthday { ...userData}}fragment userData on User {id firstName lastName roles {sector {composition {association {id}}}}}'
return sendRequest(req, token).then(body => { return sendRequest(req, token).then(body => {
const users = []; const users = [];
body.data.users.forEach(user => { body.data.users.forEach(user => {
...@@ -31,4 +31,21 @@ function getBirthdays(token) { ...@@ -31,4 +31,21 @@ function getBirthdays(token) {
}) })
} }
module.exports = { getBirthdays, sendRequest };
\ No newline at end of file function searchGroups(token, term) {
const req = `query {searchAssociations(term: "${term}") {id name code}}`
return sendRequest(req, token).then(body => {
if (!body.data) return;
return body.data.searchAssociations;
}).catch(err => { console.error(err) })
}
function getGroupById(token, id) {
const req = `query {association(id: ${id}) {name}}`
return sendRequest(req, token).then(body => {
if (!body.data) return;
return body.data.association.name;
}).catch(err => { console.error(err) })
}
module.exports = { getBirthdays, sendRequest, searchGroups, getGroupById };
\ No newline at end of file
process.env["NTBA_FIX_319"] = 1; process.env["NTBA_FIX_319"] = 1;
const TelegramBot = require('node-telegram-bot-api'); const TelegramBot = require('node-telegram-bot-api');
const Token = require('./models/Token'); const Channel = require('./models/Channel');
const config = require('./config'); const config = require('./config');
const { sendRequest, getBirthdays } = require('./requests'); const { getBirthdays, searchGroups, getGroupById } = require('./requests');
const bot = new TelegramBot(config.telegram.token, { polling: true }); const bot = new TelegramBot(config.telegram.token, { polling: true });
bot.onText(/\/start/, (msg, _) => { bot.onText(/\/start/, (msg, _) => {
console.log(msg);
const chatId = msg.chat.id; const chatId = msg.chat.id;
const resp = 'Holà, je suis le Happy Botday, je suis là pour vous souhaiter vous rapeller les anniversaires de vos potes !\nPour commencer, il faut que quelqu\'un s\'identifie : /connect'; const resp = 'Holà, je suis le Happy Botday, je suis là pour vous souhaiter vous rapeller les anniversaires de vos potes !\nPour commencer, il faut que quelqu\'un s\'identifie : /connect';
bot.sendMessage(chatId, resp); bot.sendMessage(chatId, resp);
...@@ -18,28 +17,29 @@ bot.onText(/\/start/, (msg, _) => { ...@@ -18,28 +17,29 @@ bot.onText(/\/start/, (msg, _) => {
bot.onText(/\/connect/, (msg, _) => { bot.onText(/\/connect/, (msg, _) => {
const chatId = msg.chat.id; const chatId = msg.chat.id;
const state = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); const state = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
Token.findOne({ Channel.findOne({
chatId: chatId chatId: chatId
}).then(token => { }).then(chan => {
if (!token) { if (!chan) {
return Token.create({ return Channel.create({
username: msg.from.username, username: msg.from.username,
chatId: chatId, chatId: chatId,
state: state state: state,
groups: []
}) })
} else if (!token.token) { } else if (!chan.token) {
return Token.findByIdAndDelete(token._id).then(_ => { return Channel.findByIdAndDelete(chan._id).then(_ => {
return Token.create({ return Channel.create({
username: msg.from.username, username: msg.from.username,
chatId: chatId, chatId: chatId,
state: state state: state
}) })
}) })
} else { } else {
bot.sendMessage(chatId, `Une connexion a déjà été faite par @${token.username}. Pour la réinitialiser, faites /disconnect`); bot.sendMessage(chatId, `Une connexion a déjà été faite par @${chan.username}. Pour la réinitialiser, faites /disconnect`);
} }
}).then(token => { }).then(chan => {
if (!token) return if (!chan) return
const resp = `Pour vous identifier, connectez-vous via l\'OAuth2 de ViaRézo depuis ce lien :\n${config.website.protocol}://${config.website.hostname}/?state=${state}`; const resp = `Pour vous identifier, connectez-vous via l\'OAuth2 de ViaRézo depuis ce lien :\n${config.website.protocol}://${config.website.hostname}/?state=${state}`;
bot.sendMessage(chatId, resp); bot.sendMessage(chatId, resp);
}) })
...@@ -47,20 +47,21 @@ bot.onText(/\/connect/, (msg, _) => { ...@@ -47,20 +47,21 @@ bot.onText(/\/connect/, (msg, _) => {
bot.onText(/\/disconnect/, (msg, _) => { bot.onText(/\/disconnect/, (msg, _) => {
const chatId = msg.chat.id; const chatId = msg.chat.id;
Token.findOneAndDelete({ chatId: chatId }).then(token => { Channel.findOneAndDelete({ chatId: chatId }).then(chan => {
if (!token) return bot.sendMessage(chatId, 'Pas de compte connecté'); console.log(msg);
const resp = `@${token.username} n'est plus connecté à l'OAuth2.`; if (!chan) return bot.sendMessage(chatId, 'Pas de compte connecté');
const resp = `@${chan.username} n'est plus connecté à l'OAuth2.`;
bot.sendMessage(chatId, resp); bot.sendMessage(chatId, resp);
}) })
}); });
bot.onText(/\/birthdays/, (msg, _) => { bot.onText(/\/birthdays/, (msg, _) => {
const chatId = msg.chat.id; const chatId = msg.chat.id;
Token.findOne({ Channel.findOne({
chatId: chatId, chatId: chatId,
expiration: { $gt: Date.now() } expiration: { $gt: Date.now() }
}).then(token => { }).then(chan => {
return getBirthdays(token.token) return getBirthdays(chan.token)
}).then(users => { }).then(users => {
var msg = 'Joyeux anniversaire à :\n' var msg = 'Joyeux anniversaire à :\n'
users.forEach(user => { users.forEach(user => {
...@@ -70,4 +71,50 @@ bot.onText(/\/birthdays/, (msg, _) => { ...@@ -70,4 +71,50 @@ bot.onText(/\/birthdays/, (msg, _) => {
}) })
}); });
bot.onText(/\/search (.+)/, (msg, match) => {
const chatId = msg.chat.id;
const research = match[1];
Channel.findOne({
chatId: chatId,
expiration: { $gt: Date.now() }
}).then(chan => {
return searchGroups(chan.token, research)
}).then(groups => {
if (groups.length == 0) return bot.sendMessage(chatId, 'Pas de groupe à ce nom...');
var resp = 'Voici les différentes associations. Faites /add XXXX pour ajouter les anniversaires de ses membres. ';
if (groups.length == 20) resp += 'La recherche est limitée à 20 choix.'
resp += '\n\n'
groups.forEach(group => {
resp += `${group.name} : \`/add ${group.id}\`\nhttps://linkcs.fr/association/${group.code} \n\n`
})
bot.sendMessage(chatId, resp, { parse_mode: 'Markdown' });
});
})
bot.onText(/\/nikmarine/, (msg, _) => {
const chatId = msg.chat.id;
bot.sendMessage(chatId, 'Nik bien Marine');
})
bot.onText(/\/add (.+)/, (msg, match) => {
const chatId = msg.chat.id;
Channel.findOne({
chatId: chatId,
expiration: { $gt: Date.now() }
}).then(chan => {
var id = parseInt(match[1].split(' ')[0]);
return Promise.all([getGroupById(chan.token, id), chan, id]);
}).then(([group, chan, id]) => {
if (!group) return bot.sendMessage(chatId, 'Pas de groupe trouvé ayant cette ID');
ids = chan.groups.map(g => g.id);
if (id in ids) return bot.sendMessage(chatId, 'Ce groupe est déjà est dans votre liste d\'anniversaire.');
console.log(chan.groups);
chan.groups.push({ id: id, name: group });
console.log(chan.groups);
return chan.save().then(_ => {
bot.sendMessage(chatId, `Ajout du groupe \`${group}\` à la liste des anniversaires.`, { parse_mode: 'Markdown' });
})
})
})
module.exports = bot; module.exports = bot;
\ No newline at end of file
...@@ -3,7 +3,7 @@ const config = require('./config'); ...@@ -3,7 +3,7 @@ const config = require('./config');
const app = require('express')(); const app = require('express')();
const request = require('request'); const request = require('request');
const bot = require('./telegram'); const bot = require('./telegram');
const Token = require('./models/Token'); const Channel = require('./models/Channel');
app.listen(80, config.website.hostname, () => { app.listen(80, config.website.hostname, () => {
console.log(`[express] Website is up and accessible on ${config.website.protocol}://${config.website.hostname}/`); console.log(`[express] Website is up and accessible on ${config.website.protocol}://${config.website.hostname}/`);
...@@ -13,12 +13,12 @@ app.get('/', function (req, res) { ...@@ -13,12 +13,12 @@ app.get('/', function (req, res) {
if (!req.query.state) { return res.sendFile(`${__dirname}/index.html`) }; if (!req.query.state) { return res.sendFile(`${__dirname}/index.html`) };
Token.findOne({ state: req.query.state }).then(rep => { Channel.findOne({ state: req.query.state }).then(chan => {
if (!rep || rep.token) return res.sendFile(`${__dirname}/index.html`); if (!chan || chan.token) return res.sendFile(`${__dirname}/index.html`);
const redirectURI = `${config.website.protocol}://${config.website.hostname}/auth`; const redirectURI = `${config.website.protocol}://${config.website.hostname}/auth`;
const url = `https://auth.viarezo.fr/oauth/authorize/?redirect_uri=${redirectURI}&client_id=${config.oauth2.clientid}&response_type=code&state=${rep.state}&scope=${config.oauth2.scope}`; const url = `https://auth.viarezo.fr/oauth/authorize/?redirect_uri=${redirectURI}&client_id=${config.oauth2.clientid}&response_type=code&state=${chan.state}&scope=${config.oauth2.scope}`;
return res.redirect(301, url); return res.redirect(301, url);
}) })
...@@ -46,15 +46,15 @@ app.get('/auth', function (req, res) { ...@@ -46,15 +46,15 @@ app.get('/auth', function (req, res) {
request(options, (err, res, body) => { request(options, (err, res, body) => {
if (!err && res.statusCode == 200) { if (!err && res.statusCode == 200) {
Token.findOne({ state: req.query.state }).then(token => { Channel.findOne({ state: req.query.state }).then(chan => {
rep = JSON.parse(body) rep = JSON.parse(body)
if (!token) { return req.query.state } if (!chan) { return req.query.state }
token.token = rep.access_token; chan.token = rep.access_token;
token.expiration = rep.expires_at*1000; chan.expiration = rep.expires_at*1000;
token.state = ''; chan.state = '';
return token.save(); return chan.save();
}).then(token => { }).then(chan => {
bot.sendMessage(token.chatId, `@${token.username} s'est connecté à OAuth2, shall we begin?`) bot.sendMessage(chan.chatId, `@${chan.username} s'est connecté à OAuth2, shall we begin?`)
}) })
} }
}) })
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment