2023-10-16 19:23:53 +03:00
|
|
|
import type * as dispatcherNs from '@mtcute/dispatcher'
|
2022-07-19 02:47:59 +03:00
|
|
|
|
2023-10-16 19:23:53 +03:00
|
|
|
import { I18nStrings, I18nValue } from './types.js'
|
2022-08-29 18:54:43 +03:00
|
|
|
|
2022-09-12 15:01:43 +03:00
|
|
|
/**
|
|
|
|
* Create an index of i18n strings delimited by "."
|
|
|
|
*
|
|
|
|
* @param strings Strings object
|
|
|
|
*/
|
2023-09-24 01:32:22 +03:00
|
|
|
export function createI18nStringsIndex(strings: I18nStrings): Record<string, I18nValue> {
|
2022-07-19 02:47:59 +03:00
|
|
|
const ret: Record<string, I18nValue> = {}
|
|
|
|
|
2023-06-05 03:30:48 +03:00
|
|
|
function add(obj: I18nStrings, prefix: string) {
|
2022-07-19 02:47:59 +03:00
|
|
|
for (const key in obj) {
|
|
|
|
const val = obj[key]
|
|
|
|
|
2023-06-05 03:30:48 +03:00
|
|
|
if (typeof val === 'object' && !('value' in val)) {
|
2022-07-19 02:47:59 +03:00
|
|
|
add(val, prefix + key + '.')
|
|
|
|
} else {
|
2023-06-05 03:30:48 +03:00
|
|
|
ret[prefix + key] = val as string
|
2022-07-19 02:47:59 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
add(strings, '')
|
|
|
|
|
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
2022-09-12 15:01:43 +03:00
|
|
|
/**
|
2023-10-16 19:23:53 +03:00
|
|
|
* Extract language from `@mtcute/dispatcher` context.
|
|
|
|
* Can be used for customized adapters or external i18n libraries.
|
2022-09-12 15:01:43 +03:00
|
|
|
*
|
|
|
|
* @param update Update to extract language from
|
|
|
|
*/
|
2023-10-16 19:23:53 +03:00
|
|
|
export function extractLanguageFromUpdate(update: dispatcherNs.UpdateContextType): string | null | undefined {
|
|
|
|
if (!('_name' in update)) return null
|
|
|
|
|
|
|
|
// for whatever reason eslint doesn't like this
|
|
|
|
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-return */
|
|
|
|
switch (update._name) {
|
|
|
|
case 'new_message': {
|
|
|
|
const { sender } = update
|
2022-08-29 18:54:43 +03:00
|
|
|
|
2023-10-16 19:23:53 +03:00
|
|
|
return sender.type === 'user' ? sender.language : null
|
|
|
|
}
|
|
|
|
case 'poll_vote': {
|
|
|
|
const { peer } = update
|
|
|
|
|
|
|
|
return peer?.type === 'user' ? peer.language : null
|
|
|
|
}
|
|
|
|
case 'chat_member':
|
|
|
|
case 'inline_query':
|
|
|
|
case 'chosen_inline_result':
|
|
|
|
case 'callback_query':
|
|
|
|
case 'bot_stopped':
|
|
|
|
case 'bot_chat_join_request':
|
|
|
|
return update.user.language
|
2022-07-19 02:47:59 +03:00
|
|
|
}
|
2023-10-16 19:23:53 +03:00
|
|
|
/* eslint-enable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-return */
|
2022-07-19 02:47:59 +03:00
|
|
|
|
|
|
|
return null
|
|
|
|
}
|