Compare commits

...

14 Commits

Author SHA1 Message Date
Simon Ding
f5ca53f7d7 update: required 2024-10-04 11:39:58 +08:00
Simon Ding
7461918a6c fix: qbit progress 2024-10-04 11:36:12 +08:00
Simon Ding
3af5f96cb0 feat: support download client priority 2024-10-04 11:12:06 +08:00
Simon Ding
7dfa4eafc4 feat: support reload qbit tasks 2024-10-04 10:45:31 +08:00
Simon Ding
579b010d13 fix: go mod tidy 2024-10-04 10:32:19 +08:00
Simon Ding
c42cbb5e5d feat: complete qbittorrent support 2024-10-04 10:31:49 +08:00
Simon Ding
6a5c105f8c WIP: qbittorrent support 2024-10-04 01:22:27 +08:00
Simon Ding
e8067f96f1 feat: allow set any media qulity 2024-10-03 22:19:16 +08:00
Simon Ding
84a0197776 refactor: name testing 2024-09-29 18:43:29 +08:00
Simon Ding
f9556ec2d2 feat: check movie folder upon added 2024-09-29 18:35:20 +08:00
Simon Ding
98d14befa9 fix: remove episodes no media id 2024-09-29 16:16:05 +08:00
Simon Ding
6fcc569bf2 feat: clean dangling episodes 2024-09-29 15:45:31 +08:00
Simon Ding
672e7f914d feat: desc ordering 2024-09-29 15:33:56 +08:00
Simon Ding
20bdcdbcde fix: validate 2024-09-29 14:46:06 +08:00
40 changed files with 2662 additions and 336 deletions

View File

@@ -43,7 +43,7 @@ jobs:
distribution: goreleaser
# 'latest', 'nightly', or a semver
version: '~> v2'
args: release --clean
args: release --clean --skip=validate
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Your GoReleaser Pro key, if you are using the 'goreleaser-pro' distribution

View File

@@ -66,9 +66,13 @@ func (c *Client) init() {
log.Infof("set default log level")
c.SetSetting(SettingLogLevel, "info")
}
if tr := c.GetTransmission(); tr == nil {
if tr := c.GetAllDonloadClients(); len(tr) == 0 {
log.Warnf("no download client, set default download client")
c.SaveTransmission("transmission", "http://transmission:9091", "", "")
c.SaveDownloader(&ent.DownloadClients{
Name: "transmission",
Implementation: downloadclients.ImplementationTransmission,
URL: "http://transmission:9091",
})
}
}
@@ -160,7 +164,7 @@ func (c *Client) AddMediaWatchlist(m *ent.Media, episodes []int) (*ent.Media, er
}
func (c *Client) GetMediaWatchlist(mediaType media.MediaType) []*ent.Media {
list, err := c.ent.Media.Query().Where(media.MediaTypeEQ(mediaType)).All(context.TODO())
list, err := c.ent.Media.Query().Where(media.MediaTypeEQ(mediaType)).Order(ent.Desc(media.FieldID)).All(context.TODO())
if err != nil {
log.Infof("query wtach list error: %v", err)
return nil
@@ -219,7 +223,10 @@ func (c *Client) DeleteMedia(id int) error {
return err
}
_, err = c.ent.Media.Delete().Where(media.ID(id)).Exec(context.TODO())
return err
if err != nil {
return err
}
return c.CleanAllDanglingEpisodes()
}
func (c *Client) SaveEposideDetail(d *ent.Episode) (int, error) {
@@ -319,30 +326,22 @@ func (c *Client) GetAllTorznabInfo() []*TorznabInfo {
return l
}
func (c *Client) SaveTransmission(name, url, user, password string) error {
count := c.ent.DownloadClients.Query().Where(downloadclients.Name(name)).CountX(context.TODO())
func (c *Client) SaveDownloader(downloader *ent.DownloadClients) error {
count := c.ent.DownloadClients.Query().Where(downloadclients.Name(downloader.Name)).CountX(context.TODO())
if count != 0 {
err := c.ent.DownloadClients.Update().Where(downloadclients.Name(name)).
SetURL(url).SetUser(user).SetPassword(password).Exec(context.TODO())
err := c.ent.DownloadClients.Update().Where(downloadclients.Name(downloader.Name)).SetImplementation(downloader.Implementation).
SetURL(downloader.URL).SetUser(downloader.User).SetPassword(downloader.Password).SetPriority1(downloader.Priority1).Exec(context.TODO())
return err
}
_, err := c.ent.DownloadClients.Create().SetEnable(true).SetImplementation("transmission").
SetName(name).SetURL(url).SetUser(user).SetPassword(password).Save(context.TODO())
_, err := c.ent.DownloadClients.Create().SetEnable(true).SetImplementation(downloader.Implementation).
SetName(downloader.Name).SetURL(downloader.URL).SetUser(downloader.User).SetPriority1(downloader.Priority1).SetPassword(downloader.Password).Save(context.TODO())
return err
}
func (c *Client) GetTransmission() *ent.DownloadClients {
dc, err := c.ent.DownloadClients.Query().Where(downloadclients.Implementation("transmission")).First(context.TODO())
if err != nil {
log.Errorf("no transmission client found: %v", err)
return nil
}
return dc
}
func (c *Client) GetAllDonloadClients() []*ent.DownloadClients {
cc, err := c.ent.DownloadClients.Query().All(context.TODO())
cc, err := c.ent.DownloadClients.Query().Order(ent.Asc(downloadclients.FieldPriority1)).All(context.TODO())
if err != nil {
log.Errorf("no download client")
return nil
@@ -645,3 +644,8 @@ func (c *Client) GetMovingNamingFormat() string {
}
return s
}
func (c *Client) CleanAllDanglingEpisodes() error {
_, err := c.ent.Episode.Delete().Where(episode.Not(episode.HasMedia())).Exec(context.Background())
return err
}

View File

@@ -21,7 +21,7 @@ type DownloadClients struct {
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Implementation holds the value of the "implementation" field.
Implementation string `json:"implementation,omitempty"`
Implementation downloadclients.Implementation `json:"implementation,omitempty"`
// URL holds the value of the "url" field.
URL string `json:"url,omitempty"`
// User holds the value of the "user" field.
@@ -30,8 +30,8 @@ type DownloadClients struct {
Password string `json:"password,omitempty"`
// Settings holds the value of the "settings" field.
Settings string `json:"settings,omitempty"`
// Priority holds the value of the "priority" field.
Priority string `json:"priority,omitempty"`
// Priority1 holds the value of the "priority1" field.
Priority1 int `json:"priority1,omitempty"`
// RemoveCompletedDownloads holds the value of the "remove_completed_downloads" field.
RemoveCompletedDownloads bool `json:"remove_completed_downloads,omitempty"`
// RemoveFailedDownloads holds the value of the "remove_failed_downloads" field.
@@ -48,9 +48,9 @@ func (*DownloadClients) scanValues(columns []string) ([]any, error) {
switch columns[i] {
case downloadclients.FieldEnable, downloadclients.FieldRemoveCompletedDownloads, downloadclients.FieldRemoveFailedDownloads:
values[i] = new(sql.NullBool)
case downloadclients.FieldID:
case downloadclients.FieldID, downloadclients.FieldPriority1:
values[i] = new(sql.NullInt64)
case downloadclients.FieldName, downloadclients.FieldImplementation, downloadclients.FieldURL, downloadclients.FieldUser, downloadclients.FieldPassword, downloadclients.FieldSettings, downloadclients.FieldPriority, downloadclients.FieldTags:
case downloadclients.FieldName, downloadclients.FieldImplementation, downloadclients.FieldURL, downloadclients.FieldUser, downloadclients.FieldPassword, downloadclients.FieldSettings, downloadclients.FieldTags:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
@@ -89,7 +89,7 @@ func (dc *DownloadClients) assignValues(columns []string, values []any) error {
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field implementation", values[i])
} else if value.Valid {
dc.Implementation = value.String
dc.Implementation = downloadclients.Implementation(value.String)
}
case downloadclients.FieldURL:
if value, ok := values[i].(*sql.NullString); !ok {
@@ -115,11 +115,11 @@ func (dc *DownloadClients) assignValues(columns []string, values []any) error {
} else if value.Valid {
dc.Settings = value.String
}
case downloadclients.FieldPriority:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field priority", values[i])
case downloadclients.FieldPriority1:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field priority1", values[i])
} else if value.Valid {
dc.Priority = value.String
dc.Priority1 = int(value.Int64)
}
case downloadclients.FieldRemoveCompletedDownloads:
if value, ok := values[i].(*sql.NullBool); !ok {
@@ -182,7 +182,7 @@ func (dc *DownloadClients) String() string {
builder.WriteString(dc.Name)
builder.WriteString(", ")
builder.WriteString("implementation=")
builder.WriteString(dc.Implementation)
builder.WriteString(fmt.Sprintf("%v", dc.Implementation))
builder.WriteString(", ")
builder.WriteString("url=")
builder.WriteString(dc.URL)
@@ -196,8 +196,8 @@ func (dc *DownloadClients) String() string {
builder.WriteString("settings=")
builder.WriteString(dc.Settings)
builder.WriteString(", ")
builder.WriteString("priority=")
builder.WriteString(dc.Priority)
builder.WriteString("priority1=")
builder.WriteString(fmt.Sprintf("%v", dc.Priority1))
builder.WriteString(", ")
builder.WriteString("remove_completed_downloads=")
builder.WriteString(fmt.Sprintf("%v", dc.RemoveCompletedDownloads))

View File

@@ -3,6 +3,8 @@
package downloadclients
import (
"fmt"
"entgo.io/ent/dialect/sql"
)
@@ -25,8 +27,8 @@ const (
FieldPassword = "password"
// FieldSettings holds the string denoting the settings field in the database.
FieldSettings = "settings"
// FieldPriority holds the string denoting the priority field in the database.
FieldPriority = "priority"
// FieldPriority1 holds the string denoting the priority1 field in the database.
FieldPriority1 = "priority1"
// FieldRemoveCompletedDownloads holds the string denoting the remove_completed_downloads field in the database.
FieldRemoveCompletedDownloads = "remove_completed_downloads"
// FieldRemoveFailedDownloads holds the string denoting the remove_failed_downloads field in the database.
@@ -47,7 +49,7 @@ var Columns = []string{
FieldUser,
FieldPassword,
FieldSettings,
FieldPriority,
FieldPriority1,
FieldRemoveCompletedDownloads,
FieldRemoveFailedDownloads,
FieldTags,
@@ -70,8 +72,10 @@ var (
DefaultPassword string
// DefaultSettings holds the default value on creation for the "settings" field.
DefaultSettings string
// DefaultPriority holds the default value on creation for the "priority" field.
DefaultPriority string
// DefaultPriority1 holds the default value on creation for the "priority1" field.
DefaultPriority1 int
// Priority1Validator is a validator for the "priority1" field. It is called by the builders before save.
Priority1Validator func(int) error
// DefaultRemoveCompletedDownloads holds the default value on creation for the "remove_completed_downloads" field.
DefaultRemoveCompletedDownloads bool
// DefaultRemoveFailedDownloads holds the default value on creation for the "remove_failed_downloads" field.
@@ -80,6 +84,29 @@ var (
DefaultTags string
)
// Implementation defines the type for the "implementation" enum field.
type Implementation string
// Implementation values.
const (
ImplementationTransmission Implementation = "transmission"
ImplementationQbittorrent Implementation = "qbittorrent"
)
func (i Implementation) String() string {
return string(i)
}
// ImplementationValidator is a validator for the "implementation" field enum values. It is called by the builders before save.
func ImplementationValidator(i Implementation) error {
switch i {
case ImplementationTransmission, ImplementationQbittorrent:
return nil
default:
return fmt.Errorf("downloadclients: invalid enum value for implementation field: %q", i)
}
}
// OrderOption defines the ordering options for the DownloadClients queries.
type OrderOption func(*sql.Selector)
@@ -123,9 +150,9 @@ func BySettings(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSettings, opts...).ToFunc()
}
// ByPriority orders the results by the priority field.
func ByPriority(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPriority, opts...).ToFunc()
// ByPriority1 orders the results by the priority1 field.
func ByPriority1(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPriority1, opts...).ToFunc()
}
// ByRemoveCompletedDownloads orders the results by the remove_completed_downloads field.

View File

@@ -63,11 +63,6 @@ func Name(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldEQ(FieldName, v))
}
// Implementation applies equality check predicate on the "implementation" field. It's identical to ImplementationEQ.
func Implementation(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldEQ(FieldImplementation, v))
}
// URL applies equality check predicate on the "url" field. It's identical to URLEQ.
func URL(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldEQ(FieldURL, v))
@@ -88,9 +83,9 @@ func Settings(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldEQ(FieldSettings, v))
}
// Priority applies equality check predicate on the "priority" field. It's identical to PriorityEQ.
func Priority(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldEQ(FieldPriority, v))
// Priority1 applies equality check predicate on the "priority1" field. It's identical to Priority1EQ.
func Priority1(v int) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldEQ(FieldPriority1, v))
}
// RemoveCompletedDownloads applies equality check predicate on the "remove_completed_downloads" field. It's identical to RemoveCompletedDownloadsEQ.
@@ -184,70 +179,25 @@ func NameContainsFold(v string) predicate.DownloadClients {
}
// ImplementationEQ applies the EQ predicate on the "implementation" field.
func ImplementationEQ(v string) predicate.DownloadClients {
func ImplementationEQ(v Implementation) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldEQ(FieldImplementation, v))
}
// ImplementationNEQ applies the NEQ predicate on the "implementation" field.
func ImplementationNEQ(v string) predicate.DownloadClients {
func ImplementationNEQ(v Implementation) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldNEQ(FieldImplementation, v))
}
// ImplementationIn applies the In predicate on the "implementation" field.
func ImplementationIn(vs ...string) predicate.DownloadClients {
func ImplementationIn(vs ...Implementation) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldIn(FieldImplementation, vs...))
}
// ImplementationNotIn applies the NotIn predicate on the "implementation" field.
func ImplementationNotIn(vs ...string) predicate.DownloadClients {
func ImplementationNotIn(vs ...Implementation) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldNotIn(FieldImplementation, vs...))
}
// ImplementationGT applies the GT predicate on the "implementation" field.
func ImplementationGT(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldGT(FieldImplementation, v))
}
// ImplementationGTE applies the GTE predicate on the "implementation" field.
func ImplementationGTE(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldGTE(FieldImplementation, v))
}
// ImplementationLT applies the LT predicate on the "implementation" field.
func ImplementationLT(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldLT(FieldImplementation, v))
}
// ImplementationLTE applies the LTE predicate on the "implementation" field.
func ImplementationLTE(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldLTE(FieldImplementation, v))
}
// ImplementationContains applies the Contains predicate on the "implementation" field.
func ImplementationContains(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldContains(FieldImplementation, v))
}
// ImplementationHasPrefix applies the HasPrefix predicate on the "implementation" field.
func ImplementationHasPrefix(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldHasPrefix(FieldImplementation, v))
}
// ImplementationHasSuffix applies the HasSuffix predicate on the "implementation" field.
func ImplementationHasSuffix(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldHasSuffix(FieldImplementation, v))
}
// ImplementationEqualFold applies the EqualFold predicate on the "implementation" field.
func ImplementationEqualFold(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldEqualFold(FieldImplementation, v))
}
// ImplementationContainsFold applies the ContainsFold predicate on the "implementation" field.
func ImplementationContainsFold(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldContainsFold(FieldImplementation, v))
}
// URLEQ applies the EQ predicate on the "url" field.
func URLEQ(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldEQ(FieldURL, v))
@@ -508,69 +458,44 @@ func SettingsContainsFold(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldContainsFold(FieldSettings, v))
}
// PriorityEQ applies the EQ predicate on the "priority" field.
func PriorityEQ(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldEQ(FieldPriority, v))
// Priority1EQ applies the EQ predicate on the "priority1" field.
func Priority1EQ(v int) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldEQ(FieldPriority1, v))
}
// PriorityNEQ applies the NEQ predicate on the "priority" field.
func PriorityNEQ(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldNEQ(FieldPriority, v))
// Priority1NEQ applies the NEQ predicate on the "priority1" field.
func Priority1NEQ(v int) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldNEQ(FieldPriority1, v))
}
// PriorityIn applies the In predicate on the "priority" field.
func PriorityIn(vs ...string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldIn(FieldPriority, vs...))
// Priority1In applies the In predicate on the "priority1" field.
func Priority1In(vs ...int) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldIn(FieldPriority1, vs...))
}
// PriorityNotIn applies the NotIn predicate on the "priority" field.
func PriorityNotIn(vs ...string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldNotIn(FieldPriority, vs...))
// Priority1NotIn applies the NotIn predicate on the "priority1" field.
func Priority1NotIn(vs ...int) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldNotIn(FieldPriority1, vs...))
}
// PriorityGT applies the GT predicate on the "priority" field.
func PriorityGT(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldGT(FieldPriority, v))
// Priority1GT applies the GT predicate on the "priority1" field.
func Priority1GT(v int) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldGT(FieldPriority1, v))
}
// PriorityGTE applies the GTE predicate on the "priority" field.
func PriorityGTE(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldGTE(FieldPriority, v))
// Priority1GTE applies the GTE predicate on the "priority1" field.
func Priority1GTE(v int) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldGTE(FieldPriority1, v))
}
// PriorityLT applies the LT predicate on the "priority" field.
func PriorityLT(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldLT(FieldPriority, v))
// Priority1LT applies the LT predicate on the "priority1" field.
func Priority1LT(v int) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldLT(FieldPriority1, v))
}
// PriorityLTE applies the LTE predicate on the "priority" field.
func PriorityLTE(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldLTE(FieldPriority, v))
}
// PriorityContains applies the Contains predicate on the "priority" field.
func PriorityContains(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldContains(FieldPriority, v))
}
// PriorityHasPrefix applies the HasPrefix predicate on the "priority" field.
func PriorityHasPrefix(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldHasPrefix(FieldPriority, v))
}
// PriorityHasSuffix applies the HasSuffix predicate on the "priority" field.
func PriorityHasSuffix(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldHasSuffix(FieldPriority, v))
}
// PriorityEqualFold applies the EqualFold predicate on the "priority" field.
func PriorityEqualFold(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldEqualFold(FieldPriority, v))
}
// PriorityContainsFold applies the ContainsFold predicate on the "priority" field.
func PriorityContainsFold(v string) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldContainsFold(FieldPriority, v))
// Priority1LTE applies the LTE predicate on the "priority1" field.
func Priority1LTE(v int) predicate.DownloadClients {
return predicate.DownloadClients(sql.FieldLTE(FieldPriority1, v))
}
// RemoveCompletedDownloadsEQ applies the EQ predicate on the "remove_completed_downloads" field.

View File

@@ -32,8 +32,8 @@ func (dcc *DownloadClientsCreate) SetName(s string) *DownloadClientsCreate {
}
// SetImplementation sets the "implementation" field.
func (dcc *DownloadClientsCreate) SetImplementation(s string) *DownloadClientsCreate {
dcc.mutation.SetImplementation(s)
func (dcc *DownloadClientsCreate) SetImplementation(d downloadclients.Implementation) *DownloadClientsCreate {
dcc.mutation.SetImplementation(d)
return dcc
}
@@ -85,16 +85,16 @@ func (dcc *DownloadClientsCreate) SetNillableSettings(s *string) *DownloadClient
return dcc
}
// SetPriority sets the "priority" field.
func (dcc *DownloadClientsCreate) SetPriority(s string) *DownloadClientsCreate {
dcc.mutation.SetPriority(s)
// SetPriority1 sets the "priority1" field.
func (dcc *DownloadClientsCreate) SetPriority1(i int) *DownloadClientsCreate {
dcc.mutation.SetPriority1(i)
return dcc
}
// SetNillablePriority sets the "priority" field if the given value is not nil.
func (dcc *DownloadClientsCreate) SetNillablePriority(s *string) *DownloadClientsCreate {
if s != nil {
dcc.SetPriority(*s)
// SetNillablePriority1 sets the "priority1" field if the given value is not nil.
func (dcc *DownloadClientsCreate) SetNillablePriority1(i *int) *DownloadClientsCreate {
if i != nil {
dcc.SetPriority1(*i)
}
return dcc
}
@@ -188,9 +188,9 @@ func (dcc *DownloadClientsCreate) defaults() {
v := downloadclients.DefaultSettings
dcc.mutation.SetSettings(v)
}
if _, ok := dcc.mutation.Priority(); !ok {
v := downloadclients.DefaultPriority
dcc.mutation.SetPriority(v)
if _, ok := dcc.mutation.Priority1(); !ok {
v := downloadclients.DefaultPriority1
dcc.mutation.SetPriority1(v)
}
if _, ok := dcc.mutation.RemoveCompletedDownloads(); !ok {
v := downloadclients.DefaultRemoveCompletedDownloads
@@ -217,6 +217,11 @@ func (dcc *DownloadClientsCreate) check() error {
if _, ok := dcc.mutation.Implementation(); !ok {
return &ValidationError{Name: "implementation", err: errors.New(`ent: missing required field "DownloadClients.implementation"`)}
}
if v, ok := dcc.mutation.Implementation(); ok {
if err := downloadclients.ImplementationValidator(v); err != nil {
return &ValidationError{Name: "implementation", err: fmt.Errorf(`ent: validator failed for field "DownloadClients.implementation": %w`, err)}
}
}
if _, ok := dcc.mutation.URL(); !ok {
return &ValidationError{Name: "url", err: errors.New(`ent: missing required field "DownloadClients.url"`)}
}
@@ -229,8 +234,13 @@ func (dcc *DownloadClientsCreate) check() error {
if _, ok := dcc.mutation.Settings(); !ok {
return &ValidationError{Name: "settings", err: errors.New(`ent: missing required field "DownloadClients.settings"`)}
}
if _, ok := dcc.mutation.Priority(); !ok {
return &ValidationError{Name: "priority", err: errors.New(`ent: missing required field "DownloadClients.priority"`)}
if _, ok := dcc.mutation.Priority1(); !ok {
return &ValidationError{Name: "priority1", err: errors.New(`ent: missing required field "DownloadClients.priority1"`)}
}
if v, ok := dcc.mutation.Priority1(); ok {
if err := downloadclients.Priority1Validator(v); err != nil {
return &ValidationError{Name: "priority1", err: fmt.Errorf(`ent: validator failed for field "DownloadClients.priority1": %w`, err)}
}
}
if _, ok := dcc.mutation.RemoveCompletedDownloads(); !ok {
return &ValidationError{Name: "remove_completed_downloads", err: errors.New(`ent: missing required field "DownloadClients.remove_completed_downloads"`)}
@@ -276,7 +286,7 @@ func (dcc *DownloadClientsCreate) createSpec() (*DownloadClients, *sqlgraph.Crea
_node.Name = value
}
if value, ok := dcc.mutation.Implementation(); ok {
_spec.SetField(downloadclients.FieldImplementation, field.TypeString, value)
_spec.SetField(downloadclients.FieldImplementation, field.TypeEnum, value)
_node.Implementation = value
}
if value, ok := dcc.mutation.URL(); ok {
@@ -295,9 +305,9 @@ func (dcc *DownloadClientsCreate) createSpec() (*DownloadClients, *sqlgraph.Crea
_spec.SetField(downloadclients.FieldSettings, field.TypeString, value)
_node.Settings = value
}
if value, ok := dcc.mutation.Priority(); ok {
_spec.SetField(downloadclients.FieldPriority, field.TypeString, value)
_node.Priority = value
if value, ok := dcc.mutation.Priority1(); ok {
_spec.SetField(downloadclients.FieldPriority1, field.TypeInt, value)
_node.Priority1 = value
}
if value, ok := dcc.mutation.RemoveCompletedDownloads(); ok {
_spec.SetField(downloadclients.FieldRemoveCompletedDownloads, field.TypeBool, value)

View File

@@ -56,15 +56,15 @@ func (dcu *DownloadClientsUpdate) SetNillableName(s *string) *DownloadClientsUpd
}
// SetImplementation sets the "implementation" field.
func (dcu *DownloadClientsUpdate) SetImplementation(s string) *DownloadClientsUpdate {
dcu.mutation.SetImplementation(s)
func (dcu *DownloadClientsUpdate) SetImplementation(d downloadclients.Implementation) *DownloadClientsUpdate {
dcu.mutation.SetImplementation(d)
return dcu
}
// SetNillableImplementation sets the "implementation" field if the given value is not nil.
func (dcu *DownloadClientsUpdate) SetNillableImplementation(s *string) *DownloadClientsUpdate {
if s != nil {
dcu.SetImplementation(*s)
func (dcu *DownloadClientsUpdate) SetNillableImplementation(d *downloadclients.Implementation) *DownloadClientsUpdate {
if d != nil {
dcu.SetImplementation(*d)
}
return dcu
}
@@ -125,20 +125,27 @@ func (dcu *DownloadClientsUpdate) SetNillableSettings(s *string) *DownloadClient
return dcu
}
// SetPriority sets the "priority" field.
func (dcu *DownloadClientsUpdate) SetPriority(s string) *DownloadClientsUpdate {
dcu.mutation.SetPriority(s)
// SetPriority1 sets the "priority1" field.
func (dcu *DownloadClientsUpdate) SetPriority1(i int) *DownloadClientsUpdate {
dcu.mutation.ResetPriority1()
dcu.mutation.SetPriority1(i)
return dcu
}
// SetNillablePriority sets the "priority" field if the given value is not nil.
func (dcu *DownloadClientsUpdate) SetNillablePriority(s *string) *DownloadClientsUpdate {
if s != nil {
dcu.SetPriority(*s)
// SetNillablePriority1 sets the "priority1" field if the given value is not nil.
func (dcu *DownloadClientsUpdate) SetNillablePriority1(i *int) *DownloadClientsUpdate {
if i != nil {
dcu.SetPriority1(*i)
}
return dcu
}
// AddPriority1 adds i to the "priority1" field.
func (dcu *DownloadClientsUpdate) AddPriority1(i int) *DownloadClientsUpdate {
dcu.mutation.AddPriority1(i)
return dcu
}
// SetRemoveCompletedDownloads sets the "remove_completed_downloads" field.
func (dcu *DownloadClientsUpdate) SetRemoveCompletedDownloads(b bool) *DownloadClientsUpdate {
dcu.mutation.SetRemoveCompletedDownloads(b)
@@ -213,7 +220,25 @@ func (dcu *DownloadClientsUpdate) ExecX(ctx context.Context) {
}
}
// check runs all checks and user-defined validators on the builder.
func (dcu *DownloadClientsUpdate) check() error {
if v, ok := dcu.mutation.Implementation(); ok {
if err := downloadclients.ImplementationValidator(v); err != nil {
return &ValidationError{Name: "implementation", err: fmt.Errorf(`ent: validator failed for field "DownloadClients.implementation": %w`, err)}
}
}
if v, ok := dcu.mutation.Priority1(); ok {
if err := downloadclients.Priority1Validator(v); err != nil {
return &ValidationError{Name: "priority1", err: fmt.Errorf(`ent: validator failed for field "DownloadClients.priority1": %w`, err)}
}
}
return nil
}
func (dcu *DownloadClientsUpdate) sqlSave(ctx context.Context) (n int, err error) {
if err := dcu.check(); err != nil {
return n, err
}
_spec := sqlgraph.NewUpdateSpec(downloadclients.Table, downloadclients.Columns, sqlgraph.NewFieldSpec(downloadclients.FieldID, field.TypeInt))
if ps := dcu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
@@ -229,7 +254,7 @@ func (dcu *DownloadClientsUpdate) sqlSave(ctx context.Context) (n int, err error
_spec.SetField(downloadclients.FieldName, field.TypeString, value)
}
if value, ok := dcu.mutation.Implementation(); ok {
_spec.SetField(downloadclients.FieldImplementation, field.TypeString, value)
_spec.SetField(downloadclients.FieldImplementation, field.TypeEnum, value)
}
if value, ok := dcu.mutation.URL(); ok {
_spec.SetField(downloadclients.FieldURL, field.TypeString, value)
@@ -243,8 +268,11 @@ func (dcu *DownloadClientsUpdate) sqlSave(ctx context.Context) (n int, err error
if value, ok := dcu.mutation.Settings(); ok {
_spec.SetField(downloadclients.FieldSettings, field.TypeString, value)
}
if value, ok := dcu.mutation.Priority(); ok {
_spec.SetField(downloadclients.FieldPriority, field.TypeString, value)
if value, ok := dcu.mutation.Priority1(); ok {
_spec.SetField(downloadclients.FieldPriority1, field.TypeInt, value)
}
if value, ok := dcu.mutation.AddedPriority1(); ok {
_spec.AddField(downloadclients.FieldPriority1, field.TypeInt, value)
}
if value, ok := dcu.mutation.RemoveCompletedDownloads(); ok {
_spec.SetField(downloadclients.FieldRemoveCompletedDownloads, field.TypeBool, value)
@@ -304,15 +332,15 @@ func (dcuo *DownloadClientsUpdateOne) SetNillableName(s *string) *DownloadClient
}
// SetImplementation sets the "implementation" field.
func (dcuo *DownloadClientsUpdateOne) SetImplementation(s string) *DownloadClientsUpdateOne {
dcuo.mutation.SetImplementation(s)
func (dcuo *DownloadClientsUpdateOne) SetImplementation(d downloadclients.Implementation) *DownloadClientsUpdateOne {
dcuo.mutation.SetImplementation(d)
return dcuo
}
// SetNillableImplementation sets the "implementation" field if the given value is not nil.
func (dcuo *DownloadClientsUpdateOne) SetNillableImplementation(s *string) *DownloadClientsUpdateOne {
if s != nil {
dcuo.SetImplementation(*s)
func (dcuo *DownloadClientsUpdateOne) SetNillableImplementation(d *downloadclients.Implementation) *DownloadClientsUpdateOne {
if d != nil {
dcuo.SetImplementation(*d)
}
return dcuo
}
@@ -373,20 +401,27 @@ func (dcuo *DownloadClientsUpdateOne) SetNillableSettings(s *string) *DownloadCl
return dcuo
}
// SetPriority sets the "priority" field.
func (dcuo *DownloadClientsUpdateOne) SetPriority(s string) *DownloadClientsUpdateOne {
dcuo.mutation.SetPriority(s)
// SetPriority1 sets the "priority1" field.
func (dcuo *DownloadClientsUpdateOne) SetPriority1(i int) *DownloadClientsUpdateOne {
dcuo.mutation.ResetPriority1()
dcuo.mutation.SetPriority1(i)
return dcuo
}
// SetNillablePriority sets the "priority" field if the given value is not nil.
func (dcuo *DownloadClientsUpdateOne) SetNillablePriority(s *string) *DownloadClientsUpdateOne {
if s != nil {
dcuo.SetPriority(*s)
// SetNillablePriority1 sets the "priority1" field if the given value is not nil.
func (dcuo *DownloadClientsUpdateOne) SetNillablePriority1(i *int) *DownloadClientsUpdateOne {
if i != nil {
dcuo.SetPriority1(*i)
}
return dcuo
}
// AddPriority1 adds i to the "priority1" field.
func (dcuo *DownloadClientsUpdateOne) AddPriority1(i int) *DownloadClientsUpdateOne {
dcuo.mutation.AddPriority1(i)
return dcuo
}
// SetRemoveCompletedDownloads sets the "remove_completed_downloads" field.
func (dcuo *DownloadClientsUpdateOne) SetRemoveCompletedDownloads(b bool) *DownloadClientsUpdateOne {
dcuo.mutation.SetRemoveCompletedDownloads(b)
@@ -474,7 +509,25 @@ func (dcuo *DownloadClientsUpdateOne) ExecX(ctx context.Context) {
}
}
// check runs all checks and user-defined validators on the builder.
func (dcuo *DownloadClientsUpdateOne) check() error {
if v, ok := dcuo.mutation.Implementation(); ok {
if err := downloadclients.ImplementationValidator(v); err != nil {
return &ValidationError{Name: "implementation", err: fmt.Errorf(`ent: validator failed for field "DownloadClients.implementation": %w`, err)}
}
}
if v, ok := dcuo.mutation.Priority1(); ok {
if err := downloadclients.Priority1Validator(v); err != nil {
return &ValidationError{Name: "priority1", err: fmt.Errorf(`ent: validator failed for field "DownloadClients.priority1": %w`, err)}
}
}
return nil
}
func (dcuo *DownloadClientsUpdateOne) sqlSave(ctx context.Context) (_node *DownloadClients, err error) {
if err := dcuo.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(downloadclients.Table, downloadclients.Columns, sqlgraph.NewFieldSpec(downloadclients.FieldID, field.TypeInt))
id, ok := dcuo.mutation.ID()
if !ok {
@@ -507,7 +560,7 @@ func (dcuo *DownloadClientsUpdateOne) sqlSave(ctx context.Context) (_node *Downl
_spec.SetField(downloadclients.FieldName, field.TypeString, value)
}
if value, ok := dcuo.mutation.Implementation(); ok {
_spec.SetField(downloadclients.FieldImplementation, field.TypeString, value)
_spec.SetField(downloadclients.FieldImplementation, field.TypeEnum, value)
}
if value, ok := dcuo.mutation.URL(); ok {
_spec.SetField(downloadclients.FieldURL, field.TypeString, value)
@@ -521,8 +574,11 @@ func (dcuo *DownloadClientsUpdateOne) sqlSave(ctx context.Context) (_node *Downl
if value, ok := dcuo.mutation.Settings(); ok {
_spec.SetField(downloadclients.FieldSettings, field.TypeString, value)
}
if value, ok := dcuo.mutation.Priority(); ok {
_spec.SetField(downloadclients.FieldPriority, field.TypeString, value)
if value, ok := dcuo.mutation.Priority1(); ok {
_spec.SetField(downloadclients.FieldPriority1, field.TypeInt, value)
}
if value, ok := dcuo.mutation.AddedPriority1(); ok {
_spec.AddField(downloadclients.FieldPriority1, field.TypeInt, value)
}
if value, ok := dcuo.mutation.RemoveCompletedDownloads(); ok {
_spec.SetField(downloadclients.FieldRemoveCompletedDownloads, field.TypeBool, value)

View File

@@ -131,6 +131,7 @@ const (
Resolution720p Resolution = "720p"
Resolution1080p Resolution = "1080p"
Resolution2160p Resolution = "2160p"
ResolutionAny Resolution = "any"
)
func (r Resolution) String() string {
@@ -140,7 +141,7 @@ func (r Resolution) String() string {
// ResolutionValidator is a validator for the "resolution" field enum values. It is called by the builders before save.
func ResolutionValidator(r Resolution) error {
switch r {
case Resolution720p, Resolution1080p, Resolution2160p:
case Resolution720p, Resolution1080p, Resolution2160p, ResolutionAny:
return nil
default:
return fmt.Errorf("media: invalid enum value for resolution field: %q", r)

View File

@@ -25,12 +25,12 @@ var (
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "enable", Type: field.TypeBool},
{Name: "name", Type: field.TypeString},
{Name: "implementation", Type: field.TypeString},
{Name: "implementation", Type: field.TypeEnum, Enums: []string{"transmission", "qbittorrent"}},
{Name: "url", Type: field.TypeString},
{Name: "user", Type: field.TypeString, Default: ""},
{Name: "password", Type: field.TypeString, Default: ""},
{Name: "settings", Type: field.TypeString, Default: ""},
{Name: "priority", Type: field.TypeString, Default: ""},
{Name: "priority1", Type: field.TypeInt, Default: 1},
{Name: "remove_completed_downloads", Type: field.TypeBool, Default: true},
{Name: "remove_failed_downloads", Type: field.TypeBool, Default: true},
{Name: "tags", Type: field.TypeString, Default: ""},
@@ -133,7 +133,7 @@ var (
{Name: "overview", Type: field.TypeString},
{Name: "created_at", Type: field.TypeTime},
{Name: "air_date", Type: field.TypeString, Default: ""},
{Name: "resolution", Type: field.TypeEnum, Enums: []string{"720p", "1080p", "2160p"}, Default: "1080p"},
{Name: "resolution", Type: field.TypeEnum, Enums: []string{"720p", "1080p", "2160p", "any"}, Default: "1080p"},
{Name: "storage_id", Type: field.TypeInt, Nullable: true},
{Name: "target_dir", Type: field.TypeString, Nullable: true},
{Name: "download_history_episodes", Type: field.TypeBool, Nullable: true, Default: false},

View File

@@ -434,12 +434,13 @@ type DownloadClientsMutation struct {
id *int
enable *bool
name *string
implementation *string
implementation *downloadclients.Implementation
url *string
user *string
password *string
settings *string
priority *string
priority1 *int
addpriority1 *int
remove_completed_downloads *bool
remove_failed_downloads *bool
tags *string
@@ -620,12 +621,12 @@ func (m *DownloadClientsMutation) ResetName() {
}
// SetImplementation sets the "implementation" field.
func (m *DownloadClientsMutation) SetImplementation(s string) {
m.implementation = &s
func (m *DownloadClientsMutation) SetImplementation(d downloadclients.Implementation) {
m.implementation = &d
}
// Implementation returns the value of the "implementation" field in the mutation.
func (m *DownloadClientsMutation) Implementation() (r string, exists bool) {
func (m *DownloadClientsMutation) Implementation() (r downloadclients.Implementation, exists bool) {
v := m.implementation
if v == nil {
return
@@ -636,7 +637,7 @@ func (m *DownloadClientsMutation) Implementation() (r string, exists bool) {
// OldImplementation returns the old "implementation" field's value of the DownloadClients entity.
// If the DownloadClients object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *DownloadClientsMutation) OldImplementation(ctx context.Context) (v string, err error) {
func (m *DownloadClientsMutation) OldImplementation(ctx context.Context) (v downloadclients.Implementation, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldImplementation is only allowed on UpdateOne operations")
}
@@ -799,40 +800,60 @@ func (m *DownloadClientsMutation) ResetSettings() {
m.settings = nil
}
// SetPriority sets the "priority" field.
func (m *DownloadClientsMutation) SetPriority(s string) {
m.priority = &s
// SetPriority1 sets the "priority1" field.
func (m *DownloadClientsMutation) SetPriority1(i int) {
m.priority1 = &i
m.addpriority1 = nil
}
// Priority returns the value of the "priority" field in the mutation.
func (m *DownloadClientsMutation) Priority() (r string, exists bool) {
v := m.priority
// Priority1 returns the value of the "priority1" field in the mutation.
func (m *DownloadClientsMutation) Priority1() (r int, exists bool) {
v := m.priority1
if v == nil {
return
}
return *v, true
}
// OldPriority returns the old "priority" field's value of the DownloadClients entity.
// OldPriority1 returns the old "priority1" field's value of the DownloadClients entity.
// If the DownloadClients object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *DownloadClientsMutation) OldPriority(ctx context.Context) (v string, err error) {
func (m *DownloadClientsMutation) OldPriority1(ctx context.Context) (v int, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldPriority is only allowed on UpdateOne operations")
return v, errors.New("OldPriority1 is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldPriority requires an ID field in the mutation")
return v, errors.New("OldPriority1 requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldPriority: %w", err)
return v, fmt.Errorf("querying old value for OldPriority1: %w", err)
}
return oldValue.Priority, nil
return oldValue.Priority1, nil
}
// ResetPriority resets all changes to the "priority" field.
func (m *DownloadClientsMutation) ResetPriority() {
m.priority = nil
// AddPriority1 adds i to the "priority1" field.
func (m *DownloadClientsMutation) AddPriority1(i int) {
if m.addpriority1 != nil {
*m.addpriority1 += i
} else {
m.addpriority1 = &i
}
}
// AddedPriority1 returns the value that was added to the "priority1" field in this mutation.
func (m *DownloadClientsMutation) AddedPriority1() (r int, exists bool) {
v := m.addpriority1
if v == nil {
return
}
return *v, true
}
// ResetPriority1 resets all changes to the "priority1" field.
func (m *DownloadClientsMutation) ResetPriority1() {
m.priority1 = nil
m.addpriority1 = nil
}
// SetRemoveCompletedDownloads sets the "remove_completed_downloads" field.
@@ -999,8 +1020,8 @@ func (m *DownloadClientsMutation) Fields() []string {
if m.settings != nil {
fields = append(fields, downloadclients.FieldSettings)
}
if m.priority != nil {
fields = append(fields, downloadclients.FieldPriority)
if m.priority1 != nil {
fields = append(fields, downloadclients.FieldPriority1)
}
if m.remove_completed_downloads != nil {
fields = append(fields, downloadclients.FieldRemoveCompletedDownloads)
@@ -1033,8 +1054,8 @@ func (m *DownloadClientsMutation) Field(name string) (ent.Value, bool) {
return m.Password()
case downloadclients.FieldSettings:
return m.Settings()
case downloadclients.FieldPriority:
return m.Priority()
case downloadclients.FieldPriority1:
return m.Priority1()
case downloadclients.FieldRemoveCompletedDownloads:
return m.RemoveCompletedDownloads()
case downloadclients.FieldRemoveFailedDownloads:
@@ -1064,8 +1085,8 @@ func (m *DownloadClientsMutation) OldField(ctx context.Context, name string) (en
return m.OldPassword(ctx)
case downloadclients.FieldSettings:
return m.OldSettings(ctx)
case downloadclients.FieldPriority:
return m.OldPriority(ctx)
case downloadclients.FieldPriority1:
return m.OldPriority1(ctx)
case downloadclients.FieldRemoveCompletedDownloads:
return m.OldRemoveCompletedDownloads(ctx)
case downloadclients.FieldRemoveFailedDownloads:
@@ -1096,7 +1117,7 @@ func (m *DownloadClientsMutation) SetField(name string, value ent.Value) error {
m.SetName(v)
return nil
case downloadclients.FieldImplementation:
v, ok := value.(string)
v, ok := value.(downloadclients.Implementation)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
@@ -1130,12 +1151,12 @@ func (m *DownloadClientsMutation) SetField(name string, value ent.Value) error {
}
m.SetSettings(v)
return nil
case downloadclients.FieldPriority:
v, ok := value.(string)
case downloadclients.FieldPriority1:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetPriority(v)
m.SetPriority1(v)
return nil
case downloadclients.FieldRemoveCompletedDownloads:
v, ok := value.(bool)
@@ -1165,13 +1186,21 @@ func (m *DownloadClientsMutation) SetField(name string, value ent.Value) error {
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *DownloadClientsMutation) AddedFields() []string {
return nil
var fields []string
if m.addpriority1 != nil {
fields = append(fields, downloadclients.FieldPriority1)
}
return fields
}
// AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema.
func (m *DownloadClientsMutation) AddedField(name string) (ent.Value, bool) {
switch name {
case downloadclients.FieldPriority1:
return m.AddedPriority1()
}
return nil, false
}
@@ -1180,6 +1209,13 @@ func (m *DownloadClientsMutation) AddedField(name string) (ent.Value, bool) {
// type.
func (m *DownloadClientsMutation) AddField(name string, value ent.Value) error {
switch name {
case downloadclients.FieldPriority1:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddPriority1(v)
return nil
}
return fmt.Errorf("unknown DownloadClients numeric field %s", name)
}
@@ -1228,8 +1264,8 @@ func (m *DownloadClientsMutation) ResetField(name string) error {
case downloadclients.FieldSettings:
m.ResetSettings()
return nil
case downloadclients.FieldPriority:
m.ResetPriority()
case downloadclients.FieldPriority1:
m.ResetPriority1()
return nil
case downloadclients.FieldRemoveCompletedDownloads:
m.ResetRemoveCompletedDownloads()

View File

@@ -32,10 +32,12 @@ func init() {
downloadclientsDescSettings := downloadclientsFields[6].Descriptor()
// downloadclients.DefaultSettings holds the default value on creation for the settings field.
downloadclients.DefaultSettings = downloadclientsDescSettings.Default.(string)
// downloadclientsDescPriority is the schema descriptor for priority field.
downloadclientsDescPriority := downloadclientsFields[7].Descriptor()
// downloadclients.DefaultPriority holds the default value on creation for the priority field.
downloadclients.DefaultPriority = downloadclientsDescPriority.Default.(string)
// downloadclientsDescPriority1 is the schema descriptor for priority1 field.
downloadclientsDescPriority1 := downloadclientsFields[7].Descriptor()
// downloadclients.DefaultPriority1 holds the default value on creation for the priority1 field.
downloadclients.DefaultPriority1 = downloadclientsDescPriority1.Default.(int)
// downloadclients.Priority1Validator is a validator for the "priority1" field. It is called by the builders before save.
downloadclients.Priority1Validator = downloadclientsDescPriority1.Validators[0].(func(int) error)
// downloadclientsDescRemoveCompletedDownloads is the schema descriptor for remove_completed_downloads field.
downloadclientsDescRemoveCompletedDownloads := downloadclientsFields[8].Descriptor()
// downloadclients.DefaultRemoveCompletedDownloads holds the default value on creation for the remove_completed_downloads field.

View File

@@ -1,6 +1,8 @@
package schema
import (
"errors"
"entgo.io/ent"
"entgo.io/ent/schema/field"
)
@@ -15,12 +17,20 @@ func (DownloadClients) Fields() []ent.Field {
return []ent.Field{
field.Bool("enable"),
field.String("name"),
field.String("implementation"),
field.Enum("implementation").Values("transmission", "qbittorrent"),
field.String("url"),
field.String("user").Default(""),
field.String("password").Default(""),
field.String("settings").Default(""),
field.String("priority").Default(""),
field.Int("priority1").Default(1).Validate(func(i int) error {
if i > 50 {
return errors.ErrUnsupported
}
if i <= 0 {
return errors.ErrUnsupported
}
return nil
}),
field.Bool("remove_completed_downloads").Default(true),
field.Bool("remove_failed_downloads").Default(true),
field.String("tags").Default(""),

View File

@@ -25,7 +25,7 @@ func (Media) Fields() []ent.Field {
field.String("overview"),
field.Time("created_at").Default(time.Now()),
field.String("air_date").Default(""),
field.Enum("resolution").Values("720p", "1080p", "2160p").Default("1080p"),
field.Enum("resolution").Values("720p", "1080p", "2160p", "any").Default("1080p"),
field.Int("storage_id").Optional(),
field.String("target_dir").Optional(),
field.Bool("download_history_episodes").Optional().Default(false).Comment("tv series only"),

2
go.mod
View File

@@ -13,6 +13,7 @@ require (
require (
github.com/PuerkitoBio/goquery v1.9.2
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc
github.com/gin-contrib/zap v1.1.3
github.com/ncruces/go-sqlite3 v0.18.4
github.com/nikoksr/notify v1.0.0
@@ -24,7 +25,6 @@ require (
github.com/DATA-DOG/go-sqlmock v1.5.2 // indirect
github.com/andybalholm/cascadia v1.3.2 // indirect
github.com/blinkbean/dingtalk v1.1.3 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible // indirect
github.com/go-test/deep v1.0.4 // indirect
github.com/gregdel/pushover v1.3.1 // indirect

View File

@@ -9,9 +9,12 @@ type Torrent interface {
Save() string
Exists() bool
SeedRatio() (float64, error)
GetHash() string
Reload() error
}
type Downloader interface {
GetAll() ([]Torrent, error)
Download(link, dir string) (Torrent, error)
}
type Storage interface {
}

View File

@@ -0,0 +1,32 @@
# Include any files or directories that you don't want to be copied to your
# container here (e.g., local build artifacts, temporary files, etc.).
#
# For more help, visit the .dockerignore file reference guide at
# https://docs.docker.com/engine/reference/builder/#dockerignore-file
**/.DS_Store
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/bin
**/charts
**/docker-compose*
**/compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md

1
pkg/go-qbittorrent/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
./main.go

View File

@@ -0,0 +1,19 @@
go-qbittorrent
==================
Golang wrapper for qBittorrent Web API (for versions above v4.1) forked from [superturkey650](https://github.com/superturkey650/go-qbittorrent) version (only supporting older API version)
This wrapper is based on the methods described in [qBittorrent's Official Web API](https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-(qBittorrent-4.1)>)
Some methods are only supported in qBittorent's latest version (v4.5 when writing).
It'll be best if you upgrade your client to a latest version.
An example can be found in main.go
Installation
============
The best way is to install with go get::
$ go get github.com/simon-ding/go-qbittorrent/qbt

260
pkg/go-qbittorrent/docs.txt Normal file
View File

@@ -0,0 +1,260 @@
PACKAGE DOCUMENTATION
package qbt
import "/Users/me/Repos/go/src/go-qbittorrent/qbt"
TYPES
type BasicTorrent struct {
AddedOn int `json:"added_on"`
Category string `json:"category"`
CompletionOn int64 `json:"completion_on"`
Dlspeed int `json:"dlspeed"`
Eta int `json:"eta"`
ForceStart bool `json:"force_start"`
Hash string `json:"hash"`
Name string `json:"name"`
NumComplete int `json:"num_complete"`
NumIncomplete int `json:"num_incomplete"`
NumLeechs int `json:"num_leechs"`
NumSeeds int `json:"num_seeds"`
Priority int `json:"priority"`
Progress int `json:"progress"`
Ratio int `json:"ratio"`
SavePath string `json:"save_path"`
SeqDl bool `json:"seq_dl"`
Size int `json:"size"`
State string `json:"state"`
SuperSeeding bool `json:"super_seeding"`
Upspeed int `json:"upspeed"`
}
BasicTorrent holds a basic torrent object from qbittorrent
type Client struct {
URL string
Authenticated bool
Session string //replace with session type
Jar http.CookieJar
// contains filtered or unexported fields
}
Client creates a connection to qbittorrent and performs requests
func NewClient(url string) *Client
NewClient creates a new client connection to qbittorrent
func (c *Client) AddTrackers(infoHash string, trackers string) (*http.Response, error)
AddTrackers adds trackers to a specific torrent
func (c *Client) DecreasePriority(infoHashList []string) (*http.Response, error)
DecreasePriority decreases the priority of a list of torrents
func (c *Client) DeletePermanently(infoHashList []string) (*http.Response, error)
DeletePermanently deletes all files for a list of torrents
func (c *Client) DeleteTemp(infoHashList []string) (*http.Response, error)
DeleteTemp deletes the temporary files for a list of torrents
func (c *Client) DownloadFromFile(file string, options map[string]string) (*http.Response, error)
DownloadFromFile downloads a torrent from a file
func (c *Client) DownloadFromLink(link string, options map[string]string) (*http.Response, error)
DownloadFromLink starts downloading a torrent from a link
func (c *Client) ForceStart(infoHashList []string, value bool) (*http.Response, error)
ForceStart force starts a list of torrents
func (c *Client) GetAlternativeSpeedStatus() (status bool, err error)
GetAlternativeSpeedStatus gets the alternative speed status of your
qbittorrent client
func (c *Client) GetGlobalDownloadLimit() (limit int, err error)
GetGlobalDownloadLimit gets the global download limit of your
qbittorrent client
func (c *Client) GetGlobalUploadLimit() (limit int, err error)
GetGlobalUploadLimit gets the global upload limit of your qbittorrent
client
func (c *Client) GetTorrentDownloadLimit(infoHashList []string) (limits map[string]string, err error)
GetTorrentDownloadLimit gets the download limit for a list of torrents
func (c *Client) GetTorrentUploadLimit(infoHashList []string) (limits map[string]string, err error)
GetTorrentUploadLimit gets the upload limit for a list of torrents
func (c *Client) IncreasePriority(infoHashList []string) (*http.Response, error)
IncreasePriority increases the priority of a list of torrents
func (c *Client) Login(username string, password string) (loggedIn bool, err error)
Login logs you in to the qbittorrent client
func (c *Client) Logout() (loggedOut bool, err error)
Logout logs you out of the qbittorrent client
func (c *Client) Pause(infoHash string) (*http.Response, error)
Pause pauses a specific torrent
func (c *Client) PauseAll() (*http.Response, error)
PauseAll pauses all torrents
func (c *Client) PauseMultiple(infoHashList []string) (*http.Response, error)
PauseMultiple pauses a list of torrents
func (c *Client) Recheck(infoHashList []string) (*http.Response, error)
Recheck rechecks a list of torrents
func (c *Client) Resume(infoHash string) (*http.Response, error)
Resume resumes a specific torrent
func (c *Client) ResumeAll(infoHashList []string) (*http.Response, error)
ResumeAll resumes all torrents
func (c *Client) ResumeMultiple(infoHashList []string) (*http.Response, error)
ResumeMultiple resumes a list of torrents
func (c *Client) SetCategory(infoHashList []string, category string) (*http.Response, error)
SetCategory sets the category for a list of torrents
func (c *Client) SetFilePriority(infoHash string, fileID string, priority string) (*http.Response, error)
SetFilePriority sets the priority for a specific torrent file
func (c *Client) SetGlobalDownloadLimit(limit string) (*http.Response, error)
SetGlobalDownloadLimit sets the global download limit of your
qbittorrent client
func (c *Client) SetGlobalUploadLimit(limit string) (*http.Response, error)
SetGlobalUploadLimit sets the global upload limit of your qbittorrent
client
func (c *Client) SetLabel(infoHashList []string, label string) (*http.Response, error)
SetLabel sets the labels for a list of torrents
func (c *Client) SetMaxPriority(infoHashList []string) (*http.Response, error)
SetMaxPriority sets the max priority for a list of torrents
func (c *Client) SetMinPriority(infoHashList []string) (*http.Response, error)
SetMinPriority sets the min priority for a list of torrents
func (c *Client) SetPreferences(params map[string]string) (*http.Response, error)
SetPreferences sets the preferences of your qbittorrent client
func (c *Client) SetTorrentDownloadLimit(infoHashList []string, limit string) (*http.Response, error)
SetTorrentDownloadLimit sets the download limit for a list of torrents
func (c *Client) SetTorrentUploadLimit(infoHashList []string, limit string) (*http.Response, error)
SetTorrentUploadLimit sets the upload limit of a list of torrents
func (c *Client) Shutdown() (shuttingDown bool, err error)
Shutdown shuts down the qbittorrent client
func (c *Client) Sync(rid string) (Sync, error)
Sync syncs main data of qbittorrent
func (c *Client) ToggleAlternativeSpeed() (*http.Response, error)
ToggleAlternativeSpeed toggles the alternative speed of your qbittorrent
client
func (c *Client) ToggleFirstLastPiecePriority(infoHashList []string) (*http.Response, error)
ToggleFirstLastPiecePriority toggles first last piece priority of a list
of torrents
func (c *Client) ToggleSequentialDownload(infoHashList []string) (*http.Response, error)
ToggleSequentialDownload toggles the download sequence of a list of
torrents
func (c *Client) Torrent(infoHash string) (Torrent, error)
Torrent gets a specific torrent
func (c *Client) TorrentFiles(infoHash string) ([]TorrentFile, error)
TorrentFiles gets the files of a specifc torrent
func (c *Client) TorrentTrackers(infoHash string) ([]Tracker, error)
TorrentTrackers gets all trackers for a specific torrent
func (c *Client) TorrentWebSeeds(infoHash string) ([]WebSeed, error)
TorrentWebSeeds gets seeders for a specific torrent
func (c *Client) Torrents(filters map[string]string) (torrentList []BasicTorrent, err error)
Torrents gets a list of all torrents in qbittorrent matching your filter
type Sync struct {
Categories []string `json:"categories"`
FullUpdate bool `json:"full_update"`
Rid int `json:"rid"`
ServerState struct {
ConnectionStatus string `json:"connection_status"`
DhtNodes int `json:"dht_nodes"`
DlInfoData int `json:"dl_info_data"`
DlInfoSpeed int `json:"dl_info_speed"`
DlRateLimit int `json:"dl_rate_limit"`
Queueing bool `json:"queueing"`
RefreshInterval int `json:"refresh_interval"`
UpInfoData int `json:"up_info_data"`
UpInfoSpeed int `json:"up_info_speed"`
UpRateLimit int `json:"up_rate_limit"`
UseAltSpeedLimits bool `json:"use_alt_speed_limits"`
} `json:"server_state"`
Torrents map[string]Torrent `json:"torrents"`
}
Sync holds the sync response struct
type Torrent struct {
AdditionDate int `json:"addition_date"`
Comment string `json:"comment"`
CompletionDate int `json:"completion_date"`
CreatedBy string `json:"created_by"`
CreationDate int `json:"creation_date"`
DlLimit int `json:"dl_limit"`
DlSpeed int `json:"dl_speed"`
DlSpeedAvg int `json:"dl_speed_avg"`
Eta int `json:"eta"`
LastSeen int `json:"last_seen"`
NbConnections int `json:"nb_connections"`
NbConnectionsLimit int `json:"nb_connections_limit"`
Peers int `json:"peers"`
PeersTotal int `json:"peers_total"`
PieceSize int `json:"piece_size"`
PiecesHave int `json:"pieces_have"`
PiecesNum int `json:"pieces_num"`
Reannounce int `json:"reannounce"`
SavePath string `json:"save_path"`
SeedingTime int `json:"seeding_time"`
Seeds int `json:"seeds"`
SeedsTotal int `json:"seeds_total"`
ShareRatio float64 `json:"share_ratio"`
TimeElapsed int `json:"time_elapsed"`
TotalDownloaded int `json:"total_downloaded"`
TotalDownloadedSession int `json:"total_downloaded_session"`
TotalSize int `json:"total_size"`
TotalUploaded int `json:"total_uploaded"`
TotalUploadedSession int `json:"total_uploaded_session"`
TotalWasted int `json:"total_wasted"`
UpLimit int `json:"up_limit"`
UpSpeed int `json:"up_speed"`
UpSpeedAvg int `json:"up_speed_avg"`
}
Torrent holds a torrent object from qbittorrent
type TorrentFile struct {
IsSeed bool `json:"is_seed"`
Name string `json:"name"`
Priority int `json:"priority"`
Progress int `json:"progress"`
Size int `json:"size"`
}
TorrentFile holds a torrent file object from qbittorrent
type Tracker struct {
Msg string `json:"msg"`
NumPeers int `json:"num_peers"`
Status string `json:"status"`
URL string `json:"url"`
}
Tracker holds a tracker object from qbittorrent
type WebSeed struct {
URL string `json:"url"`
}
WebSeed holds a webseed object from qbittorrent

View File

@@ -0,0 +1,66 @@
package qbittorrent
import (
"fmt"
"polaris/pkg/go-qbittorrent/qbt"
"github.com/davecgh/go-spew/spew"
)
func main() {
// connect to qbittorrent client
qb := qbt.NewClient("http://localhost:8181")
// login to the client
loginOpts := qbt.LoginOptions{
Username: "username",
Password: "password",
}
err := qb.Login(loginOpts)
if err != nil {
fmt.Println(err)
}
// ********************
// DOWNLOAD A TORRENT *
// ********************
// were not using any filters so the options map is empty
downloadOpts := qbt.DownloadOptions{}
// set the path to the file
//path := "/Users/me/Downloads/Source.Code.2011.1080p.BluRay.H264.AAC-RARBG-[rarbg.to].torrent"
links := []string{"http://rarbg.to/download.php?id=9buc5hp&h=d73&f=Courage.the.Cowardly.Dog.1999.S01.1080p.AMZN.WEBRip.DD2.0.x264-NOGRP%5Brartv%5D-[rarbg.to].torrent"}
// download the torrent using the file
// the wrapper will handle opening and closing the file for you
err = qb.DownloadLinks(links, downloadOpts)
if err != nil {
fmt.Println("[-] Download torrent from link")
fmt.Println(err)
} else {
fmt.Println("[+] Download torrent from link")
}
// ******************
// GET ALL TORRENTS *
// ******************
torrentsOpts := qbt.TorrentsOptions{}
filter := "inactive"
sort := "name"
hash := "d739f78a12b241ba62719b1064701ffbb45498a8"
torrentsOpts.Filter = &filter
torrentsOpts.Sort = &sort
torrentsOpts.Hashes = []string{hash}
torrents, err := qb.Torrents(torrentsOpts)
if err != nil {
fmt.Println("[-] Get torrent list")
fmt.Println(err)
} else {
fmt.Println("[+] Get torrent list")
if len(torrents) > 0 {
spew.Dump(torrents[0])
} else {
fmt.Println("No torrents found")
}
}
}

View File

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,387 @@
package qbt
// BasicTorrent holds a basic torrent object from qbittorrent
type BasicTorrent struct {
Category string `json:"category"`
CompletionOn int64 `json:"completion_on"`
Dlspeed int `json:"dlspeed"`
Eta int `json:"eta"`
ForceStart bool `json:"force_start"`
Hash string `json:"hash"`
Name string `json:"name"`
NumComplete int `json:"num_complete"`
NumIncomplete int `json:"num_incomplete"`
NumLeechs int `json:"num_leechs"`
NumSeeds int `json:"num_seeds"`
Priority int `json:"priority"`
Progress int `json:"progress"`
Ratio int `json:"ratio"`
SavePath string `json:"save_path"`
SeqDl bool `json:"seq_dl"`
Size int `json:"size"`
State string `json:"state"`
SuperSeeding bool `json:"super_seeding"`
Upspeed int `json:"upspeed"`
FirstLastPiecePriority bool `json:"f_l_piece_prio"`
}
// Torrent holds a torrent object from qbittorrent
// with more information than BasicTorrent
type Torrent struct {
AdditionDate int `json:"addition_date"`
Comment string `json:"comment"`
CompletionDate int `json:"completion_date"`
CreatedBy string `json:"created_by"`
CreationDate int `json:"creation_date"`
DlLimit int `json:"dl_limit"`
DlSpeed int `json:"dl_speed"`
DlSpeedAvg int `json:"dl_speed_avg"`
Eta int `json:"eta"`
LastSeen int `json:"last_seen"`
NbConnections int `json:"nb_connections"`
NbConnectionsLimit int `json:"nb_connections_limit"`
Peers int `json:"peers"`
PeersTotal int `json:"peers_total"`
PieceSize int `json:"piece_size"`
PiecesHave int `json:"pieces_have"`
PiecesNum int `json:"pieces_num"`
Reannounce int `json:"reannounce"`
SavePath string `json:"save_path"`
SeedingTime int `json:"seeding_time"`
Seeds int `json:"seeds"`
SeedsTotal int `json:"seeds_total"`
ShareRatio float64 `json:"share_ratio"`
TimeElapsed int `json:"time_elapsed"`
TotalDl int `json:"total_downloaded"`
TotalDlSession int `json:"total_downloaded_session"`
TotalSize int `json:"total_size"`
TotalUl int `json:"total_uploaded"`
TotalUlSession int `json:"total_uploaded_session"`
TotalWasted int `json:"total_wasted"`
UpLimit int `json:"up_limit"`
UpSpeed int `json:"up_speed"`
UpSpeedAvg int `json:"up_speed_avg"`
}
type TorrentInfo struct {
AddedOn int64 `json:"added_on"`
AmountLeft int64 `json:"amount_left"`
AutoTmm bool `json:"auto_tmm"`
Availability int64 `json:"availability"`
Category string `json:"category"`
Completed int64 `json:"completed"`
CompletionOn int64 `json:"completion_on"`
ContentPath string `json:"content_path"`
DlLimit int64 `json:"dl_limit"`
Dlspeed int64 `json:"dlspeed"`
Downloaded int64 `json:"downloaded"`
DownloadedSession int64 `json:"downloaded_session"`
Eta int64 `json:"eta"`
FLPiecePrio bool `json:"f_l_piece_prio"`
ForceStart bool `json:"force_start"`
Hash string `json:"hash"`
LastActivity int64 `json:"last_activity"`
MagnetURI string `json:"magnet_uri"`
MaxRatio float64 `json:"max_ratio"`
MaxSeedingTime int64 `json:"max_seeding_time"`
Name string `json:"name"`
NumComplete int64 `json:"num_complete"`
NumIncomplete int64 `json:"num_incomplete"`
NumLeechs int64 `json:"num_leechs"`
NumSeeds int64 `json:"num_seeds"`
Priority int64 `json:"priority"`
Progress float64 `json:"progress"`
Ratio float64 `json:"ratio"`
RatioLimit int64 `json:"ratio_limit"`
SavePath string `json:"save_path"`
SeedingTimeLimit int64 `json:"seeding_time_limit"`
SeenComplete int64 `json:"seen_complete"`
SeqDl bool `json:"seq_dl"`
Size int64 `json:"size"`
State string `json:"state"`
SuperSeeding bool `json:"super_seeding"`
Tags string `json:"tags"`
TimeActive int64 `json:"time_active"`
TotalSize int64 `json:"total_size"`
Tracker string `json:"tracker"`
TrackersCount int64 `json:"trackers_count"`
UpLimit int64 `json:"up_limit"`
Uploaded int64 `json:"uploaded"`
UploadedSession int64 `json:"uploaded_session"`
Upspeed int64 `json:"upspeed"`
}
// Tracker holds a tracker object from qbittorrent
type Tracker struct {
Msg string `json:"msg"`
NumPeers int `json:"num_peers"`
NumSeeds int `json:"num_seeds"`
NumLeeches int `json:"num_leeches"`
NumDownloaded int `json:"num_downloaded"`
Tier int `json:"tier"`
Status int `json:"status"`
URL string `json:"url"`
}
// WebSeed holds a webseed object from qbittorrent
type WebSeed struct {
URL string `json:"url"`
}
// TorrentFile holds a torrent file object from qbittorrent
type TorrentFile struct {
Index int `json:"index"`
IsSeed bool `json:"is_seed"`
Name string `json:"name"`
Availability float32 `json:"availability"`
Priority int `json:"priority"`
Progress int `json:"progress"`
Size int `json:"size"`
PieceRange []int `json:"piece_range"`
}
// Sync holds the sync response struct which contains
// the server state and a map of infohashes to Torrents
type Sync struct {
Categories []string `json:"categories"`
FullUpdate bool `json:"full_update"`
Rid int `json:"rid"`
ServerState struct {
ConnectionStatus string `json:"connection_status"`
DhtNodes int `json:"dht_nodes"`
DlInfoData int `json:"dl_info_data"`
DlInfoSpeed int `json:"dl_info_speed"`
DlRateLimit int `json:"dl_rate_limit"`
Queueing bool `json:"queueing"`
RefreshInterval int `json:"refresh_interval"`
UpInfoData int `json:"up_info_data"`
UpInfoSpeed int `json:"up_info_speed"`
UpRateLimit int `json:"up_rate_limit"`
UseAltSpeedLimits bool `json:"use_alt_speed_limits"`
} `json:"server_state"`
Torrents map[string]Torrent `json:"torrents"`
}
type BuildInfo struct {
QTVersion string `json:"qt"`
LibtorrentVersion string `json:"libtorrent"`
BoostVersion string `json:"boost"`
OpenSSLVersion string `json:"openssl"`
AppBitness string `json:"bitness"`
}
type Preferences struct {
Locale string `json:"locale"`
CreateSubfolderEnabled bool `json:"create_subfolder_enabled"`
StartPausedEnabled bool `json:"start_paused_enabled"`
AutoDeleteMode int `json:"auto_delete_mode"`
PreallocateAll bool `json:"preallocate_all"`
IncompleteFilesExt bool `json:"incomplete_files_ext"`
AutoTMMEnabled bool `json:"auto_tmm_enabled"`
TorrentChangedTMMEnabled bool `json:"torrent_changed_tmm_enabled"`
SavePathChangedTMMEnabled bool `json:"save_path_changed_tmm_enabled"`
CategoryChangedTMMEnabled bool `json:"category_changed_tmm_enabled"`
SavePath string `json:"save_path"`
TempPathEnabled bool `json:"temp_path_enabled"`
TempPath string `json:"temp_path"`
ScanDirs map[string]interface{} `json:"scan_dirs"`
ExportDir string `json:"export_dir"`
ExportDirFin string `json:"export_dir_fin"`
MailNotificationEnabled string `json:"mail_notification_enabled"`
MailNotificationSender string `json:"mail_notification_sender"`
MailNotificationEmail string `json:"mail_notification_email"`
MailNotificationSMPTP string `json:"mail_notification_smtp"`
MailNotificationSSLEnabled bool `json:"mail_notification_ssl_enabled"`
MailNotificationAuthEnabled bool `json:"mail_notification_auth_enabled"`
MailNotificationUsername string `json:"mail_notification_username"`
MailNotificationPassword string `json:"mail_notification_password"`
AutorunEnabled bool `json:"autorun_enabled"`
AutorunProgram string `json:"autorun_program"`
QueueingEnabled bool `json:"queueing_enabled"`
MaxActiveDls int `json:"max_active_downloads"`
MaxActiveTorrents int `json:"max_active_torrents"`
MaxActiveUls int `json:"max_active_uploads"`
DontCountSlowTorrents bool `json:"dont_count_slow_torrents"`
SlowTorrentDlRateThreshold int `json:"slow_torrent_dl_rate_threshold"`
SlowTorrentUlRateThreshold int `json:"slow_torrent_ul_rate_threshold"`
SlowTorrentInactiveTimer int `json:"slow_torrent_inactive_timer"`
MaxRatioEnabled bool `json:"max_ratio_enabled"`
MaxRatio float64 `json:"max_ratio"`
MaxRatioAct bool `json:"max_ratio_act"`
ListenPort int `json:"listen_port"`
UPNP bool `json:"upnp"`
RandomPort bool `json:"random_port"`
DlLimit int `json:"dl_limit"`
UlLimit int `json:"up_limit"`
MaxConnections int `json:"max_connec"`
MaxConnectionsPerTorrent int `json:"max_connec_per_torrent"`
MaxUls int `json:"max_uploads"`
MaxUlsPerTorrent int `json:"max_uploads_per_torrent"`
UTPEnabled bool `json:"enable_utp"`
LimitUTPRate bool `json:"limit_utp_rate"`
LimitTCPOverhead bool `json:"limit_tcp_overhead"`
LimitLANPeers bool `json:"limit_lan_peers"`
AltDlLimit int `json:"alt_dl_limit"`
AltUlLimit int `json:"alt_up_limit"`
SchedulerEnabled bool `json:"scheduler_enabled"`
ScheduleFromHour int `json:"schedule_from_hour"`
ScheduleFromMin int `json:"schedule_from_min"`
ScheduleToHour int `json:"schedule_to_hour"`
ScheduleToMin int `json:"schedule_to_min"`
SchedulerDays int `json:"scheduler_days"`
DHTEnabled bool `json:"dht"`
DHTSameAsBT bool `json:"dhtSameAsBT"`
DHTPort int `json:"dht_port"`
PexEnabled bool `json:"pex"`
LSDEnabled bool `json:"lsd"`
Encryption int `json:"encryption"`
AnonymousMode bool `json:"anonymous_mode"`
ProxyType int `json:"proxy_type"`
ProxyIP string `json:"proxy_ip"`
ProxyPort int `json:"proxy_port"`
ProxyPeerConnections bool `json:"proxy_peer_connections"`
ForceProxy bool `json:"force_proxy"`
ProxyAuthEnabled bool `json:"proxy_auth_enabled"`
ProxyUsername string `json:"proxy_username"`
ProxyPassword string `json:"proxy_password"`
IPFilterEnabled bool `json:"ip_filter_enabled"`
IPFilterPath string `json:"ip_filter_path"`
IPFilterTrackers string `json:"ip_filter_trackers"`
WebUIDomainList string `json:"web_ui_domain_list"`
WebUIAddress string `json:"web_ui_address"`
WebUIPort int `json:"web_ui_port"`
WebUIUPNPEnabled bool `json:"web_ui_upnp"`
WebUIUsername string `json:"web_ui_username"`
WebUIPassword string `json:"web_ui_password"`
WebUICSRFProtectionEnabled bool `json:"web_ui_csrf_protection_enabled"`
WebUIClickjackingProtectionEnabled bool `json:"web_ui_clickjacking_protection_enabled"`
BypassLocalAuth bool `json:"bypass_local_auth"`
BypassAuthSubnetWhitelistEnabled bool `json:"bypass_auth_subnet_whitelist_enabled"`
BypassAuthSubnetWhitelist string `json:"bypass_auth_subnet_whitelist"`
AltWebUIEnabled bool `json:"alternative_webui_enabled"`
AltWebUIPath string `json:"alternative_webui_path"`
UseHTTPS bool `json:"use_https"`
SSLKey string `json:"ssl_key"`
SSLCert string `json:"ssl_cert"`
DynDNSEnabled bool `json:"dyndns_enabled"`
DynDNSService int `json:"dyndns_service"`
DynDNSUsername string `json:"dyndns_username"`
DynDNSPassword string `json:"dyndns_password"`
DynDNSDomain string `json:"dyndns_domain"`
RSSRefreshInterval int `json:"rss_refresh_interval"`
RSSMaxArtPerFeed int `json:"rss_max_articles_per_feed"`
RSSProcessingEnabled bool `json:"rss_processing_enabled"`
RSSAutoDlEnabled bool `json:"rss_auto_downloading_enabled"`
}
// Log
type Log struct {
ID int `json:"id"`
Message string `json:"message"`
Timestamp int `json:"timestamp"`
Type int `json:"type"`
}
// PeerLog
type PeerLog struct {
ID int `json:"id"`
IP string `json:"ip"`
Blocked bool `json:"blocked"`
Timestamp int `json:"timestamp"`
Reason string `json:"reason"`
}
// Info
type Info struct {
ConnectionStatus string `json:"connection_status"`
DHTNodes int `json:"dht_nodes"`
DlInfoData int `json:"dl_info_data"`
DlInfoSpeed int `json:"dl_info_speed"`
DlRateLimit int `json:"dl_rate_limit"`
UlInfoData int `json:"up_info_data"`
UlInfoSpeed int `json:"up_info_speed"`
UlRateLimit int `json:"up_rate_limit"`
Queueing bool `json:"queueing"`
UseAltSpeedLimits bool `json:"use_alt_speed_limits"`
RefreshInterval int `json:"refresh_interval"`
}
type TorrentsOptions struct {
Filter *string // all, downloading, completed, paused, active, inactive => optional
Category *string // => optional
Sort *string // => optional
Reverse *bool // => optional
Limit *int // => optional (no negatives)
Offset *int // => optional (negatives allowed)
Hashes []string // separated by | => optional
}
// Category of torrent
type Category struct {
Name string `json:"name"`
SavePath string `json:"savePath"`
}
// Categories mapping
type Categories struct {
Category map[string]Category
}
// LoginOptions contains all options for /login endpoint
type LoginOptions struct {
Username string
Password string
}
// AddTrackersOptions contains all options for /addTrackers endpoint
type AddTrackersOptions struct {
Hash string
Trackers []string
}
// EditTrackerOptions contains all options for /editTracker endpoint
type EditTrackerOptions struct {
Hash string
OrigURL string
NewURL string
}
// RemoveTrackersOptions contains all options for /removeTrackers endpoint
type RemoveTrackersOptions struct {
Hash string
Trackers []string
}
type DownloadOptions struct {
Savepath *string
Cookie *string
Category *string
SkipHashChecking *bool
Paused *bool
RootFolder *bool
Rename *string
UploadSpeedLimit *int
DownloadSpeedLimit *int
SequentialDownload *bool
AutomaticTorrentManagement *bool
FirstLastPiecePriority *bool
}
type InfoOptions struct {
Filter *string
Category *string
Sort *string
Reverse *bool
Limit *int
Offset *int
Hashes []string
}
type PriorityValues int
const (
Do_not_download PriorityValues = 0
Normal_priority PriorityValues = 1
High_priority PriorityValues = 6
Maximal_priority PriorityValues = 7
)

View File

@@ -0,0 +1,24 @@
package tools
import (
"fmt"
"io"
"net/http"
"net/http/httputil"
)
// PrintResponse prints the body of a response
func PrintResponse(body io.ReadCloser) {
r, _ := io.ReadAll(body)
fmt.Println("response: " + string(r))
}
// PrintRequest prints a request
func PrintRequest(req *http.Request) error {
r, err := httputil.DumpRequest(req, true)
if err != nil {
return err
}
fmt.Println("request: " + string(r))
return nil
}

View File

@@ -14,6 +14,21 @@ type MovieMetadata struct {
IsQingban bool
}
func (m *MovieMetadata) IsAcceptable(names... string) bool {
for _, name := range names {
re := regexp.MustCompile(`[^\p{L}\w\s]`)
name = re.ReplaceAllString(strings.ToLower(name), " ")
name2 := re.ReplaceAllString(strings.ToLower(m.Name), " ")
name = strings.Join(strings.Fields(name), " ")
name2 = strings.Join(strings.Fields(name2), " ")
if strings.Contains(name2, name) {
return true
}
}
return false
}
func ParseMovie(name string) *MovieMetadata {
name = strings.Join(strings.Fields(name), " ") //remove unnessary spaces
name = strings.ToLower(strings.TrimSpace(name))

View File

@@ -18,6 +18,24 @@ type Metadata struct {
IsSeasonPack bool
}
func (m *Metadata) IsAcceptable(names... string) bool {
for _, name := range names {
re := regexp.MustCompile(`[^\p{L}\w\s]`)
name = re.ReplaceAllString(strings.ToLower(name), " ")
nameCN := re.ReplaceAllString(strings.ToLower(m.NameCn), " ")
nameEN := re.ReplaceAllString(strings.ToLower(m.NameEn), " ")
name = strings.Join(strings.Fields(name), " ")
nameCN = strings.Join(strings.Fields(nameCN), " ")
nameEN = strings.Join(strings.Fields(nameEN), " ")
if strings.Contains(nameCN, name) || strings.Contains(nameEN, name) {
return true
}
}
return false
}
func ParseTv(name string) *Metadata {
name = strings.ToLower(name)
name = strings.ReplaceAll(name, "\u200b", "") //remove unicode hidden character

View File

@@ -0,0 +1,196 @@
package qbittorrent
import (
"encoding/json"
"fmt"
"polaris/pkg"
"polaris/pkg/go-qbittorrent/qbt"
"time"
"github.com/pkg/errors"
)
type Info struct {
URL string
User string
Password string
}
type Client struct {
c *qbt.Client
Info
}
func NewClient(url, user, pass string) (*Client, error) {
// connect to qbittorrent client
qb := qbt.NewClient(url)
// login to the client
loginOpts := qbt.LoginOptions{
Username: user,
Password: pass,
}
err := qb.Login(loginOpts)
if err != nil {
return nil, err
}
return &Client{c: qb, Info: Info{URL: url, User: user, Password: pass}}, nil
}
func (c *Client) GetAll() ([]pkg.Torrent, error) {
tt, err :=c.c.Torrents(qbt.TorrentsOptions{})
if err != nil {
return nil, errors.Wrap(err, "get torrents")
}
var res []pkg.Torrent
for _, t := range tt {
t1 := &Torrent{
c: c.c,
Hash: t.Hash,
Info: c.Info,
}
res = append(res, t1)
}
return res, nil
}
func (c *Client) Download(link, dir string) (pkg.Torrent, error) {
all, err := c.c.Torrents(qbt.TorrentsOptions{})
if err != nil {
return nil, errors.Wrap(err, "get old torrents")
}
allHash := make(map[string]bool, len(all))
for _, t := range all {
allHash[t.Hash] = true
}
err = c.c.DownloadLinks([]string{link}, qbt.DownloadOptions{Savepath: &dir})
if err != nil {
return nil, errors.Wrap(err, "qbt download")
}
var newHash string
loop:
for i := 0; i < 10; i++ {
time.Sleep(1 * time.Second)
all, err = c.c.Torrents(qbt.TorrentsOptions{})
if err != nil {
return nil, errors.Wrap(err, "get new torrents")
}
for _, t := range all {
if !allHash[t.Hash] {
newHash = t.Hash
break loop
}
}
}
if newHash == "" {
return nil, fmt.Errorf("download torrent fail: timeout")
}
return &Torrent{Hash: newHash, c: c.c, Info: c.Info}, nil
}
type Torrent struct {
c *qbt.Client
Hash string
Info
}
func (t *Torrent) GetHash() string {
return t.Hash
}
func (t *Torrent) getTorrent() (*qbt.TorrentInfo, error) {
all, err := t.c.Torrents(qbt.TorrentsOptions{Hashes: []string{t.Hash}})
if err != nil {
return nil, err
}
if len(all) == 0 {
return nil, fmt.Errorf("no such torrent: %v", t.Hash)
}
return &all[0], nil
}
func (t *Torrent) Name() (string, error) {
qb, err := t.getTorrent()
if err != nil {
return "", err
}
return qb.Name, nil
}
func (t *Torrent) Progress() (int, error) {
qb, err := t.getTorrent()
if err != nil {
return 0, err
}
p := qb.Progress * 100
if p >= 100 {
return 100, nil
}
if int(p) == 100 {
return 99, nil
}
return int(p), nil
}
func (t *Torrent) Stop() error {
return t.c.Pause([]string{t.Hash})
}
func (t *Torrent) Start() error {
ok, err := t.c.Resume([]string{t.Hash})
if err != nil {
return err
}
if !ok {
return fmt.Errorf("status not 200")
}
return nil
}
func (t *Torrent) Remove() error {
ok, err := t.c.Delete([]string{t.Hash}, true)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("status not 200")
}
return nil
}
func (t *Torrent) Save() string {
data, _ := json.Marshal(t)
return string(data)
}
func (t *Torrent) Exists() bool {
_, err := t.getTorrent()
return err == nil
}
func (t *Torrent) SeedRatio() (float64, error) {
qb, err := t.getTorrent()
if err != nil {
return 0, err
}
return qb.Ratio, nil
}
func (t *Torrent) Reload() error {
c, err := NewClient(t.URL, t.User, t.Password)
if err != nil {
return err
}
t.c = c.c
if !t.Exists() {
return errors.Errorf("torrent not exists: %v", t.Hash)
}
return nil
}

1
pkg/thirdparty/doc.go vendored Normal file
View File

@@ -0,0 +1 @@
package thirdparty

View File

@@ -7,6 +7,7 @@ import (
"net/http"
"net/url"
"polaris/log"
"polaris/pkg"
"strings"
"github.com/hekmon/transmissionrpc/v3"
@@ -45,12 +46,12 @@ type Client struct {
cfg Config
}
func (c *Client) GetAll() ([]*Torrent, error) {
func (c *Client) GetAll() ([]pkg.Torrent, error) {
all, err := c.c.TorrentGetAll(context.TODO())
if err != nil {
return nil, errors.Wrap(err, "get all")
}
var torrents []*Torrent
var torrents []pkg.Torrent
for _, t := range all {
torrents = append(torrents, &Torrent{
Hash: *t.HashString,
@@ -61,7 +62,7 @@ func (c *Client) GetAll() ([]*Torrent, error) {
return torrents, nil
}
func (c *Client) Download(link, dir string) (*Torrent, error) {
func (c *Client) Download(link, dir string) (pkg.Torrent, error) {
if strings.HasPrefix(link, "http") {
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
@@ -104,12 +105,15 @@ type Torrent struct {
Config
}
func (t *Torrent) reloadClient() error {
func (t *Torrent) Reload() error {
c, err := NewClient(t.Config)
if err != nil {
return err
}
t.c = c.c
if !t.Exists() {
return errors.Errorf("torrent not exists: %v", t.Hash)
}
return nil
}
@@ -207,16 +211,6 @@ func (t *Torrent) Save() string {
return string(d)
}
func ReloadTorrent(s string) (*Torrent, error) {
var torrent = Torrent{}
err := json.Unmarshal([]byte(s), &torrent)
if err != nil {
return nil, err
}
err = torrent.reloadClient()
if err != nil {
return nil, errors.Wrap(err, "reload client")
}
return &torrent, nil
func (t *Torrent) GetHash() string {
return t.Hash
}

View File

@@ -56,17 +56,17 @@ func RandString(n int) string {
return string(b)
}
func IsNameAcceptable(name1, name2 string) bool {
re := regexp.MustCompile(`[^\p{L}\w\s]`)
name1 = re.ReplaceAllString(strings.ToLower(name1), " ")
name2 = re.ReplaceAllString(strings.ToLower(name2), " ")
name1 = strings.Join(strings.Fields(name1), " ")
name2 = strings.Join(strings.Fields(name2), " ")
if strings.Contains(name1, name2) || strings.Contains(name2, name1) {
return true
}
return false
}
// func IsNameAcceptable(name1, name2 string) bool {
// re := regexp.MustCompile(`[^\p{L}\w\s]`)
// name1 = re.ReplaceAllString(strings.ToLower(name1), " ")
// name2 = re.ReplaceAllString(strings.ToLower(name2), " ")
// name1 = strings.Join(strings.Fields(name1), " ")
// name2 = strings.Join(strings.Fields(name2), " ")
// if strings.Contains(name1, name2) || strings.Contains(name2, name1) {
// return true
// }
// return false
// }
func FindSeasonEpisodeNum(name string) (se int, ep int, err error) {
seRe := regexp.MustCompile(`S\d+`)

View File

@@ -123,7 +123,7 @@ type TorrentInfo struct {
}
func (s *Server) GetAllTorrents(c *gin.Context) (interface{}, error) {
trc, _, err := s.getDownloadClient()
trc, _, err := s.core.GetDownloadClient()
if err != nil {
return nil, errors.Wrap(err, "connect transmission")
}
@@ -140,7 +140,7 @@ func (s *Server) GetAllTorrents(c *gin.Context) (interface{}, error) {
p, _ := t.Progress()
infos = append(infos, TorrentInfo{
Name: name,
ID: t.Hash,
ID: t.GetHash(),
Progress: p,
})
}

View File

@@ -1,9 +1,13 @@
package core
import (
"encoding/json"
"polaris/db"
"polaris/ent"
"polaris/ent/downloadclients"
"polaris/log"
"polaris/pkg"
"polaris/pkg/qbittorrent"
"polaris/pkg/tmdb"
"polaris/pkg/transmission"
"polaris/pkg/utils"
@@ -48,30 +52,72 @@ func (c *Client) Init() {
func (c *Client) reloadTasks() {
allTasks := c.db.GetRunningHistories()
for _, t := range allTasks {
torrent, err := transmission.ReloadTorrent(t.Saved)
if err != nil {
log.Errorf("relaod task %s failed: %v", t.SourceTitle, err)
var torrent pkg.Torrent
if tt, err := c.reloadTransmiision(t.Saved); err == nil {
torrent = tt
log.Infof("load transmission task: %v", t.Saved)
} else if tt, err := c.reloadQbit(t.Saved); err == nil {
torrent = tt
log.Infof("load qbit task: %v", t.Saved)
} else {
log.Warnf("load task fail: %v", t.Saved)
continue
}
if !torrent.Exists() { //只要种子还存在于客户端中,就重新加载,有可能是还在做种中
continue
}
log.Infof("reloading task: %d %s", t.ID, t.SourceTitle)
c.tasks[t.ID] = &Task{Torrent: torrent}
}
}
func (c *Client) getDownloadClient() (*transmission.Client, *ent.DownloadClients, error) {
tr := c.db.GetTransmission()
trc, err := transmission.NewClient(transmission.Config{
URL: tr.URL,
User: tr.User,
Password: tr.Password,
})
if err != nil {
return nil, nil, errors.Wrap(err, "connect transmission")
func (c *Client) reloadTransmiision(s string) (pkg.Torrent, error) {
var t transmission.Torrent
if err := json.Unmarshal([]byte(s), &t); err != nil {
return nil, err
}
return trc, tr, nil
if err := t.Reload(); err != nil {
return nil, err
}
return &t, nil
}
func (c *Client) reloadQbit(s string) (pkg.Torrent, error) {
var t qbittorrent.Torrent
if err := json.Unmarshal([]byte(s), &t); err != nil {
return nil, err
}
if err := t.Reload(); err != nil {
return nil, err
}
return &t, nil
}
func (c *Client) GetDownloadClient() (pkg.Downloader, *ent.DownloadClients, error) {
downloaders := c.db.GetAllDonloadClients()
for _, d := range downloaders {
if !d.Enable {
continue
}
if d.Implementation == downloadclients.ImplementationTransmission {
trc, err := transmission.NewClient(transmission.Config{
URL: d.URL,
User: d.User,
Password: d.Password,
})
if err != nil {
log.Warnf("connect to download client error: %v", d.URL)
continue
}
return trc, d, nil
} else if d.Implementation == downloadclients.ImplementationQbittorrent {
qbt, err := qbittorrent.NewClient(d.URL, d.User, d.Password)
if err != nil {
log.Warnf("connect to download client error: %v", d.URL)
continue
}
return qbt, d, nil
}
}
return nil, nil, errors.Errorf("no available download client")
}
func (c *Client) TMDB() (*tmdb.Client, error) {

View File

@@ -10,11 +10,13 @@ import (
"path/filepath"
"polaris/db"
"polaris/ent"
"polaris/ent/episode"
"polaris/ent/importlist"
"polaris/ent/media"
"polaris/ent/schema"
"polaris/log"
"polaris/pkg/importlist/plexwatchlist"
"polaris/pkg/metadata"
"polaris/pkg/utils"
"regexp"
"strings"
@@ -299,6 +301,9 @@ func (c *Client) AddMovie2Watchlist(in AddWatchlistIn) (interface{}, error) {
if err := c.downloadBackdrop(detail.BackdropPath, r.ID); err != nil {
log.Errorf("download backdrop error: %v", err)
}
if err := c.checkMovieFolder(r); err != nil {
log.Warnf("check movie folder error: %v", err)
}
}()
log.Infof("add movie %s to watchlist success", detail.Title)
@@ -306,6 +311,33 @@ func (c *Client) AddMovie2Watchlist(in AddWatchlistIn) (interface{}, error) {
}
func (c *Client) checkMovieFolder(m *ent.Media) error {
var storageImpl, err = c.getStorage(m.StorageID, media.MediaTypeMovie)
if err != nil {
return err
}
files, err := storageImpl.ReadDir(m.TargetDir)
if err != nil {
return err
}
ep, err := c.db.GetMovieDummyEpisode(m.ID)
if err != nil {
return err
}
for _,f := range files {
if f.IsDir() || f.Size() < 100 * 1000 * 1000 /* 100M */{ //忽略路径和小于100M的文件
continue
}
meta := metadata.ParseMovie(f.Name())
if meta.IsAcceptable(m.NameCn) || meta.IsAcceptable(m.NameEn) {
log.Infof("found already downloaded movie: %v", f.Name())
c.db.SetEpisodeStatus(ep.ID, episode.StatusDownloaded)
}
}
return nil
}
func IsJav(detail *tmdb.MovieDetails) bool {
if detail.Adult && len(detail.ProductionCountries) > 0 && strings.ToUpper(detail.ProductionCountries[0].Iso3166_1) == "JP" {
return true

View File

@@ -14,7 +14,7 @@ import (
)
func (c *Client) DownloadEpisodeTorrent(r1 torznab.Result, seriesId, seasonNum, episodeNum int) (*string, error) {
trc, dlc, err := c.getDownloadClient()
trc, dlc, err := c.GetDownloadClient()
if err != nil {
return nil, errors.Wrap(err, "connect transmission")
}
@@ -102,7 +102,7 @@ func (c *Client) SearchAndDownload(seriesId, seasonNum, episodeNum int) (*string
}
func (c *Client) DownloadMovie(m *ent.Media, link, name string, size int, indexerID int) (*string, error) {
trc, dlc, err := c.getDownloadClient()
trc, dlc, err := c.GetDownloadClient()
if err != nil {
return nil, errors.Wrap(err, "connect transmission")
}

View File

@@ -341,7 +341,7 @@ func (c *Client) DownloadMovieByID(id int) (string, error) {
}
func (c *Client) downloadMovieSingleEpisode(ep *ent.Episode, targetDir string) (string, error) {
trc, dlc, err := c.getDownloadClient()
trc, dlc, err := c.GetDownloadClient()
if err != nil {
return "", errors.Wrap(err, "connect transmission")
}

View File

@@ -7,7 +7,6 @@ import (
"polaris/log"
"polaris/pkg/metadata"
"polaris/pkg/torznab"
"regexp"
"slices"
"sort"
"strconv"
@@ -47,7 +46,7 @@ func SearchTvSeries(db1 *db.Client, param *SearchParam) ([]torznab.Result, error
}
if !imdbIDMatchExact(series.ImdbID, r.ImdbId) { //imdb id not exact match, check file name
if !torrentNameOk(series, r.Name) {
if !torrentNameOk(series, meta) {
continue
}
}
@@ -67,7 +66,10 @@ func SearchTvSeries(db1 *db.Client, param *SearchParam) ([]torznab.Result, error
} else if len(param.Episodes) == 0 && !meta.IsSeasonPack { //want season pack, but not season pack
continue
}
if param.CheckResolution && meta.Resolution != series.Resolution.String() {
if param.CheckResolution &&
series.Resolution != media.ResolutionAny &&
meta.Resolution != series.Resolution.String() {
continue
}
@@ -160,7 +162,7 @@ func SearchMovie(db1 *db.Client, param *SearchParam) ([]torznab.Result, error) {
}
res := searchWithTorznab(db1, movieDetail.NameEn, movieDetail.NameCn, movieDetail.OriginalName)
if movieDetail.Extras.IsJav(){
if movieDetail.Extras.IsJav() {
res1 := searchWithTorznab(db1, movieDetail.Extras.JavId)
res = append(res, res1...)
}
@@ -177,7 +179,7 @@ func SearchMovie(db1 *db.Client, param *SearchParam) ([]torznab.Result, error) {
}
if !imdbIDMatchExact(movieDetail.ImdbID, r.ImdbId) {
if !torrentNameOk(movieDetail, r.Name) {
if !torrentNameOk(movieDetail, meta) {
continue
}
if !movieDetail.Extras.IsJav() {
@@ -189,7 +191,9 @@ func SearchMovie(db1 *db.Client, param *SearchParam) ([]torznab.Result, error) {
}
}
if param.CheckResolution && meta.Resolution != movieDetail.Resolution.String() {
if param.CheckResolution &&
movieDetail.Resolution != media.ResolutionAny &&
meta.Resolution != movieDetail.Resolution.String() {
continue
}
@@ -300,19 +304,13 @@ func dedup(list []torznab.Result) []torznab.Result {
return res
}
func torrentNameOk(detail *db.MediaDetails, torrentName string) bool {
if detail.Extras.IsJav() && isNameAcceptable(torrentName, detail.Extras.JavId) {
return true
}
return isNameAcceptable(torrentName, detail.NameCn) || isNameAcceptable(torrentName, detail.NameEn) ||
isNameAcceptable(torrentName, detail.OriginalName)
type NameTester interface {
IsAcceptable(names ...string) bool
}
func isNameAcceptable(torrentName, wantedName string) bool {
re := regexp.MustCompile(`[^\p{L}\w\s]`)
torrentName = re.ReplaceAllString(strings.ToLower(torrentName), " ")
wantedName = re.ReplaceAllString(strings.ToLower(wantedName), " ")
torrentName = strings.Join(strings.Fields(torrentName), " ")
wantedName = strings.Join(strings.Fields(wantedName), " ")
return strings.Contains(torrentName, wantedName)
func torrentNameOk(detail *db.MediaDetails, tester NameTester) bool {
if detail.Extras.IsJav() && tester.IsAcceptable(detail.Extras.JavId) {
return true
}
return tester.IsAcceptable(detail.NameCn, detail.NameEn, detail.OriginalName)
}

View File

@@ -6,7 +6,9 @@ import (
"html/template"
"polaris/db"
"polaris/ent"
"polaris/ent/downloadclients"
"polaris/log"
"polaris/pkg/qbittorrent"
"polaris/pkg/transmission"
"polaris/pkg/utils"
"strconv"
@@ -190,25 +192,13 @@ func (s *Server) GetAllIndexers(c *gin.Context) (interface{}, error) {
return indexers, nil
}
func (s *Server) getDownloadClient() (*transmission.Client, *ent.DownloadClients, error) {
tr := s.db.GetTransmission()
trc, err := transmission.NewClient(transmission.Config{
URL: tr.URL,
User: tr.User,
Password: tr.Password,
})
if err != nil {
return nil, nil, errors.Wrap(err, "connect transmission")
}
return trc, tr, nil
}
type downloadClientIn struct {
Name string `json:"name" binding:"required"`
URL string `json:"url" binding:"required"`
User string `json:"user"`
Password string `json:"password"`
Implementation string `json:"implementation" binding:"required"`
Priority int `json:"priority"`
}
func (s *Server) AddDownloadClient(c *gin.Context) (interface{}, error) {
@@ -217,17 +207,35 @@ func (s *Server) AddDownloadClient(c *gin.Context) (interface{}, error) {
return nil, errors.Wrap(err, "bind json")
}
utils.TrimFields(&in)
//test connection
_, err := transmission.NewClient(transmission.Config{
URL: in.URL,
User: in.User,
Password: in.Password,
})
if err != nil {
return nil, errors.Wrap(err, "tranmission setting")
if in.Priority == 0 {
in.Priority = 1 //make default
}
if err := s.db.SaveTransmission(in.Name, in.URL, in.User, in.Password); err != nil {
return nil, errors.Wrap(err, "save transmission")
//test connection
if in.Implementation == downloadclients.ImplementationTransmission.String() {
_, err := transmission.NewClient(transmission.Config{
URL: in.URL,
User: in.User,
Password: in.Password,
})
if err != nil {
return nil, errors.Wrap(err, "tranmission setting")
}
} else if in.Implementation == downloadclients.ImplementationQbittorrent.String() {
_, err := qbittorrent.NewClient(in.URL, in.User, in.Password)
if err != nil {
return nil, errors.Wrap(err, "qbittorrent")
}
}
if err := s.db.SaveDownloader(&ent.DownloadClients{
Name: in.Name,
Implementation: downloadclients.Implementation(in.Implementation),
Priority1: in.Priority,
URL: in.URL,
User: in.User,
Password: in.Password,
}); err != nil {
return nil, errors.Wrap(err, "save downloader")
}
return nil, nil
}

View File

@@ -243,6 +243,7 @@ class DownloadClient {
String? password;
bool? removeCompletedDownloads;
bool? removeFailedDownloads;
int? priority;
DownloadClient(
{this.id,
this.enable,
@@ -252,6 +253,7 @@ class DownloadClient {
this.user,
this.password,
this.removeCompletedDownloads = true,
this.priority = 1,
this.removeFailedDownloads = true});
DownloadClient.fromJson(Map<String, dynamic> json) {
@@ -262,6 +264,7 @@ class DownloadClient {
url = json['url'];
user = json['user'];
password = json['password'];
priority = json["priority1"];
removeCompletedDownloads = json["remove_completed_downloads"] ?? false;
removeFailedDownloads = json["remove_failed_downloads"] ?? false;
}
@@ -275,6 +278,7 @@ class DownloadClient {
data['url'] = url;
data['user'] = user;
data['password'] = password;
data["priority"] = priority;
data["remove_completed_downloads"] = removeCompletedDownloads;
data["remove_failed_downloads"] = removeFailedDownloads;
return data;

View File

@@ -54,6 +54,7 @@ class _SubmitSearchResultState extends ConsumerState<SubmitSearchResult> {
name: "resolution",
decoration: const InputDecoration(labelText: "清晰度"),
items: const [
DropdownMenuItem(value: "any", child: Text("不限")),
DropdownMenuItem(value: "720p", child: Text("720p")),
DropdownMenuItem(value: "1080p", child: Text("1080p")),
DropdownMenuItem(value: "2160p", child: Text("2160p")),

View File

@@ -53,9 +53,10 @@ class _DownloaderState extends ConsumerState<DownloaderSettings> {
"url": client.url,
"user": client.user,
"password": client.password,
"impl": "transmission",
"impl": client.implementation,
"remove_completed_downloads": client.removeCompletedDownloads,
"remove_failed_downloads": client.removeFailedDownloads,
"priority": client.priority.toString(),
},
child: Column(
children: [
@@ -70,7 +71,10 @@ class _DownloaderState extends ConsumerState<DownloaderSettings> {
items: const [
DropdownMenuItem(
value: "transmission", child: Text("Transmission")),
DropdownMenuItem(
value: "qbittorrent", child: Text("qBittorrent")),
],
validator: FormBuilderValidators.required(),
),
FormBuilderTextField(
name: "name",
@@ -84,6 +88,11 @@ class _DownloaderState extends ConsumerState<DownloaderSettings> {
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: FormBuilderValidators.required(),
),
FormBuilderTextField(
name: "priority",
decoration: const InputDecoration(labelText: "优先级", helperText: "1-50, 1最高优先级50最低优先级"),
validator: FormBuilderValidators.integer(),
autovalidateMode: AutovalidateMode.onUserInteraction),
FormBuilderSwitch(
name: "remove_completed_downloads",
title: const Text("任务完成后删除")),
@@ -146,6 +155,7 @@ class _DownloaderState extends ConsumerState<DownloaderSettings> {
url: values["url"],
user: _enableAuth ? values["user"] : null,
password: _enableAuth ? values["password"] : null,
priority: int.parse(values["priority"]),
removeCompletedDownloads: values["remove_completed_downloads"],
removeFailedDownloads: values["remove_failed_downloads"]));
} else {

View File

@@ -267,6 +267,7 @@ class _DetailCardState extends ConsumerState<DetailCard> {
name: "resolution",
decoration: const InputDecoration(labelText: "清晰度"),
items: const [
DropdownMenuItem(value: "any", child: Text("不限")),
DropdownMenuItem(value: "720p", child: Text("720p")),
DropdownMenuItem(value: "1080p", child: Text("1080p")),
DropdownMenuItem(value: "2160p", child: Text("2160p")),