feat: cli

This commit is contained in:
liwei committed 2021-03-25 17:30:40 +08:00
1 parent caf9bf265b
commit 359f28bb1f
12 files changed
+209 -97

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
)
type args struct {
url string
connections *int
dir *string
}
func parse() *args {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
panic(err)
}
var args args
args.connections = flag.Int("C", 16, "Concurrent connections.")
args.dir = flag.String("D", dir, "Save directory.")
flag.Parse()
t := flag.Args()
if len(t) > 0 {
args.url = t[0]
} else {
gPrintln("missing url parameter")
gPrintln("try 'gopeed -h' for more information")
os.Exit(1)
}
return &args
}
func gPrint(msg string) {
fmt.Print("gopeed: " + msg)
}
func gPrintln(msg string) {
gPrint(msg + "\n")
}
+64
View File
@@ -0,0 +1,64 @@
package main
import (
"fmt"
"github.com/monkeyWie/gopeed-core/download"
"github.com/monkeyWie/gopeed-core/download/base"
"github.com/monkeyWie/gopeed-core/download/http"
"github.com/monkeyWie/gopeed-core/util"
"path/filepath"
"sync"
)
const progressWidth = 20
func main() {
args := parse()
downloader := download.NewDownloader(http.FetcherBuilder)
res, err := downloader.Resolve(&base.Request{
URL: args.url,
})
if err != nil {
panic(err)
}
err = downloader.Create(res, &base.Options{
Path: *args.dir,
Connections: *args.connections,
})
if err != nil {
panic(err)
}
var wg sync.WaitGroup
wg.Add(1)
downloader.Listener(func(taskInfo *download.TaskInfo, eventKey base.EventKey) {
if eventKey == base.EventKeyProgress {
printProgress(taskInfo, "downloading...")
}
if eventKey == base.EventKeyDone {
printProgress(taskInfo, "complete")
wg.Done()
}
})
wg.Wait()
fmt.Println()
gPrint("saving file " + filepath.Join(*args.dir, res.Files[0].Name))
}
func printProgress(taskInfo *download.TaskInfo, title string) {
rate := float64(taskInfo.Progress.Downloaded) / float64(taskInfo.Res.TotalSize)
completeWidth := int(progressWidth * rate)
speed := util.ByteFmt(taskInfo.Progress.Speed)
totalSize := util.ByteFmt(taskInfo.Res.TotalSize)
fmt.Printf("\r%s [", title)
for i := 0; i < progressWidth; i++ {
if i < completeWidth {
fmt.Print("■")
} else {
fmt.Print("□")
}
}
fmt.Printf("] %.1f%% %s/s %s", rate*100, speed, totalSize)
}