github.com/sacloud/libsacloud/v2@v2.32.3/helper/service/archive/download_service.go (about)

     1  // Copyright 2016-2022 The Libsacloud Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package archive
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"io"
    21  	"os"
    22  
    23  	"github.com/sacloud/ftps"
    24  	"github.com/sacloud/libsacloud/v2/sacloud"
    25  	"github.com/sacloud/libsacloud/v2/sacloud/types"
    26  )
    27  
    28  func (s *Service) Download(req *DownloadRequest) error {
    29  	return s.DownloadWithContext(context.Background(), req)
    30  }
    31  
    32  func (s *Service) DownloadWithContext(ctx context.Context, req *DownloadRequest) error {
    33  	if err := req.Validate(); err != nil {
    34  		return err
    35  	}
    36  
    37  	client := sacloud.NewArchiveOp(s.caller)
    38  	resource, err := client.Read(ctx, req.Zone, req.ID)
    39  	if err != nil {
    40  		return fmt.Errorf("reading Archive[%s] failed: %s", req.ID, err)
    41  	}
    42  
    43  	if resource.Scope != types.Scopes.User {
    44  		return fmt.Errorf("Archive[%s] is not allowed to download", req.ID)
    45  	}
    46  
    47  	ftpServer, err := client.OpenFTP(ctx, req.Zone, req.ID, &sacloud.OpenFTPRequest{ChangePassword: true})
    48  	if err != nil {
    49  		return fmt.Errorf("requesting FTP server information failed: %s", err)
    50  	}
    51  
    52  	ftpsClient := ftps.NewClient(ftpServer.User, ftpServer.Password, ftpServer.HostName)
    53  	switch req.Path {
    54  	case "":
    55  		var out io.Writer = os.Stdout
    56  		if req.Writer != nil {
    57  			out = req.Writer
    58  		}
    59  		if err := ftpsClient.DownloadWriter(out); err != nil {
    60  			return fmt.Errorf("downloading via FTP failed: %s", err)
    61  		}
    62  	default:
    63  		if err := ftpsClient.Download(req.Path); err != nil {
    64  			return fmt.Errorf("downloading via FTP failed: %s", err)
    65  		}
    66  	}
    67  
    68  	// close
    69  	if err := client.CloseFTP(ctx, req.Zone, req.ID); err != nil {
    70  		return fmt.Errorf("closing FTP server failed: %s", err)
    71  	}
    72  	return nil
    73  }