2024-08-16 23:36:56 +06:00
|
|
|
import turnstile from "$lib/api/turnstile";
|
|
|
|
import { currentApiURL } from "$lib/api/api-url";
|
|
|
|
|
2024-08-26 23:38:24 +06:00
|
|
|
import type { CobaltSession, CobaltErrorResponse, CobaltSessionResponse } from "$lib/types/api";
|
|
|
|
|
2024-10-20 11:46:09 +00:00
|
|
|
let cache: CobaltSession | undefined;
|
2024-08-16 23:36:56 +06:00
|
|
|
|
2024-10-20 11:46:09 +00:00
|
|
|
export const requestSession = async () => {
|
2024-08-16 23:52:40 +06:00
|
|
|
const apiEndpoint = `${currentApiURL()}/session`;
|
2024-08-16 23:36:56 +06:00
|
|
|
|
|
|
|
let requestHeaders = {};
|
|
|
|
|
|
|
|
const turnstileResponse = turnstile.getResponse();
|
|
|
|
if (turnstileResponse) {
|
|
|
|
requestHeaders = {
|
|
|
|
"cf-turnstile-response": turnstileResponse
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
const response: CobaltSessionResponse = await fetch(apiEndpoint, {
|
|
|
|
method: "POST",
|
|
|
|
redirect: "manual",
|
|
|
|
signal: AbortSignal.timeout(10000),
|
|
|
|
headers: requestHeaders,
|
|
|
|
})
|
|
|
|
.then(r => r.json())
|
|
|
|
.catch((e) => {
|
|
|
|
if (e?.message?.includes("timed out")) {
|
|
|
|
return {
|
|
|
|
status: "error",
|
|
|
|
error: {
|
|
|
|
code: "error.api.timed_out"
|
|
|
|
}
|
|
|
|
} as CobaltErrorResponse
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2024-11-19 00:20:27 +06:00
|
|
|
turnstile.reset();
|
2024-08-16 23:36:56 +06:00
|
|
|
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const getSession = async () => {
|
2024-08-19 22:25:21 +06:00
|
|
|
const currentTime = () => Math.floor(new Date().getTime() / 1000);
|
2024-08-16 23:36:56 +06:00
|
|
|
|
2024-08-19 22:25:21 +06:00
|
|
|
if (cache?.token && cache?.exp - 2 > currentTime()) {
|
2024-08-16 23:36:56 +06:00
|
|
|
return cache;
|
|
|
|
}
|
|
|
|
|
|
|
|
const newSession = await requestSession();
|
|
|
|
|
|
|
|
if (!newSession) return {
|
|
|
|
status: "error",
|
|
|
|
error: {
|
2024-08-24 16:16:12 +06:00
|
|
|
code: "error.api.unreachable"
|
2024-08-16 23:36:56 +06:00
|
|
|
}
|
|
|
|
} as CobaltErrorResponse
|
|
|
|
|
|
|
|
if (!("status" in newSession)) {
|
2024-08-19 22:25:21 +06:00
|
|
|
newSession.exp = currentTime() + newSession.exp;
|
2024-10-20 11:46:09 +00:00
|
|
|
cache = newSession;
|
2024-08-16 23:36:56 +06:00
|
|
|
}
|
|
|
|
return newSession;
|
|
|
|
}
|