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

Add a URL panel to the right panel #9586

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions res/css/views/right_panel/_RoomSummaryCard.pcss
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,10 @@ limitations under the License.
mask-image: url('$(res)/img/element-icons/room/files.svg');
}

.mx_RoomSummaryCard_icon_urls::before {
mask-image: url('$(res)/img/element-icons/link.svg');
}

.mx_RoomSummaryCard_icon_pins::before {
mask-image: url('$(res)/img/element-icons/room/pin-upright.svg');
}
Expand Down
4 changes: 4 additions & 0 deletions src/components/structures/RightPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import TimelineCard from '../views/right_panel/TimelineCard';
import { UPDATE_EVENT } from '../../stores/AsyncStore';
import { IRightPanelCard, IRightPanelCardState } from '../../stores/right-panel/RightPanelStoreIPanelState';
import { Action } from '../../dispatcher/actions';
import UrlPanel from './UrlPanel';

interface IProps {
room?: Room; // if showing panels for a given room, this is set
Expand Down Expand Up @@ -220,6 +221,9 @@ export default class RightPanel extends React.Component<IProps, IState> {
case RightPanelPhases.FilePanel:
card = <FilePanel roomId={roomId} resizeNotifier={this.props.resizeNotifier} onClose={this.onClose} />;
break;
case RightPanelPhases.UrlPanel:
card = <UrlPanel roomId={roomId} resizeNotifier={this.props.resizeNotifier} onClose={this.onClose} />;
break;

case RightPanelPhases.ThreadView:
card = <ThreadView
Expand Down
323 changes: 323 additions & 0 deletions src/components/structures/UrlPanel.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,323 @@
/*
Copyright 2016 OpenMarket Ltd
Copyright 2019 - 2022 The Matrix.org Foundation C.I.C.

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.
*/

import React, { createRef } from 'react';
import { Filter } from 'matrix-js-sdk/src/filter';
import { EventTimelineSet, IRoomTimelineData } from "matrix-js-sdk/src/models/event-timeline-set";
import { Direction } from "matrix-js-sdk/src/models/event-timeline";
import { MatrixEvent, MatrixEventEvent } from "matrix-js-sdk/src/models/event";
import { Room, RoomEvent } from 'matrix-js-sdk/src/models/room';
import { TimelineWindow } from 'matrix-js-sdk/src/timeline-window';
import { logger } from "matrix-js-sdk/src/logger";

import { MatrixClientPeg } from '../../MatrixClientPeg';
import EventIndexPeg from "../../indexing/EventIndexPeg";
import { _t } from '../../languageHandler';
import SearchWarning, { WarningKind } from "../views/elements/SearchWarning";
import BaseCard from "../views/right_panel/BaseCard";
import ResizeNotifier from '../../utils/ResizeNotifier';
import TimelinePanel from "./TimelinePanel";
import Spinner from "../views/elements/Spinner";
import { Layout } from "../../settings/enums/Layout";
import RoomContext, { TimelineRenderingType } from '../../contexts/RoomContext';
import Measured from '../views/elements/Measured';

interface IProps {
roomId: string;
onClose: () => void;
resizeNotifier: ResizeNotifier;
}

interface IState {
timelineSet: EventTimelineSet;
narrow: boolean;
}

/*
* Component which shows the filtered urls using a TimelinePanel
*/
class UrlPanel extends React.Component<IProps, IState> {
static contextType = RoomContext;

// This is used to track if a decrypted event was a live event and should be
// added to the timeline.
private decryptingEvents = new Set<string>();
public noRoom: boolean;
private card = createRef<HTMLDivElement>();

state = {
timelineSet: null,
narrow: false,
};

private onRoomTimeline = (
ev: MatrixEvent,
room: Room | null,
toStartOfTimeline: boolean,
removed: boolean,
data: IRoomTimelineData,
): void => {
if (room?.roomId !== this.props?.roomId) return;
if (toStartOfTimeline || !data || !data.liveEvent || ev.isRedacted()) return;

const client = MatrixClientPeg.get();
client.decryptEventIfNeeded(ev);

if (ev.isBeingDecrypted()) {
this.decryptingEvents.add(ev.getId());
} else {
this.addEncryptedLiveEvent(ev);
}
};

private onEventDecrypted = (ev: MatrixEvent, err?: any): void => {
if (ev.getRoomId() !== this.props.roomId) return;
const eventId = ev.getId();

if (!this.decryptingEvents.delete(eventId)) return;
if (err) return;

this.addEncryptedLiveEvent(ev);
};

public addEncryptedLiveEvent(ev: MatrixEvent): void {
if (!this.state.timelineSet) return;

const timeline = this.state.timelineSet.getLiveTimeline();
if (ev.getType() !== "m.room.message") return;
if (["m.file", "m.image", "m.video", "m.audio"].indexOf(ev.getContent().msgtype) == -1) {
return;
}

if (!this.state.timelineSet.eventIdToTimeline(ev.getId())) {
this.state.timelineSet.addEventToTimeline(ev, timeline, false);
}
}

public async componentDidMount(): Promise<void> {
const client = MatrixClientPeg.get();

await this.updateTimelineSet(this.props.roomId);

if (!MatrixClientPeg.get().isRoomEncrypted(this.props.roomId)) return;

// The timelineSets filter makes sure that encrypted events that contain
// URLs never get added to the timeline, even if they are live events.
// These methods are here to manually listen for such events and add
// them despite the filter's best efforts.
//
// We do this only for encrypted rooms and if an event index exists,
// this could be made more general in the future or the filter logic
// could be fixed.
if (EventIndexPeg.get() !== null) {
client.on(RoomEvent.Timeline, this.onRoomTimeline);
client.on(MatrixEventEvent.Decrypted, this.onEventDecrypted);
}
}

public componentWillUnmount(): void {
const client = MatrixClientPeg.get();
if (client === null) return;

if (!MatrixClientPeg.get().isRoomEncrypted(this.props.roomId)) return;

if (EventIndexPeg.get() !== null) {
client.removeListener(RoomEvent.Timeline, this.onRoomTimeline);
client.removeListener(MatrixEventEvent.Decrypted, this.onEventDecrypted);
}
}

public async fetchFileEventsServer(room: Room): Promise<EventTimelineSet> {
const client = MatrixClientPeg.get();

const filter = new Filter(client.credentials.userId);
filter.setDefinition(
{
"room": {
"timeline": {
"types": [
"m.room.message",
],
},
},
},
);
// The "message_with_url" filter does not exist in synapse.
// So we just add it after the fact, since we have to do the filtering
// here in the frontend again anyway.
const filterId = await client.getOrCreateFilter("FILTER_URLS_" + client.credentials.userId, filter);
filter.setDefinition(
{
"room": {
"timeline": {
"message_with_url": true,
"contains_url": false, // exclude files
"types": [
"m.room.message",
],
},
},
},
);
filter.filterId = filterId;
const timelineSet = room.getOrCreateFilteredTimelineSet(filter);

return timelineSet;
}

private onPaginationRequest = (
timelineWindow: TimelineWindow,
direction: Direction,
limit: number,
): Promise<boolean> => {
const client = MatrixClientPeg.get();
const eventIndex = EventIndexPeg.get();
const roomId = this.props.roomId;

const room = client.getRoom(roomId);

// We override the pagination request for encrypted rooms so that we ask
// the event index to fulfill the pagination request. Asking the server
// to paginate won't ever work since the server can't correctly filter
// out events containing URLs
if (client.isRoomEncrypted(roomId) && eventIndex !== null) {
return eventIndex.paginateTimelineWindow(room, timelineWindow, direction, limit);
} else {
return timelineWindow.paginate(direction, limit);
}
};

private onMeasurement = (narrow: boolean): void => {
this.setState({ narrow });
};

public async updateTimelineSet(roomId: string): Promise<void> {
const client = MatrixClientPeg.get();
const room = client.getRoom(roomId);
const eventIndex = EventIndexPeg.get();

this.noRoom = !room;

if (room) {
let timelineSet;

try {
timelineSet = await this.fetchFileEventsServer(room);

// If this room is encrypted the file panel won't be populated
// correctly since the defined filter doesn't support encrypted
// events and the server can't check if encrypted events contain
// URLs.
//
// This is where our event index comes into place, we ask the
// event index to populate the timelineSet for us. This call
// will add 10 events to the live timeline of the set. More can
// be requested using pagination.
if (client.isRoomEncrypted(roomId) && eventIndex !== null) {
const timeline = timelineSet.getLiveTimeline();
await eventIndex.populateFileTimeline(timelineSet, timeline, room, 10);
}

this.setState({ timelineSet: timelineSet });
} catch (error) {
logger.error("Failed to get or create url panel filter", error);
}
} else {
logger.error("Failed to add filtered timelineSet for UrlPanel as no room!");
}
}

public render() {
if (MatrixClientPeg.get().isGuest()) {
return <BaseCard
className="mx_FilePanel mx_RoomView_messageListWrapper"
onClose={this.props.onClose}
>
<div className="mx_RoomView_empty">
{ _t("You must <a>register</a> to use this functionality",
{},
{ 'a': (sub) => <a href="#/register" key="sub">{ sub }</a> })
}
</div>
</BaseCard>;
} else if (this.noRoom) {
return <BaseCard
className="mx_FilePanel mx_RoomView_messageListWrapper"
onClose={this.props.onClose}
>
<div className="mx_RoomView_empty">{ _t("You must join the room to see its urls") }</div>
</BaseCard>;
}

// wrap a TimelinePanel with the jump-to-event bits turned off.

const emptyState = (<div className="mx_RightPanel_empty mx_FilePanel_empty">
<h2>{ _t('No urls visible in this room') }</h2>
</div>);

const isRoomEncrypted = this.noRoom ? false : MatrixClientPeg.get().isRoomEncrypted(this.props.roomId);

if (this.state.timelineSet) {
return (
<RoomContext.Provider value={{
...this.context,
timelineRenderingType: TimelineRenderingType.File,
narrow: this.state.narrow,
}}>
<BaseCard
className="mx_FilePanel"
onClose={this.props.onClose}
withoutScrollContainer
ref={this.card}
>
<Measured
sensor={this.card.current}
onMeasurement={this.onMeasurement}
/>
<SearchWarning isRoomEncrypted={isRoomEncrypted} kind={WarningKind.Files} />
<TimelinePanel
manageReadReceipts={false}
manageReadMarkers={false}
timelineSet={this.state.timelineSet}
showUrlPreview={false}
onPaginationRequest={this.onPaginationRequest}
resizeNotifier={this.props.resizeNotifier}
empty={emptyState}
layout={Layout.Group}
/>
</BaseCard>
</RoomContext.Provider>
);
} else {
return (
<RoomContext.Provider value={{
...this.context,
timelineRenderingType: TimelineRenderingType.File,
}}>
<BaseCard
className="mx_FilePanel"
onClose={this.props.onClose}
>
<Spinner />
</BaseCard>
</RoomContext.Provider>
);
}
}
}

export default UrlPanel;
17 changes: 17 additions & 0 deletions src/components/views/context_menus/RoomContextMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,22 @@ const RoomContextMenu = ({ room, onFinished, ...props }: IProps) => {
/>;
}

let urlsOption: JSX.Element;
if (!isVideoRoom) {
urlsOption = <IconizedContextMenuOption
onClick={(ev: ButtonEvent) => {
ev.preventDefault();
ev.stopPropagation();

ensureViewingRoom(ev);
RightPanelStore.instance.pushCard({ phase: RightPanelPhases.UrlPanel }, false);
onFinished();
}}
label={_t("Urls")}
iconClassName=".mx_RoomTile_iconCopyLink"
/>;
}

const pinningEnabled = useFeatureEnabled("feature_pinning");
const pinCount = usePinnedEvents(pinningEnabled && room)?.length;

Expand Down Expand Up @@ -348,6 +364,7 @@ const RoomContextMenu = ({ room, onFinished, ...props }: IProps) => {
{ favouriteOption }
{ peopleOption }
{ filesOption }
{ urlsOption }
{ pinsOption }
{ widgetsOption }
{ lowPriorityOption }
Expand Down
1 change: 1 addition & 0 deletions src/components/views/right_panel/RoomHeaderButtons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ const ROOM_INFO_PHASES = [
RightPanelPhases.RoomSummary,
RightPanelPhases.Widget,
RightPanelPhases.FilePanel,
RightPanelPhases.UrlPanel,
RightPanelPhases.RoomMemberList,
RightPanelPhases.RoomMemberInfo,
RightPanelPhases.EncryptionPanel,
Expand Down
Loading