element-call/src/config/Config.ts

84 lines
2.6 KiB
TypeScript
Raw Normal View History

/*
Copyright 2021-2022 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
2022-12-20 17:26:45 +00:00
import { DEFAULT_CONFIG, ConfigOptions } from "./ConfigOptions";
export class Config {
private static internalInstance: Config;
public static get(): ConfigOptions {
if (!this.internalInstance?.config)
throw new Error("Config instance read before config got initialized");
return this.internalInstance.config;
}
public static init(): Promise<void> {
if (Config.internalInstance?.initPromise) {
return Config.internalInstance.initPromise;
}
Config.internalInstance = new Config();
Config.internalInstance.initPromise = new Promise<void>((resolve) => {
downloadConfig("../config.json").then((config) => {
Config.internalInstance.config = { ...DEFAULT_CONFIG, ...config };
resolve();
});
});
return Config.internalInstance.initPromise;
}
2022-12-20 17:26:45 +00:00
// Convenience accessors
public static defaultHomeserverUrl(): string | undefined {
const defaultServerConfig = Config.get().default_server_config;
2022-12-20 17:26:45 +00:00
if (!defaultServerConfig) {
return undefined;
}
return defaultServerConfig["m.homeserver"].base_url;
2022-12-20 17:26:45 +00:00
}
public static defaultServerName(): string | undefined {
const defaultServerConfig = Config.get().default_server_config;
2022-12-20 17:26:45 +00:00
if (!defaultServerConfig) {
return undefined;
}
return defaultServerConfig["m.homeserver"].server_name;
2022-12-20 17:26:45 +00:00
}
public config?: ConfigOptions;
private initPromise?: Promise<void>;
}
async function downloadConfig(
configJsonFilename: string
): Promise<ConfigOptions> {
const url = new URL(configJsonFilename, window.location.href);
url.searchParams.set("cachebuster", Date.now().toString());
const res = await fetch(url, {
cache: "no-cache",
method: "GET",
});
if (!res.ok || res.status === 404 || res.status === 0) {
// Lack of a config isn't an error, we should just use the defaults.
// Also treat a blank config as no config, assuming the status code is 0, because we don't get 404s from file:
// URIs so this is the only way we can not fail if the file doesn't exist when loading from a file:// URI.
2022-12-20 17:26:45 +00:00
return DEFAULT_CONFIG;
}
return res.json();
}