get accessToken and execute callback

master
adb 3 years ago
parent b4bca549e1
commit 771974202e

1
.gitignore vendored

@ -0,0 +1 @@
./accessToken.json*

@ -0,0 +1,17 @@
import fs from "fs";
export function storeData(data, path) {
try {
fs.writeFileSync(path, JSON.stringify(data));
} catch (err) {
console.error(err);
}
}
export function loadData(path) {
try {
return JSON.parse(fs.readFileSync(path, 'utf8'))
} catch (err) {
console.error(err)
return false
}
}

@ -0,0 +1,9 @@
import {MastodonHandler} from "./mastodonHandler.js";
import {MastodonTokenHandler} from "./mastodonTokenHandler.js"
const baseUrl = "https://social.cybre.town";
let tokenHandler = new MastodonTokenHandler(baseUrl);
tokenHandler.getAccessToken((accessToken) => {
let client = new MastodonHandler(baseUrl, accessToken);
});

@ -0,0 +1,10 @@
import Mastodon from "mastodon-api";
export class MastodonHandler{
constructor(baseUrl, token) {
this.client = new Mastodon({
api_url: `${baseUrl}/api/v1/`,
access_token: token,
})
}
}

@ -0,0 +1,53 @@
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);
})
}
}

@ -2,11 +2,15 @@
"name": "mastodon_meme_bot",
"version": "1.0.0",
"description": "",
"main": "index.js",
"main": "main.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
"license": "ISC",
"dependencies": {
"mastodon-api": "^1.3.0"
}
}

Loading…
Cancel
Save