use super::{
Backend,
https::{client, response},
};
use reqwest::blocking::{Client, RequestBuilder};
use serde::Deserialize;
use serde_json::{Value, json};
use std::{
fs::File,
io::{self, Read, Seek, SeekFrom},
path::Path,
sync::Mutex,
time::{Duration, Instant},
};
const API: &str = "https://www.googleapis.com/drive/v3";
const UPLOAD: &str = "https://www.googleapis.com/upload/drive/v3";
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Profile {
#[serde(default)]
access_token: Option<String>,
#[serde(default)]
refresh_token: Option<String>,
#[serde(default)]
client_id: Option<String>,
#[serde(default)]
client_secret: Option<String>,
}
pub(super) struct Drive {
client: Client,
folder: String,
profile: std::path::PathBuf,
token: Mutex<Option<(String, Instant, String)>>,
api: String,
upload: String,
oauth: String,
}
impl Drive {
pub(super) fn new(folder: &str, profile: &Path) -> io::Result<Self> {
Self::at(
folder,
profile,
API,
UPLOAD,
"https://oauth2.googleapis.com/token",
)
}
fn at(folder: &str, path: &Path, api: &str, upload: &str, oauth: &str) -> io::Result<Self> {
let profile: Profile = serde_json::from_reader(File::open(path)?)
.map_err(|_| io::Error::other("invalid Drive OAuth profile"))?;
if profile.access_token.is_none() && profile.refresh_token.is_none() {
return Err(io::Error::other(
"Drive profile requires an access or refresh token",
));
}
let this = Self {
client: client()?,
folder: folder.into(),
profile: path.into(),
token: Mutex::new(None),
api: api.into(),
upload: upload.into(),
oauth: oauth.into(),
};
let metadata: Value = response(
this.auth(
this.client
.get(format!("{}/files/{folder}", this.api))
.query(&[
("fields", "id,mimeType,capabilities(canAddChildren)"),
("supportsAllDrives", "true"),
]),
)?
.send()
.map_err(io::Error::other)?,
)?
.json()
.map_err(io::Error::other)?;
if metadata["mimeType"] != "application/vnd.google-apps.folder"
|| metadata["capabilities"]["canAddChildren"] != true
{
return Err(io::Error::other(
"Drive destination must be a writable folder",
));
}
Ok(this)
}
fn auth(&self, request: RequestBuilder) -> io::Result<RequestBuilder> {
let mut token = self
.token
.lock()
.map_err(|_| io::Error::other("OAuth lock poisoned"))?;
let bytes = std::fs::read(&self.profile)?;
let profile: Profile = serde_json::from_slice(&bytes)
.map_err(|_| io::Error::other("invalid Drive OAuth profile"))?;
let identity = crate::artifact::digest_bytes(&bytes);
if token
.as_ref()
.is_none_or(|(_, until, key)| Instant::now() >= *until || *key != identity)
{
let mut lifetime = Duration::from_secs(3000);
let access = if let Some(refresh) = &profile.refresh_token {
let id = profile
.client_id
.as_deref()
.ok_or_else(|| io::Error::other("Drive refresh requires client_id"))?;
let secret = profile
.client_secret
.as_deref()
.ok_or_else(|| io::Error::other("Drive refresh requires client_secret"))?;
let result: Value = response(
self.client
.post(&self.oauth)
.form(&[
("grant_type", "refresh_token"),
("refresh_token", refresh),
("client_id", id),
("client_secret", secret),
])
.send()
.map_err(io::Error::other)?,
)?
.json()
.map_err(io::Error::other)?;
lifetime = Duration::from_secs(
result["expires_in"]
.as_u64()
.unwrap_or(3600)
.saturating_sub(60)
.max(1),
);
result["access_token"]
.as_str()
.ok_or_else(|| io::Error::other("OAuth response missing access token"))?
.to_owned()
} else {
profile
.access_token
.clone()
.ok_or_else(|| io::Error::other("missing Drive access token"))?
};
*token = Some((access, Instant::now() + lifetime, identity));
}
Ok(request.bearer_auth(&token.as_ref().unwrap().0))
}
fn entries(&self, exact: Option<&str>) -> io::Result<Vec<(String, String)>> {
let mut entries = Vec::new();
let mut page = String::new();
loop {
let mut q = format!(
"'{}' in parents and trashed = false and appProperties has {{ key='workflow' and value='v1' }}",
self.folder
);
if let Some(key) = exact {
let escaped = key.replace('\\', "\\\\").replace('\'', "\\'");
q.push_str(&format!(
" and appProperties has {{ key='key' and value='{escaped}' }}"
));
}
let mut req = self.client.get(format!("{}/files", self.api)).query(&[
("q", q.as_str()),
("fields", "nextPageToken,files(id,appProperties)"),
("pageSize", "1000"),
("supportsAllDrives", "true"),
("includeItemsFromAllDrives", "true"),
]);
if !page.is_empty() {
req = req.query(&[("pageToken", &page)]);
}
let data: Value = response(self.auth(req)?.send().map_err(io::Error::other)?)?
.json()
.map_err(io::Error::other)?;
for f in data["files"]
.as_array()
.ok_or_else(|| io::Error::other("invalid Drive list response"))?
{
if let (Some(id), Some(key)) =
(f["id"].as_str(), f["appProperties"]["key"].as_str())
{
entries.push((key.into(), id.into()));
}
}
match data["nextPageToken"].as_str() {
Some(next) => page = next.into(),
None => break,
}
}
Ok(entries)
}
fn find(&self, key: &str) -> io::Result<Option<String>> {
crate::artifact::validate_key(key)?;
let found = self
.entries(Some(key))?
.into_iter()
.filter(|(k, _)| k == key)
.map(|(_, id)| id)
.collect::<Vec<_>>();
if found.len() > 1 {
return Err(io::Error::other(
"ambiguous Drive logical key; concurrent destination writers are unsupported",
));
}
Ok(found.into_iter().next())
}
}
impl Backend for Drive {
fn read(&self, key: &str) -> io::Result<Box<dyn Read + Send>> {
let id = self
.find(key)?
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Drive object missing"))?;
Ok(Box::new(response(
self.auth(
self.client
.get(format!("{}/files/{id}", self.api))
.query(&[("alt", "media"), ("supportsAllDrives", "true")]),
)?
.send()
.map_err(io::Error::other)?,
)?))
}
fn write(&self, key: &str, path: &Path, create: bool) -> io::Result<()> {
self.upload(key, File::open(path)?, path.metadata()?.len(), create)
}
fn write_stream(
&self,
key: &str,
reader: Box<dyn Read + Send>,
bytes: u64,
create: bool,
) -> io::Result<()> {
self.upload(
key,
super::transfer::WindowReader::new(reader, 8 * 1024 * 1024),
bytes,
create,
)
}
fn remove(&self, key: &str) -> io::Result<()> {
if let Some(id) = self.find(key)? {
response(
self.auth(
self.client
.delete(format!("{}/files/{id}", self.api))
.query(&[("supportsAllDrives", "true")]),
)?
.send()
.map_err(io::Error::other)?,
)?;
}
Ok(())
}
fn list(&self, prefix: &str) -> io::Result<Vec<String>> {
Ok(self
.entries(None)?
.into_iter()
.map(|(k, _)| k)
.filter(|k| k.starts_with(prefix))
.collect())
}
}
impl Drive {
fn upload(
&self,
key: &str,
mut file: impl Read + Seek,
size: u64,
create: bool,
) -> io::Result<()> {
let existing = self.find(key)?;
if create && existing.is_some() {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"Drive object already exists",
));
}
let (id, request) = if let Some(id) = existing {
let request = self.client.patch(format!("{}/files/{id}", self.upload));
(id, request)
} else {
let ids: Value = response(
self.auth(
self.client
.get(format!("{}/files/generateIds", self.api))
.query(&[("count", "1")]),
)?
.send()
.map_err(io::Error::other)?,
)?
.json()
.map_err(io::Error::other)?;
let id = ids["ids"][0]
.as_str()
.ok_or_else(|| io::Error::other("Drive ID allocation failed"))?
.to_owned();
let req=self.client.post(format!("{}/files", self.upload)).json(&json!({"id":id,"name":key,"parents":[self.folder],"appProperties":{"workflow":"staging-v1","key":key}}));
(id, req)
};
let session = response(
self.auth(
request
.query(&[("uploadType", "resumable"), ("supportsAllDrives", "true")])
.header("X-Upload-Content-Type", "application/octet-stream")
.header("X-Upload-Content-Length", size),
)?
.send()
.map_err(io::Error::other)?,
)?;
let location = session
.headers()
.get("location")
.and_then(|h| h.to_str().ok())
.ok_or_else(|| io::Error::other("Drive resumable response lacks Location"))?
.to_owned();
let parsed = reqwest::Url::parse(&location).map_err(io::Error::other)?;
let allowed = reqwest::Url::parse(&self.upload).map_err(io::Error::other)?;
if parsed.origin() != allowed.origin() {
return Err(io::Error::other("unexpected Drive upload session origin"));
}
let mut offset = 0;
let mut failures = 0;
loop {
let len = (size - offset).min(8 * 1024 * 1024) as usize;
let mut chunk = vec![0; len];
file.seek(SeekFrom::Start(offset))?;
file.read_exact(&mut chunk)?;
let range = if size == 0 {
"bytes */0".into()
} else {
format!("bytes {}-{}/{size}", offset, offset + len as u64 - 1)
};
let result = self
.auth(
self.client
.put(&location)
.header("Content-Range", range)
.body(chunk),
)?
.send();
match result {
Ok(r) if r.status().is_success() => break,
Ok(r) if r.status().as_u16() == 308 => {
offset = resume_offset(&r)?;
failures = 0;
}
Ok(r) if !r.status().is_server_error() && r.status().as_u16() != 429 => {
response(r)?;
unreachable!()
}
_ => {
failures += 1;
if failures > 4 {
return Err(io::Error::other(
"Drive resumable upload retry limit reached",
));
}
std::thread::sleep(Duration::from_millis(200 * failures));
let r = self
.auth(
self.client
.put(&location)
.header("Content-Length", "0")
.header("Content-Range", format!("bytes */{size}")),
)?
.send()
.map_err(io::Error::other)?;
if r.status().is_success() {
break;
}
if r.status().as_u16() != 308 {
response(r)?;
} else {
offset = resume_offset(&r)?;
}
}
}
if offset > size {
return Err(io::Error::other("Drive upload offset exceeds file size"));
}
}
response(
self.auth(
self.client
.patch(format!("{}/files/{id}", self.api))
.query(&[("supportsAllDrives", "true")])
.json(&json!({"appProperties":{"workflow":"v1","key":key}})),
)?
.send()
.map_err(io::Error::other)?,
)?;
if create {
match self.find(key) {
Ok(Some(found)) if found == id => {}
_ => {
let _ = self
.auth(self.client.delete(format!("{}/files/{id}", self.api)))
.and_then(|request| request.send().map_err(io::Error::other))
.and_then(response);
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"another Drive object claimed this logical key",
));
}
}
}
Ok(())
}
}
fn resume_offset(response: &reqwest::blocking::Response) -> io::Result<u64> {
match response.headers().get("range") {
None => Ok(0),
Some(h) => h
.to_str()
.ok()
.and_then(|s| s.strip_prefix("bytes=0-"))
.and_then(|s| s.parse::<u64>().ok())
.and_then(|n| n.checked_add(1))
.ok_or_else(|| io::Error::other("invalid Drive resumable Range")),
}
}
#[cfg(test)]
mod tests;