diff --git a/README.md b/README.md index b703e5c..b7ca88c 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Minimal BitTorrent client skeleton in Go. go run ./cmd/torrent-client ``` -App starts a local GUI in your browser (auto-opens on macOS/Linux/Windows). +App starts a native desktop GUI window. ## Current features @@ -17,11 +17,14 @@ App starts a local GUI in your browser (auto-opens on macOS/Linux/Windows). - Single-file and multi-file torrents - Send tracker announce requests via HTTP(S) and UDP trackers - Parse compact peer list -- Browser GUI for loading torrents by path or file upload -- Show loaded torrent status and files in the GUI +- Multi-tracker fallback (including public trackers) +- Native GUI for loading torrents by path and browsing files +- Show tracker states, discovered peers, and torrent file list in the GUI ## Build (macOS/Linux/Windows) ```bash ./scripts/build-all.sh ``` + +Note: for non-host targets with native GUI, cross C toolchains are required; unsupported targets are skipped. diff --git a/dist/ztorrent-darwin-amd64 b/dist/ztorrent-darwin-amd64 index f4d34dc..4c1770a 100755 Binary files a/dist/ztorrent-darwin-amd64 and b/dist/ztorrent-darwin-amd64 differ diff --git a/dist/ztorrent-darwin-arm64 b/dist/ztorrent-darwin-arm64 index f89622e..140a88a 100755 Binary files a/dist/ztorrent-darwin-arm64 and b/dist/ztorrent-darwin-arm64 differ diff --git a/dist/ztorrent-linux-amd64 b/dist/ztorrent-linux-amd64 deleted file mode 100755 index 1387719..0000000 Binary files a/dist/ztorrent-linux-amd64 and /dev/null differ diff --git a/dist/ztorrent-linux-arm64 b/dist/ztorrent-linux-arm64 deleted file mode 100755 index 69641cc..0000000 Binary files a/dist/ztorrent-linux-arm64 and /dev/null differ diff --git a/dist/ztorrent-windows-amd64.exe b/dist/ztorrent-windows-amd64.exe deleted file mode 100755 index bee72c3..0000000 Binary files a/dist/ztorrent-windows-amd64.exe and /dev/null differ diff --git a/go.mod b/go.mod index 3ee0634..3744ab1 100644 --- a/go.mod +++ b/go.mod @@ -3,3 +3,39 @@ module github.com/veggiedefender/torrent-client go 1.22 require github.com/jackpal/bencode-go v1.0.2 + +require ( + fyne.io/fyne/v2 v2.7.3 + fyne.io/systray v1.12.0 // indirect + github.com/BurntSushi/toml v1.5.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/fredbi/uri v1.1.1 // indirect + github.com/fsnotify/fsnotify v1.9.0 // indirect + github.com/fyne-io/gl-js v0.2.0 // indirect + github.com/fyne-io/glfw-js v0.3.0 // indirect + github.com/fyne-io/image v0.1.1 // indirect + github.com/fyne-io/oksvg v0.2.0 // indirect + github.com/go-gl/gl v0.0.0-20231021071112-07e5d0ea2e71 // indirect + github.com/go-gl/glfw/v3.3/glfw v0.0.0-20240506104042-037f3cc74f2a // indirect + github.com/go-text/render v0.2.0 // indirect + github.com/go-text/typesetting v0.3.3 // indirect + github.com/godbus/dbus/v5 v5.1.0 // indirect + github.com/hack-pad/go-indexeddb v0.3.2 // indirect + github.com/hack-pad/safejs v0.1.0 // indirect + github.com/jeandeaual/go-locale v0.0.0-20250612000132-0ef82f21eade // indirect + github.com/jsummers/gobmp v0.0.0-20230614200233-a9de23ed2e25 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect + github.com/nicksnyder/go-i18n/v2 v2.5.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/rymdport/portal v0.4.2 // indirect + github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c // indirect + github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef // indirect + github.com/stretchr/testify v1.11.1 // indirect + github.com/yuin/goldmark v1.7.8 // indirect + golang.org/x/image v0.24.0 // indirect + golang.org/x/net v0.35.0 // indirect + golang.org/x/sys v0.30.0 // indirect + golang.org/x/text v0.22.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum index 3dc9f35..c84dd24 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,82 @@ +fyne.io/fyne/v2 v2.7.3 h1:xBT/iYbdnNHONWO38fZMBrVBiJG8rV/Jypmy4tVfRWE= +fyne.io/fyne/v2 v2.7.3/go.mod h1:gu+dlIcZWSzKZmnrY8Fbnj2Hirabv2ek+AKsfQ2bBlw= +fyne.io/systray v1.12.0 h1:CA1Kk0e2zwFlxtc02L3QFSiIbxJ/P0n582YrZHT7aTM= +fyne.io/systray v1.12.0/go.mod h1:RVwqP9nYMo7h5zViCBHri2FgjXF7H2cub7MAq4NSoLs= +github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg= +github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/felixge/fgprof v0.9.3 h1:VvyZxILNuCiUCSXtPtYmmtGvb65nqXh2QFWc0Wpf2/g= +github.com/felixge/fgprof v0.9.3/go.mod h1:RdbpDgzqYVh/T9fPELJyV7EYJuHB55UTEULNun8eiPw= +github.com/fredbi/uri v1.1.1 h1:xZHJC08GZNIUhbP5ImTHnt5Ya0T8FI2VAwI/37kh2Ko= +github.com/fredbi/uri v1.1.1/go.mod h1:4+DZQ5zBjEwQCDmXW5JdIjz0PUA+yJbvtBv+u+adr5o= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/fyne-io/gl-js v0.2.0 h1:+EXMLVEa18EfkXBVKhifYB6OGs3HwKO3lUElA0LlAjs= +github.com/fyne-io/gl-js v0.2.0/go.mod h1:ZcepK8vmOYLu96JoxbCKJy2ybr+g1pTnaBDdl7c3ajI= +github.com/fyne-io/glfw-js v0.3.0 h1:d8k2+Y7l+zy2pc7wlGRyPfTgZoqDf3AI4G+2zOWhWUk= +github.com/fyne-io/glfw-js v0.3.0/go.mod h1:Ri6te7rdZtBgBpxLW19uBpp3Dl6K9K/bRaYdJ22G8Jk= +github.com/fyne-io/image v0.1.1 h1:WH0z4H7qfvNUw5l4p3bC1q70sa5+YWVt6HCj7y4VNyA= +github.com/fyne-io/image v0.1.1/go.mod h1:xrfYBh6yspc+KjkgdZU/ifUC9sPA5Iv7WYUBzQKK7JM= +github.com/fyne-io/oksvg v0.2.0 h1:mxcGU2dx6nwjJsSA9PCYZDuoAcsZ/OuJlvg/Q9Njfo8= +github.com/fyne-io/oksvg v0.2.0/go.mod h1:dJ9oEkPiWhnTFNCmRgEze+YNprJF7YRbpjgpWS4kzoI= +github.com/go-gl/gl v0.0.0-20231021071112-07e5d0ea2e71 h1:5BVwOaUSBTlVZowGO6VZGw2H/zl9nrd3eCZfYV+NfQA= +github.com/go-gl/gl v0.0.0-20231021071112-07e5d0ea2e71/go.mod h1:9YTyiznxEY1fVinfM7RvRcjRHbw2xLBJ3AAGIT0I4Nw= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20240506104042-037f3cc74f2a h1:vxnBhFDDT+xzxf1jTJKMKZw3H0swfWk9RpWbBbDK5+0= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20240506104042-037f3cc74f2a/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-text/render v0.2.0 h1:LBYoTmp5jYiJ4NPqDc2pz17MLmA3wHw1dZSVGcOdeAc= +github.com/go-text/render v0.2.0/go.mod h1:CkiqfukRGKJA5vZZISkjSYrcdtgKQWRa2HIzvwNN5SU= +github.com/go-text/typesetting v0.3.3 h1:ihGNJU9KzdK2QRDy1Bm7FT5RFQoYb+3n3EIhI/4eaQc= +github.com/go-text/typesetting v0.3.3/go.mod h1:vIRUT25mLQaSh4C8H/lIsKppQz/Gdb8Pu/tNwpi52ts= +github.com/go-text/typesetting-utils v0.0.0-20250618110550-c820a94c77b8 h1:4KCscI9qYWMGTuz6BpJtbUSRzcBrUSSE0ENMJbNSrFs= +github.com/go-text/typesetting-utils v0.0.0-20250618110550-c820a94c77b8/go.mod h1:3/62I4La/HBRX9TcTpBj4eipLiwzf+vhI+7whTc9V7o= +github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= +github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/google/pprof v0.0.0-20211214055906-6f57359322fd h1:1FjCyPC+syAzJ5/2S8fqdZK1R22vvA0J7JZKcuOIQ7Y= +github.com/google/pprof v0.0.0-20211214055906-6f57359322fd/go.mod h1:KgnwoLYCZ8IQu3XUZ8Nc/bM9CCZFOyjUNOSygVozoDg= +github.com/hack-pad/go-indexeddb v0.3.2 h1:DTqeJJYc1usa45Q5r52t01KhvlSN02+Oq+tQbSBI91A= +github.com/hack-pad/go-indexeddb v0.3.2/go.mod h1:QvfTevpDVlkfomY498LhstjwbPW6QC4VC/lxYb0Kom0= +github.com/hack-pad/safejs v0.1.0 h1:qPS6vjreAqh2amUqj4WNG1zIw7qlRQJ9K10eDKMCnE8= +github.com/hack-pad/safejs v0.1.0/go.mod h1:HdS+bKF1NrE72VoXZeWzxFOVQVUSqZJAG0xNCnb+Tio= github.com/jackpal/bencode-go v1.0.2 h1:LcCNfZ344u0LpBPOZNjpCLps/wUOuN4r87Fy9+5yU8g= github.com/jackpal/bencode-go v1.0.2/go.mod h1:6jI9mUjO3GQbZti3JizEfxTzRfWOM8oBBcwbwlTfceI= +github.com/jeandeaual/go-locale v0.0.0-20250612000132-0ef82f21eade h1:FmusiCI1wHw+XQbvL9M+1r/C3SPqKrmBaIOYwVfQoDE= +github.com/jeandeaual/go-locale v0.0.0-20250612000132-0ef82f21eade/go.mod h1:ZDXo8KHryOWSIqnsb/CiDq7hQUYryCgdVnxbj8tDG7o= +github.com/jsummers/gobmp v0.0.0-20230614200233-a9de23ed2e25 h1:YLvr1eE6cdCqjOe972w/cYF+FjW34v27+9Vo5106B4M= +github.com/jsummers/gobmp v0.0.0-20230614200233-a9de23ed2e25/go.mod h1:kLgvv7o6UM+0QSf0QjAse3wReFDsb9qbZJdfexWlrQw= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ= +github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8= +github.com/nicksnyder/go-i18n/v2 v2.5.1 h1:IxtPxYsR9Gp60cGXjfuR/llTqV8aYMsC472zD0D1vHk= +github.com/nicksnyder/go-i18n/v2 v2.5.1/go.mod h1:DrhgsSDZxoAfvVrBVLXoxZn/pN5TXqaDbq7ju94viiQ= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/pkg/profile v1.7.0 h1:hnbDkaNWPCLMO9wGLdBFTIZvzDrDfBM2072E1S9gJkA= +github.com/pkg/profile v1.7.0/go.mod h1:8Uer0jas47ZQMJ7VD+OHknK4YDY07LPUC6dEvqDjvNo= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rymdport/portal v0.4.2 h1:7jKRSemwlTyVHHrTGgQg7gmNPJs88xkbKcIL3NlcmSU= +github.com/rymdport/portal v0.4.2/go.mod h1:kFF4jslnJ8pD5uCi17brj/ODlfIidOxlgUDTO5ncnC4= +github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c h1:km8GpoQut05eY3GiYWEedbTT0qnSxrCjsVbb7yKY1KE= +github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c/go.mod h1:cNQ3dwVJtS5Hmnjxy6AgTPd0Inb3pW05ftPSX7NZO7Q= +github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef h1:Ch6Q+AZUxDBCVqdkI8FSpFyZDtCVBc2VmejdNrm5rRQ= +github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef/go.mod h1:nXTWP6+gD5+LUJ8krVhhoeHjvHTutPxMYl5SvkcnJNE= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic= +github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= +golang.org/x/image v0.24.0 h1:AN7zRgVsbvmTfNyqIbbOraYL8mSwcKncEj8ofjgzcMQ= +golang.org/x/image v0.24.0/go.mod h1:4b/ITuLfqYq1hqZcjofwctIhi7sZh2WaCjvsBNjjya8= +golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8= +golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk= +golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= +golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= +golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/torrent/engine.go b/internal/torrent/engine.go index 620387e..4229d4b 100644 --- a/internal/torrent/engine.go +++ b/internal/torrent/engine.go @@ -3,6 +3,9 @@ package torrent import ( "context" "crypto/rand" + "errors" + "fmt" + "net" "sync" "time" @@ -11,12 +14,14 @@ import ( ) type Engine struct { - mu sync.RWMutex - torrent *torrentfile.TorrentFile - peers []tracker.Peer - peerID [20]byte - cancel context.CancelFunc - lastErr error + mu sync.RWMutex + torrent *torrentfile.TorrentFile + peers []PeerStatus + trackers []TrackerStatus + peerID [20]byte + cancel context.CancelFunc + lastErr error + phase string } type Status struct { @@ -28,48 +33,85 @@ type Status struct { Files []torrentfile.File Announce string PeerCount int + Peers []PeerStatus + Trackers []TrackerStatus PeerID string Progress float64 + Phase string LastError string } +type PeerStatus struct { + Address string + Port uint16 + Source string +} + +type TrackerStatus struct { + URL string + State string + PeerCount int + Error string +} + func NewEngine() *Engine { return &Engine{ peerID: generatePeerID(), + phase: "idle", } } func (e *Engine) LoadTorrent(path string) error { - + e.setPhase("loading_metadata") tf, err := torrentfile.Open(path) if err != nil { e.setError(err) + e.setPhase("failed") return err } - ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) e.swapCancel(cancel) defer e.clearCancel() - peers, err := tracker.GetPeers(ctx, tf, tracker.AnnounceOptions{ - PeerID: e.peerID, - Port: 6881, + e.setPhase("querying_trackers") + peers, trackerStatuses := e.queryTrackers(ctx, tf, tracker.AnnounceOptions{ + PeerID: e.peerID, + Port: 6881, + NumWant: 200, + Timeout: 6 * time.Second, }) - if err != nil { - e.mu.Lock() - e.torrent = tf - e.peers = nil - e.lastErr = err - e.mu.Unlock() - return err + + var finalErr error + if len(peers) == 0 { + if err := firstTrackerError(trackerStatuses); err != nil { + finalErr = fmt.Errorf("no peers found: %w", err) + } else { + finalErr = fmt.Errorf("no peers found via %d trackers", len(trackerStatuses)) + } } e.mu.Lock() e.torrent = tf e.peers = peers - e.lastErr = nil + e.trackers = trackerStatuses + e.lastErr = finalErr + if len(peers) > 0 { + e.phase = "ready" + } else { + e.phase = "waiting_peers" + } e.mu.Unlock() + if finalErr != nil { + e.mu.Lock() + if e.phase == "waiting_peers" { + e.phase = "tracker_errors" + } + e.mu.Unlock() + return finalErr + } + return nil } @@ -83,7 +125,22 @@ func (e *Engine) Stop() { } func (e *Engine) Progress() float64 { - return 0 + e.mu.RLock() + defer e.mu.RUnlock() + switch e.phase { + case "idle": + return 0 + case "loading_metadata": + return 0.1 + case "querying_trackers": + return 0.25 + case "ready": + return 0.4 + case "waiting_peers", "tracker_errors": + return 0.3 + default: + return 0 + } } func (e *Engine) Status() Status { @@ -94,7 +151,10 @@ func (e *Engine) Status() Status { Loaded: e.torrent != nil, PeerCount: len(e.peers), PeerID: string(e.peerID[:]), - Progress: e.Progress(), + Progress: e.progressUnsafe(), + Phase: e.phase, + Peers: append([]PeerStatus(nil), e.peers...), + Trackers: append([]TrackerStatus(nil), e.trackers...), } if e.torrent != nil { status.Name = e.torrent.Name @@ -111,12 +171,161 @@ func (e *Engine) Status() Status { return status } +func (e *Engine) queryTrackers(ctx context.Context, tf *torrentfile.TorrentFile, opts tracker.AnnounceOptions) ([]PeerStatus, []TrackerStatus) { + trackers := collectTrackersToTry(tf) + peerMap := make(map[string]PeerStatus) + statuses := make([]TrackerStatus, 0, len(trackers)) + + for _, announce := range trackers { + perTrackerCtx, cancel := context.WithTimeout(ctx, opts.Timeout) + peers, err := tracker.GetPeersFromURL(perTrackerCtx, announce, tf, opts) + cancel() + + st := TrackerStatus{ + URL: announce, + } + if err != nil { + st.State = "error" + st.Error = err.Error() + statuses = append(statuses, st) + continue + } + + if len(peers) == 0 { + st.State = "empty" + } else { + st.State = "ok" + st.PeerCount = len(peers) + } + statuses = append(statuses, st) + + for _, peer := range peers { + addPeer(peerMap, peer, announce) + } + } + + peerList := make([]PeerStatus, 0, len(peerMap)) + for _, peer := range peerMap { + peerList = append(peerList, peer) + } + + return peerList, statuses +} + +func addPeer(peerMap map[string]PeerStatus, peer tracker.Peer, source string) { + key := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port)) + if _, exists := peerMap[key]; exists { + return + } + peerMap[key] = PeerStatus{ + Address: peer.IP.String(), + Port: peer.Port, + Source: source, + } +} + +func collectTrackersToTry(tf *torrentfile.TorrentFile) []string { + const fallbackTrackers = ` +udp://open.stealth.si:80/announce +udp://tracker.opentrackr.org:1337/announce +udp://tracker.openbittorrent.com:6969/announce +udp://tracker.torrent.eu.org:451/announce +https://tracker.opentrackr.org:443/announce +http://tracker.opentrackr.org:1337/announce +` + + seen := make(map[string]struct{}) + list := make([]string, 0, len(tf.Trackers)+8) + + add := func(tr string) { + if tr == "" { + return + } + if _, ok := seen[tr]; ok { + return + } + seen[tr] = struct{}{} + list = append(list, tr) + } + + for _, tr := range tf.Trackers { + add(tr) + } + for _, tr := range splitLines(fallbackTrackers) { + add(tr) + } + + return list +} + +func splitLines(s string) []string { + lines := make([]string, 0) + current := make([]byte, 0, len(s)) + flush := func() { + if len(current) == 0 { + return + } + lines = append(lines, string(current)) + current = current[:0] + } + + for i := 0; i < len(s); i++ { + if s[i] == '\n' { + flush() + continue + } + if s[i] == '\r' { + continue + } + if s[i] == ' ' || s[i] == '\t' { + if len(current) == 0 { + continue + } + } + current = append(current, s[i]) + } + flush() + return lines +} + +func firstTrackerError(statuses []TrackerStatus) error { + for _, st := range statuses { + if st.State == "error" && st.Error != "" { + return errors.New(st.Error) + } + } + return nil +} + +func (e *Engine) progressUnsafe() float64 { + switch e.phase { + case "idle": + return 0 + case "loading_metadata": + return 0.1 + case "querying_trackers": + return 0.25 + case "ready": + return 0.4 + case "waiting_peers", "tracker_errors": + return 0.3 + default: + return 0 + } +} + func (e *Engine) setError(err error) { e.mu.Lock() defer e.mu.Unlock() e.lastErr = err } +func (e *Engine) setPhase(phase string) { + e.mu.Lock() + defer e.mu.Unlock() + e.phase = phase +} + func (e *Engine) swapCancel(cancel context.CancelFunc) { e.mu.Lock() defer e.mu.Unlock() diff --git a/internal/torrentfile/torrentfile.go b/internal/torrentfile/torrentfile.go index dee4a5f..e8f2d36 100644 --- a/internal/torrentfile/torrentfile.go +++ b/internal/torrentfile/torrentfile.go @@ -12,8 +12,9 @@ import ( ) type bencodeTorrent struct { - Announce string `bencode:"announce"` - Info bencodeInfo `bencode:"info"` + Announce string `bencode:"announce"` + AnnounceList [][]string `bencode:"announce-list"` + Info bencodeInfo `bencode:"info"` } type bencodeInfo struct { @@ -36,6 +37,7 @@ type File struct { type TorrentFile struct { Announce string + Trackers []string InfoHash [20]byte PieceHashes [][20]byte PieceLength int @@ -80,9 +82,11 @@ func Open(path string) (*TorrentFile, error) { } infoHash := sha1.Sum(infoBytes) + trackers := collectTrackers(bto.Announce, bto.AnnounceList) tf := TorrentFile{ Announce: bto.Announce, + Trackers: trackers, InfoHash: infoHash, PieceHashes: pieceHashes, PieceLength: bto.Info.PieceLength, @@ -330,3 +334,28 @@ func parseBencodeStringLength(data []byte, idx int) (int, int, error) { return length, idx + 1, nil } + +func collectTrackers(primary string, announceList [][]string) []string { + seen := make(map[string]struct{}) + trackers := make([]string, 0, 1+len(announceList)) + + add := func(tracker string) { + if tracker == "" { + return + } + if _, ok := seen[tracker]; ok { + return + } + seen[tracker] = struct{}{} + trackers = append(trackers, tracker) + } + + add(primary) + for _, tier := range announceList { + for _, tracker := range tier { + add(tracker) + } + } + + return trackers +} diff --git a/internal/torrentfile/torrentfile_test.go b/internal/torrentfile/torrentfile_test.go index c1d52b1..fee7067 100644 --- a/internal/torrentfile/torrentfile_test.go +++ b/internal/torrentfile/torrentfile_test.go @@ -27,6 +27,9 @@ func TestOpenParsesTorrentMetadata(t *testing.T) { if tf.Announce != "http://tracker" { t.Fatalf("unexpected announce: got %q", tf.Announce) } + if len(tf.Trackers) != 1 || tf.Trackers[0] != "http://tracker" { + t.Fatalf("unexpected trackers list: %#v", tf.Trackers) + } if tf.Name != "test.txt" { t.Fatalf("unexpected name: got %q", tf.Name) } @@ -112,6 +115,33 @@ func TestOpenRejectsPieceCountMismatch(t *testing.T) { } } +func TestOpenParsesAnnounceListAndDeduplicatesTrackers(t *testing.T) { + t.Parallel() + + info := "d6:lengthi5e4:name8:test.txt12:piece lengthi16384e6:pieces20:aaaaaaaaaaaaaaaaaaaae" + torrent := "d8:announce14:http://tracker13:announce-listll14:http://tracker17:udp://tracker.oneel17:udp://tracker.one17:udp://tracker.twoee4:info" + info + "e" + path := writeTempTorrent(t, torrent) + + tf, err := Open(path) + if err != nil { + t.Fatalf("Open returned error: %v", err) + } + + expected := []string{ + "http://tracker", + "udp://tracker.one", + "udp://tracker.two", + } + if len(tf.Trackers) != len(expected) { + t.Fatalf("unexpected trackers length: got %d want %d (%#v)", len(tf.Trackers), len(expected), tf.Trackers) + } + for i := range expected { + if tf.Trackers[i] != expected[i] { + t.Fatalf("unexpected tracker[%d]: got %q want %q", i, tf.Trackers[i], expected[i]) + } + } +} + func writeTempTorrent(t *testing.T, data string) string { t.Helper() diff --git a/internal/tracker/tracker.go b/internal/tracker/tracker.go index 44c4ea4..029d19b 100644 --- a/internal/tracker/tracker.go +++ b/internal/tracker/tracker.go @@ -45,18 +45,25 @@ func GetPeers(ctx context.Context, tf *torrentfile.TorrentFile, opts AnnounceOpt if tf == nil { return nil, errors.New("torrent metadata is nil") } + return GetPeersFromURL(ctx, tf.Announce, tf, opts) +} + +func GetPeersFromURL(ctx context.Context, announce string, tf *torrentfile.TorrentFile, opts AnnounceOptions) ([]Peer, error) { + if tf == nil { + return nil, errors.New("torrent metadata is nil") + } opts = normalizeOptions(opts) - announceURL, err := url.Parse(tf.Announce) + announceURL, err := url.Parse(announce) if err != nil { - return nil, fmt.Errorf("invalid tracker URL %q: %w", tf.Announce, err) + return nil, fmt.Errorf("invalid tracker URL %q: %w", announce, err) } switch announceURL.Scheme { case "http", "https": client := &http.Client{Timeout: opts.Timeout} - return getPeersWithClient(ctx, client, tf, opts) + return getPeersWithClient(ctx, client, announceURL, tf, opts) case "udp": return getPeersUDP(ctx, announceURL, tf, opts) default: @@ -64,23 +71,19 @@ func GetPeers(ctx context.Context, tf *torrentfile.TorrentFile, opts AnnounceOpt } } -func getPeersWithClient(ctx context.Context, client httpDoer, tf *torrentfile.TorrentFile, opts AnnounceOptions) ([]Peer, error) { - if tf == nil { - return nil, errors.New("torrent metadata is nil") - } - +func getPeersWithClient(ctx context.Context, client httpDoer, announceURL *url.URL, tf *torrentfile.TorrentFile, opts AnnounceOptions) ([]Peer, error) { opts = normalizeOptions(opts) if client == nil { client = &http.Client{Timeout: opts.Timeout} } - announceURL, err := buildAnnounceURL(tf, opts) + announceURLString, err := buildAnnounceURL(announceURL, tf, opts) if err != nil { return nil, err } - req, err := http.NewRequestWithContext(ctx, http.MethodGet, announceURL, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, announceURLString, nil) if err != nil { return nil, err } @@ -195,14 +198,12 @@ func normalizeOptions(opts AnnounceOptions) AnnounceOptions { return opts } -func buildAnnounceURL(tf *torrentfile.TorrentFile, opts AnnounceOptions) (string, error) { +func buildAnnounceURL(baseURL *url.URL, tf *torrentfile.TorrentFile, opts AnnounceOptions) (string, error) { if tf == nil { return "", errors.New("torrent metadata is nil") } - - baseURL, err := url.Parse(tf.Announce) - if err != nil { - return "", fmt.Errorf("invalid tracker URL %q: %w", tf.Announce, err) + if baseURL == nil { + return "", errors.New("tracker URL is nil") } if baseURL.Scheme != "http" && baseURL.Scheme != "https" { return "", fmt.Errorf("unsupported tracker scheme %q (only http/https are supported)", baseURL.Scheme) @@ -242,8 +243,9 @@ func buildAnnounceURL(tf *torrentfile.TorrentFile, opts AnnounceOptions) (string "numwant="+strconv.Itoa(opts.NumWant), ) - baseURL.RawQuery = strings.Join(parts, "&") - return baseURL.String(), nil + cloned := *baseURL + cloned.RawQuery = strings.Join(parts, "&") + return cloned.String(), nil } func buildUDPConnectRequest(transactionID uint32) [16]byte { diff --git a/internal/tracker/tracker_test.go b/internal/tracker/tracker_test.go index 50d827d..526e310 100644 --- a/internal/tracker/tracker_test.go +++ b/internal/tracker/tracker_test.go @@ -6,6 +6,7 @@ import ( "encoding/binary" "io" "net/http" + "net/url" "strings" "testing" @@ -67,7 +68,12 @@ func TestGetPeersBuildsAnnounceAndParsesResponse(t *testing.T) { }, } - peers, err := getPeersWithClient(context.Background(), client, tf, AnnounceOptions{ + announceURL, err := url.Parse(tf.Announce) + if err != nil { + t.Fatalf("failed to parse announce URL: %v", err) + } + + peers, err := getPeersWithClient(context.Background(), client, announceURL, tf, AnnounceOptions{ PeerID: peerID, Port: 6881, Downloaded: 100, @@ -123,7 +129,12 @@ func TestBuildAnnounceURLEncodesBinaryValues(t *testing.T) { Length: 10, } - announceURL, err := buildAnnounceURL(tf, AnnounceOptions{ + baseURL, err := url.Parse(tf.Announce) + if err != nil { + t.Fatalf("failed to parse announce URL: %v", err) + } + + announceURL, err := buildAnnounceURL(baseURL, tf, AnnounceOptions{ PeerID: peerID, Port: 6881, NumWant: 42, @@ -157,9 +168,13 @@ func TestBuildAnnounceURLEncodesBinaryValues(t *testing.T) { func TestBuildAnnounceURLRejectsUnsupportedScheme(t *testing.T) { t.Parallel() - _, err := buildAnnounceURL(&torrentfile.TorrentFile{ - Announce: "udp://tracker.test:6969/announce", - Length: 10, + baseURL, err := url.Parse("udp://tracker.test:6969/announce") + if err != nil { + t.Fatalf("failed to parse announce URL: %v", err) + } + + _, err = buildAnnounceURL(baseURL, &torrentfile.TorrentFile{ + Length: 10, }, AnnounceOptions{}) if err == nil { t.Fatal("expected buildAnnounceURL to reject unsupported tracker scheme") @@ -184,7 +199,12 @@ func TestGetPeersReturnsTrackerFailure(t *testing.T) { }, } - _, err := getPeersWithClient(context.Background(), client, tf, AnnounceOptions{}) + announceURL, err := url.Parse(tf.Announce) + if err != nil { + t.Fatalf("failed to parse announce URL: %v", err) + } + + _, err = getPeersWithClient(context.Background(), client, announceURL, tf, AnnounceOptions{}) if err == nil { t.Fatal("expected getPeersWithClient to return tracker failure error") } diff --git a/scripts/build-all.sh b/scripts/build-all.sh index 5958303..a70cd0a 100755 --- a/scripts/build-all.sh +++ b/scripts/build-all.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -set -euo pipefail +set -uo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" DIST_DIR="${ROOT_DIR}/dist" @@ -16,6 +16,10 @@ TARGETS=( "windows amd64" ) +host_os="$(go env GOOS)" +host_arch="$(go env GOARCH)" +build_failed=0 + for target in "${TARGETS[@]}"; do read -r goos goarch <<<"${target}" @@ -25,8 +29,22 @@ for target in "${TARGETS[@]}"; do fi output="${DIST_DIR}/ztorrent-${goos}-${goarch}${ext}" + rm -f "${output}" echo "Building ${output}" - GOCACHE="${GOCACHE}" CGO_ENABLED=0 GOOS="${goos}" GOARCH="${goarch}" go build -o "${output}" ./cmd/torrent-client + + if [[ "${goos}" == "${host_os}" ]]; then + if ! GOCACHE="${GOCACHE}" CGO_ENABLED=1 GOOS="${goos}" GOARCH="${goarch}" go build -o "${output}" ./cmd/torrent-client; then + echo "Failed to build local target ${goos}/${goarch}" + build_failed=1 + fi + continue + fi + + echo "Skipping ${goos}/${goarch}: native GUI build requires building on that target OS/arch (or a configured cross C toolchain)." done +if [[ "${build_failed}" -ne 0 ]]; then + exit 1 +fi + echo "Build complete. Artifacts are in ${DIST_DIR}" diff --git a/ui/window.go b/ui/window.go index 62ad9e1..d95735e 100644 --- a/ui/window.go +++ b/ui/window.go @@ -1,291 +1,369 @@ package ui import ( - "errors" "fmt" - "html/template" - "io" - "net" - "net/http" "os" - "os/exec" - "runtime" + "path/filepath" + "strconv" "strings" + "sync" + "time" - "github.com/veggiedefender/torrent-client/internal/app" + "fyne.io/fyne/v2" + fyneapp "fyne.io/fyne/v2/app" + "fyne.io/fyne/v2/container" + "fyne.io/fyne/v2/dialog" + "fyne.io/fyne/v2/layout" + "fyne.io/fyne/v2/storage" + "fyne.io/fyne/v2/widget" + appcore "github.com/veggiedefender/torrent-client/internal/app" "github.com/veggiedefender/torrent-client/internal/torrent" + "github.com/veggiedefender/torrent-client/internal/torrentfile" ) -type webUI struct { - controller *app.Controller +type desktopUI struct { + controller *appcore.Controller + app fyne.App + window fyne.Window + + pathEntry *widget.Entry + progress *widget.ProgressBar + phaseLabel *widget.Label + phaseMetricLabel *widget.Label + messageLabel *widget.Label + errorLabel *widget.Label + nameLabel *widget.Label + sizeLabel *widget.Label + pieceLabel *widget.Label + pieceCountLabel *widget.Label + peerCountLabel *widget.Label + + mu sync.RWMutex + trackers []torrent.TrackerStatus + peers []torrent.PeerStatus + files []torrentfile.File + + trackersTable *widget.Table + peersTable *widget.Table + filesTable *widget.Table + + stopRefresh chan struct{} } -type pageData struct { - Status torrent.Status - Message string - Error string +func Start(controller *appcore.Controller) { + desktop := newDesktopUI(controller) + desktop.window.ShowAndRun() } -var pageTemplate = template.Must(template.New("index").Parse(` - -
- - -Load a torrent by path or upload .torrent file
- - {{if .Message}}| File | Size (bytes) |
|---|---|
| {{.Path}} | {{.Length}} |
No torrent loaded yet.
- {{end}} -