@geogirafe/lib-geoportal
Version:
GeoGirafe is a flexible application to build online geoportals.
78 lines (77 loc) • 3.18 kB
JavaScript
// SPDX-License-Identifier: Apache-2.0
import GirafeSingleton from '../../base/GirafeSingleton.js';
import GeoGirafeShareManager from './geogirafesharemanager.js';
import GmfShareManager from './gmfsharemanager.js';
import { SHORTLINK_PARAMETER } from './iurlshortener.js';
class ShareManager extends GirafeSingleton {
urlShortener;
get UrlShortener() {
return this.urlShortener;
}
async initializeSingleton() {
const share = this.context.configManager.Config.share;
if (share) {
switch (share.service) {
case 'gmf':
this.urlShortener = new GmfShareManager(share.createUrl);
break;
case 'geogirafe':
this.urlShortener = new GeoGirafeShareManager(share.createUrl, this.context.urlManager);
break;
}
}
}
getStateToShare() {
const encodedState = this.context.stateSerializer.getSerializedState();
return encodedState;
}
hasSharedState() {
const encodedState = this.getStateFromUrl();
return encodedState !== null;
}
getStateFromUrl() {
if (this.context.sessionManager.hasState()) {
return null;
}
const shortId = this.context.urlManager.getParam(SHORTLINK_PARAMETER);
if (shortId) {
return `gg-${shortId}`;
}
// Legacy short links (#gg-xxx) and full states are stored in the hash
return this.context.urlManager.getHash();
}
async setStateFromUrl() {
// NOTE: This method should only be called when themes.json has been loaded
// (i.e. from the ThemesManager), because it needs the themes.
let encodedState = this.getStateFromUrl();
let stateRestored = false;
if (encodedState) {
if (encodedState.startsWith('gg-')) {
// The hash contains a shortlink identifier.
// We first have to load the hash from the GMF server
encodedState = await this.getStateFromServer(encodedState);
}
stateRestored = this.context.stateSerializer.deserializeAndSetState(encodedState);
}
// Like the hash (replaced by the session hash), the short link is consumed once:
// on reload, the state is then restored from the session.
this.context.urlManager.removeParams(SHORTLINK_PARAMETER);
return stateRestored;
}
async getStateFromServer(geogirafeState) {
if (this.context.configManager.Config.share?.service !== 'geogirafe' ||
!this.context.configManager.Config.share.getUrl) {
throw new Error('We get a geogirafe state but the configuration is not correct.');
}
let getUrl = this.context.configManager.Config.share.getUrl;
if (!getUrl.endsWith('/')) {
getUrl += '/';
}
getUrl += geogirafeState.substring(3);
const resp = await fetch(getUrl);
const json = await resp.json();
const compressedState = json.long_url.split('#')[1];
return compressedState;
}
}
export default ShareManager;