File size: 12,203 Bytes
c5dfbfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
296
297
298
299
300
// ═══════════════════════════════════════════════════════════════════════════
// HF STORAGE SERVICE - HuggingFace CDN & Storage Integration
// ═══════════════════════════════════════════════════════════════════════════

import { writeFile, readFile, mkdir, readdir, unlink } from 'fs/promises';
import { existsSync } from 'fs';
import path from 'path';
import { v4 as uuidv4 } from 'uuid';
import { StorageFile, SessionStorage, ChatMessage, Poll, Doubt } from './types';

// Data directory for persistent storage on HF Spaces
const DATA_DIR = process.env.DATA_DIR || '/data';
const SESSIONS_DIR = path.join(DATA_DIR, 'sessions');
const UPLOADS_DIR = path.join(DATA_DIR, 'uploads');

// Ensure directories exist
async function ensureDirectories() {
  if (!existsSync(DATA_DIR)) {
    await mkdir(DATA_DIR, { recursive: true });
  }
  if (!existsSync(SESSIONS_DIR)) {
    await mkdir(SESSIONS_DIR, { recursive: true });
  }
  if (!existsSync(UPLOADS_DIR)) {
    await mkdir(UPLOADS_DIR, { recursive: true });
  }
}

// ═══════════════════════════════════════════════════════════════════════════
// FILE STORAGE (Local files served via HF CDN)
// ═══════════════════════════════════════════════════════════════════════════

export class HFStorageService {
  private baseUrl: string;

  constructor() {
    // On HF Spaces, files are served from the Space's URL
    this.baseUrl = process.env.HF_SPACE_URL || '';
    ensureDirectories();
  }

  // ═══════════════════════════════════════════════════════════════════════════
  // SESSION STORAGE
  // ═══════════════════════════════════════════════════════════════════════════

  async saveSessionData(sessionId: string, data: any): Promise<void> {
    const sessionDir = path.join(SESSIONS_DIR, sessionId);
    if (!existsSync(sessionDir)) {
      await mkdir(sessionDir, { recursive: true });
    }
    
    const filePath = path.join(sessionDir, 'session.json');
    await writeFile(filePath, JSON.stringify(data, null, 2), 'utf-8');
  }

  async loadSessionData(sessionId: string): Promise<any | null> {
    const filePath = path.join(SESSIONS_DIR, sessionId, 'session.json');
    
    if (!existsSync(filePath)) {
      return null;
    }
    
    const data = await readFile(filePath, 'utf-8');
    return JSON.parse(data);
  }

  async deleteSession(sessionId: string): Promise<void> {
    const sessionDir = path.join(SESSIONS_DIR, sessionId);
    if (existsSync(sessionDir)) {
      const files = await readdir(sessionDir);
      for (const file of files) {
        await unlink(path.join(sessionDir, file));
      }
      await unlink(sessionDir);
    }
  }

  // ═══════════════════════════════════════════════════════════════════════════
  // FILE UPLOAD (Base64 images, slides, etc.)
  // ═══════════════════════════════════════════════════════════════════════════

  async uploadFile(
    sessionId: string,
    fileName: string,
    base64Data: string,
    contentType: string = 'image/png'
  ): Promise<StorageFile> {
    const sessionDir = path.join(SESSIONS_DIR, sessionId, 'files');
    
    if (!existsSync(sessionDir)) {
      await mkdir(sessionDir, { recursive: true });
    }
    
    // Extract base64 data
    const base64Content = base64Data.replace(/^data:[^;]+;base64,/, '');
    const buffer = Buffer.from(base64Content, 'base64');
    
    const filePath = path.join(sessionDir, fileName);
    await writeFile(filePath, buffer);
    
    return {
      path: filePath,
      url: `/api/storage/${sessionId}/${fileName}`,
      size: buffer.length,
      contentType,
      uploadedAt: new Date().toISOString()
    };
  }

  async getFile(sessionId: string, fileName: string): Promise<Buffer | null> {
    const filePath = path.join(SESSIONS_DIR, sessionId, 'files', fileName);
    
    if (!existsSync(filePath)) {
      return null;
    }
    
    return readFile(filePath);
  }

  // ═══════════════════════════════════════════════════════════════════════════
  // CHAT HISTORY
  // ═══════════════════════════════════════════════════════════════════════════

  async saveChatMessage(sessionId: string, message: ChatMessage): Promise<void> {
    const sessionDir = path.join(SESSIONS_DIR, sessionId);
    if (!existsSync(sessionDir)) {
      await mkdir(sessionDir, { recursive: true });
    }
    
    const chatFile = path.join(sessionDir, 'chat.json');
    let messages: ChatMessage[] = [];
    
    if (existsSync(chatFile)) {
      const data = await readFile(chatFile, 'utf-8');
      messages = JSON.parse(data);
    }
    
    messages.push(message);
    await writeFile(chatFile, JSON.stringify(messages, null, 2), 'utf-8');
  }

  async getChatHistory(sessionId: string): Promise<ChatMessage[]> {
    const chatFile = path.join(SESSIONS_DIR, sessionId, 'chat.json');
    
    if (!existsSync(chatFile)) {
      return [];
    }
    
    const data = await readFile(chatFile, 'utf-8');
    return JSON.parse(data);
  }

  // ═══════════════════════════════════════════════════════════════════════════
  // POLL HISTORY
  // ═══════════════════════════════════════════════════════════════════════════

  async savePoll(sessionId: string, poll: Poll): Promise<void> {
    const sessionDir = path.join(SESSIONS_DIR, sessionId);
    if (!existsSync(sessionDir)) {
      await mkdir(sessionDir, { recursive: true });
    }
    
    const pollsFile = path.join(sessionDir, 'polls.json');
    let polls: Poll[] = [];
    
    if (existsSync(pollsFile)) {
      const data = await readFile(pollsFile, 'utf-8');
      polls = JSON.parse(data);
    }
    
    const existingIndex = polls.findIndex(p => p.id === poll.id);
    if (existingIndex >= 0) {
      polls[existingIndex] = poll;
    } else {
      polls.push(poll);
    }
    
    await writeFile(pollsFile, JSON.stringify(polls, null, 2), 'utf-8');
  }

  async getPolls(sessionId: string): Promise<Poll[]> {
    const pollsFile = path.join(SESSIONS_DIR, sessionId, 'polls.json');
    
    if (!existsSync(pollsFile)) {
      return [];
    }
    
    const data = await readFile(pollsFile, 'utf-8');
    return JSON.parse(data);
  }

  // ═══════════════════════════════════════════════════════════════════════════
  // DOUBTS
  // ═══════════════════════════════════════════════════════════════════════════

  async saveDoubt(sessionId: string, doubt: Doubt): Promise<void> {
    const sessionDir = path.join(SESSIONS_DIR, sessionId);
    if (!existsSync(sessionDir)) {
      await mkdir(sessionDir, { recursive: true });
    }
    
    const doubtsFile = path.join(sessionDir, 'doubts.json');
    let doubts: Doubt[] = [];
    
    if (existsSync(doubtsFile)) {
      const data = await readFile(doubtsFile, 'utf-8');
      doubts = JSON.parse(data);
    }
    
    const existingIndex = doubts.findIndex(d => d.id === doubt.id);
    if (existingIndex >= 0) {
      doubts[existingIndex] = doubt;
    } else {
      doubts.push(doubt);
    }
    
    await writeFile(doubtsFile, JSON.stringify(doubts, null, 2), 'utf-8');
  }

  async getDoubts(sessionId: string): Promise<Doubt[]> {
    const doubtsFile = path.join(SESSIONS_DIR, sessionId, 'doubts.json');
    
    if (!existsSync(doubtsFile)) {
      return [];
    }
    
    const data = await readFile(doubtsFile, 'utf-8');
    return JSON.parse(data);
  }

  // ═══════════════════════════════════════════════════════════════════════════
  // WHITEBOARD SNAPSHOTS
  // ═══════════════════════════════════════════════════════════════════════════

  async saveWhiteboardSnapshot(
    sessionId: string,
    slideNumber: number,
    base64Data: string
  ): Promise<StorageFile> {
    const fileName = `whiteboard_slide_${slideNumber}_${Date.now()}.png`;
    return this.uploadFile(sessionId, fileName, base64Data, 'image/png');
  }

  // ═══════════════════════════════════════════════════════════════════════════
  // SESSION BACKUP (Full session export)
  // ═══════════════════════════════════════════════════════════════════════════

  async exportSession(sessionId: string): Promise<SessionStorage> {
    const sessionData = await this.loadSessionData(sessionId);
    const chatHistory = await this.getChatHistory(sessionId);
    const polls = await this.getPolls(sessionId);
    const doubts = await this.getDoubts(sessionId);
    
    const filesDir = path.join(SESSIONS_DIR, sessionId, 'files');
    const slides: StorageFile[] = [];
    const whiteboardSnapshots: StorageFile[] = [];
    
    if (existsSync(filesDir)) {
      const files = await readdir(filesDir);
      for (const file of files) {
        if (file.startsWith('slide_')) {
          slides.push({
            path: path.join(filesDir, file),
            url: `/api/storage/${sessionId}/${file}`,
            size: 0,
            contentType: 'image/png',
            uploadedAt: new Date().toISOString()
          });
        } else if (file.startsWith('whiteboard_')) {
          whiteboardSnapshots.push({
            path: path.join(filesDir, file),
            url: `/api/storage/${sessionId}/${file}`,
            size: 0,
            contentType: 'image/png',
            uploadedAt: new Date().toISOString()
          });
        }
      }
    }
    
    return {
      sessionId,
      slides,
      whiteboardSnapshots,
      doubts: doubts.map(d => ({
        path: '',
        url: '',
        size: 0,
        contentType: 'application/json',
        uploadedAt: d.createdAt
      })),
      chatHistory,
      pollHistory: polls
    };
  }
}

// Singleton instance
export const storageService = new HFStorageService();