github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/cmd/swarm/upload.go (about)

     1  // Copyright 2016 The Spectrum Authors
     2  // This file is part of Spectrum.
     3  //
     4  // Spectrum is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // Spectrum is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU General Public License
    15  // along with Spectrum. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Command bzzup uploads files to the swarm HTTP API.
    18  package main
    19  
    20  import (
    21  	"errors"
    22  	"fmt"
    23  	"io"
    24  	"io/ioutil"
    25  	"mime"
    26  	"net/http"
    27  	"os"
    28  	"os/user"
    29  	"path"
    30  	"path/filepath"
    31  	"strings"
    32  
    33  	"github.com/SmartMeshFoundation/Spectrum/cmd/utils"
    34  	swarm "github.com/SmartMeshFoundation/Spectrum/swarm/api/client"
    35  	"gopkg.in/urfave/cli.v1"
    36  )
    37  
    38  func upload(ctx *cli.Context) {
    39  
    40  	args := ctx.Args()
    41  	var (
    42  		bzzapi       = strings.TrimRight(ctx.GlobalString(SwarmApiFlag.Name), "/")
    43  		recursive    = ctx.GlobalBool(SwarmRecursiveUploadFlag.Name)
    44  		wantManifest = ctx.GlobalBoolT(SwarmWantManifestFlag.Name)
    45  		defaultPath  = ctx.GlobalString(SwarmUploadDefaultPath.Name)
    46  		fromStdin    = ctx.GlobalBool(SwarmUpFromStdinFlag.Name)
    47  		mimeType     = ctx.GlobalString(SwarmUploadMimeType.Name)
    48  		client       = swarm.NewClient(bzzapi)
    49  		file         string
    50  	)
    51  
    52  	if len(args) != 1 {
    53  		if fromStdin {
    54  			tmp, err := ioutil.TempFile("", "swarm-stdin")
    55  			if err != nil {
    56  				utils.Fatalf("error create tempfile: %s", err)
    57  			}
    58  			defer os.Remove(tmp.Name())
    59  			n, err := io.Copy(tmp, os.Stdin)
    60  			if err != nil {
    61  				utils.Fatalf("error copying stdin to tempfile: %s", err)
    62  			} else if n == 0 {
    63  				utils.Fatalf("error reading from stdin: zero length")
    64  			}
    65  			file = tmp.Name()
    66  		} else {
    67  			utils.Fatalf("Need filename as the first and only argument")
    68  		}
    69  	} else {
    70  		file = expandPath(args[0])
    71  	}
    72  
    73  	if !wantManifest {
    74  		f, err := swarm.Open(file)
    75  		if err != nil {
    76  			utils.Fatalf("Error opening file: %s", err)
    77  		}
    78  		defer f.Close()
    79  		hash, err := client.UploadRaw(f, f.Size)
    80  		if err != nil {
    81  			utils.Fatalf("Upload failed: %s", err)
    82  		}
    83  		fmt.Println(hash)
    84  		return
    85  	}
    86  
    87  	stat, err := os.Stat(file)
    88  	if err != nil {
    89  		utils.Fatalf("Error opening file: %s", err)
    90  	}
    91  
    92  	// define a function which either uploads a directory or single file
    93  	// based on the type of the file being uploaded
    94  	var doUpload func() (hash string, err error)
    95  	if stat.IsDir() {
    96  		doUpload = func() (string, error) {
    97  			if !recursive {
    98  				return "", errors.New("Argument is a directory and recursive upload is disabled")
    99  			}
   100  			return client.UploadDirectory(file, defaultPath, "")
   101  		}
   102  	} else {
   103  		doUpload = func() (string, error) {
   104  			f, err := swarm.Open(file)
   105  			if err != nil {
   106  				return "", fmt.Errorf("error opening file: %s", err)
   107  			}
   108  			defer f.Close()
   109  			if mimeType == "" {
   110  				mimeType = detectMimeType(file)
   111  			}
   112  			f.ContentType = mimeType
   113  			return client.Upload(f, "")
   114  		}
   115  	}
   116  	hash, err := doUpload()
   117  	if err != nil {
   118  		utils.Fatalf("Upload failed: %s", err)
   119  	}
   120  	fmt.Println(hash)
   121  }
   122  
   123  // Expands a file path
   124  // 1. replace tilde with users home dir
   125  // 2. expands embedded environment variables
   126  // 3. cleans the path, e.g. /a/b/../c -> /a/c
   127  // Note, it has limitations, e.g. ~someuser/tmp will not be expanded
   128  func expandPath(p string) string {
   129  	if strings.HasPrefix(p, "~/") || strings.HasPrefix(p, "~\\") {
   130  		if home := homeDir(); home != "" {
   131  			p = home + p[1:]
   132  		}
   133  	}
   134  	return path.Clean(os.ExpandEnv(p))
   135  }
   136  
   137  func homeDir() string {
   138  	if home := os.Getenv("HOME"); home != "" {
   139  		return home
   140  	}
   141  	if usr, err := user.Current(); err == nil {
   142  		return usr.HomeDir
   143  	}
   144  	return ""
   145  }
   146  
   147  func detectMimeType(file string) string {
   148  	if ext := filepath.Ext(file); ext != "" {
   149  		return mime.TypeByExtension(ext)
   150  	}
   151  	f, err := os.Open(file)
   152  	if err != nil {
   153  		return ""
   154  	}
   155  	defer f.Close()
   156  	buf := make([]byte, 512)
   157  	if n, _ := f.Read(buf); n > 0 {
   158  		return http.DetectContentType(buf)
   159  	}
   160  	return ""
   161  }