залупа

This commit is contained in:
itexpert228 2026-03-06 12:52:01 +03:00
parent 9bcf57101b
commit f5d70e9eaf
No known key found for this signature in database
15 changed files with 809 additions and 304 deletions

View file

@ -8,7 +8,7 @@ Minimal BitTorrent client skeleton in Go.
go run ./cmd/torrent-client 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 ## 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 - Single-file and multi-file torrents
- Send tracker announce requests via HTTP(S) and UDP trackers - Send tracker announce requests via HTTP(S) and UDP trackers
- Parse compact peer list - Parse compact peer list
- Browser GUI for loading torrents by path or file upload - Multi-tracker fallback (including public trackers)
- Show loaded torrent status and files in the GUI - 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) ## Build (macOS/Linux/Windows)
```bash ```bash
./scripts/build-all.sh ./scripts/build-all.sh
``` ```
Note: for non-host targets with native GUI, cross C toolchains are required; unsupported targets are skipped.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

36
go.mod
View file

@ -3,3 +3,39 @@ module github.com/veggiedefender/torrent-client
go 1.22 go 1.22
require github.com/jackpal/bencode-go v1.0.2 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
)

80
go.sum
View file

@ -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 h1:LcCNfZ344u0LpBPOZNjpCLps/wUOuN4r87Fy9+5yU8g=
github.com/jackpal/bencode-go v1.0.2/go.mod h1:6jI9mUjO3GQbZti3JizEfxTzRfWOM8oBBcwbwlTfceI= 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=

View file

@ -3,6 +3,9 @@ package torrent
import ( import (
"context" "context"
"crypto/rand" "crypto/rand"
"errors"
"fmt"
"net"
"sync" "sync"
"time" "time"
@ -11,12 +14,14 @@ import (
) )
type Engine struct { type Engine struct {
mu sync.RWMutex mu sync.RWMutex
torrent *torrentfile.TorrentFile torrent *torrentfile.TorrentFile
peers []tracker.Peer peers []PeerStatus
peerID [20]byte trackers []TrackerStatus
cancel context.CancelFunc peerID [20]byte
lastErr error cancel context.CancelFunc
lastErr error
phase string
} }
type Status struct { type Status struct {
@ -28,48 +33,85 @@ type Status struct {
Files []torrentfile.File Files []torrentfile.File
Announce string Announce string
PeerCount int PeerCount int
Peers []PeerStatus
Trackers []TrackerStatus
PeerID string PeerID string
Progress float64 Progress float64
Phase string
LastError 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 { func NewEngine() *Engine {
return &Engine{ return &Engine{
peerID: generatePeerID(), peerID: generatePeerID(),
phase: "idle",
} }
} }
func (e *Engine) LoadTorrent(path string) error { func (e *Engine) LoadTorrent(path string) error {
e.setPhase("loading_metadata")
tf, err := torrentfile.Open(path) tf, err := torrentfile.Open(path)
if err != nil { if err != nil {
e.setError(err) e.setError(err)
e.setPhase("failed")
return err return err
} }
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
e.swapCancel(cancel) e.swapCancel(cancel)
defer e.clearCancel() defer e.clearCancel()
peers, err := tracker.GetPeers(ctx, tf, tracker.AnnounceOptions{ e.setPhase("querying_trackers")
PeerID: e.peerID, peers, trackerStatuses := e.queryTrackers(ctx, tf, tracker.AnnounceOptions{
Port: 6881, PeerID: e.peerID,
Port: 6881,
NumWant: 200,
Timeout: 6 * time.Second,
}) })
if err != nil {
e.mu.Lock() var finalErr error
e.torrent = tf if len(peers) == 0 {
e.peers = nil if err := firstTrackerError(trackerStatuses); err != nil {
e.lastErr = err finalErr = fmt.Errorf("no peers found: %w", err)
e.mu.Unlock() } else {
return err finalErr = fmt.Errorf("no peers found via %d trackers", len(trackerStatuses))
}
} }
e.mu.Lock() e.mu.Lock()
e.torrent = tf e.torrent = tf
e.peers = peers 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() 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 return nil
} }
@ -83,7 +125,22 @@ func (e *Engine) Stop() {
} }
func (e *Engine) Progress() float64 { 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 { func (e *Engine) Status() Status {
@ -94,7 +151,10 @@ func (e *Engine) Status() Status {
Loaded: e.torrent != nil, Loaded: e.torrent != nil,
PeerCount: len(e.peers), PeerCount: len(e.peers),
PeerID: string(e.peerID[:]), 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 { if e.torrent != nil {
status.Name = e.torrent.Name status.Name = e.torrent.Name
@ -111,12 +171,161 @@ func (e *Engine) Status() Status {
return 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) { func (e *Engine) setError(err error) {
e.mu.Lock() e.mu.Lock()
defer e.mu.Unlock() defer e.mu.Unlock()
e.lastErr = err 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) { func (e *Engine) swapCancel(cancel context.CancelFunc) {
e.mu.Lock() e.mu.Lock()
defer e.mu.Unlock() defer e.mu.Unlock()

View file

@ -12,8 +12,9 @@ import (
) )
type bencodeTorrent struct { type bencodeTorrent struct {
Announce string `bencode:"announce"` Announce string `bencode:"announce"`
Info bencodeInfo `bencode:"info"` AnnounceList [][]string `bencode:"announce-list"`
Info bencodeInfo `bencode:"info"`
} }
type bencodeInfo struct { type bencodeInfo struct {
@ -36,6 +37,7 @@ type File struct {
type TorrentFile struct { type TorrentFile struct {
Announce string Announce string
Trackers []string
InfoHash [20]byte InfoHash [20]byte
PieceHashes [][20]byte PieceHashes [][20]byte
PieceLength int PieceLength int
@ -80,9 +82,11 @@ func Open(path string) (*TorrentFile, error) {
} }
infoHash := sha1.Sum(infoBytes) infoHash := sha1.Sum(infoBytes)
trackers := collectTrackers(bto.Announce, bto.AnnounceList)
tf := TorrentFile{ tf := TorrentFile{
Announce: bto.Announce, Announce: bto.Announce,
Trackers: trackers,
InfoHash: infoHash, InfoHash: infoHash,
PieceHashes: pieceHashes, PieceHashes: pieceHashes,
PieceLength: bto.Info.PieceLength, PieceLength: bto.Info.PieceLength,
@ -330,3 +334,28 @@ func parseBencodeStringLength(data []byte, idx int) (int, int, error) {
return length, idx + 1, nil 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
}

View file

@ -27,6 +27,9 @@ func TestOpenParsesTorrentMetadata(t *testing.T) {
if tf.Announce != "http://tracker" { if tf.Announce != "http://tracker" {
t.Fatalf("unexpected announce: got %q", tf.Announce) 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" { if tf.Name != "test.txt" {
t.Fatalf("unexpected name: got %q", tf.Name) 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 { func writeTempTorrent(t *testing.T, data string) string {
t.Helper() t.Helper()

View file

@ -45,18 +45,25 @@ func GetPeers(ctx context.Context, tf *torrentfile.TorrentFile, opts AnnounceOpt
if tf == nil { if tf == nil {
return nil, errors.New("torrent metadata is 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) opts = normalizeOptions(opts)
announceURL, err := url.Parse(tf.Announce) announceURL, err := url.Parse(announce)
if err != nil { 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 { switch announceURL.Scheme {
case "http", "https": case "http", "https":
client := &http.Client{Timeout: opts.Timeout} client := &http.Client{Timeout: opts.Timeout}
return getPeersWithClient(ctx, client, tf, opts) return getPeersWithClient(ctx, client, announceURL, tf, opts)
case "udp": case "udp":
return getPeersUDP(ctx, announceURL, tf, opts) return getPeersUDP(ctx, announceURL, tf, opts)
default: 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) { func getPeersWithClient(ctx context.Context, client httpDoer, announceURL *url.URL, tf *torrentfile.TorrentFile, opts AnnounceOptions) ([]Peer, error) {
if tf == nil {
return nil, errors.New("torrent metadata is nil")
}
opts = normalizeOptions(opts) opts = normalizeOptions(opts)
if client == nil { if client == nil {
client = &http.Client{Timeout: opts.Timeout} client = &http.Client{Timeout: opts.Timeout}
} }
announceURL, err := buildAnnounceURL(tf, opts) announceURLString, err := buildAnnounceURL(announceURL, tf, opts)
if err != nil { if err != nil {
return nil, err return nil, err
} }
req, err := http.NewRequestWithContext(ctx, http.MethodGet, announceURL, nil) req, err := http.NewRequestWithContext(ctx, http.MethodGet, announceURLString, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -195,14 +198,12 @@ func normalizeOptions(opts AnnounceOptions) AnnounceOptions {
return opts 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 { if tf == nil {
return "", errors.New("torrent metadata is nil") return "", errors.New("torrent metadata is nil")
} }
if baseURL == nil {
baseURL, err := url.Parse(tf.Announce) return "", errors.New("tracker URL is nil")
if err != nil {
return "", fmt.Errorf("invalid tracker URL %q: %w", tf.Announce, err)
} }
if baseURL.Scheme != "http" && baseURL.Scheme != "https" { if baseURL.Scheme != "http" && baseURL.Scheme != "https" {
return "", fmt.Errorf("unsupported tracker scheme %q (only http/https are supported)", baseURL.Scheme) 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), "numwant="+strconv.Itoa(opts.NumWant),
) )
baseURL.RawQuery = strings.Join(parts, "&") cloned := *baseURL
return baseURL.String(), nil cloned.RawQuery = strings.Join(parts, "&")
return cloned.String(), nil
} }
func buildUDPConnectRequest(transactionID uint32) [16]byte { func buildUDPConnectRequest(transactionID uint32) [16]byte {

View file

@ -6,6 +6,7 @@ import (
"encoding/binary" "encoding/binary"
"io" "io"
"net/http" "net/http"
"net/url"
"strings" "strings"
"testing" "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, PeerID: peerID,
Port: 6881, Port: 6881,
Downloaded: 100, Downloaded: 100,
@ -123,7 +129,12 @@ func TestBuildAnnounceURLEncodesBinaryValues(t *testing.T) {
Length: 10, 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, PeerID: peerID,
Port: 6881, Port: 6881,
NumWant: 42, NumWant: 42,
@ -157,9 +168,13 @@ func TestBuildAnnounceURLEncodesBinaryValues(t *testing.T) {
func TestBuildAnnounceURLRejectsUnsupportedScheme(t *testing.T) { func TestBuildAnnounceURLRejectsUnsupportedScheme(t *testing.T) {
t.Parallel() t.Parallel()
_, err := buildAnnounceURL(&torrentfile.TorrentFile{ baseURL, err := url.Parse("udp://tracker.test:6969/announce")
Announce: "udp://tracker.test:6969/announce", if err != nil {
Length: 10, t.Fatalf("failed to parse announce URL: %v", err)
}
_, err = buildAnnounceURL(baseURL, &torrentfile.TorrentFile{
Length: 10,
}, AnnounceOptions{}) }, AnnounceOptions{})
if err == nil { if err == nil {
t.Fatal("expected buildAnnounceURL to reject unsupported tracker scheme") 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 { if err == nil {
t.Fatal("expected getPeersWithClient to return tracker failure error") t.Fatal("expected getPeersWithClient to return tracker failure error")
} }

View file

@ -1,5 +1,5 @@
#!/usr/bin/env bash #!/usr/bin/env bash
set -euo pipefail set -uo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DIST_DIR="${ROOT_DIR}/dist" DIST_DIR="${ROOT_DIR}/dist"
@ -16,6 +16,10 @@ TARGETS=(
"windows amd64" "windows amd64"
) )
host_os="$(go env GOOS)"
host_arch="$(go env GOARCH)"
build_failed=0
for target in "${TARGETS[@]}"; do for target in "${TARGETS[@]}"; do
read -r goos goarch <<<"${target}" read -r goos goarch <<<"${target}"
@ -25,8 +29,22 @@ for target in "${TARGETS[@]}"; do
fi fi
output="${DIST_DIR}/ztorrent-${goos}-${goarch}${ext}" output="${DIST_DIR}/ztorrent-${goos}-${goarch}${ext}"
rm -f "${output}"
echo "Building ${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 done
if [[ "${build_failed}" -ne 0 ]]; then
exit 1
fi
echo "Build complete. Artifacts are in ${DIST_DIR}" echo "Build complete. Artifacts are in ${DIST_DIR}"

View file

@ -1,291 +1,369 @@
package ui package ui
import ( import (
"errors"
"fmt" "fmt"
"html/template"
"io"
"net"
"net/http"
"os" "os"
"os/exec" "path/filepath"
"runtime" "strconv"
"strings" "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/torrent"
"github.com/veggiedefender/torrent-client/internal/torrentfile"
) )
type webUI struct { type desktopUI struct {
controller *app.Controller 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 { func Start(controller *appcore.Controller) {
Status torrent.Status desktop := newDesktopUI(controller)
Message string desktop.window.ShowAndRun()
Error string
} }
var pageTemplate = template.Must(template.New("index").Parse(`<!doctype html> func newDesktopUI(controller *appcore.Controller) *desktopUI {
<html lang="en"> a := fyneapp.NewWithID("github.com/veggiedefender/ztorrent")
<head> w := a.NewWindow("Ztorrent")
<meta charset="utf-8"> w.Resize(fyne.NewSize(1200, 760))
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ztorrent</title>
<style>
:root {
--bg: #0f172a;
--card: #111827;
--text: #e5e7eb;
--muted: #94a3b8;
--accent: #22c55e;
--danger: #ef4444;
--border: #1f2937;
}
body {
margin: 0;
font-family: "Segoe UI", "Helvetica Neue", Arial, sans-serif;
background: radial-gradient(circle at top, #1f2937 0%, var(--bg) 45%);
color: var(--text);
}
.wrap {
max-width: 960px;
margin: 24px auto;
padding: 0 16px 24px;
}
.card {
border: 1px solid var(--border);
border-radius: 12px;
background: color-mix(in srgb, var(--card), transparent 10%);
backdrop-filter: blur(6px);
padding: 16px;
margin-bottom: 16px;
}
h1, h2 { margin: 0 0 12px; }
.sub { color: var(--muted); margin: 0 0 16px; }
label { display: block; margin-bottom: 8px; font-weight: 600; }
input[type="text"], input[type="file"] {
width: 100%;
box-sizing: border-box;
border: 1px solid #334155;
background: #0b1220;
color: var(--text);
border-radius: 8px;
padding: 10px 12px;
}
.row { display: grid; gap: 10px; grid-template-columns: 1fr; }
button {
border: 0;
border-radius: 10px;
padding: 10px 14px;
color: #06120a;
background: var(--accent);
font-weight: 700;
cursor: pointer;
}
.msg, .err {
margin-top: 10px;
border-radius: 8px;
padding: 10px 12px;
}
.msg { background: color-mix(in srgb, var(--accent), transparent 85%); }
.err { background: color-mix(in srgb, var(--danger), transparent 85%); }
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 10px;
}
.kv {
border: 1px solid var(--border);
border-radius: 8px;
padding: 10px;
background: #0b1220;
}
.k { color: var(--muted); font-size: 12px; text-transform: uppercase; letter-spacing: .04em; }
.v { margin-top: 6px; font-weight: 600; word-break: break-word; }
table {
width: 100%;
border-collapse: collapse;
margin-top: 12px;
font-size: 14px;
}
th, td {
border-bottom: 1px solid var(--border);
padding: 8px 4px;
text-align: left;
}
th { color: var(--muted); font-weight: 600; }
</style>
</head>
<body>
<div class="wrap">
<div class="card">
<h1>Ztorrent</h1>
<p class="sub">Load a torrent by path or upload .torrent file</p>
<form method="post" action="/load" enctype="multipart/form-data">
<div class="row">
<label for="path">Torrent path</label>
<input type="text" name="path" id="path" placeholder="/path/to/file.torrent">
<label for="torrent-file">Or upload .torrent</label>
<input type="file" name="torrent_file" id="torrent-file" accept=".torrent,application/x-bittorrent">
<button type="submit">Load Torrent</button>
</div>
</form>
{{if .Message}}<div class="msg">{{.Message}}</div>{{end}}
{{if .Error}}<div class="err">{{.Error}}</div>{{end}}
</div>
<div class="card"> ui := &desktopUI{
<h2>Status</h2> controller: controller,
{{if .Status.Loaded}} app: a,
<div class="grid"> window: w,
<div class="kv"><div class="k">Name</div><div class="v">{{.Status.Name}}</div></div> stopRefresh: make(chan struct{}),
<div class="kv"><div class="k">Size</div><div class="v">{{.Status.Length}} bytes</div></div> pathEntry: widget.NewEntry(),
<div class="kv"><div class="k">Piece Length</div><div class="v">{{.Status.PieceLength}} bytes</div></div> progress: widget.NewProgressBar(),
<div class="kv"><div class="k">Pieces</div><div class="v">{{.Status.PieceCount}}</div></div> phaseLabel: widget.NewLabel("Phase: idle"),
<div class="kv"><div class="k">Files</div><div class="v">{{len .Status.Files}}</div></div> phaseMetricLabel: widget.NewLabel("idle"),
<div class="kv"><div class="k">Peers</div><div class="v">{{.Status.PeerCount}}</div></div> messageLabel: widget.NewLabel(""),
<div class="kv"><div class="k">Tracker</div><div class="v">{{.Status.Announce}}</div></div> errorLabel: widget.NewLabel(""),
</div> nameLabel: widget.NewLabel("-"),
<table> sizeLabel: widget.NewLabel("-"),
<thead> pieceLabel: widget.NewLabel("-"),
<tr><th>File</th><th>Size (bytes)</th></tr> pieceCountLabel: widget.NewLabel("-"),
</thead> peerCountLabel: widget.NewLabel("0"),
<tbody>
{{range .Status.Files}}
<tr><td>{{.Path}}</td><td>{{.Length}}</td></tr>
{{end}}
</tbody>
</table>
{{else}}
<p class="sub">No torrent loaded yet.</p>
{{end}}
</div>
</div>
</body>
</html>`))
func Start(controller *app.Controller) {
ui := &webUI{controller: controller}
mux := http.NewServeMux()
mux.HandleFunc("/", ui.handleIndex)
mux.HandleFunc("/load", ui.handleLoad)
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
fmt.Printf("Failed to start GUI listener: %v\n", err)
return
} }
defer listener.Close()
guiURL := "http://" + listener.Addr().String() ui.pathEntry.SetPlaceHolder("/path/to/file.torrent")
fmt.Printf("Ztorrent GUI started at %s\n", guiURL)
openBrowser(guiURL)
if err := http.Serve(listener, mux); err != nil && !errors.Is(err, http.ErrServerClosed) { browseButton := widget.NewButton("Browse", ui.onBrowse)
fmt.Printf("GUI server error: %v\n", err) loadButton := widget.NewButton("Load Torrent", ui.onLoad)
topRow := container.NewBorder(nil, nil, nil, container.NewHBox(browseButton, loadButton), ui.pathEntry)
metaGrid := container.NewGridWithColumns(3,
wrapMetric("Name", ui.nameLabel),
wrapMetric("Size (bytes)", ui.sizeLabel),
wrapMetric("Piece length", ui.pieceLabel),
wrapMetric("Pieces", ui.pieceCountLabel),
wrapMetric("Discovered peers", ui.peerCountLabel),
wrapMetric("Phase", ui.phaseMetricLabel),
)
ui.trackersTable = ui.newTrackersTable()
ui.peersTable = ui.newPeersTable()
ui.filesTable = ui.newFilesTable()
tabs := container.NewAppTabs(
container.NewTabItem("Trackers", container.NewMax(ui.trackersTable)),
container.NewTabItem("Peers", container.NewMax(ui.peersTable)),
container.NewTabItem("Files", container.NewMax(ui.filesTable)),
)
statusColumn := container.NewVBox(
ui.phaseLabel,
ui.progress,
ui.messageLabel,
ui.errorLabel,
)
content := container.NewBorder(
container.NewVBox(topRow),
nil,
nil,
nil,
container.NewVBox(
statusColumn,
layout.NewSpacer(),
metaGrid,
layout.NewSpacer(),
tabs,
),
)
w.SetContent(content)
w.SetOnClosed(func() {
close(ui.stopRefresh)
})
if len(os.Args) > 1 {
ui.pathEntry.SetText(os.Args[1])
ui.onLoad()
} }
go ui.refreshLoop()
return ui
} }
func (ui *webUI) handleIndex(w http.ResponseWriter, r *http.Request) { func wrapMetric(name string, value fyne.CanvasObject) fyne.CanvasObject {
if r.Method != http.MethodGet { return container.NewVBox(widget.NewLabel(name), value)
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
ui.renderPage(w, pageData{Status: ui.controller.Status()})
} }
func (ui *webUI) handleLoad(w http.ResponseWriter, r *http.Request) { func (ui *desktopUI) onBrowse() {
if r.Method != http.MethodPost { filter := storage.NewExtensionFileFilter([]string{".torrent"})
http.Error(w, "method not allowed", http.StatusMethodNotAllowed) fd := dialog.NewFileOpen(func(reader fyne.URIReadCloser, err error) {
return
}
if err := r.ParseMultipartForm(32 << 20); err != nil {
ui.renderPage(w, pageData{
Status: ui.controller.Status(),
Error: fmt.Sprintf("failed to parse form: %v", err),
})
return
}
path := strings.TrimSpace(r.FormValue("path"))
var cleanupPath string
if path == "" {
uploadedPath, err := saveUploadedTorrent(r)
if err != nil { if err != nil {
ui.renderPage(w, pageData{ ui.setError(err.Error())
Status: ui.controller.Status(),
Error: fmt.Sprintf("failed to read uploaded file: %v", err),
})
return return
} }
path = uploadedPath if reader == nil {
cleanupPath = uploadedPath return
}
if cleanupPath != "" {
defer os.Remove(cleanupPath)
}
loadErr := ui.controller.StartTorrent(path)
status := ui.controller.Status()
data := pageData{
Status: status,
}
if loadErr != nil {
data.Error = loadErr.Error()
if status.Loaded {
data.Message = fmt.Sprintf("Metadata loaded from %s, but tracker announce failed", path)
} }
} else { defer reader.Close()
data.Message = fmt.Sprintf("Loaded torrent from %s", path)
} ui.pathEntry.SetText(reader.URI().Path())
ui.renderPage(w, data) }, ui.window)
fd.SetFilter(filter)
fd.Show()
} }
func (ui *webUI) renderPage(w http.ResponseWriter, data pageData) { func (ui *desktopUI) onLoad() {
w.Header().Set("Content-Type", "text/html; charset=utf-8") path := strings.TrimSpace(ui.pathEntry.Text)
if err := pageTemplate.Execute(w, data); err != nil { if path == "" {
http.Error(w, err.Error(), http.StatusInternalServerError) ui.setError("select a .torrent file first")
return
}
ui.setMessage("Loading torrent...")
ui.setError("")
go func() {
err := ui.controller.StartTorrent(path)
status := ui.controller.Status()
ui.updateFromStatus(status)
if err != nil {
ui.setError(err.Error())
} else {
ui.setMessage("Loaded " + filepath.Base(path))
}
}()
}
func (ui *desktopUI) refreshLoop() {
ticker := time.NewTicker(1200 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ui.stopRefresh:
return
case <-ticker.C:
ui.updateFromStatus(ui.controller.Status())
}
} }
} }
func saveUploadedTorrent(r *http.Request) (string, error) { func (ui *desktopUI) updateFromStatus(status torrent.Status) {
file, _, err := r.FormFile("torrent_file") fyne.Do(func() {
if err != nil { ui.progress.SetValue(status.Progress)
return "", err ui.phaseLabel.SetText("Phase: " + status.Phase)
} ui.phaseMetricLabel.SetText(status.Phase)
defer file.Close() ui.nameLabel.SetText(status.Name)
ui.sizeLabel.SetText(strconv.Itoa(status.Length))
ui.pieceLabel.SetText(strconv.Itoa(status.PieceLength))
ui.pieceCountLabel.SetText(strconv.Itoa(status.PieceCount))
ui.peerCountLabel.SetText(strconv.Itoa(status.PeerCount))
tmp, err := os.CreateTemp("", "ztorrent-*.torrent") ui.mu.Lock()
if err != nil { ui.trackers = append(ui.trackers[:0], status.Trackers...)
return "", err ui.peers = append(ui.peers[:0], status.Peers...)
} ui.files = append(ui.files[:0], status.Files...)
defer tmp.Close() ui.mu.Unlock()
if _, err := io.Copy(tmp, file); err != nil { ui.trackersTable.Refresh()
return "", err ui.peersTable.Refresh()
} ui.filesTable.Refresh()
return tmp.Name(), nil if status.LastError != "" {
ui.errorLabel.SetText(status.LastError)
}
})
} }
func openBrowser(targetURL string) { func (ui *desktopUI) setMessage(msg string) {
var cmd *exec.Cmd fyne.Do(func() {
switch runtime.GOOS { ui.messageLabel.SetText(msg)
case "windows": })
cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", targetURL) }
case "darwin":
cmd = exec.Command("open", targetURL) func (ui *desktopUI) setError(msg string) {
default: fyne.Do(func() {
cmd = exec.Command("xdg-open", targetURL) if msg == "" {
} ui.errorLabel.SetText("")
return
if err := cmd.Start(); err != nil { }
fmt.Printf("Failed to open browser automatically: %v\nOpen manually: %s\n", err, targetURL) ui.errorLabel.SetText("Error: " + msg)
} })
}
func (ui *desktopUI) newTrackersTable() *widget.Table {
table := widget.NewTable(
func() (int, int) {
ui.mu.RLock()
defer ui.mu.RUnlock()
return len(ui.trackers) + 1, 4
},
func() fyne.CanvasObject {
return widget.NewLabel("")
},
func(id widget.TableCellID, obj fyne.CanvasObject) {
label := obj.(*widget.Label)
if id.Row == 0 {
switch id.Col {
case 0:
label.SetText("Tracker")
case 1:
label.SetText("State")
case 2:
label.SetText("Peers")
case 3:
label.SetText("Error")
}
return
}
ui.mu.RLock()
defer ui.mu.RUnlock()
tr := ui.trackers[id.Row-1]
switch id.Col {
case 0:
label.SetText(tr.URL)
case 1:
label.SetText(tr.State)
case 2:
label.SetText(strconv.Itoa(tr.PeerCount))
case 3:
label.SetText(tr.Error)
}
},
)
table.SetColumnWidth(0, 420)
table.SetColumnWidth(1, 90)
table.SetColumnWidth(2, 70)
table.SetColumnWidth(3, 420)
return table
}
func (ui *desktopUI) newPeersTable() *widget.Table {
table := widget.NewTable(
func() (int, int) {
ui.mu.RLock()
defer ui.mu.RUnlock()
return len(ui.peers) + 1, 3
},
func() fyne.CanvasObject {
return widget.NewLabel("")
},
func(id widget.TableCellID, obj fyne.CanvasObject) {
label := obj.(*widget.Label)
if id.Row == 0 {
switch id.Col {
case 0:
label.SetText("Address")
case 1:
label.SetText("Port")
case 2:
label.SetText("Source tracker")
}
return
}
ui.mu.RLock()
defer ui.mu.RUnlock()
peer := ui.peers[id.Row-1]
switch id.Col {
case 0:
label.SetText(peer.Address)
case 1:
label.SetText(strconv.Itoa(int(peer.Port)))
case 2:
label.SetText(peer.Source)
}
},
)
table.SetColumnWidth(0, 180)
table.SetColumnWidth(1, 80)
table.SetColumnWidth(2, 700)
return table
}
func (ui *desktopUI) newFilesTable() *widget.Table {
table := widget.NewTable(
func() (int, int) {
ui.mu.RLock()
defer ui.mu.RUnlock()
return len(ui.files) + 1, 2
},
func() fyne.CanvasObject {
return widget.NewLabel("")
},
func(id widget.TableCellID, obj fyne.CanvasObject) {
label := obj.(*widget.Label)
if id.Row == 0 {
switch id.Col {
case 0:
label.SetText("File")
case 1:
label.SetText("Size")
}
return
}
ui.mu.RLock()
defer ui.mu.RUnlock()
file := ui.files[id.Row-1]
switch id.Col {
case 0:
label.SetText(file.Path)
case 1:
label.SetText(fmt.Sprintf("%d", file.Length))
}
},
)
table.SetColumnWidth(0, 780)
table.SetColumnWidth(1, 120)
return table
} }