1
|
{"version":3,"file":"MSC3089Branch.js","names":["_event","require","_eventTimeline","ownKeys","object","enumerableOnly","keys","Object","getOwnPropertySymbols","symbols","filter","sym","getOwnPropertyDescriptor","enumerable","push","apply","_objectSpread","target","i","arguments","length","source","forEach","key","_defineProperty2","default","getOwnPropertyDescriptors","defineProperties","defineProperty","MSC3089Branch","constructor","client","indexEvent","directory","id","stateKey","getStateKey","Error","isActive","getContent","version","_this$indexEvent$getC","roomId","getRoomId","delete","sendStateEvent","UNSTABLE_MSC3089_BRANCH","name","redactEvent","nextVersion","getVersionHistory","getName","setName","isLocked","setLocked","locked","getFileInfo","event","getFileEvent","file","getOriginalContent","httpUrl","mxcUrlToHttp","info","room","getRoom","getUnfilteredTimelineSet","findEventById","getLiveTimeline","getState","EventTimeline","BACKWARDS","paginationToken","scrollback","decryptEventIfNeeded","emit","isRetry","createNewVersion","encryptedContents","additionalContent","fileEventResponse","createFile","rel_type","RelationType","Replace","event_id","active","fileHistory","timelineEvents","getEvents","reverse","childEvent","parentEvent","find","e","replacingEventId","getId","branch","getFile","exports"],"sources":["../../src/models/MSC3089Branch.ts"],"sourcesContent":["/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixClient } from \"../client\";\nimport { IEncryptedFile, RelationType, UNSTABLE_MSC3089_BRANCH } from \"../@types/event\";\nimport { IContent, MatrixEvent } from \"./event\";\nimport { MSC3089TreeSpace } from \"./MSC3089TreeSpace\";\nimport { EventTimeline } from \"./event-timeline\";\nimport { FileType } from \"../http-api\";\nimport type { ISendEventResponse } from \"../@types/requests\";\n\n/**\n * Represents a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) branch - a reference\n * to a file (leaf) in the tree. Note that this is UNSTABLE and subject to breaking changes\n * without notice.\n */\nexport class MSC3089Branch {\n public constructor(\n private client: MatrixClient,\n public readonly indexEvent: MatrixEvent,\n public readonly directory: MSC3089TreeSpace,\n ) {\n // Nothing to do\n }\n\n /**\n * The file ID.\n */\n public get id(): string {\n const stateKey = this.indexEvent.getStateKey();\n if (!stateKey) {\n throw new Error(\"State key not found for branch\");\n }\n return stateKey;\n }\n\n /**\n * Whether this branch is active/valid.\n */\n public get isActive(): boolean {\n return this.indexEvent.getContent()[\"active\"] === true;\n }\n\n /**\n * Version for the file, one-indexed.\n */\n public get version(): number {\n return this.indexEvent.getContent()[\"version\"] ?? 1;\n }\n\n private get roomId(): string {\n return this.indexEvent.getRoomId()!;\n }\n\n /**\n * Deletes the file from the tree, including all prior edits/versions.\n * @returns Promise which resolves when complete.\n */\n public async delete(): Promise<void> {\n await this.client.sendStateEvent(this.roomId, UNSTABLE_MSC3089_BRANCH.name, {}, this.id);\n await this.client.redactEvent(this.roomId, this.id);\n\n const nextVersion = (await this.getVersionHistory())[1]; // [0] will be us\n if (nextVersion) await nextVersion.delete(); // implicit recursion\n }\n\n /**\n * Gets the name for this file.\n * @returns The name, or \"Unnamed File\" if unknown.\n */\n public getName(): string {\n return this.indexEvent.getContent()[\"name\"] || \"Unnamed File\";\n }\n\n /**\n * Sets the name for this file.\n * @param name - The new name for this file.\n * @returns Promise which resolves when complete.\n */\n public async setName(name: string): Promise<void> {\n await this.client.sendStateEvent(\n this.roomId,\n UNSTABLE_MSC3089_BRANCH.name,\n {\n ...this.indexEvent.getContent(),\n name: name,\n },\n this.id,\n );\n }\n\n /**\n * Gets whether or not a file is locked.\n * @returns True if locked, false otherwise.\n */\n public isLocked(): boolean {\n return this.indexEvent.getContent()[\"locked\"] || false;\n }\n\n /**\n * Sets a file as locked or unlocked.\n * @param locked - True to lock the file, false otherwise.\n * @returns Promise which resolves when complete.\n */\n public async setLocked(locked: boolean): Promise<void> {\n await this.client.sendStateEvent(\n this.roomId,\n UNSTABLE_MSC3089_BRANCH.name,\n {\n ...this.indexEvent.getContent(),\n locked: locked,\n },\n this.id,\n );\n }\n\n /**\n * Gets information about the file needed to download it.\n * @returns Information about the file.\n */\n public async getFileInfo(): Promise<{ info: IEncryptedFile; httpUrl: string }> {\n const event = await this.getFileEvent();\n\n const file = event.getOriginalContent()[\"file\"];\n const httpUrl = this.client.mxcUrlToHttp(file[\"url\"]);\n\n if (!httpUrl) {\n throw new Error(`No HTTP URL available for ${file[\"url\"]}`);\n }\n\n return { info: file, httpUrl: httpUrl };\n }\n\n /**\n * Gets the event the file points to.\n * @returns Promise which resolves to the file's event.\n */\n public async getFileEvent(): Promise<MatrixEvent> {\n const room = this.client.getRoom(this.roomId);\n if (!room) throw new Error(\"Unknown room\");\n\n let event: MatrixEvent | undefined = room.getUnfilteredTimelineSet().findEventById(this.id);\n\n // keep scrolling back if needed until we find the event or reach the start of the room:\n while (!event && room.getLiveTimeline().getState(EventTimeline.BACKWARDS)!.paginationToken) {\n await this.client.scrollback(room, 100);\n event = room.getUnfilteredTimelineSet().findEventById(this.id);\n }\n\n if (!event) throw new Error(\"Failed to find event\");\n\n // Sometimes the event isn't decrypted for us, so do that. We specifically set `emit: true`\n // to ensure that the relations system in the sdk will function.\n await this.client.decryptEventIfNeeded(event, { emit: true, isRetry: true });\n\n return event;\n }\n\n /**\n * Creates a new version of this file with contents in a type that is compatible with MatrixClient.uploadContent().\n * @param name - The name of the file.\n * @param encryptedContents - The encrypted contents.\n * @param info - The encrypted file information.\n * @param additionalContent - Optional event content fields to include in the message.\n * @returns Promise which resolves to the file event's sent response.\n */\n public async createNewVersion(\n name: string,\n encryptedContents: FileType,\n info: Partial<IEncryptedFile>,\n additionalContent?: IContent,\n ): Promise<ISendEventResponse> {\n const fileEventResponse = await this.directory.createFile(name, encryptedContents, info, {\n ...(additionalContent ?? {}),\n \"m.new_content\": true,\n \"m.relates_to\": {\n rel_type: RelationType.Replace,\n event_id: this.id,\n },\n });\n\n // Update the version of the new event\n await this.client.sendStateEvent(\n this.roomId,\n UNSTABLE_MSC3089_BRANCH.name,\n {\n active: true,\n name: name,\n version: this.version + 1,\n },\n fileEventResponse[\"event_id\"],\n );\n\n // Deprecate ourselves\n await this.client.sendStateEvent(\n this.roomId,\n UNSTABLE_MSC3089_BRANCH.name,\n {\n ...this.indexEvent.getContent(),\n active: false,\n },\n this.id,\n );\n\n return fileEventResponse;\n }\n\n /**\n * Gets the file's version history, starting at this file.\n * @returns Promise which resolves to the file's version history, with the\n * first element being the current version and the last element being the first version.\n */\n public async getVersionHistory(): Promise<MSC3089Branch[]> {\n const fileHistory: MSC3089Branch[] = [];\n fileHistory.push(this); // start with ourselves\n\n const room = this.client.getRoom(this.roomId);\n if (!room) throw new Error(\"Invalid or unknown room\");\n\n // Clone the timeline to reverse it, getting most-recent-first ordering, hopefully\n // shortening the awful loop below. Without the clone, we can unintentionally mutate\n // the timeline.\n const timelineEvents = [...room.getLiveTimeline().getEvents()].reverse();\n\n // XXX: This is a very inefficient search, but it's the best we can do with the\n // relations structure we have in the SDK. As of writing, it is not worth the\n // investment in improving the structure.\n let childEvent: MatrixEvent | undefined;\n let parentEvent = await this.getFileEvent();\n do {\n childEvent = timelineEvents.find((e) => e.replacingEventId() === parentEvent.getId());\n if (childEvent) {\n const branch = this.directory.getFile(childEvent.getId()!);\n if (branch) {\n fileHistory.push(branch);\n parentEvent = childEvent;\n } else {\n break; // prevent infinite loop\n }\n }\n } while (childEvent);\n\n return fileHistory;\n }\n}\n"],"mappings":";;;;;;;;AAiBA,IAAAA,MAAA,GAAAC,OAAA;AAGA,IAAAC,cAAA,GAAAD,OAAA;AAAiD,SAAAE,QAAAC,MAAA,EAAAC,cAAA,QAAAC,IAAA,GAAAC,MAAA,CAAAD,IAAA,CAAAF,MAAA,OAAAG,MAAA,CAAAC,qBAAA,QAAAC,OAAA,GAAAF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