залупа

This commit is contained in:
itexpert228 2026-03-06 12:52:01 +03:00
parent 9978610cae
commit 27bb592659
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
```
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.

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
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/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 (
"context"
"crypto/rand"
"errors"
"fmt"
"net"
"sync"
"time"
@ -13,10 +16,12 @@ import (
type Engine struct {
mu sync.RWMutex
torrent *torrentfile.TorrentFile
peers []tracker.Peer
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{
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 {
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()

View file

@ -13,6 +13,7 @@ import (
type bencodeTorrent struct {
Announce string `bencode:"announce"`
AnnounceList [][]string `bencode:"announce-list"`
Info bencodeInfo `bencode:"info"`
}
@ -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
}

View file

@ -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()

View file

@ -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 {

View file

@ -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,8 +168,12 @@ func TestBuildAnnounceURLEncodesBinaryValues(t *testing.T) {
func TestBuildAnnounceURLRejectsUnsupportedScheme(t *testing.T) {
t.Parallel()
_, err := buildAnnounceURL(&torrentfile.TorrentFile{
Announce: "udp://tracker.test:6969/announce",
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 {
@ -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")
}

View file

@ -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}"

View file

@ -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(`<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<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>
func newDesktopUI(controller *appcore.Controller) *desktopUI {
a := fyneapp.NewWithID("github.com/veggiedefender/ztorrent")
w := a.NewWindow("Ztorrent")
w.Resize(fyne.NewSize(1200, 760))
<div class="card">
<h2>Status</h2>
{{if .Status.Loaded}}
<div class="grid">
<div class="kv"><div class="k">Name</div><div class="v">{{.Status.Name}}</div></div>
<div class="kv"><div class="k">Size</div><div class="v">{{.Status.Length}} bytes</div></div>
<div class="kv"><div class="k">Piece Length</div><div class="v">{{.Status.PieceLength}} bytes</div></div>
<div class="kv"><div class="k">Pieces</div><div class="v">{{.Status.PieceCount}}</div></div>
<div class="kv"><div class="k">Files</div><div class="v">{{len .Status.Files}}</div></div>
<div class="kv"><div class="k">Peers</div><div class="v">{{.Status.PeerCount}}</div></div>
<div class="kv"><div class="k">Tracker</div><div class="v">{{.Status.Announce}}</div></div>
</div>
<table>
<thead>
<tr><th>File</th><th>Size (bytes)</th></tr>
</thead>
<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()
fmt.Printf("Ztorrent GUI started at %s\n", guiURL)
openBrowser(guiURL)
if err := http.Serve(listener, mux); err != nil && !errors.Is(err, http.ErrServerClosed) {
fmt.Printf("GUI server error: %v\n", err)
}
ui := &desktopUI{
controller: controller,
app: a,
window: w,
stopRefresh: make(chan struct{}),
pathEntry: widget.NewEntry(),
progress: widget.NewProgressBar(),
phaseLabel: widget.NewLabel("Phase: idle"),
phaseMetricLabel: widget.NewLabel("idle"),
messageLabel: widget.NewLabel(""),
errorLabel: widget.NewLabel(""),
nameLabel: widget.NewLabel("-"),
sizeLabel: widget.NewLabel("-"),
pieceLabel: widget.NewLabel("-"),
pieceCountLabel: widget.NewLabel("-"),
peerCountLabel: widget.NewLabel("0"),
}
func (ui *webUI) handleIndex(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
ui.renderPage(w, pageData{Status: ui.controller.Status()})
}
ui.pathEntry.SetPlaceHolder("/path/to/file.torrent")
func (ui *webUI) handleLoad(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
browseButton := widget.NewButton("Browse", ui.onBrowse)
loadButton := widget.NewButton("Load Torrent", ui.onLoad)
topRow := container.NewBorder(nil, nil, nil, container.NewHBox(browseButton, loadButton), ui.pathEntry)
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),
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)
})
return
if len(os.Args) > 1 {
ui.pathEntry.SetText(os.Args[1])
ui.onLoad()
}
path := strings.TrimSpace(r.FormValue("path"))
var cleanupPath string
go ui.refreshLoop()
return ui
}
func wrapMetric(name string, value fyne.CanvasObject) fyne.CanvasObject {
return container.NewVBox(widget.NewLabel(name), value)
}
func (ui *desktopUI) onBrowse() {
filter := storage.NewExtensionFileFilter([]string{".torrent"})
fd := dialog.NewFileOpen(func(reader fyne.URIReadCloser, err error) {
if err != nil {
ui.setError(err.Error())
return
}
if reader == nil {
return
}
defer reader.Close()
ui.pathEntry.SetText(reader.URI().Path())
}, ui.window)
fd.SetFilter(filter)
fd.Show()
}
func (ui *desktopUI) onLoad() {
path := strings.TrimSpace(ui.pathEntry.Text)
if path == "" {
uploadedPath, err := saveUploadedTorrent(r)
if err != nil {
ui.renderPage(w, pageData{
Status: ui.controller.Status(),
Error: fmt.Sprintf("failed to read uploaded file: %v", err),
})
ui.setError("select a .torrent file first")
return
}
path = uploadedPath
cleanupPath = uploadedPath
}
if cleanupPath != "" {
defer os.Remove(cleanupPath)
}
ui.setMessage("Loading torrent...")
ui.setError("")
loadErr := ui.controller.StartTorrent(path)
go func() {
err := 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)
}
ui.updateFromStatus(status)
if err != nil {
ui.setError(err.Error())
} else {
data.Message = fmt.Sprintf("Loaded torrent from %s", path)
ui.setMessage("Loaded " + filepath.Base(path))
}
ui.renderPage(w, data)
}()
}
func (ui *webUI) renderPage(w http.ResponseWriter, data pageData) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := pageTemplate.Execute(w, data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
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) {
file, _, err := r.FormFile("torrent_file")
if err != nil {
return "", err
}
defer file.Close()
func (ui *desktopUI) updateFromStatus(status torrent.Status) {
fyne.Do(func() {
ui.progress.SetValue(status.Progress)
ui.phaseLabel.SetText("Phase: " + status.Phase)
ui.phaseMetricLabel.SetText(status.Phase)
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")
if err != nil {
return "", err
}
defer tmp.Close()
ui.mu.Lock()
ui.trackers = append(ui.trackers[:0], status.Trackers...)
ui.peers = append(ui.peers[:0], status.Peers...)
ui.files = append(ui.files[:0], status.Files...)
ui.mu.Unlock()
if _, err := io.Copy(tmp, file); err != nil {
return "", err
ui.trackersTable.Refresh()
ui.peersTable.Refresh()
ui.filesTable.Refresh()
if status.LastError != "" {
ui.errorLabel.SetText(status.LastError)
}
})
}
return tmp.Name(), nil
func (ui *desktopUI) setMessage(msg string) {
fyne.Do(func() {
ui.messageLabel.SetText(msg)
})
}
func openBrowser(targetURL string) {
var cmd *exec.Cmd
switch runtime.GOOS {
case "windows":
cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", targetURL)
case "darwin":
cmd = exec.Command("open", targetURL)
default:
cmd = exec.Command("xdg-open", targetURL)
func (ui *desktopUI) setError(msg string) {
fyne.Do(func() {
if msg == "" {
ui.errorLabel.SetText("")
return
}
ui.errorLabel.SetText("Error: " + msg)
})
}
if err := cmd.Start(); err != nil {
fmt.Printf("Failed to open browser automatically: %v\nOpen manually: %s\n", err, targetURL)
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
}