From 9cafb8cd26c88eef72d95972a56673a772d4c403 Mon Sep 17 00:00:00 2001 From: Robert Long Date: Thu, 15 Sep 2022 21:21:21 -0700 Subject: [PATCH] Add setAccountData and getAccountData --- src/matrix/Session.js | 36 +++++++++++++++++++++++++++++++++ src/matrix/net/HomeServerApi.ts | 9 +++++++++ 2 files changed, 45 insertions(+) diff --git a/src/matrix/Session.js b/src/matrix/Session.js index 9ce9a9ba..5e4caa8c 100644 --- a/src/matrix/Session.js +++ b/src/matrix/Session.js @@ -963,6 +963,42 @@ export class Session { return this._roomStateHandler.subscribe(roomStateHandler); } + async setAccountData(type, content) { + const txn = await this._storage.readWriteTxn([this._storage.storeNames.accountData]); + + if (txn) { + txn.accountData.set({ type, content }); + await txn.complete(); + } + + await this.hsApi.setAccountData(this.userId, type, content).response(); + } + + async getAccountData(type) { + const txn = await this._storage.readWriteTxn([this._storage.storeNames.accountData]); + + const entry = await txn.accountData.get(type); + + if (entry) { + await txn.complete(); + return entry.content; + } else { + try { + const content = await this.hsApi.accountData(this.userId, type).response(); + + if (content) { + txn.accountData.set({ type, content }); + await txn.complete(); + } + + return content; + } catch (error) { + txn.abort(); + return undefined; + } + } + } + /** Creates an empty (summary isn't loaded) the archived room if it isn't loaded already, assuming sync will either remove it (when rejoining) or diff --git a/src/matrix/net/HomeServerApi.ts b/src/matrix/net/HomeServerApi.ts index 77eda7ee..d9bd8f50 100644 --- a/src/matrix/net/HomeServerApi.ts +++ b/src/matrix/net/HomeServerApi.ts @@ -360,6 +360,15 @@ export class HomeServerApi { createRoom(payload: Record, options?: BaseRequestOptions): IHomeServerRequest { return this._post(`/createRoom`, {}, payload, options); } + + accountData(ownUserId: string, type: string, options?: BaseRequestOptions): IHomeServerRequest { + return this._get( + `/user/${encodeURIComponent(ownUserId)}/account_data/${encodeURIComponent(type)}`, + undefined, + undefined, + options, + ); + } setAccountData(ownUserId: string, type: string, content: Record, options?: BaseRequestOptions): IHomeServerRequest { return this._put(`/user/${encodeURIComponent(ownUserId)}/account_data/${encodeURIComponent(type)}`, {}, content, options);