-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuseGenericSettings.ts
More file actions
515 lines (434 loc) · 16.8 KB
/
useGenericSettings.ts
File metadata and controls
515 lines (434 loc) · 16.8 KB
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
import { useState, useEffect, useCallback } from 'react';
import config from '@app/config/config';
import { readToken } from '@app/services/localStorage.service';
import { useHandleLogout } from './authUtils';
import { SettingsGroupName, SettingsGroupType } from '@app/types/settings.types';
// Helper function to extract the correct nested data for each settings group
const extractSettingsForGroup = (settings: any, groupName: string) => {
console.log(`Extracting settings for group: ${groupName}`, settings);
let rawData: any = {};
switch (groupName) {
case 'image_moderation':
rawData = settings?.content_filtering?.image_moderation || {};
break;
case 'content_filter':
rawData = settings?.content_filtering?.text_filter || {};
break;
case 'ollama':
rawData = settings?.external_services?.ollama || {};
break;
case 'wallet':
rawData = settings?.external_services?.wallet || {};
break;
case 'relay_info':
rawData = settings?.relay || {};
break;
case 'general':
rawData = settings?.server || {};
break;
default:
console.warn(`Unknown settings group: ${groupName}`);
return {};
}
// Handle the prefixed field name issue
// The backend returns both prefixed and unprefixed fields, but forms expect prefixed ones
if (groupName === 'image_moderation' && rawData) {
const processedData: any = {};
// Map backend fields to prefixed ones that the form expects
// Based on the actual backend response, backend sends both prefixed and unprefixed versions
const imageModerationMappings: Record<string, string[]> = {
'image_moderation_api': ['image_moderation_api', 'api'],
'image_moderation_check_interval': ['image_moderation_check_interval_seconds', 'check_interval_seconds'],
'image_moderation_concurrency': ['image_moderation_concurrency', 'concurrency'],
'image_moderation_enabled': ['image_moderation_enabled', 'enabled'],
'image_moderation_mode': ['image_moderation_mode', 'mode'],
'image_moderation_temp_dir': ['image_moderation_temp_dir', 'temp_dir'],
'image_moderation_threshold': ['image_moderation_threshold', 'threshold'],
'image_moderation_timeout': ['image_moderation_timeout_seconds', 'timeout_seconds']
};
// Map fields, prioritizing prefixed versions if they exist
Object.entries(imageModerationMappings).forEach(([formField, possibleBackendFields]) => {
for (const backendField of possibleBackendFields) {
if (rawData[backendField] !== undefined) {
processedData[formField] = rawData[backendField];
break; // Use the first found value
}
}
});
console.log(`Processed ${groupName} data:`, processedData);
return processedData;
}
if (groupName === 'content_filter' && rawData) {
const processedData: any = {};
// Handle content filter prefixed fields
const contentFilterMappings: Record<string, string> = {
'content_filter_cache_size': 'cache_size',
'content_filter_cache_ttl': 'cache_ttl_seconds',
'content_filter_enabled': 'enabled',
'full_text_kinds': 'full_text_search_kinds' // Special mapping
};
// Start with raw data
Object.keys(rawData).forEach(key => {
processedData[key] = rawData[key];
});
// Apply prefixed field mappings
Object.entries(contentFilterMappings).forEach(([prefixedKey, rawKey]) => {
if (rawData[rawKey] !== undefined) {
processedData[prefixedKey] = rawData[rawKey];
}
});
console.log(`Processed ${groupName} data:`, processedData);
return processedData;
}
// Handle wallet field name mapping
if (groupName === 'wallet' && rawData) {
const processedData: any = {};
// Map backend field names to frontend field names
const walletMappings: Record<string, string> = {
'wallet_name': 'name',
'wallet_api_key': 'key' // Backend sends 'key', frontend expects 'wallet_api_key'
};
// Apply field mappings
Object.entries(walletMappings).forEach(([frontendKey, backendKey]) => {
if (rawData[backendKey] !== undefined) {
processedData[frontendKey] = rawData[backendKey];
}
});
console.log(`Processed ${groupName} data:`, processedData);
return processedData;
}
// Handle general settings field name mapping
if (groupName === 'general' && rawData) {
const processedData: any = {};
// General settings come from both server and relay sections
// We need to access both sections from the root settings
const relayData = settings?.relay || {};
// Map backend field names to frontend field names
// Some fields come from server section, others from relay section
const generalMappings: Record<string, { section: string; field: string }> = {
'port': { section: 'server', field: 'port' },
'private_key': { section: 'relay', field: 'private_key' },
'service_tag': { section: 'relay', field: 'service_tag' },
'relay_stats_db': { section: 'server', field: 'stats_db' },
'proxy': { section: 'server', field: 'proxy' }, // May not exist
'demo_mode': { section: 'server', field: 'demo' },
'web': { section: 'server', field: 'web' }
};
// Apply field mappings
Object.entries(generalMappings).forEach(([frontendKey, mapping]) => {
const sourceData = mapping.section === 'relay' ? relayData : rawData;
if (sourceData[mapping.field] !== undefined) {
processedData[frontendKey] = sourceData[mapping.field];
} else {
// Set default values for missing fields
if (frontendKey === 'relay_stats_db') {
processedData[frontendKey] = ''; // Default empty
} else if (frontendKey === 'proxy') {
processedData[frontendKey] = false; // Default false
}
}
});
console.log(`Processed ${groupName} data:`, processedData);
return processedData;
}
// Handle relay info field name mapping
if (groupName === 'relay_info' && rawData) {
const processedData: any = {};
// Map backend field names to frontend field names
const relayInfoMappings: Record<string, string> = {
'relayname': 'name',
'relaydescription': 'description',
'relaycontact': 'contact',
'relayicon': 'icon',
'relaypubkey': 'public_key', // Backend sends 'public_key'
'relaydhtkey': 'dht_key',
'relaysoftware': 'software',
'relayversion': 'version',
'relaysupportednips': 'supported_nips'
};
// Apply field mappings
Object.entries(relayInfoMappings).forEach(([frontendKey, backendKey]) => {
if (rawData[backendKey] !== undefined) {
processedData[frontendKey] = rawData[backendKey];
if (frontendKey === 'relayicon') {
console.log(`Icon mapping: ${frontendKey} = ${rawData[backendKey]}`);
}
} else {
// Set default values for missing fields
if (frontendKey === 'relaysupportednips') {
processedData[frontendKey] = []; // Default empty array
}
if (frontendKey === 'relayicon') {
console.log(`Icon field '${backendKey}' not found in rawData:`, Object.keys(rawData));
}
}
});
console.log(`Processed ${groupName} data:`, processedData);
return processedData;
}
return rawData;
};
// Helper function to build the nested update structure for the new API
const buildNestedUpdate = (groupName: string, data: any) => {
switch (groupName) {
case 'image_moderation':
return {
settings: {
content_filtering: {
image_moderation: data
}
}
};
case 'content_filter':
return {
settings: {
content_filtering: {
text_filter: data
}
}
};
case 'ollama':
return {
settings: {
external_services: {
ollama: data
}
}
};
case 'wallet':
// Reverse the field mapping for saving
const backendWalletData: any = {};
const walletFieldMappings: Record<string, string> = {
'name': 'wallet_name',
'key': 'wallet_api_key'
};
Object.entries(walletFieldMappings).forEach(([backendKey, frontendKey]) => {
if (data[frontendKey] !== undefined) {
backendWalletData[backendKey] = data[frontendKey];
}
});
return {
settings: {
external_services: {
wallet: backendWalletData
}
}
};
case 'relay_info':
// Reverse the field mapping for saving
const backendRelayData: any = {};
const relayFieldMappings: Record<string, string> = {
'name': 'relayname',
'description': 'relaydescription',
'contact': 'relaycontact',
'icon': 'relayicon',
'public_key': 'relaypubkey', // Frontend 'relaypubkey' -> backend 'public_key'
'dht_key': 'relaydhtkey',
'software': 'relaysoftware',
'version': 'relayversion',
'supported_nips': 'relaysupportednips'
};
Object.entries(relayFieldMappings).forEach(([backendKey, frontendKey]) => {
if (data[frontendKey] !== undefined) {
// Special handling for supported_nips to ensure they're numbers
if (backendKey === 'supported_nips') {
const nips = data[frontendKey];
if (Array.isArray(nips)) {
backendRelayData[backendKey] = nips.map((nip: any) => Number(nip)).filter((nip: number) => !isNaN(nip));
} else {
backendRelayData[backendKey] = [];
}
} else {
backendRelayData[backendKey] = data[frontendKey];
}
}
});
return {
settings: {
relay: backendRelayData
}
};
case 'general':
// Reverse the field mapping for saving
// General settings need to be split between server and relay sections
const serverData: any = {};
const relayData: any = {};
const generalFieldMappings: Record<string, { section: string; field: string }> = {
'port': { section: 'server', field: 'port' },
'private_key': { section: 'relay', field: 'private_key' },
'service_tag': { section: 'relay', field: 'service_tag' },
'stats_db': { section: 'server', field: 'relay_stats_db' },
'proxy': { section: 'server', field: 'proxy' },
'demo': { section: 'server', field: 'demo_mode' }, // Frontend 'demo_mode' -> backend 'demo'
'web': { section: 'server', field: 'web' }
};
Object.entries(generalFieldMappings).forEach(([backendField, mapping]) => {
const frontendField = mapping.field;
if (data[frontendField] !== undefined) {
if (mapping.section === 'server') {
serverData[backendField] = data[frontendField];
} else {
relayData[backendField] = data[frontendField];
}
}
});
// Return nested structure with both server and relay sections
const result: any = { settings: {} };
if (Object.keys(serverData).length > 0) {
result.settings.server = serverData;
}
if (Object.keys(relayData).length > 0) {
result.settings.relay = relayData;
}
return result;
default:
console.warn(`Unknown settings group for save: ${groupName}`);
return {
settings: {}
};
}
};
interface UseGenericSettingsResult<T> {
settings: T | null;
loading: boolean;
error: Error | null;
fetchSettings: () => Promise<void>;
updateSettings: (updatedSettings: Partial<T>) => void;
saveSettings: () => Promise<void>;
updateSetting: (key: string, value: any) => Promise<void>;
}
/**
* A hook for managing generic settings groups
* @param groupName The name of the settings group to manage
* @returns Object containing settings data and methods to fetch, update, and save settings
*/
const useGenericSettings = <T extends SettingsGroupName>(
groupName: T
): UseGenericSettingsResult<SettingsGroupType<T>> => {
const [settings, setSettings] = useState<SettingsGroupType<T> | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<Error | null>(null);
const handleLogout = useHandleLogout();
const token = readToken();
const fetchSettings = useCallback(async () => {
try {
setLoading(true);
setError(null);
console.log(`Fetching ${groupName} settings...`);
const response = await fetch(`${config.baseURL}/api/settings`, {
headers: {
'Authorization': `Bearer ${token}`,
},
});
if (response.status === 401) {
console.error('Unauthorized access, logging out');
handleLogout();
return;
}
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(`Raw settings data:`, data);
// Extract the correct nested data based on groupName
const settingsData = extractSettingsForGroup(data.settings, groupName) as SettingsGroupType<T>;
if (!settingsData) {
console.warn(`No settings data found for group: ${groupName}`);
// Return empty object instead of null to prevent errors when accessing properties
setSettings({} as SettingsGroupType<T>);
} else {
console.log(`Processed ${groupName} settings:`, settingsData);
// Handle all settings groups the same way - no special handling for image_moderation
// This approach works for all other settings groups, so it should work for image_moderation too
setSettings(settingsData as SettingsGroupType<T>);
}
} catch (error) {
console.error(`Error fetching ${groupName} settings:`, error);
setError(error instanceof Error ? error : new Error(String(error)));
// Set empty object on error to prevent null reference errors
setSettings({} as SettingsGroupType<T>);
} finally {
setLoading(false);
}
}, [groupName, token, handleLogout]);
const updateSettings = useCallback((updatedSettings: Partial<SettingsGroupType<T>>) => {
console.log(`Updating ${groupName} settings:`, updatedSettings);
// All groups should preserve existing settings when updating
setSettings(prevSettings => {
if (!prevSettings) {
console.log(`No previous ${groupName} settings, using updated settings as initial`);
return updatedSettings as SettingsGroupType<T>;
}
// Create a deep copy of the previous settings
const prevSettingsCopy = { ...prevSettings };
// Only update the changed fields, preserving all other fields
const newSettings = { ...prevSettingsCopy, ...updatedSettings };
console.log(`Previous settings:`, prevSettingsCopy);
console.log(`Updated fields:`, updatedSettings);
console.log(`Merged settings:`, newSettings);
return newSettings;
});
}, [groupName]);
const updateSetting = useCallback(async (key: string, value: any) => {
try {
setLoading(true);
setError(null);
const nestedUpdate = buildNestedUpdate(groupName, { [key]: value });
const response = await fetch(`${config.baseURL}/api/settings`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify(nestedUpdate),
});
if (response.status === 401) {
handleLogout();
return;
}
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
await fetchSettings();
} catch (error) {
setError(error instanceof Error ? error : new Error(String(error)));
throw error;
} finally {
setLoading(false);
}
}, [groupName, token, handleLogout, fetchSettings]);
const saveSettings = useCallback(async () => {
if (!settings) {
console.warn('No settings to save');
return;
}
try {
setLoading(true);
setError(null);
for (const [key, value] of Object.entries(settings)) {
await updateSetting(key, value);
}
console.log(`${groupName} settings saved successfully`);
} catch (error) {
console.error(`Error saving ${groupName} settings:`, error);
setError(error instanceof Error ? error : new Error(String(error)));
throw error;
} finally {
setLoading(false);
}
}, [groupName, settings, updateSetting]);
// Fetch settings on mount
useEffect(() => {
fetchSettings();
}, [fetchSettings]);
return {
settings,
loading,
error,
fetchSettings,
updateSettings,
saveSettings,
updateSetting,
};
};
export default useGenericSettings;