feat(protocol): add FTP, FTPS and FTPES downloads (#1569)

This commit is contained in:
Silas Mariusz authored and GitHub committed 2026-10-30 17:01:46 +08:00
1 parent e0951de270
commit c0b70d319d
54 files changed
+3850 -38

No files matched your search

+3 -1
View File
@@ -10,11 +10,13 @@ require (
github.com/bodgit/sevenzip v1.6.1 github.com/bodgit/sevenzip v1.6.1
github.com/dop251/goja v0.0.0-20260106131823-651366fbe6e3 github.com/dop251/goja v0.0.0-20260106131823-651366fbe6e3
github.com/dop251/goja_nodejs v0.0.0-20240728170619-29b559befffc github.com/dop251/goja_nodejs v0.0.0-20240728170619-29b559befffc
github.com/fclairamb/ftpserverlib v0.31.0
github.com/go-git/go-git/v5 v5.8.1 github.com/go-git/go-git/v5 v5.8.1
github.com/google/jsonschema-go v0.4.3 github.com/google/jsonschema-go v0.4.3
github.com/gorilla/handlers v1.5.1 github.com/gorilla/handlers v1.5.1
github.com/gorilla/mux v1.8.0 github.com/gorilla/mux v1.8.0
github.com/imroc/req/v3 v3.52.2 github.com/imroc/req/v3 v3.52.2
github.com/jlaffaye/ftp v0.2.4
github.com/matoous/go-nanoid/v2 v2.0.0 github.com/matoous/go-nanoid/v2 v2.0.0
github.com/mattn/go-ieproxy v0.0.12 github.com/mattn/go-ieproxy v0.0.12
github.com/mholt/archives v0.1.5 github.com/mholt/archives v0.1.5
@@ -23,6 +25,7 @@ require (
github.com/pkg/errors v0.9.1 github.com/pkg/errors v0.9.1
github.com/rs/dnscache v0.0.0-20230804202142-fc85eb664529 github.com/rs/dnscache v0.0.0-20230804202142-fc85eb664529
github.com/rs/zerolog v1.31.0 github.com/rs/zerolog v1.31.0
github.com/spf13/afero v1.15.0
github.com/tetratelabs/wazero v1.12.0 github.com/tetratelabs/wazero v1.12.0
github.com/xiaoqidun/setft v0.0.0-20220310121541-be86327699ad github.com/xiaoqidun/setft v0.0.0-20220310121541-be86327699ad
go.etcd.io/bbolt v1.4.3 go.etcd.io/bbolt v1.4.3
@@ -59,7 +62,6 @@ require (
github.com/segmentio/asm v1.1.3 // indirect github.com/segmentio/asm v1.1.3 // indirect
github.com/segmentio/encoding v0.5.4 // indirect github.com/segmentio/encoding v0.5.4 // indirect
github.com/sorairolake/lzip-go v0.3.8 // indirect github.com/sorairolake/lzip-go v0.3.8 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/ulikunitz/xz v0.5.15 // indirect github.com/ulikunitz/xz v0.5.15 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect
+10
View File
@@ -205,6 +205,8 @@ github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/fclairamb/ftpserverlib v0.31.0 h1:ws4fLJvuU/mgg1uIgRjCJfc6CrFSgIBAOxVsnawXegE=
github.com/fclairamb/ftpserverlib v0.31.0/go.mod h1:C5hUT0sd9P5XsHMxsmpcrT6wdZexu3qtUu1z0Ih6aG0=
github.com/felixge/fgprof v0.9.5 h1:8+vR6yu2vvSKn08urWyEuxx75NWPEvybbkBirEpsbVY= github.com/felixge/fgprof v0.9.5 h1:8+vR6yu2vvSKn08urWyEuxx75NWPEvybbkBirEpsbVY=
github.com/felixge/fgprof v0.9.5/go.mod h1:yKl+ERSa++RYOs32d8K6WEXCB4uXdLls4ZaZPpayhMM= github.com/felixge/fgprof v0.9.5/go.mod h1:yKl+ERSa++RYOs32d8K6WEXCB4uXdLls4ZaZPpayhMM=
github.com/felixge/httpsnoop v1.0.1 h1:lvB5Jl89CsZtGIWuTcDM1E/vkVs49/Ml7JJe07l8SPQ= github.com/felixge/httpsnoop v1.0.1 h1:lvB5Jl89CsZtGIWuTcDM1E/vkVs49/Ml7JJe07l8SPQ=
@@ -347,6 +349,8 @@ github.com/imroc/req/v3 v3.52.2 h1:xJocr1aIv0a2K9knfBQ4JnZHk+kWTITdjf0mgDg229I=
github.com/imroc/req/v3 v3.52.2/go.mod h1:dBGsDloOSZJcFs6PnTjZXYBJK70OXbZpizHBLNqcH2k= github.com/imroc/req/v3 v3.52.2/go.mod h1:dBGsDloOSZJcFs6PnTjZXYBJK70OXbZpizHBLNqcH2k=
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A= github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A=
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo= github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=
github.com/jlaffaye/ftp v0.2.4 h1:JqI85DdkfZj8ntaHk8W9U2SC3jNfiPUU70+wtIWmlfE=
github.com/jlaffaye/ftp v0.2.4/go.mod h1:Y1ZnkzxownGIuX7xQ1mQzzkZ21+DbjVIyeKL/V+IIz4=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
@@ -527,6 +531,8 @@ github.com/rs/zerolog v1.31.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWR
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk= github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk=
github.com/ryszard/goskiplist v0.0.0-20150312221310-2dfbae5fcf46 h1:GHRpF1pTW19a8tTFrMLUcfWwyC0pnifVo2ClaLq+hP8= github.com/ryszard/goskiplist v0.0.0-20150312221310-2dfbae5fcf46 h1:GHRpF1pTW19a8tTFrMLUcfWwyC0pnifVo2ClaLq+hP8=
github.com/ryszard/goskiplist v0.0.0-20150312221310-2dfbae5fcf46/go.mod h1:uAQ5PCi+MFsC7HjREoAz1BU+Mq60+05gifQSsHSDG/8= github.com/ryszard/goskiplist v0.0.0-20150312221310-2dfbae5fcf46/go.mod h1:uAQ5PCi+MFsC7HjREoAz1BU+Mq60+05gifQSsHSDG/8=
github.com/secsy/goftp v0.0.0-20200609142545-aa2de14babf4 h1:PT+ElG/UUFMfqy5HrxJxNzj3QBOf7dZwupeVC+mG1Lo=
github.com/secsy/goftp v0.0.0-20200609142545-aa2de14babf4/go.mod h1:MnkX001NG75g3p8bhFycnyIjeQoOjGL6CEIsdE/nKSY=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc= github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg= github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0= github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
@@ -566,6 +572,8 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= 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/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU= github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU=
github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0= github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0=
github.com/tidwall/btree v1.8.1 h1:27ehoXvm5AG/g+1VxLS1SD3vRhp/H7LuEfwNvddEdmA= github.com/tidwall/btree v1.8.1 h1:27ehoXvm5AG/g+1VxLS1SD3vRhp/H7LuEfwNvddEdmA=
@@ -612,6 +620,8 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/mock v0.5.1 h1:ASgazW/qBmR+A32MYFDB6E2POoTgOwT509VP0CT/fjs= go.uber.org/mock v0.5.1 h1:ASgazW/qBmR+A32MYFDB6E2POoTgOwT509VP0CT/fjs=
go.uber.org/mock v0.5.1/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM= go.uber.org/mock v0.5.1/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
go4.org v0.0.0-20230225012048-214862532bf5 h1:nifaUDeh+rPaBCMPMQHZmvJf+QdpLFnuQPwx+LxVmtc= go4.org v0.0.0-20230225012048-214862532bf5 h1:nifaUDeh+rPaBCMPMQHZmvJf+QdpLFnuQPwx+LxVmtc=
go4.org v0.0.0-20230225012048-214862532bf5/go.mod h1:F57wTi5Lrj6WLyswp5EYV1ncrEbFGHD4hhz6S1ZYeaU= go4.org v0.0.0-20230225012048-214862532bf5/go.mod h1:F57wTi5Lrj6WLyswp5EYV1ncrEbFGHD4hhz6S1ZYeaU=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
+4
View File
@@ -3,6 +3,7 @@ package controller
import ( import (
"github.com/GopeedLab/gopeed/internal/tempfiles" "github.com/GopeedLab/gopeed/internal/tempfiles"
"github.com/GopeedLab/gopeed/pkg/base" "github.com/GopeedLab/gopeed/pkg/base"
"github.com/rs/zerolog"
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
@@ -15,6 +16,9 @@ type Controller struct {
TempDir string TempDir string
GetConfig func(v any) GetConfig func(v any)
GetProxy func(requestProxy *base.RequestProxy) func(*http.Request) (*url.URL, error) GetProxy func(requestProxy *base.RequestProxy) func(*http.Request) (*url.URL, error)
// Logger is the downloader's core logger. It may be nil, in which case
// fetchers log nothing.
Logger *zerolog.Logger
FileController FileController
//ContextDialer() (proxy.Dialer, error) //ContextDialer() (proxy.Dialer, error)
} }
+404
View File
@@ -0,0 +1,404 @@
package ftp
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/textproto"
"net/url"
"strings"
"sync"
"time"
"github.com/jlaffaye/ftp"
"golang.org/x/net/proxy"
pftp "github.com/GopeedLab/gopeed/pkg/protocol/ftp"
)
const (
connectTimeout = 15 * time.Second
readTimeout = 15 * time.Second
quitTimeout = 2 * time.Second
)
// target is a parsed FTP URL. It holds the password, so it must never be
// formatted into an error or a log line.
type target struct {
host string // host name or IP, the TLS server name
addr string // host:port
user string
pass string
path string // path relative to the login directory, "" for the directory itself
tlsMode string
}
// parseTarget reads an ftp, ftps or ftpes URL. The path follows RFC 1738: it
// is relative to the login directory, and an encoded leading slash
// (ftp://host/%2Fpub) makes it absolute.
func parseTarget(rawURL, optTLS string) (*target, error) {
u, err := url.Parse(rawURL)
if err != nil {
// url.Error repeats the whole URL, password included.
return nil, errors.New("ftp: invalid URL")
}
t := &target{}
switch strings.ToLower(u.Scheme) {
case "ftps":
t.tlsMode = pftp.TLSImplicit
case "ftpes":
t.tlsMode = pftp.TLSExplicit
case "ftp":
switch strings.ToLower(optTLS) {
case "", pftp.TLSNone:
t.tlsMode = pftp.TLSNone
case pftp.TLSExplicit:
t.tlsMode = pftp.TLSExplicit
case pftp.TLSImplicit:
t.tlsMode = pftp.TLSImplicit
default:
return nil, fmt.Errorf("ftp: unknown tls mode %q", optTLS)
}
default:
return nil, fmt.Errorf("ftp: unsupported scheme %q", u.Scheme)
}
t.host = u.Hostname()
if t.host == "" {
return nil, errors.New("ftp: URL has no host")
}
port := u.Port()
if port == "" {
port = "21"
if t.tlsMode == pftp.TLSImplicit {
port = "990"
}
}
t.addr = net.JoinHostPort(t.host, port)
if u.User != nil {
// Username and Password are already percent-decoded.
t.user = u.User.Username()
t.pass, _ = u.User.Password()
}
if t.user == "" {
t.user, t.pass = "anonymous", "anonymous@"
}
t.path = strings.TrimPrefix(u.Path, "/")
return t, nil
}
type dialContextFunc func(ctx context.Context, network, addr string) (net.Conn, error)
// session is one logged-in control connection. It owns the network
// connections it opens, so abort can unblock any read or write in progress.
type session struct {
*ftp.ServerConn
ctrl net.Conn // control connection as dialed, under any TLS layer
dataHost string // where data connections go
mu sync.Mutex
data net.Conn // current data connection as dialed
closed bool
stop func() bool
}
// deadline bounds the next control-connection exchange. The control
// connection is idle during a transfer, so every exchange sets a new one.
func (s *session) deadline() {
_ = s.ctrl.SetDeadline(time.Now().Add(readTimeout))
}
// clearDeadline lets the control connection stay idle through a transfer.
func (s *session) clearDeadline() {
_ = s.ctrl.SetDeadline(time.Time{})
}
// abort closes every connection at once. Pending calls fail immediately.
func (s *session) abort() {
s.mu.Lock()
defer s.mu.Unlock()
s.closed = true
_ = s.ctrl.Close()
if s.data != nil {
_ = s.data.Close()
}
}
// quit logs out and waits, briefly, for the server to hang up. Servers that
// cap logins count a session until they have seen it end, so the next login
// would otherwise be refused.
func (s *session) quit() {
if s.stop != nil {
s.stop()
}
_ = s.ctrl.SetDeadline(time.Now().Add(quitTimeout))
if s.ServerConn != nil {
_ = s.ServerConn.Quit()
}
s.abort()
}
func (s *session) setData(c net.Conn) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
_ = c.Close()
return net.ErrClosed
}
s.data = c
return nil
}
// ctrlConn is the control connection handed to the ftp library.
type ctrlConn struct {
net.Conn
}
// RemoteAddr must be a *net.TCPAddr: the library asserts it. A connection
// through a proxy may report something else, and its address is not used
// for data connections anyway (see dialData).
func (c ctrlConn) RemoteAddr() net.Addr {
if a, ok := c.Conn.RemoteAddr().(*net.TCPAddr); ok {
return a
}
return &net.TCPAddr{}
}
// Close is called by the library's Quit right after it sends QUIT. Reading
// until the server hangs up (bounded by the deadline quit set) tells us the
// server has ended the session.
func (c ctrlConn) Close() error {
_, _ = io.Copy(io.Discard, c.Conn)
return c.Conn.Close()
}
// dial opens a control connection, upgrades it to TLS when asked, and logs in.
//
// The library is given a dial function for every connection. That is how
// data connections go through the same proxy as the control connection, but
// it also means the library does no TLS on them: with a dial function it
// neither wraps an implicit-TLS control connection nor any data connection.
// We do both here. Explicit TLS (AUTH TLS) is still done by the library, and
// so are PBSZ and PROT P after login. For the same reason the library's
// DialWithTimeout and DialWithContext would have no effect: connectTimeout
// and ctx are applied to our own dials instead.
func (f *Fetcher) dial(ctx context.Context, t *target) (*session, error) {
netDial, proxied, err := f.netDialer(t)
if err != nil {
return nil, err
}
var tlsConf *tls.Config
if t.tlsMode != pftp.TLSNone {
tlsConf = f.tlsConfig(t.host)
}
dialCtx, cancel := context.WithTimeout(ctx, connectTimeout)
defer cancel()
raw, err := netDial(dialCtx, "tcp", t.addr)
if err != nil {
return nil, err
}
ctrl := raw
if t.tlsMode == pftp.TLSImplicit {
tc := tls.Client(raw, tlsConf)
if err := tc.HandshakeContext(dialCtx); err != nil {
_ = raw.Close()
return nil, err
}
ctrl = tc
}
s := &session{ctrl: raw, dataHost: t.host}
if a, ok := raw.RemoteAddr().(*net.TCPAddr); ok && !proxied {
// Same IP as the control connection, as the library itself does,
// so a name with several addresses cannot send us elsewhere.
s.dataHost = a.IP.String()
}
s.stop = context.AfterFunc(ctx, s.abort)
s.deadline()
handedOut := false
opts := []ftp.DialOption{
ftp.DialWithShutTimeout(readTimeout),
ftp.DialWithDialFunc(func(network, addr string) (net.Conn, error) {
if !handedOut {
// Dial asks for the control connection first, once.
handedOut = true
return ctrlConn{ctrl}, nil
}
return s.dialData(ctx, netDial, tlsConf, addr)
}),
}
switch t.tlsMode {
case pftp.TLSImplicit:
opts = append(opts, ftp.DialWithTLS(tlsConf))
case pftp.TLSExplicit:
opts = append(opts, ftp.DialWithExplicitTLS(tlsConf))
}
c, err := ftp.Dial(t.addr, opts...)
if err != nil {
s.stop()
s.abort()
return nil, err
}
s.ServerConn = c
s.deadline()
if err := c.Login(t.user, t.pass); err != nil {
s.stop()
s.abort()
return nil, err
}
return s, nil
}
// dialData opens a passive data connection. The library takes the host from
// the control connection's peer, which through a proxy is the proxy, so only
// the port is used here.
func (s *session) dialData(ctx context.Context, netDial dialContextFunc, tlsConf *tls.Config, addr string) (net.Conn, error) {
_, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
dialCtx, cancel := context.WithTimeout(ctx, connectTimeout)
defer cancel()
raw, err := netDial(dialCtx, "tcp", net.JoinHostPort(s.dataHost, port))
if err != nil {
return nil, err
}
if err := s.setData(raw); err != nil {
return nil, err
}
if tlsConf != nil {
// The handshake runs on the first read, as in the library, because
// some servers only start it once the transfer command is answered.
return tls.Client(raw, tlsConf), nil
}
return raw, nil
}
// tlsConfig returns the TLS settings for one control connection and its data
// connections. Certificates are verified unless the request sets
// skipVerifyCert, as for HTTP.
//
// Each call gets its own one-entry session cache, so a data connection
// resumes the TLS session of its own control connection. vsftpd
// (require_ssl_reuse) only checks that some session was resumed, but ProFTPD's
// mod_tls also checks that it is the control connection's; a cache shared by
// several workers would hand a data connection another worker's session.
// A cache in the manager's base config is kept as given.
func (f *Fetcher) tlsConfig(host string) *tls.Config {
cfg := &tls.Config{}
if f.manager != nil && f.manager.baseTLS != nil {
cfg = f.manager.baseTLS.Clone()
}
cfg.ServerName = host
if f.meta.Req != nil && f.meta.Req.SkipVerifyCert {
cfg.InsecureSkipVerify = true
}
if cfg.ClientSessionCache == nil {
cfg.ClientSessionCache = tls.NewLRUClientSessionCache(1)
}
return cfg
}
// netDialer picks how to reach the server, from the same proxy settings the
// HTTP protocol reads (the task's proxy, otherwise the global one).
func (f *Fetcher) netDialer(t *target) (dialContextFunc, bool, error) {
direct := (&net.Dialer{Timeout: connectTimeout}).DialContext
pu, err := f.proxyURL(t)
if err != nil {
return nil, false, err
}
if pu == nil {
return direct, false, nil
}
switch strings.ToLower(pu.Scheme) {
case "socks5", "socks5h":
d, err := proxy.FromURL(pu, &net.Dialer{Timeout: connectTimeout})
if err != nil {
return nil, false, fmt.Errorf("ftp: socks5 proxy: %w", err)
}
if cd, ok := d.(proxy.ContextDialer); ok {
return cd.DialContext, true, nil
}
return func(_ context.Context, network, addr string) (net.Conn, error) {
return d.Dial(network, addr)
}, true, nil
default:
// An HTTP proxy is not used. Every passive data connection goes to
// a port the server picks, and HTTP proxies usually allow CONNECT to
// port 443 only, so the transfer would fail after the login worked.
f.warnOnce.Do(func() {
if l := f.logger(); l != nil {
l.Warn().Msgf("ftp: the %s proxy at %s cannot carry FTP data connections (HTTP proxy), connecting directly; use a SOCKS5 proxy for FTP", strings.ToLower(pu.Scheme), pu.Host)
}
})
return direct, false, nil
}
}
func (f *Fetcher) proxyURL(t *target) (*url.URL, error) {
if f.ctl == nil || f.ctl.GetProxy == nil {
return nil, nil
}
handler := f.ctl.GetProxy(f.meta.Req.Proxy)
if handler == nil {
return nil, nil
}
// The proxy chooser reads only the URL; the credentials stay out.
req := &http.Request{URL: &url.URL{Scheme: "ftp", Host: t.addr, Path: "/" + t.path}, Header: http.Header{}}
pu, err := handler(req)
if err != nil {
return nil, errors.New("ftp: cannot read the proxy settings")
}
return pu, nil
}
// isLoginRefusal tells a server that is full apart from bad credentials.
// 421 always means "not now". 530 means a refused login; it is only a
// capacity limit when these credentials have worked before. The library
// drops the code when USER itself is refused, so a "too many" message counts
// as well.
func isLoginRefusal(err error, credentialsWorked bool) bool {
var te *textproto.Error
if errors.As(err, &te) {
switch te.Code {
case ftp.StatusNotAvailable:
return true
case ftp.StatusNotLoggedIn:
return credentialsWorked || strings.Contains(strings.ToLower(te.Msg), "too many")
}
return false
}
return strings.Contains(strings.ToLower(err.Error()), "too many")
}
// isPermanent reports errors a retry cannot fix: a 5xx reply and a
// certificate that does not verify.
func isPermanent(err error) bool {
var te *textproto.Error
if errors.As(err, &te) {
return te.Code >= 500
}
var verifyErr *tls.CertificateVerificationError
if errors.As(err, &verifyErr) {
return true
}
var recordErr tls.RecordHeaderError
if errors.As(err, &recordErr) {
return true
}
return errors.Is(err, errSizeChanged)
}
func replyCode(err error) int {
var te *textproto.Error
if errors.As(err, &te) {
return te.Code
}
return 0
}
+146
View File
@@ -0,0 +1,146 @@
package ftp_test
import (
"bytes"
"strings"
"sync"
"testing"
"time"
"github.com/rs/zerolog"
"github.com/GopeedLab/gopeed/internal/logger"
iftp "github.com/GopeedLab/gopeed/internal/protocol/ftp"
"github.com/GopeedLab/gopeed/pkg/base"
"github.com/GopeedLab/gopeed/pkg/download"
pftp "github.com/GopeedLab/gopeed/pkg/protocol/ftp"
)
// syncBuffer is a log sink that the downloader's goroutines can share.
type syncBuffer struct {
mu sync.Mutex
buf bytes.Buffer
}
func (b *syncBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Write(p)
}
func (b *syncBuffer) String() string {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.String()
}
// taskEvents records the first done or error event of every task, so the
// test never reads a task's status while the downloader writes it.
type taskEvents struct {
mu sync.Mutex
final map[string]download.EventKey
}
func (e *taskEvents) listen(ev *download.Event) {
if ev.Key != download.EventKeyDone && ev.Key != download.EventKeyError {
return
}
e.mu.Lock()
defer e.mu.Unlock()
if _, seen := e.final[ev.Task.ID]; !seen {
e.final[ev.Task.ID] = ev.Key
}
}
func (e *taskEvents) wait(t *testing.T, id string) download.EventKey {
t.Helper()
deadline := time.Now().Add(60 * time.Second)
for time.Now().Before(deadline) {
e.mu.Lock()
key, ok := e.final[id]
e.mu.Unlock()
if ok {
return key
}
time.Sleep(20 * time.Millisecond)
}
t.Fatalf("task %s did not finish", id)
return ""
}
// TestPasswordNeverLogged runs FTP tasks through the downloader with its core
// logger captured: a success, a missing file and a wrong password, all behind
// an HTTP proxy that FTP must skip with a warning.
func TestPasswordNeverLogged(t *testing.T) {
srv := iftp.StartFTPServer(t, iftp.ServerOptions{User: "u", Pass: "p@ss"})
want := srv.WriteFile(t, "secret.bin", iftp.RandomBytes(300000, 21))
d := download.NewDownloader(&download.DownloaderConfig{Storage: download.NewMemStorage(), StorageDir: t.TempDir()})
logs := &syncBuffer{}
d.Logger = &logger.Logger{Logger: zerolog.New(logs)}
events := &taskEvents{final: map[string]download.EventKey{}}
d.Listener(events.listen)
if err := d.Setup(); err != nil {
t.Fatal(err)
}
// Close, not Clear: Clear resets the extension list without a lock while
// the last task's done hooks may still read it.
defer d.Close()
cfg, err := d.GetConfig()
if err != nil {
t.Fatal(err)
}
cfg.Proxy = &base.DownloaderProxyConfig{Enable: true, Scheme: "http", Host: "127.0.0.1:1", Usr: "proxyuser", Pwd: "proxysecret"}
if err := d.PutConfig(cfg); err != nil {
t.Fatal(err)
}
dir := t.TempDir()
create := func(rawURL string) string {
id, err := d.CreateDirect(&base.Request{URL: rawURL}, &base.Options{Path: dir, Extra: &pftp.OptsExtra{Connections: 2}})
if err != nil {
if strings.Contains(err.Error(), "p@ss") || strings.Contains(err.Error(), "p%40ss") {
t.Fatalf("the password leaked into an error: %v", err)
}
t.Fatal(err)
}
return id
}
root := "ftp://u:p%40ss@" + srv.Addr + "/"
okID := create(root + "secret.bin")
if key := events.wait(t, okID); key != download.EventKeyDone {
t.Fatalf("download ended with %q, logs:\n%s", key, logs.String())
}
ok := d.GetTask(okID)
if ok.Protocol != "ftp" {
t.Fatalf("protocol %q, want ftp", ok.Protocol)
}
if got := iftp.FileSHA256(t, ok.Meta.SingleFilepath()); got != want {
t.Fatalf("sha256 %s, want %s", got, want)
}
missingID := create(root + "missing.bin")
if key := events.wait(t, missingID); key != download.EventKeyError {
t.Fatalf("a missing file must fail, got %q", key)
}
wrongID := create("ftp://u:wr0ng%40pw@" + srv.Addr + "/secret.bin")
if key := events.wait(t, wrongID); key != download.EventKeyError {
t.Fatalf("a wrong password must fail, got %q", key)
}
missing, wrong := d.GetTask(missingID), d.GetTask(wrongID)
for _, task := range []*download.Task{ok, missing, wrong} {
if name := task.Name(); strings.Contains(name, "p@ss") || strings.Contains(name, "p%40ss") || strings.Contains(name, "wr0ng") {
t.Fatalf("task name %q shows the password", name)
}
}
out := logs.String()
if !strings.Contains(out, "task id") || !strings.Contains(out, "HTTP proxy") {
t.Fatalf("the captured log misses the expected lines, so it proves nothing:\n%s", out)
}
for _, secret := range []string{"p@ss", "p%40ss", "wr0ng", "proxysecret"} {
if strings.Contains(out, secret) {
t.Fatalf("%q appears in the log:\n%s", secret, out)
}
}
}
File diff suppressed because it is too large. Load diff
+109
View File
@@ -0,0 +1,109 @@
package ftp
import (
"crypto/tls"
"net/url"
"path"
"strings"
"github.com/GopeedLab/gopeed/internal/fetcher"
"github.com/GopeedLab/gopeed/pkg/base"
pftp "github.com/GopeedLab/gopeed/pkg/protocol/ftp"
)
// fetcherData is what a task saves to resume later. Segments has the same
// Begin, End and Downloaded fields every version writes; the other fields are
// optional, so a save without them still restores.
type fetcherData struct {
Segments []*segment
// MaxConns is the login ceiling the server enforced, 0 when none was hit.
MaxConns int `json:",omitempty"`
// NoRest records that the server refused REST, so the task downloads each
// file in one sequential stream.
NoRest bool `json:",omitempty"`
}
// FetcherManager handles ftp://, ftps:// (implicit TLS) and ftpes:// (explicit
// TLS) URLs.
type FetcherManager struct {
// baseTLS is the base for every TLS connection. Nil means the system
// roots; the package's tests set it to trust their own certificate. The
// task's skipVerifyCert still turns verification off.
baseTLS *tls.Config
}
func (fm *FetcherManager) Name() string {
return "ftp"
}
func (fm *FetcherManager) Filters() []*fetcher.SchemeFilter {
return []*fetcher.SchemeFilter{
{Type: fetcher.FilterTypeUrl, Pattern: "FTP"},
{Type: fetcher.FilterTypeUrl, Pattern: "FTPS"},
{Type: fetcher.FilterTypeUrl, Pattern: "FTPES"},
}
}
func (fm *FetcherManager) Build() fetcher.Fetcher {
return &Fetcher{manager: fm}
}
// ParseName names a task before it is resolved. It never includes the
// userinfo of the URL.
func (fm *FetcherManager) ParseName(u string) string {
parsed, err := url.Parse(u)
if err != nil {
return ""
}
name := path.Base(strings.TrimSuffix(parsed.Path, "/"))
if name == "" || name == "/" || name == "." {
name = parsed.Hostname()
}
return name
}
func (fm *FetcherManager) AutoRename() bool {
return true
}
func (fm *FetcherManager) DefaultConfig() any {
return &config{Connections: defaultConnections}
}
func (fm *FetcherManager) Store(f fetcher.Fetcher) (any, error) {
ff := f.(*Fetcher)
ff.mu.Lock()
defer ff.mu.Unlock()
segments := make([]*segment, len(ff.segments))
for i, s := range ff.segments {
c := *s
segments[i] = &c
}
return &fetcherData{
Segments: segments,
MaxConns: ff.maxConns,
NoRest: ff.noRest,
}, nil
}
func (fm *FetcherManager) Restore() (v any, f func(meta *fetcher.FetcherMeta, v any) fetcher.Fetcher) {
return &fetcherData{}, func(meta *fetcher.FetcherMeta, v any) fetcher.Fetcher {
fd := v.(*fetcherData)
ff := fm.Build().(*Fetcher)
ff.meta = meta
if meta != nil && meta.Req != nil {
_ = base.ParseReqExtra[pftp.ReqExtra](meta.Req)
}
if meta != nil && meta.Opts != nil {
_ = base.ParseOptExtra[pftp.OptsExtra](meta.Opts)
}
ff.segments = fd.Segments
ff.maxConns = fd.MaxConns
ff.noRest = fd.NoRest
return ff
}
}
func (fm *FetcherManager) Close() error {
return nil
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+187
View File
@@ -0,0 +1,187 @@
package ftp
import (
"cmp"
"fmt"
"path"
"slices"
"strings"
"time"
"github.com/jlaffaye/ftp"
"github.com/GopeedLab/gopeed/pkg/base"
)
// Limits of a directory download. A tree past either one is refused with an
// error that names the limit; it is never cut short.
const maxWalkDepth = 8
// maxWalkFiles is a variable so tests can lower it.
var maxWalkFiles = 10000
// resolveTarget describes the URL's path: one file, or a directory walked
// into a multi-file resource whose paths are relative to it.
func (f *Fetcher) resolveTarget(s *session, t *target) (*base.Resource, error) {
isDir, size, mtime, err := f.stat(s, t.path)
if err != nil {
return nil, err
}
if !isDir {
return &base.Resource{
Size: size,
Range: true,
Files: []*base.FileInfo{{
Name: path.Base(t.path),
Size: size,
Ctime: mtime,
}},
}, nil
}
files, err := f.walk(s, t.path)
if err != nil {
return nil, err
}
name := path.Base(strings.TrimSuffix(t.path, "/"))
if name == "" || name == "." || name == "/" {
name = t.host
}
res := &base.Resource{Name: name, Range: true, Files: files}
res.CalcSize(nil)
return res, nil
}
// stat tells a file from a directory. MLST answers both at once. Without
// it, SIZE answers for a file, and a directory is one we can change into.
func (f *Fetcher) stat(s *session, p string) (isDir bool, size int64, mtime *time.Time, err error) {
if p == "" || strings.HasSuffix(p, "/") {
return true, 0, nil, nil
}
s.deadline()
if entry, mlstErr := s.GetEntry(p); mlstErr == nil {
switch entry.Type {
case ftp.EntryTypeFolder:
return true, 0, nil, nil
case ftp.EntryTypeFile:
if !entry.Time.IsZero() {
t := entry.Time
mtime = &t
}
return false, int64(entry.Size), mtime, nil
}
// A link: SIZE below follows it on the server.
}
// MLST is missing or refused the path: the older commands decide. A
// broken connection fails them too, with its own error.
s.deadline()
size, sizeErr := s.FileSize(p)
if sizeErr == nil {
if s.IsGetTimeSupported() {
s.deadline()
if t, err := s.GetTime(p); err == nil {
mtime = &t
}
}
return false, size, mtime, nil
}
if replyCode(sizeErr) == 0 {
return false, 0, nil, sizeErr
}
// SIZE failed: a directory, or a missing path.
s.deadline()
cwd, err := s.CurrentDir()
if err != nil {
return false, 0, nil, err
}
s.deadline()
if err := s.ChangeDir(p); err != nil {
return false, 0, nil, sizeErr
}
s.deadline()
if err := s.ChangeDir(cwd); err != nil {
return false, 0, nil, err
}
return true, 0, nil, nil
}
// safeEntryName reports whether a name from a listing can become a local
// path element. A hostile server could otherwise list "../x" and write
// outside the task directory.
func safeEntryName(name string) bool {
if name == "" || name == "." || name == ".." {
return false
}
return !strings.ContainsAny(name, "/\\\x00")
}
// walk lists a directory tree, at most maxWalkDepth levels below root and
// maxWalkFiles files. Files come back sorted by path, then name.
func (f *Fetcher) walk(s *session, root string) ([]*base.FileInfo, error) {
type dir struct {
remote string // path on the server
rel string // path below root, "" for root itself
depth int
}
var files []*base.FileInfo
stack := []dir{{remote: strings.TrimSuffix(root, "/"), rel: "", depth: 0}}
for len(stack) > 0 {
d := stack[len(stack)-1]
stack = stack[:len(stack)-1]
s.deadline()
entries, err := s.List(d.remote)
if err != nil {
return nil, err
}
for _, e := range entries {
if e.Name == "." || e.Name == ".." {
continue
}
if !safeEntryName(e.Name) {
f.warn("ftp: skipping a listed name that is not a safe file name: %q", e.Name)
continue
}
remote := path.Join(d.remote, e.Name)
rel := path.Join(d.rel, e.Name)
if d.remote == "" {
remote = e.Name
}
entryType, size := e.Type, int64(e.Size)
if entryType == ftp.EntryTypeLink {
// A link to a file has a size; a link to a directory is
// not followed, so a loop cannot make the walk endless.
s.deadline()
linkSize, err := s.FileSize(remote)
if err != nil {
f.warn("ftp: skipping link %q: %v", rel, err)
continue
}
entryType, size = ftp.EntryTypeFile, linkSize
}
switch entryType {
case ftp.EntryTypeFolder:
if d.depth+1 > maxWalkDepth {
return nil, fmt.Errorf("ftp: the folder is deeper than %d levels, the limit for a folder download", maxWalkDepth)
}
stack = append(stack, dir{remote: remote, rel: rel, depth: d.depth + 1})
case ftp.EntryTypeFile:
if len(files) >= maxWalkFiles {
return nil, fmt.Errorf("ftp: the folder has more than %d files, the limit for a folder download", maxWalkFiles)
}
fi := &base.FileInfo{Name: e.Name, Path: d.rel, Size: size}
if !e.Time.IsZero() {
t := e.Time
fi.Ctime = &t
}
files = append(files, fi)
}
}
}
slices.SortFunc(files, func(a, b *base.FileInfo) int {
return cmp.Or(strings.Compare(a.Path, b.Path), strings.Compare(a.Name, b.Name))
})
return files, nil
}
+32 -1
View File
@@ -25,6 +25,7 @@ import (
"github.com/GopeedLab/gopeed/internal/tempfiles" "github.com/GopeedLab/gopeed/internal/tempfiles"
webviewproxy "github.com/GopeedLab/gopeed/internal/webview/proxy" webviewproxy "github.com/GopeedLab/gopeed/internal/webview/proxy"
"github.com/GopeedLab/gopeed/pkg/base" "github.com/GopeedLab/gopeed/pkg/base"
"github.com/GopeedLab/gopeed/pkg/protocol/ftp"
"github.com/GopeedLab/gopeed/pkg/protocol/http" "github.com/GopeedLab/gopeed/pkg/protocol/http"
"github.com/GopeedLab/gopeed/pkg/util" "github.com/GopeedLab/gopeed/pkg/util"
gonanoid "github.com/matoous/go-nanoid/v2" gonanoid "github.com/matoous/go-nanoid/v2"
@@ -459,6 +460,9 @@ func (d *Downloader) setupFetcher(fm fetcher.FetcherManager, fetcher fetcher.Fet
ctl.GetConfig = func(v any) { ctl.GetConfig = func(v any) {
d.getProtocolConfig(fm.Name(), v) d.getProtocolConfig(fm.Name(), v)
} }
if d.Logger != nil {
ctl.Logger = &d.Logger.Logger
}
// Get proxy config, task request proxy config has higher priority, then use global proxy config // Get proxy config, task request proxy config has higher priority, then use global proxy config
ctl.GetProxy = func(requestProxy *base.RequestProxy) func(*gohttp.Request) (*url.URL, error) { ctl.GetProxy = func(requestProxy *base.RequestProxy) func(*gohttp.Request) (*url.URL, error) {
// Registry-backed blob URLs are loopback capability URLs and must never be // Registry-backed blob URLs are loopback capability URLs and must never be
@@ -1594,7 +1598,7 @@ func (d *Downloader) watch(task *Task) {
d.triggerWebhooks(WebhookEventDownloadDone, task, nil) d.triggerWebhooks(WebhookEventDownloadDone, task, nil)
d.triggerScripts(ScriptEventDownloadDone, task, nil) d.triggerScripts(ScriptEventDownloadDone, task, nil)
if e, ok := task.Meta.Opts.Extra.(*http.OptsExtra); ok { if e := postDownloadExtra(task.Meta); e != nil {
downloadFilePath := task.Meta.SingleFilepath() downloadFilePath := task.Meta.SingleFilepath()
cfg, _ := d.GetConfig() cfg, _ := d.GetConfig()
@@ -1654,6 +1658,33 @@ func (d *Downloader) watch(task *Task) {
} }
} }
// postDownloadExtra returns the auto-torrent and auto-extract options of a
// finished single-file task, in the HTTP options shape the extraction code
// takes. FTP options carry the same fields. An FTP folder has no single file
// to act on, so it gets nil, as does any other protocol.
func postDownloadExtra(meta *fetcher.FetcherMeta) *http.OptsExtra {
if meta == nil || meta.Opts == nil {
return nil
}
switch e := meta.Opts.Extra.(type) {
case *http.OptsExtra:
return e
case *ftp.OptsExtra:
if meta.Res == nil || meta.Res.Name != "" || len(meta.Res.Files) != 1 {
return nil
}
return &http.OptsExtra{
Connections: e.Connections,
AutoTorrent: e.AutoTorrent,
DeleteTorrentAfterDownload: e.DeleteTorrentAfterDownload,
AutoExtract: e.AutoExtract,
ArchivePassword: e.ArchivePassword,
DeleteAfterExtract: e.DeleteAfterExtract,
}
}
return nil
}
func (d *Downloader) doOnError(task *Task, err error) { func (d *Downloader) doOnError(task *Task, err error) {
d.handleOnError(task, err, false) d.handleOnError(task, err, false)
} }
+57
View File
@@ -0,0 +1,57 @@
package download
import (
"testing"
"github.com/GopeedLab/gopeed/internal/fetcher"
"github.com/GopeedLab/gopeed/pkg/base"
"github.com/GopeedLab/gopeed/pkg/protocol/ftp"
"github.com/GopeedLab/gopeed/pkg/protocol/http"
)
// TestTorrentNameIsFile checks the default manager order: an FTP URL whose
// name looks like a torrent or a playlist is still an FTP download.
func TestTorrentNameIsFile(t *testing.T) {
d := NewDownloader(nil)
for u, want := range map[string]string{
"ftp://h/x.torrent": "ftp",
"ftp://h/v.m3u8": "ftp",
"ftps://h/x.torrent": "ftp",
"ftpes://h/a.bin": "ftp",
"https://h/v.m3u8": "hls",
"https://h/x.torrent": "http",
"magnet:?xt=urn:btih:": "bt",
} {
fm, err := d.parseFm(u)
if err != nil {
t.Fatalf("%s: %v", u, err)
}
if fm.Name() != want {
t.Fatalf("%s goes to %q, want %q", u, fm.Name(), want)
}
}
}
func TestPostDownloadExtraAcceptsFTP(t *testing.T) {
yes := true
file := &base.Resource{Files: []*base.FileInfo{{Name: "a.zip"}}}
folder := &base.Resource{Name: "dir", Files: []*base.FileInfo{{Name: "a.zip"}}}
httpExtra := &http.OptsExtra{AutoExtract: &yes}
if got := postDownloadExtra(&fetcher.FetcherMeta{Res: file, Opts: &base.Options{Extra: httpExtra}}); got != httpExtra {
t.Fatalf("HTTP options must pass through unchanged, got %+v", got)
}
ftpExtra := &ftp.OptsExtra{Connections: 4, AutoTorrent: &yes, DeleteTorrentAfterDownload: &yes, AutoExtract: &yes, ArchivePassword: "pw", DeleteAfterExtract: true}
got := postDownloadExtra(&fetcher.FetcherMeta{Res: file, Opts: &base.Options{Extra: ftpExtra}})
if got == nil || got.AutoTorrent != &yes || got.DeleteTorrentAfterDownload != &yes || got.AutoExtract != &yes ||
got.ArchivePassword != "pw" || !got.DeleteAfterExtract {
t.Fatalf("FTP options were not carried over: %+v", got)
}
if got := postDownloadExtra(&fetcher.FetcherMeta{Res: folder, Opts: &base.Options{Extra: ftpExtra}}); got != nil {
t.Fatalf("an FTP folder has no single file to extract, got %+v", got)
}
if got := postDownloadExtra(&fetcher.FetcherMeta{Res: file, Opts: &base.Options{}}); got != nil {
t.Fatalf("no options, got %+v", got)
}
}
+5
View File
@@ -10,6 +10,7 @@ import (
"github.com/GopeedLab/gopeed/internal/production" "github.com/GopeedLab/gopeed/internal/production"
"github.com/GopeedLab/gopeed/internal/protocol/bt" "github.com/GopeedLab/gopeed/internal/protocol/bt"
"github.com/GopeedLab/gopeed/internal/protocol/ed2k" "github.com/GopeedLab/gopeed/internal/protocol/ed2k"
"github.com/GopeedLab/gopeed/internal/protocol/ftp"
"github.com/GopeedLab/gopeed/internal/protocol/hls" "github.com/GopeedLab/gopeed/internal/protocol/hls"
"github.com/GopeedLab/gopeed/internal/protocol/http" "github.com/GopeedLab/gopeed/internal/protocol/http"
"github.com/GopeedLab/gopeed/pkg/base" "github.com/GopeedLab/gopeed/pkg/base"
@@ -229,6 +230,10 @@ func (cfg *DownloaderConfig) Init() *DownloaderConfig {
} }
if len(cfg.FetchManagers) == 0 { if len(cfg.FetchManagers) == 0 {
cfg.FetchManagers = []fetcher.FetcherManager{ cfg.FetchManagers = []fetcher.FetcherManager{
// FTP matches by URL scheme only. It comes before the managers that
// match by file extension, so ftp://host/x.torrent or x.m3u8 is
// downloaded as a file over FTP.
new(ftp.FetcherManager),
new(hls.FetcherManager), new(hls.FetcherManager),
new(http.FetcherManager), new(http.FetcherManager),
new(bt.FetcherManager), new(bt.FetcherManager),
+54
View File
@@ -0,0 +1,54 @@
package ftp
// TLS modes for the "tls" field of an ftp:// request. ftps:// URLs always use
// implicit TLS and ftpes:// URLs always use explicit TLS.
const (
TLSNone = "none"
TLSExplicit = "explicit"
TLSImplicit = "implicit"
)
// ReqExtra is the extra of an FTP request. The TLS mode is part of the request,
// because resolving the link already needs a connection.
type ReqExtra struct {
// TLS upgrades a plain ftp:// URL: "none" (default), "explicit" (AUTH TLS)
// or "implicit". It is ignored for ftps:// and ftpes:// URLs.
TLS string `json:"tls"`
}
type OptsExtra struct {
// Connections is the maximum number of parallel logins. Servers often cap
// logins per user, so the fetcher lowers it when the server refuses one.
Connections int `json:"connections"`
// AutoTorrent when task download complete, and it is a .torrent file, it will be auto create a new task for the torrent file
// nil means use global config, true/false means explicit setting
AutoTorrent *bool `json:"autoTorrent"`
// DeleteTorrentAfterDownload when true, deletes the .torrent file after creating BT task
// nil means use global config, true/false means explicit setting
DeleteTorrentAfterDownload *bool `json:"deleteTorrentAfterDownload"`
// AutoExtract when task download complete, and it is an archive file, it will be auto extracted
// nil means use global config, true/false means explicit setting
AutoExtract *bool `json:"autoExtract"`
// ArchivePassword is the password for extracting password-protected archives
ArchivePassword string `json:"archivePassword"`
// DeleteAfterExtract when true, deletes the archive file after successful extraction
DeleteAfterExtract bool `json:"deleteAfterExtract"`
}
// Stats for download. It has the same shape as the HTTP protocol's stats, so
// clients can show FTP connections the way they show HTTP connections.
type Stats struct {
Connections []*StatsConnection `json:"connections"`
}
// StatsConnection describes one login that took part in the download.
type StatsConnection struct {
Downloaded int64 `json:"downloaded"`
// Total is the resource size divided by the number of connections,
// rounded up to a whole byte, as in the HTTP protocol's stats. It is zero
// when the resource size is unknown.
Total int64 `json:"total"`
Completed bool `json:"completed"`
Failed bool `json:"failed"`
RetryTimes int `json:"retryTimes"`
}
@@ -64,6 +64,10 @@ class ProtocolConfig {
Ed2kConfig ed2k = Ed2kConfig(); Ed2kConfig ed2k = Ed2kConfig();
HlsConfig hls = HlsConfig(); HlsConfig hls = HlsConfig();
/// A server without FTP support sends no `ftp` key; the defaults keep the rest of the config readable.
@JsonKey(fromJson: _ftpConfigFromJson)
FtpConfig ftp = FtpConfig();
ProtocolConfig(); ProtocolConfig();
factory ProtocolConfig.fromJson(Map<String, dynamic>? json) => factory ProtocolConfig.fromJson(Map<String, dynamic>? json) =>
@@ -91,6 +95,20 @@ class HlsConfig {
Map<String, dynamic> toJson() => _$HlsConfigToJson(this); Map<String, dynamic> toJson() => _$HlsConfigToJson(this);
} }
FtpConfig _ftpConfigFromJson(Map<String, dynamic>? json) => json == null ? FtpConfig() : FtpConfig.fromJson(json);
/// Global FTP defaults. It mirrors the `ftp` protocol config of the server.
@JsonSerializable()
class FtpConfig {
int connections;
FtpConfig({this.connections = 0});
factory FtpConfig.fromJson(Map<String, dynamic> json) => _$FtpConfigFromJson(json);
Map<String, dynamic> toJson() => _$FtpConfigToJson(this);
}
@JsonSerializable() @JsonSerializable()
class HttpConfig { class HttpConfig {
String userAgent; String userAgent;
@@ -67,13 +67,15 @@ ProtocolConfig _$ProtocolConfigFromJson(Map<String, dynamic> json) => ProtocolCo
..http = HttpConfig.fromJson(json['http'] as Map<String, dynamic>) ..http = HttpConfig.fromJson(json['http'] as Map<String, dynamic>)
..bt = BtConfig.fromJson(json['bt'] as Map<String, dynamic>) ..bt = BtConfig.fromJson(json['bt'] as Map<String, dynamic>)
..ed2k = Ed2kConfig.fromJson(json['ed2k'] as Map<String, dynamic>) ..ed2k = Ed2kConfig.fromJson(json['ed2k'] as Map<String, dynamic>)
..hls = HlsConfig.fromJson(json['hls'] as Map<String, dynamic>); ..hls = HlsConfig.fromJson(json['hls'] as Map<String, dynamic>)
..ftp = _ftpConfigFromJson(json['ftp'] as Map<String, dynamic>?);
Map<String, dynamic> _$ProtocolConfigToJson(ProtocolConfig instance) => <String, dynamic>{ Map<String, dynamic> _$ProtocolConfigToJson(ProtocolConfig instance) => <String, dynamic>{
'http': instance.http.toJson(), 'http': instance.http.toJson(),
'bt': instance.bt.toJson(), 'bt': instance.bt.toJson(),
'ed2k': instance.ed2k.toJson(), 'ed2k': instance.ed2k.toJson(),
'hls': instance.hls.toJson(), 'hls': instance.hls.toJson(),
'ftp': instance.ftp.toJson(),
}; };
HlsConfig _$HlsConfigFromJson(Map<String, dynamic> json) => HlsConfig( HlsConfig _$HlsConfigFromJson(Map<String, dynamic> json) => HlsConfig(
@@ -90,6 +92,11 @@ Map<String, dynamic> _$HlsConfigToJson(HlsConfig instance) => <String, dynamic>{
'prefetchContentLength': instance.prefetchContentLength, 'prefetchContentLength': instance.prefetchContentLength,
}; };
FtpConfig _$FtpConfigFromJson(Map<String, dynamic> json) =>
FtpConfig(connections: (json['connections'] as num?)?.toInt() ?? 0);
Map<String, dynamic> _$FtpConfigToJson(FtpConfig instance) => <String, dynamic>{'connections': instance.connections};
HttpConfig _$HttpConfigFromJson(Map<String, dynamic> json) => HttpConfig( HttpConfig _$HttpConfigFromJson(Map<String, dynamic> json) => HttpConfig(
userAgent: json['userAgent'] as String? ?? '', userAgent: json['userAgent'] as String? ?? '',
connections: (json['connections'] as num?)?.toInt() ?? 0, connections: (json['connections'] as num?)?.toInt() ?? 0,
+25
View File
@@ -67,3 +67,28 @@ class OptsExtraHttp {
Map<String, dynamic> toJson() => _$OptsExtraHttpToJson(this); Map<String, dynamic> toJson() => _$OptsExtraHttpToJson(this);
} }
/// Options for an FTP task. It mirrors `pkg/protocol/ftp.OptsExtra`. The TLS
/// mode of an `ftp://` link is on the request, see `ReqExtraFtp`.
@JsonSerializable()
class OptsExtraFtp {
int connections;
bool? autoTorrent;
bool? deleteTorrentAfterDownload;
bool? autoExtract;
String archivePassword;
bool deleteAfterExtract;
OptsExtraFtp({
this.connections = 0,
this.autoTorrent,
this.deleteTorrentAfterDownload,
this.autoExtract,
this.archivePassword = '',
this.deleteAfterExtract = false,
});
factory OptsExtraFtp.fromJson(Map<String, dynamic> json) => _$OptsExtraFtpFromJson(json);
Map<String, dynamic> toJson() => _$OptsExtraFtpToJson(this);
}
+18
View File
@@ -65,3 +65,21 @@ Map<String, dynamic> _$OptsExtraHttpToJson(OptsExtraHttp instance) =>
'deleteAfterExtract': instance.deleteAfterExtract, 'deleteAfterExtract': instance.deleteAfterExtract,
'checksum': ?instance.checksum?.toJson(), 'checksum': ?instance.checksum?.toJson(),
}; };
OptsExtraFtp _$OptsExtraFtpFromJson(Map<String, dynamic> json) => OptsExtraFtp(
connections: (json['connections'] as num?)?.toInt() ?? 0,
autoTorrent: json['autoTorrent'] as bool?,
deleteTorrentAfterDownload: json['deleteTorrentAfterDownload'] as bool?,
autoExtract: json['autoExtract'] as bool?,
archivePassword: json['archivePassword'] as String? ?? '',
deleteAfterExtract: json['deleteAfterExtract'] as bool? ?? false,
);
Map<String, dynamic> _$OptsExtraFtpToJson(OptsExtraFtp instance) => <String, dynamic>{
'connections': instance.connections,
'autoTorrent': ?instance.autoTorrent,
'deleteTorrentAfterDownload': ?instance.deleteTorrentAfterDownload,
'autoExtract': ?instance.autoExtract,
'archivePassword': instance.archivePassword,
'deleteAfterExtract': instance.deleteAfterExtract,
};
+14
View File
@@ -42,6 +42,20 @@ class ReqExtraBt {
Map<String, dynamic> toJson() => _$ReqExtraBtToJson(this); Map<String, dynamic> toJson() => _$ReqExtraBtToJson(this);
} }
/// The request extra of an FTP task. It mirrors `pkg/protocol/ftp.ReqExtra`;
/// [tls] only applies to `ftp://` URLs, because `ftps://` always uses
/// implicit TLS and `ftpes://` always uses explicit TLS.
@JsonSerializable()
class ReqExtraFtp {
String tls;
ReqExtraFtp({this.tls = 'none'});
factory ReqExtraFtp.fromJson(Map<String, dynamic> json) => _$ReqExtraFtpFromJson(json);
Map<String, dynamic> toJson() => _$ReqExtraFtpToJson(this);
}
enum RequestProxyMode { follow, none, custom } enum RequestProxyMode { follow, none, custom }
@JsonSerializable() @JsonSerializable()
+4
View File
@@ -41,6 +41,10 @@ ReqExtraBt _$ReqExtraBtFromJson(Map<String, dynamic> json) =>
Map<String, dynamic> _$ReqExtraBtToJson(ReqExtraBt instance) => <String, dynamic>{'trackers': instance.trackers}; Map<String, dynamic> _$ReqExtraBtToJson(ReqExtraBt instance) => <String, dynamic>{'trackers': instance.trackers};
ReqExtraFtp _$ReqExtraFtpFromJson(Map<String, dynamic> json) => ReqExtraFtp(tls: json['tls'] as String? ?? 'none');
Map<String, dynamic> _$ReqExtraFtpToJson(ReqExtraFtp instance) => <String, dynamic>{'tls': instance.tls};
RequestProxy _$RequestProxyFromJson(Map<String, dynamic> json) => RequestProxy( RequestProxy _$RequestProxyFromJson(Map<String, dynamic> json) => RequestProxy(
mode: $enumDecodeNullable(_$RequestProxyModeEnumMap, json['mode']) ?? RequestProxyMode.follow, mode: $enumDecodeNullable(_$RequestProxyModeEnumMap, json['mode']) ?? RequestProxyMode.follow,
scheme: json['scheme'] as String? ?? 'http', scheme: json['scheme'] as String? ?? 'http',
+1 -1
View File
@@ -6,7 +6,7 @@ part 'task.g.dart';
enum Status { ready, running, pause, wait, error, done } enum Status { ready, running, pause, wait, error, done }
enum Protocol { http, bt, ed2k, hls } enum Protocol { http, bt, ed2k, hls, ftp }
// ExtractStatus enum matching Go backend // ExtractStatus enum matching Go backend
enum ExtractStatus { enum ExtractStatus {
+7 -1
View File
@@ -40,7 +40,13 @@ const _$StatusEnumMap = {
Status.done: 'done', Status.done: 'done',
}; };
const _$ProtocolEnumMap = {Protocol.http: 'http', Protocol.bt: 'bt', Protocol.ed2k: 'ed2k', Protocol.hls: 'hls'}; const _$ProtocolEnumMap = {
Protocol.http: 'http',
Protocol.bt: 'bt',
Protocol.ed2k: 'ed2k',
Protocol.hls: 'hls',
Protocol.ftp: 'ftp',
};
Progress _$ProgressFromJson(Map<String, dynamic> json) => Progress( Progress _$ProgressFromJson(Map<String, dynamic> json) => Progress(
used: (json['used'] as num).toInt(), used: (json['used'] as num).toInt(),
+2 -1
View File
@@ -52,7 +52,8 @@ sealed class TaskStats {
final runtime = _map(json['runtime']); final runtime = _map(json['runtime']);
if (snapshot.isEmpty && runtime.isEmpty) return null; if (snapshot.isEmpty && runtime.isEmpty) return null;
return switch (protocol) { return switch (protocol) {
Protocol.http => HttpTaskStats.fromJson(snapshot), // FTP stats have the same shape as HTTP stats: one entry per connection.
Protocol.http || Protocol.ftp => HttpTaskStats.fromJson(snapshot),
Protocol.bt => BtTaskStats.fromJson(snapshot: snapshot, runtime: runtime), Protocol.bt => BtTaskStats.fromJson(snapshot: snapshot, runtime: runtime),
Protocol.ed2k => Ed2kTaskStats.fromJson(snapshot: snapshot, runtime: runtime), Protocol.ed2k => Ed2kTaskStats.fromJson(snapshot: snapshot, runtime: runtime),
Protocol.hls || null => null, Protocol.hls || null => null,
@@ -67,6 +67,7 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
final _maxRunningController = TextEditingController(); final _maxRunningController = TextEditingController();
final _httpUserAgentController = TextEditingController(); final _httpUserAgentController = TextEditingController();
final _httpConnectionsController = TextEditingController(); final _httpConnectionsController = TextEditingController();
final _ftpConnectionsController = TextEditingController();
final _hlsConnectionsController = TextEditingController(); final _hlsConnectionsController = TextEditingController();
final _hlsMaxRetriesController = TextEditingController(); final _hlsMaxRetriesController = TextEditingController();
final _btListenPortController = TextEditingController(); final _btListenPortController = TextEditingController();
@@ -101,6 +102,7 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
_maxRunningController, _maxRunningController,
_httpUserAgentController, _httpUserAgentController,
_httpConnectionsController, _httpConnectionsController,
_ftpConnectionsController,
_hlsConnectionsController, _hlsConnectionsController,
_hlsMaxRetriesController, _hlsMaxRetriesController,
_btListenPortController, _btListenPortController,
@@ -583,6 +585,23 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
], ],
), ),
), ),
_SettingsBlock(
key: const ValueKey('settings-ftp-block'),
title: 'FTP',
child: _SettingsGroup(
children: [
SettingsItem(
title: context.l10n.connections,
child: _NumberSettingControl(
fieldKey: const ValueKey('ftp-connections-input'),
controller: _ftpConnectionsController,
min: 1,
max: _ftpMaxConnections,
),
),
],
),
),
_SettingsBlock( _SettingsBlock(
title: 'BitTorrent', title: 'BitTorrent',
child: _SettingsGroup( child: _SettingsGroup(
@@ -1010,6 +1029,7 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
_maxRunningController.text = _config!.maxRunning.clamp(1, 256).toString(); _maxRunningController.text = _config!.maxRunning.clamp(1, 256).toString();
_httpUserAgentController.text = _config!.protocolConfig.http.userAgent; _httpUserAgentController.text = _config!.protocolConfig.http.userAgent;
_httpConnectionsController.text = _config!.protocolConfig.http.connections.clamp(1, 256).toString(); _httpConnectionsController.text = _config!.protocolConfig.http.connections.clamp(1, 256).toString();
_ftpConnectionsController.text = _config!.protocolConfig.ftp.connections.clamp(1, _ftpMaxConnections).toString();
_hlsConnectionsController.text = _config!.protocolConfig.hls.segmentConnections.clamp(1, 256).toString(); _hlsConnectionsController.text = _config!.protocolConfig.hls.segmentConnections.clamp(1, 256).toString();
_hlsMaxRetriesController.text = _config!.protocolConfig.hls.maxRetries.clamp(0, 30).toString(); _hlsMaxRetriesController.text = _config!.protocolConfig.hls.maxRetries.clamp(0, 30).toString();
_btListenPortController.text = _config!.protocolConfig.bt.listenPort.clamp(0, 65535).toString(); _btListenPortController.text = _config!.protocolConfig.bt.listenPort.clamp(0, 65535).toString();
@@ -1113,6 +1133,12 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
min: 1, min: 1,
max: 256, max: 256,
); );
config.protocolConfig.ftp.connections = _boundedInt(
_ftpConnectionsController,
fallback: config.protocolConfig.ftp.connections,
min: 1,
max: _ftpMaxConnections,
);
config.protocolConfig.hls.segmentConnections = _boundedInt( config.protocolConfig.hls.segmentConnections = _boundedInt(
_hlsConnectionsController, _hlsConnectionsController,
fallback: config.protocolConfig.hls.segmentConnections, fallback: config.protocolConfig.hls.segmentConnections,
@@ -2245,3 +2271,7 @@ class _ErrorState extends StatelessWidget {
); );
} }
} }
/// The highest number of parallel FTP logins offered, the same limit as on the create task page. FTP servers
/// usually allow only a few logins per user.
const _ftpMaxConnections = 32;
@@ -304,7 +304,7 @@ TaskAssetType _assetType(String name, {required bool isFolder, required api_task
return switch (protocol) { return switch (protocol) {
api_task.Protocol.bt => TaskAssetType.torrent, api_task.Protocol.bt => TaskAssetType.torrent,
api_task.Protocol.ed2k => TaskAssetType.ed2k, api_task.Protocol.ed2k => TaskAssetType.ed2k,
api_task.Protocol.hls || api_task.Protocol.http || null => TaskAssetType.file, api_task.Protocol.hls || api_task.Protocol.http || api_task.Protocol.ftp || null => TaskAssetType.file,
}; };
} }
@@ -82,6 +82,9 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
bool? _deleteTorrentAfterDownload; bool? _deleteTorrentAfterDownload;
bool? _autoExtract; bool? _autoExtract;
bool _deleteAfterExtract = false; bool _deleteAfterExtract = false;
String _ftpTls = _ftpTlsNone;
bool _allLinksFtp = false;
bool _hasPlainFtpLink = false;
List<DownloadCategory> _downloadCategories = const []; List<DownloadCategory> _downloadCategories = const [];
bool _showAdvanced = false; bool _showAdvanced = false;
@@ -220,6 +223,25 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
} }
} }
_recognizeMagnetUri(urlText.trim()); _recognizeMagnetUri(urlText.trim());
_refreshFtpLinks();
}
/// Shows the FTP options (the 32-connection limit and the TLS select) only
/// while the input contains FTP links.
void _refreshFtpLinks() {
final links = Util.textToLines(_urlController.text).map((line) => line.trim()).where((line) => line.isNotEmpty);
final allFtp = links.isNotEmpty && links.every((link) => _parseProtocol(link) == _TaskProtocol.ftp);
final hasPlainFtp = links.any(_isPlainFtpUrl);
if (allFtp == _allLinksFtp && hasPlainFtp == _hasPlainFtpLink) return;
if (!mounted) {
_allLinksFtp = allFtp;
_hasPlainFtpLink = hasPlainFtp;
return;
}
setState(() {
_allLinksFtp = allFtp;
_hasPlainFtpLink = hasPlainFtp;
});
} }
void _applyInitialTask(CreateTask? task) { void _applyInitialTask(CreateTask? task) {
@@ -237,6 +259,7 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
_httpBody = ''; _httpBody = '';
_replaceHttpHeaders(const {'User-Agent': '', 'Cookie': '', 'Referer': ''}); _replaceHttpHeaders(const {'User-Agent': '', 'Cookie': '', 'Referer': ''});
_trackersController.clear(); _trackersController.clear();
_ftpTls = _ftpTlsNone;
_protocolTab = 0; _protocolTab = 0;
_urlController.text = req!.url; _urlController.text = req!.url;
_initialRawUrl = req.rawUrl; _initialRawUrl = req.rawUrl;
@@ -261,6 +284,14 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
_trackersController.text = extra.trackers.join('\n'); _trackersController.text = extra.trackers.join('\n');
} }
break; break;
case _TaskProtocol.ftp:
if (req.extra is Map) {
final tls = ReqExtraFtp.fromJson(Map<String, dynamic>.from(req.extra! as Map)).tls;
if (_ftpTlsModes.contains(tls)) {
_ftpTls = tls;
}
}
break;
case _TaskProtocol.ed2k: case _TaskProtocol.ed2k:
case null: case null:
break; break;
@@ -437,10 +468,22 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
fieldKey: const ValueKey('create-task-connections-input'), fieldKey: const ValueKey('create-task-connections-input'),
controller: _connectionsController, controller: _connectionsController,
min: 1, min: 1,
max: 256, max: _allLinksFtp ? _ftpMaxConnections : 256,
hintText: context.l10n.enterCount, hintText: context.l10n.enterCount,
), ),
), ),
if (_hasPlainFtpLink) ...[
const SizedBox(height: 16),
AppFormRow(
direction: stacked ? Axis.vertical : Axis.horizontal,
label: context.l10n.ftpTls,
child: _FtpTlsSelect(
key: const ValueKey('create-task-ftp-tls'),
value: _ftpTls,
onChanged: (value) => setState(() => _ftpTls = value),
),
),
],
const SizedBox(height: 16), const SizedBox(height: 16),
AppFormRow( AppFormRow(
direction: stacked ? Axis.vertical : Axis.horizontal, direction: stacked ? Axis.vertical : Axis.horizontal,
@@ -729,7 +772,8 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
), ),
), ),
], ],
if (_inputUrls().length <= 1) ...[ // Checksum verification is HTTP only.
if (_inputUrls().length <= 1 && !_allLinksFtp) ...[
const SizedBox(height: 14), const SizedBox(height: 14),
AppFormPair( AppFormPair(
direction: stacked ? Axis.vertical : Axis.horizontal, direction: stacked ? Axis.vertical : Axis.horizontal,
@@ -964,7 +1008,10 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
.createTask( .createTask(
CreateTask( CreateTask(
req: _buildRequest(url, protocolUrl: _protocolUrlFor(url)), req: _buildRequest(url, protocolUrl: _protocolUrlFor(url)),
opts: _buildOptions(name: urls.length > 1 ? '' : _renameController.text.trim()), opts: _buildOptions(
url: _protocolUrlFor(url),
name: urls.length > 1 ? '' : _renameController.text.trim(),
),
), ),
); );
}), }),
@@ -1024,6 +1071,12 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
extra = ReqExtraBt(trackers: trackers).toJson(); extra = ReqExtraBt(trackers: trackers).toJson();
} }
break; break;
case _TaskProtocol.ftp:
// ftps:// and ftpes:// fix the TLS mode; only a plain ftp:// link carries one.
if (_isPlainFtpUrl(protocolUrl ?? url) && _ftpTls != _ftpTlsNone) {
extra = ReqExtraFtp(tls: _ftpTls).toJson();
}
break;
case _TaskProtocol.ed2k: case _TaskProtocol.ed2k:
case null: case null:
break; break;
@@ -1039,7 +1092,7 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
} }
bool _validateAdvancedOptions() { bool _validateAdvancedOptions() {
if (_protocolTab == 0 && _inputUrls().length <= 1) { if (_protocolTab == 0 && _inputUrls().length <= 1 && !_allLinksFtp) {
final checksumExpected = _checksumHashController.text.trim(); final checksumExpected = _checksumHashController.text.trim();
if (checksumExpected.isNotEmpty) { if (checksumExpected.isNotEmpty) {
final expectedLen = switch (_checksumAlgorithm.toLowerCase()) { final expectedLen = switch (_checksumAlgorithm.toLowerCase()) {
@@ -1099,6 +1152,10 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
if (uppercaseUrl.startsWith('HTTP:') || uppercaseUrl.startsWith('HTTPS:')) { if (uppercaseUrl.startsWith('HTTP:') || uppercaseUrl.startsWith('HTTPS:')) {
return _TaskProtocol.http; return _TaskProtocol.http;
} }
// Checked before BitTorrent, so ftp://host/file.torrent downloads the file over FTP.
if (uppercaseUrl.startsWith('FTP:') || uppercaseUrl.startsWith('FTPS:') || uppercaseUrl.startsWith('FTPES:')) {
return _TaskProtocol.ftp;
}
if (uppercaseUrl.startsWith('MAGNET:') || uppercaseUrl.endsWith('.TORRENT')) { if (uppercaseUrl.startsWith('MAGNET:') || uppercaseUrl.endsWith('.TORRENT')) {
return _TaskProtocol.bt; return _TaskProtocol.bt;
} }
@@ -1108,6 +1165,9 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
return null; return null;
} }
/// Whether [url] is a plain `ftp://` link, the only FTP scheme whose TLS mode is chosen by the user.
bool _isPlainFtpUrl(String url) => url.trim().toUpperCase().startsWith('FTP:');
String _normalizeTaskUrl(String url) { String _normalizeTaskUrl(String url) {
if (_isBtHash(url)) { if (_isBtHash(url)) {
return 'magnet:?xt=urn:btih:$url'; return 'magnet:?xt=urn:btih:$url';
@@ -1130,7 +1190,10 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
return text.length == 40 && RegExp(r'^[0-9a-fA-F]+$').hasMatch(text); return text.length == 40 && RegExp(r'^[0-9a-fA-F]+$').hasMatch(text);
} }
/// Builds the task options for [url]. FTP links get the FTP options, with at
/// most [_ftpMaxConnections] connections; the checksum is HTTP only.
api_options.Options _buildOptions({ api_options.Options _buildOptions({
required String url,
String? name, String? name,
List<int> selectFiles = const [], List<int> selectFiles = const [],
bool omitChecksum = false, bool omitChecksum = false,
@@ -1138,18 +1201,22 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
}) { }) {
final urls = _inputUrls(); final urls = _inputUrls();
final connections = int.tryParse(_connectionsController.text.trim()) ?? 0; final connections = int.tryParse(_connectionsController.text.trim()) ?? 0;
final checksumExpected = _checksumHashController.text.trim(); final Map<String, dynamic> extra;
final checksum = (!omitChecksum && _inputUrls().length <= 1 && checksumExpected.isNotEmpty) if (_parseProtocol(url) == _TaskProtocol.ftp) {
? api_options.ChecksumOption(algorithm: _checksumAlgorithm, expected: checksumExpected) extra = api_options.OptsExtraFtp(
: null; connections: connections.clamp(0, _ftpMaxConnections),
return api_options.Options( autoTorrent: _autoTorrent,
size: urls.length == 1 && _parseProtocol(_protocolUrlFor(urls.first)) == _TaskProtocol.http ? _initialSize : 0, deleteTorrentAfterDownload: _deleteTorrentAfterDownload,
name: name ?? _renameController.text.trim(), autoExtract: _autoExtract,
path: _directoryController.text.trim(), archivePassword: _archivePasswordController.text,
asDefaultPath: _asDefaultPath, deleteAfterExtract: _deleteAfterExtract,
skipAutoCategorize: skipAutoCategorize ?? _directoryManuallySet, ).toJson();
selectFiles: selectFiles, } else {
extra: api_options.OptsExtraHttp( final checksumExpected = _checksumHashController.text.trim();
final checksum = (!omitChecksum && urls.length <= 1 && checksumExpected.isNotEmpty)
? api_options.ChecksumOption(algorithm: _checksumAlgorithm, expected: checksumExpected)
: null;
extra = api_options.OptsExtraHttp(
connections: connections, connections: connections,
autoTorrent: _autoTorrent, autoTorrent: _autoTorrent,
deleteTorrentAfterDownload: _deleteTorrentAfterDownload, deleteTorrentAfterDownload: _deleteTorrentAfterDownload,
@@ -1157,7 +1224,16 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
archivePassword: _archivePasswordController.text, archivePassword: _archivePasswordController.text,
deleteAfterExtract: _deleteAfterExtract, deleteAfterExtract: _deleteAfterExtract,
checksum: checksum, checksum: checksum,
).toJson(), ).toJson();
}
return api_options.Options(
size: urls.length == 1 && _parseProtocol(_protocolUrlFor(urls.first)) == _TaskProtocol.http ? _initialSize : 0,
name: name ?? _renameController.text.trim(),
path: _directoryController.text.trim(),
asDefaultPath: _asDefaultPath,
skipAutoCategorize: skipAutoCategorize ?? _directoryManuallySet,
selectFiles: selectFiles,
extra: extra,
); );
} }
@@ -1232,7 +1308,7 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
.createTask( .createTask(
CreateTask( CreateTask(
rid: result.id, rid: result.id,
opts: _buildOptions(selectFiles: selected, omitChecksum: isMultiFile), opts: _buildOptions(url: request.url, selectFiles: selected, omitChecksum: isMultiFile),
), ),
); );
return; return;
@@ -1254,7 +1330,7 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
name: file.name, name: file.name,
path: path.join(_directoryController.text.trim(), result.res.name, file.path), path: path.join(_directoryController.text.trim(), result.res.name, file.path),
skipAutoCategorize: keepStructure, skipAutoCategorize: keepStructure,
extra: _buildOptions(omitChecksum: isMultiFile).extra, extra: _buildOptions(url: fileRequest.url, omitChecksum: isMultiFile).extra,
), ),
); );
}).toList(); }).toList();
@@ -1263,13 +1339,20 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
.createTaskBatch( .createTaskBatch(
CreateTaskBatch( CreateTaskBatch(
reqs: reqs, reqs: reqs,
opts: _buildOptions(omitChecksum: isMultiFile, skipAutoCategorize: keepStructure), opts: _buildOptions(url: request.url, omitChecksum: isMultiFile, skipAutoCategorize: keepStructure),
), ),
); );
return; return;
} }
await ref.read(gopeedServiceProvider).createTask(CreateTask(req: request, opts: _buildOptions())); await ref
.read(gopeedServiceProvider)
.createTask(
CreateTask(
req: request,
opts: _buildOptions(url: request.url),
),
);
} }
Future<bool> _showResolveDialog(Request request, ResolveResult result) async { Future<bool> _showResolveDialog(Request request, ResolveResult result) async {
@@ -1595,7 +1678,48 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
} }
} }
enum _TaskProtocol { http, bt, ed2k } enum _TaskProtocol { http, bt, ed2k, ftp }
/// Chooses how a plain `ftp://` link is encrypted. The values are the
/// `tls` option of an FTP task.
class _FtpTlsSelect extends StatelessWidget {
const _FtpTlsSelect({super.key, required this.value, required this.onChanged});
final String value;
final ValueChanged<String> onChanged;
@override
Widget build(BuildContext context) {
final labels = {
_ftpTlsNone: context.l10n.ftpTlsNone,
_ftpTlsExplicit: context.l10n.ftpTlsExplicit,
_ftpTlsImplicit: context.l10n.ftpTlsImplicit,
};
return LayoutBuilder(
builder: (context, constraints) => Select<String>(
value: value,
constraints: BoxConstraints.tightFor(width: constraints.maxWidth),
itemBuilder: (context, selected) =>
Text(labels[selected] ?? selected, maxLines: 1, overflow: TextOverflow.ellipsis),
popup: (context) => SelectPopup<String>(
items: SelectItemList(
children: [
for (final entry in labels.entries)
SelectItemButton<String>(
key: ValueKey('create-task-ftp-tls-${entry.key}'),
value: entry.key,
child: Text(entry.value),
),
],
),
),
onChanged: (selected) {
if (selected != null) onChanged(selected);
},
),
);
}
}
class _DirectDownloadToggle extends StatelessWidget { class _DirectDownloadToggle extends StatelessWidget {
const _DirectDownloadToggle({required this.value, required this.onChanged}); const _DirectDownloadToggle({required this.value, required this.onChanged});
@@ -2007,3 +2131,11 @@ const _advancedScrollDuration = Duration(milliseconds: 260);
const _advancedScrollExtentRetryDelay = Duration(milliseconds: 40); const _advancedScrollExtentRetryDelay = Duration(milliseconds: 40);
const _advancedScrollExtentChecks = 4; const _advancedScrollExtentChecks = 4;
const _advancedScrollDistance = 112.0; const _advancedScrollDistance = 112.0;
/// The highest number of parallel logins offered for FTP links. FTP servers
/// usually allow only a few logins per user.
const _ftpMaxConnections = 32;
const _ftpTlsNone = 'none';
const _ftpTlsExplicit = 'explicit';
const _ftpTlsImplicit = 'implicit';
const _ftpTlsModes = {_ftpTlsNone, _ftpTlsExplicit, _ftpTlsImplicit};
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "حفظ كمجلد التنزيل الافتراضي", "rememberLastDownloadDir": "حفظ كمجلد التنزيل الافتراضي",
"downloadDirValid": "الرجاء تحديد مجلد التنزيل", "downloadDirValid": "الرجاء تحديد مجلد التنزيل",
"connections": "الاتصالات", "connections": "الاتصالات",
"ftpTls": "تشفير FTP",
"ftpTlsNone": "بدون",
"ftpTlsExplicit": "TLS صريح (FTPES)",
"ftpTlsImplicit": "TLS ضمني (FTPS)",
"maxRetries": "الحد الأقصى لإعادة المحاولات", "maxRetries": "الحد الأقصى لإعادة المحاولات",
"useServerCtime": "استخدام وقت الخادم لإنشاء الملف", "useServerCtime": "استخدام وقت الخادم لإنشاء الملف",
"maxRunning": "الحد الأقصى للمهام المتزامنة", "maxRunning": "الحد الأقصى للمهام المتزامنة",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "Standart endirmə qovluğu kimi yadda saxla", "rememberLastDownloadDir": "Standart endirmə qovluğu kimi yadda saxla",
"downloadDirValid": "Zəhmət olmasa endirmə qovluğunu seçin", "downloadDirValid": "Zəhmət olmasa endirmə qovluğunu seçin",
"connections": "Əlaqələr", "connections": "Əlaqələr",
"ftpTls": "FTP şifrələməsi",
"ftpTlsNone": "Yoxdur",
"ftpTlsExplicit": "Açıq TLS (FTPES)",
"ftpTlsImplicit": "Gizli TLS (FTPS)",
"maxRetries": "Maksimum cəhd sayı", "maxRetries": "Maksimum cəhd sayı",
"useServerCtime": "Fayl yaratma tarixi üçün server vaxtından istifadə et", "useServerCtime": "Fayl yaratma tarixi üçün server vaxtından istifadə et",
"maxRunning": "Paralel Endirmələr", "maxRunning": "Paralel Endirmələr",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "Desa com a carpeta de baixades predeterminada", "rememberLastDownloadDir": "Desa com a carpeta de baixades predeterminada",
"downloadDirValid": "Seleccioneu la carpeta de baixades", "downloadDirValid": "Seleccioneu la carpeta de baixades",
"connections": "Connexions", "connections": "Connexions",
"ftpTls": "Xifratge FTP",
"ftpTlsNone": "Cap",
"ftpTlsExplicit": "TLS explícit (FTPES)",
"ftpTlsImplicit": "TLS implícit (FTPS)",
"maxRetries": "Reintents màxims", "maxRetries": "Reintents màxims",
"useServerCtime": "Utilitza l'hora del servidor per a la creació de fitxers", "useServerCtime": "Utilitza l'hora del servidor per a la creació de fitxers",
"maxRunning": "Màxim de tasques en execució", "maxRunning": "Màxim de tasques en execució",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "Als Standard-Downloadordner speichern", "rememberLastDownloadDir": "Als Standard-Downloadordner speichern",
"downloadDirValid": "Bitte wählen Sie das Download-Verzeichnis", "downloadDirValid": "Bitte wählen Sie das Download-Verzeichnis",
"connections": "Anschlüsse", "connections": "Anschlüsse",
"ftpTls": "FTP-Verschlüsselung",
"ftpTlsNone": "Keine",
"ftpTlsExplicit": "Explizites TLS (FTPES)",
"ftpTlsImplicit": "Implizites TLS (FTPS)",
"maxRetries": "Maximale Wiederholungsversuche", "maxRetries": "Maximale Wiederholungsversuche",
"useServerCtime": "Serverzeit für die Dateierstellung verwenden", "useServerCtime": "Serverzeit für die Dateierstellung verwenden",
"maxRunning": "Maximale Anzahl ausgeführter Aufgaben", "maxRunning": "Maximale Anzahl ausgeführter Aufgaben",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "Save as default download directory", "rememberLastDownloadDir": "Save as default download directory",
"downloadDirValid": "Please select the download directory", "downloadDirValid": "Please select the download directory",
"connections": "Connections", "connections": "Connections",
"ftpTls": "FTP encryption",
"ftpTlsNone": "None",
"ftpTlsExplicit": "Explicit TLS (FTPES)",
"ftpTlsImplicit": "Implicit TLS (FTPS)",
"maxRetries": "Max retries", "maxRetries": "Max retries",
"useServerCtime": "Use server time for file creation", "useServerCtime": "Use server time for file creation",
"maxRunning": "Concurrent Downloads", "maxRunning": "Concurrent Downloads",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "Guardar como carpeta de descargas predeterminada", "rememberLastDownloadDir": "Guardar como carpeta de descargas predeterminada",
"downloadDirValid": "Por favor, selecciona el directorio de descarga", "downloadDirValid": "Por favor, selecciona el directorio de descarga",
"connections": "Conexiones", "connections": "Conexiones",
"ftpTls": "Cifrado FTP",
"ftpTlsNone": "Ninguno",
"ftpTlsExplicit": "TLS explícito (FTPES)",
"ftpTlsImplicit": "TLS implícito (FTPS)",
"maxRetries": "Reintentos máximos", "maxRetries": "Reintentos máximos",
"useServerCtime": "Usar tiempo del servidor para la creación de archivos", "useServerCtime": "Usar tiempo del servidor para la creación de archivos",
"maxRunning": "Máximo de Tareas en Ejecución", "maxRunning": "Máximo de Tareas en Ejecución",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "ذخیره به‌عنوان پوشه پیش‌فرض دانلود", "rememberLastDownloadDir": "ذخیره به‌عنوان پوشه پیش‌فرض دانلود",
"downloadDirValid": "لطفا دایرکتوری دانلود را انتخاب کنید", "downloadDirValid": "لطفا دایرکتوری دانلود را انتخاب کنید",
"connections": "اتصالات", "connections": "اتصالات",
"ftpTls": "رمزگذاری FTP",
"ftpTlsNone": "هیچ",
"ftpTlsExplicit": "TLS صریح (FTPES)",
"ftpTlsImplicit": "TLS ضمنی (FTPS)",
"maxRetries": "حداکثر تلاش مجدد", "maxRetries": "حداکثر تلاش مجدد",
"useServerCtime": "استفاده از زمان سرور برای ایجاد فایل", "useServerCtime": "استفاده از زمان سرور برای ایجاد فایل",
"maxRunning": "حداکثر وظایف در حال اجرا", "maxRunning": "حداکثر وظایف در حال اجرا",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "Enregistrer comme dossier de téléchargement par défaut", "rememberLastDownloadDir": "Enregistrer comme dossier de téléchargement par défaut",
"downloadDirValid": "Veuillez sélectionner le répertoire de téléchargement", "downloadDirValid": "Veuillez sélectionner le répertoire de téléchargement",
"connections": "Connexions", "connections": "Connexions",
"ftpTls": "Chiffrement FTP",
"ftpTlsNone": "Aucun",
"ftpTlsExplicit": "TLS explicite (FTPES)",
"ftpTlsImplicit": "TLS implicite (FTPS)",
"maxRetries": "Nombre maximal de tentatives", "maxRetries": "Nombre maximal de tentatives",
"useServerCtime": "Utiliser l'heure du serveur pour la création de fichier", "useServerCtime": "Utiliser l'heure du serveur pour la création de fichier",
"maxRunning": "Tâches en cours maximum", "maxRunning": "Tâches en cours maximum",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "Mentés alapértelmezett letöltési mappaként", "rememberLastDownloadDir": "Mentés alapértelmezett letöltési mappaként",
"downloadDirValid": "Kérjük, válassza ki a letöltési könyvtárat", "downloadDirValid": "Kérjük, válassza ki a letöltési könyvtárat",
"connections": "Kapcsolatok", "connections": "Kapcsolatok",
"ftpTls": "FTP-titkosítás",
"ftpTlsNone": "Nincs",
"ftpTlsExplicit": "Explicit TLS (FTPES)",
"ftpTlsImplicit": "Implicit TLS (FTPS)",
"maxRetries": "Maximális újrapróbálkozások", "maxRetries": "Maximális újrapróbálkozások",
"useServerCtime": "Használja a szerveridőt a fájl létrehozásához", "useServerCtime": "Használja a szerveridőt a fájl létrehozásához",
"maxRunning": "Maximális futó feladatok", "maxRunning": "Maximális futó feladatok",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "Simpan sebagai folder unduhan default", "rememberLastDownloadDir": "Simpan sebagai folder unduhan default",
"downloadDirValid": "Silahkan pilih direktori unduhan", "downloadDirValid": "Silahkan pilih direktori unduhan",
"connections": "Koneksi", "connections": "Koneksi",
"ftpTls": "Enkripsi FTP",
"ftpTlsNone": "Tidak ada",
"ftpTlsExplicit": "TLS eksplisit (FTPES)",
"ftpTlsImplicit": "TLS implisit (FTPS)",
"maxRetries": "Percobaan ulang maks.", "maxRetries": "Percobaan ulang maks.",
"useServerCtime": "Gunakan waktu server untuk pembuatan file", "useServerCtime": "Gunakan waktu server untuk pembuatan file",
"maxRunning": "Tugas Maksimum yang Berjalan", "maxRunning": "Tugas Maksimum yang Berjalan",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "Salva come cartella di download predefinita", "rememberLastDownloadDir": "Salva come cartella di download predefinita",
"downloadDirValid": "Seleziona la directory di scaricamento", "downloadDirValid": "Seleziona la directory di scaricamento",
"connections": "Connessioni", "connections": "Connessioni",
"ftpTls": "Crittografia FTP",
"ftpTlsNone": "Nessuna",
"ftpTlsExplicit": "TLS esplicito (FTPES)",
"ftpTlsImplicit": "TLS implicito (FTPS)",
"maxRetries": "Tentativi massimi", "maxRetries": "Tentativi massimi",
"useServerCtime": "Utilizza l'ora del server per la creazione dei file", "useServerCtime": "Utilizza l'ora del server per la creazione dei file",
"maxRunning": "Numero massimo di attività in esecuzione", "maxRunning": "Numero massimo di attività in esecuzione",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "デフォルトのダウンロード先として保存", "rememberLastDownloadDir": "デフォルトのダウンロード先として保存",
"downloadDirValid": "ダウンロードディレクトリを選択してください", "downloadDirValid": "ダウンロードディレクトリを選択してください",
"connections": "接続", "connections": "接続",
"ftpTls": "FTP 暗号化",
"ftpTlsNone": "なし",
"ftpTlsExplicit": "明示的 TLS (FTPES)",
"ftpTlsImplicit": "暗黙的 TLS (FTPS)",
"maxRetries": "最大リトライ回数", "maxRetries": "最大リトライ回数",
"useServerCtime": "ファイル作成時にサーバー時間を使用する", "useServerCtime": "ファイル作成時にサーバー時間を使用する",
"maxRunning": "最大実行タスク", "maxRunning": "最大実行タスク",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "기본 다운로드 폴더로 저장", "rememberLastDownloadDir": "기본 다운로드 폴더로 저장",
"downloadDirValid": "다운로드 폴더를 선택해 주세요", "downloadDirValid": "다운로드 폴더를 선택해 주세요",
"connections": "연결 수", "connections": "연결 수",
"ftpTls": "FTP 암호화",
"ftpTlsNone": "없음",
"ftpTlsExplicit": "명시적 TLS (FTPES)",
"ftpTlsImplicit": "암시적 TLS (FTPS)",
"maxRetries": "최대 재시도 횟수", "maxRetries": "최대 재시도 횟수",
"useServerCtime": "파일 생성 시간에 서버 시간 사용", "useServerCtime": "파일 생성 시간에 서버 시간 사용",
"maxRunning": "최대 동시 작업 수", "maxRunning": "최대 동시 작업 수",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "Zapisz jako domyślny folder pobierania", "rememberLastDownloadDir": "Zapisz jako domyślny folder pobierania",
"downloadDirValid": "Wskaż folder pobierania", "downloadDirValid": "Wskaż folder pobierania",
"connections": "Połączenia", "connections": "Połączenia",
"ftpTls": "Szyfrowanie FTP",
"ftpTlsNone": "Brak",
"ftpTlsExplicit": "Jawne TLS (FTPES)",
"ftpTlsImplicit": "Niejawne TLS (FTPS)",
"maxRetries": "Maks. liczba ponownych prób", "maxRetries": "Maks. liczba ponownych prób",
"useServerCtime": "Użyj czasu serwera do utworzenia pliku", "useServerCtime": "Użyj czasu serwera do utworzenia pliku",
"maxRunning": "Maksymalna liczba zadań", "maxRunning": "Maksymalna liczba zadań",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "Salvar como pasta de download padrão", "rememberLastDownloadDir": "Salvar como pasta de download padrão",
"downloadDirValid": "Por favor, selecione a pasta", "downloadDirValid": "Por favor, selecione a pasta",
"connections": "Conexões", "connections": "Conexões",
"ftpTls": "Criptografia FTP",
"ftpTlsNone": "Nenhuma",
"ftpTlsExplicit": "TLS explícito (FTPES)",
"ftpTlsImplicit": "TLS implícito (FTPS)",
"maxRetries": "Tentativas máximas", "maxRetries": "Tentativas máximas",
"useServerCtime": "Usar o tempo de servidor para a criação de ficheiros", "useServerCtime": "Usar o tempo de servidor para a criação de ficheiros",
"maxRunning": "Máximo de Tarefas Simultâneas", "maxRunning": "Máximo de Tarefas Simultâneas",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "Сохранить как папку загрузок по умолчанию", "rememberLastDownloadDir": "Сохранить как папку загрузок по умолчанию",
"downloadDirValid": "Пожалуйста, выберите папку для загрузки", "downloadDirValid": "Пожалуйста, выберите папку для загрузки",
"connections": "Соединений", "connections": "Соединений",
"ftpTls": "Шифрование FTP",
"ftpTlsNone": "Нет",
"ftpTlsExplicit": "Явный TLS (FTPES)",
"ftpTlsImplicit": "Неявный TLS (FTPS)",
"maxRetries": "Макс. число повторов", "maxRetries": "Макс. число повторов",
"useServerCtime": "Использовать время сервера для создания файла", "useServerCtime": "Использовать время сервера для создания файла",
"maxRunning": "Максимальное количество активных задач", "maxRunning": "Максимальное количество активных задач",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "Uložiť ako predvolený priečinok na stiahnutie", "rememberLastDownloadDir": "Uložiť ako predvolený priečinok na stiahnutie",
"downloadDirValid": "Vyberte priečinok na stiahnutie", "downloadDirValid": "Vyberte priečinok na stiahnutie",
"connections": "Pripojenia", "connections": "Pripojenia",
"ftpTls": "Šifrovanie FTP",
"ftpTlsNone": "Žiadne",
"ftpTlsExplicit": "Explicitné TLS (FTPES)",
"ftpTlsImplicit": "Implicitné TLS (FTPS)",
"maxRetries": "Maximálny počet pokusov", "maxRetries": "Maximálny počet pokusov",
"useServerCtime": "Použiť čas servera na vytvorenie súboru", "useServerCtime": "Použiť čas servera na vytvorenie súboru",
"maxRunning": "Súbežné sťahovania", "maxRunning": "Súbežné sťahovania",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "இயல்புநிலை பதிவிறக்க கோப்புறையாக சேமி", "rememberLastDownloadDir": "இயல்புநிலை பதிவிறக்க கோப்புறையாக சேமி",
"downloadDirValid": "பதிவிரக்குமிடத்தை தேர்வு செயுங்கள்", "downloadDirValid": "பதிவிரக்குமிடத்தை தேர்வு செயுங்கள்",
"connections": "தொடர்புகள்", "connections": "தொடர்புகள்",
"ftpTls": "FTP குறியாக்கம்",
"ftpTlsNone": "இல்லை",
"ftpTlsExplicit": "வெளிப்படையான TLS (FTPES)",
"ftpTlsImplicit": "மறைமுக TLS (FTPS)",
"maxRetries": "அதிகபட்ச மறுமுயற்சிகள்", "maxRetries": "அதிகபட்ச மறுமுயற்சிகள்",
"useServerCtime": "கோப்பு உருவாக்க சேவையக நேரத்தைப் பயன்படுத்தவும்", "useServerCtime": "கோப்பு உருவாக்க சேவையக நேரத்தைப் பயன்படுத்தவும்",
"maxRunning": "அதிகபட்ச இயங்கும் பணிகள்", "maxRunning": "அதிகபட்ச இயங்கும் பணிகள்",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "Varsayılan indirme klasörü olarak kaydet", "rememberLastDownloadDir": "Varsayılan indirme klasörü olarak kaydet",
"downloadDirValid": "Lütfen indirme dizinini seçin", "downloadDirValid": "Lütfen indirme dizinini seçin",
"connections": "Bağlantılar", "connections": "Bağlantılar",
"ftpTls": "FTP şifrelemesi",
"ftpTlsNone": "Yok",
"ftpTlsExplicit": "Açık TLS (FTPES)",
"ftpTlsImplicit": "Örtük TLS (FTPS)",
"maxRetries": "Maksimum yeniden deneme", "maxRetries": "Maksimum yeniden deneme",
"useServerCtime": "Dosya oluşturma tarihi için sunucu zamanını kullan", "useServerCtime": "Dosya oluşturma tarihi için sunucu zamanını kullan",
"maxRunning": "Maksimum Çalışan İşlem", "maxRunning": "Maksimum Çalışan İşlem",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "Зберегти як типову папку завантажень", "rememberLastDownloadDir": "Зберегти як типову папку завантажень",
"downloadDirValid": "Будь ласка, виберіть каталог завантажень", "downloadDirValid": "Будь ласка, виберіть каталог завантажень",
"connections": "З’єднання", "connections": "З’єднання",
"ftpTls": "Шифрування FTP",
"ftpTlsNone": "Немає",
"ftpTlsExplicit": "Явний TLS (FTPES)",
"ftpTlsImplicit": "Неявний TLS (FTPS)",
"maxRetries": "Макс. кількість повторів", "maxRetries": "Макс. кількість повторів",
"useServerCtime": "Використовувати час сервера для створення файлу", "useServerCtime": "Використовувати час сервера для створення файлу",
"maxRunning": "Макс. завдань у черзі", "maxRunning": "Макс. завдань у черзі",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "Lưu làm thư mục tải xuống mặc định", "rememberLastDownloadDir": "Lưu làm thư mục tải xuống mặc định",
"downloadDirValid": "Vui lòng chọn thư mục tải về", "downloadDirValid": "Vui lòng chọn thư mục tải về",
"connections": "Kết nối", "connections": "Kết nối",
"ftpTls": "Mã hóa FTP",
"ftpTlsNone": "Không",
"ftpTlsExplicit": "TLS tường minh (FTPES)",
"ftpTlsImplicit": "TLS ngầm định (FTPS)",
"maxRetries": "Số lần thử lại tối đa", "maxRetries": "Số lần thử lại tối đa",
"useServerCtime": "Sử dụng thời gian máy chủ cho việc tạo tệp", "useServerCtime": "Sử dụng thời gian máy chủ cho việc tạo tệp",
"maxRunning": "Số nhiệm vụ tối đa", "maxRunning": "Số nhiệm vụ tối đa",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "保存为默认下载目录", "rememberLastDownloadDir": "保存为默认下载目录",
"downloadDirValid": "请选择下载目录", "downloadDirValid": "请选择下载目录",
"connections": "连接数", "connections": "连接数",
"ftpTls": "FTP 加密",
"ftpTlsNone": "无",
"ftpTlsExplicit": "显式 TLS (FTPES)",
"ftpTlsImplicit": "隐式 TLS (FTPS)",
"maxRetries": "最大重试次数", "maxRetries": "最大重试次数",
"useServerCtime": "创建文件使用服务器时间", "useServerCtime": "创建文件使用服务器时间",
"maxRunning": "最大下载数", "maxRunning": "最大下载数",
+4
View File
@@ -38,6 +38,10 @@
"rememberLastDownloadDir": "儲存為預設下載目錄", "rememberLastDownloadDir": "儲存為預設下載目錄",
"downloadDirValid": "請選擇下載目錄", "downloadDirValid": "請選擇下載目錄",
"connections": "連接數", "connections": "連接數",
"ftpTls": "FTP 加密",
"ftpTlsNone": "無",
"ftpTlsExplicit": "明確 TLS (FTPES)",
"ftpTlsImplicit": "隱含 TLS (FTPS)",
"maxRetries": "最大重試次數", "maxRetries": "最大重試次數",
"useServerCtime": "使用伺服器時間作為檔案建立時間", "useServerCtime": "使用伺服器時間作為檔案建立時間",
"maxRunning": "最大執行任務數", "maxRunning": "最大執行任務數",
@@ -67,6 +67,25 @@ void main() {
expect(decoded.disablePex, isTrue); expect(decoded.disablePex, isTrue);
}); });
test('FTP settings round-trip with the Go json keys', () {
final config = DownloaderConfig();
config.protocolConfig.ftp.connections = 6;
final json = config.toJson();
final ftp = (json['protocolConfig'] as Map<String, dynamic>)['ftp'] as Map<String, dynamic>;
expect(ftp, {'connections': 6});
expect(DownloaderConfig.fromJson(json).protocolConfig.ftp.connections, 6);
});
test('a stored config without FTP settings still parses', () {
final json = DownloaderConfig().toJson();
(json['protocolConfig'] as Map<String, dynamic>).remove('ftp');
final decoded = DownloaderConfig.fromJson(json);
expect(decoded.protocolConfig.ftp.connections, 0);
expect(decoded.protocolConfig.http.connections, DownloaderConfig().protocolConfig.http.connections);
});
test('BitTorrent peer discovery stays on when a stored config lacks the keys', () { test('BitTorrent peer discovery stays on when a stored config lacks the keys', () {
final bt = BtConfig.fromJson({'listenPort': 6881, 'seedRatio': 1.0}); final bt = BtConfig.fromJson({'listenPort': 6881, 'seedRatio': 1.0});
expect(bt.disableDht, isFalse); expect(bt.disableDht, isFalse);
Loaded 50 of 54 files, more files were not shown because too many files have changed in this diff. Show more