Skip to content

Commit

Permalink
feat(torrentfile): download file
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianLusina committed Jul 19, 2022
1 parent c7f35cb commit 09bb534
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions pkg/torrentfile/torrentfile.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package torrentfile

import (
"crypto/rand"
"net/http"
"net/url"
"os"
"strconv"
"time"

"github.com/brianlusina/tclient/internal/p2p"
"github.com/brianlusina/tclient/pkg/peers"
"github.com/jackpal/bencode-go"
)
Expand All @@ -28,6 +31,45 @@ type bencodeTrackerResp struct {
Peers string `bencode:"peers"`
}

// DownloadToFile downloads a torrent and writes it to a file
func (t *TorrentFile) DownloadToFile(path string) error {
var peerID [20]byte
_, err := rand.Read(peerID[:])
if err != nil {
return err
}

peers, err := t.requestPeers(peerID, Port)
if err != nil {
return err
}

torrent := p2p.Torrent{
Peers: peers,
PeerID: peerID,
InfoHash: t.InfoHash,
PieceHashes: t.PieceHashes,
PieceLength: t.PieceLength,
Length: t.Length,
Name: t.Name,
}
buf, err := torrent.Download()
if err != nil {
return err
}

outFile, err := os.Create(path)
if err != nil {
return err
}
defer outFile.Close()
_, err = outFile.Write(buf)
if err != nil {
return err
}
return nil
}

func (t *TorrentFile) buildTrackerUrl(peerId [20]byte, port uint16) (string, error) {
base, err := url.Parse(t.Announce)

Expand Down

0 comments on commit 09bb534

Please sign in to comment.