R/ee_clean.R

Defines functions ee_clean_credentials_from_folder ee_clean_user_credentials ee_clean_container ee_clean_message ee_clean_pyenv

Documented in ee_clean_container ee_clean_pyenv ee_clean_user_credentials

#' Remove rgee system variables from .Renviron
#'
#' @param Renviron Character. If it is "global" the environment variables in
#' the .Renviron located in the Sys.getenv("HOME") folder will be deleted. On the
#' other hand, if it is "local" the environment variables in the .Renviron on the
#' working directory (getwd()) will be deleted. Finally, users can also set a
#' specific path (see examples).
#'
#' @family ee_clean functions
#' @return No return value, called for cleaning environmental variables in
#' their system.
#' @export
ee_clean_pyenv <- function(Renviron = "global") {

  # Get the .Renviron on their system
  if (tolower(Renviron) == "global") {
    home <- Sys.getenv("HOME")
  } else if(tolower(Renviron) == "local") {
    home <- getwd()
  } else {
    if (dir.exists(Renviron)) {
      home <- Renviron
    } else {
      stop(sprintf("The directory %s does not exist!", Renviron))
    }
  }

  # Read line by line .Renviron
  renv <- file.path(home, ".Renviron")
  if (file.exists(renv)) {
    # Backup original .Renviron before doing anything else here.
    file.copy(renv, file.path(home, ".Renviron_backup"), overwrite = TRUE)

    con <- file(renv, open = "r")
    lines <- as.character()
    ii <- 1

    while (TRUE) {
      line <- readLines(con, n = 1, warn = FALSE)
      if (length(line) == 0) {
        break()
      }
      lines[ii] <- line
      ii <- ii + 1
    }
    on.exit(close(con), add = TRUE)

    # Remove system variables EARTHENGINE_PYTHON
    system_vars <- lines[!grepl("EARTHENGINE_PYTHON|EARTHENGINE_ENV", lines)]
    fileConn <- file(renv)
    writeLines(system_vars, fileConn)
    on.exit(close(fileConn), add = TRUE)
  }
  invisible(TRUE)
}


#' Remove EARTHENGINE_PYTHON_INIT_MESSAGE
#' @noRd
ee_clean_message <- function() {
  # Read line by line .Renviron
  home <- Sys.getenv("HOME")
  renv <- file.path(home, ".Renviron")
  if (file.exists(renv)) {
    # Backup original .Renviron before doing anything else here.
    file.copy(renv, file.path(home, ".Renviron_backup"), overwrite = TRUE)

    con <- file(renv, open = "r")
    lines <- as.character()
    ii <- 1

    while (TRUE) {
      line <- readLines(con, n = 1, warn = FALSE)
      if (length(line) == 0) {
        break()
      }
      lines[ii] <- line
      ii <- ii + 1
    }
    on.exit(close(con), add = TRUE)

    # Remove system variables EARTHENGINE_PYTHON
    system_vars <- lines[!grepl("EARTHENGINE_INIT_MESSAGE", lines)]
    fileConn <- file(renv)
    writeLines(system_vars, fileConn)
    on.exit(close(fileConn), add = TRUE)
  }
  invisible(TRUE)
}

#' Delete files from either a Folder (Google Drive) or a Bucket (GCS)
#'
#' Delete all files from a folder (Google Drive) or a bucket
#' (Google Cloud Storage). Caution: this action will permanently delete any backup
#' files that were generated using \code{ee_as_stars} and \code{ee_as_sf}.
#'
#' @param name Character. Name of the folder (Google Drive) or bucket (GCS)
#' to delete all files.
#' @param type Character. Name of the file storage web service. 'drive'
#' and 'gcs' are supported.
#' @param quiet logical. Suppress info message
#'
#' @return No return value, called for cleaning Google Drive or Google
#' Cloud Storage container.
#'
#' @family ee_clean functions
#'
#' @export
ee_clean_container <- function(name = "rgee_backup",
                               type = "drive",
                               quiet = FALSE) {

  ee_user <- ee_exist_credentials()

  if (type == "drive") {
    ee_check_packages("ee_download_drive", "googledrive")
    if (is.na(ee_user[["drive_cre"]])) {
      stop(
        "Google Drive credentials were not loaded.",
        ' Run ee_Initialize(user = "myemail", drive = TRUE)',
        " to fix it"
      )
    }

    # Check if the folder exist!
    find_folder <- googledrive::drive_find(q = sprintf("name contains '%s'", name), type = "folder")
    if (nrow(find_folder) == 0) {
      if (!quiet) {
        message("The folder that you attempt delete does not exist")
      }
      return(FALSE)
    }

    # Search if the folder exist
    if (!quiet) {
      message(sprintf("Searching files in %s.", bold(name)))
    }

    # Delete folder
    if (!quiet) {
      googledrive::with_drive_quiet(
        googledrive::drive_rm(find_folder)
      )
    } else {
      googledrive::drive_rm(find_folder)
    }

  } else if (type == "gcs") {
    # check if googleCloudStorageR is installed
    ee_check_packages("ee_download_gcs", "googleCloudStorageR")

    if (is.na(ee_user[["gcs_cre"]])) {
      stop(
        "Google Drive credentials were not loaded.",
        ' Run ee_Initialize(user = "myemail", gcs = TRUE)',
        " to fix it"
      )
    }
    if (isFALSE(quiet)) {
      googleCloudStorageR::gcs_global_bucket(name)
      buckets <- googleCloudStorageR::gcs_list_objects(bucket = name)
      gcs_todelete <- buckets[["name"]]
      mapply(googleCloudStorageR::gcs_delete_object, gcs_todelete)
    } else {
      suppressMessages(
        googleCloudStorageR::gcs_global_bucket(name)
      )
      suppressMessages(
        buckets <- googleCloudStorageR::gcs_list_objects()
      )
      gcs_todelete <- buckets[["name"]]
      suppressMessages(
        mapply(googleCloudStorageR::gcs_delete_object, gcs_todelete)
      )
    }
  } else {
    stop("type argument invalid.")
  }
  invisible(TRUE)
}

#' Clean credentials for a specific user
#'
#' @param user Character (optional, e.g. `data.colec.fbf`). The user
#' to remove credentials (See \code{~/.config/earthengine/}). A 'user' represents
#' a set of credentials that certificate a specific Google identity.
#' @param earthengine Logical. Earthengine credential.
#' @param drive Logical. Google Drive credential.
#' @param gcs Logical. Google Cloud Storage credential.
#'
#' @family ee_clean functions
#' @return No return value, called for cleaning the path \code{~/.config/earthengine/}
#' @examples
#' \dontrun{
#' library(rgee)
#'
#' # Delete caducated credentials for a specific user
#' ee_clean_user_credentials(earthengine=TRUE, drive=TRUE)
#' ee_users()
#' }
#' @export
ee_clean_user_credentials <- function(
    user = NULL,
    earthengine = TRUE,
    drive = TRUE,
    gcs = FALSE
) {

  # Detect user folder
  init <- ee_check_init()
  ee_utils <- init$ee_utils
  ee_path <- ee_utils_py_to_r(ee_utils$ee_path())

  # remove credentials from the main folder
  ee_clean_credentials_from_folder(
    ee_path = ee_path,
    earthengine = earthengine,
    drive = drive,
    gcs = gcs
  )

  if (!is.null(user)) {
    ee_path_user <- sprintf("%s/%s", ee_path, user)
    ee_clean_credentials_from_folder(
      ee_path = ee_path_user,
      earthengine = earthengine,
      drive = drive,
      gcs = gcs
    )
  }
  invisible(TRUE)
}

#' Remove credentials files from a specific folder
#' @noRd
ee_clean_credentials_from_folder <- function(ee_path, earthengine, drive, gcs) {
  usermainfiles <- setdiff(
    list.files(ee_path) ,
    list.dirs(ee_path, recursive = FALSE, full.names = FALSE)
  ) # Find user files
  usermainfiles_fullname <- sprintf("%s/%s", ee_path, usermainfiles)

  # Remove EE credential if exists
  if (earthengine) {
    eecre <- usermainfiles_fullname[grepl("credentials$", usermainfiles)]
    file.remove(eecre)
  }

  # Remove GD credential if exists
  if (drive) {
    # maybe not the optimal way to detect if a file is a GD credential
    gdcre <- usermainfiles_fullname[
      grepl(".*_.*@.*", basename(usermainfiles))
    ]
    file.remove(gdcre)
  }

  # Remove GCS credential if it exists
  if (gcs) {
    gcscre <- usermainfiles_fullname[
      grepl("\\.json$", basename(usermainfiles))
    ]
    file.remove(gcscre)
  }

  # Delete the .txt file if it exists
  txtlocfile <- grepl("\\.txt$", basename(usermainfiles))
  if (any(txtlocfile)) {
    txtfile <- usermainfiles_fullname[txtlocfile]
    file.remove(txtfile)
  }
}
r-spatial/rgee documentation built on July 4, 2024, 9:33 a.m.