-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathExporter.ts
291 lines (248 loc) · 10.7 KB
/
Exporter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/*
Copyright 2024 New Vector Ltd.
Copyright 2021, 2022 The Matrix.org Foundation C.I.C.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import { Direction, type MatrixEvent, type Relations, type Room } from "matrix-js-sdk/src/matrix";
import { type EventType, type MediaEventContent, type RelationType } from "matrix-js-sdk/src/types";
import { saveAs } from "file-saver";
import { logger } from "matrix-js-sdk/src/logger";
import sanitizeFilename from "sanitize-filename";
import { ExportType, type IExportOptions } from "./exportUtils";
import { decryptFile } from "../DecryptFile";
import { mediaFromContent } from "../../customisations/Media";
import { formatFullDateNoDay, formatFullDateNoDayISO } from "../../DateUtils";
import { isVoiceMessage } from "../EventUtils";
import { _t } from "../../languageHandler";
import SdkConfig from "../../SdkConfig";
type BlobFile = {
name: string;
blob: Blob;
};
export default abstract class Exporter {
protected files: BlobFile[] = [];
protected cancelled = false;
protected constructor(
protected room: Room,
protected exportType: ExportType,
protected exportOptions: IExportOptions,
protected setProgressText: React.Dispatch<React.SetStateAction<string>>,
) {
if (
exportOptions.maxSize < 1 * 1024 * 1024 || // Less than 1 MB
exportOptions.maxSize > 8000 * 1024 * 1024 || // More than 8 GB
(!!exportOptions.numberOfMessages && exportOptions.numberOfMessages > 10 ** 8) ||
(exportType === ExportType.LastNMessages && !exportOptions.numberOfMessages)
) {
throw new Error("Invalid export options");
}
window.addEventListener("beforeunload", this.onBeforeUnload);
}
public get destinationFileName(): string {
return this.makeFileNameNoExtension(SdkConfig.get().brand) + ".zip";
}
protected onBeforeUnload(e: BeforeUnloadEvent): string {
e.preventDefault();
return (e.returnValue = _t("export_chat|unload_confirm"));
}
protected updateProgress(progress: string, log = true, show = true): void {
if (log) logger.log(progress);
if (show) this.setProgressText(progress);
}
protected addFile(filePath: string, blob: Blob): void {
const file = {
name: filePath,
blob,
};
this.files.push(file);
}
protected makeFileNameNoExtension(brand = "matrix"): string {
// First try to use the real name of the room, then a translated copy of a generic name,
// then finally hardcoded default to guarantee we'll have a name.
const safeRoomName = sanitizeFilename(this.room.name ?? _t("common|unnamed_room")).trim() || "Unnamed Room";
const safeDate = formatFullDateNoDayISO(new Date()).replace(/:/g, "-"); // ISO format automatically removes a lot of stuff for us
const safeBrand = sanitizeFilename(brand);
return `${safeBrand} - ${safeRoomName} - Chat Export - ${safeDate}`;
}
protected async downloadZIP(): Promise<string | void> {
const filename = this.destinationFileName;
const filenameWithoutExt = filename.substring(0, filename.lastIndexOf(".")); // take off the extension
const { default: JSZip } = await import("jszip");
const zip = new JSZip();
// Create a writable stream to the directory
if (!this.cancelled) this.updateProgress(_t("export_chat|generating_zip"));
else return this.cleanUp();
for (const file of this.files) zip.file(filenameWithoutExt + "/" + file.name, file.blob);
const content = await zip.generateAsync({ type: "blob" });
saveAs(content, filenameWithoutExt + ".zip");
}
protected cleanUp(): string {
logger.log("Cleaning up...");
window.removeEventListener("beforeunload", this.onBeforeUnload);
return "";
}
public async cancelExport(): Promise<void> {
logger.log("Cancelling export...");
this.cancelled = true;
}
protected downloadPlainText(fileName: string, text: string): void {
const content = new Blob([text], { type: "text/plain" });
saveAs(content, fileName);
}
protected setEventMetadata(event: MatrixEvent): MatrixEvent {
event.setMetadata(this.room.currentState, false);
return event;
}
public getLimit(): number {
let limit: number;
switch (this.exportType) {
case ExportType.LastNMessages:
// validated in constructor that numberOfMessages is defined
// when export type is LastNMessages
limit = this.exportOptions.numberOfMessages!;
break;
default:
limit = 10 ** 8;
}
return limit;
}
protected async getRequiredEvents(): Promise<MatrixEvent[]> {
const eventMapper = this.room.client.getEventMapper();
let prevToken: string | null = null;
let events: MatrixEvent[] = [];
if (this.exportType === ExportType.Timeline) {
events = this.room.getLiveTimeline().getEvents();
} else {
let limit = this.getLimit();
while (limit) {
const eventsPerCrawl = Math.min(limit, 1000);
const res = await this.room.client.createMessagesRequest(
this.room.roomId,
prevToken,
eventsPerCrawl,
Direction.Backward,
);
if (this.cancelled) {
this.cleanUp();
return [];
}
if (res.chunk.length === 0) break;
limit -= res.chunk.length;
const matrixEvents: MatrixEvent[] = res.chunk.map(eventMapper);
for (const mxEv of matrixEvents) {
// if (this.exportOptions.startDate && mxEv.getTs() < this.exportOptions.startDate) {
// // Once the last message received is older than the start date, we break out of both the loops
// limit = 0;
// break;
// }
events.push(mxEv);
}
if (this.exportType === ExportType.LastNMessages) {
this.updateProgress(
_t("export_chat|fetched_n_events_with_total", {
count: events.length,
total: this.exportOptions.numberOfMessages,
}),
);
} else {
this.updateProgress(
_t("export_chat|fetched_n_events", {
count: events.length,
}),
);
}
prevToken = res.end ?? null;
}
// Reverse the events so that we preserve the order
events.reverse();
}
const decryptionPromises = events
.filter((event) => event.isEncrypted())
.map((event) => {
return this.room.client.decryptEventIfNeeded(event, { emit: false });
});
// Wait for all the events to get decrypted.
await Promise.all(decryptionPromises);
for (let i = 0; i < events.length; i++) this.setEventMetadata(events[i]);
return events;
}
/**
* Decrypts if necessary, and fetches media from a matrix event
* @param event - matrix event with media event content
* @resolves when media has been fetched
* @throws if media was unable to be fetched
*/
protected async getMediaBlob(event: MatrixEvent): Promise<Blob> {
let blob: Blob | undefined = undefined;
try {
const isEncrypted = event.isEncrypted();
const content = event.getContent<MediaEventContent>();
const shouldDecrypt = isEncrypted && content.hasOwnProperty("file") && event.getType() !== "m.sticker";
if (shouldDecrypt) {
blob = await decryptFile(content.file);
} else {
const media = mediaFromContent(content);
if (!media.srcHttp) {
throw new Error("Cannot fetch without srcHttp");
}
const image = await fetch(media.srcHttp);
blob = await image.blob();
}
} catch {
logger.log("Error decrypting media");
}
if (!blob) {
throw new Error("Unable to fetch file");
}
return blob;
}
public splitFileName(file: string): string[] {
const lastDot = file.lastIndexOf(".");
if (lastDot === -1) return [file, ""];
const fileName = file.slice(0, lastDot);
const ext = file.slice(lastDot + 1);
return [fileName, "." + ext];
}
public getFilePath(event: MatrixEvent): string {
const mediaType = event.getContent().msgtype;
let fileDirectory: string;
switch (mediaType) {
case "m.image":
fileDirectory = "images";
break;
case "m.video":
fileDirectory = "videos";
break;
case "m.audio":
fileDirectory = "audio";
break;
default:
fileDirectory = event.getType() === "m.sticker" ? "stickers" : "files";
}
const fileDate = formatFullDateNoDay(new Date(event.getTs()));
let [fileName, fileExt] = this.splitFileName(event.getContent().body);
if (event.getType() === "m.sticker") fileExt = ".png";
if (isVoiceMessage(event)) fileExt = ".ogg";
return fileDirectory + "/" + fileName + "-" + fileDate + fileExt;
}
protected isReply(event: MatrixEvent): boolean {
const isEncrypted = event.isEncrypted();
// If encrypted, in_reply_to lies in event.event.content
const content = isEncrypted ? event.event.content! : event.getContent();
const relatesTo = content["m.relates_to"];
return !!(relatesTo && relatesTo["m.in_reply_to"]);
}
protected isAttachment(mxEv: MatrixEvent): boolean {
const attachmentTypes = ["m.sticker", "m.image", "m.file", "m.video", "m.audio"];
return mxEv.getType() === attachmentTypes[0] || attachmentTypes.includes(mxEv.getContent().msgtype!);
}
protected getRelationsForEvent = (
eventId: string,
relationType: RelationType | string,
eventType: EventType | string,
): Relations | undefined => {
return this.room.getUnfilteredTimelineSet().relations.getChildEventsForEvent(eventId, relationType, eventType);
};
public abstract export(): Promise<void>;
}