Implement copy method, update move method and remove trailing
[arvados.git] / sdk / R / R / Collection.R
index 49a1e81d0767c7b33513a290ecad208f0a7fd216..f88eb0e7cdfd36a097cf79494a4d298b5d199d35 100644 (file)
+# Copyright (C) The Arvados Authors. All rights reserved.
+#
+# SPDX-License-Identifier: Apache-2.0
+
 source("./R/Subcollection.R")
 source("./R/ArvadosFile.R")
-source("./R/FileTree.R")
-source("./R/HttpRequest.R")
-source("./R/HttpParser.R")
+source("./R/RESTService.R")
+source("./R/util.R")
 
-#' Arvados Collection Object
+#' Collection
+#'
+#' Collection class provides interface for working with Arvados collections.
+#'
+#' @section Usage:
+#' \preformatted{collection = Collection$new(arv, uuid)}
+#'
+#' @section Arguments:
+#' \describe{
+#'   \item{arv}{Arvados object.}
+#'   \item{uuid}{UUID of a collection.}
+#' }
+#'
+#' @section Methods:
+#' \describe{
+#'   \item{add(content)}{Adds ArvadosFile or Subcollection specified by content to the collection.}
+#'   \item{create(fileNames, relativePath = "")}{Creates one or more ArvadosFiles and adds them to the collection at specified path.}
+#'   \item{remove(fileNames)}{Remove one or more files from the collection.}
+#'   \item{move(content, newLocation)}{Moves ArvadosFile or Subcollection to another location in the collection.}
+#'   \item{getFileListing()}{Returns collections file content as character vector.}
+#'   \item{get(relativePath)}{If relativePath is valid, returns ArvadosFile or Subcollection specified by relativePath, else returns NULL.}
+#' }
 #'
-#' Update description
+#' @name Collection
+#' @examples
+#' \dontrun{
+#' arv <- Arvados$new("your Arvados token", "example.arvadosapi.com")
+#' collection <- Collection$new(arv, "uuid")
 #'
-#' @examples arv = Collection$new(api, uuid)
-#' @export Collection
+#' newFile <- ArvadosFile$new("myFile")
+#' collection$add(newFile, "myFolder")
+#'
+#' createdFiles <- collection$create(c("main.cpp", lib.dll), "cpp/src/")
+#'
+#' collection$remove("location/to/my/file.cpp")
+#'
+#' collection$move("folder/file.cpp", "file.cpp")
+#'
+#' arvadosFile <- collection$get("location/to/my/file.cpp")
+#' arvadosSubcollection <- collection$get("location/to/my/directory/")
+#' }
+NULL
+
+#' @export
 Collection <- R6::R6Class(
 
     "Collection",
 
     public = list(
 
-        #Todo(Fudo): Encapsulate this?
-        uuid                     = NULL,
-        etag                     = NULL,
-        owner_uuid               = NULL,
-        created_at               = NULL,
-        modified_by_client_uuid  = NULL,
-        modified_by_user_uuid    = NULL,
-        modified_at              = NULL,
-        portable_data_hash       = NULL,
-        replication_desired      = NULL,
-        replication_confirmed_at = NULL,
-        replication_confirmed    = NULL,
-        updated_at               = NULL,
-        manifest_text            = NULL,
-        name                     = NULL,
-        description              = NULL,
-        properties               = NULL,
-        delete_at                = NULL,
-        file_names               = NULL,
-        trash_at                 = NULL,
-        is_trashed               = NULL,
-
-        initialize = function(api, uuid)
-        {
-            private$api <- api
-            result <- private$api$getCollection(uuid)
-
-            self$uuid                     <- result$uuid                               
-            self$etag                     <- result$etag                               
-            self$owner_uuid               <- result$owner_uuid                         
-            self$created_at               <- result$created_at                         
-            self$modified_by_client_uuid  <- result$modified_by_client_uuid            
-            self$modified_by_user_uuid    <- result$modified_by_user_uuid              
-            self$modified_at              <- result$modified_at                        
-            self$portable_data_hash       <- result$portable_data_hash                 
-            self$replication_desired      <- result$replication_desired                
-            self$replication_confirmed_at <- result$replication_confirmed_at           
-            self$replication_confirmed    <- result$replication_confirmed              
-            self$updated_at               <- result$updated_at                         
-            self$manifest_text            <- result$manifest_text                      
-            self$name                     <- result$name                               
-            self$description              <- result$description                        
-            self$properties               <- result$properties                         
-            self$delete_at                <- result$delete_at                          
-            self$file_names               <- result$file_names                         
-            self$trash_at                 <- result$trash_at                           
-            self$is_trashed               <- result$is_trashed                         
-
-            private$http <- HttpRequest$new()
-            private$httpParser <- HttpParser$new()
-
-            private$fileItems <- private$getCollectionContent()
-            private$fileTree <- FileTree$new(private$fileItems)
-
-        },
+               uuid = NULL,
 
-        printFileContent = function()
+               initialize = function(api, uuid)
         {
-            private$fileTree$printContent(private$fileTree$getRoot(), 0)
+            private$REST <- api$getRESTService()
+            self$uuid <- uuid
         },
 
-        getFileContent = function()
+        add = function(content, relativePath = "")
         {
-            sapply(private$fileItems, function(file)
-            {
-                file$name
-            })
-        },
+            if(is.null(private$tree))
+                private$generateCollectionTreeStructure()
 
-        get = function(relativePath)
-        {
-            treeNode <- private$fileTree$traverseInOrder(private$fileTree$getRoot(), function(node)
+            if(relativePath == ""  ||
+               relativePath == "." ||
+               relativePath == "./")
             {
-                if(node$relativePath == relativePath)
-                    return(node)
-                else
-                    return(NULL)
-            })
+                subcollection <- private$tree$getTree()
+            }
+            else
+            {
+                relativePath <- trimFromEnd(relativePath, "/")
+                subcollection <- self$get(relativePath)
+            }
 
-            if(!is.null(treeNode))
+            if(is.null(subcollection))
+                stop(paste("Subcollection", relativePath, "doesn't exist."))
+
+            if("ArvadosFile"   %in% class(content) ||
+               "Subcollection" %in% class(content))
             {
-                return(private$createSubcollectionTree(treeNode))
+                if(content$getName() == "")
+                    stop("Content has invalid name.")
+
+                subcollection$add(content)
+                content
             }
             else
             {
-                return(NULL)
+                stop(paste0("Expected AravodsFile or Subcollection object, got ",
+                            paste0("(", paste0(class(content), collapse = ", "), ")"),
+                            "."))
             }
         },
 
-        createNewFile = function(relativePath, content, contentType)
+        create = function(fileNames, relativePath = "")
         {
-            fileURL <- paste0(private$api$getWebDavHostName(), "c=", self$uuid, "/", relativePath);
-            headers <- list(Authorization = paste("OAuth2", private$api$getToken()), 
-                            "Content-Type" = contentType)
-            body <- content
+            if(is.null(private$tree))
+                private$generateCollectionTreeStructure()
+
+            if(relativePath == ""  ||
+               relativePath == "." ||
+               relativePath == "./")
+            {
+                subcollection <- private$tree$getTree()
+            }
+            else
+            {
+                relativePath  <- trimFromEnd(relativePath, "/")
+                subcollection <- self$get(relativePath)
+            }
+
+            if(is.null(subcollection))
+                stop(paste("Subcollection", relativePath, "doesn't exist."))
 
-            serverResponse <- private$http$PUT(fileURL, headers, body)
+            if(is.character(fileNames))
+            {
+                arvadosFiles <- NULL
+                sapply(fileNames, function(fileName)
+                {
+                    childWithSameName <- subcollection$get(fileName)
+                    if(!is.null(childWithSameName))
+                        stop("Destination already contains file with same name.")
 
-            if(serverResponse$status_code != 201)
-                stop(paste("Server code:", serverResponse$status_code))
+                    newFile <- ArvadosFile$new(fileName)
+                    subcollection$add(newFile)
 
-            fileSize = private$getNewFileSize(relativePath)
-            private$fileTree$addNode(relativePath, fileSize)
+                    arvadosFiles <<- c(arvadosFiles, newFile)
+                })
 
-            paste0("File created (size = ", fileSize , ")")
+                if(length(arvadosFiles) == 1)
+                    return(arvadosFiles[[1]])
+                else
+                    return(arvadosFiles)
+            }
+            else
+            {
+                stop(paste0("Expected character vector, got ",
+                            paste0("(", paste0(class(fileNames), collapse = ", "), ")"),
+                            "."))
+            }
         },
 
-        removeFile = function(relativePath)
+        remove = function(paths)
         {
-            node <- private$fileTree$getNode(relativePath)
+            if(is.null(private$tree))
+                private$generateCollectionTreeStructure()
 
-            if(is.null(node))
-                stop("File doesn't exists.")
+            if(is.character(paths))
+            {
+                sapply(paths, function(filePath)
+                {
+                    filePath <- trimFromEnd(filePath, "/")
+                    file <- self$get(filePath)
 
-            fileURL <- paste0(private$api$getWebDavHostName(), "c=", self$uuid, "/", relativePath);
-            headers <- list(Authorization = paste("OAuth2", private$api$getToken())) 
+                    if(is.null(file))
+                        stop(paste("File", filePath, "doesn't exist."))
 
-            serverResponse <- private$http$DELETE(fileURL, headers)
+                    parent <- file$getParent()
 
-            if(serverResponse$status_code != 204)
-                stop(paste("Server code:", serverResponse$status_code))
+                    if(is.null(parent))
+                        stop("You can't delete root folder.")
 
-            "File deleted"
-        },
+                    parent$remove(file$getName())
+                })
 
-        update = function(subcollection, event)
-        {
-            #Todo(Fudo): Add some king of check here later on.
-            if(event == "File size changed")
+                "Content removed"
+            }
+            else
             {
-                private$handleFileSizeChange(subcollection$getRelativePath(),
-                                             subcollection$getSizeInBytes())
+                stop(paste0("Expected character vector, got ",
+                            paste0("(", paste0(class(paths), collapse = ", "), ")"),
+                            "."))
             }
-        }
-    ),
+        },
 
-    active = list(
-        items = function(value)
+        move = function(content, destination)
         {
-            if(missing(value))
-                return(private$fileItems)
-            else
-                print("Value is read-only.")
+            if(is.null(private$tree))
+                private$generateCollectionTreeStructure()
 
-            return(NULL)
-        }
-    ),
-    
-    private = list(
+            content <- trimFromEnd(content, "/")
+
+            elementToMove <- self$get(content)
 
-        fileItems  = NULL,
-        api        = NULL,
-        fileTree   = NULL,
-        http       = NULL,
-        httpParser = NULL,
+            if(is.null(elementToMove))
+                stop("Content you want to move doesn't exist in the collection.")
 
-        handleFileSizeChange = function(filePath, newSize)
+            elementToMove$move(destination)
+        },
+
+        copy = function(content, destination)
         {
-            node <- private$fileTree$getNode(filePath)
+            if(is.null(private$tree))
+                private$generateCollectionTreeStructure()
+
+            content <- trimFromEnd(content, "/")
+
+            elementToCopy <- self$get(content)
 
-            if(is.null(node))
-                stop("File doesn't exits")
+            if(is.null(elementToCopy))
+                stop("Content you want to copy doesn't exist in the collection.")
 
-            node$size <- newSize
+            elementToCopy$copy(destination)
         },
 
-        createSubcollectionTree = function(treeNode)
+        refresh = function()
         {
-            if(treeNode$hasChildren())
-            {
-                children = NULL
+            private$tree$getTree()$setCollection(NULL, setRecursively = TRUE)
+            private$tree <- NULL
+        },
 
-                for(child in treeNode$children)
-                {
-                    child <- private$createSubcollectionTree(child)
-                    children <- c(children, child)                   
-                }
+        getFileListing = function()
+        {
+            if(is.null(private$tree))
+                private$generateCollectionTreeStructure()
 
-                return(Subcollection$new(treeNode$name, treeNode$relativePath, children))
-            }
-            else
-            {
-                if(treeNode$type == "file")
-                    return(ArvadosFile$new(treeNode$name, treeNode$relativePath, treeNode$size, private$api, self))
-                else 
-                    return(Subcollection$new(treeNode$name, treeNode$relativePath, NULL))
-            }
+            content <- private$REST$getCollectionContent(self$uuid)
+            content[order(tolower(content))]
         },
 
-        getCollectionContent = function()
+        get = function(relativePath)
         {
-            collectionURL <- URLencode(paste0(private$api$getWebDavHostName(), "c=", self$uuid))
+            if(is.null(private$tree))
+                private$generateCollectionTreeStructure()
 
-            headers = list("Authorization" = paste("OAuth2", private$api$getToken()))
+            private$tree$getElement(relativePath)
+        },
 
-            response <- private$http$PROPFIND(collectionURL, headers)
+        getRESTService = function() private$REST,
+        setRESTService = function(newRESTService) private$REST <- newRESTService
+    ),
 
-            parsedResponse <- private$httpParser$parseWebDAVResponse(response, collectionURL)
-            parsedResponse[-1]
-        },
+    private = list(
 
-        getNewFileSize = function(relativePath)
-        {
-            collectionURL <- URLencode(paste0(private$api$getWebDavHostName(), "c=", self$uuid))
-            fileURL = paste0(collectionURL, "/", relativePath);
-            headers = list("Authorization" = paste("OAuth2", private$api$getToken()))
+        REST        = NULL,
+        tree        = NULL,
+        fileContent = NULL,
 
-            propfindResponse <- private$http$PROPFIND(fileURL, headers)
+        generateCollectionTreeStructure = function()
+        {
+            if(is.null(self$uuid))
+                stop("Collection uuid is not defined.")
 
-            fileInfo <- private$httpParser$parseWebDAVResponse(propfindResponse, collectionURL)
+            if(is.null(private$REST))
+                stop("REST service is not defined.")
 
-            fileInfo[[1]]$fileSize
+            private$fileContent <- private$REST$getCollectionContent(self$uuid)
+            private$tree <- CollectionTree$new(private$fileContent, self)
         }
     ),
 
     cloneable = FALSE
 )
+
+#' print.Collection
+#'
+#' Custom print function for Collection class
+#'
+#' @param x Instance of Collection class
+#' @param ... Optional arguments.
+#' @export
+print.Collection = function(x, ...)
+{
+    cat(paste0("Type: ", "\"", "Arvados Collection", "\""), sep = "\n")
+    cat(paste0("uuid: ", "\"", x$uuid,               "\""), sep = "\n")
+}