Skip to content

Commit

Permalink
Added progress bar and banner
Browse files Browse the repository at this point in the history
  • Loading branch information
Harry-kp committed Aug 24, 2024
1 parent d48b92d commit 7b925f3
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 8 deletions.
33 changes: 26 additions & 7 deletions p2p/p2p.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import (
"bytes"
"crypto/sha1"
"fmt"
"log"
"runtime"
"time"

"github.com/Harry-kp/nebula/client"
"github.com/Harry-kp/nebula/logger"
"github.com/Harry-kp/nebula/message"
"github.com/Harry-kp/nebula/peers"
"github.com/k0kubun/go-ansi"
"github.com/schollz/progressbar/v3"
)

// MaxBlockSize is the largest number of bytes a request can ask for
Expand Down Expand Up @@ -120,11 +122,11 @@ func checkIntegrity(pw *pieceWork, data []byte) bool {
func (t *Torrent) downloadTorrentWorker(peer peers.Peer, workQueue chan *pieceWork, results chan *pieceResult) {
c, err := client.New(peer, t.InfoHash, t.PeerID)
if err != nil {
fmt.Printf("Could not able to handshake with %s. Disconnecting...\n", peer.IP)
logger.Printf("Could not able to handshake with %s. Disconnecting...\n", peer.IP)
return
}
defer c.Conn.Close()
log.Printf("Handshake with %s successful", peer.IP)
logger.Printf("Handshake with %s successful", peer.IP)

c.SendUnchoke()
c.SendInterested()
Expand All @@ -137,13 +139,13 @@ func (t *Torrent) downloadTorrentWorker(peer peers.Peer, workQueue chan *pieceWo

buf, err := attemptDownloadPiece(c, pw)
if err != nil {
log.Println("Error downloading piece", pw.index, "from", peer.IP, ":", err)
logger.Println("Error downloading piece", pw.index, "from", peer.IP, ":", err)
workQueue <- pw
return
}

if !checkIntegrity(pw, buf) {
log.Println("Piece failed integrity check", pw.index, "from", peer.IP)
logger.Println("Piece failed integrity check", pw.index, "from", peer.IP)
workQueue <- pw
continue
}
Expand All @@ -167,7 +169,7 @@ func (t *Torrent) calculatePieceSize(index int) int {
}

func (t *Torrent) Download() []byte {
log.Println("Starting download for", t.Name)
logger.Println("Starting download for", t.Name)
workQueue := make(chan *pieceWork, len(t.PieceHashes))
results := make(chan *pieceResult)
for index, hash := range t.PieceHashes {
Expand All @@ -180,16 +182,33 @@ func (t *Torrent) Download() []byte {
}

buf := make([]byte, t.Length)
bar := progressbar.NewOptions(t.Length,
progressbar.OptionEnableColorCodes(true),
progressbar.OptionSetWriter(ansi.NewAnsiStdout()),
progressbar.OptionShowBytes(true),
progressbar.OptionSetElapsedTime(false),
progressbar.OptionSetRenderBlankState(true),
progressbar.OptionSetDescription("["+t.Name+"]"),
progressbar.OptionShowElapsedTimeOnFinish(),
progressbar.OptionSetTheme(progressbar.Theme{
Saucer: "[green]=[reset]",
SaucerHead: "[green]>[reset]",
SaucerPadding: " ",
BarStart: "[",
BarEnd: "]",
}))
donePieces := 0
for donePieces < len(t.PieceHashes) {
res := <-results
begin, end := t.calculateBoundsForPiece(res.index)
copy(buf[begin:end], res.buf)
donePieces++
bar.Add(end - begin)
percent := float64(donePieces) / float64(len(t.PieceHashes)) * 100
numWorkers := runtime.NumGoroutine() - 1 // subtract 1 for main thread
log.Printf("(%0.2f%%) Downloaded piece #%d from %d peers\n", percent, res.index, numWorkers)
logger.Printf("(%0.2f%%) Downloaded piece #%d from %d peers\n", percent, res.index, numWorkers)
}
close(workQueue)
fmt.Println()
return buf
}
2 changes: 1 addition & 1 deletion torrentfile/tracker.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func (tf *TorrentFile) fetchPeers(peer_id [20]byte, port uint16) ([]peers.Peer,
case "udp://":
return nil, fmt.Errorf("UDP tracker not supported yet.We are working on it")
default:
return nil, fmt.Errorf("Unsupported protocol")
return nil, fmt.Errorf("Currently, we only support HTTP trackers protocol. Please use torrent with http:// announce URL. We are working on it")
}
}

Expand Down
18 changes: 18 additions & 0 deletions utils/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package utils

import "fmt"

func Banner() {
green := "\033[32m" // ANSI escape code for green text
reset := "\033[0m" // ANSI escape code to reset color

fmt.Println(green + ` ======================================
_ _ _ _
| \ | | | | | |
| \| | ___ | |__ _ _ | | __ _
| . ` + "`" + ` | / _ \| '_ \ | | | || | / _` + "`" + ` |
| |\ || __/| |_) || |_| || || (_| |
|_| \_| \___||_.__/ \__,_||_| \__,_|
======================================
` + reset)
}

0 comments on commit 7b925f3

Please sign in to comment.