audon/audon-fe/src/stores/mastodon.js

68 wiersze
2.0 KiB
JavaScript
Czysty Zwykły widok Historia

2022-12-06 13:20:36 +00:00
import { defineStore } from "pinia";
import axios from "axios";
2023-01-23 13:29:31 +00:00
import { createClient } from "masto";
2022-12-07 05:45:05 +00:00
import { webfinger } from "../assets/utils";
2022-12-06 13:20:36 +00:00
export const useMastodonStore = defineStore("mastodon", {
state() {
return {
2022-12-07 05:45:05 +00:00
authorized: false,
oauth: {
url: "",
token: "",
2023-01-23 12:10:21 +00:00
audon: null,
},
2022-12-07 05:45:05 +00:00
client: null,
userinfo: null,
2022-12-06 13:20:36 +00:00
};
},
2022-12-07 05:45:05 +00:00
getters: {
myWebfinger() {
if (this.userinfo !== null) {
return webfinger(this.userinfo);
}
return "";
},
},
2022-12-06 13:20:36 +00:00
actions: {
async fetchToken() {
2022-12-07 05:45:05 +00:00
const resp = await axios.get("/api/token");
this.oauth = resp.data;
2023-01-23 13:29:31 +00:00
const client = createClient({
2022-12-07 05:45:05 +00:00
url: this.oauth.url,
accessToken: this.oauth.token,
disableVersionCheck: true,
2022-12-07 05:45:05 +00:00
});
this.client = client;
2023-01-23 12:10:21 +00:00
const user = await client.v1.accounts.verifyCredentials();
this.userinfo = user;
2022-12-07 05:45:05 +00:00
this.authorized = true;
},
2023-01-23 12:10:21 +00:00
async updateAvatar(img) {
if (this.client === null) return;
2023-01-23 13:29:31 +00:00
const avatarBlob = await (await fetch(img)).blob();
2023-01-23 12:10:21 +00:00
this.userinfo = await this.client.v1.accounts.updateCredentials({
2023-01-23 13:29:31 +00:00
avatar: new File([avatarBlob], `${Date.now()}.gif`),
2023-01-23 12:10:21 +00:00
});
},
async revertAvatar() {
const t = setTimeout(async () => {
2023-01-23 13:29:31 +00:00
const token = await axios.get("/api/token");
const oldAvatar = sessionStorage.getItem("avatar_old_data");
sessionStorage.removeItem("avatar_old_data");
2023-01-23 12:10:21 +00:00
sessionStorage.removeItem("avatar_timeout");
2023-01-23 13:29:31 +00:00
if (this.client === null || !oldAvatar || !token.data.audon.avatar)
return;
2023-01-23 12:10:21 +00:00
const resp = await axios.delete("/api/room");
if (resp.status === 200) {
2023-01-23 13:29:31 +00:00
const avatarBlob = await (await fetch(oldAvatar)).blob();
2023-01-23 12:10:21 +00:00
this.userinfo = await this.client.v1.accounts.updateCredentials({
2023-01-23 13:29:31 +00:00
avatar: new File([avatarBlob], token.data.audon.avatar),
2023-01-23 12:10:21 +00:00
});
2022-12-06 13:20:36 +00:00
}
2023-01-23 16:13:50 +00:00
}, 1500);
2023-01-23 12:10:21 +00:00
sessionStorage.setItem("avatar_timeout", t.toString());
2022-12-06 13:20:36 +00:00
},
},
});