Compare commits

...

18 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
Simon Ding
577a6cee1e fix: add flutter build 2024-09-29 14:37:58 +08:00
Simon Ding
4186d7d97f update go version 2024-09-29 14:33:21 +08:00
Simon Ding
5d726dbcf1 feat: add goreleaser 2024-09-29 14:27:01 +08:00
Simon Ding
ce25c090f5 feat: open url at startup 2024-09-29 13:55:16 +08:00
59 changed files with 4918 additions and 383 deletions

50
.github/workflows/goreleaser.yml vendored Normal file
View File

@@ -0,0 +1,50 @@
name: goreleaser
on:
workflow_dispatch:
push:
tags:
- 'v*'
permissions:
contents: write
jobs:
goreleaser:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Flutter
uses: subosito/flutter-action@v2
with:
channel: stable
flutter-version: 3
- name: Build Web
run: |
cd ui
flutter pub get
flutter build web --no-web-resources-cdn --web-renderer html
-
name: Set up Go
uses: actions/setup-go@v5
with:
go-version: '>=1.23.0'
check-latest: true
-
name: Run GoReleaser
uses: goreleaser/goreleaser-action@v6
with:
# either 'goreleaser' (default) or 'goreleaser-pro'
distribution: goreleaser
# 'latest', 'nightly', or a semver
version: '~> v2'
args: release --clean --skip=validate
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Your GoReleaser Pro key, if you are using the 'goreleaser-pro' distribution
# GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }}

2
.gitignore vendored
View File

@@ -30,3 +30,5 @@ ui/dist/
# Go workspace file
go.work
go.work.sum
dist/

51
.goreleaser.yaml Normal file
View File

@@ -0,0 +1,51 @@
# This is an example .goreleaser.yml file with some sensible defaults.
# Make sure to check the documentation at https://goreleaser.com
# The lines below are called `modelines`. See `:help modeline`
# Feel free to remove those if you don't want/need to use them.
# yaml-language-server: $schema=https://goreleaser.com/static/schema.json
# vim: set ts=2 sw=2 tw=0 fo=cnqoj
version: 2
before:
hooks:
# You may remove this if you don't use go modules.
- go mod tidy
# you may remove this if you don't need go generate
#- go generate ./...
builds:
- env:
- CGO_ENABLED=0
goos:
- linux
- windows
- darwin
- freebsd
main: ./cmd
goarch:
- amd64
- arm64
archives:
- format: tar.gz
# this name template makes the OS and Arch compatible with the results of `uname`.
name_template: >-
{{ .ProjectName }}_
{{- title .Os }}_
{{- if eq .Arch "amd64" }}x86_64
{{- else if eq .Arch "386" }}i386
{{- else }}{{ .Arch }}{{ end }}
{{- if .Arm }}v{{ .Arm }}{{ end }}
# use zip for windows archives
format_overrides:
- goos: windows
format: zip
changelog:
sort: asc
filters:
exclude:
- "^docs:"
- "^test:"

View File

@@ -3,20 +3,28 @@ package main
import (
"polaris/db"
"polaris/log"
"polaris/pkg/utils"
"polaris/server"
"syscall"
"time"
)
func main() {
log.Infof("------------------- Starting Polaris ---------------------")
syscall.Umask(0) //max permission 0777
utils.MaxPermission()
dbClient, err := db.Open()
if err != nil {
log.Panicf("init db error: %v", err)
}
go func() {
time.Sleep(2 * time.Second)
if err := utils.OpenURL("http://127.0.0.1:8080"); err != nil {
log.Errorf("open url error: %v", err)
}
}()
s := server.NewServer(dbClient)
if err := s.Serve(); err != nil {
log.Errorf("server start error: %v", err)

View File

@@ -22,7 +22,8 @@ import (
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
_ "github.com/mattn/go-sqlite3"
_ "github.com/ncruces/go-sqlite3/driver"
_ "github.com/ncruces/go-sqlite3/embed"
"github.com/pkg/errors"
)
@@ -65,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",
})
}
}
@@ -159,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
@@ -218,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) {
@@ -318,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
@@ -643,4 +643,9 @@ func (c *Client) GetMovingNamingFormat() string {
return DefaultNamingFormat
}
return s
}
}
func (c *Client) CleanAllDanglingEpisodes() error {
_, err := c.ent.Episode.Delete().Where(episode.Not(episode.HasMedia())).Exec(context.Background())
return err
}

114
ent/blocklist.go Normal file
View File

@@ -0,0 +1,114 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"polaris/ent/blocklist"
"strings"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
)
// Blocklist is the model entity for the Blocklist schema.
type Blocklist struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Type holds the value of the "type" field.
Type blocklist.Type `json:"type,omitempty"`
// Value holds the value of the "value" field.
Value string `json:"value,omitempty"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Blocklist) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case blocklist.FieldID:
values[i] = new(sql.NullInt64)
case blocklist.FieldType, blocklist.FieldValue:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Blocklist fields.
func (b *Blocklist) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case blocklist.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
b.ID = int(value.Int64)
case blocklist.FieldType:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field type", values[i])
} else if value.Valid {
b.Type = blocklist.Type(value.String)
}
case blocklist.FieldValue:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field value", values[i])
} else if value.Valid {
b.Value = value.String
}
default:
b.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// GetValue returns the ent.Value that was dynamically selected and assigned to the Blocklist.
// This includes values selected through modifiers, order, etc.
func (b *Blocklist) GetValue(name string) (ent.Value, error) {
return b.selectValues.Get(name)
}
// Update returns a builder for updating this Blocklist.
// Note that you need to call Blocklist.Unwrap() before calling this method if this Blocklist
// was returned from a transaction, and the transaction was committed or rolled back.
func (b *Blocklist) Update() *BlocklistUpdateOne {
return NewBlocklistClient(b.config).UpdateOne(b)
}
// Unwrap unwraps the Blocklist entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (b *Blocklist) Unwrap() *Blocklist {
_tx, ok := b.config.driver.(*txDriver)
if !ok {
panic("ent: Blocklist is not a transactional entity")
}
b.config.driver = _tx.drv
return b
}
// String implements the fmt.Stringer.
func (b *Blocklist) String() string {
var builder strings.Builder
builder.WriteString("Blocklist(")
builder.WriteString(fmt.Sprintf("id=%v, ", b.ID))
builder.WriteString("type=")
builder.WriteString(fmt.Sprintf("%v", b.Type))
builder.WriteString(", ")
builder.WriteString("value=")
builder.WriteString(b.Value)
builder.WriteByte(')')
return builder.String()
}
// Blocklists is a parsable slice of Blocklist.
type Blocklists []*Blocklist

View File

@@ -0,0 +1,80 @@
// Code generated by ent, DO NOT EDIT.
package blocklist
import (
"fmt"
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the blocklist type in the database.
Label = "blocklist"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldType holds the string denoting the type field in the database.
FieldType = "type"
// FieldValue holds the string denoting the value field in the database.
FieldValue = "value"
// Table holds the table name of the blocklist in the database.
Table = "blocklists"
)
// Columns holds all SQL columns for blocklist fields.
var Columns = []string{
FieldID,
FieldType,
FieldValue,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
// Type defines the type for the "type" enum field.
type Type string
// Type values.
const (
TypeMedia Type = "media"
TypeTorrent Type = "torrent"
)
func (_type Type) String() string {
return string(_type)
}
// TypeValidator is a validator for the "type" field enum values. It is called by the builders before save.
func TypeValidator(_type Type) error {
switch _type {
case TypeMedia, TypeTorrent:
return nil
default:
return fmt.Errorf("blocklist: invalid enum value for type field: %q", _type)
}
}
// OrderOption defines the ordering options for the Blocklist queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByType orders the results by the type field.
func ByType(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldType, opts...).ToFunc()
}
// ByValue orders the results by the value field.
func ByValue(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldValue, opts...).ToFunc()
}

159
ent/blocklist/where.go Normal file
View File

@@ -0,0 +1,159 @@
// Code generated by ent, DO NOT EDIT.
package blocklist
import (
"polaris/ent/predicate"
"entgo.io/ent/dialect/sql"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Blocklist {
return predicate.Blocklist(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Blocklist {
return predicate.Blocklist(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Blocklist {
return predicate.Blocklist(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Blocklist {
return predicate.Blocklist(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Blocklist {
return predicate.Blocklist(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Blocklist {
return predicate.Blocklist(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Blocklist {
return predicate.Blocklist(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Blocklist {
return predicate.Blocklist(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Blocklist {
return predicate.Blocklist(sql.FieldLTE(FieldID, id))
}
// Value applies equality check predicate on the "value" field. It's identical to ValueEQ.
func Value(v string) predicate.Blocklist {
return predicate.Blocklist(sql.FieldEQ(FieldValue, v))
}
// TypeEQ applies the EQ predicate on the "type" field.
func TypeEQ(v Type) predicate.Blocklist {
return predicate.Blocklist(sql.FieldEQ(FieldType, v))
}
// TypeNEQ applies the NEQ predicate on the "type" field.
func TypeNEQ(v Type) predicate.Blocklist {
return predicate.Blocklist(sql.FieldNEQ(FieldType, v))
}
// TypeIn applies the In predicate on the "type" field.
func TypeIn(vs ...Type) predicate.Blocklist {
return predicate.Blocklist(sql.FieldIn(FieldType, vs...))
}
// TypeNotIn applies the NotIn predicate on the "type" field.
func TypeNotIn(vs ...Type) predicate.Blocklist {
return predicate.Blocklist(sql.FieldNotIn(FieldType, vs...))
}
// ValueEQ applies the EQ predicate on the "value" field.
func ValueEQ(v string) predicate.Blocklist {
return predicate.Blocklist(sql.FieldEQ(FieldValue, v))
}
// ValueNEQ applies the NEQ predicate on the "value" field.
func ValueNEQ(v string) predicate.Blocklist {
return predicate.Blocklist(sql.FieldNEQ(FieldValue, v))
}
// ValueIn applies the In predicate on the "value" field.
func ValueIn(vs ...string) predicate.Blocklist {
return predicate.Blocklist(sql.FieldIn(FieldValue, vs...))
}
// ValueNotIn applies the NotIn predicate on the "value" field.
func ValueNotIn(vs ...string) predicate.Blocklist {
return predicate.Blocklist(sql.FieldNotIn(FieldValue, vs...))
}
// ValueGT applies the GT predicate on the "value" field.
func ValueGT(v string) predicate.Blocklist {
return predicate.Blocklist(sql.FieldGT(FieldValue, v))
}
// ValueGTE applies the GTE predicate on the "value" field.
func ValueGTE(v string) predicate.Blocklist {
return predicate.Blocklist(sql.FieldGTE(FieldValue, v))
}
// ValueLT applies the LT predicate on the "value" field.
func ValueLT(v string) predicate.Blocklist {
return predicate.Blocklist(sql.FieldLT(FieldValue, v))
}
// ValueLTE applies the LTE predicate on the "value" field.
func ValueLTE(v string) predicate.Blocklist {
return predicate.Blocklist(sql.FieldLTE(FieldValue, v))
}
// ValueContains applies the Contains predicate on the "value" field.
func ValueContains(v string) predicate.Blocklist {
return predicate.Blocklist(sql.FieldContains(FieldValue, v))
}
// ValueHasPrefix applies the HasPrefix predicate on the "value" field.
func ValueHasPrefix(v string) predicate.Blocklist {
return predicate.Blocklist(sql.FieldHasPrefix(FieldValue, v))
}
// ValueHasSuffix applies the HasSuffix predicate on the "value" field.
func ValueHasSuffix(v string) predicate.Blocklist {
return predicate.Blocklist(sql.FieldHasSuffix(FieldValue, v))
}
// ValueEqualFold applies the EqualFold predicate on the "value" field.
func ValueEqualFold(v string) predicate.Blocklist {
return predicate.Blocklist(sql.FieldEqualFold(FieldValue, v))
}
// ValueContainsFold applies the ContainsFold predicate on the "value" field.
func ValueContainsFold(v string) predicate.Blocklist {
return predicate.Blocklist(sql.FieldContainsFold(FieldValue, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Blocklist) predicate.Blocklist {
return predicate.Blocklist(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Blocklist) predicate.Blocklist {
return predicate.Blocklist(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Blocklist) predicate.Blocklist {
return predicate.Blocklist(sql.NotPredicates(p))
}

201
ent/blocklist_create.go Normal file
View File

@@ -0,0 +1,201 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"polaris/ent/blocklist"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// BlocklistCreate is the builder for creating a Blocklist entity.
type BlocklistCreate struct {
config
mutation *BlocklistMutation
hooks []Hook
}
// SetType sets the "type" field.
func (bc *BlocklistCreate) SetType(b blocklist.Type) *BlocklistCreate {
bc.mutation.SetType(b)
return bc
}
// SetValue sets the "value" field.
func (bc *BlocklistCreate) SetValue(s string) *BlocklistCreate {
bc.mutation.SetValue(s)
return bc
}
// Mutation returns the BlocklistMutation object of the builder.
func (bc *BlocklistCreate) Mutation() *BlocklistMutation {
return bc.mutation
}
// Save creates the Blocklist in the database.
func (bc *BlocklistCreate) Save(ctx context.Context) (*Blocklist, error) {
return withHooks(ctx, bc.sqlSave, bc.mutation, bc.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (bc *BlocklistCreate) SaveX(ctx context.Context) *Blocklist {
v, err := bc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (bc *BlocklistCreate) Exec(ctx context.Context) error {
_, err := bc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (bc *BlocklistCreate) ExecX(ctx context.Context) {
if err := bc.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (bc *BlocklistCreate) check() error {
if _, ok := bc.mutation.GetType(); !ok {
return &ValidationError{Name: "type", err: errors.New(`ent: missing required field "Blocklist.type"`)}
}
if v, ok := bc.mutation.GetType(); ok {
if err := blocklist.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "Blocklist.type": %w`, err)}
}
}
if _, ok := bc.mutation.Value(); !ok {
return &ValidationError{Name: "value", err: errors.New(`ent: missing required field "Blocklist.value"`)}
}
return nil
}
func (bc *BlocklistCreate) sqlSave(ctx context.Context) (*Blocklist, error) {
if err := bc.check(); err != nil {
return nil, err
}
_node, _spec := bc.createSpec()
if err := sqlgraph.CreateNode(ctx, bc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
bc.mutation.id = &_node.ID
bc.mutation.done = true
return _node, nil
}
func (bc *BlocklistCreate) createSpec() (*Blocklist, *sqlgraph.CreateSpec) {
var (
_node = &Blocklist{config: bc.config}
_spec = sqlgraph.NewCreateSpec(blocklist.Table, sqlgraph.NewFieldSpec(blocklist.FieldID, field.TypeInt))
)
if value, ok := bc.mutation.GetType(); ok {
_spec.SetField(blocklist.FieldType, field.TypeEnum, value)
_node.Type = value
}
if value, ok := bc.mutation.Value(); ok {
_spec.SetField(blocklist.FieldValue, field.TypeString, value)
_node.Value = value
}
return _node, _spec
}
// BlocklistCreateBulk is the builder for creating many Blocklist entities in bulk.
type BlocklistCreateBulk struct {
config
err error
builders []*BlocklistCreate
}
// Save creates the Blocklist entities in the database.
func (bcb *BlocklistCreateBulk) Save(ctx context.Context) ([]*Blocklist, error) {
if bcb.err != nil {
return nil, bcb.err
}
specs := make([]*sqlgraph.CreateSpec, len(bcb.builders))
nodes := make([]*Blocklist, len(bcb.builders))
mutators := make([]Mutator, len(bcb.builders))
for i := range bcb.builders {
func(i int, root context.Context) {
builder := bcb.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*BlocklistMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, bcb.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, bcb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, bcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (bcb *BlocklistCreateBulk) SaveX(ctx context.Context) []*Blocklist {
v, err := bcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (bcb *BlocklistCreateBulk) Exec(ctx context.Context) error {
_, err := bcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (bcb *BlocklistCreateBulk) ExecX(ctx context.Context) {
if err := bcb.Exec(ctx); err != nil {
panic(err)
}
}

88
ent/blocklist_delete.go Normal file
View File

@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"polaris/ent/blocklist"
"polaris/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// BlocklistDelete is the builder for deleting a Blocklist entity.
type BlocklistDelete struct {
config
hooks []Hook
mutation *BlocklistMutation
}
// Where appends a list predicates to the BlocklistDelete builder.
func (bd *BlocklistDelete) Where(ps ...predicate.Blocklist) *BlocklistDelete {
bd.mutation.Where(ps...)
return bd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (bd *BlocklistDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, bd.sqlExec, bd.mutation, bd.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (bd *BlocklistDelete) ExecX(ctx context.Context) int {
n, err := bd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (bd *BlocklistDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(blocklist.Table, sqlgraph.NewFieldSpec(blocklist.FieldID, field.TypeInt))
if ps := bd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, bd.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
bd.mutation.done = true
return affected, err
}
// BlocklistDeleteOne is the builder for deleting a single Blocklist entity.
type BlocklistDeleteOne struct {
bd *BlocklistDelete
}
// Where appends a list predicates to the BlocklistDelete builder.
func (bdo *BlocklistDeleteOne) Where(ps ...predicate.Blocklist) *BlocklistDeleteOne {
bdo.bd.mutation.Where(ps...)
return bdo
}
// Exec executes the deletion query.
func (bdo *BlocklistDeleteOne) Exec(ctx context.Context) error {
n, err := bdo.bd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{blocklist.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (bdo *BlocklistDeleteOne) ExecX(ctx context.Context) {
if err := bdo.Exec(ctx); err != nil {
panic(err)
}
}

526
ent/blocklist_query.go Normal file
View File

@@ -0,0 +1,526 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"polaris/ent/blocklist"
"polaris/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// BlocklistQuery is the builder for querying Blocklist entities.
type BlocklistQuery struct {
config
ctx *QueryContext
order []blocklist.OrderOption
inters []Interceptor
predicates []predicate.Blocklist
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the BlocklistQuery builder.
func (bq *BlocklistQuery) Where(ps ...predicate.Blocklist) *BlocklistQuery {
bq.predicates = append(bq.predicates, ps...)
return bq
}
// Limit the number of records to be returned by this query.
func (bq *BlocklistQuery) Limit(limit int) *BlocklistQuery {
bq.ctx.Limit = &limit
return bq
}
// Offset to start from.
func (bq *BlocklistQuery) Offset(offset int) *BlocklistQuery {
bq.ctx.Offset = &offset
return bq
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (bq *BlocklistQuery) Unique(unique bool) *BlocklistQuery {
bq.ctx.Unique = &unique
return bq
}
// Order specifies how the records should be ordered.
func (bq *BlocklistQuery) Order(o ...blocklist.OrderOption) *BlocklistQuery {
bq.order = append(bq.order, o...)
return bq
}
// First returns the first Blocklist entity from the query.
// Returns a *NotFoundError when no Blocklist was found.
func (bq *BlocklistQuery) First(ctx context.Context) (*Blocklist, error) {
nodes, err := bq.Limit(1).All(setContextOp(ctx, bq.ctx, "First"))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{blocklist.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (bq *BlocklistQuery) FirstX(ctx context.Context) *Blocklist {
node, err := bq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Blocklist ID from the query.
// Returns a *NotFoundError when no Blocklist ID was found.
func (bq *BlocklistQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = bq.Limit(1).IDs(setContextOp(ctx, bq.ctx, "FirstID")); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{blocklist.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (bq *BlocklistQuery) FirstIDX(ctx context.Context) int {
id, err := bq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Blocklist entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Blocklist entity is found.
// Returns a *NotFoundError when no Blocklist entities are found.
func (bq *BlocklistQuery) Only(ctx context.Context) (*Blocklist, error) {
nodes, err := bq.Limit(2).All(setContextOp(ctx, bq.ctx, "Only"))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{blocklist.Label}
default:
return nil, &NotSingularError{blocklist.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (bq *BlocklistQuery) OnlyX(ctx context.Context) *Blocklist {
node, err := bq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Blocklist ID in the query.
// Returns a *NotSingularError when more than one Blocklist ID is found.
// Returns a *NotFoundError when no entities are found.
func (bq *BlocklistQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = bq.Limit(2).IDs(setContextOp(ctx, bq.ctx, "OnlyID")); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{blocklist.Label}
default:
err = &NotSingularError{blocklist.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (bq *BlocklistQuery) OnlyIDX(ctx context.Context) int {
id, err := bq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Blocklists.
func (bq *BlocklistQuery) All(ctx context.Context) ([]*Blocklist, error) {
ctx = setContextOp(ctx, bq.ctx, "All")
if err := bq.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Blocklist, *BlocklistQuery]()
return withInterceptors[[]*Blocklist](ctx, bq, qr, bq.inters)
}
// AllX is like All, but panics if an error occurs.
func (bq *BlocklistQuery) AllX(ctx context.Context) []*Blocklist {
nodes, err := bq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Blocklist IDs.
func (bq *BlocklistQuery) IDs(ctx context.Context) (ids []int, err error) {
if bq.ctx.Unique == nil && bq.path != nil {
bq.Unique(true)
}
ctx = setContextOp(ctx, bq.ctx, "IDs")
if err = bq.Select(blocklist.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (bq *BlocklistQuery) IDsX(ctx context.Context) []int {
ids, err := bq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (bq *BlocklistQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, bq.ctx, "Count")
if err := bq.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, bq, querierCount[*BlocklistQuery](), bq.inters)
}
// CountX is like Count, but panics if an error occurs.
func (bq *BlocklistQuery) CountX(ctx context.Context) int {
count, err := bq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (bq *BlocklistQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, bq.ctx, "Exist")
switch _, err := bq.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (bq *BlocklistQuery) ExistX(ctx context.Context) bool {
exist, err := bq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the BlocklistQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (bq *BlocklistQuery) Clone() *BlocklistQuery {
if bq == nil {
return nil
}
return &BlocklistQuery{
config: bq.config,
ctx: bq.ctx.Clone(),
order: append([]blocklist.OrderOption{}, bq.order...),
inters: append([]Interceptor{}, bq.inters...),
predicates: append([]predicate.Blocklist{}, bq.predicates...),
// clone intermediate query.
sql: bq.sql.Clone(),
path: bq.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Type blocklist.Type `json:"type,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Blocklist.Query().
// GroupBy(blocklist.FieldType).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (bq *BlocklistQuery) GroupBy(field string, fields ...string) *BlocklistGroupBy {
bq.ctx.Fields = append([]string{field}, fields...)
grbuild := &BlocklistGroupBy{build: bq}
grbuild.flds = &bq.ctx.Fields
grbuild.label = blocklist.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// Type blocklist.Type `json:"type,omitempty"`
// }
//
// client.Blocklist.Query().
// Select(blocklist.FieldType).
// Scan(ctx, &v)
func (bq *BlocklistQuery) Select(fields ...string) *BlocklistSelect {
bq.ctx.Fields = append(bq.ctx.Fields, fields...)
sbuild := &BlocklistSelect{BlocklistQuery: bq}
sbuild.label = blocklist.Label
sbuild.flds, sbuild.scan = &bq.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a BlocklistSelect configured with the given aggregations.
func (bq *BlocklistQuery) Aggregate(fns ...AggregateFunc) *BlocklistSelect {
return bq.Select().Aggregate(fns...)
}
func (bq *BlocklistQuery) prepareQuery(ctx context.Context) error {
for _, inter := range bq.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, bq); err != nil {
return err
}
}
}
for _, f := range bq.ctx.Fields {
if !blocklist.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if bq.path != nil {
prev, err := bq.path(ctx)
if err != nil {
return err
}
bq.sql = prev
}
return nil
}
func (bq *BlocklistQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Blocklist, error) {
var (
nodes = []*Blocklist{}
_spec = bq.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Blocklist).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Blocklist{config: bq.config}
nodes = append(nodes, node)
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, bq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (bq *BlocklistQuery) sqlCount(ctx context.Context) (int, error) {
_spec := bq.querySpec()
_spec.Node.Columns = bq.ctx.Fields
if len(bq.ctx.Fields) > 0 {
_spec.Unique = bq.ctx.Unique != nil && *bq.ctx.Unique
}
return sqlgraph.CountNodes(ctx, bq.driver, _spec)
}
func (bq *BlocklistQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(blocklist.Table, blocklist.Columns, sqlgraph.NewFieldSpec(blocklist.FieldID, field.TypeInt))
_spec.From = bq.sql
if unique := bq.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if bq.path != nil {
_spec.Unique = true
}
if fields := bq.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, blocklist.FieldID)
for i := range fields {
if fields[i] != blocklist.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := bq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := bq.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := bq.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := bq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (bq *BlocklistQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(bq.driver.Dialect())
t1 := builder.Table(blocklist.Table)
columns := bq.ctx.Fields
if len(columns) == 0 {
columns = blocklist.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if bq.sql != nil {
selector = bq.sql
selector.Select(selector.Columns(columns...)...)
}
if bq.ctx.Unique != nil && *bq.ctx.Unique {
selector.Distinct()
}
for _, p := range bq.predicates {
p(selector)
}
for _, p := range bq.order {
p(selector)
}
if offset := bq.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := bq.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// BlocklistGroupBy is the group-by builder for Blocklist entities.
type BlocklistGroupBy struct {
selector
build *BlocklistQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (bgb *BlocklistGroupBy) Aggregate(fns ...AggregateFunc) *BlocklistGroupBy {
bgb.fns = append(bgb.fns, fns...)
return bgb
}
// Scan applies the selector query and scans the result into the given value.
func (bgb *BlocklistGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, bgb.build.ctx, "GroupBy")
if err := bgb.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*BlocklistQuery, *BlocklistGroupBy](ctx, bgb.build, bgb, bgb.build.inters, v)
}
func (bgb *BlocklistGroupBy) sqlScan(ctx context.Context, root *BlocklistQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(bgb.fns))
for _, fn := range bgb.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*bgb.flds)+len(bgb.fns))
for _, f := range *bgb.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*bgb.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := bgb.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// BlocklistSelect is the builder for selecting fields of Blocklist entities.
type BlocklistSelect struct {
*BlocklistQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (bs *BlocklistSelect) Aggregate(fns ...AggregateFunc) *BlocklistSelect {
bs.fns = append(bs.fns, fns...)
return bs
}
// Scan applies the selector query and scans the result into the given value.
func (bs *BlocklistSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, bs.ctx, "Select")
if err := bs.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*BlocklistQuery, *BlocklistSelect](ctx, bs.BlocklistQuery, bs, bs.inters, v)
}
func (bs *BlocklistSelect) sqlScan(ctx context.Context, root *BlocklistQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(bs.fns))
for _, fn := range bs.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*bs.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := bs.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

269
ent/blocklist_update.go Normal file
View File

@@ -0,0 +1,269 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"polaris/ent/blocklist"
"polaris/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// BlocklistUpdate is the builder for updating Blocklist entities.
type BlocklistUpdate struct {
config
hooks []Hook
mutation *BlocklistMutation
}
// Where appends a list predicates to the BlocklistUpdate builder.
func (bu *BlocklistUpdate) Where(ps ...predicate.Blocklist) *BlocklistUpdate {
bu.mutation.Where(ps...)
return bu
}
// SetType sets the "type" field.
func (bu *BlocklistUpdate) SetType(b blocklist.Type) *BlocklistUpdate {
bu.mutation.SetType(b)
return bu
}
// SetNillableType sets the "type" field if the given value is not nil.
func (bu *BlocklistUpdate) SetNillableType(b *blocklist.Type) *BlocklistUpdate {
if b != nil {
bu.SetType(*b)
}
return bu
}
// SetValue sets the "value" field.
func (bu *BlocklistUpdate) SetValue(s string) *BlocklistUpdate {
bu.mutation.SetValue(s)
return bu
}
// SetNillableValue sets the "value" field if the given value is not nil.
func (bu *BlocklistUpdate) SetNillableValue(s *string) *BlocklistUpdate {
if s != nil {
bu.SetValue(*s)
}
return bu
}
// Mutation returns the BlocklistMutation object of the builder.
func (bu *BlocklistUpdate) Mutation() *BlocklistMutation {
return bu.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (bu *BlocklistUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, bu.sqlSave, bu.mutation, bu.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (bu *BlocklistUpdate) SaveX(ctx context.Context) int {
affected, err := bu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (bu *BlocklistUpdate) Exec(ctx context.Context) error {
_, err := bu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (bu *BlocklistUpdate) ExecX(ctx context.Context) {
if err := bu.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (bu *BlocklistUpdate) check() error {
if v, ok := bu.mutation.GetType(); ok {
if err := blocklist.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "Blocklist.type": %w`, err)}
}
}
return nil
}
func (bu *BlocklistUpdate) sqlSave(ctx context.Context) (n int, err error) {
if err := bu.check(); err != nil {
return n, err
}
_spec := sqlgraph.NewUpdateSpec(blocklist.Table, blocklist.Columns, sqlgraph.NewFieldSpec(blocklist.FieldID, field.TypeInt))
if ps := bu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := bu.mutation.GetType(); ok {
_spec.SetField(blocklist.FieldType, field.TypeEnum, value)
}
if value, ok := bu.mutation.Value(); ok {
_spec.SetField(blocklist.FieldValue, field.TypeString, value)
}
if n, err = sqlgraph.UpdateNodes(ctx, bu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{blocklist.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
bu.mutation.done = true
return n, nil
}
// BlocklistUpdateOne is the builder for updating a single Blocklist entity.
type BlocklistUpdateOne struct {
config
fields []string
hooks []Hook
mutation *BlocklistMutation
}
// SetType sets the "type" field.
func (buo *BlocklistUpdateOne) SetType(b blocklist.Type) *BlocklistUpdateOne {
buo.mutation.SetType(b)
return buo
}
// SetNillableType sets the "type" field if the given value is not nil.
func (buo *BlocklistUpdateOne) SetNillableType(b *blocklist.Type) *BlocklistUpdateOne {
if b != nil {
buo.SetType(*b)
}
return buo
}
// SetValue sets the "value" field.
func (buo *BlocklistUpdateOne) SetValue(s string) *BlocklistUpdateOne {
buo.mutation.SetValue(s)
return buo
}
// SetNillableValue sets the "value" field if the given value is not nil.
func (buo *BlocklistUpdateOne) SetNillableValue(s *string) *BlocklistUpdateOne {
if s != nil {
buo.SetValue(*s)
}
return buo
}
// Mutation returns the BlocklistMutation object of the builder.
func (buo *BlocklistUpdateOne) Mutation() *BlocklistMutation {
return buo.mutation
}
// Where appends a list predicates to the BlocklistUpdate builder.
func (buo *BlocklistUpdateOne) Where(ps ...predicate.Blocklist) *BlocklistUpdateOne {
buo.mutation.Where(ps...)
return buo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (buo *BlocklistUpdateOne) Select(field string, fields ...string) *BlocklistUpdateOne {
buo.fields = append([]string{field}, fields...)
return buo
}
// Save executes the query and returns the updated Blocklist entity.
func (buo *BlocklistUpdateOne) Save(ctx context.Context) (*Blocklist, error) {
return withHooks(ctx, buo.sqlSave, buo.mutation, buo.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (buo *BlocklistUpdateOne) SaveX(ctx context.Context) *Blocklist {
node, err := buo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (buo *BlocklistUpdateOne) Exec(ctx context.Context) error {
_, err := buo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (buo *BlocklistUpdateOne) ExecX(ctx context.Context) {
if err := buo.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (buo *BlocklistUpdateOne) check() error {
if v, ok := buo.mutation.GetType(); ok {
if err := blocklist.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "Blocklist.type": %w`, err)}
}
}
return nil
}
func (buo *BlocklistUpdateOne) sqlSave(ctx context.Context) (_node *Blocklist, err error) {
if err := buo.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(blocklist.Table, blocklist.Columns, sqlgraph.NewFieldSpec(blocklist.FieldID, field.TypeInt))
id, ok := buo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Blocklist.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := buo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, blocklist.FieldID)
for _, f := range fields {
if !blocklist.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != blocklist.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := buo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := buo.mutation.GetType(); ok {
_spec.SetField(blocklist.FieldType, field.TypeEnum, value)
}
if value, ok := buo.mutation.Value(); ok {
_spec.SetField(blocklist.FieldValue, field.TypeString, value)
}
_node = &Blocklist{config: buo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, buo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{blocklist.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
buo.mutation.done = true
return _node, nil
}

View File

@@ -11,6 +11,7 @@ import (
"polaris/ent/migrate"
"polaris/ent/blocklist"
"polaris/ent/downloadclients"
"polaris/ent/episode"
"polaris/ent/history"
@@ -32,6 +33,8 @@ type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// Blocklist is the client for interacting with the Blocklist builders.
Blocklist *BlocklistClient
// DownloadClients is the client for interacting with the DownloadClients builders.
DownloadClients *DownloadClientsClient
// Episode is the client for interacting with the Episode builders.
@@ -61,6 +64,7 @@ func NewClient(opts ...Option) *Client {
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.Blocklist = NewBlocklistClient(c.config)
c.DownloadClients = NewDownloadClientsClient(c.config)
c.Episode = NewEpisodeClient(c.config)
c.History = NewHistoryClient(c.config)
@@ -162,6 +166,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
return &Tx{
ctx: ctx,
config: cfg,
Blocklist: NewBlocklistClient(cfg),
DownloadClients: NewDownloadClientsClient(cfg),
Episode: NewEpisodeClient(cfg),
History: NewHistoryClient(cfg),
@@ -190,6 +195,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
return &Tx{
ctx: ctx,
config: cfg,
Blocklist: NewBlocklistClient(cfg),
DownloadClients: NewDownloadClientsClient(cfg),
Episode: NewEpisodeClient(cfg),
History: NewHistoryClient(cfg),
@@ -205,7 +211,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// DownloadClients.
// Blocklist.
// Query().
// Count(ctx)
func (c *Client) Debug() *Client {
@@ -228,8 +234,8 @@ func (c *Client) Close() error {
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) {
for _, n := range []interface{ Use(...Hook) }{
c.DownloadClients, c.Episode, c.History, c.ImportList, c.Indexers, c.Media,
c.NotificationClient, c.Settings, c.Storage,
c.Blocklist, c.DownloadClients, c.Episode, c.History, c.ImportList, c.Indexers,
c.Media, c.NotificationClient, c.Settings, c.Storage,
} {
n.Use(hooks...)
}
@@ -239,8 +245,8 @@ func (c *Client) Use(hooks ...Hook) {
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
func (c *Client) Intercept(interceptors ...Interceptor) {
for _, n := range []interface{ Intercept(...Interceptor) }{
c.DownloadClients, c.Episode, c.History, c.ImportList, c.Indexers, c.Media,
c.NotificationClient, c.Settings, c.Storage,
c.Blocklist, c.DownloadClients, c.Episode, c.History, c.ImportList, c.Indexers,
c.Media, c.NotificationClient, c.Settings, c.Storage,
} {
n.Intercept(interceptors...)
}
@@ -249,6 +255,8 @@ func (c *Client) Intercept(interceptors ...Interceptor) {
// Mutate implements the ent.Mutator interface.
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *BlocklistMutation:
return c.Blocklist.mutate(ctx, m)
case *DownloadClientsMutation:
return c.DownloadClients.mutate(ctx, m)
case *EpisodeMutation:
@@ -272,6 +280,139 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
}
}
// BlocklistClient is a client for the Blocklist schema.
type BlocklistClient struct {
config
}
// NewBlocklistClient returns a client for the Blocklist from the given config.
func NewBlocklistClient(c config) *BlocklistClient {
return &BlocklistClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `blocklist.Hooks(f(g(h())))`.
func (c *BlocklistClient) Use(hooks ...Hook) {
c.hooks.Blocklist = append(c.hooks.Blocklist, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `blocklist.Intercept(f(g(h())))`.
func (c *BlocklistClient) Intercept(interceptors ...Interceptor) {
c.inters.Blocklist = append(c.inters.Blocklist, interceptors...)
}
// Create returns a builder for creating a Blocklist entity.
func (c *BlocklistClient) Create() *BlocklistCreate {
mutation := newBlocklistMutation(c.config, OpCreate)
return &BlocklistCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Blocklist entities.
func (c *BlocklistClient) CreateBulk(builders ...*BlocklistCreate) *BlocklistCreateBulk {
return &BlocklistCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *BlocklistClient) MapCreateBulk(slice any, setFunc func(*BlocklistCreate, int)) *BlocklistCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &BlocklistCreateBulk{err: fmt.Errorf("calling to BlocklistClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*BlocklistCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &BlocklistCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Blocklist.
func (c *BlocklistClient) Update() *BlocklistUpdate {
mutation := newBlocklistMutation(c.config, OpUpdate)
return &BlocklistUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *BlocklistClient) UpdateOne(b *Blocklist) *BlocklistUpdateOne {
mutation := newBlocklistMutation(c.config, OpUpdateOne, withBlocklist(b))
return &BlocklistUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *BlocklistClient) UpdateOneID(id int) *BlocklistUpdateOne {
mutation := newBlocklistMutation(c.config, OpUpdateOne, withBlocklistID(id))
return &BlocklistUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Blocklist.
func (c *BlocklistClient) Delete() *BlocklistDelete {
mutation := newBlocklistMutation(c.config, OpDelete)
return &BlocklistDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *BlocklistClient) DeleteOne(b *Blocklist) *BlocklistDeleteOne {
return c.DeleteOneID(b.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *BlocklistClient) DeleteOneID(id int) *BlocklistDeleteOne {
builder := c.Delete().Where(blocklist.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &BlocklistDeleteOne{builder}
}
// Query returns a query builder for Blocklist.
func (c *BlocklistClient) Query() *BlocklistQuery {
return &BlocklistQuery{
config: c.config,
ctx: &QueryContext{Type: TypeBlocklist},
inters: c.Interceptors(),
}
}
// Get returns a Blocklist entity by its id.
func (c *BlocklistClient) Get(ctx context.Context, id int) (*Blocklist, error) {
return c.Query().Where(blocklist.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *BlocklistClient) GetX(ctx context.Context, id int) *Blocklist {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *BlocklistClient) Hooks() []Hook {
return c.hooks.Blocklist
}
// Interceptors returns the client interceptors.
func (c *BlocklistClient) Interceptors() []Interceptor {
return c.inters.Blocklist
}
func (c *BlocklistClient) mutate(ctx context.Context, m *BlocklistMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&BlocklistCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&BlocklistUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&BlocklistUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&BlocklistDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Blocklist mutation op: %q", m.Op())
}
}
// DownloadClientsClient is a client for the DownloadClients schema.
type DownloadClientsClient struct {
config
@@ -1504,11 +1645,11 @@ func (c *StorageClient) mutate(ctx context.Context, m *StorageMutation) (Value,
// hooks and interceptors per client, for fast access.
type (
hooks struct {
DownloadClients, Episode, History, ImportList, Indexers, Media,
Blocklist, DownloadClients, Episode, History, ImportList, Indexers, Media,
NotificationClient, Settings, Storage []ent.Hook
}
inters struct {
DownloadClients, Episode, History, ImportList, Indexers, Media,
Blocklist, DownloadClients, Episode, History, ImportList, Indexers, Media,
NotificationClient, Settings, Storage []ent.Interceptor
}
)

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

@@ -6,6 +6,7 @@ import (
"context"
"errors"
"fmt"
"polaris/ent/blocklist"
"polaris/ent/downloadclients"
"polaris/ent/episode"
"polaris/ent/history"
@@ -81,6 +82,7 @@ var (
func checkColumn(table, column string) error {
initCheck.Do(func() {
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
blocklist.Table: blocklist.ValidColumn,
downloadclients.Table: downloadclients.ValidColumn,
episode.Table: episode.ValidColumn,
history.Table: history.ValidColumn,

View File

@@ -8,6 +8,18 @@ import (
"polaris/ent"
)
// The BlocklistFunc type is an adapter to allow the use of ordinary
// function as Blocklist mutator.
type BlocklistFunc func(context.Context, *ent.BlocklistMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f BlocklistFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.BlocklistMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.BlocklistMutation", m)
}
// The DownloadClientsFunc type is an adapter to allow the use of ordinary
// function as DownloadClients mutator.
type DownloadClientsFunc func(context.Context, *ent.DownloadClientsMutation) (ent.Value, error)

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

@@ -8,17 +8,29 @@ import (
)
var (
// BlocklistsColumns holds the columns for the "blocklists" table.
BlocklistsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "type", Type: field.TypeEnum, Enums: []string{"media", "torrent"}},
{Name: "value", Type: field.TypeString},
}
// BlocklistsTable holds the schema information for the "blocklists" table.
BlocklistsTable = &schema.Table{
Name: "blocklists",
Columns: BlocklistsColumns,
PrimaryKey: []*schema.Column{BlocklistsColumns[0]},
}
// DownloadClientsColumns holds the columns for the "download_clients" table.
DownloadClientsColumns = []*schema.Column{
{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: ""},
@@ -121,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},
@@ -179,6 +191,7 @@ var (
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
BlocklistsTable,
DownloadClientsTable,
EpisodesTable,
HistoriesTable,

View File

@@ -6,6 +6,7 @@ import (
"context"
"errors"
"fmt"
"polaris/ent/blocklist"
"polaris/ent/downloadclients"
"polaris/ent/episode"
"polaris/ent/history"
@@ -33,6 +34,7 @@ const (
OpUpdateOne = ent.OpUpdateOne
// Node types.
TypeBlocklist = "Blocklist"
TypeDownloadClients = "DownloadClients"
TypeEpisode = "Episode"
TypeHistory = "History"
@@ -44,6 +46,386 @@ const (
TypeStorage = "Storage"
)
// BlocklistMutation represents an operation that mutates the Blocklist nodes in the graph.
type BlocklistMutation struct {
config
op Op
typ string
id *int
_type *blocklist.Type
value *string
clearedFields map[string]struct{}
done bool
oldValue func(context.Context) (*Blocklist, error)
predicates []predicate.Blocklist
}
var _ ent.Mutation = (*BlocklistMutation)(nil)
// blocklistOption allows management of the mutation configuration using functional options.
type blocklistOption func(*BlocklistMutation)
// newBlocklistMutation creates new mutation for the Blocklist entity.
func newBlocklistMutation(c config, op Op, opts ...blocklistOption) *BlocklistMutation {
m := &BlocklistMutation{
config: c,
op: op,
typ: TypeBlocklist,
clearedFields: make(map[string]struct{}),
}
for _, opt := range opts {
opt(m)
}
return m
}
// withBlocklistID sets the ID field of the mutation.
func withBlocklistID(id int) blocklistOption {
return func(m *BlocklistMutation) {
var (
err error
once sync.Once
value *Blocklist
)
m.oldValue = func(ctx context.Context) (*Blocklist, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Blocklist.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withBlocklist sets the old Blocklist of the mutation.
func withBlocklist(node *Blocklist) blocklistOption {
return func(m *BlocklistMutation) {
m.oldValue = func(context.Context) (*Blocklist, error) {
return node, nil
}
m.id = &node.ID
}
}
// Client returns a new `ent.Client` from the mutation. If the mutation was
// executed in a transaction (ent.Tx), a transactional client is returned.
func (m BlocklistMutation) Client() *Client {
client := &Client{config: m.config}
client.init()
return client
}
// Tx returns an `ent.Tx` for mutations that were executed in transactions;
// it returns an error otherwise.
func (m BlocklistMutation) Tx() (*Tx, error) {
if _, ok := m.driver.(*txDriver); !ok {
return nil, errors.New("ent: mutation is not running in a transaction")
}
tx := &Tx{config: m.config}
tx.init()
return tx, nil
}
// ID returns the ID value in the mutation. Note that the ID is only available
// if it was provided to the builder or after it was returned from the database.
func (m *BlocklistMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// IDs queries the database and returns the entity ids that match the mutation's predicate.
// That means, if the mutation is applied within a transaction with an isolation level such
// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
// or updated by the mutation.
func (m *BlocklistMutation) IDs(ctx context.Context) ([]int, error) {
switch {
case m.op.Is(OpUpdateOne | OpDeleteOne):
id, exists := m.ID()
if exists {
return []int{id}, nil
}
fallthrough
case m.op.Is(OpUpdate | OpDelete):
return m.Client().Blocklist.Query().Where(m.predicates...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
}
}
// SetType sets the "type" field.
func (m *BlocklistMutation) SetType(b blocklist.Type) {
m._type = &b
}
// GetType returns the value of the "type" field in the mutation.
func (m *BlocklistMutation) GetType() (r blocklist.Type, exists bool) {
v := m._type
if v == nil {
return
}
return *v, true
}
// OldType returns the old "type" field's value of the Blocklist entity.
// If the Blocklist 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 *BlocklistMutation) OldType(ctx context.Context) (v blocklist.Type, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldType is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldType requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldType: %w", err)
}
return oldValue.Type, nil
}
// ResetType resets all changes to the "type" field.
func (m *BlocklistMutation) ResetType() {
m._type = nil
}
// SetValue sets the "value" field.
func (m *BlocklistMutation) SetValue(s string) {
m.value = &s
}
// Value returns the value of the "value" field in the mutation.
func (m *BlocklistMutation) Value() (r string, exists bool) {
v := m.value
if v == nil {
return
}
return *v, true
}
// OldValue returns the old "value" field's value of the Blocklist entity.
// If the Blocklist 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 *BlocklistMutation) OldValue(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldValue is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldValue requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldValue: %w", err)
}
return oldValue.Value, nil
}
// ResetValue resets all changes to the "value" field.
func (m *BlocklistMutation) ResetValue() {
m.value = nil
}
// Where appends a list predicates to the BlocklistMutation builder.
func (m *BlocklistMutation) Where(ps ...predicate.Blocklist) {
m.predicates = append(m.predicates, ps...)
}
// WhereP appends storage-level predicates to the BlocklistMutation builder. Using this method,
// users can use type-assertion to append predicates that do not depend on any generated package.
func (m *BlocklistMutation) WhereP(ps ...func(*sql.Selector)) {
p := make([]predicate.Blocklist, len(ps))
for i := range ps {
p[i] = ps[i]
}
m.Where(p...)
}
// Op returns the operation name.
func (m *BlocklistMutation) Op() Op {
return m.op
}
// SetOp allows setting the mutation operation.
func (m *BlocklistMutation) SetOp(op Op) {
m.op = op
}
// Type returns the node type of this mutation (Blocklist).
func (m *BlocklistMutation) Type() string {
return m.typ
}
// Fields returns all fields that were changed during this mutation. Note that in
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *BlocklistMutation) Fields() []string {
fields := make([]string, 0, 2)
if m._type != nil {
fields = append(fields, blocklist.FieldType)
}
if m.value != nil {
fields = append(fields, blocklist.FieldValue)
}
return fields
}
// Field returns the value of 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 *BlocklistMutation) Field(name string) (ent.Value, bool) {
switch name {
case blocklist.FieldType:
return m.GetType()
case blocklist.FieldValue:
return m.Value()
}
return nil, false
}
// OldField returns the old value of the field from the database. An error is
// returned if the mutation operation is not UpdateOne, or the query to the
// database failed.
func (m *BlocklistMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case blocklist.FieldType:
return m.OldType(ctx)
case blocklist.FieldValue:
return m.OldValue(ctx)
}
return nil, fmt.Errorf("unknown Blocklist field %s", name)
}
// SetField sets the value of a field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *BlocklistMutation) SetField(name string, value ent.Value) error {
switch name {
case blocklist.FieldType:
v, ok := value.(blocklist.Type)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetType(v)
return nil
case blocklist.FieldValue:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetValue(v)
return nil
}
return fmt.Errorf("unknown Blocklist field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *BlocklistMutation) AddedFields() []string {
return nil
}
// 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 *BlocklistMutation) AddedField(name string) (ent.Value, bool) {
return nil, false
}
// AddField adds the value to the field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *BlocklistMutation) AddField(name string, value ent.Value) error {
switch name {
}
return fmt.Errorf("unknown Blocklist numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *BlocklistMutation) ClearedFields() []string {
return nil
}
// FieldCleared returns a boolean indicating if a field with the given name was
// cleared in this mutation.
func (m *BlocklistMutation) FieldCleared(name string) bool {
_, ok := m.clearedFields[name]
return ok
}
// ClearField clears the value of the field with the given name. It returns an
// error if the field is not defined in the schema.
func (m *BlocklistMutation) ClearField(name string) error {
return fmt.Errorf("unknown Blocklist nullable field %s", name)
}
// ResetField resets all changes in the mutation for the field with the given name.
// It returns an error if the field is not defined in the schema.
func (m *BlocklistMutation) ResetField(name string) error {
switch name {
case blocklist.FieldType:
m.ResetType()
return nil
case blocklist.FieldValue:
m.ResetValue()
return nil
}
return fmt.Errorf("unknown Blocklist field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *BlocklistMutation) AddedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
// name in this mutation.
func (m *BlocklistMutation) AddedIDs(name string) []ent.Value {
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *BlocklistMutation) RemovedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
// the given name in this mutation.
func (m *BlocklistMutation) RemovedIDs(name string) []ent.Value {
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *BlocklistMutation) ClearedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// EdgeCleared returns a boolean which indicates if the edge with the given name
// was cleared in this mutation.
func (m *BlocklistMutation) EdgeCleared(name string) bool {
return false
}
// ClearEdge clears the value of the edge with the given name. It returns an error
// if that edge is not defined in the schema.
func (m *BlocklistMutation) ClearEdge(name string) error {
return fmt.Errorf("unknown Blocklist unique edge %s", name)
}
// ResetEdge resets all changes to the edge with the given name in this mutation.
// It returns an error if the edge is not defined in the schema.
func (m *BlocklistMutation) ResetEdge(name string) error {
return fmt.Errorf("unknown Blocklist edge %s", name)
}
// DownloadClientsMutation represents an operation that mutates the DownloadClients nodes in the graph.
type DownloadClientsMutation struct {
config
@@ -52,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
@@ -238,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
@@ -254,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")
}
@@ -417,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.
@@ -617,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)
@@ -651,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:
@@ -682,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:
@@ -714,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)
}
@@ -748,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)
@@ -783,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
}
@@ -798,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)
}
@@ -846,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

@@ -6,6 +6,9 @@ import (
"entgo.io/ent/dialect/sql"
)
// Blocklist is the predicate function for blocklist builders.
type Blocklist func(*sql.Selector)
// DownloadClients is the predicate function for downloadclients builders.
type DownloadClients func(*sql.Selector)

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.

24
ent/schema/blocklist.go Normal file
View File

@@ -0,0 +1,24 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/field"
)
// Blocklist holds the schema definition for the Blocklist entity.
type Blocklist struct {
ent.Schema
}
// Fields of the Blocklist.
func (Blocklist) Fields() []ent.Field {
return []ent.Field{
field.Enum("type").Values("media", "torrent"),
field.String("value"),
}
}
// Edges of the Blocklist.
func (Blocklist) Edges() []ent.Edge {
return nil
}

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"),

View File

@@ -12,6 +12,8 @@ import (
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Blocklist is the client for interacting with the Blocklist builders.
Blocklist *BlocklistClient
// DownloadClients is the client for interacting with the DownloadClients builders.
DownloadClients *DownloadClientsClient
// Episode is the client for interacting with the Episode builders.
@@ -161,6 +163,7 @@ func (tx *Tx) Client() *Client {
}
func (tx *Tx) init() {
tx.Blocklist = NewBlocklistClient(tx.config)
tx.DownloadClients = NewDownloadClientsClient(tx.config)
tx.Episode = NewEpisodeClient(tx.config)
tx.History = NewHistoryClient(tx.config)
@@ -179,7 +182,7 @@ func (tx *Tx) init() {
// of them in order to commit or rollback the transaction.
//
// If a closed transaction is embedded in one of the generated entities, and the entity
// applies a query, for example: DownloadClients.QueryXXX(), the query will be executed
// applies a query, for example: Blocklist.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.

19
go.mod
View File

@@ -5,30 +5,35 @@ go 1.22.4
require (
entgo.io/ent v0.13.1
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/mattn/go-sqlite3 v1.14.16
github.com/mattn/go-sqlite3 v1.14.22 // indirect
github.com/robfig/cron v1.2.0
go.uber.org/zap v1.27.0
golang.org/x/net v0.27.0
)
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
github.com/stretchr/testify v1.9.0
)
require (
github.com/BurntSushi/toml v1.4.0 // indirect
github.com/PuerkitoBio/goquery v1.9.2 // indirect
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
github.com/ncruces/julianday v1.0.0 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/stretchr/objx v0.5.2 // indirect
github.com/technoweenie/multipartstreamer v1.0.1 // indirect
golang.org/x/sync v0.7.0 // indirect
github.com/tetratelabs/wazero v1.8.0 // indirect
golang.org/x/sync v0.8.0 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
@@ -75,11 +80,11 @@ require (
github.com/ugorji/go/codec v1.2.12 // indirect
github.com/zclconf/go-cty v1.8.0 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.25.0
golang.org/x/crypto v0.27.0
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56
golang.org/x/mod v0.19.0 // indirect
golang.org/x/sys v0.22.0
golang.org/x/text v0.16.0 // indirect
golang.org/x/sys v0.25.0
golang.org/x/text v0.18.0 // indirect
google.golang.org/protobuf v1.34.2 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect

43
go.sum
View File

@@ -4,8 +4,8 @@ entgo.io/ent v0.13.1 h1:uD8QwN1h6SNphdCCzmkMN3feSUzNnVvV/WIkHKMbzOE=
entgo.io/ent v0.13.1/go.mod h1:qCEmo+biw3ccBn9OyL4ZK5dfpwg++l1Gxwac5B1206A=
github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0=
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60=
github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
github.com/PuerkitoBio/goquery v1.9.2 h1:4/wZksC3KgkQw7SQgkKotmKljk0M6V8TUvA8Wb4yPeE=
github.com/PuerkitoBio/goquery v1.9.2/go.mod h1:GHPCaP0ODyyxqcNoFGYlAprUFH81NuRPd0GX3Zu2Mvk=
github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8=
@@ -56,8 +56,8 @@ github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBEx
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible h1:2cauKuaELYAEARXRkq2LrJ0yDDv1rW7+wrTEdVL3uaU=
github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible/go.mod h1:qf9acutJ8cwBUhm1bqgz6Bei9/C/c93FPDljKWwsOgM=
github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68=
github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
github.com/go-test/deep v1.0.4 h1:u2CU3YKy9I2pmu9pX0eq50wCgjfGIt539SqR7FbHiho=
github.com/go-test/deep v1.0.4/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
@@ -86,6 +86,7 @@ github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible
github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible/go.mod h1:1c7szIrayyPPB/987hsnvNzLushdWf4o/79s3P08L8A=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
@@ -105,10 +106,8 @@ github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0V
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y=
github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 h1:DpOJ2HYzCv8LZP15IdmG+YdwD2luVPHITV96TkirNBM=
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
@@ -120,10 +119,12 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/natefinch/lumberjack v2.0.0+incompatible h1:4QJd3OLAMgj7ph+yZTuX13Ld4UpgHp07nNdFX7mqFfM=
github.com/natefinch/lumberjack v2.0.0+incompatible/go.mod h1:Wi9p2TTF5DG5oU+6YfsmYQpsTIOm0B1VNzQg9Mw6nPk=
github.com/ncruces/go-sqlite3 v0.18.4 h1:Je8o3y33MDwPYY/Cacas8yCsuoUzpNY/AgoSlN2ekyE=
github.com/ncruces/go-sqlite3 v0.18.4/go.mod h1:4HLag13gq1k10s4dfGBhMfRVsssJRT9/5hYqVM9RUYo=
github.com/ncruces/julianday v1.0.0 h1:fH0OKwa7NWvniGQtxdJRxAgkBMolni2BjDHaWTxqt7M=
github.com/ncruces/julianday v1.0.0/go.mod h1:Dusn2KvZrrovOMJuOt0TNXL6tB7U2E8kvza5fFc9G7g=
github.com/nikoksr/notify v1.0.0 h1:qe9/6FRsWdxBgQgWcpvQ0sv8LRGJZDpRB4TkL2uNdO8=
github.com/nikoksr/notify v1.0.0/go.mod h1:hPaaDt30d6LAA7/5nb0e48Bp/MctDfycCSs8VEgN29I=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
@@ -147,8 +148,6 @@ github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI=
@@ -170,6 +169,8 @@ github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/technoweenie/multipartstreamer v1.0.1 h1:XRztA5MXiR1TIRHxH2uNxXxaIkKQDeX7m2XsSOlQEnM=
github.com/technoweenie/multipartstreamer v1.0.1/go.mod h1:jNVxdtShOxzAsukZwTSw6MDx5eUJoiEBsSvzDU9uzog=
github.com/tetratelabs/wazero v1.8.0 h1:iEKu0d4c2Pd+QSRieYbnQC9yiFlMS9D+Jr0LsRmcF4g=
github.com/tetratelabs/wazero v1.8.0/go.mod h1:yAI0XTsMBhREkM/YDAK/zNou3GoiAce1P6+rp/wQhjs=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
@@ -190,8 +191,8 @@ golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.25.0 h1:ypSNr+bnYL2YhwoMt2zPxHFmbAN1KZs/njMG3hxUp30=
golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/M=
golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A=
golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70=
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0LeHDbnYEryqj5Q1ug8=
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
@@ -210,8 +211,8 @@ golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -220,8 +221,8 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
@@ -233,14 +234,12 @@ golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224=
golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg=
golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=

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
}

25
pkg/utils/linux.go Normal file
View File

@@ -0,0 +1,25 @@
//go:build linux
// +build linux
package utils
import (
"golang.org/x/sys/unix"
"math"
"runtime"
"syscall"
)
func AvailableSpace(dir string) uint64 {
if runtime.GOOS != "linux" {
return math.MaxUint64
}
var stat unix.Statfs_t
unix.Statfs(dir, &stat)
return stat.Bavail * uint64(stat.Bsize)
}
func MaxPermission() {
syscall.Umask(0) //max permission 0777
}

16
pkg/utils/other.go Normal file
View File

@@ -0,0 +1,16 @@
//go:build !linux
// +build !linux
package utils
import (
"math"
)
func AvailableSpace(dir string) uint64 {
return math.MaxUint64
}
func MaxPermission() {
return
}

View File

@@ -3,7 +3,9 @@ package utils
import (
"encoding/json"
"os"
"os/exec"
"regexp"
"runtime"
"strconv"
"strings"
"unicode"
@@ -11,7 +13,6 @@ import (
"github.com/pkg/errors"
"golang.org/x/crypto/bcrypt"
"golang.org/x/exp/rand"
"golang.org/x/sys/unix"
)
func IsASCII(s string) bool {
@@ -55,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+`)
@@ -129,13 +130,6 @@ func SeasonId(seasonName string) (int, error) {
return num, nil
}
func AvailableSpace(dir string) uint64 {
var stat unix.Statfs_t
unix.Statfs(dir, &stat)
return stat.Bavail * uint64(stat.Bsize)
}
func ChangeFileHash(name string) error {
f, err := os.OpenFile(name, os.O_APPEND|os.O_WRONLY, 0655)
if err != nil {
@@ -183,3 +177,44 @@ func trimMapStringInterface(data interface{}) interface{} {
}
return data
}
// https://stackoverflow.com/questions/39320371/how-start-web-server-to-open-page-in-browser-in-golang
// openURL opens the specified URL in the default browser of the user.
func OpenURL(url string) error {
var cmd string
var args []string
switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start"}
case "darwin":
cmd = "open"
args = []string{url}
default: // "linux", "freebsd", "openbsd", "netbsd"
// Check if running under WSL
if isWSL() {
// Use 'cmd.exe /c start' to open the URL in the default Windows browser
cmd = "cmd.exe"
args = []string{"/c", "start", url}
} else {
// Use xdg-open on native Linux environments
cmd = "xdg-open"
args = []string{url}
}
}
if len(args) > 1 {
// args[0] is used for 'start' command argument, to prevent issues with URLs starting with a quote
args = append(args[:1], append([]string{""}, args[1:]...)...)
}
return exec.Command(cmd, args...).Start()
}
// isWSL checks if the Go program is running inside Windows Subsystem for Linux
func isWSL() bool {
releaseData, err := exec.Command("uname", "-r").Output()
if err != nil {
return false
}
return strings.Contains(strings.ToLower(string(releaseData)), "microsoft")
}

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")),