mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
feat: optionally sending cloudID for cloud related stuff when signed in
This commit is contained in:
1 parent
376ab65e3b
commit
c52217e902
8 files changed
+122
-36
No files matched your search
+10
-2
@@ -27,6 +27,7 @@ import {
|
||||
} from "./background/remoteConfig";
|
||||
import { BSPLUS_INSTALL_REGISTERED_AT_KEY } from "@/seqta/utils/remoteConfig/storageKeys";
|
||||
import { handleSearchThemeStockPhotos } from "./background/searchThemeStockPhotos";
|
||||
import { bsplusApiQueryParams, withBsplusApiQuery } from "@/seqta/utils/bsplusClientContext";
|
||||
import { initTimetableClassmatesBackgroundSync } from "./background/timetableClassmatesSync";
|
||||
|
||||
/**
|
||||
@@ -105,7 +106,11 @@ function normalizeFetchThemesResponse(json: unknown): {
|
||||
function handleFetchThemes(request: any, sendResponse: MessageSender): boolean {
|
||||
void (async () => {
|
||||
const token = await getAccessTokenFromStorage();
|
||||
const apiUrl = `${apiBase()}/api/themes?type=betterseqta&limit=100&nocache=${Date.now()}`;
|
||||
const params = await bsplusApiQueryParams();
|
||||
params.set("type", "betterseqta");
|
||||
params.set("limit", "100");
|
||||
params.set("nocache", String(Date.now()));
|
||||
const apiUrl = `${apiBase()}/api/themes?${params}`;
|
||||
const githubUrl = `https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Themes/main/store/themes.json?nocache=${Date.now()}`;
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||
@@ -151,7 +156,10 @@ function handleFetchThemeDetails(request: any, sendResponse: MessageSender): boo
|
||||
const token = await getAccessTokenFromStorage();
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||
fetch(`${apiBase()}/api/themes/${themeId}`, { cache: "no-store", headers })
|
||||
const detailUrl = await withBsplusApiQuery(
|
||||
`${apiBase()}/api/themes/${encodeURIComponent(themeId)}`,
|
||||
);
|
||||
fetch(detailUrl, { cache: "no-store", headers })
|
||||
.then((r) => r.json())
|
||||
.then(sendResponse)
|
||||
.catch((err) => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { normalizeCustomThemeApiResponse } from "@/seqta/utils/customThemes/parseApiEnvelope";
|
||||
import { bsplusApiQueryParams } from "@/seqta/utils/bsplusClientContext";
|
||||
|
||||
type MessageSender = { (response?: unknown): void };
|
||||
|
||||
@@ -115,6 +116,7 @@ export function createCustomThemesHandlers(deps: {
|
||||
params.set("type", "betterseqta");
|
||||
params.set("page", String(request.page ?? 1));
|
||||
params.set("limit", String(request.limit ?? 20));
|
||||
(await bsplusApiQueryParams()).forEach((value, key) => params.set(key, value));
|
||||
if (request.sort) params.set("sort", String(request.sort));
|
||||
const search = request.search?.trim();
|
||||
const path = search
|
||||
@@ -139,6 +141,7 @@ export function createCustomThemesHandlers(deps: {
|
||||
params.set("page", String(request.page ?? 1));
|
||||
params.set("limit", String(request.limit ?? 20));
|
||||
params.set("type", "betterseqta");
|
||||
(await bsplusApiQueryParams()).forEach((value, key) => params.set(key, value));
|
||||
if (request.status) params.set("status", String(request.status));
|
||||
sendResponse(
|
||||
await customThemesJsonFetch(`/api/custom-themes/mine?${params}`, {}, true),
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import { getBsplusDeviceName } from "@/seqta/utils/bsplusDeviceName";
|
||||
import {
|
||||
bsplusApiQueryParams,
|
||||
bsplusExtensionPayload,
|
||||
} from "@/seqta/utils/bsplusClientContext";
|
||||
import { getOrCreateInstallId } from "@/seqta/utils/feedback/installId";
|
||||
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||
import {
|
||||
@@ -21,19 +26,28 @@ import type { RemoteConfigSnapshot } from "@/seqta/utils/remoteConfig/types";
|
||||
|
||||
type MessageSender = { (response?: unknown): void };
|
||||
|
||||
function extensionChannel(): string {
|
||||
if (typeof __UPDATE_CHANNEL__ !== "undefined") {
|
||||
if (__UPDATE_CHANNEL__ === "nightly") return "nightly";
|
||||
if (__UPDATE_CHANNEL__ === "stable") return "stable";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
const ACCOUNTS_BASE = "https://accounts.betterseqta.org";
|
||||
|
||||
function extensionVersion(): string {
|
||||
async function linkCloudInstall(token: string, installId: string): Promise<void> {
|
||||
try {
|
||||
return browser.runtime.getManifest().version;
|
||||
} catch {
|
||||
return "0";
|
||||
const r = await fetch(`${ACCOUNTS_BASE}/api/bsplus/installs/link`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
installId,
|
||||
extension: bsplusExtensionPayload(),
|
||||
deviceName: await getBsplusDeviceName(),
|
||||
lastSeenAt: new Date().toISOString(),
|
||||
}),
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!r.ok) console.warn("[BetterSEQTA+] cloud install link failed:", r.status);
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] cloud install link failed:", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,6 +108,8 @@ async function registerInstall(
|
||||
"bsplus_token",
|
||||
"bsplus_user",
|
||||
]);
|
||||
const token =
|
||||
typeof bsplus_token === "string" && bsplus_token.length > 0 ? bsplus_token : undefined;
|
||||
const userId =
|
||||
bsplus_user && typeof bsplus_user === "object" && "id" in bsplus_user
|
||||
? String((bsplus_user as { id: string }).id)
|
||||
@@ -103,11 +119,7 @@ async function registerInstall(
|
||||
|
||||
const body = {
|
||||
installId,
|
||||
extension: {
|
||||
version: extensionVersion(),
|
||||
channel: extensionChannel(),
|
||||
browser: "chrome",
|
||||
},
|
||||
extension: bsplusExtensionPayload(),
|
||||
userId,
|
||||
lastSeenAt: new Date().toISOString(),
|
||||
...(hostname ? { hostname } : {}),
|
||||
@@ -118,9 +130,7 @@ async function registerInstall(
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
if (typeof bsplus_token === "string" && bsplus_token.length > 0) {
|
||||
headers.Authorization = `Bearer ${bsplus_token}`;
|
||||
}
|
||||
if (token) headers.Authorization = `Bearer ${token}`;
|
||||
const r = await fetch(`${apiBase}/api/bsplus/installs/register`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
@@ -135,6 +145,7 @@ async function registerInstall(
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] install register failed:", e);
|
||||
}
|
||||
if (token) void linkCloudInstall(token, installId);
|
||||
}
|
||||
|
||||
export async function refreshRemoteConfig(apiBase: () => string): Promise<{
|
||||
@@ -143,13 +154,8 @@ export async function refreshRemoteConfig(apiBase: () => string): Promise<{
|
||||
primaryOk: boolean;
|
||||
}> {
|
||||
const base = apiBase();
|
||||
const installId = await getOrCreateInstallId();
|
||||
const hostname = await readLastHostname();
|
||||
const params = new URLSearchParams({
|
||||
installId,
|
||||
extensionVersion: extensionVersion(),
|
||||
channel: extensionChannel(),
|
||||
});
|
||||
const params = await bsplusApiQueryParams();
|
||||
if (hostname) params.set("hostname", hostname);
|
||||
|
||||
const stored = await browser.storage.local.get([
|
||||
@@ -237,6 +243,12 @@ export function initRemoteConfigBackground(apiBase: () => string): void {
|
||||
} else {
|
||||
const res = await refreshRemoteConfig(apiBase);
|
||||
if (res.primaryOk) await registerInstall(apiBase(), true, true);
|
||||
else {
|
||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||
if (typeof bsplus_token === "string" && bsplus_token) {
|
||||
void linkCloudInstall(bsplus_token, await getOrCreateInstallId());
|
||||
}
|
||||
}
|
||||
}
|
||||
})();
|
||||
}
|
||||
@@ -295,11 +307,7 @@ export function createRemoteConfigHandlers(apiBase: () => string): Record<
|
||||
void (async () => {
|
||||
try {
|
||||
const hostname = await readLastHostname();
|
||||
const params = new URLSearchParams({
|
||||
installId: await getOrCreateInstallId(),
|
||||
extensionVersion: extensionVersion(),
|
||||
channel: extensionChannel(),
|
||||
});
|
||||
const params = await bsplusApiQueryParams();
|
||||
if (hostname) params.set("hostname", hostname);
|
||||
const base = apiBase();
|
||||
const url = `${base}/api/bsplus/remote-theme-packages/${encodeURIComponent(packageId)}?${params}`;
|
||||
|
||||
@@ -52,7 +52,9 @@ describe("cloud theme restoration", () => {
|
||||
(browser.runtime.sendMessage as jest.Mock).mockImplementation(
|
||||
async ({ url }) => {
|
||||
if (
|
||||
url === `https://betterseqta.org/api/${catalog}/catalog-id/download`
|
||||
typeof url === "string" &&
|
||||
url.includes(`/api/${catalog}/catalog-id/download`) &&
|
||||
url.includes("extensionVersion=")
|
||||
) {
|
||||
return {
|
||||
data: { success: true, data: { theme_json_url: jsonUrl } },
|
||||
|
||||
@@ -12,6 +12,7 @@ import { fullMotionEffectsEnabled } from "@/seqta/utils/performanceMode";
|
||||
import debounce from "@/seqta/utils/debounce";
|
||||
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
|
||||
import { getApiBase } from "@/seqta/utils/DevApiBase";
|
||||
import { withBsplusApiQuery } from "@/seqta/utils/bsplusClientContext";
|
||||
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||
import { updateAllColors } from "@/seqta/ui/colors/Manager";
|
||||
import {
|
||||
@@ -679,8 +680,16 @@ export class ThemeManager {
|
||||
|
||||
let themeJsonUrl = themeContent.theme_json_url;
|
||||
if (!themeJsonUrl) {
|
||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||
const auth =
|
||||
typeof bsplus_token === "string" && bsplus_token.length > 0
|
||||
? { auth: true as const }
|
||||
: undefined;
|
||||
const downloadData = (await this.fetchFromUrl(
|
||||
`${this.THEME_API_BASE}/custom-themes/${themeContent.id}/download`,
|
||||
await withBsplusApiQuery(
|
||||
`${this.THEME_API_BASE}/custom-themes/${encodeURIComponent(themeContent.id)}/download`,
|
||||
),
|
||||
auth,
|
||||
)) as { success?: boolean; data?: { theme_json_url: string } };
|
||||
if (!downloadData?.success || !downloadData?.data?.theme_json_url) {
|
||||
throw new Error("Failed to get community theme download URL");
|
||||
@@ -730,8 +739,16 @@ export class ThemeManager {
|
||||
let themeData: ThemeContent;
|
||||
|
||||
try {
|
||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||
const auth =
|
||||
typeof bsplus_token === "string" && bsplus_token.length > 0
|
||||
? { auth: true as const }
|
||||
: undefined;
|
||||
const downloadData = (await this.fetchFromUrl(
|
||||
`${this.THEME_API_BASE}/themes/${themeContent.id}/download`,
|
||||
await withBsplusApiQuery(
|
||||
`${this.THEME_API_BASE}/themes/${encodeURIComponent(themeContent.id)}/download`,
|
||||
),
|
||||
auth,
|
||||
)) as { success?: boolean; data?: { theme_json_url: string } };
|
||||
if (!downloadData?.success || !downloadData?.data?.theme_json_url) {
|
||||
throw new Error("Failed to get theme download URL");
|
||||
|
||||
Binary file not shown.
@@ -3,6 +3,7 @@ import stringToHTML from "../stringToHTML";
|
||||
import { settingsState } from "../listeners/SettingsState";
|
||||
import { closePopup } from "./PopupManager";
|
||||
import { getApiBase } from "../DevApiBase";
|
||||
import { withBsplusApiQuery } from "../bsplusClientContext";
|
||||
import { openThemeStoreWithHighlight } from "../openThemeStoreWithHighlight";
|
||||
import type { Theme } from "@/interface/types/Theme";
|
||||
import {
|
||||
@@ -62,7 +63,8 @@ async function writeCachedThemeOfTheMonth(
|
||||
*/
|
||||
export async function fetchThemeOfTheMonth(): Promise<ThemeOfTheMonthEntry | null> {
|
||||
try {
|
||||
const res = await fetch(`${getApiBase()}/api/theme-of-the-month/current`, {
|
||||
const url = await withBsplusApiQuery(`${getApiBase()}/api/theme-of-the-month/current`);
|
||||
const res = await fetch(url, {
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(TOTM_FETCH_TIMEOUT_MS),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import { getOrCreateInstallId } from "@/seqta/utils/feedback/installId";
|
||||
|
||||
function manifestVersion(): string {
|
||||
try {
|
||||
return browser.runtime.getManifest().version;
|
||||
} catch {
|
||||
return "0";
|
||||
}
|
||||
}
|
||||
|
||||
function updateChannel(): string {
|
||||
if (typeof __UPDATE_CHANNEL__ !== "undefined") {
|
||||
if (__UPDATE_CHANNEL__ === "nightly") return "nightly";
|
||||
if (__UPDATE_CHANNEL__ === "stable") return "stable";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export function bsplusExtensionPayload(): {
|
||||
version: string;
|
||||
channel: string;
|
||||
browser: "chrome";
|
||||
} {
|
||||
return { version: manifestVersion(), channel: updateChannel(), browser: "chrome" };
|
||||
}
|
||||
|
||||
/** Shared query params for betterseqta.org theme + remote-config requests. */
|
||||
export async function bsplusApiQueryParams(): Promise<URLSearchParams> {
|
||||
const params = new URLSearchParams({
|
||||
extensionVersion: manifestVersion(),
|
||||
channel: updateChannel(),
|
||||
installId: await getOrCreateInstallId(),
|
||||
});
|
||||
const { bsplus_user } = await browser.storage.local.get("bsplus_user");
|
||||
if (bsplus_user && typeof bsplus_user === "object" && "id" in bsplus_user) {
|
||||
const id = (bsplus_user as { id: unknown }).id;
|
||||
if (typeof id === "string" && id) params.set("userId", id);
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
export async function withBsplusApiQuery(url: string): Promise<string> {
|
||||
const qs = (await bsplusApiQueryParams()).toString();
|
||||
return qs ? (url.includes("?") ? `${url}&${qs}` : `${url}?${qs}`) : url;
|
||||
}
|
||||
Reference in new issue
Block a user