This commit is contained in:
Simon Ding
2024-07-10 22:07:56 +08:00
parent a81b68b236
commit 171eef57cc
7 changed files with 80 additions and 39 deletions

View File

@@ -1,10 +1,12 @@
package transmission
import (
"context"
"net/url"
"polaris/log"
"strconv"
"github.com/hekmon/transmissionrpc"
"github.com/hekmon/transmissionrpc/v3"
"github.com/pkg/errors"
)
@@ -13,7 +15,13 @@ func NewClient(url1, user, password string) (*Client, error) {
if err != nil {
return nil, errors.Wrap(err, "parse url")
}
tbt, err := transmissionrpc.New(u.Hostname(), user, password, nil)
if user != "" {
log.Info("transmission login with user: ", user)
u.User = url.UserPassword(user, password)
}
u.Path = "/transmission/rpc"
tbt, err := transmissionrpc.New(u, nil)
if err != nil {
return nil, errors.Wrap(err, "connect transmission")
}
@@ -25,47 +33,61 @@ type Client struct {
}
func (c *Client) Download(magnet, dir string) (*Torrent, error) {
t, err := c.c.TorrentAdd(&transmissionrpc.TorrentAddPayload{
Filename: &magnet,
t, err := c.c.TorrentAdd(context.TODO(), transmissionrpc.TorrentAddPayload{
Filename: &magnet,
DownloadDir: &dir,
})
log.Infof("get torrent info: %+v", t)
return &Torrent{
t: t,
c: c.c,
id: *t.ID,
c: c.c,
}, err
}
type Torrent struct {
t *transmissionrpc.Torrent
c *transmissionrpc.Client
//t *transmissionrpc.Torrent
c *transmissionrpc.Client
id int64
}
func (t *Torrent) getTorrent() transmissionrpc.Torrent {
r, err := t.c.TorrentGetAllFor(context.TODO(), []int64{t.id})
if err != nil {
log.Errorf("get torrent info for error: %v", err)
}
return r[0]
}
func (t *Torrent) Name() string {
return *t.t.Name
return *t.getTorrent().Name
}
func (t *Torrent) Progress() int {
if *t.t.IsFinished {
if t.getTorrent().IsFinished != nil && *t.getTorrent().IsFinished {
return 100
}
return int(*t.t.PercentDone*100)
if t.getTorrent().PercentDone != nil {
return int(*t.getTorrent().PercentDone * 100)
}
return 0
}
func (t *Torrent) Stop() error {
return t.c.TorrentStopIDs([]int64{*t.t.ID})
return t.c.TorrentStopIDs(context.TODO(), []int64{t.id})
}
func (t *Torrent) Start() error {
return t.c.TorrentStartIDs([]int64{*t.t.ID})
return t.c.TorrentStartIDs(context.TODO(), []int64{t.id})
}
func (t *Torrent) Remove() error {
return t.c.TorrentRemove(&transmissionrpc.TorrentRemovePayload{
IDs: []int64{*t.t.ID},
return t.c.TorrentRemove(context.TODO(), transmissionrpc.TorrentRemovePayload{
IDs: []int64{t.id},
DeleteLocalData: true,
})
}
func (t *Torrent) Save() string {
return strconv.Itoa(int(*t.t.ID))
}
return strconv.Itoa(int(t.id))
}