lobe-chat

Форк
0
/
config.ts 
109 строк · 2.7 Кб
1
import { notification } from '@/components/AntdStaticMethods';
2
import { BRANDING_NAME } from '@/const/branding';
3
import { CURRENT_CONFIG_VERSION, Migration } from '@/migrations';
4
import {
5
  ConfigFile,
6
  ConfigFileAgents,
7
  ConfigFileAll,
8
  ConfigFileSessions,
9
  ConfigFileSettings,
10
  ConfigFileSingleSession,
11
  ConfigModelMap,
12
  ExportType,
13
} from '@/types/exportConfig';
14

15
export const exportConfigFile = (config: object, fileName?: string) => {
16
  const file = `${BRANDING_NAME}-${fileName || '-config'}-v${CURRENT_CONFIG_VERSION}.json`;
17

18
  // 创建一个 Blob 对象
19
  const blob = new Blob([JSON.stringify(config)], { type: 'application/json' });
20

21
  // 创建一个 URL 对象,用于下载
22
  const url = URL.createObjectURL(blob);
23

24
  // 创建一个 <a> 元素,设置下载链接和文件名
25
  const a = document.createElement('a');
26
  a.href = url;
27
  a.download = file;
28

29
  // 触发 <a> 元素的点击事件,开始下载
30
  document.body.append(a);
31
  a.click();
32

33
  // 下载完成后,清除 URL 对象
34
  URL.revokeObjectURL(url);
35
  a.remove();
36
};
37

38
export const importConfigFile = async (
39
  file: File,
40
  onConfigImport: (config: ConfigFile) => Promise<void>,
41
) => {
42
  const text = await file.text();
43

44
  try {
45
    const config = JSON.parse(text);
46
    const { state, version } = Migration.migrate(config);
47

48
    await onConfigImport({ ...config, state, version });
49
  } catch (error) {
50
    console.error(error);
51
    notification.error({
52
      description: `出错原因: ${(error as Error).message}`,
53
      message: '导入失败',
54
    });
55
  }
56
};
57

58
type CreateConfigFileState<T extends ExportType> = ConfigModelMap[T]['state'];
59

60
type CreateConfigFile<T extends ExportType> = ConfigModelMap[T]['file'];
61

62
export const createConfigFile = <T extends ExportType>(
63
  type: T,
64
  state: CreateConfigFileState<T>,
65
): CreateConfigFile<T> => {
66
  switch (type) {
67
    case 'agents': {
68
      return {
69
        exportType: 'agents',
70
        state,
71
        version: Migration.targetVersion,
72
      } as ConfigFileAgents;
73
    }
74

75
    case 'sessions': {
76
      return {
77
        exportType: 'sessions',
78
        state,
79
        version: Migration.targetVersion,
80
      } as ConfigFileSessions;
81
    }
82

83
    case 'settings': {
84
      return {
85
        exportType: 'settings',
86
        state,
87
        version: Migration.targetVersion,
88
      } as ConfigFileSettings;
89
    }
90

91
    case 'singleSession': {
92
      return {
93
        exportType: 'sessions',
94
        state,
95
        version: Migration.targetVersion,
96
      } as ConfigFileSingleSession;
97
    }
98

99
    case 'all': {
100
      return {
101
        exportType: 'all',
102
        state,
103
        version: Migration.targetVersion,
104
      } as ConfigFileAll;
105
    }
106
  }
107

108
  throw new Error('缺少正确的导出类型,请检查实现...');
109
};
110

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.