R/AgaveCache.r

# Agave Platform Science API
#
# Power your digital lab and reduce the time from theory to discovery using the Agave Science-as-a-Service API Platform. Agave provides hosted services that allow researchers to manage data, conduct experiments, and publish and share results from anywhere at any time.
#
# Agave Platform version: 2.2.14
#
# Generated by: https://github.com/swagger-api/swagger-codegen.git


#' AgaveCache Class
#'
#' Handles access to the authentication cache including reading,
#' writing from default system locations.
#'
#' NOTE: This class is NOT generated by the swagger code generator program.
#'
#' @title Agave Cache utility class
#' @description rAgave.AgaveCache
#'
#' @section Methods:
#' \describe{
#'
#' load
#'
#' write
#'
#' getClient
#'
#' setClient
#'
#' getToken
#'
#' setToken
#'
#' getTenant
#'
#' setTenant
#'
#' getProperty
#'
#' }
#'
#' @export
AgaveCache  <- R6::R6Class(
  'AuthCache',
  private = list(
    config = NULL,
    cacheDir = NULL,
    cacheFilePath = NULL
  ),
  active = list(
    current = function() {
      jsonlite::fromJSON(jsonlite::toJSON(private$config, auto_unbox=TRUE, null="null", na="null", pretty=TRUE))
    },
    toJSON = function() {
      jsonlite::toJSON(private$config, auto_unbox=TRUE, null="null", na="null", pretty=TRUE)
    }
  ),
  public = list(
    initialize = function(cacheDir){
      if (!missing(cacheDir)) {
        if ( is.null(cacheDir) || nchar(cacheDir) == 0) {
          logger.warn("Invalid cacheDir value passed into AgaveCache constructor. Environment will be searched next")
        }
        else {
          #logger.debug(paste0(c("Cache file path ",cacheDir," was passe into the AgaveCache constructor"), collapse = " "))
          private$cacheDir <- cacheDir
        }
      }
      else {
        logger.debug("No cacheDir value passed into AgaveCache constructor. Environment will be searched next")
      }

      if (is.null(private$cacheDir) || nchar(private$cacheDir) == 0 ) {
        cacheDir <- Sys.getenv("AGAVE_CACHE_DIR")
        if (is.null(cacheDir) || nchar(cacheDir) == 0) {
          logger.debug("No value found for AGAVE_CACHE_DIR in the environment. The default cache location location will be used")
        }
        else {
          logger.debug("AGAVE_CACHE_DIR was found in the enviornment. ")
          private$cacheDir <- cacheDir
        }
      }

      if ( is.null(private$cacheDir) || nchar(private$cacheDir) == 0 ) {
        private$cacheDir = paste0(c(Sys.getenv("HOME"),".agave"), collapse = .Platform$file.sep)
        logger.debug(paste0(c("The default cache location, ",private$cacheDir, ", will be used."), collapse = ""))
      }

      private$cacheFilePath <- paste0(c(private$cacheDir,"current"),collapse = .Platform$file.sep)

      logger.debug(paste0(c("Auth cache file path is:",private$cacheFilePath), collapse = " "))

      self$load(private$cacheFilePath)
    },

    load = function(cacheFilePath) {
      # verify the argument was passed in or use the default
      # location set on init
      if (missing(cacheFilePath) || is.null(cacheFilePath)) {
        cacheFilePath = private$cacheFilePath
      }

      logger.debug(paste0(c("Loading auth cache file from",private$cacheFilePath), collapse = " "))

      # check that the file is not a directory
      if (file.exists(cacheFilePath) && is.character(list.files(cacheFilePath)) && file.size(cacheFilePath) > 0) {
        private$config <- jsonlite::read_json(private$cacheFilePath, simplifyVector = FALSE)
        logger.debug(paste0(c("Succesfully loaded auth cache file from",private$cacheFilePath), collapse = " "))
        # logger.debug(str(private$config))
      }
      # otherwise, set the config to NULL
      else {
        logger.debug(paste0(c("No auth config file found at",private$cacheFilePath), collapse = " "))
        private$config <- NULL
      }
    },

    write = function(cacheFilePath) {
      # if the argument was passed in, use that
      if (missing(cacheFilePath) || is.null(cacheFilePath)) {
        cacheFilePath <- private$cacheFilePath
      }

      # if the file exists, load it as JSON
      if (!dir.exists(dirname(cacheFilePath))) {
        dir.create(path = dirname(cacheFilePath), recursive=TRUE, mode="770")
      }

      logger.debug(paste0(c("Writing auth cache config to",private$cacheFilePath), collapse = " "))

      sjson <- sprintf('{"tenantid": %s,"baseurl": %s,"devurl": %s,"apisecret": %s,"apikey": %s,"username": %s,"access_token": %s,"refresh_token": %s,"created_at": %s,"expires_in": %s,"expires_at": %s,"client_name": %s}',
                       ifelse(is.null(private$config$tenantid), "null", paste(c('"',private$config$tenantid,'"'),collapse = '')),
                       ifelse(is.null(private$config$baseurl), "null", paste(c('"',private$config$baseurl,'"'),collapse = '')),
                       ifelse(is.null(private$config$devurl), "null", paste(c('"',private$config$devurl,'"'),collapse = '')),
                       ifelse(is.null(private$config$apisecret), "null", paste(c('"',private$config$apisecret,'"'),collapse = '')),
                       ifelse(is.null(private$config$apikey), "null", paste(c('"',private$config$apikey,'"'),collapse = '')),
                       ifelse(is.null(private$config$username), "null", paste(c('"',private$config$username,'"'),collapse = '')),
                       ifelse(is.null(private$config$access_token), "null", paste(c('"',private$config$access_token,'"'),collapse = '')),
                       ifelse(is.null(private$config$refresh_token), "null", paste(c('"',private$config$refresh_token,'"'),collapse = '')),
                       ifelse(is.null(private$config$created_at), "null", paste(c('"',private$config$created_at,'"'),collapse = '')),
                       ifelse(is.null(private$config$expires_in), "null", paste(c('"',private$config$expires_in,'"'),collapse = '')),
                       ifelse(is.null(private$config$expires_at), "null", paste(c('"',private$config$expires_at,'"'),collapse = '')),
                       ifelse(is.null(private$config$client_name), "null", paste(c('"',private$config$client_name,'"'),collapse = ''))
      )

      logger.debug(sjson)

      fileConn<-file(cacheFilePath)
      writeLines(sjson, fileConn)
      close(fileConn)
      logger.debug(paste0(c("Succesfully wrote auth cache config to",private$cacheFilePath), collapse = " "))
    },

    getClient = function() {

      client <- Client$new()

      if (! is.null(private$config)) {
        client$key = private$config$`apikey`
        client$secret = private$config$`apisecret`
        client$clientName = private$config$`client_name`
      }

      client
    },

    setClient = function(client) {

      # if the client is not provided, this is essentially just a write() operation
      if (! (missing(client) || is.null(client))) {
        logger.debug("Saving client to cache...")

        # logger.trace("Value of cache before saving client")
        # logger.trace(str(private$config))

        # set the client config we perisist to disk
        clientObject <- NULL
        if (R6::is.R6(client)) {
          clientObject <- client
        }
        else if (is.list(client)) {
          clientObject$fromJSON(client)
        }
        else {
          stop("Unable to update the auth cache. Invalid client type.")
        }

        private$config$apikey <- clientObject$key #ifelse(is.null(client$consumerKey), client$key, client$consumerKey)
        private$config$apisecret <- clientObject$secret #ifelse(is.null(client$consumerSecret), client$secret, client$consumerSecret)
        private$config$client_name <- clientObject$clientName #ifelse(is.null(client$clientName), client$name, client$clientName)
      }
      else {
        logger.debug("Skipping client update. Supplied client is empty...")
      }

      # logger.debug("Value of cache after setting client")
      # logger.trace(str(private$config))
      self$write()
      # logger.debug("Value of cache after saving client")
      # logger.debug(str(private$config))
    },

    getToken = function() {

      token <- Token$new()

      if (! is.null(private$config)) {
        token$access_token = private$config$access_token
        token$refresh_token = private$config$refresh_token
        token$created_at = private$config$created_at
        token$expires_in = private$config$expires_in
        token$expires_at = private$config$expires_at
        token$username = private$config$username
      }

      token
    },

    setToken = function(token) {
      # if the token is not provided, this is essentially just a write() operation
      if (!missing(token) && !is.null(token)) {
        logger.debug("Saving token to cache...")

        # logger.trace("Value of cache before saving token")
        # logger.trace(str(private$config))

        # set the token config we perisist to disk
        private$config$access_token = token$`access_token`
        private$config$refresh_token = token$`refresh_token`
        private$config$created_at = token$`created_at`
        private$config$expires_in = token$`expires_in`
        private$config$expires_at = token$`expires_at`
        private$config$username = token$username
      }
      else {
        logger.debug("Skipping token update. Cache is empty...")
      }

      # logger.debug("Value of cache after setting token")
      # logger.trace(str(private$config))
      self$write()
      # logger.debug("Value of cache after saving token")
      # logger.debug(str(private$config))
    },

    getTenant = function() {

      tenant <- Tenant$new()

      if (! is.null(private$config)) {
        tenant$baseUrl = private$config$baseurl
        tenant$code = private$config$tenantid
      }

      tenant
    },

    setTenant = function(tenant) {
      # if the tenant is not provided, this is essentially just a write() operation
      if (! (missing(tenant) || is.null(tenant))) {
        logger.debug("Saving tenant to cache...")

        # logger.trace("Value of cache before saving tenant...")
        # logger.trace(str(private$config))

        # set the token config we perisist to disk
        private$config$tenantid = tenant$code
        private$config$baseurl = tenant$baseUrl
      }
      else {
        logger.debug("Skipping tenant update. Cache is empty...")
      }

      # logger.debug("Value of cache after setting tenant...")
      # logger.trace(str(private$config))
      self$write()
      # logger.debug("Value of cache after saving tenant...")
      # logger.debug(str(private$config))
    },

    getProperty = function(propertyName) {
      getElement(private$config, propertyName)
    }
  )
)
agaveplatform/r-sdk documentation built on May 13, 2019, 8:20 a.m.