-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.go
184 lines (155 loc) · 4.45 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package main
import (
"bufio"
"context"
"fmt"
"io"
"log"
"net/url"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"github.com/ishanjain28/pluto/pluto"
humanize "github.com/dustin/go-humanize"
flag "github.com/jessevdk/go-flags"
)
var Version string
var Build string
var options struct {
Verbose bool `long:"verbose" description:"Enable Verbose Mode"`
Connections uint `short:"n" long:"connections" default:"1" description:"Number of concurrent connections"`
Name string `long:"name" description:"Path or Name of save file"`
LoadFromFile string `short:"f" long:"load-from-file" description:"Load URLs from a file"`
Headers []string `short:"H" long:"headers" description:"Headers to send with each request. Useful if a server requires some information in headers"`
Version bool `short:"v" long:"version" description:"Print Pluto Version and exit"`
urls []string
}
func parseArgs() error {
args, err := flag.ParseArgs(&options, os.Args)
if err != nil {
return fmt.Errorf("error parsing args: %v", err)
}
args = args[1:]
options.urls = []string{}
if options.LoadFromFile != "" {
f, err := os.OpenFile(options.LoadFromFile, os.O_RDONLY, 0x444)
if err != nil {
return fmt.Errorf("error in opening file %s: %v", options.LoadFromFile, err)
}
defer f.Close()
reader := bufio.NewReader(f)
for {
str, err := reader.ReadString('\n')
if err != nil {
if err == io.EOF {
break
}
return fmt.Errorf("error in reading file: %v", err)
}
u := str[:len(str)-1]
if u != "" {
options.urls = append(options.urls, u)
}
}
fmt.Printf("queued %d urls\n", len(options.urls))
} else {
for _, v := range args {
if v != "" && v != "\n" {
options.urls = append(options.urls, v)
}
}
}
if len(options.urls) == 0 {
return fmt.Errorf("nothing to do. Please pass some url to fetch")
}
if options.Connections == 0 {
return fmt.Errorf("connections should be > 0")
}
if len(options.urls) > 1 && options.Name != "" {
return fmt.Errorf("it is not possible to specify 'name' with more than one url")
}
return nil
}
func main() {
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
ctx, cancel := context.WithCancel(context.Background())
go func() {
<-sig
fmt.Printf("Interrupt Detected, Shutting Down.")
cancel()
}()
err := parseArgs()
if err != nil {
log.Fatalf("error parsing args: %v", err)
}
if options.Version {
fmt.Println("Pluto - A Fast Multipart File Downloader")
fmt.Printf("Version: %s\n", Version)
fmt.Printf("Build: %s\n", Build)
return
}
UrlLoop:
for _, v := range options.urls {
select {
case <-ctx.Done():
break UrlLoop
default:
}
up, err := url.Parse(v)
if err != nil {
log.Printf("Invalid URL: %v", err)
continue
}
p, err := pluto.New(up, options.Headers, options.Connections, options.Verbose)
if err != nil {
log.Fatalf("error creating pluto instance for url %s: %v\n", v, err)
}
go func() {
if p.StatsChan == nil {
return
}
for {
select {
case <-p.Finished:
// Once download is finished, We don't need any data currently in channel.
for range p.StatsChan {
}
break
case v := <-p.StatsChan:
os.Stdout.WriteString(fmt.Sprintf("\r%.2f%% - %s/%s - %s/s\r", float64(v.Downloaded)/float64(v.Size)*100, humanize.IBytes(v.Downloaded), humanize.IBytes(v.Size), humanize.IBytes(v.Speed)))
os.Stdout.Sync()
}
}
}()
var fileName string
if options.Name != "" {
fileName = options.Name
} else if p.MetaData.Name != "" {
fileName = p.MetaData.Name
} else {
fileName = strings.Split(filepath.Base(up.String()), "?")[0]
}
fileName = strings.Replace(fileName, "/", "\\/", -1)
writer, err := os.Create(fileName)
if err != nil {
log.Fatalf("unable to create file %s: %v\n", fileName, err)
}
defer writer.Close()
if !p.MetaData.MultipartSupported && options.Connections > 1 {
fmt.Printf("Downloading %s(%s) with 1 connection(Multipart downloads not supported)\n", fileName, humanize.Bytes(p.MetaData.Size))
}
result, err := p.Download(ctx, writer)
if err != nil {
log.Printf("error downloading url %s: %v", v, err)
} else {
s := humanize.IBytes(result.Size)
htime := result.TimeTaken.String()
as := humanize.IBytes(uint64(result.AvgSpeed))
fmt.Printf("\nDownloaded %s in %s. Avg. Speed - %s/s\n", s, htime, as)
fmt.Printf("File saved in %s\n", result.FileName)
}
}
}