diff --git a/botEngine.js b/botEngine.js new file mode 100644 index 0000000..5567e08 --- /dev/null +++ b/botEngine.js @@ -0,0 +1,198 @@ +const fs = require('fs'); +const path = require('path'); + +const TelegramBot = require('node-telegram-bot-api'); + +const config = require('./config'); + +let admin_chatId = null; +let authorizedUsers; +let telegram; +const SLIDESHOW_LOCATION = config.slideShowFolderPath; + +// Functions +function storeFile(fileId, callback) { + telegram.downloadFile(fileId, SLIDESHOW_LOCATION) + .then((filePath) => { + let message = config.messages.sendieResponse.fileSuccessfullySaved; + message = message.replace('{fileLocation}', filePath); + callback(null, filePath); + }) + .catch((err) => { + callback(err); + }); +} + +let storeFileCallback = (err, filePath, chatId, photoId) => { + let response; + if (err) { + response = config.messages.sendieResponse.failedToSaveFile; + response = response.replace('{error}', err); + telegram.sendMessage(chatId, response); + response = config.messages.sendieResponse.failedToSaveFile; + response = response.replace('{error}', err); + if (admin_chatId !== chatId) notifyAdmin(response, photoId); + } else { + response = config.messages.sendieResponse.fileSuccessfullySaved; + response = message.replace('{fileLocation}', filePath); + telegram.sendMessage(chatId, response); + response = config.messages.adminNotifications.fileSuccessfullySaved; + response = message.replace('{fileLocation}', filePath); + if (admin_chatId !== chatId) notifyAdmin(response, photoId); + } +}; + +let handleMessage = (msg) => { + const chatId = msg.chat.id; + if (msg.photo || (msg.document && msg.document.mime_type.indexOf('image/') === 0)) { // Handle Images + if (msg.photo) { + storeFile(msg.photo[msg.photo.length - 1].file_id, (err, filePath) => { + storeFileCallback(err, filePath, chatId, msg.photo[msg.photo.length - 1].file_id); + }); + } else { // document - uncompressed photo + storeFile(msg.document.file_id, (err, filePath) => { + storeFileCallback(err, filePath, chatId, msg.document.file_id); + }); + } + } else if (msg.contact) { // Handle Contact + addRemoveUser(msg.contact, msg.from); + } else { + // send a message to the chat acknowledging receipt of their message + let message = config.messages.sendieResponse.unableToDoThat; + message = message.replace('{username}', msg.from.username); + telegram.sendMessage(chatId, message); + } +}; + +let userAllowd = (msg) => { + if (msg.from.id === config.admin.id) { + admin_chatId = msg.chat.id; + return true; + } + if (config.permissions.allowAll) return true; + if (authorizedUsers.indexOf(msg.from.id) >= 0) return true; + return false; +}; + +let notifyAdmin = (msg, photo_id) => { + if (admin_chatId != null && config.admin.notifyActivity) { + telegram.sendMessage(admin_chatId, msg); + if (photo_id && config.admin.sendPhotoOnSave) telegram.sendPhoto(admin_chatId, photo_id); + } +}; + +let addRemoveUser = (contact, from) => { + if (!config.permissions.allowAddingUsers) { + // Ignore... + console.warn('Attempt to add/remove a user. this functionality is disabled.'); + return; + } else { + if (from.id != config.admin.id && !config.permissions.allowNonAdminToAddUsers) { + telegram.sendMessage(from.id, config.messages.sendieResponse.noPermissions); + console.warn('Attempt to add/remove a user from an unpermited user. id: ', from.id); + return; + } + } + let toAdd = true; + if (authorizedUsers.indexOf(contact.user_id) < 0) { + // Add user + authorizedUsers.push(contact.user_id); + } else { + // remove user + toAdd = false; + authorizedUsers.splice(authorizedUsers.indexOf(contact.user_id), 1); + } + if (saveToDB()) { + let message; + if (toAdd) message = config.messages.sendieResponse.userAdded; + else message = config.messages.sendieResponse.userRemoved; + message = message.replace('{username}', contact.first_name); + telegram.sendMessage(from.id, message); // response to the user that added the new one + // Not supported yet - a bot can't start a chat with a new user... so can't do this. + // if(toAdd) message = config.messages.userAdded.added; + // else message = config.messages.userRemoved.removed; + // message = message.replace('{username_add_rem}', contact.first_name); + // message = message.replace('{username}', from.first_name); + // telegram.sendMessage(contact.user_id, message); // Notify the new/old user + if (toAdd) message = config.messages.adminNotifications.userAdded; + else message = config.messages.adminNotifications.userRemoved; + message = message.replace('{username_add_rem}', contact.first_name); + message = message.replace('{username}', from.first_name); + if (from.id != config.admin.id) notifyAdmin(message); // notifyAdmin + } else { + console.log('Failed to save DB!!!'); + } +} + +let loadDB = () => { + let dbLocation = config.DBLocation; + if (dbLocation[dbLocation.length - 1] != '/') dbLocation += '/users.json'; + else dbLocation += 'users.json'; + try { + data = fs.readFileSync(path.resolve(dbLocation)); + try { + authorizedUsers = JSON.parse(data.toString()); + console.log('DB loaded. AuthorizedUsers: ', authorizedUsers); + } catch (err) { + console.error('DB file is corrupted. Please delete the file', dbLocation, 'And rerun this service'); + process.exit(1); + } + } catch (err) { + authorizedUsers = []; + if (saveToDB()) { + console.log('DB was created. Everything is Okay.'); + } else { + console.error('Unable to read from DB. Error:\n', err); + process.exit(1); + } + } +} + +let saveToDB = () => { + let dbLocation = config.DBLocation; + if (dbLocation[dbLocation.length - 1] != '/') dbLocation += '/users.json'; + else dbLocation += 'users.json'; + try { + fs.writeFileSync(dbLocation, JSON.stringify(authorizedUsers)); + return true; + } catch (err) { + console.error('Failed to save to DB... ERROR:\n', err); + return false; + } +} + +let runBot = (args) => { + /****** Run script ******/ + loadDB(); + + telegram = new TelegramBot(config.botId, { + polling: true + }); + telegram.on('message', (msg) => { + const chatId = msg.chat.id; + if (args.indexOf('--printMessage') > 0) { + console.log(JSON.stringify(msg, null, 2)); + process.exit(0); + } + if (userAllowd(msg)) { + handleMessage(msg); + } else { + let message = config.messages.sendieResponse.unauthorizedUser; + message = message.replace('{username}', msg.from.username); + message = message.replace('{messageObj}', JSON.stringify(msg, null, 2)); + telegram.sendMessage(chatId, message); + message = config.messages.adminNotifications.unauthorizedUser; + message = message.replace('{username}', msg.from.username); + message = message.replace('{messageObj}', JSON.stringify(msg, null, 2)); + console.warn(message); + notifyAdmin(message); + } + + }); +} + + + +module.exports = { + runBot: runBot +} diff --git a/config.js b/config.js index 567d3f4..bf425cc 100644 --- a/config.js +++ b/config.js @@ -32,10 +32,10 @@ module.exports = { userAdded: 'Okay, {username} was added as a trusted user.', // Placeholders: {username} userRemoved: 'Sure, I\'ll stop supporting {username}.' // Plaseholers: {username} }, - userAdded: { + userAdded: { // Not supported yet added: 'Hi {username_add_rem},\n{username} added you as a trusted user. this means that you can send me photos to add to the slide show! Try it now' // Plaseholers: {username}, {username_add_rem} }, - userRemoved:{ + userRemoved:{ // Not supported yet removed: 'Hi {username_add_rem},\n{username} removed you from my system... It\'s not you, it\'s me :(' // Plaseholers: {username}, {username_add_rem} } } diff --git a/index.js b/index.js index 3c8b52c..120fcc2 100644 --- a/index.js +++ b/index.js @@ -1,188 +1,3 @@ -const fs = require('fs'); -const path = require('path'); +const botEngine = require('./botEngine'); -const TelegramBot = require('node-telegram-bot-api'); - -const config = require('./config'); - -let admin_chatId = null; -let authorizedUsers; - -const SLIDESHOW_LOCATION = config.slideShowFolderPath; - -// Functions -function storeFile(fileId, callback) { - telegram.downloadFile(fileId, SLIDESHOW_LOCATION) - .then((filePath) => { - let message = config.messages.sendieResponse.fileSuccessfullySaved; - message = message.replace('{fileLocation}', filePath); - callback(null, filePath); - }) - .catch((err) => { - callback(err); - }); -} - -let storeFileCallback = (err, filePath, chatId, photoId) => { - let response; - if (err) { - response = config.messages.sendieResponse.failedToSaveFile; - response = response.replace('{error}', err); - telegram.sendMessage(chatId, response); - response = config.messages.sendieResponse.failedToSaveFile; - response = response.replace('{error}', err); - if (admin_chatId !== chatId) notifyAdmin(response, photoId); - } else { - response = config.messages.sendieResponse.fileSuccessfullySaved; - response = message.replace('{fileLocation}', filePath); - telegram.sendMessage(chatId, response); - response = config.messages.adminNotifications.fileSuccessfullySaved; - response = message.replace('{fileLocation}', filePath); - if (admin_chatId !== chatId) notifyAdmin(response, photoId); - } -}; - -let handleMessage = (msg) => { - const chatId = msg.chat.id; - if (msg.photo || (msg.document && msg.document.mime_type.indexOf('image/') === 0)) { // Handle Images - if (msg.photo) { - storeFile(msg.photo[msg.photo.length - 1].file_id, (err, filePath) => { - storeFileCallback(err, filePath, chatId, msg.photo[msg.photo.length - 1].file_id); - }); - } else { // document - uncompressed photo - storeFile(msg.document.file_id, (err, filePath) => { - storeFileCallback(err, filePath, chatId, msg.document.file_id); - }); - } - } else if (msg.contact) { // Handle Contact - addRemoveUser(msg.contact, msg.from); - } else { - // send a message to the chat acknowledging receipt of their message - let message = config.messages.sendieResponse.unableToDoThat; - message = message.replace('{username}', msg.from.username); - telegram.sendMessage(chatId, message); - } -}; - -let userAllowd = (msg) => { - if (msg.from.id === config.admin.id) { - admin_chatId = msg.chat.id; - return true; - } - if (config.permissions.allowAll) return true; - if (authorizedUsers.indexOf(msg.from.id) >= 0) return true; - return false; -}; - -let notifyAdmin = (msg, photo_id) => { - if (admin_chatId != null && config.admin.notifyActivity) { - telegram.sendMessage(admin_chatId, msg); - if (photo_id && config.admin.sendPhotoOnSave) telegram.sendPhoto(admin_chatId, photo_id); - } -}; - -let addRemoveUser = (contact, from) => { - if(!config.permissions.allowAddingUsers){ - // Ignore... - console.warn('Attempt to add/remove a user. this functionality is disabled.'); - return; - }else{ - if(from.id != config.admin.id && !config.permissions.allowNonAdminToAddUsers){ - telegram.sendMessage(from.id, config.messages.sendieResponse.noPermissions); - console.warn('Attempt to add/remove a user from an unpermited user. id: ',from.id); - return; - } - } - let toAdd = true; - if(authorizedUsers.indexOf(contact.user_id) < 0){ - // Add user - authorizedUsers.push(contact.user_id); - }else{ - // remove user - toAdd = false; - authorizedUsers.splice(authorizedUsers.indexOf(contact.user_id), 1); - } - if(saveToDB()){ - let message; - if(toAdd) message = config.messages.sendieResponse.userAdded; - else message = config.messages.sendieResponse.userRemoved; - message = message.replace('{username}', contact.first_name); - telegram.sendMessage(from.id, message); // response to the user that added the new one - if(toAdd) message = config.messages.userAdded.added; - else message = config.messages.userRemoved.removed; - message = message.replace('{username_add_rem}', contact.first_name); - message = message.replace('{username}', from.first_name); - telegram.sendMessage(contact.user_id, message); // Notify the new/old user - if(toAdd) message = config.messages.adminNotifications.userAdded; - else message = config.messages.adminNotifications.userRemoved; - message = message.replace('{username_add_rem}', contact.first_name); - message = message.replace('{username}', from.first_name); - if(from.id != config.admin.id) notifyAdmin(message); // notifyAdmin - }else{ - console.log('Failed to save DB!!!'); - } -} - -let loadDB = () => { - let dbLocation = config.DBLocation; - if (dbLocation[dbLocation.length - 1] != '/') dbLocation += '/users.json'; - else dbLocation += 'users.json'; - try{ - data = fs.readFileSync(path.resolve(dbLocation)); - try{ - authorizedUsers = JSON.parse(data.toString()); - console.log('DB loaded. AuthorizedUsers: ', authorizedUsers); - }catch(err){ - console.error('DB file is corrupted. Please delete the file', dbLocation, 'And rerun this service'); - process.exit(1); - } - }catch(err){ - authorizedUsers = []; - if(saveToDB()){ - console.log('DB was created. Everything is Okay.'); - }else{ - console.error('Unable to read from DB. Error:\n', err); - process.exit(1); - } - } -} - -let saveToDB = () => { - let dbLocation = config.DBLocation; - if (dbLocation[dbLocation.length - 1] != '/') dbLocation += '/users.json'; - else dbLocation += 'users.json'; - try{ - fs.writeFileSync(dbLocation, JSON.stringify(authorizedUsers)); - return true; - }catch(err){ - console.error('Failed to save to DB... ERROR:\n', err); - return false; - } -} -/****** Run script ******/ -loadDB(); - -let telegram = new TelegramBot(config.botId, { - polling: true -}); -telegram.on('message', (msg) => { - const chatId = msg.chat.id; - if(process.argv.indexOf('--printMessage') > 0){ - console.log(JSON.stringify(msg, null, 2)); - process.exit(0); - } - if (userAllowd(msg)) { - handleMessage(msg); - } else { - let message = config.messages.sendieResponse.unauthorizedUser; - message = message.replace('{username}', msg.from.username); - message = message.replace('{messageObj}', JSON.stringify(msg, null, 2)); - telegram.sendMessage(chatId, message); - message = config.messages.adminNotifications.unauthorizedUser; - message = message.replace('{username}', msg.from.username); - message = message.replace('{messageObj}', JSON.stringify(msg, null, 2)); - console.warn(message); - notifyAdmin(message); - } - -}); +botEngine.runBot(process.argv);