Laravel / Google Drive API重命名文件夹返回403原因字段NotWritable

lztngnrs  于 2023-06-24  发布在  Go
关注(0)|答案(1)|浏览(77)

当我开始调查这个问题时,我感到乐观,因为看起来我不是第一个...
我有一个Laravel应用程序使用Google Drive作为存储。当我使用Storage facade添加/重命名文件时,它可以工作。
要重命名一个文件夹,我使用$googleDriveService->files->update($folder->getId(), $folder),但我得到了一个错误403“* 资源主体包括字段,这是不能直接写的。*”
在Google OAuth 2.0 Playground上,我有以下范围:

这是我的代码

$client_id = env('GOOGLE_DRIVE_CLIENT_ID');
    $client_secret = env('GOOGLE_DRIVE_CLIENT_SECRET');
    $refresh_token = env('GOOGLE_DRIVE_REFRESH_TOKEN');

    /* Instantiate Google Client */
    $googleClient = new GoogleClient();
    $googleClient->setClientId($client_id);
    $googleClient->setClientSecret($client_secret);
    $googleClient->refreshToken($refresh_token);
    $googleClient->addScope([
        Google_Service_Drive::DRIVE,
        Google_Service_Drive::DRIVE_FILE,
        Google_Service_Drive::DRIVE_METADATA
    ]);

    /* Instantiate Google Drive service */
    $googleDriveService = new GoogleDriveService($googleClient);

    function renameFolder($oldName, $newName, $path, $service)
    {
        /* list all folders with $oldName and select the first one matching $path */
        $oldFolder = collect($service->files->listFiles(['q' => "mimeType='application/vnd.google-apps.folder' and name='$oldName'"]))
            ->first(fn($folder) => getFolderPath($folder->getId(), $service) === "$path/$oldName");

        if(!$oldFolder) { return 'folder unknown'; }

        $oldFolder->setName($newName);
        /* this is the line pointed by the error */ $service->files->update($oldFolder->getId(), $oldFolder);

        return compact('oldFolder');

    }

    function getFolderPath($folderId, $service, $delimiter = '/')
    {
        $path = '';
        while ($folderId) {
            $folder = $service->files->get($folderId, ['fields' => 'name, parents']);
            if($folder->name === env('GOOGLE_DRIVE_FOLDER')) { break; }
            $path = $folder->name . $delimiter . $path;
            $folderId = $folder->parents;
        }
        return rtrim($path, $delimiter);
    }

    return renameFolder('old_name', 'new_name', 'path_to_folder', $googleDriveService);

当我用…->files->update(…注解这一行时,我看到了正确的文件夹(我将ID与Google Drive进行了比较),并且名称是正确的。
我也试过$googleDriveService->files->update($folder->getId(), $folder)->execute(),但我不知道还有什么可以尝试...任何想法都欢迎

laawzig2

laawzig21#

感谢Tanaike的评论,我明白了问题来自于

$service->files->update($oldFolder->getId(), $oldFolder);

update方法第二个参数不应该是$oldFolder,而是一个新的元数据对象。
我已经换了

$oldFolder->setName($newName);
$service->files->update($oldFolder->getId(), $oldFolder);

$newMetadata = new GoogleServiceDriveDriveFile(['name' => $newName]);
$service->files->update($oldFolder->getId(), $newMetadata);

而且很有效。

相关问题