Skip to content

Commit

Permalink
Set comments for methods
Browse files Browse the repository at this point in the history
  • Loading branch information
jpenna committed Jan 20, 2017
1 parent f09abdd commit d4639a3
Show file tree
Hide file tree
Showing 8 changed files with 155 additions and 126 deletions.
3 changes: 2 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 10 additions & 9 deletions server/bot/bot.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,42 @@
/* 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',
message: msg.text,
sentAt: new Date().getTime(),
};

Chat.insertMessage(data);
web.sendMessage(data);
Chat.insertMessage(messageData);
web.sendMessage(messageData);
botReply.send(reply, msg, 'Hello!');
});
15 changes: 7 additions & 8 deletions server/bot/botReply.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
77 changes: 40 additions & 37 deletions server/bot/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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

};

Expand Down
2 changes: 2 additions & 0 deletions server/config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
1 change: 0 additions & 1 deletion server/db/model/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ userSchema.statics.findUserByToken = function (token) {
return this.findOne({ token });
};


userSchema.statics.findUserById = function (id) {
return this.findOne({ id });
};
Expand Down
57 changes: 37 additions & 20 deletions server/web/authenticate.js
Original file line number Diff line number Diff line change
Expand Up @@ -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('|');
Expand All @@ -43,52 +55,57 @@ auth.post('/sendcode', (request, response) => {
access_token: appAccessToken,
};

// exchange tokens
// Exchange tokens
axios.get(tokenExchangeBaseUrl, { params })
.then((res) => {

const meParams = {
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.');
});
});
Expand Down
Loading

0 comments on commit d4639a3

Please sign in to comment.