16827: Don't append '/' to requests with query params. Bump version
[arvados.git] / sdk / R / R / ArvadosFile.R
index c8950c651cfd6ee568144d7f6f647a422bbd1843..fb1d3b335cba00df4db898de20b917334b7e4610 100644 (file)
@@ -1,8 +1,58 @@
-#' ArvadosFile Object
+# Copyright (C) The Arvados Authors. All rights reserved.
+#
+# SPDX-License-Identifier: Apache-2.0
+
+#' ArvadosFile
+#'
+#' ArvadosFile class represents a file inside Arvados collection.
+#'
+#' @section Usage:
+#' \preformatted{file = ArvadosFile$new(name)}
+#'
+#' @section Arguments:
+#' \describe{
+#'   \item{name}{Name of the file.}
+#' }
+#'
+#' @section Methods:
+#' \describe{
+#'   \item{getName()}{Returns name of the file.}
+#'   \item{getRelativePath()}{Returns file path relative to the root.}
+#'   \item{read(contentType = "raw", offset = 0, length = 0)}{Read file content.}
+#'   \item{write(content, contentType = "text/html")}{Write to file (override current content of the file).}
+#'   \item{connection(rw)}{Get connection opened in "read" or "write" mode.}
+#'   \item{flush()}{Write connections content to a file (override current content of the file).}
+#'   \item{remove(name)}{Removes ArvadosFile or Subcollection specified by name from the subcollection.}
+#'   \item{getSizeInBytes()}{Returns file size in bytes.}
+#'   \item{move(destination)}{Moves file to a new location inside collection.}
+#'   \item{copy(destination)}{Copies file to a new location inside collection.}
+#' }
 #'
-#' Update description
+#' @name ArvadosFile
+#' @examples
+#' \dontrun{
+#' myFile <- ArvadosFile$new("myFile")
 #'
-#' @export ArvadosFile
+#' myFile$write("This is new file content")
+#' fileContent <- myFile$read()
+#' fileContent <- myFile$read("text")
+#' fileContent <- myFile$read("raw", offset = 8, length = 4)
+#'
+#' #Write a table:
+#' arvConnection <- myFile$connection("w")
+#' write.table(mytable, arvConnection)
+#' arvadosFile$flush()
+#'
+#' #Read a table:
+#' arvConnection <- myFile$connection("r")
+#' mytable <- read.table(arvConnection)
+#'
+#' myFile$move("newFolder/myFile")
+#' myFile$copy("newFolder/myFile")
+#' }
+NULL
+
+#' @export
 ArvadosFile <- R6::R6Class(
 
     "ArvadosFile",
@@ -11,41 +61,46 @@ ArvadosFile <- R6::R6Class(
 
         initialize = function(name)
         {
-            private$name       <- name
-            private$http       <- HttpRequest$new()
-            private$httpParser <- HttpParser$new()
+            if(name == "")
+                stop("Invalid name.")
+
+            private$name <- name
         },
 
         getName = function() private$name,
 
-        getFileList = function(fullpath = TRUE)
+        getFileListing = function(fullpath = TRUE)
         {
             self$getName()
         },
 
         getSizeInBytes = function()
         {
-            collectionURL <- URLencode(paste0(private$collection$api$getWebDavHostName(), "c=", private$collection$uuid))
-            fileURL <- paste0(collectionURL, "/", self$getRelativePath());
+            if(is.null(private$collection))
+                return(0)
 
-            headers = list("Authorization" = paste("OAuth2", private$collection$api$getToken()))
+            REST <- private$collection$getRESTService()
 
-            propfindResponse <- private$http$PROPFIND(fileURL, headers)
+            fileSize <- REST$getResourceSize(self$getRelativePath(),
+                                             private$collection$uuid)
+            fileSize
+        },
 
-            sizes <- private$httpParser$extractFileSizeFromWebDAVResponse(propfindResponse, collectionURL)
-            as.numeric(sizes)
+        get = function(fileLikeObjectName)
+        {
+            return(NULL)
         },
 
-        removeFromCollection = function()
+        getFirst = function()
         {
-            if(is.null(private$collection))
-                stop("Subcollection doesn't belong to any collection.")
-            
-            private$collection$.__enclos_env__$private$deleteFromREST(self$getRelativePath())
+            return(NULL)
+        },
+
+        getCollection = function() private$collection,
 
-            #todo rename this add to a collection
-            private$addToCollection(NULL)
-            private$detachFromParent()
+        setCollection = function(collection, setRecursively = TRUE)
+        {
+            private$collection <- collection
         },
 
         getRelativePath = function()
@@ -53,7 +108,6 @@ ArvadosFile <- R6::R6Class(
             relativePath <- c(private$name)
             parent <- private$parent
 
-            #Recurse back to root
             while(!is.null(parent))
             {
                 relativePath <- c(parent$getName(), relativePath)
@@ -66,80 +120,190 @@ ArvadosFile <- R6::R6Class(
 
         getParent = function() private$parent,
 
-        read = function(offset = 0, length = 0)
+        setParent = function(newParent) private$parent <- newParent,
+
+        read = function(contentType = "raw", offset = 0, length = 0)
         {
-            #todo range is wrong fix it
+            if(is.null(private$collection))
+                stop("ArvadosFile doesn't belong to any collection.")
+
             if(offset < 0 || length < 0)
-            stop("Offset and length must be positive values.")
+                stop("Offset and length must be positive values.")
 
-            range = paste0("bytes=", offset, "-")
+            REST <- private$collection$getRESTService()
 
-            if(length > 0)
-                range = paste0(range, offset + length - 1)
-            
-            fileURL = paste0(private$collection$api$getWebDavHostName(), "c=", private$collection$uuid, "/", self$getRelativePath());
-            headers <- list(Authorization = paste("OAuth2", private$collection$api$getToken()), 
-                            Range = range)
+            fileContent <- REST$read(self$getRelativePath(),
+                                     private$collection$uuid,
+                                     contentType, offset, length)
+            fileContent
+        },
 
-            serverResponse <- private$http$GET(fileURL, headers)
+        connection = function(rw)
+        {
+            if (rw == "r" || rw == "rb")
+            {
+                REST <- private$collection$getRESTService()
+                return(REST$getConnection(self$getRelativePath(),
+                                          private$collection$uuid,
+                                          rw))
+            }
+            else if (rw == "w")
+            {
+                private$buffer <- textConnection(NULL, "w")
 
-            if(serverResponse$status_code != 206)
-                stop(paste("Server code:", serverResponse$status_code))
+                return(private$buffer)
+            }
+        },
 
-            parsedServerResponse <- httr::content(serverResponse, "raw")
-            parsedServerResponse
+        flush = function()
+        {
+            v <- textConnectionValue(private$buffer)
+            close(private$buffer)
+            self$write(paste(v, collapse='\n'))
         },
-        
+
         write = function(content, contentType = "text/html")
         {
-            fileURL = paste0(private$collection$api$getWebDavHostName(), "c=", private$collection$uuid, "/", self$getRelativePath());
-            headers <- list(Authorization = paste("OAuth2", private$collection$api$getToken()), 
-                            "Content-Type" = contentType)
-            body <- content
+            if(is.null(private$collection))
+                stop("ArvadosFile doesn't belong to any collection.")
 
-            serverResponse <- private$http$PUT(fileURL, headers, body)
+            REST <- private$collection$getRESTService()
 
-            if(serverResponse$status_code != 201)
-                stop(paste("Server code:", serverResponse$status_code))
+            writeResult <- REST$write(self$getRelativePath(),
+                                      private$collection$uuid,
+                                      content, contentType)
+            writeResult
+        },
 
-            parsedServerResponse <- httr::content(serverResponse, "text")
-            parsedServerResponse
-        }
-    ),
+        move = function(destination)
+        {
+            if(is.null(private$collection))
+                stop("ArvadosFile doesn't belong to any collection.")
 
-    private = list(
+            destination <- trimFromEnd(destination, "/")
+            nameAndPath <- splitToPathAndName(destination)
 
-        name         = NULL,
-        size         = NULL,
-        parent       = NULL,
-        collection   = NULL,
-        http         = NULL,
-        httpParser   = NULL,
+            newParent <- private$collection$get(nameAndPath$path)
 
-        getChild = function(name)
-        {
-            return(NULL)
+            if(is.null(newParent))
+                stop("Unable to get destination subcollection.")
+
+            childWithSameName <- newParent$get(nameAndPath$name)
+
+            if(!is.null(childWithSameName))
+                stop("Destination already contains content with same name.")
+
+            REST <- private$collection$getRESTService()
+            REST$move(self$getRelativePath(),
+                      paste0(newParent$getRelativePath(), "/", nameAndPath$name),
+                      private$collection$uuid)
+
+            private$dettachFromCurrentParent()
+            private$attachToNewParent(self, newParent)
+
+            private$parent <- newParent
+            private$name <- nameAndPath$name
+
+            self
         },
 
-        getFirstChild = function()
+        copy = function(destination)
         {
-            return(NULL)
+            if(is.null(private$collection))
+                stop("ArvadosFile doesn't belong to any collection.")
+
+            destination <- trimFromEnd(destination, "/")
+            nameAndPath <- splitToPathAndName(destination)
+
+            newParent <- private$collection$get(nameAndPath$path)
+
+            if(is.null(newParent))
+                stop("Unable to get destination subcollection.")
+
+            childWithSameName <- newParent$get(nameAndPath$name)
+
+            if(!is.null(childWithSameName))
+                stop("Destination already contains content with same name.")
+
+            REST <- private$collection$getRESTService()
+            REST$copy(self$getRelativePath(),
+                      paste0(newParent$getRelativePath(), "/", nameAndPath$name),
+                      private$collection$uuid)
+
+            newFile <- self$duplicate(nameAndPath$name)
+            newFile$setCollection(self$getCollection())
+            private$attachToNewParent(newFile, newParent)
+            newFile$setParent(newParent)
+
+            newFile
         },
 
-        addToCollection = function(collection)
+        duplicate = function(newName = NULL)
+        {
+            name <- if(!is.null(newName)) newName else private$name
+            newFile <- ArvadosFile$new(name)
+            newFile
+        }
+    ),
+
+    private = list(
+
+        name       = NULL,
+        size       = NULL,
+        parent     = NULL,
+        collection = NULL,
+        buffer     = NULL,
+
+        attachToNewParent = function(content, newParent)
         {
-            private$collection = collection
+            # We temporary set parents collection to NULL. This will ensure that
+            # add method doesn't post this file on REST.
+            # We also need to set content's collection to NULL because
+            # add method throws exception if we try to add content that already
+            # belongs to a collection.
+            parentsCollection <- newParent$getCollection()
+            content$setCollection(NULL, setRecursively = FALSE)
+            newParent$setCollection(NULL, setRecursively = FALSE)
+            newParent$add(content)
+            content$setCollection(parentsCollection, setRecursively = FALSE)
+            newParent$setCollection(parentsCollection, setRecursively = FALSE)
         },
 
-        detachFromParent = function()
+        dettachFromCurrentParent = function()
         {
-            if(!is.null(private$parent))
-            {
-                private$parent$.__enclos_env__$private$removeChild(private$name)
-                private$parent <- NULL
-            }
+            # We temporary set parents collection to NULL. This will ensure that
+            # remove method doesn't remove this file from REST.
+            parent <- private$parent
+            parentsCollection <- parent$getCollection()
+            parent$setCollection(NULL, setRecursively = FALSE)
+            parent$remove(private$name)
+            parent$setCollection(parentsCollection, setRecursively = FALSE)
         }
     ),
-    
+
     cloneable = FALSE
 )
+
+#' print.ArvadosFile
+#'
+#' Custom print function for ArvadosFile class
+#'
+#' @param x Instance of ArvadosFile class
+#' @param ... Optional arguments.
+#' @export
+print.ArvadosFile = function(x, ...)
+{
+    collection   <- NULL
+    relativePath <- x$getRelativePath()
+
+    if(!is.null(x$getCollection()))
+    {
+        collection <- x$getCollection()$uuid
+        relativePath <- paste0("/", relativePath)
+    }
+
+    cat(paste0("Type:          ", "\"", "ArvadosFile", "\""), sep = "\n")
+    cat(paste0("Name:          ", "\"", x$getName(),   "\""), sep = "\n")
+    cat(paste0("Relative path: ", "\"", relativePath,  "\""), sep = "\n")
+    cat(paste0("Collection:    ", "\"", collection,    "\""), sep = "\n")
+}