- 
          
 - 
                Notifications
    
You must be signed in to change notification settings  - Fork 4.6k
 
feat: Move to ZipFolderPlugin for downloading multiple-nodes #48098
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            6 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      d66e16b
              
                feat(dav): New `ZipFolderPlugin` which allows to download folders usi…
              
              
                susnux 2f66bd5
              
                fix: Allow `Streamer` to specify type in constructor instead of magin…
              
              
                susnux 0f6760c
              
                feat(files): Make the files download action use WebDAV zip download
              
              
                susnux e9d5906
              
                feat(files_sharing): Make `ShareController` download route use the DA…
              
              
                susnux eb69e89
              
                chore: Drop unused legacy `OC_Files`
              
              
                susnux ca8d576
              
                chore: compile assets
              
              
                susnux File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| <?php | ||
| 
     | 
||
| declare(strict_types=1); | ||
| 
     | 
||
| /** | ||
| * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors | ||
| * SPDX-License-Identifier: AGPL-3.0-or-later | ||
| */ | ||
| namespace OCA\DAV\Connector\Sabre; | ||
| 
     | 
||
| use OC\Streamer; | ||
| use OCP\Files\File as NcFile; | ||
| use OCP\Files\Folder as NcFolder; | ||
| use OCP\Files\Node as NcNode; | ||
| use Psr\Log\LoggerInterface; | ||
| use Sabre\DAV\Server; | ||
| use Sabre\DAV\ServerPlugin; | ||
| use Sabre\DAV\Tree; | ||
| use Sabre\HTTP\Request; | ||
| use Sabre\HTTP\Response; | ||
| 
     | 
||
| /** | ||
| * This plugin allows to download folders accessed by GET HTTP requests on DAV. | ||
| * The WebDAV standard explicitly say that GET is not covered and should return what ever the application thinks would be a good representation. | ||
| * | ||
| * When a collection is accessed using GET, this will provide the content as a archive. | ||
| * The type can be set by the `Accept` header (MIME type of zip or tar), or as browser fallback using a `accept` GET parameter. | ||
| * It is also possible to only include some child nodes (from the collection it self) by providing a `filter` GET parameter or `X-NC-Files` custom header. | ||
| */ | ||
| class ZipFolderPlugin extends ServerPlugin { | ||
| 
     | 
||
| /** | ||
| * Reference to main server object | ||
| */ | ||
| private ?Server $server = null; | ||
| 
     | 
||
| public function __construct( | ||
| private Tree $tree, | ||
| private LoggerInterface $logger, | ||
| ) { | ||
| } | ||
| 
     | 
||
| /** | ||
| * This initializes the plugin. | ||
| * | ||
| * This function is called by \Sabre\DAV\Server, after | ||
| * addPlugin is called. | ||
| * | ||
| * This method should set up the required event subscriptions. | ||
| */ | ||
| public function initialize(Server $server): void { | ||
| $this->server = $server; | ||
| $this->server->on('method:GET', $this->handleDownload(...), 100); | ||
                
      
                  skjnldsv marked this conversation as resolved.
               
          
            Show resolved
            Hide resolved
         | 
||
| } | ||
| 
     | 
||
| /** | ||
| * Adding a node to the archive streamer. | ||
| * This will recursively add new nodes to the stream if the node is a directory. | ||
| */ | ||
| protected function streamNode(Streamer $streamer, NcNode $node, string $rootPath): void { | ||
| // Remove the root path from the filename to make it relative to the requested folder | ||
| $filename = str_replace($rootPath, '', $node->getPath()); | ||
| 
     | 
||
| if ($node instanceof NcFile) { | ||
| $resource = $node->fopen('rb'); | ||
| if ($resource === false) { | ||
| $this->logger->info('Cannot read file for zip stream', ['filePath' => $node->getPath()]); | ||
| throw new \Sabre\DAV\Exception\ServiceUnavailable('Requested file can currently not be accessed.'); | ||
| } | ||
| $streamer->addFileFromStream($resource, $filename, $node->getSize(), $node->getMTime()); | ||
| } elseif ($node instanceof NcFolder) { | ||
| $streamer->addEmptyDir($filename); | ||
| $content = $node->getDirectoryListing(); | ||
| foreach ($content as $subNode) { | ||
| $this->streamNode($streamer, $subNode, $rootPath); | ||
| } | ||
| } | ||
| } | ||
| 
     | 
||
| /** | ||
| * Download a folder as an archive. | ||
| * It is possible to filter / limit the files that should be downloaded, | ||
| * either by passing (multiple) `X-NC-Files: the-file` headers | ||
| * or by setting a `files=JSON_ARRAY_OF_FILES` URL query. | ||
| * | ||
| * @return false|null | ||
| */ | ||
| public function handleDownload(Request $request, Response $response): ?bool { | ||
| $node = $this->tree->getNodeForPath($request->getPath()); | ||
| if (!($node instanceof \OCA\DAV\Connector\Sabre\Directory)) { | ||
| // only handle directories | ||
| return null; | ||
| } | ||
| 
     | 
||
| $query = $request->getQueryParameters(); | ||
| 
     | 
||
| // Get accept header - or if set overwrite with accept GET-param | ||
| $accept = $request->getHeaderAsArray('Accept'); | ||
| $acceptParam = $query['accept'] ?? ''; | ||
| if ($acceptParam !== '') { | ||
| $accept = array_map(fn (string $name) => strtolower(trim($name)), explode(',', $acceptParam)); | ||
                
       | 
||
| } | ||
| $zipRequest = !empty(array_intersect(['application/zip', 'zip'], $accept)); | ||
| $tarRequest = !empty(array_intersect(['application/x-tar', 'tar'], $accept)); | ||
| if (!$zipRequest && !$tarRequest) { | ||
| // does not accept zip or tar stream | ||
| return null; | ||
| } | ||
| 
     | 
||
| $files = $request->getHeaderAsArray('X-NC-Files'); | ||
| $filesParam = $query['files'] ?? ''; | ||
| // The preferred way would be headers, but this is not possible for simple browser requests ("links") | ||
| // so we also need to support GET parameters | ||
| if ($filesParam !== '') { | ||
| $files = json_decode($filesParam); | ||
| if (!is_array($files)) { | ||
| if (!is_string($files)) { | ||
| // no valid parameter so continue with Sabre behavior | ||
| $this->logger->debug('Invalid files filter parameter for ZipFolderPlugin', ['filter' => $filesParam]); | ||
| return null; | ||
| } | ||
| 
     | 
||
| $files = [$files]; | ||
| } | ||
| } | ||
| 
     | 
||
| $folder = $node->getNode(); | ||
| $content = empty($files) ? $folder->getDirectoryListing() : []; | ||
| foreach ($files as $path) { | ||
| $child = $node->getChild($path); | ||
| assert($child instanceof Node); | ||
| $content[] = $child->getNode(); | ||
| } | ||
| 
     | 
||
| $archiveName = 'download'; | ||
| $rootPath = $folder->getPath(); | ||
| if (empty($files)) { | ||
| // We download the full folder so keep it in the tree | ||
| $rootPath = dirname($folder->getPath()); | ||
| // Full folder is loaded to rename the archive to the folder name | ||
| $archiveName = $folder->getName(); | ||
| } | ||
| $streamer = new Streamer($tarRequest, -1, count($content)); | ||
| $streamer->sendHeaders($archiveName); | ||
| // For full folder downloads we also add the folder itself to the archive | ||
| if (empty($files)) { | ||
| $streamer->addEmptyDir($archiveName); | ||
| } | ||
| foreach ($content as $node) { | ||
| $this->streamNode($streamer, $node, $rootPath); | ||
| } | ||
| $streamer->finalize(); | ||
| return false; | ||
| } | ||
| } | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              This file was deleted.
      
      Oops, something went wrong.
      
    
  
      
      Oops, something went wrong.
        
    
  
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.