import clsx from 'clsx'; import React, { useEffect, useState } from 'react'; import { RiFolderOpenLine, RiCheckboxCircleFill, RiErrorWarningFill, RiLoader2Line, } from 'react-icons/ri'; import { documentDir, join } from '@tauri-apps/api/path'; import { relaunch } from '@tauri-apps/plugin-process'; import { useEnv } from '@/context/EnvContext'; import { useTranslation } from '@/hooks/useTranslation'; import { useSettingsStore } from '@/store/settingsStore'; import { revealItemInDir } from '@tauri-apps/plugin-opener'; import { DATA_SUBDIR } from '@/services/constants'; import { FileItem } from '@/types/system'; import { getDirPath } from '@/utils/path'; import { formatBytes } from '@/utils/book'; import { getOSPlatform } from '@/utils/misc'; import { getExternalSDCardPath } from '@/utils/bridge'; import { FILE_REVEAL_LABELS, FILE_REVEAL_PLATFORMS } from '@/utils/os'; import { requestStoragePermission } from '@/utils/permission'; import Dialog from '@/components/Dialog'; import Dropdown from '@/components/Dropdown'; import MenuItem from '@/components/MenuItem'; export const setMigrateDataDirDialogVisible = (visible: boolean) => { const dialog = document.getElementById('migrate_data_dir_window'); if (dialog) { const event = new CustomEvent('setDialogVisibility', { detail: { visible }, }); dialog.dispatchEvent(event); } }; type MigrationStatus = 'idle' | 'selecting' | 'migrating' | 'completed' | 'error'; interface MigrationProgress { current: number; total: number; currentFile?: string; } export const MigrateDataWindow = () => { const _ = useTranslation(); const { appService, envConfig } = useEnv(); const { settings, setSettings, saveSettings } = useSettingsStore(); const [isOpen, setIsOpen] = useState(false); const [currentDataDir, setCurrentDataDir] = useState(''); const [newDataDir, setNewDataDir] = useState(''); const [migrationStatus, setMigrationStatus] = useState('idle'); const [migrationProgress, setMigrationProgress] = useState({ current: 0, total: 0, }); const [errorMessage, setErrorMessage] = useState(''); const [filesToMigrate, setFilesToMigrate] = useState([]); const [currentDirFileCount, setCurrentDirFileCount] = useState(''); const [currentDirFileSize, setCurrentDirFileSize] = useState(0); const [androidNewDirs, setAndroidNewDirs] = useState<{ path: string; label: string }[]>([]); useEffect(() => { const handleCustomEvent = (event: CustomEvent) => { setIsOpen(event.detail.visible); if (event.detail.visible) { loadCurrentDataDir(); loadAndroidDirs(); } }; const el = document.getElementById('migrate_data_dir_window'); if (el) { el.addEventListener('setDialogVisibility', handleCustomEvent as EventListener); } return () => { if (el) { el.removeEventListener('setDialogVisibility', handleCustomEvent as EventListener); } }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const loadCurrentDataDir = async () => { try { if (!appService) return; const dataDir = await appService.resolveFilePath('', 'Data'); setCurrentDataDir(dataDir); const files = await appService.readDirectory(dataDir, 'None'); setFilesToMigrate(files); setCurrentDirFileCount(files.length.toLocaleString()); setCurrentDirFileSize(files.reduce((acc, file) => acc + file.size, 0)); } catch (error) { console.error('Error loading current data directory:', error); } }; const loadAndroidDirs = async () => { try { if (appService?.isAndroidApp) { const sdCardPathResponse = await getExternalSDCardPath(); let sdcardDirs = [ { path: '/storage/emulated/0', label: '/sdcard/0' }, { path: '/storage/emulated/0/Books', label: '/sdcard/0/Books' }, { path: '/storage/emulated/0/Documents', label: '/sdcard/0/Documents' }, { path: '/storage/emulated/0/Download', label: '/sdcard/0/Download' }, ]; if (sdCardPathResponse.path) { const externalSdCardPath = sdCardPathResponse.path; sdcardDirs = [ ...sdcardDirs, { path: externalSdCardPath, label: '/sdcard/1' }, { path: `${externalSdCardPath}/Books`, label: '/sdcard/1/Books' }, { path: `${externalSdCardPath}/Documents`, label: '/sdcard/1/Documents' }, { path: `${externalSdCardPath}/Download`, label: '/sdcard/1/Download' }, ]; } const localDocumentDir = await documentDir(); setAndroidNewDirs([ // For Google Play version we won't request permission to access root of /sdcard ...(appService?.distChannel === 'playstore' ? [] : sdcardDirs), { path: localDocumentDir, label: '/sdcard/APPDATA/Documents' }, ]); } } catch (error) { console.error('Error loading app local data directory:', error); } }; const handleSelectNewDir = async () => { setMigrationStatus('selecting'); setErrorMessage(''); try { const selectedDir = await appService?.selectDirectory?.('write'); if (selectedDir) { const newDataDir = await join(selectedDir, DATA_SUBDIR); await appService?.createDir(newDataDir, 'None', true); setNewDataDir(newDataDir); setMigrationStatus('idle'); } else { setMigrationStatus('idle'); } } catch (error) { console.error('Error selecting directory:', error); setErrorMessage(_('Failed to select directory')); setMigrationStatus('error'); } }; const handleSelectedNewDir = async (dir: string) => { setErrorMessage(''); if (!dir.includes('Android/data')) { if (!(await requestStoragePermission())) return; } try { const newDataDir = await join(dir, DATA_SUBDIR); await appService?.createDir(newDataDir, 'None', true); setNewDataDir(newDataDir); setMigrationStatus('idle'); } catch (error) { console.error('Error selecting directory:', error); setErrorMessage(_('Failed to select directory')); setMigrationStatus('error'); } }; const handleStartMigration = async () => { if (!appService || !currentDataDir || !newDataDir || !filesToMigrate.length) return; setMigrationStatus('migrating'); setErrorMessage(''); setMigrationProgress({ current: 0, total: 0 }); try { if (newDataDir === currentDataDir) { throw new Error(_('The new data directory must be different from the current one.')); } // Copy all files to new location for (let i = 0; i < filesToMigrate.length; i++) { const file = filesToMigrate[i]!; setMigrationProgress({ current: i + 1, total: filesToMigrate.length, currentFile: file.path, }); const srcPath = await join(currentDataDir, file.path); const destPath = await join(newDataDir, file.path); await appService.copyFile(srcPath, destPath, 'None'); } // Verify all files copied const filesMigrated = await appService.readDirectory(newDataDir, 'None'); for (const file of filesToMigrate) { if (!filesMigrated.find((f) => f.path === file.path && f.size === file.size)) { throw new Error(`File ${file.path} failed to copy.`); } } // Delete old data directory await appService.deleteDir(currentDataDir, 'None', true); // Update settings for new data directory const customRootDir = getDirPath(newDataDir); await appService.setCustomRootDir(customRootDir); settings.customRootDir = customRootDir; settings.localBooksDir = await appService.resolveFilePath('', 'Books'); setSettings({ ...settings }); await saveSettings(envConfig, settings); // Finalize migration setMigrationStatus('completed'); setCurrentDataDir(newDataDir); setFilesToMigrate([]); setCurrentDirFileCount(''); setCurrentDirFileSize(0); loadCurrentDataDir(); } catch (error) { console.error('Error migrating data:', error); setErrorMessage(_('Migration failed: {{error}}', { error: error || 'Unknown error' })); setMigrationStatus('error'); } }; const handleClose = () => { if (migrationStatus === 'migrating') { return; } setIsOpen(false); setNewDataDir(''); setMigrationStatus('idle'); setErrorMessage(''); setMigrationProgress({ current: 0, total: 0 }); }; const handleRestartApp = () => { relaunch(); }; const handleRevealDir = (dataDir: string) => { if (dataDir && appService?.isDesktopApp) { revealItemInDir(dataDir); } }; const progressPercentage = migrationProgress.total > 0 ? Math.round((migrationProgress.current / migrationProgress.total) * 100) : 0; const canStartMigration = newDataDir && newDataDir !== currentDataDir && migrationStatus === 'idle'; const osPlatform = getOSPlatform(); const fileRevealLabel = FILE_REVEAL_LABELS[osPlatform as FILE_REVEAL_PLATFORMS] || FILE_REVEAL_LABELS.default; return ( {isOpen && (
{/* Current Data Directory */}

{_('Current Data Location')}

{currentDirFileCount ? (

{_('File count: {{size}}', { size: currentDirFileCount })}

{_('Total size: {{size}}', { size: formatBytes(currentDirFileSize) })}

) : (

{_('Calculating file info...')}

)}
{/* New Data Directory Selection */}

{_('New Data Location')}

{newDataDir && ( )} {appService?.isAndroidApp ? ( {newDataDir ? _('Choose Different Folder') : _('Choose New Folder')}
} >
{androidNewDirs.map((dir) => ( handleSelectedNewDir(dir.path)} /> ))}
) : ( )}
{/* Migration Progress */} {migrationStatus === 'migrating' && (
{_('Migrating data...')} {progressPercentage}%
{migrationProgress.currentFile && (

{_('Copying: {{file}}', { file: migrationProgress.currentFile })}

)}

{_('{{current}} of {{total}} files', { current: migrationProgress.current.toLocaleString(), total: migrationProgress.total.toLocaleString(), })}

)} {/* Success State */} {migrationStatus === 'completed' && (
{_('Migration completed successfully!')}

{_( 'Your data has been moved to the new location. Please restart the application to complete the process.', )}

)} {/* Error State */} {migrationStatus === 'error' && errorMessage && (
{_('Migration failed')}

{errorMessage}

)} {/* Warning */} {canStartMigration && (

{_('Important Notice')}

{_( 'This will move all your app data to the new location. Make sure the destination has enough free space.', )}

)} {/* Action Buttons */}
{migrationStatus === 'completed' ? ( <> ) : ( <> )}
)}
); };