]>
Commit | Line | Data |
---|---|---|
1 | import { logger } from '@root-helpers/logger' | |
2 | import { getCompleteLocale, getShortLocale, is18nLocale, isDefaultLocale } from '@shared/core-utils/i18n' | |
3 | ||
4 | export class TranslationsManager { | |
5 | private static videojsLocaleCache: { [ path: string ]: any } = {} | |
6 | ||
7 | static getServerTranslations (serverUrl: string, locale: string): Promise<{ [id: string]: string }> { | |
8 | const path = TranslationsManager.getLocalePath(serverUrl, locale) | |
9 | // It is the default locale, nothing to translate | |
10 | if (!path) return Promise.resolve(undefined) | |
11 | ||
12 | return fetch(path + '/server.json') | |
13 | .then(res => res.json()) | |
14 | .catch(err => { | |
15 | logger.error('Cannot get server translations', err) | |
16 | return undefined | |
17 | }) | |
18 | } | |
19 | ||
20 | static loadLocaleInVideoJS (serverUrl: string, locale: string, videojs: any) { | |
21 | const path = TranslationsManager.getLocalePath(serverUrl, locale) | |
22 | // It is the default locale, nothing to translate | |
23 | if (!path) return Promise.resolve(undefined) | |
24 | ||
25 | let p: Promise<any> | |
26 | ||
27 | if (TranslationsManager.videojsLocaleCache[path]) { | |
28 | p = Promise.resolve(TranslationsManager.videojsLocaleCache[path]) | |
29 | } else { | |
30 | p = fetch(path + '/player.json') | |
31 | .then(res => res.json()) | |
32 | .then(json => { | |
33 | TranslationsManager.videojsLocaleCache[path] = json | |
34 | return json | |
35 | }) | |
36 | .catch(err => { | |
37 | logger.error('Cannot get player translations', err) | |
38 | return undefined | |
39 | }) | |
40 | } | |
41 | ||
42 | const completeLocale = getCompleteLocale(locale) | |
43 | return p.then(json => videojs.addLanguage(getShortLocale(completeLocale), json)) | |
44 | } | |
45 | ||
46 | private static getLocalePath (serverUrl: string, locale: string) { | |
47 | const completeLocale = getCompleteLocale(locale) | |
48 | ||
49 | if (!is18nLocale(completeLocale) || isDefaultLocale(completeLocale)) return undefined | |
50 | ||
51 | return serverUrl + '/client/locales/' + completeLocale | |
52 | } | |
53 | } |