import Mastodon from 'mastodon-api'; import readline from 'readline'; import {storeData, loadData} from './JSONdataStore.js'; const rl = readline.createInterface({ input: process.stdin, output: process.stdout }) export class MastodonTokenHandler { constructor(config) { this.config = config??loadData("./config.json"); this.clientId; this.clientSecret; this.accessToken = this.config.token; this.baseUrl = this.config.baseUrl; } getAccessToken(_callback){ if (!this.accessToken) this.newAccessToken(_callback); else _callback(this.accessToken); return this.accessToken; } newAccessToken(_callback){ Mastodon.createOAuthApp(`${this.baseUrl}/api/v1/apps`) .catch((err) => console.error(err)) .then((res) => { console.log('Please save \'id\', \'client_id\' and \'client_secret\' in your program and use it from now on!') console.log(res) this.clientId = res.client_id this.clientSecret = res.client_secret return Mastodon.getAuthorizationUrl(this.clientId, this.clientSecret, this.baseUrl) }) .then((url) => { console.log('This is the authorization URL. Open it in your browser and authorize with your account!') console.log(url) return new Promise((resolve) => { rl.question('Please enter the code from the website: ', (code) => { resolve(code) rl.close() }) }) }) .then((code) => Mastodon.getAccessToken(this.clientId, this.clientSecret, code, this.baseUrl)) .catch((err) => console.error(err)) .then((token) => { this.accessToken = token; console.log(`This is the access token. Save it!\n${this.accessToken}`) this.config.token = this.accessToken; storeData(this.config, "./config.json"); _callback(this.accessToken); }) } }