1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
|
# Copyright (C) 2009-2014 by RStudio, Inc.
#
# This program is licensed to you under the terms of version 2 of the
# GNU General Public License. This program is distributed WITHOUT ANY
# EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
# GPL (http://www.gnu.org/licenses/gpl-2.0.txt) for more details.
#
#
#' Upload an HTML file to RPubs
#'
#' This function uploads an HTML file to rpubs.com. If the upload succeeds a
#' list that includes an \code{id} and \code{continueUrl} is returned. A browser
#' should be opened to the \code{continueUrl} to complete publishing of the
#' document. If an error occurs then a diagnostic message is returned in the
#' \code{error} element of the list.
#' @param title The title of the document.
#' @param htmlFile The path to the HTML file to upload.
#' @param id If this upload is an update of an existing document then the id
#' parameter should specify the document id to update. Note that the id is
#' provided as an element of the list returned by successful calls to
#' \code{rpubsUpload}.
#' @param properties A named list containing additional document properties
#' (RPubs doesn't currently expect any additional properties, this parameter
#' is reserved for future use).
#' @param method Method to be used for uploading. "internal" uses a plain http
#' socket connection; "curl" uses the curl binary to do an https upload;
#' "rcurl" uses the RCurl package to do an https upload; and "auto" uses the
#' best available method searched for in the following order: "curl", "rcurl",
#' and then "internal". The global default behavior can be configured by
#' setting the \code{rpubs.upload.method} option (the default is "auto").
#' @return A named list. If the upload was successful then the list contains a
#' \code{id} element that can be used to subsequently update the document as
#' well as a \code{continueUrl} element that provides a URL that a browser
#' should be opened to in order to complete publishing of the document. If the
#' upload fails then the list contains an \code{error} element which contains
#' an explanation of the error that occurred.
#' @export
#' @examples
#' \dontrun{
#' # upload a document
#' result <- rpubsUpload("My document title", "Document.html")
#' if (!is.null(result$continueUrl))
#' browseURL(result$continueUrl) else stop(result$error)
#'
#' # update the same document with a new title
#' updateResult <- rpubsUpload("My updated title", "Document.html", result$id)
#' }
rpubsUpload <- function(title,
htmlFile,
id = NULL,
properties = list(),
method = getOption("rpubs.upload.method", "auto")) {
# validate inputs
if (!is.character(title))
stop("title must be specified")
if (nzchar(title) == FALSE)
stop("title must be a non-empty string")
if (!is.character(htmlFile))
stop("htmlFile parameter must be specified")
if (!file.exists(htmlFile))
stop("specified htmlFile does not exist")
if (!is.list(properties))
stop("properties paramater must be a named list")
parseHeader <- function(header) {
split <- strsplit(header, ": ")[[1]]
if (length(split) == 2)
list(name = split[1], value = split[2])
}
jsonEscapeString <- function(value) {
chars <- strsplit(value, "")[[1]]
chars <- vapply(chars, function(x) {
if (x %in% c('"', '\\', '/'))
paste('\\', x, sep='')
else if (charToRaw(x) < 20)
paste('\\u', toupper(format(as.hexmode(as.integer(charToRaw(x))),
width=4)),
sep='')
else x
}, character(1))
paste(chars, sep="", collapse="")
}
jsonProperty <- function(name, value) {
paste("\"",
jsonEscapeString(enc2utf8(name)),
"\" : \"",
jsonEscapeString(enc2utf8(value)),
"\"",
sep="")
}
regexExtract <- function(re, input) {
match <- regexec(re, input)
matchLoc <- match[1][[1]]
if (length(matchLoc) > 1) {
matchLen <-attributes(matchLoc)$match.length
url <- substr(input, matchLoc[2], matchLoc[2] + matchLen[2]-1)
url
}
}
# NOTE: we parse the json naively using a regex because:
# - We don't want to take a dependency on a json library for just this case
# - We know the payload is an ascii url so we don't need a robust parser
parseContinueUrl <- function(continueUrl) {
regexExtract("\\{\\s*\"continueUrl\"\\s*:\\s*\"([^\"]+)\"\\s*\\}",
continueUrl)
}
parseHttpStatusCode <- function(statusLine) {
statusCode <- regexExtract("HTTP/[0-9]+\\.[0-9]+ ([0-9]+).*", statusLine)
if (is.null(statusCode)) -1 else as.integer(statusCode)
}
pathFromId <- function(id) {
split <- strsplit(id, "^https?://[^/]+")[[1]]
if (length(split) == 2) split[2]
}
buildPackage <- function(title,
htmlFile,
properties = list()) {
# build package.json
packageJson <- "{"
packageJson <- paste(packageJson, jsonProperty("title", title), ",")
for (name in names(properties)) {
if (nzchar(name) == FALSE)
stop("all properties must be named")
value <- properties[[name]]
packageJson <- paste(packageJson, jsonProperty(name, value), ",")
}
packageJson <- substr(packageJson, 1, nchar(packageJson)-1)
packageJson <- paste(packageJson,"}")
# create a tempdir to build the package in and copy the files to it
fileSep <- .Platform$file.sep
packageDir <- tempfile()
dir.create(packageDir)
packageFile <- function(fileName) {
paste(packageDir,fileName,sep=fileSep)
}
writeLines(packageJson, packageFile("package.json"))
file.copy(htmlFile, packageFile("index.html"))
# switch to the package dir for building
oldWd <- getwd()
setwd(packageDir)
on.exit(setwd(oldWd))
# create the tarball
tarfile <- tempfile("package", fileext = ".tar.gz")
utils::tar(tarfile, files = ".", compression = "gzip")
# return the full path to the tarball
return (tarfile)
}
# Use skipDecoding=TRUE if transfer-encoding: chunked but the
# chunk decoding has already been performed on conn
readResponse <- function(conn, skipDecoding) {
# read status code
resp <- readLines(conn, 1)
statusCode <- parseHttpStatusCode(resp[1])
# read response headers
contentLength <- NULL
location <- NULL
transferEncoding <- NULL
repeat {
resp <- readLines(conn, 1)
if (nzchar(resp) == 0)
break
header <- parseHeader(resp)
# Case insensitive header name comparison
headerName <- tolower(header$name)
if (!is.null(header)) {
if (identical(headerName, "content-type"))
contentType <- header$value
if (identical(headerName, "content-length"))
contentLength <- as.integer(header$value)
if (identical(headerName, "location"))
location <- header$value
if (identical(headerName, "transfer-encoding"))
transferEncoding <- tolower(header$value)
}
}
# read the response content
content <- if (is.null(transferEncoding) || skipDecoding) {
if (!is.null(contentLength)) {
rawToChar(readBin(conn, what = 'raw', n=contentLength))
}
else {
paste(readLines(conn, warn = FALSE), collapse = "\r\n")
}
} else if (identical(transferEncoding, "chunked")) {
accum <- ""
repeat {
resp <- readLines(conn, 1)
resp <- sub(";.*", "", resp) # Ignore chunk extensions
chunkLen <- as.integer(paste("0x", resp, sep = ""))
if (is.na(chunkLen)) {
stop("Unexpected chunk length")
}
if (identical(chunkLen, 0L)) {
break
}
accum <- paste0(accum, rawToChar(readBin(conn, what = 'raw', n=chunkLen)))
# Eat CRLF
if (!identical("\r\n", rawToChar(readBin(conn, what = 'raw', n=2)))) {
stop("Invalid chunk encoding: missing CRLF")
}
}
accum
} else {
stop("Unexpected transfer encoding")
}
# return list
list(status = statusCode,
location = location,
contentType = contentType,
content = content)
}
# internal sockets implementation of upload (supports http-only)
internalUpload <- function(path,
contentType,
headers,
packageFile) {
# read file in binary mode
fileLength <- file.info(packageFile)$size
fileContents <- readBin(packageFile, what="raw", n=fileLength)
# build http request
request <- NULL
request <- c(request, paste("POST ", path, " HTTP/1.1\r\n", sep=""))
request <- c(request, "User-Agent: RStudio\r\n")
request <- c(request, "Host: api.rpubs.com\r\n")
request <- c(request, "Accept: */*\r\n")
request <- c(request, paste("Content-Type: ", contentType, "\r\n", sep=""))
request <- c(request, paste("Content-Length: ", fileLength, "\r\n", sep=""))
for (name in names(headers)) {
request <- c(request,
paste(name, ": ", headers[[name]], "\r\n", sep=""))
}
request <- c(request, "\r\n")
# open socket connection
conn <- socketConnection(host="api.rpubs.com",
port=80,
open="w+b",
blocking=TRUE)
on.exit(close(conn))
# write the request header and file payload
writeBin(charToRaw(paste(request,collapse="")), conn, size=1)
writeBin(fileContents, conn, size=1)
# read the response
readResponse(conn, skipDecoding = FALSE)
}
rcurlUpload <- function(path,
contentType,
headers,
packageFile) {
# url to post to
url <- paste("https://api.rpubs.com", path, sep = "")
# upload package file
params <- list(file = RCurl::fileUpload(filename = packageFile,
contentType = contentType))
# use custom header and text gatherers
sslpath <- system.file("CurlSSL", "cacert.pem", package = "RCurl")
options <- RCurl::curlOptions(url, cainfo = sslpath)
headerGatherer <- RCurl::basicHeaderGatherer()
options$headerfunction <- headerGatherer$update
textGatherer <- RCurl::basicTextGatherer()
options$writefunction <- textGatherer$update
# add extra headers
extraHeaders <- as.character(headers)
names(extraHeaders) <- names(headers)
options$httpheader <- extraHeaders
# post the form
RCurl::postForm(paste("https://api.rpubs.com", path, sep=""),
.params = params,
.opts = options,
useragent = "RStudio")
# return list
headers <- headerGatherer$value()
location <- if ("Location" %in% names(headers)) headers[["Location"]]
list(status = as.integer(headers[["status"]]),
location = location,
contentType <- headers[["Content-Type"]],
content = textGatherer$value())
}
curlUpload <- function(path,
contentType,
headers,
packageFile) {
fileLength <- file.info(packageFile)$size
extraHeaders <- character()
for (header in names(headers)) {
extraHeaders <- paste(extraHeaders, "--header")
extraHeaders <- paste(extraHeaders,
paste(header,":",headers[[header]], sep=""))
}
outputFile <- tempfile()
command <- paste("curl",
"-X",
"POST",
"--data-binary",
shQuote(paste("@", packageFile, sep="")),
"-i",
"--header", paste("Content-Type:",contentType, sep=""),
"--header", paste("Content-Length:", fileLength, sep=""),
extraHeaders,
"--header", "Expect:",
"--silent",
"--show-error",
"-o", shQuote(outputFile),
paste("https://api.rpubs.com", path, sep=""))
result <- system(command)
if (result == 0) {
fileConn <- file(outputFile, "rb")
on.exit(close(fileConn))
readResponse(fileConn, skipDecoding = TRUE)
} else {
stop(paste("Upload failed (curl error", result, "occurred)"))
}
}
uploadFunction <- if (is.function(method)) {
method
} else switch(
method,
"auto" = {
if (nzchar(Sys.which("curl"))) curlUpload else {
if (suppressWarnings(requireNamespace("RCurl", quietly = TRUE))) {
rcurlUpload
} else internalUpload
}
},
"internal" = internalUpload,
"curl" = curlUpload,
"rcurl" = rcurlUpload,
stop(paste("Invalid upload method specified:",method))
)
# build the package
packageFile <- buildPackage(title, htmlFile, properties)
# determine whether this is a new doc or an update
isUpdate <- FALSE
path <- "/api/v1/document"
headers <- list()
headers$Connection <- "close"
if (!is.null(id)) {
isUpdate <- TRUE
path <- pathFromId(id)
headers$`X-HTTP-Method-Override` <- "PUT"
}
# send the request
result <- uploadFunction(path,
"application/x-compressed",
headers,
packageFile)
# check for success
succeeded <- (isUpdate && (result$status == 200)) || (result$status == 201)
# mark content as UTF-8
content <- result$content
Encoding(content) <- "UTF-8"
# return either id & continueUrl or error
if (succeeded) {
list(id = ifelse(isUpdate, id, result$location),
continueUrl = parseContinueUrl(content))
} else list(error = content)
}
|