aboutsummaryrefslogtreecommitdiff
path: root/cmd/mybittorrent/main.go
blob: c460c354e4df240b5bb5a36702c225989751c6e4 (plain)
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
package main

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"

	bencode "github.com/jackpal/bencode-go" // Available if you need it!
)

func main() {
	command := os.Args[1]

	switch command {
	case "decode":
		bencodedValue := os.Args[2]
		decoded, err := bencode.Decode(strings.NewReader(bencodedValue))
		if err != nil {
			fmt.Println(err)
			return
		}

		jsonOutput, _ := json.Marshal(decoded)
		fmt.Println(string(jsonOutput))

	case "info":
		c := NewClient("00112233445566778899", 6881)
		tf, err := c.AddTorrentFile(os.Args[2])
		if err != nil {
			panic(err)
		}

		fmt.Printf("Tracker URL: %s\n", tf.Meta.Announce)
		fmt.Printf("Length: %d\n", tf.Meta.Info.Length)

		infoHash, err := tf.Meta.InfoHash()
		if err != nil {
			panic(err)
		}

		fmt.Printf("Info Hash: %x", infoHash)

		fmt.Printf("Piece Length: %d\n", tf.Meta.Info.PieceLength)
		fmt.Println("Piece Hashes:")

		for _, h := range tf.Meta.PieceHashes() {
			fmt.Printf("%x\n", h)
		}

	case "peers":
		c := NewClient("00112233445566778899", 6881)

		_, err := c.AddTorrentFile(os.Args[2])
		if err != nil {
			panic(err)
		}

		pr, err := c.GetPeers(os.Args[2])

		if err != nil {
			panic(err)
		}

		for _, peer := range pr.Peers {
			fmt.Println(peer)
		}

	default:
		fmt.Println("Unknown command: " + command)
		os.Exit(1)
	}
}