All files / src/utils googleDrive.ts

100% Statements 115/115
92.42% Branches 61/66
100% Functions 12/12
100% Lines 111/111

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                          204x 204x             192x 12x     180x   24x 24x                       372x 120x     252x 252x   240x     132x 132x 120x       12x     12x                       48x   48x 48x           36x     36x   36x 12x 12x 12x   24x 24x     12x 12x                         96x   96x     96x 96x 96x     96x               96x             96x 96x 96x 96x     96x 96x 96x 96x     96x       96x   96x   96x                 96x 12x 12x 12x     84x                   48x 48x           36x             12x 12x                       96x 24x     72x 72x     60x   60x 48x             12x 12x   12x                                   60x 12x             48x     48x     48x 48x 24x             24x     24x 12x 12x       24x   24x                       48x 12x           36x 36x 36x   36x           24x                 12x 12x                       96x 12x             84x     84x   84x 12x                 72x 72x             60x     60x 60x   60x 60x 60x 24x 24x   36x       60x         12x 12x          
import { 
  listDriveFiles, 
  refreshAccessToken, 
  getDriveFileInfo, 
  createDriveFolder,
  deleteDriveFile,
  DriveFilesListResponse
} from './oauth'
 
export interface GoogleDriveCredentials {
  clientId: string
  clientSecret: string
  refreshToken: string
}
 
export interface UploadResult {
  id: string
  name: string
  webViewLink?: string
  webContentLink?: string
}
 
export interface FolderInfo {
  id: string
  name: string
  webViewLink: string | null
  createdTime: string
}
 
export interface ListFoldersResult {
  folders: FolderInfo[]
}
 
/**
 * Google OAuth2 APIからアクセストークンを取得
 */
export async function getAccessToken(credentials: GoogleDriveCredentials): Promise<string> {
  try {
    const tokenResponse = await refreshAccessToken({
      clientId: credentials.clientId,
      clientSecret: credentials.clientSecret,
      code: credentials.refreshToken, // refreshAccessToken expects 'code' parameter
      redirectUri: '' // Not used in refresh flow
    })
    
    if (!tokenResponse.access_token) {
      throw new Error('No access token in response')
    }
    
    return tokenResponse.access_token
  } catch (error) {
    console.error('Token refresh failed:', error)
    throw new Error(`Failed to refresh access token: ${error instanceof Error ? error.message : 'Unknown error'}`)
  }
}
 
/**
 * 指定されたフォルダがデフォルトフォルダの配下にあるかを再帰的にチェック
 */
export async function isUnderDefaultFolder(
  folderId: string, 
  defaultFolderId: string, 
  accessToken: string
): Promise<boolean> {
  if (folderId === defaultFolderId) {
    return true
  }
  
  try {
    const data = await getDriveFileInfo(folderId, accessToken, 'parents')
    
    if (!data.parents || data.parents.length === 0) return false
    
    // 各親フォルダを再帰的にチェック
    for (const parentId of data.parents) {
      if (await isUnderDefaultFolder(parentId, defaultFolderId, accessToken)) {
        return true
      }
    }
    
    return false
  } catch {
    /* istanbul ignore next */
    return false
  }
}
 
/**
 * 既存ファイルを検索
 */
export async function findExistingFile(
  fileName: string, 
  parentFolderId: string, 
  accessToken: string
): Promise<string | null> {
  console.log('Searching for existing file:', { fileName, parentFolderId })
  
  try {
    const result = await listDriveFiles({
      parentFolderId,
      accessToken,
      fields: 'files(id,name)'
    })
    
    console.log('Search result:', result)
    
    // Filter by exact name match
    const matchingFiles = result.files.filter(file => file.name === fileName)
    
    if (matchingFiles.length > 0) {
      const fileId = matchingFiles[0].id
      console.log('Found existing file:', fileId)
      return fileId
    } else {
      console.log('No existing file found, will create new')
      return null
    }
  } catch (error) {
    console.error('Search failed:', error)
    return null
  }
}
 
/**
 * ファイルをGoogle Driveにアップロード
 */
export async function uploadFile(
  file: File,
  parentFolderId: string,
  existingFileId: string | null,
  accessToken: string
): Promise<UploadResult> {
  const buffer = await file.arrayBuffer()
  /* istanbul ignore next */
  const fileName = file.name || 'untitled'
  
  // マルチパートフォームデータを手動で作成
  const boundary = '-------314159265358979323846'
  const delimiter = `\r\n--${boundary}\r\n`
  const close_delim = `\r\n--${boundary}--`
  
  // 更新の場合はparentsを含めない
  const metadata = existingFileId 
    ? { name: fileName }
    : { 
        name: fileName,
        parents: [parentFolderId]
      }
  
  const multipartRequestBody = 
    delimiter +
    'Content-Type: application/json\r\n\r\n' +
    JSON.stringify(metadata) +
    delimiter +
    `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n`
  
  // メタデータとファイルデータを結合
  const encoder = new TextEncoder()
  const multipartStart = encoder.encode(multipartRequestBody)
  const multipartEnd = encoder.encode(close_delim)
  const fileData = new Uint8Array(buffer)
  
  // 最終的なボディを作成
  const body = new Uint8Array(multipartStart.length + fileData.length + multipartEnd.length)
  body.set(multipartStart, 0)
  body.set(fileData, multipartStart.length)
  body.set(multipartEnd, multipartStart.length + fileData.length)
  
  // API呼び出し(既存ファイルの場合は更新、新規の場合は作成)
  const apiUrl = existingFileId 
    ? `https://www.googleapis.com/upload/drive/v3/files/${existingFileId}?uploadType=multipart&fields=id,name,webViewLink,webContentLink`
    : 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id,name,webViewLink,webContentLink'
  
  const method = existingFileId ? 'PATCH' : 'POST'
  
  console.log('API call:', { apiUrl, method, existingFileId })
  
  const uploadResponse = await fetch(apiUrl, {
    method: method,
    headers: {
      'Authorization': `Bearer ${accessToken}`,
      'Content-Type': `multipart/related; boundary="${boundary}"`
    },
    body: body
  })
  
  if (!uploadResponse.ok) {
    const errorText = await uploadResponse.text()
    console.error('Drive API Error:', errorText)
    throw new Error(`Failed to upload to Google Drive: ${errorText}`)
  }
  
  return await uploadResponse.json()
}
 
/**
 * Google Driveからフォルダ一覧を取得
 */
export async function listFolders(
  parentFolderId: string,
  accessToken: string
): Promise<FolderInfo[]> {
  try {
    const result = await listDriveFiles({
      parentFolderId,
      accessToken,
      mimeType: 'application/vnd.google-apps.folder'
    })
 
    return result.files.map((folder) => ({
      id: folder.id,
      name: folder.name,
      webViewLink: folder.webViewLink || null,
      createdTime: folder.createdTime || new Date().toISOString()
    }))
  } catch (error) {
    console.error('Drive API Error:', error)
    throw new Error(`Failed to list folders: ${error instanceof Error ? error.message : 'Unknown error'}`)
  }
}
 
/**
 * フォルダの存在と権限を検証
 */
export async function validateFolder(
  folderId: string,
  defaultFolderId: string,
  accessToken: string
): Promise<{ valid: boolean; error?: string; details?: string }> {
  if (!folderId || folderId === defaultFolderId) {
    return { valid: true }
  }
 
  try {
    const folderInfo = await getDriveFileInfo(folderId, accessToken)
    
    // フォルダがデフォルトフォルダの配下にあるかチェック
    const isValidFolder = await isUnderDefaultFolder(folderId, defaultFolderId, accessToken)
    
    if (!isValidFolder) {
      return {
        valid: false,
        error: 'Unauthorized folder access',
        details: `Folder ${folderId} is not under the allowed default folder`
      }
    }
    
    console.log('Using validated parent folder:', folderInfo)
    return { valid: true }
  } catch (error) {
    return {
      valid: false,
      error: 'Invalid folder ID',
      details: `Folder ${folderId} not found`
    }
  }
}
 
/**
 * ファイルアップロードのメインロジック
 */
export async function processFileUpload(
  file: File | null,
  folderId: string,
  overwrite: boolean,
  credentials: GoogleDriveCredentials,
  defaultFolderId: string
): Promise<{ success: boolean; error?: string; details?: string }> {
  if (!file) {
    return {
      success: false,
      error: 'No file provided'
    }
  }
 
  // アクセストークンを取得
  const accessToken = await getAccessToken(credentials)
 
  // デフォルトの親フォルダを設定し、存在を検証
  const parentFolderId = folderId || defaultFolderId
  
  // フォルダ検証
  const folderValidation = await validateFolder(parentFolderId, defaultFolderId, accessToken)
  if (!folderValidation.valid) {
    return {
      success: false,
      error: folderValidation.error!,
      details: folderValidation.details
    }
  }
  
  let existingFileId = null
  
  // ファイルが存在し、上書きが要求された場合のチェック
  if (overwrite) {
    const fileName = file.name || 'untitled'
    existingFileId = await findExistingFile(fileName, parentFolderId, accessToken)
  }
  
  // ファイルをアップロード
  await uploadFile(file, parentFolderId, existingFileId, accessToken)
 
  return { success: true }
}
 
/**
 * フォルダ作成のメインロジック
 */
export async function createFolder(
  name: string | null,
  parentId: string,
  credentials: GoogleDriveCredentials,
  defaultFolderId: string
): Promise<{ success: boolean; folder?: any; error?: string; details?: string }> {
  if (!name) {
    return {
      success: false,
      error: 'Folder name is required'
    }
  }
 
  try {
    const accessToken = await getAccessToken(credentials)
    const parentFolderId = parentId || defaultFolderId
 
    const folder = await createDriveFolder({
      name,
      parentId: parentFolderId,
      accessToken
    })
 
    return {
      success: true,
      folder: {
        id: folder.id,
        name: folder.name,
        webViewLink: folder.webViewLink
      }
    }
  } catch (error) {
    console.error('Drive API Error:', error)
    throw new Error(`Failed to create folder: ${error instanceof Error ? error.message : 'Unknown error'}`)
  }
}
 
/**
 * フォルダコンテンツ削除のメインロジック
 */
export async function deleteFolderContents(
  folderId: string | null,
  credentials: GoogleDriveCredentials,
  defaultFolderId: string
): Promise<{ success: boolean; message: string; error?: string; details?: string }> {
  if (!folderId) {
    return {
      success: false,
      error: 'Folder ID is required',
      message: ''
    }
  }
 
  const accessToken = await getAccessToken(credentials)
 
  // フォルダ検証
  const isUnderDefault = await isUnderDefaultFolder(folderId, defaultFolderId, accessToken)
  
  if (!isUnderDefault) {
    return {
      success: false,
      error: 'Unauthorized folder access',
      details: `Folder ${folderId} is not under the allowed default folder`,
      message: ''
    }
  }
 
  // Get all files in the folder (not folders)
  try {
    const result = await listDriveFiles({
      parentFolderId: folderId,
      accessToken,
      fields: 'files(id,name,mimeType)'
    })
    
    // Filter out folders
    const files = result.files.filter(file => !file.mimeType || file.mimeType !== 'application/vnd.google-apps.folder')
 
    // Delete all files (not folders)
    let deletedCount = 0
    let errors = []
 
    for (const file of files) {
      try {
        await deleteDriveFile(file.id, accessToken)
        deletedCount++
        console.log(`Deleted file: ${file.name} (${file.id})`)
      } catch (error) {
        errors.push(`Error deleting ${file.name}: ${error instanceof Error ? error.message : 'Unknown error'}`)
      }
    }
 
    return {
      success: true,
      message: `Deleted ${deletedCount} files from folder. ${errors.length > 0 ? `Errors: ${errors.length}` : ''}`
    }
  } catch (error) {
    console.error('Drive API Error:', error)
    throw new Error(`Failed to list folder contents: ${error instanceof Error ? error.message : 'Unknown error'}`)
  }
}