Skip to content

Commit

Permalink
Merge pull request #14 from cyxou/configure-session-persistence
Browse files Browse the repository at this point in the history
Configure session persistence
  • Loading branch information
cyxou authored Feb 11, 2023
2 parents 16193e6 + 731c428 commit 3e51bb1
Show file tree
Hide file tree
Showing 14 changed files with 146 additions and 211 deletions.
15 changes: 13 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "firefly-iii-telegram-bot",
"description": "A Telegram bot for working with Firefly III with a supersonic speed",
"version": "1.0.2",
"version": "1.1.0",
"homepage": "https://github.com/cyxou/firefly-iii-telegram-bot#readme",
"license": "GPL-3.0-or-later",
"repository": {
Expand Down Expand Up @@ -43,6 +43,7 @@
"@grammyjs/i18n": "0.5.1",
"@grammyjs/menu": "1.1.2",
"@grammyjs/router": "2.0.0",
"@grammyjs/storage-file": "2.1.0",
"axios": "1.2.6",
"dayjs": "1.11.7",
"debug": "4.3.4",
Expand Down
4 changes: 2 additions & 2 deletions src/composers/accounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ async function showAccounts(ctx: MyContext) {
log(`Entered showAccounts callback handler...`)
try {
log('ctx: %O', ctx)
const userId = ctx.from!.id
const userSettings = ctx.session.userSettings
const isRegularMessage = !!ctx.update.message
log('isRegularMessage: %O', isRegularMessage)
log('ctx.match: %O', ctx.match)
Expand All @@ -50,7 +50,7 @@ async function showAccounts(ctx: MyContext) {
}
log('accType: %O', accType)

const accounts = (await firefly(userId).Accounts.listAccount(
const accounts = (await firefly(userSettings).Accounts.listAccount(
page, balanceToDate, accType as AccountTypeFilter)).data.data
log('accounts: %O', accounts)

Expand Down
30 changes: 15 additions & 15 deletions src/composers/categories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,12 +134,12 @@ async function doDeleteCategoryCbQH(ctx: MyContext) {
const log = rootLog.extend('doDeleteCategoryCbQH')
log('Entered the doDeleteCategoryCbQH...')
try {
const userId = ctx.from!.id
const userSettings = ctx.session.userSettings
log('ctx.match: %O', ctx.match)
const categoryId = ctx.match![1]
log('categoryId: %O', categoryId)

await firefly(userId).Categories.deleteCategory(categoryId)
await firefly(userSettings).Categories.deleteCategory(categoryId)
await ctx.answerCallbackQuery({ text: ctx.i18n.t('categories.deleted') })

return replyWithListOfCategories(ctx)
Expand Down Expand Up @@ -179,13 +179,13 @@ async function newCategoryNameRouteHandler(ctx: MyContext) {
const log = rootLog.extend('newCategoryNameRouteHandler')
log('Entered newCategoryNameRouteHandler...')
try {
const userId = ctx.from!.id
const userSettings = ctx.session.userSettings
log('ctx.session: %O', ctx.session)
const text = ctx.msg?.text || ''

const categoryId = ctx.session.category.id

await firefly(userId).Categories.updateCategory(categoryId, { name: text })
await firefly(userSettings).Categories.updateCategory(categoryId, { name: text })
return replyWithListOfCategories(ctx)
} catch (err) {
console.error(err)
Expand Down Expand Up @@ -223,11 +223,11 @@ function parseCategoriesInput(input: string) {
async function confirmCategoriesCbQH(ctx: MyContext) {
const log = rootLog.extend('confirmCategoriesCbQH')
try {
log('Creating categories in firefly(userId): %O', ctx.session.newCategories)
const userId = ctx.from!.id
log('Creating categories in firefly: %O', ctx.session.newCategories)
const userSettings = ctx.session.userSettings

for (const category of ctx.session.newCategories) {
await firefly(userId).Categories.storeCategory({ name: category })
await firefly(userSettings).Categories.storeCategory({ name: category })
}

await ctx.answerCallbackQuery({ text: 'Категории созданы!' })
Expand All @@ -241,8 +241,8 @@ async function replyWithListOfCategories(ctx: MyContext) {
const log = rootLog.extend('replyWithListOfCategories')
log('ctx: %O', ctx)
try {
const userId = ctx.from!.id
const categories = (await firefly(userId).Categories.listCategory()).data.data
const userSettings = ctx.session.userSettings
const categories = (await firefly(userSettings).Categories.listCategory()).data.data
const categoriesNames = categories.map((c: any) => c.attributes.name)
// log('categories: %O', categories)

Expand Down Expand Up @@ -273,8 +273,8 @@ async function replyWithListOfCategories(ctx: MyContext) {
export async function createCategoriesInlineKeyboard(ctx: MyContext): Promise<InlineKeyboard> {
const log = rootLog.extend('createCategoriesInlineKeyboard')
try {
const userId = ctx.from!.id
const categories = (await firefly(userId).Categories.listCategory()).data.data
const userSettings = ctx.session.userSettings
const categories = (await firefly(userSettings).Categories.listCategory()).data.data
const keyboard = new InlineKeyboard()
const nowDate = dayjs().format('YYYY-MM-DD')

Expand Down Expand Up @@ -304,7 +304,7 @@ async function showCategoryDetails(ctx: MyContext) {
const log = rootLog.extend('showCategoryDetails')
try {
await ctx.answerCallbackQuery()
const userId = ctx.from!.id
const userSettings = ctx.session.userSettings
const categoryId = ctx.match![1]
const startDate = ctx.match![2]
log('ctx.match: %O', ctx.match)
Expand All @@ -316,10 +316,10 @@ async function showCategoryDetails(ctx: MyContext) {
log('start: %O', start)
log('end: %O', end)

const categoryPromise = firefly(userId).Categories.getCategory(categoryId)
const categoryTransactionsPromise = firefly(userId).Categories
const categoryPromise = firefly(userSettings).Categories.getCategory(categoryId)
const categoryTransactionsPromise = firefly(userSettings).Categories
.listTransactionByCategory(categoryId, 1, start, end)
const expenseCategoriesPromise = firefly(userId).Insight
const expenseCategoriesPromise = firefly(userSettings).Insight
.insightExpenseCategory(start, end, [parseInt(categoryId, 10)])

// Resolve all the promises
Expand Down
17 changes: 7 additions & 10 deletions src/composers/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { Keyboard, InlineKeyboard } from 'grammy'
import firefly from '../lib/firefly'
import Mapper from '../lib/Mapper'
import type { MyContext } from '../types/MyContext'
import { getUserStorage } from '../lib/storage'
import { TransactionRead } from '../lib/firefly/model/transaction-read'
import { TransactionTypeProperty } from '../lib/firefly/model/transaction-type-property'
import { TransactionSplit } from '../lib/firefly/model/transaction-split'
Expand Down Expand Up @@ -145,10 +144,10 @@ function formatTransaction(ctx: MyContext, tr: Partial<TransactionRead>){
return ctx.i18n.t(translationString, { ...baseProps })
}

async function createCategoriesKeyboard(userId: number, mapper: Mapper) {
async function createCategoriesKeyboard(ctx: MyContext, mapper: Mapper) {
const log = debug.extend('createCategoriesKeyboard')
try {
const categories = (await firefly(userId).Categories.listCategory()).data.data
const categories = (await firefly(ctx.session.userSettings).Categories.listCategory()).data.data
log('categories: %O', categories)

const keyboard = new InlineKeyboard()
Expand All @@ -173,7 +172,7 @@ async function createCategoriesKeyboard(userId: number, mapper: Mapper) {
}

async function createAccountsKeyboard(
userId: number,
ctx: MyContext,
accountType: AccountTypeFilter | AccountTypeFilter[],
mapper: Mapper,
opts?: { skipAccountId: string }
Expand All @@ -185,7 +184,7 @@ async function createAccountsKeyboard(

if (Array.isArray(accountType)) {
const promises: any = []
accountType.forEach(accType => promises.push(firefly(userId).Accounts.listAccount(1, now, accType)))
accountType.forEach(accType => promises.push(firefly(ctx.session.userSettings).Accounts.listAccount(1, now, accType)))
const responses = await Promise.all(promises)

log('Responses length: %s', responses.length)
Expand All @@ -194,7 +193,7 @@ async function createAccountsKeyboard(
return r.data.data
}))
} else {
accounts = (await firefly(userId).Accounts.listAccount(1, now, accountType)).data.data
accounts = (await firefly(ctx.session.userSettings).Accounts.listAccount(1, now, accountType)).data.data
}

log('accounts: %O', accounts)
Expand Down Expand Up @@ -274,8 +273,7 @@ function formatTransactionUpdate(
function createEditMenuKeyboard(ctx: MyContext, tr: TransactionRead) {
const keyboard = new InlineKeyboard()
const trId = tr.id
const userId = ctx.from!.id
const { fireflyUrl } = getUserStorage(userId)
const { fireflyUrl } = ctx.session.userSettings

// Only withdrawal transactions may have category assigned
if (tr.attributes.transactions[0].type === 'withdrawal') {
Expand Down Expand Up @@ -357,8 +355,7 @@ function generateWelcomeMessage(ctx: MyContext) {
const log = debug.extend('generateWelcomeMessage')

log('start: %O', ctx.message)
const userId = ctx.from!.id
const { fireflyUrl, fireflyAccessToken } = getUserStorage(userId)
const { fireflyUrl, fireflyAccessToken } = ctx.session.userSettings

let welcomeMessage: string = ctx.i18n.t('welcome')
const isConfigured = !!(fireflyUrl && fireflyAccessToken)
Expand Down
40 changes: 15 additions & 25 deletions src/composers/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import type { MyContext } from '../types/MyContext'
import i18n, { getLanguageIcon } from '../lib/i18n';
import { command } from '../lib/constants'
import { createMainKeyboard, generateWelcomeMessage } from './helpers'
import { getUserStorage } from '../lib/storage'
import firefly from '../lib/firefly'
import { AccountTypeFilter } from '../lib/firefly/model/account-type-filter'
import { AccountRead } from '../lib/firefly/model/account-read'
Expand Down Expand Up @@ -55,13 +54,12 @@ bot.use(router)
export default bot

function settingsText(ctx: MyContext) {
const userId = ctx.from!.id
const {
fireflyUrl,
fireflyAccessToken,
defaultSourceAccount,
language
} = getUserStorage(userId)
} = ctx.session.userSettings

// Grab only first 4 and last 4 chars of the token
const accessToken = fireflyAccessToken?.replace(/(.{4})(.*?)(.{4})$/, '$1...$3')
Expand Down Expand Up @@ -108,8 +106,6 @@ async function fireflyAccessTokenRouteHandler(ctx: MyContext) {
const log = rootLog.extend('fireflyAccessTokenRouteHandler')
log('Entered fireflyAccessTokenRouteHandler...')
try {
const userId = ctx.from!.id
const storage = getUserStorage(userId)
log('ctx.msg: %O', ctx.msg)
const text = ctx.msg!.text as string
log('User entered text: %s', text)
Expand All @@ -122,7 +118,7 @@ async function fireflyAccessTokenRouteHandler(ctx: MyContext) {
})
}

storage.fireflyAccessToken = text
ctx.session.userSettings.fireflyAccessToken = text
ctx.session.step = 'IDLE'

return ctx.reply(
Expand All @@ -137,8 +133,6 @@ async function fireflyUrlRouteHandler(ctx: MyContext) {
const log = rootLog.extend('fireflyUrlRouteHandler')
log('Entered fireflyUrlRouteHandler...')
try {
const userId = ctx.from!.id
const storage = getUserStorage(userId)
log('ctx.msg: %O', ctx.msg)
const text = ctx.msg!.text as string
log('User entered text: %s', text)
Expand All @@ -153,7 +147,8 @@ async function fireflyUrlRouteHandler(ctx: MyContext) {
})
}

storage.fireflyUrl = text
ctx.session.userSettings.fireflyUrl = text
ctx.session.userSettings.fireflyApiUrl = text
ctx.session.step = 'IDLE'

return ctx.reply(
Expand Down Expand Up @@ -200,9 +195,8 @@ async function selectDefaultAssetAccountCbQH(ctx: MyContext) {
const log = rootLog.extend('selectDefaultAssetAccountCbQH')
log(`Entered the ${SELECT_DEFAULT_ASSET_ACCOUNT} callback query handler`)
try {
const userId = ctx.from!.id
const { fireflyUrl, fireflyAccessToken } = getUserStorage(userId)
log('userId: %s', userId)
const userSettings = ctx.session.userSettings
const { fireflyUrl, fireflyAccessToken } = userSettings

if (!fireflyUrl) {
return ctx.answerCallbackQuery({
Expand All @@ -222,7 +216,7 @@ async function selectDefaultAssetAccountCbQH(ctx: MyContext) {
})
}

const accounts: AccountRead[] = (await firefly(userId).Accounts.listAccount(
const accounts: AccountRead[] = (await firefly(userSettings).Accounts.listAccount(
1, dayjs().format('YYYY-MM-DD'), AccountTypeFilter.Asset)).data.data
log('accounts: %O', accounts)

Expand Down Expand Up @@ -260,15 +254,15 @@ async function defaultAccountCbQH(ctx: MyContext) {
log(`Entered the ${SELECT_DEFAULT_ASSET_ACCOUNT} query handler`)
try {
log('ctx: %O', ctx)
const userId = ctx.from!.id
const storage = getUserStorage(userId)
const accountId = ctx.match![1]
log('accountId: %s', accountId)

const account = (await firefly(userId).Accounts.getAccount(accountId)).data.data
const userSettings = ctx.session.userSettings

const account = (await firefly(userSettings).Accounts.getAccount(accountId)).data.data
log('account: %O', account)

storage.defaultSourceAccount = {
userSettings.defaultSourceAccount = {
id: accountId.toString(),
name: account.attributes.name,
type: account.attributes.type
Expand All @@ -289,8 +283,6 @@ async function cancelCbQH(ctx: MyContext) {
const log = rootLog.extend('cancelCbQH')
try {
log('Cancelling...: ')
const userId = ctx.from!.id
log('userId: %O', userId)

ctx.session.step = 'IDLE'

Expand All @@ -309,8 +301,8 @@ async function testConnectionCbQH(ctx: MyContext) {
log('Entered testConnectionCbQH action handler')
log('ctx: %O', ctx)
try {
const userId = ctx.from!.id
const { fireflyUrl, fireflyAccessToken } = getUserStorage(userId)
const userSettings = ctx.session.userSettings
const { fireflyUrl, fireflyAccessToken } = userSettings

if (!fireflyUrl) {
return ctx.answerCallbackQuery({
Expand All @@ -330,7 +322,7 @@ async function testConnectionCbQH(ctx: MyContext) {
})
}

const userInfo = (await firefly(userId).About.getCurrentUser()).data.data
const userInfo = (await firefly(userSettings).About.getCurrentUser()).data.data
log('Firefly user info: %O', userInfo)

if (!userInfo) return ctx.answerCallbackQuery({
Expand All @@ -353,14 +345,12 @@ async function switchLanguageCbQH(ctx: MyContext) {
log(`Entered the switch language query handler`)
try {
log('ctx: %O', ctx)
const userId = ctx.from!.id
const storage = getUserStorage(userId)
const language = ctx.match![1]
log('language: %O', language)

ctx.i18n.locale(language)
dayjs.locale(language)
storage.language = language
ctx.session.userSettings.language = language

const welcomeMessage = generateWelcomeMessage(ctx)

Expand Down
Loading

0 comments on commit 3e51bb1

Please sign in to comment.