Files
google-apis-rs/gen/admin2_email_migration/src/lib.rs.in
2015-12-06 17:51:06 +01:00

641 lines
26 KiB
Rust

// DO NOT EDIT !
// This file was generated automatically from 'src/mako/api/lib.rs.in.mako'
// DO NOT EDIT !
extern crate hyper;
extern crate serde;
extern crate serde_json;
extern crate yup_oauth2 as oauth2;
extern crate mime;
extern crate url;
mod cmn;
use std::collections::HashMap;
use std::cell::RefCell;
use std::borrow::BorrowMut;
use std::default::Default;
use std::collections::BTreeMap;
use serde_json as json;
use std::io;
use std::fs;
use std::thread::sleep_ms;
pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part,
ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder,
Resource, ErrorResponse, remove_json_null_values};
// ##############
// UTILITIES ###
// ############
/// Identifies the an OAuth2 authorization scope.
/// A scope is needed when requesting an
/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
#[derive(PartialEq, Eq, Hash)]
pub enum Scope {
/// Manage email messages of users on your domain
EmailMigration,
}
impl AsRef<str> for Scope {
fn as_ref(&self) -> &str {
match *self {
Scope::EmailMigration => "https://www.googleapis.com/auth/email.migration",
}
}
}
impl Default for Scope {
fn default() -> Scope {
Scope::EmailMigration
}
}
// ########
// HUB ###
// ######
/// Central instance to access all Admin related resource activities
///
/// # Examples
///
/// Instantiate a new hub
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_admin2_email_migration as admin2_email_migration;
/// use admin2_email_migration::MailItem;
/// use admin2_email_migration::{Result, Error};
/// use std::fs;
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use admin2_email_migration::Admin;
///
/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
/// // `client_secret`, among other things.
/// let secret: ApplicationSecret = Default::default();
/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
/// // unless you replace `None` with the desired Flow.
/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
/// // retrieve them from storage.
/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// hyper::Client::new(),
/// <MemoryStorage as Default>::default(), None);
/// let mut hub = Admin::new(hyper::Client::new(), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = MailItem::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `upload(...)`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.mail().insert(req, "userKey")
/// .upload(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap());
///
/// match result {
/// Err(e) => match e {
/// // The Error enum provides details about what exactly happened.
/// // You can also just use its `Debug`, `Display` or `Error` traits
/// Error::HttpError(_)
/// |Error::MissingAPIKey
/// |Error::MissingToken(_)
/// |Error::Cancelled
/// |Error::UploadSizeLimitExceeded(_, _)
/// |Error::Failure(_)
/// |Error::BadRequest(_)
/// |Error::FieldClash(_)
/// |Error::JsonDecodeError(_, _) => println!("{}", e),
/// },
/// Ok(res) => println!("Success: {:?}", res),
/// }
/// # }
/// ```
pub struct Admin<C, A> {
client: RefCell<C>,
auth: RefCell<A>,
_user_agent: String,
}
impl<'a, C, A> Hub for Admin<C, A> {}
impl<'a, C, A> Admin<C, A>
where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
pub fn new(client: C, authenticator: A) -> Admin<C, A> {
Admin {
client: RefCell::new(client),
auth: RefCell::new(authenticator),
_user_agent: "google-api-rust-client/0.1.10".to_string(),
}
}
pub fn mail(&'a self) -> MailMethods<'a, C, A> {
MailMethods { hub: &self }
}
/// Set the user-agent header field to use in all requests to the server.
/// It defaults to `google-api-rust-client/0.1.10`.
///
/// Returns the previously set user-agent.
pub fn user_agent(&mut self, agent_name: String) -> String {
let prev = self._user_agent.clone();
self._user_agent = agent_name;
prev
}
}
// ############
// SCHEMAS ###
// ##########
/// JSON template for MailItem object in Email Migration API.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [insert mail](struct.MailInsertCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct MailItem {
/// Boolean indicating if the mail is in trash
#[serde(rename="isTrash")]
pub is_trash: Option<bool>,
/// Kind of resource this is.
pub kind: Option<String>,
/// List of labels (strings)
pub labels: Option<Vec<String>>,
/// Boolean indicating if the mail is draft
#[serde(rename="isDraft")]
pub is_draft: Option<bool>,
/// Boolean indicating if the mail is in inbox
#[serde(rename="isInbox")]
pub is_inbox: Option<bool>,
/// Boolean indicating if the mail is in 'sent mails'
#[serde(rename="isSent")]
pub is_sent: Option<bool>,
/// Boolean indicating if the mail is starred
#[serde(rename="isStarred")]
pub is_starred: Option<bool>,
/// Boolean indicating if the mail is unread
#[serde(rename="isUnread")]
pub is_unread: Option<bool>,
/// Boolean indicating if the mail is deleted (used in Vault)
#[serde(rename="isDeleted")]
pub is_deleted: Option<bool>,
}
impl RequestValue for MailItem {}
// ###################
// MethodBuilders ###
// #################
/// A builder providing access to all methods supported on *mail* resources.
/// It is not used directly, but through the `Admin` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_admin2_email_migration as admin2_email_migration;
///
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use admin2_email_migration::Admin;
///
/// let secret: ApplicationSecret = Default::default();
/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// hyper::Client::new(),
/// <MemoryStorage as Default>::default(), None);
/// let mut hub = Admin::new(hyper::Client::new(), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `insert(...)`
/// // to build up your call.
/// let rb = hub.mail();
/// # }
/// ```
pub struct MailMethods<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Admin<C, A>,
}
impl<'a, C, A> MethodsBuilder for MailMethods<'a, C, A> {}
impl<'a, C, A> MailMethods<'a, C, A> {
/// Create a builder to help you perform the following task:
///
/// Insert Mail into Google's Gmail backends
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `userKey` - The email or immutable id of the user
pub fn insert(&self, request: MailItem, user_key: &str) -> MailInsertCall<'a, C, A> {
MailInsertCall {
hub: self.hub,
_request: request,
_user_key: user_key.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
}
// ###################
// CallBuilders ###
// #################
/// Insert Mail into Google's Gmail backends
///
/// A builder for the *insert* method supported by a *mail* resource.
/// It is not used directly, but through a `MailMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_admin2_email_migration as admin2_email_migration;
/// use admin2_email_migration::MailItem;
/// use std::fs;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use admin2_email_migration::Admin;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::new(),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = Admin::new(hyper::Client::new(), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = MailItem::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `upload(...)`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.mail().insert(req, "userKey")
/// .upload(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap());
/// # }
/// ```
pub struct MailInsertCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Admin<C, A>,
_request: MailItem,
_user_key: String,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for MailInsertCall<'a, C, A> {}
impl<'a, C, A> MailInsertCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
fn doit<RS>(mut self, mut reader: RS, reader_mime_type: mime::Mime, protocol: &'static str) -> Result<hyper::client::Response>
where RS: ReadSeek {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "emailMigration.mail.insert",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len()));
params.push(("userKey", self._user_key.to_string()));
for &field in ["userKey"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
let (mut url, upload_type) =
if protocol == "simple" {
("https://www.googleapis.com/upload/email/v2/users/{userKey}/mail".to_string(), "multipart")
} else if protocol == "resumable" {
("https://www.googleapis.com/resumable/upload/email/v2/users/{userKey}/mail".to_string(), "resumable")
} else {
unreachable!()
};
params.push(("uploadType", upload_type.to_string()));
if self._scopes.len() == 0 {
self._scopes.insert(Scope::EmailMigration.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{userKey}", "userKey")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1);
for param_name in ["userKey"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default());
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request);
remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut should_ask_dlg_for_url = false;
let mut upload_url_from_server;
let mut upload_url: Option<String> = None;
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer,
access_token: token.access_token });
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
if should_ask_dlg_for_url && (upload_url = dlg.upload_url()) == () && upload_url.is_some() {
should_ask_dlg_for_url = false;
upload_url_from_server = false;
let url = upload_url.as_ref().and_then(|s| Some(hyper::Url::parse(s).unwrap())).unwrap();
hyper::client::Response::new(url, Box::new(cmn::DummyNetworkStream)).and_then(|mut res| {
res.status = hyper::status::StatusCode::Ok;
res.headers.set(Location(upload_url.as_ref().unwrap().clone()));
Ok(res)
})
} else {
let mut mp_reader: MultiPartReader = Default::default();
let (mut body_reader, content_type) = match protocol {
"simple" => {
mp_reader.reserve_exact(2);
let size = reader.seek(io::SeekFrom::End(0)).unwrap();
reader.seek(io::SeekFrom::Start(0)).unwrap();
if size > 36700160 {
return Err(Error::UploadSizeLimitExceeded(size, 36700160))
}
mp_reader.add_part(&mut request_value_reader, request_size, json_mime_type.clone())
.add_part(&mut reader, size, reader_mime_type.clone());
let mime_type = mp_reader.mime_type();
(&mut mp_reader as &mut io::Read, ContentType(mime_type))
},
_ => (&mut request_value_reader as &mut io::Read, ContentType(json_mime_type.clone())),
};
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Post, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone())
.header(content_type)
.body(&mut body_reader);
upload_url_from_server = true;
if protocol == "resumable" {
req = req.header(cmn::XUploadContentType(reader_mime_type.clone()));
}
dlg.pre_request();
req.send()
}
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep_ms(d.num_milliseconds() as u32);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep_ms(d.num_milliseconds() as u32);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
if protocol == "resumable" {
let size = reader.seek(io::SeekFrom::End(0)).unwrap();
reader.seek(io::SeekFrom::Start(0)).unwrap();
if size > 36700160 {
return Err(Error::UploadSizeLimitExceeded(size, 36700160))
}
let mut client = &mut *self.hub.client.borrow_mut();
let upload_result = {
let url_str = &res.headers.get::<Location>().expect("Location header is part of protocol").0;
if upload_url_from_server {
dlg.store_upload_url(Some(url_str));
}
cmn::ResumableUploadHelper {
client: &mut client.borrow_mut(),
delegate: dlg,
start_at: if upload_url_from_server { Some(0) } else { None },
auth: &mut *self.hub.auth.borrow_mut(),
user_agent: &self.hub._user_agent,
auth_header: auth_header.clone(),
url: url_str,
reader: &mut reader,
media_type: reader_mime_type.clone(),
content_length: size
}.upload()
};
match upload_result {
None => {
dlg.finished(false);
return Err(Error::Cancelled)
}
Some(Err(err)) => {
dlg.finished(false);
return Err(Error::HttpError(err))
}
Some(Ok(upload_result)) => {
res = upload_result;
if !res.status.is_success() {
dlg.store_upload_url(None);
dlg.finished(false);
return Err(Error::Failure(res))
}
}
}
}
let result_value = res;
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Upload media all at once.
/// If the upload fails for whichever reason, all progress is lost.
///
/// * *max size*: 35MB
/// * *multipart*: yes
/// * *valid mime types*: 'message/rfc822'
pub fn upload<RS>(self, stream: RS, mime_type: mime::Mime) -> Result<hyper::client::Response>
where RS: ReadSeek {
self.doit(stream, mime_type, "simple")
}
/// Upload media in a resumable fashion.
/// Even if the upload fails or is interrupted, it can be resumed for a
/// certain amount of time as the server maintains state temporarily.
///
/// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL
/// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate
/// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using
/// `cancel_chunk_upload(...)`.
///
/// * *max size*: 35MB
/// * *multipart*: yes
/// * *valid mime types*: 'message/rfc822'
pub fn upload_resumable<RS>(self, resumeable_stream: RS, mime_type: mime::Mime) -> Result<hyper::client::Response>
where RS: ReadSeek {
self.doit(resumeable_stream, mime_type, "resumable")
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: MailItem) -> MailInsertCall<'a, C, A> {
self._request = new_value;
self
}
/// The email or immutable id of the user
///
/// Sets the *user key* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn user_key(mut self, new_value: &str) -> MailInsertCall<'a, C, A> {
self._user_key = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> MailInsertCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> MailInsertCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::EmailMigration`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T>(mut self, scope: T) -> MailInsertCall<'a, C, A>
where T: AsRef<str> {
self._scopes.insert(scope.as_ref().to_string(), ());
self
}
}