File size: 9,119 Bytes
2fe2727
 
ffa0093
 
 
2fe2727
 
ffa0093
 
2fe2727
 
ffa0093
2fe2727
 
 
ffa0093
2fe2727
 
 
 
 
 
ffa0093
2fe2727
 
 
 
 
 
 
 
 
 
 
 
ffa0093
2fe2727
ffa0093
2fe2727
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffa0093
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61fcdc2
 
ffa0093
 
 
 
 
61fcdc2
2fe2727
 
61fcdc2
 
ffa0093
 
 
 
2fe2727
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61fcdc2
2fe2727
 
 
 
 
 
 
 
 
 
ffa0093
 
 
 
 
 
 
 
61fcdc2
2fe2727
61fcdc2
 
 
 
 
 
 
2fe2727
 
ffa0093
 
 
2fe2727
61fcdc2
ffa0093
 
 
 
 
 
2fe2727
 
 
 
 
 
 
 
 
 
 
 
 
ffa0093
2fe2727
 
 
ffa0093
61fcdc2
2fe2727
ffa0093
 
 
2fe2727
 
 
 
 
ffa0093
 
 
2fe2727
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffa0093
 
61fcdc2
2fe2727
ffa0093
 
 
 
 
 
4e3ead6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffa0093
 
 
 
 
 
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
// Enhanced HF Service with Versioning and Standardized Responses
const CACHE_TTL = 60 * 1000; // 60 seconds (aligned with backend HF cache)

class HFService {
  constructor() {
    this.apiBase = null;
    this.apiBasePromise = null;
    this.cache = new Map();
    this.retryLimit = 3;
    this.retryDelay = 1000;
  }

  async getApiBase() {
    if (this.apiBase) return this.apiBase;
    if (this.apiBasePromise) return this.apiBasePromise;

    this.apiBasePromise = (async () => {
      const configuredBase = window.__DOCVAULT_API_BASE__;
      const remoteFallbackBase = window.__DOCVAULT_REMOTE_API_BASE__;
      const { protocol, hostname, origin, port } = window.location;
      const host = hostname || '127.0.0.1';
      const candidates = [];

      if (configuredBase && typeof configuredBase === 'string') {
        candidates.push(configuredBase.replace(/\/$/, ''));
      }

      candidates.push(`${origin}/api`);

      if (port !== '5000') candidates.push(`${protocol}//${host}:5000/api`);
      if (port !== '7860') candidates.push(`${protocol}//${host}:7860/api`);

      if (remoteFallbackBase && typeof remoteFallbackBase === 'string') {
        candidates.push(remoteFallbackBase.replace(/\/$/, ''));
      }

      const uniqueCandidates = [...new Set(candidates)];

      for (const candidate of uniqueCandidates) {
        try {
          const response = await fetch(`${candidate}/health`, {
            method: 'GET',
            headers: { 'X-User-ID': 'default_user' }
          });

          if (response.ok) {
            this.apiBase = candidate;
            return candidate;
          }
        } catch (err) {
          // Try the next candidate quietly.
        }
      }

      throw new Error('DocVault backend is unreachable. Expected /api/health on the current host, ports 5000/7860, or the configured remote Space API.');
    })();

    return this.apiBasePromise;
  }

  async fetchWithRetry(url, options = {}, retries = this.retryLimit) {
    try {
      const response = await fetch(url, options);
      if (!response.ok) {
        if (response.status >= 500 && retries > 0) throw new Error('Server error');
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.error || `Request failed: ${response.status}`);
      }
      return response;
    } catch (err) {
      if (retries > 0) {
        const delay = this.retryDelay * Math.pow(2, this.retryLimit - retries);
        await new Promise(resolve => setTimeout(resolve, delay));
        return this.fetchWithRetry(url, options, retries - 1);
      }
      throw err;
    }
  }

  async listFiles(path = '') {
    const cacheKey = `list-${path}`;
    const cached = this.cache.get(cacheKey);
    if (cached && (Date.now() - cached.timestamp < CACHE_TTL)) {
      return cached.data;
    }

    const queryPath = path ? `?folder_path=${encodeURIComponent(path)}` : '';
    const apiBase = await this.getApiBase();
    const url = `${apiBase}/list${queryPath}`;
    
    const res = await this.fetchWithRetry(url, { headers: { 'X-User-ID': 'default_user' } });
    const data = await res.json();

    const result = { files: [], folders: [] };

    // Validate response structure
    if (!data || typeof data !== 'object' || data.success !== true) {
      console.warn('Invalid API response structure:', data);
      this.cache.set(cacheKey, { data: result, timestamp: Date.now() });
      return result;
    }

    if (Array.isArray(data.files)) {
      for (const item of data.files) {
        result.files.push({
          path: item.path || '',
          name: item.name || 'unnamed',
          size: item.size || 0,
          type: 'file',
          lastModified: item.modified_at,
          storage: item.storage
        });
      }
    }
    
    if (Array.isArray(data.folders)) {
      for (const item of data.folders) {
        result.folders.push({
          path: item.path || '',
          name: item.name || 'unnamed',
          type: 'folder',
          storage: item.storage
        });
      }
    }

    this.cache.set(cacheKey, { data: result, timestamp: Date.now() });
    return result;
  }

  async uploadFile(file, destPath) {
    const formData = new FormData();
    // standardized folder path extraction
    const folderPath = destPath.includes('/') ? destPath.substring(0, destPath.lastIndexOf('/')) : '';
    const filename = file instanceof File ? file.name : destPath.split('/').pop();
    const fileBlob = file instanceof File ? file : new Blob([file.content || '']);
    
    formData.append('folder_path', folderPath);
    formData.append('file', fileBlob, filename);

    const apiBase = await this.getApiBase();
    const url = `${apiBase}/upload`;

    const res = await this.fetchWithRetry(url, {
      method: 'POST',
      headers: { 'X-User-ID': 'default_user' },
      body: formData
    });

    this.clearCache();
    return await res.json();
  }

  async createFolder(folderPath) {
    const apiBase = await this.getApiBase();
    const url = `${apiBase}/create-folder`;
    const res = await this.fetchWithRetry(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'X-User-ID': 'default_user' },
      body: JSON.stringify({ folder_path: folderPath }),
    });

    this.clearCache();
    return await res.json();
  }

  async deleteFile(path) {
    const apiBase = await this.getApiBase();
    const url = `${apiBase}/delete`;
    const res = await this.fetchWithRetry(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'X-User-ID': 'default_user' },
      body: JSON.stringify({ path, type: 'file' }),
    });

    this.clearCache();
    const data = await res.json();
    if (!data.success) {
      throw new Error(data.error || 'Failed to delete file');
    }
    return data;
  }

  async deleteFolder(folderPath) {
    const apiBase = await this.getApiBase();
    const url = `${apiBase}/delete`;
    const res = await this.fetchWithRetry(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'X-User-ID': 'default_user' },
      body: JSON.stringify({ path: folderPath, type: 'folder' }),
    });

    this.clearCache();
    const data = await res.json();
    if (!data.success) {
      throw new Error(data.error || 'Failed to delete folder');
    }
    return data;
  }

  async getHistory(path) {
    const apiBase = await this.getApiBase();
    const url = `${apiBase}/history?path=${encodeURIComponent(path)}`;
    const res = await this.fetchWithRetry(url, { headers: { 'X-User-ID': 'default_user' } });
    const data = await res.json();
    
    if (!data || !data.success) {
      console.warn('Failed to get history:', data?.error || 'Unknown error');
      return [];
    }
    
    return Array.isArray(data.history) ? data.history : [];
  }

  async restoreVersion(path, revision, asCopy = false) {
    const apiBase = await this.getApiBase();
    const url = `${apiBase}/restore`;
    const res = await this.fetchWithRetry(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'X-User-ID': 'default_user' },
      body: JSON.stringify({ path, revision, as_copy: asCopy }),
    });

    this.clearCache();
    return await res.json();
  }

  async renameItem(itemPath, newName) {
    const apiBase = await this.getApiBase();
    const url = `${apiBase}/rename`;
    const res = await this.fetchWithRetry(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'X-User-ID': 'default_user' },
      body: JSON.stringify({ item_path: itemPath, new_name: newName }),
    });

    this.clearCache();
    return await res.json();
  }

  async listLinks() {
    const apiBase = await this.getApiBase();
    const res = await this.fetchWithRetry(`${apiBase}/links/list`, {
      headers: { 'X-User-ID': 'default_user' }
    });
    const data = await res.json();
    return Array.isArray(data.links) ? data.links : [];
  }

  async addLink(payload) {
    const apiBase = await this.getApiBase();
    const res = await this.fetchWithRetry(`${apiBase}/links/add`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-User-ID': 'default_user'
      },
      body: JSON.stringify(payload)
    });
    return await res.json();
  }

  async updateLink(payload) {
    const apiBase = await this.getApiBase();
    const res = await this.fetchWithRetry(`${apiBase}/links/update`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-User-ID': 'default_user'
      },
      body: JSON.stringify(payload)
    });
    return await res.json();
  }

  async deleteLink(linkId) {
    const apiBase = await this.getApiBase();
    const res = await this.fetchWithRetry(`${apiBase}/links/delete`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-User-ID': 'default_user'
      },
      body: JSON.stringify({ link_id: linkId })
    });
    return await res.json();
  }

  clearCache() {
    this.cache.clear();
  }
}

export const hfService = new HFService();