element-web/src/utils/exportUtils/HtmlExport.tsx

399 lines
16 KiB
TypeScript
Raw Normal View History

2021-07-02 11:22:33 +00:00
import React, { MutableRefObject } from "react";
2021-06-03 08:09:14 +00:00
import Exporter from "./Exporter";
2021-06-14 12:36:40 +00:00
import { mediaFromMxc } from "../../customisations/Media";
import { Room } from "matrix-js-sdk/src/models/room";
import { MatrixEvent } from "matrix-js-sdk/src/models/event";
2021-06-30 08:38:22 +00:00
import { renderToStaticMarkup } from "react-dom/server";
import { Layout } from "../../settings/Layout";
import { shouldFormContinuation } from "../../components/structures/MessagePanel";
import { formatFullDateNoDayNoTime, wantsDateSeparator } from "../../DateUtils";
import { RoomPermalinkCreator } from "../permalinks/Permalinks";
2021-06-03 07:51:56 +00:00
import { _t } from "../../languageHandler";
import { EventType } from "matrix-js-sdk/src/@types/event";
2021-05-31 16:05:08 +00:00
import * as Avatar from "../../Avatar";
import EventTile, { haveTileForEvent } from "../../components/views/rooms/EventTile";
import DateSeparator from "../../components/views/messages/DateSeparator";
2021-06-03 07:51:56 +00:00
import BaseAvatar from "../../components/views/avatars/BaseAvatar";
import exportCSS from "./exportCSS";
import exportJS from "./exportJS";
2021-06-01 07:10:03 +00:00
import exportIcons from "./exportIcons";
2021-06-04 09:38:17 +00:00
import { exportTypes } from "./exportUtils";
import { exportOptions } from "./exportUtils";
import MatrixClientContext from "../../contexts/MatrixClientContext";
export default class HTMLExporter extends Exporter {
protected avatars: Map<string, boolean>;
protected permalinkCreator: RoomPermalinkCreator;
2021-06-15 11:11:31 +00:00
protected totalSize: number;
protected mediaOmitText: string;
2021-07-02 04:53:25 +00:00
constructor(
room: Room,
exportType: exportTypes,
exportOptions: exportOptions,
2021-07-02 11:22:33 +00:00
exportProgressRef: MutableRefObject<HTMLParagraphElement>,
2021-07-02 04:53:25 +00:00
) {
2021-07-02 11:22:33 +00:00
super(room, exportType, exportOptions, exportProgressRef);
this.avatars = new Map<string, boolean>();
this.permalinkCreator = new RoomPermalinkCreator(this.room);
2021-06-15 11:11:31 +00:00
this.totalSize = 0;
this.mediaOmitText = !this.exportOptions.attachmentsIncluded
? _t("Media omitted")
: _t("Media omitted - file size limit exceeded");
}
2021-06-04 09:38:17 +00:00
protected async getRoomAvatar() {
2021-05-31 16:05:08 +00:00
let blob: Blob;
2021-06-04 09:38:17 +00:00
const avatarUrl = Avatar.avatarUrlForRoom(this.room, 32, 32, "crop");
const avatarPath = "room.png";
2021-05-31 16:05:08 +00:00
if (avatarUrl) {
2021-06-28 07:09:05 +00:00
try {
const image = await fetch(avatarUrl);
blob = await image.blob();
this.totalSize += blob.size;
this.addFile(avatarPath, blob);
} catch (err) {
console.log("Failed to fetch room's avatar" + err);
}
2021-05-31 16:05:08 +00:00
}
const avatar = (
<BaseAvatar
2021-06-04 09:38:17 +00:00
width={32}
height={32}
2021-05-31 16:05:08 +00:00
name={this.room.name}
title={this.room.name}
url={blob ? avatarPath : null}
2021-07-21 06:18:37 +00:00
resizeMethod="crop"
2021-05-31 16:05:08 +00:00
/>
);
return renderToStaticMarkup(avatar);
}
2021-06-03 07:51:56 +00:00
protected async wrapHTML(content: string) {
2021-06-04 09:38:17 +00:00
const roomAvatar = await this.getRoomAvatar();
const exportDate = formatFullDateNoDayNoTime(new Date());
2021-06-03 07:51:56 +00:00
const creator = this.room.currentState.getStateEvents(EventType.RoomCreate, "")?.getSender();
const creatorName = this.room?.getMember(creator)?.rawDisplayName || creator;
2021-06-24 12:49:12 +00:00
const exporter = this.client.getUserId();
2021-06-03 07:51:56 +00:00
const exporterName = this.room?.getMember(exporter)?.rawDisplayName;
2021-06-23 06:44:20 +00:00
const topic = this.room.currentState.getStateEvents(EventType.RoomTopic, "")?.getContent()?.topic || "";
const createdText = _t("%(creatorName)s created this room.", {
creatorName,
});
2021-06-09 10:42:57 +00:00
const exportedText = renderToStaticMarkup(
<p>
2021-07-21 06:18:37 +00:00
{ _t(
2021-06-09 10:42:57 +00:00
"This is the start of export of <roomName/>. Exported by <exporterDetails/> at %(exportDate)s.",
{
exportDate,
},
{
2021-07-21 06:18:37 +00:00
roomName: () => <b>{ this.room.name }</b>,
2021-06-09 10:42:57 +00:00
exporterDetails: () => (
<a
href={`https://matrix.to/#/${exporter}`}
target="_blank"
rel="noopener noreferrer"
>
2021-07-21 06:18:37 +00:00
{ exporterName ? (
2021-06-09 10:42:57 +00:00
<>
2021-07-21 06:18:37 +00:00
<b>{ exporterName }</b>
{ exporter }
2021-06-09 10:42:57 +00:00
</>
) : (
2021-07-21 06:18:37 +00:00
<b>{ exporter }</b>
) }
2021-06-09 10:42:57 +00:00
</a>
),
},
2021-07-21 06:18:37 +00:00
) }
2021-06-09 10:42:57 +00:00
</p>,
);
const topicText = topic ? _t("Topic: %(topic)s", { topic }) : "";
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="css/style.css" rel="stylesheet" />
<script src="js/script.js"></script>
<title>Exported Data</title>
</head>
<body style="height: 100vh;">
<section
id="matrixchat"
style="height: 100%; overflow: auto"
class="notranslate"
>
<div class="mx_MatrixChat_wrapper" aria-hidden="false">
<div class="mx_MatrixChat">
<main class="mx_RoomView">
<div class="mx_RoomHeader light-panel">
<div class="mx_RoomHeader_wrapper" aria-owns="mx_RightPanel">
<div class="mx_RoomHeader_avatar">
<div class="mx_DecoratedRoomAvatar">
${roomAvatar}
</div>
</div>
<div class="mx_RoomHeader_name">
<div
dir="auto"
class="mx_RoomHeader_nametext"
2021-06-03 07:51:56 +00:00
title="${this.room.name}"
>
2021-06-03 07:51:56 +00:00
${this.room.name}
</div>
</div>
<div class="mx_RoomHeader_topic" dir="auto"> ${topic} </div>
</div>
</div>
<div class="mx_MainSplit">
<div class="mx_RoomView_body">
<div
class="mx_RoomView_timeline mx_RoomView_timeline_rr_enabled"
>
<div
class="
mx_AutoHideScrollbar
mx_ScrollPanel
mx_RoomView_messagePanel
mx_GroupLayout
"
>
<div class="mx_RoomView_messageListWrapper">
<ol
class="mx_RoomView_MessageList"
aria-live="polite"
role="list"
>
<div class="mx_NewRoomIntro">
2021-06-04 09:38:17 +00:00
${roomAvatar}
2021-06-03 07:51:56 +00:00
<h2> ${this.room.name} </h2>
<p> ${createdText} <br/><br/> ${exportedText} </p>
2021-06-04 09:38:17 +00:00
<br/>
<p> ${topicText} </p>
</div>
${content}
</ol>
</div>
</div>
</div>
<div class="mx_RoomView_statusArea">
<div class="mx_RoomView_statusAreaBox">
<div class="mx_RoomView_statusAreaBox_line"></div>
</div>
</div>
</div>
</div>
</main>
</div>
</div>
</section>
<div id="snackbar"/>
</body>
2021-06-30 08:38:22 +00:00
</html>`;
}
2021-06-26 18:10:35 +00:00
protected getAvatarURL(event: MatrixEvent): string {
2021-05-31 16:57:29 +00:00
const member = event.sender;
2021-06-26 18:10:35 +00:00
return (
member.getMxcAvatarUrl() &&
mediaFromMxc(member.getMxcAvatarUrl()).getThumbnailOfSourceHttp(
30,
30,
"crop",
)
);
2021-05-31 16:57:29 +00:00
}
protected async saveAvatarIfNeeded(event: MatrixEvent) {
const member = event.sender;
if (!this.avatars.has(member.userId)) {
2021-06-28 07:09:05 +00:00
try {
const avatarUrl = this.getAvatarURL(event);
this.avatars.set(member.userId, true);
const image = await fetch(avatarUrl);
const blob = await image.blob();
this.addFile(`users/${member.userId.replace(/:/g, '-')}.png`, blob);
} catch (err) {
console.log("Failed to fetch user's avatar" + err);
}
2021-05-31 16:57:29 +00:00
}
}
protected getDateSeparator(event: MatrixEvent) {
const ts = event.getTs();
const dateSeparator = <li key={ts}><DateSeparator forExport={true} key={ts} ts={ts} /></li>;
return renderToStaticMarkup(dateSeparator);
}
2021-07-21 06:18:37 +00:00
protected needsDateSeparator(event: MatrixEvent, prevEvent: MatrixEvent) {
if (prevEvent == null) return true;
return wantsDateSeparator(prevEvent.getDate(), event.getDate());
}
protected async getEventTile(mxEv: MatrixEvent, continuation: boolean, filePath?: string) {
2021-06-26 18:10:35 +00:00
const hasAvatar = !!this.getAvatarURL(mxEv);
2021-06-02 07:42:03 +00:00
if (hasAvatar) await this.saveAvatarIfNeeded(mxEv);
2021-06-14 05:38:17 +00:00
2021-06-30 08:38:22 +00:00
const eventTile = (
<div className="mx_Export_EventWrapper" id={mxEv.getId()}>
<MatrixClientContext.Provider value={this.client}>
<EventTile
mxEvent={mxEv}
continuation={continuation}
isRedacted={mxEv.isRedacted()}
replacingEventId={mxEv.replacingEventId()}
forExport={true}
readReceipts={null}
readReceiptMap={null}
showUrlPreview={false}
checkUnmounting={() => false}
isTwelveHour={false}
last={false}
lastInSection={false}
permalinkCreator={this.permalinkCreator}
lastSuccessful={false}
isSelectedEvent={false}
getRelationsForEvent={null}
showReactions={false}
layout={Layout.Group}
enableFlair={false}
showReadReceipts={false}
/>
</MatrixClientContext.Provider>
</div>
);
let eventTileMarkup = renderToStaticMarkup(eventTile);
if (filePath) {
const mxc = mxEv.getContent().url || mxEv.getContent().file?.url;
eventTileMarkup = eventTileMarkup.split(mxc).join(filePath);
}
if (hasAvatar) {
2021-06-22 03:57:49 +00:00
eventTileMarkup = eventTileMarkup.replace(
2021-06-26 18:10:35 +00:00
encodeURI(this.getAvatarURL(mxEv)).replace(/&/g, '&amp;'),
`users/${mxEv.sender.userId.replace(/:/g, "-")}.png`,
2021-06-22 03:57:49 +00:00
);
}
return eventTileMarkup;
}
protected createModifiedEvent(text: string, mxEv: MatrixEvent) {
2021-06-24 08:33:12 +00:00
const modifiedContent = {
msgtype: "m.text",
body: `*${text}*`,
format: "org.matrix.custom.html",
formatted_body: `<em>${text}</em>`,
2021-06-30 08:38:22 +00:00
};
2021-06-24 08:33:12 +00:00
const modifiedEvent = new MatrixEvent();
modifiedEvent.event = mxEv.event;
modifiedEvent.sender = mxEv.sender;
modifiedEvent.event.type = "m.room.message";
modifiedEvent.event.content = modifiedContent;
return modifiedEvent;
}
protected async createMessageBody(mxEv: MatrixEvent, joined = false) {
let eventTile: string;
2021-07-23 05:17:40 +00:00
try {
if (this.isAttachment(mxEv)) {
if (this.exportOptions.attachmentsIncluded) {
try {
const blob = await this.getMediaBlob(mxEv);
if (this.totalSize + blob.size > this.exportOptions.maxSize) {
eventTile = await this.getEventTile(
this.createModifiedEvent(this.mediaOmitText, mxEv),
joined,
);
} else {
this.totalSize += blob.size;
const filePath = this.getFilePath(mxEv);
eventTile = await this.getEventTile(mxEv, joined, filePath);
if (this.totalSize == this.exportOptions.maxSize) {
this.exportOptions.attachmentsIncluded = false;
}
this.addFile(filePath, blob);
}
2021-07-23 05:17:40 +00:00
} catch (e) {
console.log("Error while fetching file" + e);
eventTile = await this.getEventTile(
this.createModifiedEvent(_t("Error fetching file"), mxEv),
joined,
);
2021-06-24 08:33:12 +00:00
}
2021-07-23 05:17:40 +00:00
} else {
eventTile = await this.getEventTile(this.createModifiedEvent(this.mediaOmitText, mxEv), joined);
2021-06-15 11:11:31 +00:00
}
2021-07-23 05:17:40 +00:00
} else eventTile = await this.getEventTile(mxEv, joined);
} catch (e) {
// TODO: Handle callEvent errors
console.error(e);
eventTile = await this.getEventTile(this.createModifiedEvent("Error parsing HTML", mxEv), joined);
}
2021-06-01 14:38:10 +00:00
return eventTile;
}
2021-06-03 07:51:56 +00:00
protected async createHTML(events: MatrixEvent[]) {
let content = "";
let prevEvent = null;
2021-06-24 08:33:12 +00:00
for (let i = 0; i < events.length; i++) {
const event = events[i];
2021-07-02 11:22:33 +00:00
this.updateProgress(`Processing event ${i + 1} out of ${events.length}`, false, true);
2021-06-27 15:25:54 +00:00
if (this.cancelled) return this.cleanUp();
if (!haveTileForEvent(event)) continue;
2021-07-21 06:18:37 +00:00
content += this.needsDateSeparator(event, prevEvent) ? this.getDateSeparator(event) : "";
const shouldBeJoined = !this.needsDateSeparator(event, prevEvent)
&& shouldFormContinuation(prevEvent, event, false);
2021-05-31 13:37:49 +00:00
const body = await this.createMessageBody(event, shouldBeJoined);
2021-06-24 08:33:12 +00:00
this.totalSize += Buffer.byteLength(body);
2021-05-31 13:37:49 +00:00
content += body;
prevEvent = event;
}
2021-06-03 07:51:56 +00:00
return await this.wrapHTML(content);
}
public async export() {
this.updateProgress("Starting export process", true, false);
this.updateProgress("Fetching events");
2021-06-25 10:19:39 +00:00
2021-06-08 07:06:28 +00:00
const fetchStart = performance.now();
const res = await this.getRequiredEvents();
2021-06-08 07:06:28 +00:00
const fetchEnd = performance.now();
2021-07-02 04:53:25 +00:00
this.updateProgress(`Fetched ${res.length} events in ${(fetchEnd - fetchStart)/1000}s`, true, false);
2021-06-08 07:06:28 +00:00
2021-07-02 04:53:25 +00:00
this.updateProgress("Creating HTML...");
2021-06-03 07:51:56 +00:00
const html = await this.createHTML(res);
this.addFile("index.html", new Blob([html]));
this.addFile("css/style.css", new Blob([exportCSS]));
this.addFile("js/script.js", new Blob([exportJS]));
2021-06-03 07:51:56 +00:00
2021-06-01 07:10:03 +00:00
for (const iconName in exportIcons) {
this.addFile(`icons/${iconName}`, new Blob([exportIcons[iconName]]));
2021-06-01 07:10:03 +00:00
}
2021-06-03 07:51:56 +00:00
await this.downloadZIP();
2021-06-08 07:06:28 +00:00
const exportEnd = performance.now();
2021-06-25 10:19:39 +00:00
2021-06-27 15:25:54 +00:00
if (this.cancelled) {
console.info("Export cancelled successfully");
} else {
2021-07-02 04:53:25 +00:00
this.updateProgress("Export successful!");
this.updateProgress(`Exported ${res.length} events in ${(exportEnd - fetchStart)/1000} seconds`);
2021-06-27 15:25:54 +00:00
}
2021-06-25 10:19:39 +00:00
2021-06-27 15:25:54 +00:00
this.cleanUp();
}
}