mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
refactor: rewrite profile picture system
This commit is contained in:
9 files changed
+264
-553
No files matched your search
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { resolveCloudPfp, defaultAccountsPfpUrl } from "@/seqta/utils/cloudPfpCache";
|
||||
import { resolveCloudPfp, defaultAccountsPfpUrl, revokePfpUrl } from "@/seqta/utils/cloudPfpCache";
|
||||
import type { CloudUser } from "@/seqta/utils/CloudAuth";
|
||||
|
||||
const { user, class: className = "" }: {
|
||||
@@ -7,36 +7,24 @@
|
||||
class?: string;
|
||||
} = $props();
|
||||
|
||||
let avatarSrc = $state<string | undefined>(undefined);
|
||||
let revokeUrl: string | undefined;
|
||||
let avatarSrc = $state<string | null>(null);
|
||||
|
||||
$effect(() => {
|
||||
const u = user;
|
||||
if (revokeUrl) {
|
||||
URL.revokeObjectURL(revokeUrl);
|
||||
revokeUrl = undefined;
|
||||
}
|
||||
avatarSrc = undefined;
|
||||
|
||||
avatarSrc = null;
|
||||
if (!u?.id) return;
|
||||
|
||||
const pfpUrl = u.pfpUrl ?? defaultAccountsPfpUrl(u.id);
|
||||
|
||||
let cancelled = false;
|
||||
void resolveCloudPfp(u.id, pfpUrl).then((resolved) => {
|
||||
if (cancelled || !resolved) return;
|
||||
if (resolved.fromCache) {
|
||||
revokeUrl = resolved.src;
|
||||
}
|
||||
avatarSrc = resolved.src;
|
||||
let resolved: string | null = null;
|
||||
void resolveCloudPfp(u.id, u.pfpUrl ?? defaultAccountsPfpUrl(u.id)).then((src) => {
|
||||
resolved = src;
|
||||
if (cancelled) return revokePfpUrl(src);
|
||||
avatarSrc = src;
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (revokeUrl) {
|
||||
URL.revokeObjectURL(revokeUrl);
|
||||
revokeUrl = undefined;
|
||||
}
|
||||
revokePfpUrl(resolved);
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -1,213 +1,110 @@
|
||||
<script lang="ts">
|
||||
import RotateCwIcon from "@lucide/svelte/icons/rotate-cw";
|
||||
import UploadIcon from "@lucide/svelte/icons/upload";
|
||||
import localforage from 'localforage'
|
||||
import { onMount } from 'svelte'
|
||||
import browser from '@/lib/browser'
|
||||
import CloudPfpAvatar from '@/interface/components/CloudPfpAvatar.svelte'
|
||||
import { cloudAuth } from '@/seqta/utils/CloudAuth'
|
||||
import {
|
||||
clearCloudProfilePicture,
|
||||
isUseCloudPfpEnabled,
|
||||
notifyProfilePictureChanged,
|
||||
pullCloudProfilePictureFromServer,
|
||||
revertCloudProfilePicture,
|
||||
syncLocalProfilePictureToCloud,
|
||||
uploadCloudProfilePicture,
|
||||
} from '@/seqta/utils/cloudPfpSync'
|
||||
import UserIcon from "@lucide/svelte/icons/user";
|
||||
import XIcon from "@lucide/svelte/icons/x";
|
||||
import { onMount } from "svelte";
|
||||
import browser from "@/lib/browser";
|
||||
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
||||
import { revokePfpUrl } from "@/seqta/utils/cloudPfpCache";
|
||||
import { uploadCloudProfilePicture } from "@/seqta/utils/cloudPfpSync";
|
||||
import { pluginSettingsStore } from "@/interface/pages/settings/pluginSettingsState.svelte";
|
||||
import { loadPicture, REVISION_KEY, setLocalPicture } from "./picture";
|
||||
|
||||
let value = $state<string | undefined>(undefined)
|
||||
let fileInput = $state<HTMLInputElement | undefined>(undefined)
|
||||
let cloudFileInput = $state<HTMLInputElement | undefined>(undefined)
|
||||
let dragging = $state(false)
|
||||
let blobUrl = $state<string | undefined>(undefined)
|
||||
let useCloudPfp = $state(false)
|
||||
let cloudState = $state(cloudAuth.state)
|
||||
let cloudBusy = $state(false)
|
||||
let cloudError = $state<string | undefined>(undefined)
|
||||
let cloud = $state(cloudAuth.state);
|
||||
let src = $state<string | null>(null);
|
||||
let removable = $state(false);
|
||||
let busy = $state(false);
|
||||
let error = $state<string>();
|
||||
let input = $state<HTMLInputElement>();
|
||||
let revision = $state(0);
|
||||
let version = 0;
|
||||
|
||||
const store = localforage.createInstance({
|
||||
name: 'profile-picture-store',
|
||||
storeName: 'profilePicture',
|
||||
})
|
||||
const useCloud = $derived(
|
||||
pluginSettingsStore.values["profile-picture"]?.useCloudPfp === true && cloud.isLoggedIn,
|
||||
);
|
||||
|
||||
async function load() {
|
||||
useCloudPfp = await isUseCloudPfpEnabled()
|
||||
const blob = await store.getItem<Blob>('profile-picture')
|
||||
if (blob && blob instanceof Blob) {
|
||||
if (blobUrl) URL.revokeObjectURL(blobUrl)
|
||||
blobUrl = URL.createObjectURL(blob)
|
||||
value = blobUrl
|
||||
} else {
|
||||
value = undefined
|
||||
}
|
||||
}
|
||||
$effect(() => {
|
||||
const cloudUser = useCloud ? cloud.user : null;
|
||||
void revision;
|
||||
const current = ++version;
|
||||
void loadPicture(cloudUser).then((url) => {
|
||||
if (current !== version) return revokePfpUrl(url);
|
||||
revokePfpUrl(src);
|
||||
src = url;
|
||||
removable = !!url && !cloudUser;
|
||||
});
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
void load()
|
||||
const unsub = cloudAuth.subscribe((s) => { cloudState = s })
|
||||
const onStorage = (
|
||||
changes: Record<string, chrome.storage.StorageChange>,
|
||||
areaName: string,
|
||||
) => {
|
||||
if (areaName === 'local' && changes['plugin.profile-picture.settings']) void load()
|
||||
}
|
||||
browser.storage.onChanged.addListener(onStorage)
|
||||
const unsubscribe = cloudAuth.subscribe((state) => (cloud = state));
|
||||
const onStorage = (changes: Record<string, chrome.storage.StorageChange>, area: string) => {
|
||||
if (area === "local" && changes[REVISION_KEY]) revision++;
|
||||
};
|
||||
browser.storage.onChanged.addListener(onStorage);
|
||||
return () => {
|
||||
browser.storage.onChanged.removeListener(onStorage)
|
||||
unsub()
|
||||
}
|
||||
})
|
||||
version++;
|
||||
unsubscribe();
|
||||
browser.storage.onChanged.removeListener(onStorage);
|
||||
revokePfpUrl(src);
|
||||
};
|
||||
});
|
||||
|
||||
async function afterProfilePictureChange() {
|
||||
window.dispatchEvent(new Event('profile-picture-updated'))
|
||||
if (await isUseCloudPfpEnabled()) await syncLocalProfilePictureToCloud()
|
||||
await notifyProfilePictureChanged()
|
||||
}
|
||||
|
||||
async function runCloud(action: () => Promise<{ success: boolean; error?: string }>) {
|
||||
cloudError = undefined
|
||||
cloudBusy = true
|
||||
const result = await action()
|
||||
cloudBusy = false
|
||||
if (!result.success) cloudError = result.error
|
||||
}
|
||||
|
||||
function triggerSelect() {
|
||||
fileInput?.click()
|
||||
}
|
||||
|
||||
async function handleFiles(files: FileList | null) {
|
||||
const file = files?.[0]
|
||||
if (!file?.type.startsWith('image/')) return
|
||||
|
||||
if (blobUrl) URL.revokeObjectURL(blobUrl)
|
||||
await store.setItem('profile-picture', file)
|
||||
blobUrl = URL.createObjectURL(file)
|
||||
value = blobUrl
|
||||
await afterProfilePictureChange()
|
||||
}
|
||||
|
||||
async function onCloudFileChange() {
|
||||
const file = cloudFileInput?.files?.[0]
|
||||
if (cloudFileInput) cloudFileInput.value = ''
|
||||
if (!file) return
|
||||
await runCloud(() => uploadCloudProfilePicture(file))
|
||||
}
|
||||
|
||||
function onFileChange() {
|
||||
handleFiles(fileInput?.files || null)
|
||||
}
|
||||
|
||||
function onDrop(event: DragEvent) {
|
||||
event.preventDefault()
|
||||
dragging = false
|
||||
handleFiles(event.dataTransfer?.files || null)
|
||||
}
|
||||
|
||||
async function removeImage() {
|
||||
if (blobUrl) {
|
||||
URL.revokeObjectURL(blobUrl)
|
||||
blobUrl = undefined
|
||||
}
|
||||
value = undefined
|
||||
await store.removeItem('profile-picture')
|
||||
if (await isUseCloudPfpEnabled()) await clearCloudProfilePicture()
|
||||
await afterProfilePictureChange()
|
||||
async function save(file: File | undefined) {
|
||||
if (!file?.type.startsWith("image/")) return;
|
||||
error = undefined;
|
||||
if (!useCloud) return setLocalPicture(file);
|
||||
busy = true;
|
||||
const result = await uploadCloudProfilePicture(file);
|
||||
busy = false;
|
||||
if (!result.success) error = result.error;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col items-end gap-1 shrink-0">
|
||||
<div class="flex items-center gap-2">
|
||||
{#if useCloudPfp && cloudState.isLoggedIn}
|
||||
<CloudPfpAvatar user={cloudState.user} class="object-cover rounded-full size-10 shrink-0" />
|
||||
<button
|
||||
type="button"
|
||||
class="flex justify-center items-center shrink-0 rounded-md size-8 bg-zinc-200 dark:bg-zinc-700 hover:bg-zinc-300 dark:hover:bg-zinc-600 disabled:opacity-50"
|
||||
disabled={cloudBusy}
|
||||
title="Refresh from cloud"
|
||||
aria-label="Refresh from cloud"
|
||||
onclick={() => runCloud(pullCloudProfilePictureFromServer)}
|
||||
>
|
||||
<RotateCwIcon size="1em" class="text-lg dark:text-white" />
|
||||
</button>
|
||||
<div class="w-px h-8 shrink-0 bg-zinc-300 dark:bg-zinc-600" aria-hidden="true"></div>
|
||||
{/if}
|
||||
|
||||
<div
|
||||
class="relative shrink-0 cursor-pointer select-none"
|
||||
onclick={() => (value ? null : triggerSelect())}
|
||||
ondragover={(e) => { e.stopPropagation(); dragging = true }}
|
||||
ondragleave={() => dragging = false}
|
||||
ondrop={onDrop}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault()
|
||||
triggerSelect()
|
||||
}
|
||||
}}
|
||||
role="button"
|
||||
tabindex="0"
|
||||
<div class="flex flex-col gap-1 items-end shrink-0">
|
||||
<div class="flex gap-2 items-center">
|
||||
<button
|
||||
type="button"
|
||||
class="flex justify-center items-center rounded-md size-8 bg-zinc-200 dark:bg-zinc-700 hover:bg-zinc-300 dark:hover:bg-zinc-600 dark:text-white {removable ? '' : 'invisible'}"
|
||||
aria-label="Remove profile picture"
|
||||
onclick={() => setLocalPicture(null)}
|
||||
>
|
||||
{#if value}
|
||||
<div class="flex items-center rounded-lg bg-zinc-200 dark:bg-zinc-800">
|
||||
<img src={value} alt="Local profile" class="object-cover rounded-full size-10" />
|
||||
<button
|
||||
class="flex justify-center items-center m-1 text-lg dark:text-white size-7"
|
||||
aria-label="Remove local profile picture"
|
||||
onclick={(e) => {
|
||||
e.stopPropagation()
|
||||
removeImage()
|
||||
}}
|
||||
>×</button>
|
||||
</div>
|
||||
<XIcon size={16} />
|
||||
</button>
|
||||
<div
|
||||
class="flex overflow-hidden justify-center items-center rounded-full size-10 bg-zinc-200 dark:bg-zinc-700 text-zinc-400"
|
||||
>
|
||||
{#if src}
|
||||
<img {src} alt="Your avatar" class="object-cover size-full" />
|
||||
{:else}
|
||||
<div class="flex gap-2 items-center px-3 py-1 text-xs rounded-lg border border-dashed transition border-zinc-300 dark:border-zinc-600 text-zinc-500 dark:text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-300 text-nowrap">
|
||||
<UploadIcon size="1em" class="text-lg" />
|
||||
<span>Upload</span>
|
||||
</div>
|
||||
{/if}
|
||||
<input type="file" accept="image/*" class="hidden" bind:this={fileInput} onchange={onFileChange} />
|
||||
{#if dragging}
|
||||
<div class="absolute inset-0 rounded-lg bg-zinc-200/40 dark:bg-zinc-700/40"></div>
|
||||
<UserIcon size={20} />
|
||||
{/if}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="flex gap-1.5 items-center px-3 h-8 text-xs rounded-md border border-dashed transition border-zinc-300 dark:border-zinc-600 text-zinc-500 dark:text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-300 text-nowrap disabled:opacity-50"
|
||||
disabled={busy}
|
||||
onclick={() => input?.click()}
|
||||
ondragover={(event) => event.preventDefault()}
|
||||
ondrop={(event) => {
|
||||
event.preventDefault();
|
||||
void save(event.dataTransfer?.files[0]);
|
||||
}}
|
||||
>
|
||||
<UploadIcon size={16} />
|
||||
Upload
|
||||
</button>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
class="hidden"
|
||||
bind:this={input}
|
||||
onchange={() => {
|
||||
void save(input?.files?.[0]);
|
||||
if (input) input.value = "";
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{#if cloudState.isLoggedIn}
|
||||
<div class="flex flex-wrap gap-2 justify-end items-center max-w-56">
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs text-zinc-600 dark:text-zinc-300 hover:underline disabled:opacity-50"
|
||||
disabled={cloudBusy}
|
||||
onclick={() => cloudFileInput?.click()}
|
||||
>
|
||||
Cloud upload
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs text-zinc-600 dark:text-zinc-300 hover:underline disabled:opacity-50"
|
||||
disabled={cloudBusy || !cloudState.user?.pfpUrl}
|
||||
onclick={() => runCloud(clearCloudProfilePicture)}
|
||||
>
|
||||
Clear cloud
|
||||
</button>
|
||||
{#each cloudState.user?.pfpHistory ?? [] as entry (entry.id)}
|
||||
<button
|
||||
type="button"
|
||||
class="size-7 overflow-hidden rounded-full ring-1 ring-zinc-300 dark:ring-zinc-600 disabled:opacity-50"
|
||||
title="Restore"
|
||||
disabled={cloudBusy}
|
||||
onclick={() => runCloud(() => revertCloudProfilePicture(entry.id))}
|
||||
>
|
||||
<img src={entry.r2Key} alt="" class="object-cover size-full" />
|
||||
</button>
|
||||
{/each}
|
||||
<input type="file" accept="image/*" class="hidden" bind:this={cloudFileInput} onchange={onCloudFileChange} />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if cloudError}
|
||||
<p class="max-w-48 text-xs text-right text-red-500">{cloudError}</p>
|
||||
{#if error}
|
||||
<p class="max-w-48 text-xs text-right text-red-500">{error}</p>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -5,19 +5,19 @@ import { toMountableComponent } from "@/types/mountableComponent";
|
||||
import { waitForElm } from "@/seqta/utils/waitForElm";
|
||||
import browser from "@/lib/browser";
|
||||
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
||||
import { resolveCloudPfp, defaultAccountsPfpUrl } from "@/seqta/utils/cloudPfpCache";
|
||||
import { revokePfpUrl } from "@/seqta/utils/cloudPfpCache";
|
||||
import { loadPicture, REVISION_KEY } from "./picture";
|
||||
import styles from "./styles.css?inline";
|
||||
import localforage from "localforage";
|
||||
|
||||
const settings = defineSettings({
|
||||
useCloudPfp: booleanSetting({
|
||||
default: false,
|
||||
title: "Use BetterSEQTA Cloud profile picture",
|
||||
description: "Use your cloud account avatar instead of the uploaded image below",
|
||||
description: "Show your cloud account picture instead of the one uploaded here",
|
||||
}),
|
||||
picture: componentSetting({
|
||||
title: "Profile Picture",
|
||||
description: "Upload or remove your custom profile image",
|
||||
description: "Upload or remove your profile picture",
|
||||
component: toMountableComponent(ProfilePictureSetting),
|
||||
}),
|
||||
});
|
||||
@@ -26,14 +26,13 @@ const profilePicturePlugin: Plugin<typeof settings> = {
|
||||
id: "profile-picture",
|
||||
name: "Custom Profile Picture",
|
||||
description: "Use your own image in place of the profile icon",
|
||||
version: "1.3.0",
|
||||
version: "2.0.0",
|
||||
settings: settings,
|
||||
disableToggle: true,
|
||||
defaultEnabled: false,
|
||||
styles,
|
||||
|
||||
run: async (api) => {
|
||||
await api.storage.loaded;
|
||||
let container: Element;
|
||||
try {
|
||||
container = await waitForElm(".userInfosvgdiv", true, 100, 60);
|
||||
@@ -41,97 +40,41 @@ const profilePicturePlugin: Plugin<typeof settings> = {
|
||||
return () => {};
|
||||
}
|
||||
|
||||
const svg = container.querySelector(".userInfosvg") as HTMLElement | null;
|
||||
let img: HTMLImageElement | null = null;
|
||||
let currentBlobUrl: string | undefined;
|
||||
const img = document.createElement("img");
|
||||
img.className = "userInfoImg";
|
||||
img.alt = "";
|
||||
let version = 0;
|
||||
|
||||
const store = localforage.createInstance({
|
||||
name: "profile-picture-store",
|
||||
storeName: "profilePicture",
|
||||
});
|
||||
|
||||
async function applyProfileImage() {
|
||||
if (img) {
|
||||
img.remove();
|
||||
img = null;
|
||||
}
|
||||
if (currentBlobUrl) {
|
||||
URL.revokeObjectURL(currentBlobUrl);
|
||||
currentBlobUrl = undefined;
|
||||
}
|
||||
|
||||
const useCloud = api.settings.useCloudPfp;
|
||||
const userId = cloudAuth.state.user?.id;
|
||||
const pfpUrl =
|
||||
cloudAuth.state.user?.pfpUrl ?? (userId ? defaultAccountsPfpUrl(userId) : undefined);
|
||||
|
||||
if (useCloud && pfpUrl && userId) {
|
||||
const resolved = await resolveCloudPfp(userId, pfpUrl);
|
||||
if (resolved) {
|
||||
currentBlobUrl = resolved.src;
|
||||
img = document.createElement("img");
|
||||
img.className = "userInfoImg";
|
||||
img.src = resolved.src;
|
||||
if (svg) svg.style.display = "none";
|
||||
container.appendChild(img);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const blob = await store.getItem<Blob>("profile-picture");
|
||||
if (blob && blob instanceof Blob) {
|
||||
currentBlobUrl = URL.createObjectURL(blob);
|
||||
img = document.createElement("img");
|
||||
img.className = "userInfoImg";
|
||||
img.src = currentBlobUrl;
|
||||
if (svg) svg.style.display = "none";
|
||||
container.appendChild(img);
|
||||
const render = async () => {
|
||||
const current = ++version;
|
||||
const { isLoggedIn, user } = cloudAuth.state;
|
||||
const cloudUser = api.settings.useCloudPfp && isLoggedIn ? user : null;
|
||||
const url = await loadPicture(cloudUser);
|
||||
if (current !== version) return revokePfpUrl(url);
|
||||
revokePfpUrl(img.src);
|
||||
if (url) {
|
||||
img.src = url;
|
||||
container.append(img);
|
||||
} else {
|
||||
if (svg) svg.style.display = "";
|
||||
}
|
||||
}
|
||||
|
||||
if (api.settings.useCloudPfp && cloudAuth.state.isLoggedIn) {
|
||||
const { pullCloudProfilePictureFromServer } = await import("@/seqta/utils/cloudPfpSync");
|
||||
await pullCloudProfilePictureFromServer();
|
||||
}
|
||||
|
||||
await applyProfileImage();
|
||||
|
||||
const onLocalPictureUpdated = () => {
|
||||
void applyProfileImage();
|
||||
};
|
||||
window.addEventListener("profile-picture-updated", onLocalPictureUpdated);
|
||||
|
||||
const onStorageRevision = (
|
||||
changes: Record<string, chrome.storage.StorageChange>,
|
||||
areaName: string,
|
||||
) => {
|
||||
if (areaName === "local" && changes.profile_picture_revision) {
|
||||
void applyProfileImage();
|
||||
img.removeAttribute("src");
|
||||
img.remove();
|
||||
}
|
||||
};
|
||||
browser.storage.onChanged.addListener(onStorageRevision);
|
||||
|
||||
const cloudUnsub = cloudAuth.subscribe(() => {
|
||||
void applyProfileImage();
|
||||
});
|
||||
|
||||
const useCloudUnreg = api.settings.onChange("useCloudPfp", (enabled: boolean) => {
|
||||
void import("@/seqta/utils/cloudPfpSync").then(({ onUseCloudPfpToggled }) =>
|
||||
onUseCloudPfpToggled(enabled),
|
||||
);
|
||||
void applyProfileImage();
|
||||
});
|
||||
const onStorage = (changes: Record<string, chrome.storage.StorageChange>, area: string) => {
|
||||
if (area === "local" && changes[REVISION_KEY]) void render();
|
||||
};
|
||||
browser.storage.onChanged.addListener(onStorage);
|
||||
const unsubscribe = cloudAuth.subscribe(() => void render());
|
||||
const setting = api.settings.onChange("useCloudPfp", () => void render());
|
||||
|
||||
return () => {
|
||||
useCloudUnreg.unregister();
|
||||
cloudUnsub();
|
||||
window.removeEventListener("profile-picture-updated", onLocalPictureUpdated);
|
||||
browser.storage.onChanged.removeListener(onStorageRevision);
|
||||
if (img) img.remove();
|
||||
if (svg) svg.style.display = "";
|
||||
if (currentBlobUrl) URL.revokeObjectURL(currentBlobUrl);
|
||||
version++;
|
||||
setting.unregister();
|
||||
unsubscribe();
|
||||
browser.storage.onChanged.removeListener(onStorage);
|
||||
revokePfpUrl(img.src);
|
||||
img.remove();
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import localforage from "localforage";
|
||||
import browser from "@/lib/browser";
|
||||
import type { CloudUser } from "@/seqta/utils/CloudAuth";
|
||||
import { defaultAccountsPfpUrl, resolveCloudPfp, revokePfpUrl } from "@/seqta/utils/cloudPfpCache";
|
||||
|
||||
export const REVISION_KEY = "profile_picture_revision";
|
||||
|
||||
const store = localforage.createInstance({
|
||||
name: "profile-picture-store",
|
||||
storeName: "profilePicture",
|
||||
});
|
||||
|
||||
export async function setLocalPicture(file: Blob | null): Promise<void> {
|
||||
if (file) await store.setItem("profile-picture", file);
|
||||
else await store.removeItem("profile-picture");
|
||||
await browser.storage.local.set({ [REVISION_KEY]: Date.now() });
|
||||
}
|
||||
|
||||
async function pictureUrl(cloudUser: CloudUser | null): Promise<string | null> {
|
||||
if (cloudUser) {
|
||||
const pfpUrl = cloudUser.pfpUrl ?? defaultAccountsPfpUrl(cloudUser.id);
|
||||
return resolveCloudPfp(cloudUser.id, pfpUrl);
|
||||
}
|
||||
const blob = await store.getItem<Blob>("profile-picture");
|
||||
return blob instanceof Blob ? URL.createObjectURL(blob) : null;
|
||||
}
|
||||
|
||||
export async function loadPicture(cloudUser: CloudUser | null): Promise<string | null> {
|
||||
const url = await pictureUrl(cloudUser).catch(() => null);
|
||||
if (!url) return null;
|
||||
const probe = new Image();
|
||||
probe.src = url;
|
||||
try {
|
||||
await probe.decode();
|
||||
return url;
|
||||
} catch {
|
||||
revokePfpUrl(url);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
.userInfoImg {
|
||||
width: 80%;
|
||||
height: 80%;
|
||||
width: calc(100% - 6px);
|
||||
height: calc(100% - 6px);
|
||||
position: absolute;
|
||||
top: 10%;
|
||||
left: 10%;
|
||||
top: 3px;
|
||||
left: 3px;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
z-index: 4;
|
||||
@@ -11,6 +11,10 @@
|
||||
transition: box-shadow 200ms;
|
||||
}
|
||||
|
||||
.userInfosvgdiv:has(> .userInfoImg) > .userInfosvg {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.dark .userInfoImg {
|
||||
box-shadow: 0 0 0 3px #ffffff;
|
||||
}
|
||||
|
||||
@@ -116,15 +116,15 @@ async function hydrateAvatarFromCloud(wrap: HTMLElement, cloudUserId: string): P
|
||||
if (mark === cloudUserId || mark === `none:${cloudUserId}`) return;
|
||||
try {
|
||||
wrap.dataset.bsplusPfp = cloudUserId;
|
||||
const resolved = await resolveCloudPfp(cloudUserId, defaultAccountsPfpUrl(cloudUserId));
|
||||
if (!resolved?.src) {
|
||||
const src = await resolveCloudPfp(cloudUserId, defaultAccountsPfpUrl(cloudUserId));
|
||||
if (!src) {
|
||||
wrap.dataset.bsplusPfp = `none:${cloudUserId}`;
|
||||
return;
|
||||
}
|
||||
const img = document.createElement("img");
|
||||
img.alt = "";
|
||||
img.loading = "lazy";
|
||||
img.src = resolved.src;
|
||||
img.src = src;
|
||||
wrap.querySelector(".bsplus-classmate-avatar-placeholder")?.remove();
|
||||
wrap.appendChild(img);
|
||||
} catch {
|
||||
|
||||
@@ -25,7 +25,6 @@ export type CloudUser = {
|
||||
displayName?: string;
|
||||
pfpUrl?: string;
|
||||
pfpHash?: string | null;
|
||||
pfpHistory?: { id: string; r2Key: string; createdAt: number }[];
|
||||
admin_level?: number;
|
||||
signup_number?: number | null;
|
||||
badges?: CloudBadge[];
|
||||
|
||||
@@ -81,13 +81,8 @@ export async function clearCloudPfpCache(userId?: string): Promise<void> {
|
||||
await clearLocal(id);
|
||||
}
|
||||
|
||||
export type ResolveCloudPfpResult = {
|
||||
src: string;
|
||||
fromCache: boolean;
|
||||
};
|
||||
|
||||
function cachedBlobUrl(blob: Blob): ResolveCloudPfpResult {
|
||||
return { src: URL.createObjectURL(blob), fromCache: true };
|
||||
export function revokePfpUrl(url: string | null | undefined): void {
|
||||
if (url?.startsWith("blob:")) URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
function sessionPfpHash(viewerId: string | null, userId: string): string | null {
|
||||
@@ -99,11 +94,11 @@ function localHashHit(
|
||||
serverHash: string | null | undefined,
|
||||
localHash: string | null | undefined,
|
||||
localBlob: Blob | null | undefined,
|
||||
): ResolveCloudPfpResult | null {
|
||||
): string | null {
|
||||
if (!serverHash || serverHash !== localHash || !(localBlob instanceof Blob)) {
|
||||
return null;
|
||||
}
|
||||
return cachedBlobUrl(localBlob);
|
||||
return URL.createObjectURL(localBlob);
|
||||
}
|
||||
|
||||
async function fetchAndCachePfp(
|
||||
@@ -112,7 +107,7 @@ async function fetchAndCachePfp(
|
||||
serverHash: string,
|
||||
localHash: string | null | undefined,
|
||||
localBlob: Blob | null | undefined,
|
||||
): Promise<ResolveCloudPfpResult | null> {
|
||||
): Promise<string | null> {
|
||||
const imageUrl = pfpUrlWithHash(pfpUrl, serverHash);
|
||||
const headers: HeadersInit = {};
|
||||
if (localHash) {
|
||||
@@ -126,27 +121,22 @@ async function fetchAndCachePfp(
|
||||
const res = await fetch(imageUrl, { headers });
|
||||
if (res.status === 304 && localBlob instanceof Blob) {
|
||||
await store.setItem(hashKey(userId), serverHash);
|
||||
return cachedBlobUrl(localBlob);
|
||||
return URL.createObjectURL(localBlob);
|
||||
}
|
||||
if (!res.ok) return null;
|
||||
|
||||
const blob = await res.blob();
|
||||
await store.setItem(blobKey(userId), blob);
|
||||
await store.setItem(hashKey(userId), serverHash);
|
||||
return { src: URL.createObjectURL(blob), fromCache: false };
|
||||
return URL.createObjectURL(blob);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an object URL or direct URL for the cloud profile picture.
|
||||
* Order: session hash match → local blob; else meta → download → store blob then hash.
|
||||
*/
|
||||
export async function resolveCloudPfp(
|
||||
userId: string,
|
||||
pfpUrl: string,
|
||||
): Promise<ResolveCloudPfpResult | null> {
|
||||
if (!isAccountsHostedPfpUrl(pfpUrl)) {
|
||||
return { src: pfpUrl, fromCache: false };
|
||||
}
|
||||
export async function resolveCloudPfp(userId: string, pfpUrl: string): Promise<string | null> {
|
||||
if (!isAccountsHostedPfpUrl(pfpUrl)) return pfpUrl;
|
||||
|
||||
const viewerId = cloudAuth.state.user?.id ?? null;
|
||||
const localHash = await store.getItem<string>(hashKey(userId));
|
||||
|
||||
+71
-221
@@ -1,193 +1,104 @@
|
||||
import browser from "@/lib/browser";
|
||||
import localforage from "localforage";
|
||||
import { cloudAuth, type CloudUser } from "@/seqta/utils/CloudAuth";
|
||||
import { clearCloudPfpCache, pfpUrlWithHash } from "@/seqta/utils/cloudPfpCache";
|
||||
|
||||
const ACCOUNTS_BASE = "https://accounts.betterseqta.org";
|
||||
const BSPLUS_PFP = `${ACCOUNTS_BASE}/api/bsplus/pfp`;
|
||||
const PLUGIN_SETTINGS_KEY = "plugin.profile-picture.settings";
|
||||
const UPLOAD_MAX_EDGE = 512;
|
||||
const MAX_SOURCE_BYTES_WEBP = 20 * 1024 * 1024;
|
||||
const MAX_SOURCE_BYTES_LEGACY = 10 * 1024 * 1024;
|
||||
const UPLOAD_EDGE = 512;
|
||||
const MAX_SOURCE_BYTES = 20 * 1024 * 1024;
|
||||
|
||||
function webpExportSupported(): boolean {
|
||||
try {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = 1;
|
||||
canvas.height = 1;
|
||||
return canvas.toDataURL("image/webp").startsWith("data:image/webp");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function maxSourceBytes(): number {
|
||||
return webpExportSupported() ? MAX_SOURCE_BYTES_WEBP : MAX_SOURCE_BYTES_LEGACY;
|
||||
}
|
||||
|
||||
const profileStore = localforage.createInstance({
|
||||
name: "profile-picture-store",
|
||||
storeName: "profilePicture",
|
||||
});
|
||||
|
||||
type PfpPayload = {
|
||||
pfpUrl: string | null;
|
||||
pfpHash: string | null;
|
||||
pfpHistory: CloudUser["pfpHistory"];
|
||||
};
|
||||
type Result = { success: boolean; error?: string };
|
||||
|
||||
async function parseJson(res: Response): Promise<Record<string, unknown>> {
|
||||
const text = await res.text();
|
||||
try {
|
||||
return text ? (JSON.parse(text) as Record<string, unknown>) : {};
|
||||
return (await res.json()) as Record<string, unknown>;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function parsePfpPayload(data: Record<string, unknown>): PfpPayload {
|
||||
const rawUrl = data.pfpUrl as string | null | undefined;
|
||||
const history = Array.isArray(data.pfpHistory) ? data.pfpHistory : [];
|
||||
const pfpHistory = history.flatMap((item) => {
|
||||
if (!item || typeof item !== "object") return [];
|
||||
const o = item as Record<string, unknown>;
|
||||
if (
|
||||
typeof o.id === "string" &&
|
||||
typeof o.r2Key === "string" &&
|
||||
typeof o.createdAt === "number"
|
||||
) {
|
||||
return [{ id: o.id, r2Key: o.r2Key, createdAt: o.createdAt }];
|
||||
}
|
||||
return [];
|
||||
});
|
||||
return {
|
||||
pfpUrl: rawUrl == null || rawUrl === "" ? null : rawUrl,
|
||||
pfpHash: (data.pfpHash as string | null | undefined) ?? null,
|
||||
pfpHistory,
|
||||
};
|
||||
function withPfp(user: CloudUser, data: Record<string, unknown>): CloudUser {
|
||||
const url = data.pfpUrl as string | null | undefined;
|
||||
const pfpHash = (data.pfpHash as string | null | undefined) ?? null;
|
||||
return { ...user, pfpUrl: url ? pfpUrlWithHash(url, pfpHash) : undefined, pfpHash };
|
||||
}
|
||||
|
||||
function mergePfpIntoUser(user: CloudUser, pfp: PfpPayload): CloudUser {
|
||||
return {
|
||||
...user,
|
||||
pfpUrl: pfp.pfpUrl ? pfpUrlWithHash(pfp.pfpUrl, pfp.pfpHash) : undefined,
|
||||
pfpHash: pfp.pfpHash,
|
||||
pfpHistory: pfp.pfpHistory,
|
||||
};
|
||||
}
|
||||
|
||||
async function applyPfpPayload(data: Record<string, unknown>): Promise<void> {
|
||||
const user = cloudAuth.state.user;
|
||||
if (!user) return;
|
||||
await cloudAuth.setUser(mergePfpIntoUser(user, parsePfpPayload(data)));
|
||||
if (user.id) await clearCloudPfpCache(user.id);
|
||||
}
|
||||
|
||||
async function bsplusPfpRequest(
|
||||
path: string,
|
||||
init?: RequestInit,
|
||||
): Promise<{ ok: boolean; data: Record<string, unknown>; error?: string }> {
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (!token) return { ok: false, data: {}, error: "Not signed in to BetterSEQTA Cloud" };
|
||||
|
||||
const res = await fetch(`${BSPLUS_PFP}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
...init?.headers,
|
||||
function withMe(user: CloudUser, data: Record<string, unknown>): CloudUser {
|
||||
const raw = (data.user as Record<string, unknown> | undefined) ?? data;
|
||||
return withPfp(
|
||||
{
|
||||
...user,
|
||||
email: (raw.email as string | undefined) ?? user.email,
|
||||
username: (raw.username as string | undefined) ?? user.username,
|
||||
displayName: (raw.displayName as string | undefined) ?? user.displayName,
|
||||
admin_level: (raw.admin_level as number | undefined) ?? user.admin_level,
|
||||
signup_number: (raw.signup_number as number | null | undefined) ?? user.signup_number,
|
||||
badges: (raw.badges as CloudUser["badges"]) ?? user.badges,
|
||||
is_founding_2500: (raw.is_founding_2500 as boolean | undefined) ?? user.is_founding_2500,
|
||||
},
|
||||
});
|
||||
const data = await parseJson(res);
|
||||
if (!res.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
data,
|
||||
error: (data.error as string) ?? `Request failed (${res.status})`,
|
||||
};
|
||||
}
|
||||
return { ok: true, data };
|
||||
raw,
|
||||
);
|
||||
}
|
||||
|
||||
async function prepareUploadFile(source: Blob): Promise<File> {
|
||||
async function authedFetch(url: string, init?: RequestInit) {
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (!token) return null;
|
||||
const res = await fetch(url, {
|
||||
...init,
|
||||
headers: { Authorization: `Bearer ${token}`, ...init?.headers },
|
||||
});
|
||||
return { res, data: await parseJson(res) };
|
||||
}
|
||||
|
||||
function requestError(data: Record<string, unknown>, status: number, fallback: string) {
|
||||
return (data.error as string | undefined) ?? `${fallback} (${status})`;
|
||||
}
|
||||
|
||||
async function cropToSquare(source: Blob): Promise<File> {
|
||||
if (!source.type.startsWith("image/")) throw new Error("Invalid file type");
|
||||
const limit = maxSourceBytes();
|
||||
if (source.size > limit) {
|
||||
const mb = Math.round(limit / (1024 * 1024));
|
||||
throw new Error(`File too large (max ${mb}MB)`);
|
||||
}
|
||||
if (source.size > MAX_SOURCE_BYTES) throw new Error("File too large (max 20MB)");
|
||||
|
||||
const bitmap = await createImageBitmap(source);
|
||||
try {
|
||||
const size = Math.min(bitmap.width, bitmap.height);
|
||||
const sx = Math.round((bitmap.width - size) / 2);
|
||||
const sy = Math.round((bitmap.height - size) / 2);
|
||||
const canvas = new OffscreenCanvas(UPLOAD_MAX_EDGE, UPLOAD_MAX_EDGE);
|
||||
const canvas = new OffscreenCanvas(UPLOAD_EDGE, UPLOAD_EDGE);
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) throw new Error("Could not prepare image");
|
||||
ctx.drawImage(bitmap, sx, sy, size, size, 0, 0, UPLOAD_MAX_EDGE, UPLOAD_MAX_EDGE);
|
||||
const sx = (bitmap.width - size) / 2;
|
||||
const sy = (bitmap.height - size) / 2;
|
||||
ctx.drawImage(bitmap, sx, sy, size, size, 0, 0, UPLOAD_EDGE, UPLOAD_EDGE);
|
||||
|
||||
const webp = webpExportSupported();
|
||||
const mime = webp ? "image/webp" : "image/jpeg";
|
||||
const blob = await canvas.convertToBlob({ type: mime, quality: webp ? 0.88 : 0.85 });
|
||||
return new File([blob], webp ? "profile.webp" : "profile.jpg", { type: mime });
|
||||
let blob = await canvas.convertToBlob({ type: "image/webp", quality: 0.88 });
|
||||
if (blob.type !== "image/webp") {
|
||||
blob = await canvas.convertToBlob({ type: "image/jpeg", quality: 0.85 });
|
||||
}
|
||||
return new File([blob], blob.type === "image/webp" ? "profile.webp" : "profile.jpg", {
|
||||
type: blob.type,
|
||||
});
|
||||
} finally {
|
||||
bitmap.close();
|
||||
}
|
||||
}
|
||||
|
||||
export async function isUseCloudPfpEnabled(): Promise<boolean> {
|
||||
const stored = await browser.storage.local.get(PLUGIN_SETTINGS_KEY);
|
||||
const settings = stored[PLUGIN_SETTINGS_KEY] as { useCloudPfp?: boolean } | undefined;
|
||||
return !!settings?.useCloudPfp;
|
||||
}
|
||||
|
||||
function mergeMeIntoUser(current: CloudUser, data: Record<string, unknown>): CloudUser {
|
||||
const raw = (data.user as Record<string, unknown> | undefined) ?? data;
|
||||
const pfpUrlRaw = raw.pfpUrl as string | null | undefined;
|
||||
const pfpHash = (raw.pfpHash as string | null | undefined) ?? null;
|
||||
const pfpUrl =
|
||||
pfpUrlRaw == null || pfpUrlRaw === "" ? undefined : pfpUrlWithHash(pfpUrlRaw, pfpHash);
|
||||
|
||||
return {
|
||||
...current,
|
||||
email: (raw.email as string | undefined) ?? current.email,
|
||||
username: (raw.username as string | undefined) ?? current.username,
|
||||
displayName: (raw.displayName as string | undefined) ?? current.displayName,
|
||||
admin_level: (raw.admin_level as number | undefined) ?? current.admin_level,
|
||||
signup_number: (raw.signup_number as number | null | undefined) ?? current.signup_number,
|
||||
badges: (raw.badges as CloudUser["badges"]) ?? current.badges,
|
||||
is_founding_2500: (raw.is_founding_2500 as boolean | undefined) ?? current.is_founding_2500,
|
||||
pfpUrl,
|
||||
pfpHash,
|
||||
};
|
||||
}
|
||||
|
||||
export async function refreshCloudUserFromServer(): Promise<{ success: boolean; error?: string }> {
|
||||
if (!cloudAuth.state.isLoggedIn) {
|
||||
return { success: false, error: "Not signed in to BetterSEQTA Cloud" };
|
||||
}
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
export async function refreshCloudUserFromServer(): Promise<Result> {
|
||||
const current = cloudAuth.state.user;
|
||||
if (!token || !current?.id) {
|
||||
if (!cloudAuth.state.isLoggedIn || !current?.id) {
|
||||
return { success: false, error: "Not signed in to BetterSEQTA Cloud" };
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`${ACCOUNTS_BASE}/api/auth/me`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
const data = await parseJson(res);
|
||||
if (!res.ok) {
|
||||
const me = await authedFetch(`${ACCOUNTS_BASE}/api/auth/me`);
|
||||
if (!me) return { success: false, error: "Not signed in to BetterSEQTA Cloud" };
|
||||
if (!me.res.ok) {
|
||||
return {
|
||||
success: false,
|
||||
error: (data.error as string) ?? `Could not refresh account (${res.status})`,
|
||||
error: requestError(me.data, me.res.status, "Could not refresh account"),
|
||||
};
|
||||
}
|
||||
|
||||
let merged = mergeMeIntoUser(current, data);
|
||||
const pfp = await bsplusPfpRequest("");
|
||||
if (pfp.ok) merged = mergePfpIntoUser(merged, parsePfpPayload(pfp.data));
|
||||
await cloudAuth.setUser(merged);
|
||||
let user = withMe(current, me.data);
|
||||
const pfp = await authedFetch(BSPLUS_PFP);
|
||||
if (pfp?.res.ok) user = withPfp(user, pfp.data);
|
||||
await cloudAuth.setUser(user);
|
||||
await clearCloudPfpCache(current.id);
|
||||
return { success: true };
|
||||
} catch (err) {
|
||||
@@ -198,91 +109,30 @@ export async function refreshCloudUserFromServer(): Promise<{ success: boolean;
|
||||
}
|
||||
}
|
||||
|
||||
export async function pullCloudProfilePictureFromServer(): Promise<{
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
export async function uploadCloudProfilePicture(source: Blob): Promise<Result> {
|
||||
const current = cloudAuth.state.user;
|
||||
if (!cloudAuth.state.isLoggedIn || !current?.id) {
|
||||
return { success: false, error: "Not signed in to BetterSEQTA Cloud" };
|
||||
}
|
||||
|
||||
const pfp = await bsplusPfpRequest("");
|
||||
if (!pfp.ok) return { success: false, error: pfp.error ?? "Could not refresh cloud photo" };
|
||||
|
||||
await applyPfpPayload(pfp.data);
|
||||
await notifyProfilePictureChanged();
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function onUseCloudPfpToggled(enabled: boolean): Promise<void> {
|
||||
if (!enabled) {
|
||||
await notifyProfilePictureChanged();
|
||||
return;
|
||||
}
|
||||
const blob = await profileStore.getItem<Blob>("profile-picture");
|
||||
if (blob instanceof Blob) await syncLocalProfilePictureToCloud();
|
||||
else await pullCloudProfilePictureFromServer();
|
||||
}
|
||||
|
||||
export async function uploadCloudProfilePicture(
|
||||
source: Blob,
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
if (!cloudAuth.state.isLoggedIn) {
|
||||
return { success: false, error: "Not signed in to BetterSEQTA Cloud" };
|
||||
}
|
||||
try {
|
||||
const file = await prepareUploadFile(source);
|
||||
const file = await cropToSquare(source);
|
||||
const form = new FormData();
|
||||
form.append("file", file, file.name);
|
||||
form.append("clientProcessed", "true");
|
||||
form.append("preCropped", "true");
|
||||
const res = await bsplusPfpRequest("", { method: "POST", body: form });
|
||||
if (!res.ok) return { success: false, error: res.error ?? "Upload failed" };
|
||||
await applyPfpPayload(res.data);
|
||||
await notifyProfilePictureChanged();
|
||||
const upload = await authedFetch(BSPLUS_PFP, { method: "POST", body: form });
|
||||
if (!upload) return { success: false, error: "Not signed in to BetterSEQTA Cloud" };
|
||||
if (!upload.res.ok) {
|
||||
return {
|
||||
success: false,
|
||||
error: requestError(upload.data, upload.res.status, "Upload failed"),
|
||||
};
|
||||
}
|
||||
await clearCloudPfpCache(current.id);
|
||||
await cloudAuth.setUser(withPfp(current, upload.data));
|
||||
return { success: true };
|
||||
} catch (err) {
|
||||
return { success: false, error: err instanceof Error ? err.message : "Upload failed" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function syncLocalProfilePictureToCloud(): Promise<{
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
if (!(await isUseCloudPfpEnabled()) || !cloudAuth.state.isLoggedIn) return { success: true };
|
||||
const blob = await profileStore.getItem<Blob>("profile-picture");
|
||||
if (!(blob instanceof Blob)) return { success: true };
|
||||
return uploadCloudProfilePicture(blob);
|
||||
}
|
||||
|
||||
export async function clearCloudProfilePicture(): Promise<{ success: boolean; error?: string }> {
|
||||
if (!cloudAuth.state.isLoggedIn) return { success: true };
|
||||
const res = await bsplusPfpRequest("/clear", { method: "POST" });
|
||||
if (!res.ok) return { success: false, error: res.error ?? "Clear failed" };
|
||||
await applyPfpPayload(res.data);
|
||||
await notifyProfilePictureChanged();
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function revertCloudProfilePicture(
|
||||
historyId: string,
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
if (!cloudAuth.state.isLoggedIn) {
|
||||
return { success: false, error: "Not signed in to BetterSEQTA Cloud" };
|
||||
}
|
||||
const res = await bsplusPfpRequest("/revert", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ historyId }),
|
||||
});
|
||||
if (!res.ok) return { success: false, error: res.error ?? "Revert failed" };
|
||||
await applyPfpPayload(res.data);
|
||||
await notifyProfilePictureChanged();
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function notifyProfilePictureChanged(): Promise<void> {
|
||||
await browser.storage.local.set({ profile_picture_revision: Date.now() });
|
||||
}
|
||||
Reference in new issue
Block a user