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">
|
<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";
|
import type { CloudUser } from "@/seqta/utils/CloudAuth";
|
||||||
|
|
||||||
const { user, class: className = "" }: {
|
const { user, class: className = "" }: {
|
||||||
@@ -7,36 +7,24 @@
|
|||||||
class?: string;
|
class?: string;
|
||||||
} = $props();
|
} = $props();
|
||||||
|
|
||||||
let avatarSrc = $state<string | undefined>(undefined);
|
let avatarSrc = $state<string | null>(null);
|
||||||
let revokeUrl: string | undefined;
|
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
const u = user;
|
const u = user;
|
||||||
if (revokeUrl) {
|
avatarSrc = null;
|
||||||
URL.revokeObjectURL(revokeUrl);
|
|
||||||
revokeUrl = undefined;
|
|
||||||
}
|
|
||||||
avatarSrc = undefined;
|
|
||||||
|
|
||||||
if (!u?.id) return;
|
if (!u?.id) return;
|
||||||
|
|
||||||
const pfpUrl = u.pfpUrl ?? defaultAccountsPfpUrl(u.id);
|
|
||||||
|
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
void resolveCloudPfp(u.id, pfpUrl).then((resolved) => {
|
let resolved: string | null = null;
|
||||||
if (cancelled || !resolved) return;
|
void resolveCloudPfp(u.id, u.pfpUrl ?? defaultAccountsPfpUrl(u.id)).then((src) => {
|
||||||
if (resolved.fromCache) {
|
resolved = src;
|
||||||
revokeUrl = resolved.src;
|
if (cancelled) return revokePfpUrl(src);
|
||||||
}
|
avatarSrc = src;
|
||||||
avatarSrc = resolved.src;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
if (revokeUrl) {
|
revokePfpUrl(resolved);
|
||||||
URL.revokeObjectURL(revokeUrl);
|
|
||||||
revokeUrl = undefined;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -1,213 +1,110 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import RotateCwIcon from "@lucide/svelte/icons/rotate-cw";
|
|
||||||
import UploadIcon from "@lucide/svelte/icons/upload";
|
import UploadIcon from "@lucide/svelte/icons/upload";
|
||||||
import localforage from 'localforage'
|
import UserIcon from "@lucide/svelte/icons/user";
|
||||||
import { onMount } from 'svelte'
|
import XIcon from "@lucide/svelte/icons/x";
|
||||||
import browser from '@/lib/browser'
|
import { onMount } from "svelte";
|
||||||
import CloudPfpAvatar from '@/interface/components/CloudPfpAvatar.svelte'
|
import browser from "@/lib/browser";
|
||||||
import { cloudAuth } from '@/seqta/utils/CloudAuth'
|
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
||||||
import {
|
import { revokePfpUrl } from "@/seqta/utils/cloudPfpCache";
|
||||||
clearCloudProfilePicture,
|
import { uploadCloudProfilePicture } from "@/seqta/utils/cloudPfpSync";
|
||||||
isUseCloudPfpEnabled,
|
import { pluginSettingsStore } from "@/interface/pages/settings/pluginSettingsState.svelte";
|
||||||
notifyProfilePictureChanged,
|
import { loadPicture, REVISION_KEY, setLocalPicture } from "./picture";
|
||||||
pullCloudProfilePictureFromServer,
|
|
||||||
revertCloudProfilePicture,
|
|
||||||
syncLocalProfilePictureToCloud,
|
|
||||||
uploadCloudProfilePicture,
|
|
||||||
} from '@/seqta/utils/cloudPfpSync'
|
|
||||||
|
|
||||||
let value = $state<string | undefined>(undefined)
|
let cloud = $state(cloudAuth.state);
|
||||||
let fileInput = $state<HTMLInputElement | undefined>(undefined)
|
let src = $state<string | null>(null);
|
||||||
let cloudFileInput = $state<HTMLInputElement | undefined>(undefined)
|
let removable = $state(false);
|
||||||
let dragging = $state(false)
|
let busy = $state(false);
|
||||||
let blobUrl = $state<string | undefined>(undefined)
|
let error = $state<string>();
|
||||||
let useCloudPfp = $state(false)
|
let input = $state<HTMLInputElement>();
|
||||||
let cloudState = $state(cloudAuth.state)
|
let revision = $state(0);
|
||||||
let cloudBusy = $state(false)
|
let version = 0;
|
||||||
let cloudError = $state<string | undefined>(undefined)
|
|
||||||
|
|
||||||
const store = localforage.createInstance({
|
const useCloud = $derived(
|
||||||
name: 'profile-picture-store',
|
pluginSettingsStore.values["profile-picture"]?.useCloudPfp === true && cloud.isLoggedIn,
|
||||||
storeName: 'profilePicture',
|
);
|
||||||
})
|
|
||||||
|
|
||||||
async function load() {
|
$effect(() => {
|
||||||
useCloudPfp = await isUseCloudPfpEnabled()
|
const cloudUser = useCloud ? cloud.user : null;
|
||||||
const blob = await store.getItem<Blob>('profile-picture')
|
void revision;
|
||||||
if (blob && blob instanceof Blob) {
|
const current = ++version;
|
||||||
if (blobUrl) URL.revokeObjectURL(blobUrl)
|
void loadPicture(cloudUser).then((url) => {
|
||||||
blobUrl = URL.createObjectURL(blob)
|
if (current !== version) return revokePfpUrl(url);
|
||||||
value = blobUrl
|
revokePfpUrl(src);
|
||||||
} else {
|
src = url;
|
||||||
value = undefined
|
removable = !!url && !cloudUser;
|
||||||
}
|
});
|
||||||
}
|
});
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
void load()
|
const unsubscribe = cloudAuth.subscribe((state) => (cloud = state));
|
||||||
const unsub = cloudAuth.subscribe((s) => { cloudState = s })
|
const onStorage = (changes: Record<string, chrome.storage.StorageChange>, area: string) => {
|
||||||
const onStorage = (
|
if (area === "local" && changes[REVISION_KEY]) revision++;
|
||||||
changes: Record<string, chrome.storage.StorageChange>,
|
};
|
||||||
areaName: string,
|
browser.storage.onChanged.addListener(onStorage);
|
||||||
) => {
|
|
||||||
if (areaName === 'local' && changes['plugin.profile-picture.settings']) void load()
|
|
||||||
}
|
|
||||||
browser.storage.onChanged.addListener(onStorage)
|
|
||||||
return () => {
|
return () => {
|
||||||
browser.storage.onChanged.removeListener(onStorage)
|
version++;
|
||||||
unsub()
|
unsubscribe();
|
||||||
}
|
browser.storage.onChanged.removeListener(onStorage);
|
||||||
})
|
revokePfpUrl(src);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
async function afterProfilePictureChange() {
|
async function save(file: File | undefined) {
|
||||||
window.dispatchEvent(new Event('profile-picture-updated'))
|
if (!file?.type.startsWith("image/")) return;
|
||||||
if (await isUseCloudPfpEnabled()) await syncLocalProfilePictureToCloud()
|
error = undefined;
|
||||||
await notifyProfilePictureChanged()
|
if (!useCloud) return setLocalPicture(file);
|
||||||
}
|
busy = true;
|
||||||
|
const result = await uploadCloudProfilePicture(file);
|
||||||
async function runCloud(action: () => Promise<{ success: boolean; error?: string }>) {
|
busy = false;
|
||||||
cloudError = undefined
|
if (!result.success) error = result.error;
|
||||||
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()
|
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="flex flex-col items-end gap-1 shrink-0">
|
<div class="flex flex-col gap-1 items-end shrink-0">
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex gap-2 items-center">
|
||||||
{#if useCloudPfp && cloudState.isLoggedIn}
|
<button
|
||||||
<CloudPfpAvatar user={cloudState.user} class="object-cover rounded-full size-10 shrink-0" />
|
type="button"
|
||||||
<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'}"
|
||||||
type="button"
|
aria-label="Remove profile picture"
|
||||||
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"
|
onclick={() => setLocalPicture(null)}
|
||||||
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"
|
|
||||||
>
|
>
|
||||||
{#if value}
|
<XIcon size={16} />
|
||||||
<div class="flex items-center rounded-lg bg-zinc-200 dark:bg-zinc-800">
|
</button>
|
||||||
<img src={value} alt="Local profile" class="object-cover rounded-full size-10" />
|
<div
|
||||||
<button
|
class="flex overflow-hidden justify-center items-center rounded-full size-10 bg-zinc-200 dark:bg-zinc-700 text-zinc-400"
|
||||||
class="flex justify-center items-center m-1 text-lg dark:text-white size-7"
|
>
|
||||||
aria-label="Remove local profile picture"
|
{#if src}
|
||||||
onclick={(e) => {
|
<img {src} alt="Your avatar" class="object-cover size-full" />
|
||||||
e.stopPropagation()
|
|
||||||
removeImage()
|
|
||||||
}}
|
|
||||||
>×</button>
|
|
||||||
</div>
|
|
||||||
{:else}
|
{: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">
|
<UserIcon size={20} />
|
||||||
<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>
|
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</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>
|
</div>
|
||||||
|
{#if error}
|
||||||
{#if cloudState.isLoggedIn}
|
<p class="max-w-48 text-xs text-right text-red-500">{error}</p>
|
||||||
<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}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
@@ -5,19 +5,19 @@ import { toMountableComponent } from "@/types/mountableComponent";
|
|||||||
import { waitForElm } from "@/seqta/utils/waitForElm";
|
import { waitForElm } from "@/seqta/utils/waitForElm";
|
||||||
import browser from "@/lib/browser";
|
import browser from "@/lib/browser";
|
||||||
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
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 styles from "./styles.css?inline";
|
||||||
import localforage from "localforage";
|
|
||||||
|
|
||||||
const settings = defineSettings({
|
const settings = defineSettings({
|
||||||
useCloudPfp: booleanSetting({
|
useCloudPfp: booleanSetting({
|
||||||
default: false,
|
default: false,
|
||||||
title: "Use BetterSEQTA Cloud profile picture",
|
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({
|
picture: componentSetting({
|
||||||
title: "Profile Picture",
|
title: "Profile Picture",
|
||||||
description: "Upload or remove your custom profile image",
|
description: "Upload or remove your profile picture",
|
||||||
component: toMountableComponent(ProfilePictureSetting),
|
component: toMountableComponent(ProfilePictureSetting),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@@ -26,14 +26,13 @@ const profilePicturePlugin: Plugin<typeof settings> = {
|
|||||||
id: "profile-picture",
|
id: "profile-picture",
|
||||||
name: "Custom Profile Picture",
|
name: "Custom Profile Picture",
|
||||||
description: "Use your own image in place of the profile icon",
|
description: "Use your own image in place of the profile icon",
|
||||||
version: "1.3.0",
|
version: "2.0.0",
|
||||||
settings: settings,
|
settings: settings,
|
||||||
disableToggle: true,
|
disableToggle: true,
|
||||||
defaultEnabled: false,
|
defaultEnabled: false,
|
||||||
styles,
|
styles,
|
||||||
|
|
||||||
run: async (api) => {
|
run: async (api) => {
|
||||||
await api.storage.loaded;
|
|
||||||
let container: Element;
|
let container: Element;
|
||||||
try {
|
try {
|
||||||
container = await waitForElm(".userInfosvgdiv", true, 100, 60);
|
container = await waitForElm(".userInfosvgdiv", true, 100, 60);
|
||||||
@@ -41,97 +40,41 @@ const profilePicturePlugin: Plugin<typeof settings> = {
|
|||||||
return () => {};
|
return () => {};
|
||||||
}
|
}
|
||||||
|
|
||||||
const svg = container.querySelector(".userInfosvg") as HTMLElement | null;
|
const img = document.createElement("img");
|
||||||
let img: HTMLImageElement | null = null;
|
img.className = "userInfoImg";
|
||||||
let currentBlobUrl: string | undefined;
|
img.alt = "";
|
||||||
|
let version = 0;
|
||||||
|
|
||||||
const store = localforage.createInstance({
|
const render = async () => {
|
||||||
name: "profile-picture-store",
|
const current = ++version;
|
||||||
storeName: "profilePicture",
|
const { isLoggedIn, user } = cloudAuth.state;
|
||||||
});
|
const cloudUser = api.settings.useCloudPfp && isLoggedIn ? user : null;
|
||||||
|
const url = await loadPicture(cloudUser);
|
||||||
async function applyProfileImage() {
|
if (current !== version) return revokePfpUrl(url);
|
||||||
if (img) {
|
revokePfpUrl(img.src);
|
||||||
img.remove();
|
if (url) {
|
||||||
img = null;
|
img.src = url;
|
||||||
}
|
container.append(img);
|
||||||
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);
|
|
||||||
} else {
|
} else {
|
||||||
if (svg) svg.style.display = "";
|
img.removeAttribute("src");
|
||||||
}
|
img.remove();
|
||||||
}
|
|
||||||
|
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
browser.storage.onChanged.addListener(onStorageRevision);
|
|
||||||
|
|
||||||
const cloudUnsub = cloudAuth.subscribe(() => {
|
const onStorage = (changes: Record<string, chrome.storage.StorageChange>, area: string) => {
|
||||||
void applyProfileImage();
|
if (area === "local" && changes[REVISION_KEY]) void render();
|
||||||
});
|
};
|
||||||
|
browser.storage.onChanged.addListener(onStorage);
|
||||||
const useCloudUnreg = api.settings.onChange("useCloudPfp", (enabled: boolean) => {
|
const unsubscribe = cloudAuth.subscribe(() => void render());
|
||||||
void import("@/seqta/utils/cloudPfpSync").then(({ onUseCloudPfpToggled }) =>
|
const setting = api.settings.onChange("useCloudPfp", () => void render());
|
||||||
onUseCloudPfpToggled(enabled),
|
|
||||||
);
|
|
||||||
void applyProfileImage();
|
|
||||||
});
|
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
useCloudUnreg.unregister();
|
version++;
|
||||||
cloudUnsub();
|
setting.unregister();
|
||||||
window.removeEventListener("profile-picture-updated", onLocalPictureUpdated);
|
unsubscribe();
|
||||||
browser.storage.onChanged.removeListener(onStorageRevision);
|
browser.storage.onChanged.removeListener(onStorage);
|
||||||
if (img) img.remove();
|
revokePfpUrl(img.src);
|
||||||
if (svg) svg.style.display = "";
|
img.remove();
|
||||||
if (currentBlobUrl) URL.revokeObjectURL(currentBlobUrl);
|
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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 {
|
.userInfoImg {
|
||||||
width: 80%;
|
width: calc(100% - 6px);
|
||||||
height: 80%;
|
height: calc(100% - 6px);
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 10%;
|
top: 3px;
|
||||||
left: 10%;
|
left: 3px;
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
object-fit: cover;
|
object-fit: cover;
|
||||||
z-index: 4;
|
z-index: 4;
|
||||||
@@ -11,6 +11,10 @@
|
|||||||
transition: box-shadow 200ms;
|
transition: box-shadow 200ms;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.userInfosvgdiv:has(> .userInfoImg) > .userInfosvg {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
.dark .userInfoImg {
|
.dark .userInfoImg {
|
||||||
box-shadow: 0 0 0 3px #ffffff;
|
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;
|
if (mark === cloudUserId || mark === `none:${cloudUserId}`) return;
|
||||||
try {
|
try {
|
||||||
wrap.dataset.bsplusPfp = cloudUserId;
|
wrap.dataset.bsplusPfp = cloudUserId;
|
||||||
const resolved = await resolveCloudPfp(cloudUserId, defaultAccountsPfpUrl(cloudUserId));
|
const src = await resolveCloudPfp(cloudUserId, defaultAccountsPfpUrl(cloudUserId));
|
||||||
if (!resolved?.src) {
|
if (!src) {
|
||||||
wrap.dataset.bsplusPfp = `none:${cloudUserId}`;
|
wrap.dataset.bsplusPfp = `none:${cloudUserId}`;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const img = document.createElement("img");
|
const img = document.createElement("img");
|
||||||
img.alt = "";
|
img.alt = "";
|
||||||
img.loading = "lazy";
|
img.loading = "lazy";
|
||||||
img.src = resolved.src;
|
img.src = src;
|
||||||
wrap.querySelector(".bsplus-classmate-avatar-placeholder")?.remove();
|
wrap.querySelector(".bsplus-classmate-avatar-placeholder")?.remove();
|
||||||
wrap.appendChild(img);
|
wrap.appendChild(img);
|
||||||
} catch {
|
} catch {
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ export type CloudUser = {
|
|||||||
displayName?: string;
|
displayName?: string;
|
||||||
pfpUrl?: string;
|
pfpUrl?: string;
|
||||||
pfpHash?: string | null;
|
pfpHash?: string | null;
|
||||||
pfpHistory?: { id: string; r2Key: string; createdAt: number }[];
|
|
||||||
admin_level?: number;
|
admin_level?: number;
|
||||||
signup_number?: number | null;
|
signup_number?: number | null;
|
||||||
badges?: CloudBadge[];
|
badges?: CloudBadge[];
|
||||||
|
|||||||
@@ -81,13 +81,8 @@ export async function clearCloudPfpCache(userId?: string): Promise<void> {
|
|||||||
await clearLocal(id);
|
await clearLocal(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ResolveCloudPfpResult = {
|
export function revokePfpUrl(url: string | null | undefined): void {
|
||||||
src: string;
|
if (url?.startsWith("blob:")) URL.revokeObjectURL(url);
|
||||||
fromCache: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
function cachedBlobUrl(blob: Blob): ResolveCloudPfpResult {
|
|
||||||
return { src: URL.createObjectURL(blob), fromCache: true };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function sessionPfpHash(viewerId: string | null, userId: string): string | null {
|
function sessionPfpHash(viewerId: string | null, userId: string): string | null {
|
||||||
@@ -99,11 +94,11 @@ function localHashHit(
|
|||||||
serverHash: string | null | undefined,
|
serverHash: string | null | undefined,
|
||||||
localHash: string | null | undefined,
|
localHash: string | null | undefined,
|
||||||
localBlob: Blob | null | undefined,
|
localBlob: Blob | null | undefined,
|
||||||
): ResolveCloudPfpResult | null {
|
): string | null {
|
||||||
if (!serverHash || serverHash !== localHash || !(localBlob instanceof Blob)) {
|
if (!serverHash || serverHash !== localHash || !(localBlob instanceof Blob)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return cachedBlobUrl(localBlob);
|
return URL.createObjectURL(localBlob);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchAndCachePfp(
|
async function fetchAndCachePfp(
|
||||||
@@ -112,7 +107,7 @@ async function fetchAndCachePfp(
|
|||||||
serverHash: string,
|
serverHash: string,
|
||||||
localHash: string | null | undefined,
|
localHash: string | null | undefined,
|
||||||
localBlob: Blob | null | undefined,
|
localBlob: Blob | null | undefined,
|
||||||
): Promise<ResolveCloudPfpResult | null> {
|
): Promise<string | null> {
|
||||||
const imageUrl = pfpUrlWithHash(pfpUrl, serverHash);
|
const imageUrl = pfpUrlWithHash(pfpUrl, serverHash);
|
||||||
const headers: HeadersInit = {};
|
const headers: HeadersInit = {};
|
||||||
if (localHash) {
|
if (localHash) {
|
||||||
@@ -126,27 +121,22 @@ async function fetchAndCachePfp(
|
|||||||
const res = await fetch(imageUrl, { headers });
|
const res = await fetch(imageUrl, { headers });
|
||||||
if (res.status === 304 && localBlob instanceof Blob) {
|
if (res.status === 304 && localBlob instanceof Blob) {
|
||||||
await store.setItem(hashKey(userId), serverHash);
|
await store.setItem(hashKey(userId), serverHash);
|
||||||
return cachedBlobUrl(localBlob);
|
return URL.createObjectURL(localBlob);
|
||||||
}
|
}
|
||||||
if (!res.ok) return null;
|
if (!res.ok) return null;
|
||||||
|
|
||||||
const blob = await res.blob();
|
const blob = await res.blob();
|
||||||
await store.setItem(blobKey(userId), blob);
|
await store.setItem(blobKey(userId), blob);
|
||||||
await store.setItem(hashKey(userId), serverHash);
|
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.
|
* 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.
|
* Order: session hash match → local blob; else meta → download → store blob then hash.
|
||||||
*/
|
*/
|
||||||
export async function resolveCloudPfp(
|
export async function resolveCloudPfp(userId: string, pfpUrl: string): Promise<string | null> {
|
||||||
userId: string,
|
if (!isAccountsHostedPfpUrl(pfpUrl)) return pfpUrl;
|
||||||
pfpUrl: string,
|
|
||||||
): Promise<ResolveCloudPfpResult | null> {
|
|
||||||
if (!isAccountsHostedPfpUrl(pfpUrl)) {
|
|
||||||
return { src: pfpUrl, fromCache: false };
|
|
||||||
}
|
|
||||||
|
|
||||||
const viewerId = cloudAuth.state.user?.id ?? null;
|
const viewerId = cloudAuth.state.user?.id ?? null;
|
||||||
const localHash = await store.getItem<string>(hashKey(userId));
|
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 { cloudAuth, type CloudUser } from "@/seqta/utils/CloudAuth";
|
||||||
import { clearCloudPfpCache, pfpUrlWithHash } from "@/seqta/utils/cloudPfpCache";
|
import { clearCloudPfpCache, pfpUrlWithHash } from "@/seqta/utils/cloudPfpCache";
|
||||||
|
|
||||||
const ACCOUNTS_BASE = "https://accounts.betterseqta.org";
|
const ACCOUNTS_BASE = "https://accounts.betterseqta.org";
|
||||||
const BSPLUS_PFP = `${ACCOUNTS_BASE}/api/bsplus/pfp`;
|
const BSPLUS_PFP = `${ACCOUNTS_BASE}/api/bsplus/pfp`;
|
||||||
const PLUGIN_SETTINGS_KEY = "plugin.profile-picture.settings";
|
const UPLOAD_EDGE = 512;
|
||||||
const UPLOAD_MAX_EDGE = 512;
|
const MAX_SOURCE_BYTES = 20 * 1024 * 1024;
|
||||||
const MAX_SOURCE_BYTES_WEBP = 20 * 1024 * 1024;
|
|
||||||
const MAX_SOURCE_BYTES_LEGACY = 10 * 1024 * 1024;
|
|
||||||
|
|
||||||
function webpExportSupported(): boolean {
|
type Result = { success: boolean; error?: string };
|
||||||
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"];
|
|
||||||
};
|
|
||||||
|
|
||||||
async function parseJson(res: Response): Promise<Record<string, unknown>> {
|
async function parseJson(res: Response): Promise<Record<string, unknown>> {
|
||||||
const text = await res.text();
|
|
||||||
try {
|
try {
|
||||||
return text ? (JSON.parse(text) as Record<string, unknown>) : {};
|
return (await res.json()) as Record<string, unknown>;
|
||||||
} catch {
|
} catch {
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function parsePfpPayload(data: Record<string, unknown>): PfpPayload {
|
function withPfp(user: CloudUser, data: Record<string, unknown>): CloudUser {
|
||||||
const rawUrl = data.pfpUrl as string | null | undefined;
|
const url = data.pfpUrl as string | null | undefined;
|
||||||
const history = Array.isArray(data.pfpHistory) ? data.pfpHistory : [];
|
const pfpHash = (data.pfpHash as string | null | undefined) ?? null;
|
||||||
const pfpHistory = history.flatMap((item) => {
|
return { ...user, pfpUrl: url ? pfpUrlWithHash(url, pfpHash) : undefined, pfpHash };
|
||||||
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 mergePfpIntoUser(user: CloudUser, pfp: PfpPayload): CloudUser {
|
function withMe(user: CloudUser, data: Record<string, unknown>): CloudUser {
|
||||||
return {
|
const raw = (data.user as Record<string, unknown> | undefined) ?? data;
|
||||||
...user,
|
return withPfp(
|
||||||
pfpUrl: pfp.pfpUrl ? pfpUrlWithHash(pfp.pfpUrl, pfp.pfpHash) : undefined,
|
{
|
||||||
pfpHash: pfp.pfpHash,
|
...user,
|
||||||
pfpHistory: pfp.pfpHistory,
|
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,
|
||||||
async function applyPfpPayload(data: Record<string, unknown>): Promise<void> {
|
signup_number: (raw.signup_number as number | null | undefined) ?? user.signup_number,
|
||||||
const user = cloudAuth.state.user;
|
badges: (raw.badges as CloudUser["badges"]) ?? user.badges,
|
||||||
if (!user) return;
|
is_founding_2500: (raw.is_founding_2500 as boolean | undefined) ?? user.is_founding_2500,
|
||||||
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,
|
|
||||||
},
|
},
|
||||||
});
|
raw,
|
||||||
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 };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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");
|
if (!source.type.startsWith("image/")) throw new Error("Invalid file type");
|
||||||
const limit = maxSourceBytes();
|
if (source.size > MAX_SOURCE_BYTES) throw new Error("File too large (max 20MB)");
|
||||||
if (source.size > limit) {
|
|
||||||
const mb = Math.round(limit / (1024 * 1024));
|
|
||||||
throw new Error(`File too large (max ${mb}MB)`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const bitmap = await createImageBitmap(source);
|
const bitmap = await createImageBitmap(source);
|
||||||
try {
|
try {
|
||||||
const size = Math.min(bitmap.width, bitmap.height);
|
const size = Math.min(bitmap.width, bitmap.height);
|
||||||
const sx = Math.round((bitmap.width - size) / 2);
|
const canvas = new OffscreenCanvas(UPLOAD_EDGE, UPLOAD_EDGE);
|
||||||
const sy = Math.round((bitmap.height - size) / 2);
|
|
||||||
const canvas = new OffscreenCanvas(UPLOAD_MAX_EDGE, UPLOAD_MAX_EDGE);
|
|
||||||
const ctx = canvas.getContext("2d");
|
const ctx = canvas.getContext("2d");
|
||||||
if (!ctx) throw new Error("Could not prepare image");
|
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();
|
let blob = await canvas.convertToBlob({ type: "image/webp", quality: 0.88 });
|
||||||
const mime = webp ? "image/webp" : "image/jpeg";
|
if (blob.type !== "image/webp") {
|
||||||
const blob = await canvas.convertToBlob({ type: mime, quality: webp ? 0.88 : 0.85 });
|
blob = await canvas.convertToBlob({ type: "image/jpeg", quality: 0.85 });
|
||||||
return new File([blob], webp ? "profile.webp" : "profile.jpg", { type: mime });
|
}
|
||||||
|
return new File([blob], blob.type === "image/webp" ? "profile.webp" : "profile.jpg", {
|
||||||
|
type: blob.type,
|
||||||
|
});
|
||||||
} finally {
|
} finally {
|
||||||
bitmap.close();
|
bitmap.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function isUseCloudPfpEnabled(): Promise<boolean> {
|
export async function refreshCloudUserFromServer(): Promise<Result> {
|
||||||
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();
|
|
||||||
const current = cloudAuth.state.user;
|
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" };
|
return { success: false, error: "Not signed in to BetterSEQTA Cloud" };
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${ACCOUNTS_BASE}/api/auth/me`, {
|
const me = await authedFetch(`${ACCOUNTS_BASE}/api/auth/me`);
|
||||||
headers: { Authorization: `Bearer ${token}` },
|
if (!me) return { success: false, error: "Not signed in to BetterSEQTA Cloud" };
|
||||||
});
|
if (!me.res.ok) {
|
||||||
const data = await parseJson(res);
|
|
||||||
if (!res.ok) {
|
|
||||||
return {
|
return {
|
||||||
success: false,
|
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);
|
let user = withMe(current, me.data);
|
||||||
const pfp = await bsplusPfpRequest("");
|
const pfp = await authedFetch(BSPLUS_PFP);
|
||||||
if (pfp.ok) merged = mergePfpIntoUser(merged, parsePfpPayload(pfp.data));
|
if (pfp?.res.ok) user = withPfp(user, pfp.data);
|
||||||
await cloudAuth.setUser(merged);
|
await cloudAuth.setUser(user);
|
||||||
await clearCloudPfpCache(current.id);
|
await clearCloudPfpCache(current.id);
|
||||||
return { success: true };
|
return { success: true };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -198,91 +109,30 @@ export async function refreshCloudUserFromServer(): Promise<{ success: boolean;
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function pullCloudProfilePictureFromServer(): Promise<{
|
export async function uploadCloudProfilePicture(source: Blob): Promise<Result> {
|
||||||
success: boolean;
|
|
||||||
error?: string;
|
|
||||||
}> {
|
|
||||||
const current = cloudAuth.state.user;
|
const current = cloudAuth.state.user;
|
||||||
if (!cloudAuth.state.isLoggedIn || !current?.id) {
|
if (!cloudAuth.state.isLoggedIn || !current?.id) {
|
||||||
return { success: false, error: "Not signed in to BetterSEQTA Cloud" };
|
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 {
|
try {
|
||||||
const file = await prepareUploadFile(source);
|
const file = await cropToSquare(source);
|
||||||
const form = new FormData();
|
const form = new FormData();
|
||||||
form.append("file", file, file.name);
|
form.append("file", file, file.name);
|
||||||
form.append("clientProcessed", "true");
|
form.append("clientProcessed", "true");
|
||||||
form.append("preCropped", "true");
|
form.append("preCropped", "true");
|
||||||
const res = await bsplusPfpRequest("", { method: "POST", body: form });
|
const upload = await authedFetch(BSPLUS_PFP, { method: "POST", body: form });
|
||||||
if (!res.ok) return { success: false, error: res.error ?? "Upload failed" };
|
if (!upload) return { success: false, error: "Not signed in to BetterSEQTA Cloud" };
|
||||||
await applyPfpPayload(res.data);
|
if (!upload.res.ok) {
|
||||||
await notifyProfilePictureChanged();
|
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 };
|
return { success: true };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return { success: false, error: err instanceof Error ? err.message : "Upload failed" };
|
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