Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 35 additions & 6 deletions R/get_file.R
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
#'
#' @param ds_name Dataset name
#' @param file_name File name
#' @param download_file_name Filename on disk after download
#' @param download_file_name Filename on disk after download - if not specified,
#' preserve original file name from Melodi - default NULL (preserve original
#' file name)
#' @param download_directory Download directory - default system tempdir
#'
#' @return downloaded file name on disk
Expand All @@ -17,23 +19,50 @@
get_file <- function(
ds_name,
file_name,
download_file_name,
download_file_name = NULL,
download_directory = tempdir()
) {
# Build useful parameters
url <- glue::glue(
"{getOption('rmelodi.base_url_api')}/file/{ds_name}/{file_name}"
)
path <- file.path(download_directory, download_file_name)

if (!is.null(download_file_name)) {
path <- file.path(download_directory, download_file_name)
message("Downloaded path : ", path)
} else {
# if no file name specified : tempfile
# and then after download, rename with original file name
path <- tempfile()
message("Temporary downloaded path : ", path)
}

# Download file
message("Request file : ", url)
message("Downloaded path : ", path)

httr2::request(url) |>
resp <- httr2::request(url) |>
httr2::req_user_agent(getOption("rmelodi.req_user_agent")) |>
httr2::req_progress() |>
httr2::req_perform(path = path)

return(path)
if (is.null(download_file_name)) {
# Extract original filename from content-disposition in request header
# Exemple of content-disposition :
# inline; filename="DS_SRCV_CONFIANCE_2025_CSV_FR.zip"
cd <- httr2::resp_headers(resp)[["content-disposition"]]
m <- regmatches(cd, regexec('filename\\*?="?([^";]+)"?', cd))
original_file_name <- if (length(m[[1]]) > 1) m[[1]][2] else basename(tmp)
message("Original file name in Melodi : ", original_file_name)

# Rename the file on disk with this new name
renamed_path <- file.path(download_directory, original_file_name)
message("Move file to path : ", renamed_path)
file.copy(path, renamed_path)
message("Remove temporary file : ", path)
unlink(path)

return(renamed_path)
} else {
return(path)
}
}
6 changes: 4 additions & 2 deletions man/get_file.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading