Skip to content

Instantly share code, notes, and snippets.

@SachaEpskamp
Last active October 2, 2016 06:56
Show Gist options
  • Save SachaEpskamp/05c2ad14bd5fc48d5b85 to your computer and use it in GitHub Desktop.
Save SachaEpskamp/05c2ad14bd5fc48d5b85 to your computer and use it in GitHub Desktop.
getOSFfile
# Function to download OSF file:
getOSFfile <- function(
code, #Either "https://osf.io/XXXXX/" or just the code
dir = getwd(), # Output location
method = c("downloader","httr","curl") # First one is chosen
){
# Check if input is code:
if (!grepl("osf\\.io",code)){
URL <- sprintf("https://osf.io/%s/",code)
} else URL <- code
# Scan page:
Page <- RCurl::getURL(URL)
# Extract download link(s):
Link <- regmatches(Page, regexpr("(?<=download: \\').*?\\?action=download(?=\\')", Page, perl = TRUE))
# Stop if no download link:
if (length(Link)==0){
stop("No download link found")
}
# (just in case) if more than one, warning:
if (length(Link)>1){
warning("Multiple download links found, only first is used")
Link <- Link[1]
}
# Full link:
Link <- paste0("https://osf.io/",Link)
# Estract file name:
FileName <- gsub("(^.*files/)|(\\/\\?action=download$)","",Link)
FullPath <- paste0(dir,"/",FileName)
# Download file:
if (method[[1]]=="httr"){
library("httr")
httr::GET(Link, httr::write_disk(FullPath, overwrite = TRUE))
} else if (method[[1]]=="downloader"){
library("downloader")
downloader:::download(Link, destfile = FullPath, quiet=TRUE)
} else if (method[[1]]=="curl"){
system(sprintf("curl -J -L %s > %s", Link, FullPath), ignore.stderr = TRUE)
}
# Return location of file:
return(FullPath)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment