|
| 1 | +// src/context/DriveContext.js |
| 2 | + |
| 3 | +import { createContext, useContext, useState, useEffect } from 'react'; |
| 4 | +import { |
| 5 | + cacheDriveFiles, |
| 6 | + getCachedDriveFiles, |
| 7 | + clearDriveCache, |
| 8 | +} from '@/lib/driveCache'; |
| 9 | + |
| 10 | +const DriveContext = createContext(); |
| 11 | + |
| 12 | +export function DriveProvider({ children }) { |
| 13 | + const [isConnected, setIsConnected] = useState(false); |
| 14 | + const [files, setFiles] = useState([]); |
| 15 | + const [isLoading, setIsLoading] = useState(true); |
| 16 | + const [userEmail, setUserEmail] = useState(null); |
| 17 | + |
| 18 | + const syncFiles = async (showNotification = false) => { |
| 19 | + setIsLoading(true); |
| 20 | + try { |
| 21 | + // First, check if we are authenticated and get the user's email |
| 22 | + const authCheckResponse = await fetch('/api/auth/google/me'); |
| 23 | + if (!authCheckResponse.ok) { |
| 24 | + throw new Error('Not authenticated'); |
| 25 | + } |
| 26 | + const userData = await authCheckResponse.json(); |
| 27 | + setUserEmail(userData.email); |
| 28 | + setIsConnected(true); |
| 29 | + |
| 30 | + // If authenticated, then fetch the files |
| 31 | + const filesResponse = await fetch('/api/files/gdrive'); |
| 32 | + if (!filesResponse.ok) throw new Error('Failed to fetch files'); |
| 33 | + const driveFiles = await filesResponse.json(); |
| 34 | + setFiles(driveFiles); |
| 35 | + await cacheDriveFiles(driveFiles); |
| 36 | + } catch (error) { |
| 37 | + // If any step fails, we are not connected |
| 38 | + setIsConnected(false); |
| 39 | + setUserEmail(null); |
| 40 | + // Try to load from cache as a fallback |
| 41 | + const cachedFiles = await getCachedDriveFiles(); |
| 42 | + setFiles(cachedFiles); // Show cached files even if disconnected |
| 43 | + } finally { |
| 44 | + setIsLoading(false); |
| 45 | + } |
| 46 | + }; |
| 47 | + |
| 48 | + useEffect(() => { |
| 49 | + syncFiles(); |
| 50 | + }, []); |
| 51 | + |
| 52 | + const connectToDrive = () => { |
| 53 | + window.location.href = '/api/auth/google/login'; |
| 54 | + }; |
| 55 | + |
| 56 | + const disconnectFromDrive = async () => { |
| 57 | + await fetch('/api/auth/google/logout'); |
| 58 | + await clearDriveCache(); |
| 59 | + setIsConnected(false); |
| 60 | + setUserEmail(null); |
| 61 | + setFiles([]); |
| 62 | + }; |
| 63 | + |
| 64 | + const value = { |
| 65 | + isConnected, |
| 66 | + files, |
| 67 | + isLoading, |
| 68 | + userEmail, |
| 69 | + connectToDrive, |
| 70 | + disconnectFromDrive, |
| 71 | + syncFiles, |
| 72 | + }; |
| 73 | + |
| 74 | + return ( |
| 75 | + <DriveContext.Provider value={value}>{children}</DriveContext.Provider> |
| 76 | + ); |
| 77 | +} |
| 78 | + |
| 79 | +export function useDrive() { |
| 80 | + return useContext(DriveContext); |
| 81 | +} |
0 commit comments