#![allow(clippy::ptr_arg)]
use std::collections::{BTreeSet, HashMap};
use tokio::time::sleep;
#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
pub enum Scope {
AppGroupMigration,
}
impl AsRef<str> for Scope {
fn as_ref(&self) -> &str {
match *self {
Scope::AppGroupMigration => "https://www.googleapis.com/auth/apps.groups.migration",
}
}
}
#[allow(clippy::derivable_impls)]
impl Default for Scope {
fn default() -> Scope {
Scope::AppGroupMigration
}
}
#[derive(Clone)]
pub struct GroupsMigration<C> {
pub client: common::Client<C>,
pub auth: Box<dyn common::GetToken>,
_user_agent: String,
_base_url: String,
_root_url: String,
}
impl<C> common::Hub for GroupsMigration<C> {}
impl<'a, C> GroupsMigration<C> {
pub fn new<A: 'static + common::GetToken>(
client: common::Client<C>,
auth: A,
) -> GroupsMigration<C> {
GroupsMigration {
client,
auth: Box::new(auth),
_user_agent: "google-api-rust-client/7.0.0".to_string(),
_base_url: "https://groupsmigration.googleapis.com/".to_string(),
_root_url: "https://groupsmigration.googleapis.com/".to_string(),
}
}
pub fn archive(&'a self) -> ArchiveMethods<'a, C> {
ArchiveMethods { hub: self }
}
pub fn user_agent(&mut self, agent_name: String) -> String {
std::mem::replace(&mut self._user_agent, agent_name)
}
pub fn base_url(&mut self, new_base_url: String) -> String {
std::mem::replace(&mut self._base_url, new_base_url)
}
pub fn root_url(&mut self, new_root_url: String) -> String {
std::mem::replace(&mut self._root_url, new_root_url)
}
}
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Groups {
pub kind: Option<String>,
#[serde(rename = "responseCode")]
pub response_code: Option<String>,
}
impl common::ResponseResult for Groups {}
pub struct ArchiveMethods<'a, C>
where
C: 'a,
{
hub: &'a GroupsMigration<C>,
}
impl<'a, C> common::MethodsBuilder for ArchiveMethods<'a, C> {}
impl<'a, C> ArchiveMethods<'a, C> {
pub fn insert(&self, group_id: &str) -> ArchiveInsertCall<'a, C> {
ArchiveInsertCall {
hub: self.hub,
_group_id: group_id.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
pub struct ArchiveInsertCall<'a, C>
where
C: 'a,
{
hub: &'a GroupsMigration<C>,
_group_id: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ArchiveInsertCall<'a, C> {}
impl<'a, C> ArchiveInsertCall<'a, C>
where
C: common::Connector,
{
async fn doit<RS>(
mut self,
mut reader: RS,
reader_mime_type: mime::Mime,
protocol: common::UploadProtocol,
) -> common::Result<(common::Response, Groups)>
where
RS: common::ReadSeek,
{
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "groupsmigration.archive.insert",
http_method: hyper::Method::POST,
});
for &field in ["alt", "groupId"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(3 + self._additional_params.len());
params.push("groupId", self._group_id);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let (mut url, upload_type) = if protocol == common::UploadProtocol::Simple {
(
self.hub._root_url.clone() + "upload/groups/v1/groups/{groupId}/archive",
"multipart",
)
} else {
unreachable!()
};
params.push("uploadType", upload_type);
if self._scopes.is_empty() {
self._scopes
.insert(Scope::AppGroupMigration.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{groupId}", "groupId")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["groupId"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = if protocol == common::UploadProtocol::Simple {
let size = reader.seek(std::io::SeekFrom::End(0)).unwrap();
reader.seek(std::io::SeekFrom::Start(0)).unwrap();
if size > 26214400 {
return Err(common::Error::UploadSizeLimitExceeded(size, 26214400));
}
let mut bytes = Vec::with_capacity(size as usize);
reader.read_to_end(&mut bytes)?;
req_builder
.header(CONTENT_TYPE, reader_mime_type.to_string())
.header(CONTENT_LENGTH, size)
.body(common::to_body(bytes.into()))
} else {
req_builder.body(common::to_body::<String>(None))
};
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
pub async fn upload<RS>(
self,
stream: RS,
mime_type: mime::Mime,
) -> common::Result<(common::Response, Groups)>
where
RS: common::ReadSeek,
{
self.doit(stream, mime_type, common::UploadProtocol::Simple)
.await
}
pub fn group_id(mut self, new_value: &str) -> ArchiveInsertCall<'a, C> {
self._group_id = new_value.to_string();
self
}
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> ArchiveInsertCall<'a, C> {
self._delegate = Some(new_value);
self
}
pub fn param<T>(mut self, name: T, value: T) -> ArchiveInsertCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
pub fn add_scope<St>(mut self, scope: St) -> ArchiveInsertCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
pub fn add_scopes<I, St>(mut self, scopes: I) -> ArchiveInsertCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
pub fn clear_scopes(mut self) -> ArchiveInsertCall<'a, C> {
self._scopes.clear();
self
}
}