From d4639a3d3b0277ae560e501f6bbdfa0d60e07d5f Mon Sep 17 00:00:00 2001 From: Juliano Penna Date: Fri, 20 Jan 2017 17:29:02 -0200 Subject: [PATCH] Set comments for methods --- .eslintrc.js | 3 +- server/bot/bot.js | 19 +++---- server/bot/botReply.js | 15 +++--- server/bot/utils.js | 77 +++++++++++++------------- server/config/config.js | 2 + server/db/model/user.js | 1 - server/web/authenticate.js | 57 +++++++++++++------- server/web/web.js | 107 ++++++++++++++++++++----------------- 8 files changed, 155 insertions(+), 126 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 405c736..3f72121 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -10,7 +10,8 @@ module.exports = { "import/no-extraneous-dependencies": "off", "consistent-return": "off", "no-trailing-spaces":"off", - "padded-blocks": "off" + "padded-blocks": "off", + "comma-dangle":"off" }, "env": { "mocha": true diff --git a/server/bot/bot.js b/server/bot/bot.js index d00fea6..37cdfad 100644 --- a/server/bot/bot.js +++ b/server/bot/bot.js @@ -1,33 +1,34 @@ -/* Bot app */ - const { bot } = require('./connection/connect'); const web = require('../web/web'); const botReply = require('./botReply'); const utils = require('./utils'); const { Chat } = require('../db/model/chat'); -// handles /start command +/* handles /start command */ bot.command('start', (msg, reply) => { const chat = msg.chat; + // get user avatar and save file in /img/avatars/[id].jpg utils.getUserAvatar(chat.id); - Chat.insertChat({ + const chatData = { chat_id: chat.id, type: chat.type, firstname: chat.firstname, lastname: chat.lastname, - }).then(() => { + }; + + Chat.insertChat(chatData).then(() => { web.newChat(chat); botReply.send(reply, msg, 'Welcome!'); }); }); -// handles text messages +/* handles text messages */ bot.text((msg, reply) => { const chat = msg.chat; - const data = { + const messageData = { chat_id: chat.id, author: chat.firstname, type: 'client', @@ -35,7 +36,7 @@ bot.text((msg, reply) => { sentAt: new Date().getTime(), }; - Chat.insertMessage(data); - web.sendMessage(data); + Chat.insertMessage(messageData); + web.sendMessage(messageData); botReply.send(reply, msg, 'Hello!'); }); diff --git a/server/bot/botReply.js b/server/bot/botReply.js index 32a7238..c5a87ff 100644 --- a/server/bot/botReply.js +++ b/server/bot/botReply.js @@ -9,19 +9,18 @@ const author = 'Telebot'; const type = 'bot'; // send reply to Telegram, web interface and persist data -function send(reply, msg, replyMessage) { - const chat = msg.chat; - const data = { +function send(reply, botAPIMsg, msg) { + const messageData = { author, type, - chat_id: chat.id, - message: replyMessage, + chat_id: botAPIMsg.chat.id, + message: msg, sentAt: new Date().getTime(), }; - reply.text(replyMessage); - web.sendMessage(data); - Chat.insertMessage(chat.id, data); + reply.text(msg); + web.sendMessage(messageData); + Chat.insertMessage(messageData); } module.exports = { send }; diff --git a/server/bot/utils.js b/server/bot/utils.js index 6304b4d..2f0d613 100644 --- a/server/bot/utils.js +++ b/server/bot/utils.js @@ -7,43 +7,46 @@ const utils = {}; utils.getUserAvatar = (userId) => { // get user profile photos axios.post(`https://api.telegram.org/bot${process.env.BOT_TOKEN}/getUserProfilePhotos`, - { user_id: userId }).then((resPrhotos) => { - const bodyPhotos = resPrhotos.data; - - if (bodyPhotos.ok) { - // get file_id from last photo 160x160 - const fileId = bodyPhotos.result.photos[0][0].file_id; - - // get user profile path - axios.post(`https://api.telegram.org/bot${process.env.BOT_TOKEN}/getFile`, - { file_id: fileId }).then((resPath) => { - const bodyPath = resPath.data; - - if (bodyPath.ok) { - // get user profile image - const filePath = bodyPath.result.file_path; - - // create folder if don't exists - const dir = './public/img/avatars'; - if (!fs.existsSync(dir)) { - fs.mkdirSync(dir); - } - const avatar = fs.createWriteStream(`${dir}/${userId}.jpg`); - - https.get(`https://api.telegram.org/file/bot${process.env.BOT_TOKEN}/${filePath}`, - (res) => { - res.pipe(avatar); - }); - - } // user photos if - - }).catch(e => console.log('PROFILE PATH:', e)); - - } else { // user path if - return console.log("Couldn't fetch user avatar"); - } - - }).catch(e => console.log('PROFILE PHOTOS:', e)); + { user_id: userId } + ).then((resPrhotos) => { // PROMISE 1 + const bodyPhotos = resPrhotos.data; + + if (bodyPhotos.ok) { // IF 1 + // get file_id from last photo 160x160 + const fileId = bodyPhotos.result.photos[0][0].file_id; + + // get user profile path + axios.post(`https://api.telegram.org/bot${process.env.BOT_TOKEN}/getFile`, + { file_id: fileId } + ).then((resPath) => { // PROMISE 2 + const bodyPath = resPath.data; + + if (bodyPath.ok) { // IF 2 + // get user profile image + const filePath = bodyPath.result.file_path; + + // create folder if don't exists + const dir = './public/img/avatars'; + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir); + } + const avatar = fs.createWriteStream(`${dir}/${userId}.jpg`); + + https.get(`https://api.telegram.org/file/bot${process.env.BOT_TOKEN}/${filePath}`, + (res) => { + res.pipe(avatar); + } + ); + + } // end IF 1 + + }).catch(e => console.log('PROFILE PATH:', e)); // PROMISE 1 + + } else { // end IF 2 + return console.log("Couldn't fetch user avatar"); + } + } +).catch(e => console.log('PROFILE PHOTOS:', e)); // PROMISE 2 }; diff --git a/server/config/config.js b/server/config/config.js index 161ba34..6cde24c 100644 --- a/server/config/config.js +++ b/server/config/config.js @@ -3,7 +3,9 @@ const _ = require('lodash'); const env = process.env.NODE_ENV || 'dev'; +// Get config for environment (development, test) const envConfig = config[env]; +// Goin defult config const configObj = _.assign(config.default, envConfig); Object.keys(configObj).forEach((key) => { diff --git a/server/db/model/user.js b/server/db/model/user.js index 7332849..8b0168a 100644 --- a/server/db/model/user.js +++ b/server/db/model/user.js @@ -33,7 +33,6 @@ userSchema.statics.findUserByToken = function (token) { return this.findOne({ token }); }; - userSchema.statics.findUserById = function (id) { return this.findOne({ id }); }; diff --git a/server/web/authenticate.js b/server/web/authenticate.js index 87a41e4..0b4b0bc 100644 --- a/server/web/authenticate.js +++ b/server/web/authenticate.js @@ -14,26 +14,38 @@ auth.use(cookieParser()); const meEndpointBaseUrl = `https://graph.accountkit.com/${process.env.FB_API_VERSION}/me`; const tokenExchangeBaseUrl = `https://graph.accountkit.com/${process.env.FB_API_VERSION}/access_token`; +// Check if user can access chatRoom on request auth.get('/views/chatRoom', (req, res, next) => { + // Check token cookie if (req.cookies && req.cookies.token) { + // Check token cookie value on DB User.findUserByToken(req.cookies.token).then((result) => { if (result) { const date = new Date().getTime(); const expiration = new Date(result.expiration_date).getTime(); + + // Expiration date on DB must be valid if (date < expiration) { return next(); } + console.log('Token expired'); } - res.redirect(401, '/views/login'); + // No user found or token expired + console.log('No user found'); + res.redirect(401, '/views/login'); }); + } else { + // No cookie token + console.log('No cookie token'); res.redirect(401, '/views/login'); } }); +// Route for Facebook authentication handlers auth.post('/sendcode', (request, response) => { const appAccessToken = ['AA', process.env.FB_APPID, process.env.FB_APP_SECRET].join('|'); @@ -43,7 +55,7 @@ auth.post('/sendcode', (request, response) => { access_token: appAccessToken, }; - // exchange tokens + // Exchange tokens axios.get(tokenExchangeBaseUrl, { params }) .then((res) => { @@ -51,44 +63,49 @@ auth.post('/sendcode', (request, response) => { access_token: res.data.access_token, }; - // get account details - axios.get(meEndpointBaseUrl, { params: meParams }) - .then((meRes) => { + // Get account details + axios.get(meEndpointBaseUrl, { params: meParams } + ).then((meRes) => { const data = meRes.data; const id = data.id; const email = data.email.address; const token = res.data.access_token; - // calculate expiration date in milliseconds + + // Calculate expiration date in milliseconds const expiration = new Date().getTime() + (res.data.token_refresh_interval_sec * 1000); User.findUserById(data.id).then((result) => { if (!result) { - // insert user + // Insert user User.insertUser(id, email, token, expiration); } else { - // remove and insert new data + // Remove and insert with new data User.removeUser(id); - User.insertUser(id, email, token, expiration); - } + User.insertUser(id, email, token, expiration) + .then(() => { - }); + // Set cookie for persistent login session + response.cookie('token', token, { expires: new Date(expiration) }); + console.log('setCookie', token); - console.log(data); + // Send user to chatRoom page + response.writeHead(302, { + Location: 'views/chatRoom', + 'x-auth': res.data.access_token, + }); - console.log('DATA', new Date(expiration)); + response.end(); + + }); + } - response.cookie('token', token, { expires: new Date(expiration) }); - response.writeHead(302, { - Location: 'views/chatRoom', - 'x-auth': res.data.access_token, }); - response.end(); - }).catch(err => console.log('me ERROR', err)); + }).catch(err => console.log('FB /ME ERROR:', err)); }).catch((err) => { - console.log('token exchange ERROR', err); + console.log('FB /TOKEN EXCHANGE ERROR:', err); response.send('Something went wrong.\nNo login for you.'); }); }); diff --git a/server/web/web.js b/server/web/web.js index 15d3b84..3014213 100644 --- a/server/web/web.js +++ b/server/web/web.js @@ -1,15 +1,16 @@ const { io } = require('../server.js'); const { request } = require('https'); const { Chat } = require('../db/model/chat'); +const axios = require('axios'); const web = { - // send message to web interface + // Send message to web interface sendMessage(data) { io.emit('newMessage', data); }, - // send chat to chat list in web interface + // Send chat to chat list in web interface newChat(data) { io.emit('newChat', data); }, @@ -18,15 +19,15 @@ const web = { io.on('connection', (socket) => { + // Send chats to populate chat list socket.on('getChats', () => { - Chat.findChats().then((chats) => { - let data; - if (!chats) { - data = null; + Chat.findChats().then((chatsResult) => { + let chats; + if (!chatsResult) { + chats = null; } else { - // don't send messages from chats user isn't seeing - data = chats.map((obj, key) => { - const msg = obj; + // Just send all messages for active chat. The others get last message for preview + chats = chatsResult.map((msg, key) => { if (key !== 0) { msg.messages = [ msg.messages[msg.messages.length - 1], @@ -35,17 +36,20 @@ io.on('connection', (socket) => { return msg; }); } - socket.emit('populateChats', { chats: data }); + + socket.emit('populateChats', { chats }); + }).catch(err => console.log(err)); }); + // Send chat messages on change active chat socket.on('getChatMessages', (chatId) => { Chat.findChatById(chatId).then((data) => { socket.emit('populateChatMessages', { messages: data.messages }); }).catch(err => console.log(err)); }); - // send message to user on Telegram + // Send message to Telegram client socket.on('sendTelegram', (data) => { const postData = JSON.stringify({ @@ -54,46 +58,49 @@ io.on('connection', (socket) => { text: data.message, }); - const options = { - hostname: 'api.telegram.org', - port: 443, - path: '/bot266093667:AAGi5U5Rdf4Di-zwJ1aFcm7idJN7Xt7tyZw/sendMessage', - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Content-Length': Buffer.byteLength(postData), - }, - }; - - const req = request(options, (res) => { - // console.log('statusCode:', res.statusCode); - // console.log('headers:', res.headers); - let body = ''; - - res.on('data', (d) => { - body += d; - }); - - res.on('end', () => { - body = JSON.parse(body); - if (body.ok) { - const message = { - author: 'Telebot', - message: data.message, - } - - Chat.insertMessage(data.chat_id, message); - } - }); - }); - - req.write(postData); - - req.on('error', (e) => { - console.error(e); - }); + // const options = { + // // hostname: 'api.telegram.org', + // // port: 443, + // // path: '/bot266093667:AAGi5U5Rdf4Di-zwJ1aFcm7idJN7Xt7tyZw/sendMessage', + // // method: 'POST', + // // headers: { + // // 'Content-Type': 'application/json', + // // 'Content-Length': Buffer.byteLength(postData), + // // }, + // }; + + axios.post(`https://api.telegram.org/bot${process.env.BOT_TOKEN}/sendMessage`, postData) + .then((res) => { + const message = { + author: 'Telebot', + message: res.data.message, + } - req.end(); + Chat.insertMessage(data.chat_id, message); + + }).catch(err => console.log('on.sendTelegram:', err)); + + // const req = request(options, (res) => { + // let body = ''; + // + // res.on('data', (d) => { + // body += d; + // }); + // + // res.on('end', () => { + // body = JSON.parse(body); + // if (body.ok) { + // } + // }); + // }); + + // req.write(postData); + // + // req.on('error', (e) => { + // console.error(e); + // }); + // + // req.end(); // run callback from client socket // callback();