Regenerate BigQueryDataTransfer client (#349)

# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.

defmodule GoogleApi.BigQueryDataTransfer.V1.Api.Projects do
  @moduledoc """
  API calls for all endpoints tagged `Projects`.
  """

  alias GoogleApi.BigQueryDataTransfer.V1.Connection
  alias GoogleApi.Gax.{Request, Response}

  @doc """
  Returns true if valid credentials exist for the given data source and requesting user. Some data sources doesn't support service account, so we need to talk to them on behalf of the end user. This API just checks whether we have OAuth token for the particular user, which is a pre-requisite before user can create a transfer config.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - name (String.t): The data source in the form: `projects/{project_id}/dataSources/{data_source_id}`
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :body (CheckValidCredsRequest):

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.CheckValidCredsResponse{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_data_sources_check_valid_creds(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.CheckValidCredsResponse.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_data_sources_check_valid_creds(
        connection,
        name,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :body => :body
    }

    request =
      Request.new()
      |> Request.method(:post)
      |> Request.url("/v1/{+name}:checkValidCreds", %{
        "name" => URI.encode_www_form(name)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.CheckValidCredsResponse{}]
    )
  end

  @doc """
  Lists supported data sources and returns their settings, which can be used for UI rendering.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - parent (String.t): The BigQuery project id for which data sources should be returned. Must be in the form: `projects/{project_id}`
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :pageSize (integer()): Page size. The default page size is the maximum value of 1000 results.
    - :pageToken (String.t): Pagination token, which can be used to request a specific page of `ListDataSourcesRequest` list results. For multiple-page results, `ListDataSourcesResponse` outputs a `next_page` token, which can be used as the `page_token` value to request the next page of list results.

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListDataSourcesResponse{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_data_sources_list(Tesla.Env.client(), String.t(), keyword()) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListDataSourcesResponse.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_data_sources_list(
        connection,
        parent,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :pageSize => :query,
      :pageToken => :query
    }

    request =
      Request.new()
      |> Request.method(:get)
      |> Request.url("/v1/{+parent}/dataSources", %{
        "parent" => URI.encode_www_form(parent)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListDataSourcesResponse{}]
    )
  end

  @doc """
  Lists information about the supported locations for this service.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - name (String.t): The resource that owns the locations collection, if applicable.
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :filter (String.t): The standard list filter.
    - :pageSize (integer()): The standard list page size.
    - :pageToken (String.t): The standard list page token.

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListLocationsResponse{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_locations_list(Tesla.Env.client(), String.t(), keyword()) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListLocationsResponse.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_locations_list(
        connection,
        name,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :filter => :query,
      :pageSize => :query,
      :pageToken => :query
    }

    request =
      Request.new()
      |> Request.method(:get)
      |> Request.url("/v1/{+name}/locations", %{
        "name" => URI.encode_www_form(name)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListLocationsResponse{}]
    )
  end

  @doc """
  Creates a new data transfer configuration.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - parent (String.t): The BigQuery project id where the transfer configuration should be created. Must be in the format projects/{project_id}/locations/{location_id} If specified location and location of the destination bigquery dataset do not match - the request will fail.
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :authorizationCode (String.t): Optional OAuth2 authorization code to use with this transfer configuration. This is required if new credentials are needed, as indicated by `CheckValidCreds`. In order to obtain authorization_code, please make a request to https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client_id=<datatransferapiclientid>&scope=<data_source_scopes>&redirect_uri=<redirect_uri>  * client_id should be OAuth client_id of BigQuery DTS API for the given   data source returned by ListDataSources method. * data_source_scopes are the scopes returned by ListDataSources method. * redirect_uri is an optional parameter. If not specified, then   authorization code is posted to the opener of authorization flow window.   Otherwise it will be sent to the redirect uri. A special value of   urn:ietf:wg:oauth:2.0:oob means that authorization code should be   returned in the title bar of the browser, with the page text prompting   the user to copy the code and paste it in the application.
    - :body (TransferConfig):

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_transfer_configs_create(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_transfer_configs_create(
        connection,
        parent,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :authorizationCode => :query,
      :body => :body
    }

    request =
      Request.new()
      |> Request.method(:post)
      |> Request.url("/v1/{+parent}/transferConfigs", %{
        "parent" => URI.encode_www_form(parent)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}]
    )
  end

  @doc """
  Returns information about all data transfers in the project.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - parent (String.t): The BigQuery project id for which data sources should be returned: `projects/{project_id}`.
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :dataSourceIds ([String.t]): When specified, only configurations of requested data sources are returned.
    - :pageSize (integer()): Page size. The default page size is the maximum value of 1000 results.
    - :pageToken (String.t): Pagination token, which can be used to request a specific page of `ListTransfersRequest` list results. For multiple-page results, `ListTransfersResponse` outputs a `next_page` token, which can be used as the `page_token` value to request the next page of list results.

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferConfigsResponse{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_transfer_configs_list(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferConfigsResponse.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_transfer_configs_list(
        connection,
        parent,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :dataSourceIds => :query,
      :pageSize => :query,
      :pageToken => :query
    }

    request =
      Request.new()
      |> Request.method(:get)
      |> Request.url("/v1/{+parent}/transferConfigs", %{
        "parent" => URI.encode_www_form(parent)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferConfigsResponse{}]
    )
  end

  @doc """
  Updates a data transfer configuration. All fields must be set, even if they are not updated.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - name (String.t): The resource name of the transfer config. Transfer config names have the form of `projects/{project_id}/location/{region}/transferConfigs/{config_id}`. The name is automatically generated based on the config_id specified in CreateTransferConfigRequest along with project_id and region. If config_id is not provided, usually a uuid, even though it is not guaranteed or required, will be generated for config_id.
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :authorizationCode (String.t): Optional OAuth2 authorization code to use with this transfer configuration. If it is provided, the transfer configuration will be associated with the authorizing user. In order to obtain authorization_code, please make a request to https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client_id=<datatransferapiclientid>&scope=<data_source_scopes>&redirect_uri=<redirect_uri>  * client_id should be OAuth client_id of BigQuery DTS API for the given   data source returned by ListDataSources method. * data_source_scopes are the scopes returned by ListDataSources method. * redirect_uri is an optional parameter. If not specified, then   authorization code is posted to the opener of authorization flow window.   Otherwise it will be sent to the redirect uri. A special value of   urn:ietf:wg:oauth:2.0:oob means that authorization code should be   returned in the title bar of the browser, with the page text prompting   the user to copy the code and paste it in the application.
    - :updateMask (String.t): Required list of fields to be updated in this request.
    - :body (TransferConfig):

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_transfer_configs_patch(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_transfer_configs_patch(
        connection,
        name,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :authorizationCode => :query,
      :updateMask => :query,
      :body => :body
    }

    request =
      Request.new()
      |> Request.method(:patch)
      |> Request.url("/v1/{+name}", %{
        "name" => URI.encode_www_form(name)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}]
    )
  end

  @doc """
  Deletes the specified transfer run.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - name (String.t): The field will contain name of the resource requested, for example: `projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.Empty{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_transfer_configs_runs_delete(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) :: {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_transfer_configs_runs_delete(
        connection,
        name,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query
    }

    request =
      Request.new()
      |> Request.method(:delete)
      |> Request.url("/v1/{+name}", %{
        "name" => URI.encode_www_form(name)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.Empty{}])
  end

  @doc """
  Returns information about the particular transfer run.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - name (String.t): The field will contain name of the resource requested, for example: `projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.TransferRun{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_transfer_configs_runs_get(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.TransferRun.t()} | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_transfer_configs_runs_get(
        connection,
        name,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query
    }

    request =
      Request.new()
      |> Request.method(:get)
      |> Request.url("/v1/{+name}", %{
        "name" => URI.encode_www_form(name)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.TransferRun{}])
  end

  @doc """
  Returns information about running and completed jobs.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - parent (String.t): Name of transfer configuration for which transfer runs should be retrieved. Format of transfer configuration resource name is: `projects/{project_id}/transferConfigs/{config_id}`.
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :pageSize (integer()): Page size. The default page size is the maximum value of 1000 results.
    - :pageToken (String.t): Pagination token, which can be used to request a specific page of `ListTransferRunsRequest` list results. For multiple-page results, `ListTransferRunsResponse` outputs a `next_page` token, which can be used as the `page_token` value to request the next page of list results.
    - :runAttempt (String.t): Indicates how run attempts are to be pulled.
    - :states ([String.t]): When specified, only transfer runs with requested states are returned.

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferRunsResponse{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_transfer_configs_runs_list(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferRunsResponse.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_transfer_configs_runs_list(
        connection,
        parent,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :pageSize => :query,
      :pageToken => :query,
      :runAttempt => :query,
      :states => :query
    }

    request =
      Request.new()
      |> Request.method(:get)
      |> Request.url("/v1/{+parent}/runs", %{
        "parent" => URI.encode_www_form(parent)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferRunsResponse{}]
    )
  end

  @doc """
  Returns user facing log messages for the data transfer run.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - parent (String.t): Transfer run name in the form: `projects/{project_id}/transferConfigs/{config_Id}/runs/{run_id}`.
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :messageTypes ([String.t]): Message types to return. If not populated - INFO, WARNING and ERROR messages are returned.
    - :pageSize (integer()): Page size. The default page size is the maximum value of 1000 results.
    - :pageToken (String.t): Pagination token, which can be used to request a specific page of `ListTransferLogsRequest` list results. For multiple-page results, `ListTransferLogsResponse` outputs a `next_page` token, which can be used as the `page_token` value to request the next page of list results.

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferLogsResponse{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_transfer_configs_runs_transfer_logs_list(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferLogsResponse.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_transfer_configs_runs_transfer_logs_list(
        connection,
        parent,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :messageTypes => :query,
      :pageSize => :query,
      :pageToken => :query
    }

    request =
      Request.new()
      |> Request.method(:get)
      |> Request.url("/v1/{+parent}/transferLogs", %{
        "parent" => URI.encode_www_form(parent)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferLogsResponse{}]
    )
  end

  @doc """
  Creates transfer runs for a time range [start_time, end_time]. For each date - or whatever granularity the data source supports - in the range, one transfer run is created. Note that runs are created per UTC time in the time range.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - parent (String.t): Transfer configuration name in the form: `projects/{project_id}/transferConfigs/{config_id}`.
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :body (ScheduleTransferRunsRequest):

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ScheduleTransferRunsResponse{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_transfer_configs_schedule_runs(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ScheduleTransferRunsResponse.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_transfer_configs_schedule_runs(
        connection,
        parent,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :body => :body
    }

    request =
      Request.new()
      |> Request.method(:post)
      |> Request.url("/v1/{+parent}:scheduleRuns", %{
        "parent" => URI.encode_www_form(parent)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ScheduleTransferRunsResponse{}]
    )
  end
end

# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.

defmodule GoogleApi.BigQueryDataTransfer.V1.Api.Projects do
  @moduledoc """
  API calls for all endpoints tagged `Projects`.
  """

  alias GoogleApi.BigQueryDataTransfer.V1.Connection
  alias GoogleApi.Gax.{Request, Response}

  @doc """
  Returns true if valid credentials exist for the given data source and requesting user. Some data sources doesn't support service account, so we need to talk to them on behalf of the end user. This API just checks whether we have OAuth token for the particular user, which is a pre-requisite before user can create a transfer config.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - name (String.t): The data source in the form: `projects/{project_id}/dataSources/{data_source_id}`
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :body (CheckValidCredsRequest):

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.CheckValidCredsResponse{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_data_sources_check_valid_creds(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.CheckValidCredsResponse.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_data_sources_check_valid_creds(
        connection,
        name,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :body => :body
    }

    request =
      Request.new()
      |> Request.method(:post)
      |> Request.url("/v1/{+name}:checkValidCreds", %{
        "name" => URI.encode_www_form(name)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.CheckValidCredsResponse{}]
    )
  end

  @doc """
  Lists supported data sources and returns their settings, which can be used for UI rendering.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - parent (String.t): The BigQuery project id for which data sources should be returned. Must be in the form: `projects/{project_id}`
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :pageSize (integer()): Page size. The default page size is the maximum value of 1000 results.
    - :pageToken (String.t): Pagination token, which can be used to request a specific page of `ListDataSourcesRequest` list results. For multiple-page results, `ListDataSourcesResponse` outputs a `next_page` token, which can be used as the `page_token` value to request the next page of list results.

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListDataSourcesResponse{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_data_sources_list(Tesla.Env.client(), String.t(), keyword()) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListDataSourcesResponse.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_data_sources_list(
        connection,
        parent,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :pageSize => :query,
      :pageToken => :query
    }

    request =
      Request.new()
      |> Request.method(:get)
      |> Request.url("/v1/{+parent}/dataSources", %{
        "parent" => URI.encode_www_form(parent)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListDataSourcesResponse{}]
    )
  end

  @doc """
  Lists information about the supported locations for this service.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - name (String.t): The resource that owns the locations collection, if applicable.
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :filter (String.t): The standard list filter.
    - :pageToken (String.t): The standard list page token.
    - :pageSize (integer()): The standard list page size.

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListLocationsResponse{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_locations_list(Tesla.Env.client(), String.t(), keyword()) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListLocationsResponse.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_locations_list(
        connection,
        name,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :filter => :query,
      :pageToken => :query,
      :pageSize => :query
    }

    request =
      Request.new()
      |> Request.method(:get)
      |> Request.url("/v1/{+name}/locations", %{
        "name" => URI.encode_www_form(name)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListLocationsResponse{}]
    )
  end

  @doc """
  Creates a new data transfer configuration.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - parent (String.t): The BigQuery project id where the transfer configuration should be created. Must be in the format projects/{project_id}/locations/{location_id} If specified location and location of the destination bigquery dataset do not match - the request will fail.
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :authorizationCode (String.t): Optional OAuth2 authorization code to use with this transfer configuration. This is required if new credentials are needed, as indicated by `CheckValidCreds`. In order to obtain authorization_code, please make a request to https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client_id=<datatransferapiclientid>&scope=<data_source_scopes>&redirect_uri=<redirect_uri>  * client_id should be OAuth client_id of BigQuery DTS API for the given   data source returned by ListDataSources method. * data_source_scopes are the scopes returned by ListDataSources method. * redirect_uri is an optional parameter. If not specified, then   authorization code is posted to the opener of authorization flow window.   Otherwise it will be sent to the redirect uri. A special value of   urn:ietf:wg:oauth:2.0:oob means that authorization code should be   returned in the title bar of the browser, with the page text prompting   the user to copy the code and paste it in the application.
    - :body (TransferConfig):

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_transfer_configs_create(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_transfer_configs_create(
        connection,
        parent,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :authorizationCode => :query,
      :body => :body
    }

    request =
      Request.new()
      |> Request.method(:post)
      |> Request.url("/v1/{+parent}/transferConfigs", %{
        "parent" => URI.encode_www_form(parent)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}]
    )
  end

  @doc """
  Returns information about all data transfers in the project.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - parent (String.t): The BigQuery project id for which data sources should be returned: `projects/{project_id}`.
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :pageToken (String.t): Pagination token, which can be used to request a specific page of `ListTransfersRequest` list results. For multiple-page results, `ListTransfersResponse` outputs a `next_page` token, which can be used as the `page_token` value to request the next page of list results.
    - :pageSize (integer()): Page size. The default page size is the maximum value of 1000 results.
    - :dataSourceIds ([String.t]): When specified, only configurations of requested data sources are returned.

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferConfigsResponse{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_transfer_configs_list(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferConfigsResponse.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_transfer_configs_list(
        connection,
        parent,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :pageToken => :query,
      :pageSize => :query,
      :dataSourceIds => :query
    }

    request =
      Request.new()
      |> Request.method(:get)
      |> Request.url("/v1/{+parent}/transferConfigs", %{
        "parent" => URI.encode_www_form(parent)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferConfigsResponse{}]
    )
  end

  @doc """
  Updates a data transfer configuration. All fields must be set, even if they are not updated.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - name (String.t): The resource name of the transfer config. Transfer config names have the form of `projects/{project_id}/location/{region}/transferConfigs/{config_id}`. The name is automatically generated based on the config_id specified in CreateTransferConfigRequest along with project_id and region. If config_id is not provided, usually a uuid, even though it is not guaranteed or required, will be generated for config_id.
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :updateMask (String.t): Required list of fields to be updated in this request.
    - :authorizationCode (String.t): Optional OAuth2 authorization code to use with this transfer configuration. If it is provided, the transfer configuration will be associated with the authorizing user. In order to obtain authorization_code, please make a request to https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client_id=<datatransferapiclientid>&scope=<data_source_scopes>&redirect_uri=<redirect_uri>  * client_id should be OAuth client_id of BigQuery DTS API for the given   data source returned by ListDataSources method. * data_source_scopes are the scopes returned by ListDataSources method. * redirect_uri is an optional parameter. If not specified, then   authorization code is posted to the opener of authorization flow window.   Otherwise it will be sent to the redirect uri. A special value of   urn:ietf:wg:oauth:2.0:oob means that authorization code should be   returned in the title bar of the browser, with the page text prompting   the user to copy the code and paste it in the application.
    - :body (TransferConfig):

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_transfer_configs_patch(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_transfer_configs_patch(
        connection,
        name,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :updateMask => :query,
      :authorizationCode => :query,
      :body => :body
    }

    request =
      Request.new()
      |> Request.method(:patch)
      |> Request.url("/v1/{+name}", %{
        "name" => URI.encode_www_form(name)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}]
    )
  end

  @doc """
  Deletes the specified transfer run.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - name (String.t): The field will contain name of the resource requested, for example: `projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.Empty{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_transfer_configs_runs_delete(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) :: {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_transfer_configs_runs_delete(
        connection,
        name,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query
    }

    request =
      Request.new()
      |> Request.method(:delete)
      |> Request.url("/v1/{+name}", %{
        "name" => URI.encode_www_form(name)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.Empty{}])
  end

  @doc """
  Returns information about the particular transfer run.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - name (String.t): The field will contain name of the resource requested, for example: `projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.TransferRun{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_transfer_configs_runs_get(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.TransferRun.t()} | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_transfer_configs_runs_get(
        connection,
        name,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query
    }

    request =
      Request.new()
      |> Request.method(:get)
      |> Request.url("/v1/{+name}", %{
        "name" => URI.encode_www_form(name)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.TransferRun{}])
  end

  @doc """
  Returns information about running and completed jobs.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - parent (String.t): Name of transfer configuration for which transfer runs should be retrieved. Format of transfer configuration resource name is: `projects/{project_id}/transferConfigs/{config_id}`.
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :pageToken (String.t): Pagination token, which can be used to request a specific page of `ListTransferRunsRequest` list results. For multiple-page results, `ListTransferRunsResponse` outputs a `next_page` token, which can be used as the `page_token` value to request the next page of list results.
    - :states ([String.t]): When specified, only transfer runs with requested states are returned.
    - :pageSize (integer()): Page size. The default page size is the maximum value of 1000 results.
    - :runAttempt (String.t): Indicates how run attempts are to be pulled.

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferRunsResponse{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_transfer_configs_runs_list(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferRunsResponse.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_transfer_configs_runs_list(
        connection,
        parent,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :pageToken => :query,
      :states => :query,
      :pageSize => :query,
      :runAttempt => :query
    }

    request =
      Request.new()
      |> Request.method(:get)
      |> Request.url("/v1/{+parent}/runs", %{
        "parent" => URI.encode_www_form(parent)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferRunsResponse{}]
    )
  end

  @doc """
  Returns user facing log messages for the data transfer run.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - parent (String.t): Transfer run name in the form: `projects/{project_id}/transferConfigs/{config_Id}/runs/{run_id}`.
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :pageSize (integer()): Page size. The default page size is the maximum value of 1000 results.
    - :messageTypes ([String.t]): Message types to return. If not populated - INFO, WARNING and ERROR messages are returned.
    - :pageToken (String.t): Pagination token, which can be used to request a specific page of `ListTransferLogsRequest` list results. For multiple-page results, `ListTransferLogsResponse` outputs a `next_page` token, which can be used as the `page_token` value to request the next page of list results.

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferLogsResponse{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_transfer_configs_runs_transfer_logs_list(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferLogsResponse.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_transfer_configs_runs_transfer_logs_list(
        connection,
        parent,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :pageSize => :query,
      :messageTypes => :query,
      :pageToken => :query
    }

    request =
      Request.new()
      |> Request.method(:get)
      |> Request.url("/v1/{+parent}/transferLogs", %{
        "parent" => URI.encode_www_form(parent)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferLogsResponse{}]
    )
  end

  @doc """
  Creates transfer runs for a time range [start_time, end_time]. For each date - or whatever granularity the data source supports - in the range, one transfer run is created. Note that runs are created per UTC time in the time range.

  ## Parameters

  - connection (GoogleApi.BigQueryDataTransfer.V1.Connection): Connection to server
  - parent (String.t): Transfer configuration name in the form: `projects/{project_id}/transferConfigs/{config_id}`.
  - optional_params (KeywordList): [optional] Optional parameters
    - :$.xgafv (String.t): V1 error format.
    - :access_token (String.t): OAuth access token.
    - :alt (String.t): Data format for response.
    - :callback (String.t): JSONP
    - :fields (String.t): Selector specifying which fields to include in a partial response.
    - :key (String.t): 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 (String.t): OAuth 2.0 token for the current user.
    - :prettyPrint (boolean()): Returns response with indentations and line breaks.
    - :quotaUser (String.t): 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.
    - :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
    - :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
    - :body (ScheduleTransferRunsRequest):

  ## Returns

  {:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ScheduleTransferRunsResponse{}} on success
  {:error, info} on failure
  """
  @spec bigquerydatatransfer_projects_transfer_configs_schedule_runs(
          Tesla.Env.client(),
          String.t(),
          keyword()
        ) ::
          {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ScheduleTransferRunsResponse.t()}
          | {:error, Tesla.Env.t()}
  def bigquerydatatransfer_projects_transfer_configs_schedule_runs(
        connection,
        parent,
        optional_params \\ [],
        opts \\ []
      ) do
    optional_params_config = %{
      :"$.xgafv" => :query,
      :access_token => :query,
      :alt => :query,
      :callback => :query,
      :fields => :query,
      :key => :query,
      :oauth_token => :query,
      :prettyPrint => :query,
      :quotaUser => :query,
      :upload_protocol => :query,
      :uploadType => :query,
      :body => :body
    }

    request =
      Request.new()
      |> Request.method(:post)
      |> Request.url("/v1/{+parent}:scheduleRuns", %{
        "parent" => URI.encode_www_form(parent)
      })
      |> Request.add_optional_params(optional_params_config, optional_params)

    connection
    |> Connection.execute(request)
    |> Response.decode(
      opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ScheduleTransferRunsResponse{}]
    )
  end
end


Fix addict.generate.configs falsly detecting :addcit_demo as existing config

defmodule Mix.Tasks.Addict.Generate.Configs do
  use Mix.Task

  def run(_) do
    configs_path = "./config/config.exs"

    if addict_config_already_exists?(configs_path) do
      Mix.shell.error "[x] Please remove the existing Addict configuration before generating a new one"
    else
      base_module = guess_application_name
      user_schema = "#{base_module}.User"
      repo        = "#{base_module}.Repo"
      mailgun_domain = ""
      mailgun_api_key = ""

      Mix.shell.info "[o] Generating Addict configuration"

      guessed = Mix.shell.yes? "Is your application root module #{base_module}?"
      unless guessed do
        base_module = Mix.shell.prompt("Please insert your application root module:") |> String.rstrip
      end

      guessed = Mix.shell.yes? "Is your Ecto Repository module #{repo}?"
      unless guessed do
        repo = Mix.shell.prompt("Please insert your Ecto Repository module:") |> String.rstrip
      end

      guessed = Mix.shell.yes? "Is your User Schema module #{user_schema}?"
      unless guessed do
        user_schema = Mix.shell.prompt("Please insert your User Schema module:") |> String.rstrip
      end

      use_mailgun = Mix.shell.yes? "Will you be using Mailgun?"
      if use_mailgun do
        mailgun_domain  = Mix.shell.prompt("Please insert your Mailgun domain: (e.g.: https://api.mailgun.net/v3/sandbox123456.mailgun.org)") |> String.rstrip
        mailgun_api_key = Mix.shell.prompt("Please insert your Mailgun API key:") |> String.rstrip
      end

      add_addict_configs(configs_path, user_schema, repo, use_mailgun, mailgun_domain, mailgun_api_key)
    end

    Mix.shell.info "[o] Done!"
  end

  defp guess_application_name do
    Mix.Project.config()[:app] |> Atom.to_string |> Mix.Utils.camelize
  end

  defp addict_config_already_exists?(configs_path) do
    {data} = with  {:ok, file} <- File.open(configs_path, [:read, :write, :utf8]),
          data <- IO.read(file, :all),
          :ok <- File.close(file),
      do: {data}

    Regex.match?  ~r/config :addict\s*?,/, data
  end

  defp add_addict_configs(configs_path, user_schema, repo, use_mailgun, mailgun_domain, mailgun_api_key) do
    {:ok, file} = File.open(configs_path, [:read, :write, :utf8])
    IO.read(file, :all)
    secret_key = Comeonin.Bcrypt.gen_salt |> Base.encode16 |> String.downcase

    default_configs = """

    config :addict,
      secret_key: "#{secret_key}",
      extra_validation: fn ({valid, errors}, user_params) -> {valid, errors} end, # define extra validation here
      user_schema: #{user_schema},
      repo: #{repo},
      from_email: "no-reply@example.com", # CHANGE THIS
    """

    if use_mailgun do
      default_configs = default_configs <> """
        mailgun_domain: "#{mailgun_domain}",
        mailgun_key: "#{mailgun_api_key}",
        mail_service: :mailgun
      """
    else
      default_configs = default_configs <> "mail_service: nil"
    end

    IO.write(file, default_configs)
    :ok = File.close(file)
  end
end

defmodule Mix.Tasks.Addict.Generate.Configs do
  use Mix.Task

  def run(_) do
    configs_path = "./config/config.exs"

    if addict_config_already_exists?(configs_path) do
      Mix.shell.error "[x] Please remove the existing Addict configuration before generating a new one"
    else
      base_module = guess_application_name
      user_schema = "#{base_module}.User"
      repo        = "#{base_module}.Repo"
      mailgun_domain = ""
      mailgun_api_key = ""

      Mix.shell.info "[o] Generating Addict configuration"

      guessed = Mix.shell.yes? "Is your application root module #{base_module}?"
      unless guessed do
        base_module = Mix.shell.prompt("Please insert your application root module:") |> String.rstrip
      end

      guessed = Mix.shell.yes? "Is your Ecto Repository module #{repo}?"
      unless guessed do
        repo = Mix.shell.prompt("Please insert your Ecto Repository module:") |> String.rstrip
      end

      guessed = Mix.shell.yes? "Is your User Schema module #{user_schema}?"
      unless guessed do
        user_schema = Mix.shell.prompt("Please insert your User Schema module:") |> String.rstrip
      end

      use_mailgun = Mix.shell.yes? "Will you be using Mailgun?"
      if use_mailgun do
        mailgun_domain  = Mix.shell.prompt("Please insert your Mailgun domain: (e.g.: https://api.mailgun.net/v3/sandbox123456.mailgun.org)") |> String.rstrip
        mailgun_api_key = Mix.shell.prompt("Please insert your Mailgun API key:") |> String.rstrip
      end

      add_addict_configs(configs_path, user_schema, repo, use_mailgun, mailgun_domain, mailgun_api_key)
    end

    Mix.shell.info "[o] Done!"
  end

  defp guess_application_name do
    Mix.Project.config()[:app] |> Atom.to_string |> Mix.Utils.camelize
  end

  defp addict_config_already_exists?(configs_path) do
    {data} = with  {:ok, file} <- File.open(configs_path, [:read, :write, :utf8]),
          data <- IO.read(file, :all),
          :ok <- File.close(file),
      do: {data}

    String.contains?(data, "config :addict")
  end

  defp add_addict_configs(configs_path, user_schema, repo, use_mailgun, mailgun_domain, mailgun_api_key) do
    {:ok, file} = File.open(configs_path, [:read, :write, :utf8])
    IO.read(file, :all)
    secret_key = Comeonin.Bcrypt.gen_salt |> Base.encode16 |> String.downcase

    default_configs = """

    config :addict,
      secret_key: "#{secret_key}",
      extra_validation: fn ({valid, errors}, user_params) -> {valid, errors} end, # define extra validation here
      user_schema: #{user_schema},
      repo: #{repo},
      from_email: "no-reply@example.com", # CHANGE THIS
    """

    if use_mailgun do
      default_configs = default_configs <> """
        mailgun_domain: "#{mailgun_domain}",
        mailgun_key: "#{mailgun_api_key}",
        mail_service: :mailgun
      """
    else
      default_configs = default_configs <> "mail_service: nil"
    end

    IO.write(file, default_configs)
    :ok = File.close(file)
  end
end


ebert

ebert

defmodule Mix.Tasks.Sesamex.Gen.Views do
  use Mix.Task

  import Sesamex
  import Sesamex.Helpers

  require EEx

  EEx.function_from_file :defp, :view_template,
    "priv/templates/sesamex.gen/view.eex", [:base, :scoped, :view]

  @spec run(List.t) :: none()
  def run([]) do
    IO.puts "Please provide model name"
  end

  @spec run(List.t) :: none()
  def run([singular]) do
    bindings = Mix.Phoenix.inflect(singular)

    create_directory_unless_exist("web/views/#{bindings[:path]}")

    Enum.each(modules, fn(file) ->
      view = view_template(bindings[:base], bindings[:scoped], String.capitalize("#{file}"))
      path = "web/views/#{bindings[:path]}/#{file}_view.ex"
      create_file_from(view, path)
    end)
  end
end

defmodule Mix.Tasks.Sesamex.Gen.Views do
  use Mix.Task

  import Sesamex
  import Sesamex.Helpers

  require EEx

  EEx.function_from_file :defp, :view_template,
    "priv/templates/sesamex.gen/view.eex", [:base, :scoped, :view]

  @spec run(List.t) :: none()
  def run([]) do
    IO.puts "Please provide model name"
  end

  @spec run(List.t) :: none()
  def run([singular]) do
    bindings = Mix.Phoenix.inflect(singular)

    create_directory_unless_exist("web/views/#{bindings[:path]}")

    Enum.each(modules, fn(file) ->
      view = view_template(bindings[:base], bindings[:scoped], String.capitalize("#{file}"))
      path ="web/views/#{bindings[:path]}/#{file}_view.ex"
      create_file_from(view, path)
    end)
  end
end


Make firmware open task persiste after initial open

This will allow for reopening in the case of a firmware being
reflashed at runtime

defmodule FarmbotCore.FirmwareOpenTask do
  @moduledoc """
  Will open the UART interface after it's been successfully flashed .
  Must configure in application env: `attempt_threshold`. It can be an integer
  or `:infinity` in which case it will try opening it indefinately.
  """

  use GenServer
  require FarmbotCore.Logger
  alias FarmbotFirmware.UARTTransport
  alias FarmbotCore.{Asset, Config}
  @attempt_threshold Application.get_env(:farmbot_core, __MODULE__)[:attempt_threshold]
  @attempt_threshold || Mix.raise """
  Firmware open attempt threshold not configured:

  config :farmbot_core, FarmbotCore.FirmwareOpenTask, [
    attempt_threshold: 10
  ]
  """

  @doc false
  def start_link(args, opts \\ [name: __MODULE__]) do
    GenServer.start_link(__MODULE__, args, opts)
  end

  @doc false
  def swap_transport(tty) do
    Application.put_env(:farmbot_firmware, FarmbotFirmware, transport: UARTTransport, device: tty)
    # Swap transport on FW module.
    # Close tranpsort if it is open currently.
    _ = FarmbotFirmware.close_transport()
    FarmbotFirmware.open_transport(UARTTransport, device: tty)
  end

  @impl GenServer
  def init(_args) do
    send(self(), :open)
    {:ok, %{timer: nil, attempts: 0, threshold: @attempt_threshold}}
  end

  @impl GenServer
  def handle_info(:open, %{attempts: at, threshold: attempt_threshold} = state) when at >= attempt_threshold do
    if state.timer, do: Process.cancel_timer(state.timer)
    FarmbotCore.Logger.debug 3, "Firmware didn't open after #{@attempt_threshold} tries. Not trying to open anymore"
    {:noreply, %{state | timer: nil}}
  end

  def handle_info(:open, state) do
    if state.timer, do: Process.cancel_timer(state.timer)

    needs_flash? = Config.get_config_value(:bool, "settings", "firmware_needs_flash")
    needs_open? = Config.get_config_value(:bool, "settings", "firmware_needs_open")
    firmware_path = Asset.fbos_config(:firmware_path)
    cond do
      needs_flash? ->
        FarmbotCore.Logger.debug 3, "Firmware needs flash still. Not opening"
        timer = Process.send_after(self(), :open, 5000)
        {:noreply, increment_attempts(%{state | timer: timer})}

      is_nil(firmware_path) ->
        FarmbotCore.Logger.debug 3, "Firmware path not detected. Not opening"
        timer = Process.send_after(self(), :open, 5000)
        {:noreply, increment_attempts(%{state | timer: timer})}

      needs_open? ->
        FarmbotCore.Logger.debug 3, "Firmware needs to be opened"
        case swap_transport(firmware_path) do
          :ok ->
            Config.update_config_value(:bool, "settings", "firmware_needs_open", false)
            timer = Process.send_after(self(), :open, 5000)
            {:noreply, %{state | timer: timer, attempts: 0}}
          _ ->
            FarmbotCore.Logger.debug 3, "Firmware failed to open"
            timer = Process.send_after(self(), :open, 5000)
            {:noreply, %{state | timer: timer, attempts: 0}}
        end
      needs_open? == false ->
        # Firmware should probably already be opened here.
        # Can just ignore
        timer = Process.send_after(self(), :open, 5000)
        {:noreply, %{state | timer: timer}}
      true ->
        FarmbotCore.Logger.debug 3, """
        Unknown firmware open state:
        firmware needs flash?: #{needs_flash?}
        firwmare needs open?: #{needs_open?}
        firmware path: #{firmware_path}
        """
        timer = Process.send_after(self(), :open, 5000)
        {:noreply, %{state | timer: timer, attempts: 0}}
    end
  end

  defp increment_attempts(%{attempts: at, attempt_threshold: :infinity} = state) do
    %{state | attempts: at + 1}
  end

  defp increment_attempts(%{attempts: at} = state) do
    %{state | attempts: at + 1}
  end
end

defmodule FarmbotCore.FirmwareOpenTask do
  @moduledoc """
  Will open the UART interface after it's been successfully flashed .
  Must configure in application env: `attempt_threshold`. It can be an integer
  or `:infinity` in which case it will try opening it indefinately.
  """

  use GenServer
  require FarmbotCore.Logger
  alias FarmbotFirmware.UARTTransport
  alias FarmbotCore.{Asset, Config}
  @attempt_threshold Application.get_env(:farmbot_core, __MODULE__)[:attempt_threshold]
  @attempt_threshold || Mix.raise """
  Firmware open attempt threshold not configured:

  config :farmbot_core, FarmbotCore.FirmwareOpenTask, [
    attempt_threshold: 10
  ]
  """

  @doc false
  def start_link(args, opts \\ [name: __MODULE__]) do
    GenServer.start_link(__MODULE__, args, opts)
  end

  @doc false
  def swap_transport(tty) do
    Application.put_env(:farmbot_firmware, FarmbotFirmware, transport: UARTTransport, device: tty)
    # Swap transport on FW module.
    # Close tranpsort if it is open currently.
    _ = FarmbotFirmware.close_transport()
    FarmbotFirmware.open_transport(UARTTransport, device: tty)
  end

  @impl GenServer
  def init(_args) do
    send(self(), :open)
    {:ok, %{timer: nil, attempts: 0, threshold: @attempt_threshold}}
  end

  @impl GenServer
  def handle_info(:open, %{attempts: at, threshold: attempt_threshold} = state) when at >= attempt_threshold do
    if state.timer, do: Process.cancel_timer(state.timer)
    FarmbotCore.Logger.debug 3, "Firmware didn't open after #{@attempt_threshold} tries. Not trying to open anymore"
    {:noreply, %{state | timer: nil}}
  end

  def handle_info(:open, state) do
    if state.timer, do: Process.cancel_timer(state.timer)

    needs_flash? = Config.get_config_value(:bool, "settings", "firmware_needs_flash")
    needs_open? = Config.get_config_value(:bool, "settings", "firmware_needs_open")
    firmware_path = Asset.fbos_config(:firmware_path)
    cond do
      needs_flash? ->
        FarmbotCore.Logger.debug 3, "Firmware needs flash still. Not opening"
        timer = Process.send_after(self(), :open, 5000)
        {:noreply, increment_attempts(%{state | timer: timer})}

      is_nil(firmware_path) ->
        FarmbotCore.Logger.debug 3, "Firmware path not detected. Not opening"
        timer = Process.send_after(self(), :open, 5000)
        {:noreply, increment_attempts(%{state | timer: timer})}

      needs_open? ->
        FarmbotCore.Logger.debug 3, "Firmware needs to be opened"
        case swap_transport(firmware_path) do
          :ok ->
            {:noreply, %{state | timer: nil, attempts: 0}, :hibernate}
          _ ->
            FarmbotCore.Logger.debug 3, "Firmware failed to open"
            timer = Process.send_after(self(), :open, 5000)
            {:noreply, %{state | timer: timer, attempts: 0}}
        end
      true ->
        FarmbotCore.Logger.debug 3, """
        Unknown firmware open state:
        firmware needs flash?: #{needs_flash?}
        firwmare needs open?: #{needs_open?}
        firmware path: #{firmware_path}
        """
        timer = Process.send_after(self(), :open, 5000)
        {:noreply, %{state | timer: timer, attempts: 0}}
    end
  end

  defp increment_attempts(%{attempts: at, attempt_threshold: :infinity} = state) do
    %{state | attempts: at + 1}
  end

  defp increment_attempts(%{attempts: at} = state) do
    %{state | attempts: at + 1}
  end
end


Improve param filtering

Improve param filtering

defmodule ElixirJobsWeb.OfferController do
  use ElixirJobsWeb, :controller

  alias ElixirJobs.{
    Offers,
    Offers.Offer
  }

  @filters_available ["text", "job_type", "job_place"]

  plug :scrub_params, "offer" when action in [:create, :preview]

  def index(conn, params) do
    page_number =
      with {:ok, page_no} <- Map.fetch(params, "page"),
           true <- is_binary(page_no),
           {value, _} <- Integer.parse(page_no) do
        value
      else
        _ -> 1
      end

    page = Offers.list_published_offers(page_number)

    render(conn, "index.html",
      offers: page.entries,
      page_number: page.page_number,
      total_pages: page.total_pages)
  end

  def search(conn, params) do
    page_number =
      with {:ok, page_no} <- Map.fetch(params, "page"),
           true <- is_binary(page_no),
           {value, _} <- Integer.parse(page_no) do
        value
      else
        _ -> 1
      end

    filters =
      params
      |> Map.get("filter", %{})
      |> Enum.reduce(%{}, fn({k, v}, acc) ->
        case {k, v} do
          {key, _} when key not in @filters_available -> acc
          {_, val} when val in ["", nil] -> acc
          {key, str} when is_binary(str) -> Map.put(acc, key, String.trim(str))
          {key, val} -> Map.put(acc, key, val)
        end
      end)

    page = Offers.filter_published_offers(filters, page_number)

    render(conn, "search.html",
      offers: page.entries,
      page_number: page.page_number,
      total_pages: page.total_pages)
  end

  def new(conn, _params) do
    changeset = Offers.change_offer(%Offer{})

    render(conn, "new.html", changeset: changeset)
  end

  def create(conn, %{"offer" => offer_params}) do
    case Offers.create_offer(offer_params) do
      {:ok, _offer} ->
        conn
        |> put_flash(:info, gettext("<b>Job offer created correctly!</b> We will review and publish it soon"))
        |> redirect(to: offer_path(conn, :index))
      {:error, changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end

  def preview(conn, %{"offer" => offer_params}) do
    job_place =
      offer_params
      |> Map.get("job_place")
      |> Kernel.||("unknown")
      |> String.to_existing_atom

    job_type =
      offer_params
      |> Map.get("job_type")
      |> Kernel.||("unknown")
      |> String.to_existing_atom

    offer_preview = %Offer{
      title: Map.get(offer_params, "title") || gettext("Title of your offer"),
      company: Map.get(offer_params, "company") || gettext("Company"),
      description: Map.get(offer_params, "description") || gettext("Description of your offer"),
      location: Map.get(offer_params, "location") || gettext("Location"),
      url: Map.get(offer_params, "url") || "https://example.com",
      slug: "",
      job_place: job_place,
      job_type: job_type,
      published_at: Ecto.DateTime.utc()
    }

    conn
    |> put_layout(false)
    |> render("preview.html", offer: offer_preview)
  end

  def show(conn, %{"slug" => slug}) do
    offer = if user_logged_in?(conn) do
      Offers.get_offer_by_slug!(slug)
    else
      Offers.get_published_offer_by_slug!(slug)
    end

    render(conn, "show.html", offer: offer)
  end

  def rss(conn, _params) do
    offers = Offers.list_offers(1)
    render(conn, "rss.xml", offers: offers.entries)
  end
end

defmodule ElixirJobsWeb.OfferController do
  use ElixirJobsWeb, :controller

  alias ElixirJobs.{
    Offers,
    Offers.Offer
  }

  plug :scrub_params, "offer" when action in [:create, :preview]

  def index(conn, params) do
    page_number =
      with {:ok, page_no} <- Map.fetch(params, "page"),
           true <- is_binary(page_no),
           {value, _} <- Integer.parse(page_no) do
        value
      else
        _ -> 1
      end

    page = Offers.list_published_offers(page_number)

    render(conn, "index.html",
      offers: page.entries,
      page_number: page.page_number,
      total_pages: page.total_pages)
  end

  def search(conn, params) do
    page_number =
      with {:ok, page_no} <- Map.fetch(params, "page"),
           true <- is_binary(page_no),
           {value, _} <- Integer.parse(page_no) do
        value
      else
        _ -> 1
      end

    filters =
      params
      |> Map.get("filters", %{})
      |> Enum.map(fn({k, v}) ->
        val = case v do
          "" -> nil
          str when is_binary(str) -> String.trim(str)
          val -> val
        end

        {k, val}
      end)
      |> Enum.reject(&(is_nil(&1) or (is_binary(&1) and length(&1) == 0)))

    page = Offers.list_published_offers(page_number, filters)

    render(conn, "search.html",
      offers: page.entries,
      page_number: page.page_number,
      total_pages: page.total_pages)
  end

  def new(conn, _params) do
    changeset = Offers.change_offer(%Offer{})

    render(conn, "new.html", changeset: changeset)
  end

  def create(conn, %{"offer" => offer_params}) do
    case Offers.create_offer(offer_params) do
      {:ok, _offer} ->
        conn
        |> put_flash(:info, gettext("<b>Job offer created correctly!</b> We will review and publish it soon"))
        |> redirect(to: offer_path(conn, :index))
      {:error, changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end

  def preview(conn, %{"offer" => offer_params}) do
    job_place =
      offer_params
      |> Map.get("job_place")
      |> Kernel.||("unknown")
      |> String.to_existing_atom

    job_type =
      offer_params
      |> Map.get("job_type")
      |> Kernel.||("unknown")
      |> String.to_existing_atom

    offer_preview = %Offer{
      title: Map.get(offer_params, "title") || gettext("Title of your offer"),
      company: Map.get(offer_params, "company") || gettext("Company"),
      description: Map.get(offer_params, "description") || gettext("Description of your offer"),
      location: Map.get(offer_params, "location") || gettext("Location"),
      url: Map.get(offer_params, "url") || "https://example.com",
      slug: "",
      job_place: job_place,
      job_type: job_type,
      published_at: Ecto.DateTime.utc()
    }

    conn
    |> put_layout(false)
    |> render("preview.html", offer: offer_preview)
  end

  def show(conn, %{"slug" => slug}) do
    offer = if user_logged_in?(conn) do
      Offers.get_offer_by_slug!(slug)
    else
      Offers.get_published_offer_by_slug!(slug)
    end

    render(conn, "show.html", offer: offer)
  end

  def rss(conn, _params) do
    offers = Offers.list_offers(1)
    render(conn, "rss.xml", offers: offers.entries)
  end
end


Also show unpublished offers if user logged in

defmodule ElixirJobsWeb.OfferController do
  use ElixirJobsWeb, :controller

  alias ElixirJobs.{
    Offers,
    Offers.Offer
  }

  plug :scrub_params, "offer" when action in [:create, :preview]

  def index(conn, params) do
    page_number =
      with {:ok, page_no} <- Map.fetch(params, "page_number"),
           true <- is_binary(page_no),
           {value, _} <- Integer.parse(page_no) do
        value
      else
        _ -> 1
      end

    page = Offers.list_published_offers(page_number)

    render(conn, "index.html",
      offers: page.entries,
      page_number: page.page_number,
      total_pages: page.total_pages)
  end

  def new(conn, _params) do
    changeset = Offers.change_offer(%Offer{})

    render(conn, "new.html", changeset: changeset)
  end

  def create(conn, %{"offer" => offer_params}) do
    case Offers.create_offer(offer_params) do
      {:ok, _offer} ->
        conn
        |> put_flash(:info, gettext("<b>Job offer created correctly!</b> We will review and publish it soon"))
        |> redirect(to: offer_path(conn, :index))
      {:error, changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end

  def preview(conn, %{"offer" => offer_params}) do
    job_place =
      offer_params
      |> Map.get("job_place")
      |> Kernel.||("unknown")
      |> String.to_existing_atom

    job_type =
      offer_params
      |> Map.get("job_type")
      |> Kernel.||("unknown")
      |> String.to_existing_atom

    offer_preview = %Offer{
      title: Map.get(offer_params, "title") || gettext("Title of your offer"),
      company: Map.get(offer_params, "company") || gettext("Company"),
      description: Map.get(offer_params, "description") || gettext("Description of your offer"),
      location: Map.get(offer_params, "location") || gettext("Location"),
      url: Map.get(offer_params, "url") || "https://example.com",
      slug: "",
      job_place: job_place,
      job_type: job_type,
      published_at: Ecto.DateTime.utc()
    }

    conn
    |> put_layout(false)
    |> render("preview.html", offer: offer_preview)
  end

  def show(conn, %{"slug" => slug}) do
    offer = if user_logged_in?(conn) do
      Offers.get_offer_by_slug!(slug)
    else
      Offers.get_published_offer_by_slug!(slug)
    end

    render(conn, "show.html", offer: offer)
  end

  def rss(conn, _params) do
    offers = Offers.list_offers(1)
    render(conn, "rss.xml", offers: offers.entries)
  end
end

defmodule ElixirJobsWeb.OfferController do
  use ElixirJobsWeb, :controller

  alias ElixirJobs.{
    Offers,
    Offers.Offer
  }

  plug :scrub_params, "offer" when action in [:create, :preview]

  def index(conn, params) do
    page_number =
      with {:ok, page_no} <- Map.fetch(params, "page_number"),
           true <- is_binary(page_no),
           {value, _} <- Integer.parse(page_no) do
        value
      else
        _ -> 1
      end

    page = Offers.list_published_offers(page_number)

    render(conn, "index.html",
      offers: page.entries,
      page_number: page.page_number,
      total_pages: page.total_pages)
  end

  def new(conn, _params) do
    changeset = Offers.change_offer(%Offer{})

    render(conn, "new.html", changeset: changeset)
  end

  def create(conn, %{"offer" => offer_params}) do
    case Offers.create_offer(offer_params) do
      {:ok, _offer} ->
        conn
        |> put_flash(:info, gettext("<b>Job offer created correctly!</b> We will review and publish it soon"))
        |> redirect(to: offer_path(conn, :index))
      {:error, changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end

  def preview(conn, %{"offer" => offer_params}) do
    job_place =
      offer_params
      |> Map.get("job_place")
      |> Kernel.||("unknown")
      |> String.to_existing_atom

    job_type =
      offer_params
      |> Map.get("job_type")
      |> Kernel.||("unknown")
      |> String.to_existing_atom

    offer_preview = %Offer{
      title: Map.get(offer_params, "title") || gettext("Title of your offer"),
      company: Map.get(offer_params, "company") || gettext("Company"),
      description: Map.get(offer_params, "description") || gettext("Description of your offer"),
      location: Map.get(offer_params, "location") || gettext("Location"),
      url: Map.get(offer_params, "url") || "https://example.com",
      slug: "",
      job_place: job_place,
      job_type: job_type,
      published_at: Ecto.DateTime.utc()
    }

    conn
    |> put_layout(false)
    |> render("preview.html", offer: offer_preview)
  end

  def show(conn, %{"slug" => slug}) do
    offer = Offers.get_offer_by_slug!(slug)
    render(conn, "show.html", offer: offer)
  end

  def rss(conn, _params) do
    offers = Offers.list_offers(1)
    render(conn, "rss.xml", offers: offers.entries)
  end
end