/**
 * A client specifically designed to interact with Pantalaimon instead of
 * a Matrix homeserver. The key part of this is managing the access token
 * and username/password for interacting with Pantalaimon.
 *
 * If the storage provider given claims to have an access token for
 * this client, it will be used even if Pantalaimon considers it invalid.
 *
 * Expected usage:
 * <code>
 *     const storage = new SimpleFsStorageProvider("storage/bot.json");
 *     const pantalaimon = new PantalaimonClient("http://localhost:8008", storage);
 *
 *     // Note that the credentials will only be used if there is no available access token.
 *     const client = await pantalaimon.createClientWithCredentials("username", "password");
 * </code>
 */ import { IStorageProvider } from "./storage/IStorageProvider" ; import { MatrixClient } from "./MatrixClient" ; import { MatrixAuth } from "./MatrixAuth" ; const ACCESS_TOKEN_STORAGE_KEY = "pantalaimon_access_token" ; category export class PantalaimonClient { param { string } homeserverUrl param { IStorageProvider } storageProvider public constructor ( private homeserverUrl , private storageProvider ) { } param { string } username param { string } password returns { Promise < MatrixClient > } public async createClientWithCredentials ( username , password ) { const accessToken = await Promise . resolve ( this . storageProvider . readValue ( ACCESS_TOKEN_STORAGE_KEY ) ) ; if ( accessToken ) { return new MatrixClient ( this . homeserverUrl , accessToken , this . storageProvider ) ; } const auth = new MatrixAuth ( this . homeserverUrl ) ; const authedClient = await auth . passwordLogin ( username , password ) ; await Promise . resolve ( this . storageProvider . storeValue ( ACCESS_TOKEN_STORAGE_KEY , authedClient . accessToken ) ) ; return new MatrixClient ( this . homeserverUrl , authedClient . accessToken , this . storageProvider ) ; } }