-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileService.ts
233 lines (201 loc) · 7.31 KB
/
fileService.ts
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import { apiRequest, getAuthHeader } from './apiUtils';
import { KnowledgeFile } from '../models/knowledge';
import { logApiRequest, logApiResponse, logApiError } from '../utils/logger';
import { IFile } from '../models/IFile';
import { getFileChunks as getNbaseFileChunks } from '../lib/services/nbaseService';
import { IChunk } from '../models/IChunk';
// Upload a single file to knowledge
export const uploadFile = async (knowledgeId: string, file: File, onProgress?: (percent: number) => void): Promise<KnowledgeFile | null> => {
const formData = new FormData();
formData.append('file', file);
formData.append('fileName', file.name);
const url = `/api/knowledge/${knowledgeId}/files`;
const method = 'POST';
// Log upload request (exclude full file data)
logApiRequest(method, url, {}, { fileName: file.name, fileSize: file.size, fileType: file.type });
const startTime = performance.now();
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = (event) => {
if (event.lengthComputable && onProgress) {
const percentComplete = Math.round((event.loaded / event.total) * 100);
onProgress(percentComplete);
}
};
xhr.onload = () => {
const endTime = performance.now();
const duration = Math.round(endTime - startTime);
if (xhr.status >= 200 && xhr.status < 300) {
try {
const responseData = JSON.parse(xhr.responseText);
// Log successful response
logApiResponse(method, url, xhr.status, responseData, duration);
resolve(responseData);
} catch (e) {
// Log parse error
logApiError(method, url, 'Invalid response format', duration);
reject(new Error('Invalid response format'));
}
} else {
// Log error response
logApiError(method, url, `Upload failed: ${xhr.status}`, duration);
reject(new Error(`Upload failed: ${xhr.status}`));
}
};
xhr.onerror = () => {
const endTime = performance.now();
const duration = Math.round(endTime - startTime);
logApiError(method, url, 'Network error', duration);
reject(new Error('Network error'));
};
xhr.open(method, url, true);
const authHeader = getAuthHeader();
if (authHeader.Authorization) {
xhr.setRequestHeader('Authorization', authHeader.Authorization);
}
xhr.send(formData);
});
};
// Upload multiple files one by one
export async function uploadFiles(knowledgeId: string, files: File[], onOverallProgress?: (percent: number) => void): Promise<(KnowledgeFile | null)[]> {
console.log('Uploading files:', files);
if (!files || files.length === 0) return [];
// Filter out any undefined or invalid files
const validFiles = files;
if (validFiles.length === 0) return [];
const results: (KnowledgeFile | null)[] = [];
for (let i = 0; i < validFiles.length; i++) {
const file = validFiles[i];
try {
// For each file, track its individual progress
const result = await uploadFile(knowledgeId, file, (fileProgress) => {
// Calculate overall progress across all files
const fileContribution = fileProgress / validFiles.length;
const previousFilesContribution = (i / validFiles.length) * 100;
const overallProgress = Math.round(previousFilesContribution + fileContribution);
if (onOverallProgress) {
onOverallProgress(overallProgress);
}
});
results.push(result);
} catch (error: unknown) {
console.error(`Error uploading file ${file ? file.name : 'unknown'}:`, error);
results.push(null);
}
}
return results;
}
// Delete a file
export const deleteFile = async (knowledgeId: string, fileId: string): Promise<boolean> => {
return apiRequest<boolean>(`/api/knowledge/${knowledgeId}/files/${fileId}`, {
method: 'DELETE',
});
};
// Get download URL for a file
export const getFileDownloadUrl = (knowledgeId: string, fileId: string): string => {
return `/api/knowledge/${knowledgeId}/files/${fileId}/download`;
};
// Fetch a specific file by ID
export async function fetchFileById(fileId: string): Promise<any | null> {
return apiRequest(`/api/files/${fileId}`, {
method: 'GET',
});
}
// Fetch all files across all knowledge items
export async function fetchAllFiles(): Promise<any[]> {
return apiRequest(`/api/files`, {
method: 'GET',
});
}
// Parse a file to create a parsing task
export const parseFile = async (fileId: string): Promise<{ success: boolean; message?: string; taskId?: string }> => {
return apiRequest<{ success: boolean; message?: string; taskId?: string }>(`/api/parsing`, {
method: 'POST',
body: JSON.stringify({ fileId }),
});
};
type IParseTaskStatus = {
completedAt: string;
createdAt: string;
fileId: string;
fileName: string;
message: string;
status: 'completed' | 'failed' | 'pending' | 'processing';
taskId: string;
updatedAt: string;
};
// Get parsing task status
export const getParsingTaskStatus = async (taskId: string): Promise<IParseTaskStatus> => {
return apiRequest<IParseTaskStatus>(`/api/parsing/${taskId}/status`, {
method: 'GET',
});
};
// Get all parsing tasks
export const getAllParsingTasks = async (): Promise<any[]> => {
return apiRequest<any[]>(`/api/parsing`, {
method: 'GET',
});
};
// Update parsing task status (for admin/worker use)
export const updateParsingTaskStatus = async (
taskId: string,
status: string,
fileContent?: string,
message?: string // Changed from errorMessage to message
): Promise<any> => {
return apiRequest<any>(`/api/parsing/${taskId}`, {
method: 'PATCH',
body: JSON.stringify({ status, fileContent, message }),
});
};
// Delete parsing task
export const deleteParsingTask = async (taskId: string): Promise<boolean> => {
return apiRequest<boolean>(`/api/parsing/${taskId}`, {
method: 'DELETE',
});
};
// Get file content
export const getFileContent = async (fileId: string): Promise<{ content: string; originalName: string }> => {
return apiRequest<{ content: string; originalName: string }>(`/api/files/${fileId}/content`, {
method: 'GET',
});
};
// Update file configuration
export const updateFileConfig = async (fileId: string, config: string | null): Promise<boolean> => {
return apiRequest<boolean>(`/api/files/${fileId}/config`, {
method: 'PATCH',
body: JSON.stringify({ config }),
});
};
export async function fetchFilesByKnowledgeId(knowledgeId: string) {
try {
return apiRequest<IFile[]>(`/api/knowledge/${knowledgeId}/files`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
} catch (error: unknown) {
console.error('Error fetching files:', error);
throw error;
}
}
// Get file chunks using nbase service
export const getFileChunks = async (fileId: string): Promise<any[]> => {
try {
// Determine which vector database to use
const vectorDBType = process.env.VECTOR_DB_TYPE || 'local';
switch (vectorDBType) {
case 'nbase':
return await getNbaseFileChunks(fileId);
default: // 'local'
const response = await apiRequest<{ chunks: IChunk[] }>(`/api/files/${fileId}/chunks`, {
method: 'GET',
});
return response.chunks || [];
}
} catch (error: unknown) {
console.error('Error getting file chunks:', error);
return [];
}
};