Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using elevatr in webrhttr/curl not available #103

Open
psychemedia opened this issue Feb 7, 2025 · 1 comment
Open

Using elevatr in webrhttr/curl not available #103

psychemedia opened this issue Feb 7, 2025 · 1 comment

Comments

@psychemedia
Copy link

I'm trying to use elevatr in ShinyLive / webR, a WASM build of R, but curl, as used in httr, is not available (example issue).

However, download.file() is available and can be used as follows (I haven't checked if the CORS proxy is required, but include it as an option just in case:

# CORS proxy function for webR environment
make_cors_url <- function(url, params = NULL) {
  if (!is.null(params)) {
    param_string <- paste(
      mapply(
        function(k, v) paste0(URLencode(k), "=", URLencode(v)),
        names(params),
        params
      ),
      collapse = "&"
    )
    url <- paste0(url, "?", param_string)
  }
  paste0("https://corsproxy.io/", URLencode(url))
}

# Apply CORS proxy if needed
 use_cors=T

dem_list <- lapply(urls, function(x) {
    
    tmpfile <- tempfile(tmpdir = tmp_dir, fileext = ".tif")
    
    # Apply CORS proxy if needed
    download_url <- if(use_cors) make_cors_url(x) else x
    
    # Use download.file with method="internal" for webR compatibility
    tryCatch({
      download.file(
        download_url, tmpfile
      )
      
      # Basic check if file exists and has content
      if (!file.exists(tmpfile) || file.size(tmpfile) == 0) {
        stop(paste("Failed to download from:", x))
      }
      
      # Note: We can't get headers like x-amz-meta-x-imagery-sources with base R
      # So we'll just return the tmpfile without the source attribute
      tmpfile
      
    }, error = function(e) {
      stop(paste("Error downloading from:", x, "\nError:", e$message))
    })
  })

Would it be possible to have fallback support for download.files() rather than httr so that elevatr can be used in a WebR/WASM context?

@jhollist
Copy link
Member

jhollist commented Feb 7, 2025

@psychemedia thanks for bringing this up!

I am amenable to including this; however, I don't have the time at the moment to make the addition. If you can submit a PR, with a test for this, I would be happy to merge it in.

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants