Compare commits

...

35 Commits

Author SHA1 Message Date
Simon Ding
93e8e78591 ui: improve external link display 2024-08-10 17:55:56 +08:00
Simon Ding
9ff12cd86b fix: movie year match 2024-08-10 17:06:33 +08:00
Simon Ding
fd2f4b140f refactor: download api 2024-08-10 16:46:49 +08:00
Simon Ding
4607af6982 feat: search original name 2024-08-10 16:46:19 +08:00
Simon Ding
984bebcfe0 ui: fine tune 2024-08-10 15:23:08 +08:00
Simon Ding
d31abd59ad chore: ui improvement 2024-08-10 15:05:18 +08:00
Simon Ding
e0ad71291c fix width 2024-08-10 11:23:17 +08:00
Simon Ding
8ecc9393cf fix: width 126->120 2024-08-10 11:16:17 +08:00
Simon Ding
b62e0e9bfd feat: small screen 2024-08-10 11:06:29 +08:00
Simon Ding
1391f55f44 feat: small screen 2024-08-10 10:52:48 +08:00
Simon Ding
0c709ee517 feat: detail card fit small screen 2024-08-10 10:45:18 +08:00
Simon Ding
806d821388 feat: better support for small screen 2024-08-10 10:35:57 +08:00
Simon Ding
829043bf28 fix: naming suggestion 2024-08-09 20:40:38 +08:00
Simon Ding
66ab418054 feat: remove name extras characters 2024-08-09 19:47:58 +08:00
Simon Ding
5fe40cc64b feat: add size to activity 2024-08-09 19:00:40 +08:00
Simon Ding
8f6f26f00e refactor: activity list 2024-08-08 19:23:23 +08:00
Simon Ding
ee0bee2b06 fix: formatting 2024-08-08 14:20:20 +08:00
Simon Ding
1bb16a8a66 feat: imdbid support 2024-08-08 14:10:26 +08:00
Simon Ding
d746032114 fix: result ordering 2024-08-08 13:40:07 +08:00
Simon Ding
b34e39889c feat: ui improvement 2024-08-08 10:56:03 +08:00
Simon Ding
64e98647a8 update go.mod 2024-08-08 00:56:49 +08:00
Simon Ding
f91c91e0b1 chore: main page ui update 2024-08-07 23:36:41 +08:00
Simon Ding
f1aaa06d05 chore: update new flutter version 2024-08-07 23:13:36 +08:00
Simon Ding
e8a38aa6f8 chore: ui update 2024-08-07 22:55:24 +08:00
Simon Ding
7e88533ea2 chore: update storage display 2024-08-07 14:12:47 +08:00
Simon Ding
05698f4047 fix: size limiter 2024-08-07 13:37:39 +08:00
Simon Ding
1daad0c236 fix size limiter 2024-08-07 13:27:41 +08:00
Simon Ding
86c8163f9c feat: default select first storage 2024-08-07 13:22:55 +08:00
Simon Ding
78ab8cc8e6 feat: add size display 2024-08-07 13:06:37 +08:00
Simon Ding
1390277b43 feat: second confirmation on deletion 2024-08-07 12:48:15 +08:00
Simon Ding
1aa3dca2c6 update 2024-08-07 11:20:21 +08:00
Simon Ding
f48b3c657e feat: change cache implementation 2024-08-07 11:07:10 +08:00
Simon Ding
d8d570f1b2 feat: change db 2024-08-07 10:46:30 +08:00
Simon Ding
bd385d4f85 feat: add simple cache, due to jackett poor performance 2024-08-07 10:42:12 +08:00
Simon Ding
466596345d feat: edit media details 2024-08-06 23:00:56 +08:00
41 changed files with 1016 additions and 541 deletions

View File

@@ -11,6 +11,7 @@ import (
"polaris/ent/history"
"polaris/ent/indexers"
"polaris/ent/media"
"polaris/ent/schema"
"polaris/ent/settings"
"polaris/ent/storage"
"polaris/log"
@@ -87,8 +88,8 @@ func (c *Client) generateDefaultLocalStorage() error {
return c.AddStorage(&StorageInfo{
Name: "local",
Implementation: "local",
TvPath: "/data/tv/",
MoviePath: "/data/movies/",
TvPath: "/data/tv/",
MoviePath: "/data/movies/",
Default: true,
})
}
@@ -137,6 +138,7 @@ func (c *Client) AddMediaWatchlist(m *ent.Media, episodes []int) (*ent.Media, er
}
r, err := c.ent.Media.Create().
SetTmdbID(m.TmdbID).
SetImdbID(m.ImdbID).
SetStorageID(m.StorageID).
SetOverview(m.Overview).
SetNameCn(m.NameCn).
@@ -249,7 +251,6 @@ type TorznabSetting struct {
ApiKey string `json:"api_key"`
}
func (c *Client) SaveIndexer(in *ent.Indexers) error {
if in.ID != 0 {
@@ -265,7 +266,7 @@ func (c *Client) SaveIndexer(in *ent.Indexers) error {
_, err := c.ent.Indexers.Create().
SetName(in.Name).SetImplementation(in.Implementation).SetPriority(in.Priority).SetSettings(in.Settings).SetSeedRatio(in.SeedRatio).
SetDisabled(in.Disabled).Save(context.TODO())
SetDisabled(in.Disabled).Save(context.TODO())
if err != nil {
return errors.Wrap(err, "save db")
}
@@ -285,11 +286,12 @@ func (c *Client) GetIndexer(id int) (*TorznabInfo, error) {
var ss TorznabSetting
err = json.Unmarshal([]byte(res.Settings), &ss)
if err != nil {
return nil, fmt.Errorf("unmarshal torznab %s error: %v", res.Name, err)
}
return &TorznabInfo{Indexers: res, TorznabSetting: ss}, nil
}
type TorznabInfo struct {
*ent.Indexers
TorznabSetting
@@ -307,7 +309,7 @@ func (c *Client) GetAllTorznabInfo() []*TorznabInfo {
continue
}
l = append(l, &TorznabInfo{
Indexers: r,
Indexers: r,
TorznabSetting: ss,
})
}
@@ -356,7 +358,7 @@ type StorageInfo struct {
Settings map[string]string `json:"settings" binding:"required"`
TvPath string `json:"tv_path" binding:"required"`
MoviePath string `json:"movie_path" binding:"required"`
Default bool `json:"default"`
Default bool `json:"default"`
}
func (s *StorageInfo) ToWebDavSetting() WebdavSetting {
@@ -371,7 +373,6 @@ func (s *StorageInfo) ToWebDavSetting() WebdavSetting {
}
}
type WebdavSetting struct {
URL string `json:"url"`
User string `json:"user"`
@@ -472,8 +473,8 @@ func (c *Client) SetDefaultStorageByName(name string) error {
func (c *Client) SaveHistoryRecord(h ent.History) (*ent.History, error) {
return c.ent.History.Create().SetMediaID(h.MediaID).SetEpisodeID(h.EpisodeID).SetDate(time.Now()).
SetStatus(h.Status).SetTargetDir(h.TargetDir).SetSourceTitle(h.SourceTitle).SetIndexerID(h.IndexerID).
SetDownloadClientID(h.DownloadClientID).SetSaved(h.Saved).Save(context.TODO())
SetStatus(h.Status).SetTargetDir(h.TargetDir).SetSourceTitle(h.SourceTitle).SetIndexerID(h.IndexerID).
SetDownloadClientID(h.DownloadClientID).SetSize(h.Size).SetSaved(h.Saved).Save(context.TODO())
}
func (c *Client) SetHistoryStatus(id int, status history.Status) error {
@@ -555,7 +556,18 @@ func (c *Client) GetDownloadClient(id int) (*ent.DownloadClients, error) {
return c.ent.DownloadClients.Query().Where(downloadclients.ID(id)).First(context.Background())
}
func (c *Client) SetEpisodeMonitoring(id int, b bool) error {
return c.ent.Episode.Update().Where(episode.ID(id)).SetMonitored(b).Exec(context.Background())
}
}
type EditMediaData struct {
ID int `json:"id"`
Resolution media.Resolution `json:"resolution"`
TargetDir string `json:"target_dir"`
Limiter schema.MediaLimiter `json:"limiter"`
}
func (c *Client) EditMediaMetadata(in EditMediaData) error {
return c.ent.Media.Update().Where(media.ID(in.ID)).SetResolution(in.Resolution).SetTargetDir(in.TargetDir).SetLimiter(in.Limiter).
Exec(context.Background())
}

View File

@@ -46,7 +46,7 @@ type Media struct {
// tv series only
DownloadHistoryEpisodes bool `json:"download_history_episodes,omitempty"`
// Limiter holds the value of the "limiter" field.
Limiter *schema.MediaLimiter `json:"limiter,omitempty"`
Limiter schema.MediaLimiter `json:"limiter,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the MediaQuery when eager-loading is set.
Edges MediaEdges `json:"edges"`

View File

@@ -157,11 +157,19 @@ func (mc *MediaCreate) SetNillableDownloadHistoryEpisodes(b *bool) *MediaCreate
}
// SetLimiter sets the "limiter" field.
func (mc *MediaCreate) SetLimiter(sl *schema.MediaLimiter) *MediaCreate {
func (mc *MediaCreate) SetLimiter(sl schema.MediaLimiter) *MediaCreate {
mc.mutation.SetLimiter(sl)
return mc
}
// SetNillableLimiter sets the "limiter" field if the given value is not nil.
func (mc *MediaCreate) SetNillableLimiter(sl *schema.MediaLimiter) *MediaCreate {
if sl != nil {
mc.SetLimiter(*sl)
}
return mc
}
// AddEpisodeIDs adds the "episodes" edge to the Episode entity by IDs.
func (mc *MediaCreate) AddEpisodeIDs(ids ...int) *MediaCreate {
mc.mutation.AddEpisodeIDs(ids...)

View File

@@ -251,11 +251,19 @@ func (mu *MediaUpdate) ClearDownloadHistoryEpisodes() *MediaUpdate {
}
// SetLimiter sets the "limiter" field.
func (mu *MediaUpdate) SetLimiter(sl *schema.MediaLimiter) *MediaUpdate {
func (mu *MediaUpdate) SetLimiter(sl schema.MediaLimiter) *MediaUpdate {
mu.mutation.SetLimiter(sl)
return mu
}
// SetNillableLimiter sets the "limiter" field if the given value is not nil.
func (mu *MediaUpdate) SetNillableLimiter(sl *schema.MediaLimiter) *MediaUpdate {
if sl != nil {
mu.SetLimiter(*sl)
}
return mu
}
// ClearLimiter clears the value of the "limiter" field.
func (mu *MediaUpdate) ClearLimiter() *MediaUpdate {
mu.mutation.ClearLimiter()
@@ -706,11 +714,19 @@ func (muo *MediaUpdateOne) ClearDownloadHistoryEpisodes() *MediaUpdateOne {
}
// SetLimiter sets the "limiter" field.
func (muo *MediaUpdateOne) SetLimiter(sl *schema.MediaLimiter) *MediaUpdateOne {
func (muo *MediaUpdateOne) SetLimiter(sl schema.MediaLimiter) *MediaUpdateOne {
muo.mutation.SetLimiter(sl)
return muo
}
// SetNillableLimiter sets the "limiter" field if the given value is not nil.
func (muo *MediaUpdateOne) SetNillableLimiter(sl *schema.MediaLimiter) *MediaUpdateOne {
if sl != nil {
muo.SetLimiter(*sl)
}
return muo
}
// ClearLimiter clears the value of the "limiter" field.
func (muo *MediaUpdateOne) ClearLimiter() *MediaUpdateOne {
muo.mutation.ClearLimiter()

View File

@@ -3601,7 +3601,7 @@ type MediaMutation struct {
addstorage_id *int
target_dir *string
download_history_episodes *bool
limiter **schema.MediaLimiter
limiter *schema.MediaLimiter
clearedFields map[string]struct{}
episodes map[int]struct{}
removedepisodes map[int]struct{}
@@ -4271,12 +4271,12 @@ func (m *MediaMutation) ResetDownloadHistoryEpisodes() {
}
// SetLimiter sets the "limiter" field.
func (m *MediaMutation) SetLimiter(sl *schema.MediaLimiter) {
func (m *MediaMutation) SetLimiter(sl schema.MediaLimiter) {
m.limiter = &sl
}
// Limiter returns the value of the "limiter" field in the mutation.
func (m *MediaMutation) Limiter() (r *schema.MediaLimiter, exists bool) {
func (m *MediaMutation) Limiter() (r schema.MediaLimiter, exists bool) {
v := m.limiter
if v == nil {
return
@@ -4287,7 +4287,7 @@ func (m *MediaMutation) Limiter() (r *schema.MediaLimiter, exists bool) {
// OldLimiter returns the old "limiter" field's value of the Media entity.
// If the Media 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 *MediaMutation) OldLimiter(ctx context.Context) (v *schema.MediaLimiter, err error) {
func (m *MediaMutation) OldLimiter(ctx context.Context) (v schema.MediaLimiter, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldLimiter is only allowed on UpdateOne operations")
}
@@ -4624,7 +4624,7 @@ func (m *MediaMutation) SetField(name string, value ent.Value) error {
m.SetDownloadHistoryEpisodes(v)
return nil
case media.FieldLimiter:
v, ok := value.(*schema.MediaLimiter)
v, ok := value.(schema.MediaLimiter)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}

View File

@@ -29,7 +29,7 @@ func (Media) Fields() []ent.Field {
field.Int("storage_id").Optional(),
field.String("target_dir").Optional(),
field.Bool("download_history_episodes").Optional().Default(false).Comment("tv series only"),
field.JSON("limiter", &MediaLimiter{}).Optional(),
field.JSON("limiter", MediaLimiter{}).Optional(),
}
}
@@ -41,6 +41,6 @@ func (Media) Edges() []ent.Edge {
}
type MediaLimiter struct {
SizeMin int `json:"size_min"`
SizeMax int `json:"size_max"`
SizeMin int `json:"size_min"` //in B
SizeMax int `json:"size_max"` //in B
}

3
go.mod
View File

@@ -12,9 +12,9 @@ require (
)
require (
github.com/adrg/strutil v0.3.1
github.com/gin-contrib/zap v1.1.3
github.com/nikoksr/notify v1.0.0
github.com/stretchr/testify v1.9.0
)
require (
@@ -25,7 +25,6 @@ require (
github.com/gregdel/pushover v1.3.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/stretchr/objx v0.5.2 // indirect
github.com/stretchr/testify v1.9.0 // indirect
github.com/technoweenie/multipartstreamer v1.0.1 // indirect
golang.org/x/sync v0.7.0 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect

12
go.sum
View File

@@ -6,8 +6,6 @@ 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/adrg/strutil v0.3.1 h1:OLvSS7CSJO8lBii4YmBt8jiK9QOtB9CzCzwl4Ic/Fz4=
github.com/adrg/strutil v0.3.1/go.mod h1:8h90y18QLrs11IBffcGX3NW/GFBXCMcNg4M7H6MspPA=
github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8=
github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw=
@@ -80,6 +78,8 @@ github.com/hekmon/cunits/v2 v2.1.0 h1:k6wIjc4PlacNOHwKEMBgWV2/c8jyD4eRMs5mR1BBhI
github.com/hekmon/cunits/v2 v2.1.0/go.mod h1:9r1TycXYXaTmEWlAIfFV8JT+Xo59U96yUJAYHxzii2M=
github.com/hekmon/transmissionrpc/v3 v3.0.0 h1:0Fb11qE0IBh4V4GlOwHNYpqpjcYDp5GouolwrpmcUDQ=
github.com/hekmon/transmissionrpc/v3 v3.0.0/go.mod h1:38SlNhFzinVUuY87wGj3acOmRxeYZAZfrj6Re7UgCDg=
github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible h1:jdpOPRN1zP63Td1hDQbZW73xKmzDvZHzVdNYxhnTMDA=
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/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
@@ -101,8 +101,6 @@ 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/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 h1:DpOJ2HYzCv8LZP15IdmG+YdwD2luVPHITV96TkirNBM=
@@ -118,8 +116,6 @@ github.com/natefinch/lumberjack v2.0.0+incompatible h1:4QJd3OLAMgj7ph+yZTuX13Ld4
github.com/natefinch/lumberjack v2.0.0+incompatible/go.mod h1:Wi9p2TTF5DG5oU+6YfsmYQpsTIOm0B1VNzQg9Mw6nPk=
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=
@@ -143,8 +139,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=
@@ -207,8 +201,6 @@ golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
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/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg=
golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=

View File

@@ -26,6 +26,7 @@ func init() {
MaxSize: 50, // megabytes
MaxBackups: 3,
MaxAge: 30, // days
Compress: true,
})
}

52
pkg/cache/cache.go vendored Normal file
View File

@@ -0,0 +1,52 @@
package cache
import (
"polaris/log"
"polaris/pkg/utils"
"time"
)
func NewCache[T comparable, S any](timeout time.Duration) *Cache[T, S] {
c := &Cache[T, S]{
m: utils.Map[T, inner[S]]{},
timeout: timeout,
}
return c
}
type Cache[T comparable, S any] struct {
m utils.Map[T, inner[S]]
timeout time.Duration
}
type inner[S any] struct {
t time.Time
s S
}
func (c *Cache[T, S]) Set(key T, value S) {
c.m.Store(key, inner[S]{t: time.Now(), s: value})
}
func (c *Cache[T, S]) Get(key T) (S, bool) {
c.m.Range(func(key T, value inner[S]) bool {
if time.Since(value.t) > c.timeout {
log.Debugf("delete old cache: %v", key)
c.m.Delete(key)
}
return true
})
v, ok := c.m.Load(key)
if !ok {
return getZero[S](), ok
}
return v.s, ok
}
func getZero[T any]() T {
var result T
return result
}

View File

@@ -8,8 +8,7 @@ import (
)
type MovieMetadata struct {
NameEn string
NameCN string
Name string
Year int
Resolution string
}
@@ -29,11 +28,22 @@ func ParseMovie(name string) *MovieMetadata {
panic(fmt.Sprintf("convert %s error: %v", y, err))
}
meta.Year = n
}
if yearIndex != -1 {
meta.NameEn = name[:yearIndex]
} else {
meta.NameEn = name
yearRe := regexp.MustCompile(`\d{4}`)
yearMatches := yearRe.FindAllString(name, -1)
if len(yearMatches) > 0 {
n, err := strconv.Atoi(yearMatches[0])
if err != nil {
panic(fmt.Sprintf("convert %s error: %v", yearMatches[0], err))
}
meta.Year = n
}
}
if yearIndex != -1 {
meta.Name = name[:yearIndex]
} else {
meta.Name = name
}
resRe := regexp.MustCompile(`\d{3,4}p`)
resMatches := resRe.FindAllString(name, -1)

View File

@@ -48,7 +48,7 @@ func NewClient(apiKey, proxyUrl string) (*Client, error) {
}
func (c *Client) GetTvDetails(id int, language string) (*tmdb.TVDetails, error) {
d, err := c.tmdbClient.GetTVDetails(id, withLangOption(language))
d, err := c.tmdbClient.GetTVDetails(id, withExternalIDs(withLangOption(language)))
if err != nil {
return nil, errors.Wrap(err, "get tv detail")
}
@@ -58,7 +58,7 @@ func (c *Client) GetTvDetails(id int, language string) (*tmdb.TVDetails, error)
log.Debug("should fetch english version")
var detailEN *tmdb.TVDetails
if language == "zh-CN" {
detailEN, err = c.tmdbClient.GetTVDetails(id, withLangOption("en-US"))
detailEN, err = c.tmdbClient.GetTVDetails(id, withExternalIDs(withLangOption("en-US")))
if err != nil {
return d, nil
}
@@ -75,7 +75,7 @@ func (c *Client) GetTvDetails(id int, language string) (*tmdb.TVDetails, error)
}
func (c *Client) GetMovieDetails(id int, language string) (*tmdb.MovieDetails, error) {
return c.tmdbClient.GetMovieDetails(id, withLangOption(language))
return c.tmdbClient.GetMovieDetails(id, withExternalIDs(withLangOption(language)))
}
func (c *Client) SearchTvShow(query string, lang string) (*tmdb.SearchTVShows, error) {
@@ -211,6 +211,11 @@ func wrapLanguage(lang string) string {
return lang
}
func withExternalIDs(m map[string]string) map[string]string {
m["append_to_response"] = "external_ids"
return m
}
func withLangOption(language string) map[string]string {
language = wrapLanguage(language)
return map[string]string{

8
pkg/torznab/cache.go Normal file
View File

@@ -0,0 +1,8 @@
package torznab
import (
"polaris/pkg/cache"
"time"
)
var cc = cache.NewCache[string, Response](time.Minute * 30)

View File

@@ -3,6 +3,7 @@ package torznab
import (
"context"
"encoding/xml"
"fmt"
"io"
"net/http"
"net/url"
@@ -112,7 +113,7 @@ func tryParseFloat(s string) float32 {
return float32(r)
}
func Search(indexer *db.TorznabInfo, api, keyWord string) ([]Result, error) {
func Search(indexer *db.TorznabInfo, keyWord string) ([]Result, error) {
ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second)
defer cancel()
@@ -121,26 +122,32 @@ func Search(indexer *db.TorznabInfo, api, keyWord string) ([]Result, error) {
return nil, errors.Wrap(err, "new request")
}
var q = url.Values{}
q.Add("apikey", api)
q.Add("apikey", indexer.ApiKey)
q.Add("t", "search")
q.Add("q", keyWord)
req.URL.RawQuery = q.Encode()
key := fmt.Sprintf("%s: %s", indexer.Name, keyWord)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, errors.Wrap(err, "do http")
cacheRes, ok := cc.Get(key)
if !ok {
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, errors.Wrap(err, "do http")
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "read http body")
}
var res Response
err = xml.Unmarshal(data, &res)
if err != nil {
return nil, errors.Wrap(err, "json unmarshal")
}
cacheRes = res
cc.Set(key, cacheRes)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "read http body")
}
var res Response
err = xml.Unmarshal(data, &res)
if err != nil {
return nil, errors.Wrap(err, "json unmarshal")
}
return res.ToResults(indexer), nil
return cacheRes.ToResults(indexer), nil
}
type Result struct {

View File

@@ -10,6 +10,7 @@ import (
"polaris/log"
"polaris/pkg/notifier"
"polaris/pkg/storage"
"strings"
"github.com/pkg/errors"
)
@@ -35,9 +36,13 @@ func (c *Client) writePlexmatch(seriesId int, episodeId int, targetDir, name str
_, err = st.ReadFile(filepath.Join(series.TargetDir, ".plexmatch"))
if err != nil {
//create new
buff := bytes.Buffer{}
if series.ImdbID != "" {
buff.WriteString(fmt.Sprintf("imdbid: %s\n", series.ImdbID))
}
buff.WriteString(fmt.Sprintf("tmdbid: %d\n", series.TmdbID))
log.Warnf(".plexmatch file not found, create new one: %s", series.NameEn)
if err := st.WriteFile(filepath.Join(series.TargetDir, ".plexmatch"),
[]byte(fmt.Sprintf("tmdbid: %d\n", series.TmdbID))); err != nil {
if err := st.WriteFile(filepath.Join(series.TargetDir, ".plexmatch"), buff.Bytes()); err != nil {
return errors.Wrap(err, "series plexmatch")
}
}
@@ -55,6 +60,10 @@ func (c *Client) writePlexmatch(seriesId int, episodeId int, targetDir, name str
} else {
buff.Write(data)
}
if strings.Contains(buff.String(), name) {
log.Debugf("already write plex episode line: %v", name)
return nil
}
buff.WriteString(fmt.Sprintf("\nep: %d: %s\n", ep.EpisodeNumber, name))
log.Infof("write season plexmatch file content: %s", buff.String())
return st.WriteFile(seasonPlex, buff.Bytes())

View File

@@ -13,54 +13,6 @@ import (
"github.com/pkg/errors"
)
func (c *Client) DownloadSeasonPackage(r1 torznab.Result, seriesId, seasonNum int) (*string, error) {
trc, dlClient, err := c.getDownloadClient()
if err != nil {
return nil, errors.Wrap(err, "connect transmission")
}
downloadDir := c.db.GetDownloadDir()
size := utils.AvailableSpace(downloadDir)
if size < uint64(r1.Size) {
log.Errorf("space available %v, space needed %v", size, r1.Size)
return nil, errors.New("no enough space")
}
torrent, err := trc.Download(r1.Link, c.db.GetDownloadDir())
if err != nil {
return nil, errors.Wrap(err, "downloading")
}
torrent.Start()
series := c.db.GetMediaDetails(seriesId)
if series == nil {
return nil, fmt.Errorf("no tv series of id %v", seriesId)
}
dir := fmt.Sprintf("%s/Season %02d/", series.TargetDir, seasonNum)
history, err := c.db.SaveHistoryRecord(ent.History{
MediaID: seriesId,
EpisodeID: 0,
SourceTitle: r1.Name,
TargetDir: dir,
Status: history.StatusRunning,
Size: r1.Size,
Saved: torrent.Save(),
DownloadClientID: dlClient.ID,
IndexerID: r1.IndexerId,
})
if err != nil {
return nil, errors.Wrap(err, "save record")
}
c.db.SetSeasonAllEpisodeStatus(seriesId, seasonNum, episode.StatusDownloading)
c.tasks[history.ID] = &Task{Torrent: torrent}
c.sendMsg(fmt.Sprintf(message.BeginDownload, r1.Name))
return &r1.Name, nil
}
func (c *Client) DownloadEpisodeTorrent(r1 torznab.Result, seriesId, seasonNum, episodeNum int) (*string, error) {
trc, dlc, err := c.getDownloadClient()
if err != nil {
@@ -70,16 +22,29 @@ func (c *Client) DownloadEpisodeTorrent(r1 torznab.Result, seriesId, seasonNum,
if series == nil {
return nil, fmt.Errorf("no tv series of id %v", seriesId)
}
//check space available
downloadDir := c.db.GetDownloadDir()
size := utils.AvailableSpace(downloadDir)
if size < uint64(r1.Size) {
log.Errorf("space available %v, space needed %v", size, r1.Size)
return nil, errors.New("no enough space")
}
var ep *ent.Episode
for _, e := range series.Episodes {
if e.SeasonNumber == seasonNum && e.EpisodeNumber == episodeNum {
ep = e
if episodeNum > 0 {
for _, e := range series.Episodes {
if e.SeasonNumber == seasonNum && e.EpisodeNumber == episodeNum {
ep = e
}
}
if ep == nil {
return nil, errors.Errorf("no episode of season %d episode %d", seasonNum, episodeNum)
}
} else { //season package download
ep = &ent.Episode{}
}
if ep == nil {
return nil, errors.Errorf("no episode of season %d episode %d", seasonNum, episodeNum)
}
torrent, err := trc.Download(r1.Link, c.db.GetDownloadDir())
torrent, err := trc.Download(r1.Link, downloadDir)
if err != nil {
return nil, errors.Wrap(err, "downloading")
}
@@ -88,7 +53,7 @@ func (c *Client) DownloadEpisodeTorrent(r1 torznab.Result, seriesId, seasonNum,
dir := fmt.Sprintf("%s/Season %02d/", series.TargetDir, seasonNum)
history, err := c.db.SaveHistoryRecord(ent.History{
MediaID: ep.MediaID,
MediaID: seriesId,
EpisodeID: ep.ID,
SourceTitle: r1.Name,
TargetDir: dir,
@@ -101,7 +66,11 @@ func (c *Client) DownloadEpisodeTorrent(r1 torznab.Result, seriesId, seasonNum,
if err != nil {
return nil, errors.Wrap(err, "save record")
}
c.db.SetEpisodeStatus(ep.ID, episode.StatusDownloading)
if episodeNum > 0 {
c.db.SetEpisodeStatus(ep.ID, episode.StatusDownloading)
} else {
c.db.SetSeasonAllEpisodeStatus(seriesId, seasonNum, episode.StatusDownloading)
}
c.tasks[history.ID] = &Task{Torrent: torrent}
c.sendMsg(fmt.Sprintf(message.BeginDownload, r1.Name))
@@ -121,7 +90,7 @@ func (c *Client) SearchAndDownload(seriesId, seasonNum, episodeNum int) (*string
return c.DownloadEpisodeTorrent(r1, seriesId, seasonNum, episodeNum)
}
func (c *Client) DownloadMovie(m *ent.Media,link, name string, size int, indexerID int) (*string, error) {
func (c *Client) DownloadMovie(m *ent.Media, link, name string, size int, indexerID int) (*string, error) {
trc, dlc, err := c.getDownloadClient()
if err != nil {
return nil, errors.Wrap(err, "connect transmission")
@@ -162,4 +131,4 @@ func (c *Client) DownloadMovie(m *ent.Media,link, name string, size int, indexer
log.Infof("success add %s to download task", name)
return &name, nil
}
}

View File

@@ -116,16 +116,16 @@ func (c *Client) moveCompletedTask(id int) (err1 error) {
return err
}
//如果种子是路径,则会把路径展开,只移动文件,类似 move dir/* dir2/, 如果种子是文件,则会直接移动文件,类似 move file dir/
if err := stImpl.Copy(filepath.Join(c.db.GetDownloadDir(), torrentName), r.TargetDir); err != nil {
return errors.Wrap(err, "move file")
}
// .plexmatch file
if err := c.writePlexmatch(r.MediaID, r.EpisodeID, r.TargetDir, torrentName); err != nil {
log.Errorf("create .plexmatch file error: %v", err)
}
//如果种子是路径,则会把路径展开,只移动文件,类似 move dir/* dir2/, 如果种子是文件,则会直接移动文件,类似 move file dir/
if err := stImpl.Copy(filepath.Join(c.db.GetDownloadDir(), torrentName), r.TargetDir); err != nil {
return errors.Wrap(err, "move file")
}
c.db.SetHistoryStatus(r.ID, history.StatusSuccess)
if r.EpisodeID != 0 {
c.db.SetEpisodeStatus(r.EpisodeID, episode.StatusDownloaded)

View File

@@ -23,9 +23,7 @@ func SearchTvSeries(db1 *db.Client, seriesId, seasonNum int, episodes []int, che
}
log.Debugf("check tv series %s, season %d, episode %v", series.NameEn, seasonNum, episodes)
res := searchWithTorznab(db1, series.NameEn)
resCn := searchWithTorznab(db1, series.NameCn)
res = append(res, resCn...)
res := searchWithTorznab(db1, series.NameEn, series.NameCn, series.OriginalName)
var filtered []torznab.Result
for _, r := range res {
@@ -52,11 +50,12 @@ func SearchTvSeries(db1 *db.Client, seriesId, seasonNum int, episodes []int, che
if checkResolution && meta.Resolution != series.Resolution.String() {
continue
}
if !utils.IsNameAcceptable(meta.NameEn, series.NameEn) && !utils.IsNameAcceptable(meta.NameCn, series.NameCn) {
if !utils.IsNameAcceptable(meta.NameEn, series.NameEn) && !utils.IsNameAcceptable(meta.NameCn, series.NameCn) &&
!utils.IsNameAcceptable(meta.NameCn, series.OriginalName) {
continue
}
if checkFileSize && series.Limiter != nil {
if checkFileSize {
if series.Limiter.SizeMin > 0 && r.Size < series.Limiter.SizeMin {
//min size not satified
continue
@@ -97,10 +96,7 @@ func SearchMovie(db1 *db.Client, movieId int, checkResolution bool, checkFileSiz
return nil, errors.New("no media found of id")
}
res := searchWithTorznab(db1, movieDetail.NameEn)
res1 := searchWithTorznab(db1, movieDetail.NameCn)
res = append(res, res1...)
res := searchWithTorznab(db1, movieDetail.NameEn, movieDetail.NameCn, movieDetail.OriginalName)
if len(res) == 0 {
return nil, fmt.Errorf("no resource found")
@@ -108,14 +104,15 @@ func SearchMovie(db1 *db.Client, movieId int, checkResolution bool, checkFileSiz
var filtered []torznab.Result
for _, r := range res {
meta := metadata.ParseMovie(r.Name)
if !utils.IsNameAcceptable(meta.NameEn, movieDetail.NameEn) {
if !utils.IsNameAcceptable(meta.Name, movieDetail.NameEn) && !utils.IsNameAcceptable(meta.Name, movieDetail.NameCn) &&
!utils.IsNameAcceptable(meta.Name, movieDetail.OriginalName) {
continue
}
if checkResolution && meta.Resolution != movieDetail.Resolution.String() {
continue
}
if checkFileSize && movieDetail.Limiter != nil {
if checkFileSize {
if movieDetail.Limiter.SizeMin > 0 && r.Size < movieDetail.Limiter.SizeMin {
//min size not satified
continue
@@ -144,7 +141,7 @@ func SearchMovie(db1 *db.Client, movieId int, checkResolution bool, checkFileSiz
}
func searchWithTorznab(db *db.Client, q string) []torznab.Result {
func searchWithTorznab(db *db.Client, queries ...string) []torznab.Result {
var res []torznab.Result
allTorznab := db.GetAllTorznabInfo()
@@ -157,14 +154,16 @@ func searchWithTorznab(db *db.Client, q string) []torznab.Result {
}
wg.Add(1)
go func() {
log.Debugf("search torznab %v with %v", tor.Name, q)
log.Debugf("search torznab %v with %v", tor.Name, queries)
defer wg.Done()
resp, err := torznab.Search(tor, tor.ApiKey, q)
if err != nil {
log.Errorf("search %s error: %v", tor.Name, err)
return
for _, q := range queries {
resp, err := torznab.Search(tor, q)
if err != nil {
log.Errorf("search %s error: %v", tor.Name, err)
return
}
resChan <- resp
}
resChan <- resp
}()
}

View File

@@ -20,7 +20,7 @@ func (s *Server) searchAndDownloadSeasonPackage(seriesId, seasonNum int) (*strin
r1 := res[0]
log.Infof("found resource to download: %+v", r1)
return s.core.DownloadSeasonPackage(r1, seriesId, seasonNum)
return s.core.DownloadEpisodeTorrent(r1, seriesId, seasonNum, -1)
}
@@ -129,7 +129,7 @@ func (s *Server) DownloadTorrent(c *gin.Context) (interface{}, error) {
name = fmt.Sprintf("%v S%02d", m.OriginalName, in.Season)
}
res := torznab.Result{Name: name, Link: in.Link, Size: in.Size}
return s.core.DownloadSeasonPackage(res, in.MediaID, in.Season)
return s.core.DownloadEpisodeTorrent(res, in.MediaID, in.Season, -1)
}
name := in.Name
if name == "" {

View File

@@ -80,6 +80,7 @@ func (s *Server) Serve() error {
tv := api.Group("/media")
{
tv.GET("/search", HttpHandler(s.SearchMedia))
tv.POST("/edit", HttpHandler(s.EditMediaMetadata))
tv.POST("/tv/watchlist", HttpHandler(s.AddTv2Watchlist))
tv.GET("/tv/watchlist", HttpHandler(s.GetTvWatchlist))
tv.POST("/torrents", HttpHandler(s.SearchAvailableTorrents))

View File

@@ -195,8 +195,8 @@ func (s *Server) DeleteDownloadCLient(c *gin.Context) (interface{}, error) {
}
type episodeMonitoringIn struct {
EpisodeID int `json:"episode_id"`
Monitor bool `json:"monitor"`
EpisodeID int `json:"episode_id"`
Monitor bool `json:"monitor"`
}
func (s *Server) ChangeEpisodeMonitoring(c *gin.Context) (interface{}, error) {
@@ -206,4 +206,16 @@ func (s *Server) ChangeEpisodeMonitoring(c *gin.Context) (interface{}, error) {
}
s.db.SetEpisodeMonitoring(in.EpisodeID, in.Monitor)
return "success", nil
}
func (s *Server) EditMediaMetadata(c *gin.Context) (interface{}, error) {
var in db.EditMediaData
if err := c.ShouldBindJSON(&in); err != nil {
return nil, errors.Wrap(err, "bind")
}
err := s.db.EditMediaMetadata(in)
if err != nil {
return nil, errors.Wrap(err, "save db")
}
return "success", nil
}

View File

@@ -3,6 +3,7 @@ package server
import (
"fmt"
"polaris/db"
"regexp"
"polaris/log"
"polaris/pkg/storage"
@@ -75,6 +76,10 @@ func (s *Server) SuggestedSeriesFolderName(c *gin.Context) (interface{}, error)
name = fmt.Sprintf("%s %s", d.Name, en.Name)
}
}
//remove extra characters
re := regexp.MustCompile(`[^\p{L}\w\s]`)
name = re.ReplaceAllString(strings.ToLower(name), " ")
name = strings.Join(strings.Fields(name), " ")
year := strings.Split(d.FirstAirDate, "-")[0]
if year != "" {
name = fmt.Sprintf("%s (%s)", name, year)
@@ -104,11 +109,15 @@ func (s *Server) SuggestedMovieFolderName(c *gin.Context) (interface{}, error) {
name = fmt.Sprintf("%s %s", d1.Title, en.Title)
}
}
//remove extra characters
re := regexp.MustCompile(`[^\p{L}\w\s]`)
name = re.ReplaceAllString(strings.ToLower(name), " ")
name = strings.Join(strings.Fields(name), " ")
year := strings.Split(d1.ReleaseDate, "-")[0]
if year != "" {
name = fmt.Sprintf("%s (%s)", name, year)
}
log.Infof("tv series of tmdb id %v suggestting name is %v", id, name)
return gin.H{"name": name}, nil
}

View File

@@ -139,6 +139,7 @@ func (s *Server) AddTv2Watchlist(c *gin.Context) (interface{}, error) {
}
m := &ent.Media{
TmdbID: int(detail.ID),
ImdbID: detail.IMDbID,
MediaType: media.MediaTypeTv,
NameCn: nameCn,
NameEn: nameEn,
@@ -149,7 +150,7 @@ func (s *Server) AddTv2Watchlist(c *gin.Context) (interface{}, error) {
StorageID: in.StorageID,
TargetDir: in.Folder,
DownloadHistoryEpisodes: in.DownloadHistoryEpisodes,
Limiter: &schema.MediaLimiter{SizeMin: in.SizeMin, SizeMax: in.SizeMax},
Limiter: schema.MediaLimiter{SizeMin: in.SizeMin, SizeMax: in.SizeMax},
}
r, err := s.db.AddMediaWatchlist(m, epIds)
@@ -210,6 +211,7 @@ func (s *Server) AddMovie2Watchlist(c *gin.Context) (interface{}, error) {
r, err := s.db.AddMediaWatchlist(&ent.Media{
TmdbID: int(detail.ID),
ImdbID: detail.IMDbID,
MediaType: media.MediaTypeMovie,
NameCn: nameCn,
NameEn: nameEn,
@@ -219,7 +221,7 @@ func (s *Server) AddMovie2Watchlist(c *gin.Context) (interface{}, error) {
Resolution: media.Resolution(in.Resolution),
StorageID: in.StorageID,
TargetDir: in.Folder,
Limiter: &schema.MediaLimiter{SizeMin: in.SizeMin, SizeMax: in.SizeMax},
Limiter: schema.MediaLimiter{SizeMin: in.SizeMin, SizeMax: in.SizeMax},
}, []int{epid})
if err != nil {
return nil, errors.Wrap(err, "add to list")

View File

@@ -4,7 +4,7 @@
# This file should be version controlled and should not be manually edited.
version:
revision: "761747bfc538b5af34aa0d3fac380f1bc331ec49"
revision: "80c2e84975bbd28ecf5f8d4bd4ca5a2490bfc819"
channel: "stable"
project_type: app
@@ -13,26 +13,11 @@ project_type: app
migration:
platforms:
- platform: root
create_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
base_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
- platform: android
create_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
base_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
create_revision: 80c2e84975bbd28ecf5f8d4bd4ca5a2490bfc819
base_revision: 80c2e84975bbd28ecf5f8d4bd4ca5a2490bfc819
- platform: ios
create_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
base_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
- platform: linux
create_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
base_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
- platform: macos
create_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
base_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
- platform: web
create_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
base_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
- platform: windows
create_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
base_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
create_revision: 80c2e84975bbd28ecf5f8d4bd4ca5a2490bfc819
base_revision: 80c2e84975bbd28ecf5f8d4bd4ca5a2490bfc819
# User provided section

View File

@@ -1,9 +1,10 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:percent_indicator/circular_percent_indicator.dart';
import 'package:ui/providers/activity.dart';
import 'package:ui/widgets/progress_indicator.dart';
import 'package:ui/widgets/utils.dart';
import 'package:ui/widgets/widgets.dart';
import 'package:timeago/timeago.dart' as timeago;
class ActivityPage extends ConsumerStatefulWidget {
const ActivityPage({super.key});
@@ -60,21 +61,76 @@ class _ActivityPageState extends ConsumerState<ActivityPage>
return activitiesWatcher.when(
data: (activities) {
return SingleChildScrollView(
child: PaginatedDataTable(
rowsPerPage: 10,
columns: const [
DataColumn(label: Text("#"), numeric: true),
DataColumn(label: Text("名称")),
DataColumn(label: Text("开始时间")),
DataColumn(label: Text("状态")),
DataColumn(label: Text("操作"))
],
source: ActivityDataSource(
activities: activities,
onDelete: selectedTab == 0 ? onDelete() : null),
),
);
return Flexible(
child: ListView.builder(
itemCount: activities.length,
itemBuilder: (context, index) {
final ac = activities[index];
return Column(
children: [
ListTile(
dense: true,
leading: () {
if (ac.status == "uploading") {
return const SizedBox(
width: 20,
height: 20,
child: Tooltip(
message: "正在上传到指定存储",
child: CircularProgressIndicator(),
));
} else if (ac.status == "fail") {
return const Tooltip(
message: "下载失败",
child: Icon(
Icons.close,
color: Colors.red,
));
} else if (ac.status == "success") {
return const Tooltip(
message: "下载成功",
child: Icon(
Icons.check,
color: Colors.green,
),
);
}
double p = ac.progress == null
? 0
: ac.progress!.toDouble() / 100;
return Tooltip(
message: "${ac.progress}%",
child: CircularProgressIndicator(
backgroundColor: Colors.black26,
value: p,
),
);
}(),
title:
Text( (ac.sourceTitle ?? "")),
subtitle: Opacity(
opacity: 0.7,
child: Wrap(
spacing: 10,
children: [
Text("开始时间:${timeago.format(ac.date!)}"),
Text("大小:${(ac.size ?? 0).readableFileSize()}")
],
),
),
trailing: selectedTab == 0
? IconButton(
tooltip: "删除任务",
onPressed: () => onDelete()(ac.id!),
icon: const Icon(Icons.delete))
: const Text("-"),
),
Divider(),
],
);
},
));
},
error: (err, trace) => Text("$err"),
loading: () => const MyProgressIndicator());
@@ -92,71 +148,3 @@ class _ActivityPageState extends ConsumerState<ActivityPage>
};
}
}
class ActivityDataSource extends DataTableSource {
List<Activity> activities;
Function(int)? onDelete;
ActivityDataSource({required this.activities, this.onDelete});
@override
int get rowCount => activities.length;
@override
DataRow? getRow(int index) {
final activity = activities[index];
return DataRow(cells: [
DataCell(Text("${activity.id}")),
DataCell(Text("${activity.sourceTitle}")),
DataCell(Text("${activity.date!.toLocal()}")),
DataCell(() {
if (activity.status == "uploading") {
return const SizedBox(
width: 20,
height: 20,
child: Tooltip(
message: "正在上传到指定存储",
child: CircularProgressIndicator(),
));
} else if (activity.status == "fail") {
return const Tooltip(
message: "下载失败",
child: Icon(
Icons.close,
color: Colors.red,
));
} else if (activity.status == "success") {
return const Tooltip(
message: "下载成功",
child: Icon(
Icons.check,
color: Colors.green,
),
);
}
double p =
activity.progress == null ? 0 : activity.progress!.toDouble() / 100;
return CircularPercentIndicator(
radius: 15.0,
lineWidth: 5.0,
percent: p,
center: Text("${p * 100}"),
progressColor: Colors.green,
);
}()),
onDelete != null
? DataCell(Tooltip(
message: "删除任务",
child: IconButton(
onPressed: () => onDelete!(activity.id!),
icon: const Icon(Icons.delete))))
: const DataCell(Text("-"))
]);
}
@override
bool get isRowCountApproximate => false;
@override
int get selectedRowCount => 0;
}

View File

@@ -11,6 +11,7 @@ import 'package:ui/settings/settings.dart';
import 'package:ui/system_page.dart';
import 'package:ui/tv_details.dart';
import 'package:ui/welcome_page.dart';
import 'package:ui/widgets/utils.dart';
void main() {
runApp(const MyApp());
@@ -49,7 +50,9 @@ class _MyAppState extends ConsumerState<MyApp> {
builder: (BuildContext context, GoRouterState state, Widget child) {
return SelectionArea(
child: MainSkeleton(
body: Padding(padding: const EdgeInsets.all(20), child: child),
body: Padding(
padding: EdgeInsets.all(isSmallScreen(context) ? 5 : 20),
child: child),
),
);
},
@@ -128,7 +131,7 @@ class _MyAppState extends ConsumerState<MyApp> {
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.blueAccent,
brightness: Brightness.dark,
surface: Colors.black54),
surface: Colors.black87),
useMaterial3: true,
//scaffoldBackgroundColor: Color.fromARGB(255, 26, 24, 24)
tooltipTheme: TooltipThemeData(
@@ -183,16 +186,13 @@ class _MainSkeletonState extends State<MainSkeleton> {
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: const Row(
children: [
Text("Polaris"),
],
),
title: Text("Polaris"),
actions: [
SearchAnchor(
builder: (BuildContext context, SearchController controller) {
return Container(
constraints: const BoxConstraints(maxWidth: 300, maxHeight: 40),
constraints: const BoxConstraints(maxWidth: 250, maxHeight: 40),
child: Opacity(
opacity: 0.8,
child: SearchBar(
@@ -282,7 +282,7 @@ class _MainSkeletonState extends State<MainSkeleton> {
label: '系统',
),
],
body: (context) => widget.body,
body: (context) => SafeArea(child: widget.body),
// Define a default secondaryBody.
// Override the default secondaryBody during the smallBreakpoint to be
// empty. Must use AdaptiveScaffold.emptyBuilder to ensure it is properly

View File

@@ -7,6 +7,7 @@ import 'package:ui/providers/server_response.dart';
class APIs {
static final _baseUrl = baseUrl();
static final searchUrl = "$_baseUrl/api/v1/media/search";
static final editMediaUrl = "$_baseUrl/api/v1/media/edit";
static final settingsUrl = "$_baseUrl/api/v1/setting/do";
static final settingsGeneralUrl = "$_baseUrl/api/v1/setting/general";
static final watchlistTvUrl = "$_baseUrl/api/v1/media/tv/watchlist";

View File

@@ -68,7 +68,8 @@ class Activity {
required this.targetDir,
required this.status,
required this.saved,
required this.progress});
required this.progress,
required this.size});
final int? id;
final int? mediaId;
@@ -79,6 +80,7 @@ class Activity {
final String? status;
final String? saved;
final int? progress;
final int? size;
factory Activity.fromJson(Map<String, dynamic> json) {
return Activity(
@@ -90,6 +92,7 @@ class Activity {
targetDir: json["target_dir"],
status: json["status"],
saved: json["saved"],
progress: json["progress"]);
progress: json["progress"],
size: json["size"]);
}
}

View File

@@ -1,5 +1,6 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:ui/providers/APIs.dart';
import 'package:ui/providers/server_response.dart';
@@ -34,7 +35,7 @@ class SeriesDetailData
Future<String> searchAndDownload(
String seriesId, int seasonNum, int episodeNum) async {
final dio = await APIs.getDio();
final dio = APIs.getDio();
var resp = await dio.post(APIs.searchAndDownloadUrl, data: {
"id": int.parse(seriesId),
"season": seasonNum,
@@ -61,11 +62,31 @@ class SeriesDetailData
}
ref.invalidateSelf();
}
Future<void> edit(
String resolution, String targetDir, RangeValues limiter) async {
final dio = APIs.getDio();
var resp = await dio.post(APIs.editMediaUrl, data: {
"id": int.parse(id!),
"resolution": resolution,
"target_dir": targetDir,
"limiter": {
"size_min": limiter.start.toInt() * 1000 * 1000,
"size_max": limiter.end.toInt() * 1000 * 1000
},
});
var sp = ServerResponse.fromJson(resp.data);
if (sp.code != 0) {
throw sp.message;
}
ref.invalidateSelf();
}
}
class SeriesDetails {
int? id;
int? tmdbId;
String? imdbid;
String? name;
String? originalName;
String? overview;
@@ -79,10 +100,12 @@ class SeriesDetails {
Storage? storage;
String? targetDir;
bool? downloadHistoryEpisodes;
Limiter? limiter;
SeriesDetails(
{this.id,
this.tmdbId,
this.imdbid,
this.name,
this.originalName,
this.overview,
@@ -95,11 +118,13 @@ class SeriesDetails {
this.mediaType,
this.targetDir,
this.storage,
this.downloadHistoryEpisodes});
this.downloadHistoryEpisodes,
this.limiter});
SeriesDetails.fromJson(Map<String, dynamic> json) {
id = json['id'];
tmdbId = json['tmdb_id'];
imdbid = json["imdb_id"];
name = json['name_cn'];
originalName = json['original_name'];
overview = json['overview'];
@@ -118,6 +143,19 @@ class SeriesDetails {
episodes!.add(Episodes.fromJson(v));
});
}
if (json["limiter"] != null) {
limiter = Limiter.fromJson(json["limiter"]);
}
}
}
class Limiter {
int sizeMax;
int sizeMin;
Limiter({required this.sizeMax, required this.sizeMin});
factory Limiter.fromJson(Map<String, dynamic> json) {
return Limiter(sizeMax: json["size_max"], sizeMin: json["size_min"]);
}
}

View File

@@ -108,8 +108,8 @@ class SearchPageData
"resolution": resolution,
"folder": folder,
"download_history_episodes": downloadHistoryEpisodes,
"size_min": (limiter.start * 1000).toInt(),
"size_max": (limiter.end * 1000).toInt(),
"size_min": (limiter.start * 1000*1000).toInt(),
"size_max": (limiter.end * 1000*1000).toInt(),
});
var sp = ServerResponse.fromJson(resp.data);
if (sp.code != 0) {

View File

@@ -62,10 +62,12 @@ class _SubmitSearchResultState extends ConsumerState<SubmitSearchResult> {
storage.when(
data: (v) {
return StatefulBuilder(builder: (context, setState) {
final id1 = v.isEmpty ? 0 : v[0].id!;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FormBuilderDropdown(
initialValue: id1,
onChanged: (v) {
setState(
() {
@@ -83,6 +85,9 @@ class _SubmitSearchResultState extends ConsumerState<SubmitSearchResult> {
),
name.when(
data: (s) {
if (storageSelected == 0) {
storageSelected = id1;
}
return storageSelected == 0
? const Text("")
: () {
@@ -125,35 +130,7 @@ class _SubmitSearchResultState extends ConsumerState<SubmitSearchResult> {
},
),
enabledSizedLimiter
? FormBuilderRangeSlider(
maxValueWidget: (max) =>
Text("${sizeMax / 1000} GB"),
minValueWidget: (min) => Text("0"),
valueWidget: (value) {
final sss = value.split(" ");
return Text(
"${readableSize(sss[0])} - ${readableSize(sss[2])}");
},
onChangeEnd: (value) {
if (value.end > sizeMax * 0.9) {
setState(
() {
sizeMax = sizeMax * 5;
},
);
} else if (value.end < sizeMax * 0.2) {
if (sizeMax > 5000) {
setState(
() {
sizeMax = sizeMax / 5;
},
);
}
}
},
name: "size_limiter",
min: 0,
max: sizeMax)
? const MyRangeSlider(name: "size_limiter")
: const SizedBox(),
widget.item.mediaType == "tv"
? SizedBox(
@@ -184,16 +161,16 @@ class _SubmitSearchResultState extends ConsumerState<SubmitSearchResult> {
Navigator.of(context).pop();
},
),
TextButton(
style: TextButton.styleFrom(
textStyle: Theme.of(context).textTheme.labelLarge,
),
child: const Text('确定'),
LoadingTextButton(
// style: TextButton.styleFrom(
// textStyle: Theme.of(context).textTheme.labelLarge,
// ),
label: const Text('确定'),
onPressed: () async {
if (_formKey.currentState!.saveAndValidate()) {
final values = _formKey.currentState!.value;
var f = ref
.read(searchPageDataProvider(widget.query ?? "").notifier)
await ref
.read(searchPageDataProvider(widget.query).notifier)
.submit2Watchlist(
widget.item.id!,
values["storage"],
@@ -208,7 +185,6 @@ class _SubmitSearchResultState extends ConsumerState<SubmitSearchResult> {
Navigator.of(context).pop();
showSnakeBar("添加成功:${widget.item.name}");
});
showLoadingWithFuture(f);
}
},
),

View File

@@ -22,12 +22,11 @@ Future<void> showSettingDialog(
),
actions: <Widget>[
showDelete
? TextButton(
onPressed: () {
final f = onDelete().then((v) => Navigator.of(context).pop());
showLoadingWithFuture(f);
? LoadingTextButton(
onPressed: () async {
await onDelete().then((v) => Navigator.of(context).pop());
},
child: const Text(
label: const Text(
'删除',
style: TextStyle(color: Colors.red),
))
@@ -35,11 +34,10 @@ Future<void> showSettingDialog(
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('取消')),
TextButton(
child: const Text('确定'),
onPressed: () {
final f = onSubmit().then((v) => Navigator.of(context).pop());
showLoadingWithFuture(f);
LoadingTextButton(
label: const Text('确定'),
onPressed: () async {
await onSubmit().then((v) => Navigator.of(context).pop());
},
),
],

View File

@@ -45,14 +45,14 @@ class _SystemSettingsPageState extends ConsumerState<SystemSettingsPage> {
),
ExpansionTile(
expandedAlignment: Alignment.centerLeft,
childrenPadding: EdgeInsets.fromLTRB(20, 0, 50, 0),
childrenPadding: EdgeInsets.fromLTRB(20, 0, 20, 0),
initiallyExpanded: false,
title: Text("存储"),
children: [StorageSettings()],
),
ExpansionTile(
expandedAlignment: Alignment.centerLeft,
childrenPadding: EdgeInsets.fromLTRB(20, 0, 50, 0),
childrenPadding: EdgeInsets.fromLTRB(20, 0, 20, 0),
initiallyExpanded: false,
title: Text("通知客户端"),
children: [NotifierSettings()],

View File

@@ -32,6 +32,7 @@ class _TvDetailsPageState extends ConsumerState<TvDetailsPage> {
@override
Widget build(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
var seriesDetails = ref.watch(mediaDetailsProvider(widget.seriesId));
return seriesDetails.when(
data: (details) {
@@ -48,62 +49,55 @@ class _TvDetailsPageState extends ConsumerState<TvDetailsPage> {
Opacity(
opacity: 0.7,
child: ep.status == "downloading"
? const Tooltip(
message: "下载中",
child: IconButton(onPressed: null, icon: Icon(Icons.downloading)),
)
? const IconButton(
tooltip: "下载中",
onPressed: null,
icon: Icon(Icons.downloading))
: (ep.status == "downloaded"
? const Tooltip(
message: "已下载",
child: IconButton(onPressed: null, icon: Icon(Icons.download_done)),
)
? const IconButton(
tooltip: "已下载",
onPressed: null,
icon: Icon(Icons.download_done))
: (ep.monitored == true
? Tooltip(
message: "监控中",
? IconButton(
tooltip: "监控中",
onPressed: () {
ref
.read(mediaDetailsProvider(
widget.seriesId)
.notifier)
.changeMonitoringStatus(
ep.id!, false);
},
icon: const Icon(Icons.alarm))
: Opacity(
opacity: 0.7,
child: IconButton(
tooltip: "未监控",
onPressed: () {
ref
.read(mediaDetailsProvider(
widget.seriesId)
.notifier)
.changeMonitoringStatus(
ep.id!, false);
ep.id!, true);
},
icon: const Icon(Icons.alarm)),
)
: Opacity(
opacity: 0.7,
child: Tooltip(
message: "未监控",
child: IconButton(
onPressed: () {
ref
.read(mediaDetailsProvider(
widget.seriesId)
.notifier)
.changeMonitoringStatus(
ep.id!, true);
},
icon: const Icon(Icons.alarm_off)),
),
icon: const Icon(Icons.alarm_off)),
)))),
),
DataCell(Row(
children: [
Tooltip(
message: "搜索下载对应剧集",
child: IconButton(
onPressed: () {
var f = ref
.read(mediaDetailsProvider(widget.seriesId)
.notifier)
.searchAndDownload(widget.seriesId,
ep.seasonNumber!, ep.episodeNumber!)
.then((v) => showSnakeBar("开始下载: $v"));
showLoadingWithFuture(f);
},
icon: const Icon(Icons.download)),
),
LoadingIconButton(
tooltip: "搜索下载对应剧集",
onPressed: () async {
await ref
.read(
mediaDetailsProvider(widget.seriesId).notifier)
.searchAndDownload(widget.seriesId,
ep.seasonNumber!, ep.episodeNumber!)
.then((v) => showSnakeBar("开始下载: $v"));
},
icon: Icons.download),
const SizedBox(
width: 10,
),
@@ -125,6 +119,41 @@ class _TvDetailsPageState extends ConsumerState<TvDetailsPage> {
}
List<ExpansionTile> list = List.empty(growable: true);
for (final k in m.keys.toList().reversed) {
final seasonEpisodes = DataTable(columns: [
const DataColumn(label: Text("#")),
const DataColumn(
label: Text("标题"),
),
const DataColumn(label: Text("播出时间")),
const DataColumn(label: Text("状态")),
DataColumn(
label: Row(
children: [
LoadingIconButton(
tooltip: "搜索下载全部剧集",
onPressed: () async {
await ref
.read(
mediaDetailsProvider(widget.seriesId).notifier)
.searchAndDownload(widget.seriesId, k, 0)
.then((v) => showSnakeBar("开始下载: $v"));
//showLoadingWithFuture(f);
},
icon: Icons.download),
const SizedBox(
width: 10,
),
Tooltip(
message: "查看可用资源",
child: IconButton(
onPressed: () =>
showAvailableTorrents(widget.seriesId, k, 0),
icon: const Icon(Icons.manage_search)),
)
],
))
], rows: m[k]!);
var seasonList = ExpansionTile(
tilePadding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
//childrenPadding: const EdgeInsets.fromLTRB(50, 0, 50, 0),
@@ -132,42 +161,12 @@ class _TvDetailsPageState extends ConsumerState<TvDetailsPage> {
title: k == 0 ? const Text("特别篇") : Text("$k"),
expandedCrossAxisAlignment: CrossAxisAlignment.stretch,
children: [
DataTable(columns: [
const DataColumn(label: Text("#")),
const DataColumn(
label: Text("标题"),
),
const DataColumn(label: Text("播出时间")),
const DataColumn(label: Text("状态")),
DataColumn(
label: Row(
children: [
Tooltip(
message: "搜索下载全部剧集",
child: IconButton(
onPressed: () {
final f = ref
.read(mediaDetailsProvider(widget.seriesId)
.notifier)
.searchAndDownload(widget.seriesId, k, 0)
.then((v) => showSnakeBar("开始下载: $v"));
showLoadingWithFuture(f);
},
icon: const Icon(Icons.download)),
),
const SizedBox(
width: 10,
),
Tooltip(
message: "查看可用资源",
child: IconButton(
onPressed: () =>
showAvailableTorrents(widget.seriesId, k, 0),
icon: const Icon(Icons.manage_search)),
screenWidth < 600
? SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: seasonEpisodes,
)
],
))
], rows: m[k]!),
: seasonEpisodes
],
);
list.add(seasonList);

View File

@@ -27,8 +27,9 @@ class WelcomePage extends ConsumerWidget {
return switch (data) {
AsyncData(:final value) => SingleChildScrollView(
child: Wrap(
spacing: 10,
runSpacing: 20,
alignment: WrapAlignment.start,
spacing: isSmallScreen(context) ? 0 : 10,
runSpacing: isSmallScreen(context) ? 10 : 20,
children: value.isEmpty
? [
Container(
@@ -41,57 +42,85 @@ class WelcomePage extends ConsumerWidget {
]
: List.generate(value.length, (i) {
final item = value[i];
return Card(
//margin: const EdgeInsets.all(4),
clipBehavior: Clip.hardEdge,
elevation: 5,
child: InkWell(
//splashColor: Colors.blue.withAlpha(30),
onTap: () {
if (uri == routeMoivie) {
context.go(MovieDetailsPage.toRoute(item.id!));
} else {
context.go(TvDetailsPage.toRoute(item.id!));
}
},
child: Column(
children: <Widget>[
SizedBox(
width: 140,
height: 210,
child: Ink.image(
image: NetworkImage(
"${APIs.imagesUrl}/${item.id}/poster.jpg",
)),
),
SizedBox(
width: 140,
child: Column(
children: [
LinearProgressIndicator(
value: 1,
color: item.downloadedNum! >=
item.monitoredNum!
? Colors.green
: Colors.blue,
),
Text(
item.name!,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
height: 2.5),
),
],
)),
],
),
));
return MediaCard(item: item);
}),
),
),
_ => const MyProgressIndicator(),
};
}
bool isSmallScreen(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
return screenWidth < 600;
}
}
class MediaCard extends StatelessWidget {
final MediaDetail item;
static const double smallWidth = 110;
static const double largeWidth = 140;
const MediaCard({super.key, required this.item});
@override
Widget build(BuildContext context) {
return Card(
shape: ContinuousRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
//margin: const EdgeInsets.all(4),
clipBehavior: Clip.hardEdge,
elevation: 10,
child: InkWell(
//splashColor: Colors.blue.withAlpha(30),
onTap: () {
if (item.mediaType == "movie") {
context.go(MovieDetailsPage.toRoute(item.id!));
} else {
context.go(TvDetailsPage.toRoute(item.id!));
}
},
child: Column(
children: <Widget>[
SizedBox(
width: cardWidth(context),
height: cardWidth(context) / 2 * 3,
child: Ink.image(
fit: BoxFit.cover,
image: NetworkImage(
"${APIs.imagesUrl}/${item.id}/poster.jpg",
)),
),
SizedBox(
width: cardWidth(context),
child: Column(
children: [
LinearProgressIndicator(
value: 1,
color: item.downloadedNum! >= item.monitoredNum!
? Colors.green
: Colors.blue,
),
Text(
item.name!,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
height: 2.5),
),
],
)),
],
),
));
}
double cardWidth(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
if (screenWidth < 600) {
return smallWidth;
}
return largeWidth;
}
}

View File

@@ -1,9 +1,14 @@
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:go_router/go_router.dart';
import 'package:quiver/strings.dart';
import 'package:ui/providers/APIs.dart';
import 'package:ui/providers/series_details.dart';
import 'package:ui/welcome_page.dart';
import 'package:ui/widgets/utils.dart';
import 'package:url_launcher/url_launcher.dart';
import 'widgets.dart';
@@ -19,14 +24,21 @@ class DetailCard extends ConsumerStatefulWidget {
}
class _DetailCardState extends ConsumerState<DetailCard> {
final tmdbBase = "https://www.themoviedb.org/";
final imdbBase = "https://www.imdb.com/title/";
@override
Widget build(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
final url = Uri.parse(tmdbBase +
(widget.details.mediaType == "tv" ? "tv/" : "movie/") +
widget.details.tmdbId.toString());
final imdbUrl = Uri.parse(imdbBase + (widget.details.imdbid ?? ""));
return Card(
margin: const EdgeInsets.all(4),
clipBehavior: Clip.hardEdge,
child: Container(
constraints:
BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.4),
constraints: BoxConstraints(maxHeight: 400),
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
@@ -39,15 +51,17 @@ class _DetailCardState extends ConsumerState<DetailCard> {
padding: const EdgeInsets.all(10),
child: Row(
children: <Widget>[
Flexible(
flex: 2,
child: Padding(
padding: const EdgeInsets.all(10),
child: Image.network(
"${APIs.imagesUrl}/${widget.details.id}/poster.jpg",
fit: BoxFit.contain),
),
),
screenWidth < 600
? SizedBox()
: Flexible(
flex: 2,
child: Padding(
padding: const EdgeInsets.all(10),
child: Image.network(
"${APIs.imagesUrl}/${widget.details.id}/poster.jpg",
fit: BoxFit.contain),
),
),
Flexible(
flex: 4,
child: Row(
@@ -56,38 +70,105 @@ class _DetailCardState extends ConsumerState<DetailCard> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(""),
Row(
children: [
Text("${widget.details.resolution}"),
const SizedBox(
width: 30,
),
Text(
"${widget.details.storage!.name} (${widget.details.storage!.implementation})"),
const SizedBox(
width: 30,
),
Expanded(child: Text(
"${widget.details.mediaType == "tv" ? widget.details.storage!.tvPath : widget.details.storage!.moviePath}"
"${widget.details.targetDir}"),)
],
),
const Divider(thickness: 1, height: 1),
//const Text(""),
Text(
"${widget.details.name} ${widget.details.name != widget.details.originalName ? widget.details.originalName : ''} (${widget.details.airDate!.split("-")[0]})",
style: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
fontSize: 24,
fontWeight: FontWeight.bold,
height: 2.5),
),
const Text(""),
const Divider(thickness: 1, height: 1),
Text(
"",
style: TextStyle(height: 0.2),
),
Wrap(
spacing: 10,
children: [
Chip(
clipBehavior: Clip.hardEdge,
shape: ContinuousRectangleBorder(
borderRadius: BorderRadius.circular(100.0)),
label: Text(
"${widget.details.storage!.name}: ${widget.details.mediaType == "tv" ? widget.details.storage!.tvPath : widget.details.storage!.moviePath}"
"${widget.details.targetDir}"),
padding: EdgeInsets.all(0),
),
Chip(
clipBehavior: Clip.hardEdge,
shape: ContinuousRectangleBorder(
borderRadius: BorderRadius.circular(100.0)),
label: Text("${widget.details.resolution}"),
padding: EdgeInsets.all(0),
),
widget.details.limiter != null &&
widget.details.limiter!.sizeMax > 0
? Chip(
clipBehavior: Clip.hardEdge,
shape: ContinuousRectangleBorder(
borderRadius:
BorderRadius.circular(100.0)),
padding: EdgeInsets.all(0),
label: Text(
"${(widget.details.limiter!.sizeMin).readableFileSize()} - ${(widget.details.limiter!.sizeMax).readableFileSize()}"))
: const SizedBox(),
MenuAnchor(
style: MenuStyle(alignment: Alignment.bottomRight),
menuChildren: [
ActionChip.elevated(
onPressed: () => launchUrl(url),
clipBehavior: Clip.hardEdge,
backgroundColor: Colors.indigo[700],
shape: ContinuousRectangleBorder(
borderRadius:
BorderRadius.circular(100.0)),
padding: EdgeInsets.all(0),
label: Text("TMDB")),
isBlank(widget.details.imdbid)
? SizedBox()
: ActionChip.elevated(
onPressed: () => launchUrl(imdbUrl),
backgroundColor: Colors.indigo[700],
clipBehavior: Clip.hardEdge,
shape: ContinuousRectangleBorder(
borderRadius:
BorderRadius.circular(100.0)),
padding: EdgeInsets.all(0),
label: Text("IMDB"),
)
],
builder: (context, controller, child) {
return ActionChip.elevated(
onPressed: () {
if (controller.isOpen) {
controller.close();
} else {
controller.open();
}
},
clipBehavior: Clip.hardEdge,
shape: ContinuousRectangleBorder(
borderRadius:
BorderRadius.circular(100.0)),
padding: EdgeInsets.all(0),
label: Text("外部链接"));
},
),
],
),
const Text("", style: TextStyle(height: 1)),
Expanded(
child: Text(
overflow: TextOverflow.ellipsis,
maxLines: 9,
maxLines: 7,
widget.details.overview ?? "",
)),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
downloadButton(),
editIcon(),
deleteIcon(),
],
)
@@ -104,20 +185,126 @@ class _DetailCardState extends ConsumerState<DetailCard> {
}
Widget deleteIcon() {
return Tooltip(
message: widget.details.mediaType == "tv" ? "删除剧集" : "删除电影",
child: IconButton(
onPressed: () {
var f = ref
.read(
mediaDetailsProvider(widget.details.id.toString()).notifier)
.delete()
.then((v) => context.go(widget.details.mediaType == "tv"
? WelcomePage.routeTv
: WelcomePage.routeMoivie));
showLoadingWithFuture(f);
},
icon: const Icon(Icons.delete)),
return IconButton(
tooltip: widget.details.mediaType == "tv" ? "删除剧集" : "删除电影",
onPressed: () => showConfirmDialog(),
icon: const Icon(Icons.delete));
}
Future<void> showConfirmDialog() {
return showDialog<void>(
context: context,
barrierDismissible: true,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("确认删除:"),
content: Text("${widget.details.name}"),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text("取消")),
TextButton(
onPressed: () {
ref
.read(mediaDetailsProvider(widget.details.id.toString())
.notifier)
.delete()
.then((v) => context.go(widget.details.mediaType == "tv"
? WelcomePage.routeTv
: WelcomePage.routeMoivie));
Navigator.of(context).pop();
},
child: const Text("确认"))
],
);
},
);
}
Widget editIcon() {
return IconButton(
tooltip: "编辑",
onPressed: () => showEditDialog(),
icon: const Icon(Icons.edit));
}
showEditDialog() {
final _formKey = GlobalKey<FormBuilderState>();
return showDialog<void>(
context: context,
barrierDismissible: true,
builder: (BuildContext context) {
return AlertDialog(
title: Text("编辑 ${widget.details.name}"),
content: SelectionArea(
child: SizedBox(
width: MediaQuery.of(context).size.width * 0.3,
height: MediaQuery.of(context).size.height * 0.4,
child: SingleChildScrollView(
child: FormBuilder(
key: _formKey,
initialValue: {
"resolution": widget.details.resolution,
"target_dir": widget.details.targetDir,
"limiter": widget.details.limiter != null
? RangeValues(
widget.details.limiter!.sizeMin.toDouble() /
1000 /
1000,
widget.details.limiter!.sizeMax.toDouble() /
1000 /
1000)
: const RangeValues(0, 0)
},
child: Column(
children: [
FormBuilderDropdown(
name: "resolution",
decoration: const InputDecoration(labelText: "清晰度"),
items: const [
DropdownMenuItem(value: "720p", child: Text("720p")),
DropdownMenuItem(value: "1080p", child: Text("1080p")),
DropdownMenuItem(value: "2160p", child: Text("2160p")),
],
),
FormBuilderTextField(
name: "target_dir",
decoration: const InputDecoration(labelText: "存储路径"),
validator: FormBuilderValidators.required(),
),
const MyRangeSlider(name: "limiter"),
],
),
)),
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text("取消")),
LoadingTextButton(
onPressed: () async {
if (_formKey.currentState!.saveAndValidate()) {
final values = _formKey.currentState!.value;
await ref
.read(mediaDetailsProvider(widget.details.id.toString())
.notifier)
.edit(values["resolution"], values["target_dir"],
values["limiter"])
.then((v) => Navigator.of(context).pop());
}
},
label: const Text("确认"))
],
);
},
);
}
Widget downloadButton() {
return IconButton(
tooltip: widget.details.mediaType == "tv" ? "查找并下载所有监控剧集" : "查找并下载此电影",
onPressed: () {},
icon: const Icon(Icons.download_rounded));
}
}

View File

@@ -59,10 +59,10 @@ class ResourceList extends ConsumerWidget {
: "-")));
}
rows.add(DataCell(IconButton(
icon: const Icon(Icons.download),
rows.add(DataCell(LoadingIconButton(
icon: Icons.download,
onPressed: () async {
var f = ref
await ref
.read(mediaTorrentsDataProvider((
mediaId: mediaId,
seasonNumber: seasonNum,
@@ -70,7 +70,6 @@ class ResourceList extends ConsumerWidget {
)).notifier)
.download(torrent)
.then((v) => showSnakeBar("开始下载:${torrent.name}"));
showLoadingWithFuture(f);
},
)));
return DataRow(cells: rows);

View File

@@ -3,6 +3,7 @@ import 'dart:math';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:ui/providers/APIs.dart';
import 'dart:io' show Platform;
class Utils {
static Future<void> showAlertDialog(BuildContext context, String msg) async {
@@ -31,21 +32,20 @@ class Utils {
},
);
}
}
showSnakeBar(String msg) {
final context = APIs.navigatorKey.currentContext;
if (context != null) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(msg),
showCloseIcon: true,
));
}
showSnakeBar(String msg) {
final context = APIs.navigatorKey.currentContext;
if (context != null) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(msg),
showCloseIcon: true,
));
}
}
extension FileFormatter on num {
String readableFileSize({bool base1024 = true}) {
String readableFileSize({bool base1024 = false}) {
final base = base1024 ? 1024 : 1000;
if (this <= 0) return "0";
final units = ["B", "kB", "MB", "GB", "TB"];
@@ -53,3 +53,12 @@ extension FileFormatter on num {
return "${NumberFormat("#,##0.#").format(this / pow(base, digitGroups))} ${units[digitGroups]}";
}
}
bool isDesktop() {
return Platform.isLinux || Platform.isWindows || Platform.isMacOS;
}
bool isSmallScreen(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
return screenWidth < 600;
}

View File

@@ -1,5 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:ui/providers/APIs.dart';
import 'package:ui/widgets/utils.dart';
class Commons {
static InputDecoration requiredTextFieldStyle({
@@ -86,3 +88,145 @@ showLoadingWithFuture(Future f) {
},
);
}
class MyRangeSlider extends StatefulWidget {
final String name;
const MyRangeSlider({super.key, required this.name});
@override
State<StatefulWidget> createState() {
return _MySliderState();
}
}
class _MySliderState extends State<MyRangeSlider> {
double sizeMax = 5000;
@override
Widget build(BuildContext context) {
return FormBuilderRangeSlider(
decoration: const InputDecoration(labelText: "文件大小限制"),
maxValueWidget: (max) => Text("${sizeMax / 1000} GB"),
minValueWidget: (min) => const Text("0"),
valueWidget: (value) {
final sss = value.split(" ");
return Text("${readableSize(sss[0])} - ${readableSize(sss[2])}");
},
onChangeEnd: (value) {
if (value.end > sizeMax * 0.9) {
setState(
() {
sizeMax = sizeMax * 5;
},
);
} else if (value.end < sizeMax * 0.2) {
if (sizeMax > 5000) {
setState(
() {
sizeMax = sizeMax / 5;
},
);
}
}
},
name: widget.name,
min: 0,
max: sizeMax);
}
String readableSize(String v) {
if (v.endsWith("K")) {
return v.replaceAll("K", " GB");
}
return "$v MB";
}
}
class LoadingIconButton extends StatefulWidget {
LoadingIconButton({required this.onPressed, required this.icon, this.tooltip});
final Future<void> Function() onPressed;
final IconData icon;
final String? tooltip;
@override
State<StatefulWidget> createState() {
return _LoadingIconButtonState();
}
}
class _LoadingIconButtonState extends State<LoadingIconButton> {
bool loading = false;
@override
Widget build(BuildContext context) {
return IconButton(
tooltip: widget.tooltip,
onPressed: loading
? null
: () async {
setState(() => loading = true);
try {
await widget.onPressed();
} catch (e) {
showSnakeBar("操作失败:$e");
} finally {
setState(() => loading = false);
}
},
icon: loading
? Container(
width: 24,
height: 24,
padding: const EdgeInsets.all(2.0),
child: const CircularProgressIndicator(
color: Colors.grey,
strokeWidth: 3,
),
)
: Icon(widget.icon));
}
}
class LoadingTextButton extends StatefulWidget {
LoadingTextButton({required this.onPressed, required this.label});
final Future<void> Function() onPressed;
final Widget label;
@override
State<StatefulWidget> createState() {
return _LoadingTextButtonState();
}
}
class _LoadingTextButtonState extends State<LoadingTextButton> {
bool loading = false;
@override
Widget build(BuildContext context) {
return TextButton.icon(
onPressed: loading
? null
: () async {
setState(() => loading = true);
try {
await widget.onPressed();
} catch (e) {
showSnakeBar("操作失败:$e");
} finally {
setState(() => loading = false);
}
},
icon: loading
? Container(
width: 24,
height: 24,
padding: const EdgeInsets.all(2.0),
child: const CircularProgressIndicator(
color: Colors.grey,
strokeWidth: 3,
),
)
: Text(""),
label: widget.label,
);
}
}

View File

@@ -69,10 +69,18 @@ packages:
dependency: "direct main"
description:
name: dio
sha256: "11e40df547d418cc0c4900a9318b26304e665da6fa4755399a9ff9efd09034b5"
sha256: e17f6b3097b8c51b72c74c9f071a605c47bcc8893839bd66732457a5ebe73714
url: "https://pub.flutter-io.cn"
source: hosted
version: "5.4.3+1"
version: "5.5.0+1"
dio_web_adapter:
dependency: transitive
description:
name: dio_web_adapter
sha256: "36c5b2d79eb17cdae41e974b7a8284fec631651d2a6f39a8a2ff22327e90aeac"
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.0.1"
equatable:
dependency: transitive
description:
@@ -169,10 +177,10 @@ packages:
dependency: "direct main"
description:
name: go_router
sha256: cdae1b9c8bd7efadcef6112e81c903662ef2ce105cbd220a04bbb7c3425b5554
sha256: ddc16d34b0d74cb313986918c0f0885a7ba2fc24d8fb8419de75f0015144ccfe
url: "https://pub.flutter-io.cn"
source: hosted
version: "14.2.0"
version: "14.2.3"
http_parser:
dependency: transitive
description:
@@ -209,18 +217,18 @@ packages:
dependency: transitive
description:
name: leak_tracker
sha256: "7f0df31977cb2c0b88585095d168e689669a2cc9b97c309665e3386f3e9d341a"
sha256: "3f87a60e8c63aecc975dda1ceedbc8f24de75f09e4856ea27daf8958f2f0ce05"
url: "https://pub.flutter-io.cn"
source: hosted
version: "10.0.4"
version: "10.0.5"
leak_tracker_flutter_testing:
dependency: transitive
description:
name: leak_tracker_flutter_testing
sha256: "06e98f569d004c1315b991ded39924b21af84cf14cc94791b8aea337d25b57f8"
sha256: "932549fb305594d82d7183ecd9fa93463e9914e1b67cacc34bc40906594a1806"
url: "https://pub.flutter-io.cn"
source: hosted
version: "3.0.3"
version: "3.0.5"
leak_tracker_testing:
dependency: transitive
description:
@@ -281,18 +289,18 @@ packages:
dependency: transitive
description:
name: material_color_utilities
sha256: "0e0a020085b65b6083975e499759762399b4475f766c21668c4ecca34ea74e5a"
sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.8.0"
version: "0.11.1"
meta:
dependency: transitive
description:
name: meta
sha256: "7687075e408b093f36e6bbf6c91878cc0d4cd10f409506f7bc996f68220b9136"
sha256: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.12.0"
version: "1.15.0"
nested:
dependency: transitive
description:
@@ -309,14 +317,6 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.9.0"
percent_indicator:
dependency: "direct main"
description:
name: percent_indicator
sha256: c37099ad833a883c9d71782321cb65c3a848c21b6939b6185f0ff6640d05814c
url: "https://pub.flutter-io.cn"
source: hosted
version: "4.2.3"
phone_numbers_parser:
dependency: transitive
description:
@@ -422,10 +422,18 @@ packages:
dependency: transitive
description:
name: test_api
sha256: "9955ae474176f7ac8ee4e989dadfb411a58c30415bcfb648fa04b2b8a03afa7f"
sha256: "5b8a98dafc4d5c4c9c72d8b31ab2b23fc13422348d2997120294d3bac86b4ddb"
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.7.0"
version: "0.7.2"
timeago:
dependency: "direct main"
description:
name: timeago
sha256: "054cedf68706bb142839ba0ae6b135f6b68039f0b8301cbe8784ae653d5ff8de"
url: "https://pub.flutter-io.cn"
source: hosted
version: "3.7.0"
typed_data:
dependency: transitive
description:
@@ -446,18 +454,18 @@ packages:
dependency: transitive
description:
name: url_launcher_android
sha256: ceb2625f0c24ade6ef6778d1de0b2e44f2db71fded235eb52295247feba8c5cf
sha256: "94d8ad05f44c6d4e2ffe5567ab4d741b82d62e3c8e288cc1fcea45965edf47c9"
url: "https://pub.flutter-io.cn"
source: hosted
version: "6.3.3"
version: "6.3.8"
url_launcher_ios:
dependency: transitive
description:
name: url_launcher_ios
sha256: "7068716403343f6ba4969b4173cbf3b84fc768042124bc2c011e5d782b24fe89"
sha256: e43b677296fadce447e987a2f519dcf5f6d1e527dc35d01ffab4fff5b8a7063e
url: "https://pub.flutter-io.cn"
source: hosted
version: "6.3.0"
version: "6.3.1"
url_launcher_linux:
dependency: transitive
description:
@@ -486,18 +494,18 @@ packages:
dependency: transitive
description:
name: url_launcher_web
sha256: "8d9e750d8c9338601e709cd0885f95825086bd8b642547f26bda435aade95d8a"
sha256: "772638d3b34c779ede05ba3d38af34657a05ac55b06279ea6edd409e323dca8e"
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.3.1"
version: "2.3.3"
url_launcher_windows:
dependency: transitive
description:
name: url_launcher_windows
sha256: ecf9725510600aa2bb6d7ddabe16357691b6d2805f66216a97d1b881e21beff7
sha256: "49c10f879746271804767cb45551ec5592cdab00ee105c06dddde1a98f73b185"
url: "https://pub.flutter-io.cn"
source: hosted
version: "3.1.1"
version: "3.1.2"
vector_math:
dependency: transitive
description:
@@ -510,18 +518,18 @@ packages:
dependency: transitive
description:
name: vm_service
sha256: "3923c89304b715fb1eb6423f017651664a03bf5f4b29983627c4da791f74a4ec"
sha256: f652077d0bdf60abe4c1f6377448e8655008eef28f128bc023f7b5e8dfeb48fc
url: "https://pub.flutter-io.cn"
source: hosted
version: "14.2.1"
version: "14.2.4"
web:
dependency: transitive
description:
name: web
sha256: "97da13628db363c635202ad97068d47c5b8aa555808e7a9411963c533b449b27"
sha256: d43c1d6b787bf0afad444700ae7f4db8827f701bc61c255ac8d328c6f4d52062
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.5.1"
version: "1.0.0"
sdks:
dart: ">=3.4.3 <4.0.0"
flutter: ">=3.22.0"

View File

@@ -40,12 +40,12 @@ dependencies:
flutter_riverpod: ^2.5.1
quiver: ^3.2.1
flutter_login: ^5.0.0
percent_indicator: ^4.2.3
intl: ^0.19.0
flutter_adaptive_scaffold: ^0.1.11+1
flutter_form_builder: ^9.3.0
form_builder_validators: ^11.0.0
url_launcher: ^6.3.0
timeago: ^3.7.0
dev_dependencies:
flutter_test: