|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "github.com/linuxsuren/http-downloader/pkg" |
| 6 | + extver "github.com/linuxsuren/cobra-extension/version" |
| 7 | + "github.com/spf13/cobra" |
| 8 | + "io/ioutil" |
| 9 | + "net/http" |
| 10 | + "os" |
| 11 | + "strconv" |
| 12 | + "strings" |
| 13 | + "sync" |
| 14 | +) |
| 15 | + |
| 16 | +// NewRoot returns the root command |
| 17 | +func NewRoot() (cmd *cobra.Command) { |
| 18 | + opt := &downloadOption{} |
| 19 | + cmd = &cobra.Command{ |
| 20 | + Use: "hd", |
| 21 | + Short: "HTTP download tool", |
| 22 | + PreRunE: opt.preRunE, |
| 23 | + RunE: opt.runE, |
| 24 | + } |
| 25 | + |
| 26 | + // set flags |
| 27 | + flags := cmd.Flags() |
| 28 | + flags.StringVarP(&opt.Output, "output", "o", "", "Write output to <file> instead of stdout.") |
| 29 | + flags.BoolVarP(&opt.ShowProgress, "show-progress", "", true, "If show the progress of download") |
| 30 | + flags.Int64VarP(&opt.ContinueAt, "continue-at", "", -1, "ContinueAt") |
| 31 | + flags.IntVarP(&opt.Thread, "thread", "", 0, "") |
| 32 | + |
| 33 | + cmd.AddCommand( |
| 34 | + extver.NewVersionCmd("linuxsuren", "http-downloader", "hd", nil)) |
| 35 | + return |
| 36 | +} |
| 37 | + |
| 38 | +type downloadOption struct { |
| 39 | + URL string |
| 40 | + Output string |
| 41 | + ShowProgress bool |
| 42 | + |
| 43 | + ContinueAt int64 |
| 44 | + |
| 45 | + Thread int |
| 46 | +} |
| 47 | + |
| 48 | +func (o *downloadOption) preRunE(cmd *cobra.Command, args []string) (err error) { |
| 49 | + if len(args) <= 0 { |
| 50 | + return fmt.Errorf("no URL provided") |
| 51 | + } |
| 52 | + |
| 53 | + url := args[0] |
| 54 | + if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") { |
| 55 | + err = fmt.Errorf("only http:// or https:// supported") |
| 56 | + } |
| 57 | + o.URL = url |
| 58 | + |
| 59 | + if o.Output == "" { |
| 60 | + err = fmt.Errorf("output cannot be empty") |
| 61 | + } |
| 62 | + return |
| 63 | +} |
| 64 | + |
| 65 | +func (o *downloadOption) runE(cmd *cobra.Command, args []string) (err error) { |
| 66 | + if o.Thread <= 1 { |
| 67 | + err = o.download(o.Output, o.ContinueAt, 0) |
| 68 | + } else { |
| 69 | + // get the total size of the target file |
| 70 | + var total int64 |
| 71 | + var rangeSupport bool |
| 72 | + if total, rangeSupport, err = o.detectSize(o.Output); err != nil { |
| 73 | + return |
| 74 | + } |
| 75 | + |
| 76 | + if rangeSupport { |
| 77 | + unit := total / int64(o.Thread) |
| 78 | + offset := total - unit*int64(o.Thread) |
| 79 | + var wg sync.WaitGroup |
| 80 | + |
| 81 | + cmd.Printf("start to download with %d threads, size: %d, unit: %d\n", o.Thread, total, unit) |
| 82 | + for i := 0; i < o.Thread; i++ { |
| 83 | + wg.Add(1) |
| 84 | + go func(index int, wg *sync.WaitGroup) { |
| 85 | + defer wg.Done() |
| 86 | + |
| 87 | + end := unit*int64(index+1) - 1 |
| 88 | + if index == o.Thread-1 { |
| 89 | + // this is the last part |
| 90 | + end += offset |
| 91 | + } |
| 92 | + start := unit * int64(index) |
| 93 | + |
| 94 | + if downloadErr := o.download(fmt.Sprintf("%s-%d", o.Output, index), start, end); downloadErr != nil { |
| 95 | + cmd.PrintErrln(downloadErr) |
| 96 | + } |
| 97 | + }(i, &wg) |
| 98 | + } |
| 99 | + |
| 100 | + wg.Wait() |
| 101 | + |
| 102 | + // concat all these partial files |
| 103 | + var f *os.File |
| 104 | + if f, err = os.OpenFile(o.Output, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); err == nil { |
| 105 | + defer func() { |
| 106 | + _ = f.Close() |
| 107 | + }() |
| 108 | + |
| 109 | + for i := 0; i < o.Thread; i++ { |
| 110 | + partFile := fmt.Sprintf("%s-%d", o.Output, i) |
| 111 | + if data, ferr := ioutil.ReadFile(partFile); ferr == nil { |
| 112 | + if _, err = f.Write(data); err != nil { |
| 113 | + err = fmt.Errorf("failed to write file: '%s'", partFile) |
| 114 | + break |
| 115 | + } else { |
| 116 | + _ = os.RemoveAll(partFile) |
| 117 | + } |
| 118 | + } else { |
| 119 | + err = fmt.Errorf("failed to read file: '%s'", partFile) |
| 120 | + break |
| 121 | + } |
| 122 | + } |
| 123 | + } |
| 124 | + } else { |
| 125 | + cmd.Println("cannot download it using multiple threads, failed to one") |
| 126 | + err = o.download(o.Output, o.ContinueAt, 0) |
| 127 | + } |
| 128 | + } |
| 129 | + return |
| 130 | +} |
| 131 | + |
| 132 | +func (o *downloadOption) detectSize(output string) (total int64, rangeSupport bool, err error) { |
| 133 | + downloader := pkg.HTTPDownloader{ |
| 134 | + TargetFilePath: output, |
| 135 | + URL: o.URL, |
| 136 | + ShowProgress: o.ShowProgress, |
| 137 | + } |
| 138 | + |
| 139 | + var detectOffset int64 |
| 140 | + var lenErr error |
| 141 | + |
| 142 | + detectOffset = 2 |
| 143 | + downloader.Header = make(map[string]string, 1) |
| 144 | + downloader.Header["Range"] = fmt.Sprintf("bytes=%d-", detectOffset) |
| 145 | + |
| 146 | + downloader.PreStart = func(resp *http.Response) bool { |
| 147 | + rangeSupport = resp.StatusCode == http.StatusPartialContent |
| 148 | + contentLen := resp.Header.Get("Content-Length") |
| 149 | + if total, lenErr = strconv.ParseInt(contentLen, 10, 0); lenErr == nil { |
| 150 | + total += detectOffset |
| 151 | + } |
| 152 | + // always return false because we just want to get the header from response |
| 153 | + return false |
| 154 | + } |
| 155 | + |
| 156 | + if err = downloader.DownloadFile(); err != nil || lenErr != nil { |
| 157 | + err = fmt.Errorf("cannot download from %s, response error: %v, content length error: %v", o.URL, err, lenErr) |
| 158 | + } |
| 159 | + return |
| 160 | +} |
| 161 | + |
| 162 | +func (o *downloadOption) download(output string, continueAt, end int64) (err error) { |
| 163 | + downloader := pkg.HTTPDownloader{ |
| 164 | + TargetFilePath: output, |
| 165 | + URL: o.URL, |
| 166 | + ShowProgress: o.ShowProgress, |
| 167 | + } |
| 168 | + |
| 169 | + if continueAt >= 0 { |
| 170 | + downloader.Header = make(map[string]string, 1) |
| 171 | + |
| 172 | + //fmt.Println("range", continueAt, end) |
| 173 | + if end > continueAt { |
| 174 | + downloader.Header["Range"] = fmt.Sprintf("bytes=%d-%d", continueAt, end) |
| 175 | + } else { |
| 176 | + downloader.Header["Range"] = fmt.Sprintf("bytes=%d-", continueAt) |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | + if err = downloader.DownloadFile(); err != nil { |
| 181 | + err = fmt.Errorf("cannot download from %s, error: %v", o.URL, err) |
| 182 | + } |
| 183 | + return |
| 184 | +} |
0 commit comments