Chat / frontend /src /lib /api /apiClient.ts
kishankrish19's picture
Deploy Stillwave fullstack clean
b0798af
Raw History Blame Contribute Delete
9.39 kB
export const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "/api/v1";
export interface Track {
id: string;
title: string;
artist_name: string;
album_title: string;
genre: string;
duration_ms: number;
status: "ready" | "missing";
owner_id: string | null;
source: string;
size: number;
folder?: string;
liked?: boolean;
has_artwork?: boolean;
backup_status?: string;
reason?: string;
created_at?: string;
has_lyrics?: boolean;
metadata_error?: string;
metadata_status?: "pending" | "ready" | "error";
metadata_updated_at?: string;
details?: Record<string, unknown>;
lyrics?: {
language?: string;
text: string;
lines: { text: string; timestamp?: number }[];
}[];
}
export interface TrackActivity {
id: string;
backup_status: string;
has_artwork: boolean;
metadata_status: "pending" | "ready" | "error";
metadata_updated_at?: string;
}
export interface User {
id: string;
display_name: string;
email: string;
username: string;
account_type: "admin" | "listener";
}
export interface UploadRecord {
id: string;
filename: string;
size: number;
offset: number;
status: string;
track_id?: string;
duplicate?: boolean;
backup_status?: string;
error?: string;
created_at: string;
folder: string;
}
export const token = () =>
typeof window === "undefined" ? null : localStorage.getItem("access_token");
export const currentUser = (): User | null => {
try {
return JSON.parse(localStorage.getItem("user") || "null");
} catch {
return null;
}
};
let refreshPromise: Promise<void> | null = null;
function saveSession(data: {
access_token: string;
refresh_token: string;
user?: User;
}) {
if (!data?.access_token || !data?.refresh_token)
throw new Error(
"The server returned an incomplete sign-in response. Please try again.",
);
localStorage.setItem("access_token", data.access_token);
localStorage.setItem("refresh_token", data.refresh_token);
if (data.user) {
localStorage.setItem("user", JSON.stringify(data.user));
window.dispatchEvent(new Event("session-changed"));
}
}
export async function ensureToken() {
return token();
}
export async function apiRequest<T = unknown>(
endpoint: string,
options: RequestInit = {},
retry = false,
responseType: "json" | "blob" = "json",
): Promise<T> {
const headers = new Headers(options.headers);
if (!(options.body instanceof FormData) && !headers.has("Content-Type"))
headers.set("Content-Type", "application/json");
if (token()) headers.set("Authorization", "Bearer " + token());
let res: Response;
try {
res = await fetch(API_BASE_URL + endpoint, {
...options,
headers,
signal: options.signal || AbortSignal.timeout(45000),
});
} catch {
throw new Error(
"Cannot reach the music server. Check that the backend is running, then try again.",
);
}
if (
res.status === 401 &&
!retry &&
!["/auth/login", "/auth/signup", "/auth/refresh-token"].includes(endpoint)
) {
const refresh = localStorage.getItem("refresh_token");
if (refresh) {
if (!refreshPromise)
refreshPromise = fetch(API_BASE_URL + "/auth/refresh-token", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refresh_token: refresh }),
signal: AbortSignal.timeout(15000),
})
.then(async (r) => {
if (!r.ok) throw new Error("Please sign in again");
saveSession(await r.json());
})
.finally(() => {
refreshPromise = null;
});
try {
await refreshPromise;
} catch {
localStorage.removeItem("access_token");
localStorage.removeItem("refresh_token");
localStorage.removeItem("user");
window.dispatchEvent(new Event("session-changed"));
throw new Error("Please sign in again");
}
return apiRequest<T>(endpoint, options, true, responseType);
}
}
if (!res.ok) {
const error = await res.json().catch(() => ({ message: "Request failed" }));
throw new Error(
Array.isArray(error.message)
? error.message.join(". ")
: error.message || "Request failed",
);
}
return responseType === "blob" ? (res.blob() as Promise<T>) : res.json();
}
const post = <T = unknown>(path: string, body: unknown = {}) =>
apiRequest<T>(path, { method: "POST", body: JSON.stringify(body) });
export const api = {
login: async (body: unknown) => {
const r = await post<{
access_token: string;
refresh_token: string;
user: User;
}>("/auth/login", body);
saveSession(r);
return r;
},
signup: async (body: unknown) => {
const r = await post<{
access_token: string;
refresh_token: string;
user: User;
}>("/auth/signup", body);
saveSession(r);
return r;
},
logout: async () => {
await post("/auth/logout").catch(() => {});
["access_token", "refresh_token", "user"].forEach((k) =>
localStorage.removeItem(k),
);
window.dispatchEvent(new Event("session-changed"));
},
getMe: () => apiRequest<User>("/auth/me"),
libraryActivity: () => apiRequest<TrackActivity[]>("/library/activity"),
getTracks: async () => {
const all: Track[] = [];
let page: Track[];
do {
page = await apiRequest<Track[]>("/tracks?offset=" + all.length);
all.push(...page);
} while (page.length === 500);
return all;
},
syncLibrary: () =>
post<{ status: string; count: number; preparing: number; error?: string }>(
"/library/sync",
),
getHome: () => apiRequest<HomeData>("/home"),
getTrack: (id: string) => apiRequest<Track>("/tracks/" + id),
search: (q: string) =>
apiRequest<{ tracks: Track[] }>("/search?q=" + encodeURIComponent(q)),
getTrackStreamUrl: (id: string) =>
apiRequest<{ signedUrl: string; expiresAt: string }>(
"/tracks/" + id + "/stream",
),
like: (id: string, liked: boolean) =>
post("/tracks/" + id + "/feedback", { value: liked ? "like" : "clear" }),
feedback: (id: string, value: string) =>
post("/tracks/" + id + "/feedback", { value }),
log: (id: string, body: unknown) => post("/tracks/" + id + "/play", body),
next: (seed: string, adventure: number, exclude: string[] = []) =>
apiRequest<Track[]>(
"/me/recommendations/next?seed=" +
seed +
"&adventure=" +
adventure +
"&exclude=" +
exclude.join(","),
),
liked: () => apiRequest<Track[]>("/me/library/tracks"),
download: (id: string) => post("/tracks/download-demand", { track_id: id }),
downloadStatus: (id: string) =>
apiRequest<{ status: string; error?: string }>(
"/tracks/download-status/" + id,
),
uploads: () => apiRequest<UploadRecord[]>("/uploads"),
upload: (id: string) => apiRequest<UploadRecord>("/uploads/" + id),
createUpload: (body: unknown) => post<UploadRecord>("/uploads", body),
completeUpload: (id: string) =>
post<UploadRecord>("/uploads/" + id + "/complete"),
cancelUpload: (id: string) =>
apiRequest("/uploads/" + id, { method: "DELETE" }),
usage: () =>
apiRequest<{
used: number;
reserved: number;
quota: number;
tracks: number;
max_file_size: number;
backup_enabled: boolean;
}>("/uploads/usage"),
playlists: () => apiRequest<Playlist[]>("/playlists"),
playlist: (id: string) =>
apiRequest<Playlist & { tracks: Track[] }>("/playlists/" + id),
createPlaylist: (title: string, track_ids: string[] = []) =>
post<Playlist>("/playlists", { title, track_ids }),
addToPlaylist: (id: string, track_ids: string[]) =>
post("/playlists/" + id + "/tracks", { track_ids }),
removeFromPlaylist: (id: string, track: string) =>
apiRequest("/playlists/" + id + "/tracks/" + track, { method: "DELETE" }),
deletePlaylist: (id: string) =>
apiRequest("/playlists/" + id, { method: "DELETE" }),
settings: () => apiRequest<Preferences>("/me/settings"),
updateSettings: (body: Partial<Preferences>) =>
apiRequest<Preferences>("/me/settings", {
method: "PATCH",
body: JSON.stringify(body),
}),
editTrack: (id: string, body: unknown) =>
apiRequest("/tracks/" + id, {
method: "PATCH",
body: JSON.stringify(body),
}),
removeTrack: (id: string) =>
apiRequest("/tracks/" + id, { method: "DELETE" }),
};
export interface Playlist {
id: string;
title: string;
track_ids: string[];
description?: string;
}
export interface Preferences {
autoplay: boolean;
adventure: number;
theme: "light" | "dark";
}
export interface HomeData {
recently_added: Track[];
recently_played: Track[];
on_repeat: Track[];
rediscover: Track[];
for_you: Track[];
resume: { track_id: string; position_ms: number } | null;
total_tracks: number;
total_duration_ms: number;
}
export const absoluteApiUrl = (path: string) =>
path.startsWith("/") ? API_BASE_URL.replace(/\/api\/v1$/, "") + path : path;
export const bytes = (n: number) =>
n >= 1e9
? (n / 1e9).toFixed(1) + " GB"
: n >= 1e6
? (n / 1e6).toFixed(1) + " MB"
: Math.round(n / 1000) + " KB";
export const duration = (ms: number) => {
const s = Math.max(0, Math.floor(ms / 1000));
return Math.floor(s / 60) + ":" + String(s % 60).padStart(2, "0");
};