File size: 5,092 Bytes
7dfae77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0f35dd
7dfae77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import type {
  OriginalTrackAsset,
  OutputFormat,
  SourceKind,
  StemAsset,
  StemResult,
} from "./types";

export interface SourceImportResponse {
  job_id: string;
  filename: string;
  source_url: string;
  resolved_url?: string;
  title?: string;
  platform: Exclude<SourceKind, "file">;
}

export async function uploadFile(
  file: File,
  onProgress?: (progress: number) => void
): Promise<{ job_id: string; filename: string }> {
  const formData = new FormData();
  formData.append("file", file);

  const xhr = new XMLHttpRequest();

  return new Promise((resolve, reject) => {
    xhr.upload.addEventListener("progress", (e) => {
      if (e.lengthComputable && onProgress) {
        onProgress(e.loaded / e.total);
      }
    });

    xhr.addEventListener("load", () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        resolve(JSON.parse(xhr.responseText));
      } else {
        try {
          const err = JSON.parse(xhr.responseText);
          reject(new Error(err.detail || `Upload failed (${xhr.status})`));
        } catch {
          reject(new Error(`Upload failed (${xhr.status})`));
        }
      }
    });

    xhr.addEventListener("error", () => reject(new Error("Upload failed")));
    xhr.open("POST", "/api/upload");
    xhr.send(formData);
  });
}

export async function importUrl(
  url: string
): Promise<SourceImportResponse> {
  const res = await fetch("/api/import-url", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ url }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ detail: "Request failed" }));
    throw new Error(err.detail || `Import failed (${res.status})`);
  }
  return res.json();
}

export async function startSeparation(
  jobId: string,
  stems: string[],
  outputFormat: OutputFormat
): Promise<void> {
  const res = await fetch("/api/separate", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ job_id: jobId, stems, output_format: outputFormat }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ detail: "Request failed" }));
    throw new Error(err.detail || `Separation failed (${res.status})`);
  }
}

export interface ProgressEvent {
  state: string;
  progress: number;
  message: string;
  stems?: Record<string, string>;
  error?: string;
}

export function subscribeProgress(
  jobId: string,
  onEvent: (event: ProgressEvent) => void,
  onDone: (stems: StemResult[]) => void,
  onError: (error: string) => void
): () => void {
  const es = new EventSource(`/api/progress/${jobId}`);
  let closedByApp = false;
  let terminalEventSeen = false;
  let errorTimer: number | null = null;

  const clearErrorTimer = () => {
    if (errorTimer !== null) {
      window.clearTimeout(errorTimer);
      errorTimer = null;
    }
  };

  es.onopen = () => {
    clearErrorTimer();
  };

  es.onmessage = (e) => {
    try {
      const data: ProgressEvent = JSON.parse(e.data);
      clearErrorTimer();
      onEvent(data);

      if (data.state === "done" && data.stems) {
        terminalEventSeen = true;
        const stemList: StemResult[] = Object.entries(data.stems).map(
          ([name, filename]) => ({ name, filename })
        );
        onDone(stemList);
        closedByApp = true;
        es.close();
      } else if (data.state === "error") {
        terminalEventSeen = true;
        onError(data.error || "Separation failed");
        closedByApp = true;
        es.close();
      }
    } catch {
      // ignore parse errors
    }
  };

  es.onerror = () => {
    if (closedByApp || terminalEventSeen) {
      return;
    }

    if (es.readyState === EventSource.CLOSED) {
      onError("Connection to server lost");
      closedByApp = true;
      es.close();
      return;
    }

    if (errorTimer === null) {
      errorTimer = window.setTimeout(() => {
        errorTimer = null;
        if (!closedByApp && !terminalEventSeen && es.readyState !== EventSource.OPEN) {
          onError("Connection to server lost");
          closedByApp = true;
          es.close();
        }
      }, 5000);
    }
  };

  return () => {
    closedByApp = true;
    clearErrorTimer();
    es.close();
  };
}

export interface ExampleOutputResponse {
  song?: string;
  original: OriginalTrackAsset;
  stems: StemAsset[];
  downloadAllUrl: string;
}

export async function fetchExampleOutput(): Promise<ExampleOutputResponse> {
  const res = await fetch("/api/examples/default");
  if (!res.ok) {
    const err = await res.json().catch(() => ({ detail: "Request failed" }));
    throw new Error(err.detail || `Example load failed (${res.status})`);
  }
  return res.json();
}

export function getAudioUrl(jobId: string, filename: string): string {
  return `/api/audio/${jobId}/${encodeURIComponent(filename)}`;
}

export function getDownloadUrl(jobId: string, filename: string): string {
  return `/api/download/${jobId}/${encodeURIComponent(filename)}`;
}

export function getDownloadAllUrl(jobId: string): string {
  return `/api/download/${jobId}/all`;
}