16827: Don't append '/' to requests with query params. Bump version
[arvados.git] / sdk / R / R / Subcollection.R
index 06df7c48767280f601dcbd30ceec9558adfccdd5..981bd687a2fbcb68f8eb0deafa7caed619dd3628 100644 (file)
@@ -1,8 +1,49 @@
-#' Arvados SubCollection Object
+# Copyright (C) The Arvados Authors. All rights reserved.
+#
+# SPDX-License-Identifier: Apache-2.0
+
+#' Subcollection
+#'
+#' Subcollection class represents a folder inside Arvados collection.
+#' It is essentially a composite of arvadosFiles and other subcollections.
+#'
+#' @section Usage:
+#' \preformatted{subcollection = Subcollection$new(name)}
+#'
+#' @section Arguments:
+#' \describe{
+#'   \item{name}{Name of the subcollection.}
+#' }
+#'
+#' @section Methods:
+#' \describe{
+#'   \item{getName()}{Returns name of the subcollection.}
+#'   \item{getRelativePath()}{Returns subcollection path relative to the root.}
+#'   \item{add(content)}{Adds ArvadosFile or Subcollection specified by content to the subcollection.}
+#'   \item{remove(name)}{Removes ArvadosFile or Subcollection specified by name from the subcollection.}
+#'   \item{get(relativePath)}{If relativePath is valid, returns ArvadosFile or Subcollection specified by relativePath, else returns NULL.}
+#'   \item{getFileListing()}{Returns subcollections file content as character vector.}
+#'   \item{getSizeInBytes()}{Returns subcollections content size in bytes.}
+#'   \item{move(destination)}{Moves subcollection to a new location inside collection.}
+#'   \item{copy(destination)}{Copies subcollection to a new location inside collection.}
+#' }
+#'
+#' @name Subcollection
+#' @examples
+#' \dontrun{
+#' myFolder <- Subcollection$new("myFolder")
+#' myFile   <- ArvadosFile$new("myFile")
 #'
-#' Update description
+#' myFolder$add(myFile)
+#' myFolder$get("myFile")
+#' myFolder$remove("myFile")
 #'
-#' @export Subcollection
+#' myFolder$move("newLocation/myFolder")
+#' myFolder$copy("newLocation/myFolder")
+#' }
+NULL
+
+#' @export
 Subcollection <- R6::R6Class(
 
     "Subcollection",
@@ -11,13 +52,11 @@ Subcollection <- R6::R6Class(
 
         initialize = function(name)
         {
-            private$name       <- name
-            private$http       <- HttpRequest$new()
-            private$httpParser <- HttpParser$new()
+            private$name <- name
         },
 
         getName = function() private$name,
-        
+
         getRelativePath = function()
         {
             relativePath <- c(private$name)
@@ -38,20 +77,28 @@ Subcollection <- R6::R6Class(
             if("ArvadosFile"   %in% class(content) ||
                "Subcollection" %in% class(content))
             {
+                if(!is.null(content$getCollection()))
+                    stop("Content already belongs to a collection.")
+
+                if(content$getName() == "")
+                    stop("Content has invalid name.")
+
                 childWithSameName <- self$get(content$getName())
+
                 if(!is.null(childWithSameName))
-                    stop("Subcollection already contains ArvadosFile
-                          or Subcollection with same name.")
+                    stop(paste("Subcollection already contains ArvadosFile",
+                               "or Subcollection with same name."))
 
                 if(!is.null(private$collection))
-                {       
+                {
                     if(self$getRelativePath() != "")
                         contentPath <- paste0(self$getRelativePath(),
                                               "/", content$getFileListing())
                     else
                         contentPath <- content$getFileListing()
 
-                    private$collection$createFilesOnREST(contentPath)
+                    REST <- private$collection$getRESTService()
+                    REST$create(contentPath, private$collection$uuid)
                     content$setCollection(private$collection)
                 }
 
@@ -62,8 +109,9 @@ Subcollection <- R6::R6Class(
             }
             else
             {
-                stop(paste("Expected AravodsFile or Subcollection object, got",
-                           class(content), "."))
+                stop(paste0("Expected AravodsFile or Subcollection object, got ",
+                            paste0("(", paste0(class(content), collapse = ", "), ")"),
+                            "."))
             }
         },
 
@@ -74,12 +122,14 @@ Subcollection <- R6::R6Class(
                 child <- self$get(name)
 
                 if(is.null(child))
-                    stop("Subcollection doesn't contains ArvadosFile
-                          or Subcollection with same name.")
+                    stop(paste("Subcollection doesn't contains ArvadosFile",
+                               "or Subcollection with specified name."))
 
                 if(!is.null(private$collection))
                 {
-                    private$collection$deleteFromREST(child$getRelativePath())
+                    REST <- private$collection$getRESTService()
+                    REST$delete(child$getRelativePath(), private$collection$uuid)
+
                     child$setCollection(NULL)
                 }
 
@@ -90,90 +140,101 @@ Subcollection <- R6::R6Class(
             }
             else
             {
-                stop(paste("Expected character, got", class(content), "."))
+                stop(paste0("Expected character, got ",
+                            paste0("(", paste0(class(name), collapse = ", "), ")"),
+                            "."))
             }
         },
 
-        getFileListing = function(fullpath = TRUE)
+        getFileListing = function(fullPath = TRUE)
         {
-            content <- NULL
+            content <- private$getContentAsCharVector(fullPath)
+            content[order(tolower(content))]
+        },
 
-            if(fullpath)
-            {
-                for(child in private$children)
-                    content <- c(content, child$getFileListing())
+        getSizeInBytes = function()
+        {
+            if(is.null(private$collection))
+                return(0)
 
-                if(private$name != "")
-                    content <- unlist(paste0(private$name, "/", content))
-            }
-            else
-            {
-                for(child in private$children)
-                    content <- c(content, child$getName())
-            }
+            REST <- private$collection$getRESTService()
 
-            content
+            fileSizes <- REST$getResourceSize(paste0(self$getRelativePath(), "/"),
+                                              private$collection$uuid)
+            return(sum(fileSizes))
         },
 
-        getSizeInBytes = function()
+        move = function(destination)
         {
-            collectionURL <- URLencode(paste0(private$collection$api$getWebDavHostName(),
-                                              "c=", private$collection$uuid))
-            subcollectionURL <- paste0(collectionURL, "/", self$getRelativePath(), "/");
+            if(is.null(private$collection))
+                stop("Subcollection doesn't belong to any collection.")
 
-            headers = list("Authorization" = paste("OAuth2", private$collection$api$getToken()))
+            destination <- trimFromEnd(destination, "/")
+            nameAndPath <- splitToPathAndName(destination)
 
-            propfindResponse <- private$http$PROPFIND(subcollectionURL, headers)
+            newParent <- private$collection$get(nameAndPath$path)
 
-            sizes <- private$httpParser$extractFileSizeFromWebDAVResponse(propfindResponse, collectionURL)
-            sizes <- as.numeric(sizes[-1])
+            if(is.null(newParent))
+                stop("Unable to get destination subcollection.")
 
-            sum(sizes)
+            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
         },
 
-        move = function(newLocation)
+        copy = function(destination)
         {
             if(is.null(private$collection))
                 stop("Subcollection doesn't belong to any collection.")
 
-            if(endsWith(newLocation, paste0(private$name, "/")))
-            {
-                newLocation <- substr(newLocation, 0,
-                                      nchar(newLocation) - nchar(paste0(private$name, "/")))
-            }
-            else if(endsWith(newLocation, private$name))
-            {
-                newLocation <- substr(newLocation, 0,
-                                      nchar(newLocation) - nchar(private$name))
-            }
-            else
-            {
-                stop("Destination path is not valid.")
-            }
+            destination <- trimFromEnd(destination, "/")
+            nameAndPath <- splitToPathAndName(destination)
 
-            newParent <- private$collection$get(newLocation)
+            newParent <- private$collection$get(nameAndPath$path)
 
-            if(is.null(newParent))
-            {
+            if(is.null(newParent) || !("Subcollection" %in% class(newParent)))
                 stop("Unable to get destination subcollection.")
-            }
 
-            status <- private$collection$moveOnREST(self$getRelativePath(),
-                                                    paste0(newParent$getRelativePath(),
-                                                           "/", self$getName()))
+            childWithSameName <- newParent$get(nameAndPath$name)
 
-            #Note: We temporary set parents collection to NULL. This will ensure that
-            #      add method doesn't post file on REST server.
-            parentsCollection <- newParent$getCollection()
-            newParent$setCollection(NULL, setRecursively = FALSE)
+            if(!is.null(childWithSameName))
+                stop("Destination already contains content with same name.")
 
-            newParent$add(self)
+            REST <- private$collection$getRESTService()
+            REST$copy(self$getRelativePath(),
+                      paste0(newParent$getRelativePath(), "/", nameAndPath$name),
+                      private$collection$uuid)
 
-            newParent$setCollection(parentsCollection, setRecursively = FALSE)
+            newContent <- self$duplicate(nameAndPath$name)
+            newContent$setCollection(self$getCollection(), setRecursively = TRUE)
+            newContent$setParent(newParent)
+            private$attachToNewParent(newContent, newParent)
 
-            private$parent <- newParent
+            newContent
+        },
 
-            "Content moved successfully."
+        duplicate = function(newName = NULL)
+        {
+            name <- if(!is.null(newName)) newName else private$name
+            root <- Subcollection$new(name)
+            for(child in private$children)
+                root$add(child$duplicate())
+
+            root
         },
 
         get = function(name)
@@ -219,8 +280,6 @@ Subcollection <- R6::R6Class(
         children   = NULL,
         parent     = NULL,
         collection = NULL,
-        http       = NULL,
-        httpParser = NULL,
 
         removeChild = function(name)
         {
@@ -236,8 +295,81 @@ Subcollection <- R6::R6Class(
                     }
                 }
             }
+        },
+
+        attachToNewParent = function(content, newParent)
+        {
+            # We temporary set parents collection to NULL. This will ensure that
+            # add method doesn't post this subcollection to 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)
+        },
+
+        dettachFromCurrentParent = function()
+        {
+            # We temporary set parents collection to NULL. This will ensure that
+            # remove method doesn't remove this subcollection from REST.
+            parent <- private$parent
+            parentsCollection <- parent$getCollection()
+            parent$setCollection(NULL, setRecursively = FALSE)
+            parent$remove(private$name)
+            parent$setCollection(parentsCollection, setRecursively = FALSE)
+        },
+
+        getContentAsCharVector = function(fullPath = TRUE)
+        {
+            content <- NULL
+
+            if(fullPath)
+            {
+                for(child in private$children)
+                    content <- c(content, child$getFileListing())
+
+                if(private$name != "")
+                    content <- unlist(paste0(private$name, "/", content))
+            }
+            else
+            {
+                for(child in private$children)
+                    content <- c(content, child$getName())
+            }
+
+            content
         }
     ),
-    
+
     cloneable = FALSE
 )
+
+#' print.Subcollection
+#'
+#' Custom print function for Subcollection class
+#'
+#' @param x Instance of Subcollection class
+#' @param ... Optional arguments.
+#' @export
+print.Subcollection = function(x, ...)
+{
+    collection   <- NULL
+    relativePath <- x$getRelativePath()
+
+    if(!is.null(x$getCollection()))
+    {
+        collection <- x$getCollection()$uuid
+
+        if(!x$getName() == "")
+            relativePath <- paste0("/", relativePath)
+    }
+
+    cat(paste0("Type:          ", "\"", "Arvados Subcollection", "\""), sep = "\n")
+    cat(paste0("Name:          ", "\"", x$getName(),             "\""), sep = "\n")
+    cat(paste0("Relative path: ", "\"", relativePath,            "\""), sep = "\n")
+    cat(paste0("Collection:    ", "\"", collection,              "\""), sep = "\n")
+}