aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/assets/player/translations-manager.ts
blob: d5a09a31a71bfc71ee8c4088533a0d66a27e7220 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { getCompleteLocale, getShortLocale, is18nLocale, isDefaultLocale } from '@shared/core-utils/i18n'

export class TranslationsManager {
  private static videojsLocaleCache: { [ path: string ]: any } = {}

  static getServerTranslations (serverUrl: string, locale: string): Promise<{ [id: string]: string }> {
    const path = TranslationsManager.getLocalePath(serverUrl, locale)
    // It is the default locale, nothing to translate
    if (!path) return Promise.resolve(undefined)

    return fetch(path + '/server.json')
      .then(res => res.json())
      .catch(err => {
        console.error('Cannot get server translations', err)
        return undefined
      })
  }

  static loadLocaleInVideoJS (serverUrl: string, locale: string, videojs: any) {
    const path = TranslationsManager.getLocalePath(serverUrl, locale)
    // It is the default locale, nothing to translate
    if (!path) return Promise.resolve(undefined)

    let p: Promise<any>

    if (TranslationsManager.videojsLocaleCache[ path ]) {
      p = Promise.resolve(TranslationsManager.videojsLocaleCache[ path ])
    } else {
      p = fetch(path + '/player.json')
        .then(res => res.json())
        .then(json => {
          TranslationsManager.videojsLocaleCache[ path ] = json
          return json
        })
        .catch(err => {
          console.error('Cannot get player translations', err)
          return undefined
        })
    }

    const completeLocale = getCompleteLocale(locale)
    return p.then(json => videojs.addLanguage(getShortLocale(completeLocale), json))
  }

  private static getLocalePath (serverUrl: string, locale: string) {
    const completeLocale = getCompleteLocale(locale)

    if (!is18nLocale(completeLocale) || isDefaultLocale(completeLocale)) return undefined

    return serverUrl + '/client/locales/' + completeLocale
  }
}