如何使用尽可能少的 API 调用获取给定文件夹子树中每个文件和文件夹的基本信息(至少 ID、标题、mime 类型)?IE。不调用 api 下载每个子文件夹的详细信息?
我找到了一种解决方法来读取具有一些非分层特征(例如所有者)的所有文件并在客户端脚本中构建树结构。不幸的是,我的文件都来自一个所有者(应用程序),所以我不能这样做。
好的,这里是递归多 API 调用方式的示例代码,这对于某些用例来说已经足够了。但我想找到更好的概念(不是讨论这个实现,而是另一种方式,如何不为每个文件夹调用 API):
class Foo {
const FOLDER_MIME_TYPE = 'application/vnd.google-apps.folder';
public function getSubtreeForFolder($parentId, $sort=true)
{
$service = $this->createCrmGService();
// A. folder info
$file = $service->files->get($parentId);
$ret = array(
'id' => $parentId,
'name' => $file->getTitle(),
'description' => $file->getDescription(),
'mimetype' => $file->getMimeType(),
'is_folder' => true,
'children' => array(),
'node' => $file,
);
if ($ret['mimetype'] != self::FOLDER_MIME_TYPE) {
throw new Exception(_t("{$ret['name']} is not a folder."));
}
$items = $this->findAllFiles($queryString='trashed = false', $parentId, $fieldsFilter='items(alternateLink,description,fileSize,id,mimeType,title)', $service);
foreach ($items as $child)
{
if ($this->isFolder($child))
{
$ret['children'][] = $this->getSubtreeForFolder($child->id, $sort);
}
else
{
// B. file info
$a['id'] = $child->id;
$a['name'] = $child->title;
$a['description'] = $child->description;
$a['is_folder'] = false;
$a['url'] = $file->getDownloadUrl();
$a['url_detail'] = $child->getAlternateLink();
$a['versionLabel'] = false; //FIXME
$a['node'] = $child;
if (!$a['versionLabel']) {
$a['versionLabel'] = '1.0'; //old files compatibility hack
}
$ret['children'][] = $a;
}
}
if ($sort && isset($ret['children']))
{
if ($sort === true) {
$sort = create_function('$a, $b', 'if ($a[\'name\'] == $b[\'name\']) return 0; return strcasecmp($a[\'name\'], $b[\'name\']);');
}
usort($ret['children'], $sort);
}
return $ret;
}
public function findAllFiles($queryString, $parentId=false, $fieldsFilter='items(id,title)', $service = false)
{
if (!$service) $service = $this->createCrmGService();
$result = array();
$pageToken = NULL;
if ($parentId) {
$queryString .= ($queryString ? ' AND ' : '') . "'{$parentId}' in parents";
}
do {
try {
$parameters = array('q' => $queryString);
if ($fieldsFilter) $parameters['fields'] = $fieldsFilter;
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
/**
* @param Google_DriveFile $file
* @return boolean, jestli je $file slozka.
*/
protected function isFolder($file)
{
return $file->getMimeType() == self::FOLDER_MIME_TYPE;
}
}