Skip to content

Commit

Permalink
First attempt to start using a database
Browse files Browse the repository at this point in the history
  • Loading branch information
amire80 committed Jul 8, 2017
1 parent db6cdb0 commit 438043c
Show file tree
Hide file tree
Showing 4 changed files with 153 additions and 25 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,6 @@ node_modules

# Service configuration. Expected to be local and private.
config.json

# Database
db/telegram-bot.db
152 changes: 127 additions & 25 deletions MediaWikiTelegramBot.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ const TelegramBot = require("tgfancy");
const jsonfile = require("jsonfile");
const i18nCache = {};

const sqlite3 = require("sqlite3").verbose();
const db = new sqlite3.Database("db/telegram-bot.db");

const mwApi = require("./MediaWikiAPI.js");

const userStatus = {};
Expand Down Expand Up @@ -52,6 +55,27 @@ function debug(fromId, info, levelRequired) {
tgBot.sendMessage(fromId, info);
}

function userKnown(userID) {
return (userStatus[userID] !== undefined);
}

function initUser(userID) {
userStatus[userID] = {
languageCode: "",
currentMwMessageIndex: 0,
loadedMwMessages: [],
publishingTgMessages: {}
};
}

function getUser(userID) {
if (!userKnown(userID)) {
initUser(userID);
}

return userStatus[userID];
}

const REDIRECT_LANGUAGES = {
"en-us": "en",
"he-il": "he",
Expand All @@ -60,36 +84,58 @@ const REDIRECT_LANGUAGES = {
};

function normalizeLanguageCode(code) {
if (typeof code !== "string") {
code = "";
}

const lower = code.toLowerCase();

return REDIRECT_LANGUAGES[lower] || lower;
}

function initUser(userID) {
userStatus[userID] = {
languageCode: "",
currentMwMessageIndex: 0,
loadedMwMessages: [],
publishingTgMessages: {}
};
function addUserToDbByTgMsg(tgMsg, cb) {
const userID = tgMsg.from.id;
const insertStmtStr = `INSERT INTO user (user_telegram_id) VALUES (${userID})`;

console.log(insertStmtStr);
db.run(insertStmtStr, (error) => {
if (error !== null) {
console.log(`Adding user ${userID} to the database failed: ${error}`);

return;
}

cb();
});
}

function getUser(userID) {
if (userStatus[userID] === undefined) {
initUser(userID);
function updateClauseString(options) {
const updateClauseParts = [];
const columns = Object.keys(options);

for (let i = 0; i < columns.length; i++) {
updateClauseParts.push(`${columns[i]} = "${options[columns[i]]}"`);
}

return userStatus[userID];
return updateClauseParts.join(", ");
}

// Returns true if the parameter contains
// a string that can be sent to Telegram.
function validTgMessage(tgMsg) {
return (typeof tgMsg === "string") &&
// Telegram messages cannot be empty strings
(tgMsg !== "") &&
// The Telegram length hard limit is 4096
(tgMsg.length < 4096);
function updateUserInDb(userID, options, cb) {
const updateString =
`UPDATE user SET ${updateClauseString(options)} WHERE user_telegram_id = "${userID}"`;

console.log(`running update: ${updateString}`);
db.run(updateString, (error) => {
if (error !== null) {
console.log(`Updating user ${userID} in the db failed: ${error}.`);

return;
}

if (typeof cb === "function") {
cb();
}
});
}

// TODO: Should be much, much more detailed.
Expand All @@ -102,7 +148,7 @@ function getLanguageCode(userID) {
return getUser(userID).languageCode;
}

function setLanguageCode(userID, newLanguageCode) {
function setLanguageCode(userID, newLanguageCode, cb) {
const user = getUser(userID);

debug(
Expand All @@ -123,6 +169,56 @@ function setLanguageCode(userID, newLanguageCode) {
user.languageCode = newLanguageCode;
user.currentMwMessageIndex = 0;
user.loadedMwMessages = [];

updateUserInDb(userID, { user_language: newLanguageCode }, cb);
}

function loadUserFromDbByTgMsg(tgMsg, cb) {
const userID = tgMsg.from.id;
const selectString = `SELECT * FROM user WHERE user_telegram_id = '${userID}'`;

console.log(`loading user ${userID}: ${selectString}`);
db.all(selectString, (error, rows) => {
if (error !== null) {
console.log(`Loading user ${userID} failed: ${error}`);

return;
}

console.log(`Finished running user loading query. rows is a ${typeof rows}:`);
console.log(rows);

if (rows.length === 0) {
console.log(`User ${userID} not found. Adding...`);
addUserToDbByTgMsg(tgMsg, cb);

return;
}

if (rows.length === 1) {
initUser(userID);

setLanguageCode(userID, rows[0].user_language);

cb();

return;
}

console.log("There's more than one user with this id in the database");

tgBot.sendMessage(userID, "There's more than one user with this id in the database");
});
}

// Returns true if the parameter contains
// a string that can be sent to Telegram.
function validTgMessage(tgMsg) {
return (typeof tgMsg === "string") &&
// Telegram messages cannot be empty strings
(tgMsg !== "") &&
// The Telegram length hard limit is 4096
(tgMsg.length < 4096);
}

// TODO: Replace with something like jquery.i18n
Expand Down Expand Up @@ -555,11 +651,7 @@ tgBot.onText(/\/ttm/, (tgMsg, match) => {
showTranslationMemory(tgMsg.from.id);
});

// Matches anything without a slash in the beginning
tgBot.onText(/^([^\/].*)/, (tgMsg, match) => {
console.log("In slashless onText");
console.log(tgMsg);

function processSlashlessTgMessage(tgMsg) {
const userID = tgMsg.from.id;
const user = getUser(userID);
const targetMwMessage = getCurrentMwMessage(userID);
Expand Down Expand Up @@ -602,4 +694,14 @@ tgBot.onText(/^([^\/].*)/, (tgMsg, match) => {
i18n(languageCode, "tgbot-what-would-you-like-prompt"),
tgMsgOptions
);
}

// Matches anything without a slash in the beginning
tgBot.onText(/^([^\/].*)/, (tgMsg) => {
console.log("In slashless onText");
console.log(tgMsg);

loadUserFromDbByTgMsg(tgMsg, () => {
processSlashlessTgMessage(tgMsg);
});
});
22 changes: 22 additions & 0 deletions db/InitDatabase.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"use strict";

const sqlite3 = require("sqlite3").verbose();
const db = new sqlite3.Database("telegram-bot.db");

db.serialize(() => {
const userColumns = [
"user_telegram_id TEXT",
// "user_mediawiki_username TEXT",
// "user_oauth_key TEXT",
// "user_oauth_secret TEXT",
"user_language TEXT"
];
const userColumnsClause = userColumns.join(", ");
const userCreateStatement = `CREATE TABLE user (${userColumnsClause})`;

db.run("DROP TABLE IF EXISTS user");

db.run(userCreateStatement);
});

db.close();
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"jsonfile": "~3.0.0",
"read": "^1.0.7",
"request": "~2.81.0",
"sqlite3": "~3.1.8",
"tgfancy": "^0.10.0"
},
"devDependencies": {
Expand Down

0 comments on commit 438043c

Please sign in to comment.