You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
2.0 KiB
JavaScript
53 lines
2.0 KiB
JavaScript
4 years ago
|
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(baseUrl) {
|
||
|
this.baseUrl = baseUrl;
|
||
|
this.clientId;
|
||
|
this.clientSecret;
|
||
|
this.accessToken = loadData("./accessToken.json");
|
||
|
}
|
||
|
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}`)
|
||
|
storeData(this.accessToken, "./accessToken.json");
|
||
|
_callback(this.accessToken);
|
||
|
})
|
||
|
}
|
||
|
}
|