use std::collections::HashMap;
use std::cell::RefCell;
use std::default::Default;
use std::collections::BTreeMap;
use serde_json as json;
use std::io;
use std::fs;
use std::mem;
use std::thread::sleep;

use crate::client;

// ##############
// 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 your YouTube account
    Full,

    /// See a list of your current active channel members, their current level, and when they became a member
    ChannelMembershipCreator,

    /// See, edit, and permanently delete your YouTube videos, ratings, comments and captions
    ForceSsl,

    /// View your YouTube account
    Readonly,

    /// Manage your YouTube videos
    Upload,

    /// View and manage your assets and associated content on YouTube
    Partner,

    /// View private information of your YouTube channel relevant during the audit process with a YouTube partner
    PartnerChannelAudit,
}

impl AsRef<str> for Scope {
    fn as_ref(&self) -> &str {
        match *self {
            Scope::Full => "https://www.googleapis.com/auth/youtube",
            Scope::ChannelMembershipCreator => "https://www.googleapis.com/auth/youtube.channel-memberships.creator",
            Scope::ForceSsl => "https://www.googleapis.com/auth/youtube.force-ssl",
            Scope::Readonly => "https://www.googleapis.com/auth/youtube.readonly",
            Scope::Upload => "https://www.googleapis.com/auth/youtube.upload",
            Scope::Partner => "https://www.googleapis.com/auth/youtubepartner",
            Scope::PartnerChannelAudit => "https://www.googleapis.com/auth/youtubepartner-channel-audit",
        }
    }
}

impl Default for Scope {
    fn default() -> Scope {
        Scope::Readonly
    }
}



// ########
// HUB ###
// ######

/// Central instance to access all YouTube related resource activities
///
/// # Examples
///
/// Instantiate a new hub
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// use youtube3::{Result, Error};
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and 
/// // `client_secret`, among other things.
/// let secret: oauth2::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 = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.videos().list(&vec!["gubergren".into()])
///              .video_category_id("rebum.")
///              .region_code("est")
///              .page_token("ipsum")
///              .on_behalf_of_content_owner("ipsum")
///              .my_rating("est")
///              .max_width(-62)
///              .max_results(84)
///              .max_height(-99)
///              .locale("Lorem")
///              .add_id("eos")
///              .hl("labore")
///              .chart("sed")
///              .doit().await;
/// 
/// 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::Io(_)
///         |Error::MissingAPIKey
///         |Error::MissingToken(_)
///         |Error::Cancelled
///         |Error::UploadSizeLimitExceeded(_, _)
///         |Error::Failure(_)
///         |Error::BadRequest(_)
///         |Error::FieldClash(_)
///         |Error::JsonDecodeError(_, _) => println!("{}", e),
///     },
///     Ok(res) => println!("Success: {:?}", res),
/// }
/// # }
/// ```
#[derive(Clone)]
pub struct YouTube<> {
    pub client: hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>,
    pub auth: oauth2::authenticator::Authenticator<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>>,
    _user_agent: String,
    _base_url: String,
    _root_url: String,
}

impl<'a, > client::Hub for YouTube<> {}

impl<'a, > YouTube<> {

    pub fn new(client: hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>, authenticator: oauth2::authenticator::Authenticator<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>>) -> YouTube<> {
        YouTube {
            client,
            auth: authenticator,
            _user_agent: "google-api-rust-client/3.1.0".to_string(),
            _base_url: "https://youtube.googleapis.com/".to_string(),
            _root_url: "https://youtube.googleapis.com/".to_string(),
        }
    }

    pub fn abuse_reports(&'a self) -> AbuseReportMethods<'a> {
        AbuseReportMethods { hub: &self }
    }
    pub fn activities(&'a self) -> ActivityMethods<'a> {
        ActivityMethods { hub: &self }
    }
    pub fn captions(&'a self) -> CaptionMethods<'a> {
        CaptionMethods { hub: &self }
    }
    pub fn channel_banners(&'a self) -> ChannelBannerMethods<'a> {
        ChannelBannerMethods { hub: &self }
    }
    pub fn channel_sections(&'a self) -> ChannelSectionMethods<'a> {
        ChannelSectionMethods { hub: &self }
    }
    pub fn channels(&'a self) -> ChannelMethods<'a> {
        ChannelMethods { hub: &self }
    }
    pub fn comment_threads(&'a self) -> CommentThreadMethods<'a> {
        CommentThreadMethods { hub: &self }
    }
    pub fn comments(&'a self) -> CommentMethods<'a> {
        CommentMethods { hub: &self }
    }
    pub fn i18n_languages(&'a self) -> I18nLanguageMethods<'a> {
        I18nLanguageMethods { hub: &self }
    }
    pub fn i18n_regions(&'a self) -> I18nRegionMethods<'a> {
        I18nRegionMethods { hub: &self }
    }
    pub fn live_broadcasts(&'a self) -> LiveBroadcastMethods<'a> {
        LiveBroadcastMethods { hub: &self }
    }
    pub fn live_chat_bans(&'a self) -> LiveChatBanMethods<'a> {
        LiveChatBanMethods { hub: &self }
    }
    pub fn live_chat_messages(&'a self) -> LiveChatMessageMethods<'a> {
        LiveChatMessageMethods { hub: &self }
    }
    pub fn live_chat_moderators(&'a self) -> LiveChatModeratorMethods<'a> {
        LiveChatModeratorMethods { hub: &self }
    }
    pub fn live_streams(&'a self) -> LiveStreamMethods<'a> {
        LiveStreamMethods { hub: &self }
    }
    pub fn members(&'a self) -> MemberMethods<'a> {
        MemberMethods { hub: &self }
    }
    pub fn memberships_levels(&'a self) -> MembershipsLevelMethods<'a> {
        MembershipsLevelMethods { hub: &self }
    }
    pub fn playlist_items(&'a self) -> PlaylistItemMethods<'a> {
        PlaylistItemMethods { hub: &self }
    }
    pub fn playlists(&'a self) -> PlaylistMethods<'a> {
        PlaylistMethods { hub: &self }
    }
    pub fn search(&'a self) -> SearchMethods<'a> {
        SearchMethods { hub: &self }
    }
    pub fn subscriptions(&'a self) -> SubscriptionMethods<'a> {
        SubscriptionMethods { hub: &self }
    }
    pub fn super_chat_events(&'a self) -> SuperChatEventMethods<'a> {
        SuperChatEventMethods { hub: &self }
    }
    pub fn tests(&'a self) -> TestMethods<'a> {
        TestMethods { hub: &self }
    }
    pub fn third_party_links(&'a self) -> ThirdPartyLinkMethods<'a> {
        ThirdPartyLinkMethods { hub: &self }
    }
    pub fn thumbnails(&'a self) -> ThumbnailMethods<'a> {
        ThumbnailMethods { hub: &self }
    }
    pub fn video_abuse_report_reasons(&'a self) -> VideoAbuseReportReasonMethods<'a> {
        VideoAbuseReportReasonMethods { hub: &self }
    }
    pub fn video_categories(&'a self) -> VideoCategoryMethods<'a> {
        VideoCategoryMethods { hub: &self }
    }
    pub fn videos(&'a self) -> VideoMethods<'a> {
        VideoMethods { hub: &self }
    }
    pub fn watermarks(&'a self) -> WatermarkMethods<'a> {
        WatermarkMethods { hub: &self }
    }
    pub fn youtube(&'a self) -> YoutubeMethods<'a> {
        YoutubeMethods { hub: &self }
    }

    /// Set the user-agent header field to use in all requests to the server.
    /// It defaults to `google-api-rust-client/3.1.0`.
    ///
    /// Returns the previously set user-agent.
    pub fn user_agent(&mut self, agent_name: String) -> String {
        mem::replace(&mut self._user_agent, agent_name)
    }

    /// Set the base url to use in all requests to the server.
    /// It defaults to `https://youtube.googleapis.com/`.
    ///
    /// Returns the previously set base url.
    pub fn base_url(&mut self, new_base_url: String) -> String {
        mem::replace(&mut self._base_url, new_base_url)
    }

    /// Set the root url to use in all requests to the server.
    /// It defaults to `https://youtube.googleapis.com/`.
    ///
    /// Returns the previously set root url.
    pub fn root_url(&mut self, new_root_url: String) -> String {
        mem::replace(&mut self._root_url, new_root_url)
    }
}


// ############
// SCHEMAS ###
// ##########
/// There is no detailed description.
/// 
/// # 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 abuse reports](AbuseReportInsertCall) (request|response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct AbuseReport {
    /// no description provided
    #[serde(rename="abuseTypes")]
    pub abuse_types: Option<Vec<AbuseType>>,
    /// no description provided
    pub description: Option<String>,
    /// no description provided
    #[serde(rename="relatedEntities")]
    pub related_entities: Option<Vec<RelatedEntity>>,
    /// no description provided
    pub subject: Option<Entity>,
}

impl client::RequestValue for AbuseReport {}
impl client::Resource for AbuseReport {}
impl client::ResponseResult for AbuseReport {}

impl client::ToParts for AbuseReport {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.abuse_types.is_some() { r = r + "abuseTypes,"; }
        if self.description.is_some() { r = r + "description,"; }
        if self.related_entities.is_some() { r = r + "relatedEntities,"; }
        if self.subject.is_some() { r = r + "subject,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct AbuseType {
    /// no description provided
    pub id: Option<String>,
}

impl client::Part for AbuseType {}


/// Rights management policy for YouTube resources.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct AccessPolicy {
    /// The value of allowed indicates whether the access to the policy is allowed or denied by default.
    pub allowed: Option<bool>,
    /// A list of region codes that identify countries where the default policy do not apply.
    pub exception: Option<Vec<String>>,
}

impl client::Part for AccessPolicy {}


/// An *activity* resource contains information about an action that a particular channel, or user, has taken on YouTube.The actions reported in activity feeds include rating a video, sharing a video, marking a video as a favorite, commenting on a video, uploading a video, and so forth. Each activity resource identifies the type of action, the channel associated with the action, and the resource(s) associated with the action, such as the video that was rated or uploaded.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Activity {
    /// The contentDetails object contains information about the content associated with the activity. For example, if the snippet.type value is videoRated, then the contentDetails object's content identifies the rated video.
    #[serde(rename="contentDetails")]
    pub content_details: Option<ActivityContentDetails>,
    /// Etag of this resource
    pub etag: Option<String>,
    /// The ID that YouTube uses to uniquely identify the activity.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#activity".
    pub kind: Option<String>,
    /// The snippet object contains basic details about the activity, including the activity's type and group ID.
    pub snippet: Option<ActivitySnippet>,
}

impl client::Part for Activity {}


/// Details about the content of an activity: the video that was shared, the channel that was subscribed to, etc.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityContentDetails {
    /// The bulletin object contains details about a channel bulletin post. This object is only present if the snippet.type is bulletin.
    pub bulletin: Option<ActivityContentDetailsBulletin>,
    /// The channelItem object contains details about a resource which was added to a channel. This property is only present if the snippet.type is channelItem.
    #[serde(rename="channelItem")]
    pub channel_item: Option<ActivityContentDetailsChannelItem>,
    /// The comment object contains information about a resource that received a comment. This property is only present if the snippet.type is comment.
    pub comment: Option<ActivityContentDetailsComment>,
    /// The favorite object contains information about a video that was marked as a favorite video. This property is only present if the snippet.type is favorite.
    pub favorite: Option<ActivityContentDetailsFavorite>,
    /// The like object contains information about a resource that received a positive (like) rating. This property is only present if the snippet.type is like.
    pub like: Option<ActivityContentDetailsLike>,
    /// The playlistItem object contains information about a new playlist item. This property is only present if the snippet.type is playlistItem.
    #[serde(rename="playlistItem")]
    pub playlist_item: Option<ActivityContentDetailsPlaylistItem>,
    /// The promotedItem object contains details about a resource which is being promoted. This property is only present if the snippet.type is promotedItem.
    #[serde(rename="promotedItem")]
    pub promoted_item: Option<ActivityContentDetailsPromotedItem>,
    /// The recommendation object contains information about a recommended resource. This property is only present if the snippet.type is recommendation.
    pub recommendation: Option<ActivityContentDetailsRecommendation>,
    /// The social object contains details about a social network post. This property is only present if the snippet.type is social.
    pub social: Option<ActivityContentDetailsSocial>,
    /// The subscription object contains information about a channel that a user subscribed to. This property is only present if the snippet.type is subscription.
    pub subscription: Option<ActivityContentDetailsSubscription>,
    /// The upload object contains information about the uploaded video. This property is only present if the snippet.type is upload.
    pub upload: Option<ActivityContentDetailsUpload>,
}

impl client::Part for ActivityContentDetails {}


/// Details about a channel bulletin post.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityContentDetailsBulletin {
    /// The resourceId object contains information that identifies the resource associated with a bulletin post. @mutable youtube.activities.insert
    #[serde(rename="resourceId")]
    pub resource_id: Option<ResourceId>,
}

impl client::Part for ActivityContentDetailsBulletin {}


/// Details about a resource which was added to a channel.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityContentDetailsChannelItem {
    /// The resourceId object contains information that identifies the resource that was added to the channel.
    #[serde(rename="resourceId")]
    pub resource_id: Option<ResourceId>,
}

impl client::Part for ActivityContentDetailsChannelItem {}


/// Information about a resource that received a comment.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityContentDetailsComment {
    /// The resourceId object contains information that identifies the resource associated with the comment.
    #[serde(rename="resourceId")]
    pub resource_id: Option<ResourceId>,
}

impl client::Part for ActivityContentDetailsComment {}


/// Information about a video that was marked as a favorite video.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityContentDetailsFavorite {
    /// The resourceId object contains information that identifies the resource that was marked as a favorite.
    #[serde(rename="resourceId")]
    pub resource_id: Option<ResourceId>,
}

impl client::Part for ActivityContentDetailsFavorite {}


/// Information about a resource that received a positive (like) rating.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityContentDetailsLike {
    /// The resourceId object contains information that identifies the rated resource.
    #[serde(rename="resourceId")]
    pub resource_id: Option<ResourceId>,
}

impl client::Part for ActivityContentDetailsLike {}


/// Information about a new playlist item.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityContentDetailsPlaylistItem {
    /// The value that YouTube uses to uniquely identify the playlist.
    #[serde(rename="playlistId")]
    pub playlist_id: Option<String>,
    /// ID of the item within the playlist.
    #[serde(rename="playlistItemId")]
    pub playlist_item_id: Option<String>,
    /// The resourceId object contains information about the resource that was added to the playlist.
    #[serde(rename="resourceId")]
    pub resource_id: Option<ResourceId>,
}

impl client::Part for ActivityContentDetailsPlaylistItem {}


/// Details about a resource which is being promoted.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityContentDetailsPromotedItem {
    /// The URL the client should fetch to request a promoted item.
    #[serde(rename="adTag")]
    pub ad_tag: Option<String>,
    /// The URL the client should ping to indicate that the user clicked through on this promoted item.
    #[serde(rename="clickTrackingUrl")]
    pub click_tracking_url: Option<String>,
    /// The URL the client should ping to indicate that the user was shown this promoted item.
    #[serde(rename="creativeViewUrl")]
    pub creative_view_url: Option<String>,
    /// The type of call-to-action, a message to the user indicating action that can be taken.
    #[serde(rename="ctaType")]
    pub cta_type: Option<String>,
    /// The custom call-to-action button text. If specified, it will override the default button text for the cta_type.
    #[serde(rename="customCtaButtonText")]
    pub custom_cta_button_text: Option<String>,
    /// The text description to accompany the promoted item.
    #[serde(rename="descriptionText")]
    pub description_text: Option<String>,
    /// The URL the client should direct the user to, if the user chooses to visit the advertiser's website.
    #[serde(rename="destinationUrl")]
    pub destination_url: Option<String>,
    /// The list of forecasting URLs. The client should ping all of these URLs when a promoted item is not available, to indicate that a promoted item could have been shown.
    #[serde(rename="forecastingUrl")]
    pub forecasting_url: Option<Vec<String>>,
    /// The list of impression URLs. The client should ping all of these URLs to indicate that the user was shown this promoted item.
    #[serde(rename="impressionUrl")]
    pub impression_url: Option<Vec<String>>,
    /// The ID that YouTube uses to uniquely identify the promoted video.
    #[serde(rename="videoId")]
    pub video_id: Option<String>,
}

impl client::Part for ActivityContentDetailsPromotedItem {}


/// Information that identifies the recommended resource.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityContentDetailsRecommendation {
    /// The reason that the resource is recommended to the user.
    pub reason: Option<String>,
    /// The resourceId object contains information that identifies the recommended resource.
    #[serde(rename="resourceId")]
    pub resource_id: Option<ResourceId>,
    /// The seedResourceId object contains information about the resource that caused the recommendation.
    #[serde(rename="seedResourceId")]
    pub seed_resource_id: Option<ResourceId>,
}

impl client::Part for ActivityContentDetailsRecommendation {}


/// Details about a social network post.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityContentDetailsSocial {
    /// The author of the social network post.
    pub author: Option<String>,
    /// An image of the post's author.
    #[serde(rename="imageUrl")]
    pub image_url: Option<String>,
    /// The URL of the social network post.
    #[serde(rename="referenceUrl")]
    pub reference_url: Option<String>,
    /// The resourceId object encapsulates information that identifies the resource associated with a social network post.
    #[serde(rename="resourceId")]
    pub resource_id: Option<ResourceId>,
    /// The name of the social network.
    #[serde(rename="type")]
    pub type_: Option<String>,
}

impl client::Part for ActivityContentDetailsSocial {}


/// Information about a channel that a user subscribed to.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityContentDetailsSubscription {
    /// The resourceId object contains information that identifies the resource that the user subscribed to.
    #[serde(rename="resourceId")]
    pub resource_id: Option<ResourceId>,
}

impl client::Part for ActivityContentDetailsSubscription {}


/// Information about the uploaded video.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityContentDetailsUpload {
    /// The ID that YouTube uses to uniquely identify the uploaded video.
    #[serde(rename="videoId")]
    pub video_id: Option<String>,
}

impl client::Part for ActivityContentDetailsUpload {}


/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list activities](ActivityListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// no description provided
    pub items: Option<Vec<Activity>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#activityListResponse".
    pub kind: Option<String>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
    #[serde(rename="nextPageToken")]
    pub next_page_token: Option<String>,
    /// General pagination information.
    #[serde(rename="pageInfo")]
    pub page_info: Option<PageInfo>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the previous page in the result set.
    #[serde(rename="prevPageToken")]
    pub prev_page_token: Option<String>,
    /// no description provided
    #[serde(rename="tokenPagination")]
    pub token_pagination: Option<TokenPagination>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for ActivityListResponse {}

impl client::ToParts for ActivityListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.next_page_token.is_some() { r = r + "nextPageToken,"; }
        if self.page_info.is_some() { r = r + "pageInfo,"; }
        if self.prev_page_token.is_some() { r = r + "prevPageToken,"; }
        if self.token_pagination.is_some() { r = r + "tokenPagination,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// Basic details about an activity, including title, description, thumbnails, activity type and group. Next ID: 12
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivitySnippet {
    /// The ID that YouTube uses to uniquely identify the channel associated with the activity.
    #[serde(rename="channelId")]
    pub channel_id: Option<String>,
    /// Channel title for the channel responsible for this activity
    #[serde(rename="channelTitle")]
    pub channel_title: Option<String>,
    /// The description of the resource primarily associated with the activity. @mutable youtube.activities.insert
    pub description: Option<String>,
    /// The group ID associated with the activity. A group ID identifies user events that are associated with the same user and resource. For example, if a user rates a video and marks the same video as a favorite, the entries for those events would have the same group ID in the user's activity feed. In your user interface, you can avoid repetition by grouping events with the same groupId value.
    #[serde(rename="groupId")]
    pub group_id: Option<String>,
    /// The date and time that the video was uploaded.
    #[serde(rename="publishedAt")]
    pub published_at: Option<String>,
    /// A map of thumbnail images associated with the resource that is primarily associated with the activity. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail.
    pub thumbnails: Option<ThumbnailDetails>,
    /// The title of the resource primarily associated with the activity.
    pub title: Option<String>,
    /// The type of activity that the resource describes.
    #[serde(rename="type")]
    pub type_: Option<String>,
}

impl client::Part for ActivitySnippet {}


/// A *caption* resource represents a YouTube caption track. A caption track is associated with exactly one YouTube video.
/// 
/// # 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*).
/// 
/// * [delete captions](CaptionDeleteCall) (none)
/// * [download captions](CaptionDownloadCall) (none)
/// * [insert captions](CaptionInsertCall) (request|response)
/// * [list captions](CaptionListCall) (none)
/// * [update captions](CaptionUpdateCall) (request|response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Caption {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube uses to uniquely identify the caption track.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#caption".
    pub kind: Option<String>,
    /// The snippet object contains basic details about the caption.
    pub snippet: Option<CaptionSnippet>,
}

impl client::RequestValue for Caption {}
impl client::Resource for Caption {}
impl client::ResponseResult for Caption {}

impl client::ToParts for Caption {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list captions](CaptionListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CaptionListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of captions that match the request criteria.
    pub items: Option<Vec<Caption>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#captionListResponse".
    pub kind: Option<String>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for CaptionListResponse {}

impl client::ToParts for CaptionListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// Basic details about a caption track, such as its language and name.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CaptionSnippet {
    /// The type of audio track associated with the caption track.
    #[serde(rename="audioTrackType")]
    pub audio_track_type: Option<String>,
    /// The reason that YouTube failed to process the caption track. This property is only present if the state property's value is failed.
    #[serde(rename="failureReason")]
    pub failure_reason: Option<String>,
    /// Indicates whether YouTube synchronized the caption track to the audio track in the video. The value will be true if a sync was explicitly requested when the caption track was uploaded. For example, when calling the captions.insert or captions.update methods, you can set the sync parameter to true to instruct YouTube to sync the uploaded track to the video. If the value is false, YouTube uses the time codes in the uploaded caption track to determine when to display captions.
    #[serde(rename="isAutoSynced")]
    pub is_auto_synced: Option<bool>,
    /// Indicates whether the track contains closed captions for the deaf and hard of hearing. The default value is false.
    #[serde(rename="isCC")]
    pub is_cc: Option<bool>,
    /// Indicates whether the caption track is a draft. If the value is true, then the track is not publicly visible. The default value is false. @mutable youtube.captions.insert youtube.captions.update
    #[serde(rename="isDraft")]
    pub is_draft: Option<bool>,
    /// Indicates whether caption track is formatted for "easy reader," meaning it is at a third-grade level for language learners. The default value is false.
    #[serde(rename="isEasyReader")]
    pub is_easy_reader: Option<bool>,
    /// Indicates whether the caption track uses large text for the vision-impaired. The default value is false.
    #[serde(rename="isLarge")]
    pub is_large: Option<bool>,
    /// The language of the caption track. The property value is a BCP-47 language tag.
    pub language: Option<String>,
    /// The date and time when the caption track was last updated.
    #[serde(rename="lastUpdated")]
    pub last_updated: Option<String>,
    /// The name of the caption track. The name is intended to be visible to the user as an option during playback.
    pub name: Option<String>,
    /// The caption track's status.
    pub status: Option<String>,
    /// The caption track's type.
    #[serde(rename="trackKind")]
    pub track_kind: Option<String>,
    /// The ID that YouTube uses to uniquely identify the video associated with the caption track. @mutable youtube.captions.insert
    #[serde(rename="videoId")]
    pub video_id: Option<String>,
}

impl client::Part for CaptionSnippet {}


/// Brief description of the live stream cdn settings.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CdnSettings {
    /// The format of the video stream that you are sending to Youtube. 
    pub format: Option<String>,
    /// The frame rate of the inbound video data.
    #[serde(rename="frameRate")]
    pub frame_rate: Option<String>,
    /// The ingestionInfo object contains information that YouTube provides that you need to transmit your RTMP or HTTP stream to YouTube.
    #[serde(rename="ingestionInfo")]
    pub ingestion_info: Option<IngestionInfo>,
    ///  The method or protocol used to transmit the video stream.
    #[serde(rename="ingestionType")]
    pub ingestion_type: Option<String>,
    /// The resolution of the inbound video data.
    pub resolution: Option<String>,
}

impl client::Part for CdnSettings {}


/// A *channel* resource contains information about a YouTube channel.
/// 
/// # 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*).
/// 
/// * [list channels](ChannelListCall) (none)
/// * [update channels](ChannelUpdateCall) (request|response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Channel {
    /// The auditionDetails object encapsulates channel data that is relevant for YouTube Partners during the audition process.
    #[serde(rename="auditDetails")]
    pub audit_details: Option<ChannelAuditDetails>,
    /// The brandingSettings object encapsulates information about the branding of the channel.
    #[serde(rename="brandingSettings")]
    pub branding_settings: Option<ChannelBrandingSettings>,
    /// The contentDetails object encapsulates information about the channel's content.
    #[serde(rename="contentDetails")]
    pub content_details: Option<ChannelContentDetails>,
    /// The contentOwnerDetails object encapsulates channel data that is relevant for YouTube Partners linked with the channel.
    #[serde(rename="contentOwnerDetails")]
    pub content_owner_details: Option<ChannelContentOwnerDetails>,
    /// The conversionPings object encapsulates information about conversion pings that need to be respected by the channel.
    #[serde(rename="conversionPings")]
    pub conversion_pings: Option<ChannelConversionPings>,
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube uses to uniquely identify the channel.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#channel".
    pub kind: Option<String>,
    /// Localizations for different languages
    pub localizations: Option<HashMap<String, ChannelLocalization>>,
    /// The snippet object contains basic details about the channel, such as its title, description, and thumbnail images.
    pub snippet: Option<ChannelSnippet>,
    /// The statistics object encapsulates statistics for the channel.
    pub statistics: Option<ChannelStatistics>,
    /// The status object encapsulates information about the privacy status of the channel.
    pub status: Option<ChannelStatus>,
    /// The topicDetails object encapsulates information about Freebase topics associated with the channel.
    #[serde(rename="topicDetails")]
    pub topic_details: Option<ChannelTopicDetails>,
}

impl client::RequestValue for Channel {}
impl client::Resource for Channel {}
impl client::ResponseResult for Channel {}

impl client::ToParts for Channel {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.audit_details.is_some() { r = r + "auditDetails,"; }
        if self.branding_settings.is_some() { r = r + "brandingSettings,"; }
        if self.content_details.is_some() { r = r + "contentDetails,"; }
        if self.content_owner_details.is_some() { r = r + "contentOwnerDetails,"; }
        if self.conversion_pings.is_some() { r = r + "conversionPings,"; }
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.localizations.is_some() { r = r + "localizations,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        if self.statistics.is_some() { r = r + "statistics,"; }
        if self.status.is_some() { r = r + "status,"; }
        if self.topic_details.is_some() { r = r + "topicDetails,"; }
        r.pop();
        r
    }
}

/// The auditDetails object encapsulates channel data that is relevant for YouTube Partners during the audit process.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelAuditDetails {
    /// Whether or not the channel respects the community guidelines.
    #[serde(rename="communityGuidelinesGoodStanding")]
    pub community_guidelines_good_standing: Option<bool>,
    /// Whether or not the channel has any unresolved claims.
    #[serde(rename="contentIdClaimsGoodStanding")]
    pub content_id_claims_good_standing: Option<bool>,
    /// Whether or not the channel has any copyright strikes.
    #[serde(rename="copyrightStrikesGoodStanding")]
    pub copyright_strikes_good_standing: Option<bool>,
}

impl client::Part for ChannelAuditDetails {}


/// A channel banner returned as the response to a channel_banner.insert call.
/// 
/// # 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 channel banners](ChannelBannerInsertCall) (request|response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelBannerResource {
    /// no description provided
    pub etag: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#channelBannerResource".
    pub kind: Option<String>,
    /// The URL of this banner image.
    pub url: Option<String>,
}

impl client::RequestValue for ChannelBannerResource {}
impl client::ResponseResult for ChannelBannerResource {}


/// Branding properties of a YouTube channel.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelBrandingSettings {
    /// Branding properties for the channel view.
    pub channel: Option<ChannelSettings>,
    /// Additional experimental branding properties.
    pub hints: Option<Vec<PropertyValue>>,
    /// Branding properties for branding images.
    pub image: Option<ImageSettings>,
    /// Branding properties for the watch page.
    pub watch: Option<WatchSettings>,
}

impl client::Part for ChannelBrandingSettings {}


/// Details about the content of a channel.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelContentDetails {
    /// no description provided
    #[serde(rename="relatedPlaylists")]
    pub related_playlists: Option<ChannelContentDetailsRelatedPlaylists>,
}

impl client::Part for ChannelContentDetails {}


/// The contentOwnerDetails object encapsulates channel data that is relevant for YouTube Partners linked with the channel.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelContentOwnerDetails {
    /// The ID of the content owner linked to the channel.
    #[serde(rename="contentOwner")]
    pub content_owner: Option<String>,
    /// The date and time when the channel was linked to the content owner.
    #[serde(rename="timeLinked")]
    pub time_linked: Option<String>,
}

impl client::Part for ChannelContentOwnerDetails {}


/// Pings that the app shall fire (authenticated by biscotti cookie). Each ping has a context, in which the app must fire the ping, and a url identifying the ping.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelConversionPing {
    /// Defines the context of the ping.
    pub context: Option<String>,
    /// The url (without the schema) that the player shall send the ping to. It's at caller's descretion to decide which schema to use (http vs https) Example of a returned url: //googleads.g.doubleclick.net/pagead/ viewthroughconversion/962985656/?data=path%3DtHe_path%3Btype%3D cview%3Butuid%3DGISQtTNGYqaYl4sKxoVvKA&labe=default The caller must append biscotti authentication (ms param in case of mobile, for example) to this ping.
    #[serde(rename="conversionUrl")]
    pub conversion_url: Option<String>,
}

impl client::Part for ChannelConversionPing {}


/// The conversionPings object encapsulates information about conversion pings that need to be respected by the channel.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelConversionPings {
    /// Pings that the app shall fire (authenticated by biscotti cookie). Each ping has a context, in which the app must fire the ping, and a url identifying the ping.
    pub pings: Option<Vec<ChannelConversionPing>>,
}

impl client::Part for ChannelConversionPings {}


/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list channels](ChannelListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// no description provided
    pub items: Option<Vec<Channel>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#channelListResponse".
    pub kind: Option<String>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
    #[serde(rename="nextPageToken")]
    pub next_page_token: Option<String>,
    /// General pagination information.
    #[serde(rename="pageInfo")]
    pub page_info: Option<PageInfo>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the previous page in the result set.
    #[serde(rename="prevPageToken")]
    pub prev_page_token: Option<String>,
    /// no description provided
    #[serde(rename="tokenPagination")]
    pub token_pagination: Option<TokenPagination>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for ChannelListResponse {}

impl client::ToParts for ChannelListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.next_page_token.is_some() { r = r + "nextPageToken,"; }
        if self.page_info.is_some() { r = r + "pageInfo,"; }
        if self.prev_page_token.is_some() { r = r + "prevPageToken,"; }
        if self.token_pagination.is_some() { r = r + "tokenPagination,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// Channel localization setting
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelLocalization {
    /// The localized strings for channel's description.
    pub description: Option<String>,
    /// The localized strings for channel's title.
    pub title: Option<String>,
}

impl client::Part for ChannelLocalization {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelProfileDetails {
    /// The YouTube channel ID.
    #[serde(rename="channelId")]
    pub channel_id: Option<String>,
    /// The channel's URL.
    #[serde(rename="channelUrl")]
    pub channel_url: Option<String>,
    /// The channel's display name.
    #[serde(rename="displayName")]
    pub display_name: Option<String>,
    /// The channels's avatar URL.
    #[serde(rename="profileImageUrl")]
    pub profile_image_url: Option<String>,
}

impl client::Part for ChannelProfileDetails {}


/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [delete channel sections](ChannelSectionDeleteCall) (none)
/// * [insert channel sections](ChannelSectionInsertCall) (request|response)
/// * [list channel sections](ChannelSectionListCall) (none)
/// * [update channel sections](ChannelSectionUpdateCall) (request|response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelSection {
    /// The contentDetails object contains details about the channel section content, such as a list of playlists or channels featured in the section.
    #[serde(rename="contentDetails")]
    pub content_details: Option<ChannelSectionContentDetails>,
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube uses to uniquely identify the channel section.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#channelSection".
    pub kind: Option<String>,
    /// Localizations for different languages
    pub localizations: Option<HashMap<String, ChannelSectionLocalization>>,
    /// The snippet object contains basic details about the channel section, such as its type, style and title.
    pub snippet: Option<ChannelSectionSnippet>,
    /// The targeting object contains basic targeting settings about the channel section.
    pub targeting: Option<ChannelSectionTargeting>,
}

impl client::RequestValue for ChannelSection {}
impl client::Resource for ChannelSection {}
impl client::ResponseResult for ChannelSection {}

impl client::ToParts for ChannelSection {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.content_details.is_some() { r = r + "contentDetails,"; }
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.localizations.is_some() { r = r + "localizations,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        if self.targeting.is_some() { r = r + "targeting,"; }
        r.pop();
        r
    }
}

/// Details about a channelsection, including playlists and channels.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelSectionContentDetails {
    /// The channel ids for type multiple_channels.
    pub channels: Option<Vec<String>>,
    /// The playlist ids for type single_playlist and multiple_playlists. For singlePlaylist, only one playlistId is allowed.
    pub playlists: Option<Vec<String>>,
}

impl client::Part for ChannelSectionContentDetails {}


/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list channel sections](ChannelSectionListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelSectionListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of ChannelSections that match the request criteria.
    pub items: Option<Vec<ChannelSection>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#channelSectionListResponse".
    pub kind: Option<String>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for ChannelSectionListResponse {}

impl client::ToParts for ChannelSectionListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// ChannelSection localization setting
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelSectionLocalization {
    /// The localized strings for channel section's title.
    pub title: Option<String>,
}

impl client::Part for ChannelSectionLocalization {}


/// Basic details about a channel section, including title, style and position.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelSectionSnippet {
    /// The ID that YouTube uses to uniquely identify the channel that published the channel section.
    #[serde(rename="channelId")]
    pub channel_id: Option<String>,
    /// The language of the channel section's default title and description.
    #[serde(rename="defaultLanguage")]
    pub default_language: Option<String>,
    /// Localized title, read-only.
    pub localized: Option<ChannelSectionLocalization>,
    /// The position of the channel section in the channel.
    pub position: Option<u32>,
    /// The style of the channel section.
    pub style: Option<String>,
    /// The channel section's title for multiple_playlists and multiple_channels.
    pub title: Option<String>,
    /// The type of the channel section.
    #[serde(rename="type")]
    pub type_: Option<String>,
}

impl client::Part for ChannelSectionSnippet {}


/// ChannelSection targeting setting.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelSectionTargeting {
    /// The country the channel section is targeting.
    pub countries: Option<Vec<String>>,
    /// The language the channel section is targeting.
    pub languages: Option<Vec<String>>,
    /// The region the channel section is targeting.
    pub regions: Option<Vec<String>>,
}

impl client::Part for ChannelSectionTargeting {}


/// Branding properties for the channel view.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelSettings {
    /// The country of the channel.
    pub country: Option<String>,
    /// no description provided
    #[serde(rename="defaultLanguage")]
    pub default_language: Option<String>,
    /// Which content tab users should see when viewing the channel.
    #[serde(rename="defaultTab")]
    pub default_tab: Option<String>,
    /// Specifies the channel description.
    pub description: Option<String>,
    /// Title for the featured channels tab.
    #[serde(rename="featuredChannelsTitle")]
    pub featured_channels_title: Option<String>,
    /// The list of featured channels.
    #[serde(rename="featuredChannelsUrls")]
    pub featured_channels_urls: Option<Vec<String>>,
    /// Lists keywords associated with the channel, comma-separated.
    pub keywords: Option<String>,
    /// Whether user-submitted comments left on the channel page need to be approved by the channel owner to be publicly visible.
    #[serde(rename="moderateComments")]
    pub moderate_comments: Option<bool>,
    /// A prominent color that can be rendered on this channel page.
    #[serde(rename="profileColor")]
    pub profile_color: Option<String>,
    /// Whether the tab to browse the videos should be displayed.
    #[serde(rename="showBrowseView")]
    pub show_browse_view: Option<bool>,
    /// Whether related channels should be proposed.
    #[serde(rename="showRelatedChannels")]
    pub show_related_channels: Option<bool>,
    /// Specifies the channel title.
    pub title: Option<String>,
    /// The ID for a Google Analytics account to track and measure traffic to the channels.
    #[serde(rename="trackingAnalyticsAccountId")]
    pub tracking_analytics_account_id: Option<String>,
    /// The trailer of the channel, for users that are not subscribers.
    #[serde(rename="unsubscribedTrailer")]
    pub unsubscribed_trailer: Option<String>,
}

impl client::Part for ChannelSettings {}


/// Basic details about a channel, including title, description and thumbnails.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelSnippet {
    /// The country of the channel.
    pub country: Option<String>,
    /// The custom url of the channel.
    #[serde(rename="customUrl")]
    pub custom_url: Option<String>,
    /// The language of the channel's default title and description.
    #[serde(rename="defaultLanguage")]
    pub default_language: Option<String>,
    /// The description of the channel.
    pub description: Option<String>,
    /// Localized title and description, read-only.
    pub localized: Option<ChannelLocalization>,
    /// The date and time that the channel was created.
    #[serde(rename="publishedAt")]
    pub published_at: Option<String>,
    /// A map of thumbnail images associated with the channel. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail. When displaying thumbnails in your application, make sure that your code uses the image URLs exactly as they are returned in API responses. For example, your application should not use the http domain instead of the https domain in a URL returned in an API response. Beginning in July 2018, channel thumbnail URLs will only be available in the https domain, which is how the URLs appear in API responses. After that time, you might see broken images in your application if it tries to load YouTube images from the http domain. Thumbnail images might be empty for newly created channels and might take up to one day to populate.
    pub thumbnails: Option<ThumbnailDetails>,
    /// The channel's title.
    pub title: Option<String>,
}

impl client::Part for ChannelSnippet {}


/// Statistics about a channel: number of subscribers, number of videos in the channel, etc.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelStatistics {
    /// The number of comments for the channel.
    #[serde(rename="commentCount")]
    pub comment_count: Option<String>,
    /// Whether or not the number of subscribers is shown for this user.
    #[serde(rename="hiddenSubscriberCount")]
    pub hidden_subscriber_count: Option<bool>,
    /// The number of subscribers that the channel has.
    #[serde(rename="subscriberCount")]
    pub subscriber_count: Option<String>,
    /// The number of videos uploaded to the channel.
    #[serde(rename="videoCount")]
    pub video_count: Option<String>,
    /// The number of times the channel has been viewed.
    #[serde(rename="viewCount")]
    pub view_count: Option<String>,
}

impl client::Part for ChannelStatistics {}


/// JSON template for the status part of a channel.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelStatus {
    /// If true, then the user is linked to either a YouTube username or G+ account. Otherwise, the user doesn't have a public YouTube identity.
    #[serde(rename="isLinked")]
    pub is_linked: Option<bool>,
    /// The long uploads status of this channel. See https://support.google.com/youtube/answer/71673 for more information.
    #[serde(rename="longUploadsStatus")]
    pub long_uploads_status: Option<String>,
    /// no description provided
    #[serde(rename="madeForKids")]
    pub made_for_kids: Option<bool>,
    /// Privacy status of the channel.
    #[serde(rename="privacyStatus")]
    pub privacy_status: Option<String>,
    /// no description provided
    #[serde(rename="selfDeclaredMadeForKids")]
    pub self_declared_made_for_kids: Option<bool>,
}

impl client::Part for ChannelStatus {}


/// Information specific to a store on a merchandising platform linked to a YouTube channel.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelToStoreLinkDetails {
    /// Name of the store.
    #[serde(rename="storeName")]
    pub store_name: Option<String>,
    /// Landing page of the store.
    #[serde(rename="storeUrl")]
    pub store_url: Option<String>,
}

impl client::Part for ChannelToStoreLinkDetails {}


/// Freebase topic information related to the channel.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelTopicDetails {
    /// A list of Wikipedia URLs that describe the channel's content.
    #[serde(rename="topicCategories")]
    pub topic_categories: Option<Vec<String>>,
    /// A list of Freebase topic IDs associated with the channel. You can retrieve information about each topic using the Freebase Topic API.
    #[serde(rename="topicIds")]
    pub topic_ids: Option<Vec<String>>,
}

impl client::Part for ChannelTopicDetails {}


/// A *comment* represents a single YouTube comment.
/// 
/// # 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*).
/// 
/// * [delete comments](CommentDeleteCall) (none)
/// * [insert comments](CommentInsertCall) (request|response)
/// * [list comments](CommentListCall) (none)
/// * [mark as spam comments](CommentMarkAsSpamCall) (none)
/// * [set moderation status comments](CommentSetModerationStatuCall) (none)
/// * [update comments](CommentUpdateCall) (request|response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Comment {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube uses to uniquely identify the comment.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#comment".
    pub kind: Option<String>,
    /// The snippet object contains basic details about the comment.
    pub snippet: Option<CommentSnippet>,
}

impl client::RequestValue for Comment {}
impl client::Resource for Comment {}
impl client::ResponseResult for Comment {}

impl client::ToParts for Comment {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list comments](CommentListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CommentListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of comments that match the request criteria.
    pub items: Option<Vec<Comment>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#commentListResponse".
    pub kind: Option<String>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
    #[serde(rename="nextPageToken")]
    pub next_page_token: Option<String>,
    /// General pagination information.
    #[serde(rename="pageInfo")]
    pub page_info: Option<PageInfo>,
    /// no description provided
    #[serde(rename="tokenPagination")]
    pub token_pagination: Option<TokenPagination>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for CommentListResponse {}

impl client::ToParts for CommentListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.next_page_token.is_some() { r = r + "nextPageToken,"; }
        if self.page_info.is_some() { r = r + "pageInfo,"; }
        if self.token_pagination.is_some() { r = r + "tokenPagination,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// Basic details about a comment, such as its author and text.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CommentSnippet {
    /// no description provided
    #[serde(rename="authorChannelId")]
    pub author_channel_id: Option<CommentSnippetAuthorChannelId>,
    /// Link to the author's YouTube channel, if any.
    #[serde(rename="authorChannelUrl")]
    pub author_channel_url: Option<String>,
    /// The name of the user who posted the comment.
    #[serde(rename="authorDisplayName")]
    pub author_display_name: Option<String>,
    /// The URL for the avatar of the user who posted the comment.
    #[serde(rename="authorProfileImageUrl")]
    pub author_profile_image_url: Option<String>,
    /// Whether the current viewer can rate this comment.
    #[serde(rename="canRate")]
    pub can_rate: Option<bool>,
    /// The id of the corresponding YouTube channel. In case of a channel comment this is the channel the comment refers to. In case of a video comment it's the video's channel.
    #[serde(rename="channelId")]
    pub channel_id: Option<String>,
    /// The total number of likes this comment has received.
    #[serde(rename="likeCount")]
    pub like_count: Option<u32>,
    /// The comment's moderation status. Will not be set if the comments were requested through the id filter.
    #[serde(rename="moderationStatus")]
    pub moderation_status: Option<String>,
    /// The unique id of the parent comment, only set for replies.
    #[serde(rename="parentId")]
    pub parent_id: Option<String>,
    /// The date and time when the comment was originally published.
    #[serde(rename="publishedAt")]
    pub published_at: Option<String>,
    /// The comment's text. The format is either plain text or HTML dependent on what has been requested. Even the plain text representation may differ from the text originally posted in that it may replace video links with video titles etc.
    #[serde(rename="textDisplay")]
    pub text_display: Option<String>,
    /// The comment's original raw text as initially posted or last updated. The original text will only be returned if it is accessible to the viewer, which is only guaranteed if the viewer is the comment's author.
    #[serde(rename="textOriginal")]
    pub text_original: Option<String>,
    /// The date and time when the comment was last updated.
    #[serde(rename="updatedAt")]
    pub updated_at: Option<String>,
    /// The ID of the video the comment refers to, if any.
    #[serde(rename="videoId")]
    pub video_id: Option<String>,
    /// The rating the viewer has given to this comment. For the time being this will never return RATE_TYPE_DISLIKE and instead return RATE_TYPE_NONE. This may change in the future.
    #[serde(rename="viewerRating")]
    pub viewer_rating: Option<String>,
}

impl client::Part for CommentSnippet {}


/// The id of the author's YouTube channel, if any.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CommentSnippetAuthorChannelId {
    /// no description provided
    pub value: Option<String>,
}

impl client::Part for CommentSnippetAuthorChannelId {}


/// A *comment thread* represents information that applies to a top level comment and all its replies. It can also include the top level comment itself and some of the replies.
/// 
/// # 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 comment threads](CommentThreadInsertCall) (request|response)
/// * [list comment threads](CommentThreadListCall) (none)
/// * [v3 update comment threads youtube](YoutubeV3UpdateCommentThreadCall) (request|response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CommentThread {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube uses to uniquely identify the comment thread.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#commentThread".
    pub kind: Option<String>,
    /// The replies object contains a limited number of replies (if any) to the top level comment found in the snippet.
    pub replies: Option<CommentThreadReplies>,
    /// The snippet object contains basic details about the comment thread and also the top level comment.
    pub snippet: Option<CommentThreadSnippet>,
}

impl client::RequestValue for CommentThread {}
impl client::Resource for CommentThread {}
impl client::ResponseResult for CommentThread {}

impl client::ToParts for CommentThread {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.replies.is_some() { r = r + "replies,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list comment threads](CommentThreadListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CommentThreadListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of comment threads that match the request criteria.
    pub items: Option<Vec<CommentThread>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#commentThreadListResponse".
    pub kind: Option<String>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
    #[serde(rename="nextPageToken")]
    pub next_page_token: Option<String>,
    /// General pagination information.
    #[serde(rename="pageInfo")]
    pub page_info: Option<PageInfo>,
    /// no description provided
    #[serde(rename="tokenPagination")]
    pub token_pagination: Option<TokenPagination>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for CommentThreadListResponse {}

impl client::ToParts for CommentThreadListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.next_page_token.is_some() { r = r + "nextPageToken,"; }
        if self.page_info.is_some() { r = r + "pageInfo,"; }
        if self.token_pagination.is_some() { r = r + "tokenPagination,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// Comments written in (direct or indirect) reply to the top level comment.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CommentThreadReplies {
    /// A limited number of replies. Unless the number of replies returned equals total_reply_count in the snippet the returned replies are only a subset of the total number of replies.
    pub comments: Option<Vec<Comment>>,
}

impl client::Part for CommentThreadReplies {}


/// Basic details about a comment thread.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CommentThreadSnippet {
    /// Whether the current viewer of the thread can reply to it. This is viewer specific - other viewers may see a different value for this field.
    #[serde(rename="canReply")]
    pub can_reply: Option<bool>,
    /// The YouTube channel the comments in the thread refer to or the channel with the video the comments refer to. If video_id isn't set the comments refer to the channel itself.
    #[serde(rename="channelId")]
    pub channel_id: Option<String>,
    /// Whether the thread (and therefore all its comments) is visible to all YouTube users.
    #[serde(rename="isPublic")]
    pub is_public: Option<bool>,
    /// The top level comment of this thread.
    #[serde(rename="topLevelComment")]
    pub top_level_comment: Option<Comment>,
    /// The total number of replies (not including the top level comment).
    #[serde(rename="totalReplyCount")]
    pub total_reply_count: Option<u32>,
    /// The ID of the video the comments refer to, if any. No video_id implies a channel discussion comment.
    #[serde(rename="videoId")]
    pub video_id: Option<String>,
}

impl client::Part for CommentThreadSnippet {}


/// Ratings schemes. The country-specific ratings are mostly for movies and shows. LINT.IfChange
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ContentRating {
    /// The video's Australian Classification Board (ACB) or Australian Communications and Media Authority (ACMA) rating. ACMA ratings are used to classify children's television programming.
    #[serde(rename="acbRating")]
    pub acb_rating: Option<String>,
    /// The video's rating from Italy's Autorità per le Garanzie nelle Comunicazioni (AGCOM).
    #[serde(rename="agcomRating")]
    pub agcom_rating: Option<String>,
    /// The video's Anatel (Asociación Nacional de Televisión) rating for Chilean television.
    #[serde(rename="anatelRating")]
    pub anatel_rating: Option<String>,
    /// The video's British Board of Film Classification (BBFC) rating.
    #[serde(rename="bbfcRating")]
    pub bbfc_rating: Option<String>,
    /// The video's rating from Thailand's Board of Film and Video Censors.
    #[serde(rename="bfvcRating")]
    pub bfvc_rating: Option<String>,
    /// The video's rating from the Austrian Board of Media Classification (Bundesministerium für Unterricht, Kunst und Kultur).
    #[serde(rename="bmukkRating")]
    pub bmukk_rating: Option<String>,
    /// Rating system for Canadian TV - Canadian TV Classification System The video's rating from the Canadian Radio-Television and Telecommunications Commission (CRTC) for Canadian English-language broadcasts. For more information, see the Canadian Broadcast Standards Council website.
    #[serde(rename="catvRating")]
    pub catv_rating: Option<String>,
    /// The video's rating from the Canadian Radio-Television and Telecommunications Commission (CRTC) for Canadian French-language broadcasts. For more information, see the Canadian Broadcast Standards Council website.
    #[serde(rename="catvfrRating")]
    pub catvfr_rating: Option<String>,
    /// The video's Central Board of Film Certification (CBFC - India) rating.
    #[serde(rename="cbfcRating")]
    pub cbfc_rating: Option<String>,
    /// The video's Consejo de Calificación Cinematográfica (Chile) rating.
    #[serde(rename="cccRating")]
    pub ccc_rating: Option<String>,
    /// The video's rating from Portugal's Comissão de Classificação de Espect´culos.
    #[serde(rename="cceRating")]
    pub cce_rating: Option<String>,
    /// The video's rating in Switzerland.
    #[serde(rename="chfilmRating")]
    pub chfilm_rating: Option<String>,
    /// The video's Canadian Home Video Rating System (CHVRS) rating.
    #[serde(rename="chvrsRating")]
    pub chvrs_rating: Option<String>,
    /// The video's rating from the Commission de Contrôle des Films (Belgium).
    #[serde(rename="cicfRating")]
    pub cicf_rating: Option<String>,
    /// The video's rating from Romania's CONSILIUL NATIONAL AL AUDIOVIZUALULUI (CNA).
    #[serde(rename="cnaRating")]
    pub cna_rating: Option<String>,
    /// Rating system in France - Commission de classification cinematographique
    #[serde(rename="cncRating")]
    pub cnc_rating: Option<String>,
    /// The video's rating from France's Conseil supérieur de l’audiovisuel, which rates broadcast content.
    #[serde(rename="csaRating")]
    pub csa_rating: Option<String>,
    /// The video's rating from Luxembourg's Commission de surveillance de la classification des films (CSCF).
    #[serde(rename="cscfRating")]
    pub cscf_rating: Option<String>,
    /// The video's rating in the Czech Republic.
    #[serde(rename="czfilmRating")]
    pub czfilm_rating: Option<String>,
    /// The video's Departamento de Justiça, Classificação, Qualificação e Títulos (DJCQT - Brazil) rating.
    #[serde(rename="djctqRating")]
    pub djctq_rating: Option<String>,
    /// Reasons that explain why the video received its DJCQT (Brazil) rating.
    #[serde(rename="djctqRatingReasons")]
    pub djctq_rating_reasons: Option<Vec<String>>,
    /// Rating system in Turkey - Evaluation and Classification Board of the Ministry of Culture and Tourism
    #[serde(rename="ecbmctRating")]
    pub ecbmct_rating: Option<String>,
    /// The video's rating in Estonia.
    #[serde(rename="eefilmRating")]
    pub eefilm_rating: Option<String>,
    /// The video's rating in Egypt.
    #[serde(rename="egfilmRating")]
    pub egfilm_rating: Option<String>,
    /// The video's Eirin (映倫) rating. Eirin is the Japanese rating system.
    #[serde(rename="eirinRating")]
    pub eirin_rating: Option<String>,
    /// The video's rating from Malaysia's Film Censorship Board.
    #[serde(rename="fcbmRating")]
    pub fcbm_rating: Option<String>,
    /// The video's rating from Hong Kong's Office for Film, Newspaper and Article Administration.
    #[serde(rename="fcoRating")]
    pub fco_rating: Option<String>,
    /// This property has been deprecated. Use the contentDetails.contentRating.cncRating instead.
    #[serde(rename="fmocRating")]
    pub fmoc_rating: Option<String>,
    /// The video's rating from South Africa's Film and Publication Board.
    #[serde(rename="fpbRating")]
    pub fpb_rating: Option<String>,
    /// Reasons that explain why the video received its FPB (South Africa) rating.
    #[serde(rename="fpbRatingReasons")]
    pub fpb_rating_reasons: Option<Vec<String>>,
    /// The video's Freiwillige Selbstkontrolle der Filmwirtschaft (FSK - Germany) rating.
    #[serde(rename="fskRating")]
    pub fsk_rating: Option<String>,
    /// The video's rating in Greece.
    #[serde(rename="grfilmRating")]
    pub grfilm_rating: Option<String>,
    /// The video's Instituto de la Cinematografía y de las Artes Audiovisuales (ICAA - Spain) rating.
    #[serde(rename="icaaRating")]
    pub icaa_rating: Option<String>,
    /// The video's Irish Film Classification Office (IFCO - Ireland) rating. See the IFCO website for more information.
    #[serde(rename="ifcoRating")]
    pub ifco_rating: Option<String>,
    /// The video's rating in Israel.
    #[serde(rename="ilfilmRating")]
    pub ilfilm_rating: Option<String>,
    /// The video's INCAA (Instituto Nacional de Cine y Artes Audiovisuales - Argentina) rating.
    #[serde(rename="incaaRating")]
    pub incaa_rating: Option<String>,
    /// The video's rating from the Kenya Film Classification Board.
    #[serde(rename="kfcbRating")]
    pub kfcb_rating: Option<String>,
    /// The video's NICAM/Kijkwijzer rating from the Nederlands Instituut voor de Classificatie van Audiovisuele Media (Netherlands).
    #[serde(rename="kijkwijzerRating")]
    pub kijkwijzer_rating: Option<String>,
    /// The video's Korea Media Rating Board (영상물등급위원회) rating. The KMRB rates videos in South Korea.
    #[serde(rename="kmrbRating")]
    pub kmrb_rating: Option<String>,
    /// The video's rating from Indonesia's Lembaga Sensor Film.
    #[serde(rename="lsfRating")]
    pub lsf_rating: Option<String>,
    /// The video's rating from Malta's Film Age-Classification Board.
    #[serde(rename="mccaaRating")]
    pub mccaa_rating: Option<String>,
    /// The video's rating from the Danish Film Institute's (Det Danske Filminstitut) Media Council for Children and Young People.
    #[serde(rename="mccypRating")]
    pub mccyp_rating: Option<String>,
    /// The video's rating system for Vietnam - MCST
    #[serde(rename="mcstRating")]
    pub mcst_rating: Option<String>,
    /// The video's rating from Singapore's Media Development Authority (MDA) and, specifically, it's Board of Film Censors (BFC).
    #[serde(rename="mdaRating")]
    pub mda_rating: Option<String>,
    /// The video's rating from Medietilsynet, the Norwegian Media Authority.
    #[serde(rename="medietilsynetRating")]
    pub medietilsynet_rating: Option<String>,
    /// The video's rating from Finland's Kansallinen Audiovisuaalinen Instituutti (National Audiovisual Institute).
    #[serde(rename="mekuRating")]
    pub meku_rating: Option<String>,
    /// The rating system for MENA countries, a clone of MPAA. It is needed to prevent titles go live w/o additional QC check, since some of them can be inappropriate for the countries at all. See b/33408548 for more details.
    #[serde(rename="menaMpaaRating")]
    pub mena_mpaa_rating: Option<String>,
    /// The video's rating from the Ministero dei Beni e delle Attività Culturali e del Turismo (Italy).
    #[serde(rename="mibacRating")]
    pub mibac_rating: Option<String>,
    /// The video's Ministerio de Cultura (Colombia) rating.
    #[serde(rename="mocRating")]
    pub moc_rating: Option<String>,
    /// The video's rating from Taiwan's Ministry of Culture (文化部).
    #[serde(rename="moctwRating")]
    pub moctw_rating: Option<String>,
    /// The video's Motion Picture Association of America (MPAA) rating.
    #[serde(rename="mpaaRating")]
    pub mpaa_rating: Option<String>,
    /// The rating system for trailer, DVD, and Ad in the US. See http://movielabs.com/md/ratings/v2.3/html/US_MPAAT_Ratings.html.
    #[serde(rename="mpaatRating")]
    pub mpaat_rating: Option<String>,
    /// The video's rating from the Movie and Television Review and Classification Board (Philippines).
    #[serde(rename="mtrcbRating")]
    pub mtrcb_rating: Option<String>,
    /// The video's rating from the Maldives National Bureau of Classification.
    #[serde(rename="nbcRating")]
    pub nbc_rating: Option<String>,
    /// The video's rating in Poland.
    #[serde(rename="nbcplRating")]
    pub nbcpl_rating: Option<String>,
    /// The video's rating from the Bulgarian National Film Center.
    #[serde(rename="nfrcRating")]
    pub nfrc_rating: Option<String>,
    /// The video's rating from Nigeria's National Film and Video Censors Board.
    #[serde(rename="nfvcbRating")]
    pub nfvcb_rating: Option<String>,
    /// The video's rating from the Nacionãlais Kino centrs (National Film Centre of Latvia).
    #[serde(rename="nkclvRating")]
    pub nkclv_rating: Option<String>,
    /// The National Media Council ratings system for United Arab Emirates.
    #[serde(rename="nmcRating")]
    pub nmc_rating: Option<String>,
    /// The video's Office of Film and Literature Classification (OFLC - New Zealand) rating.
    #[serde(rename="oflcRating")]
    pub oflc_rating: Option<String>,
    /// The video's rating in Peru.
    #[serde(rename="pefilmRating")]
    pub pefilm_rating: Option<String>,
    /// The video's rating from the Hungarian Nemzeti Filmiroda, the Rating Committee of the National Office of Film.
    #[serde(rename="rcnofRating")]
    pub rcnof_rating: Option<String>,
    /// The video's rating in Venezuela.
    #[serde(rename="resorteviolenciaRating")]
    pub resorteviolencia_rating: Option<String>,
    /// The video's General Directorate of Radio, Television and Cinematography (Mexico) rating.
    #[serde(rename="rtcRating")]
    pub rtc_rating: Option<String>,
    /// The video's rating from Ireland's Raidió Teilifís Éireann.
    #[serde(rename="rteRating")]
    pub rte_rating: Option<String>,
    /// The video's National Film Registry of the Russian Federation (MKRF - Russia) rating.
    #[serde(rename="russiaRating")]
    pub russia_rating: Option<String>,
    /// The video's rating in Slovakia.
    #[serde(rename="skfilmRating")]
    pub skfilm_rating: Option<String>,
    /// The video's rating in Iceland.
    #[serde(rename="smaisRating")]
    pub smais_rating: Option<String>,
    /// The video's rating from Statens medieråd (Sweden's National Media Council).
    #[serde(rename="smsaRating")]
    pub smsa_rating: Option<String>,
    /// The video's TV Parental Guidelines (TVPG) rating.
    #[serde(rename="tvpgRating")]
    pub tvpg_rating: Option<String>,
    /// A rating that YouTube uses to identify age-restricted content.
    #[serde(rename="ytRating")]
    pub yt_rating: Option<String>,
}

impl client::Part for ContentRating {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Entity {
    /// no description provided
    pub id: Option<String>,
    /// no description provided
    #[serde(rename="typeId")]
    pub type_id: Option<String>,
    /// no description provided
    pub url: Option<String>,
}

impl client::Part for Entity {}


/// Geographical coordinates of a point, in WGS84.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GeoPoint {
    /// Altitude above the reference ellipsoid, in meters.
    pub altitude: Option<f64>,
    /// Latitude in degrees.
    pub latitude: Option<f64>,
    /// Longitude in degrees.
    pub longitude: Option<f64>,
}

impl client::Part for GeoPoint {}


/// An *i18nLanguage* resource identifies a UI language currently supported by YouTube.
/// 
/// # 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*).
/// 
/// * [list i18n languages](I18nLanguageListCall) (none)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct I18nLanguage {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube uses to uniquely identify the i18n language.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#i18nLanguage".
    pub kind: Option<String>,
    /// The snippet object contains basic details about the i18n language, such as language code and human-readable name.
    pub snippet: Option<I18nLanguageSnippet>,
}

impl client::Resource for I18nLanguage {}

impl client::ToParts for I18nLanguage {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list i18n languages](I18nLanguageListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct I18nLanguageListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of supported i18n languages. In this map, the i18n language ID is the map key, and its value is the corresponding i18nLanguage resource.
    pub items: Option<Vec<I18nLanguage>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#i18nLanguageListResponse".
    pub kind: Option<String>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for I18nLanguageListResponse {}

impl client::ToParts for I18nLanguageListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// Basic details about an i18n language, such as language code and human-readable name.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct I18nLanguageSnippet {
    /// A short BCP-47 code that uniquely identifies a language.
    pub hl: Option<String>,
    /// The human-readable name of the language in the language itself.
    pub name: Option<String>,
}

impl client::Part for I18nLanguageSnippet {}


/// A *i18nRegion* resource identifies a region where YouTube is available.
/// 
/// # 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*).
/// 
/// * [list i18n regions](I18nRegionListCall) (none)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct I18nRegion {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube uses to uniquely identify the i18n region.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#i18nRegion".
    pub kind: Option<String>,
    /// The snippet object contains basic details about the i18n region, such as region code and human-readable name.
    pub snippet: Option<I18nRegionSnippet>,
}

impl client::Resource for I18nRegion {}

impl client::ToParts for I18nRegion {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list i18n regions](I18nRegionListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct I18nRegionListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of regions where YouTube is available. In this map, the i18n region ID is the map key, and its value is the corresponding i18nRegion resource.
    pub items: Option<Vec<I18nRegion>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#i18nRegionListResponse".
    pub kind: Option<String>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for I18nRegionListResponse {}

impl client::ToParts for I18nRegionListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// Basic details about an i18n region, such as region code and human-readable name.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct I18nRegionSnippet {
    /// The region code as a 2-letter ISO country code.
    pub gl: Option<String>,
    /// The human-readable name of the region.
    pub name: Option<String>,
}

impl client::Part for I18nRegionSnippet {}


/// Branding properties for images associated with the channel.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ImageSettings {
    /// The URL for the background image shown on the video watch page. The image should be 1200px by 615px, with a maximum file size of 128k.
    #[serde(rename="backgroundImageUrl")]
    pub background_image_url: Option<LocalizedProperty>,
    /// This is generated when a ChannelBanner.Insert request has succeeded for the given channel.
    #[serde(rename="bannerExternalUrl")]
    pub banner_external_url: Option<String>,
    /// Banner image. Desktop size (1060x175).
    #[serde(rename="bannerImageUrl")]
    pub banner_image_url: Option<String>,
    /// Banner image. Mobile size high resolution (1440x395).
    #[serde(rename="bannerMobileExtraHdImageUrl")]
    pub banner_mobile_extra_hd_image_url: Option<String>,
    /// Banner image. Mobile size high resolution (1280x360).
    #[serde(rename="bannerMobileHdImageUrl")]
    pub banner_mobile_hd_image_url: Option<String>,
    /// Banner image. Mobile size (640x175).
    #[serde(rename="bannerMobileImageUrl")]
    pub banner_mobile_image_url: Option<String>,
    /// Banner image. Mobile size low resolution (320x88).
    #[serde(rename="bannerMobileLowImageUrl")]
    pub banner_mobile_low_image_url: Option<String>,
    /// Banner image. Mobile size medium/high resolution (960x263).
    #[serde(rename="bannerMobileMediumHdImageUrl")]
    pub banner_mobile_medium_hd_image_url: Option<String>,
    /// Banner image. Tablet size extra high resolution (2560x424).
    #[serde(rename="bannerTabletExtraHdImageUrl")]
    pub banner_tablet_extra_hd_image_url: Option<String>,
    /// Banner image. Tablet size high resolution (2276x377).
    #[serde(rename="bannerTabletHdImageUrl")]
    pub banner_tablet_hd_image_url: Option<String>,
    /// Banner image. Tablet size (1707x283).
    #[serde(rename="bannerTabletImageUrl")]
    pub banner_tablet_image_url: Option<String>,
    /// Banner image. Tablet size low resolution (1138x188).
    #[serde(rename="bannerTabletLowImageUrl")]
    pub banner_tablet_low_image_url: Option<String>,
    /// Banner image. TV size high resolution (1920x1080).
    #[serde(rename="bannerTvHighImageUrl")]
    pub banner_tv_high_image_url: Option<String>,
    /// Banner image. TV size extra high resolution (2120x1192).
    #[serde(rename="bannerTvImageUrl")]
    pub banner_tv_image_url: Option<String>,
    /// Banner image. TV size low resolution (854x480).
    #[serde(rename="bannerTvLowImageUrl")]
    pub banner_tv_low_image_url: Option<String>,
    /// Banner image. TV size medium resolution (1280x720).
    #[serde(rename="bannerTvMediumImageUrl")]
    pub banner_tv_medium_image_url: Option<String>,
    /// The image map script for the large banner image.
    #[serde(rename="largeBrandedBannerImageImapScript")]
    pub large_branded_banner_image_imap_script: Option<LocalizedProperty>,
    /// The URL for the 854px by 70px image that appears below the video player in the expanded video view of the video watch page.
    #[serde(rename="largeBrandedBannerImageUrl")]
    pub large_branded_banner_image_url: Option<LocalizedProperty>,
    /// The image map script for the small banner image.
    #[serde(rename="smallBrandedBannerImageImapScript")]
    pub small_branded_banner_image_imap_script: Option<LocalizedProperty>,
    /// The URL for the 640px by 70px banner image that appears below the video player in the default view of the video watch page. The URL for the image that appears above the top-left corner of the video player. This is a 25-pixel-high image with a flexible width that cannot exceed 170 pixels.
    #[serde(rename="smallBrandedBannerImageUrl")]
    pub small_branded_banner_image_url: Option<LocalizedProperty>,
    /// The URL for a 1px by 1px tracking pixel that can be used to collect statistics for views of the channel or video pages.
    #[serde(rename="trackingImageUrl")]
    pub tracking_image_url: Option<String>,
    /// no description provided
    #[serde(rename="watchIconImageUrl")]
    pub watch_icon_image_url: Option<String>,
}

impl client::Part for ImageSettings {}


/// Describes information necessary for ingesting an RTMP, HTTP, or SRT stream.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct IngestionInfo {
    /// The backup ingestion URL that you should use to stream video to YouTube. You have the option of simultaneously streaming the content that you are sending to the ingestionAddress to this URL.
    #[serde(rename="backupIngestionAddress")]
    pub backup_ingestion_address: Option<String>,
    /// The primary ingestion URL that you should use to stream video to YouTube. You must stream video to this URL. Depending on which application or tool you use to encode your video stream, you may need to enter the stream URL and stream name separately or you may need to concatenate them in the following format: *STREAM_URL/STREAM_NAME* 
    #[serde(rename="ingestionAddress")]
    pub ingestion_address: Option<String>,
    /// This ingestion url may be used instead of backupIngestionAddress in order to stream via RTMPS. Not applicable to non-RTMP streams.
    #[serde(rename="rtmpsBackupIngestionAddress")]
    pub rtmps_backup_ingestion_address: Option<String>,
    /// This ingestion url may be used instead of ingestionAddress in order to stream via RTMPS. Not applicable to non-RTMP streams.
    #[serde(rename="rtmpsIngestionAddress")]
    pub rtmps_ingestion_address: Option<String>,
    /// The stream name that YouTube assigns to the video stream.
    #[serde(rename="streamName")]
    pub stream_name: Option<String>,
}

impl client::Part for IngestionInfo {}


/// LINT.IfChange Describes an invideo branding.
/// 
/// # 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*).
/// 
/// * [set watermarks](WatermarkSetCall) (request)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct InvideoBranding {
    /// The bytes the uploaded image. Only used in api to youtube communication.
    #[serde(rename="imageBytes")]
    pub image_bytes: Option<String>,
    /// The url of the uploaded image. Only used in apiary to api communication.
    #[serde(rename="imageUrl")]
    pub image_url: Option<String>,
    /// The spatial position within the video where the branding watermark will be displayed.
    pub position: Option<InvideoPosition>,
    /// The channel to which this branding links. If not present it defaults to the current channel.
    #[serde(rename="targetChannelId")]
    pub target_channel_id: Option<String>,
    /// The temporal position within the video where watermark will be displayed.
    pub timing: Option<InvideoTiming>,
}

impl client::RequestValue for InvideoBranding {}


/// Describes the spatial position of a visual widget inside a video. It is a union of various position types, out of which only will be set one.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct InvideoPosition {
    /// Describes in which corner of the video the visual widget will appear.
    #[serde(rename="cornerPosition")]
    pub corner_position: Option<String>,
    /// Defines the position type.
    #[serde(rename="type")]
    pub type_: Option<String>,
}

impl client::Part for InvideoPosition {}


/// Describes a temporal position of a visual widget inside a video.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct InvideoTiming {
    /// Defines the duration in milliseconds for which the promotion should be displayed. If missing, the client should use the default.
    #[serde(rename="durationMs")]
    pub duration_ms: Option<String>,
    /// Defines the time at which the promotion will appear. Depending on the value of type the value of the offsetMs field will represent a time offset from the start or from the end of the video, expressed in milliseconds.
    #[serde(rename="offsetMs")]
    pub offset_ms: Option<String>,
    /// Describes a timing type. If the value is offsetFromStart, then the offsetMs field represents an offset from the start of the video. If the value is offsetFromEnd, then the offsetMs field represents an offset from the end of the video.
    #[serde(rename="type")]
    pub type_: Option<String>,
}

impl client::Part for InvideoTiming {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LanguageTag {
    /// no description provided
    pub value: Option<String>,
}

impl client::Part for LanguageTag {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LevelDetails {
    /// The name that should be used when referring to this level.
    #[serde(rename="displayName")]
    pub display_name: Option<String>,
}

impl client::Part for LevelDetails {}


/// A *liveBroadcast* resource represents an event that will be streamed, via live video, on YouTube.
/// 
/// # 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*).
/// 
/// * [bind live broadcasts](LiveBroadcastBindCall) (response)
/// * [delete live broadcasts](LiveBroadcastDeleteCall) (none)
/// * [insert live broadcasts](LiveBroadcastInsertCall) (request|response)
/// * [list live broadcasts](LiveBroadcastListCall) (none)
/// * [transition live broadcasts](LiveBroadcastTransitionCall) (response)
/// * [update live broadcasts](LiveBroadcastUpdateCall) (request|response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveBroadcast {
    /// The contentDetails object contains information about the event's video content, such as whether the content can be shown in an embedded video player or if it will be archived and therefore available for viewing after the event has concluded.
    #[serde(rename="contentDetails")]
    pub content_details: Option<LiveBroadcastContentDetails>,
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube assigns to uniquely identify the broadcast.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#liveBroadcast".
    pub kind: Option<String>,
    /// The snippet object contains basic details about the event, including its title, description, start time, and end time.
    pub snippet: Option<LiveBroadcastSnippet>,
    /// The statistics object contains info about the event's current stats. These include concurrent viewers and total chat count. Statistics can change (in either direction) during the lifetime of an event. Statistics are only returned while the event is live.
    pub statistics: Option<LiveBroadcastStatistics>,
    /// The status object contains information about the event's status.
    pub status: Option<LiveBroadcastStatus>,
}

impl client::RequestValue for LiveBroadcast {}
impl client::Resource for LiveBroadcast {}
impl client::ResponseResult for LiveBroadcast {}

impl client::ToParts for LiveBroadcast {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.content_details.is_some() { r = r + "contentDetails,"; }
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        if self.statistics.is_some() { r = r + "statistics,"; }
        if self.status.is_some() { r = r + "status,"; }
        r.pop();
        r
    }
}

/// Detailed settings of a broadcast.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveBroadcastContentDetails {
    /// This value uniquely identifies the live stream bound to the broadcast.
    #[serde(rename="boundStreamId")]
    pub bound_stream_id: Option<String>,
    /// The date and time that the live stream referenced by boundStreamId was last updated.
    #[serde(rename="boundStreamLastUpdateTimeMs")]
    pub bound_stream_last_update_time_ms: Option<String>,
    /// no description provided
    #[serde(rename="closedCaptionsType")]
    pub closed_captions_type: Option<String>,
    /// This setting indicates whether auto start is enabled for this broadcast. The default value for this property is false. This setting can only be used by Events.
    #[serde(rename="enableAutoStart")]
    pub enable_auto_start: Option<bool>,
    /// This setting indicates whether auto stop is enabled for this broadcast. The default value for this property is false. This setting can only be used by Events.
    #[serde(rename="enableAutoStop")]
    pub enable_auto_stop: Option<bool>,
    /// This setting indicates whether HTTP POST closed captioning is enabled for this broadcast. The ingestion URL of the closed captions is returned through the liveStreams API. This is mutually exclusive with using the closed_captions_type property, and is equivalent to setting closed_captions_type to CLOSED_CAPTIONS_HTTP_POST.
    #[serde(rename="enableClosedCaptions")]
    pub enable_closed_captions: Option<bool>,
    /// This setting indicates whether YouTube should enable content encryption for the broadcast.
    #[serde(rename="enableContentEncryption")]
    pub enable_content_encryption: Option<bool>,
    /// This setting determines whether viewers can access DVR controls while watching the video. DVR controls enable the viewer to control the video playback experience by pausing, rewinding, or fast forwarding content. The default value for this property is true. *Important:* You must set the value to true and also set the enableArchive property's value to true if you want to make playback available immediately after the broadcast ends.
    #[serde(rename="enableDvr")]
    pub enable_dvr: Option<bool>,
    /// This setting indicates whether the broadcast video can be played in an embedded player. If you choose to archive the video (using the enableArchive property), this setting will also apply to the archived video.
    #[serde(rename="enableEmbed")]
    pub enable_embed: Option<bool>,
    /// Indicates whether this broadcast has low latency enabled.
    #[serde(rename="enableLowLatency")]
    pub enable_low_latency: Option<bool>,
    /// If both this and enable_low_latency are set, they must match. LATENCY_NORMAL should match enable_low_latency=false LATENCY_LOW should match enable_low_latency=true LATENCY_ULTRA_LOW should have enable_low_latency omitted.
    #[serde(rename="latencyPreference")]
    pub latency_preference: Option<String>,
    /// The mesh for projecting the video if projection is mesh. The mesh value must be a UTF-8 string containing the base-64 encoding of 3D mesh data that follows the Spherical Video V2 RFC specification for an mshp box, excluding the box size and type but including the following four reserved zero bytes for the version and flags.
    pub mesh: Option<String>,
    /// The monitorStream object contains information about the monitor stream, which the broadcaster can use to review the event content before the broadcast stream is shown publicly.
    #[serde(rename="monitorStream")]
    pub monitor_stream: Option<MonitorStreamInfo>,
    /// The projection format of this broadcast. This defaults to rectangular.
    pub projection: Option<String>,
    /// Automatically start recording after the event goes live. The default value for this property is true. *Important:* You must also set the enableDvr property's value to true if you want the playback to be available immediately after the broadcast ends. If you set this property's value to true but do not also set the enableDvr property to true, there may be a delay of around one day before the archived video will be available for playback.
    #[serde(rename="recordFromStart")]
    pub record_from_start: Option<bool>,
    /// This setting indicates whether the broadcast should automatically begin with an in-stream slate when you update the broadcast's status to live. After updating the status, you then need to send a liveCuepoints.insert request that sets the cuepoint's eventState to end to remove the in-stream slate and make your broadcast stream visible to viewers.
    #[serde(rename="startWithSlate")]
    pub start_with_slate: Option<bool>,
    /// The 3D stereo layout of this broadcast. This defaults to mono.
    #[serde(rename="stereoLayout")]
    pub stereo_layout: Option<String>,
}

impl client::Part for LiveBroadcastContentDetails {}


/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list live broadcasts](LiveBroadcastListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveBroadcastListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of broadcasts that match the request criteria.
    pub items: Option<Vec<LiveBroadcast>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#liveBroadcastListResponse".
    pub kind: Option<String>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
    #[serde(rename="nextPageToken")]
    pub next_page_token: Option<String>,
    /// General pagination information.
    #[serde(rename="pageInfo")]
    pub page_info: Option<PageInfo>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the previous page in the result set.
    #[serde(rename="prevPageToken")]
    pub prev_page_token: Option<String>,
    /// no description provided
    #[serde(rename="tokenPagination")]
    pub token_pagination: Option<TokenPagination>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for LiveBroadcastListResponse {}

impl client::ToParts for LiveBroadcastListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.next_page_token.is_some() { r = r + "nextPageToken,"; }
        if self.page_info.is_some() { r = r + "pageInfo,"; }
        if self.prev_page_token.is_some() { r = r + "prevPageToken,"; }
        if self.token_pagination.is_some() { r = r + "tokenPagination,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// Basic broadcast information.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveBroadcastSnippet {
    /// The date and time that the broadcast actually ended. This information is only available once the broadcast's state is complete.
    #[serde(rename="actualEndTime")]
    pub actual_end_time: Option<String>,
    /// The date and time that the broadcast actually started. This information is only available once the broadcast's state is live.
    #[serde(rename="actualStartTime")]
    pub actual_start_time: Option<String>,
    /// The ID that YouTube uses to uniquely identify the channel that is publishing the broadcast.
    #[serde(rename="channelId")]
    pub channel_id: Option<String>,
    /// The broadcast's description. As with the title, you can set this field by modifying the broadcast resource or by setting the description field of the corresponding video resource.
    pub description: Option<String>,
    /// Indicates whether this broadcast is the default broadcast. Internal only.
    #[serde(rename="isDefaultBroadcast")]
    pub is_default_broadcast: Option<bool>,
    /// The id of the live chat for this broadcast.
    #[serde(rename="liveChatId")]
    pub live_chat_id: Option<String>,
    /// The date and time that the broadcast was added to YouTube's live broadcast schedule.
    #[serde(rename="publishedAt")]
    pub published_at: Option<String>,
    /// The date and time that the broadcast is scheduled to end.
    #[serde(rename="scheduledEndTime")]
    pub scheduled_end_time: Option<String>,
    /// The date and time that the broadcast is scheduled to start.
    #[serde(rename="scheduledStartTime")]
    pub scheduled_start_time: Option<String>,
    /// A map of thumbnail images associated with the broadcast. For each nested object in this object, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail.
    pub thumbnails: Option<ThumbnailDetails>,
    /// The broadcast's title. Note that the broadcast represents exactly one YouTube video. You can set this field by modifying the broadcast resource or by setting the title field of the corresponding video resource.
    pub title: Option<String>,
}

impl client::Part for LiveBroadcastSnippet {}


/// Statistics about the live broadcast. These represent a snapshot of the values at the time of the request. Statistics are only returned for live broadcasts.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveBroadcastStatistics {
    /// The total number of live chat messages currently on the broadcast. The property and its value will be present if the broadcast is public, has the live chat feature enabled, and has at least one message. Note that this field will not be filled after the broadcast ends. So this property would not identify the number of chat messages for an archived video of a completed live broadcast.
    #[serde(rename="totalChatCount")]
    pub total_chat_count: Option<String>,
}

impl client::Part for LiveBroadcastStatistics {}


/// Live broadcast state.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveBroadcastStatus {
    /// The broadcast's status. The status can be updated using the API's liveBroadcasts.transition method.
    #[serde(rename="lifeCycleStatus")]
    pub life_cycle_status: Option<String>,
    /// Priority of the live broadcast event (internal state).
    #[serde(rename="liveBroadcastPriority")]
    pub live_broadcast_priority: Option<String>,
    /// Whether the broadcast is made for kids or not, decided by YouTube instead of the creator. This field is read only.
    #[serde(rename="madeForKids")]
    pub made_for_kids: Option<bool>,
    /// The broadcast's privacy status. Note that the broadcast represents exactly one YouTube video, so the privacy settings are identical to those supported for videos. In addition, you can set this field by modifying the broadcast resource or by setting the privacyStatus field of the corresponding video resource.
    #[serde(rename="privacyStatus")]
    pub privacy_status: Option<String>,
    /// The broadcast's recording status.
    #[serde(rename="recordingStatus")]
    pub recording_status: Option<String>,
    /// This field will be set to True if the creator declares the broadcast to be kids only: go/live-cw-work.
    #[serde(rename="selfDeclaredMadeForKids")]
    pub self_declared_made_for_kids: Option<bool>,
}

impl client::Part for LiveBroadcastStatus {}


/// A `__liveChatBan__` resource represents a ban for a YouTube live chat.
/// 
/// # 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*).
/// 
/// * [delete live chat bans](LiveChatBanDeleteCall) (none)
/// * [insert live chat bans](LiveChatBanInsertCall) (request|response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatBan {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube assigns to uniquely identify the ban.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string `"youtube#liveChatBan"`.
    pub kind: Option<String>,
    /// The `snippet` object contains basic details about the ban.
    pub snippet: Option<LiveChatBanSnippet>,
}

impl client::RequestValue for LiveChatBan {}
impl client::Resource for LiveChatBan {}
impl client::ResponseResult for LiveChatBan {}

impl client::ToParts for LiveChatBan {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatBanSnippet {
    /// The duration of a ban, only filled if the ban has type TEMPORARY.
    #[serde(rename="banDurationSeconds")]
    pub ban_duration_seconds: Option<String>,
    /// no description provided
    #[serde(rename="bannedUserDetails")]
    pub banned_user_details: Option<ChannelProfileDetails>,
    /// The chat this ban is pertinent to.
    #[serde(rename="liveChatId")]
    pub live_chat_id: Option<String>,
    /// The type of ban.
    #[serde(rename="type")]
    pub type_: Option<String>,
}

impl client::Part for LiveChatBanSnippet {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatFanFundingEventDetails {
    /// A rendered string that displays the fund amount and currency to the user.
    #[serde(rename="amountDisplayString")]
    pub amount_display_string: Option<String>,
    /// The amount of the fund.
    #[serde(rename="amountMicros")]
    pub amount_micros: Option<String>,
    /// The currency in which the fund was made.
    pub currency: Option<String>,
    /// The comment added by the user to this fan funding event.
    #[serde(rename="userComment")]
    pub user_comment: Option<String>,
}

impl client::Part for LiveChatFanFundingEventDetails {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatMemberMilestoneChatDetails {
    /// The name of the Level at which the viever is a member. The Level names are defined by the YouTube channel offering the Membership. In some situations this field isn't filled.
    #[serde(rename="memberLevelName")]
    pub member_level_name: Option<String>,
    /// The total amount of months (rounded up) the viewer has been a member that granted them this Member Milestone Chat. This is the same number of months as is being displayed to YouTube users.
    #[serde(rename="memberMonth")]
    pub member_month: Option<u32>,
    /// The comment added by the member to this Member Milestone Chat. This field is empty for messages without a comment from the member.
    #[serde(rename="userComment")]
    pub user_comment: Option<String>,
}

impl client::Part for LiveChatMemberMilestoneChatDetails {}


/// A *liveChatMessage* resource represents a chat message in a YouTube Live Chat.
/// 
/// # 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*).
/// 
/// * [delete live chat messages](LiveChatMessageDeleteCall) (none)
/// * [insert live chat messages](LiveChatMessageInsertCall) (request|response)
/// * [list live chat messages](LiveChatMessageListCall) (none)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatMessage {
    /// The authorDetails object contains basic details about the user that posted this message.
    #[serde(rename="authorDetails")]
    pub author_details: Option<LiveChatMessageAuthorDetails>,
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube assigns to uniquely identify the message.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#liveChatMessage".
    pub kind: Option<String>,
    /// The snippet object contains basic details about the message.
    pub snippet: Option<LiveChatMessageSnippet>,
}

impl client::RequestValue for LiveChatMessage {}
impl client::Resource for LiveChatMessage {}
impl client::ResponseResult for LiveChatMessage {}

impl client::ToParts for LiveChatMessage {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.author_details.is_some() { r = r + "authorDetails,"; }
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatMessageAuthorDetails {
    /// The YouTube channel ID.
    #[serde(rename="channelId")]
    pub channel_id: Option<String>,
    /// The channel's URL.
    #[serde(rename="channelUrl")]
    pub channel_url: Option<String>,
    /// The channel's display name.
    #[serde(rename="displayName")]
    pub display_name: Option<String>,
    /// Whether the author is a moderator of the live chat.
    #[serde(rename="isChatModerator")]
    pub is_chat_moderator: Option<bool>,
    /// Whether the author is the owner of the live chat.
    #[serde(rename="isChatOwner")]
    pub is_chat_owner: Option<bool>,
    /// Whether the author is a sponsor of the live chat.
    #[serde(rename="isChatSponsor")]
    pub is_chat_sponsor: Option<bool>,
    /// Whether the author's identity has been verified by YouTube.
    #[serde(rename="isVerified")]
    pub is_verified: Option<bool>,
    /// The channels's avatar URL.
    #[serde(rename="profileImageUrl")]
    pub profile_image_url: Option<String>,
}

impl client::Part for LiveChatMessageAuthorDetails {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatMessageDeletedDetails {
    /// no description provided
    #[serde(rename="deletedMessageId")]
    pub deleted_message_id: Option<String>,
}

impl client::Part for LiveChatMessageDeletedDetails {}


/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list live chat messages](LiveChatMessageListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatMessageListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// no description provided
    pub items: Option<Vec<LiveChatMessage>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#liveChatMessageListResponse".
    pub kind: Option<String>,
    /// no description provided
    #[serde(rename="nextPageToken")]
    pub next_page_token: Option<String>,
    /// The date and time when the underlying stream went offline.
    #[serde(rename="offlineAt")]
    pub offline_at: Option<String>,
    /// General pagination information.
    #[serde(rename="pageInfo")]
    pub page_info: Option<PageInfo>,
    /// The amount of time the client should wait before polling again.
    #[serde(rename="pollingIntervalMillis")]
    pub polling_interval_millis: Option<u32>,
    /// no description provided
    #[serde(rename="tokenPagination")]
    pub token_pagination: Option<TokenPagination>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for LiveChatMessageListResponse {}

impl client::ToParts for LiveChatMessageListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.next_page_token.is_some() { r = r + "nextPageToken,"; }
        if self.offline_at.is_some() { r = r + "offlineAt,"; }
        if self.page_info.is_some() { r = r + "pageInfo,"; }
        if self.polling_interval_millis.is_some() { r = r + "pollingIntervalMillis,"; }
        if self.token_pagination.is_some() { r = r + "tokenPagination,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatMessageRetractedDetails {
    /// no description provided
    #[serde(rename="retractedMessageId")]
    pub retracted_message_id: Option<String>,
}

impl client::Part for LiveChatMessageRetractedDetails {}


/// Next ID: 31
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatMessageSnippet {
    /// The ID of the user that authored this message, this field is not always filled. textMessageEvent - the user that wrote the message fanFundingEvent - the user that funded the broadcast newSponsorEvent - the user that just became a sponsor memberMilestoneChatEvent - the member that sent the message messageDeletedEvent - the moderator that took the action messageRetractedEvent - the author that retracted their message userBannedEvent - the moderator that took the action superChatEvent - the user that made the purchase superStickerEvent - the user that made the purchase
    #[serde(rename="authorChannelId")]
    pub author_channel_id: Option<String>,
    /// Contains a string that can be displayed to the user. If this field is not present the message is silent, at the moment only messages of type TOMBSTONE and CHAT_ENDED_EVENT are silent.
    #[serde(rename="displayMessage")]
    pub display_message: Option<String>,
    /// Details about the funding event, this is only set if the type is 'fanFundingEvent'.
    #[serde(rename="fanFundingEventDetails")]
    pub fan_funding_event_details: Option<LiveChatFanFundingEventDetails>,
    /// Whether the message has display content that should be displayed to users.
    #[serde(rename="hasDisplayContent")]
    pub has_display_content: Option<bool>,
    /// no description provided
    #[serde(rename="liveChatId")]
    pub live_chat_id: Option<String>,
    /// Details about the Member Milestone Chat event, this is only set if the type is 'memberMilestoneChatEvent'.
    #[serde(rename="memberMilestoneChatDetails")]
    pub member_milestone_chat_details: Option<LiveChatMemberMilestoneChatDetails>,
    /// no description provided
    #[serde(rename="messageDeletedDetails")]
    pub message_deleted_details: Option<LiveChatMessageDeletedDetails>,
    /// no description provided
    #[serde(rename="messageRetractedDetails")]
    pub message_retracted_details: Option<LiveChatMessageRetractedDetails>,
    /// Details about the New Member Announcement event, this is only set if the type is 'newSponsorEvent'. Please note that "member" is the new term for "sponsor".
    #[serde(rename="newSponsorDetails")]
    pub new_sponsor_details: Option<LiveChatNewSponsorDetails>,
    /// The date and time when the message was orignally published.
    #[serde(rename="publishedAt")]
    pub published_at: Option<String>,
    /// Details about the Super Chat event, this is only set if the type is 'superChatEvent'.
    #[serde(rename="superChatDetails")]
    pub super_chat_details: Option<LiveChatSuperChatDetails>,
    /// Details about the Super Sticker event, this is only set if the type is 'superStickerEvent'.
    #[serde(rename="superStickerDetails")]
    pub super_sticker_details: Option<LiveChatSuperStickerDetails>,
    /// Details about the text message, this is only set if the type is 'textMessageEvent'.
    #[serde(rename="textMessageDetails")]
    pub text_message_details: Option<LiveChatTextMessageDetails>,
    /// The type of message, this will always be present, it determines the contents of the message as well as which fields will be present.
    #[serde(rename="type")]
    pub type_: Option<String>,
    /// no description provided
    #[serde(rename="userBannedDetails")]
    pub user_banned_details: Option<LiveChatUserBannedMessageDetails>,
}

impl client::Part for LiveChatMessageSnippet {}


/// A *liveChatModerator* resource represents a moderator for a YouTube live chat. A chat moderator has the ability to ban/unban users from a chat, remove message, etc.
/// 
/// # 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*).
/// 
/// * [delete live chat moderators](LiveChatModeratorDeleteCall) (none)
/// * [insert live chat moderators](LiveChatModeratorInsertCall) (request|response)
/// * [list live chat moderators](LiveChatModeratorListCall) (none)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatModerator {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube assigns to uniquely identify the moderator.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#liveChatModerator".
    pub kind: Option<String>,
    /// The snippet object contains basic details about the moderator.
    pub snippet: Option<LiveChatModeratorSnippet>,
}

impl client::RequestValue for LiveChatModerator {}
impl client::Resource for LiveChatModerator {}
impl client::ResponseResult for LiveChatModerator {}

impl client::ToParts for LiveChatModerator {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list live chat moderators](LiveChatModeratorListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatModeratorListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of moderators that match the request criteria.
    pub items: Option<Vec<LiveChatModerator>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#liveChatModeratorListResponse".
    pub kind: Option<String>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
    #[serde(rename="nextPageToken")]
    pub next_page_token: Option<String>,
    /// General pagination information.
    #[serde(rename="pageInfo")]
    pub page_info: Option<PageInfo>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the previous page in the result set.
    #[serde(rename="prevPageToken")]
    pub prev_page_token: Option<String>,
    /// no description provided
    #[serde(rename="tokenPagination")]
    pub token_pagination: Option<TokenPagination>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for LiveChatModeratorListResponse {}

impl client::ToParts for LiveChatModeratorListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.next_page_token.is_some() { r = r + "nextPageToken,"; }
        if self.page_info.is_some() { r = r + "pageInfo,"; }
        if self.prev_page_token.is_some() { r = r + "prevPageToken,"; }
        if self.token_pagination.is_some() { r = r + "tokenPagination,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatModeratorSnippet {
    /// The ID of the live chat this moderator can act on.
    #[serde(rename="liveChatId")]
    pub live_chat_id: Option<String>,
    /// Details about the moderator.
    #[serde(rename="moderatorDetails")]
    pub moderator_details: Option<ChannelProfileDetails>,
}

impl client::Part for LiveChatModeratorSnippet {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatNewSponsorDetails {
    /// If the viewer just had upgraded from a lower level. For viewers that were not members at the time of purchase, this field is false.
    #[serde(rename="isUpgrade")]
    pub is_upgrade: Option<bool>,
    /// The name of the Level that the viewer just had joined. The Level names are defined by the YouTube channel offering the Membership. In some situations this field isn't filled.
    #[serde(rename="memberLevelName")]
    pub member_level_name: Option<String>,
}

impl client::Part for LiveChatNewSponsorDetails {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatSuperChatDetails {
    /// A rendered string that displays the fund amount and currency to the user.
    #[serde(rename="amountDisplayString")]
    pub amount_display_string: Option<String>,
    /// The amount purchased by the user, in micros (1,750,000 micros = 1.75).
    #[serde(rename="amountMicros")]
    pub amount_micros: Option<String>,
    /// The currency in which the purchase was made.
    pub currency: Option<String>,
    /// The tier in which the amount belongs. Lower amounts belong to lower tiers. The lowest tier is 1.
    pub tier: Option<u32>,
    /// The comment added by the user to this Super Chat event.
    #[serde(rename="userComment")]
    pub user_comment: Option<String>,
}

impl client::Part for LiveChatSuperChatDetails {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatSuperStickerDetails {
    /// A rendered string that displays the fund amount and currency to the user.
    #[serde(rename="amountDisplayString")]
    pub amount_display_string: Option<String>,
    /// The amount purchased by the user, in micros (1,750,000 micros = 1.75).
    #[serde(rename="amountMicros")]
    pub amount_micros: Option<String>,
    /// The currency in which the purchase was made.
    pub currency: Option<String>,
    /// Information about the Super Sticker.
    #[serde(rename="superStickerMetadata")]
    pub super_sticker_metadata: Option<SuperStickerMetadata>,
    /// The tier in which the amount belongs. Lower amounts belong to lower tiers. The lowest tier is 1.
    pub tier: Option<u32>,
}

impl client::Part for LiveChatSuperStickerDetails {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatTextMessageDetails {
    /// The user's message.
    #[serde(rename="messageText")]
    pub message_text: Option<String>,
}

impl client::Part for LiveChatTextMessageDetails {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveChatUserBannedMessageDetails {
    /// The duration of the ban. This property is only present if the banType is temporary.
    #[serde(rename="banDurationSeconds")]
    pub ban_duration_seconds: Option<String>,
    /// The type of ban.
    #[serde(rename="banType")]
    pub ban_type: Option<String>,
    /// The details of the user that was banned.
    #[serde(rename="bannedUserDetails")]
    pub banned_user_details: Option<ChannelProfileDetails>,
}

impl client::Part for LiveChatUserBannedMessageDetails {}


/// A live stream describes a live ingestion point.
/// 
/// # 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*).
/// 
/// * [delete live streams](LiveStreamDeleteCall) (none)
/// * [insert live streams](LiveStreamInsertCall) (request|response)
/// * [list live streams](LiveStreamListCall) (none)
/// * [update live streams](LiveStreamUpdateCall) (request|response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveStream {
    /// The cdn object defines the live stream's content delivery network (CDN) settings. These settings provide details about the manner in which you stream your content to YouTube.
    pub cdn: Option<CdnSettings>,
    /// The content_details object contains information about the stream, including the closed captions ingestion URL.
    #[serde(rename="contentDetails")]
    pub content_details: Option<LiveStreamContentDetails>,
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube assigns to uniquely identify the stream.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#liveStream".
    pub kind: Option<String>,
    /// The snippet object contains basic details about the stream, including its channel, title, and description.
    pub snippet: Option<LiveStreamSnippet>,
    /// The status object contains information about live stream's status.
    pub status: Option<LiveStreamStatus>,
}

impl client::RequestValue for LiveStream {}
impl client::Resource for LiveStream {}
impl client::ResponseResult for LiveStream {}

impl client::ToParts for LiveStream {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.cdn.is_some() { r = r + "cdn,"; }
        if self.content_details.is_some() { r = r + "contentDetails,"; }
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        if self.status.is_some() { r = r + "status,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveStreamConfigurationIssue {
    /// The long-form description of the issue and how to resolve it.
    pub description: Option<String>,
    /// The short-form reason for this issue.
    pub reason: Option<String>,
    /// How severe this issue is to the stream.
    pub severity: Option<String>,
    /// The kind of error happening.
    #[serde(rename="type")]
    pub type_: Option<String>,
}

impl client::Part for LiveStreamConfigurationIssue {}


/// Detailed settings of a stream.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveStreamContentDetails {
    /// The ingestion URL where the closed captions of this stream are sent.
    #[serde(rename="closedCaptionsIngestionUrl")]
    pub closed_captions_ingestion_url: Option<String>,
    /// Indicates whether the stream is reusable, which means that it can be bound to multiple broadcasts. It is common for broadcasters to reuse the same stream for many different broadcasts if those broadcasts occur at different times. If you set this value to false, then the stream will not be reusable, which means that it can only be bound to one broadcast. Non-reusable streams differ from reusable streams in the following ways: - A non-reusable stream can only be bound to one broadcast. - A non-reusable stream might be deleted by an automated process after the broadcast ends. - The liveStreams.list method does not list non-reusable streams if you call the method and set the mine parameter to true. The only way to use that method to retrieve the resource for a non-reusable stream is to use the id parameter to identify the stream. 
    #[serde(rename="isReusable")]
    pub is_reusable: Option<bool>,
}

impl client::Part for LiveStreamContentDetails {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveStreamHealthStatus {
    /// The configurations issues on this stream
    #[serde(rename="configurationIssues")]
    pub configuration_issues: Option<Vec<LiveStreamConfigurationIssue>>,
    /// The last time this status was updated (in seconds)
    #[serde(rename="lastUpdateTimeSeconds")]
    pub last_update_time_seconds: Option<String>,
    /// The status code of this stream
    pub status: Option<String>,
}

impl client::Part for LiveStreamHealthStatus {}


/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list live streams](LiveStreamListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveStreamListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of live streams that match the request criteria.
    pub items: Option<Vec<LiveStream>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#liveStreamListResponse".
    pub kind: Option<String>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
    #[serde(rename="nextPageToken")]
    pub next_page_token: Option<String>,
    /// no description provided
    #[serde(rename="pageInfo")]
    pub page_info: Option<PageInfo>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the previous page in the result set.
    #[serde(rename="prevPageToken")]
    pub prev_page_token: Option<String>,
    /// no description provided
    #[serde(rename="tokenPagination")]
    pub token_pagination: Option<TokenPagination>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for LiveStreamListResponse {}

impl client::ToParts for LiveStreamListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.next_page_token.is_some() { r = r + "nextPageToken,"; }
        if self.page_info.is_some() { r = r + "pageInfo,"; }
        if self.prev_page_token.is_some() { r = r + "prevPageToken,"; }
        if self.token_pagination.is_some() { r = r + "tokenPagination,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveStreamSnippet {
    /// The ID that YouTube uses to uniquely identify the channel that is transmitting the stream.
    #[serde(rename="channelId")]
    pub channel_id: Option<String>,
    /// The stream's description. The value cannot be longer than 10000 characters.
    pub description: Option<String>,
    /// no description provided
    #[serde(rename="isDefaultStream")]
    pub is_default_stream: Option<bool>,
    /// The date and time that the stream was created.
    #[serde(rename="publishedAt")]
    pub published_at: Option<String>,
    /// The stream's title. The value must be between 1 and 128 characters long.
    pub title: Option<String>,
}

impl client::Part for LiveStreamSnippet {}


/// Brief description of the live stream status.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LiveStreamStatus {
    /// The health status of the stream.
    #[serde(rename="healthStatus")]
    pub health_status: Option<LiveStreamHealthStatus>,
    /// no description provided
    #[serde(rename="streamStatus")]
    pub stream_status: Option<String>,
}

impl client::Part for LiveStreamStatus {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LocalizedProperty {
    /// no description provided
    pub default: Option<String>,
    /// The language of the default property.
    #[serde(rename="defaultLanguage")]
    pub default_language: Option<LanguageTag>,
    /// no description provided
    pub localized: Option<Vec<LocalizedString>>,
}

impl client::Part for LocalizedProperty {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LocalizedString {
    /// no description provided
    pub language: Option<String>,
    /// no description provided
    pub value: Option<String>,
}

impl client::Part for LocalizedString {}


/// A *member* resource represents a member for a YouTube channel. A member provides recurring monetary support to a creator and receives special benefits.
/// 
/// # 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*).
/// 
/// * [list members](MemberListCall) (none)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Member {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#member".
    pub kind: Option<String>,
    /// The snippet object contains basic details about the member.
    pub snippet: Option<MemberSnippet>,
}

impl client::Resource for Member {}

impl client::ToParts for Member {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list members](MemberListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct MemberListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of members that match the request criteria.
    pub items: Option<Vec<Member>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#memberListResponse".
    pub kind: Option<String>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
    #[serde(rename="nextPageToken")]
    pub next_page_token: Option<String>,
    /// no description provided
    #[serde(rename="pageInfo")]
    pub page_info: Option<PageInfo>,
    /// no description provided
    #[serde(rename="tokenPagination")]
    pub token_pagination: Option<TokenPagination>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for MemberListResponse {}

impl client::ToParts for MemberListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.next_page_token.is_some() { r = r + "nextPageToken,"; }
        if self.page_info.is_some() { r = r + "pageInfo,"; }
        if self.token_pagination.is_some() { r = r + "tokenPagination,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct MemberSnippet {
    /// The id of the channel that's offering memberships.
    #[serde(rename="creatorChannelId")]
    pub creator_channel_id: Option<String>,
    /// Details about the member.
    #[serde(rename="memberDetails")]
    pub member_details: Option<ChannelProfileDetails>,
    /// Details about the user's membership.
    #[serde(rename="membershipsDetails")]
    pub memberships_details: Option<MembershipsDetails>,
}

impl client::Part for MemberSnippet {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct MembershipsDetails {
    /// Ids of all levels that the user has access to. This includes the currently active level and all other levels that are included because of a higher purchase.
    #[serde(rename="accessibleLevels")]
    pub accessible_levels: Option<Vec<String>>,
    /// Id of the highest level that the user has access to at the moment.
    #[serde(rename="highestAccessibleLevel")]
    pub highest_accessible_level: Option<String>,
    /// Display name for the highest level that the user has access to at the moment.
    #[serde(rename="highestAccessibleLevelDisplayName")]
    pub highest_accessible_level_display_name: Option<String>,
    /// Data about memberships duration without taking into consideration pricing levels.
    #[serde(rename="membershipsDuration")]
    pub memberships_duration: Option<MembershipsDuration>,
    /// Data about memberships duration on particular pricing levels.
    #[serde(rename="membershipsDurationAtLevels")]
    pub memberships_duration_at_levels: Option<Vec<MembershipsDurationAtLevel>>,
}

impl client::Part for MembershipsDetails {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct MembershipsDuration {
    /// The date and time when the user became a continuous member across all levels.
    #[serde(rename="memberSince")]
    pub member_since: Option<String>,
    /// The cumulative time the user has been a member across all levels in complete months (the time is rounded down to the nearest integer).
    #[serde(rename="memberTotalDurationMonths")]
    pub member_total_duration_months: Option<i32>,
}

impl client::Part for MembershipsDuration {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct MembershipsDurationAtLevel {
    /// Pricing level ID.
    pub level: Option<String>,
    /// The date and time when the user became a continuous member for the given level.
    #[serde(rename="memberSince")]
    pub member_since: Option<String>,
    /// The cumulative time the user has been a member for the given level in complete months (the time is rounded down to the nearest integer).
    #[serde(rename="memberTotalDurationMonths")]
    pub member_total_duration_months: Option<i32>,
}

impl client::Part for MembershipsDurationAtLevel {}


/// A *membershipsLevel* resource represents an offer made by YouTube creators for their fans. Users can become members of the channel by joining one of the available levels. They will provide recurring monetary support and receives special benefits.
/// 
/// # 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*).
/// 
/// * [list memberships levels](MembershipsLevelListCall) (none)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct MembershipsLevel {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube assigns to uniquely identify the memberships level.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#membershipsLevelListResponse".
    pub kind: Option<String>,
    /// The snippet object contains basic details about the level.
    pub snippet: Option<MembershipsLevelSnippet>,
}

impl client::Resource for MembershipsLevel {}

impl client::ToParts for MembershipsLevel {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list memberships levels](MembershipsLevelListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct MembershipsLevelListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of pricing levels offered by a creator to the fans.
    pub items: Option<Vec<MembershipsLevel>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#membershipsLevelListResponse".
    pub kind: Option<String>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for MembershipsLevelListResponse {}

impl client::ToParts for MembershipsLevelListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct MembershipsLevelSnippet {
    /// The id of the channel that's offering channel memberships.
    #[serde(rename="creatorChannelId")]
    pub creator_channel_id: Option<String>,
    /// Details about the pricing level.
    #[serde(rename="levelDetails")]
    pub level_details: Option<LevelDetails>,
}

impl client::Part for MembershipsLevelSnippet {}


/// Settings and Info of the monitor stream
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct MonitorStreamInfo {
    /// If you have set the enableMonitorStream property to true, then this property determines the length of the live broadcast delay.
    #[serde(rename="broadcastStreamDelayMs")]
    pub broadcast_stream_delay_ms: Option<u32>,
    /// HTML code that embeds a player that plays the monitor stream.
    #[serde(rename="embedHtml")]
    pub embed_html: Option<String>,
    /// This value determines whether the monitor stream is enabled for the broadcast. If the monitor stream is enabled, then YouTube will broadcast the event content on a special stream intended only for the broadcaster's consumption. The broadcaster can use the stream to review the event content and also to identify the optimal times to insert cuepoints. You need to set this value to true if you intend to have a broadcast delay for your event. *Note:* This property cannot be updated once the broadcast is in the testing or live state.
    #[serde(rename="enableMonitorStream")]
    pub enable_monitor_stream: Option<bool>,
}

impl client::Part for MonitorStreamInfo {}


/// Paging details for lists of resources, including total number of items available and number of resources returned in a single page.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PageInfo {
    /// The number of results included in the API response.
    #[serde(rename="resultsPerPage")]
    pub results_per_page: Option<i32>,
    /// The total number of results in the result set.
    #[serde(rename="totalResults")]
    pub total_results: Option<i32>,
}

impl client::Part for PageInfo {}


/// A *playlist* resource represents a YouTube playlist. A playlist is a collection of videos that can be viewed sequentially and shared with other users. A playlist can contain up to 200 videos, and YouTube does not limit the number of playlists that each user creates. By default, playlists are publicly visible to other users, but playlists can be public or private. YouTube also uses playlists to identify special collections of videos for a channel, such as: - uploaded videos - favorite videos - positively rated (liked) videos - watch history - watch later To be more specific, these lists are associated with a channel, which is a collection of a person, group, or company's videos, playlists, and other YouTube information. You can retrieve the playlist IDs for each of these lists from the channel resource for a given channel. You can then use the playlistItems.list method to retrieve any of those lists. You can also add or remove items from those lists by calling the playlistItems.insert and playlistItems.delete methods.
/// 
/// # 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*).
/// 
/// * [delete playlists](PlaylistDeleteCall) (none)
/// * [insert playlists](PlaylistInsertCall) (request|response)
/// * [list playlists](PlaylistListCall) (none)
/// * [update playlists](PlaylistUpdateCall) (request|response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Playlist {
    /// The contentDetails object contains information like video count.
    #[serde(rename="contentDetails")]
    pub content_details: Option<PlaylistContentDetails>,
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube uses to uniquely identify the playlist.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#playlist".
    pub kind: Option<String>,
    /// Localizations for different languages
    pub localizations: Option<HashMap<String, PlaylistLocalization>>,
    /// The player object contains information that you would use to play the playlist in an embedded player.
    pub player: Option<PlaylistPlayer>,
    /// The snippet object contains basic details about the playlist, such as its title and description.
    pub snippet: Option<PlaylistSnippet>,
    /// The status object contains status information for the playlist.
    pub status: Option<PlaylistStatus>,
}

impl client::RequestValue for Playlist {}
impl client::Resource for Playlist {}
impl client::ResponseResult for Playlist {}

impl client::ToParts for Playlist {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.content_details.is_some() { r = r + "contentDetails,"; }
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.localizations.is_some() { r = r + "localizations,"; }
        if self.player.is_some() { r = r + "player,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        if self.status.is_some() { r = r + "status,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PlaylistContentDetails {
    /// The number of videos in the playlist.
    #[serde(rename="itemCount")]
    pub item_count: Option<u32>,
}

impl client::Part for PlaylistContentDetails {}


/// A *playlistItem* resource identifies another resource, such as a video, that is included in a playlist. In addition, the playlistItem resource contains details about the included resource that pertain specifically to how that resource is used in that playlist. YouTube uses playlists to identify special collections of videos for a channel, such as: - uploaded videos - favorite videos - positively rated (liked) videos - watch history - watch later To be more specific, these lists are associated with a channel, which is a collection of a person, group, or company's videos, playlists, and other YouTube information. You can retrieve the playlist IDs for each of these lists from the channel resource for a given channel. You can then use the playlistItems.list method to retrieve any of those lists. You can also add or remove items from those lists by calling the playlistItems.insert and playlistItems.delete methods. For example, if a user gives a positive rating to a video, you would insert that video into the liked videos playlist for that user's channel.
/// 
/// # 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*).
/// 
/// * [delete playlist items](PlaylistItemDeleteCall) (none)
/// * [insert playlist items](PlaylistItemInsertCall) (request|response)
/// * [list playlist items](PlaylistItemListCall) (none)
/// * [update playlist items](PlaylistItemUpdateCall) (request|response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PlaylistItem {
    /// The contentDetails object is included in the resource if the included item is a YouTube video. The object contains additional information about the video.
    #[serde(rename="contentDetails")]
    pub content_details: Option<PlaylistItemContentDetails>,
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube uses to uniquely identify the playlist item.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#playlistItem".
    pub kind: Option<String>,
    /// The snippet object contains basic details about the playlist item, such as its title and position in the playlist.
    pub snippet: Option<PlaylistItemSnippet>,
    /// The status object contains information about the playlist item's privacy status.
    pub status: Option<PlaylistItemStatus>,
}

impl client::RequestValue for PlaylistItem {}
impl client::Resource for PlaylistItem {}
impl client::ResponseResult for PlaylistItem {}

impl client::ToParts for PlaylistItem {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.content_details.is_some() { r = r + "contentDetails,"; }
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        if self.status.is_some() { r = r + "status,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PlaylistItemContentDetails {
    /// The time, measured in seconds from the start of the video, when the video should stop playing. (The playlist owner can specify the times when the video should start and stop playing when the video is played in the context of the playlist.) By default, assume that the video.endTime is the end of the video.
    #[serde(rename="endAt")]
    pub end_at: Option<String>,
    /// A user-generated note for this item.
    pub note: Option<String>,
    /// The time, measured in seconds from the start of the video, when the video should start playing. (The playlist owner can specify the times when the video should start and stop playing when the video is played in the context of the playlist.) The default value is 0.
    #[serde(rename="startAt")]
    pub start_at: Option<String>,
    /// The ID that YouTube uses to uniquely identify a video. To retrieve the video resource, set the id query parameter to this value in your API request.
    #[serde(rename="videoId")]
    pub video_id: Option<String>,
    /// The date and time that the video was published to YouTube.
    #[serde(rename="videoPublishedAt")]
    pub video_published_at: Option<String>,
}

impl client::Part for PlaylistItemContentDetails {}


/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list playlist items](PlaylistItemListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PlaylistItemListResponse {
    /// no description provided
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of playlist items that match the request criteria.
    pub items: Option<Vec<PlaylistItem>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#playlistItemListResponse". Etag of this resource.
    pub kind: Option<String>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
    #[serde(rename="nextPageToken")]
    pub next_page_token: Option<String>,
    /// General pagination information.
    #[serde(rename="pageInfo")]
    pub page_info: Option<PageInfo>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the previous page in the result set.
    #[serde(rename="prevPageToken")]
    pub prev_page_token: Option<String>,
    /// no description provided
    #[serde(rename="tokenPagination")]
    pub token_pagination: Option<TokenPagination>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for PlaylistItemListResponse {}

impl client::ToParts for PlaylistItemListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.next_page_token.is_some() { r = r + "nextPageToken,"; }
        if self.page_info.is_some() { r = r + "pageInfo,"; }
        if self.prev_page_token.is_some() { r = r + "prevPageToken,"; }
        if self.token_pagination.is_some() { r = r + "tokenPagination,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// Basic details about a playlist, including title, description and thumbnails. Basic details of a YouTube Playlist item provided by the author. Next ID: 15
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PlaylistItemSnippet {
    /// The ID that YouTube uses to uniquely identify the user that added the item to the playlist.
    #[serde(rename="channelId")]
    pub channel_id: Option<String>,
    /// Channel title for the channel that the playlist item belongs to.
    #[serde(rename="channelTitle")]
    pub channel_title: Option<String>,
    /// The item's description.
    pub description: Option<String>,
    /// The ID that YouTube uses to uniquely identify thGe playlist that the playlist item is in.
    #[serde(rename="playlistId")]
    pub playlist_id: Option<String>,
    /// The order in which the item appears in the playlist. The value uses a zero-based index, so the first item has a position of 0, the second item has a position of 1, and so forth.
    pub position: Option<u32>,
    /// The date and time that the item was added to the playlist.
    #[serde(rename="publishedAt")]
    pub published_at: Option<String>,
    /// The id object contains information that can be used to uniquely identify the resource that is included in the playlist as the playlist item.
    #[serde(rename="resourceId")]
    pub resource_id: Option<ResourceId>,
    /// A map of thumbnail images associated with the playlist item. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail.
    pub thumbnails: Option<ThumbnailDetails>,
    /// The item's title.
    pub title: Option<String>,
    /// Channel id for the channel this video belongs to.
    #[serde(rename="videoOwnerChannelId")]
    pub video_owner_channel_id: Option<String>,
    /// Channel title for the channel this video belongs to.
    #[serde(rename="videoOwnerChannelTitle")]
    pub video_owner_channel_title: Option<String>,
}

impl client::Part for PlaylistItemSnippet {}


/// Information about the playlist item's privacy status.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PlaylistItemStatus {
    /// This resource's privacy status.
    #[serde(rename="privacyStatus")]
    pub privacy_status: Option<String>,
}

impl client::Part for PlaylistItemStatus {}


/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list playlists](PlaylistListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PlaylistListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of playlists that match the request criteria
    pub items: Option<Vec<Playlist>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#playlistListResponse".
    pub kind: Option<String>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
    #[serde(rename="nextPageToken")]
    pub next_page_token: Option<String>,
    /// General pagination information.
    #[serde(rename="pageInfo")]
    pub page_info: Option<PageInfo>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the previous page in the result set.
    #[serde(rename="prevPageToken")]
    pub prev_page_token: Option<String>,
    /// no description provided
    #[serde(rename="tokenPagination")]
    pub token_pagination: Option<TokenPagination>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for PlaylistListResponse {}

impl client::ToParts for PlaylistListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.next_page_token.is_some() { r = r + "nextPageToken,"; }
        if self.page_info.is_some() { r = r + "pageInfo,"; }
        if self.prev_page_token.is_some() { r = r + "prevPageToken,"; }
        if self.token_pagination.is_some() { r = r + "tokenPagination,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// Playlist localization setting
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PlaylistLocalization {
    /// The localized strings for playlist's description.
    pub description: Option<String>,
    /// The localized strings for playlist's title.
    pub title: Option<String>,
}

impl client::Part for PlaylistLocalization {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PlaylistPlayer {
    /// An <iframe> tag that embeds a player that will play the playlist.
    #[serde(rename="embedHtml")]
    pub embed_html: Option<String>,
}

impl client::Part for PlaylistPlayer {}


/// Basic details about a playlist, including title, description and thumbnails.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PlaylistSnippet {
    /// The ID that YouTube uses to uniquely identify the channel that published the playlist.
    #[serde(rename="channelId")]
    pub channel_id: Option<String>,
    /// The channel title of the channel that the video belongs to.
    #[serde(rename="channelTitle")]
    pub channel_title: Option<String>,
    /// The language of the playlist's default title and description.
    #[serde(rename="defaultLanguage")]
    pub default_language: Option<String>,
    /// The playlist's description.
    pub description: Option<String>,
    /// Localized title and description, read-only.
    pub localized: Option<PlaylistLocalization>,
    /// The date and time that the playlist was created.
    #[serde(rename="publishedAt")]
    pub published_at: Option<String>,
    /// Keyword tags associated with the playlist.
    pub tags: Option<Vec<String>>,
    /// Note: if the playlist has a custom thumbnail, this field will not be populated. The video id selected by the user that will be used as the thumbnail of this playlist. This field defaults to the first publicly viewable video in the playlist, if: 1. The user has never selected a video to be the thumbnail of the playlist. 2. The user selects a video to be the thumbnail, and then removes that video from the playlist. 3. The user selects a non-owned video to be the thumbnail, but that video becomes private, or gets deleted.
    #[serde(rename="thumbnailVideoId")]
    pub thumbnail_video_id: Option<String>,
    /// A map of thumbnail images associated with the playlist. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail.
    pub thumbnails: Option<ThumbnailDetails>,
    /// The playlist's title.
    pub title: Option<String>,
}

impl client::Part for PlaylistSnippet {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PlaylistStatus {
    /// The playlist's privacy status.
    #[serde(rename="privacyStatus")]
    pub privacy_status: Option<String>,
}

impl client::Part for PlaylistStatus {}


/// A pair Property / Value.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PropertyValue {
    /// A property.
    pub property: Option<String>,
    /// The property's value.
    pub value: Option<String>,
}

impl client::Part for PropertyValue {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct RelatedEntity {
    /// no description provided
    pub entity: Option<Entity>,
}

impl client::Part for RelatedEntity {}


/// A resource id is a generic reference that points to another YouTube resource.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ResourceId {
    /// The ID that YouTube uses to uniquely identify the referred resource, if that resource is a channel. This property is only present if the resourceId.kind value is youtube#channel.
    #[serde(rename="channelId")]
    pub channel_id: Option<String>,
    /// The type of the API resource.
    pub kind: Option<String>,
    /// The ID that YouTube uses to uniquely identify the referred resource, if that resource is a playlist. This property is only present if the resourceId.kind value is youtube#playlist.
    #[serde(rename="playlistId")]
    pub playlist_id: Option<String>,
    /// The ID that YouTube uses to uniquely identify the referred resource, if that resource is a video. This property is only present if the resourceId.kind value is youtube#video.
    #[serde(rename="videoId")]
    pub video_id: Option<String>,
}

impl client::Part for ResourceId {}


/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list search](SearchListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct SearchListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// Pagination information for token pagination.
    pub items: Option<Vec<SearchResult>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#searchListResponse".
    pub kind: Option<String>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
    #[serde(rename="nextPageToken")]
    pub next_page_token: Option<String>,
    /// General pagination information.
    #[serde(rename="pageInfo")]
    pub page_info: Option<PageInfo>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the previous page in the result set.
    #[serde(rename="prevPageToken")]
    pub prev_page_token: Option<String>,
    /// no description provided
    #[serde(rename="regionCode")]
    pub region_code: Option<String>,
    /// no description provided
    #[serde(rename="tokenPagination")]
    pub token_pagination: Option<TokenPagination>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for SearchListResponse {}

impl client::ToParts for SearchListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.next_page_token.is_some() { r = r + "nextPageToken,"; }
        if self.page_info.is_some() { r = r + "pageInfo,"; }
        if self.prev_page_token.is_some() { r = r + "prevPageToken,"; }
        if self.region_code.is_some() { r = r + "regionCode,"; }
        if self.token_pagination.is_some() { r = r + "tokenPagination,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// A search result contains information about a YouTube video, channel, or playlist that matches the search parameters specified in an API request. While a search result points to a uniquely identifiable resource, like a video, it does not have its own persistent data.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct SearchResult {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The id object contains information that can be used to uniquely identify the resource that matches the search request.
    pub id: Option<ResourceId>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#searchResult".
    pub kind: Option<String>,
    /// The snippet object contains basic details about a search result, such as its title or description. For example, if the search result is a video, then the title will be the video's title and the description will be the video's description.
    pub snippet: Option<SearchResultSnippet>,
}

impl client::Part for SearchResult {}


/// Basic details about a search result, including title, description and thumbnails of the item referenced by the search result.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct SearchResultSnippet {
    /// The value that YouTube uses to uniquely identify the channel that published the resource that the search result identifies.
    #[serde(rename="channelId")]
    pub channel_id: Option<String>,
    /// The title of the channel that published the resource that the search result identifies.
    #[serde(rename="channelTitle")]
    pub channel_title: Option<String>,
    /// A description of the search result.
    pub description: Option<String>,
    /// It indicates if the resource (video or channel) has upcoming/active live broadcast content. Or it's "none" if there is not any upcoming/active live broadcasts.
    #[serde(rename="liveBroadcastContent")]
    pub live_broadcast_content: Option<String>,
    /// The creation date and time of the resource that the search result identifies.
    #[serde(rename="publishedAt")]
    pub published_at: Option<String>,
    /// A map of thumbnail images associated with the search result. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail.
    pub thumbnails: Option<ThumbnailDetails>,
    /// The title of the search result.
    pub title: Option<String>,
}

impl client::Part for SearchResultSnippet {}


/// A *subscription* resource contains information about a YouTube user subscription. A subscription notifies a user when new videos are added to a channel or when another user takes one of several actions on YouTube, such as uploading a video, rating a video, or commenting on a video.
/// 
/// # 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*).
/// 
/// * [delete subscriptions](SubscriptionDeleteCall) (none)
/// * [insert subscriptions](SubscriptionInsertCall) (request|response)
/// * [list subscriptions](SubscriptionListCall) (none)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Subscription {
    /// The contentDetails object contains basic statistics about the subscription.
    #[serde(rename="contentDetails")]
    pub content_details: Option<SubscriptionContentDetails>,
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube uses to uniquely identify the subscription.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#subscription".
    pub kind: Option<String>,
    /// The snippet object contains basic details about the subscription, including its title and the channel that the user subscribed to.
    pub snippet: Option<SubscriptionSnippet>,
    /// The subscriberSnippet object contains basic details about the subscriber.
    #[serde(rename="subscriberSnippet")]
    pub subscriber_snippet: Option<SubscriptionSubscriberSnippet>,
}

impl client::RequestValue for Subscription {}
impl client::Resource for Subscription {}
impl client::ResponseResult for Subscription {}

impl client::ToParts for Subscription {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.content_details.is_some() { r = r + "contentDetails,"; }
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        if self.subscriber_snippet.is_some() { r = r + "subscriberSnippet,"; }
        r.pop();
        r
    }
}

/// Details about the content to witch a subscription refers.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct SubscriptionContentDetails {
    /// The type of activity this subscription is for (only uploads, everything).
    #[serde(rename="activityType")]
    pub activity_type: Option<String>,
    /// The number of new items in the subscription since its content was last read.
    #[serde(rename="newItemCount")]
    pub new_item_count: Option<u32>,
    /// The approximate number of items that the subscription points to.
    #[serde(rename="totalItemCount")]
    pub total_item_count: Option<u32>,
}

impl client::Part for SubscriptionContentDetails {}


/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list subscriptions](SubscriptionListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct SubscriptionListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of subscriptions that match the request criteria.
    pub items: Option<Vec<Subscription>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#subscriptionListResponse".
    pub kind: Option<String>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
    #[serde(rename="nextPageToken")]
    pub next_page_token: Option<String>,
    /// no description provided
    #[serde(rename="pageInfo")]
    pub page_info: Option<PageInfo>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the previous page in the result set.
    #[serde(rename="prevPageToken")]
    pub prev_page_token: Option<String>,
    /// no description provided
    #[serde(rename="tokenPagination")]
    pub token_pagination: Option<TokenPagination>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for SubscriptionListResponse {}

impl client::ToParts for SubscriptionListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.next_page_token.is_some() { r = r + "nextPageToken,"; }
        if self.page_info.is_some() { r = r + "pageInfo,"; }
        if self.prev_page_token.is_some() { r = r + "prevPageToken,"; }
        if self.token_pagination.is_some() { r = r + "tokenPagination,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// Basic details about a subscription, including title, description and thumbnails of the subscribed item.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct SubscriptionSnippet {
    /// The ID that YouTube uses to uniquely identify the subscriber's channel.
    #[serde(rename="channelId")]
    pub channel_id: Option<String>,
    /// Channel title for the channel that the subscription belongs to.
    #[serde(rename="channelTitle")]
    pub channel_title: Option<String>,
    /// The subscription's details.
    pub description: Option<String>,
    /// The date and time that the subscription was created.
    #[serde(rename="publishedAt")]
    pub published_at: Option<String>,
    /// The id object contains information about the channel that the user subscribed to.
    #[serde(rename="resourceId")]
    pub resource_id: Option<ResourceId>,
    /// A map of thumbnail images associated with the video. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail.
    pub thumbnails: Option<ThumbnailDetails>,
    /// The subscription's title.
    pub title: Option<String>,
}

impl client::Part for SubscriptionSnippet {}


/// Basic details about a subscription's subscriber including title, description, channel ID and thumbnails.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct SubscriptionSubscriberSnippet {
    /// The channel ID of the subscriber.
    #[serde(rename="channelId")]
    pub channel_id: Option<String>,
    /// The description of the subscriber.
    pub description: Option<String>,
    /// Thumbnails for this subscriber.
    pub thumbnails: Option<ThumbnailDetails>,
    /// The title of the subscriber.
    pub title: Option<String>,
}

impl client::Part for SubscriptionSubscriberSnippet {}


/// A `__superChatEvent__` resource represents a Super Chat purchase on a YouTube channel.
/// 
/// # 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*).
/// 
/// * [list super chat events](SuperChatEventListCall) (none)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct SuperChatEvent {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube assigns to uniquely identify the Super Chat event.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string `"youtube#superChatEvent"`.
    pub kind: Option<String>,
    /// The `snippet` object contains basic details about the Super Chat event.
    pub snippet: Option<SuperChatEventSnippet>,
}

impl client::Resource for SuperChatEvent {}

impl client::ToParts for SuperChatEvent {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list super chat events](SuperChatEventListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct SuperChatEventListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of Super Chat purchases that match the request criteria.
    pub items: Option<Vec<SuperChatEvent>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#superChatEventListResponse".
    pub kind: Option<String>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
    #[serde(rename="nextPageToken")]
    pub next_page_token: Option<String>,
    /// no description provided
    #[serde(rename="pageInfo")]
    pub page_info: Option<PageInfo>,
    /// no description provided
    #[serde(rename="tokenPagination")]
    pub token_pagination: Option<TokenPagination>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for SuperChatEventListResponse {}

impl client::ToParts for SuperChatEventListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.next_page_token.is_some() { r = r + "nextPageToken,"; }
        if self.page_info.is_some() { r = r + "pageInfo,"; }
        if self.token_pagination.is_some() { r = r + "tokenPagination,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct SuperChatEventSnippet {
    /// The purchase amount, in micros of the purchase currency. e.g., 1 is represented as 1000000.
    #[serde(rename="amountMicros")]
    pub amount_micros: Option<String>,
    /// Channel id where the event occurred.
    #[serde(rename="channelId")]
    pub channel_id: Option<String>,
    /// The text contents of the comment left by the user.
    #[serde(rename="commentText")]
    pub comment_text: Option<String>,
    /// The date and time when the event occurred.
    #[serde(rename="createdAt")]
    pub created_at: Option<String>,
    /// The currency in which the purchase was made. ISO 4217.
    pub currency: Option<String>,
    /// A rendered string that displays the purchase amount and currency (e.g., "$1.00"). The string is rendered for the given language.
    #[serde(rename="displayString")]
    pub display_string: Option<String>,
    /// True if this event is a Super Sticker event.
    #[serde(rename="isSuperStickerEvent")]
    pub is_super_sticker_event: Option<bool>,
    /// The tier for the paid message, which is based on the amount of money spent to purchase the message.
    #[serde(rename="messageType")]
    pub message_type: Option<u32>,
    /// If this event is a Super Sticker event, this field will contain metadata about the Super Sticker.
    #[serde(rename="superStickerMetadata")]
    pub super_sticker_metadata: Option<SuperStickerMetadata>,
    /// Details about the supporter.
    #[serde(rename="supporterDetails")]
    pub supporter_details: Option<ChannelProfileDetails>,
}

impl client::Part for SuperChatEventSnippet {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct SuperStickerMetadata {
    /// Internationalized alt text that describes the sticker image and any animation associated with it.
    #[serde(rename="altText")]
    pub alt_text: Option<String>,
    /// Specifies the localization language in which the alt text is returned.
    #[serde(rename="altTextLanguage")]
    pub alt_text_language: Option<String>,
    /// Unique identifier of the Super Sticker. This is a shorter form of the alt_text that includes pack name and a recognizable characteristic of the sticker.
    #[serde(rename="stickerId")]
    pub sticker_id: Option<String>,
}

impl client::Part for SuperStickerMetadata {}


/// There is no detailed description.
/// 
/// # 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 tests](TestInsertCall) (request|response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TestItem {
    /// no description provided
    #[serde(rename="featuredPart")]
    pub featured_part: Option<bool>,
    /// no description provided
    pub gaia: Option<String>,
    /// no description provided
    pub id: Option<String>,
    /// no description provided
    pub snippet: Option<TestItemTestItemSnippet>,
}

impl client::RequestValue for TestItem {}
impl client::ResponseResult for TestItem {}

impl client::ToParts for TestItem {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.featured_part.is_some() { r = r + "featuredPart,"; }
        if self.gaia.is_some() { r = r + "gaia,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TestItemTestItemSnippet { _never_set: Option<bool> }

impl client::Part for TestItemTestItemSnippet {}


/// A *third party account link* resource represents a link between a YouTube account or a channel and an account on a third-party service.
/// 
/// # 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*).
/// 
/// * [delete third party links](ThirdPartyLinkDeleteCall) (none)
/// * [insert third party links](ThirdPartyLinkInsertCall) (request|response)
/// * [list third party links](ThirdPartyLinkListCall) (response)
/// * [update third party links](ThirdPartyLinkUpdateCall) (request|response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ThirdPartyLink {
    /// Etag of this resource
    pub etag: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#thirdPartyLink".
    pub kind: Option<String>,
    /// The linking_token identifies a YouTube account and channel with which the third party account is linked.
    #[serde(rename="linkingToken")]
    pub linking_token: Option<String>,
    /// The snippet object contains basic details about the third- party account link.
    pub snippet: Option<ThirdPartyLinkSnippet>,
    /// The status object contains information about the status of the link.
    pub status: Option<ThirdPartyLinkStatus>,
}

impl client::RequestValue for ThirdPartyLink {}
impl client::Resource for ThirdPartyLink {}
impl client::ResponseResult for ThirdPartyLink {}

impl client::ToParts for ThirdPartyLink {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.linking_token.is_some() { r = r + "linkingToken,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        if self.status.is_some() { r = r + "status,"; }
        r.pop();
        r
    }
}

/// Basic information about a third party account link, including its type and type-specific information.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ThirdPartyLinkSnippet {
    /// Information specific to a link between a channel and a store on a merchandising platform.
    #[serde(rename="channelToStoreLink")]
    pub channel_to_store_link: Option<ChannelToStoreLinkDetails>,
    /// Type of the link named after the entities that are being linked.
    #[serde(rename="type")]
    pub type_: Option<String>,
}

impl client::Part for ThirdPartyLinkSnippet {}


/// The third-party link status object contains information about the status of the link.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ThirdPartyLinkStatus {
    /// no description provided
    #[serde(rename="linkStatus")]
    pub link_status: Option<String>,
}

impl client::Part for ThirdPartyLinkStatus {}


/// A thumbnail is an image representing a YouTube resource.
/// 
/// # 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*).
/// 
/// * [set thumbnails](ThumbnailSetCall) (none)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Thumbnail {
    /// (Optional) Height of the thumbnail image.
    pub height: Option<u32>,
    /// The thumbnail image's URL.
    pub url: Option<String>,
    /// (Optional) Width of the thumbnail image.
    pub width: Option<u32>,
}

impl client::Resource for Thumbnail {}


/// Internal representation of thumbnails for a YouTube resource.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ThumbnailDetails {
    /// The default image for this resource.
    pub default: Option<Thumbnail>,
    /// The high quality image for this resource.
    pub high: Option<Thumbnail>,
    /// The maximum resolution quality image for this resource.
    pub maxres: Option<Thumbnail>,
    /// The medium quality image for this resource.
    pub medium: Option<Thumbnail>,
    /// The standard quality image for this resource.
    pub standard: Option<Thumbnail>,
}

impl client::Part for ThumbnailDetails {}


/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [set thumbnails](ThumbnailSetCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ThumbnailSetResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of thumbnails.
    pub items: Option<Vec<ThumbnailDetails>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#thumbnailSetResponse".
    pub kind: Option<String>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for ThumbnailSetResponse {}


/// Stub token pagination template to suppress results.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TokenPagination { _never_set: Option<bool> }

impl client::Part for TokenPagination {}


/// A *video* resource represents a YouTube video.
/// 
/// # 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*).
/// 
/// * [delete videos](VideoDeleteCall) (none)
/// * [get rating videos](VideoGetRatingCall) (none)
/// * [insert videos](VideoInsertCall) (request|response)
/// * [list videos](VideoListCall) (none)
/// * [rate videos](VideoRateCall) (none)
/// * [report abuse videos](VideoReportAbuseCall) (none)
/// * [update videos](VideoUpdateCall) (request|response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Video {
    /// Age restriction details related to a video. This data can only be retrieved by the video owner.
    #[serde(rename="ageGating")]
    pub age_gating: Option<VideoAgeGating>,
    /// The contentDetails object contains information about the video content, including the length of the video and its aspect ratio.
    #[serde(rename="contentDetails")]
    pub content_details: Option<VideoContentDetails>,
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The fileDetails object encapsulates information about the video file that was uploaded to YouTube, including the file's resolution, duration, audio and video codecs, stream bitrates, and more. This data can only be retrieved by the video owner.
    #[serde(rename="fileDetails")]
    pub file_details: Option<VideoFileDetails>,
    /// The ID that YouTube uses to uniquely identify the video.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#video".
    pub kind: Option<String>,
    /// The liveStreamingDetails object contains metadata about a live video broadcast. The object will only be present in a video resource if the video is an upcoming, live, or completed live broadcast.
    #[serde(rename="liveStreamingDetails")]
    pub live_streaming_details: Option<VideoLiveStreamingDetails>,
    /// The localizations object contains localized versions of the basic details about the video, such as its title and description.
    pub localizations: Option<HashMap<String, VideoLocalization>>,
    /// The monetizationDetails object encapsulates information about the monetization status of the video.
    #[serde(rename="monetizationDetails")]
    pub monetization_details: Option<VideoMonetizationDetails>,
    /// The player object contains information that you would use to play the video in an embedded player.
    pub player: Option<VideoPlayer>,
    /// The processingDetails object encapsulates information about YouTube's progress in processing the uploaded video file. The properties in the object identify the current processing status and an estimate of the time remaining until YouTube finishes processing the video. This part also indicates whether different types of data or content, such as file details or thumbnail images, are available for the video. The processingProgress object is designed to be polled so that the video uploaded can track the progress that YouTube has made in processing the uploaded video file. This data can only be retrieved by the video owner.
    #[serde(rename="processingDetails")]
    pub processing_details: Option<VideoProcessingDetails>,
    /// The projectDetails object contains information about the project specific video metadata. b/157517979: This part was never populated after it was added. However, it sees non-zero traffic because there is generated client code in the wild that refers to it [1]. We keep this field and do NOT remove it because otherwise V3 would return an error when this part gets requested [2]. [1] https://developers.google.com/resources/api-libraries/documentation/youtube/v3/csharp/latest/classGoogle_1_1Apis_1_1YouTube_1_1v3_1_1Data_1_1VideoProjectDetails.html [2] http://google3/video/youtube/src/python/servers/data_api/common.py?l=1565-1569&rcl=344141677
    #[serde(rename="projectDetails")]
    pub project_details: Option<VideoProjectDetails>,
    /// The recordingDetails object encapsulates information about the location, date and address where the video was recorded.
    #[serde(rename="recordingDetails")]
    pub recording_details: Option<VideoRecordingDetails>,
    /// The snippet object contains basic details about the video, such as its title, description, and category.
    pub snippet: Option<VideoSnippet>,
    /// The statistics object contains statistics about the video.
    pub statistics: Option<VideoStatistics>,
    /// The status object contains information about the video's uploading, processing, and privacy statuses.
    pub status: Option<VideoStatus>,
    /// The suggestions object encapsulates suggestions that identify opportunities to improve the video quality or the metadata for the uploaded video. This data can only be retrieved by the video owner.
    pub suggestions: Option<VideoSuggestions>,
    /// The topicDetails object encapsulates information about Freebase topics associated with the video.
    #[serde(rename="topicDetails")]
    pub topic_details: Option<VideoTopicDetails>,
}

impl client::RequestValue for Video {}
impl client::Resource for Video {}
impl client::ResponseResult for Video {}

impl client::ToParts for Video {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.age_gating.is_some() { r = r + "ageGating,"; }
        if self.content_details.is_some() { r = r + "contentDetails,"; }
        if self.etag.is_some() { r = r + "etag,"; }
        if self.file_details.is_some() { r = r + "fileDetails,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.live_streaming_details.is_some() { r = r + "liveStreamingDetails,"; }
        if self.localizations.is_some() { r = r + "localizations,"; }
        if self.monetization_details.is_some() { r = r + "monetizationDetails,"; }
        if self.player.is_some() { r = r + "player,"; }
        if self.processing_details.is_some() { r = r + "processingDetails,"; }
        if self.project_details.is_some() { r = r + "projectDetails,"; }
        if self.recording_details.is_some() { r = r + "recordingDetails,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        if self.statistics.is_some() { r = r + "statistics,"; }
        if self.status.is_some() { r = r + "status,"; }
        if self.suggestions.is_some() { r = r + "suggestions,"; }
        if self.topic_details.is_some() { r = r + "topicDetails,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [report abuse videos](VideoReportAbuseCall) (request)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoAbuseReport {
    /// Additional comments regarding the abuse report.
    pub comments: Option<String>,
    /// The language that the content was viewed in.
    pub language: Option<String>,
    /// The high-level, or primary, reason that the content is abusive. The value is an abuse report reason ID.
    #[serde(rename="reasonId")]
    pub reason_id: Option<String>,
    /// The specific, or secondary, reason that this content is abusive (if available). The value is an abuse report reason ID that is a valid secondary reason for the primary reason.
    #[serde(rename="secondaryReasonId")]
    pub secondary_reason_id: Option<String>,
    /// The ID that YouTube uses to uniquely identify the video.
    #[serde(rename="videoId")]
    pub video_id: Option<String>,
}

impl client::RequestValue for VideoAbuseReport {}


/// A `__videoAbuseReportReason__` resource identifies a reason that a video could be reported as abusive. Video abuse report reasons are used with `video.ReportAbuse`.
/// 
/// # 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*).
/// 
/// * [list video abuse report reasons](VideoAbuseReportReasonListCall) (none)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoAbuseReportReason {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID of this abuse report reason.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string `"youtube#videoAbuseReportReason"`.
    pub kind: Option<String>,
    /// The `snippet` object contains basic details about the abuse report reason.
    pub snippet: Option<VideoAbuseReportReasonSnippet>,
}

impl client::Resource for VideoAbuseReportReason {}

impl client::ToParts for VideoAbuseReportReason {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.id.is_some() { r = r + "id,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.snippet.is_some() { r = r + "snippet,"; }
        r.pop();
        r
    }
}

/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list video abuse report reasons](VideoAbuseReportReasonListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoAbuseReportReasonListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of valid abuse reasons that are used with `video.ReportAbuse`.
    pub items: Option<Vec<VideoAbuseReportReason>>,
    /// Identifies what kind of resource this is. Value: the fixed string `"youtube#videoAbuseReportReasonListResponse"`.
    pub kind: Option<String>,
    /// The `visitorId` identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for VideoAbuseReportReasonListResponse {}

impl client::ToParts for VideoAbuseReportReasonListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// Basic details about a video category, such as its localized title.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoAbuseReportReasonSnippet {
    /// The localized label belonging to this abuse report reason.
    pub label: Option<String>,
    /// The secondary reasons associated with this reason, if any are available. (There might be 0 or more.)
    #[serde(rename="secondaryReasons")]
    pub secondary_reasons: Option<Vec<VideoAbuseReportSecondaryReason>>,
}

impl client::Part for VideoAbuseReportReasonSnippet {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoAbuseReportSecondaryReason {
    /// The ID of this abuse report secondary reason.
    pub id: Option<String>,
    /// The localized label for this abuse report secondary reason.
    pub label: Option<String>,
}

impl client::Part for VideoAbuseReportSecondaryReason {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoAgeGating {
    /// Indicates whether or not the video has alcoholic beverage content. Only users of legal purchasing age in a particular country, as identified by ICAP, can view the content.
    #[serde(rename="alcoholContent")]
    pub alcohol_content: Option<bool>,
    /// Age-restricted trailers. For redband trailers and adult-rated video-games. Only users aged 18+ can view the content. The the field is true the content is restricted to viewers aged 18+. Otherwise The field won't be present.
    pub restricted: Option<bool>,
    /// Video game rating, if any.
    #[serde(rename="videoGameRating")]
    pub video_game_rating: Option<String>,
}

impl client::Part for VideoAgeGating {}


/// A *videoCategory* resource identifies a category that has been or could be associated with uploaded videos.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoCategory {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// The ID that YouTube uses to uniquely identify the video category.
    pub id: Option<String>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#videoCategory".
    pub kind: Option<String>,
    /// The snippet object contains basic details about the video category, including its title.
    pub snippet: Option<VideoCategorySnippet>,
}

impl client::Part for VideoCategory {}


/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list video categories](VideoCategoryListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoCategoryListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of video categories that can be associated with YouTube videos. In this map, the video category ID is the map key, and its value is the corresponding videoCategory resource.
    pub items: Option<Vec<VideoCategory>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#videoCategoryListResponse".
    pub kind: Option<String>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
    #[serde(rename="nextPageToken")]
    pub next_page_token: Option<String>,
    /// General pagination information.
    #[serde(rename="pageInfo")]
    pub page_info: Option<PageInfo>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the previous page in the result set.
    #[serde(rename="prevPageToken")]
    pub prev_page_token: Option<String>,
    /// no description provided
    #[serde(rename="tokenPagination")]
    pub token_pagination: Option<TokenPagination>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for VideoCategoryListResponse {}

impl client::ToParts for VideoCategoryListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.next_page_token.is_some() { r = r + "nextPageToken,"; }
        if self.page_info.is_some() { r = r + "pageInfo,"; }
        if self.prev_page_token.is_some() { r = r + "prevPageToken,"; }
        if self.token_pagination.is_some() { r = r + "tokenPagination,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// Basic details about a video category, such as its localized title.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoCategorySnippet {
    /// no description provided
    pub assignable: Option<bool>,
    /// The YouTube channel that created the video category.
    #[serde(rename="channelId")]
    pub channel_id: Option<String>,
    /// The video category's title.
    pub title: Option<String>,
}

impl client::Part for VideoCategorySnippet {}


/// Details about the content of a YouTube Video.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoContentDetails {
    /// The value of captions indicates whether the video has captions or not.
    pub caption: Option<String>,
    /// Specifies the ratings that the video received under various rating schemes.
    #[serde(rename="contentRating")]
    pub content_rating: Option<ContentRating>,
    /// The countryRestriction object contains information about the countries where a video is (or is not) viewable.
    #[serde(rename="countryRestriction")]
    pub country_restriction: Option<AccessPolicy>,
    /// The value of definition indicates whether the video is available in high definition or only in standard definition.
    pub definition: Option<String>,
    /// The value of dimension indicates whether the video is available in 3D or in 2D.
    pub dimension: Option<String>,
    /// The length of the video. The tag value is an ISO 8601 duration in the format PT#M#S, in which the letters PT indicate that the value specifies a period of time, and the letters M and S refer to length in minutes and seconds, respectively. The # characters preceding the M and S letters are both integers that specify the number of minutes (or seconds) of the video. For example, a value of PT15M51S indicates that the video is 15 minutes and 51 seconds long.
    pub duration: Option<String>,
    /// Indicates whether the video uploader has provided a custom thumbnail image for the video. This property is only visible to the video uploader.
    #[serde(rename="hasCustomThumbnail")]
    pub has_custom_thumbnail: Option<bool>,
    /// The value of is_license_content indicates whether the video is licensed content.
    #[serde(rename="licensedContent")]
    pub licensed_content: Option<bool>,
    /// Specifies the projection format of the video.
    pub projection: Option<String>,
    /// The regionRestriction object contains information about the countries where a video is (or is not) viewable. The object will contain either the contentDetails.regionRestriction.allowed property or the contentDetails.regionRestriction.blocked property.
    #[serde(rename="regionRestriction")]
    pub region_restriction: Option<VideoContentDetailsRegionRestriction>,
}

impl client::Part for VideoContentDetails {}


/// DEPRECATED Region restriction of the video.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoContentDetailsRegionRestriction {
    /// A list of region codes that identify countries where the video is viewable. If this property is present and a country is not listed in its value, then the video is blocked from appearing in that country. If this property is present and contains an empty list, the video is blocked in all countries.
    pub allowed: Option<Vec<String>>,
    /// A list of region codes that identify countries where the video is blocked. If this property is present and a country is not listed in its value, then the video is viewable in that country. If this property is present and contains an empty list, the video is viewable in all countries.
    pub blocked: Option<Vec<String>>,
}

impl client::Part for VideoContentDetailsRegionRestriction {}


/// Describes original video file properties, including technical details about audio and video streams, but also metadata information like content length, digitization time, or geotagging information.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoFileDetails {
    /// A list of audio streams contained in the uploaded video file. Each item in the list contains detailed metadata about an audio stream.
    #[serde(rename="audioStreams")]
    pub audio_streams: Option<Vec<VideoFileDetailsAudioStream>>,
    /// The uploaded video file's combined (video and audio) bitrate in bits per second.
    #[serde(rename="bitrateBps")]
    pub bitrate_bps: Option<String>,
    /// The uploaded video file's container format.
    pub container: Option<String>,
    /// The date and time when the uploaded video file was created. The value is specified in ISO 8601 format. Currently, the following ISO 8601 formats are supported: - Date only: YYYY-MM-DD - Naive time: YYYY-MM-DDTHH:MM:SS - Time with timezone: YYYY-MM-DDTHH:MM:SS+HH:MM 
    #[serde(rename="creationTime")]
    pub creation_time: Option<String>,
    /// The length of the uploaded video in milliseconds.
    #[serde(rename="durationMs")]
    pub duration_ms: Option<String>,
    /// The uploaded file's name. This field is present whether a video file or another type of file was uploaded.
    #[serde(rename="fileName")]
    pub file_name: Option<String>,
    /// The uploaded file's size in bytes. This field is present whether a video file or another type of file was uploaded.
    #[serde(rename="fileSize")]
    pub file_size: Option<String>,
    /// The uploaded file's type as detected by YouTube's video processing engine. Currently, YouTube only processes video files, but this field is present whether a video file or another type of file was uploaded.
    #[serde(rename="fileType")]
    pub file_type: Option<String>,
    /// A list of video streams contained in the uploaded video file. Each item in the list contains detailed metadata about a video stream.
    #[serde(rename="videoStreams")]
    pub video_streams: Option<Vec<VideoFileDetailsVideoStream>>,
}

impl client::Part for VideoFileDetails {}


/// Information about an audio stream.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoFileDetailsAudioStream {
    /// The audio stream's bitrate, in bits per second.
    #[serde(rename="bitrateBps")]
    pub bitrate_bps: Option<String>,
    /// The number of audio channels that the stream contains.
    #[serde(rename="channelCount")]
    pub channel_count: Option<u32>,
    /// The audio codec that the stream uses.
    pub codec: Option<String>,
    /// A value that uniquely identifies a video vendor. Typically, the value is a four-letter vendor code.
    pub vendor: Option<String>,
}

impl client::Part for VideoFileDetailsAudioStream {}


/// Information about a video stream.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoFileDetailsVideoStream {
    /// The video content's display aspect ratio, which specifies the aspect ratio in which the video should be displayed.
    #[serde(rename="aspectRatio")]
    pub aspect_ratio: Option<f64>,
    /// The video stream's bitrate, in bits per second.
    #[serde(rename="bitrateBps")]
    pub bitrate_bps: Option<String>,
    /// The video codec that the stream uses.
    pub codec: Option<String>,
    /// The video stream's frame rate, in frames per second.
    #[serde(rename="frameRateFps")]
    pub frame_rate_fps: Option<f64>,
    /// The encoded video content's height in pixels.
    #[serde(rename="heightPixels")]
    pub height_pixels: Option<u32>,
    /// The amount that YouTube needs to rotate the original source content to properly display the video.
    pub rotation: Option<String>,
    /// A value that uniquely identifies a video vendor. Typically, the value is a four-letter vendor code.
    pub vendor: Option<String>,
    /// The encoded video content's width in pixels. You can calculate the video's encoding aspect ratio as width_pixels / height_pixels.
    #[serde(rename="widthPixels")]
    pub width_pixels: Option<u32>,
}

impl client::Part for VideoFileDetailsVideoStream {}


/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [get rating videos](VideoGetRatingCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoGetRatingResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// A list of ratings that match the request criteria.
    pub items: Option<Vec<VideoRating>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#videoGetRatingResponse".
    pub kind: Option<String>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for VideoGetRatingResponse {}


/// There is no detailed description.
/// 
/// # 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*).
/// 
/// * [list videos](VideoListCall) (response)
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoListResponse {
    /// Etag of this resource.
    pub etag: Option<String>,
    /// Serialized EventId of the request which produced this response.
    #[serde(rename="eventId")]
    pub event_id: Option<String>,
    /// no description provided
    pub items: Option<Vec<Video>>,
    /// Identifies what kind of resource this is. Value: the fixed string "youtube#videoListResponse".
    pub kind: Option<String>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
    #[serde(rename="nextPageToken")]
    pub next_page_token: Option<String>,
    /// General pagination information.
    #[serde(rename="pageInfo")]
    pub page_info: Option<PageInfo>,
    /// The token that can be used as the value of the pageToken parameter to retrieve the previous page in the result set.
    #[serde(rename="prevPageToken")]
    pub prev_page_token: Option<String>,
    /// no description provided
    #[serde(rename="tokenPagination")]
    pub token_pagination: Option<TokenPagination>,
    /// The visitorId identifies the visitor.
    #[serde(rename="visitorId")]
    pub visitor_id: Option<String>,
}

impl client::ResponseResult for VideoListResponse {}

impl client::ToParts for VideoListResponse {
    /// Return a comma separated list of members that are currently set, i.e. for which `self.member.is_some()`.
    /// The produced string is suitable for use as a parts list that indicates the parts you are sending, and/or
    /// the parts you want to see in the server response.
    fn to_parts(&self) -> String {
        let mut r = String::new();
        if self.etag.is_some() { r = r + "etag,"; }
        if self.event_id.is_some() { r = r + "eventId,"; }
        if self.items.is_some() { r = r + "items,"; }
        if self.kind.is_some() { r = r + "kind,"; }
        if self.next_page_token.is_some() { r = r + "nextPageToken,"; }
        if self.page_info.is_some() { r = r + "pageInfo,"; }
        if self.prev_page_token.is_some() { r = r + "prevPageToken,"; }
        if self.token_pagination.is_some() { r = r + "tokenPagination,"; }
        if self.visitor_id.is_some() { r = r + "visitorId,"; }
        r.pop();
        r
    }
}

/// Details about the live streaming metadata.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoLiveStreamingDetails {
    /// The ID of the currently active live chat attached to this video. This field is filled only if the video is a currently live broadcast that has live chat. Once the broadcast transitions to complete this field will be removed and the live chat closed down. For persistent broadcasts that live chat id will no longer be tied to this video but rather to the new video being displayed at the persistent page.
    #[serde(rename="activeLiveChatId")]
    pub active_live_chat_id: Option<String>,
    /// The time that the broadcast actually ended. This value will not be available until the broadcast is over.
    #[serde(rename="actualEndTime")]
    pub actual_end_time: Option<String>,
    /// The time that the broadcast actually started. This value will not be available until the broadcast begins.
    #[serde(rename="actualStartTime")]
    pub actual_start_time: Option<String>,
    /// The number of viewers currently watching the broadcast. The property and its value will be present if the broadcast has current viewers and the broadcast owner has not hidden the viewcount for the video. Note that YouTube stops tracking the number of concurrent viewers for a broadcast when the broadcast ends. So, this property would not identify the number of viewers watching an archived video of a live broadcast that already ended.
    #[serde(rename="concurrentViewers")]
    pub concurrent_viewers: Option<String>,
    /// The time that the broadcast is scheduled to end. If the value is empty or the property is not present, then the broadcast is scheduled to contiue indefinitely.
    #[serde(rename="scheduledEndTime")]
    pub scheduled_end_time: Option<String>,
    /// The time that the broadcast is scheduled to begin.
    #[serde(rename="scheduledStartTime")]
    pub scheduled_start_time: Option<String>,
}

impl client::Part for VideoLiveStreamingDetails {}


/// Localized versions of certain video properties (e.g. title).
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoLocalization {
    /// Localized version of the video's description.
    pub description: Option<String>,
    /// Localized version of the video's title.
    pub title: Option<String>,
}

impl client::Part for VideoLocalization {}


/// Details about monetization of a YouTube Video.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoMonetizationDetails {
    /// The value of access indicates whether the video can be monetized or not.
    pub access: Option<AccessPolicy>,
}

impl client::Part for VideoMonetizationDetails {}


/// Player to be used for a video playback.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoPlayer {
    /// no description provided
    #[serde(rename="embedHeight")]
    pub embed_height: Option<String>,
    /// An <iframe> tag that embeds a player that will play the video.
    #[serde(rename="embedHtml")]
    pub embed_html: Option<String>,
    /// The embed width
    #[serde(rename="embedWidth")]
    pub embed_width: Option<String>,
}

impl client::Part for VideoPlayer {}


/// Describes processing status and progress and availability of some other Video resource parts.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoProcessingDetails {
    /// This value indicates whether video editing suggestions, which might improve video quality or the playback experience, are available for the video. You can retrieve these suggestions by requesting the suggestions part in your videos.list() request.
    #[serde(rename="editorSuggestionsAvailability")]
    pub editor_suggestions_availability: Option<String>,
    /// This value indicates whether file details are available for the uploaded video. You can retrieve a video's file details by requesting the fileDetails part in your videos.list() request.
    #[serde(rename="fileDetailsAvailability")]
    pub file_details_availability: Option<String>,
    /// The reason that YouTube failed to process the video. This property will only have a value if the processingStatus property's value is failed.
    #[serde(rename="processingFailureReason")]
    pub processing_failure_reason: Option<String>,
    /// This value indicates whether the video processing engine has generated suggestions that might improve YouTube's ability to process the the video, warnings that explain video processing problems, or errors that cause video processing problems. You can retrieve these suggestions by requesting the suggestions part in your videos.list() request.
    #[serde(rename="processingIssuesAvailability")]
    pub processing_issues_availability: Option<String>,
    /// The processingProgress object contains information about the progress YouTube has made in processing the video. The values are really only relevant if the video's processing status is processing.
    #[serde(rename="processingProgress")]
    pub processing_progress: Option<VideoProcessingDetailsProcessingProgress>,
    /// The video's processing status. This value indicates whether YouTube was able to process the video or if the video is still being processed.
    #[serde(rename="processingStatus")]
    pub processing_status: Option<String>,
    /// This value indicates whether keyword (tag) suggestions are available for the video. Tags can be added to a video's metadata to make it easier for other users to find the video. You can retrieve these suggestions by requesting the suggestions part in your videos.list() request.
    #[serde(rename="tagSuggestionsAvailability")]
    pub tag_suggestions_availability: Option<String>,
    /// This value indicates whether thumbnail images have been generated for the video.
    #[serde(rename="thumbnailsAvailability")]
    pub thumbnails_availability: Option<String>,
}

impl client::Part for VideoProcessingDetails {}


/// Video processing progress and completion time estimate.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoProcessingDetailsProcessingProgress {
    /// The number of parts of the video that YouTube has already processed. You can estimate the percentage of the video that YouTube has already processed by calculating: 100 * parts_processed / parts_total Note that since the estimated number of parts could increase without a corresponding increase in the number of parts that have already been processed, it is possible that the calculated progress could periodically decrease while YouTube processes a video.
    #[serde(rename="partsProcessed")]
    pub parts_processed: Option<String>,
    /// An estimate of the total number of parts that need to be processed for the video. The number may be updated with more precise estimates while YouTube processes the video.
    #[serde(rename="partsTotal")]
    pub parts_total: Option<String>,
    /// An estimate of the amount of time, in millseconds, that YouTube needs to finish processing the video.
    #[serde(rename="timeLeftMs")]
    pub time_left_ms: Option<String>,
}

impl client::Part for VideoProcessingDetailsProcessingProgress {}


/// DEPRECATED. b/157517979: This part was never populated after it was added. However, it sees non-zero traffic because there is generated client code in the wild that refers to it [1]. We keep this field and do NOT remove it because otherwise V3 would return an error when this part gets requested [2]. [1] https://developers.google.com/resources/api-libraries/documentation/youtube/v3/csharp/latest/classGoogle_1_1Apis_1_1YouTube_1_1v3_1_1Data_1_1VideoProjectDetails.html [2] http://google3/video/youtube/src/python/servers/data_api/common.py?l=1565-1569&rcl=344141677
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoProjectDetails { _never_set: Option<bool> }

impl client::Part for VideoProjectDetails {}


/// Basic details about rating of a video.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoRating {
    /// Rating of a video.
    pub rating: Option<String>,
    /// The ID that YouTube uses to uniquely identify the video.
    #[serde(rename="videoId")]
    pub video_id: Option<String>,
}

impl client::Part for VideoRating {}


/// Recording information associated with the video.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoRecordingDetails {
    /// The geolocation information associated with the video.
    pub location: Option<GeoPoint>,
    /// The text description of the location where the video was recorded.
    #[serde(rename="locationDescription")]
    pub location_description: Option<String>,
    /// The date and time when the video was recorded.
    #[serde(rename="recordingDate")]
    pub recording_date: Option<String>,
}

impl client::Part for VideoRecordingDetails {}


/// Basic details about a video, including title, description, uploader, thumbnails and category.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoSnippet {
    /// The YouTube video category associated with the video.
    #[serde(rename="categoryId")]
    pub category_id: Option<String>,
    /// The ID that YouTube uses to uniquely identify the channel that the video was uploaded to.
    #[serde(rename="channelId")]
    pub channel_id: Option<String>,
    /// Channel title for the channel that the video belongs to.
    #[serde(rename="channelTitle")]
    pub channel_title: Option<String>,
    /// The default_audio_language property specifies the language spoken in the video's default audio track.
    #[serde(rename="defaultAudioLanguage")]
    pub default_audio_language: Option<String>,
    /// The language of the videos's default snippet.
    #[serde(rename="defaultLanguage")]
    pub default_language: Option<String>,
    /// The video's description. @mutable youtube.videos.insert youtube.videos.update
    pub description: Option<String>,
    /// Indicates if the video is an upcoming/active live broadcast. Or it's "none" if the video is not an upcoming/active live broadcast.
    #[serde(rename="liveBroadcastContent")]
    pub live_broadcast_content: Option<String>,
    /// Localized snippet selected with the hl parameter. If no such localization exists, this field is populated with the default snippet. (Read-only)
    pub localized: Option<VideoLocalization>,
    /// The date and time when the video was uploaded.
    #[serde(rename="publishedAt")]
    pub published_at: Option<String>,
    /// A list of keyword tags associated with the video. Tags may contain spaces.
    pub tags: Option<Vec<String>>,
    /// A map of thumbnail images associated with the video. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail.
    pub thumbnails: Option<ThumbnailDetails>,
    /// The video's title. @mutable youtube.videos.insert youtube.videos.update
    pub title: Option<String>,
}

impl client::Part for VideoSnippet {}


/// Statistics about the video, such as the number of times the video was viewed or liked.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoStatistics {
    /// The number of comments for the video.
    #[serde(rename="commentCount")]
    pub comment_count: Option<String>,
    /// The number of users who have indicated that they disliked the video by giving it a negative rating.
    #[serde(rename="dislikeCount")]
    pub dislike_count: Option<String>,
    /// The number of users who currently have the video marked as a favorite video.
    #[serde(rename="favoriteCount")]
    pub favorite_count: Option<String>,
    /// The number of users who have indicated that they liked the video by giving it a positive rating.
    #[serde(rename="likeCount")]
    pub like_count: Option<String>,
    /// The number of times the video has been viewed.
    #[serde(rename="viewCount")]
    pub view_count: Option<String>,
}

impl client::Part for VideoStatistics {}


/// Basic details about a video category, such as its localized title. Next Id: 17
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoStatus {
    /// This value indicates if the video can be embedded on another website. @mutable youtube.videos.insert youtube.videos.update
    pub embeddable: Option<bool>,
    /// This value explains why a video failed to upload. This property is only present if the uploadStatus property indicates that the upload failed.
    #[serde(rename="failureReason")]
    pub failure_reason: Option<String>,
    /// The video's license. @mutable youtube.videos.insert youtube.videos.update
    pub license: Option<String>,
    /// no description provided
    #[serde(rename="madeForKids")]
    pub made_for_kids: Option<bool>,
    /// The video's privacy status.
    #[serde(rename="privacyStatus")]
    pub privacy_status: Option<String>,
    /// This value indicates if the extended video statistics on the watch page can be viewed by everyone. Note that the view count, likes, etc will still be visible if this is disabled. @mutable youtube.videos.insert youtube.videos.update
    #[serde(rename="publicStatsViewable")]
    pub public_stats_viewable: Option<bool>,
    /// The date and time when the video is scheduled to publish. It can be set only if the privacy status of the video is private..
    #[serde(rename="publishAt")]
    pub publish_at: Option<String>,
    /// This value explains why YouTube rejected an uploaded video. This property is only present if the uploadStatus property indicates that the upload was rejected.
    #[serde(rename="rejectionReason")]
    pub rejection_reason: Option<String>,
    /// no description provided
    #[serde(rename="selfDeclaredMadeForKids")]
    pub self_declared_made_for_kids: Option<bool>,
    /// The status of the uploaded video.
    #[serde(rename="uploadStatus")]
    pub upload_status: Option<String>,
}

impl client::Part for VideoStatus {}


/// Specifies suggestions on how to improve video content, including encoding hints, tag suggestions, and editor suggestions.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoSuggestions {
    /// A list of video editing operations that might improve the video quality or playback experience of the uploaded video.
    #[serde(rename="editorSuggestions")]
    pub editor_suggestions: Option<Vec<String>>,
    /// A list of errors that will prevent YouTube from successfully processing the uploaded video video. These errors indicate that, regardless of the video's current processing status, eventually, that status will almost certainly be failed.
    #[serde(rename="processingErrors")]
    pub processing_errors: Option<Vec<String>>,
    /// A list of suggestions that may improve YouTube's ability to process the video.
    #[serde(rename="processingHints")]
    pub processing_hints: Option<Vec<String>>,
    /// A list of reasons why YouTube may have difficulty transcoding the uploaded video or that might result in an erroneous transcoding. These warnings are generated before YouTube actually processes the uploaded video file. In addition, they identify issues that are unlikely to cause the video processing to fail but that might cause problems such as sync issues, video artifacts, or a missing audio track.
    #[serde(rename="processingWarnings")]
    pub processing_warnings: Option<Vec<String>>,
    /// A list of keyword tags that could be added to the video's metadata to increase the likelihood that users will locate your video when searching or browsing on YouTube.
    #[serde(rename="tagSuggestions")]
    pub tag_suggestions: Option<Vec<VideoSuggestionsTagSuggestion>>,
}

impl client::Part for VideoSuggestions {}


/// A single tag suggestion with it's relevance information.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoSuggestionsTagSuggestion {
    /// A set of video categories for which the tag is relevant. You can use this information to display appropriate tag suggestions based on the video category that the video uploader associates with the video. By default, tag suggestions are relevant for all categories if there are no restricts defined for the keyword.
    #[serde(rename="categoryRestricts")]
    pub category_restricts: Option<Vec<String>>,
    /// The keyword tag suggested for the video.
    pub tag: Option<String>,
}

impl client::Part for VideoSuggestionsTagSuggestion {}


/// Freebase topic information related to the video.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct VideoTopicDetails {
    /// Similar to topic_id, except that these topics are merely relevant to the video. These are topics that may be mentioned in, or appear in the video. You can retrieve information about each topic using Freebase Topic API.
    #[serde(rename="relevantTopicIds")]
    pub relevant_topic_ids: Option<Vec<String>>,
    /// A list of Wikipedia URLs that provide a high-level description of the video's content.
    #[serde(rename="topicCategories")]
    pub topic_categories: Option<Vec<String>>,
    /// A list of Freebase topic IDs that are centrally associated with the video. These are topics that are centrally featured in the video, and it can be said that the video is mainly about each of these. You can retrieve information about each topic using the < a href="http://wiki.freebase.com/wiki/Topic_API">Freebase Topic API.
    #[serde(rename="topicIds")]
    pub topic_ids: Option<Vec<String>>,
}

impl client::Part for VideoTopicDetails {}


/// Branding properties for the watch. All deprecated.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct WatchSettings {
    /// The text color for the video watch page's branded area.
    #[serde(rename="backgroundColor")]
    pub background_color: Option<String>,
    /// An ID that uniquely identifies a playlist that displays next to the video player.
    #[serde(rename="featuredPlaylistId")]
    pub featured_playlist_id: Option<String>,
    /// The background color for the video watch page's branded area.
    #[serde(rename="textColor")]
    pub text_color: Option<String>,
}

impl client::Part for WatchSettings {}


/// There is no detailed description.
/// 
/// This type is not used in any activity, and only used as *part* of another schema.
/// 
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ChannelContentDetailsRelatedPlaylists {
    /// The ID of the playlist that contains the channel"s favorite videos. Use the playlistItems.insert and playlistItems.delete to add or remove items from that list.
    pub favorites: Option<String>,
    /// The ID of the playlist that contains the channel"s liked videos. Use the playlistItems.insert and playlistItems.delete to add or remove items from that list.
    pub likes: Option<String>,
    /// The ID of the playlist that contains the channel"s uploaded videos. Use the videos.insert method to upload new videos and the videos.delete method to delete previously uploaded videos.
    pub uploads: Option<String>,
    /// The ID of the playlist that contains the channel"s watch history. Use the playlistItems.insert and playlistItems.delete to add or remove items from that list.
    #[serde(rename="watchHistory")]
    pub watch_history: Option<String>,
    /// The ID of the playlist that contains the channel"s watch later playlist. Use the playlistItems.insert and playlistItems.delete to add or remove items from that list.
    #[serde(rename="watchLater")]
    pub watch_later: Option<String>,
}

impl client::NestedType for ChannelContentDetailsRelatedPlaylists {}
impl client::Part for ChannelContentDetailsRelatedPlaylists {}



// ###################
// MethodBuilders ###
// #################

/// A builder providing access to all methods supported on *abuseReport* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `insert(...)`
/// // to build up your call.
/// let rb = hub.abuse_reports();
/// # }
/// ```
pub struct AbuseReportMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for AbuseReportMethods<'a> {}

impl<'a> AbuseReportMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Inserts a new resource into this collection.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn insert(&self, request: AbuseReport) -> AbuseReportInsertCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        AbuseReportInsertCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *activity* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `list(...)`
/// // to build up your call.
/// let rb = hub.activities();
/// # }
/// ```
pub struct ActivityMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for ActivityMethods<'a> {}

impl<'a> ActivityMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies a comma-separated list of one or more activity resource properties that the API response will include. If the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in an activity resource, the snippet property contains other properties that identify the type of activity, a display title for the activity, and so forth. If you set *part=snippet*, the API response will also contain all of those nested properties.
    pub fn list(&self, part: &Vec<String>) -> ActivityListCall<'a> {
        ActivityListCall {
            hub: self.hub,
            _part: part.clone(),
            _region_code: Default::default(),
            _published_before: Default::default(),
            _published_after: Default::default(),
            _page_token: Default::default(),
            _mine: Default::default(),
            _max_results: Default::default(),
            _home: Default::default(),
            _channel_id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *caption* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `download(...)`, `insert(...)`, `list(...)` and `update(...)`
/// // to build up your call.
/// let rb = hub.captions();
/// # }
/// ```
pub struct CaptionMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for CaptionMethods<'a> {}

impl<'a> CaptionMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Deletes a resource.
    /// 
    /// # Arguments
    ///
    /// * `id` - No description provided.
    pub fn delete(&self, id: &str) -> CaptionDeleteCall<'a> {
        CaptionDeleteCall {
            hub: self.hub,
            _id: id.to_string(),
            _on_behalf_of_content_owner: Default::default(),
            _on_behalf_of: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Downloads a caption track.
    /// 
    /// # Arguments
    ///
    /// * `id` - The ID of the caption track to download, required for One Platform.
    pub fn download(&self, id: &str) -> CaptionDownloadCall<'a> {
        CaptionDownloadCall {
            hub: self.hub,
            _id: id.to_string(),
            _tlang: Default::default(),
            _tfmt: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _on_behalf_of: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Inserts a new resource into this collection.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn insert(&self, request: Caption) -> CaptionInsertCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        CaptionInsertCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _sync: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _on_behalf_of: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies a comma-separated list of one or more caption resource parts that the API response will include. The part names that you can include in the parameter value are id and snippet.
    /// * `videoId` - Returns the captions for the specified video.
    pub fn list(&self, part: &Vec<String>, video_id: &str) -> CaptionListCall<'a> {
        CaptionListCall {
            hub: self.hub,
            _part: part.clone(),
            _video_id: video_id.to_string(),
            _on_behalf_of_content_owner: Default::default(),
            _on_behalf_of: Default::default(),
            _id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Updates an existing resource.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn update(&self, request: Caption) -> CaptionUpdateCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        CaptionUpdateCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _sync: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _on_behalf_of: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *channelBanner* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `insert(...)`
/// // to build up your call.
/// let rb = hub.channel_banners();
/// # }
/// ```
pub struct ChannelBannerMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for ChannelBannerMethods<'a> {}

impl<'a> ChannelBannerMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Inserts a new resource into this collection.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn insert(&self, request: ChannelBannerResource) -> ChannelBannerInsertCall<'a> {
        ChannelBannerInsertCall {
            hub: self.hub,
            _request: request,
            _on_behalf_of_content_owner_channel: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _channel_id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *channelSection* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `insert(...)`, `list(...)` and `update(...)`
/// // to build up your call.
/// let rb = hub.channel_sections();
/// # }
/// ```
pub struct ChannelSectionMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for ChannelSectionMethods<'a> {}

impl<'a> ChannelSectionMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Deletes a resource.
    /// 
    /// # Arguments
    ///
    /// * `id` - No description provided.
    pub fn delete(&self, id: &str) -> ChannelSectionDeleteCall<'a> {
        ChannelSectionDeleteCall {
            hub: self.hub,
            _id: id.to_string(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Inserts a new resource into this collection.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn insert(&self, request: ChannelSection) -> ChannelSectionInsertCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        ChannelSectionInsertCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _on_behalf_of_content_owner_channel: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies a comma-separated list of one or more channelSection resource properties that the API response will include. The part names that you can include in the parameter value are id, snippet, and contentDetails. If the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a channelSection resource, the snippet property contains other properties, such as a display title for the channelSection. If you set *part=snippet*, the API response will also contain all of those nested properties.
    pub fn list(&self, part: &Vec<String>) -> ChannelSectionListCall<'a> {
        ChannelSectionListCall {
            hub: self.hub,
            _part: part.clone(),
            _on_behalf_of_content_owner: Default::default(),
            _mine: Default::default(),
            _id: Default::default(),
            _hl: Default::default(),
            _channel_id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Updates an existing resource.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn update(&self, request: ChannelSection) -> ChannelSectionUpdateCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        ChannelSectionUpdateCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *channel* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `list(...)` and `update(...)`
/// // to build up your call.
/// let rb = hub.channels();
/// # }
/// ```
pub struct ChannelMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for ChannelMethods<'a> {}

impl<'a> ChannelMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies a comma-separated list of one or more channel resource properties that the API response will include. If the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a channel resource, the contentDetails property contains other properties, such as the uploads properties. As such, if you set *part=contentDetails*, the API response will also contain all of those nested properties.
    pub fn list(&self, part: &Vec<String>) -> ChannelListCall<'a> {
        ChannelListCall {
            hub: self.hub,
            _part: part.clone(),
            _page_token: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _my_subscribers: Default::default(),
            _mine: Default::default(),
            _max_results: Default::default(),
            _managed_by_me: Default::default(),
            _id: Default::default(),
            _hl: Default::default(),
            _for_username: Default::default(),
            _category_id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Updates an existing resource.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn update(&self, request: Channel) -> ChannelUpdateCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        ChannelUpdateCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *commentThread* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `insert(...)` and `list(...)`
/// // to build up your call.
/// let rb = hub.comment_threads();
/// # }
/// ```
pub struct CommentThreadMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for CommentThreadMethods<'a> {}

impl<'a> CommentThreadMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Inserts a new resource into this collection.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn insert(&self, request: CommentThread) -> CommentThreadInsertCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        CommentThreadInsertCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies a comma-separated list of one or more commentThread resource properties that the API response will include.
    pub fn list(&self, part: &Vec<String>) -> CommentThreadListCall<'a> {
        CommentThreadListCall {
            hub: self.hub,
            _part: part.clone(),
            _video_id: Default::default(),
            _text_format: Default::default(),
            _search_terms: Default::default(),
            _page_token: Default::default(),
            _order: Default::default(),
            _moderation_status: Default::default(),
            _max_results: Default::default(),
            _id: Default::default(),
            _channel_id: Default::default(),
            _all_threads_related_to_channel_id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *comment* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `insert(...)`, `list(...)`, `mark_as_spam(...)`, `set_moderation_status(...)` and `update(...)`
/// // to build up your call.
/// let rb = hub.comments();
/// # }
/// ```
pub struct CommentMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for CommentMethods<'a> {}

impl<'a> CommentMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Deletes a resource.
    /// 
    /// # Arguments
    ///
    /// * `id` - No description provided.
    pub fn delete(&self, id: &str) -> CommentDeleteCall<'a> {
        CommentDeleteCall {
            hub: self.hub,
            _id: id.to_string(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Inserts a new resource into this collection.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn insert(&self, request: Comment) -> CommentInsertCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        CommentInsertCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies a comma-separated list of one or more comment resource properties that the API response will include.
    pub fn list(&self, part: &Vec<String>) -> CommentListCall<'a> {
        CommentListCall {
            hub: self.hub,
            _part: part.clone(),
            _text_format: Default::default(),
            _parent_id: Default::default(),
            _page_token: Default::default(),
            _max_results: Default::default(),
            _id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Expresses the caller's opinion that one or more comments should be flagged as spam.
    /// 
    /// # Arguments
    ///
    /// * `id` - Flags the comments with the given IDs as spam in the caller's opinion.
    pub fn mark_as_spam(&self, id: &Vec<String>) -> CommentMarkAsSpamCall<'a> {
        CommentMarkAsSpamCall {
            hub: self.hub,
            _id: id.clone(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Sets the moderation status of one or more comments.
    /// 
    /// # Arguments
    ///
    /// * `id` - Modifies the moderation status of the comments with the given IDs
    /// * `moderationStatus` - Specifies the requested moderation status. Note, comments can be in statuses, which are not available through this call. For example, this call does not allow to mark a comment as 'likely spam'. Valid values: MODERATION_STATUS_PUBLISHED, MODERATION_STATUS_HELD_FOR_REVIEW, MODERATION_STATUS_REJECTED.
    pub fn set_moderation_status(&self, id: &Vec<String>, moderation_status: &str) -> CommentSetModerationStatuCall<'a> {
        CommentSetModerationStatuCall {
            hub: self.hub,
            _id: id.clone(),
            _moderation_status: moderation_status.to_string(),
            _ban_author: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Updates an existing resource.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn update(&self, request: Comment) -> CommentUpdateCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        CommentUpdateCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *i18nLanguage* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `list(...)`
/// // to build up your call.
/// let rb = hub.i18n_languages();
/// # }
/// ```
pub struct I18nLanguageMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for I18nLanguageMethods<'a> {}

impl<'a> I18nLanguageMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies the i18nLanguage resource properties that the API response will include. Set the parameter value to snippet.
    pub fn list(&self, part: &Vec<String>) -> I18nLanguageListCall<'a> {
        I18nLanguageListCall {
            hub: self.hub,
            _part: part.clone(),
            _hl: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *i18nRegion* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `list(...)`
/// // to build up your call.
/// let rb = hub.i18n_regions();
/// # }
/// ```
pub struct I18nRegionMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for I18nRegionMethods<'a> {}

impl<'a> I18nRegionMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies the i18nRegion resource properties that the API response will include. Set the parameter value to snippet.
    pub fn list(&self, part: &Vec<String>) -> I18nRegionListCall<'a> {
        I18nRegionListCall {
            hub: self.hub,
            _part: part.clone(),
            _hl: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *liveBroadcast* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `bind(...)`, `delete(...)`, `insert(...)`, `list(...)`, `transition(...)` and `update(...)`
/// // to build up your call.
/// let rb = hub.live_broadcasts();
/// # }
/// ```
pub struct LiveBroadcastMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for LiveBroadcastMethods<'a> {}

impl<'a> LiveBroadcastMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Bind a broadcast to a stream.
    /// 
    /// # Arguments
    ///
    /// * `id` - Broadcast to bind to the stream
    /// * `part` - The *part* parameter specifies a comma-separated list of one or more liveBroadcast resource properties that the API response will include. The part names that you can include in the parameter value are id, snippet, contentDetails, and status.
    pub fn bind(&self, id: &str, part: &Vec<String>) -> LiveBroadcastBindCall<'a> {
        LiveBroadcastBindCall {
            hub: self.hub,
            _id: id.to_string(),
            _part: part.clone(),
            _stream_id: Default::default(),
            _on_behalf_of_content_owner_channel: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Delete a given broadcast.
    /// 
    /// # Arguments
    ///
    /// * `id` - Broadcast to delete.
    pub fn delete(&self, id: &str) -> LiveBroadcastDeleteCall<'a> {
        LiveBroadcastDeleteCall {
            hub: self.hub,
            _id: id.to_string(),
            _on_behalf_of_content_owner_channel: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Inserts a new stream for the authenticated user.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn insert(&self, request: LiveBroadcast) -> LiveBroadcastInsertCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        LiveBroadcastInsertCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _on_behalf_of_content_owner_channel: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieve the list of broadcasts associated with the given channel.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies a comma-separated list of one or more liveBroadcast resource properties that the API response will include. The part names that you can include in the parameter value are id, snippet, contentDetails, status and statistics.
    pub fn list(&self, part: &Vec<String>) -> LiveBroadcastListCall<'a> {
        LiveBroadcastListCall {
            hub: self.hub,
            _part: part.clone(),
            _page_token: Default::default(),
            _on_behalf_of_content_owner_channel: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _mine: Default::default(),
            _max_results: Default::default(),
            _id: Default::default(),
            _broadcast_type: Default::default(),
            _broadcast_status: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Transition a broadcast to a given status.
    /// 
    /// # Arguments
    ///
    /// * `broadcastStatus` - The status to which the broadcast is going to transition.
    /// * `id` - Broadcast to transition.
    /// * `part` - The *part* parameter specifies a comma-separated list of one or more liveBroadcast resource properties that the API response will include. The part names that you can include in the parameter value are id, snippet, contentDetails, and status.
    pub fn transition(&self, broadcast_status: &str, id: &str, part: &Vec<String>) -> LiveBroadcastTransitionCall<'a> {
        LiveBroadcastTransitionCall {
            hub: self.hub,
            _broadcast_status: broadcast_status.to_string(),
            _id: id.to_string(),
            _part: part.clone(),
            _on_behalf_of_content_owner_channel: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Updates an existing broadcast for the authenticated user.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn update(&self, request: LiveBroadcast) -> LiveBroadcastUpdateCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        LiveBroadcastUpdateCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _on_behalf_of_content_owner_channel: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *liveChatBan* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)` and `insert(...)`
/// // to build up your call.
/// let rb = hub.live_chat_bans();
/// # }
/// ```
pub struct LiveChatBanMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for LiveChatBanMethods<'a> {}

impl<'a> LiveChatBanMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Deletes a chat ban.
    /// 
    /// # Arguments
    ///
    /// * `id` - No description provided.
    pub fn delete(&self, id: &str) -> LiveChatBanDeleteCall<'a> {
        LiveChatBanDeleteCall {
            hub: self.hub,
            _id: id.to_string(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Inserts a new resource into this collection.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn insert(&self, request: LiveChatBan) -> LiveChatBanInsertCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        LiveChatBanInsertCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *liveChatMessage* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `insert(...)` and `list(...)`
/// // to build up your call.
/// let rb = hub.live_chat_messages();
/// # }
/// ```
pub struct LiveChatMessageMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for LiveChatMessageMethods<'a> {}

impl<'a> LiveChatMessageMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Deletes a chat message.
    /// 
    /// # Arguments
    ///
    /// * `id` - No description provided.
    pub fn delete(&self, id: &str) -> LiveChatMessageDeleteCall<'a> {
        LiveChatMessageDeleteCall {
            hub: self.hub,
            _id: id.to_string(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Inserts a new resource into this collection.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn insert(&self, request: LiveChatMessage) -> LiveChatMessageInsertCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        LiveChatMessageInsertCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `liveChatId` - The id of the live chat for which comments should be returned.
    /// * `part` - The *part* parameter specifies the liveChatComment resource parts that the API response will include. Supported values are id and snippet.
    pub fn list(&self, live_chat_id: &str, part: &Vec<String>) -> LiveChatMessageListCall<'a> {
        LiveChatMessageListCall {
            hub: self.hub,
            _live_chat_id: live_chat_id.to_string(),
            _part: part.clone(),
            _profile_image_size: Default::default(),
            _page_token: Default::default(),
            _max_results: Default::default(),
            _hl: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *liveChatModerator* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `insert(...)` and `list(...)`
/// // to build up your call.
/// let rb = hub.live_chat_moderators();
/// # }
/// ```
pub struct LiveChatModeratorMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for LiveChatModeratorMethods<'a> {}

impl<'a> LiveChatModeratorMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Deletes a chat moderator.
    /// 
    /// # Arguments
    ///
    /// * `id` - No description provided.
    pub fn delete(&self, id: &str) -> LiveChatModeratorDeleteCall<'a> {
        LiveChatModeratorDeleteCall {
            hub: self.hub,
            _id: id.to_string(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Inserts a new resource into this collection.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn insert(&self, request: LiveChatModerator) -> LiveChatModeratorInsertCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        LiveChatModeratorInsertCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `liveChatId` - The id of the live chat for which moderators should be returned.
    /// * `part` - The *part* parameter specifies the liveChatModerator resource parts that the API response will include. Supported values are id and snippet.
    pub fn list(&self, live_chat_id: &str, part: &Vec<String>) -> LiveChatModeratorListCall<'a> {
        LiveChatModeratorListCall {
            hub: self.hub,
            _live_chat_id: live_chat_id.to_string(),
            _part: part.clone(),
            _page_token: Default::default(),
            _max_results: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *liveStream* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `insert(...)`, `list(...)` and `update(...)`
/// // to build up your call.
/// let rb = hub.live_streams();
/// # }
/// ```
pub struct LiveStreamMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for LiveStreamMethods<'a> {}

impl<'a> LiveStreamMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Deletes an existing stream for the authenticated user.
    /// 
    /// # Arguments
    ///
    /// * `id` - No description provided.
    pub fn delete(&self, id: &str) -> LiveStreamDeleteCall<'a> {
        LiveStreamDeleteCall {
            hub: self.hub,
            _id: id.to_string(),
            _on_behalf_of_content_owner_channel: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Inserts a new stream for the authenticated user.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn insert(&self, request: LiveStream) -> LiveStreamInsertCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        LiveStreamInsertCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _on_behalf_of_content_owner_channel: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieve the list of streams associated with the given channel. --
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies a comma-separated list of one or more liveStream resource properties that the API response will include. The part names that you can include in the parameter value are id, snippet, cdn, and status.
    pub fn list(&self, part: &Vec<String>) -> LiveStreamListCall<'a> {
        LiveStreamListCall {
            hub: self.hub,
            _part: part.clone(),
            _page_token: Default::default(),
            _on_behalf_of_content_owner_channel: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _mine: Default::default(),
            _max_results: Default::default(),
            _id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Updates an existing stream for the authenticated user.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn update(&self, request: LiveStream) -> LiveStreamUpdateCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        LiveStreamUpdateCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _on_behalf_of_content_owner_channel: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *member* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `list(...)`
/// // to build up your call.
/// let rb = hub.members();
/// # }
/// ```
pub struct MemberMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for MemberMethods<'a> {}

impl<'a> MemberMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of members that match the request criteria for a channel.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies the member resource parts that the API response will include. Set the parameter value to snippet.
    pub fn list(&self, part: &Vec<String>) -> MemberListCall<'a> {
        MemberListCall {
            hub: self.hub,
            _part: part.clone(),
            _page_token: Default::default(),
            _mode: Default::default(),
            _max_results: Default::default(),
            _has_access_to_level: Default::default(),
            _filter_by_member_channel_id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *membershipsLevel* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `list(...)`
/// // to build up your call.
/// let rb = hub.memberships_levels();
/// # }
/// ```
pub struct MembershipsLevelMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for MembershipsLevelMethods<'a> {}

impl<'a> MembershipsLevelMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of all pricing levels offered by a creator to the fans.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies the membershipsLevel resource parts that the API response will include. Supported values are id and snippet.
    pub fn list(&self, part: &Vec<String>) -> MembershipsLevelListCall<'a> {
        MembershipsLevelListCall {
            hub: self.hub,
            _part: part.clone(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *playlistItem* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `insert(...)`, `list(...)` and `update(...)`
/// // to build up your call.
/// let rb = hub.playlist_items();
/// # }
/// ```
pub struct PlaylistItemMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for PlaylistItemMethods<'a> {}

impl<'a> PlaylistItemMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Deletes a resource.
    /// 
    /// # Arguments
    ///
    /// * `id` - No description provided.
    pub fn delete(&self, id: &str) -> PlaylistItemDeleteCall<'a> {
        PlaylistItemDeleteCall {
            hub: self.hub,
            _id: id.to_string(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Inserts a new resource into this collection.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn insert(&self, request: PlaylistItem) -> PlaylistItemInsertCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        PlaylistItemInsertCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies a comma-separated list of one or more playlistItem resource properties that the API response will include. If the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a playlistItem resource, the snippet property contains numerous fields, including the title, description, position, and resourceId properties. As such, if you set *part=snippet*, the API response will contain all of those properties.
    pub fn list(&self, part: &Vec<String>) -> PlaylistItemListCall<'a> {
        PlaylistItemListCall {
            hub: self.hub,
            _part: part.clone(),
            _video_id: Default::default(),
            _playlist_id: Default::default(),
            _page_token: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _max_results: Default::default(),
            _id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Updates an existing resource.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn update(&self, request: PlaylistItem) -> PlaylistItemUpdateCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        PlaylistItemUpdateCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *playlist* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `insert(...)`, `list(...)` and `update(...)`
/// // to build up your call.
/// let rb = hub.playlists();
/// # }
/// ```
pub struct PlaylistMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for PlaylistMethods<'a> {}

impl<'a> PlaylistMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Deletes a resource.
    /// 
    /// # Arguments
    ///
    /// * `id` - No description provided.
    pub fn delete(&self, id: &str) -> PlaylistDeleteCall<'a> {
        PlaylistDeleteCall {
            hub: self.hub,
            _id: id.to_string(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Inserts a new resource into this collection.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn insert(&self, request: Playlist) -> PlaylistInsertCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        PlaylistInsertCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _on_behalf_of_content_owner_channel: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies a comma-separated list of one or more playlist resource properties that the API response will include. If the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a playlist resource, the snippet property contains properties like author, title, description, tags, and timeCreated. As such, if you set *part=snippet*, the API response will contain all of those properties.
    pub fn list(&self, part: &Vec<String>) -> PlaylistListCall<'a> {
        PlaylistListCall {
            hub: self.hub,
            _part: part.clone(),
            _page_token: Default::default(),
            _on_behalf_of_content_owner_channel: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _mine: Default::default(),
            _max_results: Default::default(),
            _id: Default::default(),
            _hl: Default::default(),
            _channel_id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Updates an existing resource.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn update(&self, request: Playlist) -> PlaylistUpdateCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        PlaylistUpdateCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *search* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `list(...)`
/// // to build up your call.
/// let rb = hub.search();
/// # }
/// ```
pub struct SearchMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for SearchMethods<'a> {}

impl<'a> SearchMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of search resources
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies a comma-separated list of one or more search resource properties that the API response will include. Set the parameter value to snippet.
    pub fn list(&self, part: &Vec<String>) -> SearchListCall<'a> {
        SearchListCall {
            hub: self.hub,
            _part: part.clone(),
            _video_type: Default::default(),
            _video_syndicated: Default::default(),
            _video_license: Default::default(),
            _video_embeddable: Default::default(),
            _video_duration: Default::default(),
            _video_dimension: Default::default(),
            _video_definition: Default::default(),
            _video_category_id: Default::default(),
            _video_caption: Default::default(),
            _type_: Default::default(),
            _topic_id: Default::default(),
            _safe_search: Default::default(),
            _relevance_language: Default::default(),
            _related_to_video_id: Default::default(),
            _region_code: Default::default(),
            _q: Default::default(),
            _published_before: Default::default(),
            _published_after: Default::default(),
            _page_token: Default::default(),
            _order: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _max_results: Default::default(),
            _location_radius: Default::default(),
            _location: Default::default(),
            _for_mine: Default::default(),
            _for_developer: Default::default(),
            _for_content_owner: Default::default(),
            _event_type: Default::default(),
            _channel_type: Default::default(),
            _channel_id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *subscription* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `insert(...)` and `list(...)`
/// // to build up your call.
/// let rb = hub.subscriptions();
/// # }
/// ```
pub struct SubscriptionMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for SubscriptionMethods<'a> {}

impl<'a> SubscriptionMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Deletes a resource.
    /// 
    /// # Arguments
    ///
    /// * `id` - No description provided.
    pub fn delete(&self, id: &str) -> SubscriptionDeleteCall<'a> {
        SubscriptionDeleteCall {
            hub: self.hub,
            _id: id.to_string(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Inserts a new resource into this collection.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn insert(&self, request: Subscription) -> SubscriptionInsertCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        SubscriptionInsertCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies a comma-separated list of one or more subscription resource properties that the API response will include. If the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a subscription resource, the snippet property contains other properties, such as a display title for the subscription. If you set *part=snippet*, the API response will also contain all of those nested properties.
    pub fn list(&self, part: &Vec<String>) -> SubscriptionListCall<'a> {
        SubscriptionListCall {
            hub: self.hub,
            _part: part.clone(),
            _page_token: Default::default(),
            _order: Default::default(),
            _on_behalf_of_content_owner_channel: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _my_subscribers: Default::default(),
            _my_recent_subscribers: Default::default(),
            _mine: Default::default(),
            _max_results: Default::default(),
            _id: Default::default(),
            _for_channel_id: Default::default(),
            _channel_id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *superChatEvent* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `list(...)`
/// // to build up your call.
/// let rb = hub.super_chat_events();
/// # }
/// ```
pub struct SuperChatEventMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for SuperChatEventMethods<'a> {}

impl<'a> SuperChatEventMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies the superChatEvent resource parts that the API response will include. This parameter is currently not supported.
    pub fn list(&self, part: &Vec<String>) -> SuperChatEventListCall<'a> {
        SuperChatEventListCall {
            hub: self.hub,
            _part: part.clone(),
            _page_token: Default::default(),
            _max_results: Default::default(),
            _hl: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *test* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `insert(...)`
/// // to build up your call.
/// let rb = hub.tests();
/// # }
/// ```
pub struct TestMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for TestMethods<'a> {}

impl<'a> TestMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// POST method.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn insert(&self, request: TestItem) -> TestInsertCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        TestInsertCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _external_channel_id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *thirdPartyLink* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `insert(...)`, `list(...)` and `update(...)`
/// // to build up your call.
/// let rb = hub.third_party_links();
/// # }
/// ```
pub struct ThirdPartyLinkMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for ThirdPartyLinkMethods<'a> {}

impl<'a> ThirdPartyLinkMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Deletes a resource.
    /// 
    /// # Arguments
    ///
    /// * `linkingToken` - Delete the partner links with the given linking token.
    /// * `type` - Type of the link to be deleted.
    pub fn delete(&self, linking_token: &str, type_: &str) -> ThirdPartyLinkDeleteCall<'a> {
        ThirdPartyLinkDeleteCall {
            hub: self.hub,
            _linking_token: linking_token.to_string(),
            _type_: type_.to_string(),
            _part: Default::default(),
            _external_channel_id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Inserts a new resource into this collection.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn insert(&self, request: ThirdPartyLink) -> ThirdPartyLinkInsertCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        ThirdPartyLinkInsertCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _external_channel_id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies the thirdPartyLink resource parts that the API response will include. Supported values are linkingToken, status, and snippet.
    pub fn list(&self, part: &Vec<String>) -> ThirdPartyLinkListCall<'a> {
        ThirdPartyLinkListCall {
            hub: self.hub,
            _part: part.clone(),
            _type_: Default::default(),
            _linking_token: Default::default(),
            _external_channel_id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Updates an existing resource.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn update(&self, request: ThirdPartyLink) -> ThirdPartyLinkUpdateCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        ThirdPartyLinkUpdateCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _external_channel_id: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *thumbnail* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `set(...)`
/// // to build up your call.
/// let rb = hub.thumbnails();
/// # }
/// ```
pub struct ThumbnailMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for ThumbnailMethods<'a> {}

impl<'a> ThumbnailMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// As this is not an insert in a strict sense (it supports uploading/setting of a thumbnail for multiple videos, which doesn't result in creation of a single resource), I use a custom verb here.
    /// 
    /// # Arguments
    ///
    /// * `videoId` - Returns the Thumbnail with the given video IDs for Stubby or Apiary.
    pub fn set(&self, video_id: &str) -> ThumbnailSetCall<'a> {
        ThumbnailSetCall {
            hub: self.hub,
            _video_id: video_id.to_string(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *videoAbuseReportReason* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `list(...)`
/// // to build up your call.
/// let rb = hub.video_abuse_report_reasons();
/// # }
/// ```
pub struct VideoAbuseReportReasonMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for VideoAbuseReportReasonMethods<'a> {}

impl<'a> VideoAbuseReportReasonMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies the videoCategory resource parts that the API response will include. Supported values are id and snippet.
    pub fn list(&self, part: &Vec<String>) -> VideoAbuseReportReasonListCall<'a> {
        VideoAbuseReportReasonListCall {
            hub: self.hub,
            _part: part.clone(),
            _hl: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *videoCategory* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `list(...)`
/// // to build up your call.
/// let rb = hub.video_categories();
/// # }
/// ```
pub struct VideoCategoryMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for VideoCategoryMethods<'a> {}

impl<'a> VideoCategoryMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies the videoCategory resource properties that the API response will include. Set the parameter value to snippet.
    pub fn list(&self, part: &Vec<String>) -> VideoCategoryListCall<'a> {
        VideoCategoryListCall {
            hub: self.hub,
            _part: part.clone(),
            _region_code: Default::default(),
            _id: Default::default(),
            _hl: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *video* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `get_rating(...)`, `insert(...)`, `list(...)`, `rate(...)`, `report_abuse(...)` and `update(...)`
/// // to build up your call.
/// let rb = hub.videos();
/// # }
/// ```
pub struct VideoMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for VideoMethods<'a> {}

impl<'a> VideoMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Deletes a resource.
    /// 
    /// # Arguments
    ///
    /// * `id` - No description provided.
    pub fn delete(&self, id: &str) -> VideoDeleteCall<'a> {
        VideoDeleteCall {
            hub: self.hub,
            _id: id.to_string(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves the ratings that the authorized user gave to a list of specified videos.
    /// 
    /// # Arguments
    ///
    /// * `id` - No description provided.
    pub fn get_rating(&self, id: &Vec<String>) -> VideoGetRatingCall<'a> {
        VideoGetRatingCall {
            hub: self.hub,
            _id: id.clone(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Inserts a new resource into this collection.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn insert(&self, request: Video) -> VideoInsertCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        VideoInsertCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _stabilize: Default::default(),
            _on_behalf_of_content_owner_channel: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _notify_subscribers: Default::default(),
            _auto_levels: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Retrieves a list of resources, possibly filtered.
    /// 
    /// # Arguments
    ///
    /// * `part` - The *part* parameter specifies a comma-separated list of one or more video resource properties that the API response will include. If the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a video resource, the snippet property contains the channelId, title, description, tags, and categoryId properties. As such, if you set *part=snippet*, the API response will contain all of those properties.
    pub fn list(&self, part: &Vec<String>) -> VideoListCall<'a> {
        VideoListCall {
            hub: self.hub,
            _part: part.clone(),
            _video_category_id: Default::default(),
            _region_code: Default::default(),
            _page_token: Default::default(),
            _on_behalf_of_content_owner: Default::default(),
            _my_rating: Default::default(),
            _max_width: Default::default(),
            _max_results: Default::default(),
            _max_height: Default::default(),
            _locale: Default::default(),
            _id: Default::default(),
            _hl: Default::default(),
            _chart: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Adds a like or dislike rating to a video or removes a rating from a video.
    /// 
    /// # Arguments
    ///
    /// * `id` - No description provided.
    /// * `rating` - No description provided.
    pub fn rate(&self, id: &str, rating: &str) -> VideoRateCall<'a> {
        VideoRateCall {
            hub: self.hub,
            _id: id.to_string(),
            _rating: rating.to_string(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Report abuse for a video.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn report_abuse(&self, request: VideoAbuseReport) -> VideoReportAbuseCall<'a> {
        VideoReportAbuseCall {
            hub: self.hub,
            _request: request,
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Updates an existing resource.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn update(&self, request: Video) -> VideoUpdateCall<'a> {
        use client::ToParts;
            let parts = vec![request.to_parts()];
        VideoUpdateCall {
            hub: self.hub,
            _request: request,
            _part: parts,
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *watermark* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `set(...)` and `unset(...)`
/// // to build up your call.
/// let rb = hub.watermarks();
/// # }
/// ```
pub struct WatermarkMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for WatermarkMethods<'a> {}

impl<'a> WatermarkMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Allows upload of watermark image and setting it for a channel.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    /// * `channelId` - No description provided.
    pub fn set(&self, request: InvideoBranding, channel_id: &str) -> WatermarkSetCall<'a> {
        WatermarkSetCall {
            hub: self.hub,
            _request: request,
            _channel_id: channel_id.to_string(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
    
    /// Create a builder to help you perform the following task:
    ///
    /// Allows removal of channel watermark.
    /// 
    /// # Arguments
    ///
    /// * `channelId` - No description provided.
    pub fn unset(&self, channel_id: &str) -> WatermarkUnsetCall<'a> {
        WatermarkUnsetCall {
            hub: self.hub,
            _channel_id: channel_id.to_string(),
            _on_behalf_of_content_owner: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
            _scopes: Default::default(),
        }
    }
}



/// A builder providing access to all methods supported on *youtube* resources.
/// It is not used directly, but through the `YouTube` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_youtube3 as youtube3;
/// 
/// # async fn dox() {
/// use std::default::Default;
/// use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
///         secret,
///         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
///     ).build().await.unwrap();
/// let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `v3_update_comment_threads(...)`
/// // to build up your call.
/// let rb = hub.youtube();
/// # }
/// ```
pub struct YoutubeMethods<'a>
    where  {

    hub: &'a YouTube<>,
}

impl<'a> client::MethodsBuilder for YoutubeMethods<'a> {}

impl<'a> YoutubeMethods<'a> {
    
    /// Create a builder to help you perform the following task:
    ///
    /// Updates an existing resource.
    /// 
    /// # Arguments
    ///
    /// * `request` - No description provided.
    pub fn v3_update_comment_threads(&self, request: CommentThread) -> YoutubeV3UpdateCommentThreadCall<'a> {
        YoutubeV3UpdateCommentThreadCall {
            hub: self.hub,
            _request: request,
            _part: Default::default(),
            _delegate: Default::default(),
            _additional_params: Default::default(),
        }
    }
}





// ###################
// CallBuilders   ###
// #################

/// Inserts a new resource into this collection.
///
/// A builder for the *insert* method supported by a *abuseReport* resource.
/// It is not used directly, but through a `AbuseReportMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::AbuseReport;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = AbuseReport::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.abuse_reports().insert(req)
///              .doit().await;
/// # }
/// ```
pub struct AbuseReportInsertCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: AbuseReport,
    _part: Vec<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for AbuseReportInsertCall<'a> {}

impl<'a> AbuseReportInsertCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, AbuseReport)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.abuseReports.insert",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        for &field in ["alt", "part"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/abuseReports";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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: AbuseReport) -> AbuseReportInsertCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> AbuseReportInsertCall<'a> {
        self._part.push(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 dyn client::Delegate) -> AbuseReportInsertCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> AbuseReportInsertCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> AbuseReportInsertCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *activity* resource.
/// It is not used directly, but through a `ActivityMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.activities().list(&vec!["duo".into()])
///              .region_code("sed")
///              .published_before("no")
///              .published_after("Stet")
///              .page_token("kasd")
///              .mine(true)
///              .max_results(77)
///              .home(true)
///              .channel_id("vero")
///              .doit().await;
/// # }
/// ```
pub struct ActivityListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _region_code: Option<String>,
    _published_before: Option<String>,
    _published_after: Option<String>,
    _page_token: Option<String>,
    _mine: Option<bool>,
    _max_results: Option<u32>,
    _home: Option<bool>,
    _channel_id: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for ActivityListCall<'a> {}

impl<'a> ActivityListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, ActivityListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.activities.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(11 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._region_code {
            params.push(("regionCode", value.to_string()));
        }
        if let Some(value) = self._published_before {
            params.push(("publishedBefore", value.to_string()));
        }
        if let Some(value) = self._published_after {
            params.push(("publishedAfter", value.to_string()));
        }
        if let Some(value) = self._page_token {
            params.push(("pageToken", value.to_string()));
        }
        if let Some(value) = self._mine {
            params.push(("mine", value.to_string()));
        }
        if let Some(value) = self._max_results {
            params.push(("maxResults", value.to_string()));
        }
        if let Some(value) = self._home {
            params.push(("home", value.to_string()));
        }
        if let Some(value) = self._channel_id {
            params.push(("channelId", value.to_string()));
        }
        for &field in ["alt", "part", "regionCode", "publishedBefore", "publishedAfter", "pageToken", "mine", "maxResults", "home", "channelId"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/activities";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies a comma-separated list of one or more activity resource properties that the API response will include. If the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in an activity resource, the snippet property contains other properties that identify the type of activity, a display title for the activity, and so forth. If you set *part=snippet*, the API response will also contain all of those nested properties.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    pub fn add_part(mut self, new_value: &str) -> ActivityListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    ///
    /// Sets the *region code* query property to the given value.
    pub fn region_code(mut self, new_value: &str) -> ActivityListCall<'a> {
        self._region_code = Some(new_value.to_string());
        self
    }
    ///
    /// Sets the *published before* query property to the given value.
    pub fn published_before(mut self, new_value: &str) -> ActivityListCall<'a> {
        self._published_before = Some(new_value.to_string());
        self
    }
    ///
    /// Sets the *published after* query property to the given value.
    pub fn published_after(mut self, new_value: &str) -> ActivityListCall<'a> {
        self._published_after = Some(new_value.to_string());
        self
    }
    /// The *pageToken* parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.
    ///
    /// Sets the *page token* query property to the given value.
    pub fn page_token(mut self, new_value: &str) -> ActivityListCall<'a> {
        self._page_token = Some(new_value.to_string());
        self
    }
    ///
    /// Sets the *mine* query property to the given value.
    pub fn mine(mut self, new_value: bool) -> ActivityListCall<'a> {
        self._mine = Some(new_value);
        self
    }
    /// The *maxResults* parameter specifies the maximum number of items that should be returned in the result set.
    ///
    /// Sets the *max results* query property to the given value.
    pub fn max_results(mut self, new_value: u32) -> ActivityListCall<'a> {
        self._max_results = Some(new_value);
        self
    }
    ///
    /// Sets the *home* query property to the given value.
    pub fn home(mut self, new_value: bool) -> ActivityListCall<'a> {
        self._home = Some(new_value);
        self
    }
    ///
    /// Sets the *channel id* query property to the given value.
    pub fn channel_id(mut self, new_value: &str) -> ActivityListCall<'a> {
        self._channel_id = Some(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 dyn client::Delegate) -> ActivityListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> ActivityListCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> ActivityListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Deletes a resource.
///
/// A builder for the *delete* method supported by a *caption* resource.
/// It is not used directly, but through a `CaptionMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.captions().delete("id")
///              .on_behalf_of_content_owner("sed")
///              .on_behalf_of("duo")
///              .doit().await;
/// # }
/// ```
pub struct CaptionDeleteCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: String,
    _on_behalf_of_content_owner: Option<String>,
    _on_behalf_of: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for CaptionDeleteCall<'a> {}

impl<'a> CaptionDeleteCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.captions.delete",
                               http_method: hyper::Method::DELETE });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        params.push(("id", self._id.to_string()));
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of {
            params.push(("onBehalfOf", value.to_string()));
        }
        for &field in ["id", "onBehalfOfContentOwner", "onBehalfOf"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/captions";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::ForceSsl.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::DELETE).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// Sets the *id* query 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 id(mut self, new_value: &str) -> CaptionDeleteCall<'a> {
        self._id = new_value.to_string();
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> CaptionDeleteCall<'a> {
        self._on_behalf_of_content_owner = Some(new_value.to_string());
        self
    }
    /// ID of the Google+ Page for the channel that the request is be on behalf of
    ///
    /// Sets the *on behalf of* query property to the given value.
    pub fn on_behalf_of(mut self, new_value: &str) -> CaptionDeleteCall<'a> {
        self._on_behalf_of = Some(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 dyn client::Delegate) -> CaptionDeleteCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> CaptionDeleteCall<'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::ForceSsl`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> CaptionDeleteCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Downloads a caption track.
///
/// This method supports **media download**. To enable it, adjust the builder like this:
/// `.param("alt", "media")`.
///
/// A builder for the *download* method supported by a *caption* resource.
/// It is not used directly, but through a `CaptionMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.captions().download("id")
///              .tlang("et")
///              .tfmt("voluptua.")
///              .on_behalf_of_content_owner("amet.")
///              .on_behalf_of("consetetur")
///              .doit().await;
/// # }
/// ```
pub struct CaptionDownloadCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: String,
    _tlang: Option<String>,
    _tfmt: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _on_behalf_of: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for CaptionDownloadCall<'a> {}

impl<'a> CaptionDownloadCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.captions.download",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
        params.push(("id", self._id.to_string()));
        if let Some(value) = self._tlang {
            params.push(("tlang", value.to_string()));
        }
        if let Some(value) = self._tfmt {
            params.push(("tfmt", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of {
            params.push(("onBehalfOf", value.to_string()));
        }
        for &field in ["id", "tlang", "tfmt", "onBehalfOfContentOwner", "onBehalfOf"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/captions/{id}";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::ForceSsl.as_ref().to_string(), ());
        }

        for &(find_this, param_name) in [("{id}", "id")].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 ["id"].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);
            }
        }

        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The ID of the caption track to download, required for One Platform.
    ///
    /// Sets the *id* 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 id(mut self, new_value: &str) -> CaptionDownloadCall<'a> {
        self._id = new_value.to_string();
        self
    }
    /// tlang is the language code; machine translate the captions into this language.
    ///
    /// Sets the *tlang* query property to the given value.
    pub fn tlang(mut self, new_value: &str) -> CaptionDownloadCall<'a> {
        self._tlang = Some(new_value.to_string());
        self
    }
    /// Convert the captions into this format. Supported options are sbv, srt, and vtt.
    ///
    /// Sets the *tfmt* query property to the given value.
    pub fn tfmt(mut self, new_value: &str) -> CaptionDownloadCall<'a> {
        self._tfmt = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> CaptionDownloadCall<'a> {
        self._on_behalf_of_content_owner = Some(new_value.to_string());
        self
    }
    /// ID of the Google+ Page for the channel that the request is be on behalf of
    ///
    /// Sets the *on behalf of* query property to the given value.
    pub fn on_behalf_of(mut self, new_value: &str) -> CaptionDownloadCall<'a> {
        self._on_behalf_of = Some(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 dyn client::Delegate) -> CaptionDownloadCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> CaptionDownloadCall<'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::ForceSsl`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> CaptionDownloadCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Inserts a new resource into this collection.
///
/// A builder for the *insert* method supported by a *caption* resource.
/// It is not used directly, but through a `CaptionMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::Caption;
/// use std::fs;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = Caption::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.captions().insert(req)
///              .sync(false)
///              .on_behalf_of_content_owner("dolor")
///              .on_behalf_of("et")
///              .upload(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()).await;
/// # }
/// ```
pub struct CaptionInsertCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: Caption,
    _part: Vec<String>,
    _sync: Option<bool>,
    _on_behalf_of_content_owner: Option<String>,
    _on_behalf_of: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for CaptionInsertCall<'a> {}

impl<'a> CaptionInsertCall<'a> {


    /// Perform the operation you have build so far.
    async fn doit<RS>(mut self, mut reader: RS, reader_mime_type: mime::Mime, protocol: &'static str) -> client::Result<(hyper::Response<hyper::body::Body>, Caption)>
		where RS: client::ReadSeek {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.captions.insert",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(7 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._sync {
            params.push(("sync", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of {
            params.push(("onBehalfOf", value.to_string()));
        }
        for &field in ["alt", "part", "sync", "onBehalfOfContentOwner", "onBehalfOf"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let (mut url, upload_type) =
            if protocol == "resumable" {
                (self.hub._root_url.clone() + "resumable/upload/youtube/v3/captions", "resumable")
            } else if protocol == "simple" {
                (self.hub._root_url.clone() + "upload/youtube/v3/captions", "multipart")
            } else {
                unreachable!()
            };
        params.push(("uploadType", upload_type.to_string()));
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::ForceSsl.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            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;
                    Ok(hyper::Response::builder()
                        .status(hyper::StatusCode::OK)
                        .header("Location", upload_url.as_ref().unwrap().clone())
                        .body(hyper::body::Body::empty())
                        .unwrap())
                } else {
                    let mut mp_reader: client::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 > 104857600 {
                        	return Err(client::Error::UploadSizeLimitExceeded(size, 104857600))
                        }
                            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 (dyn io::Read + Send), (CONTENT_TYPE, mime_type.to_string()))
                        },
                        _ => (&mut request_value_reader as &mut (dyn io::Read + Send), (CONTENT_TYPE, json_mime_type.to_string())),
                    };
                    let client = &self.hub.client;
                    dlg.pre_request();
                    let mut req_builder = hyper::Request::builder().method(hyper::Method::POST).uri(url.clone().into_string())
                            .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
    
                    upload_url_from_server = true;
                    if protocol == "resumable" {
                        req_builder = req_builder.header("X-Upload-Content-Type", format!("{}", reader_mime_type));
                    }
    
                            let mut body_reader_bytes = vec![];
                            body_reader.read_to_end(&mut body_reader_bytes).unwrap();
                            let request = req_builder
                            .header(content_type.0, content_type.1.to_string())
                            .body(hyper::body::Body::from(body_reader_bytes));
    
                    client.request(request.unwrap()).await
                    
                }
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    if protocol == "resumable" {
                        let size = reader.seek(io::SeekFrom::End(0)).unwrap();
                        reader.seek(io::SeekFrom::Start(0)).unwrap();
                        if size > 104857600 {
                        	return Err(client::Error::UploadSizeLimitExceeded(size, 104857600))
                        }
                        let upload_result = {
                            let url_str = &res.headers().get("Location").expect("LOCATION header is part of protocol").to_str().unwrap();
                            if upload_url_from_server {
                                dlg.store_upload_url(Some(url_str));
                            }

                            client::ResumableUploadHelper {
                                client: &self.hub.client,
                                delegate: dlg,
                                start_at: if upload_url_from_server { Some(0) } else { None },
                                auth: &self.hub.auth,
                                user_agent: &self.hub._user_agent,
                                auth_header: format!("Bearer {}", token.as_str()),
                                url: url_str,
                                reader: &mut reader,
                                media_type: reader_mime_type.clone(),
                                content_length: size
                            }.upload().await
                        };
                        match upload_result {
                            None => {
                                dlg.finished(false);
                                return Err(client::Error::Cancelled)
                            }
                            Some(Err(err)) => {
                                dlg.finished(false);
                                return Err(client::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(client::Error::Failure(res))
                                }
                            }
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }

    /// 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(...)`.
    ///
    /// * *multipart*: yes
    /// * *max size*: 104857600
    /// * *valid mime types*: 'text/xml', 'application/octet-stream' and '*/*'
    pub async fn upload_resumable<RS>(self, resumeable_stream: RS, mime_type: mime::Mime) -> client::Result<(hyper::Response<hyper::body::Body>, Caption)>
                where RS: client::ReadSeek {
        self.doit(resumeable_stream, mime_type, "resumable").await
    }
    /// Upload media all at once.
    /// If the upload fails for whichever reason, all progress is lost.
    ///
    /// * *multipart*: yes
    /// * *max size*: 104857600
    /// * *valid mime types*: 'text/xml', 'application/octet-stream' and '*/*'
    pub async fn upload<RS>(self, stream: RS, mime_type: mime::Mime) -> client::Result<(hyper::Response<hyper::body::Body>, Caption)>
                where RS: client::ReadSeek {
        self.doit(stream, mime_type, "simple").await
    }

    ///
    /// 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: Caption) -> CaptionInsertCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter specifies the caption resource parts that the API response will include. Set the parameter value to snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> CaptionInsertCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// Extra parameter to allow automatically syncing the uploaded caption/transcript with the audio.
    ///
    /// Sets the *sync* query property to the given value.
    pub fn sync(mut self, new_value: bool) -> CaptionInsertCall<'a> {
        self._sync = Some(new_value);
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> CaptionInsertCall<'a> {
        self._on_behalf_of_content_owner = Some(new_value.to_string());
        self
    }
    /// ID of the Google+ Page for the channel that the request is be on behalf of
    ///
    /// Sets the *on behalf of* query property to the given value.
    pub fn on_behalf_of(mut self, new_value: &str) -> CaptionInsertCall<'a> {
        self._on_behalf_of = Some(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 dyn client::Delegate) -> CaptionInsertCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> CaptionInsertCall<'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::ForceSsl`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> CaptionInsertCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *caption* resource.
/// It is not used directly, but through a `CaptionMethods` instance.
///
/// **Settable Parts**
/// 
/// * *id*
/// * *snippet*
///
/// # Scopes
///
/// You will need authorization for at least one of the following scopes to make a valid call, possibly depending on *parts*:
///
/// * *https://www.googleapis.com/auth/youtube.force-ssl*
/// * *https://www.googleapis.com/auth/youtubepartner*
///
/// The default scope will be `Scope::ForceSsl`.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.captions().list(&vec!["et".into()], "videoId")
///              .on_behalf_of_content_owner("Stet")
///              .on_behalf_of("dolor")
///              .add_id("duo")
///              .doit().await;
/// # }
/// ```
pub struct CaptionListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _video_id: String,
    _on_behalf_of_content_owner: Option<String>,
    _on_behalf_of: Option<String>,
    _id: Vec<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for CaptionListCall<'a> {}

impl<'a> CaptionListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, CaptionListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.captions.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(7 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        params.push(("videoId", self._video_id.to_string()));
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of {
            params.push(("onBehalfOf", value.to_string()));
        }
        if self._id.len() > 0 {
            for f in self._id.iter() {
                params.push(("id", f.to_string()));
            }
        }
        for &field in ["alt", "part", "videoId", "onBehalfOfContentOwner", "onBehalfOf", "id"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/captions";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::ForceSsl.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies a comma-separated list of one or more caption resource parts that the API response will include. The part names that you can include in the parameter value are id and snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    pub fn add_part(mut self, new_value: &str) -> CaptionListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// Returns the captions for the specified video.
    ///
    /// Sets the *video id* query 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 video_id(mut self, new_value: &str) -> CaptionListCall<'a> {
        self._video_id = new_value.to_string();
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> CaptionListCall<'a> {
        self._on_behalf_of_content_owner = Some(new_value.to_string());
        self
    }
    /// ID of the Google+ Page for the channel that the request is on behalf of.
    ///
    /// Sets the *on behalf of* query property to the given value.
    pub fn on_behalf_of(mut self, new_value: &str) -> CaptionListCall<'a> {
        self._on_behalf_of = Some(new_value.to_string());
        self
    }
    /// Returns the captions with the given IDs for Stubby or Apiary.
    ///
    /// Append the given value to the *id* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    pub fn add_id(mut self, new_value: &str) -> CaptionListCall<'a> {
        self._id.push(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 dyn client::Delegate) -> CaptionListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> CaptionListCall<'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::ForceSsl`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> CaptionListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Updates an existing resource.
///
/// A builder for the *update* method supported by a *caption* resource.
/// It is not used directly, but through a `CaptionMethods` instance.
///
/// **Settable Parts**
/// 
/// * *id*
/// * *snippet*
///
/// # Scopes
///
/// You will need authorization for at least one of the following scopes to make a valid call, possibly depending on *parts*:
///
/// * *https://www.googleapis.com/auth/youtube.force-ssl*
/// * *https://www.googleapis.com/auth/youtubepartner*
///
/// The default scope will be `Scope::ForceSsl`.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::Caption;
/// use std::fs;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = Caption::default();
/// req.id = Some("vero".to_string());
/// req.snippet = Default::default(); // is CaptionSnippet
/// 
/// // 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.captions().update(req)
///              .sync(false)
///              .on_behalf_of_content_owner("invidunt")
///              .on_behalf_of("Stet")
///              .upload(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()).await;
/// # }
/// ```
pub struct CaptionUpdateCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: Caption,
    _part: Vec<String>,
    _sync: Option<bool>,
    _on_behalf_of_content_owner: Option<String>,
    _on_behalf_of: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for CaptionUpdateCall<'a> {}

impl<'a> CaptionUpdateCall<'a> {


    /// Perform the operation you have build so far.
    async fn doit<RS>(mut self, mut reader: RS, reader_mime_type: mime::Mime, protocol: &'static str) -> client::Result<(hyper::Response<hyper::body::Body>, Caption)>
		where RS: client::ReadSeek {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.captions.update",
                               http_method: hyper::Method::PUT });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(7 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._sync {
            params.push(("sync", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of {
            params.push(("onBehalfOf", value.to_string()));
        }
        for &field in ["alt", "part", "sync", "onBehalfOfContentOwner", "onBehalfOf"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let (mut url, upload_type) =
            if protocol == "resumable" {
                (self.hub._root_url.clone() + "resumable/upload/youtube/v3/captions", "resumable")
            } else if protocol == "simple" {
                (self.hub._root_url.clone() + "upload/youtube/v3/captions", "multipart")
            } else {
                unreachable!()
            };
        params.push(("uploadType", upload_type.to_string()));
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::ForceSsl.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            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;
                    Ok(hyper::Response::builder()
                        .status(hyper::StatusCode::OK)
                        .header("Location", upload_url.as_ref().unwrap().clone())
                        .body(hyper::body::Body::empty())
                        .unwrap())
                } else {
                    let mut mp_reader: client::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 > 104857600 {
                        	return Err(client::Error::UploadSizeLimitExceeded(size, 104857600))
                        }
                            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 (dyn io::Read + Send), (CONTENT_TYPE, mime_type.to_string()))
                        },
                        _ => (&mut request_value_reader as &mut (dyn io::Read + Send), (CONTENT_TYPE, json_mime_type.to_string())),
                    };
                    let client = &self.hub.client;
                    dlg.pre_request();
                    let mut req_builder = hyper::Request::builder().method(hyper::Method::PUT).uri(url.clone().into_string())
                            .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
    
                    upload_url_from_server = true;
                    if protocol == "resumable" {
                        req_builder = req_builder.header("X-Upload-Content-Type", format!("{}", reader_mime_type));
                    }
    
                            let mut body_reader_bytes = vec![];
                            body_reader.read_to_end(&mut body_reader_bytes).unwrap();
                            let request = req_builder
                            .header(content_type.0, content_type.1.to_string())
                            .body(hyper::body::Body::from(body_reader_bytes));
    
                    client.request(request.unwrap()).await
                    
                }
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    if protocol == "resumable" {
                        let size = reader.seek(io::SeekFrom::End(0)).unwrap();
                        reader.seek(io::SeekFrom::Start(0)).unwrap();
                        if size > 104857600 {
                        	return Err(client::Error::UploadSizeLimitExceeded(size, 104857600))
                        }
                        let upload_result = {
                            let url_str = &res.headers().get("Location").expect("LOCATION header is part of protocol").to_str().unwrap();
                            if upload_url_from_server {
                                dlg.store_upload_url(Some(url_str));
                            }

                            client::ResumableUploadHelper {
                                client: &self.hub.client,
                                delegate: dlg,
                                start_at: if upload_url_from_server { Some(0) } else { None },
                                auth: &self.hub.auth,
                                user_agent: &self.hub._user_agent,
                                auth_header: format!("Bearer {}", token.as_str()),
                                url: url_str,
                                reader: &mut reader,
                                media_type: reader_mime_type.clone(),
                                content_length: size
                            }.upload().await
                        };
                        match upload_result {
                            None => {
                                dlg.finished(false);
                                return Err(client::Error::Cancelled)
                            }
                            Some(Err(err)) => {
                                dlg.finished(false);
                                return Err(client::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(client::Error::Failure(res))
                                }
                            }
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }

    /// 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(...)`.
    ///
    /// * *multipart*: yes
    /// * *max size*: 104857600
    /// * *valid mime types*: 'text/xml', 'application/octet-stream' and '*/*'
    pub async fn upload_resumable<RS>(self, resumeable_stream: RS, mime_type: mime::Mime) -> client::Result<(hyper::Response<hyper::body::Body>, Caption)>
                where RS: client::ReadSeek {
        self.doit(resumeable_stream, mime_type, "resumable").await
    }
    /// Upload media all at once.
    /// If the upload fails for whichever reason, all progress is lost.
    ///
    /// * *multipart*: yes
    /// * *max size*: 104857600
    /// * *valid mime types*: 'text/xml', 'application/octet-stream' and '*/*'
    pub async fn upload<RS>(self, stream: RS, mime_type: mime::Mime) -> client::Result<(hyper::Response<hyper::body::Body>, Caption)>
                where RS: client::ReadSeek {
        self.doit(stream, mime_type, "simple").await
    }

    ///
    /// 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.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    pub fn request(mut self, new_value: Caption) -> CaptionUpdateCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter specifies a comma-separated list of one or more caption resource parts that the API response will include. The part names that you can include in the parameter value are id and snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    pub fn add_part(mut self, new_value: &str) -> CaptionUpdateCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// Extra parameter to allow automatically syncing the uploaded caption/transcript with the audio.
    ///
    /// Sets the *sync* query property to the given value.
    pub fn sync(mut self, new_value: bool) -> CaptionUpdateCall<'a> {
        self._sync = Some(new_value);
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> CaptionUpdateCall<'a> {
        self._on_behalf_of_content_owner = Some(new_value.to_string());
        self
    }
    /// ID of the Google+ Page for the channel that the request is on behalf of.
    ///
    /// Sets the *on behalf of* query property to the given value.
    pub fn on_behalf_of(mut self, new_value: &str) -> CaptionUpdateCall<'a> {
        self._on_behalf_of = Some(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 dyn client::Delegate) -> CaptionUpdateCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> CaptionUpdateCall<'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::ForceSsl`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> CaptionUpdateCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Inserts a new resource into this collection.
///
/// A builder for the *insert* method supported by a *channelBanner* resource.
/// It is not used directly, but through a `ChannelBannerMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::ChannelBannerResource;
/// use std::fs;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = ChannelBannerResource::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `upload_resumable(...)`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.channel_banners().insert(req)
///              .on_behalf_of_content_owner_channel("vero")
///              .on_behalf_of_content_owner("elitr")
///              .channel_id("Lorem")
///              .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()).await;
/// # }
/// ```
pub struct ChannelBannerInsertCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: ChannelBannerResource,
    _on_behalf_of_content_owner_channel: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _channel_id: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for ChannelBannerInsertCall<'a> {}

impl<'a> ChannelBannerInsertCall<'a> {


    /// Perform the operation you have build so far.
    async fn doit<RS>(mut self, mut reader: RS, reader_mime_type: mime::Mime, protocol: &'static str) -> client::Result<(hyper::Response<hyper::body::Body>, ChannelBannerResource)>
		where RS: client::ReadSeek {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.channelBanners.insert",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
        if let Some(value) = self._on_behalf_of_content_owner_channel {
            params.push(("onBehalfOfContentOwnerChannel", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        if let Some(value) = self._channel_id {
            params.push(("channelId", value.to_string()));
        }
        for &field in ["alt", "onBehalfOfContentOwnerChannel", "onBehalfOfContentOwner", "channelId"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let (mut url, upload_type) =
            if protocol == "resumable" {
                (self.hub._root_url.clone() + "resumable/upload/youtube/v3/channelBanners/insert", "resumable")
            } else if protocol == "simple" {
                (self.hub._root_url.clone() + "upload/youtube/v3/channelBanners/insert", "multipart")
            } else {
                unreachable!()
            };
        params.push(("uploadType", upload_type.to_string()));
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            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;
                    Ok(hyper::Response::builder()
                        .status(hyper::StatusCode::OK)
                        .header("Location", upload_url.as_ref().unwrap().clone())
                        .body(hyper::body::Body::empty())
                        .unwrap())
                } else {
                    let mut mp_reader: client::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 > 6291456 {
                        	return Err(client::Error::UploadSizeLimitExceeded(size, 6291456))
                        }
                            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 (dyn io::Read + Send), (CONTENT_TYPE, mime_type.to_string()))
                        },
                        _ => (&mut request_value_reader as &mut (dyn io::Read + Send), (CONTENT_TYPE, json_mime_type.to_string())),
                    };
                    let client = &self.hub.client;
                    dlg.pre_request();
                    let mut req_builder = hyper::Request::builder().method(hyper::Method::POST).uri(url.clone().into_string())
                            .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
    
                    upload_url_from_server = true;
                    if protocol == "resumable" {
                        req_builder = req_builder.header("X-Upload-Content-Type", format!("{}", reader_mime_type));
                    }
    
                            let mut body_reader_bytes = vec![];
                            body_reader.read_to_end(&mut body_reader_bytes).unwrap();
                            let request = req_builder
                            .header(content_type.0, content_type.1.to_string())
                            .body(hyper::body::Body::from(body_reader_bytes));
    
                    client.request(request.unwrap()).await
                    
                }
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    if protocol == "resumable" {
                        let size = reader.seek(io::SeekFrom::End(0)).unwrap();
                        reader.seek(io::SeekFrom::Start(0)).unwrap();
                        if size > 6291456 {
                        	return Err(client::Error::UploadSizeLimitExceeded(size, 6291456))
                        }
                        let upload_result = {
                            let url_str = &res.headers().get("Location").expect("LOCATION header is part of protocol").to_str().unwrap();
                            if upload_url_from_server {
                                dlg.store_upload_url(Some(url_str));
                            }

                            client::ResumableUploadHelper {
                                client: &self.hub.client,
                                delegate: dlg,
                                start_at: if upload_url_from_server { Some(0) } else { None },
                                auth: &self.hub.auth,
                                user_agent: &self.hub._user_agent,
                                auth_header: format!("Bearer {}", token.as_str()),
                                url: url_str,
                                reader: &mut reader,
                                media_type: reader_mime_type.clone(),
                                content_length: size
                            }.upload().await
                        };
                        match upload_result {
                            None => {
                                dlg.finished(false);
                                return Err(client::Error::Cancelled)
                            }
                            Some(Err(err)) => {
                                dlg.finished(false);
                                return Err(client::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(client::Error::Failure(res))
                                }
                            }
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }

    /// 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(...)`.
    ///
    /// * *multipart*: yes
    /// * *max size*: 6291456
    /// * *valid mime types*: 'image/jpeg', 'image/png' and 'application/octet-stream'
    pub async fn upload_resumable<RS>(self, resumeable_stream: RS, mime_type: mime::Mime) -> client::Result<(hyper::Response<hyper::body::Body>, ChannelBannerResource)>
                where RS: client::ReadSeek {
        self.doit(resumeable_stream, mime_type, "resumable").await
    }
    /// Upload media all at once.
    /// If the upload fails for whichever reason, all progress is lost.
    ///
    /// * *multipart*: yes
    /// * *max size*: 6291456
    /// * *valid mime types*: 'image/jpeg', 'image/png' and 'application/octet-stream'
    pub async fn upload<RS>(self, stream: RS, mime_type: mime::Mime) -> client::Result<(hyper::Response<hyper::body::Body>, ChannelBannerResource)>
                where RS: client::ReadSeek {
        self.doit(stream, mime_type, "simple").await
    }

    ///
    /// 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: ChannelBannerResource) -> ChannelBannerInsertCall<'a> {
        self._request = new_value;
        self
    }
    /// This parameter can only be used in a properly authorized request. *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwnerChannel* parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.
    ///
    /// Sets the *on behalf of content owner channel* query property to the given value.
    pub fn on_behalf_of_content_owner_channel(mut self, new_value: &str) -> ChannelBannerInsertCall<'a> {
        self._on_behalf_of_content_owner_channel = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> ChannelBannerInsertCall<'a> {
        self._on_behalf_of_content_owner = Some(new_value.to_string());
        self
    }
    /// Unused, channel_id is currently derived from the security context of the requestor.
    ///
    /// Sets the *channel id* query property to the given value.
    pub fn channel_id(mut self, new_value: &str) -> ChannelBannerInsertCall<'a> {
        self._channel_id = Some(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 dyn client::Delegate) -> ChannelBannerInsertCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> ChannelBannerInsertCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> ChannelBannerInsertCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Deletes a resource.
///
/// A builder for the *delete* method supported by a *channelSection* resource.
/// It is not used directly, but through a `ChannelSectionMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.channel_sections().delete("id")
///              .on_behalf_of_content_owner("no")
///              .doit().await;
/// # }
/// ```
pub struct ChannelSectionDeleteCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: String,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for ChannelSectionDeleteCall<'a> {}

impl<'a> ChannelSectionDeleteCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.channelSections.delete",
                               http_method: hyper::Method::DELETE });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
        params.push(("id", self._id.to_string()));
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["id", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/channelSections";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::DELETE).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// Sets the *id* query 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 id(mut self, new_value: &str) -> ChannelSectionDeleteCall<'a> {
        self._id = new_value.to_string();
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> ChannelSectionDeleteCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> ChannelSectionDeleteCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> ChannelSectionDeleteCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> ChannelSectionDeleteCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Inserts a new resource into this collection.
///
/// A builder for the *insert* method supported by a *channelSection* resource.
/// It is not used directly, but through a `ChannelSectionMethods` instance.
///
/// **Settable Parts**
/// 
/// * *snippet*
/// * *contentDetails*
///
/// # Scopes
///
/// You will need authorization for at least one of the following scopes to make a valid call, possibly depending on *parts*:
///
/// * *https://www.googleapis.com/auth/youtube*
/// * *https://www.googleapis.com/auth/youtube.force-ssl*
/// * *https://www.googleapis.com/auth/youtubepartner*
///
/// The default scope will be `Scope::Full`.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::ChannelSection;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = ChannelSection::default();
/// req.content_details = Default::default(); // is ChannelSectionContentDetails
/// req.snippet = Default::default(); // is ChannelSectionSnippet
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.channel_sections().insert(req)
///              .on_behalf_of_content_owner_channel("ipsum")
///              .on_behalf_of_content_owner("accusam")
///              .doit().await;
/// # }
/// ```
pub struct ChannelSectionInsertCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: ChannelSection,
    _part: Vec<String>,
    _on_behalf_of_content_owner_channel: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for ChannelSectionInsertCall<'a> {}

impl<'a> ChannelSectionInsertCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, ChannelSection)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.channelSections.insert",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._on_behalf_of_content_owner_channel {
            params.push(("onBehalfOfContentOwnerChannel", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["alt", "part", "onBehalfOfContentOwnerChannel", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/channelSections";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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.
    ///
    /// **Settable Parts**
    /// 
    /// * *snippet*
    /// * *contentDetails*
    pub fn request(mut self, new_value: ChannelSection) -> ChannelSectionInsertCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include. The part names that you can include in the parameter value are snippet and contentDetails.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    ///
    /// **Settable Parts**
    /// 
    /// * *snippet*
    /// * *contentDetails*
    pub fn add_part(mut self, new_value: &str) -> ChannelSectionInsertCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// This parameter can only be used in a properly authorized request. *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwnerChannel* parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.
    ///
    /// Sets the *on behalf of content owner channel* query property to the given value.
    pub fn on_behalf_of_content_owner_channel(mut self, new_value: &str) -> ChannelSectionInsertCall<'a> {
        self._on_behalf_of_content_owner_channel = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> ChannelSectionInsertCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> ChannelSectionInsertCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> ChannelSectionInsertCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> ChannelSectionInsertCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *channelSection* resource.
/// It is not used directly, but through a `ChannelSectionMethods` instance.
///
/// **Settable Parts**
/// 
/// * *id*
/// * *snippet*
/// * *contentDetails*
///
/// # Scopes
///
/// You will need authorization for at least one of the following scopes to make a valid call, possibly depending on *parts*:
///
/// * *https://www.googleapis.com/auth/youtube*
/// * *https://www.googleapis.com/auth/youtube.force-ssl*
/// * *https://www.googleapis.com/auth/youtube.readonly*
/// * *https://www.googleapis.com/auth/youtubepartner*
///
/// The default scope will be `Scope::Readonly`.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.channel_sections().list(&vec!["takimata".into()])
///              .on_behalf_of_content_owner("consetetur")
///              .mine(false)
///              .add_id("erat")
///              .hl("consetetur")
///              .channel_id("amet.")
///              .doit().await;
/// # }
/// ```
pub struct ChannelSectionListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _on_behalf_of_content_owner: Option<String>,
    _mine: Option<bool>,
    _id: Vec<String>,
    _hl: Option<String>,
    _channel_id: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for ChannelSectionListCall<'a> {}

impl<'a> ChannelSectionListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, ChannelSectionListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.channelSections.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(8 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        if let Some(value) = self._mine {
            params.push(("mine", value.to_string()));
        }
        if self._id.len() > 0 {
            for f in self._id.iter() {
                params.push(("id", f.to_string()));
            }
        }
        if let Some(value) = self._hl {
            params.push(("hl", value.to_string()));
        }
        if let Some(value) = self._channel_id {
            params.push(("channelId", value.to_string()));
        }
        for &field in ["alt", "part", "onBehalfOfContentOwner", "mine", "id", "hl", "channelId"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/channelSections";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies a comma-separated list of one or more channelSection resource properties that the API response will include. The part names that you can include in the parameter value are id, snippet, and contentDetails. If the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a channelSection resource, the snippet property contains other properties, such as a display title for the channelSection. If you set *part=snippet*, the API response will also contain all of those nested properties.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    /// * *contentDetails*
    pub fn add_part(mut self, new_value: &str) -> ChannelSectionListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> ChannelSectionListCall<'a> {
        self._on_behalf_of_content_owner = Some(new_value.to_string());
        self
    }
    /// Return the ChannelSections owned by the authenticated user.
    ///
    /// Sets the *mine* query property to the given value.
    pub fn mine(mut self, new_value: bool) -> ChannelSectionListCall<'a> {
        self._mine = Some(new_value);
        self
    }
    /// Return the ChannelSections with the given IDs for Stubby or Apiary.
    ///
    /// Append the given value to the *id* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    pub fn add_id(mut self, new_value: &str) -> ChannelSectionListCall<'a> {
        self._id.push(new_value.to_string());
        self
    }
    /// Return content in specified language
    ///
    /// Sets the *hl* query property to the given value.
    pub fn hl(mut self, new_value: &str) -> ChannelSectionListCall<'a> {
        self._hl = Some(new_value.to_string());
        self
    }
    /// Return the ChannelSections owned by the specified channel ID.
    ///
    /// Sets the *channel id* query property to the given value.
    pub fn channel_id(mut self, new_value: &str) -> ChannelSectionListCall<'a> {
        self._channel_id = Some(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 dyn client::Delegate) -> ChannelSectionListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> ChannelSectionListCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> ChannelSectionListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Updates an existing resource.
///
/// A builder for the *update* method supported by a *channelSection* resource.
/// It is not used directly, but through a `ChannelSectionMethods` instance.
///
/// **Settable Parts**
/// 
/// * *snippet*
/// * *contentDetails*
///
/// # Scopes
///
/// You will need authorization for at least one of the following scopes to make a valid call, possibly depending on *parts*:
///
/// * *https://www.googleapis.com/auth/youtube*
/// * *https://www.googleapis.com/auth/youtube.force-ssl*
/// * *https://www.googleapis.com/auth/youtubepartner*
///
/// The default scope will be `Scope::Full`.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::ChannelSection;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = ChannelSection::default();
/// req.content_details = Default::default(); // is ChannelSectionContentDetails
/// req.snippet = Default::default(); // is ChannelSectionSnippet
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.channel_sections().update(req)
///              .on_behalf_of_content_owner("sed")
///              .doit().await;
/// # }
/// ```
pub struct ChannelSectionUpdateCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: ChannelSection,
    _part: Vec<String>,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for ChannelSectionUpdateCall<'a> {}

impl<'a> ChannelSectionUpdateCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, ChannelSection)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.channelSections.update",
                               http_method: hyper::Method::PUT });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["alt", "part", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/channelSections";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::PUT).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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.
    ///
    /// **Settable Parts**
    /// 
    /// * *snippet*
    /// * *contentDetails*
    pub fn request(mut self, new_value: ChannelSection) -> ChannelSectionUpdateCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include. The part names that you can include in the parameter value are snippet and contentDetails.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    ///
    /// **Settable Parts**
    /// 
    /// * *snippet*
    /// * *contentDetails*
    pub fn add_part(mut self, new_value: &str) -> ChannelSectionUpdateCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> ChannelSectionUpdateCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> ChannelSectionUpdateCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> ChannelSectionUpdateCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> ChannelSectionUpdateCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *channel* resource.
/// It is not used directly, but through a `ChannelMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.channels().list(&vec!["takimata".into()])
///              .page_token("dolores")
///              .on_behalf_of_content_owner("gubergren")
///              .my_subscribers(false)
///              .mine(false)
///              .max_results(67)
///              .managed_by_me(false)
///              .add_id("amet.")
///              .hl("ea")
///              .for_username("sadipscing")
///              .category_id("Lorem")
///              .doit().await;
/// # }
/// ```
pub struct ChannelListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _page_token: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _my_subscribers: Option<bool>,
    _mine: Option<bool>,
    _max_results: Option<u32>,
    _managed_by_me: Option<bool>,
    _id: Vec<String>,
    _hl: Option<String>,
    _for_username: Option<String>,
    _category_id: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for ChannelListCall<'a> {}

impl<'a> ChannelListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, ChannelListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.channels.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(13 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._page_token {
            params.push(("pageToken", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        if let Some(value) = self._my_subscribers {
            params.push(("mySubscribers", value.to_string()));
        }
        if let Some(value) = self._mine {
            params.push(("mine", value.to_string()));
        }
        if let Some(value) = self._max_results {
            params.push(("maxResults", value.to_string()));
        }
        if let Some(value) = self._managed_by_me {
            params.push(("managedByMe", value.to_string()));
        }
        if self._id.len() > 0 {
            for f in self._id.iter() {
                params.push(("id", f.to_string()));
            }
        }
        if let Some(value) = self._hl {
            params.push(("hl", value.to_string()));
        }
        if let Some(value) = self._for_username {
            params.push(("forUsername", value.to_string()));
        }
        if let Some(value) = self._category_id {
            params.push(("categoryId", value.to_string()));
        }
        for &field in ["alt", "part", "pageToken", "onBehalfOfContentOwner", "mySubscribers", "mine", "maxResults", "managedByMe", "id", "hl", "forUsername", "categoryId"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/channels";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies a comma-separated list of one or more channel resource properties that the API response will include. If the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a channel resource, the contentDetails property contains other properties, such as the uploads properties. As such, if you set *part=contentDetails*, the API response will also contain all of those nested properties.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    pub fn add_part(mut self, new_value: &str) -> ChannelListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// The *pageToken* parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.
    ///
    /// Sets the *page token* query property to the given value.
    pub fn page_token(mut self, new_value: &str) -> ChannelListCall<'a> {
        self._page_token = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> ChannelListCall<'a> {
        self._on_behalf_of_content_owner = Some(new_value.to_string());
        self
    }
    /// Return the channels subscribed to the authenticated user
    ///
    /// Sets the *my subscribers* query property to the given value.
    pub fn my_subscribers(mut self, new_value: bool) -> ChannelListCall<'a> {
        self._my_subscribers = Some(new_value);
        self
    }
    /// Return the ids of channels owned by the authenticated user.
    ///
    /// Sets the *mine* query property to the given value.
    pub fn mine(mut self, new_value: bool) -> ChannelListCall<'a> {
        self._mine = Some(new_value);
        self
    }
    /// The *maxResults* parameter specifies the maximum number of items that should be returned in the result set.
    ///
    /// Sets the *max results* query property to the given value.
    pub fn max_results(mut self, new_value: u32) -> ChannelListCall<'a> {
        self._max_results = Some(new_value);
        self
    }
    /// Return the channels managed by the authenticated user.
    ///
    /// Sets the *managed by me* query property to the given value.
    pub fn managed_by_me(mut self, new_value: bool) -> ChannelListCall<'a> {
        self._managed_by_me = Some(new_value);
        self
    }
    /// Return the channels with the specified IDs.
    ///
    /// Append the given value to the *id* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    pub fn add_id(mut self, new_value: &str) -> ChannelListCall<'a> {
        self._id.push(new_value.to_string());
        self
    }
    /// Stands for "host language". Specifies the localization language of the metadata to be filled into snippet.localized. The field is filled with the default metadata if there is no localization in the specified language. The parameter value must be a language code included in the list returned by the i18nLanguages.list method (e.g. en_US, es_MX).
    ///
    /// Sets the *hl* query property to the given value.
    pub fn hl(mut self, new_value: &str) -> ChannelListCall<'a> {
        self._hl = Some(new_value.to_string());
        self
    }
    /// Return the channel associated with a YouTube username.
    ///
    /// Sets the *for username* query property to the given value.
    pub fn for_username(mut self, new_value: &str) -> ChannelListCall<'a> {
        self._for_username = Some(new_value.to_string());
        self
    }
    /// Return the channels within the specified guide category ID.
    ///
    /// Sets the *category id* query property to the given value.
    pub fn category_id(mut self, new_value: &str) -> ChannelListCall<'a> {
        self._category_id = Some(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 dyn client::Delegate) -> ChannelListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> ChannelListCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> ChannelListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Updates an existing resource.
///
/// A builder for the *update* method supported by a *channel* resource.
/// It is not used directly, but through a `ChannelMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::Channel;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = Channel::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.channels().update(req)
///              .on_behalf_of_content_owner("invidunt")
///              .doit().await;
/// # }
/// ```
pub struct ChannelUpdateCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: Channel,
    _part: Vec<String>,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for ChannelUpdateCall<'a> {}

impl<'a> ChannelUpdateCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Channel)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.channels.update",
                               http_method: hyper::Method::PUT });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["alt", "part", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/channels";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::PUT).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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: Channel) -> ChannelUpdateCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include. The API currently only allows the parameter value to be set to either brandingSettings or invideoPromotion. (You cannot update both of those parts with a single request.) Note that this method overrides the existing values for all of the mutable properties that are contained in any parts that the parameter value specifies.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> ChannelUpdateCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// The *onBehalfOfContentOwner* parameter indicates that the authenticated user is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with needs to be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> ChannelUpdateCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> ChannelUpdateCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> ChannelUpdateCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> ChannelUpdateCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Inserts a new resource into this collection.
///
/// A builder for the *insert* method supported by a *commentThread* resource.
/// It is not used directly, but through a `CommentThreadMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::CommentThread;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = CommentThread::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.comment_threads().insert(req)
///              .doit().await;
/// # }
/// ```
pub struct CommentThreadInsertCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: CommentThread,
    _part: Vec<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for CommentThreadInsertCall<'a> {}

impl<'a> CommentThreadInsertCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, CommentThread)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.commentThreads.insert",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        for &field in ["alt", "part"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/commentThreads";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::ForceSsl.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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: CommentThread) -> CommentThreadInsertCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter identifies the properties that the API response will include. Set the parameter value to snippet. The snippet part has a quota cost of 2 units.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> CommentThreadInsertCall<'a> {
        self._part.push(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 dyn client::Delegate) -> CommentThreadInsertCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> CommentThreadInsertCall<'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::ForceSsl`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> CommentThreadInsertCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *commentThread* resource.
/// It is not used directly, but through a `CommentThreadMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.comment_threads().list(&vec!["no".into()])
///              .video_id("est")
///              .text_format("At")
///              .search_terms("sed")
///              .page_token("sit")
///              .order("et")
///              .moderation_status("tempor")
///              .max_results(69)
///              .add_id("ipsum")
///              .channel_id("et")
///              .all_threads_related_to_channel_id("sanctus")
///              .doit().await;
/// # }
/// ```
pub struct CommentThreadListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _video_id: Option<String>,
    _text_format: Option<String>,
    _search_terms: Option<String>,
    _page_token: Option<String>,
    _order: Option<String>,
    _moderation_status: Option<String>,
    _max_results: Option<u32>,
    _id: Vec<String>,
    _channel_id: Option<String>,
    _all_threads_related_to_channel_id: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for CommentThreadListCall<'a> {}

impl<'a> CommentThreadListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, CommentThreadListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.commentThreads.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(13 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._video_id {
            params.push(("videoId", value.to_string()));
        }
        if let Some(value) = self._text_format {
            params.push(("textFormat", value.to_string()));
        }
        if let Some(value) = self._search_terms {
            params.push(("searchTerms", value.to_string()));
        }
        if let Some(value) = self._page_token {
            params.push(("pageToken", value.to_string()));
        }
        if let Some(value) = self._order {
            params.push(("order", value.to_string()));
        }
        if let Some(value) = self._moderation_status {
            params.push(("moderationStatus", value.to_string()));
        }
        if let Some(value) = self._max_results {
            params.push(("maxResults", value.to_string()));
        }
        if self._id.len() > 0 {
            for f in self._id.iter() {
                params.push(("id", f.to_string()));
            }
        }
        if let Some(value) = self._channel_id {
            params.push(("channelId", value.to_string()));
        }
        if let Some(value) = self._all_threads_related_to_channel_id {
            params.push(("allThreadsRelatedToChannelId", value.to_string()));
        }
        for &field in ["alt", "part", "videoId", "textFormat", "searchTerms", "pageToken", "order", "moderationStatus", "maxResults", "id", "channelId", "allThreadsRelatedToChannelId"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/commentThreads";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::ForceSsl.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies a comma-separated list of one or more commentThread resource properties that the API response will include.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    pub fn add_part(mut self, new_value: &str) -> CommentThreadListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// Returns the comment threads of the specified video.
    ///
    /// Sets the *video id* query property to the given value.
    pub fn video_id(mut self, new_value: &str) -> CommentThreadListCall<'a> {
        self._video_id = Some(new_value.to_string());
        self
    }
    /// The requested text format for the returned comments.
    ///
    /// Sets the *text format* query property to the given value.
    pub fn text_format(mut self, new_value: &str) -> CommentThreadListCall<'a> {
        self._text_format = Some(new_value.to_string());
        self
    }
    /// Limits the returned comment threads to those matching the specified key words. Not compatible with the 'id' filter.
    ///
    /// Sets the *search terms* query property to the given value.
    pub fn search_terms(mut self, new_value: &str) -> CommentThreadListCall<'a> {
        self._search_terms = Some(new_value.to_string());
        self
    }
    /// The *pageToken* parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.
    ///
    /// Sets the *page token* query property to the given value.
    pub fn page_token(mut self, new_value: &str) -> CommentThreadListCall<'a> {
        self._page_token = Some(new_value.to_string());
        self
    }
    ///
    /// Sets the *order* query property to the given value.
    pub fn order(mut self, new_value: &str) -> CommentThreadListCall<'a> {
        self._order = Some(new_value.to_string());
        self
    }
    /// Limits the returned comment threads to those with the specified moderation status. Not compatible with the 'id' filter. Valid values: published, heldForReview, likelySpam.
    ///
    /// Sets the *moderation status* query property to the given value.
    pub fn moderation_status(mut self, new_value: &str) -> CommentThreadListCall<'a> {
        self._moderation_status = Some(new_value.to_string());
        self
    }
    /// The *maxResults* parameter specifies the maximum number of items that should be returned in the result set.
    ///
    /// Sets the *max results* query property to the given value.
    pub fn max_results(mut self, new_value: u32) -> CommentThreadListCall<'a> {
        self._max_results = Some(new_value);
        self
    }
    /// Returns the comment threads with the given IDs for Stubby or Apiary.
    ///
    /// Append the given value to the *id* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    pub fn add_id(mut self, new_value: &str) -> CommentThreadListCall<'a> {
        self._id.push(new_value.to_string());
        self
    }
    /// Returns the comment threads for all the channel comments (ie does not include comments left on videos).
    ///
    /// Sets the *channel id* query property to the given value.
    pub fn channel_id(mut self, new_value: &str) -> CommentThreadListCall<'a> {
        self._channel_id = Some(new_value.to_string());
        self
    }
    /// Returns the comment threads of all videos of the channel and the channel comments as well.
    ///
    /// Sets the *all threads related to channel id* query property to the given value.
    pub fn all_threads_related_to_channel_id(mut self, new_value: &str) -> CommentThreadListCall<'a> {
        self._all_threads_related_to_channel_id = Some(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 dyn client::Delegate) -> CommentThreadListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> CommentThreadListCall<'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::ForceSsl`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> CommentThreadListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Deletes a resource.
///
/// A builder for the *delete* method supported by a *comment* resource.
/// It is not used directly, but through a `CommentMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.comments().delete("id")
///              .doit().await;
/// # }
/// ```
pub struct CommentDeleteCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: String,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for CommentDeleteCall<'a> {}

impl<'a> CommentDeleteCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.comments.delete",
                               http_method: hyper::Method::DELETE });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(2 + self._additional_params.len());
        params.push(("id", self._id.to_string()));
        for &field in ["id"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/comments";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::ForceSsl.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::DELETE).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// Sets the *id* query 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 id(mut self, new_value: &str) -> CommentDeleteCall<'a> {
        self._id = 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 dyn client::Delegate) -> CommentDeleteCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> CommentDeleteCall<'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::ForceSsl`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> CommentDeleteCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Inserts a new resource into this collection.
///
/// A builder for the *insert* method supported by a *comment* resource.
/// It is not used directly, but through a `CommentMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::Comment;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = Comment::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.comments().insert(req)
///              .doit().await;
/// # }
/// ```
pub struct CommentInsertCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: Comment,
    _part: Vec<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for CommentInsertCall<'a> {}

impl<'a> CommentInsertCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Comment)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.comments.insert",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        for &field in ["alt", "part"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/comments";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::ForceSsl.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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: Comment) -> CommentInsertCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter identifies the properties that the API response will include. Set the parameter value to snippet. The snippet part has a quota cost of 2 units.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> CommentInsertCall<'a> {
        self._part.push(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 dyn client::Delegate) -> CommentInsertCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> CommentInsertCall<'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::ForceSsl`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> CommentInsertCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *comment* resource.
/// It is not used directly, but through a `CommentMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.comments().list(&vec!["est".into()])
///              .text_format("sed")
///              .parent_id("diam")
///              .page_token("dolores")
///              .max_results(32)
///              .add_id("et")
///              .doit().await;
/// # }
/// ```
pub struct CommentListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _text_format: Option<String>,
    _parent_id: Option<String>,
    _page_token: Option<String>,
    _max_results: Option<u32>,
    _id: Vec<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for CommentListCall<'a> {}

impl<'a> CommentListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, CommentListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.comments.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(8 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._text_format {
            params.push(("textFormat", value.to_string()));
        }
        if let Some(value) = self._parent_id {
            params.push(("parentId", value.to_string()));
        }
        if let Some(value) = self._page_token {
            params.push(("pageToken", value.to_string()));
        }
        if let Some(value) = self._max_results {
            params.push(("maxResults", value.to_string()));
        }
        if self._id.len() > 0 {
            for f in self._id.iter() {
                params.push(("id", f.to_string()));
            }
        }
        for &field in ["alt", "part", "textFormat", "parentId", "pageToken", "maxResults", "id"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/comments";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::ForceSsl.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies a comma-separated list of one or more comment resource properties that the API response will include.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    pub fn add_part(mut self, new_value: &str) -> CommentListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// The requested text format for the returned comments.
    ///
    /// Sets the *text format* query property to the given value.
    pub fn text_format(mut self, new_value: &str) -> CommentListCall<'a> {
        self._text_format = Some(new_value.to_string());
        self
    }
    /// Returns replies to the specified comment. Note, currently YouTube features only one level of replies (ie replies to top level comments). However replies to replies may be supported in the future.
    ///
    /// Sets the *parent id* query property to the given value.
    pub fn parent_id(mut self, new_value: &str) -> CommentListCall<'a> {
        self._parent_id = Some(new_value.to_string());
        self
    }
    /// The *pageToken* parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.
    ///
    /// Sets the *page token* query property to the given value.
    pub fn page_token(mut self, new_value: &str) -> CommentListCall<'a> {
        self._page_token = Some(new_value.to_string());
        self
    }
    /// The *maxResults* parameter specifies the maximum number of items that should be returned in the result set.
    ///
    /// Sets the *max results* query property to the given value.
    pub fn max_results(mut self, new_value: u32) -> CommentListCall<'a> {
        self._max_results = Some(new_value);
        self
    }
    /// Returns the comments with the given IDs for One Platform.
    ///
    /// Append the given value to the *id* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    pub fn add_id(mut self, new_value: &str) -> CommentListCall<'a> {
        self._id.push(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 dyn client::Delegate) -> CommentListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> CommentListCall<'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::ForceSsl`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> CommentListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Expresses the caller's opinion that one or more comments should be flagged as spam.
///
/// A builder for the *markAsSpam* method supported by a *comment* resource.
/// It is not used directly, but through a `CommentMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.comments().mark_as_spam(&vec!["sed".into()])
///              .doit().await;
/// # }
/// ```
pub struct CommentMarkAsSpamCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: Vec<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for CommentMarkAsSpamCall<'a> {}

impl<'a> CommentMarkAsSpamCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.comments.markAsSpam",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(2 + self._additional_params.len());
        if self._id.len() > 0 {
            for f in self._id.iter() {
                params.push(("id", f.to_string()));
            }
        }
        for &field in ["id"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/comments/markAsSpam";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::ForceSsl.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// Flags the comments with the given IDs as spam in the caller's opinion.
    ///
    /// Append the given value to the *id* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    pub fn add_id(mut self, new_value: &str) -> CommentMarkAsSpamCall<'a> {
        self._id.push(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 dyn client::Delegate) -> CommentMarkAsSpamCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> CommentMarkAsSpamCall<'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::ForceSsl`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> CommentMarkAsSpamCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Sets the moderation status of one or more comments.
///
/// A builder for the *setModerationStatus* method supported by a *comment* resource.
/// It is not used directly, but through a `CommentMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.comments().set_moderation_status(&vec!["no".into()], "moderationStatus")
///              .ban_author(false)
///              .doit().await;
/// # }
/// ```
pub struct CommentSetModerationStatuCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: Vec<String>,
    _moderation_status: String,
    _ban_author: Option<bool>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for CommentSetModerationStatuCall<'a> {}

impl<'a> CommentSetModerationStatuCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.comments.setModerationStatus",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        if self._id.len() > 0 {
            for f in self._id.iter() {
                params.push(("id", f.to_string()));
            }
        }
        params.push(("moderationStatus", self._moderation_status.to_string()));
        if let Some(value) = self._ban_author {
            params.push(("banAuthor", value.to_string()));
        }
        for &field in ["id", "moderationStatus", "banAuthor"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/comments/setModerationStatus";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::ForceSsl.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// Modifies the moderation status of the comments with the given IDs
    ///
    /// Append the given value to the *id* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    pub fn add_id(mut self, new_value: &str) -> CommentSetModerationStatuCall<'a> {
        self._id.push(new_value.to_string());
        self
    }
    /// Specifies the requested moderation status. Note, comments can be in statuses, which are not available through this call. For example, this call does not allow to mark a comment as 'likely spam'. Valid values: MODERATION_STATUS_PUBLISHED, MODERATION_STATUS_HELD_FOR_REVIEW, MODERATION_STATUS_REJECTED.
    ///
    /// Sets the *moderation status* query 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 moderation_status(mut self, new_value: &str) -> CommentSetModerationStatuCall<'a> {
        self._moderation_status = new_value.to_string();
        self
    }
    /// If set to true the author of the comment gets added to the ban list. This means all future comments of the author will autmomatically be rejected. Only valid in combination with STATUS_REJECTED.
    ///
    /// Sets the *ban author* query property to the given value.
    pub fn ban_author(mut self, new_value: bool) -> CommentSetModerationStatuCall<'a> {
        self._ban_author = Some(new_value);
        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 dyn client::Delegate) -> CommentSetModerationStatuCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> CommentSetModerationStatuCall<'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::ForceSsl`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> CommentSetModerationStatuCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Updates an existing resource.
///
/// A builder for the *update* method supported by a *comment* resource.
/// It is not used directly, but through a `CommentMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::Comment;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = Comment::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.comments().update(req)
///              .doit().await;
/// # }
/// ```
pub struct CommentUpdateCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: Comment,
    _part: Vec<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for CommentUpdateCall<'a> {}

impl<'a> CommentUpdateCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Comment)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.comments.update",
                               http_method: hyper::Method::PUT });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        for &field in ["alt", "part"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/comments";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::ForceSsl.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::PUT).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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: Comment) -> CommentUpdateCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter identifies the properties that the API response will include. You must at least include the snippet part in the parameter value since that part contains all of the properties that the API request can update.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> CommentUpdateCall<'a> {
        self._part.push(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 dyn client::Delegate) -> CommentUpdateCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> CommentUpdateCall<'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::ForceSsl`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> CommentUpdateCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *i18nLanguage* resource.
/// It is not used directly, but through a `I18nLanguageMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.i18n_languages().list(&vec!["sed".into()])
///              .hl("no")
///              .doit().await;
/// # }
/// ```
pub struct I18nLanguageListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _hl: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for I18nLanguageListCall<'a> {}

impl<'a> I18nLanguageListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, I18nLanguageListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.i18nLanguages.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._hl {
            params.push(("hl", value.to_string()));
        }
        for &field in ["alt", "part", "hl"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/i18nLanguages";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies the i18nLanguage resource properties that the API response will include. Set the parameter value to snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    pub fn add_part(mut self, new_value: &str) -> I18nLanguageListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    ///
    /// Sets the *hl* query property to the given value.
    pub fn hl(mut self, new_value: &str) -> I18nLanguageListCall<'a> {
        self._hl = Some(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 dyn client::Delegate) -> I18nLanguageListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> I18nLanguageListCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> I18nLanguageListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *i18nRegion* resource.
/// It is not used directly, but through a `I18nRegionMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.i18n_regions().list(&vec!["nonumy".into()])
///              .hl("At")
///              .doit().await;
/// # }
/// ```
pub struct I18nRegionListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _hl: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for I18nRegionListCall<'a> {}

impl<'a> I18nRegionListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, I18nRegionListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.i18nRegions.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._hl {
            params.push(("hl", value.to_string()));
        }
        for &field in ["alt", "part", "hl"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/i18nRegions";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies the i18nRegion resource properties that the API response will include. Set the parameter value to snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    pub fn add_part(mut self, new_value: &str) -> I18nRegionListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    ///
    /// Sets the *hl* query property to the given value.
    pub fn hl(mut self, new_value: &str) -> I18nRegionListCall<'a> {
        self._hl = Some(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 dyn client::Delegate) -> I18nRegionListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> I18nRegionListCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> I18nRegionListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Bind a broadcast to a stream.
///
/// A builder for the *bind* method supported by a *liveBroadcast* resource.
/// It is not used directly, but through a `LiveBroadcastMethods` instance.
///
/// **Settable Parts**
/// 
/// * *id*
/// * *snippet*
/// * *contentDetails*
/// * *status*
///
/// # Scopes
///
/// You will need authorization for at least one of the following scopes to make a valid call, possibly depending on *parts*:
///
/// * *https://www.googleapis.com/auth/youtube*
/// * *https://www.googleapis.com/auth/youtube.force-ssl*
///
/// The default scope will be `Scope::Full`.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_broadcasts().bind("id", &vec!["aliquyam".into()])
///              .stream_id("dolores")
///              .on_behalf_of_content_owner_channel("sadipscing")
///              .on_behalf_of_content_owner("erat")
///              .doit().await;
/// # }
/// ```
pub struct LiveBroadcastBindCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: String,
    _part: Vec<String>,
    _stream_id: Option<String>,
    _on_behalf_of_content_owner_channel: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveBroadcastBindCall<'a> {}

impl<'a> LiveBroadcastBindCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, LiveBroadcast)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveBroadcasts.bind",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(7 + self._additional_params.len());
        params.push(("id", self._id.to_string()));
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._stream_id {
            params.push(("streamId", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner_channel {
            params.push(("onBehalfOfContentOwnerChannel", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["alt", "id", "part", "streamId", "onBehalfOfContentOwnerChannel", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/liveBroadcasts/bind";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// Broadcast to bind to the stream
    ///
    /// Sets the *id* query 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 id(mut self, new_value: &str) -> LiveBroadcastBindCall<'a> {
        self._id = new_value.to_string();
        self
    }
    /// The *part* parameter specifies a comma-separated list of one or more liveBroadcast resource properties that the API response will include. The part names that you can include in the parameter value are id, snippet, contentDetails, and status.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    /// * *contentDetails*
    /// * *status*
    pub fn add_part(mut self, new_value: &str) -> LiveBroadcastBindCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// Stream to bind, if not set unbind the current one.
    ///
    /// Sets the *stream id* query property to the given value.
    pub fn stream_id(mut self, new_value: &str) -> LiveBroadcastBindCall<'a> {
        self._stream_id = Some(new_value.to_string());
        self
    }
    /// This parameter can only be used in a properly authorized request. *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwnerChannel* parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.
    ///
    /// Sets the *on behalf of content owner channel* query property to the given value.
    pub fn on_behalf_of_content_owner_channel(mut self, new_value: &str) -> LiveBroadcastBindCall<'a> {
        self._on_behalf_of_content_owner_channel = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> LiveBroadcastBindCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> LiveBroadcastBindCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveBroadcastBindCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveBroadcastBindCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Delete a given broadcast.
///
/// A builder for the *delete* method supported by a *liveBroadcast* resource.
/// It is not used directly, but through a `LiveBroadcastMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_broadcasts().delete("id")
///              .on_behalf_of_content_owner_channel("amet")
///              .on_behalf_of_content_owner("est")
///              .doit().await;
/// # }
/// ```
pub struct LiveBroadcastDeleteCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: String,
    _on_behalf_of_content_owner_channel: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveBroadcastDeleteCall<'a> {}

impl<'a> LiveBroadcastDeleteCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveBroadcasts.delete",
                               http_method: hyper::Method::DELETE });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        params.push(("id", self._id.to_string()));
        if let Some(value) = self._on_behalf_of_content_owner_channel {
            params.push(("onBehalfOfContentOwnerChannel", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["id", "onBehalfOfContentOwnerChannel", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/liveBroadcasts";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::DELETE).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// Broadcast to delete.
    ///
    /// Sets the *id* query 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 id(mut self, new_value: &str) -> LiveBroadcastDeleteCall<'a> {
        self._id = new_value.to_string();
        self
    }
    /// This parameter can only be used in a properly authorized request. *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwnerChannel* parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.
    ///
    /// Sets the *on behalf of content owner channel* query property to the given value.
    pub fn on_behalf_of_content_owner_channel(mut self, new_value: &str) -> LiveBroadcastDeleteCall<'a> {
        self._on_behalf_of_content_owner_channel = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> LiveBroadcastDeleteCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> LiveBroadcastDeleteCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveBroadcastDeleteCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveBroadcastDeleteCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Inserts a new stream for the authenticated user.
///
/// A builder for the *insert* method supported by a *liveBroadcast* resource.
/// It is not used directly, but through a `LiveBroadcastMethods` instance.
///
/// **Settable Parts**
/// 
/// * *id*
/// * *snippet*
/// * *contentDetails*
/// * *status*
///
/// # Scopes
///
/// You will need authorization for at least one of the following scopes to make a valid call, possibly depending on *parts*:
///
/// * *https://www.googleapis.com/auth/youtube*
/// * *https://www.googleapis.com/auth/youtube.force-ssl*
///
/// The default scope will be `Scope::Full`.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::LiveBroadcast;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = LiveBroadcast::default();
/// req.content_details = Default::default(); // is LiveBroadcastContentDetails
/// req.id = Some("et".to_string());
/// req.snippet = Default::default(); // is LiveBroadcastSnippet
/// req.status = Default::default(); // is LiveBroadcastStatus
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_broadcasts().insert(req)
///              .on_behalf_of_content_owner_channel("sea")
///              .on_behalf_of_content_owner("consetetur")
///              .doit().await;
/// # }
/// ```
pub struct LiveBroadcastInsertCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: LiveBroadcast,
    _part: Vec<String>,
    _on_behalf_of_content_owner_channel: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveBroadcastInsertCall<'a> {}

impl<'a> LiveBroadcastInsertCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, LiveBroadcast)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveBroadcasts.insert",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._on_behalf_of_content_owner_channel {
            params.push(("onBehalfOfContentOwnerChannel", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["alt", "part", "onBehalfOfContentOwnerChannel", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/liveBroadcasts";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    /// * *contentDetails*
    /// * *status*
    pub fn request(mut self, new_value: LiveBroadcast) -> LiveBroadcastInsertCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include. The part properties that you can include in the parameter value are id, snippet, contentDetails, and status.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    /// * *contentDetails*
    /// * *status*
    pub fn add_part(mut self, new_value: &str) -> LiveBroadcastInsertCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// This parameter can only be used in a properly authorized request. *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwnerChannel* parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.
    ///
    /// Sets the *on behalf of content owner channel* query property to the given value.
    pub fn on_behalf_of_content_owner_channel(mut self, new_value: &str) -> LiveBroadcastInsertCall<'a> {
        self._on_behalf_of_content_owner_channel = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> LiveBroadcastInsertCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> LiveBroadcastInsertCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveBroadcastInsertCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveBroadcastInsertCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieve the list of broadcasts associated with the given channel.
///
/// A builder for the *list* method supported by a *liveBroadcast* resource.
/// It is not used directly, but through a `LiveBroadcastMethods` instance.
///
/// **Settable Parts**
/// 
/// * *id*
/// * *snippet*
/// * *contentDetails*
/// * *status*
/// * *statistics*
///
/// # Scopes
///
/// You will need authorization for at least one of the following scopes to make a valid call, possibly depending on *parts*:
///
/// * *https://www.googleapis.com/auth/youtube*
/// * *https://www.googleapis.com/auth/youtube.force-ssl*
/// * *https://www.googleapis.com/auth/youtube.readonly*
///
/// The default scope will be `Scope::Readonly`.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_broadcasts().list(&vec!["consetetur".into()])
///              .page_token("Stet")
///              .on_behalf_of_content_owner_channel("est")
///              .on_behalf_of_content_owner("aliquyam")
///              .mine(false)
///              .max_results(81)
///              .add_id("diam")
///              .broadcast_type("est")
///              .broadcast_status("sit")
///              .doit().await;
/// # }
/// ```
pub struct LiveBroadcastListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _page_token: Option<String>,
    _on_behalf_of_content_owner_channel: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _mine: Option<bool>,
    _max_results: Option<u32>,
    _id: Vec<String>,
    _broadcast_type: Option<String>,
    _broadcast_status: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveBroadcastListCall<'a> {}

impl<'a> LiveBroadcastListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, LiveBroadcastListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveBroadcasts.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(11 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._page_token {
            params.push(("pageToken", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner_channel {
            params.push(("onBehalfOfContentOwnerChannel", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        if let Some(value) = self._mine {
            params.push(("mine", value.to_string()));
        }
        if let Some(value) = self._max_results {
            params.push(("maxResults", value.to_string()));
        }
        if self._id.len() > 0 {
            for f in self._id.iter() {
                params.push(("id", f.to_string()));
            }
        }
        if let Some(value) = self._broadcast_type {
            params.push(("broadcastType", value.to_string()));
        }
        if let Some(value) = self._broadcast_status {
            params.push(("broadcastStatus", value.to_string()));
        }
        for &field in ["alt", "part", "pageToken", "onBehalfOfContentOwnerChannel", "onBehalfOfContentOwner", "mine", "maxResults", "id", "broadcastType", "broadcastStatus"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/liveBroadcasts";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies a comma-separated list of one or more liveBroadcast resource properties that the API response will include. The part names that you can include in the parameter value are id, snippet, contentDetails, status and statistics.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    /// * *contentDetails*
    /// * *status*
    /// * *statistics*
    pub fn add_part(mut self, new_value: &str) -> LiveBroadcastListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// The *pageToken* parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.
    ///
    /// Sets the *page token* query property to the given value.
    pub fn page_token(mut self, new_value: &str) -> LiveBroadcastListCall<'a> {
        self._page_token = Some(new_value.to_string());
        self
    }
    /// This parameter can only be used in a properly authorized request. *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwnerChannel* parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.
    ///
    /// Sets the *on behalf of content owner channel* query property to the given value.
    pub fn on_behalf_of_content_owner_channel(mut self, new_value: &str) -> LiveBroadcastListCall<'a> {
        self._on_behalf_of_content_owner_channel = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> LiveBroadcastListCall<'a> {
        self._on_behalf_of_content_owner = Some(new_value.to_string());
        self
    }
    ///
    /// Sets the *mine* query property to the given value.
    pub fn mine(mut self, new_value: bool) -> LiveBroadcastListCall<'a> {
        self._mine = Some(new_value);
        self
    }
    /// The *maxResults* parameter specifies the maximum number of items that should be returned in the result set.
    ///
    /// Sets the *max results* query property to the given value.
    pub fn max_results(mut self, new_value: u32) -> LiveBroadcastListCall<'a> {
        self._max_results = Some(new_value);
        self
    }
    /// Return broadcasts with the given ids from Stubby or Apiary.
    ///
    /// Append the given value to the *id* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    pub fn add_id(mut self, new_value: &str) -> LiveBroadcastListCall<'a> {
        self._id.push(new_value.to_string());
        self
    }
    /// Return only broadcasts with the selected type.
    ///
    /// Sets the *broadcast type* query property to the given value.
    pub fn broadcast_type(mut self, new_value: &str) -> LiveBroadcastListCall<'a> {
        self._broadcast_type = Some(new_value.to_string());
        self
    }
    /// Return broadcasts with a certain status, e.g. active broadcasts.
    ///
    /// Sets the *broadcast status* query property to the given value.
    pub fn broadcast_status(mut self, new_value: &str) -> LiveBroadcastListCall<'a> {
        self._broadcast_status = Some(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 dyn client::Delegate) -> LiveBroadcastListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveBroadcastListCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveBroadcastListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Transition a broadcast to a given status.
///
/// A builder for the *transition* method supported by a *liveBroadcast* resource.
/// It is not used directly, but through a `LiveBroadcastMethods` instance.
///
/// **Settable Parts**
/// 
/// * *id*
/// * *snippet*
/// * *contentDetails*
/// * *status*
///
/// # Scopes
///
/// You will need authorization for at least one of the following scopes to make a valid call, possibly depending on *parts*:
///
/// * *https://www.googleapis.com/auth/youtube*
/// * *https://www.googleapis.com/auth/youtube.force-ssl*
///
/// The default scope will be `Scope::Full`.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_broadcasts().transition("broadcastStatus", "id", &vec!["Lorem".into()])
///              .on_behalf_of_content_owner_channel("ea")
///              .on_behalf_of_content_owner("Stet")
///              .doit().await;
/// # }
/// ```
pub struct LiveBroadcastTransitionCall<'a>
    where  {

    hub: &'a YouTube<>,
    _broadcast_status: String,
    _id: String,
    _part: Vec<String>,
    _on_behalf_of_content_owner_channel: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveBroadcastTransitionCall<'a> {}

impl<'a> LiveBroadcastTransitionCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, LiveBroadcast)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveBroadcasts.transition",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(7 + self._additional_params.len());
        params.push(("broadcastStatus", self._broadcast_status.to_string()));
        params.push(("id", self._id.to_string()));
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._on_behalf_of_content_owner_channel {
            params.push(("onBehalfOfContentOwnerChannel", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["alt", "broadcastStatus", "id", "part", "onBehalfOfContentOwnerChannel", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/liveBroadcasts/transition";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The status to which the broadcast is going to transition.
    ///
    /// Sets the *broadcast status* query 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 broadcast_status(mut self, new_value: &str) -> LiveBroadcastTransitionCall<'a> {
        self._broadcast_status = new_value.to_string();
        self
    }
    /// Broadcast to transition.
    ///
    /// Sets the *id* query 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 id(mut self, new_value: &str) -> LiveBroadcastTransitionCall<'a> {
        self._id = new_value.to_string();
        self
    }
    /// The *part* parameter specifies a comma-separated list of one or more liveBroadcast resource properties that the API response will include. The part names that you can include in the parameter value are id, snippet, contentDetails, and status.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    /// * *contentDetails*
    /// * *status*
    pub fn add_part(mut self, new_value: &str) -> LiveBroadcastTransitionCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// This parameter can only be used in a properly authorized request. *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwnerChannel* parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.
    ///
    /// Sets the *on behalf of content owner channel* query property to the given value.
    pub fn on_behalf_of_content_owner_channel(mut self, new_value: &str) -> LiveBroadcastTransitionCall<'a> {
        self._on_behalf_of_content_owner_channel = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> LiveBroadcastTransitionCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> LiveBroadcastTransitionCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveBroadcastTransitionCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveBroadcastTransitionCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Updates an existing broadcast for the authenticated user.
///
/// A builder for the *update* method supported by a *liveBroadcast* resource.
/// It is not used directly, but through a `LiveBroadcastMethods` instance.
///
/// **Settable Parts**
/// 
/// * *id*
/// * *snippet*
/// * *contentDetails*
/// * *status*
///
/// # Scopes
///
/// You will need authorization for at least one of the following scopes to make a valid call, possibly depending on *parts*:
///
/// * *https://www.googleapis.com/auth/youtube*
/// * *https://www.googleapis.com/auth/youtube.force-ssl*
///
/// The default scope will be `Scope::Full`.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::LiveBroadcast;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = LiveBroadcast::default();
/// req.content_details = Default::default(); // is LiveBroadcastContentDetails
/// req.id = Some("dolores".to_string());
/// req.snippet = Default::default(); // is LiveBroadcastSnippet
/// req.status = Default::default(); // is LiveBroadcastStatus
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_broadcasts().update(req)
///              .on_behalf_of_content_owner_channel("eos")
///              .on_behalf_of_content_owner("et")
///              .doit().await;
/// # }
/// ```
pub struct LiveBroadcastUpdateCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: LiveBroadcast,
    _part: Vec<String>,
    _on_behalf_of_content_owner_channel: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveBroadcastUpdateCall<'a> {}

impl<'a> LiveBroadcastUpdateCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, LiveBroadcast)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveBroadcasts.update",
                               http_method: hyper::Method::PUT });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._on_behalf_of_content_owner_channel {
            params.push(("onBehalfOfContentOwnerChannel", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["alt", "part", "onBehalfOfContentOwnerChannel", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/liveBroadcasts";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::PUT).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    /// * *contentDetails*
    /// * *status*
    pub fn request(mut self, new_value: LiveBroadcast) -> LiveBroadcastUpdateCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include. The part properties that you can include in the parameter value are id, snippet, contentDetails, and status. Note that this method will override the existing values for all of the mutable properties that are contained in any parts that the parameter value specifies. For example, a broadcast's privacy status is defined in the status part. As such, if your request is updating a private or unlisted broadcast, and the request's part parameter value includes the status part, the broadcast's privacy setting will be updated to whatever value the request body specifies. If the request body does not specify a value, the existing privacy setting will be removed and the broadcast will revert to the default privacy setting.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    /// * *contentDetails*
    /// * *status*
    pub fn add_part(mut self, new_value: &str) -> LiveBroadcastUpdateCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// This parameter can only be used in a properly authorized request. *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwnerChannel* parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.
    ///
    /// Sets the *on behalf of content owner channel* query property to the given value.
    pub fn on_behalf_of_content_owner_channel(mut self, new_value: &str) -> LiveBroadcastUpdateCall<'a> {
        self._on_behalf_of_content_owner_channel = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> LiveBroadcastUpdateCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> LiveBroadcastUpdateCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveBroadcastUpdateCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveBroadcastUpdateCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Deletes a chat ban.
///
/// A builder for the *delete* method supported by a *liveChatBan* resource.
/// It is not used directly, but through a `LiveChatBanMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_chat_bans().delete("id")
///              .doit().await;
/// # }
/// ```
pub struct LiveChatBanDeleteCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: String,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveChatBanDeleteCall<'a> {}

impl<'a> LiveChatBanDeleteCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveChatBans.delete",
                               http_method: hyper::Method::DELETE });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(2 + self._additional_params.len());
        params.push(("id", self._id.to_string()));
        for &field in ["id"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/liveChat/bans";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::DELETE).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// Sets the *id* query 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 id(mut self, new_value: &str) -> LiveChatBanDeleteCall<'a> {
        self._id = 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 dyn client::Delegate) -> LiveChatBanDeleteCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveChatBanDeleteCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveChatBanDeleteCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Inserts a new resource into this collection.
///
/// A builder for the *insert* method supported by a *liveChatBan* resource.
/// It is not used directly, but through a `LiveChatBanMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::LiveChatBan;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = LiveChatBan::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_chat_bans().insert(req)
///              .doit().await;
/// # }
/// ```
pub struct LiveChatBanInsertCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: LiveChatBan,
    _part: Vec<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveChatBanInsertCall<'a> {}

impl<'a> LiveChatBanInsertCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, LiveChatBan)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveChatBans.insert",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        for &field in ["alt", "part"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/liveChat/bans";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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: LiveChatBan) -> LiveChatBanInsertCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response returns. Set the parameter value to snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> LiveChatBanInsertCall<'a> {
        self._part.push(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 dyn client::Delegate) -> LiveChatBanInsertCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveChatBanInsertCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveChatBanInsertCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Deletes a chat message.
///
/// A builder for the *delete* method supported by a *liveChatMessage* resource.
/// It is not used directly, but through a `LiveChatMessageMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_chat_messages().delete("id")
///              .doit().await;
/// # }
/// ```
pub struct LiveChatMessageDeleteCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: String,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveChatMessageDeleteCall<'a> {}

impl<'a> LiveChatMessageDeleteCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveChatMessages.delete",
                               http_method: hyper::Method::DELETE });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(2 + self._additional_params.len());
        params.push(("id", self._id.to_string()));
        for &field in ["id"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/liveChat/messages";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::DELETE).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// Sets the *id* query 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 id(mut self, new_value: &str) -> LiveChatMessageDeleteCall<'a> {
        self._id = 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 dyn client::Delegate) -> LiveChatMessageDeleteCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveChatMessageDeleteCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveChatMessageDeleteCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Inserts a new resource into this collection.
///
/// A builder for the *insert* method supported by a *liveChatMessage* resource.
/// It is not used directly, but through a `LiveChatMessageMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::LiveChatMessage;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = LiveChatMessage::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_chat_messages().insert(req)
///              .doit().await;
/// # }
/// ```
pub struct LiveChatMessageInsertCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: LiveChatMessage,
    _part: Vec<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveChatMessageInsertCall<'a> {}

impl<'a> LiveChatMessageInsertCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, LiveChatMessage)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveChatMessages.insert",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        for &field in ["alt", "part"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/liveChat/messages";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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: LiveChatMessage) -> LiveChatMessageInsertCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes. It identifies the properties that the write operation will set as well as the properties that the API response will include. Set the parameter value to snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> LiveChatMessageInsertCall<'a> {
        self._part.push(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 dyn client::Delegate) -> LiveChatMessageInsertCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveChatMessageInsertCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveChatMessageInsertCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *liveChatMessage* resource.
/// It is not used directly, but through a `LiveChatMessageMethods` instance.
///
/// **Settable Parts**
/// 
/// * *id*
/// * *snippet*
///
/// # Scopes
///
/// You will need authorization for at least one of the following scopes to make a valid call, possibly depending on *parts*:
///
/// * *https://www.googleapis.com/auth/youtube*
/// * *https://www.googleapis.com/auth/youtube.force-ssl*
/// * *https://www.googleapis.com/auth/youtube.readonly*
///
/// The default scope will be `Scope::Readonly`.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_chat_messages().list("liveChatId", &vec!["dolore".into()])
///              .profile_image_size(61)
///              .page_token("Lorem")
///              .max_results(78)
///              .hl("amet")
///              .doit().await;
/// # }
/// ```
pub struct LiveChatMessageListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _live_chat_id: String,
    _part: Vec<String>,
    _profile_image_size: Option<u32>,
    _page_token: Option<String>,
    _max_results: Option<u32>,
    _hl: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveChatMessageListCall<'a> {}

impl<'a> LiveChatMessageListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, LiveChatMessageListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveChatMessages.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(8 + self._additional_params.len());
        params.push(("liveChatId", self._live_chat_id.to_string()));
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._profile_image_size {
            params.push(("profileImageSize", value.to_string()));
        }
        if let Some(value) = self._page_token {
            params.push(("pageToken", value.to_string()));
        }
        if let Some(value) = self._max_results {
            params.push(("maxResults", value.to_string()));
        }
        if let Some(value) = self._hl {
            params.push(("hl", value.to_string()));
        }
        for &field in ["alt", "liveChatId", "part", "profileImageSize", "pageToken", "maxResults", "hl"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/liveChat/messages";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The id of the live chat for which comments should be returned.
    ///
    /// Sets the *live chat id* query 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 live_chat_id(mut self, new_value: &str) -> LiveChatMessageListCall<'a> {
        self._live_chat_id = new_value.to_string();
        self
    }
    /// The *part* parameter specifies the liveChatComment resource parts that the API response will include. Supported values are id and snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    pub fn add_part(mut self, new_value: &str) -> LiveChatMessageListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// Specifies the size of the profile image that should be returned for each user.
    ///
    /// Sets the *profile image size* query property to the given value.
    pub fn profile_image_size(mut self, new_value: u32) -> LiveChatMessageListCall<'a> {
        self._profile_image_size = Some(new_value);
        self
    }
    /// The *pageToken* parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken property identify other pages that could be retrieved.
    ///
    /// Sets the *page token* query property to the given value.
    pub fn page_token(mut self, new_value: &str) -> LiveChatMessageListCall<'a> {
        self._page_token = Some(new_value.to_string());
        self
    }
    /// The *maxResults* parameter specifies the maximum number of items that should be returned in the result set.
    ///
    /// Sets the *max results* query property to the given value.
    pub fn max_results(mut self, new_value: u32) -> LiveChatMessageListCall<'a> {
        self._max_results = Some(new_value);
        self
    }
    /// Specifies the localization language in which the system messages should be returned.
    ///
    /// Sets the *hl* query property to the given value.
    pub fn hl(mut self, new_value: &str) -> LiveChatMessageListCall<'a> {
        self._hl = Some(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 dyn client::Delegate) -> LiveChatMessageListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveChatMessageListCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveChatMessageListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Deletes a chat moderator.
///
/// A builder for the *delete* method supported by a *liveChatModerator* resource.
/// It is not used directly, but through a `LiveChatModeratorMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_chat_moderators().delete("id")
///              .doit().await;
/// # }
/// ```
pub struct LiveChatModeratorDeleteCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: String,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveChatModeratorDeleteCall<'a> {}

impl<'a> LiveChatModeratorDeleteCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveChatModerators.delete",
                               http_method: hyper::Method::DELETE });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(2 + self._additional_params.len());
        params.push(("id", self._id.to_string()));
        for &field in ["id"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/liveChat/moderators";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::DELETE).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// Sets the *id* query 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 id(mut self, new_value: &str) -> LiveChatModeratorDeleteCall<'a> {
        self._id = 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 dyn client::Delegate) -> LiveChatModeratorDeleteCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveChatModeratorDeleteCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveChatModeratorDeleteCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Inserts a new resource into this collection.
///
/// A builder for the *insert* method supported by a *liveChatModerator* resource.
/// It is not used directly, but through a `LiveChatModeratorMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::LiveChatModerator;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = LiveChatModerator::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_chat_moderators().insert(req)
///              .doit().await;
/// # }
/// ```
pub struct LiveChatModeratorInsertCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: LiveChatModerator,
    _part: Vec<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveChatModeratorInsertCall<'a> {}

impl<'a> LiveChatModeratorInsertCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, LiveChatModerator)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveChatModerators.insert",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        for &field in ["alt", "part"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/liveChat/moderators";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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: LiveChatModerator) -> LiveChatModeratorInsertCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response returns. Set the parameter value to snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> LiveChatModeratorInsertCall<'a> {
        self._part.push(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 dyn client::Delegate) -> LiveChatModeratorInsertCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveChatModeratorInsertCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveChatModeratorInsertCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *liveChatModerator* resource.
/// It is not used directly, but through a `LiveChatModeratorMethods` instance.
///
/// **Settable Parts**
/// 
/// * *id*
/// * *snippet*
///
/// # Scopes
///
/// You will need authorization for at least one of the following scopes to make a valid call, possibly depending on *parts*:
///
/// * *https://www.googleapis.com/auth/youtube*
/// * *https://www.googleapis.com/auth/youtube.force-ssl*
/// * *https://www.googleapis.com/auth/youtube.readonly*
///
/// The default scope will be `Scope::Readonly`.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_chat_moderators().list("liveChatId", &vec!["erat".into()])
///              .page_token("accusam")
///              .max_results(91)
///              .doit().await;
/// # }
/// ```
pub struct LiveChatModeratorListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _live_chat_id: String,
    _part: Vec<String>,
    _page_token: Option<String>,
    _max_results: Option<u32>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveChatModeratorListCall<'a> {}

impl<'a> LiveChatModeratorListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, LiveChatModeratorListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveChatModerators.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
        params.push(("liveChatId", self._live_chat_id.to_string()));
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._page_token {
            params.push(("pageToken", value.to_string()));
        }
        if let Some(value) = self._max_results {
            params.push(("maxResults", value.to_string()));
        }
        for &field in ["alt", "liveChatId", "part", "pageToken", "maxResults"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/liveChat/moderators";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The id of the live chat for which moderators should be returned.
    ///
    /// Sets the *live chat id* query 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 live_chat_id(mut self, new_value: &str) -> LiveChatModeratorListCall<'a> {
        self._live_chat_id = new_value.to_string();
        self
    }
    /// The *part* parameter specifies the liveChatModerator resource parts that the API response will include. Supported values are id and snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    pub fn add_part(mut self, new_value: &str) -> LiveChatModeratorListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// The *pageToken* parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.
    ///
    /// Sets the *page token* query property to the given value.
    pub fn page_token(mut self, new_value: &str) -> LiveChatModeratorListCall<'a> {
        self._page_token = Some(new_value.to_string());
        self
    }
    /// The *maxResults* parameter specifies the maximum number of items that should be returned in the result set.
    ///
    /// Sets the *max results* query property to the given value.
    pub fn max_results(mut self, new_value: u32) -> LiveChatModeratorListCall<'a> {
        self._max_results = Some(new_value);
        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 dyn client::Delegate) -> LiveChatModeratorListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveChatModeratorListCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveChatModeratorListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Deletes an existing stream for the authenticated user.
///
/// A builder for the *delete* method supported by a *liveStream* resource.
/// It is not used directly, but through a `LiveStreamMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_streams().delete("id")
///              .on_behalf_of_content_owner_channel("Lorem")
///              .on_behalf_of_content_owner("et")
///              .doit().await;
/// # }
/// ```
pub struct LiveStreamDeleteCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: String,
    _on_behalf_of_content_owner_channel: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveStreamDeleteCall<'a> {}

impl<'a> LiveStreamDeleteCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveStreams.delete",
                               http_method: hyper::Method::DELETE });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        params.push(("id", self._id.to_string()));
        if let Some(value) = self._on_behalf_of_content_owner_channel {
            params.push(("onBehalfOfContentOwnerChannel", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["id", "onBehalfOfContentOwnerChannel", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/liveStreams";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::DELETE).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// Sets the *id* query 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 id(mut self, new_value: &str) -> LiveStreamDeleteCall<'a> {
        self._id = new_value.to_string();
        self
    }
    /// This parameter can only be used in a properly authorized request. *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwnerChannel* parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.
    ///
    /// Sets the *on behalf of content owner channel* query property to the given value.
    pub fn on_behalf_of_content_owner_channel(mut self, new_value: &str) -> LiveStreamDeleteCall<'a> {
        self._on_behalf_of_content_owner_channel = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> LiveStreamDeleteCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> LiveStreamDeleteCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveStreamDeleteCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveStreamDeleteCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Inserts a new stream for the authenticated user.
///
/// A builder for the *insert* method supported by a *liveStream* resource.
/// It is not used directly, but through a `LiveStreamMethods` instance.
///
/// **Settable Parts**
/// 
/// * *id*
/// * *snippet*
/// * *cdn*
/// * *content_details*
/// * *status*
///
/// # Scopes
///
/// You will need authorization for at least one of the following scopes to make a valid call, possibly depending on *parts*:
///
/// * *https://www.googleapis.com/auth/youtube*
/// * *https://www.googleapis.com/auth/youtube.force-ssl*
///
/// The default scope will be `Scope::Full`.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::LiveStream;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = LiveStream::default();
/// req.cdn = Default::default(); // is CdnSettings
/// req.id = Some("At".to_string());
/// req.snippet = Default::default(); // is LiveStreamSnippet
/// req.status = Default::default(); // is LiveStreamStatus
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_streams().insert(req)
///              .on_behalf_of_content_owner_channel("dolor")
///              .on_behalf_of_content_owner("et")
///              .doit().await;
/// # }
/// ```
pub struct LiveStreamInsertCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: LiveStream,
    _part: Vec<String>,
    _on_behalf_of_content_owner_channel: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveStreamInsertCall<'a> {}

impl<'a> LiveStreamInsertCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, LiveStream)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveStreams.insert",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._on_behalf_of_content_owner_channel {
            params.push(("onBehalfOfContentOwnerChannel", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["alt", "part", "onBehalfOfContentOwnerChannel", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/liveStreams";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    /// * *cdn*
    /// * *content_details*
    /// * *status*
    pub fn request(mut self, new_value: LiveStream) -> LiveStreamInsertCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include. The part properties that you can include in the parameter value are id, snippet, cdn, content_details, and status.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    /// * *cdn*
    /// * *content_details*
    /// * *status*
    pub fn add_part(mut self, new_value: &str) -> LiveStreamInsertCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// This parameter can only be used in a properly authorized request. *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwnerChannel* parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.
    ///
    /// Sets the *on behalf of content owner channel* query property to the given value.
    pub fn on_behalf_of_content_owner_channel(mut self, new_value: &str) -> LiveStreamInsertCall<'a> {
        self._on_behalf_of_content_owner_channel = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> LiveStreamInsertCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> LiveStreamInsertCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveStreamInsertCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveStreamInsertCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieve the list of streams associated with the given channel. --
///
/// A builder for the *list* method supported by a *liveStream* resource.
/// It is not used directly, but through a `LiveStreamMethods` instance.
///
/// **Settable Parts**
/// 
/// * *id*
/// * *snippet*
/// * *cdn*
/// * *status*
///
/// # Scopes
///
/// You will need authorization for at least one of the following scopes to make a valid call, possibly depending on *parts*:
///
/// * *https://www.googleapis.com/auth/youtube*
/// * *https://www.googleapis.com/auth/youtube.force-ssl*
/// * *https://www.googleapis.com/auth/youtube.readonly*
///
/// The default scope will be `Scope::Readonly`.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_streams().list(&vec!["sit".into()])
///              .page_token("erat")
///              .on_behalf_of_content_owner_channel("sea")
///              .on_behalf_of_content_owner("nonumy")
///              .mine(true)
///              .max_results(5)
///              .add_id("sit")
///              .doit().await;
/// # }
/// ```
pub struct LiveStreamListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _page_token: Option<String>,
    _on_behalf_of_content_owner_channel: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _mine: Option<bool>,
    _max_results: Option<u32>,
    _id: Vec<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveStreamListCall<'a> {}

impl<'a> LiveStreamListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, LiveStreamListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveStreams.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(9 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._page_token {
            params.push(("pageToken", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner_channel {
            params.push(("onBehalfOfContentOwnerChannel", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        if let Some(value) = self._mine {
            params.push(("mine", value.to_string()));
        }
        if let Some(value) = self._max_results {
            params.push(("maxResults", value.to_string()));
        }
        if self._id.len() > 0 {
            for f in self._id.iter() {
                params.push(("id", f.to_string()));
            }
        }
        for &field in ["alt", "part", "pageToken", "onBehalfOfContentOwnerChannel", "onBehalfOfContentOwner", "mine", "maxResults", "id"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/liveStreams";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies a comma-separated list of one or more liveStream resource properties that the API response will include. The part names that you can include in the parameter value are id, snippet, cdn, and status.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    /// * *cdn*
    /// * *status*
    pub fn add_part(mut self, new_value: &str) -> LiveStreamListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// The *pageToken* parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.
    ///
    /// Sets the *page token* query property to the given value.
    pub fn page_token(mut self, new_value: &str) -> LiveStreamListCall<'a> {
        self._page_token = Some(new_value.to_string());
        self
    }
    /// This parameter can only be used in a properly authorized request. *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwnerChannel* parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.
    ///
    /// Sets the *on behalf of content owner channel* query property to the given value.
    pub fn on_behalf_of_content_owner_channel(mut self, new_value: &str) -> LiveStreamListCall<'a> {
        self._on_behalf_of_content_owner_channel = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> LiveStreamListCall<'a> {
        self._on_behalf_of_content_owner = Some(new_value.to_string());
        self
    }
    ///
    /// Sets the *mine* query property to the given value.
    pub fn mine(mut self, new_value: bool) -> LiveStreamListCall<'a> {
        self._mine = Some(new_value);
        self
    }
    /// The *maxResults* parameter specifies the maximum number of items that should be returned in the result set.
    ///
    /// Sets the *max results* query property to the given value.
    pub fn max_results(mut self, new_value: u32) -> LiveStreamListCall<'a> {
        self._max_results = Some(new_value);
        self
    }
    /// Return LiveStreams with the given ids from Stubby or Apiary.
    ///
    /// Append the given value to the *id* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    pub fn add_id(mut self, new_value: &str) -> LiveStreamListCall<'a> {
        self._id.push(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 dyn client::Delegate) -> LiveStreamListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveStreamListCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveStreamListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Updates an existing stream for the authenticated user.
///
/// A builder for the *update* method supported by a *liveStream* resource.
/// It is not used directly, but through a `LiveStreamMethods` instance.
///
/// **Settable Parts**
/// 
/// * *id*
/// * *snippet*
/// * *cdn*
/// * *status*
///
/// # Scopes
///
/// You will need authorization for at least one of the following scopes to make a valid call, possibly depending on *parts*:
///
/// * *https://www.googleapis.com/auth/youtube*
/// * *https://www.googleapis.com/auth/youtube.force-ssl*
///
/// The default scope will be `Scope::Full`.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::LiveStream;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = LiveStream::default();
/// req.cdn = Default::default(); // is CdnSettings
/// req.id = Some("aliquyam".to_string());
/// req.snippet = Default::default(); // is LiveStreamSnippet
/// req.status = Default::default(); // is LiveStreamStatus
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.live_streams().update(req)
///              .on_behalf_of_content_owner_channel("eos")
///              .on_behalf_of_content_owner("At")
///              .doit().await;
/// # }
/// ```
pub struct LiveStreamUpdateCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: LiveStream,
    _part: Vec<String>,
    _on_behalf_of_content_owner_channel: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for LiveStreamUpdateCall<'a> {}

impl<'a> LiveStreamUpdateCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, LiveStream)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.liveStreams.update",
                               http_method: hyper::Method::PUT });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._on_behalf_of_content_owner_channel {
            params.push(("onBehalfOfContentOwnerChannel", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["alt", "part", "onBehalfOfContentOwnerChannel", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/liveStreams";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::PUT).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    /// * *cdn*
    /// * *status*
    pub fn request(mut self, new_value: LiveStream) -> LiveStreamUpdateCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include. The part properties that you can include in the parameter value are id, snippet, cdn, and status. Note that this method will override the existing values for all of the mutable properties that are contained in any parts that the parameter value specifies. If the request body does not specify a value for a mutable property, the existing value for that property will be removed.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    /// * *cdn*
    /// * *status*
    pub fn add_part(mut self, new_value: &str) -> LiveStreamUpdateCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// This parameter can only be used in a properly authorized request. *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwnerChannel* parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.
    ///
    /// Sets the *on behalf of content owner channel* query property to the given value.
    pub fn on_behalf_of_content_owner_channel(mut self, new_value: &str) -> LiveStreamUpdateCall<'a> {
        self._on_behalf_of_content_owner_channel = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> LiveStreamUpdateCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> LiveStreamUpdateCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> LiveStreamUpdateCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> LiveStreamUpdateCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of members that match the request criteria for a channel.
///
/// A builder for the *list* method supported by a *member* resource.
/// It is not used directly, but through a `MemberMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.members().list(&vec!["dolores".into()])
///              .page_token("consetetur")
///              .mode("gubergren")
///              .max_results(97)
///              .has_access_to_level("aliquyam")
///              .filter_by_member_channel_id("no")
///              .doit().await;
/// # }
/// ```
pub struct MemberListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _page_token: Option<String>,
    _mode: Option<String>,
    _max_results: Option<u32>,
    _has_access_to_level: Option<String>,
    _filter_by_member_channel_id: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for MemberListCall<'a> {}

impl<'a> MemberListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, MemberListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.members.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(8 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._page_token {
            params.push(("pageToken", value.to_string()));
        }
        if let Some(value) = self._mode {
            params.push(("mode", value.to_string()));
        }
        if let Some(value) = self._max_results {
            params.push(("maxResults", value.to_string()));
        }
        if let Some(value) = self._has_access_to_level {
            params.push(("hasAccessToLevel", value.to_string()));
        }
        if let Some(value) = self._filter_by_member_channel_id {
            params.push(("filterByMemberChannelId", value.to_string()));
        }
        for &field in ["alt", "part", "pageToken", "mode", "maxResults", "hasAccessToLevel", "filterByMemberChannelId"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/members";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::ChannelMembershipCreator.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies the member resource parts that the API response will include. Set the parameter value to snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    pub fn add_part(mut self, new_value: &str) -> MemberListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// The *pageToken* parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.
    ///
    /// Sets the *page token* query property to the given value.
    pub fn page_token(mut self, new_value: &str) -> MemberListCall<'a> {
        self._page_token = Some(new_value.to_string());
        self
    }
    /// Parameter that specifies which channel members to return.
    ///
    /// Sets the *mode* query property to the given value.
    pub fn mode(mut self, new_value: &str) -> MemberListCall<'a> {
        self._mode = Some(new_value.to_string());
        self
    }
    /// The *maxResults* parameter specifies the maximum number of items that should be returned in the result set.
    ///
    /// Sets the *max results* query property to the given value.
    pub fn max_results(mut self, new_value: u32) -> MemberListCall<'a> {
        self._max_results = Some(new_value);
        self
    }
    /// Filter members in the results set to the ones that have access to a level.
    ///
    /// Sets the *has access to level* query property to the given value.
    pub fn has_access_to_level(mut self, new_value: &str) -> MemberListCall<'a> {
        self._has_access_to_level = Some(new_value.to_string());
        self
    }
    /// Comma separated list of channel IDs. Only data about members that are part of this list will be included in the response.
    ///
    /// Sets the *filter by member channel id* query property to the given value.
    pub fn filter_by_member_channel_id(mut self, new_value: &str) -> MemberListCall<'a> {
        self._filter_by_member_channel_id = Some(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 dyn client::Delegate) -> MemberListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> MemberListCall<'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::ChannelMembershipCreator`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> MemberListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of all pricing levels offered by a creator to the fans.
///
/// A builder for the *list* method supported by a *membershipsLevel* resource.
/// It is not used directly, but through a `MembershipsLevelMethods` instance.
///
/// **Settable Parts**
/// 
/// * *id*
/// * *snippet*
///
/// # Scopes
///
/// You will need authorization for the *https://www.googleapis.com/auth/youtube.channel-memberships.creator* scope to make a valid call.
///
/// The default scope will be `Scope::ChannelMembershipCreator`.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.memberships_levels().list(&vec!["amet.".into()])
///              .doit().await;
/// # }
/// ```
pub struct MembershipsLevelListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for MembershipsLevelListCall<'a> {}

impl<'a> MembershipsLevelListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, MembershipsLevelListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.membershipsLevels.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        for &field in ["alt", "part"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/membershipsLevels";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::ChannelMembershipCreator.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies the membershipsLevel resource parts that the API response will include. Supported values are id and snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    pub fn add_part(mut self, new_value: &str) -> MembershipsLevelListCall<'a> {
        self._part.push(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 dyn client::Delegate) -> MembershipsLevelListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> MembershipsLevelListCall<'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::ChannelMembershipCreator`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> MembershipsLevelListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Deletes a resource.
///
/// A builder for the *delete* method supported by a *playlistItem* resource.
/// It is not used directly, but through a `PlaylistItemMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.playlist_items().delete("id")
///              .on_behalf_of_content_owner("Lorem")
///              .doit().await;
/// # }
/// ```
pub struct PlaylistItemDeleteCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: String,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for PlaylistItemDeleteCall<'a> {}

impl<'a> PlaylistItemDeleteCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.playlistItems.delete",
                               http_method: hyper::Method::DELETE });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
        params.push(("id", self._id.to_string()));
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["id", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/playlistItems";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::DELETE).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// Sets the *id* query 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 id(mut self, new_value: &str) -> PlaylistItemDeleteCall<'a> {
        self._id = new_value.to_string();
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> PlaylistItemDeleteCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> PlaylistItemDeleteCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> PlaylistItemDeleteCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> PlaylistItemDeleteCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Inserts a new resource into this collection.
///
/// A builder for the *insert* method supported by a *playlistItem* resource.
/// It is not used directly, but through a `PlaylistItemMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::PlaylistItem;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = PlaylistItem::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.playlist_items().insert(req)
///              .on_behalf_of_content_owner("accusam")
///              .doit().await;
/// # }
/// ```
pub struct PlaylistItemInsertCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: PlaylistItem,
    _part: Vec<String>,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for PlaylistItemInsertCall<'a> {}

impl<'a> PlaylistItemInsertCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, PlaylistItem)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.playlistItems.insert",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["alt", "part", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/playlistItems";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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: PlaylistItem) -> PlaylistItemInsertCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> PlaylistItemInsertCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> PlaylistItemInsertCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> PlaylistItemInsertCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> PlaylistItemInsertCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> PlaylistItemInsertCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *playlistItem* resource.
/// It is not used directly, but through a `PlaylistItemMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.playlist_items().list(&vec!["gubergren".into()])
///              .video_id("sadipscing")
///              .playlist_id("At")
///              .page_token("sit")
///              .on_behalf_of_content_owner("duo")
///              .max_results(48)
///              .add_id("magna")
///              .doit().await;
/// # }
/// ```
pub struct PlaylistItemListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _video_id: Option<String>,
    _playlist_id: Option<String>,
    _page_token: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _max_results: Option<u32>,
    _id: Vec<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for PlaylistItemListCall<'a> {}

impl<'a> PlaylistItemListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, PlaylistItemListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.playlistItems.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(9 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._video_id {
            params.push(("videoId", value.to_string()));
        }
        if let Some(value) = self._playlist_id {
            params.push(("playlistId", value.to_string()));
        }
        if let Some(value) = self._page_token {
            params.push(("pageToken", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        if let Some(value) = self._max_results {
            params.push(("maxResults", value.to_string()));
        }
        if self._id.len() > 0 {
            for f in self._id.iter() {
                params.push(("id", f.to_string()));
            }
        }
        for &field in ["alt", "part", "videoId", "playlistId", "pageToken", "onBehalfOfContentOwner", "maxResults", "id"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/playlistItems";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies a comma-separated list of one or more playlistItem resource properties that the API response will include. If the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a playlistItem resource, the snippet property contains numerous fields, including the title, description, position, and resourceId properties. As such, if you set *part=snippet*, the API response will contain all of those properties.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    pub fn add_part(mut self, new_value: &str) -> PlaylistItemListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// Return the playlist items associated with the given video ID.
    ///
    /// Sets the *video id* query property to the given value.
    pub fn video_id(mut self, new_value: &str) -> PlaylistItemListCall<'a> {
        self._video_id = Some(new_value.to_string());
        self
    }
    /// Return the playlist items within the given playlist.
    ///
    /// Sets the *playlist id* query property to the given value.
    pub fn playlist_id(mut self, new_value: &str) -> PlaylistItemListCall<'a> {
        self._playlist_id = Some(new_value.to_string());
        self
    }
    /// The *pageToken* parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.
    ///
    /// Sets the *page token* query property to the given value.
    pub fn page_token(mut self, new_value: &str) -> PlaylistItemListCall<'a> {
        self._page_token = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> PlaylistItemListCall<'a> {
        self._on_behalf_of_content_owner = Some(new_value.to_string());
        self
    }
    /// The *maxResults* parameter specifies the maximum number of items that should be returned in the result set.
    ///
    /// Sets the *max results* query property to the given value.
    pub fn max_results(mut self, new_value: u32) -> PlaylistItemListCall<'a> {
        self._max_results = Some(new_value);
        self
    }
    ///
    /// Append the given value to the *id* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    pub fn add_id(mut self, new_value: &str) -> PlaylistItemListCall<'a> {
        self._id.push(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 dyn client::Delegate) -> PlaylistItemListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> PlaylistItemListCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> PlaylistItemListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Updates an existing resource.
///
/// A builder for the *update* method supported by a *playlistItem* resource.
/// It is not used directly, but through a `PlaylistItemMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::PlaylistItem;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = PlaylistItem::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.playlist_items().update(req)
///              .on_behalf_of_content_owner("et")
///              .doit().await;
/// # }
/// ```
pub struct PlaylistItemUpdateCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: PlaylistItem,
    _part: Vec<String>,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for PlaylistItemUpdateCall<'a> {}

impl<'a> PlaylistItemUpdateCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, PlaylistItem)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.playlistItems.update",
                               http_method: hyper::Method::PUT });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["alt", "part", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/playlistItems";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::PUT).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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: PlaylistItem) -> PlaylistItemUpdateCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include. Note that this method will override the existing values for all of the mutable properties that are contained in any parts that the parameter value specifies. For example, a playlist item can specify a start time and end time, which identify the times portion of the video that should play when users watch the video in the playlist. If your request is updating a playlist item that sets these values, and the request's part parameter value includes the contentDetails part, the playlist item's start and end times will be updated to whatever value the request body specifies. If the request body does not specify values, the existing start and end times will be removed and replaced with the default settings.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> PlaylistItemUpdateCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> PlaylistItemUpdateCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> PlaylistItemUpdateCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> PlaylistItemUpdateCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> PlaylistItemUpdateCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Deletes a resource.
///
/// A builder for the *delete* method supported by a *playlist* resource.
/// It is not used directly, but through a `PlaylistMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.playlists().delete("id")
///              .on_behalf_of_content_owner("dolor")
///              .doit().await;
/// # }
/// ```
pub struct PlaylistDeleteCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: String,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for PlaylistDeleteCall<'a> {}

impl<'a> PlaylistDeleteCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.playlists.delete",
                               http_method: hyper::Method::DELETE });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
        params.push(("id", self._id.to_string()));
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["id", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/playlists";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::DELETE).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// Sets the *id* query 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 id(mut self, new_value: &str) -> PlaylistDeleteCall<'a> {
        self._id = new_value.to_string();
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> PlaylistDeleteCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> PlaylistDeleteCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> PlaylistDeleteCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> PlaylistDeleteCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Inserts a new resource into this collection.
///
/// A builder for the *insert* method supported by a *playlist* resource.
/// It is not used directly, but through a `PlaylistMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::Playlist;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = Playlist::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.playlists().insert(req)
///              .on_behalf_of_content_owner_channel("Lorem")
///              .on_behalf_of_content_owner("justo")
///              .doit().await;
/// # }
/// ```
pub struct PlaylistInsertCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: Playlist,
    _part: Vec<String>,
    _on_behalf_of_content_owner_channel: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for PlaylistInsertCall<'a> {}

impl<'a> PlaylistInsertCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Playlist)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.playlists.insert",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._on_behalf_of_content_owner_channel {
            params.push(("onBehalfOfContentOwnerChannel", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["alt", "part", "onBehalfOfContentOwnerChannel", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/playlists";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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: Playlist) -> PlaylistInsertCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> PlaylistInsertCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// This parameter can only be used in a properly authorized request. *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwnerChannel* parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.
    ///
    /// Sets the *on behalf of content owner channel* query property to the given value.
    pub fn on_behalf_of_content_owner_channel(mut self, new_value: &str) -> PlaylistInsertCall<'a> {
        self._on_behalf_of_content_owner_channel = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> PlaylistInsertCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> PlaylistInsertCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> PlaylistInsertCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> PlaylistInsertCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *playlist* resource.
/// It is not used directly, but through a `PlaylistMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.playlists().list(&vec!["amet.".into()])
///              .page_token("no")
///              .on_behalf_of_content_owner_channel("nonumy")
///              .on_behalf_of_content_owner("sed")
///              .mine(false)
///              .max_results(43)
///              .add_id("nonumy")
///              .hl("rebum.")
///              .channel_id("tempor")
///              .doit().await;
/// # }
/// ```
pub struct PlaylistListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _page_token: Option<String>,
    _on_behalf_of_content_owner_channel: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _mine: Option<bool>,
    _max_results: Option<u32>,
    _id: Vec<String>,
    _hl: Option<String>,
    _channel_id: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for PlaylistListCall<'a> {}

impl<'a> PlaylistListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, PlaylistListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.playlists.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(11 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._page_token {
            params.push(("pageToken", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner_channel {
            params.push(("onBehalfOfContentOwnerChannel", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        if let Some(value) = self._mine {
            params.push(("mine", value.to_string()));
        }
        if let Some(value) = self._max_results {
            params.push(("maxResults", value.to_string()));
        }
        if self._id.len() > 0 {
            for f in self._id.iter() {
                params.push(("id", f.to_string()));
            }
        }
        if let Some(value) = self._hl {
            params.push(("hl", value.to_string()));
        }
        if let Some(value) = self._channel_id {
            params.push(("channelId", value.to_string()));
        }
        for &field in ["alt", "part", "pageToken", "onBehalfOfContentOwnerChannel", "onBehalfOfContentOwner", "mine", "maxResults", "id", "hl", "channelId"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/playlists";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies a comma-separated list of one or more playlist resource properties that the API response will include. If the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a playlist resource, the snippet property contains properties like author, title, description, tags, and timeCreated. As such, if you set *part=snippet*, the API response will contain all of those properties.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    pub fn add_part(mut self, new_value: &str) -> PlaylistListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// The *pageToken* parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.
    ///
    /// Sets the *page token* query property to the given value.
    pub fn page_token(mut self, new_value: &str) -> PlaylistListCall<'a> {
        self._page_token = Some(new_value.to_string());
        self
    }
    /// This parameter can only be used in a properly authorized request. *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwnerChannel* parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.
    ///
    /// Sets the *on behalf of content owner channel* query property to the given value.
    pub fn on_behalf_of_content_owner_channel(mut self, new_value: &str) -> PlaylistListCall<'a> {
        self._on_behalf_of_content_owner_channel = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> PlaylistListCall<'a> {
        self._on_behalf_of_content_owner = Some(new_value.to_string());
        self
    }
    /// Return the playlists owned by the authenticated user.
    ///
    /// Sets the *mine* query property to the given value.
    pub fn mine(mut self, new_value: bool) -> PlaylistListCall<'a> {
        self._mine = Some(new_value);
        self
    }
    /// The *maxResults* parameter specifies the maximum number of items that should be returned in the result set.
    ///
    /// Sets the *max results* query property to the given value.
    pub fn max_results(mut self, new_value: u32) -> PlaylistListCall<'a> {
        self._max_results = Some(new_value);
        self
    }
    /// Return the playlists with the given IDs for Stubby or Apiary.
    ///
    /// Append the given value to the *id* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    pub fn add_id(mut self, new_value: &str) -> PlaylistListCall<'a> {
        self._id.push(new_value.to_string());
        self
    }
    /// Returen content in specified language
    ///
    /// Sets the *hl* query property to the given value.
    pub fn hl(mut self, new_value: &str) -> PlaylistListCall<'a> {
        self._hl = Some(new_value.to_string());
        self
    }
    /// Return the playlists owned by the specified channel ID.
    ///
    /// Sets the *channel id* query property to the given value.
    pub fn channel_id(mut self, new_value: &str) -> PlaylistListCall<'a> {
        self._channel_id = Some(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 dyn client::Delegate) -> PlaylistListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> PlaylistListCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> PlaylistListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Updates an existing resource.
///
/// A builder for the *update* method supported by a *playlist* resource.
/// It is not used directly, but through a `PlaylistMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::Playlist;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = Playlist::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.playlists().update(req)
///              .on_behalf_of_content_owner("dolore")
///              .doit().await;
/// # }
/// ```
pub struct PlaylistUpdateCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: Playlist,
    _part: Vec<String>,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for PlaylistUpdateCall<'a> {}

impl<'a> PlaylistUpdateCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Playlist)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.playlists.update",
                               http_method: hyper::Method::PUT });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["alt", "part", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/playlists";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::PUT).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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: Playlist) -> PlaylistUpdateCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include. Note that this method will override the existing values for mutable properties that are contained in any parts that the request body specifies. For example, a playlist's description is contained in the snippet part, which must be included in the request body. If the request does not specify a value for the snippet.description property, the playlist's existing description will be deleted.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> PlaylistUpdateCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> PlaylistUpdateCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> PlaylistUpdateCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> PlaylistUpdateCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> PlaylistUpdateCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of search resources
///
/// A builder for the *list* method supported by a *search* resource.
/// It is not used directly, but through a `SearchMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.search().list(&vec!["eos".into()])
///              .video_type("amet.")
///              .video_syndicated("dolore")
///              .video_license("amet")
///              .video_embeddable("ut")
///              .video_duration("At")
///              .video_dimension("sit")
///              .video_definition("vero")
///              .video_category_id("duo")
///              .video_caption("sadipscing")
///              .add_type("ut")
///              .topic_id("rebum.")
///              .safe_search("duo")
///              .relevance_language("kasd")
///              .related_to_video_id("sadipscing")
///              .region_code("tempor")
///              .q("sea")
///              .published_before("et")
///              .published_after("Lorem")
///              .page_token("magna")
///              .order("takimata")
///              .on_behalf_of_content_owner("rebum.")
///              .max_results(74)
///              .location_radius("invidunt")
///              .location("clita")
///              .for_mine(false)
///              .for_developer(false)
///              .for_content_owner(true)
///              .event_type("clita")
///              .channel_type("dolor")
///              .channel_id("aliquyam")
///              .doit().await;
/// # }
/// ```
pub struct SearchListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _video_type: Option<String>,
    _video_syndicated: Option<String>,
    _video_license: Option<String>,
    _video_embeddable: Option<String>,
    _video_duration: Option<String>,
    _video_dimension: Option<String>,
    _video_definition: Option<String>,
    _video_category_id: Option<String>,
    _video_caption: Option<String>,
    _type_: Vec<String>,
    _topic_id: Option<String>,
    _safe_search: Option<String>,
    _relevance_language: Option<String>,
    _related_to_video_id: Option<String>,
    _region_code: Option<String>,
    _q: Option<String>,
    _published_before: Option<String>,
    _published_after: Option<String>,
    _page_token: Option<String>,
    _order: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _max_results: Option<u32>,
    _location_radius: Option<String>,
    _location: Option<String>,
    _for_mine: Option<bool>,
    _for_developer: Option<bool>,
    _for_content_owner: Option<bool>,
    _event_type: Option<String>,
    _channel_type: Option<String>,
    _channel_id: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for SearchListCall<'a> {}

impl<'a> SearchListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, SearchListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.search.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(33 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._video_type {
            params.push(("videoType", value.to_string()));
        }
        if let Some(value) = self._video_syndicated {
            params.push(("videoSyndicated", value.to_string()));
        }
        if let Some(value) = self._video_license {
            params.push(("videoLicense", value.to_string()));
        }
        if let Some(value) = self._video_embeddable {
            params.push(("videoEmbeddable", value.to_string()));
        }
        if let Some(value) = self._video_duration {
            params.push(("videoDuration", value.to_string()));
        }
        if let Some(value) = self._video_dimension {
            params.push(("videoDimension", value.to_string()));
        }
        if let Some(value) = self._video_definition {
            params.push(("videoDefinition", value.to_string()));
        }
        if let Some(value) = self._video_category_id {
            params.push(("videoCategoryId", value.to_string()));
        }
        if let Some(value) = self._video_caption {
            params.push(("videoCaption", value.to_string()));
        }
        if self._type_.len() > 0 {
            for f in self._type_.iter() {
                params.push(("type", f.to_string()));
            }
        }
        if let Some(value) = self._topic_id {
            params.push(("topicId", value.to_string()));
        }
        if let Some(value) = self._safe_search {
            params.push(("safeSearch", value.to_string()));
        }
        if let Some(value) = self._relevance_language {
            params.push(("relevanceLanguage", value.to_string()));
        }
        if let Some(value) = self._related_to_video_id {
            params.push(("relatedToVideoId", value.to_string()));
        }
        if let Some(value) = self._region_code {
            params.push(("regionCode", value.to_string()));
        }
        if let Some(value) = self._q {
            params.push(("q", value.to_string()));
        }
        if let Some(value) = self._published_before {
            params.push(("publishedBefore", value.to_string()));
        }
        if let Some(value) = self._published_after {
            params.push(("publishedAfter", value.to_string()));
        }
        if let Some(value) = self._page_token {
            params.push(("pageToken", value.to_string()));
        }
        if let Some(value) = self._order {
            params.push(("order", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        if let Some(value) = self._max_results {
            params.push(("maxResults", value.to_string()));
        }
        if let Some(value) = self._location_radius {
            params.push(("locationRadius", value.to_string()));
        }
        if let Some(value) = self._location {
            params.push(("location", value.to_string()));
        }
        if let Some(value) = self._for_mine {
            params.push(("forMine", value.to_string()));
        }
        if let Some(value) = self._for_developer {
            params.push(("forDeveloper", value.to_string()));
        }
        if let Some(value) = self._for_content_owner {
            params.push(("forContentOwner", value.to_string()));
        }
        if let Some(value) = self._event_type {
            params.push(("eventType", value.to_string()));
        }
        if let Some(value) = self._channel_type {
            params.push(("channelType", value.to_string()));
        }
        if let Some(value) = self._channel_id {
            params.push(("channelId", value.to_string()));
        }
        for &field in ["alt", "part", "videoType", "videoSyndicated", "videoLicense", "videoEmbeddable", "videoDuration", "videoDimension", "videoDefinition", "videoCategoryId", "videoCaption", "type", "topicId", "safeSearch", "relevanceLanguage", "relatedToVideoId", "regionCode", "q", "publishedBefore", "publishedAfter", "pageToken", "order", "onBehalfOfContentOwner", "maxResults", "locationRadius", "location", "forMine", "forDeveloper", "forContentOwner", "eventType", "channelType", "channelId"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/search";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies a comma-separated list of one or more search resource properties that the API response will include. Set the parameter value to snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    pub fn add_part(mut self, new_value: &str) -> SearchListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// Filter on videos of a specific type.
    ///
    /// Sets the *video type* query property to the given value.
    pub fn video_type(mut self, new_value: &str) -> SearchListCall<'a> {
        self._video_type = Some(new_value.to_string());
        self
    }
    /// Filter on syndicated videos.
    ///
    /// Sets the *video syndicated* query property to the given value.
    pub fn video_syndicated(mut self, new_value: &str) -> SearchListCall<'a> {
        self._video_syndicated = Some(new_value.to_string());
        self
    }
    /// Filter on the license of the videos.
    ///
    /// Sets the *video license* query property to the given value.
    pub fn video_license(mut self, new_value: &str) -> SearchListCall<'a> {
        self._video_license = Some(new_value.to_string());
        self
    }
    /// Filter on embeddable videos.
    ///
    /// Sets the *video embeddable* query property to the given value.
    pub fn video_embeddable(mut self, new_value: &str) -> SearchListCall<'a> {
        self._video_embeddable = Some(new_value.to_string());
        self
    }
    /// Filter on the duration of the videos.
    ///
    /// Sets the *video duration* query property to the given value.
    pub fn video_duration(mut self, new_value: &str) -> SearchListCall<'a> {
        self._video_duration = Some(new_value.to_string());
        self
    }
    /// Filter on 3d videos.
    ///
    /// Sets the *video dimension* query property to the given value.
    pub fn video_dimension(mut self, new_value: &str) -> SearchListCall<'a> {
        self._video_dimension = Some(new_value.to_string());
        self
    }
    /// Filter on the definition of the videos.
    ///
    /// Sets the *video definition* query property to the given value.
    pub fn video_definition(mut self, new_value: &str) -> SearchListCall<'a> {
        self._video_definition = Some(new_value.to_string());
        self
    }
    /// Filter on videos in a specific category.
    ///
    /// Sets the *video category id* query property to the given value.
    pub fn video_category_id(mut self, new_value: &str) -> SearchListCall<'a> {
        self._video_category_id = Some(new_value.to_string());
        self
    }
    /// Filter on the presence of captions on the videos.
    ///
    /// Sets the *video caption* query property to the given value.
    pub fn video_caption(mut self, new_value: &str) -> SearchListCall<'a> {
        self._video_caption = Some(new_value.to_string());
        self
    }
    /// Restrict results to a particular set of resource types from One Platform.
    ///
    /// Append the given value to the *type* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    pub fn add_type(mut self, new_value: &str) -> SearchListCall<'a> {
        self._type_.push(new_value.to_string());
        self
    }
    /// Restrict results to a particular topic.
    ///
    /// Sets the *topic id* query property to the given value.
    pub fn topic_id(mut self, new_value: &str) -> SearchListCall<'a> {
        self._topic_id = Some(new_value.to_string());
        self
    }
    /// Indicates whether the search results should include restricted content as well as standard content.
    ///
    /// Sets the *safe search* query property to the given value.
    pub fn safe_search(mut self, new_value: &str) -> SearchListCall<'a> {
        self._safe_search = Some(new_value.to_string());
        self
    }
    /// Return results relevant to this language.
    ///
    /// Sets the *relevance language* query property to the given value.
    pub fn relevance_language(mut self, new_value: &str) -> SearchListCall<'a> {
        self._relevance_language = Some(new_value.to_string());
        self
    }
    /// Search related to a resource.
    ///
    /// Sets the *related to video id* query property to the given value.
    pub fn related_to_video_id(mut self, new_value: &str) -> SearchListCall<'a> {
        self._related_to_video_id = Some(new_value.to_string());
        self
    }
    /// Display the content as seen by viewers in this country.
    ///
    /// Sets the *region code* query property to the given value.
    pub fn region_code(mut self, new_value: &str) -> SearchListCall<'a> {
        self._region_code = Some(new_value.to_string());
        self
    }
    /// Textual search terms to match.
    ///
    /// Sets the *q* query property to the given value.
    pub fn q(mut self, new_value: &str) -> SearchListCall<'a> {
        self._q = Some(new_value.to_string());
        self
    }
    /// Filter on resources published before this date.
    ///
    /// Sets the *published before* query property to the given value.
    pub fn published_before(mut self, new_value: &str) -> SearchListCall<'a> {
        self._published_before = Some(new_value.to_string());
        self
    }
    /// Filter on resources published after this date.
    ///
    /// Sets the *published after* query property to the given value.
    pub fn published_after(mut self, new_value: &str) -> SearchListCall<'a> {
        self._published_after = Some(new_value.to_string());
        self
    }
    /// The *pageToken* parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.
    ///
    /// Sets the *page token* query property to the given value.
    pub fn page_token(mut self, new_value: &str) -> SearchListCall<'a> {
        self._page_token = Some(new_value.to_string());
        self
    }
    /// Sort order of the results.
    ///
    /// Sets the *order* query property to the given value.
    pub fn order(mut self, new_value: &str) -> SearchListCall<'a> {
        self._order = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> SearchListCall<'a> {
        self._on_behalf_of_content_owner = Some(new_value.to_string());
        self
    }
    /// The *maxResults* parameter specifies the maximum number of items that should be returned in the result set.
    ///
    /// Sets the *max results* query property to the given value.
    pub fn max_results(mut self, new_value: u32) -> SearchListCall<'a> {
        self._max_results = Some(new_value);
        self
    }
    /// Filter on distance from the location (specified above).
    ///
    /// Sets the *location radius* query property to the given value.
    pub fn location_radius(mut self, new_value: &str) -> SearchListCall<'a> {
        self._location_radius = Some(new_value.to_string());
        self
    }
    /// Filter on location of the video
    ///
    /// Sets the *location* query property to the given value.
    pub fn location(mut self, new_value: &str) -> SearchListCall<'a> {
        self._location = Some(new_value.to_string());
        self
    }
    /// Search for the private videos of the authenticated user.
    ///
    /// Sets the *for mine* query property to the given value.
    pub fn for_mine(mut self, new_value: bool) -> SearchListCall<'a> {
        self._for_mine = Some(new_value);
        self
    }
    /// Restrict the search to only retrieve videos uploaded using the project id of the authenticated user.
    ///
    /// Sets the *for developer* query property to the given value.
    pub fn for_developer(mut self, new_value: bool) -> SearchListCall<'a> {
        self._for_developer = Some(new_value);
        self
    }
    /// Search owned by a content owner.
    ///
    /// Sets the *for content owner* query property to the given value.
    pub fn for_content_owner(mut self, new_value: bool) -> SearchListCall<'a> {
        self._for_content_owner = Some(new_value);
        self
    }
    /// Filter on the livestream status of the videos.
    ///
    /// Sets the *event type* query property to the given value.
    pub fn event_type(mut self, new_value: &str) -> SearchListCall<'a> {
        self._event_type = Some(new_value.to_string());
        self
    }
    /// Add a filter on the channel search.
    ///
    /// Sets the *channel type* query property to the given value.
    pub fn channel_type(mut self, new_value: &str) -> SearchListCall<'a> {
        self._channel_type = Some(new_value.to_string());
        self
    }
    /// Filter on resources belonging to this channelId.
    ///
    /// Sets the *channel id* query property to the given value.
    pub fn channel_id(mut self, new_value: &str) -> SearchListCall<'a> {
        self._channel_id = Some(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 dyn client::Delegate) -> SearchListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> SearchListCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> SearchListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Deletes a resource.
///
/// A builder for the *delete* method supported by a *subscription* resource.
/// It is not used directly, but through a `SubscriptionMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.subscriptions().delete("id")
///              .doit().await;
/// # }
/// ```
pub struct SubscriptionDeleteCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: String,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for SubscriptionDeleteCall<'a> {}

impl<'a> SubscriptionDeleteCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.subscriptions.delete",
                               http_method: hyper::Method::DELETE });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(2 + self._additional_params.len());
        params.push(("id", self._id.to_string()));
        for &field in ["id"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/subscriptions";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::DELETE).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// Sets the *id* query 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 id(mut self, new_value: &str) -> SubscriptionDeleteCall<'a> {
        self._id = 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 dyn client::Delegate) -> SubscriptionDeleteCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> SubscriptionDeleteCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> SubscriptionDeleteCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Inserts a new resource into this collection.
///
/// A builder for the *insert* method supported by a *subscription* resource.
/// It is not used directly, but through a `SubscriptionMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::Subscription;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = Subscription::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.subscriptions().insert(req)
///              .doit().await;
/// # }
/// ```
pub struct SubscriptionInsertCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: Subscription,
    _part: Vec<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for SubscriptionInsertCall<'a> {}

impl<'a> SubscriptionInsertCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Subscription)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.subscriptions.insert",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        for &field in ["alt", "part"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/subscriptions";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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: Subscription) -> SubscriptionInsertCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> SubscriptionInsertCall<'a> {
        self._part.push(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 dyn client::Delegate) -> SubscriptionInsertCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> SubscriptionInsertCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> SubscriptionInsertCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *subscription* resource.
/// It is not used directly, but through a `SubscriptionMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.subscriptions().list(&vec!["diam".into()])
///              .page_token("nonumy")
///              .order("et")
///              .on_behalf_of_content_owner_channel("sanctus")
///              .on_behalf_of_content_owner("accusam")
///              .my_subscribers(true)
///              .my_recent_subscribers(true)
///              .mine(false)
///              .max_results(22)
///              .add_id("At")
///              .for_channel_id("erat")
///              .channel_id("justo")
///              .doit().await;
/// # }
/// ```
pub struct SubscriptionListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _page_token: Option<String>,
    _order: Option<String>,
    _on_behalf_of_content_owner_channel: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _my_subscribers: Option<bool>,
    _my_recent_subscribers: Option<bool>,
    _mine: Option<bool>,
    _max_results: Option<u32>,
    _id: Vec<String>,
    _for_channel_id: Option<String>,
    _channel_id: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for SubscriptionListCall<'a> {}

impl<'a> SubscriptionListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, SubscriptionListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.subscriptions.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(14 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._page_token {
            params.push(("pageToken", value.to_string()));
        }
        if let Some(value) = self._order {
            params.push(("order", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner_channel {
            params.push(("onBehalfOfContentOwnerChannel", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        if let Some(value) = self._my_subscribers {
            params.push(("mySubscribers", value.to_string()));
        }
        if let Some(value) = self._my_recent_subscribers {
            params.push(("myRecentSubscribers", value.to_string()));
        }
        if let Some(value) = self._mine {
            params.push(("mine", value.to_string()));
        }
        if let Some(value) = self._max_results {
            params.push(("maxResults", value.to_string()));
        }
        if self._id.len() > 0 {
            for f in self._id.iter() {
                params.push(("id", f.to_string()));
            }
        }
        if let Some(value) = self._for_channel_id {
            params.push(("forChannelId", value.to_string()));
        }
        if let Some(value) = self._channel_id {
            params.push(("channelId", value.to_string()));
        }
        for &field in ["alt", "part", "pageToken", "order", "onBehalfOfContentOwnerChannel", "onBehalfOfContentOwner", "mySubscribers", "myRecentSubscribers", "mine", "maxResults", "id", "forChannelId", "channelId"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/subscriptions";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies a comma-separated list of one or more subscription resource properties that the API response will include. If the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a subscription resource, the snippet property contains other properties, such as a display title for the subscription. If you set *part=snippet*, the API response will also contain all of those nested properties.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    pub fn add_part(mut self, new_value: &str) -> SubscriptionListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// The *pageToken* parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.
    ///
    /// Sets the *page token* query property to the given value.
    pub fn page_token(mut self, new_value: &str) -> SubscriptionListCall<'a> {
        self._page_token = Some(new_value.to_string());
        self
    }
    /// The order of the returned subscriptions
    ///
    /// Sets the *order* query property to the given value.
    pub fn order(mut self, new_value: &str) -> SubscriptionListCall<'a> {
        self._order = Some(new_value.to_string());
        self
    }
    /// This parameter can only be used in a properly authorized request. *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwnerChannel* parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.
    ///
    /// Sets the *on behalf of content owner channel* query property to the given value.
    pub fn on_behalf_of_content_owner_channel(mut self, new_value: &str) -> SubscriptionListCall<'a> {
        self._on_behalf_of_content_owner_channel = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> SubscriptionListCall<'a> {
        self._on_behalf_of_content_owner = Some(new_value.to_string());
        self
    }
    /// Return the subscribers of the given channel owner.
    ///
    /// Sets the *my subscribers* query property to the given value.
    pub fn my_subscribers(mut self, new_value: bool) -> SubscriptionListCall<'a> {
        self._my_subscribers = Some(new_value);
        self
    }
    ///
    /// Sets the *my recent subscribers* query property to the given value.
    pub fn my_recent_subscribers(mut self, new_value: bool) -> SubscriptionListCall<'a> {
        self._my_recent_subscribers = Some(new_value);
        self
    }
    /// Flag for returning the subscriptions of the authenticated user.
    ///
    /// Sets the *mine* query property to the given value.
    pub fn mine(mut self, new_value: bool) -> SubscriptionListCall<'a> {
        self._mine = Some(new_value);
        self
    }
    /// The *maxResults* parameter specifies the maximum number of items that should be returned in the result set.
    ///
    /// Sets the *max results* query property to the given value.
    pub fn max_results(mut self, new_value: u32) -> SubscriptionListCall<'a> {
        self._max_results = Some(new_value);
        self
    }
    /// Return the subscriptions with the given IDs for Stubby or Apiary.
    ///
    /// Append the given value to the *id* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    pub fn add_id(mut self, new_value: &str) -> SubscriptionListCall<'a> {
        self._id.push(new_value.to_string());
        self
    }
    /// Return the subscriptions to the subset of these channels that the authenticated user is subscribed to.
    ///
    /// Sets the *for channel id* query property to the given value.
    pub fn for_channel_id(mut self, new_value: &str) -> SubscriptionListCall<'a> {
        self._for_channel_id = Some(new_value.to_string());
        self
    }
    /// Return the subscriptions of the given channel owner.
    ///
    /// Sets the *channel id* query property to the given value.
    pub fn channel_id(mut self, new_value: &str) -> SubscriptionListCall<'a> {
        self._channel_id = Some(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 dyn client::Delegate) -> SubscriptionListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> SubscriptionListCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> SubscriptionListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *superChatEvent* resource.
/// It is not used directly, but through a `SuperChatEventMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.super_chat_events().list(&vec!["ipsum".into()])
///              .page_token("accusam")
///              .max_results(82)
///              .hl("consetetur")
///              .doit().await;
/// # }
/// ```
pub struct SuperChatEventListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _page_token: Option<String>,
    _max_results: Option<u32>,
    _hl: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for SuperChatEventListCall<'a> {}

impl<'a> SuperChatEventListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, SuperChatEventListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.superChatEvents.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._page_token {
            params.push(("pageToken", value.to_string()));
        }
        if let Some(value) = self._max_results {
            params.push(("maxResults", value.to_string()));
        }
        if let Some(value) = self._hl {
            params.push(("hl", value.to_string()));
        }
        for &field in ["alt", "part", "pageToken", "maxResults", "hl"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/superChatEvents";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies the superChatEvent resource parts that the API response will include. This parameter is currently not supported.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    pub fn add_part(mut self, new_value: &str) -> SuperChatEventListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// The *pageToken* parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.
    ///
    /// Sets the *page token* query property to the given value.
    pub fn page_token(mut self, new_value: &str) -> SuperChatEventListCall<'a> {
        self._page_token = Some(new_value.to_string());
        self
    }
    /// The *maxResults* parameter specifies the maximum number of items that should be returned in the result set.
    ///
    /// Sets the *max results* query property to the given value.
    pub fn max_results(mut self, new_value: u32) -> SuperChatEventListCall<'a> {
        self._max_results = Some(new_value);
        self
    }
    /// Return rendered funding amounts in specified language.
    ///
    /// Sets the *hl* query property to the given value.
    pub fn hl(mut self, new_value: &str) -> SuperChatEventListCall<'a> {
        self._hl = Some(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 dyn client::Delegate) -> SuperChatEventListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> SuperChatEventListCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> SuperChatEventListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// POST method.
///
/// A builder for the *insert* method supported by a *test* resource.
/// It is not used directly, but through a `TestMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::TestItem;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = TestItem::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.tests().insert(req)
///              .external_channel_id("no")
///              .doit().await;
/// # }
/// ```
pub struct TestInsertCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: TestItem,
    _part: Vec<String>,
    _external_channel_id: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for TestInsertCall<'a> {}

impl<'a> TestInsertCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, TestItem)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.tests.insert",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._external_channel_id {
            params.push(("externalChannelId", value.to_string()));
        }
        for &field in ["alt", "part", "externalChannelId"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/tests";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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: TestItem) -> TestInsertCall<'a> {
        self._request = new_value;
        self
    }
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> TestInsertCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    ///
    /// Sets the *external channel id* query property to the given value.
    pub fn external_channel_id(mut self, new_value: &str) -> TestInsertCall<'a> {
        self._external_channel_id = Some(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 dyn client::Delegate) -> TestInsertCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> TestInsertCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> TestInsertCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Deletes a resource.
///
/// A builder for the *delete* method supported by a *thirdPartyLink* resource.
/// It is not used directly, but through a `ThirdPartyLinkMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.third_party_links().delete("linkingToken", "type")
///              .add_part("diam")
///              .external_channel_id("sea")
///              .doit().await;
/// # }
/// ```
pub struct ThirdPartyLinkDeleteCall<'a>
    where  {

    hub: &'a YouTube<>,
    _linking_token: String,
    _type_: String,
    _part: Vec<String>,
    _external_channel_id: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
}

impl<'a> client::CallBuilder for ThirdPartyLinkDeleteCall<'a> {}

impl<'a> ThirdPartyLinkDeleteCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.thirdPartyLinks.delete",
                               http_method: hyper::Method::DELETE });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
        params.push(("linkingToken", self._linking_token.to_string()));
        params.push(("type", self._type_.to_string()));
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._external_channel_id {
            params.push(("externalChannelId", value.to_string()));
        }
        for &field in ["linkingToken", "type", "part", "externalChannelId"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/thirdPartyLinks";
        
        let key = dlg.api_key();
        match key {
            Some(value) => params.push(("key", value)),
            None => {
                dlg.finished(false);
                return Err(client::Error::MissingAPIKey)
            }
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::DELETE).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone());


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// Delete the partner links with the given linking token.
    ///
    /// Sets the *linking token* query 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 linking_token(mut self, new_value: &str) -> ThirdPartyLinkDeleteCall<'a> {
        self._linking_token = new_value.to_string();
        self
    }
    /// Type of the link to be deleted.
    ///
    /// Sets the *type* query 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 type_(mut self, new_value: &str) -> ThirdPartyLinkDeleteCall<'a> {
        self._type_ = new_value.to_string();
        self
    }
    /// Do not use. Required for compatibility.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    pub fn add_part(mut self, new_value: &str) -> ThirdPartyLinkDeleteCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// Channel ID to which changes should be applied, for delegation.
    ///
    /// Sets the *external channel id* query property to the given value.
    pub fn external_channel_id(mut self, new_value: &str) -> ThirdPartyLinkDeleteCall<'a> {
        self._external_channel_id = Some(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 dyn client::Delegate) -> ThirdPartyLinkDeleteCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> ThirdPartyLinkDeleteCall<'a>
                                                        where T: AsRef<str> {
        self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
        self
    }

}


/// Inserts a new resource into this collection.
///
/// A builder for the *insert* method supported by a *thirdPartyLink* resource.
/// It is not used directly, but through a `ThirdPartyLinkMethods` instance.
///
/// **Settable Parts**
/// 
/// * *linkingToken*
/// * *status*
/// * *snippet*
///
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::ThirdPartyLink;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = ThirdPartyLink::default();
/// req.linking_token = Some("ipsum".to_string());
/// req.snippet = Default::default(); // is ThirdPartyLinkSnippet
/// req.status = Default::default(); // is ThirdPartyLinkStatus
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.third_party_links().insert(req)
///              .external_channel_id("Stet")
///              .doit().await;
/// # }
/// ```
pub struct ThirdPartyLinkInsertCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: ThirdPartyLink,
    _part: Vec<String>,
    _external_channel_id: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
}

impl<'a> client::CallBuilder for ThirdPartyLinkInsertCall<'a> {}

impl<'a> ThirdPartyLinkInsertCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, ThirdPartyLink)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.thirdPartyLinks.insert",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._external_channel_id {
            params.push(("externalChannelId", value.to_string()));
        }
        for &field in ["alt", "part", "externalChannelId"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/thirdPartyLinks";
        
        let key = dlg.api_key();
        match key {
            Some(value) => params.push(("key", value)),
            None => {
                dlg.finished(false);
                return Err(client::Error::MissingAPIKey)
            }
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone());


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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.
    ///
    /// **Settable Parts**
    /// 
    /// * *linkingToken*
    /// * *status*
    /// * *snippet*
    pub fn request(mut self, new_value: ThirdPartyLink) -> ThirdPartyLinkInsertCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter specifies the thirdPartyLink resource parts that the API request and response will include. Supported values are linkingToken, status, and snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    ///
    /// **Settable Parts**
    /// 
    /// * *linkingToken*
    /// * *status*
    /// * *snippet*
    pub fn add_part(mut self, new_value: &str) -> ThirdPartyLinkInsertCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// Channel ID to which changes should be applied, for delegation.
    ///
    /// Sets the *external channel id* query property to the given value.
    pub fn external_channel_id(mut self, new_value: &str) -> ThirdPartyLinkInsertCall<'a> {
        self._external_channel_id = Some(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 dyn client::Delegate) -> ThirdPartyLinkInsertCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> ThirdPartyLinkInsertCall<'a>
                                                        where T: AsRef<str> {
        self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
        self
    }

}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *thirdPartyLink* resource.
/// It is not used directly, but through a `ThirdPartyLinkMethods` instance.
///
/// **Settable Parts**
/// 
/// * *linkingToken*
/// * *status*
/// * *snippet*
///
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.third_party_links().list(&vec!["gubergren".into()])
///              .type_("ipsum")
///              .linking_token("no")
///              .external_channel_id("sit")
///              .doit().await;
/// # }
/// ```
pub struct ThirdPartyLinkListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _type_: Option<String>,
    _linking_token: Option<String>,
    _external_channel_id: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
}

impl<'a> client::CallBuilder for ThirdPartyLinkListCall<'a> {}

impl<'a> ThirdPartyLinkListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, ThirdPartyLink)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.thirdPartyLinks.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._type_ {
            params.push(("type", value.to_string()));
        }
        if let Some(value) = self._linking_token {
            params.push(("linkingToken", value.to_string()));
        }
        if let Some(value) = self._external_channel_id {
            params.push(("externalChannelId", value.to_string()));
        }
        for &field in ["alt", "part", "type", "linkingToken", "externalChannelId"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/thirdPartyLinks";
        
        let key = dlg.api_key();
        match key {
            Some(value) => params.push(("key", value)),
            None => {
                dlg.finished(false);
                return Err(client::Error::MissingAPIKey)
            }
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone());


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies the thirdPartyLink resource parts that the API response will include. Supported values are linkingToken, status, and snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    ///
    /// **Settable Parts**
    /// 
    /// * *linkingToken*
    /// * *status*
    /// * *snippet*
    pub fn add_part(mut self, new_value: &str) -> ThirdPartyLinkListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// Get a third party link of the given type.
    ///
    /// Sets the *type* query property to the given value.
    pub fn type_(mut self, new_value: &str) -> ThirdPartyLinkListCall<'a> {
        self._type_ = Some(new_value.to_string());
        self
    }
    /// Get a third party link with the given linking token.
    ///
    /// Sets the *linking token* query property to the given value.
    pub fn linking_token(mut self, new_value: &str) -> ThirdPartyLinkListCall<'a> {
        self._linking_token = Some(new_value.to_string());
        self
    }
    /// Channel ID to which changes should be applied, for delegation.
    ///
    /// Sets the *external channel id* query property to the given value.
    pub fn external_channel_id(mut self, new_value: &str) -> ThirdPartyLinkListCall<'a> {
        self._external_channel_id = Some(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 dyn client::Delegate) -> ThirdPartyLinkListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> ThirdPartyLinkListCall<'a>
                                                        where T: AsRef<str> {
        self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
        self
    }

}


/// Updates an existing resource.
///
/// A builder for the *update* method supported by a *thirdPartyLink* resource.
/// It is not used directly, but through a `ThirdPartyLinkMethods` instance.
///
/// **Settable Parts**
/// 
/// * *linkingToken*
/// * *status*
/// * *snippet*
///
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::ThirdPartyLink;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = ThirdPartyLink::default();
/// req.linking_token = Some("kasd".to_string());
/// req.snippet = Default::default(); // is ThirdPartyLinkSnippet
/// req.status = Default::default(); // is ThirdPartyLinkStatus
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.third_party_links().update(req)
///              .external_channel_id("amet")
///              .doit().await;
/// # }
/// ```
pub struct ThirdPartyLinkUpdateCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: ThirdPartyLink,
    _part: Vec<String>,
    _external_channel_id: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
}

impl<'a> client::CallBuilder for ThirdPartyLinkUpdateCall<'a> {}

impl<'a> ThirdPartyLinkUpdateCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, ThirdPartyLink)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.thirdPartyLinks.update",
                               http_method: hyper::Method::PUT });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._external_channel_id {
            params.push(("externalChannelId", value.to_string()));
        }
        for &field in ["alt", "part", "externalChannelId"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/thirdPartyLinks";
        
        let key = dlg.api_key();
        match key {
            Some(value) => params.push(("key", value)),
            None => {
                dlg.finished(false);
                return Err(client::Error::MissingAPIKey)
            }
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::PUT).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone());


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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.
    ///
    /// **Settable Parts**
    /// 
    /// * *linkingToken*
    /// * *status*
    /// * *snippet*
    pub fn request(mut self, new_value: ThirdPartyLink) -> ThirdPartyLinkUpdateCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter specifies the thirdPartyLink resource parts that the API request and response will include. Supported values are linkingToken, status, and snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    ///
    /// **Settable Parts**
    /// 
    /// * *linkingToken*
    /// * *status*
    /// * *snippet*
    pub fn add_part(mut self, new_value: &str) -> ThirdPartyLinkUpdateCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// Channel ID to which changes should be applied, for delegation.
    ///
    /// Sets the *external channel id* query property to the given value.
    pub fn external_channel_id(mut self, new_value: &str) -> ThirdPartyLinkUpdateCall<'a> {
        self._external_channel_id = Some(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 dyn client::Delegate) -> ThirdPartyLinkUpdateCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> ThirdPartyLinkUpdateCall<'a>
                                                        where T: AsRef<str> {
        self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
        self
    }

}


/// As this is not an insert in a strict sense (it supports uploading/setting of a thumbnail for multiple videos, which doesn't result in creation of a single resource), I use a custom verb here.
///
/// A builder for the *set* method supported by a *thumbnail* resource.
/// It is not used directly, but through a `ThumbnailMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use std::fs;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `upload_resumable(...)`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.thumbnails().set("videoId")
///              .on_behalf_of_content_owner("justo")
///              .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()).await;
/// # }
/// ```
pub struct ThumbnailSetCall<'a>
    where  {

    hub: &'a YouTube<>,
    _video_id: String,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for ThumbnailSetCall<'a> {}

impl<'a> ThumbnailSetCall<'a> {


    /// Perform the operation you have build so far.
    async fn doit<RS>(mut self, mut reader: RS, reader_mime_type: mime::Mime, protocol: &'static str) -> client::Result<(hyper::Response<hyper::body::Body>, ThumbnailSetResponse)>
		where RS: client::ReadSeek {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.thumbnails.set",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        params.push(("videoId", self._video_id.to_string()));
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["alt", "videoId", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let (mut url, upload_type) =
            if protocol == "resumable" {
                (self.hub._root_url.clone() + "resumable/upload/youtube/v3/thumbnails/set", "resumable")
            } else if protocol == "simple" {
                (self.hub._root_url.clone() + "upload/youtube/v3/thumbnails/set", "multipart")
            } else {
                unreachable!()
            };
        params.push(("uploadType", upload_type.to_string()));
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).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.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            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;
                    Ok(hyper::Response::builder()
                        .status(hyper::StatusCode::OK)
                        .header("Location", upload_url.as_ref().unwrap().clone())
                        .body(hyper::body::Body::empty())
                        .unwrap())
                } else {
                    let client = &self.hub.client;
                    dlg.pre_request();
                    let mut req_builder = hyper::Request::builder().method(hyper::Method::POST).uri(url.clone().into_string())
                            .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
    
                    upload_url_from_server = true;
                    if protocol == "resumable" {
                        req_builder = req_builder.header("X-Upload-Content-Type", format!("{}", reader_mime_type));
                    }
    
                            let request = if protocol == "simple" {
                                let size = reader.seek(io::SeekFrom::End(0)).unwrap();
                    reader.seek(io::SeekFrom::Start(0)).unwrap();
                    if size > 2097152 {
                    	return Err(client::Error::UploadSizeLimitExceeded(size, 2097152))
                    }
                                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(hyper::body::Body::from(bytes))
                            } else {
                                req_builder.body(hyper::body::Body::from(Vec::new()))
                            };
    
                    client.request(request.unwrap()).await
                    
                }
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    if protocol == "resumable" {
                        let size = reader.seek(io::SeekFrom::End(0)).unwrap();
                        reader.seek(io::SeekFrom::Start(0)).unwrap();
                        if size > 2097152 {
                        	return Err(client::Error::UploadSizeLimitExceeded(size, 2097152))
                        }
                        let upload_result = {
                            let url_str = &res.headers().get("Location").expect("LOCATION header is part of protocol").to_str().unwrap();
                            if upload_url_from_server {
                                dlg.store_upload_url(Some(url_str));
                            }

                            client::ResumableUploadHelper {
                                client: &self.hub.client,
                                delegate: dlg,
                                start_at: if upload_url_from_server { Some(0) } else { None },
                                auth: &self.hub.auth,
                                user_agent: &self.hub._user_agent,
                                auth_header: format!("Bearer {}", token.as_str()),
                                url: url_str,
                                reader: &mut reader,
                                media_type: reader_mime_type.clone(),
                                content_length: size
                            }.upload().await
                        };
                        match upload_result {
                            None => {
                                dlg.finished(false);
                                return Err(client::Error::Cancelled)
                            }
                            Some(Err(err)) => {
                                dlg.finished(false);
                                return Err(client::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(client::Error::Failure(res))
                                }
                            }
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }

    /// 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(...)`.
    ///
    /// * *multipart*: yes
    /// * *max size*: 2097152
    /// * *valid mime types*: 'image/jpeg', 'image/png' and 'application/octet-stream'
    pub async fn upload_resumable<RS>(self, resumeable_stream: RS, mime_type: mime::Mime) -> client::Result<(hyper::Response<hyper::body::Body>, ThumbnailSetResponse)>
                where RS: client::ReadSeek {
        self.doit(resumeable_stream, mime_type, "resumable").await
    }
    /// Upload media all at once.
    /// If the upload fails for whichever reason, all progress is lost.
    ///
    /// * *multipart*: yes
    /// * *max size*: 2097152
    /// * *valid mime types*: 'image/jpeg', 'image/png' and 'application/octet-stream'
    pub async fn upload<RS>(self, stream: RS, mime_type: mime::Mime) -> client::Result<(hyper::Response<hyper::body::Body>, ThumbnailSetResponse)>
                where RS: client::ReadSeek {
        self.doit(stream, mime_type, "simple").await
    }

    /// Returns the Thumbnail with the given video IDs for Stubby or Apiary.
    ///
    /// Sets the *video id* query 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 video_id(mut self, new_value: &str) -> ThumbnailSetCall<'a> {
        self._video_id = new_value.to_string();
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> ThumbnailSetCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> ThumbnailSetCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> ThumbnailSetCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> ThumbnailSetCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *videoAbuseReportReason* resource.
/// It is not used directly, but through a `VideoAbuseReportReasonMethods` instance.
///
/// **Settable Parts**
/// 
/// * *id*
/// * *snippet*
///
/// # Scopes
///
/// You will need authorization for at least one of the following scopes to make a valid call, possibly depending on *parts*:
///
/// * *https://www.googleapis.com/auth/youtube*
/// * *https://www.googleapis.com/auth/youtube.force-ssl*
/// * *https://www.googleapis.com/auth/youtube.readonly*
///
/// The default scope will be `Scope::Readonly`.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.video_abuse_report_reasons().list(&vec!["invidunt".into()])
///              .hl("sed")
///              .doit().await;
/// # }
/// ```
pub struct VideoAbuseReportReasonListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _hl: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for VideoAbuseReportReasonListCall<'a> {}

impl<'a> VideoAbuseReportReasonListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, VideoAbuseReportReasonListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.videoAbuseReportReasons.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._hl {
            params.push(("hl", value.to_string()));
        }
        for &field in ["alt", "part", "hl"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/videoAbuseReportReasons";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies the videoCategory resource parts that the API response will include. Supported values are id and snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    ///
    /// **Settable Parts**
    /// 
    /// * *id*
    /// * *snippet*
    pub fn add_part(mut self, new_value: &str) -> VideoAbuseReportReasonListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    ///
    /// Sets the *hl* query property to the given value.
    pub fn hl(mut self, new_value: &str) -> VideoAbuseReportReasonListCall<'a> {
        self._hl = Some(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 dyn client::Delegate) -> VideoAbuseReportReasonListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> VideoAbuseReportReasonListCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> VideoAbuseReportReasonListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *videoCategory* resource.
/// It is not used directly, but through a `VideoCategoryMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.video_categories().list(&vec!["nonumy".into()])
///              .region_code("sea")
///              .add_id("ipsum")
///              .hl("kasd")
///              .doit().await;
/// # }
/// ```
pub struct VideoCategoryListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _region_code: Option<String>,
    _id: Vec<String>,
    _hl: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for VideoCategoryListCall<'a> {}

impl<'a> VideoCategoryListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, VideoCategoryListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.videoCategories.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._region_code {
            params.push(("regionCode", value.to_string()));
        }
        if self._id.len() > 0 {
            for f in self._id.iter() {
                params.push(("id", f.to_string()));
            }
        }
        if let Some(value) = self._hl {
            params.push(("hl", value.to_string()));
        }
        for &field in ["alt", "part", "regionCode", "id", "hl"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/videoCategories";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies the videoCategory resource properties that the API response will include. Set the parameter value to snippet.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    pub fn add_part(mut self, new_value: &str) -> VideoCategoryListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    ///
    /// Sets the *region code* query property to the given value.
    pub fn region_code(mut self, new_value: &str) -> VideoCategoryListCall<'a> {
        self._region_code = Some(new_value.to_string());
        self
    }
    /// Returns the video categories with the given IDs for Stubby or Apiary.
    ///
    /// Append the given value to the *id* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    pub fn add_id(mut self, new_value: &str) -> VideoCategoryListCall<'a> {
        self._id.push(new_value.to_string());
        self
    }
    ///
    /// Sets the *hl* query property to the given value.
    pub fn hl(mut self, new_value: &str) -> VideoCategoryListCall<'a> {
        self._hl = Some(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 dyn client::Delegate) -> VideoCategoryListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> VideoCategoryListCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> VideoCategoryListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Deletes a resource.
///
/// A builder for the *delete* method supported by a *video* resource.
/// It is not used directly, but through a `VideoMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.videos().delete("id")
///              .on_behalf_of_content_owner("ea")
///              .doit().await;
/// # }
/// ```
pub struct VideoDeleteCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: String,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for VideoDeleteCall<'a> {}

impl<'a> VideoDeleteCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.videos.delete",
                               http_method: hyper::Method::DELETE });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
        params.push(("id", self._id.to_string()));
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["id", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/videos";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::DELETE).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// Sets the *id* query 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 id(mut self, new_value: &str) -> VideoDeleteCall<'a> {
        self._id = new_value.to_string();
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> VideoDeleteCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> VideoDeleteCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> VideoDeleteCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> VideoDeleteCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves the ratings that the authorized user gave to a list of specified videos.
///
/// A builder for the *getRating* method supported by a *video* resource.
/// It is not used directly, but through a `VideoMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.videos().get_rating(&vec!["At".into()])
///              .on_behalf_of_content_owner("erat")
///              .doit().await;
/// # }
/// ```
pub struct VideoGetRatingCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: Vec<String>,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for VideoGetRatingCall<'a> {}

impl<'a> VideoGetRatingCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, VideoGetRatingResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.videos.getRating",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        if self._id.len() > 0 {
            for f in self._id.iter() {
                params.push(("id", f.to_string()));
            }
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["alt", "id", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/videos/getRating";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// Append the given value to the *id* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    pub fn add_id(mut self, new_value: &str) -> VideoGetRatingCall<'a> {
        self._id.push(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> VideoGetRatingCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> VideoGetRatingCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> VideoGetRatingCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> VideoGetRatingCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Inserts a new resource into this collection.
///
/// A builder for the *insert* method supported by a *video* resource.
/// It is not used directly, but through a `VideoMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::Video;
/// use std::fs;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = Video::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.videos().insert(req)
///              .stabilize(false)
///              .on_behalf_of_content_owner_channel("invidunt")
///              .on_behalf_of_content_owner("nonumy")
///              .notify_subscribers(false)
///              .auto_levels(true)
///              .upload(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()).await;
/// # }
/// ```
pub struct VideoInsertCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: Video,
    _part: Vec<String>,
    _stabilize: Option<bool>,
    _on_behalf_of_content_owner_channel: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _notify_subscribers: Option<bool>,
    _auto_levels: Option<bool>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for VideoInsertCall<'a> {}

impl<'a> VideoInsertCall<'a> {


    /// Perform the operation you have build so far.
    async fn doit<RS>(mut self, mut reader: RS, reader_mime_type: mime::Mime, protocol: &'static str) -> client::Result<(hyper::Response<hyper::body::Body>, Video)>
		where RS: client::ReadSeek {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.videos.insert",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(9 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._stabilize {
            params.push(("stabilize", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner_channel {
            params.push(("onBehalfOfContentOwnerChannel", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        if let Some(value) = self._notify_subscribers {
            params.push(("notifySubscribers", value.to_string()));
        }
        if let Some(value) = self._auto_levels {
            params.push(("autoLevels", value.to_string()));
        }
        for &field in ["alt", "part", "stabilize", "onBehalfOfContentOwnerChannel", "onBehalfOfContentOwner", "notifySubscribers", "autoLevels"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let (mut url, upload_type) =
            if protocol == "resumable" {
                (self.hub._root_url.clone() + "resumable/upload/youtube/v3/videos", "resumable")
            } else if protocol == "simple" {
                (self.hub._root_url.clone() + "upload/youtube/v3/videos", "multipart")
            } else {
                unreachable!()
            };
        params.push(("uploadType", upload_type.to_string()));
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            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;
                    Ok(hyper::Response::builder()
                        .status(hyper::StatusCode::OK)
                        .header("Location", upload_url.as_ref().unwrap().clone())
                        .body(hyper::body::Body::empty())
                        .unwrap())
                } else {
                    let mut mp_reader: client::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 > 137438953472 {
                        	return Err(client::Error::UploadSizeLimitExceeded(size, 137438953472))
                        }
                            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 (dyn io::Read + Send), (CONTENT_TYPE, mime_type.to_string()))
                        },
                        _ => (&mut request_value_reader as &mut (dyn io::Read + Send), (CONTENT_TYPE, json_mime_type.to_string())),
                    };
                    let client = &self.hub.client;
                    dlg.pre_request();
                    let mut req_builder = hyper::Request::builder().method(hyper::Method::POST).uri(url.clone().into_string())
                            .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
    
                    upload_url_from_server = true;
                    if protocol == "resumable" {
                        req_builder = req_builder.header("X-Upload-Content-Type", format!("{}", reader_mime_type));
                    }
    
                            let mut body_reader_bytes = vec![];
                            body_reader.read_to_end(&mut body_reader_bytes).unwrap();
                            let request = req_builder
                            .header(content_type.0, content_type.1.to_string())
                            .body(hyper::body::Body::from(body_reader_bytes));
    
                    client.request(request.unwrap()).await
                    
                }
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    if protocol == "resumable" {
                        let size = reader.seek(io::SeekFrom::End(0)).unwrap();
                        reader.seek(io::SeekFrom::Start(0)).unwrap();
                        if size > 137438953472 {
                        	return Err(client::Error::UploadSizeLimitExceeded(size, 137438953472))
                        }
                        let upload_result = {
                            let url_str = &res.headers().get("Location").expect("LOCATION header is part of protocol").to_str().unwrap();
                            if upload_url_from_server {
                                dlg.store_upload_url(Some(url_str));
                            }

                            client::ResumableUploadHelper {
                                client: &self.hub.client,
                                delegate: dlg,
                                start_at: if upload_url_from_server { Some(0) } else { None },
                                auth: &self.hub.auth,
                                user_agent: &self.hub._user_agent,
                                auth_header: format!("Bearer {}", token.as_str()),
                                url: url_str,
                                reader: &mut reader,
                                media_type: reader_mime_type.clone(),
                                content_length: size
                            }.upload().await
                        };
                        match upload_result {
                            None => {
                                dlg.finished(false);
                                return Err(client::Error::Cancelled)
                            }
                            Some(Err(err)) => {
                                dlg.finished(false);
                                return Err(client::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(client::Error::Failure(res))
                                }
                            }
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }

    /// 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(...)`.
    ///
    /// * *multipart*: yes
    /// * *max size*: 137438953472
    /// * *valid mime types*: 'video/*' and 'application/octet-stream'
    pub async fn upload_resumable<RS>(self, resumeable_stream: RS, mime_type: mime::Mime) -> client::Result<(hyper::Response<hyper::body::Body>, Video)>
                where RS: client::ReadSeek {
        self.doit(resumeable_stream, mime_type, "resumable").await
    }
    /// Upload media all at once.
    /// If the upload fails for whichever reason, all progress is lost.
    ///
    /// * *multipart*: yes
    /// * *max size*: 137438953472
    /// * *valid mime types*: 'video/*' and 'application/octet-stream'
    pub async fn upload<RS>(self, stream: RS, mime_type: mime::Mime) -> client::Result<(hyper::Response<hyper::body::Body>, Video)>
                where RS: client::ReadSeek {
        self.doit(stream, mime_type, "simple").await
    }

    ///
    /// 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: Video) -> VideoInsertCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include. Note that not all parts contain properties that can be set when inserting or updating a video. For example, the statistics object encapsulates statistics that YouTube calculates for a video and does not contain values that you can set or modify. If the parameter value specifies a part that does not contain mutable values, that part will still be included in the API response.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> VideoInsertCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// Should stabilize be applied to the upload.
    ///
    /// Sets the *stabilize* query property to the given value.
    pub fn stabilize(mut self, new_value: bool) -> VideoInsertCall<'a> {
        self._stabilize = Some(new_value);
        self
    }
    /// This parameter can only be used in a properly authorized request. *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwnerChannel* parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.
    ///
    /// Sets the *on behalf of content owner channel* query property to the given value.
    pub fn on_behalf_of_content_owner_channel(mut self, new_value: &str) -> VideoInsertCall<'a> {
        self._on_behalf_of_content_owner_channel = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> VideoInsertCall<'a> {
        self._on_behalf_of_content_owner = Some(new_value.to_string());
        self
    }
    /// Notify the channel subscribers about the new video. As default, the notification is enabled.
    ///
    /// Sets the *notify subscribers* query property to the given value.
    pub fn notify_subscribers(mut self, new_value: bool) -> VideoInsertCall<'a> {
        self._notify_subscribers = Some(new_value);
        self
    }
    /// Should auto-levels be applied to the upload.
    ///
    /// Sets the *auto levels* query property to the given value.
    pub fn auto_levels(mut self, new_value: bool) -> VideoInsertCall<'a> {
        self._auto_levels = Some(new_value);
        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 dyn client::Delegate) -> VideoInsertCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> VideoInsertCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> VideoInsertCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Retrieves a list of resources, possibly filtered.
///
/// A builder for the *list* method supported by a *video* resource.
/// It is not used directly, but through a `VideoMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.videos().list(&vec!["voluptua.".into()])
///              .video_category_id("eos")
///              .region_code("duo")
///              .page_token("elitr")
///              .on_behalf_of_content_owner("consetetur")
///              .my_rating("et")
///              .max_width(-14)
///              .max_results(100)
///              .max_height(-48)
///              .locale("takimata")
///              .add_id("erat")
///              .hl("diam")
///              .chart("nonumy")
///              .doit().await;
/// # }
/// ```
pub struct VideoListCall<'a>
    where  {

    hub: &'a YouTube<>,
    _part: Vec<String>,
    _video_category_id: Option<String>,
    _region_code: Option<String>,
    _page_token: Option<String>,
    _on_behalf_of_content_owner: Option<String>,
    _my_rating: Option<String>,
    _max_width: Option<i32>,
    _max_results: Option<u32>,
    _max_height: Option<i32>,
    _locale: Option<String>,
    _id: Vec<String>,
    _hl: Option<String>,
    _chart: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for VideoListCall<'a> {}

impl<'a> VideoListCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, VideoListResponse)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.videos.list",
                               http_method: hyper::Method::GET });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(15 + self._additional_params.len());
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._video_category_id {
            params.push(("videoCategoryId", value.to_string()));
        }
        if let Some(value) = self._region_code {
            params.push(("regionCode", value.to_string()));
        }
        if let Some(value) = self._page_token {
            params.push(("pageToken", value.to_string()));
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        if let Some(value) = self._my_rating {
            params.push(("myRating", value.to_string()));
        }
        if let Some(value) = self._max_width {
            params.push(("maxWidth", value.to_string()));
        }
        if let Some(value) = self._max_results {
            params.push(("maxResults", value.to_string()));
        }
        if let Some(value) = self._max_height {
            params.push(("maxHeight", value.to_string()));
        }
        if let Some(value) = self._locale {
            params.push(("locale", value.to_string()));
        }
        if self._id.len() > 0 {
            for f in self._id.iter() {
                params.push(("id", f.to_string()));
            }
        }
        if let Some(value) = self._hl {
            params.push(("hl", value.to_string()));
        }
        if let Some(value) = self._chart {
            params.push(("chart", value.to_string()));
        }
        for &field in ["alt", "part", "videoCategoryId", "regionCode", "pageToken", "onBehalfOfContentOwner", "myRating", "maxWidth", "maxResults", "maxHeight", "locale", "id", "hl", "chart"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/videos";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    /// The *part* parameter specifies a comma-separated list of one or more video resource properties that the API response will include. If the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a video resource, the snippet property contains the channelId, title, description, tags, and categoryId properties. As such, if you set *part=snippet*, the API response will contain all of those properties.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the property as already been set when instantiating this call,
    /// we provide this method for API completeness.
    pub fn add_part(mut self, new_value: &str) -> VideoListCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// Use chart that is specific to the specified video category
    ///
    /// Sets the *video category id* query property to the given value.
    pub fn video_category_id(mut self, new_value: &str) -> VideoListCall<'a> {
        self._video_category_id = Some(new_value.to_string());
        self
    }
    /// Use a chart that is specific to the specified region
    ///
    /// Sets the *region code* query property to the given value.
    pub fn region_code(mut self, new_value: &str) -> VideoListCall<'a> {
        self._region_code = Some(new_value.to_string());
        self
    }
    /// The *pageToken* parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved. *Note:* This parameter is supported for use in conjunction with the myRating and chart parameters, but it is not supported for use in conjunction with the id parameter.
    ///
    /// Sets the *page token* query property to the given value.
    pub fn page_token(mut self, new_value: &str) -> VideoListCall<'a> {
        self._page_token = Some(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> VideoListCall<'a> {
        self._on_behalf_of_content_owner = Some(new_value.to_string());
        self
    }
    /// Return videos liked/disliked by the authenticated user. Does not support RateType.RATED_TYPE_NONE.
    ///
    /// Sets the *my rating* query property to the given value.
    pub fn my_rating(mut self, new_value: &str) -> VideoListCall<'a> {
        self._my_rating = Some(new_value.to_string());
        self
    }
    /// Return the player with maximum height specified in
    ///
    /// Sets the *max width* query property to the given value.
    pub fn max_width(mut self, new_value: i32) -> VideoListCall<'a> {
        self._max_width = Some(new_value);
        self
    }
    /// The *maxResults* parameter specifies the maximum number of items that should be returned in the result set. *Note:* This parameter is supported for use in conjunction with the myRating and chart parameters, but it is not supported for use in conjunction with the id parameter.
    ///
    /// Sets the *max results* query property to the given value.
    pub fn max_results(mut self, new_value: u32) -> VideoListCall<'a> {
        self._max_results = Some(new_value);
        self
    }
    ///
    /// Sets the *max height* query property to the given value.
    pub fn max_height(mut self, new_value: i32) -> VideoListCall<'a> {
        self._max_height = Some(new_value);
        self
    }
    ///
    /// Sets the *locale* query property to the given value.
    pub fn locale(mut self, new_value: &str) -> VideoListCall<'a> {
        self._locale = Some(new_value.to_string());
        self
    }
    /// Return videos with the given ids.
    ///
    /// Append the given value to the *id* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    pub fn add_id(mut self, new_value: &str) -> VideoListCall<'a> {
        self._id.push(new_value.to_string());
        self
    }
    /// Stands for "host language". Specifies the localization language of the metadata to be filled into snippet.localized. The field is filled with the default metadata if there is no localization in the specified language. The parameter value must be a language code included in the list returned by the i18nLanguages.list method (e.g. en_US, es_MX).
    ///
    /// Sets the *hl* query property to the given value.
    pub fn hl(mut self, new_value: &str) -> VideoListCall<'a> {
        self._hl = Some(new_value.to_string());
        self
    }
    /// Return the videos that are in the specified chart.
    ///
    /// Sets the *chart* query property to the given value.
    pub fn chart(mut self, new_value: &str) -> VideoListCall<'a> {
        self._chart = Some(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 dyn client::Delegate) -> VideoListCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> VideoListCall<'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::Readonly`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> VideoListCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Adds a like or dislike rating to a video or removes a rating from a video.
///
/// A builder for the *rate* method supported by a *video* resource.
/// It is not used directly, but through a `VideoMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.videos().rate("id", "rating")
///              .doit().await;
/// # }
/// ```
pub struct VideoRateCall<'a>
    where  {

    hub: &'a YouTube<>,
    _id: String,
    _rating: String,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for VideoRateCall<'a> {}

impl<'a> VideoRateCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.videos.rate",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
        params.push(("id", self._id.to_string()));
        params.push(("rating", self._rating.to_string()));
        for &field in ["id", "rating"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/videos/rate";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// Sets the *id* query 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 id(mut self, new_value: &str) -> VideoRateCall<'a> {
        self._id = new_value.to_string();
        self
    }
    ///
    /// Sets the *rating* query 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 rating(mut self, new_value: &str) -> VideoRateCall<'a> {
        self._rating = 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 dyn client::Delegate) -> VideoRateCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> VideoRateCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> VideoRateCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Report abuse for a video.
///
/// A builder for the *reportAbuse* method supported by a *video* resource.
/// It is not used directly, but through a `VideoMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::VideoAbuseReport;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = VideoAbuseReport::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.videos().report_abuse(req)
///              .on_behalf_of_content_owner("diam")
///              .doit().await;
/// # }
/// ```
pub struct VideoReportAbuseCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: VideoAbuseReport,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for VideoReportAbuseCall<'a> {}

impl<'a> VideoReportAbuseCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.videos.reportAbuse",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/videos/reportAbuse";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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: VideoAbuseReport) -> VideoReportAbuseCall<'a> {
        self._request = new_value;
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> VideoReportAbuseCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> VideoReportAbuseCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> VideoReportAbuseCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> VideoReportAbuseCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Updates an existing resource.
///
/// A builder for the *update* method supported by a *video* resource.
/// It is not used directly, but through a `VideoMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::Video;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = Video::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.videos().update(req)
///              .on_behalf_of_content_owner("diam")
///              .doit().await;
/// # }
/// ```
pub struct VideoUpdateCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: Video,
    _part: Vec<String>,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for VideoUpdateCall<'a> {}

impl<'a> VideoUpdateCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Video)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.videos.update",
                               http_method: hyper::Method::PUT });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["alt", "part", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/videos";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::PUT).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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: Video) -> VideoUpdateCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include. Note that this method will override the existing values for all of the mutable properties that are contained in any parts that the parameter value specifies. For example, a video's privacy setting is contained in the status part. As such, if your request is updating a private video, and the request's part parameter value includes the status part, the video's privacy setting will be updated to whatever value the request body specifies. If the request body does not specify a value, the existing privacy setting will be removed and the video will revert to the default privacy setting. In addition, not all parts contain properties that can be set when inserting or updating a video. For example, the statistics object encapsulates statistics that YouTube calculates for a video and does not contain values that you can set or modify. If the parameter value specifies a part that does not contain mutable values, that part will still be included in the API response.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> VideoUpdateCall<'a> {
        self._part.push(new_value.to_string());
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> VideoUpdateCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> VideoUpdateCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> VideoUpdateCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> VideoUpdateCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Allows upload of watermark image and setting it for a channel.
///
/// A builder for the *set* method supported by a *watermark* resource.
/// It is not used directly, but through a `WatermarkMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::InvideoBranding;
/// use std::fs;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = InvideoBranding::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `upload_resumable(...)`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.watermarks().set(req, "channelId")
///              .on_behalf_of_content_owner("et")
///              .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()).await;
/// # }
/// ```
pub struct WatermarkSetCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: InvideoBranding,
    _channel_id: String,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for WatermarkSetCall<'a> {}

impl<'a> WatermarkSetCall<'a> {


    /// Perform the operation you have build so far.
    async fn doit<RS>(mut self, mut reader: RS, reader_mime_type: mime::Mime, protocol: &'static str) -> client::Result<hyper::Response<hyper::body::Body>>
		where RS: client::ReadSeek {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.watermarks.set",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        params.push(("channelId", self._channel_id.to_string()));
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["channelId", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let (mut url, upload_type) =
            if protocol == "resumable" {
                (self.hub._root_url.clone() + "resumable/upload/youtube/v3/watermarks/set", "resumable")
            } else if protocol == "simple" {
                (self.hub._root_url.clone() + "upload/youtube/v3/watermarks/set", "multipart")
            } else {
                unreachable!()
            };
        params.push(("uploadType", upload_type.to_string()));
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            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;
                    Ok(hyper::Response::builder()
                        .status(hyper::StatusCode::OK)
                        .header("Location", upload_url.as_ref().unwrap().clone())
                        .body(hyper::body::Body::empty())
                        .unwrap())
                } else {
                    let mut mp_reader: client::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 > 10485760 {
                        	return Err(client::Error::UploadSizeLimitExceeded(size, 10485760))
                        }
                            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 (dyn io::Read + Send), (CONTENT_TYPE, mime_type.to_string()))
                        },
                        _ => (&mut request_value_reader as &mut (dyn io::Read + Send), (CONTENT_TYPE, json_mime_type.to_string())),
                    };
                    let client = &self.hub.client;
                    dlg.pre_request();
                    let mut req_builder = hyper::Request::builder().method(hyper::Method::POST).uri(url.clone().into_string())
                            .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
    
                    upload_url_from_server = true;
                    if protocol == "resumable" {
                        req_builder = req_builder.header("X-Upload-Content-Type", format!("{}", reader_mime_type));
                    }
    
                            let mut body_reader_bytes = vec![];
                            body_reader.read_to_end(&mut body_reader_bytes).unwrap();
                            let request = req_builder
                            .header(content_type.0, content_type.1.to_string())
                            .body(hyper::body::Body::from(body_reader_bytes));
    
                    client.request(request.unwrap()).await
                    
                }
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    if protocol == "resumable" {
                        let size = reader.seek(io::SeekFrom::End(0)).unwrap();
                        reader.seek(io::SeekFrom::Start(0)).unwrap();
                        if size > 10485760 {
                        	return Err(client::Error::UploadSizeLimitExceeded(size, 10485760))
                        }
                        let upload_result = {
                            let url_str = &res.headers().get("Location").expect("LOCATION header is part of protocol").to_str().unwrap();
                            if upload_url_from_server {
                                dlg.store_upload_url(Some(url_str));
                            }

                            client::ResumableUploadHelper {
                                client: &self.hub.client,
                                delegate: dlg,
                                start_at: if upload_url_from_server { Some(0) } else { None },
                                auth: &self.hub.auth,
                                user_agent: &self.hub._user_agent,
                                auth_header: format!("Bearer {}", token.as_str()),
                                url: url_str,
                                reader: &mut reader,
                                media_type: reader_mime_type.clone(),
                                content_length: size
                            }.upload().await
                        };
                        match upload_result {
                            None => {
                                dlg.finished(false);
                                return Err(client::Error::Cancelled)
                            }
                            Some(Err(err)) => {
                                dlg.finished(false);
                                return Err(client::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(client::Error::Failure(res))
                                }
                            }
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }

    /// 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(...)`.
    ///
    /// * *multipart*: yes
    /// * *max size*: 10485760
    /// * *valid mime types*: 'image/jpeg', 'image/png' and 'application/octet-stream'
    pub async fn upload_resumable<RS>(self, resumeable_stream: RS, mime_type: mime::Mime) -> client::Result<hyper::Response<hyper::body::Body>>
                where RS: client::ReadSeek {
        self.doit(resumeable_stream, mime_type, "resumable").await
    }
    /// Upload media all at once.
    /// If the upload fails for whichever reason, all progress is lost.
    ///
    /// * *multipart*: yes
    /// * *max size*: 10485760
    /// * *valid mime types*: 'image/jpeg', 'image/png' and 'application/octet-stream'
    pub async fn upload<RS>(self, stream: RS, mime_type: mime::Mime) -> client::Result<hyper::Response<hyper::body::Body>>
                where RS: client::ReadSeek {
        self.doit(stream, mime_type, "simple").await
    }

    ///
    /// 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: InvideoBranding) -> WatermarkSetCall<'a> {
        self._request = new_value;
        self
    }
    ///
    /// Sets the *channel id* query 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 channel_id(mut self, new_value: &str) -> WatermarkSetCall<'a> {
        self._channel_id = new_value.to_string();
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> WatermarkSetCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> WatermarkSetCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> WatermarkSetCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> WatermarkSetCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Allows removal of channel watermark.
///
/// A builder for the *unset* method supported by a *watermark* resource.
/// It is not used directly, but through a `WatermarkMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.watermarks().unset("channelId")
///              .on_behalf_of_content_owner("dolore")
///              .doit().await;
/// # }
/// ```
pub struct WatermarkUnsetCall<'a>
    where  {

    hub: &'a YouTube<>,
    _channel_id: String,
    _on_behalf_of_content_owner: Option<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
    _scopes: BTreeMap<String, ()>
}

impl<'a> client::CallBuilder for WatermarkUnsetCall<'a> {}

impl<'a> WatermarkUnsetCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.watermarks.unset",
                               http_method: hyper::Method::POST });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
        params.push(("channelId", self._channel_id.to_string()));
        if let Some(value) = self._on_behalf_of_content_owner {
            params.push(("onBehalfOfContentOwner", value.to_string()));
        }
        for &field in ["channelId", "onBehalfOfContentOwner"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }


        let mut url = self.hub._base_url.clone() + "youtube/v3/watermarks/unset";
        if self._scopes.len() == 0 {
            self._scopes.insert(Scope::Full.as_ref().to_string(), ());
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();



        loop {
            let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
                Ok(token) => token.clone(),
                Err(err) => {
                    match  dlg.token(&err) {
                        Some(token) => token,
                        None => {
                            dlg.finished(false);
                            return Err(client::Error::MissingToken(err))
                        }
                    }
                }
            };
            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.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone())                            .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));


                        let request = req_builder
                        .body(hyper::body::Body::empty());

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = res;

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// Sets the *channel id* query 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 channel_id(mut self, new_value: &str) -> WatermarkUnsetCall<'a> {
        self._channel_id = new_value.to_string();
        self
    }
    /// *Note:* This parameter is intended exclusively for YouTube content partners. The *onBehalfOfContentOwner* parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.
    ///
    /// Sets the *on behalf of content owner* query property to the given value.
    pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> WatermarkUnsetCall<'a> {
        self._on_behalf_of_content_owner = Some(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 dyn client::Delegate) -> WatermarkUnsetCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> WatermarkUnsetCall<'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::Full`.
    ///
    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
    /// tokens for more than one scope.
    /// If `None` is specified, then all scopes will be removed and no default scope will be used either.
    /// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
    /// function for details).
    ///
    /// 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, S>(mut self, scope: T) -> WatermarkUnsetCall<'a>
                                                        where T: Into<Option<S>>,
                                                              S: AsRef<str> {
        match scope.into() {
          Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
          None => None,
        };
        self
    }
}


/// Updates an existing resource.
///
/// A builder for the *v3.updateCommentThreads* method supported by a *youtube* resource.
/// It is not used directly, but through a `YoutubeMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_youtube3 as youtube3;
/// use youtube3::api::CommentThread;
/// # async fn dox() {
/// # use std::default::Default;
/// # use youtube3::{YouTube, oauth2, hyper, hyper_rustls};
/// 
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// #         secret,
/// #         oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// #     ).build().await.unwrap();
/// # let mut hub = YouTube::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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 = CommentThread::default();
/// 
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.youtube().v3_update_comment_threads(req)
///              .add_part("ipsum")
///              .doit().await;
/// # }
/// ```
pub struct YoutubeV3UpdateCommentThreadCall<'a>
    where  {

    hub: &'a YouTube<>,
    _request: CommentThread,
    _part: Vec<String>,
    _delegate: Option<&'a mut dyn client::Delegate>,
    _additional_params: HashMap<String, String>,
}

impl<'a> client::CallBuilder for YoutubeV3UpdateCommentThreadCall<'a> {}

impl<'a> YoutubeV3UpdateCommentThreadCall<'a> {


    /// Perform the operation you have build so far.
    pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, CommentThread)> {
        use std::io::{Read, Seek};
        use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
        use client::ToParts;
        let mut dd = client::DefaultDelegate;
        let mut dlg: &mut dyn client::Delegate = match self._delegate {
            Some(d) => d,
            None => &mut dd
        };
        dlg.begin(client::MethodInfo { id: "youtube.youtube.v3.updateCommentThreads",
                               http_method: hyper::Method::PUT });
        let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
        if self._part.is_empty() {
            self._part.push(self._request.to_parts());
        }
        if self._part.len() > 0 {
            for f in self._part.iter() {
                params.push(("part", f.to_string()));
            }
        }
        for &field in ["alt", "part"].iter() {
            if self._additional_params.contains_key(field) {
                dlg.finished(false);
                return Err(client::Error::FieldClash(field));
            }
        }
        for (name, value) in self._additional_params.iter() {
            params.push((&name, value.clone()));
        }

        params.push(("alt", "json".to_string()));

        let mut url = self.hub._base_url.clone() + "youtube/v3/commentThreads";
        
        let key = dlg.api_key();
        match key {
            Some(value) => params.push(("key", value)),
            None => {
                dlg.finished(false);
                return Err(client::Error::MissingAPIKey)
            }
        }


        let url = url::Url::parse_with_params(&url, params).unwrap();

        let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
        let mut request_value_reader =
            {
                let mut value = json::value::to_value(&self._request).expect("serde to work");
                client::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();


        loop {
            request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
            let mut req_result = {
                let client = &self.hub.client;
                dlg.pre_request();
                let mut req_builder = hyper::Request::builder().method(hyper::Method::PUT).uri(url.clone().into_string())
                        .header(USER_AGENT, self.hub._user_agent.clone());


                        let request = req_builder
                        .header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
                        .header(CONTENT_LENGTH, request_size as u64)
                        .body(hyper::body::Body::from(request_value_reader.get_ref().clone()));

                client.request(request.unwrap()).await
                
            };

            match req_result {
                Err(err) => {
                    if let client::Retry::After(d) = dlg.http_error(&err) {
                        sleep(d);
                        continue;
                    }
                    dlg.finished(false);
                    return Err(client::Error::HttpError(err))
                }
                Ok(mut res) => {
                    if !res.status().is_success() {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;
                        let (parts, _) = res.into_parts();
                        let body = hyper::Body::from(res_body_string.clone());
                        let restored_response = hyper::Response::from_parts(parts, body);

                        let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();

                        if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
                            sleep(d);
                            continue;
                        }

                        dlg.finished(false);

                        return match server_response {
                            Some(error_value) => Err(client::Error::BadRequest(error_value)),
                            None => Err(client::Error::Failure(restored_response)),
                        }
                    }
                    let result_value = {
                        let res_body_string = client::get_body_as_string(res.body_mut()).await;

                        match json::from_str(&res_body_string) {
                            Ok(decoded) => (res, decoded),
                            Err(err) => {
                                dlg.response_json_decode_error(&res_body_string, &err);
                                return Err(client::Error::JsonDecodeError(res_body_string, err));
                            }
                        }
                    };

                    dlg.finished(true);
                    return Ok(result_value)
                }
            }
        }
    }


    ///
    /// 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: CommentThread) -> YoutubeV3UpdateCommentThreadCall<'a> {
        self._request = new_value;
        self
    }
    /// The *part* parameter specifies a comma-separated list of commentThread resource properties that the API response will include. You must at least include the snippet part in the parameter value since that part contains all of the properties that the API request can update.
    ///
    /// Append the given value to the *part* query property.
    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
    ///
    /// Even though the *parts* list is automatically derived from *Resource* passed in
    /// during instantiation and indicates which values you are passing, the response would contain the very same parts.
    /// This may not always be desirable, as you can obtain (newly generated) parts you cannot pass in,
    /// like statistics that are generated server side. Therefore you should use this method to specify
    /// the parts you provide in addition to the ones you want in the response.
    pub fn add_part(mut self, new_value: &str) -> YoutubeV3UpdateCommentThreadCall<'a> {
        self._part.push(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 dyn client::Delegate) -> YoutubeV3UpdateCommentThreadCall<'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 parameters
    /// which have their own setter method. If done anyway, the request will fail.
    ///
    /// # Additional Parameters
    ///
    /// * *$.xgafv* (query-string) - V1 error format.
    /// * *access_token* (query-string) - OAuth access token.
    /// * *alt* (query-string) - Data format for response.
    /// * *callback* (query-string) - JSONP
    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
    /// * *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.
    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
    /// * *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.
    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
    pub fn param<T>(mut self, name: T, value: T) -> YoutubeV3UpdateCommentThreadCall<'a>
                                                        where T: AsRef<str> {
        self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
        self
    }

}


