Skip to content

Commit

Permalink
Use cheggaaa/pb.v1 to implement download progress bar
Browse files Browse the repository at this point in the history
Solves #2
  • Loading branch information
nishanthvijayan committed Mar 26, 2019
1 parent 12d2753 commit f17d591
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions nptel/nptel.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import (
"log"
"net/http"
"os"
"strconv"
"strings"

"github.com/PuerkitoBio/goquery"
pb "gopkg.in/cheggaaa/pb.v1"
)

const baseURL = "https://nptel.ac.in"
Expand Down Expand Up @@ -78,6 +80,22 @@ func ExtractLectureDownloadUrls(page io.Reader, format string) []string {
return urls
}

func ioCopyWithReporting(r io.Reader, w io.Writer, totalBytes int) error {
bar := pb.New(totalBytes).SetUnits(pb.U_BYTES)

bar.Format(" \u2580-- ")
bar.ShowSpeed = true

bar.Start()

barProxyReader := bar.NewProxyReader(r)
_, err := io.Copy(w, barProxyReader)

bar.Finish()

return err
}

// downloadFile saves the contents of url to destinationFilePath
func downloadFile(url string, destinationFilepath string) error {
resp, err := http.Get(url)
Expand All @@ -86,14 +104,15 @@ func downloadFile(url string, destinationFilepath string) error {
}
defer resp.Body.Close()

fileSize, _ := strconv.Atoi(resp.Header.Get("Content-Length"))

out, err := os.Create(destinationFilepath)
if err != nil {
return err
}
defer out.Close()

_, err = io.Copy(out, resp.Body)
return err
return ioCopyWithReporting(resp.Body, out, fileSize)
}

func escapeSpaceInURL(url string) string {
Expand Down

0 comments on commit f17d591

Please sign in to comment.