Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Video-Downloader/web/src/lib/api/session.ts
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
64 lines (51 sloc)
1.61 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import turnstile from "$lib/api/turnstile"; | |
import { currentApiURL } from "$lib/api/api-url"; | |
import type { CobaltSession, CobaltErrorResponse, CobaltSessionResponse } from "$lib/types/api"; | |
let cache: CobaltSession | undefined; | |
export const requestSession = async () => { | |
const apiEndpoint = `${currentApiURL()}/session`; | |
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 | |
} | |
}); | |
turnstile.reset(); | |
return response; | |
} | |
export const getSession = async () => { | |
const currentTime = () => Math.floor(new Date().getTime() / 1000); | |
if (cache?.token && cache?.exp - 2 > currentTime()) { | |
return cache; | |
} | |
const newSession = await requestSession(); | |
if (!newSession) return { | |
status: "error", | |
error: { | |
code: "error.api.unreachable" | |
} | |
} as CobaltErrorResponse | |
if (!("status" in newSession)) { | |
newSession.exp = currentTime() + newSession.exp; | |
cache = newSession; | |
} | |
return newSession; | |
} |