Compare commits

...

75 Commits

Author SHA1 Message Date
Simon Ding
60110f4ca6 feat: add db extra fields 2024-08-24 21:03:08 +08:00
Simon Ding
b7ca02429c chore: jav name suggest 2024-08-19 17:45:34 +08:00
Simon Ding
ff63084014 feat: better jav search support 2024-08-19 17:39:37 +08:00
Simon Ding
821d6859ff feat: option to enable adult content 2024-08-19 16:39:34 +08:00
Simon Ding
10e6e99990 update readme 2024-08-16 11:49:23 +08:00
Simon Ding
23a5997814 fix: episode status 2024-08-13 11:27:54 +08:00
Simon Ding
b487c81865 feat: cache errored request 2024-08-13 11:05:46 +08:00
Simon Ding
32914344d1 fix: remove seeding torrent status not right 2024-08-13 10:57:04 +08:00
Simon Ding
644c9ed228 feat: marshal indented 2024-08-13 10:41:40 +08:00
Simon Ding
d3ad80380f feat: nfo support frontend 2024-08-13 10:17:46 +08:00
Simon Ding
19c6308a81 feat: nfo support backend 2024-08-13 10:05:38 +08:00
Simon Ding
7017f32fe3 feat: nfo support backend 2024-08-13 10:02:34 +08:00
Simon Ding
02a23f13f9 fix: mkdir 2024-08-13 00:11:27 +08:00
Simon Ding
cc211a89a4 fix: dir not exist 2024-08-12 23:06:51 +08:00
Simon Ding
4800e6c79d chore: update 2024-08-12 22:57:21 +08:00
Simon Ding
b5f0b28c61 fix 2024-08-12 22:44:36 +08:00
Simon Ding
081338df24 feat: code refactor and support season pack write .plexmatch file 2024-08-12 22:19:57 +08:00
Simon Ding
9632ca45b3 fix: match logic 2024-08-12 20:59:31 +08:00
Simon Ding
b948bff497 chore: if imdbid match no need check name 2024-08-12 19:02:43 +08:00
Simon Ding
29383cf75c feat: should match imdbid if present 2024-08-12 18:47:38 +08:00
Simon Ding
57ec0b9eb9 fix: download series all 2024-08-12 18:13:34 +08:00
Simon Ding
0cce4ffee0 add button to appbar 2024-08-12 14:53:23 +08:00
Simon Ding
5c01c45068 feat: fliter audios 2024-08-12 14:23:20 +08:00
Simon Ding
712bf84c90 feat: add app icon 2024-08-12 14:23:09 +08:00
Simon Ding
fdb63a8459 fix 2024-08-12 10:28:28 +08:00
Simon Ding
990d9dab08 update image 2024-08-12 10:27:20 +08:00
Simon Ding
da863588e4 feat: show snakebar 2024-08-12 10:23:28 +08:00
Simon Ding
09ff67fef7 feat: download per media feature 2024-08-12 10:16:36 +08:00
Simon Ding
3c37948798 ui: change icon 2024-08-11 23:42:43 +08:00
Simon Ding
6fd39d818c feat: better seeding status 2024-08-11 23:09:34 +08:00
Simon Ding
a0e211c328 fix: activity 2024-08-11 22:44:52 +08:00
Simon Ding
27d8b1672a feat: show seed as active 2024-08-11 22:40:38 +08:00
Simon Ding
349e394e8e chore: updates 2024-08-11 22:06:54 +08:00
Simon Ding
620f085ca5 add log 2024-08-11 20:54:12 +08:00
Simon Ding
5b70badb50 feat: add seed ratio display 2024-08-11 20:41:26 +08:00
Simon Ding
5c6ac2c430 fix: movie target dir 2024-08-11 20:19:51 +08:00
Simon Ding
365cfddf8f change icon 2024-08-11 19:20:23 +08:00
Simon Ding
6c26812b92 feat: filter resources that is qiangban 2024-08-11 19:18:27 +08:00
Simon Ding
0057a75a95 feat: find season pack first 2024-08-11 18:06:50 +08:00
Simon Ding
f110f257d4 code refactor and add season pack size limit 2024-08-11 17:40:01 +08:00
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
66 changed files with 2523 additions and 713 deletions

View File

@@ -14,7 +14,11 @@ Polaris 是一个电视剧和电影的追踪软件。配置好了之后,当剧
交流群: https://t.me/+8R2nzrlSs2JhMDgx
## 功能
## 快速开始
使用此程序参考 [【快速开始】](https://simonding.gitbook.io/polaris/quick_start)
## Features
- [x] 电视剧自动追踪下载
- [x] 电影自动追踪下载
@@ -23,17 +27,17 @@ Polaris 是一个电视剧和电影的追踪软件。配置好了之后,当剧
- [x] 后台代理支持
- [x] 用户认证
- [x] plex 刮削支持
- [x] NFO 刮削文件支持
- [x] BT/PT 支持
- [x] and more...
## Todos
- [] qbittorrent客户端支持
- [] 更多通知客户端支持
- [] 第三方watchlist导入支持
- [ ] qbittorrent客户端支持
- [ ] 更多通知客户端支持
- [ ] 第三方watchlist导入支持
- [ ] 手机客户端
## 使用
使用此程序参考 [【快速开始】](./doc/quick_start.md)
## 原理

View File

@@ -3,27 +3,30 @@ package db
var Version = "undefined"
const (
SettingTmdbApiKey = "tmdb_api_key"
SettingLanguage = "language"
SettingJacketUrl = "jacket_url"
SettingJacketApiKey = "jacket_api_key"
SettingDownloadDir = "download_dir"
SettingLogLevel = "log_level"
SettingProxy = "proxy"
SettingPlexMatchEnabled = "plexmatch_enabled"
SettingTmdbApiKey = "tmdb_api_key"
SettingLanguage = "language"
SettingJacketUrl = "jacket_url"
SettingJacketApiKey = "jacket_api_key"
SettingDownloadDir = "download_dir"
SettingLogLevel = "log_level"
SettingProxy = "proxy"
SettingPlexMatchEnabled = "plexmatch_enabled"
SettingNfoSupportEnabled = "nfo_support_enabled"
SettingAllowQiangban = "filter_qiangban"
SettingEnableTmdbAdultContent = "tmdb_adult_content"
)
const (
SettingAuthEnabled = "auth_enbled"
SettingUsername = "auth_username"
SettingPassword = "auth_password"
SettingUsername = "auth_username"
SettingPassword = "auth_password"
)
const (
IndexerTorznabImpl = "torznab"
DataPath = "./data"
ImgPath = DataPath + "/img"
LogPath = DataPath + "/logs"
DataPath = "./data"
ImgPath = DataPath + "/img"
LogPath = DataPath + "/logs"
)
const (
@@ -33,4 +36,4 @@ const (
type ResolutionType string
const JwtSerectKey = "jwt_secrect_key"
const JwtSerectKey = "jwt_secrect_key"

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).
@@ -148,6 +150,7 @@ func (c *Client) AddMediaWatchlist(m *ent.Media, episodes []int) (*ent.Media, er
SetTargetDir(m.TargetDir).
SetDownloadHistoryEpisodes(m.DownloadHistoryEpisodes).
SetLimiter(m.Limiter).
SetExtras(m.Extras).
AddEpisodeIDs(episodes...).
Save(context.TODO())
return r, err
@@ -249,7 +252,6 @@ type TorznabSetting struct {
ApiKey string `json:"api_key"`
}
func (c *Client) SaveIndexer(in *ent.Indexers) error {
if in.ID != 0 {
@@ -265,7 +267,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 +287,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 +310,7 @@ func (c *Client) GetAllTorznabInfo() []*TorznabInfo {
continue
}
l = append(l, &TorznabInfo{
Indexers: r,
Indexers: r,
TorznabSetting: ss,
})
}
@@ -356,7 +359,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 +374,6 @@ func (s *StorageInfo) ToWebDavSetting() WebdavSetting {
}
}
type WebdavSetting struct {
URL string `json:"url"`
User string `json:"user"`
@@ -472,8 +474,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 {
@@ -490,7 +492,7 @@ func (c *Client) GetHistories() ent.Histories {
func (c *Client) GetRunningHistories() ent.Histories {
h, err := c.ent.History.Query().Where(history.Or(history.StatusEQ(history.StatusRunning),
history.StatusEQ(history.StatusUploading))).All(context.TODO())
history.StatusEQ(history.StatusUploading), history.StatusEQ(history.StatusSeeding))).All(context.TODO())
if err != nil {
return nil
}
@@ -555,7 +557,26 @@ 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())
}
func (c *Client) UpdateEpisodeTargetFile(id int, filename string) error {
return c.ent.Episode.Update().Where(episode.ID(id)).SetTargetFile(filename).Exec(context.Background())
}
func (c *Client) GetSeasonEpisodes(mediaId, seasonNum int) ([]*ent.Episode, error) {
return c.ent.Episode.Query().Where(episode.MediaID(mediaId), episode.SeasonNumber(seasonNum)).All(context.Background())
}

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 MiB

After

Width:  |  Height:  |  Size: 2.6 MiB

View File

@@ -33,6 +33,8 @@ type Episode struct {
Status episode.Status `json:"status,omitempty"`
// Monitored holds the value of the "monitored" field.
Monitored bool `json:"monitored"`
// TargetFile holds the value of the "target_file" field.
TargetFile string `json:"target_file,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the EpisodeQuery when eager-loading is set.
Edges EpisodeEdges `json:"edges"`
@@ -68,7 +70,7 @@ func (*Episode) scanValues(columns []string) ([]any, error) {
values[i] = new(sql.NullBool)
case episode.FieldID, episode.FieldMediaID, episode.FieldSeasonNumber, episode.FieldEpisodeNumber:
values[i] = new(sql.NullInt64)
case episode.FieldTitle, episode.FieldOverview, episode.FieldAirDate, episode.FieldStatus:
case episode.FieldTitle, episode.FieldOverview, episode.FieldAirDate, episode.FieldStatus, episode.FieldTargetFile:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
@@ -139,6 +141,12 @@ func (e *Episode) assignValues(columns []string, values []any) error {
} else if value.Valid {
e.Monitored = value.Bool
}
case episode.FieldTargetFile:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field target_file", values[i])
} else if value.Valid {
e.TargetFile = value.String
}
default:
e.selectValues.Set(columns[i], values[i])
}
@@ -203,6 +211,9 @@ func (e *Episode) String() string {
builder.WriteString(", ")
builder.WriteString("monitored=")
builder.WriteString(fmt.Sprintf("%v", e.Monitored))
builder.WriteString(", ")
builder.WriteString("target_file=")
builder.WriteString(e.TargetFile)
builder.WriteByte(')')
return builder.String()
}

View File

@@ -30,6 +30,8 @@ const (
FieldStatus = "status"
// FieldMonitored holds the string denoting the monitored field in the database.
FieldMonitored = "monitored"
// FieldTargetFile holds the string denoting the target_file field in the database.
FieldTargetFile = "target_file"
// EdgeMedia holds the string denoting the media edge name in mutations.
EdgeMedia = "media"
// Table holds the table name of the episode in the database.
@@ -54,6 +56,7 @@ var Columns = []string{
FieldAirDate,
FieldStatus,
FieldMonitored,
FieldTargetFile,
}
// ValidColumn reports if the column name is valid (part of the table columns).
@@ -146,6 +149,11 @@ func ByMonitored(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldMonitored, opts...).ToFunc()
}
// ByTargetFile orders the results by the target_file field.
func ByTargetFile(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldTargetFile, opts...).ToFunc()
}
// ByMediaField orders the results by media field.
func ByMediaField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {

View File

@@ -89,6 +89,11 @@ func Monitored(v bool) predicate.Episode {
return predicate.Episode(sql.FieldEQ(FieldMonitored, v))
}
// TargetFile applies equality check predicate on the "target_file" field. It's identical to TargetFileEQ.
func TargetFile(v string) predicate.Episode {
return predicate.Episode(sql.FieldEQ(FieldTargetFile, v))
}
// MediaIDEQ applies the EQ predicate on the "media_id" field.
func MediaIDEQ(v int) predicate.Episode {
return predicate.Episode(sql.FieldEQ(FieldMediaID, v))
@@ -424,6 +429,81 @@ func MonitoredNEQ(v bool) predicate.Episode {
return predicate.Episode(sql.FieldNEQ(FieldMonitored, v))
}
// TargetFileEQ applies the EQ predicate on the "target_file" field.
func TargetFileEQ(v string) predicate.Episode {
return predicate.Episode(sql.FieldEQ(FieldTargetFile, v))
}
// TargetFileNEQ applies the NEQ predicate on the "target_file" field.
func TargetFileNEQ(v string) predicate.Episode {
return predicate.Episode(sql.FieldNEQ(FieldTargetFile, v))
}
// TargetFileIn applies the In predicate on the "target_file" field.
func TargetFileIn(vs ...string) predicate.Episode {
return predicate.Episode(sql.FieldIn(FieldTargetFile, vs...))
}
// TargetFileNotIn applies the NotIn predicate on the "target_file" field.
func TargetFileNotIn(vs ...string) predicate.Episode {
return predicate.Episode(sql.FieldNotIn(FieldTargetFile, vs...))
}
// TargetFileGT applies the GT predicate on the "target_file" field.
func TargetFileGT(v string) predicate.Episode {
return predicate.Episode(sql.FieldGT(FieldTargetFile, v))
}
// TargetFileGTE applies the GTE predicate on the "target_file" field.
func TargetFileGTE(v string) predicate.Episode {
return predicate.Episode(sql.FieldGTE(FieldTargetFile, v))
}
// TargetFileLT applies the LT predicate on the "target_file" field.
func TargetFileLT(v string) predicate.Episode {
return predicate.Episode(sql.FieldLT(FieldTargetFile, v))
}
// TargetFileLTE applies the LTE predicate on the "target_file" field.
func TargetFileLTE(v string) predicate.Episode {
return predicate.Episode(sql.FieldLTE(FieldTargetFile, v))
}
// TargetFileContains applies the Contains predicate on the "target_file" field.
func TargetFileContains(v string) predicate.Episode {
return predicate.Episode(sql.FieldContains(FieldTargetFile, v))
}
// TargetFileHasPrefix applies the HasPrefix predicate on the "target_file" field.
func TargetFileHasPrefix(v string) predicate.Episode {
return predicate.Episode(sql.FieldHasPrefix(FieldTargetFile, v))
}
// TargetFileHasSuffix applies the HasSuffix predicate on the "target_file" field.
func TargetFileHasSuffix(v string) predicate.Episode {
return predicate.Episode(sql.FieldHasSuffix(FieldTargetFile, v))
}
// TargetFileIsNil applies the IsNil predicate on the "target_file" field.
func TargetFileIsNil() predicate.Episode {
return predicate.Episode(sql.FieldIsNull(FieldTargetFile))
}
// TargetFileNotNil applies the NotNil predicate on the "target_file" field.
func TargetFileNotNil() predicate.Episode {
return predicate.Episode(sql.FieldNotNull(FieldTargetFile))
}
// TargetFileEqualFold applies the EqualFold predicate on the "target_file" field.
func TargetFileEqualFold(v string) predicate.Episode {
return predicate.Episode(sql.FieldEqualFold(FieldTargetFile, v))
}
// TargetFileContainsFold applies the ContainsFold predicate on the "target_file" field.
func TargetFileContainsFold(v string) predicate.Episode {
return predicate.Episode(sql.FieldContainsFold(FieldTargetFile, v))
}
// HasMedia applies the HasEdge predicate on the "media" edge.
func HasMedia() predicate.Episode {
return predicate.Episode(func(s *sql.Selector) {

View File

@@ -92,6 +92,20 @@ func (ec *EpisodeCreate) SetNillableMonitored(b *bool) *EpisodeCreate {
return ec
}
// SetTargetFile sets the "target_file" field.
func (ec *EpisodeCreate) SetTargetFile(s string) *EpisodeCreate {
ec.mutation.SetTargetFile(s)
return ec
}
// SetNillableTargetFile sets the "target_file" field if the given value is not nil.
func (ec *EpisodeCreate) SetNillableTargetFile(s *string) *EpisodeCreate {
if s != nil {
ec.SetTargetFile(*s)
}
return ec
}
// SetMedia sets the "media" edge to the Media entity.
func (ec *EpisodeCreate) SetMedia(m *Media) *EpisodeCreate {
return ec.SetMediaID(m.ID)
@@ -224,6 +238,10 @@ func (ec *EpisodeCreate) createSpec() (*Episode, *sqlgraph.CreateSpec) {
_spec.SetField(episode.FieldMonitored, field.TypeBool, value)
_node.Monitored = value
}
if value, ok := ec.mutation.TargetFile(); ok {
_spec.SetField(episode.FieldTargetFile, field.TypeString, value)
_node.TargetFile = value
}
if nodes := ec.mutation.MediaIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,

View File

@@ -160,6 +160,26 @@ func (eu *EpisodeUpdate) SetNillableMonitored(b *bool) *EpisodeUpdate {
return eu
}
// SetTargetFile sets the "target_file" field.
func (eu *EpisodeUpdate) SetTargetFile(s string) *EpisodeUpdate {
eu.mutation.SetTargetFile(s)
return eu
}
// SetNillableTargetFile sets the "target_file" field if the given value is not nil.
func (eu *EpisodeUpdate) SetNillableTargetFile(s *string) *EpisodeUpdate {
if s != nil {
eu.SetTargetFile(*s)
}
return eu
}
// ClearTargetFile clears the value of the "target_file" field.
func (eu *EpisodeUpdate) ClearTargetFile() *EpisodeUpdate {
eu.mutation.ClearTargetFile()
return eu
}
// SetMedia sets the "media" edge to the Media entity.
func (eu *EpisodeUpdate) SetMedia(m *Media) *EpisodeUpdate {
return eu.SetMediaID(m.ID)
@@ -252,6 +272,12 @@ func (eu *EpisodeUpdate) sqlSave(ctx context.Context) (n int, err error) {
if value, ok := eu.mutation.Monitored(); ok {
_spec.SetField(episode.FieldMonitored, field.TypeBool, value)
}
if value, ok := eu.mutation.TargetFile(); ok {
_spec.SetField(episode.FieldTargetFile, field.TypeString, value)
}
if eu.mutation.TargetFileCleared() {
_spec.ClearField(episode.FieldTargetFile, field.TypeString)
}
if eu.mutation.MediaCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
@@ -433,6 +459,26 @@ func (euo *EpisodeUpdateOne) SetNillableMonitored(b *bool) *EpisodeUpdateOne {
return euo
}
// SetTargetFile sets the "target_file" field.
func (euo *EpisodeUpdateOne) SetTargetFile(s string) *EpisodeUpdateOne {
euo.mutation.SetTargetFile(s)
return euo
}
// SetNillableTargetFile sets the "target_file" field if the given value is not nil.
func (euo *EpisodeUpdateOne) SetNillableTargetFile(s *string) *EpisodeUpdateOne {
if s != nil {
euo.SetTargetFile(*s)
}
return euo
}
// ClearTargetFile clears the value of the "target_file" field.
func (euo *EpisodeUpdateOne) ClearTargetFile() *EpisodeUpdateOne {
euo.mutation.ClearTargetFile()
return euo
}
// SetMedia sets the "media" edge to the Media entity.
func (euo *EpisodeUpdateOne) SetMedia(m *Media) *EpisodeUpdateOne {
return euo.SetMediaID(m.ID)
@@ -555,6 +601,12 @@ func (euo *EpisodeUpdateOne) sqlSave(ctx context.Context) (_node *Episode, err e
if value, ok := euo.mutation.Monitored(); ok {
_spec.SetField(episode.FieldMonitored, field.TypeBool, value)
}
if value, ok := euo.mutation.TargetFile(); ok {
_spec.SetField(episode.FieldTargetFile, field.TypeString, value)
}
if euo.mutation.TargetFileCleared() {
_spec.ClearField(episode.FieldTargetFile, field.TypeString)
}
if euo.mutation.MediaCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,

View File

@@ -76,6 +76,7 @@ const (
StatusSuccess Status = "success"
StatusFail Status = "fail"
StatusUploading Status = "uploading"
StatusSeeding Status = "seeding"
)
func (s Status) String() string {
@@ -85,7 +86,7 @@ func (s Status) String() string {
// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save.
func StatusValidator(s Status) error {
switch s {
case StatusRunning, StatusSuccess, StatusFail, StatusUploading:
case StatusRunning, StatusSuccess, StatusFail, StatusUploading, StatusSeeding:
return nil
default:
return fmt.Errorf("history: invalid enum value for status field: %q", s)

View File

@@ -46,7 +46,9 @@ 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"`
// Extras holds the value of the "extras" field.
Extras schema.MediaExtras `json:"extras,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"`
@@ -76,7 +78,7 @@ func (*Media) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case media.FieldLimiter:
case media.FieldLimiter, media.FieldExtras:
values[i] = new([]byte)
case media.FieldDownloadHistoryEpisodes:
values[i] = new(sql.NullBool)
@@ -193,6 +195,14 @@ func (m *Media) assignValues(columns []string, values []any) error {
return fmt.Errorf("unmarshal field limiter: %w", err)
}
}
case media.FieldExtras:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field extras", values[i])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &m.Extras); err != nil {
return fmt.Errorf("unmarshal field extras: %w", err)
}
}
default:
m.selectValues.Set(columns[i], values[i])
}
@@ -275,6 +285,9 @@ func (m *Media) String() string {
builder.WriteString(", ")
builder.WriteString("limiter=")
builder.WriteString(fmt.Sprintf("%v", m.Limiter))
builder.WriteString(", ")
builder.WriteString("extras=")
builder.WriteString(fmt.Sprintf("%v", m.Extras))
builder.WriteByte(')')
return builder.String()
}

View File

@@ -43,6 +43,8 @@ const (
FieldDownloadHistoryEpisodes = "download_history_episodes"
// FieldLimiter holds the string denoting the limiter field in the database.
FieldLimiter = "limiter"
// FieldExtras holds the string denoting the extras field in the database.
FieldExtras = "extras"
// EdgeEpisodes holds the string denoting the episodes edge name in mutations.
EdgeEpisodes = "episodes"
// Table holds the table name of the media in the database.
@@ -73,6 +75,7 @@ var Columns = []string{
FieldTargetDir,
FieldDownloadHistoryEpisodes,
FieldLimiter,
FieldExtras,
}
// ValidColumn reports if the column name is valid (part of the table columns).

View File

@@ -785,6 +785,16 @@ func LimiterNotNil() predicate.Media {
return predicate.Media(sql.FieldNotNull(FieldLimiter))
}
// ExtrasIsNil applies the IsNil predicate on the "extras" field.
func ExtrasIsNil() predicate.Media {
return predicate.Media(sql.FieldIsNull(FieldExtras))
}
// ExtrasNotNil applies the NotNil predicate on the "extras" field.
func ExtrasNotNil() predicate.Media {
return predicate.Media(sql.FieldNotNull(FieldExtras))
}
// HasEpisodes applies the HasEdge predicate on the "episodes" edge.
func HasEpisodes() predicate.Media {
return predicate.Media(func(s *sql.Selector) {

View File

@@ -157,11 +157,33 @@ 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
}
// SetExtras sets the "extras" field.
func (mc *MediaCreate) SetExtras(se schema.MediaExtras) *MediaCreate {
mc.mutation.SetExtras(se)
return mc
}
// SetNillableExtras sets the "extras" field if the given value is not nil.
func (mc *MediaCreate) SetNillableExtras(se *schema.MediaExtras) *MediaCreate {
if se != nil {
mc.SetExtras(*se)
}
return mc
}
// AddEpisodeIDs adds the "episodes" edge to the Episode entity by IDs.
func (mc *MediaCreate) AddEpisodeIDs(ids ...int) *MediaCreate {
mc.mutation.AddEpisodeIDs(ids...)
@@ -351,6 +373,10 @@ func (mc *MediaCreate) createSpec() (*Media, *sqlgraph.CreateSpec) {
_spec.SetField(media.FieldLimiter, field.TypeJSON, value)
_node.Limiter = value
}
if value, ok := mc.mutation.Extras(); ok {
_spec.SetField(media.FieldExtras, field.TypeJSON, value)
_node.Extras = value
}
if nodes := mc.mutation.EpisodesIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,

View File

@@ -251,17 +251,45 @@ 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()
return mu
}
// SetExtras sets the "extras" field.
func (mu *MediaUpdate) SetExtras(se schema.MediaExtras) *MediaUpdate {
mu.mutation.SetExtras(se)
return mu
}
// SetNillableExtras sets the "extras" field if the given value is not nil.
func (mu *MediaUpdate) SetNillableExtras(se *schema.MediaExtras) *MediaUpdate {
if se != nil {
mu.SetExtras(*se)
}
return mu
}
// ClearExtras clears the value of the "extras" field.
func (mu *MediaUpdate) ClearExtras() *MediaUpdate {
mu.mutation.ClearExtras()
return mu
}
// AddEpisodeIDs adds the "episodes" edge to the Episode entity by IDs.
func (mu *MediaUpdate) AddEpisodeIDs(ids ...int) *MediaUpdate {
mu.mutation.AddEpisodeIDs(ids...)
@@ -420,6 +448,12 @@ func (mu *MediaUpdate) sqlSave(ctx context.Context) (n int, err error) {
if mu.mutation.LimiterCleared() {
_spec.ClearField(media.FieldLimiter, field.TypeJSON)
}
if value, ok := mu.mutation.Extras(); ok {
_spec.SetField(media.FieldExtras, field.TypeJSON, value)
}
if mu.mutation.ExtrasCleared() {
_spec.ClearField(media.FieldExtras, field.TypeJSON)
}
if mu.mutation.EpisodesCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
@@ -706,17 +740,45 @@ 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()
return muo
}
// SetExtras sets the "extras" field.
func (muo *MediaUpdateOne) SetExtras(se schema.MediaExtras) *MediaUpdateOne {
muo.mutation.SetExtras(se)
return muo
}
// SetNillableExtras sets the "extras" field if the given value is not nil.
func (muo *MediaUpdateOne) SetNillableExtras(se *schema.MediaExtras) *MediaUpdateOne {
if se != nil {
muo.SetExtras(*se)
}
return muo
}
// ClearExtras clears the value of the "extras" field.
func (muo *MediaUpdateOne) ClearExtras() *MediaUpdateOne {
muo.mutation.ClearExtras()
return muo
}
// AddEpisodeIDs adds the "episodes" edge to the Episode entity by IDs.
func (muo *MediaUpdateOne) AddEpisodeIDs(ids ...int) *MediaUpdateOne {
muo.mutation.AddEpisodeIDs(ids...)
@@ -905,6 +967,12 @@ func (muo *MediaUpdateOne) sqlSave(ctx context.Context) (_node *Media, err error
if muo.mutation.LimiterCleared() {
_spec.ClearField(media.FieldLimiter, field.TypeJSON)
}
if value, ok := muo.mutation.Extras(); ok {
_spec.SetField(media.FieldExtras, field.TypeJSON, value)
}
if muo.mutation.ExtrasCleared() {
_spec.ClearField(media.FieldExtras, field.TypeJSON)
}
if muo.mutation.EpisodesCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,

View File

@@ -39,6 +39,7 @@ var (
{Name: "air_date", Type: field.TypeString},
{Name: "status", Type: field.TypeEnum, Enums: []string{"missing", "downloading", "downloaded"}, Default: "missing"},
{Name: "monitored", Type: field.TypeBool, Default: false},
{Name: "target_file", Type: field.TypeString, Nullable: true},
{Name: "media_id", Type: field.TypeInt, Nullable: true},
}
// EpisodesTable holds the schema information for the "episodes" table.
@@ -49,7 +50,7 @@ var (
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "episodes_media_episodes",
Columns: []*schema.Column{EpisodesColumns[8]},
Columns: []*schema.Column{EpisodesColumns[9]},
RefColumns: []*schema.Column{MediaColumns[0]},
OnDelete: schema.SetNull,
},
@@ -66,7 +67,7 @@ var (
{Name: "size", Type: field.TypeInt, Default: 0},
{Name: "download_client_id", Type: field.TypeInt, Nullable: true},
{Name: "indexer_id", Type: field.TypeInt, Nullable: true},
{Name: "status", Type: field.TypeEnum, Enums: []string{"running", "success", "fail", "uploading"}},
{Name: "status", Type: field.TypeEnum, Enums: []string{"running", "success", "fail", "uploading", "seeding"}},
{Name: "saved", Type: field.TypeString, Nullable: true},
}
// HistoriesTable holds the schema information for the "histories" table.
@@ -109,6 +110,7 @@ var (
{Name: "target_dir", Type: field.TypeString, Nullable: true},
{Name: "download_history_episodes", Type: field.TypeBool, Nullable: true, Default: false},
{Name: "limiter", Type: field.TypeJSON, Nullable: true},
{Name: "extras", Type: field.TypeJSON, Nullable: true},
}
// MediaTable holds the schema information for the "media" table.
MediaTable = &schema.Table{

View File

@@ -923,6 +923,7 @@ type EpisodeMutation struct {
air_date *string
status *episode.Status
monitored *bool
target_file *string
clearedFields map[string]struct{}
media *int
clearedmedia bool
@@ -1370,6 +1371,55 @@ func (m *EpisodeMutation) ResetMonitored() {
m.monitored = nil
}
// SetTargetFile sets the "target_file" field.
func (m *EpisodeMutation) SetTargetFile(s string) {
m.target_file = &s
}
// TargetFile returns the value of the "target_file" field in the mutation.
func (m *EpisodeMutation) TargetFile() (r string, exists bool) {
v := m.target_file
if v == nil {
return
}
return *v, true
}
// OldTargetFile returns the old "target_file" field's value of the Episode entity.
// If the Episode 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 *EpisodeMutation) OldTargetFile(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldTargetFile is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldTargetFile requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldTargetFile: %w", err)
}
return oldValue.TargetFile, nil
}
// ClearTargetFile clears the value of the "target_file" field.
func (m *EpisodeMutation) ClearTargetFile() {
m.target_file = nil
m.clearedFields[episode.FieldTargetFile] = struct{}{}
}
// TargetFileCleared returns if the "target_file" field was cleared in this mutation.
func (m *EpisodeMutation) TargetFileCleared() bool {
_, ok := m.clearedFields[episode.FieldTargetFile]
return ok
}
// ResetTargetFile resets all changes to the "target_file" field.
func (m *EpisodeMutation) ResetTargetFile() {
m.target_file = nil
delete(m.clearedFields, episode.FieldTargetFile)
}
// ClearMedia clears the "media" edge to the Media entity.
func (m *EpisodeMutation) ClearMedia() {
m.clearedmedia = true
@@ -1431,7 +1481,7 @@ func (m *EpisodeMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *EpisodeMutation) Fields() []string {
fields := make([]string, 0, 8)
fields := make([]string, 0, 9)
if m.media != nil {
fields = append(fields, episode.FieldMediaID)
}
@@ -1456,6 +1506,9 @@ func (m *EpisodeMutation) Fields() []string {
if m.monitored != nil {
fields = append(fields, episode.FieldMonitored)
}
if m.target_file != nil {
fields = append(fields, episode.FieldTargetFile)
}
return fields
}
@@ -1480,6 +1533,8 @@ func (m *EpisodeMutation) Field(name string) (ent.Value, bool) {
return m.Status()
case episode.FieldMonitored:
return m.Monitored()
case episode.FieldTargetFile:
return m.TargetFile()
}
return nil, false
}
@@ -1505,6 +1560,8 @@ func (m *EpisodeMutation) OldField(ctx context.Context, name string) (ent.Value,
return m.OldStatus(ctx)
case episode.FieldMonitored:
return m.OldMonitored(ctx)
case episode.FieldTargetFile:
return m.OldTargetFile(ctx)
}
return nil, fmt.Errorf("unknown Episode field %s", name)
}
@@ -1570,6 +1627,13 @@ func (m *EpisodeMutation) SetField(name string, value ent.Value) error {
}
m.SetMonitored(v)
return nil
case episode.FieldTargetFile:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetTargetFile(v)
return nil
}
return fmt.Errorf("unknown Episode field %s", name)
}
@@ -1630,6 +1694,9 @@ func (m *EpisodeMutation) ClearedFields() []string {
if m.FieldCleared(episode.FieldMediaID) {
fields = append(fields, episode.FieldMediaID)
}
if m.FieldCleared(episode.FieldTargetFile) {
fields = append(fields, episode.FieldTargetFile)
}
return fields
}
@@ -1647,6 +1714,9 @@ func (m *EpisodeMutation) ClearField(name string) error {
case episode.FieldMediaID:
m.ClearMediaID()
return nil
case episode.FieldTargetFile:
m.ClearTargetFile()
return nil
}
return fmt.Errorf("unknown Episode nullable field %s", name)
}
@@ -1679,6 +1749,9 @@ func (m *EpisodeMutation) ResetField(name string) error {
case episode.FieldMonitored:
m.ResetMonitored()
return nil
case episode.FieldTargetFile:
m.ResetTargetFile()
return nil
}
return fmt.Errorf("unknown Episode field %s", name)
}
@@ -3601,7 +3674,8 @@ type MediaMutation struct {
addstorage_id *int
target_dir *string
download_history_episodes *bool
limiter **schema.MediaLimiter
limiter *schema.MediaLimiter
extras *schema.MediaExtras
clearedFields map[string]struct{}
episodes map[int]struct{}
removedepisodes map[int]struct{}
@@ -4271,12 +4345,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 +4361,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")
}
@@ -4319,6 +4393,55 @@ func (m *MediaMutation) ResetLimiter() {
delete(m.clearedFields, media.FieldLimiter)
}
// SetExtras sets the "extras" field.
func (m *MediaMutation) SetExtras(se schema.MediaExtras) {
m.extras = &se
}
// Extras returns the value of the "extras" field in the mutation.
func (m *MediaMutation) Extras() (r schema.MediaExtras, exists bool) {
v := m.extras
if v == nil {
return
}
return *v, true
}
// OldExtras returns the old "extras" 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) OldExtras(ctx context.Context) (v schema.MediaExtras, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldExtras is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldExtras requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldExtras: %w", err)
}
return oldValue.Extras, nil
}
// ClearExtras clears the value of the "extras" field.
func (m *MediaMutation) ClearExtras() {
m.extras = nil
m.clearedFields[media.FieldExtras] = struct{}{}
}
// ExtrasCleared returns if the "extras" field was cleared in this mutation.
func (m *MediaMutation) ExtrasCleared() bool {
_, ok := m.clearedFields[media.FieldExtras]
return ok
}
// ResetExtras resets all changes to the "extras" field.
func (m *MediaMutation) ResetExtras() {
m.extras = nil
delete(m.clearedFields, media.FieldExtras)
}
// AddEpisodeIDs adds the "episodes" edge to the Episode entity by ids.
func (m *MediaMutation) AddEpisodeIDs(ids ...int) {
if m.episodes == nil {
@@ -4407,7 +4530,7 @@ func (m *MediaMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *MediaMutation) Fields() []string {
fields := make([]string, 0, 14)
fields := make([]string, 0, 15)
if m.tmdb_id != nil {
fields = append(fields, media.FieldTmdbID)
}
@@ -4450,6 +4573,9 @@ func (m *MediaMutation) Fields() []string {
if m.limiter != nil {
fields = append(fields, media.FieldLimiter)
}
if m.extras != nil {
fields = append(fields, media.FieldExtras)
}
return fields
}
@@ -4486,6 +4612,8 @@ func (m *MediaMutation) Field(name string) (ent.Value, bool) {
return m.DownloadHistoryEpisodes()
case media.FieldLimiter:
return m.Limiter()
case media.FieldExtras:
return m.Extras()
}
return nil, false
}
@@ -4523,6 +4651,8 @@ func (m *MediaMutation) OldField(ctx context.Context, name string) (ent.Value, e
return m.OldDownloadHistoryEpisodes(ctx)
case media.FieldLimiter:
return m.OldLimiter(ctx)
case media.FieldExtras:
return m.OldExtras(ctx)
}
return nil, fmt.Errorf("unknown Media field %s", name)
}
@@ -4624,12 +4754,19 @@ 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)
}
m.SetLimiter(v)
return nil
case media.FieldExtras:
v, ok := value.(schema.MediaExtras)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetExtras(v)
return nil
}
return fmt.Errorf("unknown Media field %s", name)
}
@@ -4702,6 +4839,9 @@ func (m *MediaMutation) ClearedFields() []string {
if m.FieldCleared(media.FieldLimiter) {
fields = append(fields, media.FieldLimiter)
}
if m.FieldCleared(media.FieldExtras) {
fields = append(fields, media.FieldExtras)
}
return fields
}
@@ -4731,6 +4871,9 @@ func (m *MediaMutation) ClearField(name string) error {
case media.FieldLimiter:
m.ClearLimiter()
return nil
case media.FieldExtras:
m.ClearExtras()
return nil
}
return fmt.Errorf("unknown Media nullable field %s", name)
}
@@ -4781,6 +4924,9 @@ func (m *MediaMutation) ResetField(name string) error {
case media.FieldLimiter:
m.ResetLimiter()
return nil
case media.FieldExtras:
m.ResetExtras()
return nil
}
return fmt.Errorf("unknown Media field %s", name)
}

View File

@@ -22,16 +22,17 @@ func (Episode) Fields() []ent.Field {
field.String("air_date"),
field.Enum("status").Values("missing", "downloading", "downloaded").Default("missing"),
field.Bool("monitored").Default(false).StructTag("json:\"monitored\""), //whether this episode is monitored
field.String("target_file").Optional(),
}
}
// Edges of the Episode.
func (Episode) Edges() []ent.Edge {
return []ent.Edge{
edge.From("media", Media.Type).
Ref("episodes").
Unique().
edge.From("media", Media.Type).
Ref("episodes").
Unique().
Field("media_id"),
}
}
}

View File

@@ -21,7 +21,7 @@ func (History) Fields() []ent.Field {
field.Int("size").Default(0),
field.Int("download_client_id").Optional(),
field.Int("indexer_id").Optional(),
field.Enum("status").Values("running", "success", "fail", "uploading"),
field.Enum("status").Values("running", "success", "fail", "uploading", "seeding"),
field.String("saved").Optional(),
}
}

View File

@@ -29,7 +29,8 @@ 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(),
field.JSON("extras", MediaExtras{}).Optional(),
}
}
@@ -41,6 +42,21 @@ 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
}
type MediaExtras struct {
IsAdultMovie bool `json:"is_adult_movie"`
JavId string `json:"javid"`
//OriginCountry []string `json:"origin_country"`
OriginalLanguage string `json:"original_language"`
Genres []struct {
ID int64 `json:"id"`
Name string `json:"name"`
} `json:"genres"`
}
func (m *MediaExtras) IsJav() bool {
return m.IsAdultMovie && m.JavId != ""
}

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

4
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=

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,10 +8,10 @@ import (
)
type MovieMetadata struct {
NameEn string
NameCN string
Name string
Year int
Resolution string
IsQingban bool
}
func ParseMovie(name string) *MovieMetadata {
@@ -29,16 +29,44 @@ 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)
if len(resMatches) > 0 {
meta.Resolution = resMatches[0]
}
meta.IsQingban = isQiangban(name)
return meta
}
// https://en.wikipedia.org/wiki/Pirated_movie_release_types
func isQiangban(name string) bool {
qiangbanFilter := []string{"CAMRip","CAM-Rip", "CAM", "HDCAM", "TS","TSRip", "HDTS", "TELESYNC", "PDVD", "PreDVDRip", "TC", "HDTC", "TELECINE", "WP", "WORKPRINT"}
re := regexp.MustCompile(`\W`)
name = re.ReplaceAllString(strings.ToLower(name), " ")
fields := strings.Fields(name)
for _, q := range qiangbanFilter {
for _, f := range fields {
if strings.EqualFold(q, f) {
return true
}
}
}
return false
}

View File

@@ -99,5 +99,7 @@ func (l *LocalStorage) ReadFile(name string) ([]byte, error) {
}
func (l *LocalStorage) WriteFile(name string, data []byte) error {
return os.WriteFile(filepath.Join(l.dir, name), data, os.ModePerm)
path := filepath.Join(l.dir, name)
os.MkdirAll(filepath.Dir(path), os.ModePerm)
return os.WriteFile(path, data, os.ModePerm)
}

View File

@@ -15,9 +15,10 @@ import (
type Client struct {
apiKey string
tmdbClient *tmdb.Client
enableAdultContent bool
}
func NewClient(apiKey, proxyUrl string) (*Client, error) {
func NewClient(apiKey, proxyUrl string, enableAdultContent bool) (*Client, error) {
tmdbClient, err := tmdb.Init(apiKey)
if err != nil {
@@ -44,11 +45,12 @@ func NewClient(apiKey, proxyUrl string) (*Client, error) {
return &Client{
apiKey: apiKey,
tmdbClient: tmdbClient,
enableAdultContent: enableAdultContent,
}, nil
}
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 +60,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 +77,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) {
@@ -114,6 +116,9 @@ func (c *Client) SearchMedia(query string, lang string, page int) (*SearchResult
}
options := withLangOption(lang)
options["page"] = strconv.Itoa(page)
if c.enableAdultContent {
options["include_adult"] = "true"
}
res, err := c.tmdbClient.GetSearchMulti(query, options)
if err != nil {
return nil, errors.Wrap(err, "query imdb")
@@ -204,6 +209,11 @@ func (c *Client) GetTVAlternativeTitles(id int, language string) (*tmdb.TVAltern
return c.tmdbClient.GetTVAlternativeTitles(id, withLangOption(language))
}
func (c *Client) GetMovieAlternativeTitles(id int, language string) (*tmdb.MovieAlternativeTitles, error) {
return c.tmdbClient.GetMovieAlternativeTitles(id, withLangOption(language))
}
func wrapLanguage(lang string) string {
if lang == "" {
lang = "zh-CN"
@@ -211,6 +221,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,11 +3,13 @@ package torznab
import (
"context"
"encoding/xml"
"fmt"
"io"
"net/http"
"net/url"
"polaris/db"
"polaris/log"
"slices"
"strconv"
"time"
@@ -75,6 +77,9 @@ func (i *Item) GetAttr(key string) string {
func (r *Response) ToResults(indexer *db.TorznabInfo) []Result {
var res []Result
for _, item := range r.Channel.Item {
if slices.Contains(item.Category, "3000") { //exclude audio files
continue
}
r := Result{
Name: item.Title,
Link: item.Link,
@@ -82,6 +87,7 @@ func (r *Response) ToResults(indexer *db.TorznabInfo) []Result {
Seeders: mustAtoI(item.GetAttr("seeders")),
Peers: mustAtoI(item.GetAttr("peers")),
Category: mustAtoI(item.GetAttr("category")),
ImdbId: item.GetAttr("imdbid"),
DownloadVolumeFactor: tryParseFloat(item.GetAttr("downloadvolumefactor")),
UploadVolumeFactor: tryParseFloat(item.GetAttr("uploadvolumefactor")),
Source: indexer.Name,
@@ -112,7 +118,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,11 +127,26 @@ 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)
cacheRes, ok := cc.Get(key)
if !ok {
res, err := doRequest(req)
if err != nil {
cc.Set(key, &Response{})
return nil, errors.Wrap(err, "do http request")
}
cacheRes = res
cc.Set(key, cacheRes)
}
return cacheRes.ToResults(indexer), nil
}
func doRequest(req *http.Request) (*Response, error) {
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, errors.Wrap(err, "do http")
@@ -138,9 +159,9 @@ func Search(indexer *db.TorznabInfo, api, keyWord string) ([]Result, error) {
var res Response
err = xml.Unmarshal(data, &res)
if err != nil {
return nil, errors.Wrap(err, "json unmarshal")
return nil, errors.Wrapf(err, "xml unmarshal data: %v", string(data))
}
return res.ToResults(indexer), nil
return &res, nil
}
type Result struct {
@@ -156,4 +177,5 @@ type Result struct {
IndexerId int `json:"indexer_id"`
Priority int `json:"priority"`
IsPrivate bool `json:"is_private"`
ImdbId string `json:"imdb_id"`
}

View File

@@ -15,31 +15,41 @@ import (
type Activity struct {
*ent.History
Progress int `json:"progress"`
Progress int `json:"progress"`
SeedRatio float32 `json:"seed_ratio"`
}
func (s *Server) GetAllActivities(c *gin.Context) (interface{}, error) {
q := c.Query("status")
his := s.db.GetHistories()
var activities = make([]Activity, 0, len(his))
for _, h := range his {
if q == "active" && (h.Status != history.StatusRunning && h.Status != history.StatusUploading) {
continue //active downloads
} else if q == "archive" && (h.Status == history.StatusRunning || h.Status == history.StatusUploading) {
continue //archived downloads
}
a := Activity{
History: h,
}
for id, task := range s.core.GetTasks() {
if h.ID == id && task.Exists() {
a.Progress = task.Progress()
var activities = make([]Activity, 0)
if q == "active" {
his := s.db.GetRunningHistories()
for _, h := range his {
a := Activity{
History: h,
}
for id, task := range s.core.GetTasks() {
if h.ID == id && task.Exists() {
a.Progress = task.Progress()
a.SeedRatio = float32(*task.SeedRatio())
}
}
activities = append(activities, a)
}
activities = append(activities, a)
}
} else {
his := s.db.GetHistories()
for _, h := range his {
if h.Status == history.StatusRunning || h.Status == history.StatusUploading || h.Status == history.StatusSeeding {
continue //archived downloads
}
a := Activity{
History: h,
}
activities = append(activities, a)
}
}
return activities, nil
}
@@ -60,7 +70,9 @@ func (s *Server) RemoveActivity(c *gin.Context) (interface{}, error) {
}
if his.EpisodeID != 0 {
s.db.SetEpisodeStatus(his.EpisodeID, episode.StatusMissing)
if his.Status == history.StatusRunning || his.Status == history.StatusUploading {
s.db.SetEpisodeStatus(his.EpisodeID, episode.StatusMissing)
}
} else {
seasonNum, err := utils.SeasonId(his.TargetDir)
@@ -68,8 +80,9 @@ func (s *Server) RemoveActivity(c *gin.Context) (interface{}, error) {
log.Errorf("no season id: %v", his.TargetDir)
seasonNum = -1
}
s.db.SetSeasonAllEpisodeStatus(his.MediaID, seasonNum, episode.StatusMissing)
if his.Status == history.StatusRunning || his.Status == history.StatusUploading {
s.db.SetSeasonAllEpisodeStatus(his.MediaID, seasonNum, episode.StatusMissing)
}
}
err = s.db.DeleteHistory(id)

View File

@@ -33,7 +33,7 @@ func (c *Client) Init() {
}
func (c *Client) reloadTasks() {
allTasks := c.db.GetHistories()
allTasks := c.db.GetRunningHistories()
for _, t := range allTasks {
torrent, err := transmission.ReloadTorrent(t.Saved)
if err != nil {
@@ -67,7 +67,8 @@ func (c *Client) TMDB() (*tmdb.Client, error) {
return nil, errors.New("TMDB apiKey not set")
}
proxy := c.db.GetSetting(db.SettingProxy)
return tmdb.NewClient(api, proxy)
adult := c.db.GetSetting(db.SettingEnableTmdbAdultContent)
return tmdb.NewClient(api, proxy, adult == "true")
}
func (c *Client) MustTMDB() *tmdb.Client {
@@ -78,8 +79,7 @@ func (c *Client) MustTMDB() *tmdb.Client {
return t
}
func (c *Client) RemoveTaskAndTorrent(id int)error {
func (c *Client) RemoveTaskAndTorrent(id int) error {
torrent := c.tasks[id]
if torrent != nil {
if err := torrent.Remove(); err != nil {
@@ -92,4 +92,4 @@ func (c *Client) RemoveTaskAndTorrent(id int)error {
func (c *Client) GetTasks() map[int]*Task {
return c.tasks
}
}

View File

@@ -2,28 +2,122 @@ package core
import (
"bytes"
"encoding/xml"
"fmt"
"github.com/pkg/errors"
"os"
"path/filepath"
"polaris/db"
"polaris/ent/media"
storage1 "polaris/ent/storage"
"polaris/log"
"polaris/pkg/metadata"
"polaris/pkg/notifier"
"polaris/pkg/storage"
"github.com/pkg/errors"
"polaris/pkg/utils"
"slices"
"strconv"
"strings"
)
func (c *Client) writePlexmatch(seriesId int, episodeId int, targetDir, name string) error {
func (c *Client) writeNfoFile(historyId int) error {
if !c.nfoSupportEnabled() {
return nil
}
his := c.db.GetHistory(historyId)
md, err := c.db.GetMedia(his.MediaID)
if err != nil {
return err
}
if md.MediaType == media.MediaTypeTv { //tvshow.nfo
st, err := c.getStorage(md.StorageID, media.MediaTypeTv)
if err != nil {
return errors.Wrap(err, "get storage")
}
nfoPath := filepath.Join(md.TargetDir, "tvshow.nfo")
_, err = st.ReadFile(nfoPath)
if err != nil {
log.Infof("tvshow.nfo file missing, create new one, tv series name: %s", md.NameEn)
show := Tvshow{
Title: md.NameCn,
Originaltitle: md.OriginalName,
Showtitle: md.NameCn,
Plot: md.Overview,
ID: strconv.Itoa(md.TmdbID),
Uniqueid: []UniqueId{
{
Text: strconv.Itoa(md.TmdbID),
Type: "tmdb",
Default: "true",
},
{
Text: md.ImdbID,
Type: "imdb",
},
},
}
data, err := xml.MarshalIndent(&show, " ", " ")
if err != nil {
return errors.Wrap(err, "xml marshal")
}
return st.WriteFile(nfoPath, data)
}
} else if md.MediaType == media.MediaTypeMovie { //movie.nfo
st, err := c.getStorage(md.StorageID, media.MediaTypeMovie)
if err != nil {
return errors.Wrap(err, "get storage")
}
nfoPath := filepath.Join(md.TargetDir, "movie.nfo")
_, err = st.ReadFile(nfoPath)
if err != nil {
log.Infof("movie.nfo file missing, create new one, tv series name: %s", md.NameEn)
nfoData := Movie{
Title: md.NameCn,
Originaltitle: md.OriginalName,
Sorttitle: md.NameCn,
Plot: md.Overview,
ID: strconv.Itoa(md.TmdbID),
Uniqueid: []UniqueId{
{
Text: strconv.Itoa(md.TmdbID),
Type: "tmdb",
Default: "true",
},
{
Text: md.ImdbID,
Type: "imdb",
},
},
}
data, err := xml.MarshalIndent(&nfoData, " ", " ")
if err != nil {
return errors.Wrap(err, "xml marshal")
}
return st.WriteFile(nfoPath, data)
}
}
return nil
}
func (c *Client) writePlexmatch(historyId int) error {
if !c.plexmatchEnabled() {
return nil
}
series, err := c.db.GetMedia(seriesId)
his := c.db.GetHistory(historyId)
series, err := c.db.GetMedia(his.MediaID)
if err != nil {
return err
}
if series.MediaType != media.MediaTypeTv {
if series.MediaType != media.MediaTypeTv { //.plexmatch only support tv series
return nil
}
st, err := c.getStorage(series.StorageID, media.MediaTypeTv)
@@ -35,27 +129,60 @@ 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")
}
}
//season plexmatch file
ep, err := c.db.GetEpisodeByID(episodeId)
if err != nil {
return errors.Wrap(err, "query episode")
}
buff := bytes.Buffer{}
seasonPlex := filepath.Join(targetDir, ".plexmatch")
seasonPlex := filepath.Join(his.TargetDir, ".plexmatch")
data, err := st.ReadFile(seasonPlex)
if err != nil {
log.Infof("read season plexmatch: %v", err)
} else {
buff.Write(data)
}
buff.WriteString(fmt.Sprintf("\nep: %d: %s\n", ep.EpisodeNumber, name))
if his.EpisodeID > 0 {
//single episode download
ep, err := c.db.GetEpisodeByID(his.EpisodeID)
if err != nil {
return errors.Wrap(err, "query episode")
}
if strings.Contains(buff.String(), ep.TargetFile) {
log.Debugf("already write plex episode line: %v", ep.TargetFile)
return nil
}
buff.WriteString(fmt.Sprintf("\nep: %d: %s\n", ep.EpisodeNumber, ep.TargetFile))
} else {
seasonNum, err := utils.SeasonId(his.TargetDir)
if err != nil {
return errors.Wrap(err, "no season id")
}
allEpisodes, err := c.db.GetSeasonEpisodes(his.MediaID, seasonNum)
if err != nil {
return errors.Wrap(err, "query season episode")
}
for _, ep := range allEpisodes {
if ep.TargetFile == "" {
log.Errorf("no episode file of episode %d, season %d", ep.EpisodeNumber, ep.SeasonNumber)
//TODO update db
continue
}
if strings.Contains(buff.String(), ep.TargetFile) {
log.Debugf("already write plex episode line: %v", ep.TargetFile)
continue
}
buff.WriteString(fmt.Sprintf("\nep: %d: %s\n", ep.EpisodeNumber, ep.TargetFile))
}
}
log.Infof("write season plexmatch file content: %s", buff.String())
return st.WriteFile(seasonPlex, buff.Bytes())
}
@@ -64,6 +191,10 @@ func (c *Client) plexmatchEnabled() bool {
return c.db.GetSetting(db.SettingPlexMatchEnabled) == "true"
}
func (c *Client) nfoSupportEnabled() bool {
return c.db.GetSetting(db.SettingNfoSupportEnabled) == "true"
}
func (c *Client) getStorage(storageId int, mediaType media.MediaType) (storage.Storage, error) {
st := c.db.GetStorage(storageId)
targetPath := st.TvPath
@@ -119,3 +250,63 @@ func (c *Client) sendMsg(msg string) {
log.Debugf("send message to %s success, msg is %s", cl.Name, msg)
}
}
func (c *Client) findEpisodeFilesPreMoving(historyId int) error {
his := c.db.GetHistory(historyId)
isSingleEpisode := his.EpisodeID > 0
downloadDir := c.db.GetDownloadDir()
task := c.tasks[historyId]
target := filepath.Join(downloadDir, task.Name())
fi, err := os.Stat(target)
if err != nil {
return errors.Wrapf(err, "read dir %v", target)
}
if isSingleEpisode {
if fi.IsDir() {
//download single episode in dir
//TODO
} else {
//is file
if err := c.db.UpdateEpisodeTargetFile(his.EpisodeID, fi.Name()); err != nil {
log.Errorf("writing downloaded file name to db error: %v", err)
}
}
} else {
if !fi.IsDir() {
return fmt.Errorf("not season pack downloaded")
}
seasonNum, err := utils.SeasonId(his.TargetDir)
if err != nil {
return errors.Wrap(err, "no season id")
}
files, err := os.ReadDir(target)
if err != nil {
return err
}
for _, f := range files {
if f.IsDir() { //want media file
continue
}
excludedExt := []string{".txt", ".srt", ".ass", ".sub"}
ext := filepath.Ext(f.Name())
if slices.Contains(excludedExt, strings.ToLower(ext)) {
continue
}
meta := metadata.ParseTv(f.Name())
if meta.Episode > 0 {
//episode exists
ep, err := c.db.GetEpisode(his.MediaID, seasonNum, meta.Episode)
if err != nil {
return err
}
if err := c.db.UpdateEpisodeTargetFile(ep.ID, f.Name()); err != nil {
return errors.Wrap(err, "update episode file")
}
}
}
}
return nil
}

253
server/core/nfo.go Normal file
View File

@@ -0,0 +1,253 @@
package core
import "encoding/xml"
type Tvshow struct {
XMLName xml.Name `xml:"tvshow"`
Text string `xml:",chardata"`
Title string `xml:"title"`
Originaltitle string `xml:"originaltitle"`
Showtitle string `xml:"showtitle"`
Ratings struct {
Text string `xml:",chardata"`
Rating []struct {
Text string `xml:",chardata"`
Name string `xml:"name,attr"`
Max string `xml:"max,attr"`
Default string `xml:"default,attr"`
Value string `xml:"value"`
Votes string `xml:"votes"`
} `xml:"rating"`
} `xml:"ratings"`
Userrating string `xml:"userrating"`
Top250 string `xml:"top250"`
Season string `xml:"season"`
Episode string `xml:"episode"`
Displayseason string `xml:"displayseason"`
Displayepisode string `xml:"displayepisode"`
Outline string `xml:"outline"`
Plot string `xml:"plot"`
Tagline string `xml:"tagline"`
Runtime string `xml:"runtime"`
Thumb []struct {
Text string `xml:",chardata"`
Spoof string `xml:"spoof,attr"`
Cache string `xml:"cache,attr"`
Aspect string `xml:"aspect,attr"`
Preview string `xml:"preview,attr"`
Season string `xml:"season,attr"`
Type string `xml:"type,attr"`
} `xml:"thumb"`
Fanart struct {
Text string `xml:",chardata"`
Thumb []struct {
Text string `xml:",chardata"`
Colors string `xml:"colors,attr"`
Preview string `xml:"preview,attr"`
} `xml:"thumb"`
} `xml:"fanart"`
Mpaa string `xml:"mpaa"`
Playcount string `xml:"playcount"`
Lastplayed string `xml:"lastplayed"`
ID string `xml:"id"`
Uniqueid []UniqueId `xml:"uniqueid"`
Genre string `xml:"genre"`
Premiered string `xml:"premiered"`
Year string `xml:"year"`
Status string `xml:"status"`
Code string `xml:"code"`
Aired string `xml:"aired"`
Studio string `xml:"studio"`
Trailer string `xml:"trailer"`
Actor []struct {
Text string `xml:",chardata"`
Name string `xml:"name"`
Role string `xml:"role"`
Order string `xml:"order"`
Thumb string `xml:"thumb"`
} `xml:"actor"`
Namedseason []struct {
Text string `xml:",chardata"`
Number string `xml:"number,attr"`
} `xml:"namedseason"`
Resume struct {
Text string `xml:",chardata"`
Position string `xml:"position"`
Total string `xml:"total"`
} `xml:"resume"`
Dateadded string `xml:"dateadded"`
}
type UniqueId struct {
Text string `xml:",chardata"`
Type string `xml:"type,attr"`
Default string `xml:"default,attr"`
}
type Episodedetails struct {
XMLName xml.Name `xml:"episodedetails"`
Text string `xml:",chardata"`
Title string `xml:"title"`
Showtitle string `xml:"showtitle"`
Ratings struct {
Text string `xml:",chardata"`
Rating []struct {
Text string `xml:",chardata"`
Name string `xml:"name,attr"`
Max string `xml:"max,attr"`
Default string `xml:"default,attr"`
Value string `xml:"value"`
Votes string `xml:"votes"`
} `xml:"rating"`
} `xml:"ratings"`
Userrating string `xml:"userrating"`
Top250 string `xml:"top250"`
Season string `xml:"season"`
Episode string `xml:"episode"`
Displayseason string `xml:"displayseason"`
Displayepisode string `xml:"displayepisode"`
Outline string `xml:"outline"`
Plot string `xml:"plot"`
Tagline string `xml:"tagline"`
Runtime string `xml:"runtime"`
Thumb []struct {
Text string `xml:",chardata"`
Spoof string `xml:"spoof,attr"`
Cache string `xml:"cache,attr"`
Aspect string `xml:"aspect,attr"`
Preview string `xml:"preview,attr"`
} `xml:"thumb"`
Mpaa string `xml:"mpaa"`
Playcount string `xml:"playcount"`
Lastplayed string `xml:"lastplayed"`
ID string `xml:"id"`
Uniqueid []struct {
Text string `xml:",chardata"`
Type string `xml:"type,attr"`
Default string `xml:"default,attr"`
} `xml:"uniqueid"`
Genre string `xml:"genre"`
Credits []string `xml:"credits"`
Director string `xml:"director"`
Premiered string `xml:"premiered"`
Year string `xml:"year"`
Status string `xml:"status"`
Code string `xml:"code"`
Aired string `xml:"aired"`
Studio string `xml:"studio"`
Trailer string `xml:"trailer"`
Actor []struct {
Text string `xml:",chardata"`
Name string `xml:"name"`
Role string `xml:"role"`
Order string `xml:"order"`
Thumb string `xml:"thumb"`
} `xml:"actor"`
Resume struct {
Text string `xml:",chardata"`
Position string `xml:"position"`
Total string `xml:"total"`
} `xml:"resume"`
Dateadded string `xml:"dateadded"`
}
type Movie struct {
XMLName xml.Name `xml:"movie"`
Text string `xml:",chardata"`
Title string `xml:"title"`
Originaltitle string `xml:"originaltitle"`
Sorttitle string `xml:"sorttitle"`
Ratings struct {
Text string `xml:",chardata"`
Rating []struct {
Text string `xml:",chardata"`
Name string `xml:"name,attr"`
Max string `xml:"max,attr"`
Default string `xml:"default,attr"`
Value string `xml:"value"`
Votes string `xml:"votes"`
} `xml:"rating"`
} `xml:"ratings"`
Userrating string `xml:"userrating"`
Top250 string `xml:"top250"`
Outline string `xml:"outline"`
Plot string `xml:"plot"`
Tagline string `xml:"tagline"`
Runtime string `xml:"runtime"`
Thumb []struct {
Text string `xml:",chardata"`
Spoof string `xml:"spoof,attr"`
Cache string `xml:"cache,attr"`
Aspect string `xml:"aspect,attr"`
Preview string `xml:"preview,attr"`
} `xml:"thumb"`
Fanart struct {
Text string `xml:",chardata"`
Thumb struct {
Text string `xml:",chardata"`
Colors string `xml:"colors,attr"`
Preview string `xml:"preview,attr"`
} `xml:"thumb"`
} `xml:"fanart"`
Mpaa string `xml:"mpaa"`
Playcount string `xml:"playcount"`
Lastplayed string `xml:"lastplayed"`
ID string `xml:"id"`
Uniqueid []UniqueId `xml:"uniqueid"`
Genre string `xml:"genre"`
Country []string `xml:"country"`
Set struct {
Text string `xml:",chardata"`
Name string `xml:"name"`
Overview string `xml:"overview"`
} `xml:"set"`
Tag []string `xml:"tag"`
Videoassettitle string `xml:"videoassettitle"`
Videoassetid string `xml:"videoassetid"`
Videoassettype string `xml:"videoassettype"`
Hasvideoversions string `xml:"hasvideoversions"`
Hasvideoextras string `xml:"hasvideoextras"`
Isdefaultvideoversion string `xml:"isdefaultvideoversion"`
Credits []string `xml:"credits"`
Director string `xml:"director"`
Premiered string `xml:"premiered"`
Year string `xml:"year"`
Status string `xml:"status"`
Code string `xml:"code"`
Aired string `xml:"aired"`
Studio string `xml:"studio"`
Trailer string `xml:"trailer"`
Fileinfo struct {
Text string `xml:",chardata"`
Streamdetails struct {
Text string `xml:",chardata"`
Video struct {
Text string `xml:",chardata"`
Codec string `xml:"codec"`
Aspect string `xml:"aspect"`
Width string `xml:"width"`
Height string `xml:"height"`
Durationinseconds string `xml:"durationinseconds"`
Stereomode string `xml:"stereomode"`
Hdrtype string `xml:"hdrtype"`
} `xml:"video"`
Audio struct {
Text string `xml:",chardata"`
Codec string `xml:"codec"`
Language string `xml:"language"`
Channels string `xml:"channels"`
} `xml:"audio"`
Subtitle struct {
Text string `xml:",chardata"`
Language string `xml:"language"`
} `xml:"subtitle"`
} `xml:"streamdetails"`
} `xml:"fileinfo"`
Actor []struct {
Text string `xml:",chardata"`
Name string `xml:"name"`
Role string `xml:"role"`
Order string `xml:"order"`
Thumb string `xml:"thumb"`
} `xml:"actor"`
}

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,13 @@ 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 {
if ep.Status == episode.StatusMissing {
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))
@@ -111,8 +82,17 @@ func (c *Client) DownloadEpisodeTorrent(r1 torznab.Result, seriesId, seasonNum,
}
func (c *Client) SearchAndDownload(seriesId, seasonNum, episodeNum int) (*string, error) {
res, err := SearchTvSeries(c.db, seriesId, seasonNum, []int{episodeNum}, true, true)
var episodes []int
if episodeNum > 0 {
episodes = append(episodes, episodeNum)
}
res, err := SearchTvSeries(c.db, &SearchParam{
MediaId: seriesId,
SeasonNum: seasonNum,
Episodes: episodes,
CheckFileSize: true,
CheckResolution: true,
})
if err != nil {
return nil, err
}
@@ -121,7 +101,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")
@@ -155,11 +135,14 @@ func (c *Client) DownloadMovie(m *ent.Media,link, name string, size int, indexer
c.tasks[history.ID] = &Task{Torrent: torrent}
c.db.SetEpisodeStatus(ep.ID, episode.StatusDownloading)
if ep.Status == episode.StatusMissing {
c.db.SetEpisodeStatus(ep.ID, episode.StatusDownloading)
}
}()
c.sendMsg(fmt.Sprintf(message.BeginDownload, name))
log.Infof("success add %s to download task", name)
return &name, nil
}
}

View File

@@ -3,6 +3,7 @@ package core
import (
"fmt"
"path/filepath"
"polaris/db"
"polaris/ent"
"polaris/ent/episode"
"polaris/ent/history"
@@ -18,8 +19,8 @@ import (
func (c *Client) addSysCron() {
c.mustAddCron("@every 1m", c.checkTasks)
c.mustAddCron("0 0 * * * *", func() {
c.downloadTvSeries()
c.downloadMovie()
c.downloadAllTvSeries()
c.downloadAllMovies()
})
c.mustAddCron("0 0 */12 * * *", c.checkAllSeriesNewSeason)
c.cron.Start()
@@ -35,38 +36,53 @@ func (c *Client) mustAddCron(spec string, cmd func()) {
func (c *Client) checkTasks() {
log.Debug("begin check tasks...")
for id, t := range c.tasks {
r := c.db.GetHistory(id)
if !t.Exists() {
log.Infof("task no longer exists: %v", id)
delete(c.tasks, id)
continue
}
log.Infof("task (%s) percentage done: %d%%", t.Name(), t.Progress())
if t.Progress() == 100 {
r := c.db.GetHistory(id)
if r.Status == history.StatusSuccess {
if r.Status == history.StatusSeeding {
//task already success, check seed ratio
torrent := c.tasks[id]
ok := c.isSeedRatioLimitReached(r.IndexerID, torrent)
if ok {
log.Infof("torrent file seed ratio reached, remove: %v", torrent.Name())
log.Infof("torrent file seed ratio reached, remove: %v, current seed ratio: %v", torrent.Name(), *torrent.SeedRatio())
torrent.Remove()
delete(c.tasks, id)
} else {
log.Infof("torrent file still sedding: %v", torrent.Name())
log.Infof("torrent file still sedding: %v, current seed ratio: %v", torrent.Name(), *torrent.SeedRatio())
}
continue
}
log.Infof("task is done: %v", t.Name())
c.sendMsg(fmt.Sprintf(message.DownloadComplete, t.Name()))
go func() {
if err := c.moveCompletedTask(id); err != nil {
log.Infof("post tasks for id %v fail: %v", id, err)
}
}()
go c.postTaskProcessing(id)
}
}
}
func (c *Client) postTaskProcessing(id int) {
if err := c.findEpisodeFilesPreMoving(id); err != nil {
log.Errorf("finding all episode file error: %v", err)
} else {
if err := c.writePlexmatch(id); err != nil {
log.Errorf("write plexmatch file error: %v", err)
}
if err := c.writeNfoFile(id); err != nil {
log.Errorf("write nfo file error: %v", err)
}
}
if err := c.moveCompletedTask(id); err != nil {
log.Infof("post tasks for id %v fail: %v", id, err)
}
}
func (c *Client) moveCompletedTask(id int) (err1 error) {
torrent := c.tasks[id]
r := c.db.GetHistory(id)
@@ -96,7 +112,7 @@ func (c *Client) moveCompletedTask(id int) (err1 error) {
} else {
c.db.SetSeasonAllEpisodeStatus(r.MediaID, seasonNum, episode.StatusMissing)
}
c.sendMsg(fmt.Sprintf(message.ProcessingFailed, err))
c.sendMsg(fmt.Sprintf(message.ProcessingFailed, err1))
if downloadclient.RemoveFailedDownloads {
log.Debugf("task failed, remove failed torrent and files related")
delete(c.tasks, r.ID)
@@ -121,12 +137,7 @@ func (c *Client) moveCompletedTask(id int) (err1 error) {
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)
}
c.db.SetHistoryStatus(r.ID, history.StatusSuccess)
c.db.SetHistoryStatus(r.ID, history.StatusSeeding)
if r.EpisodeID != 0 {
c.db.SetEpisodeStatus(r.EpisodeID, episode.StatusDownloaded)
} else {
@@ -137,7 +148,8 @@ func (c *Client) moveCompletedTask(id int) (err1 error) {
//判断是否需要删除本地文件
ok := c.isSeedRatioLimitReached(r.IndexerID, torrent)
if downloadclient.RemoveCompletedDownloads && ok {
log.Debugf("download complete,remove torrent and files related")
log.Debugf("download complete,remove torrent and files related, torrent: %v, seed ratio: %v", torrentName, *torrent.SeedRatio())
c.db.SetHistoryStatus(r.ID, history.StatusSuccess)
delete(c.tasks, r.ID)
torrent.Remove()
}
@@ -202,68 +214,123 @@ type Task struct {
pkg.Torrent
}
func (c *Client) downloadTvSeries() {
log.Infof("begin check all tv series resources")
allSeries := c.db.GetMediaWatchlist(media.MediaTypeTv)
for _, series := range allSeries {
tvDetail := c.db.GetMediaDetails(series.ID)
for _, ep := range tvDetail.Episodes {
if !ep.Monitored { //未监控的剧集不去下载
continue
func (c *Client) DownloadSeriesAllEpisodes(id int) []string {
tvDetail := c.db.GetMediaDetails(id)
m := make(map[int][]*ent.Episode)
for _, ep := range tvDetail.Episodes {
m[ep.SeasonNumber] = append(m[ep.SeasonNumber], ep)
}
var allNames []string
for seasonNum, epsides := range m {
if seasonNum == 0 {
continue
}
wantedSeasonPack := true
for _, ep := range epsides {
if !ep.Monitored {
wantedSeasonPack = false
}
if ep.Status != episode.StatusMissing {
wantedSeasonPack = false
}
}
if wantedSeasonPack {
name, err := c.SearchAndDownload(id, seasonNum, -1)
if err == nil {
allNames = append(allNames, *name)
log.Infof("begin download torrent resource: %v", name)
} else {
log.Warnf("finding season pack error: %v", err)
wantedSeasonPack = false
}
if ep.Status != episode.StatusMissing { //已经下载的不去下载
continue
}
name, err := c.SearchAndDownload(series.ID, ep.SeasonNumber, ep.EpisodeNumber)
if err != nil {
log.Infof("cannot find resource to download for %s: %v", ep.Title, err)
} else {
log.Infof("begin download torrent resource: %v", name)
}
if !wantedSeasonPack {
for _, ep := range epsides {
if !ep.Monitored {
continue
}
if ep.Status != episode.StatusMissing {
continue
}
name, err := c.SearchAndDownload(id, ep.SeasonNumber, ep.EpisodeNumber)
if err != nil {
log.Warnf("finding resoruces of season %d episode %d error: %v", ep.SeasonNumber, ep.EpisodeNumber, err)
continue
} else {
allNames = append(allNames, *name)
log.Infof("begin download torrent resource: %v", name)
}
}
}
}
return allNames
}
func (c *Client) downloadMovie() {
func (c *Client) downloadAllTvSeries() {
log.Infof("begin check all tv series resources")
allSeries := c.db.GetMediaWatchlist(media.MediaTypeTv)
for _, series := range allSeries {
c.DownloadSeriesAllEpisodes(series.ID)
}
}
func (c *Client) downloadAllMovies() {
log.Infof("begin check all movie resources")
allSeries := c.db.GetMediaWatchlist(media.MediaTypeMovie)
for _, series := range allSeries {
detail := c.db.GetMediaDetails(series.ID)
if len(detail.Episodes) == 0 {
log.Errorf("no related dummy episode: %v", detail.NameEn)
continue
}
ep := detail.Episodes[0]
if ep.Status == episode.StatusDownloaded {
continue
}
if err := c.downloadMovieSingleEpisode(ep); err != nil {
if _, err := c.DownloadMovieByID(series.ID); err != nil {
log.Errorf("download movie error: %v", err)
}
}
}
func (c *Client) downloadMovieSingleEpisode(ep *ent.Episode) error {
trc, dlc, err := c.getDownloadClient()
if err != nil {
return errors.Wrap(err, "connect transmission")
func (c *Client) DownloadMovieByID(id int) (string, error) {
detail := c.db.GetMediaDetails(id)
if len(detail.Episodes) == 0 {
return "", fmt.Errorf("no related dummy episode: %v", detail.NameEn)
}
ep := detail.Episodes[0]
if ep.Status != episode.StatusMissing {
return "", nil
}
res, err := SearchMovie(c.db, ep.MediaID, true, true)
if name, err := c.downloadMovieSingleEpisode(ep, detail.TargetDir); err != nil {
return "", errors.Wrap(err, "download movie")
} else {
return name, nil
}
}
func (c *Client) downloadMovieSingleEpisode(ep *ent.Episode, targetDir string) (string, error) {
trc, dlc, err := c.getDownloadClient()
if err != nil {
return "", errors.Wrap(err, "connect transmission")
}
qiangban := c.db.GetSetting(db.SettingAllowQiangban)
allowQiangban := false
if qiangban == "true" {
allowQiangban = false
}
res, err := SearchMovie(c.db, &SearchParam{
MediaId: ep.MediaID,
CheckFileSize: true,
CheckResolution: true,
FilterQiangban: !allowQiangban,
})
if err != nil {
return errors.Wrap(err, "search movie")
return "", errors.Wrap(err, "search movie")
}
r1 := res[0]
log.Infof("begin download torrent resource: %v", r1.Name)
torrent, err := trc.Download(r1.Link, c.db.GetDownloadDir())
if err != nil {
return errors.Wrap(err, "downloading")
return "", errors.Wrap(err, "downloading")
}
torrent.Start()
@@ -271,7 +338,7 @@ func (c *Client) downloadMovieSingleEpisode(ep *ent.Episode) error {
MediaID: ep.MediaID,
EpisodeID: ep.ID,
SourceTitle: r1.Name,
TargetDir: "./",
TargetDir: targetDir,
Status: history.StatusRunning,
Size: r1.Size,
Saved: torrent.Save(),
@@ -285,7 +352,7 @@ func (c *Client) downloadMovieSingleEpisode(ep *ent.Episode) error {
c.tasks[history.ID] = &Task{Torrent: torrent}
c.db.SetEpisodeStatus(ep.ID, episode.StatusDownloading)
return nil
return r1.Name, nil
}
func (c *Client) checkAllSeriesNewSeason() {

View File

@@ -3,10 +3,11 @@ package core
import (
"fmt"
"polaris/db"
"polaris/ent/media"
"polaris/log"
"polaris/pkg/metadata"
"polaris/pkg/torznab"
"polaris/pkg/utils"
"regexp"
"slices"
"sort"
"strconv"
@@ -16,16 +17,23 @@ import (
"github.com/pkg/errors"
)
func SearchTvSeries(db1 *db.Client, seriesId, seasonNum int, episodes []int, checkResolution bool, checkFileSize bool) ([]torznab.Result, error) {
series := db1.GetMediaDetails(seriesId)
if series == nil {
return nil, fmt.Errorf("no tv series of id %v", seriesId)
}
log.Debugf("check tv series %s, season %d, episode %v", series.NameEn, seasonNum, episodes)
type SearchParam struct {
MediaId int
SeasonNum int //for tv
Episodes []int //for tv
CheckResolution bool
CheckFileSize bool
FilterQiangban bool //for movie, 是否过滤枪版电影
}
res := searchWithTorznab(db1, series.NameEn)
resCn := searchWithTorznab(db1, series.NameCn)
res = append(res, resCn...)
func SearchTvSeries(db1 *db.Client, param *SearchParam) ([]torznab.Result, error) {
series := db1.GetMediaDetails(param.MediaId)
if series == nil {
return nil, fmt.Errorf("no tv series of id %v", param.MediaId)
}
log.Debugf("check tv series %s, season %d, episode %v", series.NameEn, param.SeasonNum, param.Episodes)
res := searchWithTorznab(db1, series.NameEn, series.NameCn, series.OriginalName)
var filtered []torznab.Result
for _, r := range res {
@@ -34,38 +42,39 @@ func SearchTvSeries(db1 *db.Client, seriesId, seasonNum int, episodes []int, che
if meta == nil { //cannot parse name
continue
}
if !isNumberedSeries(series) && meta.Season != seasonNum { //do not check season on series that only rely on episode number
if isImdbidNotMatch(series.ImdbID, r.ImdbId) { //has imdb id and not match
continue
}
if !imdbIDMatchExact(series.ImdbID, r.ImdbId) { //imdb id not exact match, check file name
if !torrentNameOk(series, r.Name) {
continue
}
}
if !isNoSeasonSeries(series) && meta.Season != param.SeasonNum { //do not check season on series that only rely on episode number
continue
}
if isNumberedSeries(series) && len(episodes) == 0 {
if isNoSeasonSeries(series) && len(param.Episodes) == 0 {
//should not want season
continue
}
if len(episodes) > 0 && !slices.Contains(episodes, meta.Episode) { //not season pack, but episode number not equal
if len(param.Episodes) > 0 && !slices.Contains(param.Episodes, meta.Episode) { //not season pack, but episode number not equal
continue
} else if len(episodes) == 0 && !meta.IsSeasonPack { //want season pack, but not season pack
} else if len(param.Episodes) == 0 && !meta.IsSeasonPack { //want season pack, but not season pack
continue
}
if checkResolution && meta.Resolution != series.Resolution.String() {
continue
}
if !utils.IsNameAcceptable(meta.NameEn, series.NameEn) && !utils.IsNameAcceptable(meta.NameCn, series.NameCn) {
if param.CheckResolution && meta.Resolution != series.Resolution.String() {
continue
}
if checkFileSize && series.Limiter != nil {
if series.Limiter.SizeMin > 0 && r.Size < series.Limiter.SizeMin {
//min size not satified
continue
}
if series.Limiter.SizeMax > 0 && r.Size > series.Limiter.SizeMax {
//max size not satified
continue
}
if !torrentSizeOk(series, r.Size, param) {
continue
}
filtered = append(filtered, r)
}
if len(filtered) == 0 {
@@ -76,7 +85,60 @@ func SearchTvSeries(db1 *db.Client, seriesId, seasonNum int, episodes []int, che
}
func isNumberedSeries(detail *db.MediaDetails) bool {
// imdbid not exist consider match
func isImdbidNotMatch(id1, id2 string) bool {
if id1 == "" || id2 == "" {
return false
}
id1 = strings.TrimPrefix(id1, "tt")
id2 = strings.TrimPrefix(id2, "tt")
return id1 != id2
}
// imdbid not exist consider not match
func imdbIDMatchExact(id1, id2 string) bool {
if id1 == "" || id2 == "" {
return false
}
id1 = strings.TrimPrefix(id1, "tt")
id2 = strings.TrimPrefix(id2, "tt")
return id1 == id2
}
func torrentSizeOk(detail *db.MediaDetails, torrentSize int, param *SearchParam) bool {
if param.CheckFileSize {
multiplier := 1 //大小倍数正常为1如果是季包则为季内集数
if detail.MediaType == media.MediaTypeTv && len(param.Episodes) == 0 { //tv season pack
multiplier = seasonEpisodeCount(detail, param.SeasonNum)
}
if detail.Limiter.SizeMin > 0 { //min size
sizeMin := detail.Limiter.SizeMin * multiplier
if torrentSize < sizeMin { //比最小要求的大小还要小
return false
}
}
if detail.Limiter.SizeMax > 0 { //max size
sizeMax := detail.Limiter.SizeMax * multiplier
if torrentSize > sizeMax { //larger than max size wanted
return false
}
}
}
return true
}
func seasonEpisodeCount(detail *db.MediaDetails, seasonNum int) int {
count := 0
for _, ep := range detail.Episodes {
if ep.SeasonNumber == seasonNum {
count++
}
}
return count
}
func isNoSeasonSeries(detail *db.MediaDetails) bool {
hasSeason2 := false
season2HasEpisode1 := false
for _, ep := range detail.Episodes {
@@ -91,16 +153,17 @@ func isNumberedSeries(detail *db.MediaDetails) bool {
return hasSeason2 && !season2HasEpisode1 //only one 1st episode
}
func SearchMovie(db1 *db.Client, movieId int, checkResolution bool, checkFileSize bool) ([]torznab.Result, error) {
movieDetail := db1.GetMediaDetails(movieId)
func SearchMovie(db1 *db.Client, param *SearchParam) ([]torznab.Result, error) {
movieDetail := db1.GetMediaDetails(param.MediaId)
if movieDetail == nil {
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 movieDetail.Extras.IsJav(){
res1 := searchWithTorznab(db1, movieDetail.Extras.JavId)
res = append(res, res1...)
}
if len(res) == 0 {
return nil, fmt.Errorf("no resource found")
@@ -108,27 +171,33 @@ 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) {
continue
}
if checkResolution && meta.Resolution != movieDetail.Resolution.String() {
if isImdbidNotMatch(movieDetail.ImdbID, r.ImdbId) { //imdb id not match
continue
}
if checkFileSize && movieDetail.Limiter != nil {
if movieDetail.Limiter.SizeMin > 0 && r.Size < movieDetail.Limiter.SizeMin {
//min size not satified
if !imdbIDMatchExact(movieDetail.ImdbID, r.ImdbId) {
if !torrentNameOk(movieDetail, r.Name) {
continue
}
if movieDetail.Limiter.SizeMax > 0 && r.Size > movieDetail.Limiter.SizeMax {
//max size not satified
continue
if !movieDetail.Extras.IsJav() {
ss := strings.Split(movieDetail.AirDate, "-")[0]
year, _ := strconv.Atoi(ss)
if meta.Year != year && meta.Year != year-1 && meta.Year != year+1 { //year not match
continue
}
}
}
ss := strings.Split(movieDetail.AirDate, "-")[0]
year, _ := strconv.Atoi(ss)
if meta.Year != year && meta.Year != year-1 && meta.Year != year+1 { //year not match
if param.CheckResolution && meta.Resolution != movieDetail.Resolution.String() {
continue
}
if param.FilterQiangban && meta.IsQingban { //过滤枪版电影
continue
}
if !torrentSizeOk(movieDetail, r.Size, param) {
continue
}
@@ -144,7 +213,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()
@@ -155,18 +224,21 @@ func searchWithTorznab(db *db.Client, q string) []torznab.Result {
if tor.Disabled {
continue
}
wg.Add(1)
go func() {
log.Debugf("search torznab %v with %v", tor.Name, q)
defer wg.Done()
resp, err := torznab.Search(tor, tor.ApiKey, q)
if err != nil {
log.Errorf("search %s error: %v", tor.Name, err)
return
}
resChan <- resp
for _, q := range queries {
wg.Add(1)
}()
go func() {
log.Debugf("search torznab %v with %v", tor.Name, queries)
defer wg.Done()
resp, err := torznab.Search(tor, q)
if err != nil {
log.Warnf("search %s with query %s error: %v", tor.Name, q, err)
return
}
resChan <- resp
}()
}
}
go func() {
wg.Wait()
@@ -177,7 +249,7 @@ func searchWithTorznab(db *db.Client, q string) []torznab.Result {
res = append(res, result...)
}
//res = dedup(res)
res = dedup(res)
sort.SliceStable(res, func(i, j int) bool { //先按做种人数排序
var s1 = res[i]
@@ -227,3 +299,20 @@ 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)
}
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)
}

View File

@@ -2,10 +2,12 @@ package server
import (
"fmt"
"polaris/db"
"polaris/ent/media"
"polaris/log"
"polaris/pkg/torznab"
"polaris/server/core"
"strconv"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
@@ -13,14 +15,20 @@ import (
func (s *Server) searchAndDownloadSeasonPackage(seriesId, seasonNum int) (*string, error) {
res, err := core.SearchTvSeries(s.db, seriesId, seasonNum, nil, true, true)
res, err := core.SearchTvSeries(s.db, &core.SearchParam{
MediaId: seriesId,
SeasonNum: seasonNum,
Episodes: nil,
CheckResolution: true,
CheckFileSize: true,
})
if err != nil {
return nil, err
}
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)
}
@@ -46,13 +54,21 @@ func (s *Server) SearchAvailableTorrents(c *gin.Context) (interface{}, error) {
if in.Episode == 0 {
//search season package
log.Infof("search series season package S%02d", in.Season)
res, err = core.SearchTvSeries(s.db, in.ID, in.Season, nil, false, false)
res, err = core.SearchTvSeries(s.db, &core.SearchParam{
MediaId: in.ID,
SeasonNum: in.Season,
Episodes: nil,
})
if err != nil {
return nil, errors.Wrap(err, "search season package")
}
} else {
log.Infof("search series episode S%02dE%02d", in.Season, in.Episode)
res, err = core.SearchTvSeries(s.db, in.ID, in.Season, []int{in.Episode}, false, false)
res, err = core.SearchTvSeries(s.db, &core.SearchParam{
MediaId: in.ID,
SeasonNum: in.Season,
Episodes: []int{in.Episode},
})
if err != nil {
if err.Error() == "no resource found" {
return []string{}, nil
@@ -63,7 +79,16 @@ func (s *Server) SearchAvailableTorrents(c *gin.Context) (interface{}, error) {
}
} else {
log.Info("search movie %d", in.ID)
res, err = core.SearchMovie(s.db, in.ID, false, false)
qiangban := s.db.GetSetting(db.SettingAllowQiangban)
allowQiangban := false
if qiangban == "true" {
allowQiangban = true
}
res, err = core.SearchMovie(s.db, &core.SearchParam{
MediaId: in.ID,
FilterQiangban: !allowQiangban,
})
if err != nil {
if err.Error() == "no resource found" {
return []string{}, nil
@@ -129,7 +154,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 == "" {
@@ -143,3 +168,21 @@ func (s *Server) DownloadTorrent(c *gin.Context) (interface{}, error) {
}
}
func (s *Server) DownloadAll(c *gin.Context) (interface{}, error) {
ids := c.Param("id")
id, err := strconv.Atoi(ids)
if err != nil {
return nil, errors.Wrap(err, "convert")
}
m, err := s.db.GetMedia(id)
if err != nil {
return nil, errors.Wrap(err, "get media")
}
if m.MediaType == media.MediaTypeTv {
return s.core.DownloadSeriesAllEpisodes(m.ID), nil
}
name, err := s.core.DownloadMovieByID(m.ID)
return []string{name}, err
}

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))
@@ -90,6 +91,7 @@ func (s *Server) Serve() error {
tv.DELETE("/record/:id", HttpHandler(s.DeleteFromWatchlist))
tv.GET("/suggest/tv/:tmdb_id", HttpHandler(s.SuggestedSeriesFolderName))
tv.GET("/suggest/movie/:tmdb_id", HttpHandler(s.SuggestedMovieFolderName))
tv.GET("/downloadall/:id", HttpHandler(s.DownloadAll))
}
indexer := api.Group("/indexer")
{
@@ -129,7 +131,8 @@ func (s *Server) TMDB() (*tmdb.Client, error) {
return nil, errors.New("TMDB apiKey not set")
}
proxy := s.db.GetSetting(db.SettingProxy)
return tmdb.NewClient(api, proxy)
adult := s.db.GetSetting(db.SettingEnableTmdbAdultContent)
return tmdb.NewClient(api, proxy, adult=="true")
}
func (s *Server) MustTMDB() *tmdb.Client {

View File

@@ -14,11 +14,14 @@ import (
)
type GeneralSettings struct {
TmdbApiKey string `json:"tmdb_api_key"`
DownloadDir string `json:"download_dir"`
LogLevel string `json:"log_level"`
Proxy string `json:"proxy"`
EnablePlexmatch bool `json:"enable_plexmatch"`
TmdbApiKey string `json:"tmdb_api_key"`
DownloadDir string `json:"download_dir"`
LogLevel string `json:"log_level"`
Proxy string `json:"proxy"`
EnablePlexmatch bool `json:"enable_plexmatch"`
EnableNfo bool `json:"enable_nfo"`
AllowQiangban bool `json:"allow_qiangban"`
EnableAdultContent bool `json:"enable_adult_content"`
}
func (s *Server) SetSetting(c *gin.Context) (interface{}, error) {
@@ -54,6 +57,24 @@ func (s *Server) SetSetting(c *gin.Context) (interface{}, error) {
}
s.db.SetSetting(db.SettingProxy, in.Proxy)
if in.AllowQiangban {
s.db.SetSetting(db.SettingAllowQiangban, "true")
} else {
s.db.SetSetting(db.SettingAllowQiangban, "false")
}
if in.EnableNfo {
s.db.SetSetting(db.SettingNfoSupportEnabled, "true")
} else {
s.db.SetSetting(db.SettingNfoSupportEnabled, "false")
}
if in.EnableAdultContent {
s.db.SetSetting(db.SettingEnableTmdbAdultContent, "true")
} else {
s.db.SetSetting(db.SettingEnableTmdbAdultContent, "false")
}
return nil, nil
}
@@ -62,12 +83,18 @@ func (s *Server) GetSetting(c *gin.Context) (interface{}, error) {
downloadDir := s.db.GetSetting(db.SettingDownloadDir)
logLevel := s.db.GetSetting(db.SettingLogLevel)
plexmatchEnabled := s.db.GetSetting(db.SettingPlexMatchEnabled)
allowQiangban := s.db.GetSetting(db.SettingAllowQiangban)
enableNfo := s.db.GetSetting(db.SettingNfoSupportEnabled)
enableAdult := s.db.GetSetting(db.SettingEnableTmdbAdultContent)
return &GeneralSettings{
TmdbApiKey: tmdb,
DownloadDir: downloadDir,
LogLevel: logLevel,
Proxy: s.db.GetSetting(db.SettingProxy),
EnablePlexmatch: plexmatchEnabled == "true",
AllowQiangban: allowQiangban == "true",
EnableNfo: enableNfo == "true",
EnableAdultContent: enableAdult == "true",
}, nil
}
@@ -195,8 +222,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 +233,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)
@@ -96,6 +101,13 @@ func (s *Server) SuggestedMovieFolderName(c *gin.Context) (interface{}, error) {
}
name := d1.Title
if isJav(d1) {
javid := s.getJavid(id)
if javid != "" {
return gin.H{"name": javid}, nil
}
}
if s.language == db.LanguageCN {
en, err := s.MustTMDB().GetMovieDetails(id, db.LanguageEN)
if err != nil {
@@ -104,11 +116,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

@@ -13,6 +13,7 @@ import (
"polaris/ent/schema"
"polaris/log"
"strconv"
"strings"
"time"
tmdb "github.com/cyruzin/golang-tmdb"
@@ -139,6 +140,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 +151,11 @@ 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},
Extras: schema.MediaExtras{
OriginalLanguage: detail.OriginalLanguage,
Genres: detail.Genres,
},
}
r, err := s.db.AddMediaWatchlist(m, epIds)
@@ -173,6 +179,26 @@ func (s *Server) AddTv2Watchlist(c *gin.Context) (interface{}, error) {
return nil, nil
}
func isJav(detail *tmdb.MovieDetails) bool {
if detail.Adult && len(detail.ProductionCountries) > 0 && strings.ToUpper(detail.ProductionCountries[0].Iso3166_1) == "JP" {
return true
}
return false
}
func (s *Server) getJavid(id int) string {
alters, err := s.MustTMDB().GetMovieAlternativeTitles(id, s.language)
if err != nil {
return ""
}
for _, t := range alters.Titles {
if t.Iso3166_1 == "JP" && t.Type == "" {
return t.Title
}
}
return ""
}
func (s *Server) AddMovie2Watchlist(c *gin.Context) (interface{}, error) {
var in addWatchlistIn
if err := c.ShouldBindJSON(&in); err != nil {
@@ -208,8 +234,9 @@ func (s *Server) AddMovie2Watchlist(c *gin.Context) (interface{}, error) {
}
log.Infof("added dummy episode for movie: %v", nameEn)
r, err := s.db.AddMediaWatchlist(&ent.Media{
movie := ent.Media{
TmdbID: int(detail.ID),
ImdbID: detail.IMDbID,
MediaType: media.MediaTypeMovie,
NameCn: nameCn,
NameEn: nameEn,
@@ -219,8 +246,21 @@ 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},
}, []int{epid})
Limiter: schema.MediaLimiter{SizeMin: in.SizeMin, SizeMax: in.SizeMax},
}
extras := schema.MediaExtras{
IsAdultMovie: detail.Adult,
OriginalLanguage: detail.OriginalLanguage,
Genres: detail.Genres,
}
if isJav(detail) {
javid := s.getJavid(in.TmdbID)
extras.JavId = javid
}
movie.Extras = extras
r, err := s.db.AddMediaWatchlist(&movie, []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});
@@ -53,28 +54,99 @@ class _ActivityPageState extends ConsumerState<ActivityPage>
],
),
Builder(builder: (context) {
var activitiesWatcher = ref.watch(activitiesDataProvider("active"));
AsyncValue<List<Activity>>? activitiesWatcher;
if (selectedTab == 1) {
activitiesWatcher = ref.watch(activitiesDataProvider("archive"));
} else if (selectedTab == 0) {
activitiesWatcher = ref.watch(activitiesDataProvider("active"));
}
return activitiesWatcher.when(
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 == "seeding") {
//seeding
return Tooltip(
message: "做种中",
child: Icon(
Icons.keyboard_double_arrow_up,
color: Theme.of(context)
.colorScheme
.inversePrimary,
),
);
} 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()}"),
ac.seedRatio > 0
? Text("分享率:${ac.seedRatio}")
: SizedBox()
],
),
),
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 +164,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,20 @@ 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: TextButton(
onPressed: () => context.go(WelcomePage.routeTv),
child: Text(
"Polaris",
overflow: TextOverflow.clip,
style: TextStyle(fontSize: 28),
),
),
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 +289,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,8 @@ 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 downloadAllUrl = "$_baseUrl/api/v1/media/downloadall/";
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

@@ -5,7 +5,7 @@ import 'package:ui/providers/APIs.dart';
import 'package:ui/providers/server_response.dart';
var activitiesDataProvider =
AsyncNotifierProvider.family<ActivityData, List<Activity>, String>(
AsyncNotifierProvider.autoDispose.family<ActivityData, List<Activity>, String>(
ActivityData.new);
var mediaHistoryDataProvider = FutureProvider.autoDispose.family(
@@ -24,7 +24,7 @@ var mediaHistoryDataProvider = FutureProvider.autoDispose.family(
},
);
class ActivityData extends FamilyAsyncNotifier<List<Activity>, String> {
class ActivityData extends AutoDisposeFamilyAsyncNotifier<List<Activity>, String> {
@override
FutureOr<List<Activity>> build(String arg) async {
if (arg == "active") {
@@ -68,7 +68,9 @@ class Activity {
required this.targetDir,
required this.status,
required this.saved,
required this.progress});
required this.progress,
required this.size,
required this.seedRatio});
final int? id;
final int? mediaId;
@@ -79,6 +81,8 @@ class Activity {
final String? status;
final String? saved;
final int? progress;
final int? size;
final double seedRatio;
factory Activity.fromJson(Map<String, dynamic> json) {
return Activity(
@@ -90,6 +94,8 @@ class Activity {
targetDir: json["target_dir"],
status: json["status"],
saved: json["saved"],
progress: json["progress"]);
progress: json["progress"],
seedRatio: json["seed_ratio"],
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,42 @@ 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();
}
Future<dynamic> downloadall() async {
final dio = APIs.getDio();
var resp = await dio.get(APIs.downloadAllUrl + id!);
var sp = ServerResponse.fromJson(resp.data);
if (sp.code != 0) {
throw sp.message;
}
ref.invalidateSelf();
return sp.data;
}
}
class SeriesDetails {
int? id;
int? tmdbId;
String? imdbid;
String? name;
String? originalName;
String? overview;
@@ -79,10 +111,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 +129,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 +154,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

@@ -52,13 +52,19 @@ class GeneralSetting {
String? logLevel;
String? proxy;
bool? enablePlexmatch;
bool? allowQiangban;
bool? enableNfo;
bool? enableAdult;
GeneralSetting(
{this.tmdbApiKey,
this.downloadDIr,
this.logLevel,
this.proxy,
this.enablePlexmatch});
this.enablePlexmatch,
this.enableNfo,
this.allowQiangban,
this.enableAdult});
factory GeneralSetting.fromJson(Map<String, dynamic> json) {
return GeneralSetting(
@@ -66,6 +72,9 @@ class GeneralSetting {
downloadDIr: json["download_dir"],
logLevel: json["log_level"],
proxy: json["proxy"],
enableAdult: json["enable_adult_content"]??false,
allowQiangban: json["allow_qiangban"] ?? false,
enableNfo: json["enable_nfo"] ?? false,
enablePlexmatch: json["enable_plexmatch"] ?? false);
}
@@ -76,6 +85,9 @@ class GeneralSetting {
data["log_level"] = logLevel;
data["proxy"] = proxy;
data["enable_plexmatch"] = enablePlexmatch;
data["allow_qiangban"] = allowQiangban;
data["enable_nfo"] = enableNfo;
data["enable_adult_content"] = enableAdult;
return data;
}
}
@@ -134,7 +146,14 @@ class Indexer {
double? seedRatio;
bool? disabled;
Indexer({this.name, this.url, this.apiKey, this.id, this.priority=50, this.seedRatio=0, this.disabled});
Indexer(
{this.name,
this.url,
this.apiKey,
this.id,
this.priority = 50,
this.seedRatio = 0,
this.disabled});
Indexer.fromJson(Map<String, dynamic> json) {
name = json['name'];
@@ -142,7 +161,7 @@ class Indexer {
apiKey = json['api_key'];
id = json["id"];
priority = json["priority"];
seedRatio = json["seed_ratio"]??0;
seedRatio = json["seed_ratio"] ?? 0;
disabled = json["disabled"] ?? false;
}
Map<String, dynamic> toJson() {

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

@@ -34,7 +34,10 @@ class _GeneralState extends ConsumerState<GeneralSettings> {
"download_dir": v.downloadDIr,
"log_level": v.logLevel,
"proxy": v.proxy,
"enable_plexmatch": v.enablePlexmatch
"enable_plexmatch": v.enablePlexmatch,
"allow_qiangban": v.allowQiangban,
"enable_nfo": v.enableNfo,
"enable_adult": v.enableAdult,
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -81,8 +84,36 @@ class _GeneralState extends ConsumerState<GeneralSettings> {
),
SizedBox(
width: 300,
child: FormBuilderSwitch(decoration: const InputDecoration(icon: Icon(Icons.token)),
name: "enable_plexmatch", title: const Text("Plex 刮削支持")),
child: FormBuilderSwitch(
decoration:
const InputDecoration(icon: Icon(Icons.back_hand)),
name: "enable_adult",
title: const Text("是否显示成人内容")),
),
SizedBox(
width: 300,
child: FormBuilderSwitch(
decoration:
const InputDecoration(icon: Icon(Icons.token)),
name: "enable_plexmatch",
title: const Text("Plex 刮削支持")),
),
SizedBox(
width: 300,
child: FormBuilderSwitch(
decoration: const InputDecoration(
icon: Icon(Icons.library_books),
helperText: "emby/kodi等软件刮削需要"),
name: "enable_nfo",
title: const Text("nfo 文件支持")),
),
SizedBox(
width: 300,
child: FormBuilderSwitch(
decoration: const InputDecoration(
icon: Icon(Icons.remove_circle)),
name: "allow_qiangban",
title: const Text("是否下载枪版资源")),
),
Center(
child: Padding(
@@ -102,6 +133,9 @@ class _GeneralState extends ConsumerState<GeneralSettings> {
downloadDIr: values["download_dir"],
logLevel: values["log_level"],
proxy: values["proxy"],
allowQiangban: values["allow_qiangban"],
enableAdult: values["enable_adult"],
enableNfo: values["enable_nfo"],
enablePlexmatch:
values["enable_plexmatch"]))
.then((v) => showSnakeBar("更新成功"));

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,106 @@ 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 +186,133 @@ 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 LoadingIconButton(
tooltip: widget.details.mediaType == "tv" ? "查找并下载所有监控剧集" : "查找并下载此电影",
onPressed: () async {
await ref
.read(mediaDetailsProvider(widget.details.id.toString()).notifier)
.downloadall()
.then((list) => {
if (list != null) {showSnakeBar("开始下载:$list")}
});
},
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:

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 917 B

After

Width:  |  Height:  |  Size: 29 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 29 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.1 KiB

After

Width:  |  Height:  |  Size: 163 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 29 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 163 KiB