2019-06-27 06:21:51 +02:00
|
|
|
import DefaultStrings from "../data/strings";
|
|
|
|
import DiscordModules from "./discordmodules";
|
|
|
|
import Utilities from "./utilities";
|
|
|
|
import Events from "./emitter";
|
|
|
|
import DataStore from "./datastore";
|
|
|
|
const request = require("request");
|
|
|
|
|
|
|
|
const {Dispatcher, DiscordConstants, UserSettingsStore} = DiscordModules;
|
|
|
|
|
|
|
|
export default new class LocaleManager {
|
|
|
|
get discordLocale() {return UserSettingsStore.locale.split("-")[0];}
|
|
|
|
get defaultLocale() {return "en";}
|
|
|
|
|
|
|
|
constructor() {
|
|
|
|
this.locale = "";
|
|
|
|
this.strings = {};
|
|
|
|
}
|
2019-06-28 01:50:20 +02:00
|
|
|
|
2019-06-27 06:21:51 +02:00
|
|
|
async initialize() {
|
|
|
|
await this.setLocale(this.discordLocale);
|
|
|
|
Dispatcher.subscribe(DiscordConstants.ActionTypes.USER_SETTINGS_UPDATE, ({settings}) => {
|
|
|
|
const newLocale = settings.locale;
|
|
|
|
if (newLocale && newLocale != this.locale) this.setLocale(newLocale.split("-")[0]);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async setLocale(newLocale) {
|
|
|
|
let newStrings;
|
|
|
|
if (newLocale != this.defaultLocale) {
|
2019-06-28 01:50:20 +02:00
|
|
|
newStrings = await this.getLocaleStrings(newLocale);
|
2019-06-27 06:21:51 +02:00
|
|
|
if (!newStrings) return this.setLocale(this.defaultLocale);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
newStrings = DefaultStrings;
|
|
|
|
}
|
|
|
|
this.locale = newLocale;
|
|
|
|
Utilities.extend(this.strings, newStrings);
|
|
|
|
Events.emit("strings-updated");
|
|
|
|
}
|
|
|
|
|
2019-06-28 01:50:20 +02:00
|
|
|
async getLocaleStrings(locale) {
|
2019-06-28 07:36:05 +02:00
|
|
|
const hash = DataStore.getCacheHash("locales", locale);
|
2019-06-28 01:50:20 +02:00
|
|
|
if (!hash) return await this.downloadLocale(locale);
|
|
|
|
const invalid = await this.downloadLocale(locale, hash);
|
|
|
|
if (!invalid) return DataStore.getLocale(locale);
|
|
|
|
return invalid;
|
|
|
|
}
|
|
|
|
|
|
|
|
downloadLocale(locale, hash = "") {
|
2019-06-27 06:21:51 +02:00
|
|
|
return new Promise(resolve => {
|
|
|
|
const options = {
|
2020-07-19 06:44:53 +02:00
|
|
|
url: Utilities.repoUrl(`assets/locales/${locale}.json`),
|
2019-06-27 06:21:51 +02:00
|
|
|
timeout: 2000,
|
|
|
|
json: true
|
|
|
|
};
|
2019-06-28 01:50:20 +02:00
|
|
|
if (hash) options.headers = {"If-None-Match": hash};
|
2019-06-27 06:21:51 +02:00
|
|
|
request.get(options, (err, resp, newStrings) => {
|
2019-06-28 01:50:20 +02:00
|
|
|
if (err || resp.statusCode !== 200) return resolve(null);
|
|
|
|
DataStore.saveLocale(locale, newStrings);
|
2019-06-28 07:36:05 +02:00
|
|
|
DataStore.setCacheHash("locales", locale, resp.headers.etag);
|
2019-06-27 06:21:51 +02:00
|
|
|
resolve(newStrings);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|