R/utils.R

Defines functions .fetch_county_file .load_rdata_file .get_source .osf_default_source `%||%`

# eiballots/R/utils.R
# Internal utilities — not exported

#' @importFrom stats complete.cases
NULL

# ----------------------------------------------------------------------------
# Null-coalescing operator
# ----------------------------------------------------------------------------

`%||%` <- function(x, y) if (!is.null(x)) x else y


# ----------------------------------------------------------------------------
# Data source resolution
# Priority: explicit argument > options(data_dir) > OSF default
# ----------------------------------------------------------------------------

#.zenodo_base_url <- function() {
#  "https://osf.io/np73b/"
#}

#.get_source <- function(source = NULL) {
#  source %||% getOption("data_dir") %||% .zenodo_base_url()
#}

.osf_default_source <- function() {
  "OSF_DEFAULT"
}

.get_source <- function(source = NULL) {
  if (is.null(source) && is.null(getOption("data_dir"))) {
    message(
      "\n[Performance Note]: You are loading data directly from OSF.\n",
      "To speed up execution, avoid download wait times, and remove dependency\n",
      "on OSF server availability, it is highly recommended to:\n",
      "  1. Download the .RData files from https://osf.io/np73b/overview to a local folder.\n",
      "  2. Set your local path by running: options(data_dir = '/path/to/files/')\n"
    )
  }

  source %||% getOption("data_dir") %||% .osf_default_source()
}

# ----------------------------------------------------------------------------
# RData loading (local or remote)
# ----------------------------------------------------------------------------

# Load the first object stored in an RData file into the caller's environment.
.load_rdata_file <- function(filepath) {
  env  <- new.env(parent = emptyenv())
  nms  <- load(filepath, envir = env)
  if (length(nms) == 0L)
    stop("The RData file contains no objects.", call. = FALSE)
  if (length(nms) > 1L)
    warning(
      sprintf(
        "The RData file contains %d objects; using the first one ('%s').",
        length(nms), nms[1L]
      ),
      call. = FALSE
    )
  get(nms[1L], envir = env)
}

# Fetch a county RData file from a local path or a remote URL.
#.fetch_county_file <- function(county, source) {
#  filename <- paste0(county, ".RData")
#
#  if (grepl("^https?://", source)) {
#    url <- paste0(source, filename)
#    tmp <- tempfile(fileext = ".RData")
#    on.exit(unlink(tmp), add = TRUE)
#    tryCatch(
#      utils::download.file(url, tmp, quiet = TRUE, mode = "wb"),
#      error = function(e)
#        stop(
#          sprintf(
#            "Could not download data file for county '%s'.\n  URL: %s\n  Error: %s",
#            county, url, conditionMessage(e)
#          ),
#          call. = FALSE
#        )
#    )
#    .load_rdata_file(tmp)
#  } else {
#    filepath <- file.path(source, filename)
#    if (!file.exists(filepath))
#      stop(
#        sprintf(
#          "File not found: %s\n  Check options(data_dir) or the 'source' argument.",
#          filepath
#        ),
#        call. = FALSE
#      )
#    .load_rdata_file(filepath)
#  }
#}

.fetch_county_file <- function(county, source) {
  filename <- paste0(county, ".RData")

  # INTERCEPCIÓN OSF: Si el origen es el por defecto, construimos su URL de OSF
  if (identical(source, "OSF_DEFAULT")) {
    diccionario_osf <- c(
      "Broward"      = "ptd9y",
      "Highlands"    = "suthg",
      "Hillsborough" = "wdy3m",
      "Lee"          = "vx2gb",
      "Marion"       = "3gf9r",
      "Miami_Dade"   = "ce9hj",
      "Palm_Beach"   = "bsqm7",
      "Pasco"        = "j8kfv",
      "Pinellas"     = "pey7x",
      "Sarasota"     = "pkzc4"
    )

    guid <- diccionario_osf[county]
    if (is.na(guid) || length(guid) == 0) {
      stop(sprintf("County '%s' not found in OSF catalog.", county), call. = FALSE)
    }

    # CONCATENACIÓN CON PASTE0 (Limpia y sin errores)
    url <- paste0("https://osf.io/", guid, "/download")
    tmp <- tempfile(fileext = ".RData")
    on.exit(unlink(tmp), add = TRUE)

    tryCatch(
      utils::download.file(url, tmp, quiet = TRUE, mode = "wb"),
      error = function(e)
        stop(
          sprintf(
            "Could not download data file for county '%s' from OSF.\n  URL: %s\n  Error: %s",
            county, url, conditionMessage(e)
          ),
          call. = FALSE
        )
    )
    return(.load_rdata_file(tmp))
  }

  # 2. CASOS MANUALES (URL externa genérica o Ruta Local del usuario)
  filename <- paste0(county, ".RData")
  if (grepl("^https?://", source)) {
    url <- paste0(source, filename)
    tmp <- tempfile(fileext = ".RData")
    on.exit(unlink(tmp), add = TRUE)
    tryCatch(
      utils::download.file(url, tmp, quiet = TRUE, mode = "wb"),
      error = function(e)
        stop(
          sprintf(
            "Could not download data file for county '%s'.\n  URL: %s\n  Error: %s",
            county, url, conditionMessage(e)
          ),
          call. = FALSE
        )
    )
    .load_rdata_file(tmp)
  } else {
    filepath <- file.path(source, filename)
    if (!file.exists(filepath))
      stop(
        sprintf(
          "File not found: %s\n  Check options(data_dir) or the 'source' argument.",
          filepath
        ),
        call. = FALSE
      )
    .load_rdata_file(filepath)
  }
}

Try the eiballots package in your browser

Any scripts or data that you put into this service are public.

eiballots documentation built on Sept. 26, 2026, 5:06 p.m.