Compare commits

...

97 Commits

Author SHA1 Message Date
Simon Ding
89104785d7 fix: monitor lastest season 2024-09-23 23:12:06 +08:00
Simon Ding
f4ccc69b50 feat: trim white space 2024-09-23 22:44:15 +08:00
Simon Ding
40c6e2df5c fix: panic when torrent not exist 2024-09-21 21:47:26 +08:00
Simon Ding
37dfb0fe94 feat: add check 2024-09-21 21:23:47 +08:00
Simon Ding
9968f9f225 feat: add ability to change folder naming convention 2024-09-20 20:03:05 +08:00
Simon Ding
f5c977224b fix 2024-09-20 14:27:49 +08:00
Simon Ding
8af3ffccd3 fix: double downloading status problem 2024-09-20 11:40:22 +08:00
Simon Ding
c535dfd714 feat: do not use lowercase 2024-09-20 11:11:27 +08:00
Simon Ding
f696b78260 feat: default monitor lastest season all episodes 2024-09-20 11:03:01 +08:00
Simon Ding
4f3e3e399d feat: transmission use hash instead of id 2024-09-20 10:45:10 +08:00
Simon Ding
e4e3c9a851 fix: suggestted name when name_cn is in english 2024-09-07 13:45:27 +08:00
Simon Ding
bf608f933d feat: ui to manaul trigger cron jobs 2024-09-07 13:18:12 +08:00
Simon Ding
5923fc73e1 fix: new import list display 2024-09-04 16:51:49 +08:00
Simon Ding
c2d9ccfd4c chore: update ui details 2024-09-04 16:20:33 +08:00
Simon Ding
5d4429bf7c chore: update watchlist 2024-09-04 15:55:15 +08:00
Simon Ding
e4c111ac2a fix: cron jobs 2024-09-04 13:18:14 +08:00
Simon Ding
3e5e20e933 fix: naming 2024-09-03 10:04:56 +08:00
Simon Ding
ba1be8f279 feat: cron trigger api and fix import lists 2024-09-03 09:46:23 +08:00
Simon Ding
361556228b feat: add import list & calendar 2024-09-02 23:47:19 +08:00
Simon Ding
ca414a73ff fix: logout 2024-09-02 14:07:47 +08:00
Simon Ding
32b595e116 fix: change token name and same site lax rule 2024-09-02 13:59:36 +08:00
Simon Ding
b12bbd2ad9 fix: http auth 2024-09-02 13:45:49 +08:00
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
94 changed files with 6900 additions and 1079 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,33 @@ 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"
SetttingSizeLimiter = "size_limiter"
SettingTvNamingFormat = "tv_naming_format"
SettingMovieNamingFormat = "movie_naming_format"
)
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 (
@@ -31,6 +37,26 @@ const (
LanguageCN = "zh-CN"
)
const DefaultNamingFormat = "{{.NameCN}} {{.NameEN}} ({{.Year}})"
type NamingInfo struct {
NameCN string
NameEN string
Year string
TmdbID int
}
type ResolutionType string
const JwtSerectKey = "jwt_secrect_key"
const JwtSerectKey = "jwt_secrect_key"
type SizeLimiter struct {
R720p Limiter `json:"720p"`
R1080p Limiter `json:"1080p"`
R2160p Limiter `json:"2160p"`
}
type Limiter struct {
Max int `json:"max"`
Min int `json:"min"`
}

111
db/db.go
View File

@@ -9,8 +9,10 @@ import (
"polaris/ent/downloadclients"
"polaris/ent/episode"
"polaris/ent/history"
"polaris/ent/importlist"
"polaris/ent/indexers"
"polaris/ent/media"
"polaris/ent/schema"
"polaris/ent/settings"
"polaris/ent/storage"
"polaris/log"
@@ -87,8 +89,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,
})
}
@@ -117,7 +119,7 @@ func (c *Client) GetLanguage() string {
lang := c.GetSetting(SettingLanguage)
log.Infof("get application language: %s", lang)
if lang == "" {
return "zh-CN"
return LanguageCN
}
return lang
}
@@ -137,6 +139,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 +151,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 +253,6 @@ type TorznabSetting struct {
ApiKey string `json:"api_key"`
}
func (c *Client) SaveIndexer(in *ent.Indexers) error {
if in.ID != 0 {
@@ -265,7 +268,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 +288,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 +311,7 @@ func (c *Client) GetAllTorznabInfo() []*TorznabInfo {
continue
}
l = append(l, &TorznabInfo{
Indexers: r,
Indexers: r,
TorznabSetting: ss,
})
}
@@ -356,7 +360,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 +375,6 @@ func (s *StorageInfo) ToWebDavSetting() WebdavSetting {
}
}
type WebdavSetting struct {
URL string `json:"url"`
User string `json:"user"`
@@ -472,8 +475,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 +493,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
}
@@ -527,6 +530,16 @@ func (c *Client) SetEpisodeStatus(id int, status episode.Status) error {
return c.ent.Episode.Update().Where(episode.ID(id)).SetStatus(status).Exec(context.TODO())
}
func (c *Client) IsEpisodeDownloadingOrDownloaded(id int) bool {
his := c.ent.History.Query().Where(history.EpisodeID(id)).AllX(context.Background())
for _, h := range his {
if h.Status != history.StatusFail {
return true
}
}
return false
}
func (c *Client) SetSeasonAllEpisodeStatus(mediaID, seasonNum int, status episode.Status) error {
return c.ent.Episode.Update().Where(episode.MediaID(mediaID), episode.SeasonNumber(seasonNum)).SetStatus(status).Exec(context.TODO())
}
@@ -555,7 +568,79 @@ 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())
}
func (c *Client) GetAllImportLists() ([]*ent.ImportList, error) {
return c.ent.ImportList.Query().All(context.Background())
}
func (c *Client) AddImportlist(il *ent.ImportList) error {
count, err := c.ent.ImportList.Query().Where(importlist.Name(il.Name)).Count(context.Background())
if err != nil {
return err
}
if count > 0 {
//edit exist record
return c.ent.ImportList.Update().Where(importlist.Name(il.Name)).
SetURL(il.URL).SetQulity(il.Qulity).SetType(il.Type).SetStorageID(il.StorageID).Exec(context.Background())
}
return c.ent.ImportList.Create().SetName(il.Name).SetURL(il.URL).SetQulity(il.Qulity).SetStorageID(il.StorageID).
SetType(il.Type).Exec(context.Background())
}
func (c *Client) DeleteImportlist(id int) error {
return c.ent.ImportList.DeleteOneID(id).Exec(context.TODO())
}
func (c *Client) GetSizeLimiter() (*SizeLimiter, error) {
v := c.GetSetting(SetttingSizeLimiter)
var limiter SizeLimiter
err := json.Unmarshal([]byte(v), &limiter)
return &limiter, err
}
func (c *Client) SetSizeLimiter(limiter *SizeLimiter) error {
data, err := json.Marshal(limiter)
if err != nil {
return err
}
return c.SetSetting(SetttingSizeLimiter, string(data))
}
func (c *Client) GetTvNamingFormat() string {
s := c.GetSetting(SettingTvNamingFormat)
if s == "" {
return DefaultNamingFormat
}
return s
}
func (c *Client) GetMovingNamingFormat() string {
s := c.GetSetting(SettingMovieNamingFormat)
if s == "" {
return DefaultNamingFormat
}
return s
}

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 MiB

After

Width:  |  Height:  |  Size: 2.6 MiB

View File

@@ -14,6 +14,7 @@ import (
"polaris/ent/downloadclients"
"polaris/ent/episode"
"polaris/ent/history"
"polaris/ent/importlist"
"polaris/ent/indexers"
"polaris/ent/media"
"polaris/ent/notificationclient"
@@ -37,6 +38,8 @@ type Client struct {
Episode *EpisodeClient
// History is the client for interacting with the History builders.
History *HistoryClient
// ImportList is the client for interacting with the ImportList builders.
ImportList *ImportListClient
// Indexers is the client for interacting with the Indexers builders.
Indexers *IndexersClient
// Media is the client for interacting with the Media builders.
@@ -61,6 +64,7 @@ func (c *Client) init() {
c.DownloadClients = NewDownloadClientsClient(c.config)
c.Episode = NewEpisodeClient(c.config)
c.History = NewHistoryClient(c.config)
c.ImportList = NewImportListClient(c.config)
c.Indexers = NewIndexersClient(c.config)
c.Media = NewMediaClient(c.config)
c.NotificationClient = NewNotificationClientClient(c.config)
@@ -161,6 +165,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
DownloadClients: NewDownloadClientsClient(cfg),
Episode: NewEpisodeClient(cfg),
History: NewHistoryClient(cfg),
ImportList: NewImportListClient(cfg),
Indexers: NewIndexersClient(cfg),
Media: NewMediaClient(cfg),
NotificationClient: NewNotificationClientClient(cfg),
@@ -188,6 +193,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
DownloadClients: NewDownloadClientsClient(cfg),
Episode: NewEpisodeClient(cfg),
History: NewHistoryClient(cfg),
ImportList: NewImportListClient(cfg),
Indexers: NewIndexersClient(cfg),
Media: NewMediaClient(cfg),
NotificationClient: NewNotificationClientClient(cfg),
@@ -222,7 +228,7 @@ func (c *Client) Close() error {
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) {
for _, n := range []interface{ Use(...Hook) }{
c.DownloadClients, c.Episode, c.History, c.Indexers, c.Media,
c.DownloadClients, c.Episode, c.History, c.ImportList, c.Indexers, c.Media,
c.NotificationClient, c.Settings, c.Storage,
} {
n.Use(hooks...)
@@ -233,7 +239,7 @@ func (c *Client) Use(hooks ...Hook) {
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
func (c *Client) Intercept(interceptors ...Interceptor) {
for _, n := range []interface{ Intercept(...Interceptor) }{
c.DownloadClients, c.Episode, c.History, c.Indexers, c.Media,
c.DownloadClients, c.Episode, c.History, c.ImportList, c.Indexers, c.Media,
c.NotificationClient, c.Settings, c.Storage,
} {
n.Intercept(interceptors...)
@@ -249,6 +255,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
return c.Episode.mutate(ctx, m)
case *HistoryMutation:
return c.History.mutate(ctx, m)
case *ImportListMutation:
return c.ImportList.mutate(ctx, m)
case *IndexersMutation:
return c.Indexers.mutate(ctx, m)
case *MediaMutation:
@@ -679,6 +687,139 @@ func (c *HistoryClient) mutate(ctx context.Context, m *HistoryMutation) (Value,
}
}
// ImportListClient is a client for the ImportList schema.
type ImportListClient struct {
config
}
// NewImportListClient returns a client for the ImportList from the given config.
func NewImportListClient(c config) *ImportListClient {
return &ImportListClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `importlist.Hooks(f(g(h())))`.
func (c *ImportListClient) Use(hooks ...Hook) {
c.hooks.ImportList = append(c.hooks.ImportList, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `importlist.Intercept(f(g(h())))`.
func (c *ImportListClient) Intercept(interceptors ...Interceptor) {
c.inters.ImportList = append(c.inters.ImportList, interceptors...)
}
// Create returns a builder for creating a ImportList entity.
func (c *ImportListClient) Create() *ImportListCreate {
mutation := newImportListMutation(c.config, OpCreate)
return &ImportListCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of ImportList entities.
func (c *ImportListClient) CreateBulk(builders ...*ImportListCreate) *ImportListCreateBulk {
return &ImportListCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *ImportListClient) MapCreateBulk(slice any, setFunc func(*ImportListCreate, int)) *ImportListCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &ImportListCreateBulk{err: fmt.Errorf("calling to ImportListClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*ImportListCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &ImportListCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for ImportList.
func (c *ImportListClient) Update() *ImportListUpdate {
mutation := newImportListMutation(c.config, OpUpdate)
return &ImportListUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *ImportListClient) UpdateOne(il *ImportList) *ImportListUpdateOne {
mutation := newImportListMutation(c.config, OpUpdateOne, withImportList(il))
return &ImportListUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *ImportListClient) UpdateOneID(id int) *ImportListUpdateOne {
mutation := newImportListMutation(c.config, OpUpdateOne, withImportListID(id))
return &ImportListUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for ImportList.
func (c *ImportListClient) Delete() *ImportListDelete {
mutation := newImportListMutation(c.config, OpDelete)
return &ImportListDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *ImportListClient) DeleteOne(il *ImportList) *ImportListDeleteOne {
return c.DeleteOneID(il.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *ImportListClient) DeleteOneID(id int) *ImportListDeleteOne {
builder := c.Delete().Where(importlist.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &ImportListDeleteOne{builder}
}
// Query returns a query builder for ImportList.
func (c *ImportListClient) Query() *ImportListQuery {
return &ImportListQuery{
config: c.config,
ctx: &QueryContext{Type: TypeImportList},
inters: c.Interceptors(),
}
}
// Get returns a ImportList entity by its id.
func (c *ImportListClient) Get(ctx context.Context, id int) (*ImportList, error) {
return c.Query().Where(importlist.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *ImportListClient) GetX(ctx context.Context, id int) *ImportList {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *ImportListClient) Hooks() []Hook {
return c.hooks.ImportList
}
// Interceptors returns the client interceptors.
func (c *ImportListClient) Interceptors() []Interceptor {
return c.inters.ImportList
}
func (c *ImportListClient) mutate(ctx context.Context, m *ImportListMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&ImportListCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&ImportListUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&ImportListUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&ImportListDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown ImportList mutation op: %q", m.Op())
}
}
// IndexersClient is a client for the Indexers schema.
type IndexersClient struct {
config
@@ -1363,11 +1504,11 @@ func (c *StorageClient) mutate(ctx context.Context, m *StorageMutation) (Value,
// hooks and interceptors per client, for fast access.
type (
hooks struct {
DownloadClients, Episode, History, Indexers, Media, NotificationClient,
Settings, Storage []ent.Hook
DownloadClients, Episode, History, ImportList, Indexers, Media,
NotificationClient, Settings, Storage []ent.Hook
}
inters struct {
DownloadClients, Episode, History, Indexers, Media, NotificationClient,
Settings, Storage []ent.Interceptor
DownloadClients, Episode, History, ImportList, Indexers, Media,
NotificationClient, Settings, Storage []ent.Interceptor
}
)

View File

@@ -9,6 +9,7 @@ import (
"polaris/ent/downloadclients"
"polaris/ent/episode"
"polaris/ent/history"
"polaris/ent/importlist"
"polaris/ent/indexers"
"polaris/ent/media"
"polaris/ent/notificationclient"
@@ -83,6 +84,7 @@ func checkColumn(table, column string) error {
downloadclients.Table: downloadclients.ValidColumn,
episode.Table: episode.ValidColumn,
history.Table: history.ValidColumn,
importlist.Table: importlist.ValidColumn,
indexers.Table: indexers.ValidColumn,
media.Table: media.ValidColumn,
notificationclient.Table: notificationclient.ValidColumn,

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

@@ -44,6 +44,18 @@ func (f HistoryFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, err
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.HistoryMutation", m)
}
// The ImportListFunc type is an adapter to allow the use of ordinary
// function as ImportList mutator.
type ImportListFunc func(context.Context, *ent.ImportListMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f ImportListFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.ImportListMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ImportListMutation", m)
}
// The IndexersFunc type is an adapter to allow the use of ordinary
// function as Indexers mutator.
type IndexersFunc func(context.Context, *ent.IndexersMutation) (ent.Value, error)

164
ent/importlist.go Normal file
View File

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

View File

@@ -0,0 +1,107 @@
// Code generated by ent, DO NOT EDIT.
package importlist
import (
"fmt"
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the importlist type in the database.
Label = "import_list"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldType holds the string denoting the type field in the database.
FieldType = "type"
// FieldURL holds the string denoting the url field in the database.
FieldURL = "url"
// FieldQulity holds the string denoting the qulity field in the database.
FieldQulity = "qulity"
// FieldStorageID holds the string denoting the storage_id field in the database.
FieldStorageID = "storage_id"
// FieldSettings holds the string denoting the settings field in the database.
FieldSettings = "settings"
// Table holds the table name of the importlist in the database.
Table = "import_lists"
)
// Columns holds all SQL columns for importlist fields.
var Columns = []string{
FieldID,
FieldName,
FieldType,
FieldURL,
FieldQulity,
FieldStorageID,
FieldSettings,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
// Type defines the type for the "type" enum field.
type Type string
// Type values.
const (
TypePlex Type = "plex"
TypeDoulist Type = "doulist"
)
func (_type Type) String() string {
return string(_type)
}
// TypeValidator is a validator for the "type" field enum values. It is called by the builders before save.
func TypeValidator(_type Type) error {
switch _type {
case TypePlex, TypeDoulist:
return nil
default:
return fmt.Errorf("importlist: invalid enum value for type field: %q", _type)
}
}
// OrderOption defines the ordering options for the ImportList queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByType orders the results by the type field.
func ByType(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldType, opts...).ToFunc()
}
// ByURL orders the results by the url field.
func ByURL(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldURL, opts...).ToFunc()
}
// ByQulity orders the results by the qulity field.
func ByQulity(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldQulity, opts...).ToFunc()
}
// ByStorageID orders the results by the storage_id field.
func ByStorageID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldStorageID, opts...).ToFunc()
}

364
ent/importlist/where.go Normal file
View File

@@ -0,0 +1,364 @@
// Code generated by ent, DO NOT EDIT.
package importlist
import (
"polaris/ent/predicate"
"entgo.io/ent/dialect/sql"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.ImportList {
return predicate.ImportList(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.ImportList {
return predicate.ImportList(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.ImportList {
return predicate.ImportList(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.ImportList {
return predicate.ImportList(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.ImportList {
return predicate.ImportList(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.ImportList {
return predicate.ImportList(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.ImportList {
return predicate.ImportList(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.ImportList {
return predicate.ImportList(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.ImportList {
return predicate.ImportList(sql.FieldLTE(FieldID, id))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldEQ(FieldName, v))
}
// URL applies equality check predicate on the "url" field. It's identical to URLEQ.
func URL(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldEQ(FieldURL, v))
}
// Qulity applies equality check predicate on the "qulity" field. It's identical to QulityEQ.
func Qulity(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldEQ(FieldQulity, v))
}
// StorageID applies equality check predicate on the "storage_id" field. It's identical to StorageIDEQ.
func StorageID(v int) predicate.ImportList {
return predicate.ImportList(sql.FieldEQ(FieldStorageID, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.ImportList {
return predicate.ImportList(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.ImportList {
return predicate.ImportList(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldContainsFold(FieldName, v))
}
// TypeEQ applies the EQ predicate on the "type" field.
func TypeEQ(v Type) predicate.ImportList {
return predicate.ImportList(sql.FieldEQ(FieldType, v))
}
// TypeNEQ applies the NEQ predicate on the "type" field.
func TypeNEQ(v Type) predicate.ImportList {
return predicate.ImportList(sql.FieldNEQ(FieldType, v))
}
// TypeIn applies the In predicate on the "type" field.
func TypeIn(vs ...Type) predicate.ImportList {
return predicate.ImportList(sql.FieldIn(FieldType, vs...))
}
// TypeNotIn applies the NotIn predicate on the "type" field.
func TypeNotIn(vs ...Type) predicate.ImportList {
return predicate.ImportList(sql.FieldNotIn(FieldType, vs...))
}
// URLEQ applies the EQ predicate on the "url" field.
func URLEQ(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldEQ(FieldURL, v))
}
// URLNEQ applies the NEQ predicate on the "url" field.
func URLNEQ(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldNEQ(FieldURL, v))
}
// URLIn applies the In predicate on the "url" field.
func URLIn(vs ...string) predicate.ImportList {
return predicate.ImportList(sql.FieldIn(FieldURL, vs...))
}
// URLNotIn applies the NotIn predicate on the "url" field.
func URLNotIn(vs ...string) predicate.ImportList {
return predicate.ImportList(sql.FieldNotIn(FieldURL, vs...))
}
// URLGT applies the GT predicate on the "url" field.
func URLGT(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldGT(FieldURL, v))
}
// URLGTE applies the GTE predicate on the "url" field.
func URLGTE(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldGTE(FieldURL, v))
}
// URLLT applies the LT predicate on the "url" field.
func URLLT(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldLT(FieldURL, v))
}
// URLLTE applies the LTE predicate on the "url" field.
func URLLTE(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldLTE(FieldURL, v))
}
// URLContains applies the Contains predicate on the "url" field.
func URLContains(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldContains(FieldURL, v))
}
// URLHasPrefix applies the HasPrefix predicate on the "url" field.
func URLHasPrefix(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldHasPrefix(FieldURL, v))
}
// URLHasSuffix applies the HasSuffix predicate on the "url" field.
func URLHasSuffix(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldHasSuffix(FieldURL, v))
}
// URLIsNil applies the IsNil predicate on the "url" field.
func URLIsNil() predicate.ImportList {
return predicate.ImportList(sql.FieldIsNull(FieldURL))
}
// URLNotNil applies the NotNil predicate on the "url" field.
func URLNotNil() predicate.ImportList {
return predicate.ImportList(sql.FieldNotNull(FieldURL))
}
// URLEqualFold applies the EqualFold predicate on the "url" field.
func URLEqualFold(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldEqualFold(FieldURL, v))
}
// URLContainsFold applies the ContainsFold predicate on the "url" field.
func URLContainsFold(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldContainsFold(FieldURL, v))
}
// QulityEQ applies the EQ predicate on the "qulity" field.
func QulityEQ(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldEQ(FieldQulity, v))
}
// QulityNEQ applies the NEQ predicate on the "qulity" field.
func QulityNEQ(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldNEQ(FieldQulity, v))
}
// QulityIn applies the In predicate on the "qulity" field.
func QulityIn(vs ...string) predicate.ImportList {
return predicate.ImportList(sql.FieldIn(FieldQulity, vs...))
}
// QulityNotIn applies the NotIn predicate on the "qulity" field.
func QulityNotIn(vs ...string) predicate.ImportList {
return predicate.ImportList(sql.FieldNotIn(FieldQulity, vs...))
}
// QulityGT applies the GT predicate on the "qulity" field.
func QulityGT(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldGT(FieldQulity, v))
}
// QulityGTE applies the GTE predicate on the "qulity" field.
func QulityGTE(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldGTE(FieldQulity, v))
}
// QulityLT applies the LT predicate on the "qulity" field.
func QulityLT(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldLT(FieldQulity, v))
}
// QulityLTE applies the LTE predicate on the "qulity" field.
func QulityLTE(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldLTE(FieldQulity, v))
}
// QulityContains applies the Contains predicate on the "qulity" field.
func QulityContains(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldContains(FieldQulity, v))
}
// QulityHasPrefix applies the HasPrefix predicate on the "qulity" field.
func QulityHasPrefix(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldHasPrefix(FieldQulity, v))
}
// QulityHasSuffix applies the HasSuffix predicate on the "qulity" field.
func QulityHasSuffix(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldHasSuffix(FieldQulity, v))
}
// QulityEqualFold applies the EqualFold predicate on the "qulity" field.
func QulityEqualFold(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldEqualFold(FieldQulity, v))
}
// QulityContainsFold applies the ContainsFold predicate on the "qulity" field.
func QulityContainsFold(v string) predicate.ImportList {
return predicate.ImportList(sql.FieldContainsFold(FieldQulity, v))
}
// StorageIDEQ applies the EQ predicate on the "storage_id" field.
func StorageIDEQ(v int) predicate.ImportList {
return predicate.ImportList(sql.FieldEQ(FieldStorageID, v))
}
// StorageIDNEQ applies the NEQ predicate on the "storage_id" field.
func StorageIDNEQ(v int) predicate.ImportList {
return predicate.ImportList(sql.FieldNEQ(FieldStorageID, v))
}
// StorageIDIn applies the In predicate on the "storage_id" field.
func StorageIDIn(vs ...int) predicate.ImportList {
return predicate.ImportList(sql.FieldIn(FieldStorageID, vs...))
}
// StorageIDNotIn applies the NotIn predicate on the "storage_id" field.
func StorageIDNotIn(vs ...int) predicate.ImportList {
return predicate.ImportList(sql.FieldNotIn(FieldStorageID, vs...))
}
// StorageIDGT applies the GT predicate on the "storage_id" field.
func StorageIDGT(v int) predicate.ImportList {
return predicate.ImportList(sql.FieldGT(FieldStorageID, v))
}
// StorageIDGTE applies the GTE predicate on the "storage_id" field.
func StorageIDGTE(v int) predicate.ImportList {
return predicate.ImportList(sql.FieldGTE(FieldStorageID, v))
}
// StorageIDLT applies the LT predicate on the "storage_id" field.
func StorageIDLT(v int) predicate.ImportList {
return predicate.ImportList(sql.FieldLT(FieldStorageID, v))
}
// StorageIDLTE applies the LTE predicate on the "storage_id" field.
func StorageIDLTE(v int) predicate.ImportList {
return predicate.ImportList(sql.FieldLTE(FieldStorageID, v))
}
// SettingsIsNil applies the IsNil predicate on the "settings" field.
func SettingsIsNil() predicate.ImportList {
return predicate.ImportList(sql.FieldIsNull(FieldSettings))
}
// SettingsNotNil applies the NotNil predicate on the "settings" field.
func SettingsNotNil() predicate.ImportList {
return predicate.ImportList(sql.FieldNotNull(FieldSettings))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.ImportList) predicate.ImportList {
return predicate.ImportList(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.ImportList) predicate.ImportList {
return predicate.ImportList(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.ImportList) predicate.ImportList {
return predicate.ImportList(sql.NotPredicates(p))
}

264
ent/importlist_create.go Normal file
View File

@@ -0,0 +1,264 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"polaris/ent/importlist"
"polaris/ent/schema"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// ImportListCreate is the builder for creating a ImportList entity.
type ImportListCreate struct {
config
mutation *ImportListMutation
hooks []Hook
}
// SetName sets the "name" field.
func (ilc *ImportListCreate) SetName(s string) *ImportListCreate {
ilc.mutation.SetName(s)
return ilc
}
// SetType sets the "type" field.
func (ilc *ImportListCreate) SetType(i importlist.Type) *ImportListCreate {
ilc.mutation.SetType(i)
return ilc
}
// SetURL sets the "url" field.
func (ilc *ImportListCreate) SetURL(s string) *ImportListCreate {
ilc.mutation.SetURL(s)
return ilc
}
// SetNillableURL sets the "url" field if the given value is not nil.
func (ilc *ImportListCreate) SetNillableURL(s *string) *ImportListCreate {
if s != nil {
ilc.SetURL(*s)
}
return ilc
}
// SetQulity sets the "qulity" field.
func (ilc *ImportListCreate) SetQulity(s string) *ImportListCreate {
ilc.mutation.SetQulity(s)
return ilc
}
// SetStorageID sets the "storage_id" field.
func (ilc *ImportListCreate) SetStorageID(i int) *ImportListCreate {
ilc.mutation.SetStorageID(i)
return ilc
}
// SetSettings sets the "settings" field.
func (ilc *ImportListCreate) SetSettings(sls schema.ImportListSettings) *ImportListCreate {
ilc.mutation.SetSettings(sls)
return ilc
}
// SetNillableSettings sets the "settings" field if the given value is not nil.
func (ilc *ImportListCreate) SetNillableSettings(sls *schema.ImportListSettings) *ImportListCreate {
if sls != nil {
ilc.SetSettings(*sls)
}
return ilc
}
// Mutation returns the ImportListMutation object of the builder.
func (ilc *ImportListCreate) Mutation() *ImportListMutation {
return ilc.mutation
}
// Save creates the ImportList in the database.
func (ilc *ImportListCreate) Save(ctx context.Context) (*ImportList, error) {
return withHooks(ctx, ilc.sqlSave, ilc.mutation, ilc.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (ilc *ImportListCreate) SaveX(ctx context.Context) *ImportList {
v, err := ilc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (ilc *ImportListCreate) Exec(ctx context.Context) error {
_, err := ilc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ilc *ImportListCreate) ExecX(ctx context.Context) {
if err := ilc.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (ilc *ImportListCreate) check() error {
if _, ok := ilc.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "ImportList.name"`)}
}
if _, ok := ilc.mutation.GetType(); !ok {
return &ValidationError{Name: "type", err: errors.New(`ent: missing required field "ImportList.type"`)}
}
if v, ok := ilc.mutation.GetType(); ok {
if err := importlist.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "ImportList.type": %w`, err)}
}
}
if _, ok := ilc.mutation.Qulity(); !ok {
return &ValidationError{Name: "qulity", err: errors.New(`ent: missing required field "ImportList.qulity"`)}
}
if _, ok := ilc.mutation.StorageID(); !ok {
return &ValidationError{Name: "storage_id", err: errors.New(`ent: missing required field "ImportList.storage_id"`)}
}
return nil
}
func (ilc *ImportListCreate) sqlSave(ctx context.Context) (*ImportList, error) {
if err := ilc.check(); err != nil {
return nil, err
}
_node, _spec := ilc.createSpec()
if err := sqlgraph.CreateNode(ctx, ilc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
ilc.mutation.id = &_node.ID
ilc.mutation.done = true
return _node, nil
}
func (ilc *ImportListCreate) createSpec() (*ImportList, *sqlgraph.CreateSpec) {
var (
_node = &ImportList{config: ilc.config}
_spec = sqlgraph.NewCreateSpec(importlist.Table, sqlgraph.NewFieldSpec(importlist.FieldID, field.TypeInt))
)
if value, ok := ilc.mutation.Name(); ok {
_spec.SetField(importlist.FieldName, field.TypeString, value)
_node.Name = value
}
if value, ok := ilc.mutation.GetType(); ok {
_spec.SetField(importlist.FieldType, field.TypeEnum, value)
_node.Type = value
}
if value, ok := ilc.mutation.URL(); ok {
_spec.SetField(importlist.FieldURL, field.TypeString, value)
_node.URL = value
}
if value, ok := ilc.mutation.Qulity(); ok {
_spec.SetField(importlist.FieldQulity, field.TypeString, value)
_node.Qulity = value
}
if value, ok := ilc.mutation.StorageID(); ok {
_spec.SetField(importlist.FieldStorageID, field.TypeInt, value)
_node.StorageID = value
}
if value, ok := ilc.mutation.Settings(); ok {
_spec.SetField(importlist.FieldSettings, field.TypeJSON, value)
_node.Settings = value
}
return _node, _spec
}
// ImportListCreateBulk is the builder for creating many ImportList entities in bulk.
type ImportListCreateBulk struct {
config
err error
builders []*ImportListCreate
}
// Save creates the ImportList entities in the database.
func (ilcb *ImportListCreateBulk) Save(ctx context.Context) ([]*ImportList, error) {
if ilcb.err != nil {
return nil, ilcb.err
}
specs := make([]*sqlgraph.CreateSpec, len(ilcb.builders))
nodes := make([]*ImportList, len(ilcb.builders))
mutators := make([]Mutator, len(ilcb.builders))
for i := range ilcb.builders {
func(i int, root context.Context) {
builder := ilcb.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ImportListMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, ilcb.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, ilcb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, ilcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (ilcb *ImportListCreateBulk) SaveX(ctx context.Context) []*ImportList {
v, err := ilcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (ilcb *ImportListCreateBulk) Exec(ctx context.Context) error {
_, err := ilcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ilcb *ImportListCreateBulk) ExecX(ctx context.Context) {
if err := ilcb.Exec(ctx); err != nil {
panic(err)
}
}

88
ent/importlist_delete.go Normal file
View File

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

526
ent/importlist_query.go Normal file
View File

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

462
ent/importlist_update.go Normal file
View File

@@ -0,0 +1,462 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"polaris/ent/importlist"
"polaris/ent/predicate"
"polaris/ent/schema"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// ImportListUpdate is the builder for updating ImportList entities.
type ImportListUpdate struct {
config
hooks []Hook
mutation *ImportListMutation
}
// Where appends a list predicates to the ImportListUpdate builder.
func (ilu *ImportListUpdate) Where(ps ...predicate.ImportList) *ImportListUpdate {
ilu.mutation.Where(ps...)
return ilu
}
// SetName sets the "name" field.
func (ilu *ImportListUpdate) SetName(s string) *ImportListUpdate {
ilu.mutation.SetName(s)
return ilu
}
// SetNillableName sets the "name" field if the given value is not nil.
func (ilu *ImportListUpdate) SetNillableName(s *string) *ImportListUpdate {
if s != nil {
ilu.SetName(*s)
}
return ilu
}
// SetType sets the "type" field.
func (ilu *ImportListUpdate) SetType(i importlist.Type) *ImportListUpdate {
ilu.mutation.SetType(i)
return ilu
}
// SetNillableType sets the "type" field if the given value is not nil.
func (ilu *ImportListUpdate) SetNillableType(i *importlist.Type) *ImportListUpdate {
if i != nil {
ilu.SetType(*i)
}
return ilu
}
// SetURL sets the "url" field.
func (ilu *ImportListUpdate) SetURL(s string) *ImportListUpdate {
ilu.mutation.SetURL(s)
return ilu
}
// SetNillableURL sets the "url" field if the given value is not nil.
func (ilu *ImportListUpdate) SetNillableURL(s *string) *ImportListUpdate {
if s != nil {
ilu.SetURL(*s)
}
return ilu
}
// ClearURL clears the value of the "url" field.
func (ilu *ImportListUpdate) ClearURL() *ImportListUpdate {
ilu.mutation.ClearURL()
return ilu
}
// SetQulity sets the "qulity" field.
func (ilu *ImportListUpdate) SetQulity(s string) *ImportListUpdate {
ilu.mutation.SetQulity(s)
return ilu
}
// SetNillableQulity sets the "qulity" field if the given value is not nil.
func (ilu *ImportListUpdate) SetNillableQulity(s *string) *ImportListUpdate {
if s != nil {
ilu.SetQulity(*s)
}
return ilu
}
// SetStorageID sets the "storage_id" field.
func (ilu *ImportListUpdate) SetStorageID(i int) *ImportListUpdate {
ilu.mutation.ResetStorageID()
ilu.mutation.SetStorageID(i)
return ilu
}
// SetNillableStorageID sets the "storage_id" field if the given value is not nil.
func (ilu *ImportListUpdate) SetNillableStorageID(i *int) *ImportListUpdate {
if i != nil {
ilu.SetStorageID(*i)
}
return ilu
}
// AddStorageID adds i to the "storage_id" field.
func (ilu *ImportListUpdate) AddStorageID(i int) *ImportListUpdate {
ilu.mutation.AddStorageID(i)
return ilu
}
// SetSettings sets the "settings" field.
func (ilu *ImportListUpdate) SetSettings(sls schema.ImportListSettings) *ImportListUpdate {
ilu.mutation.SetSettings(sls)
return ilu
}
// SetNillableSettings sets the "settings" field if the given value is not nil.
func (ilu *ImportListUpdate) SetNillableSettings(sls *schema.ImportListSettings) *ImportListUpdate {
if sls != nil {
ilu.SetSettings(*sls)
}
return ilu
}
// ClearSettings clears the value of the "settings" field.
func (ilu *ImportListUpdate) ClearSettings() *ImportListUpdate {
ilu.mutation.ClearSettings()
return ilu
}
// Mutation returns the ImportListMutation object of the builder.
func (ilu *ImportListUpdate) Mutation() *ImportListMutation {
return ilu.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (ilu *ImportListUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, ilu.sqlSave, ilu.mutation, ilu.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (ilu *ImportListUpdate) SaveX(ctx context.Context) int {
affected, err := ilu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (ilu *ImportListUpdate) Exec(ctx context.Context) error {
_, err := ilu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ilu *ImportListUpdate) ExecX(ctx context.Context) {
if err := ilu.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (ilu *ImportListUpdate) check() error {
if v, ok := ilu.mutation.GetType(); ok {
if err := importlist.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "ImportList.type": %w`, err)}
}
}
return nil
}
func (ilu *ImportListUpdate) sqlSave(ctx context.Context) (n int, err error) {
if err := ilu.check(); err != nil {
return n, err
}
_spec := sqlgraph.NewUpdateSpec(importlist.Table, importlist.Columns, sqlgraph.NewFieldSpec(importlist.FieldID, field.TypeInt))
if ps := ilu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := ilu.mutation.Name(); ok {
_spec.SetField(importlist.FieldName, field.TypeString, value)
}
if value, ok := ilu.mutation.GetType(); ok {
_spec.SetField(importlist.FieldType, field.TypeEnum, value)
}
if value, ok := ilu.mutation.URL(); ok {
_spec.SetField(importlist.FieldURL, field.TypeString, value)
}
if ilu.mutation.URLCleared() {
_spec.ClearField(importlist.FieldURL, field.TypeString)
}
if value, ok := ilu.mutation.Qulity(); ok {
_spec.SetField(importlist.FieldQulity, field.TypeString, value)
}
if value, ok := ilu.mutation.StorageID(); ok {
_spec.SetField(importlist.FieldStorageID, field.TypeInt, value)
}
if value, ok := ilu.mutation.AddedStorageID(); ok {
_spec.AddField(importlist.FieldStorageID, field.TypeInt, value)
}
if value, ok := ilu.mutation.Settings(); ok {
_spec.SetField(importlist.FieldSettings, field.TypeJSON, value)
}
if ilu.mutation.SettingsCleared() {
_spec.ClearField(importlist.FieldSettings, field.TypeJSON)
}
if n, err = sqlgraph.UpdateNodes(ctx, ilu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{importlist.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
ilu.mutation.done = true
return n, nil
}
// ImportListUpdateOne is the builder for updating a single ImportList entity.
type ImportListUpdateOne struct {
config
fields []string
hooks []Hook
mutation *ImportListMutation
}
// SetName sets the "name" field.
func (iluo *ImportListUpdateOne) SetName(s string) *ImportListUpdateOne {
iluo.mutation.SetName(s)
return iluo
}
// SetNillableName sets the "name" field if the given value is not nil.
func (iluo *ImportListUpdateOne) SetNillableName(s *string) *ImportListUpdateOne {
if s != nil {
iluo.SetName(*s)
}
return iluo
}
// SetType sets the "type" field.
func (iluo *ImportListUpdateOne) SetType(i importlist.Type) *ImportListUpdateOne {
iluo.mutation.SetType(i)
return iluo
}
// SetNillableType sets the "type" field if the given value is not nil.
func (iluo *ImportListUpdateOne) SetNillableType(i *importlist.Type) *ImportListUpdateOne {
if i != nil {
iluo.SetType(*i)
}
return iluo
}
// SetURL sets the "url" field.
func (iluo *ImportListUpdateOne) SetURL(s string) *ImportListUpdateOne {
iluo.mutation.SetURL(s)
return iluo
}
// SetNillableURL sets the "url" field if the given value is not nil.
func (iluo *ImportListUpdateOne) SetNillableURL(s *string) *ImportListUpdateOne {
if s != nil {
iluo.SetURL(*s)
}
return iluo
}
// ClearURL clears the value of the "url" field.
func (iluo *ImportListUpdateOne) ClearURL() *ImportListUpdateOne {
iluo.mutation.ClearURL()
return iluo
}
// SetQulity sets the "qulity" field.
func (iluo *ImportListUpdateOne) SetQulity(s string) *ImportListUpdateOne {
iluo.mutation.SetQulity(s)
return iluo
}
// SetNillableQulity sets the "qulity" field if the given value is not nil.
func (iluo *ImportListUpdateOne) SetNillableQulity(s *string) *ImportListUpdateOne {
if s != nil {
iluo.SetQulity(*s)
}
return iluo
}
// SetStorageID sets the "storage_id" field.
func (iluo *ImportListUpdateOne) SetStorageID(i int) *ImportListUpdateOne {
iluo.mutation.ResetStorageID()
iluo.mutation.SetStorageID(i)
return iluo
}
// SetNillableStorageID sets the "storage_id" field if the given value is not nil.
func (iluo *ImportListUpdateOne) SetNillableStorageID(i *int) *ImportListUpdateOne {
if i != nil {
iluo.SetStorageID(*i)
}
return iluo
}
// AddStorageID adds i to the "storage_id" field.
func (iluo *ImportListUpdateOne) AddStorageID(i int) *ImportListUpdateOne {
iluo.mutation.AddStorageID(i)
return iluo
}
// SetSettings sets the "settings" field.
func (iluo *ImportListUpdateOne) SetSettings(sls schema.ImportListSettings) *ImportListUpdateOne {
iluo.mutation.SetSettings(sls)
return iluo
}
// SetNillableSettings sets the "settings" field if the given value is not nil.
func (iluo *ImportListUpdateOne) SetNillableSettings(sls *schema.ImportListSettings) *ImportListUpdateOne {
if sls != nil {
iluo.SetSettings(*sls)
}
return iluo
}
// ClearSettings clears the value of the "settings" field.
func (iluo *ImportListUpdateOne) ClearSettings() *ImportListUpdateOne {
iluo.mutation.ClearSettings()
return iluo
}
// Mutation returns the ImportListMutation object of the builder.
func (iluo *ImportListUpdateOne) Mutation() *ImportListMutation {
return iluo.mutation
}
// Where appends a list predicates to the ImportListUpdate builder.
func (iluo *ImportListUpdateOne) Where(ps ...predicate.ImportList) *ImportListUpdateOne {
iluo.mutation.Where(ps...)
return iluo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (iluo *ImportListUpdateOne) Select(field string, fields ...string) *ImportListUpdateOne {
iluo.fields = append([]string{field}, fields...)
return iluo
}
// Save executes the query and returns the updated ImportList entity.
func (iluo *ImportListUpdateOne) Save(ctx context.Context) (*ImportList, error) {
return withHooks(ctx, iluo.sqlSave, iluo.mutation, iluo.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (iluo *ImportListUpdateOne) SaveX(ctx context.Context) *ImportList {
node, err := iluo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (iluo *ImportListUpdateOne) Exec(ctx context.Context) error {
_, err := iluo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (iluo *ImportListUpdateOne) ExecX(ctx context.Context) {
if err := iluo.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (iluo *ImportListUpdateOne) check() error {
if v, ok := iluo.mutation.GetType(); ok {
if err := importlist.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "ImportList.type": %w`, err)}
}
}
return nil
}
func (iluo *ImportListUpdateOne) sqlSave(ctx context.Context) (_node *ImportList, err error) {
if err := iluo.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(importlist.Table, importlist.Columns, sqlgraph.NewFieldSpec(importlist.FieldID, field.TypeInt))
id, ok := iluo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "ImportList.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := iluo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, importlist.FieldID)
for _, f := range fields {
if !importlist.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != importlist.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := iluo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := iluo.mutation.Name(); ok {
_spec.SetField(importlist.FieldName, field.TypeString, value)
}
if value, ok := iluo.mutation.GetType(); ok {
_spec.SetField(importlist.FieldType, field.TypeEnum, value)
}
if value, ok := iluo.mutation.URL(); ok {
_spec.SetField(importlist.FieldURL, field.TypeString, value)
}
if iluo.mutation.URLCleared() {
_spec.ClearField(importlist.FieldURL, field.TypeString)
}
if value, ok := iluo.mutation.Qulity(); ok {
_spec.SetField(importlist.FieldQulity, field.TypeString, value)
}
if value, ok := iluo.mutation.StorageID(); ok {
_spec.SetField(importlist.FieldStorageID, field.TypeInt, value)
}
if value, ok := iluo.mutation.AddedStorageID(); ok {
_spec.AddField(importlist.FieldStorageID, field.TypeInt, value)
}
if value, ok := iluo.mutation.Settings(); ok {
_spec.SetField(importlist.FieldSettings, field.TypeJSON, value)
}
if iluo.mutation.SettingsCleared() {
_spec.ClearField(importlist.FieldSettings, field.TypeJSON)
}
_node = &ImportList{config: iluo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, iluo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{importlist.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
iluo.mutation.done = true
return _node, nil
}

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.
@@ -75,6 +76,22 @@ var (
Columns: HistoriesColumns,
PrimaryKey: []*schema.Column{HistoriesColumns[0]},
}
// ImportListsColumns holds the columns for the "import_lists" table.
ImportListsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString},
{Name: "type", Type: field.TypeEnum, Enums: []string{"plex", "doulist"}},
{Name: "url", Type: field.TypeString, Nullable: true},
{Name: "qulity", Type: field.TypeString},
{Name: "storage_id", Type: field.TypeInt},
{Name: "settings", Type: field.TypeJSON, Nullable: true},
}
// ImportListsTable holds the schema information for the "import_lists" table.
ImportListsTable = &schema.Table{
Name: "import_lists",
Columns: ImportListsColumns,
PrimaryKey: []*schema.Column{ImportListsColumns[0]},
}
// IndexersColumns holds the columns for the "indexers" table.
IndexersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
@@ -109,6 +126,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{
@@ -164,6 +182,7 @@ var (
DownloadClientsTable,
EpisodesTable,
HistoriesTable,
ImportListsTable,
IndexersTable,
MediaTable,
NotificationClientsTable,

View File

@@ -9,6 +9,7 @@ import (
"polaris/ent/downloadclients"
"polaris/ent/episode"
"polaris/ent/history"
"polaris/ent/importlist"
"polaris/ent/indexers"
"polaris/ent/media"
"polaris/ent/notificationclient"
@@ -35,6 +36,7 @@ const (
TypeDownloadClients = "DownloadClients"
TypeEpisode = "Episode"
TypeHistory = "History"
TypeImportList = "ImportList"
TypeIndexers = "Indexers"
TypeMedia = "Media"
TypeNotificationClient = "NotificationClient"
@@ -923,6 +925,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 +1373,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 +1483,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 +1508,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 +1535,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 +1562,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 +1629,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 +1696,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 +1716,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 +1751,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)
}
@@ -2819,6 +2894,679 @@ func (m *HistoryMutation) ResetEdge(name string) error {
return fmt.Errorf("unknown History edge %s", name)
}
// ImportListMutation represents an operation that mutates the ImportList nodes in the graph.
type ImportListMutation struct {
config
op Op
typ string
id *int
name *string
_type *importlist.Type
url *string
qulity *string
storage_id *int
addstorage_id *int
settings *schema.ImportListSettings
clearedFields map[string]struct{}
done bool
oldValue func(context.Context) (*ImportList, error)
predicates []predicate.ImportList
}
var _ ent.Mutation = (*ImportListMutation)(nil)
// importlistOption allows management of the mutation configuration using functional options.
type importlistOption func(*ImportListMutation)
// newImportListMutation creates new mutation for the ImportList entity.
func newImportListMutation(c config, op Op, opts ...importlistOption) *ImportListMutation {
m := &ImportListMutation{
config: c,
op: op,
typ: TypeImportList,
clearedFields: make(map[string]struct{}),
}
for _, opt := range opts {
opt(m)
}
return m
}
// withImportListID sets the ID field of the mutation.
func withImportListID(id int) importlistOption {
return func(m *ImportListMutation) {
var (
err error
once sync.Once
value *ImportList
)
m.oldValue = func(ctx context.Context) (*ImportList, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().ImportList.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withImportList sets the old ImportList of the mutation.
func withImportList(node *ImportList) importlistOption {
return func(m *ImportListMutation) {
m.oldValue = func(context.Context) (*ImportList, error) {
return node, nil
}
m.id = &node.ID
}
}
// Client returns a new `ent.Client` from the mutation. If the mutation was
// executed in a transaction (ent.Tx), a transactional client is returned.
func (m ImportListMutation) Client() *Client {
client := &Client{config: m.config}
client.init()
return client
}
// Tx returns an `ent.Tx` for mutations that were executed in transactions;
// it returns an error otherwise.
func (m ImportListMutation) Tx() (*Tx, error) {
if _, ok := m.driver.(*txDriver); !ok {
return nil, errors.New("ent: mutation is not running in a transaction")
}
tx := &Tx{config: m.config}
tx.init()
return tx, nil
}
// ID returns the ID value in the mutation. Note that the ID is only available
// if it was provided to the builder or after it was returned from the database.
func (m *ImportListMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// IDs queries the database and returns the entity ids that match the mutation's predicate.
// That means, if the mutation is applied within a transaction with an isolation level such
// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
// or updated by the mutation.
func (m *ImportListMutation) IDs(ctx context.Context) ([]int, error) {
switch {
case m.op.Is(OpUpdateOne | OpDeleteOne):
id, exists := m.ID()
if exists {
return []int{id}, nil
}
fallthrough
case m.op.Is(OpUpdate | OpDelete):
return m.Client().ImportList.Query().Where(m.predicates...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
}
}
// SetName sets the "name" field.
func (m *ImportListMutation) SetName(s string) {
m.name = &s
}
// Name returns the value of the "name" field in the mutation.
func (m *ImportListMutation) Name() (r string, exists bool) {
v := m.name
if v == nil {
return
}
return *v, true
}
// OldName returns the old "name" field's value of the ImportList entity.
// If the ImportList 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 *ImportListMutation) OldName(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldName is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldName requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldName: %w", err)
}
return oldValue.Name, nil
}
// ResetName resets all changes to the "name" field.
func (m *ImportListMutation) ResetName() {
m.name = nil
}
// SetType sets the "type" field.
func (m *ImportListMutation) SetType(i importlist.Type) {
m._type = &i
}
// GetType returns the value of the "type" field in the mutation.
func (m *ImportListMutation) GetType() (r importlist.Type, exists bool) {
v := m._type
if v == nil {
return
}
return *v, true
}
// OldType returns the old "type" field's value of the ImportList entity.
// If the ImportList 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 *ImportListMutation) OldType(ctx context.Context) (v importlist.Type, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldType is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldType requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldType: %w", err)
}
return oldValue.Type, nil
}
// ResetType resets all changes to the "type" field.
func (m *ImportListMutation) ResetType() {
m._type = nil
}
// SetURL sets the "url" field.
func (m *ImportListMutation) SetURL(s string) {
m.url = &s
}
// URL returns the value of the "url" field in the mutation.
func (m *ImportListMutation) URL() (r string, exists bool) {
v := m.url
if v == nil {
return
}
return *v, true
}
// OldURL returns the old "url" field's value of the ImportList entity.
// If the ImportList 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 *ImportListMutation) OldURL(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldURL is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldURL requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldURL: %w", err)
}
return oldValue.URL, nil
}
// ClearURL clears the value of the "url" field.
func (m *ImportListMutation) ClearURL() {
m.url = nil
m.clearedFields[importlist.FieldURL] = struct{}{}
}
// URLCleared returns if the "url" field was cleared in this mutation.
func (m *ImportListMutation) URLCleared() bool {
_, ok := m.clearedFields[importlist.FieldURL]
return ok
}
// ResetURL resets all changes to the "url" field.
func (m *ImportListMutation) ResetURL() {
m.url = nil
delete(m.clearedFields, importlist.FieldURL)
}
// SetQulity sets the "qulity" field.
func (m *ImportListMutation) SetQulity(s string) {
m.qulity = &s
}
// Qulity returns the value of the "qulity" field in the mutation.
func (m *ImportListMutation) Qulity() (r string, exists bool) {
v := m.qulity
if v == nil {
return
}
return *v, true
}
// OldQulity returns the old "qulity" field's value of the ImportList entity.
// If the ImportList 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 *ImportListMutation) OldQulity(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldQulity is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldQulity requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldQulity: %w", err)
}
return oldValue.Qulity, nil
}
// ResetQulity resets all changes to the "qulity" field.
func (m *ImportListMutation) ResetQulity() {
m.qulity = nil
}
// SetStorageID sets the "storage_id" field.
func (m *ImportListMutation) SetStorageID(i int) {
m.storage_id = &i
m.addstorage_id = nil
}
// StorageID returns the value of the "storage_id" field in the mutation.
func (m *ImportListMutation) StorageID() (r int, exists bool) {
v := m.storage_id
if v == nil {
return
}
return *v, true
}
// OldStorageID returns the old "storage_id" field's value of the ImportList entity.
// If the ImportList 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 *ImportListMutation) OldStorageID(ctx context.Context) (v int, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldStorageID is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldStorageID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldStorageID: %w", err)
}
return oldValue.StorageID, nil
}
// AddStorageID adds i to the "storage_id" field.
func (m *ImportListMutation) AddStorageID(i int) {
if m.addstorage_id != nil {
*m.addstorage_id += i
} else {
m.addstorage_id = &i
}
}
// AddedStorageID returns the value that was added to the "storage_id" field in this mutation.
func (m *ImportListMutation) AddedStorageID() (r int, exists bool) {
v := m.addstorage_id
if v == nil {
return
}
return *v, true
}
// ResetStorageID resets all changes to the "storage_id" field.
func (m *ImportListMutation) ResetStorageID() {
m.storage_id = nil
m.addstorage_id = nil
}
// SetSettings sets the "settings" field.
func (m *ImportListMutation) SetSettings(sls schema.ImportListSettings) {
m.settings = &sls
}
// Settings returns the value of the "settings" field in the mutation.
func (m *ImportListMutation) Settings() (r schema.ImportListSettings, exists bool) {
v := m.settings
if v == nil {
return
}
return *v, true
}
// OldSettings returns the old "settings" field's value of the ImportList entity.
// If the ImportList 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 *ImportListMutation) OldSettings(ctx context.Context) (v schema.ImportListSettings, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldSettings is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldSettings requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldSettings: %w", err)
}
return oldValue.Settings, nil
}
// ClearSettings clears the value of the "settings" field.
func (m *ImportListMutation) ClearSettings() {
m.settings = nil
m.clearedFields[importlist.FieldSettings] = struct{}{}
}
// SettingsCleared returns if the "settings" field was cleared in this mutation.
func (m *ImportListMutation) SettingsCleared() bool {
_, ok := m.clearedFields[importlist.FieldSettings]
return ok
}
// ResetSettings resets all changes to the "settings" field.
func (m *ImportListMutation) ResetSettings() {
m.settings = nil
delete(m.clearedFields, importlist.FieldSettings)
}
// Where appends a list predicates to the ImportListMutation builder.
func (m *ImportListMutation) Where(ps ...predicate.ImportList) {
m.predicates = append(m.predicates, ps...)
}
// WhereP appends storage-level predicates to the ImportListMutation builder. Using this method,
// users can use type-assertion to append predicates that do not depend on any generated package.
func (m *ImportListMutation) WhereP(ps ...func(*sql.Selector)) {
p := make([]predicate.ImportList, len(ps))
for i := range ps {
p[i] = ps[i]
}
m.Where(p...)
}
// Op returns the operation name.
func (m *ImportListMutation) Op() Op {
return m.op
}
// SetOp allows setting the mutation operation.
func (m *ImportListMutation) SetOp(op Op) {
m.op = op
}
// Type returns the node type of this mutation (ImportList).
func (m *ImportListMutation) Type() string {
return m.typ
}
// Fields returns all fields that were changed during this mutation. Note that in
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *ImportListMutation) Fields() []string {
fields := make([]string, 0, 6)
if m.name != nil {
fields = append(fields, importlist.FieldName)
}
if m._type != nil {
fields = append(fields, importlist.FieldType)
}
if m.url != nil {
fields = append(fields, importlist.FieldURL)
}
if m.qulity != nil {
fields = append(fields, importlist.FieldQulity)
}
if m.storage_id != nil {
fields = append(fields, importlist.FieldStorageID)
}
if m.settings != nil {
fields = append(fields, importlist.FieldSettings)
}
return fields
}
// Field returns the value of a field with the given name. The second boolean
// return value indicates that this field was not set, or was not defined in the
// schema.
func (m *ImportListMutation) Field(name string) (ent.Value, bool) {
switch name {
case importlist.FieldName:
return m.Name()
case importlist.FieldType:
return m.GetType()
case importlist.FieldURL:
return m.URL()
case importlist.FieldQulity:
return m.Qulity()
case importlist.FieldStorageID:
return m.StorageID()
case importlist.FieldSettings:
return m.Settings()
}
return nil, false
}
// OldField returns the old value of the field from the database. An error is
// returned if the mutation operation is not UpdateOne, or the query to the
// database failed.
func (m *ImportListMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case importlist.FieldName:
return m.OldName(ctx)
case importlist.FieldType:
return m.OldType(ctx)
case importlist.FieldURL:
return m.OldURL(ctx)
case importlist.FieldQulity:
return m.OldQulity(ctx)
case importlist.FieldStorageID:
return m.OldStorageID(ctx)
case importlist.FieldSettings:
return m.OldSettings(ctx)
}
return nil, fmt.Errorf("unknown ImportList field %s", name)
}
// SetField sets the value of a field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *ImportListMutation) SetField(name string, value ent.Value) error {
switch name {
case importlist.FieldName:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetName(v)
return nil
case importlist.FieldType:
v, ok := value.(importlist.Type)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetType(v)
return nil
case importlist.FieldURL:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetURL(v)
return nil
case importlist.FieldQulity:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetQulity(v)
return nil
case importlist.FieldStorageID:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetStorageID(v)
return nil
case importlist.FieldSettings:
v, ok := value.(schema.ImportListSettings)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetSettings(v)
return nil
}
return fmt.Errorf("unknown ImportList field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *ImportListMutation) AddedFields() []string {
var fields []string
if m.addstorage_id != nil {
fields = append(fields, importlist.FieldStorageID)
}
return fields
}
// AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema.
func (m *ImportListMutation) AddedField(name string) (ent.Value, bool) {
switch name {
case importlist.FieldStorageID:
return m.AddedStorageID()
}
return nil, false
}
// AddField adds the value to the field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *ImportListMutation) AddField(name string, value ent.Value) error {
switch name {
case importlist.FieldStorageID:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddStorageID(v)
return nil
}
return fmt.Errorf("unknown ImportList numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *ImportListMutation) ClearedFields() []string {
var fields []string
if m.FieldCleared(importlist.FieldURL) {
fields = append(fields, importlist.FieldURL)
}
if m.FieldCleared(importlist.FieldSettings) {
fields = append(fields, importlist.FieldSettings)
}
return fields
}
// FieldCleared returns a boolean indicating if a field with the given name was
// cleared in this mutation.
func (m *ImportListMutation) FieldCleared(name string) bool {
_, ok := m.clearedFields[name]
return ok
}
// ClearField clears the value of the field with the given name. It returns an
// error if the field is not defined in the schema.
func (m *ImportListMutation) ClearField(name string) error {
switch name {
case importlist.FieldURL:
m.ClearURL()
return nil
case importlist.FieldSettings:
m.ClearSettings()
return nil
}
return fmt.Errorf("unknown ImportList nullable field %s", name)
}
// ResetField resets all changes in the mutation for the field with the given name.
// It returns an error if the field is not defined in the schema.
func (m *ImportListMutation) ResetField(name string) error {
switch name {
case importlist.FieldName:
m.ResetName()
return nil
case importlist.FieldType:
m.ResetType()
return nil
case importlist.FieldURL:
m.ResetURL()
return nil
case importlist.FieldQulity:
m.ResetQulity()
return nil
case importlist.FieldStorageID:
m.ResetStorageID()
return nil
case importlist.FieldSettings:
m.ResetSettings()
return nil
}
return fmt.Errorf("unknown ImportList field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *ImportListMutation) AddedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
// name in this mutation.
func (m *ImportListMutation) AddedIDs(name string) []ent.Value {
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *ImportListMutation) RemovedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
// the given name in this mutation.
func (m *ImportListMutation) RemovedIDs(name string) []ent.Value {
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *ImportListMutation) ClearedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// EdgeCleared returns a boolean which indicates if the edge with the given name
// was cleared in this mutation.
func (m *ImportListMutation) EdgeCleared(name string) bool {
return false
}
// ClearEdge clears the value of the edge with the given name. It returns an error
// if that edge is not defined in the schema.
func (m *ImportListMutation) ClearEdge(name string) error {
return fmt.Errorf("unknown ImportList unique edge %s", name)
}
// ResetEdge resets all changes to the edge with the given name in this mutation.
// It returns an error if the edge is not defined in the schema.
func (m *ImportListMutation) ResetEdge(name string) error {
return fmt.Errorf("unknown ImportList edge %s", name)
}
// IndexersMutation represents an operation that mutates the Indexers nodes in the graph.
type IndexersMutation struct {
config
@@ -3601,7 +4349,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 +5020,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 +5036,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 +5068,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 +5205,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 +5248,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 +5287,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 +5326,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 +5429,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 +5514,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 +5546,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 +5599,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

@@ -15,6 +15,9 @@ type Episode func(*sql.Selector)
// History is the predicate function for history builders.
type History func(*sql.Selector)
// ImportList is the predicate function for importlist builders.
type ImportList func(*sql.Selector)
// Indexers is the predicate function for indexers builders.
type Indexers func(*sql.Selector)

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(),
}
}

32
ent/schema/importlist.go Normal file
View File

@@ -0,0 +1,32 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/field"
)
// ImportList holds the schema definition for the ImportList entity.
type ImportList struct {
ent.Schema
}
// Fields of the ImportList.
func (ImportList) Fields() []ent.Field {
return []ent.Field{
field.String("name"),
field.Enum("type").Values("plex", "doulist"),
field.String("url").Optional(),
field.String("qulity"),
field.Int("storage_id"),
field.JSON("settings", ImportListSettings{}).Optional(),
}
}
// Edges of the ImportList.
func (ImportList) Edges() []ent.Edge {
return nil
}
type ImportListSettings struct {
//Url string `json:"url"`
}

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 != ""
}

View File

@@ -18,6 +18,8 @@ type Tx struct {
Episode *EpisodeClient
// History is the client for interacting with the History builders.
History *HistoryClient
// ImportList is the client for interacting with the ImportList builders.
ImportList *ImportListClient
// Indexers is the client for interacting with the Indexers builders.
Indexers *IndexersClient
// Media is the client for interacting with the Media builders.
@@ -162,6 +164,7 @@ func (tx *Tx) init() {
tx.DownloadClients = NewDownloadClientsClient(tx.config)
tx.Episode = NewEpisodeClient(tx.config)
tx.History = NewHistoryClient(tx.config)
tx.ImportList = NewImportListClient(tx.config)
tx.Indexers = NewIndexersClient(tx.config)
tx.Media = NewMediaClient(tx.config)
tx.NotificationClient = NewNotificationClientClient(tx.config)

5
go.mod
View File

@@ -12,20 +12,21 @@ 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 (
github.com/BurntSushi/toml v1.4.0 // indirect
github.com/PuerkitoBio/goquery v1.9.2 // indirect
github.com/andybalholm/cascadia v1.3.2 // indirect
github.com/blinkbean/dingtalk v1.1.3 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible // indirect
github.com/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

37
go.sum
View File

@@ -6,10 +6,12 @@ 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/PuerkitoBio/goquery v1.9.2 h1:4/wZksC3KgkQw7SQgkKotmKljk0M6V8TUvA8Wb4yPeE=
github.com/PuerkitoBio/goquery v1.9.2/go.mod h1:GHPCaP0ODyyxqcNoFGYlAprUFH81NuRPd0GX3Zu2Mvk=
github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8=
github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss=
github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU=
github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw=
github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo=
github.com/blinkbean/dingtalk v1.1.3 h1:MbidFZYom7DTFHD/YIs+eaI7kRy52kmWE/sy0xjo6E4=
@@ -80,6 +82,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=
@@ -172,6 +176,7 @@ github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65E
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
github.com/vmihailenco/msgpack/v4 v4.3.12/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4=
github.com/vmihailenco/tagparser v0.1.1/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/zclconf/go-cty v1.8.0 h1:s4AvqaeQzJIu3ndv4gVIhplVD0krU+bgrcLSVUnaWuA=
github.com/zclconf/go-cty v1.8.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
@@ -184,31 +189,59 @@ golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUu
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.25.0 h1:ypSNr+bnYL2YhwoMt2zPxHFmbAN1KZs/njMG3hxUp30=
golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/M=
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0LeHDbnYEryqj5Q1ug8=
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8=
golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys=
golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg=
golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=

View File

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

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

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

View File

@@ -1,14 +1,14 @@
package pkg
type Torrent interface {
Name() string
Progress() int
Name() (string, error)
Progress() (int, error)
Stop() error
Start() error
Remove() error
Save() string
Exists() bool
SeedRatio() *float64
SeedRatio() (float64, error)
}

View File

@@ -0,0 +1,100 @@
package douban
import (
"fmt"
"net/http"
"polaris/log"
"polaris/pkg/importlist"
"strconv"
"strings"
"github.com/PuerkitoBio/goquery"
)
const ua = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"
func ParseDoulist(doulistUrl string) (*importlist.Response, error) {
if !strings.Contains(doulistUrl, "doulist") {
return nil, fmt.Errorf("not doulist")
}
req, err := http.NewRequest("GET", doulistUrl, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", ua)
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return nil, fmt.Errorf("status code error: %d %s", res.StatusCode, res.Status)
}
doc, err := goquery.NewDocumentFromReader(res.Body)
if err != nil {
return nil, err
}
doc.Find("div[class=doulist-item]").Each(func(i int, selection *goquery.Selection) {
titleDiv := selection.Find("div[class=title]")
link := titleDiv.Find("div>a")
href, ok := link.Attr("href")
if !ok {
return
}
abstract := selection.Find("div[class=abstract]")
lines := strings.Split(abstract.Text(), "\n")
year := 0
for _, l := range lines {
if strings.Contains(l, "年份") {
ppp := strings.Split(l, ":")
if len(ppp) < 2 {
continue
} else {
n := ppp[1]
n1, err := strconv.Atoi(strings.TrimSpace(n))
if err != nil {
log.Errorf("convert year number %s to int error: %v", n, err)
continue
}
year = n1
}
}
}
item := importlist.Item{
Title: strings.TrimSpace(link.Text()),
Year: year,
}
_ = item
println(link.Text(), href)
})
return nil, nil
}
func parseDetailPage(url string) (string, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", err
}
req.Header.Set("User-Agent", ua)
res, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return "", fmt.Errorf("status code error: %d %s", res.StatusCode, res.Status)
}
doc, err := goquery.NewDocumentFromReader(res.Body)
if err != nil {
return "", err
}
_ = doc
return "", nil
}

View File

@@ -0,0 +1,11 @@
package douban
import (
"polaris/log"
"testing"
)
func TestParseDoulist(t *testing.T) {
r, err := ParseDoulist("https://www.douban.com/doulist/166422/")
log.Info(r, err)
}

View File

@@ -0,0 +1,13 @@
package importlist
type Item struct {
Title string
Year int
ImdbID string
TvdbID string
TmdbID string
}
type Response struct {
Items []Item
}

View File

@@ -0,0 +1,96 @@
package plexwatchlist
import (
"encoding/xml"
"io"
"net/http"
"polaris/pkg/importlist"
"strings"
"github.com/pkg/errors"
)
type Response struct {
XMLName xml.Name `xml:"rss"`
Text string `xml:",chardata"`
Atom string `xml:"atom,attr"`
Media string `xml:"media,attr"`
Version string `xml:"version,attr"`
Channel struct {
Text string `xml:",chardata"`
Title string `xml:"title"`
Link struct {
Text string `xml:",chardata"`
Href string `xml:"href,attr"`
Rel string `xml:"rel,attr"`
Type string `xml:"type,attr"`
} `xml:"link"`
Description string `xml:"description"`
Category string `xml:"category"`
Item []struct {
Text string `xml:",chardata"`
Title string `xml:"title"`
PubDate string `xml:"pubDate"`
Link string `xml:"link"`
Description string `xml:"description"`
Category string `xml:"category"`
Credit []struct {
Text string `xml:",chardata"`
Role string `xml:"role,attr"`
} `xml:"credit"`
Thumbnail struct {
Text string `xml:",chardata"`
URL string `xml:"url,attr"`
} `xml:"thumbnail"`
Keywords string `xml:"keywords"`
Rating struct {
Text string `xml:",chardata"`
Scheme string `xml:"scheme,attr"`
} `xml:"rating"`
Guid struct {
Text string `xml:",chardata"`
IsPermaLink string `xml:"isPermaLink,attr"`
} `xml:"guid"`
} `xml:"item"`
} `xml:"channel"`
}
func (r *Response) convert() *importlist.Response {
res := &importlist.Response{}
for _, im := range r.Channel.Item {
item := importlist.Item{
Title: im.Title,
}
id := strings.ToLower(im.Guid.Text)
if strings.HasPrefix(id, "tvdb") {
tvdbid := strings.TrimPrefix(id, "tvdb://")
item.TvdbID = tvdbid
} else if strings.HasPrefix(id, "imdb") {
imdbid := strings.TrimPrefix(id, "imdb://")
item.ImdbID = imdbid
} else if strings.HasPrefix(id, "tmdb") {
tmdbid := strings.TrimPrefix(id, "tmdb://")
item.TmdbID = tmdbid
}
res.Items = append(res.Items, item)
}
return res
}
func ParsePlexWatchlist(url string) (*importlist.Response, error) {
resp, err := http.Get(url)
if err != nil {
return nil, errors.Wrap(err, "http get")
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "read data")
}
var rrr Response
err = xml.Unmarshal(data, &rrr)
if err != nil {
return nil, errors.Wrap(err, "xml")
}
return rrr.convert(), nil
}

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

@@ -13,11 +13,12 @@ import (
)
type Client struct {
apiKey string
tmdbClient *tmdb.Client
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 {
@@ -42,13 +43,14 @@ func NewClient(apiKey, proxyUrl string) (*Client, error) {
}
return &Client{
apiKey: apiKey,
tmdbClient: tmdbClient,
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")
}
@@ -57,8 +59,8 @@ func (c *Client) GetTvDetails(id int, language string) (*tmdb.TVDetails, error)
if !episodeNameUseful(d.LastEpisodeToAir.Name) {
log.Debug("should fetch english version")
var detailEN *tmdb.TVDetails
if language == "zh-CN" {
detailEN, err = c.tmdbClient.GetTVDetails(id, withLangOption("en-US"))
if language == "zh-CN" || language == "" {
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")
@@ -162,7 +167,7 @@ func (c *Client) GetEposideDetail(id, seasonNumber, eposideNumber int, language
}
if !episodeNameUseful(d.Name) {
var detailEN *tmdb.TVEpisodeDetails
if language == "zh-CN" {
if language == "zh-CN" || language == "" {
detailEN, err = c.tmdbClient.GetTVEpisodeDetails(id, seasonNumber, eposideNumber, withLangOption("en-US"))
if err != nil {
return d, nil
@@ -184,7 +189,7 @@ func (c *Client) GetSeasonDetails(id, seasonNumber int, language string) (*tmdb.
return nil, err
}
var detailEN *tmdb.TVSeasonDetails
if language == "zh-CN" {
if language == "zh-CN" || language == "" {
detailEN, err = c.tmdbClient.GetTVSeasonDetails(id, seasonNumber, withLangOption("en-US"))
if err != nil {
return detailCN, nil
@@ -204,6 +209,22 @@ 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 (c *Client) GetByImdbId(imdbId string, lang string) (*tmdb.FindByID, error) {
m := withLangOption(lang)
m["external_source"] = "imdb_id"
return c.tmdbClient.GetFindByID(imdbId, m)
}
func (c *Client) GetByTvdbId(imdbId string, lang string) (*tmdb.FindByID, error) {
m := withLangOption(lang)
m["external_source"] = "tvdb_id"
return c.tmdbClient.GetFindByID(imdbId, m)
}
func wrapLanguage(lang string) string {
if lang == "" {
lang = "zh-CN"
@@ -211,6 +232,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

@@ -53,7 +53,7 @@ func (c *Client) GetAll() ([]*Torrent, error) {
var torrents []*Torrent
for _, t := range all {
torrents = append(torrents, &Torrent{
ID: *t.ID,
Hash: *t.HashString,
c: c.c,
Config: c.cfg,
})
@@ -86,12 +86,12 @@ func (c *Client) Download(link, dir string) (*Torrent, error) {
DownloadDir: &dir,
})
log.Infof("get torrent info: %+v", t)
if t.ID == nil {
if t.HashString == nil {
return nil, fmt.Errorf("download torrent error: %v", link)
}
return &Torrent{
ID: *t.ID,
Hash: *t.HashString,
c: c.c,
Config: c.cfg,
}, err
@@ -100,7 +100,7 @@ func (c *Client) Download(link, dir string) (*Torrent, error) {
type Torrent struct {
//t *transmissionrpc.Torrent
c *transmissionrpc.Client
ID int64 `json:"id"`
Hash string `json:"hash"`
Config
}
@@ -113,68 +113,92 @@ func (t *Torrent) reloadClient() error {
return nil
}
func (t *Torrent) getTorrent() transmissionrpc.Torrent {
r, err := t.c.TorrentGetAllFor(context.TODO(), []int64{t.ID})
func (t *Torrent) getTorrent() (transmissionrpc.Torrent, error) {
r, err := t.c.TorrentGetAllForHashes(context.TODO(), []string{t.Hash})
if err != nil {
log.Errorf("get torrent info for error: %v", err)
}
return r[0]
if len(r) == 0 {
return transmissionrpc.Torrent{}, fmt.Errorf("no torrent")
}
return r[0], nil
}
func (t *Torrent) Exists() bool {
r, err := t.c.TorrentGetAllFor(context.TODO(), []int64{t.ID})
r, err := t.c.TorrentGetAllForHashes(context.TODO(), []string{t.Hash})
if err != nil {
log.Errorf("get torrent info for error: %v", err)
}
return len(r) > 0
}
func (t *Torrent) Name() string {
if !t.Exists() {
return ""
func (t *Torrent) Name() (string, error) {
tt, err := t.getTorrent()
if err != nil {
return "", err
}
return *t.getTorrent().Name
return *tt.Name, nil
}
func (t *Torrent) Progress() int {
if t.getTorrent().IsFinished != nil && *t.getTorrent().IsFinished {
return 100
func (t *Torrent) Progress() (int, error) {
tt, err := t.getTorrent()
if err != nil {
return 0, err
}
if t.getTorrent().PercentComplete != nil && *t.getTorrent().PercentComplete >= 1 {
return 100
if tt.IsFinished != nil && *tt.IsFinished {
return 100, nil
}
if tt.PercentComplete != nil && *tt.PercentComplete >= 1 {
return 100, nil
}
if t.getTorrent().PercentComplete != nil {
p := int(*t.getTorrent().PercentComplete * 100)
if tt.PercentComplete != nil {
p := int(*tt.PercentComplete * 100)
if p == 100 {
p = 99
}
return p
return p, nil
}
return 0
return 0, nil
}
func (t *Torrent) Stop() error {
return t.c.TorrentStopIDs(context.TODO(), []int64{t.ID})
return t.c.TorrentStopHashes(context.TODO(), []string{t.Hash})
}
func (t *Torrent) SeedRatio() *float64 {
return t.getTorrent().UploadRatio
func (t *Torrent) SeedRatio() (float64, error) {
tt, err := t.getTorrent()
if err != nil {
return 0, err
}
if tt.UploadRatio == nil {
return 0, nil
}
return *tt.UploadRatio, nil
}
func (t *Torrent) Start() error {
return t.c.TorrentStartIDs(context.TODO(), []int64{t.ID})
return t.c.TorrentStartHashes(context.TODO(), []string{t.Hash})
}
func (t *Torrent) Remove() error {
tt, err := t.getTorrent()
if err != nil {
return errors.Wrap(err, "get torrent")
}
return t.c.TorrentRemove(context.TODO(), transmissionrpc.TorrentRemovePayload{
IDs: []int64{t.ID},
IDs: []int64{*tt.ID},
DeleteLocalData: true,
})
}
func (t *Torrent) Size() int {
return int(t.getTorrent().TotalSize.Byte())
func (t *Torrent) Size() (int, error) {
tt, err := t.getTorrent()
if err != nil {
return 0, errors.Wrap(err, "get torrent")
}
return int(tt.TotalSize.Byte()), nil
}
func (t *Torrent) Save() string {

View File

@@ -1,6 +1,7 @@
package utils
import (
"encoding/json"
"os"
"regexp"
"strconv"
@@ -147,3 +148,38 @@ func ChangeFileHash(name string) error {
}
return nil
}
func TrimFields(v interface{}) error {
bytes, err := json.Marshal(v)
if err != nil {
return err
}
var mapSI map[string]interface{}
if err := json.Unmarshal(bytes, &mapSI); err != nil {
return err
}
mapSI = trimMapStringInterface(mapSI).(map[string]interface{})
bytes2, err := json.Marshal(mapSI)
if err != nil {
return err
}
if err := json.Unmarshal(bytes2, v); err != nil {
return err
}
return nil
}
func trimMapStringInterface(data interface{}) interface{} {
if values, valid := data.([]interface{}); valid {
for i := range values {
data.([]interface{})[i] = trimMapStringInterface(values[i])
}
} else if values, valid := data.(map[string]interface{}); valid {
for k, v := range values {
data.(map[string]interface{})[k] = trimMapStringInterface(v)
}
} else if value, valid := data.(string); valid {
data = strings.TrimSpace(value)
}
return data
}

View File

@@ -15,31 +15,51 @@ import (
type Activity struct {
*ent.History
Progress int `json:"progress"`
Progress int `json:"progress"`
SeedRatio float64 `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() {
p, err := task.Progress()
if err != nil {
log.Warnf("get task progress error: %v", err)
} else {
a.Progress = p
}
r, err := task.SeedRatio()
if err != nil {
log.Warnf("get task seed ratio error: %v", err)
} else {
a.SeedRatio = r
}
}
}
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
}
@@ -58,9 +78,15 @@ func (s *Server) RemoveActivity(c *gin.Context) (interface{}, error) {
if err := s.core.RemoveTaskAndTorrent(his.ID); err != nil {
return nil, errors.Wrap(err, "remove torrent")
}
err = s.db.DeleteHistory(id)
if err != nil {
return nil, errors.Wrap(err, "db")
}
if his.EpisodeID != 0 {
s.db.SetEpisodeStatus(his.EpisodeID, episode.StatusMissing)
if !s.db.IsEpisodeDownloadingOrDownloaded(his.EpisodeID) {
s.db.SetEpisodeStatus(his.EpisodeID, episode.StatusMissing)
}
} else {
seasonNum, err := utils.SeasonId(his.TargetDir)
@@ -68,14 +94,11 @@ 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)
if err != nil {
return nil, errors.Wrap(err, "db")
}
log.Infof("history record successful deleted: %v", his.SourceTitle)
return nil, nil
}
@@ -94,7 +117,7 @@ func (s *Server) GetMediaDownloadHistory(c *gin.Context) (interface{}, error) {
type TorrentInfo struct {
Name string `json:"name"`
ID int64 `json:"id"`
ID string `json:"id"`
SeedRatio float32 `json:"seed_ratio"`
Progress int `json:"progress"`
}
@@ -113,10 +136,12 @@ func (s *Server) GetAllTorrents(c *gin.Context) (interface{}, error) {
if !t.Exists() {
continue
}
name, _ := t.Name()
p, _ := t.Progress()
infos = append(infos, TorrentInfo{
Name: t.Name(),
ID: t.ID,
Progress: t.Progress(),
Name: name,
ID: t.Hash,
Progress: p,
})
}
return infos, nil

View File

@@ -22,7 +22,7 @@ func (s *Server) authModdleware(c *gin.Context) {
c.Next()
return
}
token, err := c.Cookie("token")
token, err := c.Cookie("polaris_token")
if err != nil {
log.Errorf("token error: %v", err)
c.AbortWithStatus(http.StatusForbidden)
@@ -90,11 +90,9 @@ func (s *Server) Login(c *gin.Context) (interface{}, error) {
if err != nil {
return nil, errors.Wrap(err, "sign")
}
c.SetSameSite(http.SameSiteNoneMode)
c.SetCookie("token", sig, 0, "/", "", true, false)
return gin.H{
"token": sig,
}, nil
c.SetSameSite(http.SameSiteLaxMode)
c.SetCookie("polaris_token", sig, 0, "/", "", false, false)
return "success", nil
}
func (s *Server) Logout(c *gin.Context) (interface{}, error) {
@@ -102,8 +100,8 @@ func (s *Server) Logout(c *gin.Context) (interface{}, error) {
return nil, errors.New( "auth is not enabled")
}
c.SetSameSite(http.SameSiteNoneMode)
c.SetCookie("token", "", -1, "/", "", true, false)
c.SetSameSite(http.SameSiteLaxMode)
c.SetCookie("polaris_token", "", -1, "/", "", false, false)
return nil, nil
}

View File

@@ -6,6 +6,7 @@ import (
"polaris/log"
"polaris/pkg/tmdb"
"polaris/pkg/transmission"
"polaris/pkg/utils"
"github.com/pkg/errors"
"github.com/robfig/cron"
@@ -20,11 +21,23 @@ func NewClient(db *db.Client, language string) *Client {
}
}
type scheduler struct {
cron string
f func() error
}
type Client struct {
db *db.Client
cron *cron.Cron
tasks map[int]*Task
language string
schedulers utils.Map[string, scheduler]
}
func (c *Client) registerCronJob(name string, cron string, f func() error) {
c.schedulers.Store(name, scheduler{
cron: cron,
f: f,
})
}
func (c *Client) Init() {
@@ -33,7 +46,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 +80,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 +92,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 +105,4 @@ func (c *Client) RemoveTaskAndTorrent(id int)error {
func (c *Client) GetTasks() map[int]*Task {
return c.tasks
}
}

455
server/core/importlist.go Normal file
View File

@@ -0,0 +1,455 @@
package core
import (
"bytes"
"fmt"
"html/template"
"io"
"net/http"
"os"
"path/filepath"
"polaris/db"
"polaris/ent"
"polaris/ent/importlist"
"polaris/ent/media"
"polaris/ent/schema"
"polaris/log"
"polaris/pkg/importlist/plexwatchlist"
"polaris/pkg/utils"
"regexp"
"strings"
tmdb "github.com/cyruzin/golang-tmdb"
"github.com/pkg/errors"
)
func (c *Client) periodicallyUpdateImportlist() error {
log.Infof("begin check import list")
lists, err := c.db.GetAllImportLists()
if err != nil {
return errors.Wrap(err, "get from db")
}
for _, l := range lists {
log.Infof("check import list content for %v", l.Name)
if l.Type == importlist.TypePlex {
res, err := plexwatchlist.ParsePlexWatchlist(l.URL)
if err != nil {
log.Errorf("parse plex watchlist: %v", err)
continue
}
for _, item := range res.Items {
var tmdbRes *tmdb.FindByID
if item.ImdbID != "" {
tmdbRes1, err := c.MustTMDB().GetByImdbId(item.ImdbID, c.language)
if err != nil {
log.Errorf("get by imdb id error: %v", err)
continue
}
tmdbRes = tmdbRes1
} else if item.TvdbID != "" {
tmdbRes1, err := c.MustTMDB().GetByTvdbId(item.TvdbID, c.language)
if err != nil {
log.Errorf("get by imdb id error: %v", err)
continue
}
tmdbRes = tmdbRes1
}
if tmdbRes == nil {
log.Errorf("can not find media for : %+v", item)
continue
}
if len(tmdbRes.MovieResults) > 0 {
d := tmdbRes.MovieResults[0]
name, err := c.SuggestedMovieFolderName(int(d.ID))
if err != nil {
log.Errorf("suggesting name error: %v", err)
continue
}
_, err = c.AddMovie2Watchlist(AddWatchlistIn{
TmdbID: int(d.ID),
StorageID: l.StorageID,
Resolution: l.Qulity,
Folder: name,
})
if err != nil {
log.Errorf("[update_import_lists] add movie to watchlist error: %v", err)
} else {
log.Infof("[update_import_lists] add movie to watchlist success")
}
} else if len(tmdbRes.TvResults) > 0 {
d := tmdbRes.TvResults[0]
name, err := c.SuggestedSeriesFolderName(int(d.ID))
if err != nil {
log.Errorf("suggesting name error: %v", err)
continue
}
_, err = c.AddTv2Watchlist(AddWatchlistIn{
TmdbID: int(d.ID),
StorageID: l.StorageID,
Resolution: l.Qulity,
Folder: name,
})
if err != nil {
log.Errorf("[update_import_lists] add tv to watchlist error: %v", err)
} else {
log.Infof("[update_import_lists] add tv to watchlist success")
}
}
}
}
}
return nil
}
type AddWatchlistIn struct {
TmdbID int `json:"tmdb_id" binding:"required"`
StorageID int `json:"storage_id" `
Resolution string `json:"resolution" binding:"required"`
Folder string `json:"folder" binding:"required"`
DownloadHistoryEpisodes bool `json:"download_history_episodes"` //for tv
SizeMin int `json:"size_min"`
SizeMax int `json:"size_max"`
}
func (c *Client) AddTv2Watchlist(in AddWatchlistIn) (interface{}, error) {
log.Debugf("add tv watchlist input %+v", in)
if in.Folder == "" {
return nil, errors.New("folder should be provided")
}
detailCn, err := c.MustTMDB().GetTvDetails(in.TmdbID, db.LanguageCN)
if err != nil {
return nil, errors.Wrap(err, "get tv detail")
}
var nameCn = detailCn.Name
detailEn, _ := c.MustTMDB().GetTvDetails(in.TmdbID, db.LanguageEN)
var nameEn = detailEn.Name
var detail *tmdb.TVDetails
if c.language == "" || c.language == db.LanguageCN {
detail = detailCn
} else {
detail = detailEn
}
log.Infof("find detail for tv id %d: %+v", in.TmdbID, detail)
lastSeason := 0
for _, season := range detail.Seasons {
if season.SeasonNumber > lastSeason && season.EpisodeCount > 0 { //如果最新一季已经有剧集信息,则以最新一季为准
lastSeason = season.SeasonNumber
}
}
log.Debugf("latest season is %v", lastSeason)
var epIds []int
for _, season := range detail.Seasons {
seasonId := season.SeasonNumber
se, err := c.MustTMDB().GetSeasonDetails(int(detail.ID), seasonId, c.language)
if err != nil {
log.Errorf("get season detail (%s) error: %v", detail.Name, err)
continue
}
shouldMonitor := seasonId >= lastSeason //监控最新的一季
for _, ep := range se.Episodes {
// //如果设置下载往期剧集则监控所有剧集。如果没有则监控未上映的剧集考虑时差等问题留24h余量
// if in.DownloadHistoryEpisodes {
// shouldMonitor = true
// } else {
// t, err := time.Parse("2006-01-02", ep.AirDate)
// if err != nil {
// log.Error("air date not known, will monitor: %v", ep.AirDate)
// shouldMonitor = true
// } else {
// if time.Since(t) < 24*time.Hour { //monitor episode air 24h before now
// shouldMonitor = true
// }
// }
// }
ep := ent.Episode{
SeasonNumber: seasonId,
EpisodeNumber: ep.EpisodeNumber,
Title: ep.Name,
Overview: ep.Overview,
AirDate: ep.AirDate,
Monitored: shouldMonitor,
}
epid, err := c.db.SaveEposideDetail(&ep)
if err != nil {
log.Errorf("save episode info error: %v", err)
continue
}
log.Debugf("success save episode %+v", ep)
epIds = append(epIds, epid)
}
}
m := &ent.Media{
TmdbID: int(detail.ID),
ImdbID: detail.IMDbID,
MediaType: media.MediaTypeTv,
NameCn: nameCn,
NameEn: nameEn,
OriginalName: detail.OriginalName,
Overview: detail.Overview,
AirDate: detail.FirstAirDate,
Resolution: media.Resolution(in.Resolution),
StorageID: in.StorageID,
TargetDir: in.Folder,
DownloadHistoryEpisodes: in.DownloadHistoryEpisodes,
Limiter: schema.MediaLimiter{SizeMin: in.SizeMin, SizeMax: in.SizeMax},
Extras: schema.MediaExtras{
OriginalLanguage: detail.OriginalLanguage,
Genres: detail.Genres,
},
}
r, err := c.db.AddMediaWatchlist(m, epIds)
if err != nil {
return nil, errors.Wrap(err, "add to list")
}
go func() {
if err := c.downloadPoster(detail.PosterPath, r.ID); err != nil {
log.Errorf("download poster error: %v", err)
}
if err := c.downloadBackdrop(detail.BackdropPath, r.ID); err != nil {
log.Errorf("download poster error: %v", err)
}
if err := c.CheckDownloadedSeriesFiles(r); err != nil {
log.Errorf("check downloaded files error: %v", err)
}
}()
log.Infof("add tv %s to watchlist success", detail.Name)
return nil, nil
}
func (c *Client) AddMovie2Watchlist(in AddWatchlistIn) (interface{}, error) {
log.Infof("add movie watchlist input: %+v", in)
detailCn, err := c.MustTMDB().GetMovieDetails(in.TmdbID, db.LanguageCN)
if err != nil {
return nil, errors.Wrap(err, "get movie detail")
}
var nameCn = detailCn.Title
detailEn, _ := c.MustTMDB().GetMovieDetails(in.TmdbID, db.LanguageEN)
var nameEn = detailEn.Title
var detail *tmdb.MovieDetails
if c.language == "" || c.language == db.LanguageCN {
detail = detailCn
} else {
detail = detailEn
}
log.Infof("find detail for movie id %d: %v", in.TmdbID, detail)
epid, err := c.db.SaveEposideDetail(&ent.Episode{
SeasonNumber: 1,
EpisodeNumber: 1,
Title: "dummy episode for movies",
Overview: "dummy episode for movies",
AirDate: detail.ReleaseDate,
Monitored: true,
})
if err != nil {
return nil, errors.Wrap(err, "add dummy episode")
}
log.Infof("added dummy episode for movie: %v", nameEn)
movie := ent.Media{
TmdbID: int(detail.ID),
ImdbID: detail.IMDbID,
MediaType: media.MediaTypeMovie,
NameCn: nameCn,
NameEn: nameEn,
OriginalName: detail.OriginalTitle,
Overview: detail.Overview,
AirDate: detail.ReleaseDate,
Resolution: media.Resolution(in.Resolution),
StorageID: in.StorageID,
TargetDir: in.Folder,
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 := c.GetJavid(in.TmdbID)
extras.JavId = javid
}
movie.Extras = extras
r, err := c.db.AddMediaWatchlist(&movie, []int{epid})
if err != nil {
return nil, errors.Wrap(err, "add to list")
}
go func() {
if err := c.downloadPoster(detail.PosterPath, r.ID); err != nil {
log.Errorf("download poster error: %v", err)
}
if err := c.downloadBackdrop(detail.BackdropPath, r.ID); err != nil {
log.Errorf("download backdrop error: %v", err)
}
}()
log.Infof("add movie %s to watchlist success", detail.Title)
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 (c *Client) GetJavid(id int) string {
alters, err := c.MustTMDB().GetMovieAlternativeTitles(id, c.language)
if err != nil {
return ""
}
for _, t := range alters.Titles {
if t.Iso3166_1 == "JP" && t.Type == "" {
return t.Title
}
}
return ""
}
func (c *Client) downloadBackdrop(path string, mediaID int) error {
url := "https://image.tmdb.org/t/p/original" + path
return c.downloadImage(url, mediaID, "backdrop.jpg")
}
func (c *Client) downloadPoster(path string, mediaID int) error {
var url = "https://image.tmdb.org/t/p/original" + path
return c.downloadImage(url, mediaID, "poster.jpg")
}
func (c *Client) downloadImage(url string, mediaID int, name string) error {
log.Infof("try to download image: %v", url)
var resp, err = http.Get(url)
if err != nil {
return errors.Wrap(err, "http get")
}
targetDir := fmt.Sprintf("%v/%d", db.ImgPath, mediaID)
os.MkdirAll(targetDir, 0777)
//ext := filepath.Ext(path)
targetFile := filepath.Join(targetDir, name)
f, err := os.Create(targetFile)
if err != nil {
return errors.Wrap(err, "new file")
}
defer f.Close()
_, err = io.Copy(f, resp.Body)
if err != nil {
return errors.Wrap(err, "copy http response")
}
log.Infof("image successfully downlaoded: %v", targetFile)
return nil
}
func (c *Client) SuggestedMovieFolderName(tmdbId int) (string, error) {
d1, err := c.MustTMDB().GetMovieDetails(tmdbId, c.language)
if err != nil {
return "", errors.Wrap(err, "get movie details")
}
name := d1.Title
if IsJav(d1) {
javid := c.GetJavid(tmdbId)
if javid != "" {
return javid, nil
}
}
info := db.NamingInfo{TmdbID: tmdbId}
if utils.IsASCII(name) {
info.NameEN = stripExtraCharacters(name)
} else {
info.NameCN = stripExtraCharacters(name)
en, err := c.MustTMDB().GetMovieDetails(tmdbId, db.LanguageEN)
if err != nil {
log.Errorf("get en tv detail error: %v", err)
} else {
info.NameEN = stripExtraCharacters(en.Title)
}
}
year := strings.Split(d1.ReleaseDate, "-")[0]
info.Year = year
movieNamingFormat := c.db.GetMovingNamingFormat()
tmpl, err := template.New("test").Parse(movieNamingFormat)
if err != nil {
return "", errors.Wrap(err, "naming format")
}
buff := &bytes.Buffer{}
err = tmpl.Execute(buff, info)
if err != nil {
return "", errors.Wrap(err, "tmpl exec")
}
res := strings.TrimSpace(buff.String())
log.Infof("tv series of tmdb id %v suggestting name is %v", tmdbId, res)
return res, nil
}
func (c *Client) SuggestedSeriesFolderName(tmdbId int) (string, error) {
d, err := c.MustTMDB().GetTvDetails(tmdbId, c.language)
if err != nil {
return "", errors.Wrap(err, "get tv details")
}
name := d.Name
info := db.NamingInfo{TmdbID: tmdbId}
if utils.IsASCII(name) {
info.NameEN = stripExtraCharacters(name)
} else {
info.NameCN = stripExtraCharacters(name)
en, err := c.MustTMDB().GetTvDetails(tmdbId, db.LanguageEN)
if err != nil {
log.Errorf("get en tv detail error: %v", err)
} else {
info.NameEN = stripExtraCharacters(en.Name)
}
}
year := strings.Split(d.FirstAirDate, "-")[0]
info.Year = year
tvNamingFormat := c.db.GetTvNamingFormat()
tmpl, err := template.New("test").Parse(tvNamingFormat)
if err != nil {
return "", errors.Wrap(err, "naming format")
}
buff := &bytes.Buffer{}
err = tmpl.Execute(buff, info)
if err != nil {
return "", errors.Wrap(err, "tmpl exec")
}
res := strings.TrimSpace(buff.String())
log.Infof("tv series of tmdb id %v suggestting name is %v", tmdbId, res)
return res, nil
}
func stripExtraCharacters(s string) string {
re := regexp.MustCompile(`[^\p{L}\w\s]`)
s = re.ReplaceAllString(s, " ")
return strings.Join(strings.Fields(s), " ")
}

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,67 @@ 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]
name, err := task.Name()
if err != nil {
return err
}
target := filepath.Join(downloadDir, 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"
@@ -16,12 +17,24 @@ import (
)
func (c *Client) addSysCron() {
c.mustAddCron("@every 1m", c.checkTasks)
c.mustAddCron("0 0 * * * *", func() {
c.downloadTvSeries()
c.downloadMovie()
c.registerCronJob("check_running_tasks", "@every 1m", c.checkTasks)
c.registerCronJob("check_available_medias_to_download", "0 0 * * * *", func() error {
c.downloadAllTvSeries()
c.downloadAllMovies()
return nil
})
c.registerCronJob("check_series_new_release", "0 0 */12 * * *", c.checkAllSeriesNewSeason)
c.registerCronJob("update_import_lists", "0 30 * * * *", c.periodicallyUpdateImportlist)
c.schedulers.Range(func(key string, value scheduler) bool {
log.Debugf("add cron job: %v", key)
c.mustAddCron(value.cron, func() {
if err := value.f(); err != nil {
log.Errorf("exexuting cron job %s error: %v", key, err)
}
})
return true
})
c.mustAddCron("0 0 */12 * * *", c.checkAllSeriesNewSeason)
c.cron.Start()
}
@@ -32,39 +45,72 @@ func (c *Client) mustAddCron(spec string, cmd func()) {
}
}
func (c *Client) checkTasks() {
func (c *Client) TriggerCronJob(name string) error {
job, ok := c.schedulers.Load(name)
if !ok {
return fmt.Errorf("job name not exists: %s", name)
}
return job.f()
}
func (c *Client) checkTasks() error {
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 {
name, err := t.Name()
if err != nil {
return errors.Wrap(err, "get name")
}
progress, err := t.Progress()
if err != nil {
return errors.Wrap(err, "get progress")
}
log.Infof("task (%s) percentage done: %d%%", name, progress)
if progress == 100 {
if r.Status == history.StatusSeeding {
//task already success, check seed ratio
torrent := c.tasks[id]
ok := c.isSeedRatioLimitReached(r.IndexerID, torrent)
ratio, 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", name, ratio)
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", name, ratio)
}
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)
}
}()
log.Infof("task is done: %v", name)
c.sendMsg(fmt.Sprintf(message.DownloadComplete, name))
go c.postTaskProcessing(id)
}
}
return nil
}
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) {
@@ -85,18 +131,23 @@ func (c *Client) moveCompletedTask(id int) (err1 error) {
log.Errorf("get task download client error: %v, use default one", err)
downloadclient = &ent.DownloadClients{RemoveCompletedDownloads: true, RemoveFailedDownloads: true}
}
torrentName := torrent.Name()
torrentName, err := torrent.Name()
if err != nil {
return err
}
defer func() {
if err1 != nil {
c.db.SetHistoryStatus(r.ID, history.StatusFail)
if r.EpisodeID != 0 {
c.db.SetEpisodeStatus(r.EpisodeID, episode.StatusMissing)
if !c.db.IsEpisodeDownloadingOrDownloaded(r.EpisodeID) {
c.db.SetEpisodeStatus(r.EpisodeID, episode.StatusMissing)
}
} 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 +172,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 {
@@ -135,9 +181,10 @@ func (c *Client) moveCompletedTask(id int) (err1 error) {
c.sendMsg(fmt.Sprintf(message.ProcessingComplete, torrentName))
//判断是否需要删除本地文件
ok := c.isSeedRatioLimitReached(r.IndexerID, torrent)
r1, 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, r1)
c.db.SetHistoryStatus(r.ID, history.StatusSuccess)
delete(c.tasks, r.ID)
torrent.Remove()
}
@@ -202,68 +249,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 +373,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,10 +387,10 @@ 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() {
func (c *Client) checkAllSeriesNewSeason() error {
log.Infof("begin checking series all new season")
allSeries := c.db.GetMediaWatchlist(media.MediaTypeTv)
for _, series := range allSeries {
@@ -297,6 +399,7 @@ func (c *Client) checkAllSeriesNewSeason() {
log.Errorf("check series new season error: series name %v, error: %v", series.NameEn, err)
}
}
return nil
}
func (c *Client) checkSeiesNewSeason(media *ent.Media) error {
@@ -337,15 +440,15 @@ func (c *Client) checkSeiesNewSeason(media *ent.Media) error {
return nil
}
func (c *Client) isSeedRatioLimitReached(indexId int, t pkg.Torrent) bool {
func (c *Client) isSeedRatioLimitReached(indexId int, t pkg.Torrent)(float64,bool) {
indexer, err := c.db.GetIndexer(indexId)
if err != nil {
return true
return 0, true
}
currentRatio := t.SeedRatio()
if currentRatio == nil {
log.Warnf("get current seed ratio error, current ratio is nil")
return indexer.SeedRatio == 0
currentRatio, err := t.SeedRatio()
if err != nil {
log.Warnf("get current seed ratio error: %v", err)
return currentRatio, indexer.SeedRatio == 0
}
return *currentRatio >= float64(indexer.SeedRatio)
return currentRatio, currentRatio >= float64(indexer.SeedRatio)
}

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)
}

63
server/importlist.go Normal file
View File

@@ -0,0 +1,63 @@
package server
import (
"fmt"
"polaris/ent"
"polaris/ent/importlist"
"polaris/pkg/utils"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
)
func (s *Server) getAllImportLists(c *gin.Context) (interface{}, error) {
lists, err := s.db.GetAllImportLists()
return lists, err
}
type addImportlistIn struct {
Name string `json:"name" binding:"required"`
Url string `json:"url"`
Type string `json:"type"`
Qulity string `json:"qulity"`
StorageId int `json:"storage_id"`
}
func (s *Server) addImportlist(c *gin.Context) (interface{}, error) {
var in addImportlistIn
if err := c.ShouldBindJSON(&in); err != nil {
return nil, errors.Wrap(err, "json")
}
utils.TrimFields(&in)
st := s.db.GetStorage(in.StorageId)
if st == nil {
return nil, fmt.Errorf("storage id not exist: %v", in.StorageId)
}
err := s.db.AddImportlist(&ent.ImportList{
Name: in.Name,
URL: in.Url,
Type: importlist.Type(in.Type),
Qulity: in.Qulity,
StorageID: in.StorageId,
})
if err != nil {
return nil, err
}
return "success", nil
}
type deleteImportlistIn struct {
ID int `json:"id"`
}
func (s *Server) deleteImportList(c *gin.Context) (interface{}, error) {
var in deleteImportlistIn
if err := c.ShouldBindJSON(&in); err != nil {
return nil, errors.Wrap(err, "json")
}
s.db.DeleteImportlist(in.ID)
return "sucess", nil
}

View File

@@ -2,6 +2,7 @@ package server
import (
"polaris/ent"
"polaris/pkg/utils"
"strconv"
"github.com/gin-gonic/gin"
@@ -35,6 +36,7 @@ func (s *Server) AddNotificationClient(c *gin.Context) (interface{}, error) {
if err := c.ShouldBindJSON(&in); err != nil {
return nil, errors.Wrap(err, "json")
}
utils.TrimFields(&in)
err := s.db.AddNotificationClient(in.Name, in.Service, in.Settings, in.Enabled)
if err != nil {

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

@@ -22,8 +22,9 @@ import (
func NewServer(db *db.Client) *Server {
r := gin.Default()
s := &Server{
r: r,
db: db,
r: r,
db: db,
language: db.GetLanguage(),
}
s.core = core.NewClient(db, s.language)
return s
@@ -68,6 +69,7 @@ func (s *Server) Serve() error {
setting.POST("/parse/tv", HttpHandler(s.ParseTv))
setting.POST("/parse/movie", HttpHandler(s.ParseMovie))
setting.POST("/monitoring", HttpHandler(s.ChangeEpisodeMonitoring))
setting.POST("/cron/trigger", HttpHandler(s.TriggerCronJob))
}
activity := api.Group("/activity")
{
@@ -80,6 +82,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 +93,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")
{
@@ -118,8 +122,13 @@ func (s *Server) Serve() error {
notifier.DELETE("/id/:id", HttpHandler(s.DeleteNotificationClient))
notifier.POST("/add", HttpHandler(s.AddNotificationClient))
}
importlist := api.Group("/importlist")
{
importlist.GET("/", HttpHandler(s.getAllImportLists))
importlist.POST("/add", HttpHandler(s.addImportlist))
importlist.DELETE("/delete", HttpHandler(s.deleteImportList))
}
s.language = s.db.GetLanguage()
return s.r.Run(":8080")
}
@@ -129,7 +138,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

@@ -3,10 +3,12 @@ package server
import (
"encoding/json"
"fmt"
"html/template"
"polaris/db"
"polaris/ent"
"polaris/log"
"polaris/pkg/transmission"
"polaris/pkg/utils"
"strconv"
"github.com/gin-gonic/gin"
@@ -14,11 +16,16 @@ 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"`
TvNamingFormat string `json:"tv_naming_format"`
MovieNamingFormat string `json:"movie_naming_format"`
}
func (s *Server) SetSetting(c *gin.Context) (interface{}, error) {
@@ -26,6 +33,8 @@ func (s *Server) SetSetting(c *gin.Context) (interface{}, error) {
if err := c.ShouldBindJSON(&in); err != nil {
return nil, errors.Wrap(err, "bind json")
}
utils.TrimFields(&in)
log.Infof("set setting input: %+v", in)
if in.TmdbApiKey != "" {
if err := s.db.SetSetting(db.SettingTmdbApiKey, in.TmdbApiKey); err != nil {
@@ -43,7 +52,20 @@ func (s *Server) SetSetting(c *gin.Context) (interface{}, error) {
if err := s.db.SetSetting(db.SettingLogLevel, in.LogLevel); err != nil {
return nil, errors.Wrap(err, "save log level")
}
}
if in.TvNamingFormat != "" {
if _, err := template.New("test").Parse(in.TvNamingFormat);err != nil {
return nil, errors.Wrap(err, "tv format")
}
s.db.SetSetting(db.SettingTvNamingFormat, in.TvNamingFormat)
}
if in.MovieNamingFormat != "" {
if _, err := template.New("test").Parse(in.MovieNamingFormat);err != nil {
return nil, errors.Wrap(err, "movie format")
}
s.db.SetSetting(db.SettingMovieNamingFormat, in.MovieNamingFormat)
}
plexmatchEnabled := s.db.GetSetting(db.SettingPlexMatchEnabled)
@@ -54,6 +76,23 @@ 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 +101,22 @@ 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)
tvFormat := s.db.GetTvNamingFormat()
movieFormat := s.db.GetMovingNamingFormat()
return &GeneralSettings{
TmdbApiKey: tmdb,
DownloadDir: downloadDir,
LogLevel: logLevel,
Proxy: s.db.GetSetting(db.SettingProxy),
EnablePlexmatch: plexmatchEnabled == "true",
TmdbApiKey: tmdb,
DownloadDir: downloadDir,
LogLevel: logLevel,
Proxy: s.db.GetSetting(db.SettingProxy),
EnablePlexmatch: plexmatchEnabled == "true",
AllowQiangban: allowQiangban == "true",
EnableNfo: enableNfo == "true",
EnableAdultContent: enableAdult == "true",
TvNamingFormat: tvFormat,
MovieNamingFormat: movieFormat,
}, nil
}
@@ -86,6 +135,7 @@ func (s *Server) AddTorznabInfo(c *gin.Context) (interface{}, error) {
if err := c.ShouldBindJSON(&in); err != nil {
return nil, errors.Wrap(err, "bind json")
}
utils.TrimFields(&in)
log.Infof("add indexer settings: %+v", in)
setting := db.TorznabSetting{
@@ -161,6 +211,7 @@ func (s *Server) AddDownloadClient(c *gin.Context) (interface{}, error) {
if err := c.ShouldBindJSON(&in); err != nil {
return nil, errors.Wrap(err, "bind json")
}
utils.TrimFields(&in)
//test connection
_, err := transmission.NewClient(transmission.Config{
URL: in.URL,
@@ -195,8 +246,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 +257,33 @@ 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
}
type triggerCronJobIn struct {
JobName string `json:"job_name"`
}
func (s *Server) TriggerCronJob(c *gin.Context) (interface{}, error) {
var in triggerCronJobIn
if err := c.ShouldBindJSON(&in); err != nil {
return nil, errors.Wrap(err, "bind")
}
err := s.core.TriggerCronJob(in.JobName)
if err != nil {
return nil, err
}
return "success", nil
}

View File

@@ -6,8 +6,8 @@ import (
"polaris/log"
"polaris/pkg/storage"
"polaris/pkg/utils"
"strconv"
"strings"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
@@ -23,6 +23,7 @@ func (s *Server) AddStorage(c *gin.Context) (interface{}, error) {
if err := c.ShouldBindJSON(&in); err != nil {
return nil, errors.Wrap(err, "bind json")
}
utils.TrimFields(&in)
if in.Implementation == "webdav" {
//test webdav
@@ -60,27 +61,10 @@ func (s *Server) SuggestedSeriesFolderName(c *gin.Context) (interface{}, error)
if err != nil {
return nil, fmt.Errorf("id is not int: %v", ids)
}
d, err := s.MustTMDB().GetTvDetails(id, s.language)
name, err := s.core.SuggestedSeriesFolderName(id)
if err != nil {
return nil, errors.Wrap(err, "get tv details")
return nil, err
}
name := d.Name
if s.language == db.LanguageCN {
en, err := s.MustTMDB().GetTvDetails(id, db.LanguageEN)
if err != nil {
log.Errorf("get en tv detail error: %v", err)
} else {
name = fmt.Sprintf("%s %s", d.Name, en.Name)
}
}
year := strings.Split(d.FirstAirDate, "-")[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
}
@@ -90,25 +74,9 @@ func (s *Server) SuggestedMovieFolderName(c *gin.Context) (interface{}, error) {
if err != nil {
return nil, fmt.Errorf("id is not int: %v", ids)
}
d1, err := s.MustTMDB().GetMovieDetails(id, s.language)
name, err := s.core.SuggestedMovieFolderName(id)
if err != nil {
return nil, errors.Wrap(err, "get movie details")
return nil, err
}
name := d1.Title
if s.language == db.LanguageCN {
en, err := s.MustTMDB().GetMovieDetails(id, db.LanguageEN)
if err != nil {
log.Errorf("get en movie detail error: %v", err)
} else {
name = fmt.Sprintf("%s %s", d1.Title, en.Title)
}
}
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

@@ -1,21 +1,16 @@
package server
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"polaris/db"
"polaris/ent"
"polaris/ent/episode"
"polaris/ent/media"
"polaris/ent/schema"
"polaris/log"
"polaris/server/core"
"strconv"
"time"
tmdb "github.com/cyruzin/golang-tmdb"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
)
@@ -72,206 +67,19 @@ type addWatchlistIn struct {
}
func (s *Server) AddTv2Watchlist(c *gin.Context) (interface{}, error) {
var in addWatchlistIn
var in core.AddWatchlistIn
if err := c.ShouldBindJSON(&in); err != nil {
return nil, errors.Wrap(err, "bind query")
}
log.Debugf("add tv watchlist input %+v", in)
if in.Folder == "" {
return nil, errors.New("folder should be provided")
}
detailCn, err := s.MustTMDB().GetTvDetails(in.TmdbID, db.LanguageCN)
if err != nil {
return nil, errors.Wrap(err, "get tv detail")
}
var nameCn = detailCn.Name
detailEn, _ := s.MustTMDB().GetTvDetails(in.TmdbID, db.LanguageEN)
var nameEn = detailEn.Name
var detail *tmdb.TVDetails
if s.language == "" || s.language == db.LanguageCN {
detail = detailCn
} else {
detail = detailEn
}
log.Infof("find detail for tv id %d: %v", in.TmdbID, detail)
var epIds []int
for _, season := range detail.Seasons {
seasonId := season.SeasonNumber
se, err := s.MustTMDB().GetSeasonDetails(int(detail.ID), seasonId, s.language)
if err != nil {
log.Errorf("get season detail (%s) error: %v", detail.Name, err)
continue
}
for _, ep := range se.Episodes {
shouldMonitor := false
//如果设置下载往期剧集则监控所有剧集。如果没有则监控未上映的剧集考虑时差等问题留24h余量
if in.DownloadHistoryEpisodes {
shouldMonitor = true
} else {
t, err := time.Parse("2006-01-02", ep.AirDate)
if err != nil {
log.Error("air date not known, will monitor: %v", ep.AirDate)
shouldMonitor = true
} else {
if time.Since(t) < 24*time.Hour { //monitor episode air 24h before now
shouldMonitor = true
}
}
}
epid, err := s.db.SaveEposideDetail(&ent.Episode{
SeasonNumber: seasonId,
EpisodeNumber: ep.EpisodeNumber,
Title: ep.Name,
Overview: ep.Overview,
AirDate: ep.AirDate,
Monitored: shouldMonitor,
})
if err != nil {
log.Errorf("save episode info error: %v", err)
continue
}
epIds = append(epIds, epid)
}
}
m := &ent.Media{
TmdbID: int(detail.ID),
MediaType: media.MediaTypeTv,
NameCn: nameCn,
NameEn: nameEn,
OriginalName: detail.OriginalName,
Overview: detail.Overview,
AirDate: detail.FirstAirDate,
Resolution: media.Resolution(in.Resolution),
StorageID: in.StorageID,
TargetDir: in.Folder,
DownloadHistoryEpisodes: in.DownloadHistoryEpisodes,
Limiter: &schema.MediaLimiter{SizeMin: in.SizeMin, SizeMax: in.SizeMax},
}
r, err := s.db.AddMediaWatchlist(m, epIds)
if err != nil {
return nil, errors.Wrap(err, "add to list")
}
go func() {
if err := s.downloadPoster(detail.PosterPath, r.ID); err != nil {
log.Errorf("download poster error: %v", err)
}
if err := s.downloadBackdrop(detail.BackdropPath, r.ID); err != nil {
log.Errorf("download poster error: %v", err)
}
if err := s.core.CheckDownloadedSeriesFiles(r); err != nil {
log.Errorf("check downloaded files error: %v", err)
}
}()
log.Infof("add tv %s to watchlist success", detail.Name)
return nil, nil
return s.core.AddTv2Watchlist(in)
}
func (s *Server) AddMovie2Watchlist(c *gin.Context) (interface{}, error) {
var in addWatchlistIn
var in core.AddWatchlistIn
if err := c.ShouldBindJSON(&in); err != nil {
return nil, errors.Wrap(err, "bind query")
}
log.Infof("add movie watchlist input: %+v", in)
detailCn, err := s.MustTMDB().GetMovieDetails(in.TmdbID, db.LanguageCN)
if err != nil {
return nil, errors.Wrap(err, "get movie detail")
}
var nameCn = detailCn.Title
detailEn, _ := s.MustTMDB().GetMovieDetails(in.TmdbID, db.LanguageEN)
var nameEn = detailEn.Title
var detail *tmdb.MovieDetails
if s.language == "" || s.language == db.LanguageCN {
detail = detailCn
} else {
detail = detailEn
}
log.Infof("find detail for movie id %d: %v", in.TmdbID, detail)
epid, err := s.db.SaveEposideDetail(&ent.Episode{
SeasonNumber: 1,
EpisodeNumber: 1,
Title: "dummy episode for movies",
Overview: "dummy episode for movies",
AirDate: detail.ReleaseDate,
Monitored: true,
})
if err != nil {
return nil, errors.Wrap(err, "add dummy episode")
}
log.Infof("added dummy episode for movie: %v", nameEn)
r, err := s.db.AddMediaWatchlist(&ent.Media{
TmdbID: int(detail.ID),
MediaType: media.MediaTypeMovie,
NameCn: nameCn,
NameEn: nameEn,
OriginalName: detail.OriginalTitle,
Overview: detail.Overview,
AirDate: detail.ReleaseDate,
Resolution: media.Resolution(in.Resolution),
StorageID: in.StorageID,
TargetDir: in.Folder,
Limiter: &schema.MediaLimiter{SizeMin: in.SizeMin, SizeMax: in.SizeMax},
}, []int{epid})
if err != nil {
return nil, errors.Wrap(err, "add to list")
}
go func() {
if err := s.downloadPoster(detail.PosterPath, r.ID); err != nil {
log.Errorf("download poster error: %v", err)
}
if err := s.downloadBackdrop(detail.BackdropPath, r.ID); err != nil {
log.Errorf("download backdrop error: %v", err)
}
}()
log.Infof("add movie %s to watchlist success", detail.Title)
return nil, nil
}
func (s *Server) downloadBackdrop(path string, mediaID int) error {
url := "https://image.tmdb.org/t/p/original" + path
return s.downloadImage(url, mediaID, "backdrop.jpg")
}
func (s *Server) downloadPoster(path string, mediaID int) error {
var url = "https://image.tmdb.org/t/p/original" + path
return s.downloadImage(url, mediaID, "poster.jpg")
}
func (s *Server) downloadImage(url string, mediaID int, name string) error {
log.Infof("try to download image: %v", url)
var resp, err = http.Get(url)
if err != nil {
return errors.Wrap(err, "http get")
}
targetDir := fmt.Sprintf("%v/%d", db.ImgPath, mediaID)
os.MkdirAll(targetDir, 0777)
//ext := filepath.Ext(path)
targetFile := filepath.Join(targetDir, name)
f, err := os.Create(targetFile)
if err != nil {
return errors.Wrap(err, "new file")
}
defer f.Close()
_, err = io.Copy(f, resp.Body)
if err != nil {
return errors.Wrap(err, "copy http response")
}
log.Infof("image successfully downlaoded: %v", targetFile)
return nil
return s.core.AddMovie2Watchlist(in)
}
type MediaWithStatus struct {

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!.toString()),
icon: const Icon(Icons.delete))
: const Text("-"),
),
Divider(),
],
);
},
));
},
error: (err, trace) => Text("$err"),
loading: () => const MyProgressIndicator());
@@ -83,7 +155,7 @@ class _ActivityPageState extends ConsumerState<ActivityPage>
);
}
Function(int) onDelete() {
Function(String) onDelete() {
return (id) {
final f = ref
.read(activitiesDataProvider("active").notifier)
@@ -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;
}

60
ui/lib/calendar.dart Normal file
View File

@@ -0,0 +1,60 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:table_calendar/table_calendar.dart';
class Calendar extends ConsumerStatefulWidget {
@override
ConsumerState<ConsumerStatefulWidget> createState() {
return _CalendarSate();
}
}
class _CalendarSate extends ConsumerState<Calendar> {
DateTime? _selectedDay;
DateTime _focusedDay = DateTime.now();
CalendarFormat _calendarFormat = CalendarFormat.month;
@override
Widget build(BuildContext context) {
return TableCalendar(
locale: "zh_CN",
firstDay: DateTime.utc(2010, 10, 16),
lastDay: DateTime.utc(2030, 3, 14),
focusedDay: _focusedDay,
selectedDayPredicate: (day) {
return isSameDay(_selectedDay, day);
},
onDaySelected: (selectedDay, focusedDay) {
setState(() {
_selectedDay = selectedDay;
_focusedDay = focusedDay; // update `_focusedDay` here as well
});
},
calendarFormat: _calendarFormat,
onFormatChanged: (format) {
setState(() {
_calendarFormat = format;
});
},
//locale: "zh_CN",
//eventLoader: (day) {},
);
}
}
showCalendar(BuildContext context) {
return showDialog<void>(
context: context,
barrierDismissible: true,
builder: (BuildContext context) {
return AlertDialog(
//title: Text("资源"),
content: SizedBox(
width: MediaQuery.of(context).size.width * 0.7,
height: MediaQuery.of(context).size.height * 0.6,
child: Calendar()),
);
},
);
}

View File

@@ -2,7 +2,9 @@ import 'package:flutter/material.dart';
import 'package:flutter_adaptive_scaffold/flutter_adaptive_scaffold.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:ui/activity.dart';
import 'package:ui/calendar.dart';
import 'package:ui/login_page.dart';
import 'package:ui/movie_watchlist.dart';
import 'package:ui/providers/APIs.dart';
@@ -11,9 +13,10 @@ 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());
initializeDateFormatting().then((_) => runApp(MyApp()));
}
class MyApp extends ConsumerStatefulWidget {
@@ -49,7 +52,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 +133,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 +188,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(
@@ -212,6 +221,9 @@ class _MainSkeletonState extends State<MainSkeleton> {
(BuildContext context, SearchController controller) {
return [Text("dadada")];
}),
IconButton(
onPressed: () => showCalendar(context),
icon: Icon(Icons.calendar_month)),
MenuAnchor(
menuChildren: [
MenuItemButton(
@@ -282,7 +294,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";
@@ -34,6 +36,9 @@ class APIs {
static final logFilesUrl = "$_baseUrl/api/v1/setting/logfiles";
static final aboutUrl = "$_baseUrl/api/v1/setting/about";
static final changeMonitoringUrl = "$_baseUrl/api/v1/setting/monitoring";
static final addImportlistUrl = "$_baseUrl/api/v1/importlist/add";
static final deleteImportlistUrl = "$_baseUrl/api/v1/importlist/delete";
static final getAllImportlists = "$_baseUrl/api/v1/importlist/";
static final notifierAllUrl = "$_baseUrl/api/v1/notifier/all";
static final notifierDeleteUrl = "$_baseUrl/api/v1/notifier/id/";
@@ -41,6 +46,8 @@ class APIs {
static final tmdbImgBaseUrl = "$_baseUrl/api/v1/posters";
static final cronJobUrl = "$_baseUrl/api/v1/setting/cron/trigger";
static const tmdbApiKey = "tmdb_api_key";
static const downloadDirKey = "download_dir";
@@ -95,4 +102,14 @@ class APIs {
context.go('/login');
}
}
static Future<void> triggerCronJob(String name) async {
var resp = await getDio().post(APIs.cronJobUrl, data: {"job_name": name});
var sp = ServerResponse.fromJson(resp.data);
if (sp.code != 0) {
throw sp.message;
}
}
}

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") {
@@ -47,7 +47,7 @@ class ActivityData extends FamilyAsyncNotifier<List<Activity>, String> {
return activities;
}
Future<void> deleteActivity(int id) async {
Future<void> deleteActivity(String id) async {
final dio = await APIs.getDio();
var resp = await dio.delete("${APIs.activityUrl}$id");
final sp = ServerResponse.fromJson(resp.data);
@@ -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

@@ -21,6 +21,10 @@ var storageSettingProvider =
AsyncNotifierProvider.autoDispose<StorageSettingData, List<Storage>>(
StorageSettingData.new);
var importlistProvider =
AsyncNotifierProvider.autoDispose<ImportListData, List<ImportList>>(
ImportListData.new);
class EditSettingData extends AutoDisposeAsyncNotifier<GeneralSetting> {
@override
FutureOr<GeneralSetting> build() async {
@@ -52,13 +56,23 @@ class GeneralSetting {
String? logLevel;
String? proxy;
bool? enablePlexmatch;
bool? allowQiangban;
bool? enableNfo;
bool? enableAdult;
String? tvNamingFormat;
String? movieNamingFormat;
GeneralSetting(
{this.tmdbApiKey,
this.downloadDIr,
this.logLevel,
this.proxy,
this.enablePlexmatch});
this.enablePlexmatch,
this.enableNfo,
this.allowQiangban,
this.tvNamingFormat,
this.movieNamingFormat,
this.enableAdult});
factory GeneralSetting.fromJson(Map<String, dynamic> json) {
return GeneralSetting(
@@ -66,6 +80,11 @@ 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,
tvNamingFormat: json["tv_naming_format"],
movieNamingFormat: json["movie_naming_format"],
enablePlexmatch: json["enable_plexmatch"] ?? false);
}
@@ -76,6 +95,11 @@ 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;
data["tv_naming_format"] = tvNamingFormat;
data["movie_naming_format"] = movieNamingFormat;
return data;
}
}
@@ -134,7 +158,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 +173,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() {
@@ -394,3 +425,77 @@ class About {
);
}
}
class ImportList {
final int? id;
final String? name;
final String? url;
final String? qulity;
final int? storageId;
final String? type;
ImportList({
this.id,
this.name,
this.url,
this.qulity,
this.storageId,
this.type,
});
factory ImportList.fromJson(Map<String, dynamic> json) {
return ImportList(
id: json["id"],
name: json["name"],
url: json["url"],
qulity: json["qulity"],
type: json["type"],
storageId: json["storage_id"]);
}
Map<String, dynamic> tojson() => {
"name": name,
"url": url,
"qulity": qulity,
"type": type,
"storage_id": storageId
};
}
class ImportListData extends AutoDisposeAsyncNotifier<List<ImportList>> {
@override
FutureOr<List<ImportList>> build() async {
final dio = APIs.getDio();
var resp = await dio.get(APIs.getAllImportlists);
var sp = ServerResponse.fromJson(resp.data);
if (sp.code != 0) {
throw sp.message;
}
List<ImportList> list = List.empty(growable: true);
for (var item in sp.data as List) {
var il = ImportList.fromJson(item);
list.add(il);
}
return list;
}
addImportlist(ImportList il) async {
final dio = APIs.getDio();
var resp = await dio.post(APIs.addImportlistUrl, data: il.tojson());
var sp = ServerResponse.fromJson(resp.data);
if (sp.code != 0) {
throw sp.message;
}
ref.invalidateSelf();
}
deleteimportlist(int id) async {
final dio = APIs.getDio();
var resp = await dio.post(APIs.deleteImportlistUrl, data: {"id": id});
var sp = ServerResponse.fromJson(resp.data);
if (sp.code != 0) {
throw sp.message;
}
ref.invalidateSelf();
}
}

View File

@@ -108,14 +108,14 @@ 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) {
throw sp.message;
}
ref.invalidate(tvWatchlistDataProvider);
//ref.invalidate(tvWatchlistDataProvider);
} else {
var resp = await dio.post(APIs.watchlistMovieUrl, data: {
"tmdb_id": tmdbId,

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

@@ -17,17 +17,16 @@ Future<void> showSettingDialog(
content: SingleChildScrollView(
child: SizedBox(
width: 400,
child: body,
child: SelectionArea(child: body),
),
),
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,12 @@ 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,
"tv_naming_format": v.tvNamingFormat,
"movie_naming_format": v.movieNamingFormat,
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -60,8 +65,25 @@ class _GeneralState extends ConsumerState<GeneralSettings> {
decoration: const InputDecoration(
labelText: "代理地址",
icon: Icon(Icons.web),
hintText: "http://10.0.0.1:1080",
helperText: "后台联网代理地址,留空表示不启用代理"),
),
FormBuilderTextField(
decoration: const InputDecoration(
icon: Icon(Icons.folder),
labelText: "电视剧路径命名规则",
helperText:
"go template语法可用的变量为.NameCN, .NameEN, .Year, .TmdbID"),
name: "tv_naming_format",
),
FormBuilderTextField(
decoration: const InputDecoration(
icon: Icon(Icons.folder),
labelText: "电影路径命名规则",
helperText:
"go template语法可用的变量为.NameCN, .NameEN, .Year, .TmdbID"),
name: "movie_naming_format",
),
SizedBox(
width: 300,
child: FormBuilderDropdown(
@@ -81,8 +103,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 +152,12 @@ 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"],
tvNamingFormat: values["tv_naming_format"],
movieNamingFormat:
values["movie_naming_format"],
enablePlexmatch:
values["enable_plexmatch"]))
.then((v) => showSnakeBar("更新成功"));

View File

@@ -0,0 +1,147 @@
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:ui/providers/settings.dart';
import 'package:ui/settings/dialog.dart';
import 'package:ui/widgets/progress_indicator.dart';
import 'package:ui/widgets/widgets.dart';
class Importlist extends ConsumerStatefulWidget {
const Importlist({super.key});
@override
ConsumerState<ConsumerStatefulWidget> createState() {
return _ImportlistState();
}
}
class _ImportlistState extends ConsumerState<Importlist> {
@override
Widget build(BuildContext context) {
var importlists = ref.watch(importlistProvider);
return importlists.when(
data: (value) => Wrap(
children: List.generate(value.length + 1, (i) {
if (i < value.length) {
var indexer = value[i];
return SettingsCard(
onTap: () => showImportlistDetails(indexer),
child: Text(indexer.name ?? ""));
}
return SettingsCard(
onTap: () => showImportlistDetails(ImportList()),
child: const Icon(Icons.add));
}),
),
error: (err, trace) => Text("$err"),
loading: () => const MyProgressIndicator());
}
Future<void> showImportlistDetails(ImportList list) {
final _formKey = GlobalKey<FormBuilderState>();
String? _selectedType = list.type;
var body = StatefulBuilder(builder: (context, setState) {
return FormBuilder(
key: _formKey,
initialValue: {
"name": list.name,
"url": list.url,
"qulity": list.qulity,
"type": list.type,
"storage_id": list.storageId
},
child: Column(
children: [
FormBuilderDropdown(
name: "type",
decoration: const InputDecoration(
labelText: "类型",
hintText:
"Plex Watchlist: https://support.plex.tv/articles/universal-watchlist/"),
items: const [
DropdownMenuItem(value: "plex", child: Text("Plex Watchlist")),
],
onChanged: (value) {
setState(() {
_selectedType = value;
});
},
),
_selectedType == "plex"
? const Text(
"Plex Watchlist: https://support.plex.tv/articles/universal-watchlist/")
: const Text(""),
FormBuilderTextField(
name: "name",
decoration: Commons.requiredTextFieldStyle(text: "名称"),
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: FormBuilderValidators.required(),
),
FormBuilderTextField(
name: "url",
decoration: Commons.requiredTextFieldStyle(text: "地址"),
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: FormBuilderValidators.required(),
),
FormBuilderDropdown(
name: "qulity",
decoration: const InputDecoration(labelText: "清晰度"),
items: const [
DropdownMenuItem(value: "720p", child: Text("720p")),
DropdownMenuItem(value: "1080p", child: Text("1080p")),
DropdownMenuItem(value: "2160p", child: Text("2160p")),
],
),
Consumer(
builder: (context, ref, child) {
var storage = ref.watch(storageSettingProvider);
return storage.when(
data: (v) {
return FormBuilderDropdown(
name: "storage_id",
decoration: const InputDecoration(labelText: "存储"),
items: List.generate(
v.length,
(i) => DropdownMenuItem(
value: v[i].id,
child: Text(v[i].name!),
)),
);
},
error: (err, trace) => Text("$err"),
loading: () => const MyProgressIndicator());
},
),
],
),
);
});
onDelete() async {
return ref.read(importlistProvider.notifier).deleteimportlist(list.id!);
}
onSubmit() async {
if (_formKey.currentState!.saveAndValidate()) {
var values = _formKey.currentState!.value;
return ref.read(importlistProvider.notifier).addImportlist(ImportList(
id: list.id,
name: values["name"],
url: values["url"],
type: values["type"],
qulity: values["qulity"],
storageId: values["storage_id"],
));
} else {
throw "validation_error";
}
}
return showSettingDialog(
context, "监控列表", list.id != null, body, onSubmit, onDelete);
}
}

View File

@@ -116,6 +116,7 @@ class _NotifierState extends ConsumerState<NotifierSettings> {
},
child: Column(
children: [
const Text("https://bark.day.app/#/"),
FormBuilderTextField(
name: "name",
decoration: Commons.requiredTextFieldStyle(text: "名称"),
@@ -176,6 +177,7 @@ class _NotifierState extends ConsumerState<NotifierSettings> {
},
child: Column(
children: [
const Text("https://pushover.net/"),
FormBuilderTextField(
name: "name",
decoration: Commons.requiredTextFieldStyle(text: "名称"),

View File

@@ -3,6 +3,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:ui/settings/auth.dart';
import 'package:ui/settings/downloader.dart';
import 'package:ui/settings/general.dart';
import 'package:ui/settings/importlist.dart';
import 'package:ui/settings/indexer.dart';
import 'package:ui/settings/notifier.dart';
import 'package:ui/settings/storage.dart';
@@ -21,49 +22,25 @@ class _SystemSettingsPageState extends ConsumerState<SystemSettingsPage> {
@override
Widget build(BuildContext context) {
return ListView(
children: const [
ExpansionTile(
expandedAlignment: Alignment.centerLeft,
childrenPadding: EdgeInsets.fromLTRB(20, 0, 20, 0),
initiallyExpanded: true,
title: Text("常规"),
children: [GeneralSettings()],
),
ExpansionTile(
expandedAlignment: Alignment.centerLeft,
childrenPadding: EdgeInsets.fromLTRB(20, 0, 20, 0),
initiallyExpanded: false,
title: Text("索引器"),
children: [IndexerSettings()],
),
ExpansionTile(
expandedAlignment: Alignment.centerLeft,
childrenPadding: EdgeInsets.fromLTRB(20, 0, 20, 0),
initiallyExpanded: false,
title: Text("下载器"),
children: [DownloaderSettings()],
),
ExpansionTile(
expandedAlignment: Alignment.centerLeft,
childrenPadding: EdgeInsets.fromLTRB(20, 0, 50, 0),
initiallyExpanded: false,
title: Text("存储"),
children: [StorageSettings()],
),
ExpansionTile(
expandedAlignment: Alignment.centerLeft,
childrenPadding: EdgeInsets.fromLTRB(20, 0, 50, 0),
initiallyExpanded: false,
title: Text("通知客户端"),
children: [NotifierSettings()],
),
ExpansionTile(
childrenPadding: EdgeInsets.fromLTRB(20, 0, 20, 0),
initiallyExpanded: false,
title: Text("认证"),
children: [AuthSettings()],
),
children: [
getExpansionTile("常规", const GeneralSettings()),
getExpansionTile("索引器", const IndexerSettings()),
getExpansionTile("下载器", const DownloaderSettings()),
getExpansionTile("存储", const StorageSettings()),
getExpansionTile("通知客户端", const NotifierSettings()),
getExpansionTile("监控列表", const Importlist()),
getExpansionTile("认证", const AuthSettings())
],
);
}
Widget getExpansionTile(String name, Widget body) {
return ExpansionTile(
childrenPadding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
expandedAlignment: Alignment.topLeft,
initiallyExpanded: false,
title: Text(name),
children: [body],
);
}
}

View File

@@ -5,6 +5,7 @@ import 'package:ui/providers/APIs.dart';
import 'package:ui/providers/settings.dart';
import 'package:ui/widgets/utils.dart';
import 'package:ui/widgets/progress_indicator.dart';
import 'package:ui/widgets/widgets.dart';
import 'package:url_launcher/url_launcher.dart';
class SystemPage extends ConsumerStatefulWidget {
@@ -28,8 +29,8 @@ class _SystemPageState extends ConsumerState<SystemPage> {
ExpansionTile(
expandedCrossAxisAlignment: CrossAxisAlignment.stretch,
initiallyExpanded: true,
childrenPadding: EdgeInsets.all(20),
title: Text("日志"),
childrenPadding: const EdgeInsets.all(20),
title: const Text("日志"),
children: [
logs.when(
data: (list) {
@@ -59,7 +60,62 @@ class _SystemPageState extends ConsumerState<SystemPage> {
],
),
ExpansionTile(
title: Text("关于"),
expandedCrossAxisAlignment: CrossAxisAlignment.stretch,
initiallyExpanded: true,
childrenPadding: const EdgeInsets.all(20),
title: const Text("定时任务"),
children: [
logs.when(
data: (list) {
return DataTable(columns: const [
DataColumn(label: Text("任务")),
DataColumn(label: Text("间隔")),
DataColumn(label: Text("手动触发"))
], rows: [
DataRow(cells: [
const DataCell(Text("检查并处理已完成任务")),
const DataCell(Text("每分钟")),
DataCell(LoadingIconButton(
icon: Icons.not_started,
onPressed: () =>
APIs.triggerCronJob("check_running_tasks"),
))
]),
DataRow(cells: [
const DataCell(Text("下载监控中的剧集和电影")),
const DataCell(Text("每小时")),
DataCell(LoadingIconButton(
icon: Icons.not_started,
onPressed: () => APIs.triggerCronJob(
"check_available_medias_to_download"),
))
]),
DataRow(cells: [
const DataCell(Text("更新监控列表")),
const DataCell(Text("每小时")),
DataCell(IconButton(
icon: const Icon(Icons.not_started),
onPressed: () =>
APIs.triggerCronJob("update_import_lists"),
))
]),
DataRow(cells: [
const DataCell(Text("更新最新剧集信息")),
const DataCell(Text("每天2次")),
DataCell(LoadingIconButton(
icon: Icons.not_started,
onPressed: () =>
APIs.triggerCronJob("check_series_new_release"),
))
]),
]);
},
error: (err, trace) => Text("$err"),
loading: () => const MyProgressIndicator())
],
),
ExpansionTile(
title: const Text("关于"),
expandedCrossAxisAlignment: CrossAxisAlignment.center,
initiallyExpanded: true,
children: [

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 {
const LoadingIconButton({super.key, 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 {
const LoadingTextButton({super.key, 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:
@@ -365,6 +365,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "3.2.0"
simple_gesture_detector:
dependency: transitive
description:
name: simple_gesture_detector
sha256: ba2cd5af24ff20a0b8d609cec3f40e5b0744d2a71804a2616ae086b9c19d19a3
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.2.1"
sky_engine:
dependency: transitive
description: flutter
@@ -410,6 +418,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.2.0"
table_calendar:
dependency: "direct main"
description:
name: table_calendar
sha256: "4ca32b2fc919452c9974abd4c6ea611a63e33b9e4f0b8c38dba3ac1f4a6549d1"
url: "https://pub.flutter-io.cn"
source: hosted
version: "3.1.2"
term_glyph:
dependency: transitive
description:
@@ -422,10 +438,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 +470,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 +510,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 +534,18 @@ packages:
dependency: transitive
description:
name: vm_service
sha256: "3923c89304b715fb1eb6423f017651664a03bf5f4b29983627c4da791f74a4ec"
sha256: "5c5f338a667b4c644744b661f309fb8080bb94b18a7e91ef1dbd343bed00ed6d"
url: "https://pub.flutter-io.cn"
source: hosted
version: "14.2.1"
version: "14.2.5"
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,13 @@ 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
table_calendar: ^3.1.2
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