Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 61 additions & 5 deletions crates/utopia-server/src/google_drive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ pub const DRIVE_SCOPE: &str = "https://www.googleapis.com/auth/drive.readonly";
pub const SCOPES: &str = "openid email https://www.googleapis.com/auth/drive.readonly";

const FOLDER_MIME: &str = "application/vnd.google-apps.folder";
const SHORTCUT_MIME: &str = "application/vnd.google-apps.shortcut";
/// 一个文件要用到的元数据,列表与快捷方式的目标都取这些
const FILE_FIELDS: &str = "id,name,mimeType,modifiedTime,md5Checksum,size";

/// 一次遍历最多列多少个文件。列表只是元数据,标记没变的文件不下载,所以这里放得宽;
/// 它只防一棵大得离谱的树把内存撑爆。到了这个数,这一轮说出来,不报成功
Expand Down Expand Up @@ -317,8 +320,10 @@ pub struct Listing {
/// 选中却打不开的文件夹(删了、或不再共享给这个人)。有它时不对账:
/// 打不开不等于里面的东西都没了
pub unreachable: Vec<String>,
/// 跳过的文件,每个一句原因:表单、快捷方式、超大的
/// 跳过的文件,每个一句原因:表单、超大的
pub skipped: usize,
/// 指向这个人打不开的文件的快捷方式(没共享给他、删了),按快捷方式的名字
pub broken_shortcuts: Vec<String>,
}

/// 读一个文件拿到的字节
Expand Down Expand Up @@ -575,13 +580,31 @@ impl Drive {
}
let q = format!("'{folder}' in parents and trashed = false");
let room = MAX_FILES_LISTED.saturating_sub(listing.files.len()) + MAX_FOLDERS_LISTED;
let (items, cut) = self
.list(&q, "id,name,mimeType,modifiedTime,md5Checksum,size", room)
.await?;
let fields = format!("{FILE_FIELDS},shortcutDetails(targetId,targetMimeType)");
let (items, cut) = self.list(&q, &fields, room).await?;
if cut {
listing.truncated = true;
}
for f in items {
for item in items {
// 别人组织的会议,纪要与转写住在他的 Drive 里,这边的文件夹里只有快捷方式:
// 换成它指向的那一个,之后与普通文件一样
let f = if item["mimeType"] == SHORTCUT_MIME {
match self.shortcut_target(&item).await {
Ok(Some(target)) => target,
Ok(None) => {
listing.skipped += 1;
continue;
}
Err(e) if is_inaccessible(&e) => {
let name = item["name"].as_str().unwrap_or("a shortcut");
listing.broken_shortcuts.push(name.to_string());
continue;
}
Err(e) => return Err(e),
}
} else {
item
};
let (Some(id), Some(name), Some(mime)) =
(f["id"].as_str(), f["name"].as_str(), f["mimeType"].as_str())
else {
Expand Down Expand Up @@ -630,6 +653,33 @@ impl Drive {
Ok(listing)
}

/// 快捷方式指向的那一个。指向文件夹的照文件夹走;指向文件的取目标自己的元数据,
/// 变更标记、大小、导出格式都按目标算,文件也按目标的 id 认(直接选到与经快捷方式
/// 到达的是同一份)。目标在回收站里 → `None`;打不开 → 403/404 的错误
async fn shortcut_target(&self, shortcut: &Value) -> anyhow::Result<Option<Value>> {
let details = &shortcut["shortcutDetails"];
let Some(target) = details["targetId"].as_str().filter(|id| valid_id(id)) else {
return Ok(None);
};
if details["targetMimeType"] == FOLDER_MIME {
return Ok(Some(serde_json::json!({
"id": target,
"name": shortcut["name"],
"mimeType": FOLDER_MIME,
})));
}
let url = format!("{}/files/{target}", self.api_root);
let fields = format!("{FILE_FIELDS},trashed");
let v = self
.get_json(
"files.get",
&url,
&[("fields", fields.as_str()), ("supportsAllDrives", "true")],
)
.await?;
Ok((v["trashed"].as_bool() != Some(true)).then_some(v))
}

/// 选中的这个还在不在:在且没进回收站 → true;进了回收站 → false;
/// 打不开 → 404 的错误。`root` 是「我的云端硬盘」,共享盘的 id 也能当文件夹用
async fn folder_is_open(&self, id: &str) -> anyhow::Result<bool> {
Expand Down Expand Up @@ -708,6 +758,12 @@ fn is_not_found(e: &anyhow::Error) -> bool {
.is_some_and(|d| d.status == StatusCode::NOT_FOUND)
}

/// 打不开:Drive 对没共享给这个人的文件有时回 404,有时回 403
fn is_inaccessible(e: &anyhow::Error) -> bool {
e.downcast_ref::<DriveError>()
.is_some_and(|d| d.status == StatusCode::NOT_FOUND || d.status == StatusCode::FORBIDDEN)
}

/// 读一个限了体积的响应体。先看 Content-Length,再边读边数
async fn read_capped(mut resp: reqwest::Response, limit: u64) -> anyhow::Result<Vec<u8>> {
if resp.content_length().is_some_and(|n| n > limit) {
Expand Down
88 changes: 88 additions & 0 deletions crates/utopia-server/src/google_drive_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,94 @@ async fn a_walk_descends_skips_what_cannot_be_read_and_counts_each_file_once() -
Ok(())
}

/// 别人组织的会议:文件夹里只有快捷方式,纪要住在组织者的 Drive 里。
/// 指向文件的按目标收(目标自己的标记与时间),指向文件夹的往里走;
/// 同一个目标既被直接选到、又经快捷方式到达,只收一次
#[tokio::test]
async fn a_shortcut_brings_in_what_it_points_to() -> anyhow::Result<()> {
let server = MockServer::start().await;
mount_folder(&server, "meeting", false).await;
mount_folder(&server, "theirs", false).await;
mount_children(
&server,
"meeting",
json!([
{"id": "s1", "name": "Notes by Gemini", "mimeType": SHORTCUT_MIME,
"shortcutDetails": {"targetId": "notes1",
"targetMimeType": "application/vnd.google-apps.document"}},
{"id": "s2", "name": "Recordings", "mimeType": SHORTCUT_MIME,
"shortcutDetails": {"targetId": "theirs", "targetMimeType": FOLDER_MIME}}
]),
)
.await;
mount_children(
&server,
"theirs",
json!([
{"id": "notes1", "name": "Notes by Gemini", "mimeType": "application/vnd.google-apps.document",
"modifiedTime": "2026-10-20T10:00:00.000Z"},
{"id": "t1", "name": "Transcript", "mimeType": "application/vnd.google-apps.document",
"modifiedTime": "2026-10-20T10:05:00.000Z"}
]),
)
.await;
Mock::given(method("GET"))
.and(path("/files/notes1"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"id": "notes1", "name": "Notes by Gemini",
"mimeType": "application/vnd.google-apps.document",
"modifiedTime": "2026-10-20T10:00:00.000Z", "trashed": false
})))
.mount(&server)
.await;

let listing = drive(&server).walk(&["meeting".to_string()]).await?;
let files: Vec<(&str, String)> = listing
.files
.iter()
.map(|f| (f.id.as_str(), f.marker()))
.collect();
assert_eq!(
files,
[
("notes1", "2026-10-20T10:00:00.000Z".to_string()),
("t1", "2026-10-20T10:05:00.000Z".to_string())
]
);
Ok(())
}

/// 快捷方式指向的文件没共享给这个人:点名,不当作「没东西」
#[tokio::test]
async fn a_shortcut_to_a_file_the_person_cannot_open_is_named() -> anyhow::Result<()> {
let server = MockServer::start().await;
mount_folder(&server, "meeting", false).await;
mount_children(
&server,
"meeting",
json!([
{"id": "s1", "name": "Transcript", "mimeType": SHORTCUT_MIME,
"shortcutDetails": {"targetId": "private1",
"targetMimeType": "application/vnd.google-apps.document"}}
]),
)
.await;
Mock::given(method("GET"))
.and(path("/files/private1"))
.respond_with(ResponseTemplate::new(404).set_body_json(json!({
"error": {"message": "File not found: private1."}
})))
.mount(&server)
.await;

let listing = drive(&server).walk(&["meeting".to_string()]).await?;
assert_eq!(
(listing.files.len(), listing.broken_shortcuts),
(0, vec!["Transcript".to_string()])
);
Ok(())
}

/// 选中的文件夹打不开(删了、或不再共享)不是错误,但要点名——同步据此不对账
#[tokio::test]
async fn an_unreachable_folder_is_named_not_fatal() -> anyhow::Result<()> {
Expand Down
13 changes: 13 additions & 0 deletions crates/utopia-server/src/ingest_sources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1667,6 +1667,19 @@ async fn sync_google_drive(state: &AppState, source: &Source) -> anyhow::Result<
.join("; ")
));
}
if !listing.broken_shortcuts.is_empty() {
gaps.push(format!(
"{} shortcut(s) point to files the connected account cannot open: {}",
listing.broken_shortcuts.len(),
listing
.broken_shortcuts
.iter()
.take(3)
.map(String::as_str)
.collect::<Vec<_>>()
.join("; ")
));
}
if listing.truncated {
gaps.push(
"the folders go deeper or hold more files than one walk lists, so the rest were not looked at"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ Every existing connector is configured with a key an administrator pastes in. Dr

7. **The cap is on downloads, not on the listing.** A run downloads or exports at most 2000 files, the same order as WebDAV and object storage. The listing is metadata only and unchanged files cost nothing (decision 9), so it is bounded only by a guard of 50,000 files, 16 levels and 32 MB per file. A run that hits the download cap fails with how many files wait, and the next run starts where it stopped, because the files it already took now match their markers. A listing cut at the same place every time would never reach the tail (the gap in #1212). Every limit that is hit is reported, and none of them is reported as success.

8. **Google formats are exported to Office formats.** Docs become DOCX, Sheets XLSX and Slides PPTX, and the existing parsers read them with headings, tables and every sheet. Plain text or CSV would have lost the headings that 0039's chunks and 0064's section dates depend on, and CSV keeps only the first sheet. Forms, drawings, shortcuts and sites have no readable body and are skipped. Everything else is downloaded as bytes with `application/octet-stream`, because the parser trusts magic bytes over names, as object storage already does.
8. **Google formats are exported to Office formats.** Docs become DOCX, Sheets XLSX and Slides PPTX, and the existing parsers read them with headings, tables and every sheet. Plain text or CSV would have lost the headings that 0039's chunks and 0064's section dates depend on, and CSV keeps only the first sheet. Forms, drawings and sites have no readable body and are skipped. A shortcut is followed to what it points at: a folder is walked, and a file is taken with its own metadata, marker and id, so a file reached directly and through a shortcut is one document. This matters for meetings someone else organised, whose notes and transcripts live in the organiser's Drive and reach the person only as shortcuts. A shortcut to a file the connected account cannot open is named in the run's result, which is reported as failed, not as an empty success. Everything else is downloaded as bytes with `application/octet-stream`, because the parser trusts magic bytes over names, as object storage already does.

9. **Change is detected from Drive's marker, not from the bytes.** An export of an unchanged Doc is a new zip with new timestamps, so a content hash changes on every run, and every run would re-extract every Doc. `google_drive_files` keeps one marker per file: `md5Checksum` for binary files, and `modifiedTime` for Google formats, which have no checksum. When the marker is unchanged and the document is live, the file is not downloaded at all.

Expand Down
Loading