autobrr/pkg/transmission/transmission.go
Kyle Sanderson 3234f0d919
refactor(http): implement shared transport and clients (#1288)
* fix(http): flip to a shared transport and clients

* nice threads

* that is terrible

* fake uri for magnet

* lazy locking

* why bother with r's

* flip magic params to struct

* refactor(http-clients): use separate clients with shared transport

* refactor(http-clients): add missing license header

* refactor(http-clients): defer and fix errors

---------

Co-authored-by: ze0s <ze0s@riseup.net>
2023-12-29 23:49:22 +01:00

60 lines
1.1 KiB
Go

package transmission
import (
"crypto/tls"
"net/http"
"net/url"
"time"
"github.com/autobrr/autobrr/pkg/sharedhttp"
"github.com/hekmon/transmissionrpc/v3"
)
type Config struct {
UserAgent string
CustomClient *http.Client
Username string
Password string
TLSSkipVerify bool
Timeout int
}
func New(endpoint *url.URL, cfg *Config) (*transmissionrpc.Client, error) {
ct := &customTransport{
Username: cfg.Username,
Password: cfg.Password,
TLSSkipVerify: cfg.TLSSkipVerify,
}
extra := &transmissionrpc.Config{
CustomClient: &http.Client{
Transport: ct,
Timeout: time.Second * 60,
},
UserAgent: cfg.UserAgent,
}
return transmissionrpc.New(endpoint, extra)
}
type customTransport struct {
Username string
Password string
TLSSkipVerify bool
}
func (t *customTransport) RoundTrip(req *http.Request) (*http.Response, error) {
dt := sharedhttp.Transport
if t.TLSSkipVerify {
dt.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
}
r := req.Clone(req.Context())
if t.Username != "" && t.Password != "" {
r.SetBasicAuth(t.Username, t.Password)
}
return dt.RoundTrip(r)
}