diff --git a/app/api/nextcloud/status/route.ts b/app/api/nextcloud/status/route.ts index 260bba7d..e07dbafd 100644 --- a/app/api/nextcloud/status/route.ts +++ b/app/api/nextcloud/status/route.ts @@ -52,6 +52,21 @@ async function parseXMLResponse(response: Response): Promise { async function createFolder(nextcloudUrl: string, username: string, password: string, folderPath: string) { try { + // First check if folder exists + const checkResponse = await fetch(`${nextcloudUrl}/remote.php/dav/files/${encodeURIComponent(username)}/${encodeURIComponent(folderPath)}`, { + method: 'PROPFIND', + headers: { + 'Authorization': `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`, + 'Depth': '0', + }, + }); + + if (checkResponse.ok) { + console.log(`Folder ${folderPath} already exists`); + return; + } + + // If folder doesn't exist, create it const response = await fetch(`${nextcloudUrl}/remote.php/dav/files/${encodeURIComponent(username)}/${encodeURIComponent(folderPath)}`, { method: 'MKCOL', headers: { @@ -86,7 +101,8 @@ async function ensureFolderStructure(nextcloudUrl: string, username: string, pas await createFolder(nextcloudUrl, username, password, 'Private/Health'); } catch (error) { console.error('Error creating folder structure:', error); - throw error; + // Don't throw the error, just log it + // This way we don't trigger password regeneration } } @@ -110,17 +126,13 @@ async function getWebDAVCredentials(nextcloudUrl: string, username: string, admi }); if (verifyResponse.ok) { - try { - // Ensure required folders exist - await ensureFolderStructure(nextcloudUrl, username, credentials.password); - return credentials.password; - } catch (folderError) { - console.error('Failed to create folders with existing credentials:', folderError); - // If folder creation fails, we'll try with new credentials - } + // Try to create folders, but don't fail if it doesn't work + await ensureFolderStructure(nextcloudUrl, username, credentials.password); + return credentials.password; } - // If verification failed or folder creation failed, delete the old credentials + // Only delete credentials if verification actually failed + console.log('Credentials verification failed, deleting old credentials'); await prisma.webDAVCredentials.delete({ where: { userId }, }); @@ -169,7 +181,7 @@ async function getWebDAVCredentials(nextcloudUrl: string, username: string, admi }, }); - // Create required folder structure + // Try to create folders, but don't fail if it doesn't work await ensureFolderStructure(nextcloudUrl, username, newPassword); return newPassword;