Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Look up tile server info in homeserver's .well-known area #7623

Merged
merged 9 commits into from
Jan 27, 2022
42 changes: 28 additions & 14 deletions src/components/views/location/LocationPicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,17 @@ import React, { SyntheticEvent } from 'react';
import maplibregl from 'maplibre-gl';
import { logger } from "matrix-js-sdk/src/logger";
import { RoomMember } from 'matrix-js-sdk/src/models/room-member';
import { IClientWellKnown } from 'matrix-js-sdk/src/client';

import SdkConfig from '../../../SdkConfig';
import DialogButtons from "../elements/DialogButtons";
import { _t } from '../../../languageHandler';
import { replaceableComponent } from "../../../utils/replaceableComponent";
import MemberAvatar from '../avatars/MemberAvatar';
import MatrixClientContext from '../../../contexts/MatrixClientContext';
import Modal from '../../../Modal';
import ErrorDialog from '../dialogs/ErrorDialog';
import { findMapStyleUrl } from '../messages/MLocationBody';
import { tileServerFromWellKnown } from '../../../utils/WellKnownUtils';

interface IProps {
sender: RoomMember;
Expand All @@ -51,9 +53,9 @@ interface IState {
class LocationPicker extends React.Component<IProps, IState> {
public static contextType = MatrixClientContext;
public context!: React.ContextType<typeof MatrixClientContext>;
private map: maplibregl.Map;
private geolocate: maplibregl.GeolocateControl;
private marker: maplibregl.Marker;
private map?: maplibregl.Map;
private geolocate?: maplibregl.GeolocateControl;
private marker?: maplibregl.Marker;

constructor(props: IProps) {
super(props);
Expand All @@ -62,22 +64,26 @@ class LocationPicker extends React.Component<IProps, IState> {
position: undefined,
error: undefined,
};
this.map = null;
this.geolocate = null;
this.marker = null;
andybalaam marked this conversation as resolved.
Show resolved Hide resolved
}

private getMarkerId = () => {
return "mx_MLocationPicker_marker";
};

componentDidMount() {
const config = SdkConfig.get();
this.map = new maplibregl.Map({
container: 'mx_LocationPicker_map',
style: config.map_style_url,
center: [0, 0],
zoom: 1,
});
this.context.on("WellKnown.client", this.updateStyleUrl);

try {
this.map = new maplibregl.Map({
container: 'mx_LocationPicker_map',
style: findMapStyleUrl(),
center: [0, 0],
zoom: 1,
});

// Add geolocate control to the map.
this.geolocate = new maplibregl.GeolocateControl({
positionOptions: {
Expand Down Expand Up @@ -124,18 +130,26 @@ class LocationPicker extends React.Component<IProps, IState> {

this.geolocate.on('geolocate', this.onGeolocate);
} catch (e) {
logger.error("Failed to render map", e.error);
this.setState({ error: e.error });
logger.error("Failed to render map", e);
this.setState({ error: e });
}
}

componentWillUnmount() {
this.geolocate?.off('geolocate', this.onGeolocate);
this.context.off("WellKnown.client", this.updateStyleUrl);
}

private updateStyleUrl = (clientWellKnown: IClientWellKnown) => {
const style = tileServerFromWellKnown(clientWellKnown)?.["map_style_url"];
if (style) {
this.map?.setStyle(style);
}
};

private onGeolocate = (position: GeolocationPosition) => {
this.setState({ position });
this.marker.setLngLat(
this.marker?.setLngLat(
new maplibregl.LngLat(
position.coords.longitude,
position.coords.latitude,
Expand Down
16 changes: 16 additions & 0 deletions src/components/views/location/LocationViewDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,16 @@ limitations under the License.

import React from 'react';
import { MatrixEvent } from 'matrix-js-sdk/src/models/event';
import { IClientWellKnown, MatrixClient } from 'matrix-js-sdk/src/client';

import { replaceableComponent } from "../../../utils/replaceableComponent";
import BaseDialog from "../dialogs/BaseDialog";
import { IDialogProps } from "../dialogs/IDialogProps";
import { createMap, LocationBodyContent, locationEventGeoUri, parseGeoUri } from '../messages/MLocationBody';
import { tileServerFromWellKnown } from '../../../utils/WellKnownUtils';

interface IProps extends IDialogProps {
matrixClient: MatrixClient;
mxEvent: MatrixEvent;
}

Expand Down Expand Up @@ -50,6 +53,8 @@ export default class LocationViewDialog extends React.Component<IProps, IState>
return;
}

this.props.matrixClient.on("WellKnown.client", this.updateStyleUrl);

this.map = createMap(
this.coords,
true,
Expand All @@ -59,6 +64,17 @@ export default class LocationViewDialog extends React.Component<IProps, IState>
);
}

componentWillUnmount() {
this.props.matrixClient.off("WellKnown.client", this.updateStyleUrl);
}

private updateStyleUrl = (clientWellKnown: IClientWellKnown) => {
const style = tileServerFromWellKnown(clientWellKnown)?.["map_style_url"];
if (style) {
this.map?.setStyle(style);
}
};

private getBodyId = () => {
return `mx_LocationViewDialog_${this.props.mxEvent.getId()}`;
};
Expand Down
111 changes: 80 additions & 31 deletions src/components/views/messages/MLocationBody.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
ILocationContent,
LOCATION_EVENT_TYPE,
} from 'matrix-js-sdk/src/@types/location';
import { IClientWellKnown } from 'matrix-js-sdk/src/client';

import SdkConfig from '../../../SdkConfig';
import { replaceableComponent } from "../../../utils/replaceableComponent";
Expand All @@ -35,16 +36,21 @@ import LocationViewDialog from '../location/LocationViewDialog';
import TooltipTarget from '../elements/TooltipTarget';
import { Alignment } from '../elements/Tooltip';
import AccessibleButton from '../elements/AccessibleButton';
import { getTileServerWellKnown, tileServerFromWellKnown } from '../../../utils/WellKnownUtils';
import MatrixClientContext from '../../../contexts/MatrixClientContext';

interface IState {
error: Error;
}

@replaceableComponent("views.messages.MLocationBody")
export default class MLocationBody extends React.Component<IBodyProps, IState> {
public static contextType = MatrixClientContext;
public context!: React.ContextType<typeof MatrixClientContext>;
private coords: GeolocationCoordinates;
private bodyId: string;
private markerId: string;
private map?: maplibregl.Map;

constructor(props: IBodyProps) {
super(props);
Expand All @@ -54,6 +60,7 @@ export default class MLocationBody extends React.Component<IBodyProps, IState> {
this.bodyId = `mx_MLocationBody_${idSuffix}`;
this.markerId = `mx_MLocationBody_marker_${idSuffix}`;
this.coords = parseGeoUri(locationEventGeoUri(this.props.mxEvent));
this.map = null;
andybalaam marked this conversation as resolved.
Show resolved Hide resolved

this.state = {
error: undefined,
Expand All @@ -65,7 +72,9 @@ export default class MLocationBody extends React.Component<IBodyProps, IState> {
return;
}

createMap(
this.context.on("WellKnown.client", this.updateStyleUrl);

this.map = createMap(
this.coords,
false,
this.bodyId,
Expand All @@ -74,6 +83,17 @@ export default class MLocationBody extends React.Component<IBodyProps, IState> {
);
}

componentWillUnmount() {
this.context.off("WellKnown.client", this.updateStyleUrl);
}

private updateStyleUrl = (clientWellKnown: IClientWellKnown) => {
const style = tileServerFromWellKnown(clientWellKnown)?.["map_style_url"];
if (style) {
this.map?.setStyle(style);
}
};

private onClick = (
event: React.MouseEvent<HTMLDivElement, MouseEvent>,
) => {
Expand All @@ -87,7 +107,10 @@ export default class MLocationBody extends React.Component<IBodyProps, IState> {
'Location View',
'',
LocationViewDialog,
{ mxEvent: this.props.mxEvent },
{
matrixClient: this.context,
mxEvent: this.props.mxEvent,
},
"mx_LocationViewDialog_wrapper",
false, // isPriority
true, // isStatic
Expand Down Expand Up @@ -206,42 +229,68 @@ function ZoomButtons(props: IZoomButtonsProps): React.ReactElement<HTMLDivElemen
</div>;
}

/**
* Look up what map tile server style URL was provided in the homeserver's
* .well-known location, or, failing that, in our local config, or, failing
* that, defaults to the same tile server listed by matrix.org.
*/
export function findMapStyleUrl(): string {
const mapStyleUrl = (
getTileServerWellKnown()?.map_style_url ??
SdkConfig.get().map_style_url
);

if (!mapStyleUrl) {
throw new Error(
"'map_style_url' missing from homeserver .well-known area, and " +
"missing from from config.json.",
);
}

return mapStyleUrl;
}

export function createMap(
coords: GeolocationCoordinates,
interactive: boolean,
bodyId: string,
markerId: string,
onError: (error: Error) => void,
): maplibregl.Map {
const styleUrl = SdkConfig.get().map_style_url;
const coordinates = new maplibregl.LngLat(coords.longitude, coords.latitude);

const map = new maplibregl.Map({
container: bodyId,
style: styleUrl,
center: coordinates,
zoom: 15,
interactive,
});

new maplibregl.Marker({
element: document.getElementById(markerId),
anchor: 'bottom',
offset: [0, -1],
})
.setLngLat(coordinates)
.addTo(map);

map.on('error', (e) => {
logger.error(
"Failed to load map: check map_style_url in config.json has a "
+ "valid URL and API key",
e.error,
);
onError(e.error);
});

return map;
try {
const styleUrl = findMapStyleUrl();
const coordinates = new maplibregl.LngLat(coords.longitude, coords.latitude);

const map = new maplibregl.Map({
container: bodyId,
style: styleUrl,
center: coordinates,
zoom: 15,
interactive,
});

new maplibregl.Marker({
element: document.getElementById(markerId),
anchor: 'bottom',
offset: [0, -1],
})
.setLngLat(coordinates)
.addTo(map);

map.on('error', (e) => {
logger.error(
"Failed to load map: check map_style_url in config.json has a "
+ "valid URL and API key",
e.error,
);
onError(e.error);
});

return map;
} catch (e) {
logger.error("Failed to render map", e);
onError(e);
}
}

/**
Expand Down
22 changes: 22 additions & 0 deletions src/utils/WellKnownUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,16 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import { IClientWellKnown } from 'matrix-js-sdk/src/client';
import { UnstableValue } from 'matrix-js-sdk/src/NamespacedValue';

import { MatrixClientPeg } from '../MatrixClientPeg';

const CALL_BEHAVIOUR_WK_KEY = "io.element.call_behaviour";
const E2EE_WK_KEY = "io.element.e2ee";
const E2EE_WK_KEY_DEPRECATED = "im.vector.riot.e2ee";
const TILE_SERVER_WK_KEY = new UnstableValue(
"m.tile_server", "org.matrix.msc3488.tile_server");

/* eslint-disable camelcase */
export interface ICallBehaviourWellKnown {
Expand All @@ -30,6 +35,10 @@ export interface IE2EEWellKnown {
secure_backup_required?: boolean;
secure_backup_setup_methods?: SecureBackupSetupMethod[];
}

export interface ITileServerWellKnown {
map_style_url?: string;
}
/* eslint-enable camelcase */

export function getCallBehaviourWellKnown(): ICallBehaviourWellKnown {
Expand All @@ -48,6 +57,19 @@ export function getE2EEWellKnown(): IE2EEWellKnown {
return null;
}

export function getTileServerWellKnown(): ITileServerWellKnown | undefined {
return tileServerFromWellKnown(MatrixClientPeg.get().getClientWellKnown());
}

export function tileServerFromWellKnown(
clientWellKnown?: IClientWellKnown | undefined,
): ITileServerWellKnown {
return (
clientWellKnown?.[TILE_SERVER_WK_KEY.name] ??
clientWellKnown?.[TILE_SERVER_WK_KEY.altName]
);
}

export function isSecureBackupRequired(): boolean {
const wellKnown = getE2EEWellKnown();
return wellKnown && wellKnown["secure_backup_required"] === true;
Expand Down