From e28c5ac467983ca984e16d1878e738b6c04426f6 Mon Sep 17 00:00:00 2001 From: Guillaume Vagner <guillaume.vagner@supelec.fr> Date: Sat, 16 Feb 2019 18:19:01 +0100 Subject: [PATCH] save group list --- index.js | 2 +- models/Channel.js | 12 +++++++ models/Token.js | 11 ------ requests.js | 25 +++++++++++--- telegram.js | 87 ++++++++++++++++++++++++++++++++++++----------- website.js | 24 ++++++------- 6 files changed, 113 insertions(+), 48 deletions(-) create mode 100644 models/Channel.js delete mode 100644 models/Token.js diff --git a/index.js b/index.js index c1d3d05..cf49623 100644 --- a/index.js +++ b/index.js @@ -2,4 +2,4 @@ const bot = require('./telegram'); const app = require('./website'); const mongoose = require('./mongoose'); const { sendRequest, getBirthdays } = require('./requests'); -const Token = require('./models/Token'); +const Channel = require('./models/Channel'); diff --git a/models/Channel.js b/models/Channel.js new file mode 100644 index 0000000..30216e9 --- /dev/null +++ b/models/Channel.js @@ -0,0 +1,12 @@ +const mongoose = require('../mongoose'); + +const channelSchema = new mongoose.Schema({ + token: String, + expiration: Date, + username: String, + chatId: Number, + state: String, + groups: [{ id: Number, name: String }] +}) + +module.exports = mongoose.model('Channel', channelSchema); \ No newline at end of file diff --git a/models/Token.js b/models/Token.js deleted file mode 100644 index 08d7137..0000000 --- a/models/Token.js +++ /dev/null @@ -1,11 +0,0 @@ -const mongoose = require('../mongoose'); - -const tokenSchema = new mongoose.Schema({ - token: String, - expiration: Date, - username: String, - chatId: Number, - state: String -}) - -module.exports = mongoose.model('Token', tokenSchema); \ No newline at end of file diff --git a/requests.js b/requests.js index 729b2cd..713aed7 100644 --- a/requests.js +++ b/requests.js @@ -1,9 +1,9 @@ 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 = { headers: { 'Authorization': `Bearer ${token}` }, json: true @@ -15,7 +15,7 @@ function sendRequest(req, token, callback) { 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 => { const users = []; body.data.users.forEach(user => { @@ -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 diff --git a/telegram.js b/telegram.js index 4ca2008..991a207 100644 --- a/telegram.js +++ b/telegram.js @@ -1,15 +1,14 @@ process.env["NTBA_FIX_319"] = 1; const TelegramBot = require('node-telegram-bot-api'); -const Token = require('./models/Token'); +const Channel = require('./models/Channel'); const config = require('./config'); -const { sendRequest, getBirthdays } = require('./requests'); +const { getBirthdays, searchGroups, getGroupById } = require('./requests'); const bot = new TelegramBot(config.telegram.token, { polling: true }); bot.onText(/\/start/, (msg, _) => { - console.log(msg); 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'; bot.sendMessage(chatId, resp); @@ -18,28 +17,29 @@ bot.onText(/\/start/, (msg, _) => { bot.onText(/\/connect/, (msg, _) => { const chatId = msg.chat.id; const state = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); - Token.findOne({ + Channel.findOne({ chatId: chatId - }).then(token => { - if (!token) { - return Token.create({ + }).then(chan => { + if (!chan) { + return Channel.create({ username: msg.from.username, chatId: chatId, - state: state + state: state, + groups: [] }) - } else if (!token.token) { - return Token.findByIdAndDelete(token._id).then(_ => { - return Token.create({ + } else if (!chan.token) { + return Channel.findByIdAndDelete(chan._id).then(_ => { + return Channel.create({ username: msg.from.username, chatId: chatId, state: state }) }) } 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 => { - if (!token) return + }).then(chan => { + 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}`; bot.sendMessage(chatId, resp); }) @@ -47,20 +47,21 @@ bot.onText(/\/connect/, (msg, _) => { bot.onText(/\/disconnect/, (msg, _) => { const chatId = msg.chat.id; - Token.findOneAndDelete({ chatId: chatId }).then(token => { - if (!token) return bot.sendMessage(chatId, 'Pas de compte connecté'); - const resp = `@${token.username} n'est plus connecté à l'OAuth2.`; + Channel.findOneAndDelete({ chatId: chatId }).then(chan => { + console.log(msg); + 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.onText(/\/birthdays/, (msg, _) => { const chatId = msg.chat.id; - Token.findOne({ + Channel.findOne({ chatId: chatId, expiration: { $gt: Date.now() } - }).then(token => { - return getBirthdays(token.token) + }).then(chan => { + return getBirthdays(chan.token) }).then(users => { var msg = 'Joyeux anniversaire à :\n' users.forEach(user => { @@ -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; \ No newline at end of file diff --git a/website.js b/website.js index f19dc98..27b203f 100644 --- a/website.js +++ b/website.js @@ -3,7 +3,7 @@ const config = require('./config'); const app = require('express')(); const request = require('request'); const bot = require('./telegram'); -const Token = require('./models/Token'); +const Channel = require('./models/Channel'); app.listen(80, 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) { 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 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); }) @@ -46,15 +46,15 @@ app.get('/auth', function (req, res) { request(options, (err, res, body) => { 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) - if (!token) { return req.query.state } - token.token = rep.access_token; - token.expiration = rep.expires_at*1000; - token.state = ''; - return token.save(); - }).then(token => { - bot.sendMessage(token.chatId, `@${token.username} s'est connecté à OAuth2, shall we begin?`) + if (!chan) { return req.query.state } + chan.token = rep.access_token; + chan.expiration = rep.expires_at*1000; + chan.state = ''; + return chan.save(); + }).then(chan => { + bot.sendMessage(chan.chatId, `@${chan.username} s'est connecté à OAuth2, shall we begin?`) }) } }) -- GitLab