mirror of
https://github.com/simon-ding/polaris.git
synced 2026-02-24 04:30:47 +08:00
Compare commits
141 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ca414a73ff | ||
|
|
32b595e116 | ||
|
|
b12bbd2ad9 | ||
|
|
60110f4ca6 | ||
|
|
b7ca02429c | ||
|
|
ff63084014 | ||
|
|
821d6859ff | ||
|
|
10e6e99990 | ||
|
|
23a5997814 | ||
|
|
b487c81865 | ||
|
|
32914344d1 | ||
|
|
644c9ed228 | ||
|
|
d3ad80380f | ||
|
|
19c6308a81 | ||
|
|
7017f32fe3 | ||
|
|
02a23f13f9 | ||
|
|
cc211a89a4 | ||
|
|
4800e6c79d | ||
|
|
b5f0b28c61 | ||
|
|
081338df24 | ||
|
|
9632ca45b3 | ||
|
|
b948bff497 | ||
|
|
29383cf75c | ||
|
|
57ec0b9eb9 | ||
|
|
0cce4ffee0 | ||
|
|
5c01c45068 | ||
|
|
712bf84c90 | ||
|
|
fdb63a8459 | ||
|
|
990d9dab08 | ||
|
|
da863588e4 | ||
|
|
09ff67fef7 | ||
|
|
3c37948798 | ||
|
|
6fd39d818c | ||
|
|
a0e211c328 | ||
|
|
27d8b1672a | ||
|
|
349e394e8e | ||
|
|
620f085ca5 | ||
|
|
5b70badb50 | ||
|
|
5c6ac2c430 | ||
|
|
365cfddf8f | ||
|
|
6c26812b92 | ||
|
|
0057a75a95 | ||
|
|
f110f257d4 | ||
|
|
93e8e78591 | ||
|
|
9ff12cd86b | ||
|
|
fd2f4b140f | ||
|
|
4607af6982 | ||
|
|
984bebcfe0 | ||
|
|
d31abd59ad | ||
|
|
e0ad71291c | ||
|
|
8ecc9393cf | ||
|
|
b62e0e9bfd | ||
|
|
1391f55f44 | ||
|
|
0c709ee517 | ||
|
|
806d821388 | ||
|
|
829043bf28 | ||
|
|
66ab418054 | ||
|
|
5fe40cc64b | ||
|
|
8f6f26f00e | ||
|
|
ee0bee2b06 | ||
|
|
1bb16a8a66 | ||
|
|
d746032114 | ||
|
|
b34e39889c | ||
|
|
64e98647a8 | ||
|
|
f91c91e0b1 | ||
|
|
f1aaa06d05 | ||
|
|
e8a38aa6f8 | ||
|
|
7e88533ea2 | ||
|
|
05698f4047 | ||
|
|
1daad0c236 | ||
|
|
86c8163f9c | ||
|
|
78ab8cc8e6 | ||
|
|
1390277b43 | ||
|
|
1aa3dca2c6 | ||
|
|
f48b3c657e | ||
|
|
d8d570f1b2 | ||
|
|
bd385d4f85 | ||
|
|
466596345d | ||
|
|
8ab33f3d54 | ||
|
|
4d3b26135c | ||
|
|
56d5cdb2bf | ||
|
|
6f80da779b | ||
|
|
5fef156052 | ||
|
|
eab3a6ca2b | ||
|
|
ffa5c37c4c | ||
|
|
241e30152b | ||
|
|
16216fcc4f | ||
|
|
578b6a9d78 | ||
|
|
f4da80c845 | ||
|
|
5a9acd3e6e | ||
|
|
8bfa8f84b9 | ||
|
|
5b0b2ce5b0 | ||
|
|
b24c1a1501 | ||
|
|
aa320c6dcb | ||
|
|
5132714247 | ||
|
|
3aeecac4fb | ||
|
|
7f8c613a65 | ||
|
|
c787d71fbd | ||
|
|
c28e16805e | ||
|
|
fc3d3878bc | ||
|
|
e26e86a63f | ||
|
|
408ff163ef | ||
|
|
35d299b60c | ||
|
|
6e002b1198 | ||
|
|
7508a264a6 | ||
|
|
0022c9dad5 | ||
|
|
654d8b50b4 | ||
|
|
97ede5d9c9 | ||
|
|
4803567818 | ||
|
|
4e0014cb3f | ||
|
|
c256d46d5c | ||
|
|
b765f16ea6 | ||
|
|
9350e376f4 | ||
|
|
06f935871a | ||
|
|
001b850d8f | ||
|
|
1340305f2d | ||
|
|
b337e40fcc | ||
|
|
e94386e455 | ||
|
|
2b4fb99c89 | ||
|
|
faa603d5df | ||
|
|
9ba59a7d5a | ||
|
|
0ea1c040a2 | ||
|
|
eba646f5db | ||
|
|
ebcc0c32da | ||
|
|
769f217506 | ||
|
|
3525d1bb83 | ||
|
|
2c3fd89f2a | ||
|
|
19ab8c65de | ||
|
|
979218f615 | ||
|
|
d4dd2da335 | ||
|
|
000717fcd9 | ||
|
|
300f9a478b | ||
|
|
88a554b186 | ||
|
|
6ef4bedebe | ||
|
|
233970ef39 | ||
|
|
e2bba8ec71 | ||
|
|
b7aeb9c3c6 | ||
|
|
4a93d51fdc | ||
|
|
f158b74be6 | ||
|
|
2c8c715540 | ||
|
|
ba532d406a |
11
.github/workflows/go.yml
vendored
11
.github/workflows/go.yml
vendored
@@ -17,11 +17,6 @@ jobs:
|
||||
|
||||
build-and-push-image:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
attestations: write
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -51,9 +46,3 @@ jobs:
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
- name: Generate artifact attestation
|
||||
uses: actions/attest-build-provenance@v1
|
||||
with:
|
||||
subject-name: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME}}
|
||||
subject-digest: ${{ steps.push.outputs.digest }}
|
||||
push-to-registry: true
|
||||
|
||||
2
.github/workflows/release.yml
vendored
2
.github/workflows/release.yml
vendored
@@ -61,4 +61,4 @@ jobs:
|
||||
with:
|
||||
subject-name: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME}}
|
||||
subject-digest: ${{ steps.push.outputs.digest }}
|
||||
push-to-registry: true
|
||||
push-to-registry: false
|
||||
|
||||
@@ -3,7 +3,7 @@ WORKDIR /app
|
||||
COPY ./ui/pubspec.yaml ./ui/pubspec.lock ./
|
||||
RUN flutter pub get
|
||||
COPY ./ui/ ./
|
||||
RUN flutter build web --no-web-resources-cdn
|
||||
RUN flutter build web --no-web-resources-cdn --web-renderer html
|
||||
|
||||
# 打包依赖阶段使用golang作为基础镜像
|
||||
FROM golang:1.22 as builder
|
||||
|
||||
37
README.md
37
README.md
@@ -1,23 +1,52 @@
|
||||
# polaris
|
||||
# Polaris
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
|
||||
Polaris 是一个电视剧和电影的追踪软件。配置好了之后,当剧集或者电影播出后,会第一时间下载对应的资源。支持本地存储或者webdav。
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
交流群: https://t.me/+8R2nzrlSs2JhMDgx
|
||||
|
||||
## 功能
|
||||
## 快速开始
|
||||
|
||||
使用此程序参考 [【快速开始】](https://simonding.gitbook.io/polaris/quick_start)
|
||||
|
||||
## Features
|
||||
|
||||
- [x] 电视剧自动追踪下载
|
||||
- [x] 电影自动追踪下载
|
||||
- [x] webdav 存储支持,配合 [alist](https://github.com/alist-org/alist) 或阿里云等实现更多功能
|
||||
- [x] 事件通知推送,目前支持 Pushover和 Bark,还在扩充中
|
||||
- [x] 后台代理支持
|
||||
- [x] 用户认证
|
||||
- [x] plex 刮削支持
|
||||
- [x] NFO 刮削文件支持
|
||||
- [x] BT/PT 支持
|
||||
- [x] and more...
|
||||
|
||||
## 使用
|
||||
## Todos
|
||||
|
||||
使用此程序参考 [【快速开始】](./doc/quick_start.md)
|
||||
- [ ] qbittorrent客户端支持
|
||||
- [ ] 更多通知客户端支持
|
||||
- [ ] 第三方watchlist导入支持
|
||||
- [ ] 手机客户端
|
||||
|
||||
|
||||
## 原理
|
||||
|
||||
本程序不提供任何视频相关资源,所有的资源都通过 jackett/prowlarr 所对接的BT/PT站点提供。
|
||||
|
||||
1. 此程序通过调用 jackett/prowlarr API搜索相关资源,然后匹配上对应的剧集
|
||||
2. 把搜索到的资源送到下载器下载
|
||||
3. 下载完成后归入对应的路径
|
||||
|
||||
## 对比 sonarr/radarr
|
||||
* 更好的中文支持
|
||||
* 对于动漫、日剧的良好支持,配合国内站点基本能匹配上对应资源
|
||||
|
||||
@@ -4,10 +4,14 @@ import (
|
||||
"polaris/db"
|
||||
"polaris/log"
|
||||
"polaris/server"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log.Infof("------------------- Starting Polaris ---------------------")
|
||||
|
||||
syscall.Umask(0) //max permission 0777
|
||||
|
||||
dbClient, err := db.Open()
|
||||
if err != nil {
|
||||
log.Panicf("init db error: %v", err)
|
||||
|
||||
42
db/const.go
42
db/const.go
@@ -3,26 +3,30 @@ package db
|
||||
var Version = "undefined"
|
||||
|
||||
const (
|
||||
SettingTmdbApiKey = "tmdb_api_key"
|
||||
SettingLanguage = "language"
|
||||
SettingJacketUrl = "jacket_url"
|
||||
SettingJacketApiKey = "jacket_api_key"
|
||||
SettingDownloadDir = "download_dir"
|
||||
SettingLogLevel = "log_level"
|
||||
SettingProxy = "proxy"
|
||||
SettingTmdbApiKey = "tmdb_api_key"
|
||||
SettingLanguage = "language"
|
||||
SettingJacketUrl = "jacket_url"
|
||||
SettingJacketApiKey = "jacket_api_key"
|
||||
SettingDownloadDir = "download_dir"
|
||||
SettingLogLevel = "log_level"
|
||||
SettingProxy = "proxy"
|
||||
SettingPlexMatchEnabled = "plexmatch_enabled"
|
||||
SettingNfoSupportEnabled = "nfo_support_enabled"
|
||||
SettingAllowQiangban = "filter_qiangban"
|
||||
SettingEnableTmdbAdultContent = "tmdb_adult_content"
|
||||
)
|
||||
|
||||
const (
|
||||
SettingAuthEnabled = "auth_enbled"
|
||||
SettingUsername = "auth_username"
|
||||
SettingPassword = "auth_password"
|
||||
SettingUsername = "auth_username"
|
||||
SettingPassword = "auth_password"
|
||||
)
|
||||
|
||||
const (
|
||||
IndexerTorznabImpl = "torznab"
|
||||
DataPath = "./data"
|
||||
ImgPath = DataPath + "/img"
|
||||
LogPath = DataPath + "/logs"
|
||||
DataPath = "./data"
|
||||
ImgPath = DataPath + "/img"
|
||||
LogPath = DataPath + "/logs"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -32,16 +36,4 @@ const (
|
||||
|
||||
type ResolutionType string
|
||||
|
||||
const (
|
||||
Any ResolutionType = "any"
|
||||
R720p ResolutionType = "720p"
|
||||
R1080p ResolutionType = "1080p"
|
||||
R4k ResolutionType = "4k"
|
||||
)
|
||||
|
||||
func (r ResolutionType) String() string {
|
||||
return string(r)
|
||||
}
|
||||
|
||||
|
||||
const JwtSerectKey = "jwt_secrect_key"
|
||||
const JwtSerectKey = "jwt_secrect_key"
|
||||
|
||||
134
db/db.go
134
db/db.go
@@ -11,6 +11,7 @@ import (
|
||||
"polaris/ent/history"
|
||||
"polaris/ent/indexers"
|
||||
"polaris/ent/media"
|
||||
"polaris/ent/schema"
|
||||
"polaris/ent/settings"
|
||||
"polaris/ent/storage"
|
||||
"polaris/log"
|
||||
@@ -87,18 +88,16 @@ func (c *Client) generateDefaultLocalStorage() error {
|
||||
return c.AddStorage(&StorageInfo{
|
||||
Name: "local",
|
||||
Implementation: "local",
|
||||
TvPath: "/data/tv/",
|
||||
MoviePath: "/data/movies/",
|
||||
Default: true,
|
||||
Settings: map[string]string{
|
||||
"tv_path": "/data/tv/",
|
||||
"movie_path": "/data/movies/",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Client) GetSetting(key string) string {
|
||||
v, err := c.ent.Settings.Query().Where(settings.Key(key)).Only(context.TODO())
|
||||
if err != nil {
|
||||
log.Warnf("get setting by key: %s error: %v", key, err)
|
||||
log.Debugf("get setting by key: %s error: %v", key, err)
|
||||
return ""
|
||||
}
|
||||
return v.Value
|
||||
@@ -139,6 +138,7 @@ func (c *Client) AddMediaWatchlist(m *ent.Media, episodes []int) (*ent.Media, er
|
||||
}
|
||||
r, err := c.ent.Media.Create().
|
||||
SetTmdbID(m.TmdbID).
|
||||
SetImdbID(m.ImdbID).
|
||||
SetStorageID(m.StorageID).
|
||||
SetOverview(m.Overview).
|
||||
SetNameCn(m.NameCn).
|
||||
@@ -148,6 +148,9 @@ func (c *Client) AddMediaWatchlist(m *ent.Media, episodes []int) (*ent.Media, er
|
||||
SetAirDate(m.AirDate).
|
||||
SetResolution(m.Resolution).
|
||||
SetTargetDir(m.TargetDir).
|
||||
SetDownloadHistoryEpisodes(m.DownloadHistoryEpisodes).
|
||||
SetLimiter(m.Limiter).
|
||||
SetExtras(m.Extras).
|
||||
AddEpisodeIDs(episodes...).
|
||||
Save(context.TODO())
|
||||
return r, err
|
||||
@@ -167,6 +170,9 @@ func (c *Client) GetEpisode(seriesId, seasonNum, episodeNum int) (*ent.Episode,
|
||||
return c.ent.Episode.Query().Where(episode.MediaID(seriesId), episode.SeasonNumber(seasonNum),
|
||||
episode.EpisodeNumber(episodeNum)).First(context.TODO())
|
||||
}
|
||||
func (c *Client) GetEpisodeByID(epID int) (*ent.Episode, error) {
|
||||
return c.ent.Episode.Query().Where(episode.ID(epID)).First(context.TODO())
|
||||
}
|
||||
|
||||
func (c *Client) UpdateEpiode(episodeId int, name, overview string) error {
|
||||
return c.ent.Episode.Update().Where(episode.ID(episodeId)).SetTitle(name).SetOverview(overview).Exec(context.TODO())
|
||||
@@ -220,6 +226,7 @@ func (c *Client) SaveEposideDetail(d *ent.Episode) (int, error) {
|
||||
SetSeasonNumber(d.SeasonNumber).
|
||||
SetEpisodeNumber(d.EpisodeNumber).
|
||||
SetOverview(d.Overview).
|
||||
SetMonitored(d.Monitored).
|
||||
SetTitle(d.Title).Save(context.TODO())
|
||||
if err != nil {
|
||||
return 0, errors.Wrap(err, "save episode")
|
||||
@@ -245,19 +252,22 @@ type TorznabSetting struct {
|
||||
ApiKey string `json:"api_key"`
|
||||
}
|
||||
|
||||
func (c *Client) SaveTorznabInfo(name string, setting TorznabSetting) error {
|
||||
data, err := json.Marshal(setting)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "marshal json")
|
||||
func (c *Client) SaveIndexer(in *ent.Indexers) error {
|
||||
|
||||
if in.ID != 0 {
|
||||
//update setting
|
||||
return c.ent.Indexers.Update().Where(indexers.ID(in.ID)).SetName(in.Name).SetImplementation(in.Implementation).
|
||||
SetPriority(in.Priority).SetSettings(in.Settings).SetSeedRatio(in.SeedRatio).SetDisabled(in.Disabled).Exec(context.Background())
|
||||
}
|
||||
count := c.ent.Indexers.Query().Where(indexers.Name(name)).CountX(context.TODO())
|
||||
//create new one
|
||||
count := c.ent.Indexers.Query().Where(indexers.Name(in.Name)).CountX(context.TODO())
|
||||
if count > 0 {
|
||||
c.ent.Indexers.Update().Where(indexers.Name(name)).SetSettings(string(data)).Save(context.TODO())
|
||||
return err
|
||||
return fmt.Errorf("name already esxits: %v", in.Name)
|
||||
}
|
||||
|
||||
_, err = c.ent.Indexers.Create().
|
||||
SetName(name).SetImplementation(IndexerTorznabImpl).SetPriority(1).SetSettings(string(data)).Save(context.TODO())
|
||||
_, 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())
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "save db")
|
||||
}
|
||||
@@ -269,9 +279,22 @@ func (c *Client) DeleteTorznab(id int) {
|
||||
c.ent.Indexers.Delete().Where(indexers.ID(id)).Exec(context.TODO())
|
||||
}
|
||||
|
||||
func (c *Client) GetIndexer(id int) (*TorznabInfo, error) {
|
||||
res, err := c.ent.Indexers.Query().Where(indexers.ID(id)).First(context.TODO())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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 {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
*ent.Indexers
|
||||
TorznabSetting
|
||||
}
|
||||
|
||||
@@ -287,8 +310,7 @@ func (c *Client) GetAllTorznabInfo() []*TorznabInfo {
|
||||
continue
|
||||
}
|
||||
l = append(l, &TorznabInfo{
|
||||
ID: r.ID,
|
||||
Name: r.Name,
|
||||
Indexers: r,
|
||||
TorznabSetting: ss,
|
||||
})
|
||||
}
|
||||
@@ -335,6 +357,8 @@ type StorageInfo struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Implementation string `json:"implementation" binding:"required"`
|
||||
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"`
|
||||
}
|
||||
|
||||
@@ -344,34 +368,28 @@ func (s *StorageInfo) ToWebDavSetting() WebdavSetting {
|
||||
}
|
||||
return WebdavSetting{
|
||||
URL: s.Settings["url"],
|
||||
TvPath: s.Settings["tv_path"],
|
||||
MoviePath: s.Settings["movie_path"],
|
||||
User: s.Settings["user"],
|
||||
Password: s.Settings["password"],
|
||||
ChangeFileHash: s.Settings["change_file_hash"],
|
||||
}
|
||||
}
|
||||
|
||||
type LocalDirSetting struct {
|
||||
TvPath string `json:"tv_path"`
|
||||
MoviePath string `json:"movie_path"`
|
||||
}
|
||||
|
||||
type WebdavSetting struct {
|
||||
URL string `json:"url"`
|
||||
TvPath string `json:"tv_path"`
|
||||
MoviePath string `json:"movie_path"`
|
||||
User string `json:"user"`
|
||||
Password string `json:"password"`
|
||||
ChangeFileHash string `json:"change_file_hash"`
|
||||
}
|
||||
|
||||
func (c *Client) AddStorage(st *StorageInfo) error {
|
||||
if !strings.HasSuffix(st.Settings["tv_path"], "/") {
|
||||
st.Settings["tv_path"] += "/"
|
||||
if !strings.HasSuffix(st.TvPath, "/") {
|
||||
st.TvPath += "/"
|
||||
}
|
||||
if !strings.HasSuffix(st.Settings["movie_path"], "/") {
|
||||
st.Settings["movie_path"] += "/"
|
||||
if !strings.HasSuffix(st.MoviePath, "/") {
|
||||
st.MoviePath += "/"
|
||||
}
|
||||
if st.Settings == nil {
|
||||
st.Settings = map[string]string{}
|
||||
}
|
||||
|
||||
data, err := json.Marshal(st.Settings)
|
||||
@@ -383,7 +401,7 @@ func (c *Client) AddStorage(st *StorageInfo) error {
|
||||
if count > 0 {
|
||||
//storage already exist, edit exist one
|
||||
return c.ent.Storage.Update().Where(storage.Name(st.Name)).
|
||||
SetImplementation(storage.Implementation(st.Implementation)).
|
||||
SetImplementation(storage.Implementation(st.Implementation)).SetTvPath(st.TvPath).SetMoviePath(st.MoviePath).
|
||||
SetSettings(string(data)).Exec(context.TODO())
|
||||
}
|
||||
countAll := c.ent.Storage.Query().Where(storage.Deleted(false)).CountX(context.TODO())
|
||||
@@ -392,7 +410,7 @@ func (c *Client) AddStorage(st *StorageInfo) error {
|
||||
st.Default = true
|
||||
}
|
||||
_, err = c.ent.Storage.Create().SetName(st.Name).
|
||||
SetImplementation(storage.Implementation(st.Implementation)).
|
||||
SetImplementation(storage.Implementation(st.Implementation)).SetTvPath(st.TvPath).SetMoviePath(st.MoviePath).
|
||||
SetSettings(string(data)).SetDefault(st.Default).Save(context.TODO())
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -413,15 +431,6 @@ type Storage struct {
|
||||
ent.Storage
|
||||
}
|
||||
|
||||
func (s *Storage) ToLocalSetting() LocalDirSetting {
|
||||
if s.Implementation != storage.ImplementationLocal {
|
||||
panic("not local storage")
|
||||
}
|
||||
var localSetting LocalDirSetting
|
||||
json.Unmarshal([]byte(s.Settings), &localSetting)
|
||||
return localSetting
|
||||
}
|
||||
|
||||
func (s *Storage) ToWebDavSetting() WebdavSetting {
|
||||
if s.Implementation != storage.ImplementationWebdav {
|
||||
panic("not webdav storage")
|
||||
@@ -431,12 +440,6 @@ func (s *Storage) ToWebDavSetting() WebdavSetting {
|
||||
return webdavSetting
|
||||
}
|
||||
|
||||
func (s *Storage) GetPath() (tvPath string, moviePath string) {
|
||||
var m map[string]string
|
||||
json.Unmarshal([]byte(s.Settings), &m)
|
||||
return m["tv_path"], m["movie_path"]
|
||||
}
|
||||
|
||||
func (c *Client) GetStorage(id int) *Storage {
|
||||
r, err := c.ent.Storage.Query().Where(storage.ID(id)).First(context.TODO())
|
||||
if err != nil {
|
||||
@@ -471,7 +474,8 @@ func (c *Client) SetDefaultStorageByName(name string) error {
|
||||
|
||||
func (c *Client) SaveHistoryRecord(h ent.History) (*ent.History, error) {
|
||||
return c.ent.History.Create().SetMediaID(h.MediaID).SetEpisodeID(h.EpisodeID).SetDate(time.Now()).
|
||||
SetStatus(h.Status).SetTargetDir(h.TargetDir).SetSourceTitle(h.SourceTitle).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 {
|
||||
@@ -488,7 +492,7 @@ func (c *Client) GetHistories() ent.Histories {
|
||||
|
||||
func (c *Client) GetRunningHistories() ent.Histories {
|
||||
h, err := c.ent.History.Query().Where(history.Or(history.StatusEQ(history.StatusRunning),
|
||||
history.StatusEQ(history.StatusUploading))).All(context.TODO())
|
||||
history.StatusEQ(history.StatusUploading), history.StatusEQ(history.StatusSeeding))).All(context.TODO())
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
@@ -547,4 +551,32 @@ func (c *Client) GetMovieDummyEpisode(movieId int) (*ent.Episode, error) {
|
||||
return nil, errors.Wrap(err, "query episode")
|
||||
}
|
||||
return ep, nil
|
||||
}
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
BIN
doc/assets/anime_match.png
Normal file
BIN
doc/assets/anime_match.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 774 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 2.1 MiB After Width: | Height: | Size: 2.6 MiB |
@@ -31,6 +31,10 @@ type Episode struct {
|
||||
AirDate string `json:"air_date,omitempty"`
|
||||
// Status holds the value of the "status" field.
|
||||
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"`
|
||||
@@ -62,9 +66,11 @@ func (*Episode) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case episode.FieldMonitored:
|
||||
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)
|
||||
@@ -129,6 +135,18 @@ func (e *Episode) assignValues(columns []string, values []any) error {
|
||||
} else if value.Valid {
|
||||
e.Status = episode.Status(value.String)
|
||||
}
|
||||
case episode.FieldMonitored:
|
||||
if value, ok := values[i].(*sql.NullBool); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field monitored", values[i])
|
||||
} 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])
|
||||
}
|
||||
@@ -190,6 +208,12 @@ func (e *Episode) String() string {
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("status=")
|
||||
builder.WriteString(fmt.Sprintf("%v", e.Status))
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -28,6 +28,10 @@ const (
|
||||
FieldAirDate = "air_date"
|
||||
// FieldStatus holds the string denoting the status field in the database.
|
||||
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.
|
||||
@@ -51,6 +55,8 @@ var Columns = []string{
|
||||
FieldOverview,
|
||||
FieldAirDate,
|
||||
FieldStatus,
|
||||
FieldMonitored,
|
||||
FieldTargetFile,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
@@ -63,6 +69,11 @@ func ValidColumn(column string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
var (
|
||||
// DefaultMonitored holds the default value on creation for the "monitored" field.
|
||||
DefaultMonitored bool
|
||||
)
|
||||
|
||||
// Status defines the type for the "status" enum field.
|
||||
type Status string
|
||||
|
||||
@@ -133,6 +144,16 @@ func ByStatus(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldStatus, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByMonitored orders the results by the monitored field.
|
||||
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) {
|
||||
|
||||
@@ -84,6 +84,16 @@ func AirDate(v string) predicate.Episode {
|
||||
return predicate.Episode(sql.FieldEQ(FieldAirDate, v))
|
||||
}
|
||||
|
||||
// Monitored applies equality check predicate on the "monitored" field. It's identical to MonitoredEQ.
|
||||
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))
|
||||
@@ -409,6 +419,91 @@ func StatusNotIn(vs ...Status) predicate.Episode {
|
||||
return predicate.Episode(sql.FieldNotIn(FieldStatus, vs...))
|
||||
}
|
||||
|
||||
// MonitoredEQ applies the EQ predicate on the "monitored" field.
|
||||
func MonitoredEQ(v bool) predicate.Episode {
|
||||
return predicate.Episode(sql.FieldEQ(FieldMonitored, v))
|
||||
}
|
||||
|
||||
// MonitoredNEQ applies the NEQ predicate on the "monitored" field.
|
||||
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) {
|
||||
|
||||
@@ -78,6 +78,34 @@ func (ec *EpisodeCreate) SetNillableStatus(e *episode.Status) *EpisodeCreate {
|
||||
return ec
|
||||
}
|
||||
|
||||
// SetMonitored sets the "monitored" field.
|
||||
func (ec *EpisodeCreate) SetMonitored(b bool) *EpisodeCreate {
|
||||
ec.mutation.SetMonitored(b)
|
||||
return ec
|
||||
}
|
||||
|
||||
// SetNillableMonitored sets the "monitored" field if the given value is not nil.
|
||||
func (ec *EpisodeCreate) SetNillableMonitored(b *bool) *EpisodeCreate {
|
||||
if b != nil {
|
||||
ec.SetMonitored(*b)
|
||||
}
|
||||
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)
|
||||
@@ -122,6 +150,10 @@ func (ec *EpisodeCreate) defaults() {
|
||||
v := episode.DefaultStatus
|
||||
ec.mutation.SetStatus(v)
|
||||
}
|
||||
if _, ok := ec.mutation.Monitored(); !ok {
|
||||
v := episode.DefaultMonitored
|
||||
ec.mutation.SetMonitored(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
@@ -149,6 +181,9 @@ func (ec *EpisodeCreate) check() error {
|
||||
return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Episode.status": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := ec.mutation.Monitored(); !ok {
|
||||
return &ValidationError{Name: "monitored", err: errors.New(`ent: missing required field "Episode.monitored"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -199,6 +234,14 @@ func (ec *EpisodeCreate) createSpec() (*Episode, *sqlgraph.CreateSpec) {
|
||||
_spec.SetField(episode.FieldStatus, field.TypeEnum, value)
|
||||
_node.Status = value
|
||||
}
|
||||
if value, ok := ec.mutation.Monitored(); ok {
|
||||
_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,
|
||||
|
||||
@@ -146,6 +146,40 @@ func (eu *EpisodeUpdate) SetNillableStatus(e *episode.Status) *EpisodeUpdate {
|
||||
return eu
|
||||
}
|
||||
|
||||
// SetMonitored sets the "monitored" field.
|
||||
func (eu *EpisodeUpdate) SetMonitored(b bool) *EpisodeUpdate {
|
||||
eu.mutation.SetMonitored(b)
|
||||
return eu
|
||||
}
|
||||
|
||||
// SetNillableMonitored sets the "monitored" field if the given value is not nil.
|
||||
func (eu *EpisodeUpdate) SetNillableMonitored(b *bool) *EpisodeUpdate {
|
||||
if b != nil {
|
||||
eu.SetMonitored(*b)
|
||||
}
|
||||
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)
|
||||
@@ -235,6 +269,15 @@ func (eu *EpisodeUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
if value, ok := eu.mutation.Status(); ok {
|
||||
_spec.SetField(episode.FieldStatus, field.TypeEnum, value)
|
||||
}
|
||||
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,
|
||||
@@ -402,6 +445,40 @@ func (euo *EpisodeUpdateOne) SetNillableStatus(e *episode.Status) *EpisodeUpdate
|
||||
return euo
|
||||
}
|
||||
|
||||
// SetMonitored sets the "monitored" field.
|
||||
func (euo *EpisodeUpdateOne) SetMonitored(b bool) *EpisodeUpdateOne {
|
||||
euo.mutation.SetMonitored(b)
|
||||
return euo
|
||||
}
|
||||
|
||||
// SetNillableMonitored sets the "monitored" field if the given value is not nil.
|
||||
func (euo *EpisodeUpdateOne) SetNillableMonitored(b *bool) *EpisodeUpdateOne {
|
||||
if b != nil {
|
||||
euo.SetMonitored(*b)
|
||||
}
|
||||
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)
|
||||
@@ -521,6 +598,15 @@ func (euo *EpisodeUpdateOne) sqlSave(ctx context.Context) (_node *Episode, err e
|
||||
if value, ok := euo.mutation.Status(); ok {
|
||||
_spec.SetField(episode.FieldStatus, field.TypeEnum, value)
|
||||
}
|
||||
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,
|
||||
|
||||
@@ -29,6 +29,10 @@ type History struct {
|
||||
TargetDir string `json:"target_dir,omitempty"`
|
||||
// Size holds the value of the "size" field.
|
||||
Size int `json:"size,omitempty"`
|
||||
// DownloadClientID holds the value of the "download_client_id" field.
|
||||
DownloadClientID int `json:"download_client_id,omitempty"`
|
||||
// IndexerID holds the value of the "indexer_id" field.
|
||||
IndexerID int `json:"indexer_id,omitempty"`
|
||||
// Status holds the value of the "status" field.
|
||||
Status history.Status `json:"status,omitempty"`
|
||||
// Saved holds the value of the "saved" field.
|
||||
@@ -41,7 +45,7 @@ func (*History) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case history.FieldID, history.FieldMediaID, history.FieldEpisodeID, history.FieldSize:
|
||||
case history.FieldID, history.FieldMediaID, history.FieldEpisodeID, history.FieldSize, history.FieldDownloadClientID, history.FieldIndexerID:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case history.FieldSourceTitle, history.FieldTargetDir, history.FieldStatus, history.FieldSaved:
|
||||
values[i] = new(sql.NullString)
|
||||
@@ -104,6 +108,18 @@ func (h *History) assignValues(columns []string, values []any) error {
|
||||
} else if value.Valid {
|
||||
h.Size = int(value.Int64)
|
||||
}
|
||||
case history.FieldDownloadClientID:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field download_client_id", values[i])
|
||||
} else if value.Valid {
|
||||
h.DownloadClientID = int(value.Int64)
|
||||
}
|
||||
case history.FieldIndexerID:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field indexer_id", values[i])
|
||||
} else if value.Valid {
|
||||
h.IndexerID = int(value.Int64)
|
||||
}
|
||||
case history.FieldStatus:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field status", values[i])
|
||||
@@ -170,6 +186,12 @@ func (h *History) String() string {
|
||||
builder.WriteString("size=")
|
||||
builder.WriteString(fmt.Sprintf("%v", h.Size))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("download_client_id=")
|
||||
builder.WriteString(fmt.Sprintf("%v", h.DownloadClientID))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("indexer_id=")
|
||||
builder.WriteString(fmt.Sprintf("%v", h.IndexerID))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("status=")
|
||||
builder.WriteString(fmt.Sprintf("%v", h.Status))
|
||||
builder.WriteString(", ")
|
||||
|
||||
@@ -25,6 +25,10 @@ const (
|
||||
FieldTargetDir = "target_dir"
|
||||
// FieldSize holds the string denoting the size field in the database.
|
||||
FieldSize = "size"
|
||||
// FieldDownloadClientID holds the string denoting the download_client_id field in the database.
|
||||
FieldDownloadClientID = "download_client_id"
|
||||
// FieldIndexerID holds the string denoting the indexer_id field in the database.
|
||||
FieldIndexerID = "indexer_id"
|
||||
// FieldStatus holds the string denoting the status field in the database.
|
||||
FieldStatus = "status"
|
||||
// FieldSaved holds the string denoting the saved field in the database.
|
||||
@@ -42,6 +46,8 @@ var Columns = []string{
|
||||
FieldDate,
|
||||
FieldTargetDir,
|
||||
FieldSize,
|
||||
FieldDownloadClientID,
|
||||
FieldIndexerID,
|
||||
FieldStatus,
|
||||
FieldSaved,
|
||||
}
|
||||
@@ -70,6 +76,7 @@ const (
|
||||
StatusSuccess Status = "success"
|
||||
StatusFail Status = "fail"
|
||||
StatusUploading Status = "uploading"
|
||||
StatusSeeding Status = "seeding"
|
||||
)
|
||||
|
||||
func (s Status) String() string {
|
||||
@@ -79,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)
|
||||
@@ -124,6 +131,16 @@ func BySize(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldSize, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByDownloadClientID orders the results by the download_client_id field.
|
||||
func ByDownloadClientID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldDownloadClientID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByIndexerID orders the results by the indexer_id field.
|
||||
func ByIndexerID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldIndexerID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByStatus orders the results by the status field.
|
||||
func ByStatus(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldStatus, opts...).ToFunc()
|
||||
|
||||
@@ -84,6 +84,16 @@ func Size(v int) predicate.History {
|
||||
return predicate.History(sql.FieldEQ(FieldSize, v))
|
||||
}
|
||||
|
||||
// DownloadClientID applies equality check predicate on the "download_client_id" field. It's identical to DownloadClientIDEQ.
|
||||
func DownloadClientID(v int) predicate.History {
|
||||
return predicate.History(sql.FieldEQ(FieldDownloadClientID, v))
|
||||
}
|
||||
|
||||
// IndexerID applies equality check predicate on the "indexer_id" field. It's identical to IndexerIDEQ.
|
||||
func IndexerID(v int) predicate.History {
|
||||
return predicate.History(sql.FieldEQ(FieldIndexerID, v))
|
||||
}
|
||||
|
||||
// Saved applies equality check predicate on the "saved" field. It's identical to SavedEQ.
|
||||
func Saved(v string) predicate.History {
|
||||
return predicate.History(sql.FieldEQ(FieldSaved, v))
|
||||
@@ -389,6 +399,106 @@ func SizeLTE(v int) predicate.History {
|
||||
return predicate.History(sql.FieldLTE(FieldSize, v))
|
||||
}
|
||||
|
||||
// DownloadClientIDEQ applies the EQ predicate on the "download_client_id" field.
|
||||
func DownloadClientIDEQ(v int) predicate.History {
|
||||
return predicate.History(sql.FieldEQ(FieldDownloadClientID, v))
|
||||
}
|
||||
|
||||
// DownloadClientIDNEQ applies the NEQ predicate on the "download_client_id" field.
|
||||
func DownloadClientIDNEQ(v int) predicate.History {
|
||||
return predicate.History(sql.FieldNEQ(FieldDownloadClientID, v))
|
||||
}
|
||||
|
||||
// DownloadClientIDIn applies the In predicate on the "download_client_id" field.
|
||||
func DownloadClientIDIn(vs ...int) predicate.History {
|
||||
return predicate.History(sql.FieldIn(FieldDownloadClientID, vs...))
|
||||
}
|
||||
|
||||
// DownloadClientIDNotIn applies the NotIn predicate on the "download_client_id" field.
|
||||
func DownloadClientIDNotIn(vs ...int) predicate.History {
|
||||
return predicate.History(sql.FieldNotIn(FieldDownloadClientID, vs...))
|
||||
}
|
||||
|
||||
// DownloadClientIDGT applies the GT predicate on the "download_client_id" field.
|
||||
func DownloadClientIDGT(v int) predicate.History {
|
||||
return predicate.History(sql.FieldGT(FieldDownloadClientID, v))
|
||||
}
|
||||
|
||||
// DownloadClientIDGTE applies the GTE predicate on the "download_client_id" field.
|
||||
func DownloadClientIDGTE(v int) predicate.History {
|
||||
return predicate.History(sql.FieldGTE(FieldDownloadClientID, v))
|
||||
}
|
||||
|
||||
// DownloadClientIDLT applies the LT predicate on the "download_client_id" field.
|
||||
func DownloadClientIDLT(v int) predicate.History {
|
||||
return predicate.History(sql.FieldLT(FieldDownloadClientID, v))
|
||||
}
|
||||
|
||||
// DownloadClientIDLTE applies the LTE predicate on the "download_client_id" field.
|
||||
func DownloadClientIDLTE(v int) predicate.History {
|
||||
return predicate.History(sql.FieldLTE(FieldDownloadClientID, v))
|
||||
}
|
||||
|
||||
// DownloadClientIDIsNil applies the IsNil predicate on the "download_client_id" field.
|
||||
func DownloadClientIDIsNil() predicate.History {
|
||||
return predicate.History(sql.FieldIsNull(FieldDownloadClientID))
|
||||
}
|
||||
|
||||
// DownloadClientIDNotNil applies the NotNil predicate on the "download_client_id" field.
|
||||
func DownloadClientIDNotNil() predicate.History {
|
||||
return predicate.History(sql.FieldNotNull(FieldDownloadClientID))
|
||||
}
|
||||
|
||||
// IndexerIDEQ applies the EQ predicate on the "indexer_id" field.
|
||||
func IndexerIDEQ(v int) predicate.History {
|
||||
return predicate.History(sql.FieldEQ(FieldIndexerID, v))
|
||||
}
|
||||
|
||||
// IndexerIDNEQ applies the NEQ predicate on the "indexer_id" field.
|
||||
func IndexerIDNEQ(v int) predicate.History {
|
||||
return predicate.History(sql.FieldNEQ(FieldIndexerID, v))
|
||||
}
|
||||
|
||||
// IndexerIDIn applies the In predicate on the "indexer_id" field.
|
||||
func IndexerIDIn(vs ...int) predicate.History {
|
||||
return predicate.History(sql.FieldIn(FieldIndexerID, vs...))
|
||||
}
|
||||
|
||||
// IndexerIDNotIn applies the NotIn predicate on the "indexer_id" field.
|
||||
func IndexerIDNotIn(vs ...int) predicate.History {
|
||||
return predicate.History(sql.FieldNotIn(FieldIndexerID, vs...))
|
||||
}
|
||||
|
||||
// IndexerIDGT applies the GT predicate on the "indexer_id" field.
|
||||
func IndexerIDGT(v int) predicate.History {
|
||||
return predicate.History(sql.FieldGT(FieldIndexerID, v))
|
||||
}
|
||||
|
||||
// IndexerIDGTE applies the GTE predicate on the "indexer_id" field.
|
||||
func IndexerIDGTE(v int) predicate.History {
|
||||
return predicate.History(sql.FieldGTE(FieldIndexerID, v))
|
||||
}
|
||||
|
||||
// IndexerIDLT applies the LT predicate on the "indexer_id" field.
|
||||
func IndexerIDLT(v int) predicate.History {
|
||||
return predicate.History(sql.FieldLT(FieldIndexerID, v))
|
||||
}
|
||||
|
||||
// IndexerIDLTE applies the LTE predicate on the "indexer_id" field.
|
||||
func IndexerIDLTE(v int) predicate.History {
|
||||
return predicate.History(sql.FieldLTE(FieldIndexerID, v))
|
||||
}
|
||||
|
||||
// IndexerIDIsNil applies the IsNil predicate on the "indexer_id" field.
|
||||
func IndexerIDIsNil() predicate.History {
|
||||
return predicate.History(sql.FieldIsNull(FieldIndexerID))
|
||||
}
|
||||
|
||||
// IndexerIDNotNil applies the NotNil predicate on the "indexer_id" field.
|
||||
func IndexerIDNotNil() predicate.History {
|
||||
return predicate.History(sql.FieldNotNull(FieldIndexerID))
|
||||
}
|
||||
|
||||
// StatusEQ applies the EQ predicate on the "status" field.
|
||||
func StatusEQ(v Status) predicate.History {
|
||||
return predicate.History(sql.FieldEQ(FieldStatus, v))
|
||||
|
||||
@@ -72,6 +72,34 @@ func (hc *HistoryCreate) SetNillableSize(i *int) *HistoryCreate {
|
||||
return hc
|
||||
}
|
||||
|
||||
// SetDownloadClientID sets the "download_client_id" field.
|
||||
func (hc *HistoryCreate) SetDownloadClientID(i int) *HistoryCreate {
|
||||
hc.mutation.SetDownloadClientID(i)
|
||||
return hc
|
||||
}
|
||||
|
||||
// SetNillableDownloadClientID sets the "download_client_id" field if the given value is not nil.
|
||||
func (hc *HistoryCreate) SetNillableDownloadClientID(i *int) *HistoryCreate {
|
||||
if i != nil {
|
||||
hc.SetDownloadClientID(*i)
|
||||
}
|
||||
return hc
|
||||
}
|
||||
|
||||
// SetIndexerID sets the "indexer_id" field.
|
||||
func (hc *HistoryCreate) SetIndexerID(i int) *HistoryCreate {
|
||||
hc.mutation.SetIndexerID(i)
|
||||
return hc
|
||||
}
|
||||
|
||||
// SetNillableIndexerID sets the "indexer_id" field if the given value is not nil.
|
||||
func (hc *HistoryCreate) SetNillableIndexerID(i *int) *HistoryCreate {
|
||||
if i != nil {
|
||||
hc.SetIndexerID(*i)
|
||||
}
|
||||
return hc
|
||||
}
|
||||
|
||||
// SetStatus sets the "status" field.
|
||||
func (hc *HistoryCreate) SetStatus(h history.Status) *HistoryCreate {
|
||||
hc.mutation.SetStatus(h)
|
||||
@@ -208,6 +236,14 @@ func (hc *HistoryCreate) createSpec() (*History, *sqlgraph.CreateSpec) {
|
||||
_spec.SetField(history.FieldSize, field.TypeInt, value)
|
||||
_node.Size = value
|
||||
}
|
||||
if value, ok := hc.mutation.DownloadClientID(); ok {
|
||||
_spec.SetField(history.FieldDownloadClientID, field.TypeInt, value)
|
||||
_node.DownloadClientID = value
|
||||
}
|
||||
if value, ok := hc.mutation.IndexerID(); ok {
|
||||
_spec.SetField(history.FieldIndexerID, field.TypeInt, value)
|
||||
_node.IndexerID = value
|
||||
}
|
||||
if value, ok := hc.mutation.Status(); ok {
|
||||
_spec.SetField(history.FieldStatus, field.TypeEnum, value)
|
||||
_node.Status = value
|
||||
|
||||
@@ -139,6 +139,60 @@ func (hu *HistoryUpdate) AddSize(i int) *HistoryUpdate {
|
||||
return hu
|
||||
}
|
||||
|
||||
// SetDownloadClientID sets the "download_client_id" field.
|
||||
func (hu *HistoryUpdate) SetDownloadClientID(i int) *HistoryUpdate {
|
||||
hu.mutation.ResetDownloadClientID()
|
||||
hu.mutation.SetDownloadClientID(i)
|
||||
return hu
|
||||
}
|
||||
|
||||
// SetNillableDownloadClientID sets the "download_client_id" field if the given value is not nil.
|
||||
func (hu *HistoryUpdate) SetNillableDownloadClientID(i *int) *HistoryUpdate {
|
||||
if i != nil {
|
||||
hu.SetDownloadClientID(*i)
|
||||
}
|
||||
return hu
|
||||
}
|
||||
|
||||
// AddDownloadClientID adds i to the "download_client_id" field.
|
||||
func (hu *HistoryUpdate) AddDownloadClientID(i int) *HistoryUpdate {
|
||||
hu.mutation.AddDownloadClientID(i)
|
||||
return hu
|
||||
}
|
||||
|
||||
// ClearDownloadClientID clears the value of the "download_client_id" field.
|
||||
func (hu *HistoryUpdate) ClearDownloadClientID() *HistoryUpdate {
|
||||
hu.mutation.ClearDownloadClientID()
|
||||
return hu
|
||||
}
|
||||
|
||||
// SetIndexerID sets the "indexer_id" field.
|
||||
func (hu *HistoryUpdate) SetIndexerID(i int) *HistoryUpdate {
|
||||
hu.mutation.ResetIndexerID()
|
||||
hu.mutation.SetIndexerID(i)
|
||||
return hu
|
||||
}
|
||||
|
||||
// SetNillableIndexerID sets the "indexer_id" field if the given value is not nil.
|
||||
func (hu *HistoryUpdate) SetNillableIndexerID(i *int) *HistoryUpdate {
|
||||
if i != nil {
|
||||
hu.SetIndexerID(*i)
|
||||
}
|
||||
return hu
|
||||
}
|
||||
|
||||
// AddIndexerID adds i to the "indexer_id" field.
|
||||
func (hu *HistoryUpdate) AddIndexerID(i int) *HistoryUpdate {
|
||||
hu.mutation.AddIndexerID(i)
|
||||
return hu
|
||||
}
|
||||
|
||||
// ClearIndexerID clears the value of the "indexer_id" field.
|
||||
func (hu *HistoryUpdate) ClearIndexerID() *HistoryUpdate {
|
||||
hu.mutation.ClearIndexerID()
|
||||
return hu
|
||||
}
|
||||
|
||||
// SetStatus sets the "status" field.
|
||||
func (hu *HistoryUpdate) SetStatus(h history.Status) *HistoryUpdate {
|
||||
hu.mutation.SetStatus(h)
|
||||
@@ -257,6 +311,24 @@ func (hu *HistoryUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
if value, ok := hu.mutation.AddedSize(); ok {
|
||||
_spec.AddField(history.FieldSize, field.TypeInt, value)
|
||||
}
|
||||
if value, ok := hu.mutation.DownloadClientID(); ok {
|
||||
_spec.SetField(history.FieldDownloadClientID, field.TypeInt, value)
|
||||
}
|
||||
if value, ok := hu.mutation.AddedDownloadClientID(); ok {
|
||||
_spec.AddField(history.FieldDownloadClientID, field.TypeInt, value)
|
||||
}
|
||||
if hu.mutation.DownloadClientIDCleared() {
|
||||
_spec.ClearField(history.FieldDownloadClientID, field.TypeInt)
|
||||
}
|
||||
if value, ok := hu.mutation.IndexerID(); ok {
|
||||
_spec.SetField(history.FieldIndexerID, field.TypeInt, value)
|
||||
}
|
||||
if value, ok := hu.mutation.AddedIndexerID(); ok {
|
||||
_spec.AddField(history.FieldIndexerID, field.TypeInt, value)
|
||||
}
|
||||
if hu.mutation.IndexerIDCleared() {
|
||||
_spec.ClearField(history.FieldIndexerID, field.TypeInt)
|
||||
}
|
||||
if value, ok := hu.mutation.Status(); ok {
|
||||
_spec.SetField(history.FieldStatus, field.TypeEnum, value)
|
||||
}
|
||||
@@ -397,6 +469,60 @@ func (huo *HistoryUpdateOne) AddSize(i int) *HistoryUpdateOne {
|
||||
return huo
|
||||
}
|
||||
|
||||
// SetDownloadClientID sets the "download_client_id" field.
|
||||
func (huo *HistoryUpdateOne) SetDownloadClientID(i int) *HistoryUpdateOne {
|
||||
huo.mutation.ResetDownloadClientID()
|
||||
huo.mutation.SetDownloadClientID(i)
|
||||
return huo
|
||||
}
|
||||
|
||||
// SetNillableDownloadClientID sets the "download_client_id" field if the given value is not nil.
|
||||
func (huo *HistoryUpdateOne) SetNillableDownloadClientID(i *int) *HistoryUpdateOne {
|
||||
if i != nil {
|
||||
huo.SetDownloadClientID(*i)
|
||||
}
|
||||
return huo
|
||||
}
|
||||
|
||||
// AddDownloadClientID adds i to the "download_client_id" field.
|
||||
func (huo *HistoryUpdateOne) AddDownloadClientID(i int) *HistoryUpdateOne {
|
||||
huo.mutation.AddDownloadClientID(i)
|
||||
return huo
|
||||
}
|
||||
|
||||
// ClearDownloadClientID clears the value of the "download_client_id" field.
|
||||
func (huo *HistoryUpdateOne) ClearDownloadClientID() *HistoryUpdateOne {
|
||||
huo.mutation.ClearDownloadClientID()
|
||||
return huo
|
||||
}
|
||||
|
||||
// SetIndexerID sets the "indexer_id" field.
|
||||
func (huo *HistoryUpdateOne) SetIndexerID(i int) *HistoryUpdateOne {
|
||||
huo.mutation.ResetIndexerID()
|
||||
huo.mutation.SetIndexerID(i)
|
||||
return huo
|
||||
}
|
||||
|
||||
// SetNillableIndexerID sets the "indexer_id" field if the given value is not nil.
|
||||
func (huo *HistoryUpdateOne) SetNillableIndexerID(i *int) *HistoryUpdateOne {
|
||||
if i != nil {
|
||||
huo.SetIndexerID(*i)
|
||||
}
|
||||
return huo
|
||||
}
|
||||
|
||||
// AddIndexerID adds i to the "indexer_id" field.
|
||||
func (huo *HistoryUpdateOne) AddIndexerID(i int) *HistoryUpdateOne {
|
||||
huo.mutation.AddIndexerID(i)
|
||||
return huo
|
||||
}
|
||||
|
||||
// ClearIndexerID clears the value of the "indexer_id" field.
|
||||
func (huo *HistoryUpdateOne) ClearIndexerID() *HistoryUpdateOne {
|
||||
huo.mutation.ClearIndexerID()
|
||||
return huo
|
||||
}
|
||||
|
||||
// SetStatus sets the "status" field.
|
||||
func (huo *HistoryUpdateOne) SetStatus(h history.Status) *HistoryUpdateOne {
|
||||
huo.mutation.SetStatus(h)
|
||||
@@ -545,6 +671,24 @@ func (huo *HistoryUpdateOne) sqlSave(ctx context.Context) (_node *History, err e
|
||||
if value, ok := huo.mutation.AddedSize(); ok {
|
||||
_spec.AddField(history.FieldSize, field.TypeInt, value)
|
||||
}
|
||||
if value, ok := huo.mutation.DownloadClientID(); ok {
|
||||
_spec.SetField(history.FieldDownloadClientID, field.TypeInt, value)
|
||||
}
|
||||
if value, ok := huo.mutation.AddedDownloadClientID(); ok {
|
||||
_spec.AddField(history.FieldDownloadClientID, field.TypeInt, value)
|
||||
}
|
||||
if huo.mutation.DownloadClientIDCleared() {
|
||||
_spec.ClearField(history.FieldDownloadClientID, field.TypeInt)
|
||||
}
|
||||
if value, ok := huo.mutation.IndexerID(); ok {
|
||||
_spec.SetField(history.FieldIndexerID, field.TypeInt, value)
|
||||
}
|
||||
if value, ok := huo.mutation.AddedIndexerID(); ok {
|
||||
_spec.AddField(history.FieldIndexerID, field.TypeInt, value)
|
||||
}
|
||||
if huo.mutation.IndexerIDCleared() {
|
||||
_spec.ClearField(history.FieldIndexerID, field.TypeInt)
|
||||
}
|
||||
if value, ok := huo.mutation.Status(); ok {
|
||||
_spec.SetField(history.FieldStatus, field.TypeEnum, value)
|
||||
}
|
||||
|
||||
@@ -25,7 +25,11 @@ type Indexers struct {
|
||||
// EnableRss holds the value of the "enable_rss" field.
|
||||
EnableRss bool `json:"enable_rss,omitempty"`
|
||||
// Priority holds the value of the "priority" field.
|
||||
Priority int `json:"priority,omitempty"`
|
||||
Priority int `json:"priority,omitempty"`
|
||||
// minimal seed ratio requied, before removing torrent
|
||||
SeedRatio float32 `json:"seed_ratio,omitempty"`
|
||||
// Disabled holds the value of the "disabled" field.
|
||||
Disabled bool `json:"disabled,omitempty"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
@@ -34,8 +38,10 @@ func (*Indexers) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case indexers.FieldEnableRss:
|
||||
case indexers.FieldEnableRss, indexers.FieldDisabled:
|
||||
values[i] = new(sql.NullBool)
|
||||
case indexers.FieldSeedRatio:
|
||||
values[i] = new(sql.NullFloat64)
|
||||
case indexers.FieldID, indexers.FieldPriority:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case indexers.FieldName, indexers.FieldImplementation, indexers.FieldSettings:
|
||||
@@ -91,6 +97,18 @@ func (i *Indexers) assignValues(columns []string, values []any) error {
|
||||
} else if value.Valid {
|
||||
i.Priority = int(value.Int64)
|
||||
}
|
||||
case indexers.FieldSeedRatio:
|
||||
if value, ok := values[j].(*sql.NullFloat64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field seed_ratio", values[j])
|
||||
} else if value.Valid {
|
||||
i.SeedRatio = float32(value.Float64)
|
||||
}
|
||||
case indexers.FieldDisabled:
|
||||
if value, ok := values[j].(*sql.NullBool); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field disabled", values[j])
|
||||
} else if value.Valid {
|
||||
i.Disabled = value.Bool
|
||||
}
|
||||
default:
|
||||
i.selectValues.Set(columns[j], values[j])
|
||||
}
|
||||
@@ -141,6 +159,12 @@ func (i *Indexers) String() string {
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("priority=")
|
||||
builder.WriteString(fmt.Sprintf("%v", i.Priority))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("seed_ratio=")
|
||||
builder.WriteString(fmt.Sprintf("%v", i.SeedRatio))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("disabled=")
|
||||
builder.WriteString(fmt.Sprintf("%v", i.Disabled))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
@@ -21,6 +21,10 @@ const (
|
||||
FieldEnableRss = "enable_rss"
|
||||
// FieldPriority holds the string denoting the priority field in the database.
|
||||
FieldPriority = "priority"
|
||||
// FieldSeedRatio holds the string denoting the seed_ratio field in the database.
|
||||
FieldSeedRatio = "seed_ratio"
|
||||
// FieldDisabled holds the string denoting the disabled field in the database.
|
||||
FieldDisabled = "disabled"
|
||||
// Table holds the table name of the indexers in the database.
|
||||
Table = "indexers"
|
||||
)
|
||||
@@ -33,6 +37,8 @@ var Columns = []string{
|
||||
FieldSettings,
|
||||
FieldEnableRss,
|
||||
FieldPriority,
|
||||
FieldSeedRatio,
|
||||
FieldDisabled,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
@@ -48,6 +54,12 @@ func ValidColumn(column string) bool {
|
||||
var (
|
||||
// DefaultEnableRss holds the default value on creation for the "enable_rss" field.
|
||||
DefaultEnableRss bool
|
||||
// DefaultPriority holds the default value on creation for the "priority" field.
|
||||
DefaultPriority int
|
||||
// DefaultSeedRatio holds the default value on creation for the "seed_ratio" field.
|
||||
DefaultSeedRatio float32
|
||||
// DefaultDisabled holds the default value on creation for the "disabled" field.
|
||||
DefaultDisabled bool
|
||||
)
|
||||
|
||||
// OrderOption defines the ordering options for the Indexers queries.
|
||||
@@ -82,3 +94,13 @@ func ByEnableRss(opts ...sql.OrderTermOption) OrderOption {
|
||||
func ByPriority(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldPriority, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// BySeedRatio orders the results by the seed_ratio field.
|
||||
func BySeedRatio(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldSeedRatio, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByDisabled orders the results by the disabled field.
|
||||
func ByDisabled(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldDisabled, opts...).ToFunc()
|
||||
}
|
||||
|
||||
@@ -78,6 +78,16 @@ func Priority(v int) predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldEQ(FieldPriority, v))
|
||||
}
|
||||
|
||||
// SeedRatio applies equality check predicate on the "seed_ratio" field. It's identical to SeedRatioEQ.
|
||||
func SeedRatio(v float32) predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldEQ(FieldSeedRatio, v))
|
||||
}
|
||||
|
||||
// Disabled applies equality check predicate on the "disabled" field. It's identical to DisabledEQ.
|
||||
func Disabled(v bool) predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldEQ(FieldDisabled, v))
|
||||
}
|
||||
|
||||
// NameEQ applies the EQ predicate on the "name" field.
|
||||
func NameEQ(v string) predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldEQ(FieldName, v))
|
||||
@@ -323,6 +333,76 @@ func PriorityLTE(v int) predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldLTE(FieldPriority, v))
|
||||
}
|
||||
|
||||
// SeedRatioEQ applies the EQ predicate on the "seed_ratio" field.
|
||||
func SeedRatioEQ(v float32) predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldEQ(FieldSeedRatio, v))
|
||||
}
|
||||
|
||||
// SeedRatioNEQ applies the NEQ predicate on the "seed_ratio" field.
|
||||
func SeedRatioNEQ(v float32) predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldNEQ(FieldSeedRatio, v))
|
||||
}
|
||||
|
||||
// SeedRatioIn applies the In predicate on the "seed_ratio" field.
|
||||
func SeedRatioIn(vs ...float32) predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldIn(FieldSeedRatio, vs...))
|
||||
}
|
||||
|
||||
// SeedRatioNotIn applies the NotIn predicate on the "seed_ratio" field.
|
||||
func SeedRatioNotIn(vs ...float32) predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldNotIn(FieldSeedRatio, vs...))
|
||||
}
|
||||
|
||||
// SeedRatioGT applies the GT predicate on the "seed_ratio" field.
|
||||
func SeedRatioGT(v float32) predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldGT(FieldSeedRatio, v))
|
||||
}
|
||||
|
||||
// SeedRatioGTE applies the GTE predicate on the "seed_ratio" field.
|
||||
func SeedRatioGTE(v float32) predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldGTE(FieldSeedRatio, v))
|
||||
}
|
||||
|
||||
// SeedRatioLT applies the LT predicate on the "seed_ratio" field.
|
||||
func SeedRatioLT(v float32) predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldLT(FieldSeedRatio, v))
|
||||
}
|
||||
|
||||
// SeedRatioLTE applies the LTE predicate on the "seed_ratio" field.
|
||||
func SeedRatioLTE(v float32) predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldLTE(FieldSeedRatio, v))
|
||||
}
|
||||
|
||||
// SeedRatioIsNil applies the IsNil predicate on the "seed_ratio" field.
|
||||
func SeedRatioIsNil() predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldIsNull(FieldSeedRatio))
|
||||
}
|
||||
|
||||
// SeedRatioNotNil applies the NotNil predicate on the "seed_ratio" field.
|
||||
func SeedRatioNotNil() predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldNotNull(FieldSeedRatio))
|
||||
}
|
||||
|
||||
// DisabledEQ applies the EQ predicate on the "disabled" field.
|
||||
func DisabledEQ(v bool) predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldEQ(FieldDisabled, v))
|
||||
}
|
||||
|
||||
// DisabledNEQ applies the NEQ predicate on the "disabled" field.
|
||||
func DisabledNEQ(v bool) predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldNEQ(FieldDisabled, v))
|
||||
}
|
||||
|
||||
// DisabledIsNil applies the IsNil predicate on the "disabled" field.
|
||||
func DisabledIsNil() predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldIsNull(FieldDisabled))
|
||||
}
|
||||
|
||||
// DisabledNotNil applies the NotNil predicate on the "disabled" field.
|
||||
func DisabledNotNil() predicate.Indexers {
|
||||
return predicate.Indexers(sql.FieldNotNull(FieldDisabled))
|
||||
}
|
||||
|
||||
// And groups predicates with the AND operator between them.
|
||||
func And(predicates ...predicate.Indexers) predicate.Indexers {
|
||||
return predicate.Indexers(sql.AndPredicates(predicates...))
|
||||
|
||||
@@ -57,6 +57,42 @@ func (ic *IndexersCreate) SetPriority(i int) *IndexersCreate {
|
||||
return ic
|
||||
}
|
||||
|
||||
// SetNillablePriority sets the "priority" field if the given value is not nil.
|
||||
func (ic *IndexersCreate) SetNillablePriority(i *int) *IndexersCreate {
|
||||
if i != nil {
|
||||
ic.SetPriority(*i)
|
||||
}
|
||||
return ic
|
||||
}
|
||||
|
||||
// SetSeedRatio sets the "seed_ratio" field.
|
||||
func (ic *IndexersCreate) SetSeedRatio(f float32) *IndexersCreate {
|
||||
ic.mutation.SetSeedRatio(f)
|
||||
return ic
|
||||
}
|
||||
|
||||
// SetNillableSeedRatio sets the "seed_ratio" field if the given value is not nil.
|
||||
func (ic *IndexersCreate) SetNillableSeedRatio(f *float32) *IndexersCreate {
|
||||
if f != nil {
|
||||
ic.SetSeedRatio(*f)
|
||||
}
|
||||
return ic
|
||||
}
|
||||
|
||||
// SetDisabled sets the "disabled" field.
|
||||
func (ic *IndexersCreate) SetDisabled(b bool) *IndexersCreate {
|
||||
ic.mutation.SetDisabled(b)
|
||||
return ic
|
||||
}
|
||||
|
||||
// SetNillableDisabled sets the "disabled" field if the given value is not nil.
|
||||
func (ic *IndexersCreate) SetNillableDisabled(b *bool) *IndexersCreate {
|
||||
if b != nil {
|
||||
ic.SetDisabled(*b)
|
||||
}
|
||||
return ic
|
||||
}
|
||||
|
||||
// Mutation returns the IndexersMutation object of the builder.
|
||||
func (ic *IndexersCreate) Mutation() *IndexersMutation {
|
||||
return ic.mutation
|
||||
@@ -96,6 +132,18 @@ func (ic *IndexersCreate) defaults() {
|
||||
v := indexers.DefaultEnableRss
|
||||
ic.mutation.SetEnableRss(v)
|
||||
}
|
||||
if _, ok := ic.mutation.Priority(); !ok {
|
||||
v := indexers.DefaultPriority
|
||||
ic.mutation.SetPriority(v)
|
||||
}
|
||||
if _, ok := ic.mutation.SeedRatio(); !ok {
|
||||
v := indexers.DefaultSeedRatio
|
||||
ic.mutation.SetSeedRatio(v)
|
||||
}
|
||||
if _, ok := ic.mutation.Disabled(); !ok {
|
||||
v := indexers.DefaultDisabled
|
||||
ic.mutation.SetDisabled(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
@@ -161,6 +209,14 @@ func (ic *IndexersCreate) createSpec() (*Indexers, *sqlgraph.CreateSpec) {
|
||||
_spec.SetField(indexers.FieldPriority, field.TypeInt, value)
|
||||
_node.Priority = value
|
||||
}
|
||||
if value, ok := ic.mutation.SeedRatio(); ok {
|
||||
_spec.SetField(indexers.FieldSeedRatio, field.TypeFloat32, value)
|
||||
_node.SeedRatio = value
|
||||
}
|
||||
if value, ok := ic.mutation.Disabled(); ok {
|
||||
_spec.SetField(indexers.FieldDisabled, field.TypeBool, value)
|
||||
_node.Disabled = value
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
|
||||
@@ -104,6 +104,53 @@ func (iu *IndexersUpdate) AddPriority(i int) *IndexersUpdate {
|
||||
return iu
|
||||
}
|
||||
|
||||
// SetSeedRatio sets the "seed_ratio" field.
|
||||
func (iu *IndexersUpdate) SetSeedRatio(f float32) *IndexersUpdate {
|
||||
iu.mutation.ResetSeedRatio()
|
||||
iu.mutation.SetSeedRatio(f)
|
||||
return iu
|
||||
}
|
||||
|
||||
// SetNillableSeedRatio sets the "seed_ratio" field if the given value is not nil.
|
||||
func (iu *IndexersUpdate) SetNillableSeedRatio(f *float32) *IndexersUpdate {
|
||||
if f != nil {
|
||||
iu.SetSeedRatio(*f)
|
||||
}
|
||||
return iu
|
||||
}
|
||||
|
||||
// AddSeedRatio adds f to the "seed_ratio" field.
|
||||
func (iu *IndexersUpdate) AddSeedRatio(f float32) *IndexersUpdate {
|
||||
iu.mutation.AddSeedRatio(f)
|
||||
return iu
|
||||
}
|
||||
|
||||
// ClearSeedRatio clears the value of the "seed_ratio" field.
|
||||
func (iu *IndexersUpdate) ClearSeedRatio() *IndexersUpdate {
|
||||
iu.mutation.ClearSeedRatio()
|
||||
return iu
|
||||
}
|
||||
|
||||
// SetDisabled sets the "disabled" field.
|
||||
func (iu *IndexersUpdate) SetDisabled(b bool) *IndexersUpdate {
|
||||
iu.mutation.SetDisabled(b)
|
||||
return iu
|
||||
}
|
||||
|
||||
// SetNillableDisabled sets the "disabled" field if the given value is not nil.
|
||||
func (iu *IndexersUpdate) SetNillableDisabled(b *bool) *IndexersUpdate {
|
||||
if b != nil {
|
||||
iu.SetDisabled(*b)
|
||||
}
|
||||
return iu
|
||||
}
|
||||
|
||||
// ClearDisabled clears the value of the "disabled" field.
|
||||
func (iu *IndexersUpdate) ClearDisabled() *IndexersUpdate {
|
||||
iu.mutation.ClearDisabled()
|
||||
return iu
|
||||
}
|
||||
|
||||
// Mutation returns the IndexersMutation object of the builder.
|
||||
func (iu *IndexersUpdate) Mutation() *IndexersMutation {
|
||||
return iu.mutation
|
||||
@@ -163,6 +210,21 @@ func (iu *IndexersUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
if value, ok := iu.mutation.AddedPriority(); ok {
|
||||
_spec.AddField(indexers.FieldPriority, field.TypeInt, value)
|
||||
}
|
||||
if value, ok := iu.mutation.SeedRatio(); ok {
|
||||
_spec.SetField(indexers.FieldSeedRatio, field.TypeFloat32, value)
|
||||
}
|
||||
if value, ok := iu.mutation.AddedSeedRatio(); ok {
|
||||
_spec.AddField(indexers.FieldSeedRatio, field.TypeFloat32, value)
|
||||
}
|
||||
if iu.mutation.SeedRatioCleared() {
|
||||
_spec.ClearField(indexers.FieldSeedRatio, field.TypeFloat32)
|
||||
}
|
||||
if value, ok := iu.mutation.Disabled(); ok {
|
||||
_spec.SetField(indexers.FieldDisabled, field.TypeBool, value)
|
||||
}
|
||||
if iu.mutation.DisabledCleared() {
|
||||
_spec.ClearField(indexers.FieldDisabled, field.TypeBool)
|
||||
}
|
||||
if n, err = sqlgraph.UpdateNodes(ctx, iu.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{indexers.Label}
|
||||
@@ -260,6 +322,53 @@ func (iuo *IndexersUpdateOne) AddPriority(i int) *IndexersUpdateOne {
|
||||
return iuo
|
||||
}
|
||||
|
||||
// SetSeedRatio sets the "seed_ratio" field.
|
||||
func (iuo *IndexersUpdateOne) SetSeedRatio(f float32) *IndexersUpdateOne {
|
||||
iuo.mutation.ResetSeedRatio()
|
||||
iuo.mutation.SetSeedRatio(f)
|
||||
return iuo
|
||||
}
|
||||
|
||||
// SetNillableSeedRatio sets the "seed_ratio" field if the given value is not nil.
|
||||
func (iuo *IndexersUpdateOne) SetNillableSeedRatio(f *float32) *IndexersUpdateOne {
|
||||
if f != nil {
|
||||
iuo.SetSeedRatio(*f)
|
||||
}
|
||||
return iuo
|
||||
}
|
||||
|
||||
// AddSeedRatio adds f to the "seed_ratio" field.
|
||||
func (iuo *IndexersUpdateOne) AddSeedRatio(f float32) *IndexersUpdateOne {
|
||||
iuo.mutation.AddSeedRatio(f)
|
||||
return iuo
|
||||
}
|
||||
|
||||
// ClearSeedRatio clears the value of the "seed_ratio" field.
|
||||
func (iuo *IndexersUpdateOne) ClearSeedRatio() *IndexersUpdateOne {
|
||||
iuo.mutation.ClearSeedRatio()
|
||||
return iuo
|
||||
}
|
||||
|
||||
// SetDisabled sets the "disabled" field.
|
||||
func (iuo *IndexersUpdateOne) SetDisabled(b bool) *IndexersUpdateOne {
|
||||
iuo.mutation.SetDisabled(b)
|
||||
return iuo
|
||||
}
|
||||
|
||||
// SetNillableDisabled sets the "disabled" field if the given value is not nil.
|
||||
func (iuo *IndexersUpdateOne) SetNillableDisabled(b *bool) *IndexersUpdateOne {
|
||||
if b != nil {
|
||||
iuo.SetDisabled(*b)
|
||||
}
|
||||
return iuo
|
||||
}
|
||||
|
||||
// ClearDisabled clears the value of the "disabled" field.
|
||||
func (iuo *IndexersUpdateOne) ClearDisabled() *IndexersUpdateOne {
|
||||
iuo.mutation.ClearDisabled()
|
||||
return iuo
|
||||
}
|
||||
|
||||
// Mutation returns the IndexersMutation object of the builder.
|
||||
func (iuo *IndexersUpdateOne) Mutation() *IndexersMutation {
|
||||
return iuo.mutation
|
||||
@@ -349,6 +458,21 @@ func (iuo *IndexersUpdateOne) sqlSave(ctx context.Context) (_node *Indexers, err
|
||||
if value, ok := iuo.mutation.AddedPriority(); ok {
|
||||
_spec.AddField(indexers.FieldPriority, field.TypeInt, value)
|
||||
}
|
||||
if value, ok := iuo.mutation.SeedRatio(); ok {
|
||||
_spec.SetField(indexers.FieldSeedRatio, field.TypeFloat32, value)
|
||||
}
|
||||
if value, ok := iuo.mutation.AddedSeedRatio(); ok {
|
||||
_spec.AddField(indexers.FieldSeedRatio, field.TypeFloat32, value)
|
||||
}
|
||||
if iuo.mutation.SeedRatioCleared() {
|
||||
_spec.ClearField(indexers.FieldSeedRatio, field.TypeFloat32)
|
||||
}
|
||||
if value, ok := iuo.mutation.Disabled(); ok {
|
||||
_spec.SetField(indexers.FieldDisabled, field.TypeBool, value)
|
||||
}
|
||||
if iuo.mutation.DisabledCleared() {
|
||||
_spec.ClearField(indexers.FieldDisabled, field.TypeBool)
|
||||
}
|
||||
_node = &Indexers{config: iuo.config}
|
||||
_spec.Assign = _node.assignValues
|
||||
_spec.ScanValues = _node.scanValues
|
||||
|
||||
30
ent/media.go
30
ent/media.go
@@ -3,8 +3,10 @@
|
||||
package ent
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"polaris/ent/media"
|
||||
"polaris/ent/schema"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -43,6 +45,10 @@ type Media struct {
|
||||
TargetDir string `json:"target_dir,omitempty"`
|
||||
// tv series only
|
||||
DownloadHistoryEpisodes bool `json:"download_history_episodes,omitempty"`
|
||||
// Limiter holds the value of the "limiter" field.
|
||||
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"`
|
||||
@@ -72,6 +78,8 @@ func (*Media) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case media.FieldLimiter, media.FieldExtras:
|
||||
values[i] = new([]byte)
|
||||
case media.FieldDownloadHistoryEpisodes:
|
||||
values[i] = new(sql.NullBool)
|
||||
case media.FieldID, media.FieldTmdbID, media.FieldStorageID:
|
||||
@@ -179,6 +187,22 @@ func (m *Media) assignValues(columns []string, values []any) error {
|
||||
} else if value.Valid {
|
||||
m.DownloadHistoryEpisodes = value.Bool
|
||||
}
|
||||
case media.FieldLimiter:
|
||||
if value, ok := values[i].(*[]byte); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field limiter", values[i])
|
||||
} else if value != nil && len(*value) > 0 {
|
||||
if err := json.Unmarshal(*value, &m.Limiter); err != nil {
|
||||
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])
|
||||
}
|
||||
@@ -258,6 +282,12 @@ func (m *Media) String() string {
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("download_history_episodes=")
|
||||
builder.WriteString(fmt.Sprintf("%v", m.DownloadHistoryEpisodes))
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -41,6 +41,10 @@ const (
|
||||
FieldTargetDir = "target_dir"
|
||||
// FieldDownloadHistoryEpisodes holds the string denoting the download_history_episodes field in the database.
|
||||
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.
|
||||
@@ -70,6 +74,8 @@ var Columns = []string{
|
||||
FieldStorageID,
|
||||
FieldTargetDir,
|
||||
FieldDownloadHistoryEpisodes,
|
||||
FieldLimiter,
|
||||
FieldExtras,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
@@ -124,7 +130,7 @@ const DefaultResolution = Resolution1080p
|
||||
const (
|
||||
Resolution720p Resolution = "720p"
|
||||
Resolution1080p Resolution = "1080p"
|
||||
Resolution4k Resolution = "4k"
|
||||
Resolution2160p Resolution = "2160p"
|
||||
)
|
||||
|
||||
func (r Resolution) String() string {
|
||||
@@ -134,7 +140,7 @@ func (r Resolution) String() string {
|
||||
// ResolutionValidator is a validator for the "resolution" field enum values. It is called by the builders before save.
|
||||
func ResolutionValidator(r Resolution) error {
|
||||
switch r {
|
||||
case Resolution720p, Resolution1080p, Resolution4k:
|
||||
case Resolution720p, Resolution1080p, Resolution2160p:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("media: invalid enum value for resolution field: %q", r)
|
||||
|
||||
@@ -775,6 +775,26 @@ func DownloadHistoryEpisodesNotNil() predicate.Media {
|
||||
return predicate.Media(sql.FieldNotNull(FieldDownloadHistoryEpisodes))
|
||||
}
|
||||
|
||||
// LimiterIsNil applies the IsNil predicate on the "limiter" field.
|
||||
func LimiterIsNil() predicate.Media {
|
||||
return predicate.Media(sql.FieldIsNull(FieldLimiter))
|
||||
}
|
||||
|
||||
// LimiterNotNil applies the NotNil predicate on the "limiter" field.
|
||||
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) {
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"fmt"
|
||||
"polaris/ent/episode"
|
||||
"polaris/ent/media"
|
||||
"polaris/ent/schema"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
@@ -155,6 +156,34 @@ func (mc *MediaCreate) SetNillableDownloadHistoryEpisodes(b *bool) *MediaCreate
|
||||
return mc
|
||||
}
|
||||
|
||||
// SetLimiter sets the "limiter" field.
|
||||
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...)
|
||||
@@ -340,6 +369,14 @@ func (mc *MediaCreate) createSpec() (*Media, *sqlgraph.CreateSpec) {
|
||||
_spec.SetField(media.FieldDownloadHistoryEpisodes, field.TypeBool, value)
|
||||
_node.DownloadHistoryEpisodes = value
|
||||
}
|
||||
if value, ok := mc.mutation.Limiter(); ok {
|
||||
_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,
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"polaris/ent/episode"
|
||||
"polaris/ent/media"
|
||||
"polaris/ent/predicate"
|
||||
"polaris/ent/schema"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
@@ -249,6 +250,46 @@ func (mu *MediaUpdate) ClearDownloadHistoryEpisodes() *MediaUpdate {
|
||||
return mu
|
||||
}
|
||||
|
||||
// SetLimiter sets the "limiter" field.
|
||||
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...)
|
||||
@@ -401,6 +442,18 @@ func (mu *MediaUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
if mu.mutation.DownloadHistoryEpisodesCleared() {
|
||||
_spec.ClearField(media.FieldDownloadHistoryEpisodes, field.TypeBool)
|
||||
}
|
||||
if value, ok := mu.mutation.Limiter(); ok {
|
||||
_spec.SetField(media.FieldLimiter, field.TypeJSON, value)
|
||||
}
|
||||
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,
|
||||
@@ -686,6 +739,46 @@ func (muo *MediaUpdateOne) ClearDownloadHistoryEpisodes() *MediaUpdateOne {
|
||||
return muo
|
||||
}
|
||||
|
||||
// SetLimiter sets the "limiter" field.
|
||||
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...)
|
||||
@@ -868,6 +961,18 @@ func (muo *MediaUpdateOne) sqlSave(ctx context.Context) (_node *Media, err error
|
||||
if muo.mutation.DownloadHistoryEpisodesCleared() {
|
||||
_spec.ClearField(media.FieldDownloadHistoryEpisodes, field.TypeBool)
|
||||
}
|
||||
if value, ok := muo.mutation.Limiter(); ok {
|
||||
_spec.SetField(media.FieldLimiter, field.TypeJSON, value)
|
||||
}
|
||||
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,
|
||||
|
||||
@@ -38,6 +38,8 @@ var (
|
||||
{Name: "overview", Type: field.TypeString},
|
||||
{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.
|
||||
@@ -48,7 +50,7 @@ var (
|
||||
ForeignKeys: []*schema.ForeignKey{
|
||||
{
|
||||
Symbol: "episodes_media_episodes",
|
||||
Columns: []*schema.Column{EpisodesColumns[7]},
|
||||
Columns: []*schema.Column{EpisodesColumns[9]},
|
||||
RefColumns: []*schema.Column{MediaColumns[0]},
|
||||
OnDelete: schema.SetNull,
|
||||
},
|
||||
@@ -63,7 +65,9 @@ var (
|
||||
{Name: "date", Type: field.TypeTime},
|
||||
{Name: "target_dir", Type: field.TypeString},
|
||||
{Name: "size", Type: field.TypeInt, Default: 0},
|
||||
{Name: "status", Type: field.TypeEnum, Enums: []string{"running", "success", "fail", "uploading"}},
|
||||
{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", "seeding"}},
|
||||
{Name: "saved", Type: field.TypeString, Nullable: true},
|
||||
}
|
||||
// HistoriesTable holds the schema information for the "histories" table.
|
||||
@@ -79,7 +83,9 @@ var (
|
||||
{Name: "implementation", Type: field.TypeString},
|
||||
{Name: "settings", Type: field.TypeString},
|
||||
{Name: "enable_rss", Type: field.TypeBool, Default: true},
|
||||
{Name: "priority", Type: field.TypeInt},
|
||||
{Name: "priority", Type: field.TypeInt, Default: 50},
|
||||
{Name: "seed_ratio", Type: field.TypeFloat32, Nullable: true, Default: 0},
|
||||
{Name: "disabled", Type: field.TypeBool, Nullable: true, Default: false},
|
||||
}
|
||||
// IndexersTable holds the schema information for the "indexers" table.
|
||||
IndexersTable = &schema.Table{
|
||||
@@ -99,10 +105,12 @@ var (
|
||||
{Name: "overview", Type: field.TypeString},
|
||||
{Name: "created_at", Type: field.TypeTime},
|
||||
{Name: "air_date", Type: field.TypeString, Default: ""},
|
||||
{Name: "resolution", Type: field.TypeEnum, Enums: []string{"720p", "1080p", "4k"}, Default: "1080p"},
|
||||
{Name: "resolution", Type: field.TypeEnum, Enums: []string{"720p", "1080p", "2160p"}, Default: "1080p"},
|
||||
{Name: "storage_id", Type: field.TypeInt, Nullable: true},
|
||||
{Name: "target_dir", Type: field.TypeString, Nullable: true},
|
||||
{Name: "download_history_episodes", Type: field.TypeBool, Nullable: true, Default: false},
|
||||
{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{
|
||||
@@ -141,6 +149,8 @@ var (
|
||||
{Name: "id", Type: field.TypeInt, Increment: true},
|
||||
{Name: "name", Type: field.TypeString, Unique: true},
|
||||
{Name: "implementation", Type: field.TypeEnum, Enums: []string{"webdav", "local"}},
|
||||
{Name: "tv_path", Type: field.TypeString, Nullable: true},
|
||||
{Name: "movie_path", Type: field.TypeString, Nullable: true},
|
||||
{Name: "settings", Type: field.TypeString, Nullable: true},
|
||||
{Name: "deleted", Type: field.TypeBool, Default: false},
|
||||
{Name: "default", Type: field.TypeBool, Default: false},
|
||||
|
||||
865
ent/mutation.go
865
ent/mutation.go
File diff suppressed because it is too large
Load Diff
@@ -4,6 +4,7 @@ package ent
|
||||
|
||||
import (
|
||||
"polaris/ent/downloadclients"
|
||||
"polaris/ent/episode"
|
||||
"polaris/ent/history"
|
||||
"polaris/ent/indexers"
|
||||
"polaris/ent/media"
|
||||
@@ -49,6 +50,10 @@ func init() {
|
||||
downloadclients.DefaultTags = downloadclientsDescTags.Default.(string)
|
||||
episodeFields := schema.Episode{}.Fields()
|
||||
_ = episodeFields
|
||||
// episodeDescMonitored is the schema descriptor for monitored field.
|
||||
episodeDescMonitored := episodeFields[7].Descriptor()
|
||||
// episode.DefaultMonitored holds the default value on creation for the monitored field.
|
||||
episode.DefaultMonitored = episodeDescMonitored.Default.(bool)
|
||||
historyFields := schema.History{}.Fields()
|
||||
_ = historyFields
|
||||
// historyDescSize is the schema descriptor for size field.
|
||||
@@ -61,6 +66,18 @@ func init() {
|
||||
indexersDescEnableRss := indexersFields[3].Descriptor()
|
||||
// indexers.DefaultEnableRss holds the default value on creation for the enable_rss field.
|
||||
indexers.DefaultEnableRss = indexersDescEnableRss.Default.(bool)
|
||||
// indexersDescPriority is the schema descriptor for priority field.
|
||||
indexersDescPriority := indexersFields[4].Descriptor()
|
||||
// indexers.DefaultPriority holds the default value on creation for the priority field.
|
||||
indexers.DefaultPriority = indexersDescPriority.Default.(int)
|
||||
// indexersDescSeedRatio is the schema descriptor for seed_ratio field.
|
||||
indexersDescSeedRatio := indexersFields[5].Descriptor()
|
||||
// indexers.DefaultSeedRatio holds the default value on creation for the seed_ratio field.
|
||||
indexers.DefaultSeedRatio = indexersDescSeedRatio.Default.(float32)
|
||||
// indexersDescDisabled is the schema descriptor for disabled field.
|
||||
indexersDescDisabled := indexersFields[6].Descriptor()
|
||||
// indexers.DefaultDisabled holds the default value on creation for the disabled field.
|
||||
indexers.DefaultDisabled = indexersDescDisabled.Default.(bool)
|
||||
mediaFields := schema.Media{}.Fields()
|
||||
_ = mediaFields
|
||||
// mediaDescCreatedAt is the schema descriptor for created_at field.
|
||||
@@ -84,11 +101,11 @@ func init() {
|
||||
storageFields := schema.Storage{}.Fields()
|
||||
_ = storageFields
|
||||
// storageDescDeleted is the schema descriptor for deleted field.
|
||||
storageDescDeleted := storageFields[3].Descriptor()
|
||||
storageDescDeleted := storageFields[5].Descriptor()
|
||||
// storage.DefaultDeleted holds the default value on creation for the deleted field.
|
||||
storage.DefaultDeleted = storageDescDeleted.Default.(bool)
|
||||
// storageDescDefault is the schema descriptor for default field.
|
||||
storageDescDefault := storageFields[4].Descriptor()
|
||||
storageDescDefault := storageFields[6].Descriptor()
|
||||
// storage.DefaultDefault holds the default value on creation for the default field.
|
||||
storage.DefaultDefault = storageDescDefault.Default.(bool)
|
||||
}
|
||||
|
||||
@@ -21,16 +21,18 @@ func (Episode) Fields() []ent.Field {
|
||||
field.String("overview"),
|
||||
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"),
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -19,7 +19,9 @@ func (History) Fields() []ent.Field {
|
||||
field.Time("date"),
|
||||
field.String("target_dir"),
|
||||
field.Int("size").Default(0),
|
||||
field.Enum("status").Values("running", "success", "fail", "uploading"),
|
||||
field.Int("download_client_id").Optional(),
|
||||
field.Int("indexer_id").Optional(),
|
||||
field.Enum("status").Values("running", "success", "fail", "uploading", "seeding"),
|
||||
field.String("saved").Optional(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,9 @@ func (Indexers) Fields() []ent.Field {
|
||||
field.String("implementation"),
|
||||
field.String("settings"),
|
||||
field.Bool("enable_rss").Default(true),
|
||||
field.Int("priority"),
|
||||
field.Int("priority").Default(50),
|
||||
field.Float32("seed_ratio").Optional().Default(0).Comment("minimal seed ratio requied, before removing torrent"),
|
||||
field.Bool("disabled").Optional().Default(false),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,10 +25,12 @@ func (Media) Fields() []ent.Field {
|
||||
field.String("overview"),
|
||||
field.Time("created_at").Default(time.Now()),
|
||||
field.String("air_date").Default(""),
|
||||
field.Enum("resolution").Values("720p", "1080p", "4k").Default("1080p"),
|
||||
field.Enum("resolution").Values("720p", "1080p", "2160p").Default("1080p"),
|
||||
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("extras", MediaExtras{}).Optional(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,3 +40,23 @@ func (Media) Edges() []ent.Edge {
|
||||
edge.To("episodes", Episode.Type),
|
||||
}
|
||||
}
|
||||
|
||||
type MediaLimiter struct {
|
||||
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 != ""
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@ func (Storage) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.String("name").Unique(),
|
||||
field.Enum("implementation").Values("webdav", "local"),
|
||||
field.String("tv_path").Optional(),
|
||||
field.String("movie_path").Optional(),
|
||||
field.String("settings").Optional(),
|
||||
field.Bool("deleted").Default(false),
|
||||
field.Bool("default").Default(false),
|
||||
|
||||
@@ -20,6 +20,10 @@ type Storage struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
// Implementation holds the value of the "implementation" field.
|
||||
Implementation storage.Implementation `json:"implementation,omitempty"`
|
||||
// TvPath holds the value of the "tv_path" field.
|
||||
TvPath string `json:"tv_path,omitempty"`
|
||||
// MoviePath holds the value of the "movie_path" field.
|
||||
MoviePath string `json:"movie_path,omitempty"`
|
||||
// Settings holds the value of the "settings" field.
|
||||
Settings string `json:"settings,omitempty"`
|
||||
// Deleted holds the value of the "deleted" field.
|
||||
@@ -38,7 +42,7 @@ func (*Storage) scanValues(columns []string) ([]any, error) {
|
||||
values[i] = new(sql.NullBool)
|
||||
case storage.FieldID:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case storage.FieldName, storage.FieldImplementation, storage.FieldSettings:
|
||||
case storage.FieldName, storage.FieldImplementation, storage.FieldTvPath, storage.FieldMoviePath, storage.FieldSettings:
|
||||
values[i] = new(sql.NullString)
|
||||
default:
|
||||
values[i] = new(sql.UnknownType)
|
||||
@@ -73,6 +77,18 @@ func (s *Storage) assignValues(columns []string, values []any) error {
|
||||
} else if value.Valid {
|
||||
s.Implementation = storage.Implementation(value.String)
|
||||
}
|
||||
case storage.FieldTvPath:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field tv_path", values[i])
|
||||
} else if value.Valid {
|
||||
s.TvPath = value.String
|
||||
}
|
||||
case storage.FieldMoviePath:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field movie_path", values[i])
|
||||
} else if value.Valid {
|
||||
s.MoviePath = value.String
|
||||
}
|
||||
case storage.FieldSettings:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field settings", values[i])
|
||||
@@ -133,6 +149,12 @@ func (s *Storage) String() string {
|
||||
builder.WriteString("implementation=")
|
||||
builder.WriteString(fmt.Sprintf("%v", s.Implementation))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("tv_path=")
|
||||
builder.WriteString(s.TvPath)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("movie_path=")
|
||||
builder.WriteString(s.MoviePath)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("settings=")
|
||||
builder.WriteString(s.Settings)
|
||||
builder.WriteString(", ")
|
||||
|
||||
@@ -17,6 +17,10 @@ const (
|
||||
FieldName = "name"
|
||||
// FieldImplementation holds the string denoting the implementation field in the database.
|
||||
FieldImplementation = "implementation"
|
||||
// FieldTvPath holds the string denoting the tv_path field in the database.
|
||||
FieldTvPath = "tv_path"
|
||||
// FieldMoviePath holds the string denoting the movie_path field in the database.
|
||||
FieldMoviePath = "movie_path"
|
||||
// FieldSettings holds the string denoting the settings field in the database.
|
||||
FieldSettings = "settings"
|
||||
// FieldDeleted holds the string denoting the deleted field in the database.
|
||||
@@ -32,6 +36,8 @@ var Columns = []string{
|
||||
FieldID,
|
||||
FieldName,
|
||||
FieldImplementation,
|
||||
FieldTvPath,
|
||||
FieldMoviePath,
|
||||
FieldSettings,
|
||||
FieldDeleted,
|
||||
FieldDefault,
|
||||
@@ -95,6 +101,16 @@ func ByImplementation(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldImplementation, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByTvPath orders the results by the tv_path field.
|
||||
func ByTvPath(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldTvPath, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByMoviePath orders the results by the movie_path field.
|
||||
func ByMoviePath(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldMoviePath, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// BySettings orders the results by the settings field.
|
||||
func BySettings(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldSettings, opts...).ToFunc()
|
||||
|
||||
@@ -58,6 +58,16 @@ func Name(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldEQ(FieldName, v))
|
||||
}
|
||||
|
||||
// TvPath applies equality check predicate on the "tv_path" field. It's identical to TvPathEQ.
|
||||
func TvPath(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldEQ(FieldTvPath, v))
|
||||
}
|
||||
|
||||
// MoviePath applies equality check predicate on the "movie_path" field. It's identical to MoviePathEQ.
|
||||
func MoviePath(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldEQ(FieldMoviePath, v))
|
||||
}
|
||||
|
||||
// Settings applies equality check predicate on the "settings" field. It's identical to SettingsEQ.
|
||||
func Settings(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldEQ(FieldSettings, v))
|
||||
@@ -158,6 +168,156 @@ func ImplementationNotIn(vs ...Implementation) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldNotIn(FieldImplementation, vs...))
|
||||
}
|
||||
|
||||
// TvPathEQ applies the EQ predicate on the "tv_path" field.
|
||||
func TvPathEQ(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldEQ(FieldTvPath, v))
|
||||
}
|
||||
|
||||
// TvPathNEQ applies the NEQ predicate on the "tv_path" field.
|
||||
func TvPathNEQ(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldNEQ(FieldTvPath, v))
|
||||
}
|
||||
|
||||
// TvPathIn applies the In predicate on the "tv_path" field.
|
||||
func TvPathIn(vs ...string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldIn(FieldTvPath, vs...))
|
||||
}
|
||||
|
||||
// TvPathNotIn applies the NotIn predicate on the "tv_path" field.
|
||||
func TvPathNotIn(vs ...string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldNotIn(FieldTvPath, vs...))
|
||||
}
|
||||
|
||||
// TvPathGT applies the GT predicate on the "tv_path" field.
|
||||
func TvPathGT(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldGT(FieldTvPath, v))
|
||||
}
|
||||
|
||||
// TvPathGTE applies the GTE predicate on the "tv_path" field.
|
||||
func TvPathGTE(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldGTE(FieldTvPath, v))
|
||||
}
|
||||
|
||||
// TvPathLT applies the LT predicate on the "tv_path" field.
|
||||
func TvPathLT(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldLT(FieldTvPath, v))
|
||||
}
|
||||
|
||||
// TvPathLTE applies the LTE predicate on the "tv_path" field.
|
||||
func TvPathLTE(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldLTE(FieldTvPath, v))
|
||||
}
|
||||
|
||||
// TvPathContains applies the Contains predicate on the "tv_path" field.
|
||||
func TvPathContains(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldContains(FieldTvPath, v))
|
||||
}
|
||||
|
||||
// TvPathHasPrefix applies the HasPrefix predicate on the "tv_path" field.
|
||||
func TvPathHasPrefix(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldHasPrefix(FieldTvPath, v))
|
||||
}
|
||||
|
||||
// TvPathHasSuffix applies the HasSuffix predicate on the "tv_path" field.
|
||||
func TvPathHasSuffix(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldHasSuffix(FieldTvPath, v))
|
||||
}
|
||||
|
||||
// TvPathIsNil applies the IsNil predicate on the "tv_path" field.
|
||||
func TvPathIsNil() predicate.Storage {
|
||||
return predicate.Storage(sql.FieldIsNull(FieldTvPath))
|
||||
}
|
||||
|
||||
// TvPathNotNil applies the NotNil predicate on the "tv_path" field.
|
||||
func TvPathNotNil() predicate.Storage {
|
||||
return predicate.Storage(sql.FieldNotNull(FieldTvPath))
|
||||
}
|
||||
|
||||
// TvPathEqualFold applies the EqualFold predicate on the "tv_path" field.
|
||||
func TvPathEqualFold(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldEqualFold(FieldTvPath, v))
|
||||
}
|
||||
|
||||
// TvPathContainsFold applies the ContainsFold predicate on the "tv_path" field.
|
||||
func TvPathContainsFold(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldContainsFold(FieldTvPath, v))
|
||||
}
|
||||
|
||||
// MoviePathEQ applies the EQ predicate on the "movie_path" field.
|
||||
func MoviePathEQ(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldEQ(FieldMoviePath, v))
|
||||
}
|
||||
|
||||
// MoviePathNEQ applies the NEQ predicate on the "movie_path" field.
|
||||
func MoviePathNEQ(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldNEQ(FieldMoviePath, v))
|
||||
}
|
||||
|
||||
// MoviePathIn applies the In predicate on the "movie_path" field.
|
||||
func MoviePathIn(vs ...string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldIn(FieldMoviePath, vs...))
|
||||
}
|
||||
|
||||
// MoviePathNotIn applies the NotIn predicate on the "movie_path" field.
|
||||
func MoviePathNotIn(vs ...string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldNotIn(FieldMoviePath, vs...))
|
||||
}
|
||||
|
||||
// MoviePathGT applies the GT predicate on the "movie_path" field.
|
||||
func MoviePathGT(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldGT(FieldMoviePath, v))
|
||||
}
|
||||
|
||||
// MoviePathGTE applies the GTE predicate on the "movie_path" field.
|
||||
func MoviePathGTE(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldGTE(FieldMoviePath, v))
|
||||
}
|
||||
|
||||
// MoviePathLT applies the LT predicate on the "movie_path" field.
|
||||
func MoviePathLT(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldLT(FieldMoviePath, v))
|
||||
}
|
||||
|
||||
// MoviePathLTE applies the LTE predicate on the "movie_path" field.
|
||||
func MoviePathLTE(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldLTE(FieldMoviePath, v))
|
||||
}
|
||||
|
||||
// MoviePathContains applies the Contains predicate on the "movie_path" field.
|
||||
func MoviePathContains(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldContains(FieldMoviePath, v))
|
||||
}
|
||||
|
||||
// MoviePathHasPrefix applies the HasPrefix predicate on the "movie_path" field.
|
||||
func MoviePathHasPrefix(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldHasPrefix(FieldMoviePath, v))
|
||||
}
|
||||
|
||||
// MoviePathHasSuffix applies the HasSuffix predicate on the "movie_path" field.
|
||||
func MoviePathHasSuffix(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldHasSuffix(FieldMoviePath, v))
|
||||
}
|
||||
|
||||
// MoviePathIsNil applies the IsNil predicate on the "movie_path" field.
|
||||
func MoviePathIsNil() predicate.Storage {
|
||||
return predicate.Storage(sql.FieldIsNull(FieldMoviePath))
|
||||
}
|
||||
|
||||
// MoviePathNotNil applies the NotNil predicate on the "movie_path" field.
|
||||
func MoviePathNotNil() predicate.Storage {
|
||||
return predicate.Storage(sql.FieldNotNull(FieldMoviePath))
|
||||
}
|
||||
|
||||
// MoviePathEqualFold applies the EqualFold predicate on the "movie_path" field.
|
||||
func MoviePathEqualFold(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldEqualFold(FieldMoviePath, v))
|
||||
}
|
||||
|
||||
// MoviePathContainsFold applies the ContainsFold predicate on the "movie_path" field.
|
||||
func MoviePathContainsFold(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldContainsFold(FieldMoviePath, v))
|
||||
}
|
||||
|
||||
// SettingsEQ applies the EQ predicate on the "settings" field.
|
||||
func SettingsEQ(v string) predicate.Storage {
|
||||
return predicate.Storage(sql.FieldEQ(FieldSettings, v))
|
||||
|
||||
@@ -31,6 +31,34 @@ func (sc *StorageCreate) SetImplementation(s storage.Implementation) *StorageCre
|
||||
return sc
|
||||
}
|
||||
|
||||
// SetTvPath sets the "tv_path" field.
|
||||
func (sc *StorageCreate) SetTvPath(s string) *StorageCreate {
|
||||
sc.mutation.SetTvPath(s)
|
||||
return sc
|
||||
}
|
||||
|
||||
// SetNillableTvPath sets the "tv_path" field if the given value is not nil.
|
||||
func (sc *StorageCreate) SetNillableTvPath(s *string) *StorageCreate {
|
||||
if s != nil {
|
||||
sc.SetTvPath(*s)
|
||||
}
|
||||
return sc
|
||||
}
|
||||
|
||||
// SetMoviePath sets the "movie_path" field.
|
||||
func (sc *StorageCreate) SetMoviePath(s string) *StorageCreate {
|
||||
sc.mutation.SetMoviePath(s)
|
||||
return sc
|
||||
}
|
||||
|
||||
// SetNillableMoviePath sets the "movie_path" field if the given value is not nil.
|
||||
func (sc *StorageCreate) SetNillableMoviePath(s *string) *StorageCreate {
|
||||
if s != nil {
|
||||
sc.SetMoviePath(*s)
|
||||
}
|
||||
return sc
|
||||
}
|
||||
|
||||
// SetSettings sets the "settings" field.
|
||||
func (sc *StorageCreate) SetSettings(s string) *StorageCreate {
|
||||
sc.mutation.SetSettings(s)
|
||||
@@ -171,6 +199,14 @@ func (sc *StorageCreate) createSpec() (*Storage, *sqlgraph.CreateSpec) {
|
||||
_spec.SetField(storage.FieldImplementation, field.TypeEnum, value)
|
||||
_node.Implementation = value
|
||||
}
|
||||
if value, ok := sc.mutation.TvPath(); ok {
|
||||
_spec.SetField(storage.FieldTvPath, field.TypeString, value)
|
||||
_node.TvPath = value
|
||||
}
|
||||
if value, ok := sc.mutation.MoviePath(); ok {
|
||||
_spec.SetField(storage.FieldMoviePath, field.TypeString, value)
|
||||
_node.MoviePath = value
|
||||
}
|
||||
if value, ok := sc.mutation.Settings(); ok {
|
||||
_spec.SetField(storage.FieldSettings, field.TypeString, value)
|
||||
_node.Settings = value
|
||||
|
||||
@@ -55,6 +55,46 @@ func (su *StorageUpdate) SetNillableImplementation(s *storage.Implementation) *S
|
||||
return su
|
||||
}
|
||||
|
||||
// SetTvPath sets the "tv_path" field.
|
||||
func (su *StorageUpdate) SetTvPath(s string) *StorageUpdate {
|
||||
su.mutation.SetTvPath(s)
|
||||
return su
|
||||
}
|
||||
|
||||
// SetNillableTvPath sets the "tv_path" field if the given value is not nil.
|
||||
func (su *StorageUpdate) SetNillableTvPath(s *string) *StorageUpdate {
|
||||
if s != nil {
|
||||
su.SetTvPath(*s)
|
||||
}
|
||||
return su
|
||||
}
|
||||
|
||||
// ClearTvPath clears the value of the "tv_path" field.
|
||||
func (su *StorageUpdate) ClearTvPath() *StorageUpdate {
|
||||
su.mutation.ClearTvPath()
|
||||
return su
|
||||
}
|
||||
|
||||
// SetMoviePath sets the "movie_path" field.
|
||||
func (su *StorageUpdate) SetMoviePath(s string) *StorageUpdate {
|
||||
su.mutation.SetMoviePath(s)
|
||||
return su
|
||||
}
|
||||
|
||||
// SetNillableMoviePath sets the "movie_path" field if the given value is not nil.
|
||||
func (su *StorageUpdate) SetNillableMoviePath(s *string) *StorageUpdate {
|
||||
if s != nil {
|
||||
su.SetMoviePath(*s)
|
||||
}
|
||||
return su
|
||||
}
|
||||
|
||||
// ClearMoviePath clears the value of the "movie_path" field.
|
||||
func (su *StorageUpdate) ClearMoviePath() *StorageUpdate {
|
||||
su.mutation.ClearMoviePath()
|
||||
return su
|
||||
}
|
||||
|
||||
// SetSettings sets the "settings" field.
|
||||
func (su *StorageUpdate) SetSettings(s string) *StorageUpdate {
|
||||
su.mutation.SetSettings(s)
|
||||
@@ -163,6 +203,18 @@ func (su *StorageUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
if value, ok := su.mutation.Implementation(); ok {
|
||||
_spec.SetField(storage.FieldImplementation, field.TypeEnum, value)
|
||||
}
|
||||
if value, ok := su.mutation.TvPath(); ok {
|
||||
_spec.SetField(storage.FieldTvPath, field.TypeString, value)
|
||||
}
|
||||
if su.mutation.TvPathCleared() {
|
||||
_spec.ClearField(storage.FieldTvPath, field.TypeString)
|
||||
}
|
||||
if value, ok := su.mutation.MoviePath(); ok {
|
||||
_spec.SetField(storage.FieldMoviePath, field.TypeString, value)
|
||||
}
|
||||
if su.mutation.MoviePathCleared() {
|
||||
_spec.ClearField(storage.FieldMoviePath, field.TypeString)
|
||||
}
|
||||
if value, ok := su.mutation.Settings(); ok {
|
||||
_spec.SetField(storage.FieldSettings, field.TypeString, value)
|
||||
}
|
||||
@@ -223,6 +275,46 @@ func (suo *StorageUpdateOne) SetNillableImplementation(s *storage.Implementation
|
||||
return suo
|
||||
}
|
||||
|
||||
// SetTvPath sets the "tv_path" field.
|
||||
func (suo *StorageUpdateOne) SetTvPath(s string) *StorageUpdateOne {
|
||||
suo.mutation.SetTvPath(s)
|
||||
return suo
|
||||
}
|
||||
|
||||
// SetNillableTvPath sets the "tv_path" field if the given value is not nil.
|
||||
func (suo *StorageUpdateOne) SetNillableTvPath(s *string) *StorageUpdateOne {
|
||||
if s != nil {
|
||||
suo.SetTvPath(*s)
|
||||
}
|
||||
return suo
|
||||
}
|
||||
|
||||
// ClearTvPath clears the value of the "tv_path" field.
|
||||
func (suo *StorageUpdateOne) ClearTvPath() *StorageUpdateOne {
|
||||
suo.mutation.ClearTvPath()
|
||||
return suo
|
||||
}
|
||||
|
||||
// SetMoviePath sets the "movie_path" field.
|
||||
func (suo *StorageUpdateOne) SetMoviePath(s string) *StorageUpdateOne {
|
||||
suo.mutation.SetMoviePath(s)
|
||||
return suo
|
||||
}
|
||||
|
||||
// SetNillableMoviePath sets the "movie_path" field if the given value is not nil.
|
||||
func (suo *StorageUpdateOne) SetNillableMoviePath(s *string) *StorageUpdateOne {
|
||||
if s != nil {
|
||||
suo.SetMoviePath(*s)
|
||||
}
|
||||
return suo
|
||||
}
|
||||
|
||||
// ClearMoviePath clears the value of the "movie_path" field.
|
||||
func (suo *StorageUpdateOne) ClearMoviePath() *StorageUpdateOne {
|
||||
suo.mutation.ClearMoviePath()
|
||||
return suo
|
||||
}
|
||||
|
||||
// SetSettings sets the "settings" field.
|
||||
func (suo *StorageUpdateOne) SetSettings(s string) *StorageUpdateOne {
|
||||
suo.mutation.SetSettings(s)
|
||||
@@ -361,6 +453,18 @@ func (suo *StorageUpdateOne) sqlSave(ctx context.Context) (_node *Storage, err e
|
||||
if value, ok := suo.mutation.Implementation(); ok {
|
||||
_spec.SetField(storage.FieldImplementation, field.TypeEnum, value)
|
||||
}
|
||||
if value, ok := suo.mutation.TvPath(); ok {
|
||||
_spec.SetField(storage.FieldTvPath, field.TypeString, value)
|
||||
}
|
||||
if suo.mutation.TvPathCleared() {
|
||||
_spec.ClearField(storage.FieldTvPath, field.TypeString)
|
||||
}
|
||||
if value, ok := suo.mutation.MoviePath(); ok {
|
||||
_spec.SetField(storage.FieldMoviePath, field.TypeString, value)
|
||||
}
|
||||
if suo.mutation.MoviePathCleared() {
|
||||
_spec.ClearField(storage.FieldMoviePath, field.TypeString)
|
||||
}
|
||||
if value, ok := suo.mutation.Settings(); ok {
|
||||
_spec.SetField(storage.FieldSettings, field.TypeString, value)
|
||||
}
|
||||
|
||||
3
go.mod
3
go.mod
@@ -12,9 +12,9 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/adrg/strutil v0.3.1
|
||||
github.com/gin-contrib/zap v1.1.3
|
||||
github.com/nikoksr/notify v1.0.0
|
||||
github.com/stretchr/testify v1.9.0
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -25,7 +25,6 @@ require (
|
||||
github.com/gregdel/pushover v1.3.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/stretchr/objx v0.5.2 // indirect
|
||||
github.com/stretchr/testify v1.9.0 // indirect
|
||||
github.com/technoweenie/multipartstreamer v1.0.1 // indirect
|
||||
golang.org/x/sync v0.7.0 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
|
||||
4
go.sum
4
go.sum
@@ -6,8 +6,6 @@ github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0
|
||||
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
|
||||
github.com/adrg/strutil v0.3.1 h1:OLvSS7CSJO8lBii4YmBt8jiK9QOtB9CzCzwl4Ic/Fz4=
|
||||
github.com/adrg/strutil v0.3.1/go.mod h1:8h90y18QLrs11IBffcGX3NW/GFBXCMcNg4M7H6MspPA=
|
||||
github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8=
|
||||
github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
|
||||
github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw=
|
||||
@@ -80,6 +78,8 @@ github.com/hekmon/cunits/v2 v2.1.0 h1:k6wIjc4PlacNOHwKEMBgWV2/c8jyD4eRMs5mR1BBhI
|
||||
github.com/hekmon/cunits/v2 v2.1.0/go.mod h1:9r1TycXYXaTmEWlAIfFV8JT+Xo59U96yUJAYHxzii2M=
|
||||
github.com/hekmon/transmissionrpc/v3 v3.0.0 h1:0Fb11qE0IBh4V4GlOwHNYpqpjcYDp5GouolwrpmcUDQ=
|
||||
github.com/hekmon/transmissionrpc/v3 v3.0.0/go.mod h1:38SlNhFzinVUuY87wGj3acOmRxeYZAZfrj6Re7UgCDg=
|
||||
github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible h1:jdpOPRN1zP63Td1hDQbZW73xKmzDvZHzVdNYxhnTMDA=
|
||||
github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible/go.mod h1:1c7szIrayyPPB/987hsnvNzLushdWf4o/79s3P08L8A=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
|
||||
@@ -26,13 +26,14 @@ func init() {
|
||||
MaxSize: 50, // megabytes
|
||||
MaxBackups: 3,
|
||||
MaxAge: 30, // days
|
||||
Compress: true,
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
consoleEncoder := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())
|
||||
|
||||
logger := zap.New(zapcore.NewCore(consoleEncoder, w, atom), zap.AddCallerSkip(1))
|
||||
logger := zap.New(zapcore.NewCore(consoleEncoder, w, atom), zap.AddCallerSkip(1),zap.AddCaller())
|
||||
|
||||
sugar = logger.Sugar()
|
||||
|
||||
|
||||
52
pkg/cache/cache.go
vendored
Normal file
52
pkg/cache/cache.go
vendored
Normal 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
|
||||
}
|
||||
@@ -8,6 +8,7 @@ type Torrent interface {
|
||||
Remove() error
|
||||
Save() string
|
||||
Exists() bool
|
||||
SeedRatio() *float64
|
||||
}
|
||||
|
||||
|
||||
|
||||
23
pkg/metadata/doc.go
Normal file
23
pkg/metadata/doc.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package metadata
|
||||
|
||||
/*
|
||||
tv name examples
|
||||
|
||||
Cowboy Cartel S01E02 XviD-AFG [eztv]
|
||||
The.Bold.and.the.Beautiful.S37E219.XviD-AFG
|
||||
As Husband As Wife 2024 S01E05-E06 1080p WEB-DL HEVC DDP 2Audios-QHstudIo
|
||||
Twinkle Love 2024 S04 Complete 2160p WEB-DL HEVC AAC-QHstudIo
|
||||
[HorribleSubs] One Punch Man S2 - 08 [720p].mkv
|
||||
[Breeze] One Punch Man S01 S02 [1080p BD AV1][dual audio]
|
||||
[HYSUB]ONE PUNCH MAN[S1+S2][BDrip][GB_MP4][1920X1080]
|
||||
Cowboy Cartel S01E04 Photo Finish 1080p ATVP WEB-DL DDP5 1 Atmos H 264-FLUX [eztv]
|
||||
Limitless Wrestling 2021 01 06 The Road Season 2 Episode 12 XviD-AFG [eztv]
|
||||
|
||||
[千夏字幕组][小市民系列_Shoushimin Series][第03话][1080p_HEVC][简繁内封][招募新人]
|
||||
[OPFans楓雪動漫][ONE PIECE 海賊王][第1113話][周日版][1080p][MP4][簡體]
|
||||
[桜都字幕组] 亦叶亦花 / Nanare Hananare [04][1080p][简体内嵌]
|
||||
[ANi] 戰國妖狐 千魔混沌篇 - 16 [1080P][Baha][WEB-DL][AAC AVC][CHT][MP4]
|
||||
[ANi] 這是妳與我的最後戰場,或是開創世界的聖戰 第二季 - 04 [1080P][Baha][WEB-DL][AAC AVC][CHT][MP4]
|
||||
[桜都字幕组][一拳超人 第2季/One Punch Man 2nd Season][01-12 END][BIG5][720P]
|
||||
一拳超人第二季One.Punch.Man.Season2.2160p.10Bit.HEVC.AAC.CHS&JPN
|
||||
*/
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -29,20 +29,11 @@ func ParseTv(name string) *Metadata {
|
||||
func parseEnglishName(name string) *Metadata {
|
||||
re := regexp.MustCompile(`[^\p{L}\w\s]`)
|
||||
name = re.ReplaceAllString(strings.ToLower(name), " ")
|
||||
|
||||
splits := strings.Split(strings.TrimSpace(name), " ")
|
||||
var newSplits []string
|
||||
for _, p := range splits {
|
||||
p = strings.TrimSpace(p)
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
newSplits = append(newSplits, p)
|
||||
}
|
||||
newSplits := strings.Split(strings.TrimSpace(name), " ")
|
||||
|
||||
seasonRe := regexp.MustCompile(`^s\d{1,2}`)
|
||||
resRe := regexp.MustCompile(`^\d{3,4}p`)
|
||||
episodeRe := regexp.MustCompile(`e\d{1,2}`)
|
||||
episodeRe := regexp.MustCompile(`e\d{1,3}`)
|
||||
|
||||
var seasonIndex = -1
|
||||
var episodeIndex = -1
|
||||
@@ -58,7 +49,7 @@ func parseEnglishName(name string) *Metadata {
|
||||
} else if resRe.MatchString(p) {
|
||||
resIndex = i
|
||||
}
|
||||
if episodeRe.MatchString(p) {
|
||||
if i >= seasonIndex && episodeRe.MatchString(p) {
|
||||
episodeIndex = i
|
||||
}
|
||||
}
|
||||
@@ -137,7 +128,7 @@ func parseEnglishName(name string) *Metadata {
|
||||
//resolution exists
|
||||
meta.Resolution = newSplits[resIndex]
|
||||
}
|
||||
if meta.Episode == -1 || strings.Contains(name, "complete") {
|
||||
if meta.Episode == -1 {
|
||||
meta.Episode = -1
|
||||
meta.IsSeasonPack = true
|
||||
}
|
||||
@@ -154,9 +145,11 @@ func parseEnglishName(name string) *Metadata {
|
||||
}
|
||||
|
||||
func parseChineseName(name string) *Metadata {
|
||||
var meta = &Metadata{
|
||||
Season: 1,
|
||||
var meta = parseEnglishName(name)
|
||||
if meta.Season != -1 && (meta.Episode != -1 || meta.IsSeasonPack) {
|
||||
return meta
|
||||
}
|
||||
meta = &Metadata{Season: 1}
|
||||
//season pack
|
||||
packRe := regexp.MustCompile(`(\d{1,2}-\d{1,2})|(全集)`)
|
||||
if packRe.MatchString(name) {
|
||||
|
||||
147
pkg/metadata/tv_test.go
Normal file
147
pkg/metadata/tv_test.go
Normal file
@@ -0,0 +1,147 @@
|
||||
package metadata
|
||||
|
||||
import (
|
||||
"polaris/log"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func Test_ParseTV1(t *testing.T) {
|
||||
s1 := "Twinkle Love 2024 S04 Complete 2160p WEB-DL HEVC AAC-QHstudIo"
|
||||
m := ParseTv(s1)
|
||||
log.Infof("results: %+v", m)
|
||||
assert.Equal(t, m.Season, 4)
|
||||
assert.Equal(t, m.IsSeasonPack, true)
|
||||
assert.Equal(t, m.Resolution, "2160p")
|
||||
}
|
||||
|
||||
func Test_ParseTV2(t *testing.T) {
|
||||
s1 := "Cowboy Cartel S01E04 Photo Finish 1080p ATVP WEB-DL DDP5 1 Atmos H 264-FLUX [eztv] "
|
||||
m := ParseTv(s1)
|
||||
log.Infof("results: %+v", m)
|
||||
assert.Equal(t, m.Season, 1)
|
||||
assert.Equal(t, m.Episode, 4)
|
||||
assert.Equal(t, m.IsSeasonPack, false)
|
||||
assert.Equal(t, m.Resolution, "1080p")
|
||||
}
|
||||
|
||||
func Test_ParseTV3(t *testing.T) {
|
||||
s1 := "The.Bold.and.the.Beautiful.S37E219.XviD-AFG "
|
||||
m := ParseTv(s1)
|
||||
log.Infof("results: %+v", m)
|
||||
assert.Equal(t, m.Season, 37)
|
||||
assert.Equal(t, m.Episode, 219)
|
||||
assert.Equal(t, m.IsSeasonPack, false)
|
||||
//assert.Equal(t, m.Resolution, "1080p")
|
||||
}
|
||||
|
||||
func Test_ParseTV4(t *testing.T) {
|
||||
s1 := "Limitless Wrestling 2021 01 06 The Road Season 2 Episode 12 XviD-AFG [eztv] "
|
||||
m := ParseTv(s1)
|
||||
log.Infof("results: %+v", m)
|
||||
assert.Equal(t, m.Season, 2)
|
||||
//assert.Equal(t, m.Episode, 219)
|
||||
assert.Equal(t, m.IsSeasonPack, true)
|
||||
//assert.Equal(t, m.Resolution, "1080p")
|
||||
}
|
||||
|
||||
func Test_ParseTV5(t *testing.T) {
|
||||
s1 := "[Breeze] One Punch Man S01 S02 [1080p BD AV1][dual audio]"
|
||||
m := ParseTv(s1)
|
||||
log.Infof("results: %+v", m)
|
||||
assert.Equal(t, m.Season, 1)
|
||||
//assert.Equal(t, m.Episode, 219)
|
||||
assert.Equal(t, m.IsSeasonPack, true)
|
||||
//assert.Equal(t, m.Resolution, "1080p")
|
||||
}
|
||||
|
||||
func Test_ParseTV6(t *testing.T) {
|
||||
s1 := "[千夏字幕组][小市民系列_Shoushimin Series][第03话][1080p_HEVC][简繁内封][招募新人]"
|
||||
m := ParseTv(s1)
|
||||
log.Infof("results: %+v", m)
|
||||
assert.Equal(t, m.Season, 1)
|
||||
assert.Equal(t, m.Episode, 3)
|
||||
assert.Equal(t, m.IsSeasonPack, false)
|
||||
assert.Equal(t, m.Resolution, "1080p")
|
||||
}
|
||||
|
||||
func Test_ParseTV7(t *testing.T) {
|
||||
s1 := " [OPFans楓雪動漫][ONE PIECE 海賊王][第1113話][周日版][1080p][MP4][簡體]"
|
||||
m := ParseTv(s1)
|
||||
log.Infof("results: %+v", m)
|
||||
assert.Equal(t, m.Season, 1)
|
||||
assert.Equal(t, m.Episode, 1113)
|
||||
assert.Equal(t, m.IsSeasonPack, false)
|
||||
assert.Equal(t, m.Resolution, "1080p")
|
||||
}
|
||||
|
||||
func Test_ParseTV8(t *testing.T) {
|
||||
s1 := "[桜都字幕组] 亦叶亦花 / Nanare Hananare [04][1080p][简体内嵌] "
|
||||
m := ParseTv(s1)
|
||||
log.Infof("results: %+v", m)
|
||||
assert.Equal(t, m.Season, 1)
|
||||
assert.Equal(t, m.Episode, 4)
|
||||
assert.Equal(t, m.IsSeasonPack, false)
|
||||
assert.Equal(t, m.Resolution, "1080p")
|
||||
}
|
||||
|
||||
func Test_ParseTV9(t *testing.T) {
|
||||
s1 := "[ANi] 戰國妖狐 千魔混沌篇 - 16 [1080P][Baha][WEB-DL][AAC AVC][CHT][MP4]"
|
||||
m := ParseTv(s1)
|
||||
log.Infof("results: %+v", m)
|
||||
assert.Equal(t, m.Season, 1)
|
||||
assert.Equal(t, m.Episode, 16)
|
||||
assert.Equal(t, m.IsSeasonPack, false)
|
||||
assert.Equal(t, m.Resolution, "1080p")
|
||||
}
|
||||
|
||||
func Test_ParseTV10(t *testing.T) {
|
||||
s1 := " [桜都字幕组][一拳超人 第2季/One Punch Man 2nd Season][01-12 END][BIG5][720P]"
|
||||
m := ParseTv(s1)
|
||||
log.Infof("results: %+v", m)
|
||||
assert.Equal(t, 2, m.Season)
|
||||
//assert.Equal(t, 01, m.Episode)
|
||||
assert.Equal(t, true, m.IsSeasonPack)
|
||||
assert.Equal(t, "720p", m.Resolution)
|
||||
}
|
||||
|
||||
func Test_ParseTV11(t *testing.T) {
|
||||
s1 := " [ANi] 這是妳與我的最後戰場,或是開創世界的聖戰 第二季 - 04 [1080P][Baha][WEB-DL][AAC AVC][CHT][MP4] "
|
||||
m := ParseTv(s1)
|
||||
log.Infof("results: %+v", m)
|
||||
assert.Equal(t, 2, m.Season)
|
||||
assert.Equal(t, 4, m.Episode)
|
||||
assert.Equal(t, false, m.IsSeasonPack)
|
||||
assert.Equal(t, "1080p", m.Resolution)
|
||||
}
|
||||
|
||||
func Test_ParseTV12(t *testing.T) {
|
||||
s1 := " 牛仔Cowboy Cartel S02E04 Photo Finish 1080p ATVP WEB-DL DDP5 1 Atmos H 264-FLUX [eztv] "
|
||||
m := ParseTv(s1)
|
||||
log.Infof("results: %+v", m)
|
||||
assert.Equal(t, 2, m.Season)
|
||||
assert.Equal(t, 4, m.Episode)
|
||||
assert.Equal(t, false, m.IsSeasonPack)
|
||||
assert.Equal(t, "1080p", m.Resolution)
|
||||
}
|
||||
|
||||
func Test_ParseTV13(t *testing.T) {
|
||||
s1 := "House of Dragon 2024 1080p S02E08 Leaked HQCAM NOT COMPLETE English Audio x264 ESub BOTHD"
|
||||
m := ParseTv(s1)
|
||||
log.Infof("results: %+v", m)
|
||||
assert.Equal(t, 2, m.Season)
|
||||
assert.Equal(t, 8, m.Episode)
|
||||
assert.Equal(t, false, m.IsSeasonPack)
|
||||
assert.Equal(t, "1080p", m.Resolution)
|
||||
}
|
||||
|
||||
func Test_ParseTV14(t *testing.T) {
|
||||
s1 := ""
|
||||
m := ParseTv(s1)
|
||||
log.Infof("results: %+v", m)
|
||||
assert.Equal(t, 2, m.Season)
|
||||
assert.Equal(t, 01, m.Episode)
|
||||
assert.Equal(t, false, m.IsSeasonPack)
|
||||
assert.Equal(t, "720p", m.Resolution)
|
||||
}
|
||||
@@ -13,7 +13,10 @@ import (
|
||||
|
||||
type Storage interface {
|
||||
Move(src, dest string) error
|
||||
Copy(src, dest string) error
|
||||
ReadDir(dir string) ([]fs.FileInfo, error)
|
||||
ReadFile(string) ([]byte, error)
|
||||
WriteFile(string, []byte) error
|
||||
}
|
||||
|
||||
func NewLocalStorage(dir string) (*LocalStorage, error) {
|
||||
@@ -26,10 +29,20 @@ type LocalStorage struct {
|
||||
dir string
|
||||
}
|
||||
|
||||
func (l *LocalStorage) Move(src, dest string) error {
|
||||
targetDir := filepath.Join(l.dir, dest)
|
||||
os.MkdirAll(filepath.Dir(targetDir), os.ModePerm)
|
||||
err := filepath.Walk(src, func(path string, info fs.FileInfo, err error) error {
|
||||
func (l *LocalStorage) Copy(src, destDir string) error {
|
||||
os.MkdirAll(filepath.Join(l.dir, destDir), os.ModePerm)
|
||||
|
||||
targetBase := filepath.Join(l.dir, destDir, filepath.Base(src)) //文件的场景,要加上文件名, move filename ./dir/
|
||||
info, err := os.Stat(src)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "read source dir")
|
||||
}
|
||||
if info.IsDir() { //如果是路径,则只移动路径里面的文件,不管当前路径, 行为类似 move dirname/* target_dir/
|
||||
targetBase = filepath.Join(l.dir, destDir)
|
||||
}
|
||||
log.Debugf("local storage target base dir is: %v", targetBase)
|
||||
|
||||
err = filepath.Walk(src, func(path string, info fs.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -37,24 +50,28 @@ func (l *LocalStorage) Move(src, dest string) error {
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "relation between %s and %s", src, path)
|
||||
}
|
||||
destName := filepath.Join(targetDir, rel)
|
||||
destName := filepath.Join(targetBase, rel)
|
||||
|
||||
if info.IsDir() {
|
||||
os.Mkdir(destName, os.ModePerm)
|
||||
} else { //is file
|
||||
if writer, err := os.Create(destName); err != nil {
|
||||
return errors.Wrapf(err, "create file %s", destName)
|
||||
} else {
|
||||
defer writer.Close()
|
||||
if f, err := os.OpenFile(path, os.O_RDONLY, os.ModePerm); err != nil {
|
||||
return errors.Wrapf(err, "read file %v", path)
|
||||
} else { //open success
|
||||
defer f.Close()
|
||||
_, err := io.Copy(writer, f)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "transmitting data error")
|
||||
if err := os.Link(path, destName); err != nil {
|
||||
log.Warnf("hard link file error: %v, will try copy file, source: %s, dest: %s", err, path, destName)
|
||||
if writer, err := os.OpenFile(destName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, os.ModePerm); err != nil {
|
||||
return errors.Wrapf(err, "create file %s", destName)
|
||||
} else {
|
||||
defer writer.Close()
|
||||
if f, err := os.OpenFile(path, os.O_RDONLY, os.ModePerm); err != nil {
|
||||
return errors.Wrapf(err, "read file %v", path)
|
||||
} else { //open success
|
||||
defer f.Close()
|
||||
_, err := io.Copy(writer, f)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "transmitting data error")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
log.Infof("file copy complete: %v", destName)
|
||||
@@ -63,10 +80,26 @@ func (l *LocalStorage) Move(src, dest string) error {
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "move file error")
|
||||
}
|
||||
return os.RemoveAll(src)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *LocalStorage) Move(src, destDir string) error {
|
||||
if err := l.Copy(src, destDir); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.RemoveAll(src)
|
||||
}
|
||||
|
||||
func (l *LocalStorage) ReadDir(dir string) ([]fs.FileInfo, error) {
|
||||
return ioutil.ReadDir(filepath.Join(l.dir, dir))
|
||||
}
|
||||
|
||||
func (l *LocalStorage) ReadFile(name string) ([]byte, error) {
|
||||
return os.ReadFile(filepath.Join(l.dir, name))
|
||||
}
|
||||
|
||||
func (l *LocalStorage) WriteFile(name string, data []byte) error {
|
||||
path := filepath.Join(l.dir, name)
|
||||
os.MkdirAll(filepath.Dir(path), os.ModePerm)
|
||||
return os.WriteFile(path, data, os.ModePerm)
|
||||
}
|
||||
|
||||
@@ -14,8 +14,8 @@ import (
|
||||
)
|
||||
|
||||
type WebdavStorage struct {
|
||||
fs *gowebdav.Client
|
||||
dir string
|
||||
fs *gowebdav.Client
|
||||
dir string
|
||||
changeMediaHash bool
|
||||
}
|
||||
|
||||
@@ -25,18 +25,24 @@ func NewWebdavStorage(url, user, password, path string, changeMediaHash bool) (*
|
||||
return nil, errors.Wrap(err, "connect webdav")
|
||||
}
|
||||
return &WebdavStorage{
|
||||
fs: c,
|
||||
fs: c,
|
||||
dir: path,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (w *WebdavStorage) Move(local, remote string) error {
|
||||
|
||||
remoteBase := filepath.Join(w.dir,remote)
|
||||
func (w *WebdavStorage) Copy(local, remoteDir string) error {
|
||||
remoteBase := filepath.Join(w.dir, remoteDir, filepath.Base(local))
|
||||
info, err := os.Stat(local)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "read source dir")
|
||||
}
|
||||
if info.IsDir() { //如果是路径,则只移动路径里面的文件,不管当前路径, 行为类似 move dirname/* target_dir/
|
||||
remoteBase = filepath.Join(w.dir, remoteDir)
|
||||
}
|
||||
|
||||
//log.Infof("remove all content in %s", remoteBase)
|
||||
//w.fs.RemoveAll(remoteBase)
|
||||
err := filepath.Walk(local, func(path string, info fs.FileInfo, err error) error {
|
||||
err = filepath.Walk(local, func(path string, info fs.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "read file %v", path)
|
||||
}
|
||||
@@ -73,7 +79,7 @@ func (w *WebdavStorage) Move(local, remote string) error {
|
||||
r.Header.Set("Content-Type", mtype.String())
|
||||
r.ContentLength = info.Size()
|
||||
}
|
||||
|
||||
|
||||
if err := w.fs.WriteStream(remoteName, f, 0666, callback); err != nil {
|
||||
return errors.Wrap(err, "transmitting data error")
|
||||
}
|
||||
@@ -85,9 +91,24 @@ func (w *WebdavStorage) Move(local, remote string) error {
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "move file error")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *WebdavStorage) Move(local, remoteDir string) error {
|
||||
if err := w.Copy(local, remoteDir); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.RemoveAll(local)
|
||||
}
|
||||
|
||||
func (w *WebdavStorage) ReadDir(dir string) ([]fs.FileInfo, error) {
|
||||
return w.fs.ReadDir(filepath.Join(w.dir, dir))
|
||||
}
|
||||
|
||||
func (w *WebdavStorage) ReadFile(name string) ([]byte, error) {
|
||||
return w.fs.Read(filepath.Join(w.dir, name))
|
||||
}
|
||||
|
||||
func (w *WebdavStorage) WriteFile(name string, data []byte) error {
|
||||
return w.fs.Write(filepath.Join(w.dir, name), data, os.ModePerm)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
package tmdb
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"polaris/log"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
tmdb "github.com/cyruzin/golang-tmdb"
|
||||
"github.com/pkg/errors"
|
||||
@@ -12,22 +15,42 @@ import (
|
||||
type Client struct {
|
||||
apiKey string
|
||||
tmdbClient *tmdb.Client
|
||||
enableAdultContent bool
|
||||
}
|
||||
|
||||
func NewClient(apiKey string) (*Client, error) {
|
||||
func NewClient(apiKey, proxyUrl string, enableAdultContent bool) (*Client, error) {
|
||||
|
||||
tmdbClient, err := tmdb.Init(apiKey)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "new tmdb client")
|
||||
}
|
||||
if proxyUrl != "" {
|
||||
//set proxy
|
||||
u, err := url.Parse(proxyUrl)
|
||||
if err != nil {
|
||||
log.Errorf("parse proxy %v error, skip: %v", proxyUrl, err)
|
||||
} else {
|
||||
tmdbClient.SetClientConfig(http.Client{
|
||||
Timeout: time.Second * 10,
|
||||
Transport: &http.Transport{
|
||||
Proxy: http.ProxyURL(u),
|
||||
MaxIdleConns: 10,
|
||||
IdleConnTimeout: 15 * time.Second,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return &Client{
|
||||
apiKey: apiKey,
|
||||
tmdbClient: tmdbClient,
|
||||
enableAdultContent: enableAdultContent,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetTvDetails(id int, language string) (*tmdb.TVDetails, error) {
|
||||
d, err := c.tmdbClient.GetTVDetails(id, withLangOption(language))
|
||||
d, err := c.tmdbClient.GetTVDetails(id, withExternalIDs(withLangOption(language)))
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "get tv detail")
|
||||
}
|
||||
@@ -37,7 +60,7 @@ func (c *Client) GetTvDetails(id int, language string) (*tmdb.TVDetails, error)
|
||||
log.Debug("should fetch english version")
|
||||
var detailEN *tmdb.TVDetails
|
||||
if language == "zh-CN" {
|
||||
detailEN, err = c.tmdbClient.GetTVDetails(id, withLangOption("en-US"))
|
||||
detailEN, err = c.tmdbClient.GetTVDetails(id, withExternalIDs(withLangOption("en-US")))
|
||||
if err != nil {
|
||||
return d, nil
|
||||
}
|
||||
@@ -50,12 +73,11 @@ func (c *Client) GetTvDetails(id int, language string) (*tmdb.TVDetails, error)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return d, err
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -94,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")
|
||||
@@ -152,7 +177,7 @@ func (c *Client) GetEposideDetail(id, seasonNumber, eposideNumber int, language
|
||||
return d, err
|
||||
}
|
||||
d.Name = detailEN.Name
|
||||
d.Overview = detailEN.Overview
|
||||
d.Overview = detailEN.Overview
|
||||
}
|
||||
|
||||
return d, err
|
||||
@@ -172,7 +197,7 @@ func (c *Client) GetSeasonDetails(id, seasonNumber int, language string) (*tmdb.
|
||||
}
|
||||
|
||||
for i, ep := range detailCN.Episodes {
|
||||
if !episodeNameUseful(ep.Name) && episodeNameUseful(detailEN.Episodes[i].Name){
|
||||
if !episodeNameUseful(ep.Name) && episodeNameUseful(detailEN.Episodes[i].Name) {
|
||||
detailCN.Episodes[i].Name = detailEN.Episodes[i].Name
|
||||
detailCN.Episodes[i].Overview = detailEN.Episodes[i].Overview
|
||||
}
|
||||
@@ -184,6 +209,11 @@ func (c *Client) GetTVAlternativeTitles(id int, language string) (*tmdb.TVAltern
|
||||
return c.tmdbClient.GetTVAlternativeTitles(id, withLangOption(language))
|
||||
}
|
||||
|
||||
func (c *Client) GetMovieAlternativeTitles(id int, language string) (*tmdb.MovieAlternativeTitles, error) {
|
||||
return c.tmdbClient.GetMovieAlternativeTitles(id, withLangOption(language))
|
||||
}
|
||||
|
||||
|
||||
func wrapLanguage(lang string) string {
|
||||
if lang == "" {
|
||||
lang = "zh-CN"
|
||||
@@ -191,6 +221,11 @@ func wrapLanguage(lang string) string {
|
||||
return lang
|
||||
}
|
||||
|
||||
func withExternalIDs(m map[string]string) map[string]string {
|
||||
m["append_to_response"] = "external_ids"
|
||||
return m
|
||||
}
|
||||
|
||||
func withLangOption(language string) map[string]string {
|
||||
language = wrapLanguage(language)
|
||||
return map[string]string{
|
||||
@@ -198,7 +233,6 @@ func withLangOption(language string) map[string]string {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func episodeNameUseful(name string) bool {
|
||||
return !strings.HasSuffix(name, "集") && !strings.HasPrefix(strings.ToLower(name), "episode")
|
||||
}
|
||||
}
|
||||
|
||||
8
pkg/torznab/cache.go
Normal file
8
pkg/torznab/cache.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package torznab
|
||||
|
||||
import (
|
||||
"polaris/pkg/cache"
|
||||
"time"
|
||||
)
|
||||
|
||||
var cc = cache.NewCache[string, *Response](time.Minute * 30)
|
||||
@@ -3,10 +3,13 @@ package torznab
|
||||
import (
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"polaris/db"
|
||||
"polaris/log"
|
||||
"slices"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
@@ -71,17 +74,26 @@ func (i *Item) GetAttr(key string) string {
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func (r *Response) ToResults() []Result {
|
||||
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,
|
||||
Size: mustAtoI(item.Size),
|
||||
Seeders: mustAtoI(item.GetAttr("seeders")),
|
||||
Peers: mustAtoI(item.GetAttr("peers")),
|
||||
Category: mustAtoI(item.GetAttr("category")),
|
||||
Source: r.Channel.Title,
|
||||
Name: item.Title,
|
||||
Link: item.Link,
|
||||
Size: mustAtoI(item.Size),
|
||||
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,
|
||||
IndexerId: indexer.ID,
|
||||
Priority: indexer.Priority,
|
||||
IsPrivate: item.Type == "private",
|
||||
}
|
||||
res = append(res, r)
|
||||
}
|
||||
@@ -96,20 +108,45 @@ func mustAtoI(key string) int {
|
||||
}
|
||||
return i
|
||||
}
|
||||
func Search(torznabUrl, api, keyWord string) ([]Result, error) {
|
||||
|
||||
func tryParseFloat(s string) float32 {
|
||||
r, err := strconv.ParseFloat(s, 32)
|
||||
if err != nil {
|
||||
log.Warnf("parse float error: %v", err)
|
||||
return 0
|
||||
}
|
||||
return float32(r)
|
||||
}
|
||||
|
||||
func Search(indexer *db.TorznabInfo, keyWord string) ([]Result, error) {
|
||||
ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, torznabUrl, nil)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, indexer.URL, nil)
|
||||
if err != nil {
|
||||
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")
|
||||
@@ -122,17 +159,23 @@ func Search(torznabUrl, 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(), nil
|
||||
return &res, nil
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
Name string
|
||||
Link string
|
||||
Size int
|
||||
Seeders int
|
||||
Peers int
|
||||
Category int
|
||||
Source string
|
||||
Name string `json:"name"`
|
||||
Link string `json:"link"`
|
||||
Size int `json:"size"`
|
||||
Seeders int `json:"seeders"`
|
||||
Peers int `json:"peers"`
|
||||
Category int `json:"category"`
|
||||
Source string `json:"source"`
|
||||
DownloadVolumeFactor float32 `json:"download_volume_factor"`
|
||||
UploadVolumeFactor float32 `json:"upload_volume_factor"`
|
||||
IndexerId int `json:"indexer_id"`
|
||||
Priority int `json:"priority"`
|
||||
IsPrivate bool `json:"is_private"`
|
||||
ImdbId string `json:"imdb_id"`
|
||||
}
|
||||
|
||||
@@ -130,6 +130,9 @@ func (t *Torrent) Exists() bool {
|
||||
}
|
||||
|
||||
func (t *Torrent) Name() string {
|
||||
if !t.Exists() {
|
||||
return ""
|
||||
}
|
||||
return *t.getTorrent().Name
|
||||
}
|
||||
|
||||
@@ -155,6 +158,10 @@ func (t *Torrent) Stop() error {
|
||||
return t.c.TorrentStopIDs(context.TODO(), []int64{t.ID})
|
||||
}
|
||||
|
||||
func (t *Torrent) SeedRatio() *float64 {
|
||||
return t.getTorrent().UploadRatio
|
||||
}
|
||||
|
||||
func (t *Torrent) Start() error {
|
||||
return t.c.TorrentStartIDs(context.TODO(), []int64{t.ID})
|
||||
}
|
||||
|
||||
@@ -7,8 +7,6 @@ import (
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/adrg/strutil"
|
||||
"github.com/adrg/strutil/metrics"
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"golang.org/x/exp/rand"
|
||||
@@ -65,7 +63,7 @@ func IsNameAcceptable(name1, name2 string) bool {
|
||||
if strings.Contains(name1, name2) || strings.Contains(name2, name1) {
|
||||
return true
|
||||
}
|
||||
return strutil.Similarity(name1, name2, metrics.NewHamming()) > 0.4
|
||||
return false
|
||||
}
|
||||
|
||||
func FindSeasonEpisodeNum(name string) (se int, ep int, err error) {
|
||||
@@ -112,21 +110,6 @@ func FindSeasonPackageInfo(name string) (se int, err error) {
|
||||
return se, err
|
||||
}
|
||||
|
||||
func IsSeasonPackageName(name string) bool {
|
||||
seRe := regexp.MustCompile(`S\d+`)
|
||||
epRe := regexp.MustCompile(`E\d+`)
|
||||
nameUpper := strings.ToUpper(name)
|
||||
matchEp := epRe.FindAllString(nameUpper, -1)
|
||||
if len(matchEp) != 0 {
|
||||
return false //episode number should not exist
|
||||
}
|
||||
matchSe := seRe.FindAllString(nameUpper, -1)
|
||||
if len(matchSe) == 0 {
|
||||
return false //no season num
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func ContainsIgnoreCase(s, substr string) bool {
|
||||
return strings.Contains(strings.ToLower(s), strings.ToLower(substr))
|
||||
}
|
||||
|
||||
@@ -15,31 +15,41 @@ import (
|
||||
|
||||
type Activity struct {
|
||||
*ent.History
|
||||
Progress int `json:"progress"`
|
||||
Progress int `json:"progress"`
|
||||
SeedRatio float32 `json:"seed_ratio"`
|
||||
}
|
||||
|
||||
func (s *Server) GetAllActivities(c *gin.Context) (interface{}, error) {
|
||||
q := c.Query("status")
|
||||
his := s.db.GetHistories()
|
||||
var activities = make([]Activity, 0, len(his))
|
||||
for _, h := range his {
|
||||
if q == "active" && (h.Status != history.StatusRunning && h.Status != history.StatusUploading) {
|
||||
continue //active downloads
|
||||
} else if q == "archive" && (h.Status == history.StatusRunning || h.Status == history.StatusUploading) {
|
||||
continue //archived downloads
|
||||
}
|
||||
|
||||
a := Activity{
|
||||
History: h,
|
||||
}
|
||||
for id, task := range s.tasks {
|
||||
if h.ID == id && task.Exists() {
|
||||
a.Progress = task.Progress()
|
||||
var activities = make([]Activity, 0)
|
||||
if q == "active" {
|
||||
his := s.db.GetRunningHistories()
|
||||
for _, h := range his {
|
||||
a := Activity{
|
||||
History: h,
|
||||
}
|
||||
for id, task := range s.core.GetTasks() {
|
||||
if h.ID == id && task.Exists() {
|
||||
a.Progress = task.Progress()
|
||||
a.SeedRatio = float32(*task.SeedRatio())
|
||||
}
|
||||
}
|
||||
activities = append(activities, a)
|
||||
}
|
||||
activities = append(activities, a)
|
||||
}
|
||||
} else {
|
||||
his := s.db.GetHistories()
|
||||
for _, h := range his {
|
||||
if h.Status == history.StatusRunning || h.Status == history.StatusUploading || h.Status == history.StatusSeeding {
|
||||
continue //archived downloads
|
||||
}
|
||||
|
||||
a := Activity{
|
||||
History: h,
|
||||
}
|
||||
activities = append(activities, a)
|
||||
}
|
||||
|
||||
}
|
||||
return activities, nil
|
||||
}
|
||||
|
||||
@@ -54,15 +64,15 @@ func (s *Server) RemoveActivity(c *gin.Context) (interface{}, error) {
|
||||
log.Errorf("no record of id: %d", id)
|
||||
return nil, nil
|
||||
}
|
||||
torrent := s.tasks[his.ID]
|
||||
if torrent != nil {
|
||||
if err := torrent.Remove(); err != nil {
|
||||
return nil, errors.Wrap(err, "remove torrent")
|
||||
}
|
||||
delete(s.tasks, his.ID)
|
||||
|
||||
if err := s.core.RemoveTaskAndTorrent(his.ID); err != nil {
|
||||
return nil, errors.Wrap(err, "remove torrent")
|
||||
}
|
||||
|
||||
if his.EpisodeID != 0 {
|
||||
s.db.SetEpisodeStatus(his.EpisodeID, episode.StatusMissing)
|
||||
if his.Status == history.StatusRunning || his.Status == history.StatusUploading {
|
||||
s.db.SetEpisodeStatus(his.EpisodeID, episode.StatusMissing)
|
||||
}
|
||||
|
||||
} else {
|
||||
seasonNum, err := utils.SeasonId(his.TargetDir)
|
||||
@@ -70,8 +80,9 @@ func (s *Server) RemoveActivity(c *gin.Context) (interface{}, error) {
|
||||
log.Errorf("no season id: %v", his.TargetDir)
|
||||
seasonNum = -1
|
||||
}
|
||||
s.db.SetSeasonAllEpisodeStatus(his.MediaID, seasonNum, episode.StatusMissing)
|
||||
|
||||
if his.Status == history.StatusRunning || his.Status == history.StatusUploading {
|
||||
s.db.SetSeasonAllEpisodeStatus(his.MediaID, seasonNum, episode.StatusMissing)
|
||||
}
|
||||
}
|
||||
|
||||
err = s.db.DeleteHistory(id)
|
||||
@@ -96,13 +107,13 @@ func (s *Server) GetMediaDownloadHistory(c *gin.Context) (interface{}, error) {
|
||||
|
||||
type TorrentInfo struct {
|
||||
Name string `json:"name"`
|
||||
ID int64 `json:"id"`
|
||||
ID int64 `json:"id"`
|
||||
SeedRatio float32 `json:"seed_ratio"`
|
||||
Progress int `json:"progress"`
|
||||
}
|
||||
|
||||
func (s *Server) GetAllTorrents(c *gin.Context) (interface{}, error) {
|
||||
trc, err := s.getDownloadClient()
|
||||
trc, _, err := s.getDownloadClient()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "connect transmission")
|
||||
}
|
||||
@@ -116,8 +127,8 @@ func (s *Server) GetAllTorrents(c *gin.Context) (interface{}, error) {
|
||||
continue
|
||||
}
|
||||
infos = append(infos, TorrentInfo{
|
||||
Name: t.Name(),
|
||||
ID: t.ID,
|
||||
Name: t.Name(),
|
||||
ID: t.ID,
|
||||
Progress: t.Progress(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ func HttpHandler(f func(*gin.Context) (interface{}, error)) gin.HandlerFunc {
|
||||
})
|
||||
return
|
||||
}
|
||||
log.Debug("url %v return: %+v", ctx.Request.URL, r)
|
||||
log.Debugf("url %v return: %+v", ctx.Request.URL, r)
|
||||
|
||||
ctx.JSON(200, Response{
|
||||
Code: 0,
|
||||
|
||||
95
server/core/client.go
Normal file
95
server/core/client.go
Normal file
@@ -0,0 +1,95 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"polaris/db"
|
||||
"polaris/ent"
|
||||
"polaris/log"
|
||||
"polaris/pkg/tmdb"
|
||||
"polaris/pkg/transmission"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/robfig/cron"
|
||||
)
|
||||
|
||||
func NewClient(db *db.Client, language string) *Client {
|
||||
return &Client{
|
||||
db: db,
|
||||
cron: cron.New(),
|
||||
tasks: make(map[int]*Task, 0),
|
||||
language: language,
|
||||
}
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
db *db.Client
|
||||
cron *cron.Cron
|
||||
tasks map[int]*Task
|
||||
language string
|
||||
}
|
||||
|
||||
func (c *Client) Init() {
|
||||
c.reloadTasks()
|
||||
c.addSysCron()
|
||||
}
|
||||
|
||||
func (c *Client) reloadTasks() {
|
||||
allTasks := c.db.GetRunningHistories()
|
||||
for _, t := range allTasks {
|
||||
torrent, err := transmission.ReloadTorrent(t.Saved)
|
||||
if err != nil {
|
||||
log.Errorf("relaod task %s failed: %v", t.SourceTitle, err)
|
||||
continue
|
||||
}
|
||||
if !torrent.Exists() { //只要种子还存在于客户端中,就重新加载,有可能是还在做种中
|
||||
continue
|
||||
}
|
||||
log.Infof("reloading task: %d %s", t.ID, t.SourceTitle)
|
||||
c.tasks[t.ID] = &Task{Torrent: torrent}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) getDownloadClient() (*transmission.Client, *ent.DownloadClients, error) {
|
||||
tr := c.db.GetTransmission()
|
||||
trc, err := transmission.NewClient(transmission.Config{
|
||||
URL: tr.URL,
|
||||
User: tr.User,
|
||||
Password: tr.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, errors.Wrap(err, "connect transmission")
|
||||
}
|
||||
return trc, tr, nil
|
||||
}
|
||||
|
||||
func (c *Client) TMDB() (*tmdb.Client, error) {
|
||||
api := c.db.GetSetting(db.SettingTmdbApiKey)
|
||||
if api == "" {
|
||||
return nil, errors.New("TMDB apiKey not set")
|
||||
}
|
||||
proxy := c.db.GetSetting(db.SettingProxy)
|
||||
adult := c.db.GetSetting(db.SettingEnableTmdbAdultContent)
|
||||
return tmdb.NewClient(api, proxy, adult == "true")
|
||||
}
|
||||
|
||||
func (c *Client) MustTMDB() *tmdb.Client {
|
||||
t, err := c.TMDB()
|
||||
if err != nil {
|
||||
log.Panicf("get tmdb: %v", err)
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func (c *Client) RemoveTaskAndTorrent(id int) error {
|
||||
torrent := c.tasks[id]
|
||||
if torrent != nil {
|
||||
if err := torrent.Remove(); err != nil {
|
||||
return errors.Wrap(err, "remove torrent")
|
||||
}
|
||||
delete(c.tasks, id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) GetTasks() map[int]*Task {
|
||||
return c.tasks
|
||||
}
|
||||
312
server/core/integration.go
Normal file
312
server/core/integration.go
Normal file
@@ -0,0 +1,312 @@
|
||||
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"
|
||||
"polaris/pkg/utils"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
his := c.db.GetHistory(historyId)
|
||||
|
||||
series, err := c.db.GetMedia(his.MediaID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if series.MediaType != media.MediaTypeTv { //.plexmatch only support tv series
|
||||
return nil
|
||||
}
|
||||
st, err := c.getStorage(series.StorageID, media.MediaTypeTv)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "get storage")
|
||||
}
|
||||
|
||||
//series plexmatch file
|
||||
_, 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"), buff.Bytes()); err != nil {
|
||||
return errors.Wrap(err, "series plexmatch")
|
||||
}
|
||||
}
|
||||
|
||||
buff := bytes.Buffer{}
|
||||
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)
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
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
|
||||
if mediaType == media.MediaTypeMovie {
|
||||
targetPath = st.MoviePath
|
||||
}
|
||||
|
||||
switch st.Implementation {
|
||||
case storage1.ImplementationLocal:
|
||||
|
||||
storageImpl1, err := storage.NewLocalStorage(targetPath)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "new local")
|
||||
}
|
||||
return storageImpl1, nil
|
||||
|
||||
case storage1.ImplementationWebdav:
|
||||
ws := st.ToWebDavSetting()
|
||||
storageImpl1, err := storage.NewWebdavStorage(ws.URL, ws.User, ws.Password, targetPath, ws.ChangeFileHash == "true")
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "new webdav")
|
||||
}
|
||||
return storageImpl1, nil
|
||||
}
|
||||
return nil, errors.New("no storage found")
|
||||
}
|
||||
|
||||
func (c *Client) sendMsg(msg string) {
|
||||
clients, err := c.db.GetAllNotificationClients2()
|
||||
if err != nil {
|
||||
log.Errorf("query notification clients: %v", err)
|
||||
return
|
||||
}
|
||||
for _, cl := range clients {
|
||||
if !cl.Enabled {
|
||||
continue
|
||||
}
|
||||
handler, ok := notifier.Gethandler(cl.Service)
|
||||
if !ok {
|
||||
log.Errorf("no notification implementation of service %s", cl.Service)
|
||||
continue
|
||||
}
|
||||
noCl, err := handler(cl.Settings)
|
||||
if err != nil {
|
||||
log.Errorf("handle setting for name %s error: %v", cl.Name, err)
|
||||
continue
|
||||
}
|
||||
err = noCl.SendMsg(msg)
|
||||
if err != nil {
|
||||
log.Errorf("send message error: %v", err)
|
||||
continue
|
||||
}
|
||||
log.Debugf("send message to %s success, msg is %s", cl.Name, msg)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) findEpisodeFilesPreMoving(historyId int) error {
|
||||
his := c.db.GetHistory(historyId)
|
||||
|
||||
isSingleEpisode := his.EpisodeID > 0
|
||||
downloadDir := c.db.GetDownloadDir()
|
||||
task := c.tasks[historyId]
|
||||
target := filepath.Join(downloadDir, task.Name())
|
||||
fi, err := os.Stat(target)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "read dir %v", target)
|
||||
}
|
||||
if isSingleEpisode {
|
||||
if fi.IsDir() {
|
||||
//download single episode in dir
|
||||
//TODO
|
||||
} else {
|
||||
//is file
|
||||
if err := c.db.UpdateEpisodeTargetFile(his.EpisodeID, fi.Name()); err != nil {
|
||||
log.Errorf("writing downloaded file name to db error: %v", err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if !fi.IsDir() {
|
||||
return fmt.Errorf("not season pack downloaded")
|
||||
}
|
||||
seasonNum, err := utils.SeasonId(his.TargetDir)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "no season id")
|
||||
}
|
||||
|
||||
files, err := os.ReadDir(target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, f := range files {
|
||||
if f.IsDir() { //want media file
|
||||
continue
|
||||
}
|
||||
excludedExt := []string{".txt", ".srt", ".ass", ".sub"}
|
||||
ext := filepath.Ext(f.Name())
|
||||
if slices.Contains(excludedExt, strings.ToLower(ext)) {
|
||||
continue
|
||||
}
|
||||
|
||||
meta := metadata.ParseTv(f.Name())
|
||||
if meta.Episode > 0 {
|
||||
//episode exists
|
||||
ep, err := c.db.GetEpisode(his.MediaID, seasonNum, meta.Episode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := c.db.UpdateEpisodeTargetFile(ep.ID, f.Name()); err != nil {
|
||||
return errors.Wrap(err, "update episode file")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
253
server/core/nfo.go
Normal file
253
server/core/nfo.go
Normal 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"`
|
||||
}
|
||||
148
server/core/resources.go
Normal file
148
server/core/resources.go
Normal file
@@ -0,0 +1,148 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"polaris/ent"
|
||||
"polaris/ent/episode"
|
||||
"polaris/ent/history"
|
||||
"polaris/log"
|
||||
"polaris/pkg/notifier/message"
|
||||
"polaris/pkg/torznab"
|
||||
"polaris/pkg/utils"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func (c *Client) DownloadEpisodeTorrent(r1 torznab.Result, seriesId, seasonNum, episodeNum int) (*string, error) {
|
||||
trc, dlc, err := c.getDownloadClient()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "connect transmission")
|
||||
}
|
||||
series := c.db.GetMediaDetails(seriesId)
|
||||
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
|
||||
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{}
|
||||
}
|
||||
torrent, err := trc.Download(r1.Link, downloadDir)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "downloading")
|
||||
}
|
||||
torrent.Start()
|
||||
|
||||
dir := fmt.Sprintf("%s/Season %02d/", series.TargetDir, seasonNum)
|
||||
|
||||
history, err := c.db.SaveHistoryRecord(ent.History{
|
||||
MediaID: seriesId,
|
||||
EpisodeID: ep.ID,
|
||||
SourceTitle: r1.Name,
|
||||
TargetDir: dir,
|
||||
Status: history.StatusRunning,
|
||||
Size: r1.Size,
|
||||
Saved: torrent.Save(),
|
||||
DownloadClientID: dlc.ID,
|
||||
IndexerID: r1.IndexerId,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "save record")
|
||||
}
|
||||
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))
|
||||
|
||||
log.Infof("success add %s to download task", r1.Name)
|
||||
return &r1.Name, nil
|
||||
|
||||
}
|
||||
func (c *Client) SearchAndDownload(seriesId, seasonNum, episodeNum int) (*string, error) {
|
||||
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
|
||||
}
|
||||
r1 := res[0]
|
||||
log.Infof("found resource to download: %+v", r1)
|
||||
return c.DownloadEpisodeTorrent(r1, seriesId, seasonNum, episodeNum)
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
torrent, err := trc.Download(link, c.db.GetDownloadDir())
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "downloading")
|
||||
}
|
||||
torrent.Start()
|
||||
|
||||
if name == "" {
|
||||
name = m.OriginalName
|
||||
}
|
||||
go func() {
|
||||
ep, _ := c.db.GetMovieDummyEpisode(m.ID)
|
||||
history, err := c.db.SaveHistoryRecord(ent.History{
|
||||
MediaID: m.ID,
|
||||
EpisodeID: ep.ID,
|
||||
SourceTitle: name,
|
||||
TargetDir: m.TargetDir,
|
||||
Status: history.StatusRunning,
|
||||
Size: size,
|
||||
Saved: torrent.Save(),
|
||||
DownloadClientID: dlc.ID,
|
||||
IndexerID: indexerID,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorf("save history error: %v", err)
|
||||
}
|
||||
|
||||
c.tasks[history.ID] = &Task{Torrent: torrent}
|
||||
|
||||
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
|
||||
|
||||
}
|
||||
418
server/core/scheduler.go
Normal file
418
server/core/scheduler.go
Normal file
@@ -0,0 +1,418 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"polaris/db"
|
||||
"polaris/ent"
|
||||
"polaris/ent/episode"
|
||||
"polaris/ent/history"
|
||||
"polaris/ent/media"
|
||||
"polaris/log"
|
||||
"polaris/pkg"
|
||||
"polaris/pkg/notifier/message"
|
||||
"polaris/pkg/utils"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func (c *Client) addSysCron() {
|
||||
c.mustAddCron("@every 1m", c.checkTasks)
|
||||
c.mustAddCron("0 0 * * * *", func() {
|
||||
c.downloadAllTvSeries()
|
||||
c.downloadAllMovies()
|
||||
})
|
||||
c.mustAddCron("0 0 */12 * * *", c.checkAllSeriesNewSeason)
|
||||
c.cron.Start()
|
||||
}
|
||||
|
||||
func (c *Client) mustAddCron(spec string, cmd func()) {
|
||||
if err := c.cron.AddFunc(spec, cmd); err != nil {
|
||||
log.Errorf("add func error: %v", err)
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) checkTasks() {
|
||||
log.Debug("begin check tasks...")
|
||||
for id, t := range c.tasks {
|
||||
r := c.db.GetHistory(id)
|
||||
if !t.Exists() {
|
||||
log.Infof("task no longer exists: %v", id)
|
||||
|
||||
delete(c.tasks, id)
|
||||
continue
|
||||
}
|
||||
log.Infof("task (%s) percentage done: %d%%", t.Name(), t.Progress())
|
||||
if t.Progress() == 100 {
|
||||
|
||||
if r.Status == history.StatusSeeding {
|
||||
//task already success, check seed ratio
|
||||
torrent := c.tasks[id]
|
||||
ok := c.isSeedRatioLimitReached(r.IndexerID, torrent)
|
||||
if ok {
|
||||
log.Infof("torrent file seed ratio reached, remove: %v, current seed ratio: %v", torrent.Name(), *torrent.SeedRatio())
|
||||
torrent.Remove()
|
||||
delete(c.tasks, id)
|
||||
} else {
|
||||
log.Infof("torrent file still sedding: %v, current seed ratio: %v", torrent.Name(), *torrent.SeedRatio())
|
||||
}
|
||||
continue
|
||||
}
|
||||
log.Infof("task is done: %v", t.Name())
|
||||
c.sendMsg(fmt.Sprintf(message.DownloadComplete, t.Name()))
|
||||
|
||||
go c.postTaskProcessing(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) postTaskProcessing(id int) {
|
||||
if err := c.findEpisodeFilesPreMoving(id); err != nil {
|
||||
log.Errorf("finding all episode file error: %v", err)
|
||||
} else {
|
||||
if err := c.writePlexmatch(id); err != nil {
|
||||
log.Errorf("write plexmatch file error: %v", err)
|
||||
}
|
||||
if err := c.writeNfoFile(id); err != nil {
|
||||
log.Errorf("write nfo file error: %v", err)
|
||||
}
|
||||
}
|
||||
if err := c.moveCompletedTask(id); err != nil {
|
||||
log.Infof("post tasks for id %v fail: %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) moveCompletedTask(id int) (err1 error) {
|
||||
torrent := c.tasks[id]
|
||||
r := c.db.GetHistory(id)
|
||||
if r.Status == history.StatusUploading {
|
||||
log.Infof("task %d is already uploading, skip", id)
|
||||
return nil
|
||||
}
|
||||
c.db.SetHistoryStatus(r.ID, history.StatusUploading)
|
||||
seasonNum, err := utils.SeasonId(r.TargetDir)
|
||||
if err != nil {
|
||||
log.Errorf("no season id: %v", r.TargetDir)
|
||||
seasonNum = -1
|
||||
}
|
||||
downloadclient, err := c.db.GetDownloadClient(r.DownloadClientID)
|
||||
if err != nil {
|
||||
log.Errorf("get task download client error: %v, use default one", err)
|
||||
downloadclient = &ent.DownloadClients{RemoveCompletedDownloads: true, RemoveFailedDownloads: true}
|
||||
}
|
||||
torrentName := torrent.Name()
|
||||
|
||||
defer func() {
|
||||
|
||||
if err1 != nil {
|
||||
c.db.SetHistoryStatus(r.ID, history.StatusFail)
|
||||
if r.EpisodeID != 0 {
|
||||
c.db.SetEpisodeStatus(r.EpisodeID, episode.StatusMissing)
|
||||
} else {
|
||||
c.db.SetSeasonAllEpisodeStatus(r.MediaID, seasonNum, episode.StatusMissing)
|
||||
}
|
||||
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)
|
||||
torrent.Remove()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
series := c.db.GetMediaDetails(r.MediaID)
|
||||
if series == nil {
|
||||
return nil
|
||||
}
|
||||
st := c.db.GetStorage(series.StorageID)
|
||||
log.Infof("move task files to target dir: %v", r.TargetDir)
|
||||
stImpl, err := c.getStorage(st.ID, series.MediaType)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
//如果种子是路径,则会把路径展开,只移动文件,类似 move dir/* dir2/, 如果种子是文件,则会直接移动文件,类似 move file dir/
|
||||
if err := stImpl.Copy(filepath.Join(c.db.GetDownloadDir(), torrentName), r.TargetDir); err != nil {
|
||||
return errors.Wrap(err, "move file")
|
||||
}
|
||||
|
||||
c.db.SetHistoryStatus(r.ID, history.StatusSeeding)
|
||||
if r.EpisodeID != 0 {
|
||||
c.db.SetEpisodeStatus(r.EpisodeID, episode.StatusDownloaded)
|
||||
} else {
|
||||
c.db.SetSeasonAllEpisodeStatus(r.MediaID, seasonNum, episode.StatusDownloaded)
|
||||
}
|
||||
c.sendMsg(fmt.Sprintf(message.ProcessingComplete, torrentName))
|
||||
|
||||
//判断是否需要删除本地文件
|
||||
ok := c.isSeedRatioLimitReached(r.IndexerID, torrent)
|
||||
if downloadclient.RemoveCompletedDownloads && ok {
|
||||
log.Debugf("download complete,remove torrent and files related, torrent: %v, seed ratio: %v", torrentName, *torrent.SeedRatio())
|
||||
c.db.SetHistoryStatus(r.ID, history.StatusSuccess)
|
||||
delete(c.tasks, r.ID)
|
||||
torrent.Remove()
|
||||
}
|
||||
|
||||
log.Infof("move downloaded files to target dir success, file: %v, target dir: %v", torrentName, r.TargetDir)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) CheckDownloadedSeriesFiles(m *ent.Media) error {
|
||||
if m.MediaType != media.MediaTypeTv {
|
||||
return nil
|
||||
}
|
||||
log.Infof("check files in directory: %s", m.TargetDir)
|
||||
|
||||
var storageImpl, err = c.getStorage(m.StorageID, media.MediaTypeTv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
files, err := storageImpl.ReadDir(m.TargetDir)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "read dir %s", m.TargetDir)
|
||||
}
|
||||
|
||||
for _, in := range files {
|
||||
if !in.IsDir() { //season dir, ignore file
|
||||
continue
|
||||
}
|
||||
dir := filepath.Join(m.TargetDir, in.Name())
|
||||
epFiles, err := storageImpl.ReadDir(dir)
|
||||
if err != nil {
|
||||
log.Errorf("read dir %s error: %v", dir, err)
|
||||
continue
|
||||
}
|
||||
for _, ep := range epFiles {
|
||||
log.Infof("found file: %v", ep.Name())
|
||||
seNum, epNum, err := utils.FindSeasonEpisodeNum(ep.Name())
|
||||
if err != nil {
|
||||
log.Errorf("find season episode num error: %v", err)
|
||||
continue
|
||||
}
|
||||
log.Infof("found match, season num %d, episode num %d", seNum, epNum)
|
||||
ep, err := c.db.GetEpisode(m.ID, seNum, epNum)
|
||||
if err != nil {
|
||||
log.Error("update episode: %v", err)
|
||||
continue
|
||||
}
|
||||
err = c.db.SetEpisodeStatus(ep.ID, episode.StatusDownloaded)
|
||||
if err != nil {
|
||||
log.Error("update episode: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
type Task struct {
|
||||
//Processing bool
|
||||
pkg.Torrent
|
||||
}
|
||||
|
||||
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 !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) 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 {
|
||||
if _, err := c.DownloadMovieByID(series.ID); err != nil {
|
||||
log.Errorf("download movie error: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
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")
|
||||
}
|
||||
torrent.Start()
|
||||
|
||||
history, err := c.db.SaveHistoryRecord(ent.History{
|
||||
MediaID: ep.MediaID,
|
||||
EpisodeID: ep.ID,
|
||||
SourceTitle: r1.Name,
|
||||
TargetDir: targetDir,
|
||||
Status: history.StatusRunning,
|
||||
Size: r1.Size,
|
||||
Saved: torrent.Save(),
|
||||
DownloadClientID: dlc.ID,
|
||||
IndexerID: r1.IndexerId,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorf("save history error: %v", err)
|
||||
}
|
||||
|
||||
c.tasks[history.ID] = &Task{Torrent: torrent}
|
||||
|
||||
c.db.SetEpisodeStatus(ep.ID, episode.StatusDownloading)
|
||||
return r1.Name, nil
|
||||
}
|
||||
|
||||
func (c *Client) checkAllSeriesNewSeason() {
|
||||
log.Infof("begin checking series all new season")
|
||||
allSeries := c.db.GetMediaWatchlist(media.MediaTypeTv)
|
||||
for _, series := range allSeries {
|
||||
err := c.checkSeiesNewSeason(series)
|
||||
if err != nil {
|
||||
log.Errorf("check series new season error: series name %v, error: %v", series.NameEn, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) checkSeiesNewSeason(media *ent.Media) error {
|
||||
d, err := c.MustTMDB().GetTvDetails(media.TmdbID, c.language)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "tmdb")
|
||||
}
|
||||
lastsSason := d.NumberOfSeasons
|
||||
seasonDetail, err := c.MustTMDB().GetSeasonDetails(media.TmdbID, lastsSason, c.language)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "tmdb season")
|
||||
}
|
||||
|
||||
for _, ep := range seasonDetail.Episodes {
|
||||
epDb, err := c.db.GetEpisode(media.ID, ep.SeasonNumber, ep.EpisodeNumber)
|
||||
if err != nil {
|
||||
if ent.IsNotFound(err) {
|
||||
log.Infof("add new episode: %+v", ep)
|
||||
episode := &ent.Episode{
|
||||
MediaID: media.ID,
|
||||
SeasonNumber: ep.SeasonNumber,
|
||||
EpisodeNumber: ep.EpisodeNumber,
|
||||
Title: ep.Name,
|
||||
Overview: ep.Overview,
|
||||
AirDate: ep.AirDate,
|
||||
Status: episode.StatusMissing,
|
||||
Monitored: true,
|
||||
}
|
||||
c.db.SaveEposideDetail2(episode)
|
||||
}
|
||||
} else { //update episode
|
||||
if ep.Name != epDb.Title || ep.Overview != epDb.Overview || ep.AirDate != epDb.AirDate {
|
||||
log.Infof("update new episode: %+v", ep)
|
||||
c.db.UpdateEpiode2(epDb.ID, ep.Name, ep.Overview, ep.AirDate)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) isSeedRatioLimitReached(indexId int, t pkg.Torrent) bool {
|
||||
indexer, err := c.db.GetIndexer(indexId)
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
currentRatio := t.SeedRatio()
|
||||
if currentRatio == nil {
|
||||
log.Warnf("get current seed ratio error, current ratio is nil")
|
||||
return indexer.SeedRatio == 0
|
||||
}
|
||||
return *currentRatio >= float64(indexer.SeedRatio)
|
||||
}
|
||||
@@ -3,10 +3,12 @@ package core
|
||||
import (
|
||||
"fmt"
|
||||
"polaris/db"
|
||||
"polaris/ent/media"
|
||||
"polaris/log"
|
||||
"polaris/pkg/metadata"
|
||||
"polaris/pkg/torznab"
|
||||
"polaris/pkg/utils"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -15,11 +17,128 @@ import (
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func SearchSeasonPackage(db1 *db.Client, seriesId, seasonNum int, checkResolution bool) ([]torznab.Result, error) {
|
||||
return SearchEpisode(db1, seriesId, seasonNum, -1, checkResolution)
|
||||
type SearchParam struct {
|
||||
MediaId int
|
||||
SeasonNum int //for tv
|
||||
Episodes []int //for tv
|
||||
CheckResolution bool
|
||||
CheckFileSize bool
|
||||
FilterQiangban bool //for movie, 是否过滤枪版电影
|
||||
}
|
||||
|
||||
func isNumberedSeries(detail *db.MediaDetails) bool {
|
||||
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 {
|
||||
//log.Infof("torrent resource: %+v", r)
|
||||
meta := metadata.ParseTv(r.Name)
|
||||
if meta == nil { //cannot parse name
|
||||
continue
|
||||
}
|
||||
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 isNoSeasonSeries(series) && len(param.Episodes) == 0 {
|
||||
//should not want season
|
||||
continue
|
||||
}
|
||||
|
||||
if len(param.Episodes) > 0 && !slices.Contains(param.Episodes, meta.Episode) { //not season pack, but episode number not equal
|
||||
continue
|
||||
|
||||
} else if len(param.Episodes) == 0 && !meta.IsSeasonPack { //want season pack, but not season pack
|
||||
continue
|
||||
}
|
||||
if param.CheckResolution && meta.Resolution != series.Resolution.String() {
|
||||
continue
|
||||
}
|
||||
|
||||
if !torrentSizeOk(series, r.Size, param) {
|
||||
continue
|
||||
}
|
||||
|
||||
filtered = append(filtered, r)
|
||||
}
|
||||
if len(filtered) == 0 {
|
||||
return nil, errors.New("no resource found")
|
||||
}
|
||||
filtered = dedup(filtered)
|
||||
return filtered, nil
|
||||
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -34,64 +153,17 @@ func isNumberedSeries(detail *db.MediaDetails) bool {
|
||||
return hasSeason2 && !season2HasEpisode1 //only one 1st episode
|
||||
}
|
||||
|
||||
func SearchEpisode(db1 *db.Client, seriesId, seasonNum, episodeNum int, checkResolution bool) ([]torznab.Result, error) {
|
||||
series := db1.GetMediaDetails(seriesId)
|
||||
if series == nil {
|
||||
return nil, fmt.Errorf("no tv series of id %v", seriesId)
|
||||
}
|
||||
|
||||
res := searchWithTorznab(db1, series.NameEn)
|
||||
resCn := searchWithTorznab(db1, series.NameCn)
|
||||
res = append(res, resCn...)
|
||||
|
||||
var filtered []torznab.Result
|
||||
for _, r := range res {
|
||||
//log.Infof("torrent resource: %+v", r)
|
||||
meta := metadata.ParseTv(r.Name)
|
||||
if meta == nil { //cannot parse name
|
||||
continue
|
||||
}
|
||||
if !isNumberedSeries(series) { //do not check season on series that only rely on episode number
|
||||
if meta.Season != seasonNum {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if isNumberedSeries(series) && episodeNum == -1 {
|
||||
//should not want season
|
||||
continue
|
||||
}
|
||||
|
||||
if episodeNum != -1 && meta.Episode != episodeNum { //not season pack, episode number equals
|
||||
continue
|
||||
}else if episodeNum == -1 && !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) {
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, r)
|
||||
}
|
||||
if len(filtered) == 0 {
|
||||
return nil, errors.New("no resource found")
|
||||
}
|
||||
|
||||
return filtered, nil
|
||||
|
||||
}
|
||||
|
||||
func SearchMovie(db1 *db.Client, movieId int, checkResolution 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")
|
||||
@@ -99,15 +171,33 @@ func SearchMovie(db1 *db.Client, movieId int, checkResolution bool) ([]torznab.R
|
||||
var filtered []torznab.Result
|
||||
for _, r := range res {
|
||||
meta := metadata.ParseMovie(r.Name)
|
||||
if !utils.IsNameAcceptable(meta.NameEn, movieDetail.NameEn) {
|
||||
|
||||
if isImdbidNotMatch(movieDetail.ImdbID, r.ImdbId) { //imdb id not match
|
||||
continue
|
||||
}
|
||||
if checkResolution && meta.Resolution != movieDetail.Resolution.String() {
|
||||
|
||||
if !imdbIDMatchExact(movieDetail.ImdbID, r.ImdbId) {
|
||||
if !torrentNameOk(movieDetail, r.Name) {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if param.CheckResolution && meta.Resolution != movieDetail.Resolution.String() {
|
||||
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.FilterQiangban && meta.IsQingban { //过滤枪版电影
|
||||
continue
|
||||
}
|
||||
|
||||
if !torrentSizeOk(movieDetail, r.Size, param) {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -117,12 +207,13 @@ func SearchMovie(db1 *db.Client, movieId int, checkResolution bool) ([]torznab.R
|
||||
if len(filtered) == 0 {
|
||||
return nil, errors.New("no resource found")
|
||||
}
|
||||
filtered = dedup(filtered)
|
||||
|
||||
return filtered, nil
|
||||
|
||||
}
|
||||
|
||||
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()
|
||||
@@ -130,18 +221,24 @@ func searchWithTorznab(db *db.Client, q string) []torznab.Result {
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for _, tor := range allTorznab {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
log.Debugf("search torznab %v with %v", tor.Name, q)
|
||||
defer wg.Done()
|
||||
resp, err := torznab.Search(tor.URL, tor.ApiKey, q)
|
||||
if err != nil {
|
||||
log.Errorf("search %s error: %v", tor.Name, err)
|
||||
return
|
||||
}
|
||||
resChan <- resp
|
||||
if tor.Disabled {
|
||||
continue
|
||||
}
|
||||
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()
|
||||
@@ -152,11 +249,70 @@ func searchWithTorznab(db *db.Client, q string) []torznab.Result {
|
||||
res = append(res, result...)
|
||||
}
|
||||
|
||||
sort.Slice(res, func(i, j int) bool {
|
||||
res = dedup(res)
|
||||
|
||||
sort.SliceStable(res, func(i, j int) bool { //先按做种人数排序
|
||||
var s1 = res[i]
|
||||
var s2 = res[j]
|
||||
return s1.Seeders > s2.Seeders
|
||||
})
|
||||
|
||||
sort.SliceStable(res, func(i, j int) bool { //再按优先级排序,优先级高的种子排前面
|
||||
var s1 = res[i]
|
||||
var s2 = res[j]
|
||||
return s1.Priority > s2.Priority
|
||||
})
|
||||
|
||||
//pt资源中,同一indexer内部,优先下载free的资源
|
||||
sort.SliceStable(res, func(i, j int) bool {
|
||||
var s1 = res[i]
|
||||
var s2 = res[j]
|
||||
if s1.IndexerId == s2.IndexerId && s1.IsPrivate {
|
||||
return s1.DownloadVolumeFactor < s2.DownloadVolumeFactor
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
//同一indexer内部,如果下载消耗一样,则优先下载上传奖励较多的
|
||||
sort.SliceStable(res, func(i, j int) bool {
|
||||
var s1 = res[i]
|
||||
var s2 = res[j]
|
||||
if s1.IndexerId == s2.IndexerId && s1.IsPrivate && s1.DownloadVolumeFactor == s2.DownloadVolumeFactor {
|
||||
return s1.UploadVolumeFactor > s2.UploadVolumeFactor
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
func dedup(list []torznab.Result) []torznab.Result {
|
||||
var res = make([]torznab.Result, 0, len(list))
|
||||
seen := make(map[string]bool, 0)
|
||||
for _, r := range list {
|
||||
key := fmt.Sprintf("%s%s%d%d", r.Name, r.Source, r.Seeders, r.Peers)
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
res = append(res, r)
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -2,8 +2,6 @@ package server
|
||||
|
||||
import (
|
||||
"polaris/ent"
|
||||
"polaris/log"
|
||||
"polaris/pkg/notifier"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -44,32 +42,3 @@ func (s *Server) AddNotificationClient(c *gin.Context) (interface{}, error) {
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *Server) sendMsg(msg string) {
|
||||
clients, err := s.db.GetAllNotificationClients2()
|
||||
if err != nil {
|
||||
log.Errorf("query notification clients: %v", err)
|
||||
return
|
||||
}
|
||||
for _, cl := range clients {
|
||||
if !cl.Enabled {
|
||||
continue
|
||||
}
|
||||
handler, ok := notifier.Gethandler(cl.Service)
|
||||
if !ok {
|
||||
log.Errorf("no notification implementation of service %s", cl.Service)
|
||||
continue
|
||||
}
|
||||
noCl, err := handler(cl.Settings)
|
||||
if err != nil {
|
||||
log.Errorf("handle setting for name %s error: %v", cl.Name, err)
|
||||
continue
|
||||
}
|
||||
err = noCl.SendMsg(msg)
|
||||
if err != nil {
|
||||
log.Errorf("send message error: %v", err)
|
||||
continue
|
||||
}
|
||||
log.Debugf("send message to %s success, msg is %s", cl.Name, msg)
|
||||
}
|
||||
}
|
||||
@@ -2,15 +2,12 @@ package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"polaris/ent"
|
||||
"polaris/ent/episode"
|
||||
"polaris/ent/history"
|
||||
"polaris/db"
|
||||
"polaris/ent/media"
|
||||
"polaris/log"
|
||||
"polaris/pkg/notifier/message"
|
||||
"polaris/pkg/torznab"
|
||||
"polaris/pkg/utils"
|
||||
"polaris/server/core"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/pkg/errors"
|
||||
@@ -18,120 +15,23 @@ import (
|
||||
|
||||
func (s *Server) searchAndDownloadSeasonPackage(seriesId, seasonNum int) (*string, error) {
|
||||
|
||||
res, err := core.SearchSeasonPackage(s.db, seriesId, seasonNum, 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.downloadSeasonPackage(r1, seriesId, seasonNum)
|
||||
return s.core.DownloadEpisodeTorrent(r1, seriesId, seasonNum, -1)
|
||||
|
||||
}
|
||||
|
||||
func (s *Server) downloadSeasonPackage(r1 torznab.Result, seriesId, seasonNum int) (*string, error) {
|
||||
trc, err := s.getDownloadClient()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "connect transmission")
|
||||
}
|
||||
downloadDir := s.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, s.db.GetDownloadDir())
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "downloading")
|
||||
}
|
||||
torrent.Start()
|
||||
|
||||
series := s.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 := s.db.SaveHistoryRecord(ent.History{
|
||||
MediaID: seriesId,
|
||||
EpisodeID: 0,
|
||||
SourceTitle: r1.Name,
|
||||
TargetDir: dir,
|
||||
Status: history.StatusRunning,
|
||||
Size: r1.Size,
|
||||
Saved: torrent.Save(),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "save record")
|
||||
}
|
||||
s.db.SetSeasonAllEpisodeStatus(seriesId, seasonNum, episode.StatusDownloading)
|
||||
|
||||
s.tasks[history.ID] = &Task{Torrent: torrent}
|
||||
|
||||
s.sendMsg(fmt.Sprintf(message.BeginDownload, r1.Name))
|
||||
return &r1.Name, nil
|
||||
|
||||
}
|
||||
|
||||
func (s *Server) downloadEpisodeTorrent(r1 torznab.Result, seriesId, seasonNum, episodeNum int) (*string, error) {
|
||||
trc, err := s.getDownloadClient()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "connect transmission")
|
||||
}
|
||||
series := s.db.GetMediaDetails(seriesId)
|
||||
if series == nil {
|
||||
return nil, fmt.Errorf("no tv series of id %v", seriesId)
|
||||
}
|
||||
var ep *ent.Episode
|
||||
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)
|
||||
}
|
||||
torrent, err := trc.Download(r1.Link, s.db.GetDownloadDir())
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "downloading")
|
||||
}
|
||||
torrent.Start()
|
||||
|
||||
dir := fmt.Sprintf("%s/Season %02d/", series.TargetDir, seasonNum)
|
||||
|
||||
history, err := s.db.SaveHistoryRecord(ent.History{
|
||||
MediaID: ep.MediaID,
|
||||
EpisodeID: ep.ID,
|
||||
SourceTitle: r1.Name,
|
||||
TargetDir: dir,
|
||||
Status: history.StatusRunning,
|
||||
Size: r1.Size,
|
||||
Saved: torrent.Save(),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "save record")
|
||||
}
|
||||
s.db.SetEpisodeStatus(ep.ID, episode.StatusDownloading)
|
||||
|
||||
s.tasks[history.ID] = &Task{Torrent: torrent}
|
||||
s.sendMsg(fmt.Sprintf(message.BeginDownload, r1.Name))
|
||||
|
||||
log.Infof("success add %s to download task", r1.Name)
|
||||
return &r1.Name, nil
|
||||
|
||||
}
|
||||
func (s *Server) searchAndDownload(seriesId, seasonNum, episodeNum int) (*string, error) {
|
||||
|
||||
res, err := core.SearchEpisode(s.db, seriesId, seasonNum, episodeNum, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r1 := res[0]
|
||||
log.Infof("found resource to download: %+v", r1)
|
||||
return s.downloadEpisodeTorrent(r1, seriesId, seasonNum, episodeNum)
|
||||
}
|
||||
|
||||
type searchAndDownloadIn struct {
|
||||
ID int `json:"id" binding:"required"`
|
||||
Season int `json:"season"`
|
||||
@@ -154,16 +54,24 @@ 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.SearchSeasonPackage(s.db, in.ID, in.Season, 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.SearchEpisode(s.db, in.ID, in.Season, in.Episode, 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 []TorznabSearchResult{}, nil
|
||||
return []string{}, nil
|
||||
}
|
||||
return nil, errors.Wrap(err, "search episode")
|
||||
}
|
||||
@@ -171,25 +79,24 @@ 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)
|
||||
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 []TorznabSearchResult{}, nil
|
||||
return []string{}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
var searchResults []TorznabSearchResult
|
||||
for _, r := range res {
|
||||
searchResults = append(searchResults, TorznabSearchResult{
|
||||
Name: r.Name,
|
||||
Size: r.Size,
|
||||
Seeders: r.Seeders,
|
||||
Peers: r.Peers,
|
||||
Link: r.Link,
|
||||
})
|
||||
}
|
||||
return searchResults, nil
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (s *Server) SearchTvAndDownload(c *gin.Context) (interface{}, error) {
|
||||
@@ -209,7 +116,7 @@ func (s *Server) SearchTvAndDownload(c *gin.Context) (interface{}, error) {
|
||||
name = *name1
|
||||
} else {
|
||||
log.Infof("season episode search")
|
||||
name1, err := s.searchAndDownload(in.ID, in.Season, in.Episode)
|
||||
name1, err := s.core.SearchAndDownload(in.ID, in.Season, in.Episode)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "download")
|
||||
}
|
||||
@@ -221,19 +128,11 @@ func (s *Server) SearchTvAndDownload(c *gin.Context) (interface{}, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
type TorznabSearchResult struct {
|
||||
Name string `json:"name"`
|
||||
Size int `json:"size"`
|
||||
Link string `json:"link"`
|
||||
Seeders int `json:"seeders"`
|
||||
Peers int `json:"peers"`
|
||||
Source string `json:"source"`
|
||||
}
|
||||
type downloadTorrentIn struct {
|
||||
MediaID int `json:"id" binding:"required"`
|
||||
Season int `json:"season"`
|
||||
Episode int `json:"episode"`
|
||||
TorznabSearchResult
|
||||
torznab.Result
|
||||
}
|
||||
|
||||
func (s *Server) DownloadTorrent(c *gin.Context) (interface{}, error) {
|
||||
@@ -255,51 +154,35 @@ 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.downloadSeasonPackage(res, in.MediaID, in.Season)
|
||||
return s.core.DownloadEpisodeTorrent(res, in.MediaID, in.Season, -1)
|
||||
}
|
||||
name := in.Name
|
||||
if name == "" {
|
||||
name = fmt.Sprintf("%v S%02dE%02d", m.OriginalName, in.Season, in.Episode)
|
||||
}
|
||||
res := torznab.Result{Name: name, Link: in.Link, Size: in.Size}
|
||||
return s.downloadEpisodeTorrent(res, in.MediaID, in.Season, in.Episode)
|
||||
res := torznab.Result{Name: name, Link: in.Link, Size: in.Size, IndexerId: in.IndexerId}
|
||||
return s.core.DownloadEpisodeTorrent(res, in.MediaID, in.Season, in.Episode)
|
||||
} else {
|
||||
//movie
|
||||
return s.core.DownloadMovie(m, in.Link, in.Name, in.Size, in.IndexerId)
|
||||
}
|
||||
trc, err := s.getDownloadClient()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "connect transmission")
|
||||
}
|
||||
|
||||
torrent, err := trc.Download(in.Link, s.db.GetDownloadDir())
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "downloading")
|
||||
}
|
||||
torrent.Start()
|
||||
name := in.Name
|
||||
if name == "" {
|
||||
name = m.OriginalName
|
||||
}
|
||||
go func() {
|
||||
ep, _ := s.db.GetMovieDummyEpisode(m.ID)
|
||||
history, err := s.db.SaveHistoryRecord(ent.History{
|
||||
MediaID: m.ID,
|
||||
EpisodeID: ep.ID,
|
||||
SourceTitle: name,
|
||||
TargetDir: "./",
|
||||
Status: history.StatusRunning,
|
||||
Size: in.Size,
|
||||
Saved: torrent.Save(),
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorf("save history error: %v", err)
|
||||
}
|
||||
|
||||
s.tasks[history.ID] = &Task{Torrent: torrent}
|
||||
|
||||
s.db.SetEpisodeStatus(ep.ID, episode.StatusDownloading)
|
||||
}()
|
||||
|
||||
s.sendMsg(fmt.Sprintf(message.BeginDownload, in.Name))
|
||||
log.Infof("success add %s to download task", in.Name)
|
||||
return in.Name, nil
|
||||
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
@@ -1,359 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"polaris/ent"
|
||||
"polaris/ent/episode"
|
||||
"polaris/ent/history"
|
||||
"polaris/ent/media"
|
||||
storage1 "polaris/ent/storage"
|
||||
"polaris/log"
|
||||
"polaris/pkg"
|
||||
"polaris/pkg/notifier/message"
|
||||
"polaris/pkg/storage"
|
||||
"polaris/pkg/utils"
|
||||
"polaris/server/core"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func (s *Server) scheduler() {
|
||||
s.mustAddCron("@every 1m", s.checkTasks)
|
||||
s.mustAddCron("0 0 * * * *", func() {
|
||||
s.downloadTvSeries()
|
||||
s.downloadMovie()
|
||||
})
|
||||
s.mustAddCron("0 0 */12 * * *", s.checkAllSeriesNewSeason)
|
||||
s.cron.Start()
|
||||
}
|
||||
|
||||
func (s *Server) mustAddCron(spec string, cmd func()) {
|
||||
if err := s.cron.AddFunc(spec, cmd); err != nil {
|
||||
log.Errorf("add func error: %v", err)
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) checkTasks() {
|
||||
log.Debug("begin check tasks...")
|
||||
for id, t := range s.tasks {
|
||||
if !t.Exists() {
|
||||
log.Infof("task no longer exists: %v", id)
|
||||
continue
|
||||
}
|
||||
log.Infof("task (%s) percentage done: %d%%", t.Name(), t.Progress())
|
||||
if t.Progress() == 100 {
|
||||
log.Infof("task is done: %v", t.Name())
|
||||
s.sendMsg(fmt.Sprintf(message.DownloadComplete, t.Name()))
|
||||
go func() {
|
||||
if err := s.moveCompletedTask(id); err != nil {
|
||||
log.Infof("post tasks for id %v fail: %v", id, err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) moveCompletedTask(id int) (err1 error) {
|
||||
torrent := s.tasks[id]
|
||||
r := s.db.GetHistory(id)
|
||||
if r.Status == history.StatusUploading {
|
||||
log.Infof("task %d is already uploading, skip", id)
|
||||
return nil
|
||||
}
|
||||
s.db.SetHistoryStatus(r.ID, history.StatusUploading)
|
||||
|
||||
defer func() {
|
||||
seasonNum, err := utils.SeasonId(r.TargetDir)
|
||||
if err != nil {
|
||||
log.Errorf("no season id: %v", r.TargetDir)
|
||||
seasonNum = -1
|
||||
}
|
||||
|
||||
if err1 != nil {
|
||||
s.db.SetHistoryStatus(r.ID, history.StatusFail)
|
||||
if r.EpisodeID != 0 {
|
||||
s.db.SetEpisodeStatus(r.EpisodeID, episode.StatusMissing)
|
||||
} else {
|
||||
s.db.SetSeasonAllEpisodeStatus(r.MediaID, seasonNum, episode.StatusMissing)
|
||||
}
|
||||
s.sendMsg(fmt.Sprintf(message.ProcessingFailed, err))
|
||||
} else {
|
||||
delete(s.tasks, r.ID)
|
||||
s.db.SetHistoryStatus(r.ID, history.StatusSuccess)
|
||||
if r.EpisodeID != 0 {
|
||||
s.db.SetEpisodeStatus(r.EpisodeID, episode.StatusDownloaded)
|
||||
} else {
|
||||
s.db.SetSeasonAllEpisodeStatus(r.MediaID, seasonNum, episode.StatusDownloaded)
|
||||
}
|
||||
s.sendMsg(fmt.Sprintf(message.ProcessingComplete, torrent.Name()))
|
||||
|
||||
torrent.Remove()
|
||||
}
|
||||
}()
|
||||
|
||||
series := s.db.GetMediaDetails(r.MediaID)
|
||||
if series == nil {
|
||||
return nil
|
||||
}
|
||||
st := s.db.GetStorage(series.StorageID)
|
||||
log.Infof("move task files to target dir: %v", r.TargetDir)
|
||||
var stImpl storage.Storage
|
||||
if st.Implementation == storage1.ImplementationWebdav {
|
||||
ws := st.ToWebDavSetting()
|
||||
targetPath := ws.TvPath
|
||||
if series.MediaType == media.MediaTypeMovie {
|
||||
targetPath = ws.MoviePath
|
||||
}
|
||||
storageImpl, err := storage.NewWebdavStorage(ws.URL, ws.User, ws.Password, targetPath, ws.ChangeFileHash == "true")
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "new webdav")
|
||||
}
|
||||
stImpl = storageImpl
|
||||
|
||||
} else if st.Implementation == storage1.ImplementationLocal {
|
||||
ls := st.ToLocalSetting()
|
||||
targetPath := ls.TvPath
|
||||
if series.MediaType == media.MediaTypeMovie {
|
||||
targetPath = ls.MoviePath
|
||||
}
|
||||
|
||||
storageImpl, err := storage.NewLocalStorage(targetPath)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "new storage")
|
||||
|
||||
}
|
||||
stImpl = storageImpl
|
||||
|
||||
}
|
||||
if r.EpisodeID == 0 {
|
||||
//season package download
|
||||
if err := stImpl.Move(filepath.Join(s.db.GetDownloadDir(), torrent.Name()), r.TargetDir); err != nil {
|
||||
return errors.Wrap(err, "move file")
|
||||
|
||||
}
|
||||
|
||||
} else {
|
||||
if err := stImpl.Move(filepath.Join(s.db.GetDownloadDir(), torrent.Name()), filepath.Join(r.TargetDir, torrent.Name())); err != nil {
|
||||
return errors.Wrap(err, "move file")
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
log.Infof("move downloaded files to target dir success, file: %v, target dir: %v", torrent.Name(), r.TargetDir)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) checkDownloadedSeriesFiles(m *ent.Media) error {
|
||||
if m.MediaType != media.MediaTypeTv {
|
||||
return nil
|
||||
}
|
||||
log.Infof("check files in directory: %s", m.TargetDir)
|
||||
st := s.db.GetStorage(m.StorageID)
|
||||
|
||||
var storageImpl storage.Storage
|
||||
|
||||
switch st.Implementation {
|
||||
case storage1.ImplementationLocal:
|
||||
ls := st.ToLocalSetting()
|
||||
targetPath := ls.TvPath
|
||||
storageImpl1, err := storage.NewLocalStorage(targetPath)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "new local")
|
||||
}
|
||||
storageImpl = storageImpl1
|
||||
|
||||
case storage1.ImplementationWebdav:
|
||||
ws := st.ToWebDavSetting()
|
||||
targetPath := ws.TvPath
|
||||
storageImpl1, err := storage.NewWebdavStorage(ws.URL, ws.User, ws.Password, targetPath, ws.ChangeFileHash == "true")
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "new webdav")
|
||||
}
|
||||
storageImpl = storageImpl1
|
||||
}
|
||||
files, err := storageImpl.ReadDir(m.TargetDir)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "read dir %s", m.TargetDir)
|
||||
}
|
||||
|
||||
for _, in := range files {
|
||||
if !in.IsDir() { //season dir, ignore file
|
||||
continue
|
||||
}
|
||||
dir := filepath.Join(m.TargetDir, in.Name())
|
||||
epFiles, err := storageImpl.ReadDir(dir)
|
||||
if err != nil {
|
||||
log.Errorf("read dir %s error: %v", dir, err)
|
||||
continue
|
||||
}
|
||||
for _, ep := range epFiles {
|
||||
log.Infof("found file: %v", ep.Name())
|
||||
seNum, epNum, err := utils.FindSeasonEpisodeNum(ep.Name())
|
||||
if err != nil {
|
||||
log.Errorf("find season episode num error: %v", err)
|
||||
continue
|
||||
}
|
||||
log.Infof("found match, season num %d, episode num %d", seNum, epNum)
|
||||
ep, err := s.db.GetEpisode(m.ID, seNum, epNum)
|
||||
if err != nil {
|
||||
log.Error("update episode: %v", err)
|
||||
continue
|
||||
}
|
||||
err = s.db.SetEpisodeStatus(ep.ID, episode.StatusDownloaded)
|
||||
if err != nil {
|
||||
log.Error("update episode: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
type Task struct {
|
||||
//Processing bool
|
||||
pkg.Torrent
|
||||
}
|
||||
|
||||
func (s *Server) downloadTvSeries() {
|
||||
log.Infof("begin check all tv series resources")
|
||||
allSeries := s.db.GetMediaWatchlist(media.MediaTypeTv)
|
||||
for _, series := range allSeries {
|
||||
tvDetail := s.db.GetMediaDetails(series.ID)
|
||||
for _, ep := range tvDetail.Episodes {
|
||||
if !series.DownloadHistoryEpisodes { //设置不下载历史已播出剧集,只下载将来剧集
|
||||
t, err := time.Parse("2006-01-02", ep.AirDate)
|
||||
if err != nil {
|
||||
log.Error("air date not known, skip: %v", ep.Title)
|
||||
continue
|
||||
}
|
||||
if series.CreatedAt.Sub(t) > 24*time.Hour { //剧集在加入watchlist之前,不去下载
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if ep.Status != episode.StatusMissing { //已经下载的不去下载
|
||||
continue
|
||||
}
|
||||
name, err := s.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)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) downloadMovie() {
|
||||
log.Infof("begin check all movie resources")
|
||||
allSeries := s.db.GetMediaWatchlist(media.MediaTypeMovie)
|
||||
|
||||
for _, series := range allSeries {
|
||||
detail := s.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 := s.downloadMovieSingleEpisode(ep); err != nil {
|
||||
log.Errorf("download movie error: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) downloadMovieSingleEpisode(ep *ent.Episode) error {
|
||||
trc, err := s.getDownloadClient()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "connect transmission")
|
||||
}
|
||||
|
||||
res, err := core.SearchMovie(s.db, ep.MediaID, true)
|
||||
if err != nil {
|
||||
|
||||
return errors.Wrap(err, "search movie")
|
||||
}
|
||||
r1 := res[0]
|
||||
log.Infof("begin download torrent resource: %v", r1.Name)
|
||||
torrent, err := trc.Download(r1.Link, s.db.GetDownloadDir())
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "downloading")
|
||||
}
|
||||
torrent.Start()
|
||||
|
||||
history, err := s.db.SaveHistoryRecord(ent.History{
|
||||
MediaID: ep.MediaID,
|
||||
EpisodeID: ep.ID,
|
||||
SourceTitle: r1.Name,
|
||||
TargetDir: "./",
|
||||
Status: history.StatusRunning,
|
||||
Size: r1.Size,
|
||||
Saved: torrent.Save(),
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorf("save history error: %v", err)
|
||||
}
|
||||
|
||||
s.tasks[history.ID] = &Task{Torrent: torrent}
|
||||
|
||||
s.db.SetEpisodeStatus(ep.ID, episode.StatusDownloading)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) checkAllSeriesNewSeason() {
|
||||
log.Infof("begin checking series all new season")
|
||||
allSeries := s.db.GetMediaWatchlist(media.MediaTypeTv)
|
||||
for _, series := range allSeries {
|
||||
err := s.checkSeiesNewSeason(series)
|
||||
if err != nil {
|
||||
log.Errorf("check series new season error: series name %v, error: %v", series.NameEn, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) checkSeiesNewSeason(media *ent.Media) error {
|
||||
d, err := s.MustTMDB().GetTvDetails(media.TmdbID, s.language)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "tmdb")
|
||||
}
|
||||
lastsSason := d.NumberOfSeasons
|
||||
seasonDetail, err := s.MustTMDB().GetSeasonDetails(media.TmdbID, lastsSason, s.language)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "tmdb season")
|
||||
}
|
||||
|
||||
for _, ep := range seasonDetail.Episodes {
|
||||
epDb, err := s.db.GetEpisode(media.ID, ep.SeasonNumber, ep.EpisodeNumber)
|
||||
if err != nil {
|
||||
if ent.IsNotFound(err) {
|
||||
log.Infof("add new episode: %+v", ep)
|
||||
episode := &ent.Episode{
|
||||
MediaID: media.ID,
|
||||
SeasonNumber: ep.SeasonNumber,
|
||||
EpisodeNumber: ep.EpisodeNumber,
|
||||
Title: ep.Name,
|
||||
Overview: ep.Overview,
|
||||
AirDate: ep.AirDate,
|
||||
Status: episode.StatusMissing,
|
||||
}
|
||||
s.db.SaveEposideDetail2(episode)
|
||||
}
|
||||
} else { //update episode
|
||||
if ep.Name != epDb.Title || ep.Overview != epDb.Overview || ep.AirDate != epDb.AirDate {
|
||||
log.Infof("update new episode: %+v", ep)
|
||||
s.db.UpdateEpiode2(epDb.ID, ep.Name, ep.Overview, ep.AirDate)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -8,14 +8,12 @@ import (
|
||||
"polaris/db"
|
||||
"polaris/log"
|
||||
"polaris/pkg/tmdb"
|
||||
"polaris/pkg/transmission"
|
||||
"polaris/server/core"
|
||||
"polaris/ui"
|
||||
"time"
|
||||
|
||||
ginzap "github.com/gin-contrib/zap"
|
||||
|
||||
"github.com/gin-contrib/static"
|
||||
"github.com/robfig/cron"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/pkg/errors"
|
||||
@@ -23,32 +21,29 @@ import (
|
||||
|
||||
func NewServer(db *db.Client) *Server {
|
||||
r := gin.Default()
|
||||
return &Server{
|
||||
r: r,
|
||||
db: db,
|
||||
cron: cron.New(),
|
||||
tasks: make(map[int]*Task),
|
||||
s := &Server{
|
||||
r: r,
|
||||
db: db,
|
||||
}
|
||||
s.core = core.NewClient(db, s.language)
|
||||
return s
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
r *gin.Engine
|
||||
db *db.Client
|
||||
cron *cron.Cron
|
||||
core *core.Client
|
||||
language string
|
||||
tasks map[int]*Task
|
||||
jwtSerect string
|
||||
}
|
||||
|
||||
func (s *Server) Serve() error {
|
||||
s.scheduler()
|
||||
s.reloadTasks()
|
||||
s.restoreProxy()
|
||||
s.core.Init()
|
||||
|
||||
s.jwtSerect = s.db.GetSetting(db.JwtSerectKey)
|
||||
//st, _ := fs.Sub(ui.Web, "build/web")
|
||||
s.r.Use(static.Serve("/", static.EmbedFolder(ui.Web, "build/web")))
|
||||
s.r.Use(ginzap.Ginzap(log.Logger().Desugar(), time.RFC3339, false))
|
||||
//s.r.Use(ginzap.Ginzap(log.Logger().Desugar(), time.RFC3339, false))
|
||||
s.r.Use(ginzap.RecoveryWithZap(log.Logger().Desugar(), true))
|
||||
|
||||
log.SetLogLevel(s.db.GetSetting(db.SettingLogLevel)) //restore log level
|
||||
@@ -72,6 +67,7 @@ func (s *Server) Serve() error {
|
||||
setting.GET("/about", HttpHandler(s.About))
|
||||
setting.POST("/parse/tv", HttpHandler(s.ParseTv))
|
||||
setting.POST("/parse/movie", HttpHandler(s.ParseMovie))
|
||||
setting.POST("/monitoring", HttpHandler(s.ChangeEpisodeMonitoring))
|
||||
}
|
||||
activity := api.Group("/activity")
|
||||
{
|
||||
@@ -84,6 +80,7 @@ func (s *Server) Serve() error {
|
||||
tv := api.Group("/media")
|
||||
{
|
||||
tv.GET("/search", HttpHandler(s.SearchMedia))
|
||||
tv.POST("/edit", HttpHandler(s.EditMediaMetadata))
|
||||
tv.POST("/tv/watchlist", HttpHandler(s.AddTv2Watchlist))
|
||||
tv.GET("/tv/watchlist", HttpHandler(s.GetTvWatchlist))
|
||||
tv.POST("/torrents", HttpHandler(s.SearchAvailableTorrents))
|
||||
@@ -92,8 +89,9 @@ func (s *Server) Serve() error {
|
||||
tv.GET("/movie/watchlist", HttpHandler(s.GetMovieWatchlist))
|
||||
tv.GET("/record/:id", HttpHandler(s.GetMediaDetails))
|
||||
tv.DELETE("/record/:id", HttpHandler(s.DeleteFromWatchlist))
|
||||
tv.GET("/resolutions", HttpHandler(s.GetAvailableResolutions))
|
||||
tv.GET("/suggest/:tmdb_id", HttpHandler(s.SuggestedSeriesFolderName))
|
||||
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")
|
||||
{
|
||||
@@ -130,9 +128,11 @@ func (s *Server) Serve() error {
|
||||
func (s *Server) TMDB() (*tmdb.Client, error) {
|
||||
api := s.db.GetSetting(db.SettingTmdbApiKey)
|
||||
if api == "" {
|
||||
return nil, errors.New("tmdb api not set")
|
||||
return nil, errors.New("TMDB apiKey not set")
|
||||
}
|
||||
return tmdb.NewClient(api)
|
||||
proxy := s.db.GetSetting(db.SettingProxy)
|
||||
adult := s.db.GetSetting(db.SettingEnableTmdbAdultContent)
|
||||
return tmdb.NewClient(api, proxy, adult=="true")
|
||||
}
|
||||
|
||||
func (s *Server) MustTMDB() *tmdb.Client {
|
||||
@@ -143,22 +143,6 @@ func (s *Server) MustTMDB() *tmdb.Client {
|
||||
return t
|
||||
}
|
||||
|
||||
func (s *Server) reloadTasks() {
|
||||
runningTasks := s.db.GetRunningHistories()
|
||||
if len(runningTasks) == 0 {
|
||||
return
|
||||
}
|
||||
for _, t := range runningTasks {
|
||||
log.Infof("reloading task: %d %s", t.ID, t.SourceTitle)
|
||||
torrent, err := transmission.ReloadTorrent(t.Saved)
|
||||
if err != nil {
|
||||
log.Errorf("relaod task %s failed: %v", t.SourceTitle, err)
|
||||
continue
|
||||
}
|
||||
s.tasks[t.ID] = &Task{Torrent: torrent}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) proxyPosters(c *gin.Context) {
|
||||
remote, _ := url.Parse("https://image.tmdb.org")
|
||||
proxy := httputil.NewSingleHostReverseProxy(remote)
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"polaris/db"
|
||||
"polaris/ent"
|
||||
"polaris/log"
|
||||
"polaris/pkg/transmission"
|
||||
"strconv"
|
||||
@@ -14,10 +14,14 @@ import (
|
||||
)
|
||||
|
||||
type GeneralSettings struct {
|
||||
TmdbApiKey string `json:"tmdb_api_key"`
|
||||
DownloadDir string `json:"download_dir"`
|
||||
LogLevel string `json:"log_level"`
|
||||
Proxy string `json:"proxy"`
|
||||
TmdbApiKey string `json:"tmdb_api_key"`
|
||||
DownloadDir string `json:"download_dir"`
|
||||
LogLevel string `json:"log_level"`
|
||||
Proxy string `json:"proxy"`
|
||||
EnablePlexmatch bool `json:"enable_plexmatch"`
|
||||
EnableNfo bool `json:"enable_nfo"`
|
||||
AllowQiangban bool `json:"allow_qiangban"`
|
||||
EnableAdultContent bool `json:"enable_adult_content"`
|
||||
}
|
||||
|
||||
func (s *Server) SetSetting(c *gin.Context) (interface{}, error) {
|
||||
@@ -45,45 +49,63 @@ func (s *Server) SetSetting(c *gin.Context) (interface{}, error) {
|
||||
|
||||
}
|
||||
|
||||
s.setProxy(in.Proxy)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *Server) setProxy(proxy string) {
|
||||
proxyUrl, err := url.Parse(proxy)
|
||||
tp := http.DefaultTransport.(*http.Transport)
|
||||
if proxy == "" || err != nil {
|
||||
log.Warnf("proxy url not valid, disabling: %v", proxy)
|
||||
tp.Proxy = nil
|
||||
s.db.SetSetting(db.SettingProxy, "")
|
||||
} else {
|
||||
log.Infof("set proxy to %v", proxy)
|
||||
tp.Proxy = http.ProxyURL(proxyUrl)
|
||||
s.db.SetSetting(db.SettingProxy, proxy)
|
||||
plexmatchEnabled := s.db.GetSetting(db.SettingPlexMatchEnabled)
|
||||
if in.EnablePlexmatch && plexmatchEnabled != "true" {
|
||||
s.db.SetSetting(db.SettingPlexMatchEnabled, "true")
|
||||
} else if !in.EnablePlexmatch && plexmatchEnabled != "false" {
|
||||
s.db.SetSetting(db.SettingPlexMatchEnabled, "false")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) restoreProxy() {
|
||||
p := s.db.GetSetting(db.SettingProxy)
|
||||
s.setProxy(p)
|
||||
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
|
||||
}
|
||||
|
||||
func (s *Server) GetSetting(c *gin.Context) (interface{}, error) {
|
||||
tmdb := s.db.GetSetting(db.SettingTmdbApiKey)
|
||||
downloadDir := s.db.GetSetting(db.SettingDownloadDir)
|
||||
logLevel := s.db.GetSetting(db.SettingLogLevel)
|
||||
plexmatchEnabled := s.db.GetSetting(db.SettingPlexMatchEnabled)
|
||||
allowQiangban := s.db.GetSetting(db.SettingAllowQiangban)
|
||||
enableNfo := s.db.GetSetting(db.SettingNfoSupportEnabled)
|
||||
enableAdult := s.db.GetSetting(db.SettingEnableTmdbAdultContent)
|
||||
return &GeneralSettings{
|
||||
TmdbApiKey: tmdb,
|
||||
DownloadDir: downloadDir,
|
||||
LogLevel: logLevel,
|
||||
Proxy: s.db.GetSetting(db.SettingProxy),
|
||||
TmdbApiKey: tmdb,
|
||||
DownloadDir: downloadDir,
|
||||
LogLevel: logLevel,
|
||||
Proxy: s.db.GetSetting(db.SettingProxy),
|
||||
EnablePlexmatch: plexmatchEnabled == "true",
|
||||
AllowQiangban: allowQiangban == "true",
|
||||
EnableNfo: enableNfo == "true",
|
||||
EnableAdultContent: enableAdult == "true",
|
||||
}, nil
|
||||
}
|
||||
|
||||
type addTorznabIn struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
URL string `json:"url" binding:"required"`
|
||||
ApiKey string `json:"api_key" binding:"required"`
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
URL string `json:"url" binding:"required"`
|
||||
ApiKey string `json:"api_key" binding:"required"`
|
||||
Disabled bool `json:"disabled"`
|
||||
Priority int `json:"priority"`
|
||||
SeedRatio float32 `json:"seed_ratio"`
|
||||
}
|
||||
|
||||
func (s *Server) AddTorznabInfo(c *gin.Context) (interface{}, error) {
|
||||
@@ -91,10 +113,31 @@ func (s *Server) AddTorznabInfo(c *gin.Context) (interface{}, error) {
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
return nil, errors.Wrap(err, "bind json")
|
||||
}
|
||||
err := s.db.SaveTorznabInfo(in.Name, db.TorznabSetting{
|
||||
|
||||
log.Infof("add indexer settings: %+v", in)
|
||||
setting := db.TorznabSetting{
|
||||
URL: in.URL,
|
||||
ApiKey: in.ApiKey,
|
||||
})
|
||||
}
|
||||
|
||||
data, err := json.Marshal(setting)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "marshal json")
|
||||
}
|
||||
if in.Priority > 128 {
|
||||
in.Priority = 128
|
||||
}
|
||||
|
||||
indexer := ent.Indexers{
|
||||
ID: in.ID,
|
||||
Name: in.Name,
|
||||
Implementation: "torznab",
|
||||
Settings: string(data),
|
||||
Priority: in.Priority,
|
||||
Disabled: in.Disabled,
|
||||
SeedRatio: in.SeedRatio,
|
||||
}
|
||||
err = s.db.SaveIndexer(&indexer)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "add ")
|
||||
}
|
||||
@@ -119,7 +162,7 @@ func (s *Server) GetAllIndexers(c *gin.Context) (interface{}, error) {
|
||||
return indexers, nil
|
||||
}
|
||||
|
||||
func (s *Server) getDownloadClient() (*transmission.Client, error) {
|
||||
func (s *Server) getDownloadClient() (*transmission.Client, *ent.DownloadClients, error) {
|
||||
tr := s.db.GetTransmission()
|
||||
trc, err := transmission.NewClient(transmission.Config{
|
||||
URL: tr.URL,
|
||||
@@ -127,9 +170,9 @@ func (s *Server) getDownloadClient() (*transmission.Client, error) {
|
||||
Password: tr.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "connect transmission")
|
||||
return nil, nil, errors.Wrap(err, "connect transmission")
|
||||
}
|
||||
return trc, nil
|
||||
return trc, tr, nil
|
||||
}
|
||||
|
||||
type downloadClientIn struct {
|
||||
@@ -177,3 +220,29 @@ func (s *Server) DeleteDownloadCLient(c *gin.Context) (interface{}, error) {
|
||||
s.db.DeleteDownloadCLient(id)
|
||||
return "success", nil
|
||||
}
|
||||
|
||||
type episodeMonitoringIn struct {
|
||||
EpisodeID int `json:"episode_id"`
|
||||
Monitor bool `json:"monitor"`
|
||||
}
|
||||
|
||||
func (s *Server) ChangeEpisodeMonitoring(c *gin.Context) (interface{}, error) {
|
||||
var in episodeMonitoringIn
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
return nil, errors.Wrap(err, "bind")
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -3,9 +3,10 @@ package server
|
||||
import (
|
||||
"fmt"
|
||||
"polaris/db"
|
||||
"regexp"
|
||||
|
||||
"polaris/log"
|
||||
"polaris/pkg/storage"
|
||||
"polaris/pkg/utils"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -27,7 +28,7 @@ func (s *Server) AddStorage(c *gin.Context) (interface{}, error) {
|
||||
if in.Implementation == "webdav" {
|
||||
//test webdav
|
||||
wd := in.ToWebDavSetting()
|
||||
st, err := storage.NewWebdavStorage(wd.URL, wd.User, wd.Password, wd.TvPath, false)
|
||||
st, err := storage.NewWebdavStorage(wd.URL, wd.User, wd.Password, in.TvPath, false)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "new webdav")
|
||||
}
|
||||
@@ -60,30 +61,70 @@ func (s *Server) SuggestedSeriesFolderName(c *gin.Context) (interface{}, error)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("id is not int: %v", ids)
|
||||
}
|
||||
var name, originalName, year string
|
||||
d, err := s.MustTMDB().GetTvDetails(id, s.language)
|
||||
if err != nil {
|
||||
d1, err := s.MustTMDB().GetMovieDetails(id, s.language)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "get movie details")
|
||||
}
|
||||
name = d1.Title
|
||||
originalName = d1.OriginalTitle
|
||||
year = strings.Split(d1.ReleaseDate, "-")[0]
|
||||
|
||||
} else {
|
||||
name = d.Name
|
||||
originalName = d.OriginalName
|
||||
year = strings.Split(d.FirstAirDate, "-")[0]
|
||||
return nil, errors.Wrap(err, "get tv details")
|
||||
}
|
||||
name = fmt.Sprintf("%s %s", name, originalName)
|
||||
|
||||
if !utils.ContainsChineseChar(name) {
|
||||
name = originalName
|
||||
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)
|
||||
}
|
||||
}
|
||||
//remove extra characters
|
||||
re := regexp.MustCompile(`[^\p{L}\w\s]`)
|
||||
name = re.ReplaceAllString(strings.ToLower(name), " ")
|
||||
name = strings.Join(strings.Fields(name), " ")
|
||||
year := strings.Split(d.FirstAirDate, "-")[0]
|
||||
if year != "" {
|
||||
name = fmt.Sprintf("%s (%s)", name, year)
|
||||
}
|
||||
|
||||
log.Infof("tv series of tmdb id %v suggestting name is %v", id, name)
|
||||
return gin.H{"name": name}, nil
|
||||
}
|
||||
|
||||
func (s *Server) SuggestedMovieFolderName(c *gin.Context) (interface{}, error) {
|
||||
ids := c.Param("tmdb_id")
|
||||
id, err := strconv.Atoi(ids)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("id is not int: %v", ids)
|
||||
}
|
||||
d1, err := s.MustTMDB().GetMovieDetails(id, s.language)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "get movie details")
|
||||
}
|
||||
name := d1.Title
|
||||
|
||||
if isJav(d1) {
|
||||
javid := s.getJavid(id)
|
||||
if javid != "" {
|
||||
return gin.H{"name": javid}, nil
|
||||
}
|
||||
}
|
||||
|
||||
if s.language == db.LanguageCN {
|
||||
en, err := s.MustTMDB().GetMovieDetails(id, db.LanguageEN)
|
||||
if err != nil {
|
||||
log.Errorf("get en movie detail error: %v", err)
|
||||
} else {
|
||||
name = fmt.Sprintf("%s %s", d1.Title, en.Title)
|
||||
}
|
||||
}
|
||||
//remove extra characters
|
||||
re := regexp.MustCompile(`[^\p{L}\w\s]`)
|
||||
name = re.ReplaceAllString(strings.ToLower(name), " ")
|
||||
name = strings.Join(strings.Fields(name), " ")
|
||||
year := strings.Split(d1.ReleaseDate, "-")[0]
|
||||
if year != "" {
|
||||
name = fmt.Sprintf("%s (%s)", name, year)
|
||||
}
|
||||
|
||||
log.Infof("tv series of tmdb id %v suggestting name is %v", id, name)
|
||||
return gin.H{"name": name}, nil
|
||||
}
|
||||
|
||||
@@ -10,8 +10,10 @@ import (
|
||||
"polaris/ent"
|
||||
"polaris/ent/episode"
|
||||
"polaris/ent/media"
|
||||
"polaris/ent/schema"
|
||||
"polaris/log"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
tmdb "github.com/cyruzin/golang-tmdb"
|
||||
@@ -43,7 +45,11 @@ func (s *Server) SearchMedia(c *gin.Context) (interface{}, error) {
|
||||
return nil, errors.Wrap(err, "bind query")
|
||||
}
|
||||
log.Infof("search media with keyword: %v", q.Query)
|
||||
r, err := s.MustTMDB().SearchMedia(q.Query, s.language, q.Page)
|
||||
tmdb, err := s.TMDB()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r, err := tmdb.SearchMedia(q.Query, s.language, q.Page)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "search tv")
|
||||
}
|
||||
@@ -60,8 +66,10 @@ 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"`
|
||||
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 (s *Server) AddTv2Watchlist(c *gin.Context) (interface{}, error) {
|
||||
@@ -69,6 +77,7 @@ func (s *Server) AddTv2Watchlist(c *gin.Context) (interface{}, error) {
|
||||
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")
|
||||
}
|
||||
@@ -97,12 +106,30 @@ func (s *Server) AddTv2Watchlist(c *gin.Context) (interface{}, error) {
|
||||
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)
|
||||
@@ -111,19 +138,27 @@ func (s *Server) AddTv2Watchlist(c *gin.Context) (interface{}, error) {
|
||||
epIds = append(epIds, epid)
|
||||
}
|
||||
}
|
||||
r, err := s.db.AddMediaWatchlist(&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,
|
||||
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,
|
||||
}, epIds)
|
||||
Limiter: schema.MediaLimiter{SizeMin: in.SizeMin, SizeMax: in.SizeMax},
|
||||
Extras: schema.MediaExtras{
|
||||
OriginalLanguage: detail.OriginalLanguage,
|
||||
Genres: detail.Genres,
|
||||
},
|
||||
}
|
||||
|
||||
r, err := s.db.AddMediaWatchlist(m, epIds)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "add to list")
|
||||
}
|
||||
@@ -134,7 +169,7 @@ func (s *Server) AddTv2Watchlist(c *gin.Context) (interface{}, error) {
|
||||
if err := s.downloadBackdrop(detail.BackdropPath, r.ID); err != nil {
|
||||
log.Errorf("download poster error: %v", err)
|
||||
}
|
||||
if err := s.checkDownloadedSeriesFiles(r); err != nil {
|
||||
if err := s.core.CheckDownloadedSeriesFiles(r); err != nil {
|
||||
log.Errorf("check downloaded files error: %v", err)
|
||||
}
|
||||
|
||||
@@ -144,11 +179,32 @@ func (s *Server) AddTv2Watchlist(c *gin.Context) (interface{}, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func isJav(detail *tmdb.MovieDetails) bool {
|
||||
if detail.Adult && len(detail.ProductionCountries) > 0 && strings.ToUpper(detail.ProductionCountries[0].Iso3166_1) == "JP" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Server) getJavid(id int) string {
|
||||
alters, err := s.MustTMDB().GetMovieAlternativeTitles(id, s.language)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
for _, t := range alters.Titles {
|
||||
if t.Iso3166_1 == "JP" && t.Type == "" {
|
||||
return t.Title
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Server) AddMovie2Watchlist(c *gin.Context) (interface{}, error) {
|
||||
var in addWatchlistIn
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
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")
|
||||
@@ -171,14 +227,16 @@ func (s *Server) AddMovie2Watchlist(c *gin.Context) (interface{}, error) {
|
||||
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{
|
||||
movie := ent.Media{
|
||||
TmdbID: int(detail.ID),
|
||||
ImdbID: detail.IMDbID,
|
||||
MediaType: media.MediaTypeMovie,
|
||||
NameCn: nameCn,
|
||||
NameEn: nameEn,
|
||||
@@ -187,8 +245,22 @@ func (s *Server) AddMovie2Watchlist(c *gin.Context) (interface{}, error) {
|
||||
AirDate: detail.ReleaseDate,
|
||||
Resolution: media.Resolution(in.Resolution),
|
||||
StorageID: in.StorageID,
|
||||
TargetDir: "./",
|
||||
}, []int{epid})
|
||||
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 := s.getJavid(in.TmdbID)
|
||||
extras.JavId = javid
|
||||
}
|
||||
|
||||
movie.Extras = extras
|
||||
r, err := s.db.AddMediaWatchlist(&movie, []int{epid})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "add to list")
|
||||
}
|
||||
@@ -244,7 +316,8 @@ func (s *Server) downloadImage(url string, mediaID int, name string) error {
|
||||
|
||||
type MediaWithStatus struct {
|
||||
*ent.Media
|
||||
Status string `json:"status"`
|
||||
MonitoredNum int `json:"monitored_num"`
|
||||
DownloadedNum int `json:"downloaded_num"`
|
||||
}
|
||||
|
||||
//missing: episode aired missing
|
||||
@@ -257,24 +330,18 @@ func (s *Server) GetTvWatchlist(c *gin.Context) (interface{}, error) {
|
||||
res := make([]MediaWithStatus, len(list))
|
||||
for i, item := range list {
|
||||
var ms = MediaWithStatus{
|
||||
Media: item,
|
||||
Status: "downloaded",
|
||||
Media: item,
|
||||
MonitoredNum: 0,
|
||||
DownloadedNum: 0,
|
||||
}
|
||||
|
||||
details := s.db.GetMediaDetails(item.ID)
|
||||
|
||||
for _, ep := range details.Episodes {
|
||||
if ep.SeasonNumber == 0 {
|
||||
continue
|
||||
}
|
||||
t, err := time.Parse("2006-01-02", ep.AirDate)
|
||||
if err != nil { //airdate not exist
|
||||
ms.Status = "monitoring"
|
||||
} else {
|
||||
if item.CreatedAt.Sub(t) > 24*time.Hour { //剧集在加入watchlist之前,不去下载
|
||||
continue
|
||||
}
|
||||
if ep.Status == episode.StatusMissing {
|
||||
ms.Status = "monitoring"
|
||||
if ep.Monitored {
|
||||
ms.MonitoredNum++
|
||||
if ep.Status == episode.StatusDownloaded {
|
||||
ms.DownloadedNum++
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -288,15 +355,16 @@ func (s *Server) GetMovieWatchlist(c *gin.Context) (interface{}, error) {
|
||||
res := make([]MediaWithStatus, len(list))
|
||||
for i, item := range list {
|
||||
var ms = MediaWithStatus{
|
||||
Media: item,
|
||||
Status: "monitoring",
|
||||
Media: item,
|
||||
MonitoredNum: 1,
|
||||
DownloadedNum: 0,
|
||||
}
|
||||
dummyEp, err := s.db.GetMovieDummyEpisode(item.ID)
|
||||
if err != nil {
|
||||
log.Errorf("get dummy episode: %v", err)
|
||||
} else {
|
||||
if dummyEp.Status != episode.StatusMissing {
|
||||
ms.Status = "downloaded"
|
||||
if dummyEp.Status == episode.StatusDownloaded {
|
||||
ms.DownloadedNum++
|
||||
}
|
||||
}
|
||||
res[i] = ms
|
||||
@@ -304,6 +372,11 @@ func (s *Server) GetMovieWatchlist(c *gin.Context) (interface{}, error) {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
type MediaDetails struct {
|
||||
*db.MediaDetails
|
||||
Storage *ent.Storage `json:"storage"`
|
||||
}
|
||||
|
||||
func (s *Server) GetMediaDetails(c *gin.Context) (interface{}, error) {
|
||||
ids := c.Param("id")
|
||||
id, err := strconv.Atoi(ids)
|
||||
@@ -311,15 +384,8 @@ func (s *Server) GetMediaDetails(c *gin.Context) (interface{}, error) {
|
||||
return nil, errors.Wrap(err, "convert")
|
||||
}
|
||||
detail := s.db.GetMediaDetails(id)
|
||||
return detail, nil
|
||||
}
|
||||
|
||||
func (s *Server) GetAvailableResolutions(c *gin.Context) (interface{}, error) {
|
||||
return []db.ResolutionType{
|
||||
db.R720p,
|
||||
db.R1080p,
|
||||
db.R4k,
|
||||
}, nil
|
||||
st := s.db.GetStorage(detail.StorageID)
|
||||
return MediaDetails{MediaDetails: detail, Storage: &st.Storage}, nil
|
||||
}
|
||||
|
||||
func (s *Server) DeleteFromWatchlist(c *gin.Context) (interface{}, error) {
|
||||
|
||||
25
ui/.metadata
25
ui/.metadata
@@ -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
|
||||
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
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/utils.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});
|
||||
static const route = "/activities";
|
||||
|
||||
@override
|
||||
_ActivityPageState createState() => _ActivityPageState();
|
||||
ConsumerState<ConsumerStatefulWidget> createState() => _ActivityPageState();
|
||||
}
|
||||
|
||||
class _ActivityPageState extends ConsumerState<ActivityPage>
|
||||
@@ -53,28 +54,99 @@ class _ActivityPageState extends ConsumerState<ActivityPage>
|
||||
],
|
||||
),
|
||||
Builder(builder: (context) {
|
||||
var activitiesWatcher = ref.watch(activitiesDataProvider("active"));
|
||||
AsyncValue<List<Activity>>? activitiesWatcher;
|
||||
|
||||
if (selectedTab == 1) {
|
||||
activitiesWatcher = ref.watch(activitiesDataProvider("archive"));
|
||||
} else if (selectedTab == 0) {
|
||||
activitiesWatcher = ref.watch(activitiesDataProvider("active"));
|
||||
}
|
||||
|
||||
return activitiesWatcher.when(
|
||||
return activitiesWatcher!.when(
|
||||
data: (activities) {
|
||||
return SingleChildScrollView(
|
||||
child: PaginatedDataTable(
|
||||
rowsPerPage: 10,
|
||||
columns: const [
|
||||
DataColumn(label: Text("#"), numeric: true),
|
||||
DataColumn(label: Text("名称")),
|
||||
DataColumn(label: Text("开始时间")),
|
||||
DataColumn(label: Text("状态")),
|
||||
DataColumn(label: Text("操作"))
|
||||
],
|
||||
source: ActivityDataSource(
|
||||
activities: activities,
|
||||
onDelete: selectedTab == 0 ? onDelete() : null),
|
||||
),
|
||||
);
|
||||
return Flexible(
|
||||
child: ListView.builder(
|
||||
itemCount: activities.length,
|
||||
itemBuilder: (context, index) {
|
||||
final ac = activities[index];
|
||||
return Column(
|
||||
children: [
|
||||
ListTile(
|
||||
dense: true,
|
||||
leading: () {
|
||||
if (ac.status == "uploading") {
|
||||
return const SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: Tooltip(
|
||||
message: "正在上传到指定存储",
|
||||
child: CircularProgressIndicator(),
|
||||
));
|
||||
} else if (ac.status == "fail") {
|
||||
return const Tooltip(
|
||||
message: "下载失败",
|
||||
child: Icon(
|
||||
Icons.close,
|
||||
color: Colors.red,
|
||||
));
|
||||
} else if (ac.status == "seeding") {
|
||||
//seeding
|
||||
return Tooltip(
|
||||
message: "做种中",
|
||||
child: Icon(
|
||||
Icons.keyboard_double_arrow_up,
|
||||
color: Theme.of(context)
|
||||
.colorScheme
|
||||
.inversePrimary,
|
||||
),
|
||||
);
|
||||
} else if (ac.status == "success") {
|
||||
return const Tooltip(
|
||||
message: "下载成功",
|
||||
child: Icon(
|
||||
Icons.check,
|
||||
color: Colors.green,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
double p = ac.progress == null
|
||||
? 0
|
||||
: ac.progress!.toDouble() / 100;
|
||||
return Tooltip(
|
||||
message: "${ac.progress}%",
|
||||
child: CircularProgressIndicator(
|
||||
backgroundColor: Colors.black26,
|
||||
value: p,
|
||||
),
|
||||
);
|
||||
}(),
|
||||
title: Text((ac.sourceTitle ?? "")),
|
||||
subtitle: Opacity(
|
||||
opacity: 0.7,
|
||||
child: Wrap(
|
||||
spacing: 10,
|
||||
children: [
|
||||
Text("开始时间:${timeago.format(ac.date!)}"),
|
||||
Text("大小:${(ac.size ?? 0).readableFileSize()}"),
|
||||
ac.seedRatio > 0
|
||||
? Text("分享率:${ac.seedRatio}")
|
||||
: SizedBox()
|
||||
],
|
||||
),
|
||||
),
|
||||
trailing: selectedTab == 0
|
||||
? IconButton(
|
||||
tooltip: "删除任务",
|
||||
onPressed: () => onDelete()(ac.id!),
|
||||
icon: const Icon(Icons.delete))
|
||||
: const Text("-"),
|
||||
),
|
||||
Divider(),
|
||||
],
|
||||
);
|
||||
},
|
||||
));
|
||||
},
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator());
|
||||
@@ -85,79 +157,10 @@ class _ActivityPageState extends ConsumerState<ActivityPage>
|
||||
|
||||
Function(int) onDelete() {
|
||||
return (id) {
|
||||
ref
|
||||
final f = ref
|
||||
.read(activitiesDataProvider("active").notifier)
|
||||
.deleteActivity(id)
|
||||
.then((v) => Utils.showSnakeBar("删除成功"))
|
||||
.onError((error, trace) => Utils.showSnakeBar("删除失败:$error"));
|
||||
.deleteActivity(id);
|
||||
showLoadingWithFuture(f);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -6,11 +6,12 @@ import 'package:ui/activity.dart';
|
||||
import 'package:ui/login_page.dart';
|
||||
import 'package:ui/movie_watchlist.dart';
|
||||
import 'package:ui/providers/APIs.dart';
|
||||
import 'package:ui/search.dart';
|
||||
import 'package:ui/settings.dart';
|
||||
import 'package:ui/search_page/search.dart';
|
||||
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());
|
||||
@@ -35,7 +36,8 @@ CustomTransitionPage buildPageWithDefaultTransition<T>({
|
||||
reverseTransitionDuration: Duration.zero,
|
||||
key: state.pageKey,
|
||||
child: child,
|
||||
transitionsBuilder: (context, animation, secondaryAnimation, child) => child,
|
||||
transitionsBuilder: (context, animation, secondaryAnimation, child) =>
|
||||
child,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -48,7 +50,9 @@ class _MyAppState extends ConsumerState<MyApp> {
|
||||
builder: (BuildContext context, GoRouterState state, Widget child) {
|
||||
return SelectionArea(
|
||||
child: MainSkeleton(
|
||||
body: Padding(padding: const EdgeInsets.all(20), child: child),
|
||||
body: Padding(
|
||||
padding: EdgeInsets.all(isSmallScreen(context) ? 5 : 20),
|
||||
child: child),
|
||||
),
|
||||
);
|
||||
},
|
||||
@@ -121,16 +125,24 @@ class _MyAppState extends ConsumerState<MyApp> {
|
||||
|
||||
return ProviderScope(
|
||||
child: MaterialApp.router(
|
||||
title: 'Polaris 影视追踪',
|
||||
title: 'Polaris 影视追踪下载',
|
||||
theme: ThemeData(
|
||||
fontFamily: "NotoSansSC",
|
||||
colorScheme: ColorScheme.fromSeed(
|
||||
seedColor: Colors.blueAccent,
|
||||
brightness: Brightness.dark,
|
||||
surface: Colors.black54),
|
||||
useMaterial3: true,
|
||||
//scaffoldBackgroundColor: Color.fromARGB(255, 26, 24, 24)
|
||||
),
|
||||
fontFamily: "NotoSansSC",
|
||||
colorScheme: ColorScheme.fromSeed(
|
||||
seedColor: Colors.blueAccent,
|
||||
brightness: Brightness.dark,
|
||||
surface: Colors.black87),
|
||||
useMaterial3: true,
|
||||
//scaffoldBackgroundColor: Color.fromARGB(255, 26, 24, 24)
|
||||
tooltipTheme: TooltipThemeData(
|
||||
textStyle: const TextStyle(
|
||||
color: Colors.grey,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black54,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
)),
|
||||
routerConfig: router,
|
||||
),
|
||||
);
|
||||
@@ -174,16 +186,20 @@ class _MainSkeletonState extends State<MainSkeleton> {
|
||||
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
||||
// Here we take the value from the MyHomePage object that was created by
|
||||
// the App.build method, and use it to set our appbar title.
|
||||
title: const Row(
|
||||
children: [
|
||||
Text("Polaris"),
|
||||
],
|
||||
title: TextButton(
|
||||
onPressed: () => context.go(WelcomePage.routeTv),
|
||||
child: Text(
|
||||
"Polaris",
|
||||
overflow: TextOverflow.clip,
|
||||
style: TextStyle(fontSize: 28),
|
||||
),
|
||||
),
|
||||
|
||||
actions: [
|
||||
SearchAnchor(
|
||||
builder: (BuildContext context, SearchController controller) {
|
||||
return Container(
|
||||
constraints: const BoxConstraints(maxWidth: 300, maxHeight: 40),
|
||||
constraints: const BoxConstraints(maxWidth: 250, maxHeight: 40),
|
||||
child: Opacity(
|
||||
opacity: 0.8,
|
||||
child: SearchBar(
|
||||
@@ -248,27 +264,32 @@ class _MainSkeletonState extends State<MainSkeleton> {
|
||||
},
|
||||
destinations: const <NavigationDestination>[
|
||||
NavigationDestination(
|
||||
icon: Icon(Icons.live_tv),
|
||||
icon: Icon(Icons.live_tv_outlined),
|
||||
selectedIcon: Icon(Icons.live_tv),
|
||||
label: '剧集',
|
||||
),
|
||||
NavigationDestination(
|
||||
icon: Icon(Icons.movie),
|
||||
icon: Icon(Icons.movie_outlined),
|
||||
selectedIcon: Icon(Icons.movie),
|
||||
label: '电影',
|
||||
),
|
||||
NavigationDestination(
|
||||
icon: Icon(Icons.download),
|
||||
icon: Icon(Icons.download_outlined),
|
||||
selectedIcon: Icon(Icons.download),
|
||||
label: '活动',
|
||||
),
|
||||
NavigationDestination(
|
||||
icon: Icon(Icons.settings),
|
||||
icon: Icon(Icons.settings_outlined),
|
||||
selectedIcon: Icon(Icons.settings),
|
||||
label: '设置',
|
||||
),
|
||||
NavigationDestination(
|
||||
icon: Icon(Icons.computer_rounded),
|
||||
icon: Icon(Icons.computer_outlined),
|
||||
selectedIcon: Icon(Icons.computer),
|
||||
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
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:ui/providers/APIs.dart';
|
||||
import 'package:ui/providers/activity.dart';
|
||||
import 'package:ui/providers/series_details.dart';
|
||||
import 'package:ui/providers/settings.dart';
|
||||
import 'package:ui/widgets/utils.dart';
|
||||
import 'package:ui/welcome_page.dart';
|
||||
import 'package:ui/widgets/detail_card.dart';
|
||||
import 'package:ui/widgets/resource_list.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
|
||||
class MovieDetailsPage extends ConsumerStatefulWidget {
|
||||
@@ -30,105 +27,12 @@ class _MovieDetailsPageState extends ConsumerState<MovieDetailsPage> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
var seriesDetails = ref.watch(mediaDetailsProvider(widget.id));
|
||||
var storage = ref.watch(storageSettingProvider);
|
||||
|
||||
return seriesDetails.when(
|
||||
data: (details) {
|
||||
return ListView(
|
||||
children: [
|
||||
Card(
|
||||
margin: const EdgeInsets.all(4),
|
||||
clipBehavior: Clip.hardEdge,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
image: DecorationImage(
|
||||
fit: BoxFit.cover,
|
||||
opacity: 0.5,
|
||||
image: NetworkImage(
|
||||
"${APIs.imagesUrl}/${details.id}/backdrop.jpg",
|
||||
))),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(10),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Flexible(
|
||||
flex: 1,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(10),
|
||||
child: Image.network(
|
||||
"${APIs.imagesUrl}/${details.id}/poster.jpg",
|
||||
fit: BoxFit.contain,
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
flex: 6,
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text("${details.resolution}"),
|
||||
const SizedBox(
|
||||
width: 30,
|
||||
),
|
||||
storage.when(
|
||||
data: (value) {
|
||||
for (final s in value) {
|
||||
if (s.id == details.storageId) {
|
||||
return Text(
|
||||
"${s.name}(${s.implementation})");
|
||||
}
|
||||
}
|
||||
return const Text("未知存储");
|
||||
},
|
||||
error: (error, stackTrace) =>
|
||||
Text("$error"),
|
||||
loading: () =>
|
||||
const MyProgressIndicator()),
|
||||
],
|
||||
),
|
||||
const Divider(thickness: 1, height: 1),
|
||||
Text(
|
||||
"${details.name} (${details.airDate!.split("-")[0]})",
|
||||
style: const TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold),
|
||||
),
|
||||
const Text(""),
|
||||
Text(
|
||||
details.overview!,
|
||||
),
|
||||
],
|
||||
)),
|
||||
Column(
|
||||
children: [
|
||||
IconButton(
|
||||
onPressed: () {
|
||||
ref
|
||||
.read(mediaDetailsProvider(
|
||||
widget.id)
|
||||
.notifier)
|
||||
.delete()
|
||||
.then((v) => context
|
||||
.go(WelcomePage.routeMoivie))
|
||||
.onError((error, trace) =>
|
||||
Utils.showSnakeBar(
|
||||
"删除失败:$error"));
|
||||
},
|
||||
icon: const Icon(Icons.delete))
|
||||
],
|
||||
)
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
)),
|
||||
),
|
||||
DetailCard(details: details),
|
||||
NestedTabBar(
|
||||
id: widget.id,
|
||||
)
|
||||
@@ -148,7 +52,7 @@ class NestedTabBar extends ConsumerStatefulWidget {
|
||||
const NestedTabBar({super.key, required this.id});
|
||||
|
||||
@override
|
||||
_NestedTabBarState createState() => _NestedTabBarState();
|
||||
ConsumerState<ConsumerStatefulWidget> createState() => _NestedTabBarState();
|
||||
}
|
||||
|
||||
class _NestedTabBarState extends ConsumerState<NestedTabBar>
|
||||
@@ -157,7 +61,7 @@ class _NestedTabBarState extends ConsumerState<NestedTabBar>
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_nestedTabController = new TabController(length: 2, vsync: this);
|
||||
_nestedTabController = TabController(length: 2, vsync: this);
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -220,58 +124,7 @@ class _NestedTabBarState extends ConsumerState<NestedTabBar>
|
||||
error: (error, trace) => Text("$error"),
|
||||
loading: () => const MyProgressIndicator());
|
||||
} else {
|
||||
return Consumer(
|
||||
builder: (context, ref, child) {
|
||||
var torrents = ref.watch(mediaTorrentsDataProvider(
|
||||
(mediaId: widget.id, seasonNumber: 0, episodeNumber: 0)));
|
||||
return torrents.when(
|
||||
data: (v) {
|
||||
if (v.isEmpty) {
|
||||
return const Center(
|
||||
child: Text("无可用资源"),
|
||||
);
|
||||
}
|
||||
|
||||
return DataTable(
|
||||
columns: const [
|
||||
DataColumn(label: Text("名称")),
|
||||
DataColumn(label: Text("大小")),
|
||||
DataColumn(label: Text("seeders")),
|
||||
DataColumn(label: Text("peers")),
|
||||
DataColumn(label: Text("操作"))
|
||||
],
|
||||
rows: List.generate(v.length, (i) {
|
||||
final torrent = v[i];
|
||||
return DataRow(cells: [
|
||||
DataCell(Text("${torrent.name}")),
|
||||
DataCell(
|
||||
Text("${torrent.size?.readableFileSize()}")),
|
||||
DataCell(Text("${torrent.seeders}")),
|
||||
DataCell(Text("${torrent.peers}")),
|
||||
DataCell(IconButton(
|
||||
icon: const Icon(Icons.download),
|
||||
onPressed: () {
|
||||
ref
|
||||
.read(mediaTorrentsDataProvider((
|
||||
mediaId: widget.id,
|
||||
seasonNumber: 0,
|
||||
episodeNumber: 0
|
||||
)).notifier)
|
||||
.download(torrent)
|
||||
.then((v) => Utils.showSnakeBar(
|
||||
"开始下载:${torrent.name}"))
|
||||
.onError((error, trace) =>
|
||||
Utils.showSnakeBar("操作失败: $error"));
|
||||
},
|
||||
))
|
||||
]);
|
||||
}),
|
||||
);
|
||||
},
|
||||
error: (error, trace) => Text("$error"),
|
||||
loading: () => const MyProgressIndicator());
|
||||
},
|
||||
);
|
||||
return ResourceList(mediaId: widget.id);
|
||||
}
|
||||
})
|
||||
],
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:ui/activity.dart';
|
||||
import 'package:ui/settings.dart';
|
||||
import 'package:ui/settings/settings.dart';
|
||||
import 'package:ui/welcome_page.dart';
|
||||
|
||||
class NavDrawer extends StatefulWidget {
|
||||
|
||||
@@ -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";
|
||||
@@ -14,7 +16,8 @@ class APIs {
|
||||
static final availableTorrentsUrl = "$_baseUrl/api/v1/media/torrents/";
|
||||
static final downloadTorrentUrl = "$_baseUrl/api/v1/media/torrents/download";
|
||||
static final seriesDetailUrl = "$_baseUrl/api/v1/media/record/";
|
||||
static final suggestedTvName = "$_baseUrl/api/v1/media/suggest/";
|
||||
static final suggestedTvName = "$_baseUrl/api/v1/media/suggest/tv/";
|
||||
static final suggestedMovieName = "$_baseUrl/api/v1/media/suggest/movie/";
|
||||
static final searchAndDownloadUrl = "$_baseUrl/api/v1/indexer/download";
|
||||
static final allIndexersUrl = "$_baseUrl/api/v1/indexer/";
|
||||
static final addIndexerUrl = "$_baseUrl/api/v1/indexer/add";
|
||||
@@ -32,6 +35,7 @@ class APIs {
|
||||
static final logsBaseUrl = "$_baseUrl/api/v1/logs/";
|
||||
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 notifierAllUrl = "$_baseUrl/api/v1/notifier/all";
|
||||
static final notifierDeleteUrl = "$_baseUrl/api/v1/notifier/id/";
|
||||
|
||||
@@ -5,7 +5,7 @@ import 'package:ui/providers/APIs.dart';
|
||||
import 'package:ui/providers/server_response.dart';
|
||||
|
||||
var activitiesDataProvider =
|
||||
AsyncNotifierProvider.family<ActivityData, List<Activity>, String>(
|
||||
AsyncNotifierProvider.autoDispose.family<ActivityData, List<Activity>, String>(
|
||||
ActivityData.new);
|
||||
|
||||
var mediaHistoryDataProvider = FutureProvider.autoDispose.family(
|
||||
@@ -24,7 +24,7 @@ var mediaHistoryDataProvider = FutureProvider.autoDispose.family(
|
||||
},
|
||||
);
|
||||
|
||||
class ActivityData extends FamilyAsyncNotifier<List<Activity>, String> {
|
||||
class ActivityData extends AutoDisposeFamilyAsyncNotifier<List<Activity>, String> {
|
||||
@override
|
||||
FutureOr<List<Activity>> build(String arg) async {
|
||||
if (arg == "active") {
|
||||
@@ -68,7 +68,9 @@ class Activity {
|
||||
required this.targetDir,
|
||||
required this.status,
|
||||
required this.saved,
|
||||
required this.progress});
|
||||
required this.progress,
|
||||
required this.size,
|
||||
required this.seedRatio});
|
||||
|
||||
final int? id;
|
||||
final int? mediaId;
|
||||
@@ -79,6 +81,8 @@ class Activity {
|
||||
final String? status;
|
||||
final String? saved;
|
||||
final int? progress;
|
||||
final int? size;
|
||||
final double seedRatio;
|
||||
|
||||
factory Activity.fromJson(Map<String, dynamic> json) {
|
||||
return Activity(
|
||||
@@ -90,6 +94,8 @@ class Activity {
|
||||
targetDir: json["target_dir"],
|
||||
status: json["status"],
|
||||
saved: json["saved"],
|
||||
progress: json["progress"]);
|
||||
progress: json["progress"],
|
||||
seedRatio: json["seed_ratio"],
|
||||
size: json["size"]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
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';
|
||||
import 'package:ui/providers/settings.dart';
|
||||
|
||||
var mediaDetailsProvider = AsyncNotifierProvider.autoDispose
|
||||
.family<SeriesDetailData, SeriesDetails, String>(SeriesDetailData.new);
|
||||
@@ -33,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,
|
||||
@@ -47,11 +49,55 @@ class SeriesDetailData
|
||||
var name = (sp.data as Map<String, dynamic>)["name"];
|
||||
return name;
|
||||
}
|
||||
|
||||
Future<void> changeMonitoringStatus(int episodeId, bool b) async {
|
||||
final dio = APIs.getDio();
|
||||
var resp = await dio.post(APIs.changeMonitoringUrl, data: {
|
||||
"episode_id": episodeId,
|
||||
"monitor": b,
|
||||
});
|
||||
var sp = ServerResponse.fromJson(resp.data);
|
||||
if (sp.code != 0) {
|
||||
throw sp.message;
|
||||
}
|
||||
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;
|
||||
@@ -61,10 +107,16 @@ class SeriesDetails {
|
||||
String? resolution;
|
||||
int? storageId;
|
||||
String? airDate;
|
||||
String? mediaType;
|
||||
Storage? storage;
|
||||
String? targetDir;
|
||||
bool? downloadHistoryEpisodes;
|
||||
Limiter? limiter;
|
||||
|
||||
SeriesDetails(
|
||||
{this.id,
|
||||
this.tmdbId,
|
||||
this.imdbid,
|
||||
this.name,
|
||||
this.originalName,
|
||||
this.overview,
|
||||
@@ -73,11 +125,17 @@ class SeriesDetails {
|
||||
this.resolution,
|
||||
this.storageId,
|
||||
this.airDate,
|
||||
this.episodes});
|
||||
this.episodes,
|
||||
this.mediaType,
|
||||
this.targetDir,
|
||||
this.storage,
|
||||
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'];
|
||||
@@ -86,12 +144,29 @@ class SeriesDetails {
|
||||
resolution = json["resolution"];
|
||||
storageId = json["storage_id"];
|
||||
airDate = json["air_date"];
|
||||
mediaType = json["media_type"];
|
||||
storage = Storage.fromJson(json["storage"]);
|
||||
targetDir = json["target_dir"];
|
||||
downloadHistoryEpisodes = json["download_history_episodes"] ?? false;
|
||||
if (json['episodes'] != null) {
|
||||
episodes = <Episodes>[];
|
||||
json['episodes'].forEach((v) {
|
||||
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"]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +179,7 @@ class Episodes {
|
||||
int? seasonNumber;
|
||||
String? overview;
|
||||
String? status;
|
||||
bool? monitored;
|
||||
|
||||
Episodes(
|
||||
{this.id,
|
||||
@@ -113,6 +189,7 @@ class Episodes {
|
||||
this.airDate,
|
||||
this.seasonNumber,
|
||||
this.status,
|
||||
this.monitored,
|
||||
this.overview});
|
||||
|
||||
Episodes.fromJson(Map<String, dynamic> json) {
|
||||
@@ -124,6 +201,7 @@ class Episodes {
|
||||
seasonNumber = json['season_number'];
|
||||
status = json['status'];
|
||||
overview = json['overview'];
|
||||
monitored = json["monitored"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,14 +224,12 @@ var mediaTorrentsDataProvider = AsyncNotifierProvider.autoDispose
|
||||
// }
|
||||
// }
|
||||
|
||||
typedef TorrentQuery =({String mediaId, int seasonNumber, int episodeNumber});
|
||||
typedef TorrentQuery = ({String mediaId, int seasonNumber, int episodeNumber});
|
||||
|
||||
class MediaTorrentResource extends AutoDisposeFamilyAsyncNotifier<
|
||||
List<TorrentResource>, TorrentQuery> {
|
||||
|
||||
@override
|
||||
FutureOr<List<TorrentResource>> build(TorrentQuery arg) async {
|
||||
|
||||
final dio = await APIs.getDio();
|
||||
var resp = await dio.post(APIs.availableTorrentsUrl, data: {
|
||||
"id": int.parse(arg.mediaId),
|
||||
@@ -184,13 +260,28 @@ class MediaTorrentResource extends AutoDisposeFamilyAsyncNotifier<
|
||||
}
|
||||
|
||||
class TorrentResource {
|
||||
TorrentResource({this.name, this.size, this.seeders, this.peers, this.link});
|
||||
TorrentResource(
|
||||
{this.name,
|
||||
this.size,
|
||||
this.seeders,
|
||||
this.peers,
|
||||
this.link,
|
||||
this.source,
|
||||
this.indexerId,
|
||||
this.downloadFactor,
|
||||
this.uploadFactor,
|
||||
this.isPrivate});
|
||||
|
||||
String? name;
|
||||
int? size;
|
||||
int? seeders;
|
||||
int? peers;
|
||||
String? link;
|
||||
String? source;
|
||||
int? indexerId;
|
||||
double? downloadFactor;
|
||||
double? uploadFactor;
|
||||
bool? isPrivate;
|
||||
|
||||
factory TorrentResource.fromJson(Map<String, dynamic> json) {
|
||||
return TorrentResource(
|
||||
@@ -198,13 +289,20 @@ class TorrentResource {
|
||||
size: json["size"],
|
||||
seeders: json["seeders"],
|
||||
peers: json["peers"],
|
||||
link: json["link"]);
|
||||
link: json["link"],
|
||||
source: json["source"],
|
||||
indexerId: json["indexer_id"],
|
||||
isPrivate: json["is_private"] ?? false,
|
||||
downloadFactor: json["download_volume_factor"],
|
||||
uploadFactor: json["upload_volume_factor"]);
|
||||
}
|
||||
Map<String, dynamic> toJson() {
|
||||
final Map<String, dynamic> data = <String, dynamic>{};
|
||||
data['name'] = name;
|
||||
data['size'] = size;
|
||||
data["link"] = link;
|
||||
data["indexer_id"] = indexerId;
|
||||
data["source"] = source;
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,16 +51,31 @@ class GeneralSetting {
|
||||
String? downloadDIr;
|
||||
String? logLevel;
|
||||
String? proxy;
|
||||
bool? enablePlexmatch;
|
||||
bool? allowQiangban;
|
||||
bool? enableNfo;
|
||||
bool? enableAdult;
|
||||
|
||||
GeneralSetting(
|
||||
{this.tmdbApiKey, this.downloadDIr, this.logLevel, this.proxy});
|
||||
{this.tmdbApiKey,
|
||||
this.downloadDIr,
|
||||
this.logLevel,
|
||||
this.proxy,
|
||||
this.enablePlexmatch,
|
||||
this.enableNfo,
|
||||
this.allowQiangban,
|
||||
this.enableAdult});
|
||||
|
||||
factory GeneralSetting.fromJson(Map<String, dynamic> json) {
|
||||
return GeneralSetting(
|
||||
tmdbApiKey: json["tmdb_api_key"],
|
||||
downloadDIr: json["download_dir"],
|
||||
logLevel: json["log_level"],
|
||||
proxy: json["proxy"]);
|
||||
proxy: json["proxy"],
|
||||
enableAdult: json["enable_adult_content"]??false,
|
||||
allowQiangban: json["allow_qiangban"] ?? false,
|
||||
enableNfo: json["enable_nfo"] ?? false,
|
||||
enablePlexmatch: json["enable_plexmatch"] ?? false);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
@@ -69,6 +84,10 @@ class GeneralSetting {
|
||||
data['download_dir'] = downloadDIr;
|
||||
data["log_level"] = logLevel;
|
||||
data["proxy"] = proxy;
|
||||
data["enable_plexmatch"] = enablePlexmatch;
|
||||
data["allow_qiangban"] = allowQiangban;
|
||||
data["enable_nfo"] = enableNfo;
|
||||
data["enable_adult_content"] = enableAdult;
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -123,20 +142,37 @@ class Indexer {
|
||||
String? url;
|
||||
String? apiKey;
|
||||
int? id;
|
||||
int? priority;
|
||||
double? seedRatio;
|
||||
bool? disabled;
|
||||
|
||||
Indexer({this.name, this.url, this.apiKey});
|
||||
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'];
|
||||
url = json['url'];
|
||||
apiKey = json['api_key'];
|
||||
id = json["id"];
|
||||
priority = json["priority"];
|
||||
seedRatio = json["seed_ratio"] ?? 0;
|
||||
disabled = json["disabled"] ?? false;
|
||||
}
|
||||
Map<String, dynamic> toJson() {
|
||||
final Map<String, dynamic> data = <String, dynamic>{};
|
||||
data['name'] = name;
|
||||
data['url'] = url;
|
||||
data['api_key'] = apiKey;
|
||||
data["id"] = id;
|
||||
data["priority"] = priority;
|
||||
data["seed_ratio"] = seedRatio;
|
||||
data["disabled"] = disabled;
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -193,7 +229,8 @@ class DownloadClient {
|
||||
String? url;
|
||||
String? user;
|
||||
String? password;
|
||||
|
||||
bool? removeCompletedDownloads;
|
||||
bool? removeFailedDownloads;
|
||||
DownloadClient(
|
||||
{this.id,
|
||||
this.enable,
|
||||
@@ -201,7 +238,9 @@ class DownloadClient {
|
||||
this.implementation,
|
||||
this.url,
|
||||
this.user,
|
||||
this.password});
|
||||
this.password,
|
||||
this.removeCompletedDownloads = true,
|
||||
this.removeFailedDownloads = true});
|
||||
|
||||
DownloadClient.fromJson(Map<String, dynamic> json) {
|
||||
id = json['id'];
|
||||
@@ -211,6 +250,8 @@ class DownloadClient {
|
||||
url = json['url'];
|
||||
user = json['user'];
|
||||
password = json['password'];
|
||||
removeCompletedDownloads = json["remove_completed_downloads"] ?? false;
|
||||
removeFailedDownloads = json["remove_failed_downloads"] ?? false;
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
@@ -222,6 +263,8 @@ class DownloadClient {
|
||||
data['url'] = url;
|
||||
data['user'] = user;
|
||||
data['password'] = password;
|
||||
data["remove_completed_downloads"] = removeCompletedDownloads;
|
||||
data["remove_failed_downloads"] = removeFailedDownloads;
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -269,6 +312,8 @@ class Storage {
|
||||
this.id,
|
||||
this.name,
|
||||
this.implementation,
|
||||
this.tvPath,
|
||||
this.moviePath,
|
||||
this.settings,
|
||||
this.isDefault,
|
||||
});
|
||||
@@ -276,6 +321,8 @@ class Storage {
|
||||
final int? id;
|
||||
final String? name;
|
||||
final String? implementation;
|
||||
final String? tvPath;
|
||||
final String? moviePath;
|
||||
final Map<String, dynamic>? settings;
|
||||
final bool? isDefault;
|
||||
|
||||
@@ -284,6 +331,8 @@ class Storage {
|
||||
id: json1["id"],
|
||||
name: json1["name"],
|
||||
implementation: json1["implementation"],
|
||||
tvPath: json1["tv_path"],
|
||||
moviePath: json1["movie_path"],
|
||||
settings: json.decode(json1["settings"]),
|
||||
isDefault: json1["default"]);
|
||||
}
|
||||
@@ -292,6 +341,8 @@ class Storage {
|
||||
"id": id,
|
||||
"name": name,
|
||||
"implementation": implementation,
|
||||
"tv_path": tvPath,
|
||||
"movie_path": moviePath,
|
||||
"settings": settings,
|
||||
"default": isDefault,
|
||||
};
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:quiver/strings.dart';
|
||||
import 'package:ui/providers/APIs.dart';
|
||||
import 'package:ui/providers/server_response.dart';
|
||||
|
||||
final tvWatchlistDataProvider = FutureProvider.autoDispose((ref) async {
|
||||
final dio = await APIs.getDio();
|
||||
final dio = APIs.getDio();
|
||||
var resp = await dio.get(APIs.watchlistTvUrl);
|
||||
var sp = ServerResponse.fromJson(resp.data);
|
||||
List<MediaDetail> favList = List.empty(growable: true);
|
||||
@@ -17,10 +19,17 @@ final tvWatchlistDataProvider = FutureProvider.autoDispose((ref) async {
|
||||
return favList;
|
||||
});
|
||||
|
||||
typedef NamingType = ({int id, String mediaType});
|
||||
|
||||
final suggestNameDataProvider = FutureProvider.autoDispose.family(
|
||||
(ref, int arg) async {
|
||||
final dio = await APIs.getDio();
|
||||
var resp = await dio.get(APIs.suggestedTvName + arg.toString());
|
||||
(ref, NamingType arg) async {
|
||||
final dio = APIs.getDio();
|
||||
Response<dynamic> resp;
|
||||
if (arg.mediaType == "tv") {
|
||||
resp = await dio.get(APIs.suggestedTvName + arg.id.toString());
|
||||
} else {
|
||||
resp = await dio.get(APIs.suggestedMovieName + arg.id.toString());
|
||||
}
|
||||
var sp = ServerResponse.fromJson(resp.data);
|
||||
if (sp.code != 0) {
|
||||
throw sp.message;
|
||||
@@ -83,16 +92,24 @@ class SearchPageData
|
||||
state = newState;
|
||||
}
|
||||
|
||||
Future<void> submit2Watchlist(int tmdbId, int storageId, String resolution,
|
||||
String mediaType, String folder, bool downloadHistoryEpisodes) async {
|
||||
final dio = await APIs.getDio();
|
||||
Future<void> submit2Watchlist(
|
||||
int tmdbId,
|
||||
int storageId,
|
||||
String resolution,
|
||||
String mediaType,
|
||||
String folder,
|
||||
bool downloadHistoryEpisodes,
|
||||
RangeValues limiter) async {
|
||||
final dio = APIs.getDio();
|
||||
if (mediaType == "tv") {
|
||||
var resp = await dio.post(APIs.watchlistTvUrl, data: {
|
||||
"tmdb_id": tmdbId,
|
||||
"storage_id": storageId,
|
||||
"resolution": resolution,
|
||||
"folder": folder,
|
||||
"download_history_episodes":downloadHistoryEpisodes
|
||||
"download_history_episodes": downloadHistoryEpisodes,
|
||||
"size_min": (limiter.start * 1000*1000).toInt(),
|
||||
"size_max": (limiter.end * 1000*1000).toInt(),
|
||||
});
|
||||
var sp = ServerResponse.fromJson(resp.data);
|
||||
if (sp.code != 0) {
|
||||
@@ -104,7 +121,9 @@ class SearchPageData
|
||||
"tmdb_id": tmdbId,
|
||||
"storage_id": storageId,
|
||||
"resolution": resolution,
|
||||
"folder": folder
|
||||
"folder": folder,
|
||||
"size_min": (limiter.start * 1000).toInt(),
|
||||
"size_max": (limiter.end * 1000).toInt(),
|
||||
});
|
||||
var sp = ServerResponse.fromJson(resp.data);
|
||||
if (sp.code != 0) {
|
||||
@@ -147,22 +166,23 @@ class MediaDetail {
|
||||
String? resolution;
|
||||
int? storageId;
|
||||
String? airDate;
|
||||
String? status;
|
||||
int? monitoredNum;
|
||||
int? downloadedNum;
|
||||
|
||||
MediaDetail({
|
||||
this.id,
|
||||
this.tmdbId,
|
||||
this.mediaType,
|
||||
this.name,
|
||||
this.originalName,
|
||||
this.overview,
|
||||
this.posterPath,
|
||||
this.createdAt,
|
||||
this.resolution,
|
||||
this.storageId,
|
||||
this.airDate,
|
||||
this.status,
|
||||
});
|
||||
MediaDetail(
|
||||
{this.id,
|
||||
this.tmdbId,
|
||||
this.mediaType,
|
||||
this.name,
|
||||
this.originalName,
|
||||
this.overview,
|
||||
this.posterPath,
|
||||
this.createdAt,
|
||||
this.resolution,
|
||||
this.storageId,
|
||||
this.airDate,
|
||||
this.monitoredNum,
|
||||
this.downloadedNum});
|
||||
|
||||
MediaDetail.fromJson(Map<String, dynamic> json) {
|
||||
id = json['id'];
|
||||
@@ -176,7 +196,8 @@ class MediaDetail {
|
||||
resolution = json["resolution"];
|
||||
storageId = json["storage_id"];
|
||||
airDate = json["air_date"];
|
||||
status = json["status"];
|
||||
monitoredNum = json["monitored_num"] ?? 0;
|
||||
downloadedNum = json["downloaded_num"] ?? 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,4 +262,3 @@ class SearchResult {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,354 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:ui/providers/APIs.dart';
|
||||
import 'package:ui/providers/settings.dart';
|
||||
import 'package:ui/providers/welcome_data.dart';
|
||||
import 'package:ui/widgets/utils.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
|
||||
class SearchPage extends ConsumerStatefulWidget {
|
||||
const SearchPage({super.key, this.query});
|
||||
|
||||
static const route = "/search";
|
||||
final String? query;
|
||||
|
||||
@override
|
||||
ConsumerState<ConsumerStatefulWidget> createState() {
|
||||
return _SearchPageState();
|
||||
}
|
||||
}
|
||||
|
||||
class _SearchPageState extends ConsumerState<SearchPage> {
|
||||
List<dynamic> list = List.empty();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final q = widget.query ?? "";
|
||||
var searchList = ref.watch(searchPageDataProvider(q));
|
||||
|
||||
List<Widget> res = searchList.when(
|
||||
data: (data) {
|
||||
if (data.isEmpty) {
|
||||
return [Container(
|
||||
height: MediaQuery.of(context).size.height * 0.6,
|
||||
alignment: Alignment.center,
|
||||
child: const Text(
|
||||
"啥都没有...",
|
||||
style: TextStyle(fontSize: 16),
|
||||
))];
|
||||
}
|
||||
var cards = List<Widget>.empty(growable: true);
|
||||
for (final item in data) {
|
||||
cards.add(Card(
|
||||
margin: const EdgeInsets.all(4),
|
||||
clipBehavior: Clip.hardEdge,
|
||||
child: InkWell(
|
||||
//splashColor: Colors.blue.withAlpha(30),
|
||||
onTap: () {
|
||||
if (item.inWatchlist != true) {
|
||||
_showSubmitDialog(context, item);
|
||||
}
|
||||
},
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Flexible(
|
||||
child: SizedBox(
|
||||
width: 150,
|
||||
height: 200,
|
||||
child: Image.network(
|
||||
"${APIs.tmdbImgBaseUrl}${item.posterPath}",
|
||||
fit: BoxFit.contain,
|
||||
),
|
||||
),
|
||||
),
|
||||
Flexible(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
"${item.name} ${item.name != item.originalName ? item.originalName : ''} (${item.firstAirDate?.year})",
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(
|
||||
width: 10,
|
||||
),
|
||||
item.mediaType == "tv"
|
||||
? const Chip(
|
||||
avatar: Icon(Icons.live_tv),
|
||||
label: Text(
|
||||
"电视剧",
|
||||
))
|
||||
: const Chip(
|
||||
avatar: Icon(Icons.movie),
|
||||
label: Text("电影")),
|
||||
item.inWatchlist == true
|
||||
? const Chip(
|
||||
label: Icon(
|
||||
Icons.done,
|
||||
color: Colors.green,
|
||||
))
|
||||
: const Text("")
|
||||
],
|
||||
),
|
||||
const Text(""),
|
||||
item.originCountry.isNotEmpty
|
||||
? Text("国家:${item.originCountry[0]}")
|
||||
: Container(),
|
||||
Text("${item.overview}")
|
||||
],
|
||||
),
|
||||
)
|
||||
],
|
||||
),
|
||||
)));
|
||||
}
|
||||
return cards;
|
||||
},
|
||||
error: (err, trace) => [Text("$err")],
|
||||
loading: () => [const MyProgressIndicator()]);
|
||||
|
||||
var f = NotificationListener(
|
||||
onNotification: (ScrollNotification scrollInfo) {
|
||||
if (scrollInfo is ScrollEndNotification &&
|
||||
scrollInfo.metrics.axisDirection == AxisDirection.down &&
|
||||
scrollInfo.metrics.pixels >= scrollInfo.metrics.maxScrollExtent) {
|
||||
ref.read(searchPageDataProvider(q).notifier).queryNextPage();
|
||||
}
|
||||
return true;
|
||||
},
|
||||
child: ListView(
|
||||
children: res,
|
||||
));
|
||||
return Column(
|
||||
children: [
|
||||
TextField(
|
||||
autofocus: true,
|
||||
controller: TextEditingController(text: q),
|
||||
onSubmitted: (value) async {
|
||||
context.go(
|
||||
Uri(path: SearchPage.route, queryParameters: {'query': value})
|
||||
.toString());
|
||||
},
|
||||
decoration: const InputDecoration(
|
||||
labelText: "搜索",
|
||||
hintText: "搜索剧集名称",
|
||||
prefixIcon: Icon(Icons.search)),
|
||||
),
|
||||
Expanded(child: f)
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _showSubmitDialog(BuildContext context, SearchResult item) {
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
builder: (BuildContext context) {
|
||||
return Consumer(
|
||||
builder: (context, ref, _) {
|
||||
String resSelected = "1080p";
|
||||
int storageSelected = 0;
|
||||
var storage = ref.watch(storageSettingProvider);
|
||||
var name = ref.watch(suggestNameDataProvider(item.id!));
|
||||
bool downloadHistoryEpisodes = false;
|
||||
bool buttonTapped = false;
|
||||
|
||||
var pathController = TextEditingController();
|
||||
return AlertDialog(
|
||||
title: Text('添加剧集: ${item.name}'),
|
||||
content: SizedBox(
|
||||
width: 500,
|
||||
height: 200,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
DropdownMenu(
|
||||
width: 200,
|
||||
label: const Text("清晰度"),
|
||||
initialSelection: resSelected,
|
||||
dropdownMenuEntries: const [
|
||||
DropdownMenuEntry(value: "720p", label: "720p"),
|
||||
DropdownMenuEntry(value: "1080p", label: "1080p"),
|
||||
DropdownMenuEntry(value: "4k", label: "4k"),
|
||||
],
|
||||
onSelected: (value) {
|
||||
setState(() {
|
||||
resSelected = value!;
|
||||
});
|
||||
},
|
||||
),
|
||||
storage.when(
|
||||
data: (v) {
|
||||
return StatefulBuilder(
|
||||
builder: (context, setState) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
DropdownMenu(
|
||||
width: 200,
|
||||
label: const Text("存储位置"),
|
||||
initialSelection: storageSelected,
|
||||
dropdownMenuEntries: v
|
||||
.map((s) => DropdownMenuEntry(
|
||||
label: s.name!, value: s.id))
|
||||
.toList(),
|
||||
onSelected: (value) {
|
||||
setState(() {
|
||||
storageSelected = value!;
|
||||
});
|
||||
},
|
||||
),
|
||||
item.mediaType == "tv"
|
||||
? name.when(
|
||||
data: (s) {
|
||||
return storageSelected == 0
|
||||
? const Text("")
|
||||
: () {
|
||||
final storage = v
|
||||
.where((e) =>
|
||||
e.id ==
|
||||
storageSelected)
|
||||
.first;
|
||||
final path = storage
|
||||
.settings!["tv_path"];
|
||||
|
||||
pathController.text = s;
|
||||
return SizedBox(
|
||||
//width: 300,
|
||||
child: TextField(
|
||||
controller:
|
||||
pathController,
|
||||
decoration:
|
||||
InputDecoration(
|
||||
labelText:
|
||||
"存储路径",
|
||||
prefix:
|
||||
Text(path)),
|
||||
),
|
||||
);
|
||||
}();
|
||||
},
|
||||
error: (error, stackTrace) =>
|
||||
Text("$error"),
|
||||
loading: () =>
|
||||
const MyProgressIndicator(
|
||||
size: 20,
|
||||
),
|
||||
)
|
||||
: Text(""),
|
||||
item.mediaType == "tv"
|
||||
? SizedBox(
|
||||
width: 250,
|
||||
child: CheckboxListTile(
|
||||
title: const Text("是否下载往期剧集"),
|
||||
value: downloadHistoryEpisodes,
|
||||
onChanged: (v) {
|
||||
setState(() {
|
||||
downloadHistoryEpisodes = v!;
|
||||
});
|
||||
}),
|
||||
)
|
||||
: const SizedBox(),
|
||||
],
|
||||
);
|
||||
});
|
||||
},
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator()),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: <Widget>[
|
||||
TextButton(
|
||||
style: TextButton.styleFrom(
|
||||
textStyle: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
child: const Text('取消'),
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
),
|
||||
TextButton(
|
||||
style: TextButton.styleFrom(
|
||||
textStyle: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
child: const Text('确定'),
|
||||
onPressed: () async {
|
||||
if (buttonTapped) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
buttonTapped = true;
|
||||
});
|
||||
|
||||
await ref
|
||||
.read(searchPageDataProvider(widget.query ?? "")
|
||||
.notifier)
|
||||
.submit2Watchlist(
|
||||
item.id!,
|
||||
storageSelected,
|
||||
resSelected,
|
||||
item.mediaType!,
|
||||
pathController.text,
|
||||
downloadHistoryEpisodes)
|
||||
.then((v) {
|
||||
Utils.showSnakeBar("添加成功");
|
||||
Navigator.of(context).pop();
|
||||
}).onError((error, trace) {
|
||||
Utils.showSnakeBar("添加失败:$error");
|
||||
});
|
||||
setState(() {
|
||||
buttonTapped = false;
|
||||
});
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class SearchBarApp extends StatefulWidget {
|
||||
const SearchBarApp({
|
||||
super.key,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
final ValueChanged<String> onChanged;
|
||||
@override
|
||||
State<SearchBarApp> createState() => _SearchBarAppState();
|
||||
}
|
||||
|
||||
class _SearchBarAppState extends State<SearchBarApp> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SearchAnchor(
|
||||
builder: (BuildContext context, SearchController controller) {
|
||||
return SearchBar(
|
||||
controller: controller,
|
||||
padding: const WidgetStatePropertyAll<EdgeInsets>(
|
||||
EdgeInsets.symmetric(horizontal: 16.0)),
|
||||
onSubmitted: (value) => {widget.onChanged(controller.text)},
|
||||
leading: const Icon(Icons.search),
|
||||
);
|
||||
}, suggestionsBuilder: (BuildContext context, SearchController controller) {
|
||||
return List<ListTile>.generate(0, (int index) {
|
||||
final String item = 'item $index';
|
||||
return ListTile(
|
||||
title: Text(item),
|
||||
onTap: () {
|
||||
setState(() {
|
||||
controller.closeView(item);
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
158
ui/lib/search_page/search.dart
Normal file
158
ui/lib/search_page/search.dart
Normal file
@@ -0,0 +1,158 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:ui/providers/APIs.dart';
|
||||
import 'package:ui/providers/welcome_data.dart';
|
||||
import 'package:ui/search_page/submit_dialog.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
|
||||
class SearchPage extends ConsumerStatefulWidget {
|
||||
const SearchPage({super.key, this.query});
|
||||
|
||||
static const route = "/search";
|
||||
final String? query;
|
||||
|
||||
@override
|
||||
ConsumerState<ConsumerStatefulWidget> createState() {
|
||||
return _SearchPageState();
|
||||
}
|
||||
}
|
||||
|
||||
class _SearchPageState extends ConsumerState<SearchPage> {
|
||||
List<dynamic> list = List.empty();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final q = widget.query ?? "";
|
||||
var searchList = ref.watch(searchPageDataProvider(q));
|
||||
|
||||
List<Widget> res = searchList.when(
|
||||
data: (data) {
|
||||
if (data.isEmpty) {
|
||||
return [
|
||||
Container(
|
||||
height: MediaQuery.of(context).size.height * 0.6,
|
||||
alignment: Alignment.center,
|
||||
child: const Text(
|
||||
"啥都没有...",
|
||||
style: TextStyle(fontSize: 16),
|
||||
))
|
||||
];
|
||||
}
|
||||
var cards = List<Widget>.empty(growable: true);
|
||||
for (final item in data) {
|
||||
cards.add(Card(
|
||||
margin: const EdgeInsets.all(4),
|
||||
clipBehavior: Clip.hardEdge,
|
||||
child: InkWell(
|
||||
//splashColor: Colors.blue.withAlpha(30),
|
||||
onTap: () {
|
||||
if (item.inWatchlist != true) {
|
||||
_showSubmitDialog(context, item);
|
||||
}
|
||||
},
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Flexible(
|
||||
child: SizedBox(
|
||||
width: 150,
|
||||
height: 200,
|
||||
child: Image.network(
|
||||
"${APIs.tmdbImgBaseUrl}${item.posterPath}",
|
||||
fit: BoxFit.contain,
|
||||
),
|
||||
),
|
||||
),
|
||||
Flexible(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
"${item.name} ${item.name != item.originalName ? item.originalName : ''} (${item.firstAirDate?.year})",
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(
|
||||
width: 10,
|
||||
),
|
||||
item.mediaType == "tv"
|
||||
? const Chip(
|
||||
avatar: Icon(Icons.live_tv),
|
||||
label: Text(
|
||||
"剧集",
|
||||
))
|
||||
: const Chip(
|
||||
avatar: Icon(Icons.movie),
|
||||
label: Text("电影")),
|
||||
item.inWatchlist == true
|
||||
? const Chip(
|
||||
label: Icon(
|
||||
Icons.done,
|
||||
color: Colors.green,
|
||||
))
|
||||
: const Text("")
|
||||
],
|
||||
),
|
||||
const Text(""),
|
||||
item.originCountry.isNotEmpty
|
||||
? Text("国家:${item.originCountry[0]}")
|
||||
: Container(),
|
||||
Text("${item.overview}")
|
||||
],
|
||||
),
|
||||
)
|
||||
],
|
||||
),
|
||||
)));
|
||||
}
|
||||
return cards;
|
||||
},
|
||||
error: (err, trace) => [Text("$err")],
|
||||
loading: () => [const MyProgressIndicator()]);
|
||||
|
||||
var f = NotificationListener(
|
||||
onNotification: (ScrollNotification scrollInfo) {
|
||||
if (scrollInfo is ScrollEndNotification &&
|
||||
scrollInfo.metrics.axisDirection == AxisDirection.down &&
|
||||
scrollInfo.metrics.pixels >= scrollInfo.metrics.maxScrollExtent) {
|
||||
ref.read(searchPageDataProvider(q).notifier).queryNextPage();
|
||||
}
|
||||
return true;
|
||||
},
|
||||
child: ListView(
|
||||
children: res,
|
||||
));
|
||||
return Column(
|
||||
children: [
|
||||
TextField(
|
||||
autofocus: true,
|
||||
controller: TextEditingController(text: q),
|
||||
onSubmitted: (value) async {
|
||||
context.go(
|
||||
Uri(path: SearchPage.route, queryParameters: {'query': value})
|
||||
.toString());
|
||||
},
|
||||
decoration: const InputDecoration(
|
||||
labelText: "搜索",
|
||||
hintText: "搜索剧集名称",
|
||||
prefixIcon: Icon(Icons.search)),
|
||||
),
|
||||
Expanded(child: f)
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _showSubmitDialog(BuildContext context, SearchResult item) {
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
builder: (BuildContext context) {
|
||||
return SubmitSearchResult(
|
||||
item: item,
|
||||
query: widget.query!,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
201
ui/lib/search_page/submit_dialog.dart
Normal file
201
ui/lib/search_page/submit_dialog.dart
Normal file
@@ -0,0 +1,201 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_form_builder/flutter_form_builder.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:ui/providers/settings.dart';
|
||||
import 'package:ui/providers/welcome_data.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
import 'package:ui/widgets/utils.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
|
||||
class SubmitSearchResult extends ConsumerStatefulWidget {
|
||||
final SearchResult item;
|
||||
final String query;
|
||||
const SubmitSearchResult(
|
||||
{super.key, required this.item, required this.query});
|
||||
|
||||
@override
|
||||
ConsumerState<ConsumerStatefulWidget> createState() {
|
||||
return _SubmitSearchResultState();
|
||||
}
|
||||
}
|
||||
|
||||
class _SubmitSearchResultState extends ConsumerState<SubmitSearchResult> {
|
||||
final _formKey = GlobalKey<FormBuilderState>();
|
||||
bool enabledSizedLimiter = false;
|
||||
double sizeMax = 5000;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
int storageSelected = 0;
|
||||
var storage = ref.watch(storageSettingProvider);
|
||||
var name = ref.watch(suggestNameDataProvider(
|
||||
(id: widget.item.id!, mediaType: widget.item.mediaType!)));
|
||||
|
||||
var pathController = TextEditingController();
|
||||
return AlertDialog(
|
||||
title: Text('添加: ${widget.item.name}'),
|
||||
content: SizedBox(
|
||||
width: 500,
|
||||
height: 400,
|
||||
child: FormBuilder(
|
||||
key: _formKey,
|
||||
initialValue: const {
|
||||
"resolution": "1080p",
|
||||
"storage": null,
|
||||
"folder": "",
|
||||
"history_episodes": false,
|
||||
"eanble_size_limier": false,
|
||||
"size_limiter": RangeValues(400, 4000),
|
||||
},
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
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")),
|
||||
],
|
||||
),
|
||||
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(
|
||||
() {
|
||||
storageSelected = v!;
|
||||
},
|
||||
);
|
||||
},
|
||||
name: "storage",
|
||||
decoration:
|
||||
const InputDecoration(labelText: "存储位置"),
|
||||
items: v
|
||||
.map((s) => DropdownMenuItem(
|
||||
value: s.id, child: Text(s.name!)))
|
||||
.toList(),
|
||||
),
|
||||
name.when(
|
||||
data: (s) {
|
||||
if (storageSelected == 0) {
|
||||
storageSelected = id1;
|
||||
}
|
||||
return storageSelected == 0
|
||||
? const Text("")
|
||||
: () {
|
||||
final storage = v
|
||||
.where((e) => e.id == storageSelected)
|
||||
.first;
|
||||
final path = widget.item.mediaType == "tv"
|
||||
? storage.tvPath
|
||||
: storage.moviePath;
|
||||
|
||||
pathController.text = s;
|
||||
return SizedBox(
|
||||
//width: 300,
|
||||
child: FormBuilderTextField(
|
||||
name: "folder",
|
||||
controller: pathController,
|
||||
decoration: InputDecoration(
|
||||
labelText: "存储路径",
|
||||
prefix: Text(path ?? "unknown")),
|
||||
),
|
||||
);
|
||||
}();
|
||||
},
|
||||
error: (error, stackTrace) => Text("$error"),
|
||||
loading: () => const MyProgressIndicator(
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
FormBuilderSwitch(
|
||||
name: "eanble_size_limier",
|
||||
title: Text(widget.item.mediaType == "tv"
|
||||
? "是否限制每集文件大小"
|
||||
: "是否限制电影文件大小"),
|
||||
onChanged: (value) {
|
||||
setState(
|
||||
() {
|
||||
enabledSizedLimiter = value!;
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
enabledSizedLimiter
|
||||
? const MyRangeSlider(name: "size_limiter")
|
||||
: const SizedBox(),
|
||||
widget.item.mediaType == "tv"
|
||||
? SizedBox(
|
||||
width: 250,
|
||||
child: FormBuilderCheckbox(
|
||||
name: "history_episodes",
|
||||
title: const Text("是否下载往期剧集"),
|
||||
),
|
||||
)
|
||||
: const SizedBox(),
|
||||
],
|
||||
);
|
||||
});
|
||||
},
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator()),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: <Widget>[
|
||||
TextButton(
|
||||
style: TextButton.styleFrom(
|
||||
textStyle: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
child: const Text('取消'),
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
),
|
||||
LoadingTextButton(
|
||||
// style: TextButton.styleFrom(
|
||||
// textStyle: Theme.of(context).textTheme.labelLarge,
|
||||
// ),
|
||||
label: const Text('确定'),
|
||||
onPressed: () async {
|
||||
if (_formKey.currentState!.saveAndValidate()) {
|
||||
final values = _formKey.currentState!.value;
|
||||
await ref
|
||||
.read(searchPageDataProvider(widget.query).notifier)
|
||||
.submit2Watchlist(
|
||||
widget.item.id!,
|
||||
values["storage"],
|
||||
values["resolution"],
|
||||
widget.item.mediaType!,
|
||||
values["folder"],
|
||||
values["history_episodes"] ?? false,
|
||||
enabledSizedLimiter
|
||||
? values["size_limiter"]
|
||||
: const RangeValues(-1, -1))
|
||||
.then((v) {
|
||||
Navigator.of(context).pop();
|
||||
showSnakeBar("添加成功:${widget.item.name}");
|
||||
});
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String readableSize(String v) {
|
||||
if (v.endsWith("K")) {
|
||||
return v.replaceAll("K", " GB");
|
||||
}
|
||||
return "$v MB";
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ class AuthSettings extends ConsumerStatefulWidget {
|
||||
}
|
||||
|
||||
class _AuthState extends ConsumerState<AuthSettings> {
|
||||
final _formKey2 = GlobalKey<FormBuilderState>();
|
||||
final _formKey2 = GlobalKey<FormBuilderState>();
|
||||
bool? _enableAuth;
|
||||
|
||||
@override
|
||||
@@ -84,12 +84,11 @@ class _AuthState extends ConsumerState<AuthSettings> {
|
||||
var f = ref
|
||||
.read(authSettingProvider.notifier)
|
||||
.updateAuthSetting(_enableAuth!,
|
||||
values["user"], values["password"]);
|
||||
f.then((v) {
|
||||
Utils.showSnakeBar("更新成功");
|
||||
}).onError((e, s) {
|
||||
Utils.showSnakeBar("更新失败:$e");
|
||||
values["user"], values["password"])
|
||||
.then((v) {
|
||||
showSnakeBar("更新成功");
|
||||
});
|
||||
showLoadingWithFuture(f);
|
||||
}
|
||||
}))
|
||||
],
|
||||
@@ -98,5 +97,4 @@ class _AuthState extends ConsumerState<AuthSettings> {
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:ui/widgets/utils.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
|
||||
Future<void> showSettingDialog(BuildContext context,String title, bool showDelete, Widget body,
|
||||
Future Function() onSubmit, Future Function() onDelete) {
|
||||
Future<void> showSettingDialog(
|
||||
BuildContext context,
|
||||
String title,
|
||||
bool showDelete,
|
||||
Widget body,
|
||||
Future Function() onSubmit,
|
||||
Future Function() onDelete) {
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
barrierDismissible: true,
|
||||
@@ -11,23 +16,17 @@ Future<void> showSettingDialog(BuildContext context,String title, bool showDelet
|
||||
title: Text(title),
|
||||
content: SingleChildScrollView(
|
||||
child: SizedBox(
|
||||
width: 300,
|
||||
width: 400,
|
||||
child: body,
|
||||
),
|
||||
),
|
||||
actions: <Widget>[
|
||||
showDelete
|
||||
? TextButton(
|
||||
onPressed: () {
|
||||
final f = onDelete();
|
||||
f.then((v) {
|
||||
Utils.showSnakeBar("删除成功");
|
||||
Navigator.of(context).pop();
|
||||
}).onError((e, s) {
|
||||
Utils.showSnakeBar("删除失败:$e");
|
||||
});
|
||||
? LoadingTextButton(
|
||||
onPressed: () async {
|
||||
await onDelete().then((v) => Navigator.of(context).pop());
|
||||
},
|
||||
child: const Text(
|
||||
label: const Text(
|
||||
'删除',
|
||||
style: TextStyle(color: Colors.red),
|
||||
))
|
||||
@@ -35,18 +34,10 @@ Future<void> showSettingDialog(BuildContext context,String title, bool showDelet
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('取消')),
|
||||
TextButton(
|
||||
child: const Text('确定'),
|
||||
onPressed: () {
|
||||
final f = onSubmit();
|
||||
f.then((v) {
|
||||
Utils.showSnakeBar("操作成功");
|
||||
Navigator.of(context).pop();
|
||||
}).onError((e, s) {
|
||||
if (e.toString() != "validation_error") {
|
||||
Utils.showSnakeBar("操作失败:$e");
|
||||
}
|
||||
});
|
||||
LoadingTextButton(
|
||||
label: const Text('确定'),
|
||||
onPressed: () async {
|
||||
await onSubmit().then((v) => Navigator.of(context).pop());
|
||||
},
|
||||
),
|
||||
],
|
||||
|
||||
@@ -53,7 +53,9 @@ class _DownloaderState extends ConsumerState<DownloaderSettings> {
|
||||
"url": client.url,
|
||||
"user": client.user,
|
||||
"password": client.password,
|
||||
"impl": "transmission"
|
||||
"impl": "transmission",
|
||||
"remove_completed_downloads": client.removeCompletedDownloads,
|
||||
"remove_failed_downloads": client.removeFailedDownloads,
|
||||
},
|
||||
child: Column(
|
||||
children: [
|
||||
@@ -82,6 +84,12 @@ class _DownloaderState extends ConsumerState<DownloaderSettings> {
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderSwitch(
|
||||
name: "remove_completed_downloads",
|
||||
title: const Text("任务完成后删除")),
|
||||
FormBuilderSwitch(
|
||||
name: "remove_failed_downloads",
|
||||
title: const Text("任务失败后删除")),
|
||||
StatefulBuilder(
|
||||
builder: (BuildContext context, StateSetter setState) {
|
||||
return Column(
|
||||
@@ -137,7 +145,9 @@ class _DownloaderState extends ConsumerState<DownloaderSettings> {
|
||||
implementation: values["impl"],
|
||||
url: values["url"],
|
||||
user: _enableAuth ? values["user"] : null,
|
||||
password: _enableAuth ? values["password"] : null));
|
||||
password: _enableAuth ? values["password"] : null,
|
||||
removeCompletedDownloads: values["remove_completed_downloads"],
|
||||
removeFailedDownloads: values["remove_failed_downloads"]));
|
||||
} else {
|
||||
throw "validation_error";
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@ 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/widgets/utils.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
import 'package:ui/widgets/utils.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
|
||||
class GeneralSettings extends ConsumerStatefulWidget {
|
||||
@@ -17,9 +17,8 @@ class GeneralSettings extends ConsumerStatefulWidget {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class _GeneralState extends ConsumerState<GeneralSettings> {
|
||||
final _formKey = GlobalKey<FormBuilderState>();
|
||||
final _formKey = GlobalKey<FormBuilderState>();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -35,6 +34,10 @@ class _GeneralState extends ConsumerState<GeneralSettings> {
|
||||
"download_dir": v.downloadDIr,
|
||||
"log_level": v.logLevel,
|
||||
"proxy": v.proxy,
|
||||
"enable_plexmatch": v.enablePlexmatch,
|
||||
"allow_qiangban": v.allowQiangban,
|
||||
"enable_nfo": v.enableNfo,
|
||||
"enable_adult": v.enableAdult,
|
||||
},
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -59,7 +62,7 @@ class _GeneralState extends ConsumerState<GeneralSettings> {
|
||||
name: "proxy",
|
||||
decoration: const InputDecoration(
|
||||
labelText: "代理地址",
|
||||
icon: Icon(Icons.folder),
|
||||
icon: Icon(Icons.web),
|
||||
helperText: "后台联网代理地址,留空表示不启用代理"),
|
||||
),
|
||||
SizedBox(
|
||||
@@ -79,6 +82,39 @@ class _GeneralState extends ConsumerState<GeneralSettings> {
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 300,
|
||||
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(
|
||||
padding: const EdgeInsets.only(top: 28.0),
|
||||
@@ -96,12 +132,14 @@ class _GeneralState extends ConsumerState<GeneralSettings> {
|
||||
tmdbApiKey: values["tmdb_api"],
|
||||
downloadDIr: values["download_dir"],
|
||||
logLevel: values["log_level"],
|
||||
proxy: values["proxy"]));
|
||||
f.then((v) {
|
||||
Utils.showSnakeBar("更新成功");
|
||||
}).onError((e, s) {
|
||||
Utils.showSnakeBar("更新失败:$e");
|
||||
});
|
||||
proxy: values["proxy"],
|
||||
allowQiangban: values["allow_qiangban"],
|
||||
enableAdult: values["enable_adult"],
|
||||
enableNfo: values["enable_nfo"],
|
||||
enablePlexmatch:
|
||||
values["enable_plexmatch"]))
|
||||
.then((v) => showSnakeBar("更新成功"));
|
||||
showLoadingWithFuture(f);
|
||||
}
|
||||
}),
|
||||
),
|
||||
@@ -113,5 +151,4 @@ class _GeneralState extends ConsumerState<GeneralSettings> {
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import 'package:ui/widgets/progress_indicator.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
|
||||
class IndexerSettings extends ConsumerStatefulWidget {
|
||||
|
||||
const IndexerSettings({super.key});
|
||||
@override
|
||||
ConsumerState<ConsumerStatefulWidget> createState() {
|
||||
@@ -47,7 +46,10 @@ class _IndexerState extends ConsumerState<IndexerSettings> {
|
||||
"name": indexer.name,
|
||||
"url": indexer.url,
|
||||
"api_key": indexer.apiKey,
|
||||
"impl": "torznab"
|
||||
"impl": "torznab",
|
||||
"priority": indexer.priority.toString(),
|
||||
"seed_ratio": indexer.seedRatio.toString(),
|
||||
"disabled": indexer.disabled
|
||||
},
|
||||
child: Column(
|
||||
children: [
|
||||
@@ -76,6 +78,26 @@ class _IndexerState extends ConsumerState<IndexerSettings> {
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "priority",
|
||||
decoration: const InputDecoration(
|
||||
labelText: "索引优先级",
|
||||
helperText: "取值范围1-128, 数值越大,优先级越高",
|
||||
),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.positiveNumber(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "seed_ratio",
|
||||
decoration: const InputDecoration(
|
||||
labelText: "做种率",
|
||||
helperText: "种子的做种率,达到此做种率后,种子才会被删除, 0表示不做种",
|
||||
hintText: "1.0",
|
||||
),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.numeric(),
|
||||
),
|
||||
FormBuilderSwitch(name: "disabled", title: const Text("禁用此索引器"))
|
||||
],
|
||||
),
|
||||
);
|
||||
@@ -87,9 +109,13 @@ class _IndexerState extends ConsumerState<IndexerSettings> {
|
||||
if (_formKey.currentState!.saveAndValidate()) {
|
||||
var values = _formKey.currentState!.value;
|
||||
return ref.read(indexersProvider.notifier).addIndexer(Indexer(
|
||||
id: indexer.id,
|
||||
name: values["name"],
|
||||
url: values["url"],
|
||||
apiKey: values["api_key"]));
|
||||
apiKey: values["api_key"],
|
||||
priority: int.parse(values["priority"]),
|
||||
seedRatio: double.parse(values["seed_ratio"]),
|
||||
disabled: values["disabled"]));
|
||||
} else {
|
||||
throw "validation_error";
|
||||
}
|
||||
|
||||
@@ -45,14 +45,14 @@ class _SystemSettingsPageState extends ConsumerState<SystemSettingsPage> {
|
||||
),
|
||||
ExpansionTile(
|
||||
expandedAlignment: Alignment.centerLeft,
|
||||
childrenPadding: EdgeInsets.fromLTRB(20, 0, 50, 0),
|
||||
childrenPadding: EdgeInsets.fromLTRB(20, 0, 20, 0),
|
||||
initiallyExpanded: false,
|
||||
title: Text("存储"),
|
||||
children: [StorageSettings()],
|
||||
),
|
||||
ExpansionTile(
|
||||
expandedAlignment: Alignment.centerLeft,
|
||||
childrenPadding: EdgeInsets.fromLTRB(20, 0, 50, 0),
|
||||
childrenPadding: EdgeInsets.fromLTRB(20, 0, 20, 0),
|
||||
initiallyExpanded: false,
|
||||
title: Text("通知客户端"),
|
||||
children: [NotifierSettings()],
|
||||
@@ -39,7 +39,7 @@ class _StorageState extends ConsumerState<StorageSettings> {
|
||||
loading: () => const MyProgressIndicator());
|
||||
}
|
||||
|
||||
Future<void> showStorageDetails(Storage s) {
|
||||
Future<void> showStorageDetails(Storage s) {
|
||||
final _formKey = GlobalKey<FormBuilderState>();
|
||||
|
||||
String selectImpl = s.implementation == null ? "local" : s.implementation!;
|
||||
@@ -53,10 +53,9 @@ class _StorageState extends ConsumerState<StorageSettings> {
|
||||
"impl": s.implementation == null ? "local" : s.implementation!,
|
||||
"user": s.settings != null ? s.settings!["user"] ?? "" : "",
|
||||
"password": s.settings != null ? s.settings!["password"] ?? "" : "",
|
||||
"tv_path": s.settings != null ? s.settings!["tv_path"] ?? "" : "",
|
||||
"tv_path": s.tvPath,
|
||||
"url": s.settings != null ? s.settings!["url"] ?? "" : "",
|
||||
"movie_path":
|
||||
s.settings != null ? s.settings!["movie_path"] ?? "" : "",
|
||||
"movie_path": s.moviePath,
|
||||
"change_file_hash": s.settings != null
|
||||
? s.settings!["change_file_hash"] == "true"
|
||||
? true
|
||||
@@ -147,9 +146,9 @@ class _StorageState extends ConsumerState<StorageSettings> {
|
||||
return ref.read(storageSettingProvider.notifier).addStorage(Storage(
|
||||
name: values["name"],
|
||||
implementation: selectImpl,
|
||||
tvPath: values["tv_path"],
|
||||
moviePath: values["movie_path"],
|
||||
settings: {
|
||||
"tv_path": values["tv_path"],
|
||||
"movie_path": values["movie_path"],
|
||||
"url": values["url"],
|
||||
"user": values["user"],
|
||||
"password": values["password"],
|
||||
@@ -168,7 +167,7 @@ class _StorageState extends ConsumerState<StorageSettings> {
|
||||
return ref.read(storageSettingProvider.notifier).deleteStorage(s.id!);
|
||||
}
|
||||
|
||||
return showSettingDialog(context,'存储', s.id != null, widgets, onSubmit, onDelete);
|
||||
return showSettingDialog(
|
||||
context, '存储', s.id != null, widgets, onSubmit, onDelete);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:ui/providers/APIs.dart';
|
||||
import 'package:ui/providers/series_details.dart';
|
||||
import 'package:ui/providers/settings.dart';
|
||||
import 'package:ui/widgets/detail_card.dart';
|
||||
import 'package:ui/widgets/resource_list.dart';
|
||||
import 'package:ui/widgets/utils.dart';
|
||||
import 'package:ui/welcome_page.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
|
||||
class TvDetailsPage extends ConsumerStatefulWidget {
|
||||
static const route = "/series/:id";
|
||||
@@ -33,8 +32,8 @@ class _TvDetailsPageState extends ConsumerState<TvDetailsPage> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final screenWidth = MediaQuery.of(context).size.width;
|
||||
var seriesDetails = ref.watch(mediaDetailsProvider(widget.seriesId));
|
||||
var storage = ref.watch(storageSettingProvider);
|
||||
return seriesDetails.when(
|
||||
data: (details) {
|
||||
Map<int, List<DataRow>> m = {};
|
||||
@@ -50,44 +49,65 @@ class _TvDetailsPageState extends ConsumerState<TvDetailsPage> {
|
||||
Opacity(
|
||||
opacity: 0.7,
|
||||
child: ep.status == "downloading"
|
||||
? const Tooltip(
|
||||
message: "下载中",
|
||||
child: Icon(Icons.downloading),
|
||||
)
|
||||
? const IconButton(
|
||||
tooltip: "下载中",
|
||||
onPressed: null,
|
||||
icon: Icon(Icons.downloading))
|
||||
: (ep.status == "downloaded"
|
||||
? const Tooltip(
|
||||
message: "已下载",
|
||||
child: Icon(Icons.download_done),
|
||||
)
|
||||
: const Tooltip(
|
||||
message: "未下载",
|
||||
child: Icon(Icons.warning_amber_rounded),
|
||||
))),
|
||||
? const IconButton(
|
||||
tooltip: "已下载",
|
||||
onPressed: null,
|
||||
icon: Icon(Icons.download_done))
|
||||
: (ep.monitored == true
|
||||
? 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!, true);
|
||||
},
|
||||
icon: const Icon(Icons.alarm_off)),
|
||||
)))),
|
||||
),
|
||||
DataCell(Row(
|
||||
children: [
|
||||
Tooltip(
|
||||
message: "搜索下载对应剧集",
|
||||
child: IconButton(
|
||||
onPressed: () {
|
||||
ref
|
||||
.read(mediaDetailsProvider(widget.seriesId)
|
||||
.notifier)
|
||||
.searchAndDownload(widget.seriesId,
|
||||
ep.seasonNumber!, ep.episodeNumber!)
|
||||
.then((v) => Utils.showSnakeBar("开始下载: $v"))
|
||||
.onError((error, trace) =>
|
||||
Utils.showSnakeBar("操作失败: $error"));
|
||||
},
|
||||
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,
|
||||
),
|
||||
IconButton(
|
||||
onPressed: () => showAvailableTorrents(widget.seriesId,
|
||||
ep.seasonNumber ?? 0, ep.episodeNumber ?? 0),
|
||||
icon: const Icon(Icons.manage_search))
|
||||
Tooltip(
|
||||
message: "查看可用资源",
|
||||
child: IconButton(
|
||||
onPressed: () => showAvailableTorrents(widget.seriesId,
|
||||
ep.seasonNumber ?? 0, ep.episodeNumber ?? 0),
|
||||
icon: const Icon(Icons.manage_search)),
|
||||
)
|
||||
],
|
||||
))
|
||||
]);
|
||||
@@ -99,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),
|
||||
@@ -106,138 +161,19 @@ 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: () {
|
||||
ref
|
||||
.read(mediaDetailsProvider(widget.seriesId)
|
||||
.notifier)
|
||||
.searchAndDownload(widget.seriesId, k, 0)
|
||||
.then((v) => Utils.showSnakeBar("开始下载: $v"))
|
||||
.onError((error, trace) =>
|
||||
Utils.showSnakeBar("操作失败: $error"));
|
||||
},
|
||||
icon: const Icon(Icons.download)),
|
||||
),
|
||||
const SizedBox(
|
||||
width: 10,
|
||||
),
|
||||
IconButton(
|
||||
onPressed: () =>
|
||||
showAvailableTorrents(widget.seriesId, k, 0),
|
||||
icon: const Icon(Icons.manage_search))
|
||||
],
|
||||
))
|
||||
], rows: m[k]!),
|
||||
screenWidth < 600
|
||||
? SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: seasonEpisodes,
|
||||
)
|
||||
: seasonEpisodes
|
||||
],
|
||||
);
|
||||
list.add(seasonList);
|
||||
}
|
||||
return ListView(
|
||||
children: [
|
||||
Card(
|
||||
margin: const EdgeInsets.all(4),
|
||||
clipBehavior: Clip.hardEdge,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
image: DecorationImage(
|
||||
fit: BoxFit.cover,
|
||||
opacity: 0.5,
|
||||
image: NetworkImage(
|
||||
"${APIs.imagesUrl}/${details.id}/backdrop.jpg"))),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(10),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Flexible(
|
||||
flex: 1,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(10),
|
||||
child: Image.network(
|
||||
"${APIs.imagesUrl}/${details.id}/poster.jpg",
|
||||
fit: BoxFit.contain
|
||||
),
|
||||
),
|
||||
),
|
||||
Flexible(
|
||||
flex: 6,
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text("${details.resolution}"),
|
||||
const SizedBox(
|
||||
width: 30,
|
||||
),
|
||||
storage.when(
|
||||
data: (value) {
|
||||
for (final s in value) {
|
||||
if (s.id == details.storageId) {
|
||||
return Text(
|
||||
"${s.name}(${s.implementation})");
|
||||
}
|
||||
}
|
||||
return const Text("未知存储");
|
||||
},
|
||||
error: (error, stackTrace) =>
|
||||
Text("$error"),
|
||||
loading: () => const Text("")),
|
||||
],
|
||||
),
|
||||
const Divider(thickness: 1, height: 1),
|
||||
Text(
|
||||
"${details.name} ${details.name != details.originalName ? details.originalName : ''} (${details.airDate!.split("-")[0]})",
|
||||
style: const TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold),
|
||||
),
|
||||
const Text(""),
|
||||
Text(
|
||||
details.overview ?? "",
|
||||
),
|
||||
],
|
||||
)),
|
||||
Column(
|
||||
children: [
|
||||
IconButton(
|
||||
onPressed: () {
|
||||
ref
|
||||
.read(mediaDetailsProvider(
|
||||
widget.seriesId)
|
||||
.notifier)
|
||||
.delete()
|
||||
.then((v) =>
|
||||
context.go(WelcomePage.routeTv))
|
||||
.onError((error, trace) =>
|
||||
Utils.showSnakeBar(
|
||||
"删除失败: $error"));
|
||||
},
|
||||
icon: const Icon(Icons.delete))
|
||||
],
|
||||
)
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
DetailCard(details: details),
|
||||
Column(
|
||||
children: list,
|
||||
),
|
||||
@@ -255,64 +191,21 @@ class _TvDetailsPageState extends ConsumerState<TvDetailsPage> {
|
||||
context: context,
|
||||
barrierDismissible: true,
|
||||
builder: (BuildContext context) {
|
||||
return Consumer(builder: (context, ref, _) {
|
||||
final torrents = ref.watch(mediaTorrentsDataProvider(
|
||||
(mediaId: id, seasonNumber: season, episodeNumber: episode)));
|
||||
|
||||
return AlertDialog(
|
||||
//title: Text("资源"),
|
||||
content: SelectionArea(
|
||||
child: SizedBox(
|
||||
width: 800,
|
||||
height: 400,
|
||||
child: torrents.when(
|
||||
data: (v) {
|
||||
return SingleChildScrollView(
|
||||
child: DataTable(
|
||||
dataTextStyle: const TextStyle(fontSize: 12, height: 0),
|
||||
columns: const [
|
||||
DataColumn(label: Text("名称")),
|
||||
DataColumn(label: Text("大小")),
|
||||
DataColumn(label: Text("seeders")),
|
||||
DataColumn(label: Text("peers")),
|
||||
DataColumn(label: Text("操作"))
|
||||
],
|
||||
rows: List.generate(v.length, (i) {
|
||||
final torrent = v[i];
|
||||
return DataRow(cells: [
|
||||
DataCell(Text("${torrent.name}")),
|
||||
DataCell(Text(
|
||||
"${torrent.size?.readableFileSize()}")),
|
||||
DataCell(Text("${torrent.seeders}")),
|
||||
DataCell(Text("${torrent.peers}")),
|
||||
DataCell(IconButton(
|
||||
icon: const Icon(Icons.download),
|
||||
onPressed: () async {
|
||||
await ref
|
||||
.read(mediaTorrentsDataProvider((
|
||||
mediaId: id,
|
||||
seasonNumber: season,
|
||||
episodeNumber: episode
|
||||
)).notifier)
|
||||
.download(torrent)
|
||||
.then((v) {
|
||||
Navigator.of(context).pop();
|
||||
Utils.showSnakeBar(
|
||||
"开始下载:${torrent.name}");
|
||||
}).onError((error, trace) =>
|
||||
Utils.showSnakeBar("下载失败:$error"));
|
||||
},
|
||||
))
|
||||
]);
|
||||
})));
|
||||
},
|
||||
error: (err, trace) {
|
||||
return Text("$err");
|
||||
},
|
||||
loading: () => const MyProgressIndicator()),
|
||||
return AlertDialog(
|
||||
//title: Text("资源"),
|
||||
content: SelectionArea(
|
||||
child: SizedBox(
|
||||
width: MediaQuery.of(context).size.width * 0.7,
|
||||
height: MediaQuery.of(context).size.height * 0.6,
|
||||
child: SingleChildScrollView(
|
||||
child: ResourceList(
|
||||
mediaId: id,
|
||||
seasonNum: season,
|
||||
episodeNum: episode,
|
||||
),
|
||||
),
|
||||
));
|
||||
});
|
||||
),
|
||||
));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
@@ -40,50 +41,86 @@ class WelcomePage extends ConsumerWidget {
|
||||
))
|
||||
]
|
||||
: List.generate(value.length, (i) {
|
||||
var item = value[i];
|
||||
return Card(
|
||||
margin: const EdgeInsets.all(4),
|
||||
clipBehavior: Clip.hardEdge,
|
||||
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: Image.network(
|
||||
"${APIs.imagesUrl}/${item.id}/poster.jpg",
|
||||
fit: BoxFit.fill),
|
||||
),
|
||||
SizedBox(
|
||||
width: 140,
|
||||
child: LinearProgressIndicator(
|
||||
value: 1,
|
||||
color: item.status == "downloaded"
|
||||
? Colors.green
|
||||
: Colors.blue,
|
||||
)),
|
||||
Text(
|
||||
item.name!,
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.bold,
|
||||
height: 2.5),
|
||||
),
|
||||
],
|
||||
),
|
||||
));
|
||||
final item = value[i];
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
318
ui/lib/widgets/detail_card.dart
Normal file
318
ui/lib/widgets/detail_card.dart
Normal file
@@ -0,0 +1,318 @@
|
||||
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';
|
||||
|
||||
class DetailCard extends ConsumerStatefulWidget {
|
||||
final SeriesDetails details;
|
||||
|
||||
const DetailCard({super.key, required this.details});
|
||||
|
||||
@override
|
||||
ConsumerState<ConsumerStatefulWidget> createState() {
|
||||
return _DetailCardState();
|
||||
}
|
||||
}
|
||||
|
||||
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: 400),
|
||||
decoration: BoxDecoration(
|
||||
image: DecorationImage(
|
||||
fit: BoxFit.cover,
|
||||
opacity: 0.3,
|
||||
colorFilter: ColorFilter.mode(
|
||||
Colors.black.withOpacity(0.3), BlendMode.dstATop),
|
||||
image: NetworkImage(
|
||||
"${APIs.imagesUrl}/${widget.details.id}/backdrop.jpg"))),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(10),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
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(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
//const Text(""),
|
||||
Text(
|
||||
"${widget.details.name} ${widget.details.name != widget.details.originalName ? widget.details.originalName : ''} (${widget.details.airDate!.split("-")[0]})",
|
||||
style: const TextStyle(
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.bold,
|
||||
height: 2.5),
|
||||
),
|
||||
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: 7,
|
||||
widget.details.overview ?? "",
|
||||
)),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
children: [
|
||||
downloadButton(),
|
||||
editIcon(),
|
||||
deleteIcon(),
|
||||
],
|
||||
)
|
||||
],
|
||||
)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget deleteIcon() {
|
||||
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);
|
||||
}
|
||||
}
|
||||
87
ui/lib/widgets/resource_list.dart
Normal file
87
ui/lib/widgets/resource_list.dart
Normal file
@@ -0,0 +1,87 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:ui/providers/series_details.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
import 'package:ui/widgets/utils.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
|
||||
class ResourceList extends ConsumerWidget {
|
||||
final String mediaId;
|
||||
final int seasonNum;
|
||||
final int episodeNum;
|
||||
|
||||
const ResourceList(
|
||||
{super.key,
|
||||
required this.mediaId,
|
||||
this.seasonNum = 0,
|
||||
this.episodeNum = 0});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final torrents = ref.watch(mediaTorrentsDataProvider((
|
||||
mediaId: mediaId,
|
||||
seasonNumber: seasonNum,
|
||||
episodeNumber: episodeNum
|
||||
)));
|
||||
return torrents.when(
|
||||
data: (v) {
|
||||
bool hasPrivate = false;
|
||||
for (final item in v) {
|
||||
if (item.isPrivate == true) {
|
||||
hasPrivate = true;
|
||||
}
|
||||
}
|
||||
final columns = [
|
||||
const DataColumn(label: Text("名称")),
|
||||
const DataColumn(label: Text("大小")),
|
||||
const DataColumn(label: Text("S/P")),
|
||||
const DataColumn(label: Text("来源")),
|
||||
];
|
||||
if (hasPrivate) {
|
||||
columns.add(const DataColumn(label: Text("消耗")));
|
||||
}
|
||||
columns.add(const DataColumn(label: Text("下载")));
|
||||
|
||||
return DataTable(
|
||||
dataTextStyle: const TextStyle(fontSize: 12),
|
||||
columns: columns,
|
||||
rows: List.generate(v.length, (i) {
|
||||
final torrent = v[i];
|
||||
final rows = [
|
||||
DataCell(Text("${torrent.name}")),
|
||||
DataCell(Text("${torrent.size?.readableFileSize()}")),
|
||||
DataCell(Text("${torrent.seeders}/${torrent.peers}")),
|
||||
DataCell(Text(torrent.source ?? "-")),
|
||||
];
|
||||
if (hasPrivate) {
|
||||
rows.add(DataCell(Text(torrent.isPrivate == true
|
||||
? "${torrent.downloadFactor}dl/${torrent.uploadFactor}up"
|
||||
: "-")));
|
||||
}
|
||||
|
||||
rows.add(DataCell(LoadingIconButton(
|
||||
icon: Icons.download,
|
||||
onPressed: () async {
|
||||
await ref
|
||||
.read(mediaTorrentsDataProvider((
|
||||
mediaId: mediaId,
|
||||
seasonNumber: seasonNum,
|
||||
episodeNumber: episodeNum
|
||||
)).notifier)
|
||||
.download(torrent)
|
||||
.then((v) => showSnakeBar("开始下载:${torrent.name}"));
|
||||
},
|
||||
)));
|
||||
return DataRow(cells: rows);
|
||||
}));
|
||||
},
|
||||
error: (err, trace) {
|
||||
return "$err".contains("no resource found")
|
||||
? const Center(
|
||||
child: Text("没有资源"),
|
||||
)
|
||||
: Text("$err");
|
||||
},
|
||||
loading: () => const MyProgressIndicator());
|
||||
}
|
||||
}
|
||||
@@ -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,34 +32,33 @@ class Utils {
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
static showSnakeBar(String msg) {
|
||||
final context = APIs.navigatorKey.currentContext;
|
||||
if (context != null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: Text(msg),
|
||||
showCloseIcon: true,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
static bool showError(BuildContext context, AsyncSnapshot snapshot) {
|
||||
final isErrored = snapshot.hasError &&
|
||||
snapshot.connectionState != ConnectionState.waiting;
|
||||
if (isErrored) {
|
||||
Utils.showSnakeBar("当前操作出错: ${snapshot.error}");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
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"];
|
||||
int digitGroups = (log(this) / log(base)).round();
|
||||
int digitGroups = (log(this) / log(base)).floor();
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -1,4 +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({
|
||||
@@ -41,3 +44,189 @@ class SettingsCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
showLoadingWithFuture(Future f) {
|
||||
final context = APIs.navigatorKey.currentContext;
|
||||
if (context == null) {
|
||||
return;
|
||||
}
|
||||
showDialog(
|
||||
context: context,
|
||||
barrierDismissible: false, //点击遮罩不关闭对话框
|
||||
builder: (context) {
|
||||
return FutureBuilder(
|
||||
future: f,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState == ConnectionState.done) {
|
||||
if (snapshot.hasError) {
|
||||
return AlertDialog(
|
||||
content: Text("处理失败:${snapshot.error}"),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text("好"))
|
||||
],
|
||||
);
|
||||
}
|
||||
Navigator.of(context).pop();
|
||||
return Container();
|
||||
} else {
|
||||
return const AlertDialog(
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
CircularProgressIndicator(),
|
||||
Padding(
|
||||
padding: EdgeInsets.only(top: 26.0),
|
||||
child: Text("正在处理,请稍后..."),
|
||||
)
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
class MyRangeSlider extends StatefulWidget {
|
||||
final String name;
|
||||
const MyRangeSlider({super.key, required this.name});
|
||||
|
||||
@override
|
||||
State<StatefulWidget> createState() {
|
||||
return _MySliderState();
|
||||
}
|
||||
}
|
||||
|
||||
class _MySliderState extends State<MyRangeSlider> {
|
||||
double sizeMax = 5000;
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FormBuilderRangeSlider(
|
||||
decoration: const InputDecoration(labelText: "文件大小限制"),
|
||||
maxValueWidget: (max) => Text("${sizeMax / 1000} GB"),
|
||||
minValueWidget: (min) => const Text("0"),
|
||||
valueWidget: (value) {
|
||||
final sss = value.split(" ");
|
||||
return Text("${readableSize(sss[0])} - ${readableSize(sss[2])}");
|
||||
},
|
||||
onChangeEnd: (value) {
|
||||
if (value.end > sizeMax * 0.9) {
|
||||
setState(
|
||||
() {
|
||||
sizeMax = sizeMax * 5;
|
||||
},
|
||||
);
|
||||
} else if (value.end < sizeMax * 0.2) {
|
||||
if (sizeMax > 5000) {
|
||||
setState(
|
||||
() {
|
||||
sizeMax = sizeMax / 5;
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
name: widget.name,
|
||||
min: 0,
|
||||
max: sizeMax);
|
||||
}
|
||||
|
||||
String readableSize(String v) {
|
||||
if (v.endsWith("K")) {
|
||||
return v.replaceAll("K", " GB");
|
||||
}
|
||||
return "$v MB";
|
||||
}
|
||||
}
|
||||
|
||||
class LoadingIconButton extends StatefulWidget {
|
||||
LoadingIconButton({required this.onPressed, required this.icon, this.tooltip});
|
||||
final Future<void> Function() onPressed;
|
||||
final IconData icon;
|
||||
final String? tooltip;
|
||||
|
||||
@override
|
||||
State<StatefulWidget> createState() {
|
||||
return _LoadingIconButtonState();
|
||||
}
|
||||
}
|
||||
|
||||
class _LoadingIconButtonState extends State<LoadingIconButton> {
|
||||
bool loading = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return IconButton(
|
||||
tooltip: widget.tooltip,
|
||||
onPressed: loading
|
||||
? null
|
||||
: () async {
|
||||
setState(() => loading = true);
|
||||
try {
|
||||
await widget.onPressed();
|
||||
} catch (e) {
|
||||
showSnakeBar("操作失败:$e");
|
||||
} finally {
|
||||
setState(() => loading = false);
|
||||
}
|
||||
},
|
||||
icon: loading
|
||||
? Container(
|
||||
width: 24,
|
||||
height: 24,
|
||||
padding: const EdgeInsets.all(2.0),
|
||||
child: const CircularProgressIndicator(
|
||||
color: Colors.grey,
|
||||
strokeWidth: 3,
|
||||
),
|
||||
)
|
||||
: Icon(widget.icon));
|
||||
}
|
||||
}
|
||||
|
||||
class LoadingTextButton extends StatefulWidget {
|
||||
LoadingTextButton({required this.onPressed, required this.label});
|
||||
final Future<void> Function() onPressed;
|
||||
final Widget label;
|
||||
|
||||
@override
|
||||
State<StatefulWidget> createState() {
|
||||
return _LoadingTextButtonState();
|
||||
}
|
||||
}
|
||||
|
||||
class _LoadingTextButtonState extends State<LoadingTextButton> {
|
||||
bool loading = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return TextButton.icon(
|
||||
onPressed: loading
|
||||
? null
|
||||
: () async {
|
||||
setState(() => loading = true);
|
||||
try {
|
||||
await widget.onPressed();
|
||||
} catch (e) {
|
||||
showSnakeBar("操作失败:$e");
|
||||
} finally {
|
||||
setState(() => loading = false);
|
||||
}
|
||||
},
|
||||
icon: loading
|
||||
? Container(
|
||||
width: 24,
|
||||
height: 24,
|
||||
padding: const EdgeInsets.all(2.0),
|
||||
child: const CircularProgressIndicator(
|
||||
color: Colors.grey,
|
||||
strokeWidth: 3,
|
||||
),
|
||||
)
|
||||
: Text(""),
|
||||
label: widget.label,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user