File size: 1,359 Bytes
a6060b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import type { Message } from 'ai';
import { toast } from 'react-toastify';

export interface ChatExportData {
  messages: Message[];
  description?: string;
  exportDate: string;
}

export const exportChat = (messages: Message[], description?: string) => {
  const chatData: ChatExportData = {
    messages,
    description,
    exportDate: new Date().toISOString(),
  };

  const blob = new Blob([JSON.stringify(chatData, null, 2)], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `chat-${new Date().toISOString()}.json`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

export const importChat = async (file: File): Promise<ChatExportData> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const content = e.target?.result as string;
        const data = JSON.parse(content);
        if (!Array.isArray(data.messages)) {
          throw new Error('Invalid chat file format');
        }
        resolve(data);
      } catch (error) {
        reject(new Error('Failed to parse chat file'));
      }
    };
    reader.onerror = () => reject(new Error('Failed to read chat file'));
    reader.readAsText(file);
  });
};