Rename folder "modules" to "features"

This commit is contained in:
schroda
2025-08-15 22:02:58 +02:00
parent 7e6ced1d09
commit 1b4bf22542
415 changed files with 1859 additions and 1852 deletions

View File

@@ -0,0 +1,189 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { DEFAULT_DEVICE } from '@/features/device/services/Device.ts';
import { DEFAULT_SORT_SETTINGS } from '@/features/migration/Migration.constants.ts';
import { GlobalUpdateSkipEntriesSettings, MetadataServerSettings } from '@/features/settings/Settings.types.ts';
import { GridLayout } from '@/features/core/Core.types.ts';
import { getDefaultLanguages } from '@/features/core/utils/Languages.ts';
import { ThemeMode } from '@/features/theme/contexts/AppThemeContext.tsx';
import {
SelectSettingValue,
SelectSettingValueDisplayInfo,
} from '@/features/core/components/settings/SelectSetting.tsx';
import { AuthMode, WebUiChannel, WebUiFlavor, WebUiInterface } from '@/lib/graphql/generated/graphql.ts';
import { TranslationKey } from '@/Base.types.ts';
export const MANGA_GRID_WIDTH = {
min: 100,
max: 1000,
step: 10,
default: 300,
};
export const SERVER_SETTINGS_METADATA_DEFAULT: MetadataServerSettings = {
// downloads
deleteChaptersManuallyMarkedRead: false,
deleteChaptersWhileReading: 0,
deleteChaptersWithBookmark: false,
downloadAheadLimit: 0,
// library
showAddToLibraryCategorySelectDialog: true,
ignoreFilters: false,
removeMangaFromCategories: false,
showTabSize: false,
showContinueReadingButton: false,
showDownloadBadge: false,
showUnreadBadge: false,
gridLayout: GridLayout.Compact,
// client
devices: [DEFAULT_DEVICE],
// migration
migrateChapters: true,
migrateCategories: true,
migrateTracking: true,
deleteChapters: true,
migrateSortSettings: DEFAULT_SORT_SETTINGS,
// browse
hideLibraryEntries: false,
extensionLanguages: getDefaultLanguages(),
sourceLanguages: getDefaultLanguages(),
showNsfw: true,
lastUsedSourceId: null,
shouldShowOnlySourcesWithResults: true,
// history
hideHistory: false,
// tracking
updateProgressAfterReading: true,
updateProgressManualMarkRead: false,
// updates
webUIInformAvailableUpdate: true,
serverInformAvailableUpdate: true,
// themes
appTheme: 'default',
themeMode: ThemeMode.SYSTEM,
shouldUsePureBlackMode: false,
customThemes: {},
mangaThumbnailBackdrop: true,
mangaDynamicColorSchemes: true,
mangaGridItemWidth: MANGA_GRID_WIDTH.default,
};
const AUTH_MODES = [AuthMode.None].concat(Object.values(AuthMode).filter((mode) => mode !== AuthMode.None));
const AUTH_MODES_TO_TRANSLATION_KEY: { [mode in AuthMode]: SelectSettingValueDisplayInfo } = {
[AuthMode.None]: {
text: 'settings.server.auth.mode.option.none.label.title',
description: 'settings.server.auth.mode.option.none.label.description',
disclaimer: 'settings.server.auth.mode.option.none.label.info',
},
[AuthMode.BasicAuth]: {
text: 'settings.server.auth.mode.option.basicAuth.label.title',
description: 'settings.server.auth.mode.option.basicAuth.label.description',
},
[AuthMode.SimpleLogin]: {
text: 'settings.server.auth.mode.option.simpleLogin.label.title',
description: 'settings.server.auth.mode.option.simpleLogin.label.description',
disclaimer: 'settings.server.auth.mode.option.simpleLogin.label.info',
},
};
export const AUTH_MODES_SELECT_VALUES: SelectSettingValue<AuthMode>[] = AUTH_MODES.map((mode) => [
mode,
AUTH_MODES_TO_TRANSLATION_KEY[mode],
]);
const WEB_UI_FLAVORS = Object.values(WebUiFlavor);
const WEB_UI_FLAVOR_TO_TRANSLATION_KEY: { [flavor in WebUiFlavor]: SelectSettingValueDisplayInfo } = {
[WebUiFlavor.Webui]: {
text: 'settings.webui.title.webui',
description: 'settings.webui.flavor.option.webui.label.description',
disclaimer: 'settings.webui.flavor.label.info',
},
[WebUiFlavor.Vui]: {
text: 'settings.webui.flavor.option.vui.label.title',
description: 'settings.webui.flavor.option.vui.label.description',
disclaimer: 'settings.webui.flavor.label.info',
},
[WebUiFlavor.Custom]: {
text: 'settings.webui.flavor.option.custom.label.title',
description: 'settings.webui.flavor.option.custom.label.description',
},
};
export const WEB_UI_FLAVOR_SELECT_VALUES: SelectSettingValue<WebUiFlavor>[] = WEB_UI_FLAVORS.map((flavor) => [
flavor,
WEB_UI_FLAVOR_TO_TRANSLATION_KEY[flavor],
]);
const WEB_UI_CHANNELS = Object.values(WebUiChannel);
const WEB_UI_CHANNEL_TO_TRANSLATION_KEYS: {
[channel in WebUiChannel]: SelectSettingValueDisplayInfo;
} = {
[WebUiChannel.Bundled]: {
text: 'settings.webui.channel.option.bundled.label.title',
description: 'settings.webui.channel.option.bundled.label.description',
disclaimer: 'settings.webui.flavor.label.info',
},
[WebUiChannel.Stable]: {
text: 'settings.webui.channel.option.stable.label.title',
description: 'settings.webui.channel.option.stable.label.description',
disclaimer: 'settings.webui.flavor.label.info',
},
[WebUiChannel.Preview]: {
text: 'settings.webui.channel.option.preview.label.title',
description: 'settings.webui.channel.option.preview.label.description',
disclaimer: 'settings.webui.channel.option.preview.label.disclaimer',
},
};
export const WEB_UI_CHANNEL_SELECT_VALUES: SelectSettingValue<WebUiChannel>[] = WEB_UI_CHANNELS.map((channel) => [
channel,
WEB_UI_CHANNEL_TO_TRANSLATION_KEYS[channel],
]);
const WEB_UI_INTERFACES = Object.values(WebUiInterface);
const WEB_UI_INTERFACE_TO_TRANSLATION_KEYS: {
[webUIInterface in WebUiInterface]: SelectSettingValueDisplayInfo;
} = {
[WebUiInterface.Browser]: {
text: 'settings.webui.interface.option.label.browser',
description: 'settings.webui.interface.label.description',
},
[WebUiInterface.Electron]: {
text: 'settings.webui.interface.option.label.electron',
description: 'settings.webui.interface.label.description',
},
};
export const WEB_UI_INTERFACE_SELECT_VALUES: SelectSettingValue<WebUiInterface>[] = WEB_UI_INTERFACES.map(
(webUIInterface) => [webUIInterface, WEB_UI_INTERFACE_TO_TRANSLATION_KEYS[webUIInterface]],
);
export const GLOBAL_UPDATE_INTERVAL = {
default: 12,
min: 6,
max: 24 * 7 * 4, // 1 month
};
export const GLOBAL_UPDATE_SKIP_ENTRIES_TO_TRANSLATION: {
[setting in keyof GlobalUpdateSkipEntriesSettings]: TranslationKey;
} = {
excludeUnreadChapters: 'library.settings.global_update.entries.label.unread_chapters',
excludeNotStarted: 'library.settings.global_update.entries.label.not_started',
excludeCompleted: 'library.settings.global_update.entries.label.completed',
};
export const WEB_UI_UPDATE_INTERVAL = {
default: 23,
min: 1,
max: 23,
};

View File

@@ -0,0 +1,88 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { MetadataDownloadSettings } from '@/features/downloads/Downloads.types.ts';
import { MetadataLibrarySettings } from '@/features/library/Library.types.ts';
import { MetadataClientSettings } from '@/features/device/Device.types.ts';
import { MetadataMigrationSettings } from '@/features/migration/Migration.types.ts';
import { MetadataBrowseSettings } from '@/features/browse/Browse.types.ts';
import { MetadataTrackingSettings } from '@/features/tracker/Tracker.types.ts';
import { MetadataUpdateSettings } from '@/features/app-updates/AppUpdateChecker.types.ts';
import { MetadataThemeSettings } from '@/features/theme/AppTheme.types.ts';
import { GetServerSettingsQuery } from '@/lib/graphql/generated/graphql.ts';
import { MetadataHistorySettings } from '@/features/history/History.types.ts';
import { ServerSettings as GqlServerSettings } from '@/features/settings/Settings.types.ts';
export type MetadataServerSettingKeys = keyof MetadataServerSettings;
export type SearchMetadataKeys = keyof ISearchSettings;
export type MetadataServerSettings = MetadataDownloadSettings &
MetadataLibrarySettings &
MetadataClientSettings &
MetadataMigrationSettings &
MetadataBrowseSettings &
MetadataTrackingSettings &
MetadataUpdateSettings &
MetadataThemeSettings &
MetadataHistorySettings;
export interface ISearchSettings {
ignoreFilters: boolean;
}
export type ServerSettings = Omit<GetServerSettingsQuery['settings'], '__typename'>;
export type ServerSettingsType = Pick<
GqlServerSettings,
| 'ip'
| 'port'
| 'socksProxyEnabled'
| 'socksProxyVersion'
| 'socksProxyHost'
| 'socksProxyPort'
| 'socksProxyUsername'
| 'socksProxyPassword'
| 'debugLogsEnabled'
| 'systemTrayEnabled'
| 'maxLogFiles'
| 'maxLogFileSize'
| 'maxLogFolderSize'
| 'authMode'
| 'authUsername'
| 'authPassword'
| 'flareSolverrEnabled'
| 'flareSolverrTimeout'
| 'flareSolverrUrl'
| 'flareSolverrSessionName'
| 'flareSolverrSessionTtl'
| 'flareSolverrAsResponseFallback'
| 'opdsUseBinaryFileSizes'
| 'opdsItemsPerPage'
| 'opdsEnablePageReadProgress'
| 'opdsMarkAsReadOnDownload'
| 'opdsShowOnlyUnreadChapters'
| 'opdsShowOnlyDownloadedChapters'
| 'opdsChapterSortOrder'
>;
export type WebUISettingsType = Pick<
ServerSettings,
| 'webUIFlavor'
| 'initialOpenInBrowserEnabled'
| 'webUIInterface'
| 'electronPath'
| 'webUIChannel'
| 'webUIUpdateCheckInterval'
>;
export type GlobalUpdateSkipEntriesSettings = Pick<
ServerSettings,
'excludeUnreadChapters' | 'excludeNotStarted' | 'excludeCompleted'
>;
export type LibrarySettingsType = Pick<ServerSettings, 'updateMangas'>;

View File

@@ -0,0 +1,77 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import List from '@mui/material/List';
import ListSubheader from '@mui/material/ListSubheader';
import { useTranslation } from 'react-i18next';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import Switch from '@mui/material/Switch';
import {
CategoriesInclusionSetting,
CategoriesInclusionSettingProps,
} from '@/features/category/components/CategoriesInclusionSetting.tsx';
import { GlobalUpdateSettingsEntries } from '@/features/settings/components/globalUpdate/GlobalUpdateSettingsEntries.tsx';
import { GlobalUpdateSettingsInterval } from '@/features/settings/components/globalUpdate/GlobalUpdateSettingsInterval.tsx';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { LibrarySettingsType, ServerSettings } from '@/features/settings/Settings.types.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
export const GlobalUpdateSettings = ({
serverSettings,
categories,
}: {
serverSettings: ServerSettings;
categories: CategoriesInclusionSettingProps['categories'];
}) => {
const { t } = useTranslation();
const { updateMangas } = serverSettings;
const [mutateSettings] = requestManager.useUpdateServerSettings();
const updateSetting = async <Setting extends keyof LibrarySettingsType>(
setting: Setting,
value: LibrarySettingsType[Setting],
) => {
try {
await mutateSettings({ variables: { input: { settings: { [setting]: value } } } });
} catch (e) {
makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e));
}
};
return (
<List
subheader={
<ListSubheader component="div" id="global-update-settings">
{t('library.settings.global_update.title')}
</ListSubheader>
}
>
<GlobalUpdateSettingsInterval globalUpdateInterval={serverSettings.globalUpdateInterval} />
<GlobalUpdateSettingsEntries serverSettings={serverSettings} />
<CategoriesInclusionSetting
categories={categories}
includeField="includeInUpdate"
dialogText={t('library.settings.global_update.categories.label.info')}
/>
<ListItem>
<ListItemText
primary={t('library.settings.global_update.metadata.label.title')}
secondary={t('library.settings.global_update.metadata.label.description')}
/>
<Switch
edge="end"
checked={updateMangas}
onChange={(e) => updateSetting('updateMangas', e.target.checked)}
/>
</ListItem>
</List>
);
};

View File

@@ -0,0 +1,149 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { t as translate } from 'i18next';
import { useTranslation } from 'react-i18next';
import { useEffect, useState } from 'react';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemText from '@mui/material/ListItemText';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { CheckboxContainer } from '@/features/core/components/inputs/CheckboxContainer.ts';
import { CheckboxInput } from '@/features/core/components/inputs/CheckboxInput.tsx';
import { GlobalUpdateSkipEntriesSettings, ServerSettings } from '@/features/settings/Settings.types.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { GLOBAL_UPDATE_SKIP_ENTRIES_TO_TRANSLATION } from '@/features/settings/Settings.constants.ts';
const getSkipMangasText = (settings: GlobalUpdateSkipEntriesSettings) => {
const skipSettings: string[] = [];
if (settings.excludeUnreadChapters) {
skipSettings.push(translate(GLOBAL_UPDATE_SKIP_ENTRIES_TO_TRANSLATION.excludeUnreadChapters) as string);
}
if (settings.excludeNotStarted) {
skipSettings.push(translate(GLOBAL_UPDATE_SKIP_ENTRIES_TO_TRANSLATION.excludeNotStarted) as string);
}
if (settings.excludeCompleted) {
skipSettings.push(translate(GLOBAL_UPDATE_SKIP_ENTRIES_TO_TRANSLATION.excludeCompleted) as string);
}
const isNothingExcluded = !skipSettings.length;
if (isNothingExcluded) {
skipSettings.push(translate('global.label.none'));
}
return skipSettings.join(', ');
};
const extractSkipEntriesSettings = (serverSettings: ServerSettings): GlobalUpdateSkipEntriesSettings => ({
excludeCompleted: serverSettings.excludeCompleted,
excludeNotStarted: serverSettings.excludeNotStarted,
excludeUnreadChapters: serverSettings.excludeUnreadChapters,
});
export const GlobalUpdateSettingsEntries = ({ serverSettings }: { serverSettings: ServerSettings }) => {
const { t } = useTranslation();
const globalUpdateSettings = extractSkipEntriesSettings(serverSettings);
const [mutateSettings] = requestManager.useUpdateServerSettings();
const [dialogSettings, setDialogSettings] = useState<GlobalUpdateSkipEntriesSettings>(
globalUpdateSettings ?? ({} as GlobalUpdateSkipEntriesSettings),
);
const [isDialogOpen, setIsDialogOpen] = useState(false);
const skipEntriesText = getSkipMangasText(globalUpdateSettings);
const updateSettings = async () => {
const didSettingsChange =
globalUpdateSettings?.excludeCompleted !== dialogSettings.excludeCompleted ||
globalUpdateSettings.excludeNotStarted !== dialogSettings.excludeNotStarted ||
globalUpdateSettings.excludeUnreadChapters !== dialogSettings.excludeUnreadChapters;
setIsDialogOpen(false);
if (!didSettingsChange) {
return;
}
try {
await mutateSettings({ variables: { input: { settings: dialogSettings } } });
} catch (e) {
makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e));
}
};
const closeDialog = () => {
setDialogSettings(globalUpdateSettings ?? ({} as GlobalUpdateSkipEntriesSettings));
setIsDialogOpen(false);
};
useEffect(() => {
if (!globalUpdateSettings) {
return;
}
setDialogSettings(globalUpdateSettings);
}, [
globalUpdateSettings?.excludeCompleted,
globalUpdateSettings?.excludeNotStarted,
globalUpdateSettings?.excludeUnreadChapters,
]);
return (
<>
<ListItemButton onClick={() => setIsDialogOpen(true)}>
<ListItemText
primary={t('library.settings.global_update.entries.title')}
secondary={skipEntriesText}
onClick={() => setIsDialogOpen(true)}
/>
</ListItemButton>
<Dialog open={isDialogOpen} onClose={closeDialog}>
<DialogTitle>{t('library.settings.global_update.entries.title')}</DialogTitle>
<DialogContent>
<CheckboxContainer>
{Object.entries(dialogSettings).map(([setting, value]) => (
<CheckboxInput
key={setting}
label={t(
GLOBAL_UPDATE_SKIP_ENTRIES_TO_TRANSLATION[
setting as keyof GlobalUpdateSkipEntriesSettings
],
)}
checked={value}
onChange={(_, checked) => {
setDialogSettings({
...dialogSettings,
[setting]: checked,
});
}}
/>
))}
</CheckboxContainer>
</DialogContent>
<DialogActions>
<Button onClick={closeDialog} color="primary">
{t('global.button.cancel')}
</Button>
<Button onClick={updateSettings} color="primary">
{t('global.button.ok')}
</Button>
</DialogActions>
</Dialog>
</>
);
};

View File

@@ -0,0 +1,76 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { useTranslation } from 'react-i18next';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import Switch from '@mui/material/Switch';
import { useCallback } from 'react';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { NumberSetting } from '@/features/core/components/settings/NumberSetting.tsx';
import { getPersistedServerSetting, usePersistedValue } from '@/features/core/hooks/usePersistedValue.tsx';
import { ServerSettings } from '@/features/settings/Settings.types.ts';
import { GLOBAL_UPDATE_INTERVAL } from '@/features/settings/Settings.constants.ts';
export const GlobalUpdateSettingsInterval = ({
globalUpdateInterval,
}: {
globalUpdateInterval: ServerSettings['globalUpdateInterval'];
}) => {
const { t } = useTranslation();
const autoUpdateIntervalHours = globalUpdateInterval;
const doAutoUpdates = !!autoUpdateIntervalHours;
const [mutateSettings] = requestManager.useUpdateServerSettings();
const [currentAutoUpdateIntervalHours, persistAutoUpdateIntervalHours] = usePersistedValue(
'lastGlobalUpdateInterval',
GLOBAL_UPDATE_INTERVAL.default,
autoUpdateIntervalHours,
getPersistedServerSetting,
);
const updateSetting = useCallback(
(newGlobalUpdateInterval: number) => {
persistAutoUpdateIntervalHours(
newGlobalUpdateInterval === 0 ? currentAutoUpdateIntervalHours : newGlobalUpdateInterval,
);
mutateSettings({ variables: { input: { settings: { globalUpdateInterval: newGlobalUpdateInterval } } } });
},
[currentAutoUpdateIntervalHours],
);
const setDoAutoUpdates = (enable: boolean) => {
const newGlobalUpdateInterval = enable ? currentAutoUpdateIntervalHours : 0;
updateSetting(newGlobalUpdateInterval);
};
return (
<List>
<ListItem>
<ListItemText primary={t('library.settings.global_update.auto_update.label.title')} />
<Switch edge="end" checked={doAutoUpdates} onChange={(e) => setDoAutoUpdates(e.target.checked)} />
</ListItem>
<NumberSetting
settingTitle={t('library.settings.global_update.auto_update.interval.label.title')}
settingValue={t('library.settings.global_update.auto_update.interval.label.value', {
hours: currentAutoUpdateIntervalHours,
})}
value={currentAutoUpdateIntervalHours}
minValue={GLOBAL_UPDATE_INTERVAL.min}
maxValue={GLOBAL_UPDATE_INTERVAL.max}
defaultValue={GLOBAL_UPDATE_INTERVAL.default}
showSlider
valueUnit={t('global.time.hour_short')}
handleUpdate={updateSetting}
disabled={!doAutoUpdates}
/>
</List>
);
};

View File

@@ -0,0 +1,85 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { useTranslation } from 'react-i18next';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import Switch from '@mui/material/Switch';
import { useCallback } from 'react';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { NumberSetting } from '@/features/core/components/settings/NumberSetting.tsx';
import { getPersistedServerSetting, usePersistedValue } from '@/features/core/hooks/usePersistedValue.tsx';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { ServerSettings } from '@/features/settings/Settings.types.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { WEB_UI_UPDATE_INTERVAL } from '@/features/settings/Settings.constants.ts';
export const WebUIUpdateIntervalSetting = ({
disabled = false,
updateCheckInterval,
}: {
disabled?: boolean;
updateCheckInterval: ServerSettings['webUIUpdateCheckInterval'];
}) => {
const { t } = useTranslation();
const shouldAutoUpdate = !!updateCheckInterval;
const [mutateSettings] = requestManager.useUpdateServerSettings();
const [currentUpdateCheckInterval, persistUpdateCheckInterval] = usePersistedValue(
'lastUpdateCheckInterval',
WEB_UI_UPDATE_INTERVAL.default,
updateCheckInterval,
getPersistedServerSetting,
);
const updateSetting = useCallback(
(webUIUpdateCheckInterval: number) => {
persistUpdateCheckInterval(
webUIUpdateCheckInterval === 0 ? currentUpdateCheckInterval : webUIUpdateCheckInterval,
);
mutateSettings({ variables: { input: { settings: { webUIUpdateCheckInterval } } } }).catch((e) =>
makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e)),
);
},
[currentUpdateCheckInterval],
);
const setDoAutoUpdates = (enable: boolean) => {
const globalUpdateInterval = enable ? currentUpdateCheckInterval : 0;
updateSetting(globalUpdateInterval);
};
return (
<List>
<ListItem>
<ListItemText primary={t('settings.webui.auto_update.label.title')} />
<Switch
disabled={disabled}
edge="end"
checked={shouldAutoUpdate}
onChange={(e) => setDoAutoUpdates(e.target.checked)}
/>
</ListItem>
<NumberSetting
settingTitle={t('settings.webui.auto_update.label.interval')}
settingValue={t('library.settings.global_update.auto_update.interval.label.value', {
hours: currentUpdateCheckInterval,
})}
value={currentUpdateCheckInterval}
minValue={WEB_UI_UPDATE_INTERVAL.min}
maxValue={WEB_UI_UPDATE_INTERVAL.max}
defaultValue={WEB_UI_UPDATE_INTERVAL.default}
showSlider
valueUnit={t('global.time.hour_short')}
handleUpdate={updateSetting}
disabled={disabled || !shouldAutoUpdate}
/>
</List>
);
};

View File

@@ -0,0 +1,174 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import { useTranslation } from 'react-i18next';
import ListSubheader from '@mui/material/ListSubheader';
import Divider from '@mui/material/Divider';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { ListItemLink } from '@/features/core/components/lists/ListItemLink.tsx';
import { LoadingPlaceholder } from '@/features/core/components/feedback/LoadingPlaceholder.tsx';
import { UpdateState } from '@/lib/graphql/generated/graphql.ts';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import { EmptyViewAbsoluteCentered } from '@/features/core/components/feedback/EmptyViewAbsoluteCentered.tsx';
import { VersionInfo } from '@/features/app-updates/components/VersionInfo.tsx';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { epochToDate } from '@/util/DateHelper.ts';
import { useAppTitle } from '@/features/navigation-bar/hooks/useAppTitle.ts';
export function About() {
const { t } = useTranslation();
useAppTitle(t('settings.about.title'));
const { data, loading, error, refetch } = requestManager.useGetAbout({ notifyOnNetworkStatusChange: true });
const {
data: serverUpdateCheckData,
loading: isCheckingForServerUpdate,
refetch: checkForServerUpdate,
error: serverUpdateCheckError,
} = requestManager.useCheckForServerUpdate({ notifyOnNetworkStatusChange: true });
const {
data: webUIUpdateData,
loading: isCheckingForWebUIUpdate,
refetch: checkForWebUIUpdate,
error: orgWebUIUpdateCheckError,
} = requestManager.useCheckForWebUIUpdate({ notifyOnNetworkStatusChange: true });
const webUIUpdateCheckError = orgWebUIUpdateCheckError || webUIUpdateData?.checkForWebUIUpdate.tag === '';
const { data: webUIUpdateStatusData } = requestManager.useGetWebUIUpdateStatus();
const { state: webUIUpdateState, progress: webUIUpdateProgress } = webUIUpdateStatusData?.getWebUIUpdateStatus ?? {
state: UpdateState.Idle,
progress: 0,
};
if (loading) {
return <LoadingPlaceholder />;
}
if (error) {
return (
<EmptyViewAbsoluteCentered
message={t('global.error.label.failed_to_load_data')}
messageExtra={getErrorMessage(error)}
retry={() => refetch().catch(defaultPromiseErrorHandler('About::refetch'))}
/>
);
}
const { aboutServer, aboutWebUI } = data!;
const selectedServerChannelInfo = serverUpdateCheckData?.checkForServerUpdates?.find(
(channel) => channel.channel === aboutServer.buildType,
);
const isServerUpdateAvailable =
!!selectedServerChannelInfo?.tag && selectedServerChannelInfo.tag !== aboutServer.version;
const isWebUIUpdateAvailable = !!webUIUpdateData?.checkForWebUIUpdate.updateAvailable;
return (
<List sx={{ pt: 0 }}>
<List
sx={{ padding: 0 }}
subheader={
<ListSubheader component="div" id="about-server-info">
{t('settings.server.title.server')}
</ListSubheader>
}
>
<ListItem>
<ListItemText
primary={t('settings.server.title.server')}
secondary={`${aboutServer.name} (${aboutServer.buildType})`}
/>
</ListItem>
<ListItem>
<ListItemText
primary={t('settings.about.server.label.version')}
secondary={
<VersionInfo
version={aboutServer.version}
isCheckingForUpdate={isCheckingForServerUpdate}
isUpdateAvailable={isServerUpdateAvailable}
updateCheckError={serverUpdateCheckError}
checkForUpdate={checkForServerUpdate}
downloadAsLink
url={selectedServerChannelInfo?.url ?? ''}
/>
}
/>
</ListItem>
<ListItem>
<ListItemText
primary={t('settings.about.server.label.build_time')}
secondary={epochToDate(Number(aboutServer.buildTime)).toString()}
/>
</ListItem>
</List>
<Divider />
<List
sx={{ padding: 0 }}
subheader={
<ListSubheader component="div" id="about-webui-info">
{t('settings.webui.title.webui')}
</ListSubheader>
}
>
<ListItem>
<ListItemText
primary={t('settings.about.webui.label.channel')}
secondary={aboutWebUI.channel.toLocaleUpperCase()}
/>
</ListItem>
<ListItem>
<ListItemText
primary={t('settings.about.webui.label.version')}
secondary={
<VersionInfo
version={aboutWebUI.tag}
isCheckingForUpdate={isCheckingForWebUIUpdate}
isUpdateAvailable={isWebUIUpdateAvailable}
updateCheckError={webUIUpdateCheckError}
checkForUpdate={checkForWebUIUpdate}
triggerUpdate={() =>
requestManager
.updateWebUI()
.response.catch(defaultPromiseErrorHandler('About::updateWebUI'))
}
progress={webUIUpdateProgress}
updateState={webUIUpdateState}
/>
}
/>
</ListItem>
</List>
<Divider />
<List
subheader={
<ListSubheader component="div" id="about-links">
{t('global.label.links')}
</ListSubheader>
}
>
<ListItemLink to={aboutServer.github} target="_blank" rel="noreferrer">
<ListItemText primary={t('settings.about.server.label.github')} secondary={aboutServer.github} />
</ListItemLink>
<ListItemLink to="https://github.com/Suwayomi/Suwayomi-WebUI" target="_blank" rel="noreferrer">
<ListItemText
primary={t('settings.about.webui.label.github')}
secondary="https://github.com/Suwayomi/Suwayomi-WebUI"
/>
</ListItemLink>
<ListItemLink to={aboutServer.discord} target="_blank" rel="noreferrer">
<ListItemText primary={t('global.label.discord')} secondary={aboutServer.discord} />
</ListItemLink>
</List>
</List>
);
}

View File

@@ -0,0 +1,193 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { useTranslation } from 'react-i18next';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import MenuItem from '@mui/material/MenuItem';
import ListSubheader from '@mui/material/ListSubheader';
import Switch from '@mui/material/Switch';
import Link from '@mui/material/Link';
import { useColorScheme } from '@mui/material/styles';
import { ThemeMode, useAppThemeContext } from '@/features/theme/contexts/AppThemeContext.tsx';
import { Select } from '@/features/core/components/inputs/Select.tsx';
import { MediaQuery } from '@/features/core/utils/MediaQuery.tsx';
import { NumberSetting } from '@/features/core/components/settings/NumberSetting.tsx';
import { I18nResourceCode, i18nResources } from '@/i18n';
import { languageCodeToName } from '@/features/core/utils/Languages.ts';
import { ThemeList } from '@/features/theme/components/ThemeList.tsx';
import {
createUpdateMetadataServerSettings,
useMetadataServerSettings,
} from '@/features/settings/services/ServerSettingsMetadata.ts';
import { LoadingPlaceholder } from '@/features/core/components/feedback/LoadingPlaceholder.tsx';
import { EmptyViewAbsoluteCentered } from '@/features/core/components/feedback/EmptyViewAbsoluteCentered.tsx';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { MetadataThemeSettings } from '@/features/theme/AppTheme.types.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { AppStorage } from '@/lib/storage/AppStorage.ts';
import { useAppTitle } from '@/features/navigation-bar/hooks/useAppTitle.ts';
import { MANGA_GRID_WIDTH, SERVER_SETTINGS_METADATA_DEFAULT } from '@/features/settings/Settings.constants.ts';
import { MUI_THEME_MODE_KEY } from '@/lib/mui/MUI.constants.ts';
export const Appearance = () => {
const { t, i18n } = useTranslation();
const { themeMode, setThemeMode, shouldUsePureBlackMode, setShouldUsePureBlackMode } = useAppThemeContext();
const { mode, setMode } = useColorScheme();
const actualThemeMode = (mode ?? themeMode) as ThemeMode;
useAppTitle(t('settings.appearance.title'));
const {
settings: { mangaThumbnailBackdrop, mangaDynamicColorSchemes, mangaGridItemWidth },
request: { loading, error, refetch },
} = useMetadataServerSettings();
const updateMetadataSetting = createUpdateMetadataServerSettings<keyof MetadataThemeSettings>((e) =>
makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e)),
);
const isDarkMode = MediaQuery.getThemeMode(actualThemeMode) === ThemeMode.DARK;
if (loading) {
return <LoadingPlaceholder />;
}
if (error) {
return (
<EmptyViewAbsoluteCentered
message={t('global.error.label.failed_to_load_data')}
messageExtra={getErrorMessage(error)}
retry={() => refetch().catch(defaultPromiseErrorHandler('Appearance::refetch'))}
/>
);
}
return (
<List
subheader={
<ListSubheader component="div" id="appearance-theme">
{t('settings.appearance.theme.title')}
</ListSubheader>
}
>
<ListItem>
<ListItemText primary={t('settings.appearance.theme.mode')} />
<Select<ThemeMode>
value={actualThemeMode}
onChange={(e) => {
const newMode = e.target.value as 'system' | 'light' | 'dark';
setThemeMode(newMode as ThemeMode);
setMode(newMode);
// in case a non "colorSchemes" mui theme is active, "setMode" does not update the mode ("mui-mode") value
AppStorage.local.setItem(MUI_THEME_MODE_KEY, newMode, true);
}}
>
<MenuItem key={ThemeMode.SYSTEM} value={ThemeMode.SYSTEM}>
{t('global.label.system')}
</MenuItem>
<MenuItem key={ThemeMode.DARK} value={ThemeMode.DARK}>
{t('global.label.dark')}
</MenuItem>
<MenuItem key={ThemeMode.LIGHT} value={ThemeMode.LIGHT}>
{t('global.label.light')}
</MenuItem>
</Select>
</ListItem>
<ThemeList />
{isDarkMode && (
<ListItem>
<ListItemText primary={t('settings.appearance.theme.pure_black_mode')} />
<Switch
checked={shouldUsePureBlackMode}
onChange={(_, enabled) => setShouldUsePureBlackMode(enabled)}
/>
</ListItem>
)}
<List
subheader={
<ListSubheader component="div" id="appearance-theme">
{t('global.label.display')}
</ListSubheader>
}
>
<ListItem>
<ListItemText
primary={t('global.language.label.language')}
secondary={
<>
<span>{t('settings.label.language_description')} </span>
<Link
href="https://hosted.weblate.org/projects/suwayomi/suwayomi-webui"
target="_blank"
rel="noreferrer"
>
{t('global.language.title.weblate')}
</Link>
</>
}
/>
<Select
value={i18nResources.includes(i18n.language as I18nResourceCode) ? i18n.language : 'en'}
onChange={({ target: { value: language } }) =>
i18n.changeLanguage(language, (e) => {
if (e) {
makeToast(t('global.language.error.load'), 'error', getErrorMessage(e));
}
})
}
>
{i18nResources.map((language) => (
<MenuItem key={language} value={language}>
{languageCodeToName(language)}
</MenuItem>
))}
</Select>
</ListItem>
<NumberSetting
settingTitle={t('settings.label.manga_item_width')}
settingValue={`px: ${mangaGridItemWidth}`}
value={mangaGridItemWidth}
defaultValue={SERVER_SETTINGS_METADATA_DEFAULT.mangaGridItemWidth}
minValue={MANGA_GRID_WIDTH.min}
maxValue={MANGA_GRID_WIDTH.max}
stepSize={MANGA_GRID_WIDTH.step}
valueUnit="px"
showSlider
handleUpdate={(width) => updateMetadataSetting('mangaGridItemWidth', width)}
/>
<ListItem>
<ListItemText
primary={t('settings.appearance.manga_thumbnail_backdrop.title')}
secondary={t('settings.appearance.manga_thumbnail_backdrop.description')}
/>
<Switch
edge="end"
checked={mangaThumbnailBackdrop}
onChange={(e) => updateMetadataSetting('mangaThumbnailBackdrop', e.target.checked)}
/>
</ListItem>
<ListItem>
<ListItemText
primary={t('settings.appearance.manga_dynamic_color_schemes.title')}
secondary={t('settings.appearance.manga_dynamic_color_schemes.description')}
/>
<Switch
edge="end"
checked={mangaDynamicColorSchemes}
onChange={(e) => updateMetadataSetting('mangaDynamicColorSchemes', e.target.checked)}
/>
</ListItem>
</List>
</List>
);
};

View File

@@ -0,0 +1,82 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { Fragment } from 'react';
import { useTranslation } from 'react-i18next';
import List from '@mui/material/List';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import ListAltIcon from '@mui/icons-material/ListAlt';
import Divider from '@mui/material/Divider';
import { AppRoutes } from '@/features/core/AppRoute.constants.ts';
import { ListItemLink } from '@/features/core/components/lists/ListItemLink.tsx';
import { NAVIGATION_BAR_ITEMS } from '@/features/navigation-bar/NavigationBar.constants.ts';
import { MediaQuery } from '@/features/core/utils/MediaQuery.tsx';
import { NavigationBarUtil } from '@/features/navigation-bar/NavigationBar.util.ts';
import { useMetadataServerSettings } from '@/features/settings/services/ServerSettingsMetadata.ts';
import { NavbarItem, NavBarItemMoreGroup } from '@/features/navigation-bar/NavigationBar.types.ts';
import { useAppTitle } from '@/features/navigation-bar/hooks/useAppTitle.ts';
export const More = () => {
const { t } = useTranslation();
const isMobileWidth = MediaQuery.useIsMobileWidth();
useAppTitle(t('global.label.more'));
const {
settings: { hideHistory },
} = useMetadataServerSettings();
const hiddenNavBarItems = NavigationBarUtil.filterItems(NAVIGATION_BAR_ITEMS, {
hideHistory,
hideMore: true,
hideBoth: true,
hideDesktop: !isMobileWidth,
hideMobile: isMobileWidth,
});
const hiddenNavBarItemsByMoreGroup = Object.groupBy(hiddenNavBarItems, (item) => item.moreGroup);
const hiddenItemsMoreGroup = [
...(hiddenNavBarItemsByMoreGroup[NavBarItemMoreGroup.HIDDEN_ITEM] ?? []),
{
path: AppRoutes.settings.childRoutes.categories.path,
title: 'category.title.category_other',
SelectedIconComponent: ListAltIcon,
IconComponent: ListAltIcon,
show: 'both',
moreGroup: NavBarItemMoreGroup.HIDDEN_ITEM,
},
] satisfies NavbarItem[];
const finalHiddenNavBarItemsByGroup: typeof hiddenNavBarItemsByMoreGroup = {
...hiddenNavBarItemsByMoreGroup,
[NavBarItemMoreGroup.HIDDEN_ITEM]: hiddenItemsMoreGroup,
};
return (
<List sx={{ p: 0 }}>
{Object.entries(finalHiddenNavBarItemsByGroup).map(([group, items], index, list) => (
<Fragment key={group}>
{items.map((item) => (
<ListItemLink key={item.path} to={item.path}>
<ListItemIcon>
<item.IconComponent />
</ListItemIcon>
<ListItemText
primary={t(item.moreTitle ?? item.title)}
secondary={item.useBadge?.().title}
/>
</ListItemLink>
))}
{index !== list.length - 1 && <Divider />}
</Fragment>
))}
</List>
);
};

View File

@@ -0,0 +1,506 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { Trans, useTranslation } from 'react-i18next';
import { useMemo } from 'react';
import Link from '@mui/material/Link';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import Switch from '@mui/material/Switch';
import ListSubheader from '@mui/material/ListSubheader';
import { t as translate } from 'i18next';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { useLocalStorage } from '@/features/core/hooks/useStorage.tsx';
import { TextSetting } from '@/features/core/components/settings/text/TextSetting.tsx';
import { NumberSetting } from '@/features/core/components/settings/NumberSetting.tsx';
import { SelectSetting } from '@/features/core/components/settings/SelectSetting.tsx';
import { LoadingPlaceholder } from '@/features/core/components/feedback/LoadingPlaceholder.tsx';
import { EmptyViewAbsoluteCentered } from '@/features/core/components/feedback/EmptyViewAbsoluteCentered.tsx';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import {
createUpdateMetadataServerSettings,
useMetadataServerSettings,
} from '@/features/settings/services/ServerSettingsMetadata.ts';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { MetadataUpdateSettings } from '@/features/app-updates/AppUpdateChecker.types.ts';
import { ServerSettings as GqlServerSettings, ServerSettingsType } from '@/features/settings/Settings.types.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { useAppTitle } from '@/features/navigation-bar/hooks/useAppTitle.ts';
import { AuthMode, SortOrder } from '@/lib/graphql/generated/graphql';
import { AUTH_MODES_SELECT_VALUES } from '@/features/settings/Settings.constants.ts';
const extractServerSettings = (settings: GqlServerSettings): ServerSettingsType => ({
ip: settings.ip,
port: settings.port,
socksProxyEnabled: settings.socksProxyEnabled,
socksProxyVersion: settings.socksProxyVersion,
socksProxyHost: settings.socksProxyHost,
socksProxyPort: settings.socksProxyPort,
socksProxyUsername: settings.socksProxyUsername,
socksProxyPassword: settings.socksProxyPassword,
debugLogsEnabled: settings.debugLogsEnabled,
systemTrayEnabled: settings.systemTrayEnabled,
maxLogFiles: settings.maxLogFiles,
maxLogFileSize: settings.maxLogFileSize,
maxLogFolderSize: settings.maxLogFolderSize,
authMode: settings.authMode,
authUsername: settings.authUsername,
authPassword: settings.authPassword,
flareSolverrEnabled: settings.flareSolverrEnabled,
flareSolverrTimeout: settings.flareSolverrTimeout,
flareSolverrUrl: settings.flareSolverrUrl,
flareSolverrSessionName: settings.flareSolverrSessionName,
flareSolverrSessionTtl: settings.flareSolverrSessionTtl,
flareSolverrAsResponseFallback: settings.flareSolverrAsResponseFallback,
opdsUseBinaryFileSizes: settings.opdsUseBinaryFileSizes,
opdsItemsPerPage: settings.opdsItemsPerPage,
opdsEnablePageReadProgress: settings.opdsEnablePageReadProgress,
opdsMarkAsReadOnDownload: settings.opdsMarkAsReadOnDownload,
opdsShowOnlyUnreadChapters: settings.opdsShowOnlyUnreadChapters,
opdsShowOnlyDownloadedChapters: settings.opdsShowOnlyDownloadedChapters,
opdsChapterSortOrder: settings.opdsChapterSortOrder,
});
const getLogFilesCleanupDisplayValue = (ttl: number): string => {
if (ttl === 0) {
return translate('global.label.never');
}
return translate('settings.server.misc.log_files.file_cleanup.value', { days: ttl, count: ttl });
};
export const ServerSettings = () => {
const { t } = useTranslation();
useAppTitle(t('settings.server.title.server'));
const {
settings: { serverInformAvailableUpdate },
loading: areMetadataServerSettingsLoading,
request: { error: metadataServerSettingsError, refetch: refetchServerMetadataSettings },
} = useMetadataServerSettings();
const updateMetadataServerSettings = createUpdateMetadataServerSettings<
keyof Pick<MetadataUpdateSettings, 'serverInformAvailableUpdate'>
>((e) => makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e)));
const {
data,
loading: areServerSettingsLoading,
error: serverSettingsError,
refetch: refetchServerSettings,
} = requestManager.useGetServerSettings({
notifyOnNetworkStatusChange: true,
});
const [mutateSettings] = requestManager.useUpdateServerSettings();
const [serverAddress, setServerAddress] = useLocalStorage<string>(
'serverBaseURL',
import.meta.env.VITE_SERVER_URL_DEFAULT,
);
const handleServerAddressChange = (address: string) => {
const serverBaseUrl = address.replaceAll(/(\/)+$/g, '');
setServerAddress(serverBaseUrl);
requestManager.reset();
};
const updateSetting = <Setting extends keyof ServerSettingsType>(
setting: Setting,
value: ServerSettingsType[Setting],
) => {
mutateSettings({ variables: { input: { settings: { [setting]: value } } } }).catch((e) =>
makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e)),
);
};
const localSettings = useMemo(
() => (
<List
subheader={
<ListSubheader component="div" id="server-settings-client">
{t('global.label.client')}
</ListSubheader>
}
>
<TextSetting
settingName={t('settings.about.server.label.address')}
handleChange={handleServerAddressChange}
value={serverAddress}
placeholder="http://localhost:4567"
/>
<ListItem>
<ListItemText
primary={t('global.update.settings.inform.label.title')}
secondary={t('global.update.settings.inform.label.description')}
/>
<Switch
edge="end"
checked={serverInformAvailableUpdate}
onChange={(e) => updateMetadataServerSettings('serverInformAvailableUpdate', e.target.checked)}
/>
</ListItem>
</List>
),
[serverAddress, serverInformAvailableUpdate],
);
const loading = areMetadataServerSettingsLoading || areServerSettingsLoading;
if (loading) {
return (
<>
{localSettings}
<LoadingPlaceholder />
</>
);
}
const error = metadataServerSettingsError ?? serverSettingsError;
if (error) {
return (
<>
{localSettings}
<EmptyViewAbsoluteCentered
message={t('global.error.label.failed_to_load_data')}
messageExtra={getErrorMessage(error)}
retry={() => {
if (metadataServerSettingsError) {
refetchServerMetadataSettings().catch(
defaultPromiseErrorHandler('ServerSettings::refetchServerMetadataSettings'),
);
}
if (serverSettingsError) {
refetchServerSettings().catch(
defaultPromiseErrorHandler('ServerSettings::refetchServerSettings'),
);
}
}}
/>
</>
);
}
const serverSettings = extractServerSettings(data!.settings);
const authModeDisabled = !serverSettings.authUsername.trim() || !serverSettings.authPassword.trim();
return (
<List sx={{ pt: 0 }}>
{localSettings}
<List
subheader={
<ListSubheader component="div" id="server-settings-server-address">
{t('settings.server.address.server.title')}
</ListSubheader>
}
>
<TextSetting
settingName={t('settings.server.address.server.label.ip')}
handleChange={(ip) => updateSetting('ip', ip)}
value={serverSettings.ip}
placeholder="0.0.0.0"
/>
<NumberSetting
settingTitle={t('settings.server.address.server.label.port')}
settingValue={serverSettings.port.toString()}
handleUpdate={(port) => updateSetting('port', port)}
value={serverSettings.port}
defaultValue={4567}
valueUnit={t('settings.server.address.server.label.port')}
/>
</List>
<List
subheader={
<ListSubheader component="div" id="server-settings-socks-proxy">
{t('settings.server.socks_proxy.title')}
</ListSubheader>
}
>
<ListItem>
<ListItemText primary={t('settings.server.socks_proxy.label.enable')} />
<Switch
edge="end"
checked={serverSettings.socksProxyEnabled}
onChange={(e) => updateSetting('socksProxyEnabled', e.target.checked)}
/>
</ListItem>
<SelectSetting<number>
settingName={t('settings.server.socks_proxy.label.version')}
value={serverSettings.socksProxyVersion}
values={[
[4, { text: '4' }],
[5, { text: '5' }],
]}
handleChange={(socksProxyVersion) => updateSetting('socksProxyVersion', socksProxyVersion)}
/>
<TextSetting
settingName={t('settings.server.socks_proxy.label.host')}
value={serverSettings.socksProxyHost}
handleChange={(proxyHost) => updateSetting('socksProxyHost', proxyHost)}
/>
<TextSetting
settingName={t('settings.server.socks_proxy.label.port')}
value={serverSettings.socksProxyPort}
handleChange={(proxyPort) => updateSetting('socksProxyPort', proxyPort)}
/>
<TextSetting
settingName={t('settings.server.socks_proxy.label.username')}
value={serverSettings.socksProxyUsername}
handleChange={(proxyUsername) => updateSetting('socksProxyUsername', proxyUsername)}
/>
<TextSetting
settingName={t('settings.server.socks_proxy.label.password')}
value={serverSettings.socksProxyPassword}
handleChange={(proxyPassword) => updateSetting('socksProxyPassword', proxyPassword)}
isPassword
/>
</List>
<List
subheader={
<ListSubheader component="div" id="server-settings-auth">
{t('settings.server.auth.title')}
</ListSubheader>
}
>
<SelectSetting<AuthMode>
settingName={t('settings.server.auth.label.title')}
value={serverSettings.authMode}
values={AUTH_MODES_SELECT_VALUES}
handleChange={(mode) => updateSetting('authMode', mode)}
disabled={authModeDisabled}
/>
<TextSetting
settingName={t('settings.server.auth.label.username')}
value={serverSettings.authUsername}
validate={(value) => serverSettings.authMode === AuthMode.None || !!value.trim()}
handleChange={(authUsername) => updateSetting('authUsername', authUsername)}
/>
<TextSetting
settingName={t('settings.server.auth.label.password')}
value={serverSettings.authPassword}
isPassword
validate={(value) => serverSettings.authMode === AuthMode.None || !!value.trim()}
handleChange={(authPassword) => updateSetting('authPassword', authPassword)}
/>
</List>
<List
subheader={
<ListSubheader component="div" id="server-settings-clouadflare-bypass">
{t('settings.server.cloudflare.title')}
</ListSubheader>
}
>
<ListItem>
<ListItemText
primary={t('settings.server.cloudflare.flaresolverr.enabled.label.title')}
secondary={
<Trans i18nKey="settings.server.cloudflare.flaresolverr.enabled.label.description">
See{' '}
<Link
href="https://github.com/FlareSolverr/FlareSolverr?tab=readme-ov-file#installation"
target="_blank"
rel="noreferrer"
>
FlareSolverr
</Link>{' '}
for information on how to set it up
</Trans>
}
/>
<Switch
edge="end"
checked={serverSettings.flareSolverrEnabled}
onChange={(e) => updateSetting('flareSolverrEnabled', e.target.checked)}
/>
</ListItem>
<TextSetting
settingName={t('settings.server.cloudflare.flaresolverr.url.label.title')}
dialogDescription={t('settings.server.cloudflare.flaresolverr.url.label.description')}
value={serverSettings.flareSolverrUrl}
handleChange={(url) => updateSetting('flareSolverrUrl', url)}
/>
<NumberSetting
settingTitle={t('settings.server.cloudflare.flaresolverr.timeout.label.title')}
settingValue={t('global.time.seconds.value', { count: serverSettings.flareSolverrTimeout })}
dialogDescription={t('settings.server.cloudflare.flaresolverr.timeout.label.description')}
value={serverSettings.flareSolverrTimeout}
defaultValue={60}
minValue={20}
maxValue={60 * 5}
stepSize={1}
showSlider
valueUnit={t('global.time.seconds.second_other')}
handleUpdate={(timeout) => updateSetting('flareSolverrTimeout', timeout)}
/>
<TextSetting
settingName={t('settings.server.cloudflare.flaresolverr.session.name.label.title')}
value={serverSettings.flareSolverrSessionName}
handleChange={(sessionName) => updateSetting('flareSolverrSessionName', sessionName)}
/>
<NumberSetting
settingTitle={t('settings.server.cloudflare.flaresolverr.session.ttl.label.title')}
settingValue={t('global.time.minutes.value', { count: serverSettings.flareSolverrSessionTtl })}
dialogDescription={t('settings.server.cloudflare.flaresolverr.session.ttl.label.description')}
value={serverSettings.flareSolverrSessionTtl}
defaultValue={15}
minValue={1}
maxValue={60}
stepSize={1}
showSlider
valueUnit={t('global.time.minutes.minute_other')}
handleUpdate={(sessionTTL) => updateSetting('flareSolverrSessionTtl', sessionTTL)}
/>
<ListItem>
<ListItemText
primary={t('settings.server.cloudflare.flaresolverr.response_fallback.label.title')}
secondary={t('settings.server.cloudflare.flaresolverr.response_fallback.label.description')}
/>
<Switch
edge="end"
checked={serverSettings.flareSolverrAsResponseFallback}
onChange={(e) => updateSetting('flareSolverrAsResponseFallback', e.target.checked)}
/>
</ListItem>
</List>
<List
subheader={
<ListSubheader component="div" id="server-settings-opds">
{t('settings.server.opds.title')}
</ListSubheader>
}
>
<ListItem>
<ListItemText
primary={t('settings.server.opds.binary_file_sizes.label.title')}
secondary={t('settings.server.opds.binary_file_sizes.label.description')}
/>
<Switch
edge="end"
checked={serverSettings.opdsUseBinaryFileSizes}
onChange={(e) => updateSetting('opdsUseBinaryFileSizes', e.target.checked)}
/>
</ListItem>
<NumberSetting
settingTitle={t('settings.server.opds.items_per_page.label.title')}
settingValue={serverSettings.opdsItemsPerPage.toString()}
dialogDescription={t('settings.server.opds.items_per_page.label.description')}
value={serverSettings.opdsItemsPerPage}
defaultValue={50}
minValue={10}
maxValue={5000}
stepSize={10}
showSlider
valueUnit={t('settings.server.opds.items_per_page.label.unit_other')}
handleUpdate={(value) => updateSetting('opdsItemsPerPage', value)}
/>
<ListItem>
<ListItemText
primary={t('settings.server.opds.enable_page_read_progress.label.title')}
secondary={t('settings.server.opds.enable_page_read_progress.label.description')}
/>
<Switch
edge="end"
checked={serverSettings.opdsEnablePageReadProgress}
onChange={(e) => updateSetting('opdsEnablePageReadProgress', e.target.checked)}
/>
</ListItem>
<ListItem>
<ListItemText
primary={t('settings.server.opds.mark_as_read_on_download.label.title')}
secondary={t('settings.server.opds.mark_as_read_on_download.label.description')}
/>
<Switch
edge="end"
checked={serverSettings.opdsMarkAsReadOnDownload}
onChange={(e) => updateSetting('opdsMarkAsReadOnDownload', e.target.checked)}
/>
</ListItem>
<ListItem>
<ListItemText
primary={t('settings.server.opds.show_only_unread_chapters.label.title')}
secondary={t('settings.server.opds.show_only_unread_chapters.label.description')}
/>
<Switch
edge="end"
checked={serverSettings.opdsShowOnlyUnreadChapters}
onChange={(e) => updateSetting('opdsShowOnlyUnreadChapters', e.target.checked)}
/>
</ListItem>
<ListItem>
<ListItemText
primary={t('settings.server.opds.show_only_downloaded_chapters.label.title')}
secondary={t('settings.server.opds.show_only_downloaded_chapters.label.description')}
/>
<Switch
edge="end"
checked={serverSettings.opdsShowOnlyDownloadedChapters}
onChange={(e) => updateSetting('opdsShowOnlyDownloadedChapters', e.target.checked)}
/>
</ListItem>
<SelectSetting<SortOrder>
settingName={t('settings.server.opds.chapter_sort_order.label.title')}
dialogDescription={t('settings.server.opds.chapter_sort_order.label.description')}
value={serverSettings.opdsChapterSortOrder}
values={[
[SortOrder.Asc, { text: t('global.sort.label.asc') }],
[SortOrder.Desc, { text: t('global.sort.label.desc') }],
]}
handleChange={(value) => updateSetting('opdsChapterSortOrder', value)}
/>
</List>
<List
subheader={
<ListSubheader component="div" id="server-settings-misc">
{t('settings.server.misc.title')}
</ListSubheader>
}
>
<ListItem>
<ListItemText primary={t('settings.server.misc.log_level.label.server')} />
<Switch
edge="end"
checked={serverSettings.debugLogsEnabled}
onChange={(e) => updateSetting('debugLogsEnabled', e.target.checked)}
/>
</ListItem>
<ListItem>
<ListItemText
primary={t('settings.server.misc.tray_icon.label.title')}
secondary={t('settings.server.misc.tray_icon.label.description')}
/>
<Switch
edge="end"
checked={serverSettings.systemTrayEnabled}
onChange={(e) => updateSetting('systemTrayEnabled', e.target.checked)}
/>
</ListItem>
<NumberSetting
settingTitle={t('settings.server.misc.log_files.file_cleanup.title')}
settingValue={getLogFilesCleanupDisplayValue(serverSettings.maxLogFiles)}
value={serverSettings.maxLogFiles}
valueUnit={t('global.date.label.day_one')}
handleUpdate={(maxFiles) => updateSetting('maxLogFiles', maxFiles)}
/>
<TextSetting
settingName={t('settings.server.misc.log_files.file_size.title')}
value={serverSettings.maxLogFileSize}
dialogDescription={t('settings.server.misc.log_files.file_size.description')}
validate={(value) => !!value.match(/^[0-9]+(|kb|KB|mb|MB|gb|GB)$/g)}
handleChange={(maxLogFileSize) => updateSetting('maxLogFileSize', maxLogFileSize)}
/>
<TextSetting
settingName={t('settings.server.misc.log_files.total_size.title')}
value={serverSettings.maxLogFolderSize}
dialogDescription={t('settings.server.misc.log_files.total_size.description')}
validate={(value) => !!value.match(/^[0-9]+(|kb|KB|mb|MB|gb|GB)$/g)}
handleChange={(maxLogFolderSize) => updateSetting('maxLogFolderSize', maxLogFolderSize)}
/>
</List>
</List>
);
};

View File

@@ -0,0 +1,129 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import AutoStoriesIcon from '@mui/icons-material/AutoStories';
import List from '@mui/material/List';
import BackupIcon from '@mui/icons-material/Backup';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import ListItemButton from '@mui/material/ListItemButton';
import { useTranslation } from 'react-i18next';
import CollectionsOutlinedBookmarkIcon from '@mui/icons-material/CollectionsBookmarkOutlined';
import GetAppOutlinedIcon from '@mui/icons-material/GetAppOutlined';
import DnsIcon from '@mui/icons-material/Dns';
import WebIcon from '@mui/icons-material/Web';
import DeleteForeverIcon from '@mui/icons-material/DeleteForever';
import ExploreOutlinedIcon from '@mui/icons-material/ExploreOutlined';
import DevicesIcon from '@mui/icons-material/Devices';
import SyncIcon from '@mui/icons-material/Sync';
import PaletteIcon from '@mui/icons-material/Palette';
import HistoryIcon from '@mui/icons-material/History';
import { ListItemLink } from '@/features/core/components/lists/ListItemLink.tsx';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { AppRoutes } from '@/features/core/AppRoute.constants.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { useAppTitle } from '@/features/navigation-bar/hooks/useAppTitle.ts';
export function Settings() {
const { t } = useTranslation();
useAppTitle(t('settings.title'));
const [triggerClearServerCache, { loading: isClearingServerCache }] = requestManager.useClearServerCache();
const clearServerCache = async () => {
try {
await triggerClearServerCache();
makeToast(t('settings.clear_cache.label.success'), 'success');
} catch (e) {
makeToast(t('settings.clear_cache.label.failure'), 'error', getErrorMessage(e));
}
};
return (
<List sx={{ padding: 0 }}>
<ListItemLink to={AppRoutes.settings.childRoutes.appearance.path}>
<ListItemIcon>
<PaletteIcon />
</ListItemIcon>
<ListItemText primary={t('settings.appearance.title')} />
</ListItemLink>
<ListItemLink to={AppRoutes.settings.childRoutes.reader.path}>
<ListItemIcon>
<AutoStoriesIcon />
</ListItemIcon>
<ListItemText primary={t('reader.settings.title.reader')} />
</ListItemLink>
<ListItemLink to={AppRoutes.settings.childRoutes.library.path}>
<ListItemIcon>
<CollectionsOutlinedBookmarkIcon />
</ListItemIcon>
<ListItemText primary={t('library.title')} />
</ListItemLink>
<ListItemLink to={AppRoutes.settings.childRoutes.download.path}>
<ListItemIcon>
<GetAppOutlinedIcon />
</ListItemIcon>
<ListItemText primary={t('download.title.download')} />
</ListItemLink>
<ListItemLink to={AppRoutes.settings.childRoutes.tracking.path}>
<ListItemIcon>
<SyncIcon />
</ListItemIcon>
<ListItemText primary={t('tracking.title')} />
</ListItemLink>
<ListItemLink to={AppRoutes.settings.childRoutes.backup.path}>
<ListItemIcon>
<BackupIcon />
</ListItemIcon>
<ListItemText primary={t('settings.backup.title')} />
</ListItemLink>
<ListItemButton disabled={isClearingServerCache} onClick={clearServerCache}>
<ListItemIcon>
<DeleteForeverIcon />
</ListItemIcon>
<ListItemText
primary={t('settings.clear_cache.label.title')}
secondary={t('settings.clear_cache.label.description')}
/>
</ListItemButton>
<ListItemLink to={AppRoutes.settings.childRoutes.browse.path}>
<ListItemIcon>
<ExploreOutlinedIcon />
</ListItemIcon>
<ListItemText primary={t('global.label.browse')} />
</ListItemLink>
<ListItemLink to={AppRoutes.settings.childRoutes.history.path}>
<ListItemIcon>
<HistoryIcon />
</ListItemIcon>
<ListItemText primary={t('history.title')} />
</ListItemLink>
<ListItemLink to={AppRoutes.settings.childRoutes.device.path}>
<ListItemIcon>
<DevicesIcon />
</ListItemIcon>
<ListItemText primary={t('settings.device.title.device')} />
</ListItemLink>
<ListItemLink to={AppRoutes.settings.childRoutes.webui.path}>
<ListItemIcon>
<WebIcon />
</ListItemIcon>
<ListItemText primary={t('settings.webui.title.webui')} />
</ListItemLink>
<ListItemLink to={AppRoutes.settings.childRoutes.server.path}>
<ListItemIcon>
<DnsIcon />
</ListItemIcon>
<ListItemText primary={t('settings.server.title.server')} />
</ListItemLink>
</List>
);
}

View File

@@ -0,0 +1,171 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { useTranslation } from 'react-i18next';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import Switch from '@mui/material/Switch';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { WebUIUpdateIntervalSetting } from '@/features/settings/components/webUI/WebUIUpdateIntervalSetting.tsx';
import { TextSetting } from '@/features/core/components/settings/text/TextSetting.tsx';
import { SelectSetting } from '@/features/core/components/settings/SelectSetting.tsx';
import { WebUiChannel, WebUiFlavor, WebUiInterface } from '@/lib/graphql/generated/graphql.ts';
import { LoadingPlaceholder } from '@/features/core/components/feedback/LoadingPlaceholder.tsx';
import { EmptyViewAbsoluteCentered } from '@/features/core/components/feedback/EmptyViewAbsoluteCentered.tsx';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import {
createUpdateMetadataServerSettings,
useMetadataServerSettings,
} from '@/features/settings/services/ServerSettingsMetadata.ts';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { MetadataUpdateSettings } from '@/features/app-updates/AppUpdateChecker.types.ts';
import { ServerSettings, WebUISettingsType } from '@/features/settings/Settings.types.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { useAppTitle } from '@/features/navigation-bar/hooks/useAppTitle.ts';
import {
WEB_UI_CHANNEL_SELECT_VALUES,
WEB_UI_FLAVOR_SELECT_VALUES,
WEB_UI_INTERFACE_SELECT_VALUES,
} from '@/features/settings/Settings.constants.ts';
const extractWebUISettings = (settings: ServerSettings): WebUISettingsType => ({
webUIFlavor: settings.webUIFlavor,
initialOpenInBrowserEnabled: settings.initialOpenInBrowserEnabled,
webUIInterface: settings.webUIInterface,
electronPath: settings.electronPath,
webUIChannel: settings.webUIChannel,
webUIUpdateCheckInterval: settings.webUIUpdateCheckInterval,
});
export const WebUISettings = () => {
const { t } = useTranslation();
useAppTitle(t('settings.webui.title.webui'));
const {
settings: { webUIInformAvailableUpdate },
loading: areMetadataServerSettingsLoading,
request: { error: metadataServerSettingsError, refetch: refetchServerMetadataSettings },
} = useMetadataServerSettings();
const updateMetadataServerSettings = createUpdateMetadataServerSettings<
keyof Pick<MetadataUpdateSettings, 'webUIInformAvailableUpdate'>
>((e) => makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e)));
const {
data,
loading: areServerSettingsLoading,
error: serverSettingsError,
refetch: refetchServerSettings,
} = requestManager.useGetServerSettings({
notifyOnNetworkStatusChange: true,
});
const [mutateSettings] = requestManager.useUpdateServerSettings();
const updateSetting = <Setting extends keyof WebUISettingsType>(
setting: Setting,
value: WebUISettingsType[Setting],
) => {
if (setting === 'webUIChannel') {
requestManager.graphQLClient.client.cache.evict({ fieldName: 'checkForWebUIUpdate' });
}
mutateSettings({ variables: { input: { settings: { [setting]: value } } } }).catch((e) =>
makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e)),
);
};
const loading = areMetadataServerSettingsLoading || areServerSettingsLoading;
if (loading) {
return <LoadingPlaceholder />;
}
const error = metadataServerSettingsError ?? serverSettingsError;
if (error) {
return (
<EmptyViewAbsoluteCentered
message={t('global.error.label.failed_to_load_data')}
messageExtra={getErrorMessage(error)}
retry={() => {
if (metadataServerSettingsError) {
refetchServerMetadataSettings().catch(
defaultPromiseErrorHandler('WebUISettings::refetchServerMetadataSettings'),
);
}
if (serverSettingsError) {
refetchServerSettings().catch(
defaultPromiseErrorHandler('WebUISettings::refetchServerSettings'),
);
}
}}
/>
);
}
const webUISettings = extractWebUISettings(data!.settings);
const isCustomWebUI = webUISettings.webUIFlavor === WebUiFlavor.Custom;
return (
<List sx={{ pt: 0 }}>
<SelectSetting<WebUiFlavor>
settingName={t('settings.webui.flavor.label.title')}
value={webUISettings.webUIFlavor}
values={WEB_UI_FLAVOR_SELECT_VALUES}
handleChange={(flavor) => updateSetting('webUIFlavor', flavor)}
/>
<ListItem>
<ListItemText primary={t('settings.webui.label.initial_open_browser')} />
<Switch
edge="end"
checked={webUISettings.initialOpenInBrowserEnabled}
onChange={(e) => updateSetting('initialOpenInBrowserEnabled', e.target.checked)}
/>
</ListItem>
<SelectSetting<WebUiInterface>
settingName={t('settings.webui.interface.label.title')}
value={webUISettings.webUIInterface}
values={WEB_UI_INTERFACE_SELECT_VALUES}
handleChange={(webUIInterface) => updateSetting('webUIInterface', webUIInterface)}
/>
<TextSetting
settingName={t('settings.webui.electron_path.label.title')}
dialogDescription={t('settings.webui.electron_path.label.description')}
value={webUISettings.electronPath}
settingDescription={
webUISettings.electronPath.length ? webUISettings.electronPath : t('global.label.default')
}
handleChange={(path) => updateSetting('electronPath', path)}
/>
<SelectSetting<WebUiChannel>
settingName={t('settings.webui.channel.label.title')}
value={webUISettings.webUIChannel}
values={WEB_UI_CHANNEL_SELECT_VALUES}
handleChange={(channel) => updateSetting('webUIChannel', channel)}
disabled={isCustomWebUI}
/>
<WebUIUpdateIntervalSetting
disabled={isCustomWebUI}
updateCheckInterval={webUISettings.webUIUpdateCheckInterval}
/>
{!webUISettings.webUIUpdateCheckInterval && (
<ListItem>
<ListItemText
primary={t('global.update.settings.inform.label.title')}
secondary={t('global.update.settings.inform.label.description')}
/>
<Switch
edge="end"
checked={webUIInformAvailableUpdate}
onChange={(e) => updateMetadataServerSettings('webUIInformAvailableUpdate', e.target.checked)}
/>
</ListItem>
)}
</List>
);
};

View File

@@ -0,0 +1,76 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { useEffect, useMemo } from 'react';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { requestUpdateServerMetadata } from '@/features/metadata/services/MetadataUpdater.ts';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import { SERVER_SETTINGS_METADATA_DEFAULT } from '@/features/settings/Settings.constants.ts';
import { MetadataServerSettingKeys, MetadataServerSettings } from '@/features/settings/Settings.types.ts';
import { convertFromGqlMeta } from '@/features/metadata/services/MetadataConverter.ts';
import { getMetadataFrom } from '@/features/metadata/services/MetadataReader.ts';
import { AllowedMetadataValueTypes, Metadata } from '@/features/metadata/Metadata.types.ts';
export const convertSettingsToMetadata = (
settings: Partial<MetadataServerSettings>,
): Metadata<string, AllowedMetadataValueTypes> => ({
...settings,
devices: JSON.stringify(settings.devices),
customThemes: JSON.stringify(settings.customThemes),
migrateSortSettings: JSON.stringify(settings.migrateSortSettings),
extensionLanguages: JSON.stringify(settings.extensionLanguages),
sourceLanguages: JSON.stringify(settings.sourceLanguages),
});
const getMetadataServerSettingsWithDefaultFallback = (
meta?: Metadata,
defaultSettings: MetadataServerSettings = SERVER_SETTINGS_METADATA_DEFAULT,
useEffectFn?: typeof useEffect,
): MetadataServerSettings => getMetadataFrom('global', { meta }, defaultSettings, undefined, useEffectFn);
export const useMetadataServerSettings = (): {
metadata?: Metadata;
settings: MetadataServerSettings;
loading: boolean;
request: ReturnType<typeof requestManager.useGetGlobalMeta>;
} => {
const request = requestManager.useGetGlobalMeta({ notifyOnNetworkStatusChange: true });
const { data, loading } = request;
const metadata = useMemo(() => convertFromGqlMeta(data?.metas.nodes), [data?.metas.nodes]);
const tmpSettings = getMetadataServerSettingsWithDefaultFallback(metadata, undefined, useEffect);
const settings = useMemo(() => tmpSettings, [metadata]);
return useMemo(() => ({ metadata, settings, loading, request }), [metadata, settings, loading, request]);
};
export const getMetadataServerSettings = async (): Promise<MetadataServerSettings> => {
const { data, error } = await requestManager.getGlobalMeta().response;
if (error) {
throw error;
}
const metadata = convertFromGqlMeta(data?.metas.nodes);
return getMetadataServerSettingsWithDefaultFallback(metadata);
};
export const updateMetadataServerSettings = async <
Settings extends MetadataServerSettingKeys = MetadataServerSettingKeys,
Setting extends Settings = Settings,
>(
setting: Setting,
value: MetadataServerSettings[Setting],
): Promise<void[]> =>
requestUpdateServerMetadata([[setting, convertSettingsToMetadata({ [setting]: value })[setting]]]);
export const createUpdateMetadataServerSettings =
<Settings extends MetadataServerSettingKeys>(
handleError: (error: any) => void = defaultPromiseErrorHandler('createUpdateMetadataServerSettings'),
): ((...args: Parameters<typeof updateMetadataServerSettings<Settings>>) => Promise<void | void[]>) =>
(setting, value) =>
updateMetadataServerSettings(setting, value).catch(handleError);