2022-08-29 18:54:43 +03:00
|
|
|
import type { ParsedUpdate } from '@mtcute/client'
|
2022-07-19 02:47:59 +03:00
|
|
|
import { I18nValue } from './types'
|
|
|
|
|
2022-08-29 18:54:43 +03:00
|
|
|
let client: any
|
|
|
|
try {
|
|
|
|
client = require('@mtcute/client')
|
|
|
|
} catch (e) {}
|
|
|
|
|
2022-09-12 15:01:43 +03:00
|
|
|
/**
|
|
|
|
* Create an index of i18n strings delimited by "."
|
|
|
|
*
|
|
|
|
* @param strings Strings object
|
|
|
|
*/
|
2022-07-19 02:47:59 +03:00
|
|
|
export function createI18nStringsIndex(
|
|
|
|
strings: Record<string, any>
|
|
|
|
): Record<string, I18nValue> {
|
|
|
|
const ret: Record<string, I18nValue> = {}
|
|
|
|
|
|
|
|
function add(obj: Record<string, any>, prefix: string) {
|
|
|
|
for (const key in obj) {
|
|
|
|
const val = obj[key]
|
|
|
|
|
|
|
|
if (typeof val === 'object') {
|
|
|
|
add(val, prefix + key + '.')
|
|
|
|
} else {
|
|
|
|
ret[prefix + key] = val
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
add(strings, '')
|
|
|
|
|
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
2022-09-12 15:01:43 +03:00
|
|
|
/**
|
|
|
|
* Extract language from `@mtcute/client` update. Can be used for customized
|
|
|
|
* adapters or external i18n libraries.
|
|
|
|
*
|
|
|
|
* @param update Update to extract language from
|
|
|
|
*/
|
2022-07-19 02:47:59 +03:00
|
|
|
export function extractLanguageFromUpdate(
|
|
|
|
update: ParsedUpdate['data']
|
|
|
|
): string | null | undefined {
|
2022-08-29 18:54:43 +03:00
|
|
|
if (!client) {
|
|
|
|
throw new Error(
|
|
|
|
'@mtcute/client is not installed, you must provide your own adapter'
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
const upd = update as any
|
|
|
|
switch (upd.constructor) {
|
|
|
|
case client.Message:
|
2022-07-19 02:47:59 +03:00
|
|
|
// if sender is Chat it will just be undefined
|
2022-08-29 18:54:43 +03:00
|
|
|
return upd.sender.language
|
|
|
|
case client.ChatMemberUpdate:
|
|
|
|
case client.InlineQuery:
|
|
|
|
case client.ChosenInlineResult:
|
|
|
|
case client.CallbackQuery:
|
|
|
|
case client.PollVoteUpdate:
|
|
|
|
case client.BotStoppedUpdate:
|
|
|
|
case client.BotChatJoinRequestUpdate:
|
|
|
|
return upd.user.language
|
2022-07-19 02:47:59 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return null
|
|
|
|
}
|