import io from "socket.io-client" class APIConnector { constructor(url) { this.url = url ?? "" this.socket = io(url) this.assetIndex = 0 this.movement = 0 this.assets = null this.currentAsset = null this.seekCallbacks = [] this.socket.on("seek", e => { this.assetIndex = e.asset_index this.movement = e.movement this.assets = e.assets this.currentAsset = e.current_asset for (const cb of this.seekCallbacks) cb() }) this.downloadAnchor = document.createElement("a") this.downloadAnchor.classList = "hidden" document.body.appendChild(this.downloadAnchor) } fetch(endpoint, c) { return fetch(this.url + "/api" + endpoint, c ?? {}) .then(response => { if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`) return response.json() }) .then(data => { return data }) .catch(error => { console.error("Fetch error:", error) }) } async assetDownload(key) { const filename = await this.assetFileName(key) console.log(filename) fetch(this.assetFullsizeSrc(key)) .then(response => { if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`) return response.blob() }) .then(blob => { const blobUrl = URL.createObjectURL(blob) this.downloadAnchor.href = blobUrl this.downloadAnchor.download = filename this.downloadAnchor.click() URL.revokeObjectURL(blobUrl) }) .catch(error => { console.error("Fetch error:", error) }) } post(endpoint, body) { return this.fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }) } seek(increment) { this.socket.emit("seek", increment) } fetchAlbums() { return this.fetch("/albums") } fetchConfig() { return this.fetch("/config") } updateAlbums(albums) { return this.post("/albums/update", albums) } updateConfig(config) { return this.post("/config/update", config) } albumSrc(key) { return `${this.url}/api/redirect/albums/${key}` } assetPreviewSrc(key) { return `${this.url}/api/asset/${key}` } assetThumbnailSrc(key) { return `${this.url}/api/asset/${key}/thumbnail` } assetFullsizeSrc(key) { return `${this.url}/api/asset/${key}/fullsize` } assetFileName(key) { return this.fetch(`/asset/${key}/filename`).then(d => d.filename) } } const apiConnector = new APIConnector("http://localhost:5000") export default apiConnector