mirror of
https://github.com/simon-ding/polaris.git
synced 2026-02-21 14:30:50 +08:00
Compare commits
40 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
cff093ca98 | ||
|
|
8f677b29a7 | ||
|
|
e08c126af2 | ||
|
|
eed72c5eb9 | ||
|
|
fcff47041a | ||
|
|
f9d4f851eb | ||
|
|
262baf769f | ||
|
|
6ef2e5b347 | ||
|
|
e0e11b70bb | ||
|
|
3de2f89107 | ||
|
|
b024b5f6dc |
@@ -3,7 +3,7 @@ WORKDIR /app
|
||||
COPY ./ui/pubspec.yaml ./ui/pubspec.lock ./
|
||||
RUN flutter pub get
|
||||
COPY ./ui/ ./
|
||||
RUN flutter build web
|
||||
RUN flutter build web --no-web-resources-cdn --web-renderer html
|
||||
|
||||
# 打包依赖阶段使用golang作为基础镜像
|
||||
FROM golang:1.22 as builder
|
||||
@@ -24,7 +24,7 @@ COPY --from=flutter /app/build/web ./ui/build/web/
|
||||
# 指定OS等,并go build
|
||||
RUN CGO_ENABLED=1 go build -o polaris -ldflags="-X polaris/db.Version=$(git describe --tags --long)" ./cmd/
|
||||
|
||||
FROM debian:12
|
||||
FROM debian:stable-slim
|
||||
ENV TZ="Asia/Shanghai" GIN_MODE=release
|
||||
|
||||
WORKDIR /app
|
||||
@@ -35,4 +35,6 @@ COPY --from=builder /app/polaris .
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
#USER 1000:1000
|
||||
|
||||
ENTRYPOINT ["./polaris"]
|
||||
12
README.md
12
README.md
@@ -12,11 +12,23 @@ Polaris 是一个电视剧和电影的追踪软件。配置好了之后,当剧
|
||||
- [x] 电视剧自动追踪下载
|
||||
- [x] 电影自动追踪下载
|
||||
- [x] webdav 存储支持,配合 [alist](https://github.com/alist-org/alist) 或阿里云等实现更多功能
|
||||
- [x] 事件通知推送,目前支持 Pushover和 Bark,还在扩充中
|
||||
- [x] 后台代理支持
|
||||
- [x] 用户认证
|
||||
- [x] plex 刮削支持
|
||||
- [x] and more...
|
||||
|
||||
## 使用
|
||||
|
||||
使用此程序参考 [【快速开始】](./doc/quick_start.md)
|
||||
|
||||
## 原理
|
||||
|
||||
本程序不提供任何视频相关资源,所有的资源都通过 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(0000) //max permission 0777
|
||||
|
||||
dbClient, err := db.Open()
|
||||
if err != nil {
|
||||
log.Panicf("init db error: %v", err)
|
||||
|
||||
13
db/const.go
13
db/const.go
@@ -10,6 +10,7 @@ const (
|
||||
SettingDownloadDir = "download_dir"
|
||||
SettingLogLevel = "log_level"
|
||||
SettingProxy = "proxy"
|
||||
SettingPlexMatchEnabled = "plexmatch_enabled"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -32,16 +33,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"
|
||||
74
db/db.go
74
db/db.go
@@ -63,10 +63,10 @@ func (c *Client) init() {
|
||||
log.Infof("set default log level")
|
||||
c.SetSetting(SettingLogLevel, "info")
|
||||
}
|
||||
// if tr := c.GetTransmission(); tr == nil {
|
||||
// log.Warnf("no download client, set default download client")
|
||||
// c.SaveTransmission("transmission", "http://transmission:9091", "", "")
|
||||
// }
|
||||
if tr := c.GetTransmission(); tr == nil {
|
||||
log.Warnf("no download client, set default download client")
|
||||
c.SaveTransmission("transmission", "http://transmission:9091", "", "")
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) generateJwtSerectIfNotExist() {
|
||||
@@ -87,18 +87,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
|
||||
@@ -148,6 +146,7 @@ func (c *Client) AddMediaWatchlist(m *ent.Media, episodes []int) (*ent.Media, er
|
||||
SetAirDate(m.AirDate).
|
||||
SetResolution(m.Resolution).
|
||||
SetTargetDir(m.TargetDir).
|
||||
SetDownloadHistoryEpisodes(m.DownloadHistoryEpisodes).
|
||||
AddEpisodeIDs(episodes...).
|
||||
Save(context.TODO())
|
||||
return r, err
|
||||
@@ -167,6 +166,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())
|
||||
@@ -221,8 +223,10 @@ func (c *Client) SaveEposideDetail(d *ent.Episode) (int, error) {
|
||||
SetEpisodeNumber(d.EpisodeNumber).
|
||||
SetOverview(d.Overview).
|
||||
SetTitle(d.Title).Save(context.TODO())
|
||||
|
||||
return ep.ID, err
|
||||
if err != nil {
|
||||
return 0, errors.Wrap(err, "save episode")
|
||||
}
|
||||
return ep.ID, nil
|
||||
}
|
||||
|
||||
func (c *Client) SaveEposideDetail2(d *ent.Episode) (int, error) {
|
||||
@@ -333,7 +337,9 @@ type StorageInfo struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Implementation string `json:"implementation" binding:"required"`
|
||||
Settings map[string]string `json:"settings" binding:"required"`
|
||||
Default bool `json:"default"`
|
||||
TvPath string `json:"tv_path" binding:"required"`
|
||||
MoviePath string `json:"movie_path" binding:"required"`
|
||||
Default bool `json:"default"`
|
||||
}
|
||||
|
||||
func (s *StorageInfo) ToWebDavSetting() WebdavSetting {
|
||||
@@ -342,34 +348,29 @@ 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)
|
||||
@@ -381,7 +382,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())
|
||||
@@ -390,7 +391,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
|
||||
@@ -411,15 +412,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")
|
||||
@@ -429,12 +421,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 {
|
||||
@@ -545,4 +531,8 @@ 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())
|
||||
}
|
||||
|
||||
97
db/notification.go
Normal file
97
db/notification.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"polaris/ent"
|
||||
"polaris/ent/notificationclient"
|
||||
"polaris/pkg/notifier"
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func (c *Client) GetAllNotificationClients2() ([]*ent.NotificationClient, error) {
|
||||
return c.ent.NotificationClient.Query().All(context.TODO())
|
||||
}
|
||||
|
||||
func (c *Client) GetAllNotificationClients() ([]*NotificationClient, error) {
|
||||
all, err := c.ent.NotificationClient.Query().All(context.TODO())
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "query db")
|
||||
}
|
||||
var all1 []*NotificationClient
|
||||
for _, item := range all {
|
||||
cl, err := toNotificationClient(item)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "convert")
|
||||
}
|
||||
all1 = append(all1, cl)
|
||||
}
|
||||
return all1, nil
|
||||
}
|
||||
|
||||
func (c *Client) AddNotificationClient(name, service string, setting string, enabled bool) error {
|
||||
// data, err := json.Marshal(setting)
|
||||
// if err != nil {
|
||||
// return errors.Wrap(err, "json")
|
||||
// }
|
||||
service = strings.ToLower(service)
|
||||
count, err := c.ent.NotificationClient.Query().Where(notificationclient.Name(name)).Count(context.Background())
|
||||
if err == nil && count > 0 {
|
||||
//update exist one
|
||||
return c.ent.NotificationClient.Update().Where(notificationclient.Name(name)).SetService(service).
|
||||
SetSettings(setting).SetEnabled(enabled).Exec(context.Background())
|
||||
}
|
||||
|
||||
return c.ent.NotificationClient.Create().SetName(name).SetService(service).
|
||||
SetSettings(setting).SetEnabled(enabled).Exec(context.Background())
|
||||
}
|
||||
|
||||
func (c *Client) DeleteNotificationClient(id int) error {
|
||||
_, err := c.ent.NotificationClient.Delete().Where(notificationclient.ID(id)).Exec(context.Background())
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Client) GetNotificationClient(id int) (*NotificationClient, error) {
|
||||
noti, err := c.ent.NotificationClient.Query().Where(notificationclient.ID(id)).First(context.Background())
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "query")
|
||||
}
|
||||
|
||||
return toNotificationClient(noti)
|
||||
}
|
||||
|
||||
func toNotificationClient(cl *ent.NotificationClient) (*NotificationClient, error) {
|
||||
var settings interface{}
|
||||
switch cl.Service {
|
||||
case "pushover":
|
||||
settings = notifier.PushoverConfig{}
|
||||
case "dingtalk":
|
||||
settings = notifier.DingTalkConfig{}
|
||||
case "telegram":
|
||||
settings = notifier.TelegramConfig{}
|
||||
case "bark":
|
||||
settings = notifier.BarkConfig{}
|
||||
}
|
||||
err := json.Unmarshal([]byte(cl.Settings), &settings)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "json")
|
||||
}
|
||||
return &NotificationClient{
|
||||
ID: cl.ID,
|
||||
Name: cl.Name,
|
||||
Service: cl.Service,
|
||||
Enabled: cl.Enabled,
|
||||
Settings: settings,
|
||||
}, nil
|
||||
|
||||
}
|
||||
|
||||
type NotificationClient struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Service string `json:"service"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Settings interface{} `json:"settings"`
|
||||
}
|
||||
192
ent/client.go
192
ent/client.go
@@ -16,6 +16,7 @@ import (
|
||||
"polaris/ent/history"
|
||||
"polaris/ent/indexers"
|
||||
"polaris/ent/media"
|
||||
"polaris/ent/notificationclient"
|
||||
"polaris/ent/settings"
|
||||
"polaris/ent/storage"
|
||||
|
||||
@@ -40,6 +41,8 @@ type Client struct {
|
||||
Indexers *IndexersClient
|
||||
// Media is the client for interacting with the Media builders.
|
||||
Media *MediaClient
|
||||
// NotificationClient is the client for interacting with the NotificationClient builders.
|
||||
NotificationClient *NotificationClientClient
|
||||
// Settings is the client for interacting with the Settings builders.
|
||||
Settings *SettingsClient
|
||||
// Storage is the client for interacting with the Storage builders.
|
||||
@@ -60,6 +63,7 @@ func (c *Client) init() {
|
||||
c.History = NewHistoryClient(c.config)
|
||||
c.Indexers = NewIndexersClient(c.config)
|
||||
c.Media = NewMediaClient(c.config)
|
||||
c.NotificationClient = NewNotificationClientClient(c.config)
|
||||
c.Settings = NewSettingsClient(c.config)
|
||||
c.Storage = NewStorageClient(c.config)
|
||||
}
|
||||
@@ -152,15 +156,16 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
|
||||
cfg := c.config
|
||||
cfg.driver = tx
|
||||
return &Tx{
|
||||
ctx: ctx,
|
||||
config: cfg,
|
||||
DownloadClients: NewDownloadClientsClient(cfg),
|
||||
Episode: NewEpisodeClient(cfg),
|
||||
History: NewHistoryClient(cfg),
|
||||
Indexers: NewIndexersClient(cfg),
|
||||
Media: NewMediaClient(cfg),
|
||||
Settings: NewSettingsClient(cfg),
|
||||
Storage: NewStorageClient(cfg),
|
||||
ctx: ctx,
|
||||
config: cfg,
|
||||
DownloadClients: NewDownloadClientsClient(cfg),
|
||||
Episode: NewEpisodeClient(cfg),
|
||||
History: NewHistoryClient(cfg),
|
||||
Indexers: NewIndexersClient(cfg),
|
||||
Media: NewMediaClient(cfg),
|
||||
NotificationClient: NewNotificationClientClient(cfg),
|
||||
Settings: NewSettingsClient(cfg),
|
||||
Storage: NewStorageClient(cfg),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -178,15 +183,16 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
|
||||
cfg := c.config
|
||||
cfg.driver = &txDriver{tx: tx, drv: c.driver}
|
||||
return &Tx{
|
||||
ctx: ctx,
|
||||
config: cfg,
|
||||
DownloadClients: NewDownloadClientsClient(cfg),
|
||||
Episode: NewEpisodeClient(cfg),
|
||||
History: NewHistoryClient(cfg),
|
||||
Indexers: NewIndexersClient(cfg),
|
||||
Media: NewMediaClient(cfg),
|
||||
Settings: NewSettingsClient(cfg),
|
||||
Storage: NewStorageClient(cfg),
|
||||
ctx: ctx,
|
||||
config: cfg,
|
||||
DownloadClients: NewDownloadClientsClient(cfg),
|
||||
Episode: NewEpisodeClient(cfg),
|
||||
History: NewHistoryClient(cfg),
|
||||
Indexers: NewIndexersClient(cfg),
|
||||
Media: NewMediaClient(cfg),
|
||||
NotificationClient: NewNotificationClientClient(cfg),
|
||||
Settings: NewSettingsClient(cfg),
|
||||
Storage: NewStorageClient(cfg),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -216,8 +222,8 @@ func (c *Client) Close() error {
|
||||
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
|
||||
func (c *Client) Use(hooks ...Hook) {
|
||||
for _, n := range []interface{ Use(...Hook) }{
|
||||
c.DownloadClients, c.Episode, c.History, c.Indexers, c.Media, c.Settings,
|
||||
c.Storage,
|
||||
c.DownloadClients, c.Episode, c.History, c.Indexers, c.Media,
|
||||
c.NotificationClient, c.Settings, c.Storage,
|
||||
} {
|
||||
n.Use(hooks...)
|
||||
}
|
||||
@@ -227,8 +233,8 @@ func (c *Client) Use(hooks ...Hook) {
|
||||
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
|
||||
func (c *Client) Intercept(interceptors ...Interceptor) {
|
||||
for _, n := range []interface{ Intercept(...Interceptor) }{
|
||||
c.DownloadClients, c.Episode, c.History, c.Indexers, c.Media, c.Settings,
|
||||
c.Storage,
|
||||
c.DownloadClients, c.Episode, c.History, c.Indexers, c.Media,
|
||||
c.NotificationClient, c.Settings, c.Storage,
|
||||
} {
|
||||
n.Intercept(interceptors...)
|
||||
}
|
||||
@@ -247,6 +253,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
|
||||
return c.Indexers.mutate(ctx, m)
|
||||
case *MediaMutation:
|
||||
return c.Media.mutate(ctx, m)
|
||||
case *NotificationClientMutation:
|
||||
return c.NotificationClient.mutate(ctx, m)
|
||||
case *SettingsMutation:
|
||||
return c.Settings.mutate(ctx, m)
|
||||
case *StorageMutation:
|
||||
@@ -953,6 +961,139 @@ func (c *MediaClient) mutate(ctx context.Context, m *MediaMutation) (Value, erro
|
||||
}
|
||||
}
|
||||
|
||||
// NotificationClientClient is a client for the NotificationClient schema.
|
||||
type NotificationClientClient struct {
|
||||
config
|
||||
}
|
||||
|
||||
// NewNotificationClientClient returns a client for the NotificationClient from the given config.
|
||||
func NewNotificationClientClient(c config) *NotificationClientClient {
|
||||
return &NotificationClientClient{config: c}
|
||||
}
|
||||
|
||||
// Use adds a list of mutation hooks to the hooks stack.
|
||||
// A call to `Use(f, g, h)` equals to `notificationclient.Hooks(f(g(h())))`.
|
||||
func (c *NotificationClientClient) Use(hooks ...Hook) {
|
||||
c.hooks.NotificationClient = append(c.hooks.NotificationClient, hooks...)
|
||||
}
|
||||
|
||||
// Intercept adds a list of query interceptors to the interceptors stack.
|
||||
// A call to `Intercept(f, g, h)` equals to `notificationclient.Intercept(f(g(h())))`.
|
||||
func (c *NotificationClientClient) Intercept(interceptors ...Interceptor) {
|
||||
c.inters.NotificationClient = append(c.inters.NotificationClient, interceptors...)
|
||||
}
|
||||
|
||||
// Create returns a builder for creating a NotificationClient entity.
|
||||
func (c *NotificationClientClient) Create() *NotificationClientCreate {
|
||||
mutation := newNotificationClientMutation(c.config, OpCreate)
|
||||
return &NotificationClientCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// CreateBulk returns a builder for creating a bulk of NotificationClient entities.
|
||||
func (c *NotificationClientClient) CreateBulk(builders ...*NotificationClientCreate) *NotificationClientCreateBulk {
|
||||
return &NotificationClientCreateBulk{config: c.config, builders: builders}
|
||||
}
|
||||
|
||||
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
|
||||
// a builder and applies setFunc on it.
|
||||
func (c *NotificationClientClient) MapCreateBulk(slice any, setFunc func(*NotificationClientCreate, int)) *NotificationClientCreateBulk {
|
||||
rv := reflect.ValueOf(slice)
|
||||
if rv.Kind() != reflect.Slice {
|
||||
return &NotificationClientCreateBulk{err: fmt.Errorf("calling to NotificationClientClient.MapCreateBulk with wrong type %T, need slice", slice)}
|
||||
}
|
||||
builders := make([]*NotificationClientCreate, rv.Len())
|
||||
for i := 0; i < rv.Len(); i++ {
|
||||
builders[i] = c.Create()
|
||||
setFunc(builders[i], i)
|
||||
}
|
||||
return &NotificationClientCreateBulk{config: c.config, builders: builders}
|
||||
}
|
||||
|
||||
// Update returns an update builder for NotificationClient.
|
||||
func (c *NotificationClientClient) Update() *NotificationClientUpdate {
|
||||
mutation := newNotificationClientMutation(c.config, OpUpdate)
|
||||
return &NotificationClientUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOne returns an update builder for the given entity.
|
||||
func (c *NotificationClientClient) UpdateOne(nc *NotificationClient) *NotificationClientUpdateOne {
|
||||
mutation := newNotificationClientMutation(c.config, OpUpdateOne, withNotificationClient(nc))
|
||||
return &NotificationClientUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOneID returns an update builder for the given id.
|
||||
func (c *NotificationClientClient) UpdateOneID(id int) *NotificationClientUpdateOne {
|
||||
mutation := newNotificationClientMutation(c.config, OpUpdateOne, withNotificationClientID(id))
|
||||
return &NotificationClientUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// Delete returns a delete builder for NotificationClient.
|
||||
func (c *NotificationClientClient) Delete() *NotificationClientDelete {
|
||||
mutation := newNotificationClientMutation(c.config, OpDelete)
|
||||
return &NotificationClientDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// DeleteOne returns a builder for deleting the given entity.
|
||||
func (c *NotificationClientClient) DeleteOne(nc *NotificationClient) *NotificationClientDeleteOne {
|
||||
return c.DeleteOneID(nc.ID)
|
||||
}
|
||||
|
||||
// DeleteOneID returns a builder for deleting the given entity by its id.
|
||||
func (c *NotificationClientClient) DeleteOneID(id int) *NotificationClientDeleteOne {
|
||||
builder := c.Delete().Where(notificationclient.ID(id))
|
||||
builder.mutation.id = &id
|
||||
builder.mutation.op = OpDeleteOne
|
||||
return &NotificationClientDeleteOne{builder}
|
||||
}
|
||||
|
||||
// Query returns a query builder for NotificationClient.
|
||||
func (c *NotificationClientClient) Query() *NotificationClientQuery {
|
||||
return &NotificationClientQuery{
|
||||
config: c.config,
|
||||
ctx: &QueryContext{Type: TypeNotificationClient},
|
||||
inters: c.Interceptors(),
|
||||
}
|
||||
}
|
||||
|
||||
// Get returns a NotificationClient entity by its id.
|
||||
func (c *NotificationClientClient) Get(ctx context.Context, id int) (*NotificationClient, error) {
|
||||
return c.Query().Where(notificationclient.ID(id)).Only(ctx)
|
||||
}
|
||||
|
||||
// GetX is like Get, but panics if an error occurs.
|
||||
func (c *NotificationClientClient) GetX(ctx context.Context, id int) *NotificationClient {
|
||||
obj, err := c.Get(ctx, id)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
// Hooks returns the client hooks.
|
||||
func (c *NotificationClientClient) Hooks() []Hook {
|
||||
return c.hooks.NotificationClient
|
||||
}
|
||||
|
||||
// Interceptors returns the client interceptors.
|
||||
func (c *NotificationClientClient) Interceptors() []Interceptor {
|
||||
return c.inters.NotificationClient
|
||||
}
|
||||
|
||||
func (c *NotificationClientClient) mutate(ctx context.Context, m *NotificationClientMutation) (Value, error) {
|
||||
switch m.Op() {
|
||||
case OpCreate:
|
||||
return (&NotificationClientCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpUpdate:
|
||||
return (&NotificationClientUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpUpdateOne:
|
||||
return (&NotificationClientUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpDelete, OpDeleteOne:
|
||||
return (&NotificationClientDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
|
||||
default:
|
||||
return nil, fmt.Errorf("ent: unknown NotificationClient mutation op: %q", m.Op())
|
||||
}
|
||||
}
|
||||
|
||||
// SettingsClient is a client for the Settings schema.
|
||||
type SettingsClient struct {
|
||||
config
|
||||
@@ -1222,10 +1363,11 @@ func (c *StorageClient) mutate(ctx context.Context, m *StorageMutation) (Value,
|
||||
// hooks and interceptors per client, for fast access.
|
||||
type (
|
||||
hooks struct {
|
||||
DownloadClients, Episode, History, Indexers, Media, Settings, Storage []ent.Hook
|
||||
DownloadClients, Episode, History, Indexers, Media, NotificationClient,
|
||||
Settings, Storage []ent.Hook
|
||||
}
|
||||
inters struct {
|
||||
DownloadClients, Episode, History, Indexers, Media, Settings,
|
||||
Storage []ent.Interceptor
|
||||
DownloadClients, Episode, History, Indexers, Media, NotificationClient,
|
||||
Settings, Storage []ent.Interceptor
|
||||
}
|
||||
)
|
||||
|
||||
16
ent/ent.go
16
ent/ent.go
@@ -11,6 +11,7 @@ import (
|
||||
"polaris/ent/history"
|
||||
"polaris/ent/indexers"
|
||||
"polaris/ent/media"
|
||||
"polaris/ent/notificationclient"
|
||||
"polaris/ent/settings"
|
||||
"polaris/ent/storage"
|
||||
"reflect"
|
||||
@@ -79,13 +80,14 @@ var (
|
||||
func checkColumn(table, column string) error {
|
||||
initCheck.Do(func() {
|
||||
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
|
||||
downloadclients.Table: downloadclients.ValidColumn,
|
||||
episode.Table: episode.ValidColumn,
|
||||
history.Table: history.ValidColumn,
|
||||
indexers.Table: indexers.ValidColumn,
|
||||
media.Table: media.ValidColumn,
|
||||
settings.Table: settings.ValidColumn,
|
||||
storage.Table: storage.ValidColumn,
|
||||
downloadclients.Table: downloadclients.ValidColumn,
|
||||
episode.Table: episode.ValidColumn,
|
||||
history.Table: history.ValidColumn,
|
||||
indexers.Table: indexers.ValidColumn,
|
||||
media.Table: media.ValidColumn,
|
||||
notificationclient.Table: notificationclient.ValidColumn,
|
||||
settings.Table: settings.ValidColumn,
|
||||
storage.Table: storage.ValidColumn,
|
||||
})
|
||||
})
|
||||
return columnCheck(table, column)
|
||||
|
||||
@@ -29,6 +29,8 @@ 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"`
|
||||
// Status holds the value of the "status" field.
|
||||
Status history.Status `json:"status,omitempty"`
|
||||
// Saved holds the value of the "saved" field.
|
||||
@@ -41,7 +43,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:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case history.FieldSourceTitle, history.FieldTargetDir, history.FieldStatus, history.FieldSaved:
|
||||
values[i] = new(sql.NullString)
|
||||
@@ -104,6 +106,12 @@ 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.FieldStatus:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field status", values[i])
|
||||
@@ -170,6 +178,9 @@ 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("status=")
|
||||
builder.WriteString(fmt.Sprintf("%v", h.Status))
|
||||
builder.WriteString(", ")
|
||||
|
||||
@@ -25,6 +25,8 @@ 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"
|
||||
// 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 +44,7 @@ var Columns = []string{
|
||||
FieldDate,
|
||||
FieldTargetDir,
|
||||
FieldSize,
|
||||
FieldDownloadClientID,
|
||||
FieldStatus,
|
||||
FieldSaved,
|
||||
}
|
||||
@@ -124,6 +127,11 @@ 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()
|
||||
}
|
||||
|
||||
// ByStatus orders the results by the status field.
|
||||
func ByStatus(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldStatus, opts...).ToFunc()
|
||||
|
||||
@@ -84,6 +84,11 @@ 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))
|
||||
}
|
||||
|
||||
// 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 +394,56 @@ 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))
|
||||
}
|
||||
|
||||
// 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,20 @@ 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
|
||||
}
|
||||
|
||||
// SetStatus sets the "status" field.
|
||||
func (hc *HistoryCreate) SetStatus(h history.Status) *HistoryCreate {
|
||||
hc.mutation.SetStatus(h)
|
||||
@@ -208,6 +222,10 @@ 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.Status(); ok {
|
||||
_spec.SetField(history.FieldStatus, field.TypeEnum, value)
|
||||
_node.Status = value
|
||||
|
||||
@@ -139,6 +139,33 @@ 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
|
||||
}
|
||||
|
||||
// SetStatus sets the "status" field.
|
||||
func (hu *HistoryUpdate) SetStatus(h history.Status) *HistoryUpdate {
|
||||
hu.mutation.SetStatus(h)
|
||||
@@ -257,6 +284,15 @@ 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.Status(); ok {
|
||||
_spec.SetField(history.FieldStatus, field.TypeEnum, value)
|
||||
}
|
||||
@@ -397,6 +433,33 @@ 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
|
||||
}
|
||||
|
||||
// SetStatus sets the "status" field.
|
||||
func (huo *HistoryUpdateOne) SetStatus(h history.Status) *HistoryUpdateOne {
|
||||
huo.mutation.SetStatus(h)
|
||||
@@ -545,6 +608,15 @@ 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.Status(); ok {
|
||||
_spec.SetField(history.FieldStatus, field.TypeEnum, value)
|
||||
}
|
||||
|
||||
@@ -68,6 +68,18 @@ func (f MediaFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error
|
||||
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.MediaMutation", m)
|
||||
}
|
||||
|
||||
// The NotificationClientFunc type is an adapter to allow the use of ordinary
|
||||
// function as NotificationClient mutator.
|
||||
type NotificationClientFunc func(context.Context, *ent.NotificationClientMutation) (ent.Value, error)
|
||||
|
||||
// Mutate calls f(ctx, m).
|
||||
func (f NotificationClientFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
|
||||
if mv, ok := m.(*ent.NotificationClientMutation); ok {
|
||||
return f(ctx, mv)
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.NotificationClientMutation", m)
|
||||
}
|
||||
|
||||
// The SettingsFunc type is an adapter to allow the use of ordinary
|
||||
// function as Settings mutator.
|
||||
type SettingsFunc func(context.Context, *ent.SettingsMutation) (ent.Value, error)
|
||||
|
||||
@@ -124,7 +124,7 @@ const DefaultResolution = Resolution1080p
|
||||
const (
|
||||
Resolution720p Resolution = "720p"
|
||||
Resolution1080p Resolution = "1080p"
|
||||
Resolution4k Resolution = "4k"
|
||||
Resolution2160p Resolution = "2160p"
|
||||
)
|
||||
|
||||
func (r Resolution) String() string {
|
||||
@@ -134,7 +134,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)
|
||||
|
||||
@@ -63,6 +63,7 @@ var (
|
||||
{Name: "date", Type: field.TypeTime},
|
||||
{Name: "target_dir", Type: field.TypeString},
|
||||
{Name: "size", Type: field.TypeInt, Default: 0},
|
||||
{Name: "download_client_id", Type: field.TypeInt, Nullable: true},
|
||||
{Name: "status", Type: field.TypeEnum, Enums: []string{"running", "success", "fail", "uploading"}},
|
||||
{Name: "saved", Type: field.TypeString, Nullable: true},
|
||||
}
|
||||
@@ -99,7 +100,7 @@ var (
|
||||
{Name: "overview", Type: field.TypeString},
|
||||
{Name: "created_at", Type: field.TypeTime},
|
||||
{Name: "air_date", Type: field.TypeString, Default: ""},
|
||||
{Name: "resolution", Type: field.TypeEnum, Enums: []string{"720p", "1080p", "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},
|
||||
@@ -110,6 +111,20 @@ var (
|
||||
Columns: MediaColumns,
|
||||
PrimaryKey: []*schema.Column{MediaColumns[0]},
|
||||
}
|
||||
// NotificationClientsColumns holds the columns for the "notification_clients" table.
|
||||
NotificationClientsColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeInt, Increment: true},
|
||||
{Name: "name", Type: field.TypeString},
|
||||
{Name: "service", Type: field.TypeString},
|
||||
{Name: "settings", Type: field.TypeString},
|
||||
{Name: "enabled", Type: field.TypeBool, Default: true},
|
||||
}
|
||||
// NotificationClientsTable holds the schema information for the "notification_clients" table.
|
||||
NotificationClientsTable = &schema.Table{
|
||||
Name: "notification_clients",
|
||||
Columns: NotificationClientsColumns,
|
||||
PrimaryKey: []*schema.Column{NotificationClientsColumns[0]},
|
||||
}
|
||||
// SettingsColumns holds the columns for the "settings" table.
|
||||
SettingsColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeInt, Increment: true},
|
||||
@@ -127,6 +142,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},
|
||||
@@ -144,6 +161,7 @@ var (
|
||||
HistoriesTable,
|
||||
IndexersTable,
|
||||
MediaTable,
|
||||
NotificationClientsTable,
|
||||
SettingsTable,
|
||||
StoragesTable,
|
||||
}
|
||||
|
||||
797
ent/mutation.go
797
ent/mutation.go
@@ -11,6 +11,7 @@ import (
|
||||
"polaris/ent/history"
|
||||
"polaris/ent/indexers"
|
||||
"polaris/ent/media"
|
||||
"polaris/ent/notificationclient"
|
||||
"polaris/ent/predicate"
|
||||
"polaris/ent/settings"
|
||||
"polaris/ent/storage"
|
||||
@@ -30,13 +31,14 @@ const (
|
||||
OpUpdateOne = ent.OpUpdateOne
|
||||
|
||||
// Node types.
|
||||
TypeDownloadClients = "DownloadClients"
|
||||
TypeEpisode = "Episode"
|
||||
TypeHistory = "History"
|
||||
TypeIndexers = "Indexers"
|
||||
TypeMedia = "Media"
|
||||
TypeSettings = "Settings"
|
||||
TypeStorage = "Storage"
|
||||
TypeDownloadClients = "DownloadClients"
|
||||
TypeEpisode = "Episode"
|
||||
TypeHistory = "History"
|
||||
TypeIndexers = "Indexers"
|
||||
TypeMedia = "Media"
|
||||
TypeNotificationClient = "NotificationClient"
|
||||
TypeSettings = "Settings"
|
||||
TypeStorage = "Storage"
|
||||
)
|
||||
|
||||
// DownloadClientsMutation represents an operation that mutates the DownloadClients nodes in the graph.
|
||||
@@ -1703,24 +1705,26 @@ func (m *EpisodeMutation) ResetEdge(name string) error {
|
||||
// HistoryMutation represents an operation that mutates the History nodes in the graph.
|
||||
type HistoryMutation struct {
|
||||
config
|
||||
op Op
|
||||
typ string
|
||||
id *int
|
||||
media_id *int
|
||||
addmedia_id *int
|
||||
episode_id *int
|
||||
addepisode_id *int
|
||||
source_title *string
|
||||
date *time.Time
|
||||
target_dir *string
|
||||
size *int
|
||||
addsize *int
|
||||
status *history.Status
|
||||
saved *string
|
||||
clearedFields map[string]struct{}
|
||||
done bool
|
||||
oldValue func(context.Context) (*History, error)
|
||||
predicates []predicate.History
|
||||
op Op
|
||||
typ string
|
||||
id *int
|
||||
media_id *int
|
||||
addmedia_id *int
|
||||
episode_id *int
|
||||
addepisode_id *int
|
||||
source_title *string
|
||||
date *time.Time
|
||||
target_dir *string
|
||||
size *int
|
||||
addsize *int
|
||||
download_client_id *int
|
||||
adddownload_client_id *int
|
||||
status *history.Status
|
||||
saved *string
|
||||
clearedFields map[string]struct{}
|
||||
done bool
|
||||
oldValue func(context.Context) (*History, error)
|
||||
predicates []predicate.History
|
||||
}
|
||||
|
||||
var _ ent.Mutation = (*HistoryMutation)(nil)
|
||||
@@ -2111,6 +2115,76 @@ func (m *HistoryMutation) ResetSize() {
|
||||
m.addsize = nil
|
||||
}
|
||||
|
||||
// SetDownloadClientID sets the "download_client_id" field.
|
||||
func (m *HistoryMutation) SetDownloadClientID(i int) {
|
||||
m.download_client_id = &i
|
||||
m.adddownload_client_id = nil
|
||||
}
|
||||
|
||||
// DownloadClientID returns the value of the "download_client_id" field in the mutation.
|
||||
func (m *HistoryMutation) DownloadClientID() (r int, exists bool) {
|
||||
v := m.download_client_id
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldDownloadClientID returns the old "download_client_id" field's value of the History entity.
|
||||
// If the History object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *HistoryMutation) OldDownloadClientID(ctx context.Context) (v int, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldDownloadClientID is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldDownloadClientID requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldDownloadClientID: %w", err)
|
||||
}
|
||||
return oldValue.DownloadClientID, nil
|
||||
}
|
||||
|
||||
// AddDownloadClientID adds i to the "download_client_id" field.
|
||||
func (m *HistoryMutation) AddDownloadClientID(i int) {
|
||||
if m.adddownload_client_id != nil {
|
||||
*m.adddownload_client_id += i
|
||||
} else {
|
||||
m.adddownload_client_id = &i
|
||||
}
|
||||
}
|
||||
|
||||
// AddedDownloadClientID returns the value that was added to the "download_client_id" field in this mutation.
|
||||
func (m *HistoryMutation) AddedDownloadClientID() (r int, exists bool) {
|
||||
v := m.adddownload_client_id
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ClearDownloadClientID clears the value of the "download_client_id" field.
|
||||
func (m *HistoryMutation) ClearDownloadClientID() {
|
||||
m.download_client_id = nil
|
||||
m.adddownload_client_id = nil
|
||||
m.clearedFields[history.FieldDownloadClientID] = struct{}{}
|
||||
}
|
||||
|
||||
// DownloadClientIDCleared returns if the "download_client_id" field was cleared in this mutation.
|
||||
func (m *HistoryMutation) DownloadClientIDCleared() bool {
|
||||
_, ok := m.clearedFields[history.FieldDownloadClientID]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ResetDownloadClientID resets all changes to the "download_client_id" field.
|
||||
func (m *HistoryMutation) ResetDownloadClientID() {
|
||||
m.download_client_id = nil
|
||||
m.adddownload_client_id = nil
|
||||
delete(m.clearedFields, history.FieldDownloadClientID)
|
||||
}
|
||||
|
||||
// SetStatus sets the "status" field.
|
||||
func (m *HistoryMutation) SetStatus(h history.Status) {
|
||||
m.status = &h
|
||||
@@ -2230,7 +2304,7 @@ func (m *HistoryMutation) Type() string {
|
||||
// order to get all numeric fields that were incremented/decremented, call
|
||||
// AddedFields().
|
||||
func (m *HistoryMutation) Fields() []string {
|
||||
fields := make([]string, 0, 8)
|
||||
fields := make([]string, 0, 9)
|
||||
if m.media_id != nil {
|
||||
fields = append(fields, history.FieldMediaID)
|
||||
}
|
||||
@@ -2249,6 +2323,9 @@ func (m *HistoryMutation) Fields() []string {
|
||||
if m.size != nil {
|
||||
fields = append(fields, history.FieldSize)
|
||||
}
|
||||
if m.download_client_id != nil {
|
||||
fields = append(fields, history.FieldDownloadClientID)
|
||||
}
|
||||
if m.status != nil {
|
||||
fields = append(fields, history.FieldStatus)
|
||||
}
|
||||
@@ -2275,6 +2352,8 @@ func (m *HistoryMutation) Field(name string) (ent.Value, bool) {
|
||||
return m.TargetDir()
|
||||
case history.FieldSize:
|
||||
return m.Size()
|
||||
case history.FieldDownloadClientID:
|
||||
return m.DownloadClientID()
|
||||
case history.FieldStatus:
|
||||
return m.Status()
|
||||
case history.FieldSaved:
|
||||
@@ -2300,6 +2379,8 @@ func (m *HistoryMutation) OldField(ctx context.Context, name string) (ent.Value,
|
||||
return m.OldTargetDir(ctx)
|
||||
case history.FieldSize:
|
||||
return m.OldSize(ctx)
|
||||
case history.FieldDownloadClientID:
|
||||
return m.OldDownloadClientID(ctx)
|
||||
case history.FieldStatus:
|
||||
return m.OldStatus(ctx)
|
||||
case history.FieldSaved:
|
||||
@@ -2355,6 +2436,13 @@ func (m *HistoryMutation) SetField(name string, value ent.Value) error {
|
||||
}
|
||||
m.SetSize(v)
|
||||
return nil
|
||||
case history.FieldDownloadClientID:
|
||||
v, ok := value.(int)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetDownloadClientID(v)
|
||||
return nil
|
||||
case history.FieldStatus:
|
||||
v, ok := value.(history.Status)
|
||||
if !ok {
|
||||
@@ -2386,6 +2474,9 @@ func (m *HistoryMutation) AddedFields() []string {
|
||||
if m.addsize != nil {
|
||||
fields = append(fields, history.FieldSize)
|
||||
}
|
||||
if m.adddownload_client_id != nil {
|
||||
fields = append(fields, history.FieldDownloadClientID)
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
@@ -2400,6 +2491,8 @@ func (m *HistoryMutation) AddedField(name string) (ent.Value, bool) {
|
||||
return m.AddedEpisodeID()
|
||||
case history.FieldSize:
|
||||
return m.AddedSize()
|
||||
case history.FieldDownloadClientID:
|
||||
return m.AddedDownloadClientID()
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
@@ -2430,6 +2523,13 @@ func (m *HistoryMutation) AddField(name string, value ent.Value) error {
|
||||
}
|
||||
m.AddSize(v)
|
||||
return nil
|
||||
case history.FieldDownloadClientID:
|
||||
v, ok := value.(int)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.AddDownloadClientID(v)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown History numeric field %s", name)
|
||||
}
|
||||
@@ -2441,6 +2541,9 @@ func (m *HistoryMutation) ClearedFields() []string {
|
||||
if m.FieldCleared(history.FieldEpisodeID) {
|
||||
fields = append(fields, history.FieldEpisodeID)
|
||||
}
|
||||
if m.FieldCleared(history.FieldDownloadClientID) {
|
||||
fields = append(fields, history.FieldDownloadClientID)
|
||||
}
|
||||
if m.FieldCleared(history.FieldSaved) {
|
||||
fields = append(fields, history.FieldSaved)
|
||||
}
|
||||
@@ -2461,6 +2564,9 @@ func (m *HistoryMutation) ClearField(name string) error {
|
||||
case history.FieldEpisodeID:
|
||||
m.ClearEpisodeID()
|
||||
return nil
|
||||
case history.FieldDownloadClientID:
|
||||
m.ClearDownloadClientID()
|
||||
return nil
|
||||
case history.FieldSaved:
|
||||
m.ClearSaved()
|
||||
return nil
|
||||
@@ -2490,6 +2596,9 @@ func (m *HistoryMutation) ResetField(name string) error {
|
||||
case history.FieldSize:
|
||||
m.ResetSize()
|
||||
return nil
|
||||
case history.FieldDownloadClientID:
|
||||
m.ResetDownloadClientID()
|
||||
return nil
|
||||
case history.FieldStatus:
|
||||
m.ResetStatus()
|
||||
return nil
|
||||
@@ -4342,6 +4451,494 @@ func (m *MediaMutation) ResetEdge(name string) error {
|
||||
return fmt.Errorf("unknown Media edge %s", name)
|
||||
}
|
||||
|
||||
// NotificationClientMutation represents an operation that mutates the NotificationClient nodes in the graph.
|
||||
type NotificationClientMutation struct {
|
||||
config
|
||||
op Op
|
||||
typ string
|
||||
id *int
|
||||
name *string
|
||||
service *string
|
||||
settings *string
|
||||
enabled *bool
|
||||
clearedFields map[string]struct{}
|
||||
done bool
|
||||
oldValue func(context.Context) (*NotificationClient, error)
|
||||
predicates []predicate.NotificationClient
|
||||
}
|
||||
|
||||
var _ ent.Mutation = (*NotificationClientMutation)(nil)
|
||||
|
||||
// notificationclientOption allows management of the mutation configuration using functional options.
|
||||
type notificationclientOption func(*NotificationClientMutation)
|
||||
|
||||
// newNotificationClientMutation creates new mutation for the NotificationClient entity.
|
||||
func newNotificationClientMutation(c config, op Op, opts ...notificationclientOption) *NotificationClientMutation {
|
||||
m := &NotificationClientMutation{
|
||||
config: c,
|
||||
op: op,
|
||||
typ: TypeNotificationClient,
|
||||
clearedFields: make(map[string]struct{}),
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(m)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// withNotificationClientID sets the ID field of the mutation.
|
||||
func withNotificationClientID(id int) notificationclientOption {
|
||||
return func(m *NotificationClientMutation) {
|
||||
var (
|
||||
err error
|
||||
once sync.Once
|
||||
value *NotificationClient
|
||||
)
|
||||
m.oldValue = func(ctx context.Context) (*NotificationClient, error) {
|
||||
once.Do(func() {
|
||||
if m.done {
|
||||
err = errors.New("querying old values post mutation is not allowed")
|
||||
} else {
|
||||
value, err = m.Client().NotificationClient.Get(ctx, id)
|
||||
}
|
||||
})
|
||||
return value, err
|
||||
}
|
||||
m.id = &id
|
||||
}
|
||||
}
|
||||
|
||||
// withNotificationClient sets the old NotificationClient of the mutation.
|
||||
func withNotificationClient(node *NotificationClient) notificationclientOption {
|
||||
return func(m *NotificationClientMutation) {
|
||||
m.oldValue = func(context.Context) (*NotificationClient, error) {
|
||||
return node, nil
|
||||
}
|
||||
m.id = &node.ID
|
||||
}
|
||||
}
|
||||
|
||||
// Client returns a new `ent.Client` from the mutation. If the mutation was
|
||||
// executed in a transaction (ent.Tx), a transactional client is returned.
|
||||
func (m NotificationClientMutation) Client() *Client {
|
||||
client := &Client{config: m.config}
|
||||
client.init()
|
||||
return client
|
||||
}
|
||||
|
||||
// Tx returns an `ent.Tx` for mutations that were executed in transactions;
|
||||
// it returns an error otherwise.
|
||||
func (m NotificationClientMutation) Tx() (*Tx, error) {
|
||||
if _, ok := m.driver.(*txDriver); !ok {
|
||||
return nil, errors.New("ent: mutation is not running in a transaction")
|
||||
}
|
||||
tx := &Tx{config: m.config}
|
||||
tx.init()
|
||||
return tx, nil
|
||||
}
|
||||
|
||||
// ID returns the ID value in the mutation. Note that the ID is only available
|
||||
// if it was provided to the builder or after it was returned from the database.
|
||||
func (m *NotificationClientMutation) ID() (id int, exists bool) {
|
||||
if m.id == nil {
|
||||
return
|
||||
}
|
||||
return *m.id, true
|
||||
}
|
||||
|
||||
// IDs queries the database and returns the entity ids that match the mutation's predicate.
|
||||
// That means, if the mutation is applied within a transaction with an isolation level such
|
||||
// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
|
||||
// or updated by the mutation.
|
||||
func (m *NotificationClientMutation) IDs(ctx context.Context) ([]int, error) {
|
||||
switch {
|
||||
case m.op.Is(OpUpdateOne | OpDeleteOne):
|
||||
id, exists := m.ID()
|
||||
if exists {
|
||||
return []int{id}, nil
|
||||
}
|
||||
fallthrough
|
||||
case m.op.Is(OpUpdate | OpDelete):
|
||||
return m.Client().NotificationClient.Query().Where(m.predicates...).IDs(ctx)
|
||||
default:
|
||||
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
|
||||
}
|
||||
}
|
||||
|
||||
// SetName sets the "name" field.
|
||||
func (m *NotificationClientMutation) SetName(s string) {
|
||||
m.name = &s
|
||||
}
|
||||
|
||||
// Name returns the value of the "name" field in the mutation.
|
||||
func (m *NotificationClientMutation) Name() (r string, exists bool) {
|
||||
v := m.name
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldName returns the old "name" field's value of the NotificationClient entity.
|
||||
// If the NotificationClient object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *NotificationClientMutation) OldName(ctx context.Context) (v string, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldName is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldName requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldName: %w", err)
|
||||
}
|
||||
return oldValue.Name, nil
|
||||
}
|
||||
|
||||
// ResetName resets all changes to the "name" field.
|
||||
func (m *NotificationClientMutation) ResetName() {
|
||||
m.name = nil
|
||||
}
|
||||
|
||||
// SetService sets the "service" field.
|
||||
func (m *NotificationClientMutation) SetService(s string) {
|
||||
m.service = &s
|
||||
}
|
||||
|
||||
// Service returns the value of the "service" field in the mutation.
|
||||
func (m *NotificationClientMutation) Service() (r string, exists bool) {
|
||||
v := m.service
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldService returns the old "service" field's value of the NotificationClient entity.
|
||||
// If the NotificationClient object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *NotificationClientMutation) OldService(ctx context.Context) (v string, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldService is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldService requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldService: %w", err)
|
||||
}
|
||||
return oldValue.Service, nil
|
||||
}
|
||||
|
||||
// ResetService resets all changes to the "service" field.
|
||||
func (m *NotificationClientMutation) ResetService() {
|
||||
m.service = nil
|
||||
}
|
||||
|
||||
// SetSettings sets the "settings" field.
|
||||
func (m *NotificationClientMutation) SetSettings(s string) {
|
||||
m.settings = &s
|
||||
}
|
||||
|
||||
// Settings returns the value of the "settings" field in the mutation.
|
||||
func (m *NotificationClientMutation) Settings() (r string, exists bool) {
|
||||
v := m.settings
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldSettings returns the old "settings" field's value of the NotificationClient entity.
|
||||
// If the NotificationClient object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *NotificationClientMutation) OldSettings(ctx context.Context) (v string, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldSettings is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldSettings requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldSettings: %w", err)
|
||||
}
|
||||
return oldValue.Settings, nil
|
||||
}
|
||||
|
||||
// ResetSettings resets all changes to the "settings" field.
|
||||
func (m *NotificationClientMutation) ResetSettings() {
|
||||
m.settings = nil
|
||||
}
|
||||
|
||||
// SetEnabled sets the "enabled" field.
|
||||
func (m *NotificationClientMutation) SetEnabled(b bool) {
|
||||
m.enabled = &b
|
||||
}
|
||||
|
||||
// Enabled returns the value of the "enabled" field in the mutation.
|
||||
func (m *NotificationClientMutation) Enabled() (r bool, exists bool) {
|
||||
v := m.enabled
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldEnabled returns the old "enabled" field's value of the NotificationClient entity.
|
||||
// If the NotificationClient object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *NotificationClientMutation) OldEnabled(ctx context.Context) (v bool, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldEnabled is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldEnabled requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldEnabled: %w", err)
|
||||
}
|
||||
return oldValue.Enabled, nil
|
||||
}
|
||||
|
||||
// ResetEnabled resets all changes to the "enabled" field.
|
||||
func (m *NotificationClientMutation) ResetEnabled() {
|
||||
m.enabled = nil
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the NotificationClientMutation builder.
|
||||
func (m *NotificationClientMutation) Where(ps ...predicate.NotificationClient) {
|
||||
m.predicates = append(m.predicates, ps...)
|
||||
}
|
||||
|
||||
// WhereP appends storage-level predicates to the NotificationClientMutation builder. Using this method,
|
||||
// users can use type-assertion to append predicates that do not depend on any generated package.
|
||||
func (m *NotificationClientMutation) WhereP(ps ...func(*sql.Selector)) {
|
||||
p := make([]predicate.NotificationClient, len(ps))
|
||||
for i := range ps {
|
||||
p[i] = ps[i]
|
||||
}
|
||||
m.Where(p...)
|
||||
}
|
||||
|
||||
// Op returns the operation name.
|
||||
func (m *NotificationClientMutation) Op() Op {
|
||||
return m.op
|
||||
}
|
||||
|
||||
// SetOp allows setting the mutation operation.
|
||||
func (m *NotificationClientMutation) SetOp(op Op) {
|
||||
m.op = op
|
||||
}
|
||||
|
||||
// Type returns the node type of this mutation (NotificationClient).
|
||||
func (m *NotificationClientMutation) Type() string {
|
||||
return m.typ
|
||||
}
|
||||
|
||||
// Fields returns all fields that were changed during this mutation. Note that in
|
||||
// order to get all numeric fields that were incremented/decremented, call
|
||||
// AddedFields().
|
||||
func (m *NotificationClientMutation) Fields() []string {
|
||||
fields := make([]string, 0, 4)
|
||||
if m.name != nil {
|
||||
fields = append(fields, notificationclient.FieldName)
|
||||
}
|
||||
if m.service != nil {
|
||||
fields = append(fields, notificationclient.FieldService)
|
||||
}
|
||||
if m.settings != nil {
|
||||
fields = append(fields, notificationclient.FieldSettings)
|
||||
}
|
||||
if m.enabled != nil {
|
||||
fields = append(fields, notificationclient.FieldEnabled)
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
// Field returns the value of a field with the given name. The second boolean
|
||||
// return value indicates that this field was not set, or was not defined in the
|
||||
// schema.
|
||||
func (m *NotificationClientMutation) Field(name string) (ent.Value, bool) {
|
||||
switch name {
|
||||
case notificationclient.FieldName:
|
||||
return m.Name()
|
||||
case notificationclient.FieldService:
|
||||
return m.Service()
|
||||
case notificationclient.FieldSettings:
|
||||
return m.Settings()
|
||||
case notificationclient.FieldEnabled:
|
||||
return m.Enabled()
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// OldField returns the old value of the field from the database. An error is
|
||||
// returned if the mutation operation is not UpdateOne, or the query to the
|
||||
// database failed.
|
||||
func (m *NotificationClientMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
|
||||
switch name {
|
||||
case notificationclient.FieldName:
|
||||
return m.OldName(ctx)
|
||||
case notificationclient.FieldService:
|
||||
return m.OldService(ctx)
|
||||
case notificationclient.FieldSettings:
|
||||
return m.OldSettings(ctx)
|
||||
case notificationclient.FieldEnabled:
|
||||
return m.OldEnabled(ctx)
|
||||
}
|
||||
return nil, fmt.Errorf("unknown NotificationClient field %s", name)
|
||||
}
|
||||
|
||||
// SetField sets the value of a field with the given name. It returns an error if
|
||||
// the field is not defined in the schema, or if the type mismatched the field
|
||||
// type.
|
||||
func (m *NotificationClientMutation) SetField(name string, value ent.Value) error {
|
||||
switch name {
|
||||
case notificationclient.FieldName:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetName(v)
|
||||
return nil
|
||||
case notificationclient.FieldService:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetService(v)
|
||||
return nil
|
||||
case notificationclient.FieldSettings:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetSettings(v)
|
||||
return nil
|
||||
case notificationclient.FieldEnabled:
|
||||
v, ok := value.(bool)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetEnabled(v)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown NotificationClient field %s", name)
|
||||
}
|
||||
|
||||
// AddedFields returns all numeric fields that were incremented/decremented during
|
||||
// this mutation.
|
||||
func (m *NotificationClientMutation) AddedFields() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddedField returns the numeric value that was incremented/decremented on a field
|
||||
// with the given name. The second boolean return value indicates that this field
|
||||
// was not set, or was not defined in the schema.
|
||||
func (m *NotificationClientMutation) AddedField(name string) (ent.Value, bool) {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// AddField adds the value to the field with the given name. It returns an error if
|
||||
// the field is not defined in the schema, or if the type mismatched the field
|
||||
// type.
|
||||
func (m *NotificationClientMutation) AddField(name string, value ent.Value) error {
|
||||
switch name {
|
||||
}
|
||||
return fmt.Errorf("unknown NotificationClient numeric field %s", name)
|
||||
}
|
||||
|
||||
// ClearedFields returns all nullable fields that were cleared during this
|
||||
// mutation.
|
||||
func (m *NotificationClientMutation) ClearedFields() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
// FieldCleared returns a boolean indicating if a field with the given name was
|
||||
// cleared in this mutation.
|
||||
func (m *NotificationClientMutation) FieldCleared(name string) bool {
|
||||
_, ok := m.clearedFields[name]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ClearField clears the value of the field with the given name. It returns an
|
||||
// error if the field is not defined in the schema.
|
||||
func (m *NotificationClientMutation) ClearField(name string) error {
|
||||
return fmt.Errorf("unknown NotificationClient nullable field %s", name)
|
||||
}
|
||||
|
||||
// ResetField resets all changes in the mutation for the field with the given name.
|
||||
// It returns an error if the field is not defined in the schema.
|
||||
func (m *NotificationClientMutation) ResetField(name string) error {
|
||||
switch name {
|
||||
case notificationclient.FieldName:
|
||||
m.ResetName()
|
||||
return nil
|
||||
case notificationclient.FieldService:
|
||||
m.ResetService()
|
||||
return nil
|
||||
case notificationclient.FieldSettings:
|
||||
m.ResetSettings()
|
||||
return nil
|
||||
case notificationclient.FieldEnabled:
|
||||
m.ResetEnabled()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown NotificationClient field %s", name)
|
||||
}
|
||||
|
||||
// AddedEdges returns all edge names that were set/added in this mutation.
|
||||
func (m *NotificationClientMutation) AddedEdges() []string {
|
||||
edges := make([]string, 0, 0)
|
||||
return edges
|
||||
}
|
||||
|
||||
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
|
||||
// name in this mutation.
|
||||
func (m *NotificationClientMutation) AddedIDs(name string) []ent.Value {
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemovedEdges returns all edge names that were removed in this mutation.
|
||||
func (m *NotificationClientMutation) RemovedEdges() []string {
|
||||
edges := make([]string, 0, 0)
|
||||
return edges
|
||||
}
|
||||
|
||||
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
|
||||
// the given name in this mutation.
|
||||
func (m *NotificationClientMutation) RemovedIDs(name string) []ent.Value {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearedEdges returns all edge names that were cleared in this mutation.
|
||||
func (m *NotificationClientMutation) ClearedEdges() []string {
|
||||
edges := make([]string, 0, 0)
|
||||
return edges
|
||||
}
|
||||
|
||||
// EdgeCleared returns a boolean which indicates if the edge with the given name
|
||||
// was cleared in this mutation.
|
||||
func (m *NotificationClientMutation) EdgeCleared(name string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// ClearEdge clears the value of the edge with the given name. It returns an error
|
||||
// if that edge is not defined in the schema.
|
||||
func (m *NotificationClientMutation) ClearEdge(name string) error {
|
||||
return fmt.Errorf("unknown NotificationClient unique edge %s", name)
|
||||
}
|
||||
|
||||
// ResetEdge resets all changes to the edge with the given name in this mutation.
|
||||
// It returns an error if the edge is not defined in the schema.
|
||||
func (m *NotificationClientMutation) ResetEdge(name string) error {
|
||||
return fmt.Errorf("unknown NotificationClient edge %s", name)
|
||||
}
|
||||
|
||||
// SettingsMutation represents an operation that mutates the Settings nodes in the graph.
|
||||
type SettingsMutation struct {
|
||||
config
|
||||
@@ -4730,6 +5327,8 @@ type StorageMutation struct {
|
||||
id *int
|
||||
name *string
|
||||
implementation *storage.Implementation
|
||||
tv_path *string
|
||||
movie_path *string
|
||||
settings *string
|
||||
deleted *bool
|
||||
_default *bool
|
||||
@@ -4909,6 +5508,104 @@ func (m *StorageMutation) ResetImplementation() {
|
||||
m.implementation = nil
|
||||
}
|
||||
|
||||
// SetTvPath sets the "tv_path" field.
|
||||
func (m *StorageMutation) SetTvPath(s string) {
|
||||
m.tv_path = &s
|
||||
}
|
||||
|
||||
// TvPath returns the value of the "tv_path" field in the mutation.
|
||||
func (m *StorageMutation) TvPath() (r string, exists bool) {
|
||||
v := m.tv_path
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldTvPath returns the old "tv_path" field's value of the Storage entity.
|
||||
// If the Storage object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *StorageMutation) OldTvPath(ctx context.Context) (v string, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldTvPath is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldTvPath requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldTvPath: %w", err)
|
||||
}
|
||||
return oldValue.TvPath, nil
|
||||
}
|
||||
|
||||
// ClearTvPath clears the value of the "tv_path" field.
|
||||
func (m *StorageMutation) ClearTvPath() {
|
||||
m.tv_path = nil
|
||||
m.clearedFields[storage.FieldTvPath] = struct{}{}
|
||||
}
|
||||
|
||||
// TvPathCleared returns if the "tv_path" field was cleared in this mutation.
|
||||
func (m *StorageMutation) TvPathCleared() bool {
|
||||
_, ok := m.clearedFields[storage.FieldTvPath]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ResetTvPath resets all changes to the "tv_path" field.
|
||||
func (m *StorageMutation) ResetTvPath() {
|
||||
m.tv_path = nil
|
||||
delete(m.clearedFields, storage.FieldTvPath)
|
||||
}
|
||||
|
||||
// SetMoviePath sets the "movie_path" field.
|
||||
func (m *StorageMutation) SetMoviePath(s string) {
|
||||
m.movie_path = &s
|
||||
}
|
||||
|
||||
// MoviePath returns the value of the "movie_path" field in the mutation.
|
||||
func (m *StorageMutation) MoviePath() (r string, exists bool) {
|
||||
v := m.movie_path
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldMoviePath returns the old "movie_path" field's value of the Storage entity.
|
||||
// If the Storage object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *StorageMutation) OldMoviePath(ctx context.Context) (v string, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldMoviePath is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldMoviePath requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldMoviePath: %w", err)
|
||||
}
|
||||
return oldValue.MoviePath, nil
|
||||
}
|
||||
|
||||
// ClearMoviePath clears the value of the "movie_path" field.
|
||||
func (m *StorageMutation) ClearMoviePath() {
|
||||
m.movie_path = nil
|
||||
m.clearedFields[storage.FieldMoviePath] = struct{}{}
|
||||
}
|
||||
|
||||
// MoviePathCleared returns if the "movie_path" field was cleared in this mutation.
|
||||
func (m *StorageMutation) MoviePathCleared() bool {
|
||||
_, ok := m.clearedFields[storage.FieldMoviePath]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ResetMoviePath resets all changes to the "movie_path" field.
|
||||
func (m *StorageMutation) ResetMoviePath() {
|
||||
m.movie_path = nil
|
||||
delete(m.clearedFields, storage.FieldMoviePath)
|
||||
}
|
||||
|
||||
// SetSettings sets the "settings" field.
|
||||
func (m *StorageMutation) SetSettings(s string) {
|
||||
m.settings = &s
|
||||
@@ -5064,13 +5761,19 @@ func (m *StorageMutation) Type() string {
|
||||
// order to get all numeric fields that were incremented/decremented, call
|
||||
// AddedFields().
|
||||
func (m *StorageMutation) Fields() []string {
|
||||
fields := make([]string, 0, 5)
|
||||
fields := make([]string, 0, 7)
|
||||
if m.name != nil {
|
||||
fields = append(fields, storage.FieldName)
|
||||
}
|
||||
if m.implementation != nil {
|
||||
fields = append(fields, storage.FieldImplementation)
|
||||
}
|
||||
if m.tv_path != nil {
|
||||
fields = append(fields, storage.FieldTvPath)
|
||||
}
|
||||
if m.movie_path != nil {
|
||||
fields = append(fields, storage.FieldMoviePath)
|
||||
}
|
||||
if m.settings != nil {
|
||||
fields = append(fields, storage.FieldSettings)
|
||||
}
|
||||
@@ -5092,6 +5795,10 @@ func (m *StorageMutation) Field(name string) (ent.Value, bool) {
|
||||
return m.Name()
|
||||
case storage.FieldImplementation:
|
||||
return m.Implementation()
|
||||
case storage.FieldTvPath:
|
||||
return m.TvPath()
|
||||
case storage.FieldMoviePath:
|
||||
return m.MoviePath()
|
||||
case storage.FieldSettings:
|
||||
return m.Settings()
|
||||
case storage.FieldDeleted:
|
||||
@@ -5111,6 +5818,10 @@ func (m *StorageMutation) OldField(ctx context.Context, name string) (ent.Value,
|
||||
return m.OldName(ctx)
|
||||
case storage.FieldImplementation:
|
||||
return m.OldImplementation(ctx)
|
||||
case storage.FieldTvPath:
|
||||
return m.OldTvPath(ctx)
|
||||
case storage.FieldMoviePath:
|
||||
return m.OldMoviePath(ctx)
|
||||
case storage.FieldSettings:
|
||||
return m.OldSettings(ctx)
|
||||
case storage.FieldDeleted:
|
||||
@@ -5140,6 +5851,20 @@ func (m *StorageMutation) SetField(name string, value ent.Value) error {
|
||||
}
|
||||
m.SetImplementation(v)
|
||||
return nil
|
||||
case storage.FieldTvPath:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetTvPath(v)
|
||||
return nil
|
||||
case storage.FieldMoviePath:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetMoviePath(v)
|
||||
return nil
|
||||
case storage.FieldSettings:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
@@ -5191,6 +5916,12 @@ func (m *StorageMutation) AddField(name string, value ent.Value) error {
|
||||
// mutation.
|
||||
func (m *StorageMutation) ClearedFields() []string {
|
||||
var fields []string
|
||||
if m.FieldCleared(storage.FieldTvPath) {
|
||||
fields = append(fields, storage.FieldTvPath)
|
||||
}
|
||||
if m.FieldCleared(storage.FieldMoviePath) {
|
||||
fields = append(fields, storage.FieldMoviePath)
|
||||
}
|
||||
if m.FieldCleared(storage.FieldSettings) {
|
||||
fields = append(fields, storage.FieldSettings)
|
||||
}
|
||||
@@ -5208,6 +5939,12 @@ func (m *StorageMutation) FieldCleared(name string) bool {
|
||||
// error if the field is not defined in the schema.
|
||||
func (m *StorageMutation) ClearField(name string) error {
|
||||
switch name {
|
||||
case storage.FieldTvPath:
|
||||
m.ClearTvPath()
|
||||
return nil
|
||||
case storage.FieldMoviePath:
|
||||
m.ClearMoviePath()
|
||||
return nil
|
||||
case storage.FieldSettings:
|
||||
m.ClearSettings()
|
||||
return nil
|
||||
@@ -5225,6 +5962,12 @@ func (m *StorageMutation) ResetField(name string) error {
|
||||
case storage.FieldImplementation:
|
||||
m.ResetImplementation()
|
||||
return nil
|
||||
case storage.FieldTvPath:
|
||||
m.ResetTvPath()
|
||||
return nil
|
||||
case storage.FieldMoviePath:
|
||||
m.ResetMoviePath()
|
||||
return nil
|
||||
case storage.FieldSettings:
|
||||
m.ResetSettings()
|
||||
return nil
|
||||
|
||||
138
ent/notificationclient.go
Normal file
138
ent/notificationclient.go
Normal file
@@ -0,0 +1,138 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"polaris/ent/notificationclient"
|
||||
"strings"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
// NotificationClient is the model entity for the NotificationClient schema.
|
||||
type NotificationClient struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID int `json:"id,omitempty"`
|
||||
// Name holds the value of the "name" field.
|
||||
Name string `json:"name,omitempty"`
|
||||
// Service holds the value of the "service" field.
|
||||
Service string `json:"service,omitempty"`
|
||||
// Settings holds the value of the "settings" field.
|
||||
Settings string `json:"settings,omitempty"`
|
||||
// Enabled holds the value of the "enabled" field.
|
||||
Enabled bool `json:"enabled,omitempty"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*NotificationClient) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case notificationclient.FieldEnabled:
|
||||
values[i] = new(sql.NullBool)
|
||||
case notificationclient.FieldID:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case notificationclient.FieldName, notificationclient.FieldService, notificationclient.FieldSettings:
|
||||
values[i] = new(sql.NullString)
|
||||
default:
|
||||
values[i] = new(sql.UnknownType)
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// assignValues assigns the values that were returned from sql.Rows (after scanning)
|
||||
// to the NotificationClient fields.
|
||||
func (nc *NotificationClient) assignValues(columns []string, values []any) error {
|
||||
if m, n := len(values), len(columns); m < n {
|
||||
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
|
||||
}
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case notificationclient.FieldID:
|
||||
value, ok := values[i].(*sql.NullInt64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", value)
|
||||
}
|
||||
nc.ID = int(value.Int64)
|
||||
case notificationclient.FieldName:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field name", values[i])
|
||||
} else if value.Valid {
|
||||
nc.Name = value.String
|
||||
}
|
||||
case notificationclient.FieldService:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field service", values[i])
|
||||
} else if value.Valid {
|
||||
nc.Service = value.String
|
||||
}
|
||||
case notificationclient.FieldSettings:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field settings", values[i])
|
||||
} else if value.Valid {
|
||||
nc.Settings = value.String
|
||||
}
|
||||
case notificationclient.FieldEnabled:
|
||||
if value, ok := values[i].(*sql.NullBool); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field enabled", values[i])
|
||||
} else if value.Valid {
|
||||
nc.Enabled = value.Bool
|
||||
}
|
||||
default:
|
||||
nc.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value returns the ent.Value that was dynamically selected and assigned to the NotificationClient.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (nc *NotificationClient) Value(name string) (ent.Value, error) {
|
||||
return nc.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this NotificationClient.
|
||||
// Note that you need to call NotificationClient.Unwrap() before calling this method if this NotificationClient
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (nc *NotificationClient) Update() *NotificationClientUpdateOne {
|
||||
return NewNotificationClientClient(nc.config).UpdateOne(nc)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the NotificationClient entity that was returned from a transaction after it was closed,
|
||||
// so that all future queries will be executed through the driver which created the transaction.
|
||||
func (nc *NotificationClient) Unwrap() *NotificationClient {
|
||||
_tx, ok := nc.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: NotificationClient is not a transactional entity")
|
||||
}
|
||||
nc.config.driver = _tx.drv
|
||||
return nc
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (nc *NotificationClient) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("NotificationClient(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", nc.ID))
|
||||
builder.WriteString("name=")
|
||||
builder.WriteString(nc.Name)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("service=")
|
||||
builder.WriteString(nc.Service)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("settings=")
|
||||
builder.WriteString(nc.Settings)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("enabled=")
|
||||
builder.WriteString(fmt.Sprintf("%v", nc.Enabled))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// NotificationClients is a parsable slice of NotificationClient.
|
||||
type NotificationClients []*NotificationClient
|
||||
76
ent/notificationclient/notificationclient.go
Normal file
76
ent/notificationclient/notificationclient.go
Normal file
@@ -0,0 +1,76 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package notificationclient
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the notificationclient type in the database.
|
||||
Label = "notification_client"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldName holds the string denoting the name field in the database.
|
||||
FieldName = "name"
|
||||
// FieldService holds the string denoting the service field in the database.
|
||||
FieldService = "service"
|
||||
// FieldSettings holds the string denoting the settings field in the database.
|
||||
FieldSettings = "settings"
|
||||
// FieldEnabled holds the string denoting the enabled field in the database.
|
||||
FieldEnabled = "enabled"
|
||||
// Table holds the table name of the notificationclient in the database.
|
||||
Table = "notification_clients"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for notificationclient fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldName,
|
||||
FieldService,
|
||||
FieldSettings,
|
||||
FieldEnabled,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
if column == Columns[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var (
|
||||
// DefaultEnabled holds the default value on creation for the "enabled" field.
|
||||
DefaultEnabled bool
|
||||
)
|
||||
|
||||
// OrderOption defines the ordering options for the NotificationClient queries.
|
||||
type OrderOption func(*sql.Selector)
|
||||
|
||||
// ByID orders the results by the id field.
|
||||
func ByID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByName orders the results by the name field.
|
||||
func ByName(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldName, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByService orders the results by the service field.
|
||||
func ByService(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldService, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// BySettings orders the results by the settings field.
|
||||
func BySettings(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldSettings, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByEnabled orders the results by the enabled field.
|
||||
func ByEnabled(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldEnabled, opts...).ToFunc()
|
||||
}
|
||||
294
ent/notificationclient/where.go
Normal file
294
ent/notificationclient/where.go
Normal file
@@ -0,0 +1,294 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package notificationclient
|
||||
|
||||
import (
|
||||
"polaris/ent/predicate"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id int) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id int) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id int) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...int) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...int) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id int) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id int) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id int) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id int) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
|
||||
func Name(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldEQ(FieldName, v))
|
||||
}
|
||||
|
||||
// Service applies equality check predicate on the "service" field. It's identical to ServiceEQ.
|
||||
func Service(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldEQ(FieldService, v))
|
||||
}
|
||||
|
||||
// Settings applies equality check predicate on the "settings" field. It's identical to SettingsEQ.
|
||||
func Settings(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldEQ(FieldSettings, v))
|
||||
}
|
||||
|
||||
// Enabled applies equality check predicate on the "enabled" field. It's identical to EnabledEQ.
|
||||
func Enabled(v bool) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldEQ(FieldEnabled, v))
|
||||
}
|
||||
|
||||
// NameEQ applies the EQ predicate on the "name" field.
|
||||
func NameEQ(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldEQ(FieldName, v))
|
||||
}
|
||||
|
||||
// NameNEQ applies the NEQ predicate on the "name" field.
|
||||
func NameNEQ(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldNEQ(FieldName, v))
|
||||
}
|
||||
|
||||
// NameIn applies the In predicate on the "name" field.
|
||||
func NameIn(vs ...string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldIn(FieldName, vs...))
|
||||
}
|
||||
|
||||
// NameNotIn applies the NotIn predicate on the "name" field.
|
||||
func NameNotIn(vs ...string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldNotIn(FieldName, vs...))
|
||||
}
|
||||
|
||||
// NameGT applies the GT predicate on the "name" field.
|
||||
func NameGT(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldGT(FieldName, v))
|
||||
}
|
||||
|
||||
// NameGTE applies the GTE predicate on the "name" field.
|
||||
func NameGTE(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldGTE(FieldName, v))
|
||||
}
|
||||
|
||||
// NameLT applies the LT predicate on the "name" field.
|
||||
func NameLT(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldLT(FieldName, v))
|
||||
}
|
||||
|
||||
// NameLTE applies the LTE predicate on the "name" field.
|
||||
func NameLTE(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldLTE(FieldName, v))
|
||||
}
|
||||
|
||||
// NameContains applies the Contains predicate on the "name" field.
|
||||
func NameContains(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldContains(FieldName, v))
|
||||
}
|
||||
|
||||
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
|
||||
func NameHasPrefix(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldHasPrefix(FieldName, v))
|
||||
}
|
||||
|
||||
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
|
||||
func NameHasSuffix(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldHasSuffix(FieldName, v))
|
||||
}
|
||||
|
||||
// NameEqualFold applies the EqualFold predicate on the "name" field.
|
||||
func NameEqualFold(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldEqualFold(FieldName, v))
|
||||
}
|
||||
|
||||
// NameContainsFold applies the ContainsFold predicate on the "name" field.
|
||||
func NameContainsFold(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldContainsFold(FieldName, v))
|
||||
}
|
||||
|
||||
// ServiceEQ applies the EQ predicate on the "service" field.
|
||||
func ServiceEQ(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldEQ(FieldService, v))
|
||||
}
|
||||
|
||||
// ServiceNEQ applies the NEQ predicate on the "service" field.
|
||||
func ServiceNEQ(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldNEQ(FieldService, v))
|
||||
}
|
||||
|
||||
// ServiceIn applies the In predicate on the "service" field.
|
||||
func ServiceIn(vs ...string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldIn(FieldService, vs...))
|
||||
}
|
||||
|
||||
// ServiceNotIn applies the NotIn predicate on the "service" field.
|
||||
func ServiceNotIn(vs ...string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldNotIn(FieldService, vs...))
|
||||
}
|
||||
|
||||
// ServiceGT applies the GT predicate on the "service" field.
|
||||
func ServiceGT(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldGT(FieldService, v))
|
||||
}
|
||||
|
||||
// ServiceGTE applies the GTE predicate on the "service" field.
|
||||
func ServiceGTE(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldGTE(FieldService, v))
|
||||
}
|
||||
|
||||
// ServiceLT applies the LT predicate on the "service" field.
|
||||
func ServiceLT(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldLT(FieldService, v))
|
||||
}
|
||||
|
||||
// ServiceLTE applies the LTE predicate on the "service" field.
|
||||
func ServiceLTE(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldLTE(FieldService, v))
|
||||
}
|
||||
|
||||
// ServiceContains applies the Contains predicate on the "service" field.
|
||||
func ServiceContains(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldContains(FieldService, v))
|
||||
}
|
||||
|
||||
// ServiceHasPrefix applies the HasPrefix predicate on the "service" field.
|
||||
func ServiceHasPrefix(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldHasPrefix(FieldService, v))
|
||||
}
|
||||
|
||||
// ServiceHasSuffix applies the HasSuffix predicate on the "service" field.
|
||||
func ServiceHasSuffix(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldHasSuffix(FieldService, v))
|
||||
}
|
||||
|
||||
// ServiceEqualFold applies the EqualFold predicate on the "service" field.
|
||||
func ServiceEqualFold(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldEqualFold(FieldService, v))
|
||||
}
|
||||
|
||||
// ServiceContainsFold applies the ContainsFold predicate on the "service" field.
|
||||
func ServiceContainsFold(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldContainsFold(FieldService, v))
|
||||
}
|
||||
|
||||
// SettingsEQ applies the EQ predicate on the "settings" field.
|
||||
func SettingsEQ(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldEQ(FieldSettings, v))
|
||||
}
|
||||
|
||||
// SettingsNEQ applies the NEQ predicate on the "settings" field.
|
||||
func SettingsNEQ(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldNEQ(FieldSettings, v))
|
||||
}
|
||||
|
||||
// SettingsIn applies the In predicate on the "settings" field.
|
||||
func SettingsIn(vs ...string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldIn(FieldSettings, vs...))
|
||||
}
|
||||
|
||||
// SettingsNotIn applies the NotIn predicate on the "settings" field.
|
||||
func SettingsNotIn(vs ...string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldNotIn(FieldSettings, vs...))
|
||||
}
|
||||
|
||||
// SettingsGT applies the GT predicate on the "settings" field.
|
||||
func SettingsGT(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldGT(FieldSettings, v))
|
||||
}
|
||||
|
||||
// SettingsGTE applies the GTE predicate on the "settings" field.
|
||||
func SettingsGTE(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldGTE(FieldSettings, v))
|
||||
}
|
||||
|
||||
// SettingsLT applies the LT predicate on the "settings" field.
|
||||
func SettingsLT(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldLT(FieldSettings, v))
|
||||
}
|
||||
|
||||
// SettingsLTE applies the LTE predicate on the "settings" field.
|
||||
func SettingsLTE(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldLTE(FieldSettings, v))
|
||||
}
|
||||
|
||||
// SettingsContains applies the Contains predicate on the "settings" field.
|
||||
func SettingsContains(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldContains(FieldSettings, v))
|
||||
}
|
||||
|
||||
// SettingsHasPrefix applies the HasPrefix predicate on the "settings" field.
|
||||
func SettingsHasPrefix(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldHasPrefix(FieldSettings, v))
|
||||
}
|
||||
|
||||
// SettingsHasSuffix applies the HasSuffix predicate on the "settings" field.
|
||||
func SettingsHasSuffix(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldHasSuffix(FieldSettings, v))
|
||||
}
|
||||
|
||||
// SettingsEqualFold applies the EqualFold predicate on the "settings" field.
|
||||
func SettingsEqualFold(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldEqualFold(FieldSettings, v))
|
||||
}
|
||||
|
||||
// SettingsContainsFold applies the ContainsFold predicate on the "settings" field.
|
||||
func SettingsContainsFold(v string) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldContainsFold(FieldSettings, v))
|
||||
}
|
||||
|
||||
// EnabledEQ applies the EQ predicate on the "enabled" field.
|
||||
func EnabledEQ(v bool) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldEQ(FieldEnabled, v))
|
||||
}
|
||||
|
||||
// EnabledNEQ applies the NEQ predicate on the "enabled" field.
|
||||
func EnabledNEQ(v bool) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.FieldNEQ(FieldEnabled, v))
|
||||
}
|
||||
|
||||
// And groups predicates with the AND operator between them.
|
||||
func And(predicates ...predicate.NotificationClient) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.AndPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.NotificationClient) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.OrPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.NotificationClient) predicate.NotificationClient {
|
||||
return predicate.NotificationClient(sql.NotPredicates(p))
|
||||
}
|
||||
240
ent/notificationclient_create.go
Normal file
240
ent/notificationclient_create.go
Normal file
@@ -0,0 +1,240 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"polaris/ent/notificationclient"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// NotificationClientCreate is the builder for creating a NotificationClient entity.
|
||||
type NotificationClientCreate struct {
|
||||
config
|
||||
mutation *NotificationClientMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetName sets the "name" field.
|
||||
func (ncc *NotificationClientCreate) SetName(s string) *NotificationClientCreate {
|
||||
ncc.mutation.SetName(s)
|
||||
return ncc
|
||||
}
|
||||
|
||||
// SetService sets the "service" field.
|
||||
func (ncc *NotificationClientCreate) SetService(s string) *NotificationClientCreate {
|
||||
ncc.mutation.SetService(s)
|
||||
return ncc
|
||||
}
|
||||
|
||||
// SetSettings sets the "settings" field.
|
||||
func (ncc *NotificationClientCreate) SetSettings(s string) *NotificationClientCreate {
|
||||
ncc.mutation.SetSettings(s)
|
||||
return ncc
|
||||
}
|
||||
|
||||
// SetEnabled sets the "enabled" field.
|
||||
func (ncc *NotificationClientCreate) SetEnabled(b bool) *NotificationClientCreate {
|
||||
ncc.mutation.SetEnabled(b)
|
||||
return ncc
|
||||
}
|
||||
|
||||
// SetNillableEnabled sets the "enabled" field if the given value is not nil.
|
||||
func (ncc *NotificationClientCreate) SetNillableEnabled(b *bool) *NotificationClientCreate {
|
||||
if b != nil {
|
||||
ncc.SetEnabled(*b)
|
||||
}
|
||||
return ncc
|
||||
}
|
||||
|
||||
// Mutation returns the NotificationClientMutation object of the builder.
|
||||
func (ncc *NotificationClientCreate) Mutation() *NotificationClientMutation {
|
||||
return ncc.mutation
|
||||
}
|
||||
|
||||
// Save creates the NotificationClient in the database.
|
||||
func (ncc *NotificationClientCreate) Save(ctx context.Context) (*NotificationClient, error) {
|
||||
ncc.defaults()
|
||||
return withHooks(ctx, ncc.sqlSave, ncc.mutation, ncc.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (ncc *NotificationClientCreate) SaveX(ctx context.Context) *NotificationClient {
|
||||
v, err := ncc.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (ncc *NotificationClientCreate) Exec(ctx context.Context) error {
|
||||
_, err := ncc.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (ncc *NotificationClientCreate) ExecX(ctx context.Context) {
|
||||
if err := ncc.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaults sets the default values of the builder before save.
|
||||
func (ncc *NotificationClientCreate) defaults() {
|
||||
if _, ok := ncc.mutation.Enabled(); !ok {
|
||||
v := notificationclient.DefaultEnabled
|
||||
ncc.mutation.SetEnabled(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (ncc *NotificationClientCreate) check() error {
|
||||
if _, ok := ncc.mutation.Name(); !ok {
|
||||
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "NotificationClient.name"`)}
|
||||
}
|
||||
if _, ok := ncc.mutation.Service(); !ok {
|
||||
return &ValidationError{Name: "service", err: errors.New(`ent: missing required field "NotificationClient.service"`)}
|
||||
}
|
||||
if _, ok := ncc.mutation.Settings(); !ok {
|
||||
return &ValidationError{Name: "settings", err: errors.New(`ent: missing required field "NotificationClient.settings"`)}
|
||||
}
|
||||
if _, ok := ncc.mutation.Enabled(); !ok {
|
||||
return &ValidationError{Name: "enabled", err: errors.New(`ent: missing required field "NotificationClient.enabled"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ncc *NotificationClientCreate) sqlSave(ctx context.Context) (*NotificationClient, error) {
|
||||
if err := ncc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := ncc.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, ncc.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
id := _spec.ID.Value.(int64)
|
||||
_node.ID = int(id)
|
||||
ncc.mutation.id = &_node.ID
|
||||
ncc.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (ncc *NotificationClientCreate) createSpec() (*NotificationClient, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &NotificationClient{config: ncc.config}
|
||||
_spec = sqlgraph.NewCreateSpec(notificationclient.Table, sqlgraph.NewFieldSpec(notificationclient.FieldID, field.TypeInt))
|
||||
)
|
||||
if value, ok := ncc.mutation.Name(); ok {
|
||||
_spec.SetField(notificationclient.FieldName, field.TypeString, value)
|
||||
_node.Name = value
|
||||
}
|
||||
if value, ok := ncc.mutation.Service(); ok {
|
||||
_spec.SetField(notificationclient.FieldService, field.TypeString, value)
|
||||
_node.Service = value
|
||||
}
|
||||
if value, ok := ncc.mutation.Settings(); ok {
|
||||
_spec.SetField(notificationclient.FieldSettings, field.TypeString, value)
|
||||
_node.Settings = value
|
||||
}
|
||||
if value, ok := ncc.mutation.Enabled(); ok {
|
||||
_spec.SetField(notificationclient.FieldEnabled, field.TypeBool, value)
|
||||
_node.Enabled = value
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// NotificationClientCreateBulk is the builder for creating many NotificationClient entities in bulk.
|
||||
type NotificationClientCreateBulk struct {
|
||||
config
|
||||
err error
|
||||
builders []*NotificationClientCreate
|
||||
}
|
||||
|
||||
// Save creates the NotificationClient entities in the database.
|
||||
func (nccb *NotificationClientCreateBulk) Save(ctx context.Context) ([]*NotificationClient, error) {
|
||||
if nccb.err != nil {
|
||||
return nil, nccb.err
|
||||
}
|
||||
specs := make([]*sqlgraph.CreateSpec, len(nccb.builders))
|
||||
nodes := make([]*NotificationClient, len(nccb.builders))
|
||||
mutators := make([]Mutator, len(nccb.builders))
|
||||
for i := range nccb.builders {
|
||||
func(i int, root context.Context) {
|
||||
builder := nccb.builders[i]
|
||||
builder.defaults()
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*NotificationClientMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err := builder.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
builder.mutation = mutation
|
||||
var err error
|
||||
nodes[i], specs[i] = builder.createSpec()
|
||||
if i < len(mutators)-1 {
|
||||
_, err = mutators[i+1].Mutate(root, nccb.builders[i+1].mutation)
|
||||
} else {
|
||||
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
|
||||
// Invoke the actual operation on the latest mutation in the chain.
|
||||
if err = sqlgraph.BatchCreate(ctx, nccb.driver, spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &nodes[i].ID
|
||||
if specs[i].ID.Value != nil {
|
||||
id := specs[i].ID.Value.(int64)
|
||||
nodes[i].ID = int(id)
|
||||
}
|
||||
mutation.done = true
|
||||
return nodes[i], nil
|
||||
})
|
||||
for i := len(builder.hooks) - 1; i >= 0; i-- {
|
||||
mut = builder.hooks[i](mut)
|
||||
}
|
||||
mutators[i] = mut
|
||||
}(i, ctx)
|
||||
}
|
||||
if len(mutators) > 0 {
|
||||
if _, err := mutators[0].Mutate(ctx, nccb.builders[0].mutation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (nccb *NotificationClientCreateBulk) SaveX(ctx context.Context) []*NotificationClient {
|
||||
v, err := nccb.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (nccb *NotificationClientCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := nccb.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (nccb *NotificationClientCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := nccb.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
88
ent/notificationclient_delete.go
Normal file
88
ent/notificationclient_delete.go
Normal file
@@ -0,0 +1,88 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"polaris/ent/notificationclient"
|
||||
"polaris/ent/predicate"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// NotificationClientDelete is the builder for deleting a NotificationClient entity.
|
||||
type NotificationClientDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *NotificationClientMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the NotificationClientDelete builder.
|
||||
func (ncd *NotificationClientDelete) Where(ps ...predicate.NotificationClient) *NotificationClientDelete {
|
||||
ncd.mutation.Where(ps...)
|
||||
return ncd
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (ncd *NotificationClientDelete) Exec(ctx context.Context) (int, error) {
|
||||
return withHooks(ctx, ncd.sqlExec, ncd.mutation, ncd.hooks)
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (ncd *NotificationClientDelete) ExecX(ctx context.Context) int {
|
||||
n, err := ncd.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (ncd *NotificationClientDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(notificationclient.Table, sqlgraph.NewFieldSpec(notificationclient.FieldID, field.TypeInt))
|
||||
if ps := ncd.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
affected, err := sqlgraph.DeleteNodes(ctx, ncd.driver, _spec)
|
||||
if err != nil && sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
ncd.mutation.done = true
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// NotificationClientDeleteOne is the builder for deleting a single NotificationClient entity.
|
||||
type NotificationClientDeleteOne struct {
|
||||
ncd *NotificationClientDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the NotificationClientDelete builder.
|
||||
func (ncdo *NotificationClientDeleteOne) Where(ps ...predicate.NotificationClient) *NotificationClientDeleteOne {
|
||||
ncdo.ncd.mutation.Where(ps...)
|
||||
return ncdo
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (ncdo *NotificationClientDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := ncdo.ncd.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{notificationclient.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (ncdo *NotificationClientDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := ncdo.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
526
ent/notificationclient_query.go
Normal file
526
ent/notificationclient_query.go
Normal file
@@ -0,0 +1,526 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"polaris/ent/notificationclient"
|
||||
"polaris/ent/predicate"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// NotificationClientQuery is the builder for querying NotificationClient entities.
|
||||
type NotificationClientQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []notificationclient.OrderOption
|
||||
inters []Interceptor
|
||||
predicates []predicate.NotificationClient
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the NotificationClientQuery builder.
|
||||
func (ncq *NotificationClientQuery) Where(ps ...predicate.NotificationClient) *NotificationClientQuery {
|
||||
ncq.predicates = append(ncq.predicates, ps...)
|
||||
return ncq
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
func (ncq *NotificationClientQuery) Limit(limit int) *NotificationClientQuery {
|
||||
ncq.ctx.Limit = &limit
|
||||
return ncq
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
func (ncq *NotificationClientQuery) Offset(offset int) *NotificationClientQuery {
|
||||
ncq.ctx.Offset = &offset
|
||||
return ncq
|
||||
}
|
||||
|
||||
// Unique configures the query builder to filter duplicate records on query.
|
||||
// By default, unique is set to true, and can be disabled using this method.
|
||||
func (ncq *NotificationClientQuery) Unique(unique bool) *NotificationClientQuery {
|
||||
ncq.ctx.Unique = &unique
|
||||
return ncq
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
func (ncq *NotificationClientQuery) Order(o ...notificationclient.OrderOption) *NotificationClientQuery {
|
||||
ncq.order = append(ncq.order, o...)
|
||||
return ncq
|
||||
}
|
||||
|
||||
// First returns the first NotificationClient entity from the query.
|
||||
// Returns a *NotFoundError when no NotificationClient was found.
|
||||
func (ncq *NotificationClientQuery) First(ctx context.Context) (*NotificationClient, error) {
|
||||
nodes, err := ncq.Limit(1).All(setContextOp(ctx, ncq.ctx, "First"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nil, &NotFoundError{notificationclient.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (ncq *NotificationClientQuery) FirstX(ctx context.Context) *NotificationClient {
|
||||
node, err := ncq.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first NotificationClient ID from the query.
|
||||
// Returns a *NotFoundError when no NotificationClient ID was found.
|
||||
func (ncq *NotificationClientQuery) FirstID(ctx context.Context) (id int, err error) {
|
||||
var ids []int
|
||||
if ids, err = ncq.Limit(1).IDs(setContextOp(ctx, ncq.ctx, "FirstID")); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &NotFoundError{notificationclient.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (ncq *NotificationClientQuery) FirstIDX(ctx context.Context) int {
|
||||
id, err := ncq.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single NotificationClient entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when more than one NotificationClient entity is found.
|
||||
// Returns a *NotFoundError when no NotificationClient entities are found.
|
||||
func (ncq *NotificationClientQuery) Only(ctx context.Context) (*NotificationClient, error) {
|
||||
nodes, err := ncq.Limit(2).All(setContextOp(ctx, ncq.ctx, "Only"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch len(nodes) {
|
||||
case 1:
|
||||
return nodes[0], nil
|
||||
case 0:
|
||||
return nil, &NotFoundError{notificationclient.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{notificationclient.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (ncq *NotificationClientQuery) OnlyX(ctx context.Context) *NotificationClient {
|
||||
node, err := ncq.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only NotificationClient ID in the query.
|
||||
// Returns a *NotSingularError when more than one NotificationClient ID is found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (ncq *NotificationClientQuery) OnlyID(ctx context.Context) (id int, err error) {
|
||||
var ids []int
|
||||
if ids, err = ncq.Limit(2).IDs(setContextOp(ctx, ncq.ctx, "OnlyID")); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(ids) {
|
||||
case 1:
|
||||
id = ids[0]
|
||||
case 0:
|
||||
err = &NotFoundError{notificationclient.Label}
|
||||
default:
|
||||
err = &NotSingularError{notificationclient.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (ncq *NotificationClientQuery) OnlyIDX(ctx context.Context) int {
|
||||
id, err := ncq.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of NotificationClients.
|
||||
func (ncq *NotificationClientQuery) All(ctx context.Context) ([]*NotificationClient, error) {
|
||||
ctx = setContextOp(ctx, ncq.ctx, "All")
|
||||
if err := ncq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*NotificationClient, *NotificationClientQuery]()
|
||||
return withInterceptors[[]*NotificationClient](ctx, ncq, qr, ncq.inters)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (ncq *NotificationClientQuery) AllX(ctx context.Context) []*NotificationClient {
|
||||
nodes, err := ncq.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of NotificationClient IDs.
|
||||
func (ncq *NotificationClientQuery) IDs(ctx context.Context) (ids []int, err error) {
|
||||
if ncq.ctx.Unique == nil && ncq.path != nil {
|
||||
ncq.Unique(true)
|
||||
}
|
||||
ctx = setContextOp(ctx, ncq.ctx, "IDs")
|
||||
if err = ncq.Select(notificationclient.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (ncq *NotificationClientQuery) IDsX(ctx context.Context) []int {
|
||||
ids, err := ncq.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (ncq *NotificationClientQuery) Count(ctx context.Context) (int, error) {
|
||||
ctx = setContextOp(ctx, ncq.ctx, "Count")
|
||||
if err := ncq.prepareQuery(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return withInterceptors[int](ctx, ncq, querierCount[*NotificationClientQuery](), ncq.inters)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (ncq *NotificationClientQuery) CountX(ctx context.Context) int {
|
||||
count, err := ncq.Count(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// Exist returns true if the query has elements in the graph.
|
||||
func (ncq *NotificationClientQuery) Exist(ctx context.Context) (bool, error) {
|
||||
ctx = setContextOp(ctx, ncq.ctx, "Exist")
|
||||
switch _, err := ncq.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExistX is like Exist, but panics if an error occurs.
|
||||
func (ncq *NotificationClientQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := ncq.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the NotificationClientQuery builder, including all associated steps. It can be
|
||||
// used to prepare common query builders and use them differently after the clone is made.
|
||||
func (ncq *NotificationClientQuery) Clone() *NotificationClientQuery {
|
||||
if ncq == nil {
|
||||
return nil
|
||||
}
|
||||
return &NotificationClientQuery{
|
||||
config: ncq.config,
|
||||
ctx: ncq.ctx.Clone(),
|
||||
order: append([]notificationclient.OrderOption{}, ncq.order...),
|
||||
inters: append([]Interceptor{}, ncq.inters...),
|
||||
predicates: append([]predicate.NotificationClient{}, ncq.predicates...),
|
||||
// clone intermediate query.
|
||||
sql: ncq.sql.Clone(),
|
||||
path: ncq.path,
|
||||
}
|
||||
}
|
||||
|
||||
// GroupBy is used to group vertices by one or more fields/columns.
|
||||
// It is often used with aggregate functions, like: count, max, mean, min, sum.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// Name string `json:"name,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.NotificationClient.Query().
|
||||
// GroupBy(notificationclient.FieldName).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (ncq *NotificationClientQuery) GroupBy(field string, fields ...string) *NotificationClientGroupBy {
|
||||
ncq.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &NotificationClientGroupBy{build: ncq}
|
||||
grbuild.flds = &ncq.ctx.Fields
|
||||
grbuild.label = notificationclient.Label
|
||||
grbuild.scan = grbuild.Scan
|
||||
return grbuild
|
||||
}
|
||||
|
||||
// Select allows the selection one or more fields/columns for the given query,
|
||||
// instead of selecting all fields in the entity.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// Name string `json:"name,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.NotificationClient.Query().
|
||||
// Select(notificationclient.FieldName).
|
||||
// Scan(ctx, &v)
|
||||
func (ncq *NotificationClientQuery) Select(fields ...string) *NotificationClientSelect {
|
||||
ncq.ctx.Fields = append(ncq.ctx.Fields, fields...)
|
||||
sbuild := &NotificationClientSelect{NotificationClientQuery: ncq}
|
||||
sbuild.label = notificationclient.Label
|
||||
sbuild.flds, sbuild.scan = &ncq.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a NotificationClientSelect configured with the given aggregations.
|
||||
func (ncq *NotificationClientQuery) Aggregate(fns ...AggregateFunc) *NotificationClientSelect {
|
||||
return ncq.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (ncq *NotificationClientQuery) prepareQuery(ctx context.Context) error {
|
||||
for _, inter := range ncq.inters {
|
||||
if inter == nil {
|
||||
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
|
||||
}
|
||||
if trv, ok := inter.(Traverser); ok {
|
||||
if err := trv.Traverse(ctx, ncq); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range ncq.ctx.Fields {
|
||||
if !notificationclient.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
}
|
||||
if ncq.path != nil {
|
||||
prev, err := ncq.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ncq.sql = prev
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ncq *NotificationClientQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*NotificationClient, error) {
|
||||
var (
|
||||
nodes = []*NotificationClient{}
|
||||
_spec = ncq.querySpec()
|
||||
)
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*NotificationClient).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &NotificationClient{config: ncq.config}
|
||||
nodes = append(nodes, node)
|
||||
return node.assignValues(columns, values)
|
||||
}
|
||||
for i := range hooks {
|
||||
hooks[i](ctx, _spec)
|
||||
}
|
||||
if err := sqlgraph.QueryNodes(ctx, ncq.driver, _spec); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nodes, nil
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (ncq *NotificationClientQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := ncq.querySpec()
|
||||
_spec.Node.Columns = ncq.ctx.Fields
|
||||
if len(ncq.ctx.Fields) > 0 {
|
||||
_spec.Unique = ncq.ctx.Unique != nil && *ncq.ctx.Unique
|
||||
}
|
||||
return sqlgraph.CountNodes(ctx, ncq.driver, _spec)
|
||||
}
|
||||
|
||||
func (ncq *NotificationClientQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := sqlgraph.NewQuerySpec(notificationclient.Table, notificationclient.Columns, sqlgraph.NewFieldSpec(notificationclient.FieldID, field.TypeInt))
|
||||
_spec.From = ncq.sql
|
||||
if unique := ncq.ctx.Unique; unique != nil {
|
||||
_spec.Unique = *unique
|
||||
} else if ncq.path != nil {
|
||||
_spec.Unique = true
|
||||
}
|
||||
if fields := ncq.ctx.Fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, notificationclient.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != notificationclient.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := ncq.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit := ncq.ctx.Limit; limit != nil {
|
||||
_spec.Limit = *limit
|
||||
}
|
||||
if offset := ncq.ctx.Offset; offset != nil {
|
||||
_spec.Offset = *offset
|
||||
}
|
||||
if ps := ncq.order; len(ps) > 0 {
|
||||
_spec.Order = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
return _spec
|
||||
}
|
||||
|
||||
func (ncq *NotificationClientQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(ncq.driver.Dialect())
|
||||
t1 := builder.Table(notificationclient.Table)
|
||||
columns := ncq.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = notificationclient.Columns
|
||||
}
|
||||
selector := builder.Select(t1.Columns(columns...)...).From(t1)
|
||||
if ncq.sql != nil {
|
||||
selector = ncq.sql
|
||||
selector.Select(selector.Columns(columns...)...)
|
||||
}
|
||||
if ncq.ctx.Unique != nil && *ncq.ctx.Unique {
|
||||
selector.Distinct()
|
||||
}
|
||||
for _, p := range ncq.predicates {
|
||||
p(selector)
|
||||
}
|
||||
for _, p := range ncq.order {
|
||||
p(selector)
|
||||
}
|
||||
if offset := ncq.ctx.Offset; offset != nil {
|
||||
// limit is mandatory for offset clause. We start
|
||||
// with default value, and override it below if needed.
|
||||
selector.Offset(*offset).Limit(math.MaxInt32)
|
||||
}
|
||||
if limit := ncq.ctx.Limit; limit != nil {
|
||||
selector.Limit(*limit)
|
||||
}
|
||||
return selector
|
||||
}
|
||||
|
||||
// NotificationClientGroupBy is the group-by builder for NotificationClient entities.
|
||||
type NotificationClientGroupBy struct {
|
||||
selector
|
||||
build *NotificationClientQuery
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (ncgb *NotificationClientGroupBy) Aggregate(fns ...AggregateFunc) *NotificationClientGroupBy {
|
||||
ncgb.fns = append(ncgb.fns, fns...)
|
||||
return ncgb
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (ncgb *NotificationClientGroupBy) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, ncgb.build.ctx, "GroupBy")
|
||||
if err := ncgb.build.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*NotificationClientQuery, *NotificationClientGroupBy](ctx, ncgb.build, ncgb, ncgb.build.inters, v)
|
||||
}
|
||||
|
||||
func (ncgb *NotificationClientGroupBy) sqlScan(ctx context.Context, root *NotificationClientQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx).Select()
|
||||
aggregation := make([]string, 0, len(ncgb.fns))
|
||||
for _, fn := range ncgb.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(*ncgb.flds)+len(ncgb.fns))
|
||||
for _, f := range *ncgb.flds {
|
||||
columns = append(columns, selector.C(f))
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
selector.GroupBy(selector.Columns(*ncgb.flds...)...)
|
||||
if err := selector.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := ncgb.build.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
// NotificationClientSelect is the builder for selecting fields of NotificationClient entities.
|
||||
type NotificationClientSelect struct {
|
||||
*NotificationClientQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (ncs *NotificationClientSelect) Aggregate(fns ...AggregateFunc) *NotificationClientSelect {
|
||||
ncs.fns = append(ncs.fns, fns...)
|
||||
return ncs
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (ncs *NotificationClientSelect) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, ncs.ctx, "Select")
|
||||
if err := ncs.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*NotificationClientQuery, *NotificationClientSelect](ctx, ncs.NotificationClientQuery, ncs, ncs.inters, v)
|
||||
}
|
||||
|
||||
func (ncs *NotificationClientSelect) sqlScan(ctx context.Context, root *NotificationClientQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx)
|
||||
aggregation := make([]string, 0, len(ncs.fns))
|
||||
for _, fn := range ncs.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
switch n := len(*ncs.selector.flds); {
|
||||
case n == 0 && len(aggregation) > 0:
|
||||
selector.Select(aggregation...)
|
||||
case n != 0 && len(aggregation) > 0:
|
||||
selector.AppendSelect(aggregation...)
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := ncs.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
311
ent/notificationclient_update.go
Normal file
311
ent/notificationclient_update.go
Normal file
@@ -0,0 +1,311 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"polaris/ent/notificationclient"
|
||||
"polaris/ent/predicate"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// NotificationClientUpdate is the builder for updating NotificationClient entities.
|
||||
type NotificationClientUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *NotificationClientMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the NotificationClientUpdate builder.
|
||||
func (ncu *NotificationClientUpdate) Where(ps ...predicate.NotificationClient) *NotificationClientUpdate {
|
||||
ncu.mutation.Where(ps...)
|
||||
return ncu
|
||||
}
|
||||
|
||||
// SetName sets the "name" field.
|
||||
func (ncu *NotificationClientUpdate) SetName(s string) *NotificationClientUpdate {
|
||||
ncu.mutation.SetName(s)
|
||||
return ncu
|
||||
}
|
||||
|
||||
// SetNillableName sets the "name" field if the given value is not nil.
|
||||
func (ncu *NotificationClientUpdate) SetNillableName(s *string) *NotificationClientUpdate {
|
||||
if s != nil {
|
||||
ncu.SetName(*s)
|
||||
}
|
||||
return ncu
|
||||
}
|
||||
|
||||
// SetService sets the "service" field.
|
||||
func (ncu *NotificationClientUpdate) SetService(s string) *NotificationClientUpdate {
|
||||
ncu.mutation.SetService(s)
|
||||
return ncu
|
||||
}
|
||||
|
||||
// SetNillableService sets the "service" field if the given value is not nil.
|
||||
func (ncu *NotificationClientUpdate) SetNillableService(s *string) *NotificationClientUpdate {
|
||||
if s != nil {
|
||||
ncu.SetService(*s)
|
||||
}
|
||||
return ncu
|
||||
}
|
||||
|
||||
// SetSettings sets the "settings" field.
|
||||
func (ncu *NotificationClientUpdate) SetSettings(s string) *NotificationClientUpdate {
|
||||
ncu.mutation.SetSettings(s)
|
||||
return ncu
|
||||
}
|
||||
|
||||
// SetNillableSettings sets the "settings" field if the given value is not nil.
|
||||
func (ncu *NotificationClientUpdate) SetNillableSettings(s *string) *NotificationClientUpdate {
|
||||
if s != nil {
|
||||
ncu.SetSettings(*s)
|
||||
}
|
||||
return ncu
|
||||
}
|
||||
|
||||
// SetEnabled sets the "enabled" field.
|
||||
func (ncu *NotificationClientUpdate) SetEnabled(b bool) *NotificationClientUpdate {
|
||||
ncu.mutation.SetEnabled(b)
|
||||
return ncu
|
||||
}
|
||||
|
||||
// SetNillableEnabled sets the "enabled" field if the given value is not nil.
|
||||
func (ncu *NotificationClientUpdate) SetNillableEnabled(b *bool) *NotificationClientUpdate {
|
||||
if b != nil {
|
||||
ncu.SetEnabled(*b)
|
||||
}
|
||||
return ncu
|
||||
}
|
||||
|
||||
// Mutation returns the NotificationClientMutation object of the builder.
|
||||
func (ncu *NotificationClientUpdate) Mutation() *NotificationClientMutation {
|
||||
return ncu.mutation
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (ncu *NotificationClientUpdate) Save(ctx context.Context) (int, error) {
|
||||
return withHooks(ctx, ncu.sqlSave, ncu.mutation, ncu.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (ncu *NotificationClientUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := ncu.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (ncu *NotificationClientUpdate) Exec(ctx context.Context) error {
|
||||
_, err := ncu.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (ncu *NotificationClientUpdate) ExecX(ctx context.Context) {
|
||||
if err := ncu.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (ncu *NotificationClientUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
_spec := sqlgraph.NewUpdateSpec(notificationclient.Table, notificationclient.Columns, sqlgraph.NewFieldSpec(notificationclient.FieldID, field.TypeInt))
|
||||
if ps := ncu.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := ncu.mutation.Name(); ok {
|
||||
_spec.SetField(notificationclient.FieldName, field.TypeString, value)
|
||||
}
|
||||
if value, ok := ncu.mutation.Service(); ok {
|
||||
_spec.SetField(notificationclient.FieldService, field.TypeString, value)
|
||||
}
|
||||
if value, ok := ncu.mutation.Settings(); ok {
|
||||
_spec.SetField(notificationclient.FieldSettings, field.TypeString, value)
|
||||
}
|
||||
if value, ok := ncu.mutation.Enabled(); ok {
|
||||
_spec.SetField(notificationclient.FieldEnabled, field.TypeBool, value)
|
||||
}
|
||||
if n, err = sqlgraph.UpdateNodes(ctx, ncu.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{notificationclient.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
ncu.mutation.done = true
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// NotificationClientUpdateOne is the builder for updating a single NotificationClient entity.
|
||||
type NotificationClientUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *NotificationClientMutation
|
||||
}
|
||||
|
||||
// SetName sets the "name" field.
|
||||
func (ncuo *NotificationClientUpdateOne) SetName(s string) *NotificationClientUpdateOne {
|
||||
ncuo.mutation.SetName(s)
|
||||
return ncuo
|
||||
}
|
||||
|
||||
// SetNillableName sets the "name" field if the given value is not nil.
|
||||
func (ncuo *NotificationClientUpdateOne) SetNillableName(s *string) *NotificationClientUpdateOne {
|
||||
if s != nil {
|
||||
ncuo.SetName(*s)
|
||||
}
|
||||
return ncuo
|
||||
}
|
||||
|
||||
// SetService sets the "service" field.
|
||||
func (ncuo *NotificationClientUpdateOne) SetService(s string) *NotificationClientUpdateOne {
|
||||
ncuo.mutation.SetService(s)
|
||||
return ncuo
|
||||
}
|
||||
|
||||
// SetNillableService sets the "service" field if the given value is not nil.
|
||||
func (ncuo *NotificationClientUpdateOne) SetNillableService(s *string) *NotificationClientUpdateOne {
|
||||
if s != nil {
|
||||
ncuo.SetService(*s)
|
||||
}
|
||||
return ncuo
|
||||
}
|
||||
|
||||
// SetSettings sets the "settings" field.
|
||||
func (ncuo *NotificationClientUpdateOne) SetSettings(s string) *NotificationClientUpdateOne {
|
||||
ncuo.mutation.SetSettings(s)
|
||||
return ncuo
|
||||
}
|
||||
|
||||
// SetNillableSettings sets the "settings" field if the given value is not nil.
|
||||
func (ncuo *NotificationClientUpdateOne) SetNillableSettings(s *string) *NotificationClientUpdateOne {
|
||||
if s != nil {
|
||||
ncuo.SetSettings(*s)
|
||||
}
|
||||
return ncuo
|
||||
}
|
||||
|
||||
// SetEnabled sets the "enabled" field.
|
||||
func (ncuo *NotificationClientUpdateOne) SetEnabled(b bool) *NotificationClientUpdateOne {
|
||||
ncuo.mutation.SetEnabled(b)
|
||||
return ncuo
|
||||
}
|
||||
|
||||
// SetNillableEnabled sets the "enabled" field if the given value is not nil.
|
||||
func (ncuo *NotificationClientUpdateOne) SetNillableEnabled(b *bool) *NotificationClientUpdateOne {
|
||||
if b != nil {
|
||||
ncuo.SetEnabled(*b)
|
||||
}
|
||||
return ncuo
|
||||
}
|
||||
|
||||
// Mutation returns the NotificationClientMutation object of the builder.
|
||||
func (ncuo *NotificationClientUpdateOne) Mutation() *NotificationClientMutation {
|
||||
return ncuo.mutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the NotificationClientUpdate builder.
|
||||
func (ncuo *NotificationClientUpdateOne) Where(ps ...predicate.NotificationClient) *NotificationClientUpdateOne {
|
||||
ncuo.mutation.Where(ps...)
|
||||
return ncuo
|
||||
}
|
||||
|
||||
// Select allows selecting one or more fields (columns) of the returned entity.
|
||||
// The default is selecting all fields defined in the entity schema.
|
||||
func (ncuo *NotificationClientUpdateOne) Select(field string, fields ...string) *NotificationClientUpdateOne {
|
||||
ncuo.fields = append([]string{field}, fields...)
|
||||
return ncuo
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated NotificationClient entity.
|
||||
func (ncuo *NotificationClientUpdateOne) Save(ctx context.Context) (*NotificationClient, error) {
|
||||
return withHooks(ctx, ncuo.sqlSave, ncuo.mutation, ncuo.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (ncuo *NotificationClientUpdateOne) SaveX(ctx context.Context) *NotificationClient {
|
||||
node, err := ncuo.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (ncuo *NotificationClientUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := ncuo.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (ncuo *NotificationClientUpdateOne) ExecX(ctx context.Context) {
|
||||
if err := ncuo.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (ncuo *NotificationClientUpdateOne) sqlSave(ctx context.Context) (_node *NotificationClient, err error) {
|
||||
_spec := sqlgraph.NewUpdateSpec(notificationclient.Table, notificationclient.Columns, sqlgraph.NewFieldSpec(notificationclient.FieldID, field.TypeInt))
|
||||
id, ok := ncuo.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "NotificationClient.id" for update`)}
|
||||
}
|
||||
_spec.Node.ID.Value = id
|
||||
if fields := ncuo.fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, notificationclient.FieldID)
|
||||
for _, f := range fields {
|
||||
if !notificationclient.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != notificationclient.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := ncuo.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := ncuo.mutation.Name(); ok {
|
||||
_spec.SetField(notificationclient.FieldName, field.TypeString, value)
|
||||
}
|
||||
if value, ok := ncuo.mutation.Service(); ok {
|
||||
_spec.SetField(notificationclient.FieldService, field.TypeString, value)
|
||||
}
|
||||
if value, ok := ncuo.mutation.Settings(); ok {
|
||||
_spec.SetField(notificationclient.FieldSettings, field.TypeString, value)
|
||||
}
|
||||
if value, ok := ncuo.mutation.Enabled(); ok {
|
||||
_spec.SetField(notificationclient.FieldEnabled, field.TypeBool, value)
|
||||
}
|
||||
_node = &NotificationClient{config: ncuo.config}
|
||||
_spec.Assign = _node.assignValues
|
||||
_spec.ScanValues = _node.scanValues
|
||||
if err = sqlgraph.UpdateNode(ctx, ncuo.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{notificationclient.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
ncuo.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
@@ -21,6 +21,9 @@ type Indexers func(*sql.Selector)
|
||||
// Media is the predicate function for media builders.
|
||||
type Media func(*sql.Selector)
|
||||
|
||||
// NotificationClient is the predicate function for notificationclient builders.
|
||||
type NotificationClient func(*sql.Selector)
|
||||
|
||||
// Settings is the predicate function for settings builders.
|
||||
type Settings func(*sql.Selector)
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"polaris/ent/history"
|
||||
"polaris/ent/indexers"
|
||||
"polaris/ent/media"
|
||||
"polaris/ent/notificationclient"
|
||||
"polaris/ent/schema"
|
||||
"polaris/ent/storage"
|
||||
"time"
|
||||
@@ -74,14 +75,20 @@ func init() {
|
||||
mediaDescDownloadHistoryEpisodes := mediaFields[12].Descriptor()
|
||||
// media.DefaultDownloadHistoryEpisodes holds the default value on creation for the download_history_episodes field.
|
||||
media.DefaultDownloadHistoryEpisodes = mediaDescDownloadHistoryEpisodes.Default.(bool)
|
||||
notificationclientFields := schema.NotificationClient{}.Fields()
|
||||
_ = notificationclientFields
|
||||
// notificationclientDescEnabled is the schema descriptor for enabled field.
|
||||
notificationclientDescEnabled := notificationclientFields[3].Descriptor()
|
||||
// notificationclient.DefaultEnabled holds the default value on creation for the enabled field.
|
||||
notificationclient.DefaultEnabled = notificationclientDescEnabled.Default.(bool)
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ func (History) Fields() []ent.Field {
|
||||
field.Time("date"),
|
||||
field.String("target_dir"),
|
||||
field.Int("size").Default(0),
|
||||
field.Int("download_client_id").Optional(),
|
||||
field.Enum("status").Values("running", "success", "fail", "uploading"),
|
||||
field.String("saved").Optional(),
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ func (Media) Fields() []ent.Field {
|
||||
field.String("overview"),
|
||||
field.Time("created_at").Default(time.Now()),
|
||||
field.String("air_date").Default(""),
|
||||
field.Enum("resolution").Values("720p", "1080p", "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"),
|
||||
|
||||
26
ent/schema/notificationclient.go
Normal file
26
ent/schema/notificationclient.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// NotificationClient holds the schema definition for the NotificationClient entity.
|
||||
type NotificationClient struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
// Fields of the NotificationClient.
|
||||
func (NotificationClient) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.String("name"),
|
||||
field.String("service"),
|
||||
field.String("settings"),
|
||||
field.Bool("enabled").Default(true),
|
||||
}
|
||||
}
|
||||
|
||||
// Edges of the NotificationClient.
|
||||
func (NotificationClient) Edges() []ent.Edge {
|
||||
return nil
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -22,6 +22,8 @@ type Tx struct {
|
||||
Indexers *IndexersClient
|
||||
// Media is the client for interacting with the Media builders.
|
||||
Media *MediaClient
|
||||
// NotificationClient is the client for interacting with the NotificationClient builders.
|
||||
NotificationClient *NotificationClientClient
|
||||
// Settings is the client for interacting with the Settings builders.
|
||||
Settings *SettingsClient
|
||||
// Storage is the client for interacting with the Storage builders.
|
||||
@@ -162,6 +164,7 @@ func (tx *Tx) init() {
|
||||
tx.History = NewHistoryClient(tx.config)
|
||||
tx.Indexers = NewIndexersClient(tx.config)
|
||||
tx.Media = NewMediaClient(tx.config)
|
||||
tx.NotificationClient = NewNotificationClientClient(tx.config)
|
||||
tx.Settings = NewSettingsClient(tx.config)
|
||||
tx.Storage = NewStorageClient(tx.config)
|
||||
}
|
||||
|
||||
32
go.mod
32
go.mod
@@ -8,14 +8,28 @@ require (
|
||||
github.com/mattn/go-sqlite3 v1.14.16
|
||||
github.com/robfig/cron v1.2.0
|
||||
go.uber.org/zap v1.27.0
|
||||
golang.org/x/net v0.25.0
|
||||
golang.org/x/net v0.27.0
|
||||
)
|
||||
|
||||
require github.com/adrg/strutil v0.3.1
|
||||
require (
|
||||
github.com/adrg/strutil v0.3.1
|
||||
github.com/gin-contrib/zap v1.1.3
|
||||
github.com/nikoksr/notify v1.0.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/gin-contrib/zap v1.1.3 // indirect
|
||||
github.com/BurntSushi/toml v1.4.0 // indirect
|
||||
github.com/blinkbean/dingtalk v1.1.3 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible // indirect
|
||||
github.com/gregdel/pushover v1.3.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/stretchr/objx v0.5.2 // indirect
|
||||
github.com/stretchr/testify v1.9.0 // indirect
|
||||
github.com/technoweenie/multipartstreamer v1.0.1 // indirect
|
||||
golang.org/x/sync v0.7.0 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -36,7 +50,7 @@ require (
|
||||
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/google/go-cmp v0.6.0 // indirect
|
||||
github.com/google/uuid v1.4.0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/hashicorp/hcl/v2 v2.13.0 // indirect
|
||||
@@ -60,12 +74,12 @@ require (
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
github.com/zclconf/go-cty v1.8.0 // indirect
|
||||
golang.org/x/arch v0.8.0 // indirect
|
||||
golang.org/x/crypto v0.23.0
|
||||
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842
|
||||
golang.org/x/mod v0.17.0 // indirect
|
||||
golang.org/x/sys v0.21.0
|
||||
golang.org/x/crypto v0.25.0
|
||||
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56
|
||||
golang.org/x/mod v0.19.0 // indirect
|
||||
golang.org/x/sys v0.22.0
|
||||
golang.org/x/text v0.16.0 // indirect
|
||||
google.golang.org/protobuf v1.34.1 // indirect
|
||||
google.golang.org/protobuf v1.34.2 // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
49
go.sum
49
go.sum
@@ -2,6 +2,8 @@ ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43 h1:GwdJbXydHCYPedeeLt4x/lrl
|
||||
ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43/go.mod h1:uj3pm+hUTVN/X5yfdBexHlZv+1Xu5u5ZbZx7+CDavNU=
|
||||
entgo.io/ent v0.13.1 h1:uD8QwN1h6SNphdCCzmkMN3feSUzNnVvV/WIkHKMbzOE=
|
||||
entgo.io/ent v0.13.1/go.mod h1:qCEmo+biw3ccBn9OyL4ZK5dfpwg++l1Gxwac5B1206A=
|
||||
github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0=
|
||||
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
|
||||
github.com/adrg/strutil v0.3.1 h1:OLvSS7CSJO8lBii4YmBt8jiK9QOtB9CzCzwl4Ic/Fz4=
|
||||
@@ -10,6 +12,8 @@ github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tj
|
||||
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=
|
||||
github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo=
|
||||
github.com/blinkbean/dingtalk v1.1.3 h1:MbidFZYom7DTFHD/YIs+eaI7kRy52kmWE/sy0xjo6E4=
|
||||
github.com/blinkbean/dingtalk v1.1.3/go.mod h1:9BaLuGSBqY3vT5hstValh48DbsKO7vaHaJnG9pXwbto=
|
||||
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
|
||||
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
||||
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
||||
@@ -48,6 +52,8 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
|
||||
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
||||
github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible h1:2cauKuaELYAEARXRkq2LrJ0yDDv1rW7+wrTEdVL3uaU=
|
||||
github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible/go.mod h1:qf9acutJ8cwBUhm1bqgz6Bei9/C/c93FPDljKWwsOgM=
|
||||
github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68=
|
||||
github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
@@ -60,8 +66,10 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4=
|
||||
github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gregdel/pushover v1.3.1 h1:4bMLITOZ15+Zpi6qqoGqOPuVHCwSUvMCgVnN5Xhilfo=
|
||||
github.com/gregdel/pushover v1.3.1/go.mod h1:EcaO66Nn1StkpEm1iKtBTV3d2A16SoMsVER1PthX7to=
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ=
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48=
|
||||
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
|
||||
@@ -108,6 +116,8 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/natefinch/lumberjack v2.0.0+incompatible h1:4QJd3OLAMgj7ph+yZTuX13Ld4UpgHp07nNdFX7mqFfM=
|
||||
github.com/natefinch/lumberjack v2.0.0+incompatible/go.mod h1:Wi9p2TTF5DG5oU+6YfsmYQpsTIOm0B1VNzQg9Mw6nPk=
|
||||
github.com/nikoksr/notify v1.0.0 h1:qe9/6FRsWdxBgQgWcpvQ0sv8LRGJZDpRB4TkL2uNdO8=
|
||||
github.com/nikoksr/notify v1.0.0/go.mod h1:hPaaDt30d6LAA7/5nb0e48Bp/MctDfycCSs8VEgN29I=
|
||||
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
|
||||
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
|
||||
@@ -142,6 +152,7 @@ github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
@@ -153,6 +164,8 @@ github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsT
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/technoweenie/multipartstreamer v1.0.1 h1:XRztA5MXiR1TIRHxH2uNxXxaIkKQDeX7m2XsSOlQEnM=
|
||||
github.com/technoweenie/multipartstreamer v1.0.1/go.mod h1:jNVxdtShOxzAsukZwTSw6MDx5eUJoiEBsSvzDU9uzog=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
||||
@@ -163,8 +176,6 @@ github.com/zclconf/go-cty v1.8.0 h1:s4AvqaeQzJIu3ndv4gVIhplVD0krU+bgrcLSVUnaWuA=
|
||||
github.com/zclconf/go-cty v1.8.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
|
||||
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
|
||||
@@ -173,34 +184,34 @@ golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUu
|
||||
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
|
||||
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM=
|
||||
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc=
|
||||
golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
|
||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/crypto v0.25.0 h1:ypSNr+bnYL2YhwoMt2zPxHFmbAN1KZs/njMG3hxUp30=
|
||||
golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/M=
|
||||
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0LeHDbnYEryqj5Q1ug8=
|
||||
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY=
|
||||
golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8=
|
||||
golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
|
||||
golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys=
|
||||
golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE=
|
||||
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
|
||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws=
|
||||
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
|
||||
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
|
||||
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg=
|
||||
golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI=
|
||||
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
|
||||
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
|
||||
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
|
||||
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
@@ -209,6 +220,8 @@ gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
|
||||
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
@@ -32,7 +32,7 @@ func init() {
|
||||
|
||||
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()
|
||||
|
||||
|
||||
90
pkg/notifier/clients.go
Normal file
90
pkg/notifier/clients.go
Normal file
@@ -0,0 +1,90 @@
|
||||
package notifier
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/nikoksr/notify/service/bark"
|
||||
"github.com/nikoksr/notify/service/dingding"
|
||||
po "github.com/nikoksr/notify/service/pushover"
|
||||
"github.com/nikoksr/notify/service/telegram"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type PushoverConfig struct {
|
||||
UserKey string `json:"user_key"`
|
||||
GroupKey string `json:"group_key"`
|
||||
AppToken string `json:"app_token"`
|
||||
}
|
||||
|
||||
func NewPushoverClient(s string) (NotificationClient, error) {
|
||||
var cfg PushoverConfig
|
||||
if err := json.Unmarshal([]byte(s), &cfg); err != nil {
|
||||
return nil, errors.Wrap(err, "json")
|
||||
}
|
||||
|
||||
c := po.New(cfg.AppToken)
|
||||
if cfg.UserKey != "" {
|
||||
c.AddReceivers(cfg.UserKey)
|
||||
}
|
||||
if cfg.GroupKey != "" {
|
||||
c.AddReceivers(cfg.GroupKey)
|
||||
}
|
||||
|
||||
return &Notifier{service: c}, nil
|
||||
}
|
||||
|
||||
type DingTalkConfig struct {
|
||||
Token string `json:"token"`
|
||||
Secret string `json:"secret"`
|
||||
}
|
||||
|
||||
func NewDingTalkClient(s string) (NotificationClient, error) {
|
||||
var cfg DingTalkConfig
|
||||
if err := json.Unmarshal([]byte(s), &cfg); err != nil {
|
||||
return nil, errors.Wrap(err, "json")
|
||||
}
|
||||
|
||||
svc := dingding.New(&dingding.Config{
|
||||
Token: cfg.Token,
|
||||
Secret: cfg.Secret,
|
||||
})
|
||||
return &Notifier{service: svc}, nil
|
||||
}
|
||||
|
||||
type TelegramConfig struct {
|
||||
Token string `json:"token"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
}
|
||||
|
||||
func NewTelegramClient(s string) (NotificationClient, error) {
|
||||
var cfg TelegramConfig
|
||||
if err := json.Unmarshal([]byte(s), &cfg); err != nil {
|
||||
return nil, errors.Wrap(err, "json")
|
||||
}
|
||||
|
||||
svc, err := telegram.New(cfg.Token)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
svc.AddReceivers(cfg.ChatID)
|
||||
return &Notifier{service: svc}, nil
|
||||
}
|
||||
|
||||
|
||||
type BarkConfig struct {
|
||||
DeviceKey string `json:"device_key"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
func NewbarkClient(s string) (NotificationClient, error) {
|
||||
var cfg BarkConfig
|
||||
if err := json.Unmarshal([]byte(s), &cfg); err != nil {
|
||||
return nil, errors.Wrap(err, "json")
|
||||
}
|
||||
url := cfg.URL
|
||||
if url == "" {
|
||||
url = bark.DefaultServerURL
|
||||
}
|
||||
b := bark.NewWithServers(cfg.DeviceKey, url)
|
||||
return &Notifier{service: b}, nil
|
||||
}
|
||||
37
pkg/notifier/doc.go
Normal file
37
pkg/notifier/doc.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package notifier
|
||||
|
||||
import (
|
||||
"context"
|
||||
"polaris/pkg/utils"
|
||||
|
||||
"github.com/nikoksr/notify"
|
||||
)
|
||||
|
||||
type HandlerFunc func(string) (NotificationClient, error)
|
||||
|
||||
type NotificationClient interface {
|
||||
SendMsg(msg string) error
|
||||
}
|
||||
|
||||
type Notifier struct {
|
||||
service notify.Notifier
|
||||
}
|
||||
|
||||
func (s *Notifier) SendMsg(msg string) error {
|
||||
notifier := notify.New()
|
||||
notifier.UseServices(s.service)
|
||||
return notifier.Send(context.TODO(), "Polaris", msg)
|
||||
}
|
||||
|
||||
var handler = utils.Map[string, HandlerFunc]{}
|
||||
|
||||
func init() {
|
||||
handler.Store("pushover", NewPushoverClient)
|
||||
handler.Store("dingtalk", NewDingTalkClient)
|
||||
handler.Store("telegram", NewTelegramClient)
|
||||
handler.Store("bark", NewbarkClient)
|
||||
}
|
||||
|
||||
func Gethandler(name string) (HandlerFunc, bool) {
|
||||
return handler.Load(name)
|
||||
}
|
||||
8
pkg/notifier/message/message.go
Normal file
8
pkg/notifier/message/message.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package message
|
||||
|
||||
const (
|
||||
BeginDownload = "开始下载:%v"
|
||||
DownloadComplete = "下载完成:%v"
|
||||
ProcessingComplete = "文件处理完成:%v"
|
||||
ProcessingFailed = "文件处理失败:%v"
|
||||
)
|
||||
@@ -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), 0655)
|
||||
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, 0655)
|
||||
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, 0666); 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,24 @@ 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 {
|
||||
return os.WriteFile(filepath.Join(l.dir, name), 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)
|
||||
}
|
||||
|
||||
31
pkg/utils/map.go
Normal file
31
pkg/utils/map.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package utils
|
||||
|
||||
import "sync"
|
||||
|
||||
type Map[K comparable, V any] struct {
|
||||
m sync.Map
|
||||
}
|
||||
|
||||
func (m *Map[K, V]) Delete(key K) { m.m.Delete(key) }
|
||||
func (m *Map[K, V]) Load(key K) (value V, ok bool) {
|
||||
v, ok := m.m.Load(key)
|
||||
if !ok {
|
||||
return value, ok
|
||||
}
|
||||
return v.(V), ok
|
||||
}
|
||||
func (m *Map[K, V]) LoadAndDelete(key K) (value V, loaded bool) {
|
||||
v, loaded := m.m.LoadAndDelete(key)
|
||||
if !loaded {
|
||||
return value, loaded
|
||||
}
|
||||
return v.(V), loaded
|
||||
}
|
||||
func (m *Map[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) {
|
||||
a, loaded := m.m.LoadOrStore(key, value)
|
||||
return a.(V), loaded
|
||||
}
|
||||
func (m *Map[K, V]) Range(f func(key K, value V) bool) {
|
||||
m.m.Range(func(key, value any) bool { return f(key.(K), value.(V)) })
|
||||
}
|
||||
func (m *Map[K, V]) Store(key K, value V) { m.m.Store(key, value) }
|
||||
@@ -102,7 +102,7 @@ type TorrentInfo struct {
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"polaris/db"
|
||||
"polaris/log"
|
||||
"polaris/pkg/utils"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -23,16 +22,15 @@ func (s *Server) authModdleware(c *gin.Context) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
auth := c.GetHeader("Authorization")
|
||||
if auth == "" {
|
||||
log.Infof("token is not present, abort")
|
||||
token, err := c.Cookie("token")
|
||||
if err != nil {
|
||||
log.Errorf("token error: %v", err)
|
||||
c.AbortWithStatus(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
auth = strings.TrimPrefix(auth, "Bearer ")
|
||||
|
||||
//log.Debugf("current token: %v", auth)
|
||||
token, err := jwt.ParseWithClaims(auth, &jwt.RegisteredClaims{}, func(t *jwt.Token) (interface{}, error) {
|
||||
tokenParsed, err := jwt.ParseWithClaims(token, &jwt.RegisteredClaims{}, func(t *jwt.Token) (interface{}, error) {
|
||||
return []byte(s.jwtSerect), nil
|
||||
})
|
||||
if err != nil {
|
||||
@@ -40,15 +38,15 @@ func (s *Server) authModdleware(c *gin.Context) {
|
||||
c.AbortWithStatus(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if !token.Valid {
|
||||
log.Errorf("token is not valid: %v", auth)
|
||||
if !tokenParsed.Valid {
|
||||
log.Errorf("token is not valid: %v", token)
|
||||
c.AbortWithStatus(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
claim := token.Claims.(*jwt.RegisteredClaims)
|
||||
claim := tokenParsed.Claims.(*jwt.RegisteredClaims)
|
||||
|
||||
if time.Until(claim.ExpiresAt.Time) <= 0 {
|
||||
log.Infof("token is no longer valid: %s", auth)
|
||||
log.Infof("token is no longer valid: %s", token)
|
||||
c.AbortWithStatus(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
@@ -61,7 +59,6 @@ type LoginIn struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
|
||||
func (s *Server) Login(c *gin.Context) (interface{}, error) {
|
||||
var in LoginIn
|
||||
|
||||
@@ -93,11 +90,23 @@ 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
|
||||
}
|
||||
|
||||
func (s *Server) Logout(c *gin.Context) (interface{}, error) {
|
||||
if !s.isAuthEnabled() {
|
||||
return nil, errors.New( "auth is not enabled")
|
||||
}
|
||||
|
||||
c.SetSameSite(http.SameSiteNoneMode)
|
||||
c.SetCookie("token", "", -1, "/", "", true, false)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type EnableAuthIn struct {
|
||||
Enable bool `json:"enable"`
|
||||
User string `json:"user"`
|
||||
|
||||
@@ -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,
|
||||
|
||||
62
server/integration.go
Normal file
62
server/integration.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"polaris/db"
|
||||
"polaris/ent/media"
|
||||
"polaris/log"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func (s *Server) writePlexmatch(seriesId int, episodeId int, targetDir, name string) error {
|
||||
|
||||
if !s.plexmatchEnabled() {
|
||||
return nil
|
||||
}
|
||||
series, err := s.db.GetMedia(seriesId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if series.MediaType != media.MediaTypeTv {
|
||||
return nil
|
||||
}
|
||||
st, err := s.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
|
||||
log.Warnf(".plexmatch file not found, create new one: %s", series.NameEn)
|
||||
if err := st.WriteFile(filepath.Join(series.TargetDir, ".plexmatch"),
|
||||
[]byte(fmt.Sprintf("tmdbid: %d\n",series.TmdbID))); err != nil {
|
||||
return errors.Wrap(err, "series plexmatch")
|
||||
}
|
||||
}
|
||||
|
||||
//season plexmatch file
|
||||
ep, err := s.db.GetEpisodeByID(episodeId)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "query episode")
|
||||
}
|
||||
buff := bytes.Buffer{}
|
||||
seasonPlex := filepath.Join(targetDir, ".plexmatch")
|
||||
data, err := st.ReadFile(seasonPlex)
|
||||
if err != nil {
|
||||
log.Infof("read season plexmatch: %v", err)
|
||||
} else {
|
||||
buff.Write(data)
|
||||
}
|
||||
buff.WriteString(fmt.Sprintf("\nep: %d: %s\n", ep.EpisodeNumber, name))
|
||||
log.Infof("write season plexmatch file content: %s", buff.String())
|
||||
return st.WriteFile(seasonPlex, buff.Bytes())
|
||||
}
|
||||
|
||||
func (s *Server) plexmatchEnabled() bool {
|
||||
return s.db.GetSetting(db.SettingPlexMatchEnabled) == "true"
|
||||
}
|
||||
75
server/notify_client.go
Normal file
75
server/notify_client.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"polaris/ent"
|
||||
"polaris/log"
|
||||
"polaris/pkg/notifier"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func (s *Server) GetAllNotificationClients(c *gin.Context) (interface{}, error) {
|
||||
return s.db.GetAllNotificationClients()
|
||||
}
|
||||
|
||||
func (s *Server) GetNotificationClient(c *gin.Context) (interface{}, error) {
|
||||
ids := c.Param("id")
|
||||
id, err := strconv.Atoi(ids)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "convert")
|
||||
}
|
||||
return s.db.GetNotificationClient(id)
|
||||
}
|
||||
|
||||
func (s *Server) DeleteNotificationClient(c *gin.Context) (interface{}, error) {
|
||||
ids := c.Param("id")
|
||||
id, err := strconv.Atoi(ids)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "convert")
|
||||
}
|
||||
return nil, s.db.DeleteNotificationClient(id)
|
||||
}
|
||||
|
||||
func (s *Server) AddNotificationClient(c *gin.Context) (interface{}, error) {
|
||||
var in ent.NotificationClient
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
return nil, errors.Wrap(err, "json")
|
||||
}
|
||||
|
||||
err := s.db.AddNotificationClient(in.Name, in.Service, in.Settings, in.Enabled)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "save db")
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"polaris/ent/history"
|
||||
"polaris/ent/media"
|
||||
"polaris/log"
|
||||
"polaris/pkg/notifier/message"
|
||||
"polaris/pkg/torznab"
|
||||
"polaris/pkg/utils"
|
||||
"polaris/server/core"
|
||||
@@ -29,7 +30,7 @@ func (s *Server) searchAndDownloadSeasonPackage(seriesId, seasonNum int) (*strin
|
||||
}
|
||||
|
||||
func (s *Server) downloadSeasonPackage(r1 torznab.Result, seriesId, seasonNum int) (*string, error) {
|
||||
trc, err := s.getDownloadClient()
|
||||
trc, dlClient, err := s.getDownloadClient()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "connect transmission")
|
||||
}
|
||||
@@ -53,13 +54,14 @@ func (s *Server) downloadSeasonPackage(r1 torznab.Result, seriesId, seasonNum in
|
||||
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(),
|
||||
MediaID: seriesId,
|
||||
EpisodeID: 0,
|
||||
SourceTitle: r1.Name,
|
||||
TargetDir: dir,
|
||||
Status: history.StatusRunning,
|
||||
Size: r1.Size,
|
||||
Saved: torrent.Save(),
|
||||
DownloadClientID: dlClient.ID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "save record")
|
||||
@@ -67,12 +69,14 @@ func (s *Server) downloadSeasonPackage(r1 torznab.Result, seriesId, seasonNum in
|
||||
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()
|
||||
trc, dlc, err := s.getDownloadClient()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "connect transmission")
|
||||
}
|
||||
@@ -98,13 +102,14 @@ func (s *Server) downloadEpisodeTorrent(r1 torznab.Result, seriesId, seasonNum,
|
||||
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(),
|
||||
MediaID: ep.MediaID,
|
||||
EpisodeID: ep.ID,
|
||||
SourceTitle: r1.Name,
|
||||
TargetDir: dir,
|
||||
Status: history.StatusRunning,
|
||||
Size: r1.Size,
|
||||
Saved: torrent.Save(),
|
||||
DownloadClientID: dlc.ID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "save record")
|
||||
@@ -112,6 +117,7 @@ func (s *Server) downloadEpisodeTorrent(r1 torznab.Result, seriesId, seasonNum,
|
||||
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
|
||||
@@ -259,42 +265,46 @@ func (s *Server) DownloadTorrent(c *gin.Context) (interface{}, error) {
|
||||
}
|
||||
res := torznab.Result{Name: name, Link: in.Link, Size: in.Size}
|
||||
return s.downloadEpisodeTorrent(res, in.MediaID, in.Season, in.Episode)
|
||||
}
|
||||
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(),
|
||||
})
|
||||
} else {
|
||||
//movie
|
||||
trc, dlc, err := s.getDownloadClient()
|
||||
if err != nil {
|
||||
log.Errorf("save history error: %v", err)
|
||||
return nil, errors.Wrap(err, "connect transmission")
|
||||
}
|
||||
|
||||
s.tasks[history.ID] = &Task{Torrent: torrent}
|
||||
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: m.TargetDir,
|
||||
Status: history.StatusRunning,
|
||||
Size: in.Size,
|
||||
Saved: torrent.Save(),
|
||||
DownloadClientID: dlc.ID,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorf("save history error: %v", err)
|
||||
}
|
||||
|
||||
s.db.SetEpisodeStatus(ep.ID, episode.StatusDownloading)
|
||||
}()
|
||||
s.tasks[history.ID] = &Task{Torrent: torrent}
|
||||
|
||||
log.Infof("success add %s to download task", media.NameEn)
|
||||
return media.NameEn, nil
|
||||
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
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
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/storage"
|
||||
"polaris/pkg/notifier/message"
|
||||
"polaris/pkg/utils"
|
||||
"polaris/server/core"
|
||||
"time"
|
||||
@@ -19,11 +19,11 @@ import (
|
||||
|
||||
func (s *Server) scheduler() {
|
||||
s.mustAddCron("@every 1m", s.checkTasks)
|
||||
s.mustAddCron("@every 1h", func() {
|
||||
s.mustAddCron("0 0 * * * *", func() {
|
||||
s.downloadTvSeries()
|
||||
s.downloadMovie()
|
||||
})
|
||||
s.mustAddCron("@every 12h", s.checkAllSeriesNewSeason)
|
||||
s.mustAddCron("0 0 */12 * * *", s.checkAllSeriesNewSeason)
|
||||
s.cron.Start()
|
||||
}
|
||||
|
||||
@@ -39,11 +39,13 @@ func (s *Server) checkTasks() {
|
||||
for id, t := range s.tasks {
|
||||
if !t.Exists() {
|
||||
log.Infof("task no longer exists: %v", id)
|
||||
delete(s.tasks, 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)
|
||||
@@ -61,13 +63,19 @@ func (s *Server) moveCompletedTask(id int) (err1 error) {
|
||||
return nil
|
||||
}
|
||||
s.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 := s.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() {
|
||||
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)
|
||||
@@ -76,17 +84,12 @@ func (s *Server) moveCompletedTask(id int) (err1 error) {
|
||||
} else {
|
||||
s.db.SetSeasonAllEpisodeStatus(r.MediaID, seasonNum, episode.StatusMissing)
|
||||
}
|
||||
|
||||
} 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.ProcessingFailed, err))
|
||||
if downloadclient.RemoveFailedDownloads {
|
||||
log.Debugf("task failed, remove failed torrent and files related")
|
||||
delete(s.tasks, r.ID)
|
||||
torrent.Remove()
|
||||
}
|
||||
|
||||
torrent.Remove()
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -96,49 +99,39 @@ func (s *Server) moveCompletedTask(id int) (err1 error) {
|
||||
}
|
||||
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
|
||||
|
||||
stImpl, err := s.getStorage(st.ID, series.MediaType)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
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")
|
||||
|
||||
}
|
||||
//如果种子是路径,则会把路径展开,只移动文件,类似 move dir/* dir2/, 如果种子是文件,则会直接移动文件,类似 move file dir/
|
||||
if err := stImpl.Copy(filepath.Join(s.db.GetDownloadDir(), torrentName), r.TargetDir); err != nil {
|
||||
return errors.Wrap(err, "move file")
|
||||
}
|
||||
|
||||
// .plexmatch file
|
||||
if err := s.writePlexmatch(r.MediaID, r.EpisodeID, r.TargetDir, torrentName); err != nil {
|
||||
log.Errorf("create .plexmatch file error: %v", err)
|
||||
}
|
||||
|
||||
|
||||
s.db.SetHistoryStatus(r.ID, history.StatusSuccess)
|
||||
if r.EpisodeID != 0 {
|
||||
s.db.SetEpisodeStatus(r.EpisodeID, episode.StatusDownloaded)
|
||||
} 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")
|
||||
s.db.SetSeasonAllEpisodeStatus(r.MediaID, seasonNum, episode.StatusDownloaded)
|
||||
}
|
||||
s.sendMsg(fmt.Sprintf(message.ProcessingComplete, torrentName))
|
||||
|
||||
}
|
||||
//判断是否需要删除本地文件
|
||||
if downloadclient.RemoveCompletedDownloads {
|
||||
log.Debugf("download complete,remove torrent and files related")
|
||||
delete(s.tasks, r.ID)
|
||||
torrent.Remove()
|
||||
}
|
||||
|
||||
log.Infof("move downloaded files to target dir success, file: %v, target dir: %v", torrent.Name(), r.TargetDir)
|
||||
|
||||
log.Infof("move downloaded files to target dir success, file: %v, target dir: %v", torrentName, r.TargetDir)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -147,29 +140,12 @@ func (s *Server) checkDownloadedSeriesFiles(m *ent.Media) error {
|
||||
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
|
||||
var storageImpl, err = s.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)
|
||||
@@ -229,9 +205,9 @@ func (s *Server) downloadTvSeries() {
|
||||
}
|
||||
if series.CreatedAt.Sub(t) > 24*time.Hour { //剧集在加入watchlist之前,不去下载
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if ep.Status != episode.StatusMissing { //已经下载的不去下载
|
||||
continue
|
||||
}
|
||||
@@ -252,7 +228,7 @@ func (s *Server) downloadMovie() {
|
||||
allSeries := s.db.GetMediaWatchlist(media.MediaTypeMovie)
|
||||
|
||||
for _, series := range allSeries {
|
||||
detail := s.db.GetMediaDetails(series.ID)
|
||||
detail := s.db.GetMediaDetails(series.ID)
|
||||
if len(detail.Episodes) == 0 {
|
||||
log.Errorf("no related dummy episode: %v", detail.NameEn)
|
||||
continue
|
||||
@@ -269,7 +245,7 @@ func (s *Server) downloadMovie() {
|
||||
}
|
||||
|
||||
func (s *Server) downloadMovieSingleEpisode(ep *ent.Episode) error {
|
||||
trc, err := s.getDownloadClient()
|
||||
trc, dlc, err := s.getDownloadClient()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "connect transmission")
|
||||
}
|
||||
@@ -288,13 +264,14 @@ func (s *Server) downloadMovieSingleEpisode(ep *ent.Episode) error {
|
||||
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(),
|
||||
MediaID: ep.MediaID,
|
||||
EpisodeID: ep.ID,
|
||||
SourceTitle: r1.Name,
|
||||
TargetDir: "./",
|
||||
Status: history.StatusRunning,
|
||||
Size: r1.Size,
|
||||
Saved: torrent.Save(),
|
||||
DownloadClientID: dlc.ID,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorf("save history error: %v", err)
|
||||
@@ -317,7 +294,7 @@ func (s *Server) checkAllSeriesNewSeason() {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) checkSeiesNewSeason(media *ent.Media) error{
|
||||
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")
|
||||
@@ -327,29 +304,29 @@ func (s *Server) checkSeiesNewSeason(media *ent.Media) error{
|
||||
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,
|
||||
MediaID: media.ID,
|
||||
SeasonNumber: ep.SeasonNumber,
|
||||
EpisodeNumber: ep.EpisodeNumber,
|
||||
Title: ep.Name,
|
||||
Overview: ep.Overview,
|
||||
AirDate: ep.AirDate,
|
||||
Status: episode.StatusMissing,
|
||||
Title: ep.Name,
|
||||
Overview: ep.Overview,
|
||||
AirDate: ep.AirDate,
|
||||
Status: episode.StatusMissing,
|
||||
}
|
||||
s.db.SaveEposideDetail2(episode)
|
||||
}
|
||||
} else {//update 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)
|
||||
s.db.UpdateEpiode2(epDb.ID, ep.Name, ep.Overview, ep.AirDate)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"polaris/pkg/tmdb"
|
||||
"polaris/pkg/transmission"
|
||||
"polaris/ui"
|
||||
"time"
|
||||
|
||||
ginzap "github.com/gin-contrib/zap"
|
||||
|
||||
@@ -48,7 +47,7 @@ func (s *Server) Serve() error {
|
||||
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
|
||||
@@ -63,6 +62,7 @@ func (s *Server) Serve() error {
|
||||
|
||||
setting := api.Group("/setting")
|
||||
{
|
||||
setting.GET("/logout", HttpHandler(s.Logout))
|
||||
setting.POST("/general", HttpHandler(s.SetSetting))
|
||||
setting.GET("/general", HttpHandler(s.GetSetting))
|
||||
setting.POST("/auth", HttpHandler(s.EnableAuth))
|
||||
@@ -91,8 +91,8 @@ 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))
|
||||
}
|
||||
indexer := api.Group("/indexer")
|
||||
{
|
||||
@@ -114,6 +114,13 @@ func (s *Server) Serve() error {
|
||||
storage.POST("/", HttpHandler(s.AddStorage))
|
||||
storage.DELETE("/:id", HttpHandler(s.DeleteStorage))
|
||||
}
|
||||
notifier := api.Group("/notifier")
|
||||
{
|
||||
notifier.GET("/all", HttpHandler(s.GetAllNotificationClients))
|
||||
notifier.GET("/id/:id", HttpHandler(s.GetNotificationClient))
|
||||
notifier.DELETE("/id/:id", HttpHandler(s.DeleteNotificationClient))
|
||||
notifier.POST("/add", HttpHandler(s.AddNotificationClient))
|
||||
}
|
||||
|
||||
s.language = s.db.GetLanguage()
|
||||
return s.r.Run(":8080")
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"polaris/db"
|
||||
"polaris/ent"
|
||||
"polaris/log"
|
||||
"polaris/pkg/transmission"
|
||||
"strconv"
|
||||
@@ -14,10 +15,11 @@ 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"`
|
||||
}
|
||||
|
||||
func (s *Server) SetSetting(c *gin.Context) (interface{}, error) {
|
||||
@@ -45,6 +47,13 @@ func (s *Server) SetSetting(c *gin.Context) (interface{}, error) {
|
||||
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
s.setProxy(in.Proxy)
|
||||
return nil, nil
|
||||
}
|
||||
@@ -72,11 +81,13 @@ 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)
|
||||
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",
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -119,7 +130,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 +138,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 {
|
||||
|
||||
@@ -3,9 +3,10 @@ package server
|
||||
import (
|
||||
"fmt"
|
||||
"polaris/db"
|
||||
"polaris/ent/media"
|
||||
storage1 "polaris/ent/storage"
|
||||
"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,82 @@ 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)
|
||||
}
|
||||
}
|
||||
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 s.language == db.LanguageCN {
|
||||
en, err := s.MustTMDB().GetMovieDetails(id, db.LanguageEN)
|
||||
if err != nil {
|
||||
log.Errorf("get en movie detail error: %v", err)
|
||||
} else {
|
||||
name = fmt.Sprintf("%s %s", d1.Title, en.Title)
|
||||
}
|
||||
}
|
||||
|
||||
year := strings.Split(d1.ReleaseDate, "-")[0]
|
||||
if year != "" {
|
||||
name = fmt.Sprintf("%s (%s)", name, year)
|
||||
}
|
||||
log.Infof("tv series of tmdb id %v suggestting name is %v", id, name)
|
||||
return gin.H{"name": name}, nil
|
||||
}
|
||||
|
||||
func (s *Server) getStorage(storageId int, mediaType media.MediaType) (storage.Storage, error) {
|
||||
st := s.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")
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ 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
|
||||
}
|
||||
|
||||
@@ -69,6 +69,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")
|
||||
}
|
||||
@@ -112,16 +113,16 @@ func (s *Server) AddTv2Watchlist(c *gin.Context) (interface{}, error) {
|
||||
}
|
||||
}
|
||||
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,
|
||||
TmdbID: int(detail.ID),
|
||||
MediaType: media.MediaTypeTv,
|
||||
NameCn: nameCn,
|
||||
NameEn: nameEn,
|
||||
OriginalName: detail.OriginalName,
|
||||
Overview: detail.Overview,
|
||||
AirDate: detail.FirstAirDate,
|
||||
Resolution: media.Resolution(in.Resolution),
|
||||
StorageID: in.StorageID,
|
||||
TargetDir: in.Folder,
|
||||
DownloadHistoryEpisodes: in.DownloadHistoryEpisodes,
|
||||
}, epIds)
|
||||
if err != nil {
|
||||
@@ -187,7 +188,7 @@ func (s *Server) AddMovie2Watchlist(c *gin.Context) (interface{}, error) {
|
||||
AirDate: detail.ReleaseDate,
|
||||
Resolution: media.Resolution(in.Resolution),
|
||||
StorageID: in.StorageID,
|
||||
TargetDir: "./",
|
||||
TargetDir: in.Folder,
|
||||
}, []int{epid})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "add to list")
|
||||
@@ -244,7 +245,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,26 +259,38 @@ 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 {
|
||||
monitored := false
|
||||
if ep.SeasonNumber == 0 {
|
||||
continue
|
||||
}
|
||||
t, err := time.Parse("2006-01-02", ep.AirDate)
|
||||
if err != nil { //airdate not exist
|
||||
ms.Status = "monitoring"
|
||||
if item.DownloadHistoryEpisodes {
|
||||
monitored = true
|
||||
} else {
|
||||
if item.CreatedAt.Sub(t) > 24*time.Hour { //剧集在加入watchlist之前,不去下载
|
||||
continue
|
||||
}
|
||||
if ep.Status == episode.StatusMissing {
|
||||
ms.Status = "monitoring"
|
||||
t, err := time.Parse("2006-01-02", ep.AirDate)
|
||||
if err != nil { //airdate not exist, maybe airdate not set yet
|
||||
monitored = true
|
||||
} else {
|
||||
if item.CreatedAt.Sub(t) > 24*time.Hour { //剧集在加入watchlist之前,不去下载
|
||||
continue
|
||||
}
|
||||
monitored = true
|
||||
}
|
||||
}
|
||||
if monitored {
|
||||
ms.MonitoredNum++
|
||||
if ep.Status == episode.StatusDownloaded {
|
||||
ms.DownloadedNum++
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
res[i] = ms
|
||||
}
|
||||
@@ -289,14 +303,15 @@ func (s *Server) GetMovieWatchlist(c *gin.Context) (interface{}, error) {
|
||||
for i, item := range list {
|
||||
var ms = MediaWithStatus{
|
||||
Media: item,
|
||||
Status: "monitoring",
|
||||
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 +319,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 +331,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) {
|
||||
|
||||
@@ -2,8 +2,8 @@ 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/utils.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
|
||||
class ActivityPage extends ConsumerStatefulWidget {
|
||||
const ActivityPage({super.key});
|
||||
@@ -68,7 +68,7 @@ class _ActivityPageState extends ConsumerState<ActivityPage>
|
||||
DataColumn(label: Text("名称")),
|
||||
DataColumn(label: Text("开始时间")),
|
||||
DataColumn(label: Text("状态")),
|
||||
DataColumn(label: Text("操作"))
|
||||
DataColumn(label: Text("操作"))
|
||||
],
|
||||
source: ActivityDataSource(
|
||||
activities: activities,
|
||||
@@ -85,11 +85,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);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
131
ui/lib/main.dart
131
ui/lib/main.dart
@@ -2,7 +2,6 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_adaptive_scaffold/flutter_adaptive_scaffold.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:ui/activity.dart';
|
||||
import 'package:ui/login_page.dart';
|
||||
import 'package:ui/movie_watchlist.dart';
|
||||
@@ -26,6 +25,20 @@ class MyApp extends ConsumerStatefulWidget {
|
||||
}
|
||||
}
|
||||
|
||||
CustomTransitionPage buildPageWithDefaultTransition<T>({
|
||||
required BuildContext context,
|
||||
required GoRouterState state,
|
||||
required Widget child,
|
||||
}) {
|
||||
return CustomTransitionPage<T>(
|
||||
transitionDuration: Duration.zero,
|
||||
reverseTransitionDuration: Duration.zero,
|
||||
key: state.pageKey,
|
||||
child: child,
|
||||
transitionsBuilder: (context, animation, secondaryAnimation, child) => child,
|
||||
);
|
||||
}
|
||||
|
||||
class _MyAppState extends ConsumerState<MyApp> {
|
||||
// This widget is the root of your application.
|
||||
@override
|
||||
@@ -46,38 +59,51 @@ class _MyAppState extends ConsumerState<MyApp> {
|
||||
),
|
||||
GoRoute(
|
||||
path: WelcomePage.routeTv,
|
||||
builder: (context, state) => const WelcomePage(),
|
||||
),
|
||||
GoRoute(
|
||||
path: TvDetailsPage.route,
|
||||
builder: (context, state) =>
|
||||
TvDetailsPage(seriesId: state.pathParameters['id']!),
|
||||
pageBuilder: (context, state) => buildPageWithDefaultTransition(
|
||||
context: context, state: state, child: const WelcomePage()),
|
||||
),
|
||||
GoRoute(
|
||||
path: WelcomePage.routeMoivie,
|
||||
builder: (context, state) => const WelcomePage(),
|
||||
pageBuilder: (context, state) => buildPageWithDefaultTransition(
|
||||
context: context, state: state, child: const WelcomePage()),
|
||||
),
|
||||
GoRoute(
|
||||
path: TvDetailsPage.route,
|
||||
pageBuilder: (context, state) => buildPageWithDefaultTransition(
|
||||
context: context,
|
||||
state: state,
|
||||
child: TvDetailsPage(seriesId: state.pathParameters['id']!)),
|
||||
),
|
||||
GoRoute(
|
||||
path: MovieDetailsPage.route,
|
||||
builder: (context, state) =>
|
||||
MovieDetailsPage(id: state.pathParameters['id']!),
|
||||
pageBuilder: (context, state) => buildPageWithDefaultTransition(
|
||||
context: context,
|
||||
state: state,
|
||||
child: MovieDetailsPage(id: state.pathParameters['id']!)),
|
||||
),
|
||||
GoRoute(
|
||||
path: SearchPage.route,
|
||||
builder: (context, state) =>
|
||||
SearchPage(query: state.uri.queryParameters["query"]),
|
||||
pageBuilder: (context, state) => buildPageWithDefaultTransition(
|
||||
context: context,
|
||||
state: state,
|
||||
child: SearchPage(query: state.uri.queryParameters["query"])),
|
||||
),
|
||||
GoRoute(
|
||||
path: SystemSettingsPage.route,
|
||||
builder: (context, state) => const SystemSettingsPage(),
|
||||
pageBuilder: (context, state) => buildPageWithDefaultTransition(
|
||||
context: context,
|
||||
state: state,
|
||||
child: const SystemSettingsPage()),
|
||||
),
|
||||
GoRoute(
|
||||
path: ActivityPage.route,
|
||||
builder: (context, state) => const ActivityPage(),
|
||||
pageBuilder: (context, state) => buildPageWithDefaultTransition(
|
||||
context: context, state: state, child: const ActivityPage()),
|
||||
),
|
||||
GoRoute(
|
||||
path: SystemPage.route,
|
||||
builder: (context, state) => const SystemPage(),
|
||||
pageBuilder: (context, state) => buildPageWithDefaultTransition(
|
||||
context: context, state: state, child: const SystemPage()),
|
||||
)
|
||||
],
|
||||
);
|
||||
@@ -95,7 +121,7 @@ class _MyAppState extends ConsumerState<MyApp> {
|
||||
|
||||
return ProviderScope(
|
||||
child: MaterialApp.router(
|
||||
title: 'Polaris 影视追踪',
|
||||
title: 'Polaris 影视追踪下载',
|
||||
theme: ThemeData(
|
||||
fontFamily: "NotoSansSC",
|
||||
colorScheme: ColorScheme.fromSeed(
|
||||
@@ -177,41 +203,29 @@ class _MainSkeletonState extends State<MainSkeleton> {
|
||||
(BuildContext context, SearchController controller) {
|
||||
return [Text("dadada")];
|
||||
}),
|
||||
FutureBuilder(
|
||||
future: APIs.isLoggedIn(),
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.hasData && snapshot.data == true) {
|
||||
return MenuAnchor(
|
||||
menuChildren: [
|
||||
MenuItemButton(
|
||||
leadingIcon: const Icon(Icons.exit_to_app),
|
||||
child: const Text("登出"),
|
||||
onPressed: () async {
|
||||
final SharedPreferences prefs =
|
||||
await SharedPreferences.getInstance();
|
||||
await prefs.remove('token');
|
||||
if (context.mounted) {
|
||||
context.go(LoginScreen.route);
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
builder: (context, controller, child) {
|
||||
return TextButton(
|
||||
onPressed: () {
|
||||
if (controller.isOpen) {
|
||||
controller.close();
|
||||
} else {
|
||||
controller.open();
|
||||
}
|
||||
},
|
||||
child: const Icon(Icons.account_circle),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
return Container();
|
||||
})
|
||||
MenuAnchor(
|
||||
menuChildren: [
|
||||
MenuItemButton(
|
||||
leadingIcon: const Icon(Icons.exit_to_app),
|
||||
child: const Text("登出"),
|
||||
onPressed: () async {
|
||||
await APIs.logout();
|
||||
},
|
||||
),
|
||||
],
|
||||
builder: (context, controller, child) {
|
||||
return TextButton(
|
||||
onPressed: () {
|
||||
if (controller.isOpen) {
|
||||
controller.close();
|
||||
} else {
|
||||
controller.open();
|
||||
}
|
||||
},
|
||||
child: const Icon(Icons.account_circle),
|
||||
);
|
||||
},
|
||||
)
|
||||
],
|
||||
),
|
||||
useDrawer: false,
|
||||
@@ -234,23 +248,28 @@ 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: '系统',
|
||||
),
|
||||
],
|
||||
|
||||
@@ -1,13 +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/activity.dart';
|
||||
import 'package:ui/providers/series_details.dart';
|
||||
import 'package:ui/providers/settings.dart';
|
||||
import 'package:ui/utils.dart';
|
||||
import 'package:ui/welcome_page.dart';
|
||||
import 'package:ui/widgets/detail_card.dart';
|
||||
import 'package:ui/widgets/utils.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
|
||||
class MovieDetailsPage extends ConsumerStatefulWidget {
|
||||
static const route = "/movie/:id";
|
||||
@@ -30,106 +28,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.fitWidth,
|
||||
opacity: 0.5,
|
||||
image: NetworkImage(
|
||||
"${APIs.imagesUrl}/${details.id}/backdrop.jpg",
|
||||
headers: APIs.authHeaders))),
|
||||
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,
|
||||
headers: APIs.authHeaders,
|
||||
),
|
||||
),
|
||||
),
|
||||
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,
|
||||
)
|
||||
@@ -158,7 +62,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
|
||||
@@ -252,17 +156,18 @@ class _NestedTabBarState extends ConsumerState<NestedTabBar>
|
||||
DataCell(IconButton(
|
||||
icon: const Icon(Icons.download),
|
||||
onPressed: () {
|
||||
ref
|
||||
final f = 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"));
|
||||
.then((v) => showSnakeBar(
|
||||
"开始下载:${torrent.name}"));
|
||||
// .onError((error, trace) =>
|
||||
// Utils.showSnakeBar("操作失败: $error"));
|
||||
showLoadingWithFuture(f);
|
||||
},
|
||||
))
|
||||
]);
|
||||
|
||||
@@ -2,8 +2,6 @@ import 'package:dio/dio.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:quiver/strings.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:ui/providers/server_response.dart';
|
||||
|
||||
class APIs {
|
||||
@@ -16,7 +14,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";
|
||||
@@ -26,6 +25,7 @@ class APIs {
|
||||
static final delDownloadClientUrl = "$_baseUrl/api/v1/downloader/del/";
|
||||
static final storageUrl = "$_baseUrl/api/v1/storage/";
|
||||
static final loginUrl = "$_baseUrl/api/login";
|
||||
static final logoutUrl = "$_baseUrl/api/v1/setting/logout";
|
||||
static final loginSettingUrl = "$_baseUrl/api/v1/setting/auth";
|
||||
static final activityUrl = "$_baseUrl/api/v1/activity/";
|
||||
static final activityMediaUrl = "$_baseUrl/api/v1/activity/media/";
|
||||
@@ -34,6 +34,10 @@ class APIs {
|
||||
static final logFilesUrl = "$_baseUrl/api/v1/setting/logfiles";
|
||||
static final aboutUrl = "$_baseUrl/api/v1/setting/about";
|
||||
|
||||
static final notifierAllUrl = "$_baseUrl/api/v1/notifier/all";
|
||||
static final notifierDeleteUrl = "$_baseUrl/api/v1/notifier/id/";
|
||||
static final notifierAddUrl = "$_baseUrl/api/v1/notifier/add/";
|
||||
|
||||
static final tmdbImgBaseUrl = "$_baseUrl/api/v1/posters";
|
||||
|
||||
static const tmdbApiKey = "tmdb_api_key";
|
||||
@@ -49,53 +53,20 @@ class APIs {
|
||||
return "http://127.0.0.1:8080";
|
||||
}
|
||||
|
||||
static Dio? gDio;
|
||||
static Map<String, String> authHeaders = {};
|
||||
|
||||
static Future<bool> isLoggedIn() async {
|
||||
return isNotBlank(await getToken());
|
||||
}
|
||||
|
||||
static Future<String> getToken() async {
|
||||
var token = authHeaders["Authorization"];
|
||||
if (isBlank(token)) {
|
||||
final SharedPreferences prefs = await SharedPreferences.getInstance();
|
||||
var t = prefs.getString("token");
|
||||
if (isNotBlank(t)) {
|
||||
authHeaders["Authorization"] = t!;
|
||||
token = t;
|
||||
}
|
||||
}
|
||||
return token ?? "";
|
||||
}
|
||||
|
||||
static Future<Dio> getDio() async {
|
||||
if (gDio != null) {
|
||||
return gDio!;
|
||||
}
|
||||
var token = await getToken();
|
||||
|
||||
static Dio getDio() {
|
||||
var dio = Dio();
|
||||
dio.interceptors.add(InterceptorsWrapper(
|
||||
onRequest: (options, handler) {
|
||||
options.headers['Authorization'] = token;
|
||||
return handler.next(options);
|
||||
},
|
||||
onError: (error, handler) {
|
||||
if (error.response?.statusCode != null &&
|
||||
error.response?.statusCode! == 403) {
|
||||
final context = navigatorKey.currentContext;
|
||||
if (context != null) {
|
||||
context.go('/login');
|
||||
gDio = null;
|
||||
}
|
||||
}
|
||||
return handler.next(error);
|
||||
},
|
||||
));
|
||||
if (isNotBlank(token)) {
|
||||
gDio = dio;
|
||||
}
|
||||
return dio;
|
||||
}
|
||||
|
||||
@@ -108,9 +79,19 @@ class APIs {
|
||||
if (sp.code != 0) {
|
||||
throw sp.message;
|
||||
}
|
||||
final SharedPreferences prefs = await SharedPreferences.getInstance();
|
||||
var t = sp.data["token"];
|
||||
authHeaders["Authorization"] = "Bearer $t";
|
||||
prefs.setString("token", "Bearer $t");
|
||||
}
|
||||
|
||||
static Future<void> logout() async {
|
||||
var resp = await getDio().get(APIs.logoutUrl);
|
||||
|
||||
var sp = ServerResponse.fromJson(resp.data);
|
||||
|
||||
if (sp.code != 0) {
|
||||
throw sp.message;
|
||||
}
|
||||
final context = navigatorKey.currentContext;
|
||||
if (context != null) {
|
||||
context.go('/login');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
75
ui/lib/providers/notifier.dart
Normal file
75
ui/lib/providers/notifier.dart
Normal file
@@ -0,0 +1,75 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:ui/providers/APIs.dart';
|
||||
import 'package:ui/providers/server_response.dart';
|
||||
|
||||
final notifiersDataProvider =
|
||||
AsyncNotifierProvider.autoDispose<NotifiersData, List<NotifierData>>(
|
||||
NotifiersData.new);
|
||||
|
||||
class NotifierData {
|
||||
int? id;
|
||||
String? name;
|
||||
String? service;
|
||||
Map<String, dynamic>? settings;
|
||||
bool? enabled;
|
||||
|
||||
NotifierData({this.id, this.name, this.service, this.enabled, this.settings});
|
||||
|
||||
factory NotifierData.fromJson(Map<String, dynamic> json) {
|
||||
return NotifierData(
|
||||
id: json["id"],
|
||||
name: json["name"],
|
||||
service: json["service"],
|
||||
enabled: json["enabled"] ?? true,
|
||||
settings: json["settings"]);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
final data = <String, dynamic>{};
|
||||
data["name"] = name;
|
||||
data["service"] = service;
|
||||
data["enabled"] = enabled;
|
||||
|
||||
data["settings"] = jsonEncode(settings);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
class NotifiersData extends AutoDisposeAsyncNotifier<List<NotifierData>> {
|
||||
@override
|
||||
FutureOr<List<NotifierData>> build() async {
|
||||
final dio = APIs.getDio();
|
||||
final resp = await dio.get(APIs.notifierAllUrl);
|
||||
final sp = ServerResponse.fromJson(resp.data);
|
||||
if (sp.code != 0) {
|
||||
throw sp.message;
|
||||
}
|
||||
|
||||
return sp.data == null
|
||||
? List.empty()
|
||||
: (sp.data as List).map((e) => NotifierData.fromJson(e)).toList();
|
||||
}
|
||||
|
||||
Future<void> delete(int id) async {
|
||||
final dio = APIs.getDio();
|
||||
final resp = await dio.delete(APIs.notifierDeleteUrl + id.toString());
|
||||
final sp = ServerResponse.fromJson(resp.data);
|
||||
if (sp.code != 0) {
|
||||
throw sp.message;
|
||||
}
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
|
||||
Future<void> add(NotifierData n) async {
|
||||
final dio = APIs.getDio();
|
||||
final resp = await dio.post(APIs.notifierAddUrl, data: n.toJson());
|
||||
final sp = ServerResponse.fromJson(resp.data);
|
||||
if (sp.code != 0) {
|
||||
throw sp.message;
|
||||
}
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import 'dart:async';
|
||||
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);
|
||||
@@ -61,6 +62,10 @@ class SeriesDetails {
|
||||
String? resolution;
|
||||
int? storageId;
|
||||
String? airDate;
|
||||
String? mediaType;
|
||||
Storage? storage;
|
||||
String? targetDir;
|
||||
bool? downloadHistoryEpisodes;
|
||||
|
||||
SeriesDetails(
|
||||
{this.id,
|
||||
@@ -73,7 +78,11 @@ class SeriesDetails {
|
||||
this.resolution,
|
||||
this.storageId,
|
||||
this.airDate,
|
||||
this.episodes});
|
||||
this.episodes,
|
||||
this.mediaType,
|
||||
this.targetDir,
|
||||
this.storage,
|
||||
this.downloadHistoryEpisodes});
|
||||
|
||||
SeriesDetails.fromJson(Map<String, dynamic> json) {
|
||||
id = json['id'];
|
||||
@@ -86,6 +95,10 @@ 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) {
|
||||
@@ -146,14 +159,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),
|
||||
|
||||
@@ -51,16 +51,22 @@ class GeneralSetting {
|
||||
String? downloadDIr;
|
||||
String? logLevel;
|
||||
String? proxy;
|
||||
bool? enablePlexmatch;
|
||||
|
||||
GeneralSetting(
|
||||
{this.tmdbApiKey, this.downloadDIr, this.logLevel, this.proxy});
|
||||
{this.tmdbApiKey,
|
||||
this.downloadDIr,
|
||||
this.logLevel,
|
||||
this.proxy,
|
||||
this.enablePlexmatch});
|
||||
|
||||
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"],
|
||||
enablePlexmatch: json["enable_plexmatch"] ?? false);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
@@ -69,6 +75,7 @@ class GeneralSetting {
|
||||
data['download_dir'] = downloadDIr;
|
||||
data["log_level"] = logLevel;
|
||||
data["proxy"] = proxy;
|
||||
data["enable_plexmatch"] = enablePlexmatch;
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -193,7 +200,8 @@ class DownloadClient {
|
||||
String? url;
|
||||
String? user;
|
||||
String? password;
|
||||
|
||||
bool? removeCompletedDownloads;
|
||||
bool? removeFailedDownloads;
|
||||
DownloadClient(
|
||||
{this.id,
|
||||
this.enable,
|
||||
@@ -201,7 +209,9 @@ class DownloadClient {
|
||||
this.implementation,
|
||||
this.url,
|
||||
this.user,
|
||||
this.password});
|
||||
this.password,
|
||||
this.removeCompletedDownloads,
|
||||
this.removeFailedDownloads});
|
||||
|
||||
DownloadClient.fromJson(Map<String, dynamic> json) {
|
||||
id = json['id'];
|
||||
@@ -211,6 +221,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 +234,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 +283,8 @@ class Storage {
|
||||
this.id,
|
||||
this.name,
|
||||
this.implementation,
|
||||
this.tvPath,
|
||||
this.moviePath,
|
||||
this.settings,
|
||||
this.isDefault,
|
||||
});
|
||||
@@ -276,6 +292,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 +302,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 +312,8 @@ class Storage {
|
||||
"id": id,
|
||||
"name": name,
|
||||
"implementation": implementation,
|
||||
"tv_path": tvPath,
|
||||
"movie_path": moviePath,
|
||||
"settings": settings,
|
||||
"default": isDefault,
|
||||
};
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:dio/dio.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 +18,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;
|
||||
@@ -92,7 +100,7 @@ class SearchPageData
|
||||
"storage_id": storageId,
|
||||
"resolution": resolution,
|
||||
"folder": folder,
|
||||
"download_history_episodes":downloadHistoryEpisodes
|
||||
"download_history_episodes": downloadHistoryEpisodes
|
||||
});
|
||||
var sp = ServerResponse.fromJson(resp.data);
|
||||
if (sp.code != 0) {
|
||||
@@ -147,22 +155,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 +185,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 +251,3 @@ class SearchResult {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_form_builder/flutter_form_builder.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/utils.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
import 'package:ui/widgets/utils.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
|
||||
class SearchPage extends ConsumerStatefulWidget {
|
||||
const SearchPage({super.key, this.query});
|
||||
@@ -29,6 +31,17 @@ class _SearchPageState extends ConsumerState<SearchPage> {
|
||||
|
||||
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(
|
||||
@@ -50,7 +63,6 @@ class _SearchPageState extends ConsumerState<SearchPage> {
|
||||
child: Image.network(
|
||||
"${APIs.tmdbImgBaseUrl}${item.posterPath}",
|
||||
fit: BoxFit.contain,
|
||||
headers: APIs.authHeaders,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -137,121 +149,122 @@ class _SearchPageState extends ConsumerState<SearchPage> {
|
||||
}
|
||||
|
||||
Future<void> _showSubmitDialog(BuildContext context, SearchResult item) {
|
||||
final _formKey = GlobalKey<FormBuilderState>();
|
||||
|
||||
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 name = ref.watch(suggestNameDataProvider(
|
||||
(id: item.id!, mediaType: item.mediaType!)));
|
||||
|
||||
var pathController = TextEditingController();
|
||||
return AlertDialog(
|
||||
title: Text('添加剧集: ${item.name}'),
|
||||
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)),
|
||||
),
|
||||
);
|
||||
}();
|
||||
child: FormBuilder(
|
||||
key: _formKey,
|
||||
initialValue: const {
|
||||
"resolution": "1080p",
|
||||
"storage": null,
|
||||
"folder": "",
|
||||
"history_episodes": false,
|
||||
},
|
||||
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) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
FormBuilderDropdown(
|
||||
onChanged: (v) {
|
||||
setState(
|
||||
() {
|
||||
storageSelected = v!;
|
||||
},
|
||||
error: (error, stackTrace) =>
|
||||
Text("$error"),
|
||||
loading: () =>
|
||||
const MyProgressIndicator(
|
||||
size: 20,
|
||||
),
|
||||
)
|
||||
: Text(""),
|
||||
item.mediaType == "tv"
|
||||
? SizedBox(
|
||||
width: 250,
|
||||
child: CheckboxListTile(
|
||||
);
|
||||
},
|
||||
name: "storage",
|
||||
decoration: const InputDecoration(
|
||||
labelText: "存储位置"),
|
||||
items: v
|
||||
.map((s) => DropdownMenuItem(
|
||||
value: s.id,
|
||||
child: Text(s.name!)))
|
||||
.toList(),
|
||||
),
|
||||
name.when(
|
||||
data: (s) {
|
||||
return storageSelected == 0
|
||||
? const Text("")
|
||||
: () {
|
||||
final storage = v
|
||||
.where((e) =>
|
||||
e.id == storageSelected)
|
||||
.first;
|
||||
final path =
|
||||
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,
|
||||
),
|
||||
),
|
||||
item.mediaType == "tv"
|
||||
? SizedBox(
|
||||
width: 250,
|
||||
child: FormBuilderCheckbox(
|
||||
name: "history_episodes",
|
||||
title: const Text("是否下载往期剧集"),
|
||||
value: downloadHistoryEpisodes,
|
||||
onChanged: (v) {
|
||||
setState(() {
|
||||
downloadHistoryEpisodes = v!;
|
||||
});
|
||||
}),
|
||||
)
|
||||
: const SizedBox(),
|
||||
],
|
||||
);
|
||||
});
|
||||
},
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator()),
|
||||
],
|
||||
),
|
||||
)
|
||||
: const SizedBox(),
|
||||
],
|
||||
);
|
||||
});
|
||||
},
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator()),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: <Widget>[
|
||||
@@ -270,32 +283,25 @@ class _SearchPageState extends ConsumerState<SearchPage> {
|
||||
),
|
||||
child: const Text('确定'),
|
||||
onPressed: () async {
|
||||
if (buttonTapped) {
|
||||
return;
|
||||
if (_formKey.currentState!.saveAndValidate()) {
|
||||
final values = _formKey.currentState!.value;
|
||||
//print(values);
|
||||
var f = ref
|
||||
.read(searchPageDataProvider(widget.query ?? "")
|
||||
.notifier)
|
||||
.submit2Watchlist(
|
||||
item.id!,
|
||||
values["storage"],
|
||||
values["resolution"],
|
||||
item.mediaType!,
|
||||
values["folder"],
|
||||
values["history_episodes"] ?? false)
|
||||
.then((v) {
|
||||
Navigator.of(context).pop();
|
||||
showSnakeBar("添加成功:${item.name}");
|
||||
});
|
||||
showLoadingWithFuture(f);
|
||||
}
|
||||
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;
|
||||
});
|
||||
},
|
||||
),
|
||||
],
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_form_builder/flutter_form_builder.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:quiver/strings.dart';
|
||||
import 'package:ui/providers/login.dart';
|
||||
import 'package:ui/providers/settings.dart';
|
||||
import 'package:ui/utils.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
import 'package:form_builder_validators/form_builder_validators.dart';
|
||||
import 'package:ui/settings/auth.dart';
|
||||
import 'package:ui/settings/downloader.dart';
|
||||
import 'package:ui/settings/general.dart';
|
||||
import 'package:ui/settings/indexer.dart';
|
||||
import 'package:ui/settings/notifier.dart';
|
||||
import 'package:ui/settings/storage.dart';
|
||||
|
||||
class SystemSettingsPage extends ConsumerStatefulWidget {
|
||||
static const route = "/settings";
|
||||
@@ -20,615 +18,52 @@ class SystemSettingsPage extends ConsumerStatefulWidget {
|
||||
}
|
||||
|
||||
class _SystemSettingsPageState extends ConsumerState<SystemSettingsPage> {
|
||||
final _formKey = GlobalKey<FormBuilderState>();
|
||||
final _formKey2 = GlobalKey<FormBuilderState>();
|
||||
bool? _enableAuth;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
var settings = ref.watch(settingProvider);
|
||||
|
||||
var tmdbSetting = settings.when(
|
||||
data: (v) {
|
||||
return FormBuilder(
|
||||
key: _formKey, //设置globalKey,用于后面获取FormState
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
initialValue: {
|
||||
"tmdb_api": v.tmdbApiKey,
|
||||
"download_dir": v.downloadDIr,
|
||||
"log_level": v.logLevel,
|
||||
"proxy": v.proxy,
|
||||
},
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
FormBuilderTextField(
|
||||
name: "tmdb_api",
|
||||
decoration: Commons.requiredTextFieldStyle(
|
||||
text: "TMDB Api Key", icon: const Icon(Icons.key)),
|
||||
//
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "download_dir",
|
||||
decoration: Commons.requiredTextFieldStyle(
|
||||
text: "下载路径", icon: const Icon(Icons.folder), helperText: "媒体文件临时下载路径,非最终存储路径"),
|
||||
//
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "proxy",
|
||||
decoration: const InputDecoration(
|
||||
labelText: "代理地址", icon: Icon(Icons.folder), helperText: "后台联网代理地址,留空表示不启用代理"),
|
||||
),
|
||||
SizedBox(
|
||||
width: 300,
|
||||
child: FormBuilderDropdown(
|
||||
name: "log_level",
|
||||
decoration: const InputDecoration(
|
||||
labelText: "日志级别",
|
||||
icon: Icon(Icons.file_present_rounded),
|
||||
),
|
||||
items: const [
|
||||
DropdownMenuItem(value: "debug", child: Text("DEBUG")),
|
||||
DropdownMenuItem(value: "info", child: Text("INFO")),
|
||||
DropdownMenuItem(value: "warn", child: Text("WARN")),
|
||||
DropdownMenuItem(value: "error", child: Text("ERROR")),
|
||||
],
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
),
|
||||
Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(top: 28.0),
|
||||
child: ElevatedButton(
|
||||
child: const Padding(
|
||||
padding: EdgeInsets.all(16.0),
|
||||
child: Text("保存"),
|
||||
),
|
||||
onPressed: () {
|
||||
if (_formKey.currentState!.saveAndValidate()) {
|
||||
var values = _formKey.currentState!.value;
|
||||
var f = ref
|
||||
.read(settingProvider.notifier)
|
||||
.updateSettings(GeneralSetting(
|
||||
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");
|
||||
});
|
||||
}
|
||||
}),
|
||||
),
|
||||
)
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator());
|
||||
|
||||
var indexers = ref.watch(indexersProvider);
|
||||
var indexerSetting = indexers.when(
|
||||
data: (value) => Wrap(
|
||||
children: List.generate(value.length + 1, (i) {
|
||||
if (i < value.length) {
|
||||
var indexer = value[i];
|
||||
return SettingsCard(
|
||||
onTap: () => showIndexerDetails(indexer),
|
||||
child: Text(indexer.name ?? ""));
|
||||
}
|
||||
return SettingsCard(
|
||||
onTap: () => showIndexerDetails(Indexer()),
|
||||
child: const Icon(Icons.add));
|
||||
}),
|
||||
),
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator());
|
||||
|
||||
var downloadClients = ref.watch(dwonloadClientsProvider);
|
||||
var downloadSetting = downloadClients.when(
|
||||
data: (value) => Wrap(
|
||||
children: List.generate(value.length + 1, (i) {
|
||||
if (i < value.length) {
|
||||
var client = value[i];
|
||||
return SettingsCard(
|
||||
onTap: () => showDownloadClientDetails(client),
|
||||
child: Text(client.name ?? ""));
|
||||
}
|
||||
return SettingsCard(
|
||||
onTap: () => showDownloadClientDetails(DownloadClient()),
|
||||
child: const Icon(Icons.add));
|
||||
})),
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator());
|
||||
|
||||
var storageSettingData = ref.watch(storageSettingProvider);
|
||||
var storageSetting = storageSettingData.when(
|
||||
data: (value) => Wrap(
|
||||
children: List.generate(value.length + 1, (i) {
|
||||
if (i < value.length) {
|
||||
var storage = value[i];
|
||||
return SettingsCard(
|
||||
onTap: () => showStorageDetails(storage),
|
||||
child: Text(storage.name ?? ""));
|
||||
}
|
||||
return SettingsCard(
|
||||
onTap: () => showStorageDetails(Storage()),
|
||||
child: const Icon(Icons.add));
|
||||
}),
|
||||
),
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator());
|
||||
|
||||
var authData = ref.watch(authSettingProvider);
|
||||
var authSetting = authData.when(
|
||||
data: (data) {
|
||||
if (_enableAuth == null) {
|
||||
setState(() {
|
||||
_enableAuth = data.enable;
|
||||
});
|
||||
}
|
||||
return FormBuilder(
|
||||
key: _formKey2,
|
||||
initialValue: {
|
||||
"user": data.user,
|
||||
"password": data.password,
|
||||
"enable": data.enable
|
||||
},
|
||||
child: Column(
|
||||
children: [
|
||||
FormBuilderSwitch(
|
||||
name: "enable",
|
||||
title: const Text("开启认证"),
|
||||
onChanged: (v) {
|
||||
setState(() {
|
||||
_enableAuth = v;
|
||||
});
|
||||
}),
|
||||
_enableAuth!
|
||||
? Column(
|
||||
children: [
|
||||
FormBuilderTextField(
|
||||
name: "user",
|
||||
autovalidateMode:
|
||||
AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
decoration: Commons.requiredTextFieldStyle(
|
||||
text: "用户名",
|
||||
icon: const Icon(Icons.account_box),
|
||||
)),
|
||||
FormBuilderTextField(
|
||||
name: "password",
|
||||
obscureText: true,
|
||||
enableSuggestions: false,
|
||||
autocorrect: false,
|
||||
autovalidateMode:
|
||||
AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
decoration: Commons.requiredTextFieldStyle(
|
||||
text: "密码",
|
||||
icon: const Icon(Icons.password),
|
||||
))
|
||||
],
|
||||
)
|
||||
: const Column(),
|
||||
Center(
|
||||
child: ElevatedButton(
|
||||
child: const Text("保存"),
|
||||
onPressed: () {
|
||||
if (_formKey2.currentState!.saveAndValidate()) {
|
||||
var values = _formKey2.currentState!.value;
|
||||
var f = ref
|
||||
.read(authSettingProvider.notifier)
|
||||
.updateAuthSetting(_enableAuth!,
|
||||
values["user"], values["password"]);
|
||||
f.then((v) {
|
||||
Utils.showSnakeBar("更新成功");
|
||||
}).onError((e, s) {
|
||||
Utils.showSnakeBar("更新失败:$e");
|
||||
});
|
||||
}
|
||||
}))
|
||||
],
|
||||
));
|
||||
},
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator());
|
||||
|
||||
return ListView(
|
||||
children: [
|
||||
children: const [
|
||||
ExpansionTile(
|
||||
expandedAlignment: Alignment.centerLeft,
|
||||
childrenPadding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
|
||||
childrenPadding: EdgeInsets.fromLTRB(20, 0, 20, 0),
|
||||
initiallyExpanded: true,
|
||||
title: const Text("常规设置"),
|
||||
children: [tmdbSetting],
|
||||
title: Text("常规"),
|
||||
children: [GeneralSettings()],
|
||||
),
|
||||
ExpansionTile(
|
||||
expandedAlignment: Alignment.centerLeft,
|
||||
childrenPadding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
|
||||
childrenPadding: EdgeInsets.fromLTRB(20, 0, 20, 0),
|
||||
initiallyExpanded: false,
|
||||
title: const Text("索引器设置"),
|
||||
children: [indexerSetting],
|
||||
title: Text("索引器"),
|
||||
children: [IndexerSettings()],
|
||||
),
|
||||
ExpansionTile(
|
||||
expandedAlignment: Alignment.centerLeft,
|
||||
childrenPadding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
|
||||
childrenPadding: EdgeInsets.fromLTRB(20, 0, 20, 0),
|
||||
initiallyExpanded: false,
|
||||
title: const Text("下载器设置"),
|
||||
children: [downloadSetting],
|
||||
title: Text("下载器"),
|
||||
children: [DownloaderSettings()],
|
||||
),
|
||||
ExpansionTile(
|
||||
expandedAlignment: Alignment.centerLeft,
|
||||
childrenPadding: const EdgeInsets.fromLTRB(20, 0, 50, 0),
|
||||
childrenPadding: EdgeInsets.fromLTRB(20, 0, 50, 0),
|
||||
initiallyExpanded: false,
|
||||
title: const Text("存储设置"),
|
||||
children: [storageSetting],
|
||||
title: Text("存储"),
|
||||
children: [StorageSettings()],
|
||||
),
|
||||
ExpansionTile(
|
||||
childrenPadding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
|
||||
expandedAlignment: Alignment.centerLeft,
|
||||
childrenPadding: EdgeInsets.fromLTRB(20, 0, 50, 0),
|
||||
initiallyExpanded: false,
|
||||
title: const Text("认证设置"),
|
||||
children: [authSetting],
|
||||
title: Text("通知客户端"),
|
||||
children: [NotifierSettings()],
|
||||
),
|
||||
ExpansionTile(
|
||||
childrenPadding: EdgeInsets.fromLTRB(20, 0, 20, 0),
|
||||
initiallyExpanded: false,
|
||||
title: Text("认证"),
|
||||
children: [AuthSettings()],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> showIndexerDetails(Indexer indexer) {
|
||||
final _formKey = GlobalKey<FormBuilderState>();
|
||||
|
||||
var body = FormBuilder(
|
||||
key: _formKey,
|
||||
initialValue: {
|
||||
"name": indexer.name,
|
||||
"url": indexer.url,
|
||||
"api_key": indexer.apiKey,
|
||||
"impl": "torznab"
|
||||
},
|
||||
child: Column(
|
||||
children: [
|
||||
FormBuilderDropdown(
|
||||
name: "impl",
|
||||
decoration: const InputDecoration(labelText: "类型"),
|
||||
items: const [
|
||||
DropdownMenuItem(value: "torznab", child: Text("Torznab")),
|
||||
],
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "name",
|
||||
decoration: Commons.requiredTextFieldStyle(text: "名称"),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "url",
|
||||
decoration: Commons.requiredTextFieldStyle(text: "地址"),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "api_key",
|
||||
decoration: Commons.requiredTextFieldStyle(text: "API Key"),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
onDelete() async {
|
||||
return ref.read(indexersProvider.notifier).deleteIndexer(indexer.id!);
|
||||
}
|
||||
|
||||
onSubmit() async {
|
||||
if (_formKey.currentState!.saveAndValidate()) {
|
||||
var values = _formKey.currentState!.value;
|
||||
return ref.read(indexersProvider.notifier).addIndexer(Indexer(
|
||||
name: values["name"],
|
||||
url: values["url"],
|
||||
apiKey: values["api_key"]));
|
||||
} else {
|
||||
throw "validation_error";
|
||||
}
|
||||
}
|
||||
|
||||
return showSettingDialog(
|
||||
"索引器", indexer.id != null, body, onSubmit, onDelete);
|
||||
}
|
||||
|
||||
Future<void> showDownloadClientDetails(DownloadClient client) {
|
||||
final _formKey = GlobalKey<FormBuilderState>();
|
||||
var _enableAuth = isNotBlank(client.user);
|
||||
String selectImpl = "transmission";
|
||||
|
||||
final body =
|
||||
StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
|
||||
return FormBuilder(
|
||||
key: _formKey,
|
||||
initialValue: {
|
||||
"name": client.name,
|
||||
"url": client.url,
|
||||
"user": client.user,
|
||||
"password": client.password,
|
||||
"impl": "transmission"
|
||||
},
|
||||
child: Column(
|
||||
children: [
|
||||
FormBuilderDropdown<String>(
|
||||
name: "impl",
|
||||
decoration: const InputDecoration(labelText: "类型"),
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
selectImpl = value!;
|
||||
});
|
||||
},
|
||||
items: const [
|
||||
DropdownMenuItem(
|
||||
value: "transmission", child: Text("Transmission")),
|
||||
],
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "name",
|
||||
decoration: const InputDecoration(labelText: "名称"),
|
||||
validator: FormBuilderValidators.required(),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction),
|
||||
FormBuilderTextField(
|
||||
name: "url",
|
||||
decoration: const InputDecoration(
|
||||
labelText: "地址", hintText: "http://127.0.0.1:9091"),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
StatefulBuilder(
|
||||
builder: (BuildContext context, StateSetter setState) {
|
||||
return Column(
|
||||
children: [
|
||||
FormBuilderSwitch(
|
||||
name: "auth",
|
||||
title: const Text("需要认证"),
|
||||
initialValue: _enableAuth,
|
||||
onChanged: (v) {
|
||||
setState(() {
|
||||
_enableAuth = v!;
|
||||
});
|
||||
}),
|
||||
_enableAuth
|
||||
? Column(
|
||||
children: [
|
||||
FormBuilderTextField(
|
||||
name: "user",
|
||||
decoration: Commons.requiredTextFieldStyle(
|
||||
text: "用户"),
|
||||
validator: FormBuilderValidators.required(),
|
||||
autovalidateMode:
|
||||
AutovalidateMode.onUserInteraction),
|
||||
FormBuilderTextField(
|
||||
name: "password",
|
||||
decoration: Commons.requiredTextFieldStyle(
|
||||
text: "密码"),
|
||||
validator: FormBuilderValidators.required(),
|
||||
obscureText: true,
|
||||
autovalidateMode:
|
||||
AutovalidateMode.onUserInteraction),
|
||||
],
|
||||
)
|
||||
: Container()
|
||||
],
|
||||
);
|
||||
})
|
||||
],
|
||||
));
|
||||
});
|
||||
onDelete() async {
|
||||
return ref
|
||||
.read(dwonloadClientsProvider.notifier)
|
||||
.deleteDownloadClients(client.id!);
|
||||
}
|
||||
|
||||
onSubmit() async {
|
||||
if (_formKey.currentState!.saveAndValidate()) {
|
||||
var values = _formKey.currentState!.value;
|
||||
return ref.read(dwonloadClientsProvider.notifier).addDownloadClients(
|
||||
DownloadClient(
|
||||
name: values["name"],
|
||||
implementation: values["impl"],
|
||||
url: values["url"],
|
||||
user: _enableAuth ? values["user"] : null,
|
||||
password: _enableAuth ? values["password"] : null));
|
||||
} else {
|
||||
throw "validation_error";
|
||||
}
|
||||
}
|
||||
|
||||
return showSettingDialog(
|
||||
"下载器", client.id != null, body, onSubmit, onDelete);
|
||||
}
|
||||
|
||||
Future<void> showStorageDetails(Storage s) {
|
||||
final _formKey = GlobalKey<FormBuilderState>();
|
||||
|
||||
String selectImpl = s.implementation == null ? "local" : s.implementation!;
|
||||
final widgets =
|
||||
StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
|
||||
return FormBuilder(
|
||||
key: _formKey,
|
||||
autovalidateMode: AutovalidateMode.disabled,
|
||||
initialValue: {
|
||||
"name": s.name,
|
||||
"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"] ?? "" : "",
|
||||
"url": s.settings != null ? s.settings!["url"] ?? "" : "",
|
||||
"movie_path":
|
||||
s.settings != null ? s.settings!["movie_path"] ?? "" : "",
|
||||
"change_file_hash": s.settings != null
|
||||
? s.settings!["change_file_hash"] == "true"
|
||||
? true
|
||||
: false
|
||||
: false,
|
||||
},
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
FormBuilderDropdown<String>(
|
||||
name: "impl",
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
decoration: const InputDecoration(labelText: "类型"),
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
selectImpl = value!;
|
||||
});
|
||||
},
|
||||
items: const [
|
||||
DropdownMenuItem(
|
||||
value: "local",
|
||||
child: Text("本地存储"),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: "webdav",
|
||||
child: Text("webdav"),
|
||||
)
|
||||
],
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "name",
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
initialValue: s.name,
|
||||
decoration: const InputDecoration(labelText: "名称"),
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
selectImpl != "local"
|
||||
? Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
FormBuilderTextField(
|
||||
name: "url",
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
decoration:
|
||||
const InputDecoration(labelText: "Webdav地址"),
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "user",
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
decoration: const InputDecoration(labelText: "用户"),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "password",
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
decoration: const InputDecoration(labelText: "密码"),
|
||||
obscureText: true,
|
||||
),
|
||||
FormBuilderCheckbox(
|
||||
name: "change_file_hash",
|
||||
title: const Text(
|
||||
"上传时更改文件哈希",
|
||||
style: TextStyle(fontSize: 14),
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: Container(),
|
||||
FormBuilderTextField(
|
||||
name: "tv_path",
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
decoration: const InputDecoration(labelText: "电视剧路径"),
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "movie_path",
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
decoration: const InputDecoration(labelText: "电影路径"),
|
||||
validator: FormBuilderValidators.required(),
|
||||
)
|
||||
],
|
||||
));
|
||||
});
|
||||
onSubmit() async {
|
||||
if (_formKey.currentState!.saveAndValidate()) {
|
||||
final values = _formKey.currentState!.value;
|
||||
return ref.read(storageSettingProvider.notifier).addStorage(Storage(
|
||||
name: values["name"],
|
||||
implementation: selectImpl,
|
||||
settings: {
|
||||
"tv_path": values["tv_path"],
|
||||
"movie_path": values["movie_path"],
|
||||
"url": values["url"],
|
||||
"user": values["user"],
|
||||
"password": values["password"],
|
||||
"change_file_hash":
|
||||
(values["change_file_hash"]??false) as bool ? "true" : "false"
|
||||
},
|
||||
));
|
||||
} else {
|
||||
throw "validation_error";
|
||||
}
|
||||
}
|
||||
|
||||
onDelete() async {
|
||||
return ref.read(storageSettingProvider.notifier).deleteStorage(s.id!);
|
||||
}
|
||||
|
||||
return showSettingDialog('存储', s.id != null, widgets, onSubmit, onDelete);
|
||||
}
|
||||
|
||||
Future<void> showSettingDialog(String title, bool showDelete, Widget body,
|
||||
Future Function() onSubmit, Future Function() onDelete) {
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
barrierDismissible: true,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: Text(title),
|
||||
content: SingleChildScrollView(
|
||||
child: SizedBox(
|
||||
width: 300,
|
||||
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");
|
||||
});
|
||||
},
|
||||
child: const Text(
|
||||
'删除',
|
||||
style: TextStyle(color: Colors.red),
|
||||
))
|
||||
: const Text(""),
|
||||
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");
|
||||
}
|
||||
});
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
100
ui/lib/settings/auth.dart
Normal file
100
ui/lib/settings/auth.dart
Normal file
@@ -0,0 +1,100 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_form_builder/flutter_form_builder.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:form_builder_validators/form_builder_validators.dart';
|
||||
import 'package:ui/providers/login.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
import 'package:ui/widgets/utils.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
|
||||
class AuthSettings extends ConsumerStatefulWidget {
|
||||
static const route = "/settings";
|
||||
|
||||
const AuthSettings({super.key});
|
||||
@override
|
||||
ConsumerState<ConsumerStatefulWidget> createState() {
|
||||
return _AuthState();
|
||||
}
|
||||
}
|
||||
|
||||
class _AuthState extends ConsumerState<AuthSettings> {
|
||||
final _formKey2 = GlobalKey<FormBuilderState>();
|
||||
bool? _enableAuth;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
var authData = ref.watch(authSettingProvider);
|
||||
return authData.when(
|
||||
data: (data) {
|
||||
if (_enableAuth == null) {
|
||||
setState(() {
|
||||
_enableAuth = data.enable;
|
||||
});
|
||||
}
|
||||
return FormBuilder(
|
||||
key: _formKey2,
|
||||
initialValue: {
|
||||
"user": data.user,
|
||||
"password": data.password,
|
||||
"enable": data.enable
|
||||
},
|
||||
child: Column(
|
||||
children: [
|
||||
FormBuilderSwitch(
|
||||
name: "enable",
|
||||
title: const Text("开启认证"),
|
||||
onChanged: (v) {
|
||||
setState(() {
|
||||
_enableAuth = v;
|
||||
});
|
||||
}),
|
||||
_enableAuth!
|
||||
? Column(
|
||||
children: [
|
||||
FormBuilderTextField(
|
||||
name: "user",
|
||||
autovalidateMode:
|
||||
AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
decoration: Commons.requiredTextFieldStyle(
|
||||
text: "用户名",
|
||||
icon: const Icon(Icons.account_box),
|
||||
)),
|
||||
FormBuilderTextField(
|
||||
name: "password",
|
||||
obscureText: true,
|
||||
enableSuggestions: false,
|
||||
autocorrect: false,
|
||||
autovalidateMode:
|
||||
AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
decoration: Commons.requiredTextFieldStyle(
|
||||
text: "密码",
|
||||
icon: const Icon(Icons.password),
|
||||
))
|
||||
],
|
||||
)
|
||||
: const Column(),
|
||||
Center(
|
||||
child: ElevatedButton(
|
||||
child: const Text("保存"),
|
||||
onPressed: () {
|
||||
if (_formKey2.currentState!.saveAndValidate()) {
|
||||
var values = _formKey2.currentState!.value;
|
||||
var f = ref
|
||||
.read(authSettingProvider.notifier)
|
||||
.updateAuthSetting(_enableAuth!,
|
||||
values["user"], values["password"])
|
||||
.then((v) {
|
||||
showSnakeBar("更新成功");
|
||||
});
|
||||
showLoadingWithFuture(f);
|
||||
}
|
||||
}))
|
||||
],
|
||||
));
|
||||
},
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator());
|
||||
}
|
||||
}
|
||||
48
ui/lib/settings/dialog.dart
Normal file
48
ui/lib/settings/dialog.dart
Normal file
@@ -0,0 +1,48 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
|
||||
Future<void> showSettingDialog(
|
||||
BuildContext context,
|
||||
String title,
|
||||
bool showDelete,
|
||||
Widget body,
|
||||
Future Function() onSubmit,
|
||||
Future Function() onDelete) {
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
barrierDismissible: true,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: Text(title),
|
||||
content: SingleChildScrollView(
|
||||
child: SizedBox(
|
||||
width: 300,
|
||||
child: body,
|
||||
),
|
||||
),
|
||||
actions: <Widget>[
|
||||
showDelete
|
||||
? TextButton(
|
||||
onPressed: () {
|
||||
final f = onDelete().then((v) => Navigator.of(context).pop());
|
||||
showLoadingWithFuture(f);
|
||||
},
|
||||
child: const Text(
|
||||
'删除',
|
||||
style: TextStyle(color: Colors.red),
|
||||
))
|
||||
: const Text(""),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('取消')),
|
||||
TextButton(
|
||||
child: const Text('确定'),
|
||||
onPressed: () {
|
||||
final f = onSubmit().then((v) => Navigator.of(context).pop());
|
||||
showLoadingWithFuture(f);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
});
|
||||
}
|
||||
159
ui/lib/settings/downloader.dart
Normal file
159
ui/lib/settings/downloader.dart
Normal file
@@ -0,0 +1,159 @@
|
||||
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:quiver/strings.dart';
|
||||
import 'package:ui/providers/settings.dart';
|
||||
import 'package:ui/settings/dialog.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
|
||||
class DownloaderSettings extends ConsumerStatefulWidget {
|
||||
static const route = "/settings";
|
||||
|
||||
const DownloaderSettings({super.key});
|
||||
@override
|
||||
ConsumerState<ConsumerStatefulWidget> createState() {
|
||||
return _DownloaderState();
|
||||
}
|
||||
}
|
||||
|
||||
class _DownloaderState extends ConsumerState<DownloaderSettings> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
var downloadClients = ref.watch(dwonloadClientsProvider);
|
||||
return downloadClients.when(
|
||||
data: (value) => Wrap(
|
||||
children: List.generate(value.length + 1, (i) {
|
||||
if (i < value.length) {
|
||||
var client = value[i];
|
||||
return SettingsCard(
|
||||
onTap: () => showDownloadClientDetails(client),
|
||||
child: Text(client.name ?? ""));
|
||||
}
|
||||
return SettingsCard(
|
||||
onTap: () => showDownloadClientDetails(DownloadClient()),
|
||||
child: const Icon(Icons.add));
|
||||
})),
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator());
|
||||
}
|
||||
|
||||
Future<void> showDownloadClientDetails(DownloadClient client) {
|
||||
final _formKey = GlobalKey<FormBuilderState>();
|
||||
var _enableAuth = isNotBlank(client.user);
|
||||
String selectImpl = "transmission";
|
||||
|
||||
final body =
|
||||
StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
|
||||
return FormBuilder(
|
||||
key: _formKey,
|
||||
initialValue: {
|
||||
"name": client.name,
|
||||
"url": client.url,
|
||||
"user": client.user,
|
||||
"password": client.password,
|
||||
"impl": "transmission",
|
||||
"remove_completed_downloads": client.removeCompletedDownloads,
|
||||
"remove_failed_downloads": client.removeFailedDownloads,
|
||||
},
|
||||
child: Column(
|
||||
children: [
|
||||
FormBuilderDropdown<String>(
|
||||
name: "impl",
|
||||
decoration: const InputDecoration(labelText: "类型"),
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
selectImpl = value!;
|
||||
});
|
||||
},
|
||||
items: const [
|
||||
DropdownMenuItem(
|
||||
value: "transmission", child: Text("Transmission")),
|
||||
],
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "name",
|
||||
decoration: const InputDecoration(labelText: "名称"),
|
||||
validator: FormBuilderValidators.required(),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction),
|
||||
FormBuilderTextField(
|
||||
name: "url",
|
||||
decoration: const InputDecoration(
|
||||
labelText: "地址", hintText: "http://127.0.0.1:9091"),
|
||||
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(
|
||||
children: [
|
||||
FormBuilderSwitch(
|
||||
name: "auth",
|
||||
title: const Text("需要认证"),
|
||||
initialValue: _enableAuth,
|
||||
onChanged: (v) {
|
||||
setState(() {
|
||||
_enableAuth = v!;
|
||||
});
|
||||
}),
|
||||
_enableAuth
|
||||
? Column(
|
||||
children: [
|
||||
FormBuilderTextField(
|
||||
name: "user",
|
||||
decoration: Commons.requiredTextFieldStyle(
|
||||
text: "用户"),
|
||||
validator: FormBuilderValidators.required(),
|
||||
autovalidateMode:
|
||||
AutovalidateMode.onUserInteraction),
|
||||
FormBuilderTextField(
|
||||
name: "password",
|
||||
decoration: Commons.requiredTextFieldStyle(
|
||||
text: "密码"),
|
||||
validator: FormBuilderValidators.required(),
|
||||
obscureText: true,
|
||||
autovalidateMode:
|
||||
AutovalidateMode.onUserInteraction),
|
||||
],
|
||||
)
|
||||
: Container()
|
||||
],
|
||||
);
|
||||
})
|
||||
],
|
||||
));
|
||||
});
|
||||
onDelete() async {
|
||||
return ref
|
||||
.read(dwonloadClientsProvider.notifier)
|
||||
.deleteDownloadClients(client.id!);
|
||||
}
|
||||
|
||||
onSubmit() async {
|
||||
if (_formKey.currentState!.saveAndValidate()) {
|
||||
var values = _formKey.currentState!.value;
|
||||
return ref.read(dwonloadClientsProvider.notifier).addDownloadClients(
|
||||
DownloadClient(
|
||||
name: values["name"],
|
||||
implementation: values["impl"],
|
||||
url: values["url"],
|
||||
user: _enableAuth ? values["user"] : null,
|
||||
password: _enableAuth ? values["password"] : null,
|
||||
removeCompletedDownloads: values["remove_completed_downloads"],
|
||||
removeFailedDownloads: values["remove_failed_downloads"]));
|
||||
} else {
|
||||
throw "validation_error";
|
||||
}
|
||||
}
|
||||
|
||||
return showSettingDialog(
|
||||
context, "下载器", client.id != null, body, onSubmit, onDelete);
|
||||
}
|
||||
}
|
||||
120
ui/lib/settings/general.dart
Normal file
120
ui/lib/settings/general.dart
Normal file
@@ -0,0 +1,120 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_form_builder/flutter_form_builder.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:form_builder_validators/form_builder_validators.dart';
|
||||
import 'package:ui/providers/settings.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
import 'package:ui/widgets/utils.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
|
||||
class GeneralSettings extends ConsumerStatefulWidget {
|
||||
static const route = "/settings";
|
||||
|
||||
const GeneralSettings({super.key});
|
||||
@override
|
||||
ConsumerState<ConsumerStatefulWidget> createState() {
|
||||
return _GeneralState();
|
||||
}
|
||||
}
|
||||
|
||||
class _GeneralState extends ConsumerState<GeneralSettings> {
|
||||
final _formKey = GlobalKey<FormBuilderState>();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
var settings = ref.watch(settingProvider);
|
||||
|
||||
return settings.when(
|
||||
data: (v) {
|
||||
return FormBuilder(
|
||||
key: _formKey, //设置globalKey,用于后面获取FormState
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
initialValue: {
|
||||
"tmdb_api": v.tmdbApiKey,
|
||||
"download_dir": v.downloadDIr,
|
||||
"log_level": v.logLevel,
|
||||
"proxy": v.proxy,
|
||||
"enable_plexmatch": v.enablePlexmatch
|
||||
},
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
FormBuilderTextField(
|
||||
name: "tmdb_api",
|
||||
decoration: Commons.requiredTextFieldStyle(
|
||||
text: "TMDB Api Key", icon: const Icon(Icons.key)),
|
||||
//
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "download_dir",
|
||||
decoration: Commons.requiredTextFieldStyle(
|
||||
text: "下载路径",
|
||||
icon: const Icon(Icons.folder),
|
||||
helperText: "媒体文件临时下载路径,非最终存储路径"),
|
||||
//
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "proxy",
|
||||
decoration: const InputDecoration(
|
||||
labelText: "代理地址",
|
||||
icon: Icon(Icons.web),
|
||||
helperText: "后台联网代理地址,留空表示不启用代理"),
|
||||
),
|
||||
SizedBox(
|
||||
width: 300,
|
||||
child: FormBuilderDropdown(
|
||||
name: "log_level",
|
||||
decoration: const InputDecoration(
|
||||
labelText: "日志级别",
|
||||
icon: Icon(Icons.file_present_rounded),
|
||||
),
|
||||
items: const [
|
||||
DropdownMenuItem(value: "debug", child: Text("DEBUG")),
|
||||
DropdownMenuItem(value: "info", child: Text("INFO")),
|
||||
DropdownMenuItem(value: "warn", child: Text("WARN")),
|
||||
DropdownMenuItem(value: "error", child: Text("ERROR")),
|
||||
],
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 300,
|
||||
child: FormBuilderSwitch(decoration: const InputDecoration(icon: Icon(Icons.token)),
|
||||
name: "enable_plexmatch", title: const Text("Plex 刮削支持")),
|
||||
),
|
||||
Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(top: 28.0),
|
||||
child: ElevatedButton(
|
||||
child: const Padding(
|
||||
padding: EdgeInsets.all(16.0),
|
||||
child: Text("保存"),
|
||||
),
|
||||
onPressed: () {
|
||||
if (_formKey.currentState!.saveAndValidate()) {
|
||||
var values = _formKey.currentState!.value;
|
||||
var f = ref
|
||||
.read(settingProvider.notifier)
|
||||
.updateSettings(GeneralSetting(
|
||||
tmdbApiKey: values["tmdb_api"],
|
||||
downloadDIr: values["download_dir"],
|
||||
logLevel: values["log_level"],
|
||||
proxy: values["proxy"],
|
||||
enablePlexmatch:
|
||||
values["enable_plexmatch"]))
|
||||
.then((v) => showSnakeBar("更新成功"));
|
||||
showLoadingWithFuture(f);
|
||||
}
|
||||
}),
|
||||
),
|
||||
)
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator());
|
||||
}
|
||||
}
|
||||
101
ui/lib/settings/indexer.dart
Normal file
101
ui/lib/settings/indexer.dart
Normal file
@@ -0,0 +1,101 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_form_builder/flutter_form_builder.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:form_builder_validators/form_builder_validators.dart';
|
||||
import 'package:ui/providers/settings.dart';
|
||||
import 'package:ui/settings/dialog.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
|
||||
class IndexerSettings extends ConsumerStatefulWidget {
|
||||
|
||||
const IndexerSettings({super.key});
|
||||
@override
|
||||
ConsumerState<ConsumerStatefulWidget> createState() {
|
||||
return _IndexerState();
|
||||
}
|
||||
}
|
||||
|
||||
class _IndexerState extends ConsumerState<IndexerSettings> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
var indexers = ref.watch(indexersProvider);
|
||||
return indexers.when(
|
||||
data: (value) => Wrap(
|
||||
children: List.generate(value.length + 1, (i) {
|
||||
if (i < value.length) {
|
||||
var indexer = value[i];
|
||||
return SettingsCard(
|
||||
onTap: () => showIndexerDetails(indexer),
|
||||
child: Text(indexer.name ?? ""));
|
||||
}
|
||||
return SettingsCard(
|
||||
onTap: () => showIndexerDetails(Indexer()),
|
||||
child: const Icon(Icons.add));
|
||||
}),
|
||||
),
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator());
|
||||
}
|
||||
|
||||
Future<void> showIndexerDetails(Indexer indexer) {
|
||||
final _formKey = GlobalKey<FormBuilderState>();
|
||||
|
||||
var body = FormBuilder(
|
||||
key: _formKey,
|
||||
initialValue: {
|
||||
"name": indexer.name,
|
||||
"url": indexer.url,
|
||||
"api_key": indexer.apiKey,
|
||||
"impl": "torznab"
|
||||
},
|
||||
child: Column(
|
||||
children: [
|
||||
FormBuilderDropdown(
|
||||
name: "impl",
|
||||
decoration: const InputDecoration(labelText: "类型"),
|
||||
items: const [
|
||||
DropdownMenuItem(value: "torznab", child: Text("Torznab")),
|
||||
],
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "name",
|
||||
decoration: Commons.requiredTextFieldStyle(text: "名称"),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "url",
|
||||
decoration: Commons.requiredTextFieldStyle(text: "地址"),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "api_key",
|
||||
decoration: Commons.requiredTextFieldStyle(text: "API Key"),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
onDelete() async {
|
||||
return ref.read(indexersProvider.notifier).deleteIndexer(indexer.id!);
|
||||
}
|
||||
|
||||
onSubmit() async {
|
||||
if (_formKey.currentState!.saveAndValidate()) {
|
||||
var values = _formKey.currentState!.value;
|
||||
return ref.read(indexersProvider.notifier).addIndexer(Indexer(
|
||||
name: values["name"],
|
||||
url: values["url"],
|
||||
apiKey: values["api_key"]));
|
||||
} else {
|
||||
throw "validation_error";
|
||||
}
|
||||
}
|
||||
|
||||
return showSettingDialog(
|
||||
context, "索引器", indexer.id != null, body, onSubmit, onDelete);
|
||||
}
|
||||
}
|
||||
224
ui/lib/settings/notifier.dart
Normal file
224
ui/lib/settings/notifier.dart
Normal file
@@ -0,0 +1,224 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_form_builder/flutter_form_builder.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:form_builder_validators/form_builder_validators.dart';
|
||||
import 'package:ui/providers/notifier.dart';
|
||||
import 'package:ui/settings/dialog.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
|
||||
class NotifierSettings extends ConsumerStatefulWidget {
|
||||
static const route = "/settings";
|
||||
|
||||
const NotifierSettings({super.key});
|
||||
@override
|
||||
ConsumerState<ConsumerStatefulWidget> createState() {
|
||||
return _NotifierState();
|
||||
}
|
||||
}
|
||||
|
||||
class _NotifierState extends ConsumerState<NotifierSettings> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final notifierData = ref.watch(notifiersDataProvider);
|
||||
return notifierData.when(
|
||||
data: (v) => Wrap(
|
||||
children: List.generate(v.length + 1, (i) {
|
||||
if (i < v.length) {
|
||||
final client = v[i];
|
||||
return SettingsCard(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
client.name!,
|
||||
style: TextStyle(fontSize: 20, height: 3),
|
||||
),
|
||||
Opacity(
|
||||
opacity: 0.5,
|
||||
child: Text(client.service!),
|
||||
)
|
||||
],
|
||||
),
|
||||
onTap: () => showNotifierAccordingToService(client),
|
||||
);
|
||||
}
|
||||
return SettingsCard(
|
||||
onTap: () => showSelections(),
|
||||
child: const Icon(Icons.add));
|
||||
}),
|
||||
),
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator());
|
||||
}
|
||||
|
||||
Future<void> showSelections() {
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
barrierDismissible: true,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
content: SizedBox(
|
||||
height: 500,
|
||||
width: 500,
|
||||
child: Wrap(
|
||||
children: [
|
||||
SettingsCard(
|
||||
child: InkWell(
|
||||
child: const Center(
|
||||
child: Text("Pushover"),
|
||||
),
|
||||
onTap: () {
|
||||
Navigator.of(context).pop();
|
||||
showPushoverNotifierDetails(NotifierData());
|
||||
},
|
||||
),
|
||||
),
|
||||
SettingsCard(
|
||||
child: InkWell(
|
||||
child: const Center(
|
||||
child: Text("Bark"),
|
||||
),
|
||||
onTap: () {
|
||||
Navigator.of(context).pop();
|
||||
showBarkNotifierDetails(NotifierData());
|
||||
},
|
||||
),
|
||||
)
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> showNotifierAccordingToService(NotifierData notifier) {
|
||||
switch (notifier.service) {
|
||||
case "bark":
|
||||
return showBarkNotifierDetails(notifier);
|
||||
case "pushover":
|
||||
return showPushoverNotifierDetails(notifier);
|
||||
}
|
||||
return Future<void>.value();
|
||||
}
|
||||
|
||||
Future<void> showBarkNotifierDetails(NotifierData notifier) {
|
||||
final _formKey = GlobalKey<FormBuilderState>();
|
||||
|
||||
var body = FormBuilder(
|
||||
key: _formKey,
|
||||
initialValue: {
|
||||
"name": notifier.name,
|
||||
"enabled": notifier.enabled ?? true,
|
||||
"device_key":
|
||||
notifier.settings != null ? notifier.settings!["device_key"] : "",
|
||||
"url": notifier.settings != null ? notifier.settings!["url"] : "",
|
||||
},
|
||||
child: Column(
|
||||
children: [
|
||||
FormBuilderTextField(
|
||||
name: "name",
|
||||
decoration: Commons.requiredTextFieldStyle(text: "名称"),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "url",
|
||||
decoration: const InputDecoration(
|
||||
labelText: "服务器地址", helperText: "留空使用默认地址"),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "device_key",
|
||||
decoration: Commons.requiredTextFieldStyle(text: "Device Key"),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderSwitch(name: "enabled", title: const Text("启用"))
|
||||
],
|
||||
),
|
||||
);
|
||||
onDelete() async {
|
||||
return ref.read(notifiersDataProvider.notifier).delete(notifier.id!);
|
||||
}
|
||||
|
||||
onSubmit() async {
|
||||
if (_formKey.currentState!.saveAndValidate()) {
|
||||
var values = _formKey.currentState!.value;
|
||||
return ref.read(notifiersDataProvider.notifier).add(NotifierData(
|
||||
name: values["name"],
|
||||
service: "bark",
|
||||
enabled: values["enabled"],
|
||||
settings: {
|
||||
"device_key": values["device_key"],
|
||||
"url": values["url"]
|
||||
}));
|
||||
} else {
|
||||
throw "validation_error";
|
||||
}
|
||||
}
|
||||
|
||||
return showSettingDialog(
|
||||
context, "Bark", notifier.id != null, body, onSubmit, onDelete);
|
||||
}
|
||||
|
||||
Future<void> showPushoverNotifierDetails(NotifierData notifier) {
|
||||
final _formKey = GlobalKey<FormBuilderState>();
|
||||
|
||||
var body = FormBuilder(
|
||||
key: _formKey,
|
||||
initialValue: {
|
||||
"name": notifier.name,
|
||||
"enabled": notifier.enabled ?? true,
|
||||
"app_token":
|
||||
notifier.settings != null ? notifier.settings!["app_token"] : "",
|
||||
"user_key":
|
||||
notifier.settings != null ? notifier.settings!["user_key"] : "",
|
||||
},
|
||||
child: Column(
|
||||
children: [
|
||||
FormBuilderTextField(
|
||||
name: "name",
|
||||
decoration: Commons.requiredTextFieldStyle(text: "名称"),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "app_token",
|
||||
decoration: Commons.requiredTextFieldStyle(text: "APP密钥"),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "user_key",
|
||||
decoration: Commons.requiredTextFieldStyle(text: "用户密钥"),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderSwitch(name: "enabled", title: const Text("启用"))
|
||||
],
|
||||
),
|
||||
);
|
||||
onDelete() async {
|
||||
return ref.read(notifiersDataProvider.notifier).delete(notifier.id!);
|
||||
}
|
||||
|
||||
onSubmit() async {
|
||||
if (_formKey.currentState!.saveAndValidate()) {
|
||||
var values = _formKey.currentState!.value;
|
||||
return ref.read(notifiersDataProvider.notifier).add(NotifierData(
|
||||
name: values["name"],
|
||||
service: "pushover",
|
||||
enabled: values["enabled"],
|
||||
settings: {
|
||||
"app_token": values["app_token"],
|
||||
"user_key": values["user_key"]
|
||||
}));
|
||||
} else {
|
||||
throw "validation_error";
|
||||
}
|
||||
}
|
||||
|
||||
return showSettingDialog(
|
||||
context, "Pushover", notifier.id != null, body, onSubmit, onDelete);
|
||||
}
|
||||
}
|
||||
173
ui/lib/settings/storage.dart
Normal file
173
ui/lib/settings/storage.dart
Normal file
@@ -0,0 +1,173 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_form_builder/flutter_form_builder.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:form_builder_validators/form_builder_validators.dart';
|
||||
import 'package:ui/providers/settings.dart';
|
||||
import 'package:ui/settings/dialog.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
|
||||
class StorageSettings extends ConsumerStatefulWidget {
|
||||
static const route = "/settings";
|
||||
|
||||
const StorageSettings({super.key});
|
||||
@override
|
||||
ConsumerState<ConsumerStatefulWidget> createState() {
|
||||
return _StorageState();
|
||||
}
|
||||
}
|
||||
|
||||
class _StorageState extends ConsumerState<StorageSettings> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
var storageSettingData = ref.watch(storageSettingProvider);
|
||||
return storageSettingData.when(
|
||||
data: (value) => Wrap(
|
||||
children: List.generate(value.length + 1, (i) {
|
||||
if (i < value.length) {
|
||||
var storage = value[i];
|
||||
return SettingsCard(
|
||||
onTap: () => showStorageDetails(storage),
|
||||
child: Text(storage.name ?? ""));
|
||||
}
|
||||
return SettingsCard(
|
||||
onTap: () => showStorageDetails(Storage()),
|
||||
child: const Icon(Icons.add));
|
||||
}),
|
||||
),
|
||||
error: (err, trace) => Text("$err"),
|
||||
loading: () => const MyProgressIndicator());
|
||||
}
|
||||
|
||||
Future<void> showStorageDetails(Storage s) {
|
||||
final _formKey = GlobalKey<FormBuilderState>();
|
||||
|
||||
String selectImpl = s.implementation == null ? "local" : s.implementation!;
|
||||
final widgets =
|
||||
StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
|
||||
return FormBuilder(
|
||||
key: _formKey,
|
||||
autovalidateMode: AutovalidateMode.disabled,
|
||||
initialValue: {
|
||||
"name": s.name,
|
||||
"impl": s.implementation == null ? "local" : s.implementation!,
|
||||
"user": s.settings != null ? s.settings!["user"] ?? "" : "",
|
||||
"password": s.settings != null ? s.settings!["password"] ?? "" : "",
|
||||
"tv_path": s.tvPath,
|
||||
"url": s.settings != null ? s.settings!["url"] ?? "" : "",
|
||||
"movie_path": s.moviePath,
|
||||
"change_file_hash": s.settings != null
|
||||
? s.settings!["change_file_hash"] == "true"
|
||||
? true
|
||||
: false
|
||||
: false,
|
||||
},
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
FormBuilderDropdown<String>(
|
||||
name: "impl",
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
decoration: const InputDecoration(labelText: "类型"),
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
selectImpl = value!;
|
||||
});
|
||||
},
|
||||
items: const [
|
||||
DropdownMenuItem(
|
||||
value: "local",
|
||||
child: Text("本地存储"),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: "webdav",
|
||||
child: Text("webdav"),
|
||||
)
|
||||
],
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "name",
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
initialValue: s.name,
|
||||
decoration: const InputDecoration(labelText: "名称"),
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
selectImpl != "local"
|
||||
? Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
FormBuilderTextField(
|
||||
name: "url",
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
decoration:
|
||||
const InputDecoration(labelText: "Webdav地址"),
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "user",
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
decoration: const InputDecoration(labelText: "用户"),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "password",
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
decoration: const InputDecoration(labelText: "密码"),
|
||||
obscureText: true,
|
||||
),
|
||||
FormBuilderCheckbox(
|
||||
name: "change_file_hash",
|
||||
title: const Text(
|
||||
"上传时更改文件哈希",
|
||||
style: TextStyle(fontSize: 14),
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: Container(),
|
||||
FormBuilderTextField(
|
||||
name: "tv_path",
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
decoration: const InputDecoration(labelText: "电视剧路径"),
|
||||
validator: FormBuilderValidators.required(),
|
||||
),
|
||||
FormBuilderTextField(
|
||||
name: "movie_path",
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
decoration: const InputDecoration(labelText: "电影路径"),
|
||||
validator: FormBuilderValidators.required(),
|
||||
)
|
||||
],
|
||||
));
|
||||
});
|
||||
onSubmit() async {
|
||||
if (_formKey.currentState!.saveAndValidate()) {
|
||||
final values = _formKey.currentState!.value;
|
||||
return ref.read(storageSettingProvider.notifier).addStorage(Storage(
|
||||
name: values["name"],
|
||||
implementation: selectImpl,
|
||||
tvPath: values["tv_path"],
|
||||
moviePath: values["movie_path"],
|
||||
settings: {
|
||||
"url": values["url"],
|
||||
"user": values["user"],
|
||||
"password": values["password"],
|
||||
"change_file_hash":
|
||||
(values["change_file_hash"] ?? false) as bool
|
||||
? "true"
|
||||
: "false"
|
||||
},
|
||||
));
|
||||
} else {
|
||||
throw "validation_error";
|
||||
}
|
||||
}
|
||||
|
||||
onDelete() async {
|
||||
return ref.read(storageSettingProvider.notifier).deleteStorage(s.id!);
|
||||
}
|
||||
|
||||
return showSettingDialog(
|
||||
context, '存储', s.id != null, widgets, onSubmit, onDelete);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:ui/providers/APIs.dart';
|
||||
|
||||
import 'package:ui/providers/settings.dart';
|
||||
import 'package:ui/utils.dart';
|
||||
import 'package:ui/widgets/utils.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
@@ -49,9 +49,7 @@ class _SystemPageState extends ConsumerState<SystemPage> {
|
||||
DataCell(Text((item.size ?? 0).readableFileSize())),
|
||||
DataCell(InkWell(
|
||||
child: const Icon(Icons.download),
|
||||
onTap: () => launchUrl(uri,
|
||||
webViewConfiguration: WebViewConfiguration(
|
||||
headers: APIs.authHeaders)),
|
||||
onTap: () => launchUrl(uri),
|
||||
))
|
||||
]);
|
||||
}));
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
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/utils.dart';
|
||||
import 'package:ui/welcome_page.dart';
|
||||
import 'package:ui/widgets/detail_card.dart';
|
||||
import 'package:ui/widgets/utils.dart';
|
||||
import 'package:ui/widgets/progress_indicator.dart';
|
||||
import 'package:ui/widgets/widgets.dart';
|
||||
|
||||
class TvDetailsPage extends ConsumerStatefulWidget {
|
||||
static const route = "/series/:id";
|
||||
@@ -34,7 +32,6 @@ class _TvDetailsPageState extends ConsumerState<TvDetailsPage> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
var seriesDetails = ref.watch(mediaDetailsProvider(widget.seriesId));
|
||||
var storage = ref.watch(storageSettingProvider);
|
||||
return seriesDetails.when(
|
||||
data: (details) {
|
||||
Map<int, List<DataRow>> m = {};
|
||||
@@ -70,14 +67,12 @@ class _TvDetailsPageState extends ConsumerState<TvDetailsPage> {
|
||||
message: "搜索下载对应剧集",
|
||||
child: IconButton(
|
||||
onPressed: () {
|
||||
ref
|
||||
var f = ref
|
||||
.read(mediaDetailsProvider(widget.seriesId)
|
||||
.notifier)
|
||||
.searchAndDownload(widget.seriesId,
|
||||
ep.seasonNumber!, ep.episodeNumber!)
|
||||
.then((v) => Utils.showSnakeBar("开始下载: $v"))
|
||||
.onError((error, trace) =>
|
||||
Utils.showSnakeBar("操作失败: $error"));
|
||||
ep.seasonNumber!, ep.episodeNumber!).then((v) => showSnakeBar("开始下载: $v"));
|
||||
showLoadingWithFuture(f);
|
||||
},
|
||||
icon: const Icon(Icons.download)),
|
||||
),
|
||||
@@ -120,13 +115,11 @@ class _TvDetailsPageState extends ConsumerState<TvDetailsPage> {
|
||||
message: "搜索下载全部剧集",
|
||||
child: IconButton(
|
||||
onPressed: () {
|
||||
ref
|
||||
final f = ref
|
||||
.read(mediaDetailsProvider(widget.seriesId)
|
||||
.notifier)
|
||||
.searchAndDownload(widget.seriesId, k, 0)
|
||||
.then((v) => Utils.showSnakeBar("开始下载: $v"))
|
||||
.onError((error, trace) =>
|
||||
Utils.showSnakeBar("操作失败: $error"));
|
||||
.searchAndDownload(widget.seriesId, k, 0).then((v) => showSnakeBar("开始下载: $v"));
|
||||
showLoadingWithFuture(f);
|
||||
},
|
||||
icon: const Icon(Icons.download)),
|
||||
),
|
||||
@@ -146,100 +139,7 @@ class _TvDetailsPageState extends ConsumerState<TvDetailsPage> {
|
||||
}
|
||||
return ListView(
|
||||
children: [
|
||||
Card(
|
||||
margin: const EdgeInsets.all(4),
|
||||
clipBehavior: Clip.hardEdge,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
image: DecorationImage(
|
||||
fit: BoxFit.fitWidth,
|
||||
opacity: 0.5,
|
||||
image: NetworkImage(
|
||||
"${APIs.imagesUrl}/${details.id}/backdrop.jpg",
|
||||
headers: APIs.authHeaders))),
|
||||
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,
|
||||
headers: APIs.authHeaders,
|
||||
),
|
||||
),
|
||||
),
|
||||
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,
|
||||
),
|
||||
@@ -265,13 +165,14 @@ class _TvDetailsPageState extends ConsumerState<TvDetailsPage> {
|
||||
//title: Text("资源"),
|
||||
content: SelectionArea(
|
||||
child: SizedBox(
|
||||
width: 800,
|
||||
height: 400,
|
||||
width: MediaQuery.of(context).size.width*0.7,
|
||||
height: MediaQuery.of(context).size.height*0.6,
|
||||
child: torrents.when(
|
||||
data: (v) {
|
||||
return SingleChildScrollView(
|
||||
child: DataTable(
|
||||
dataTextStyle: const TextStyle(fontSize: 12, height: 0),
|
||||
dataTextStyle:
|
||||
const TextStyle(fontSize: 12, height: 0),
|
||||
columns: const [
|
||||
DataColumn(label: Text("名称")),
|
||||
DataColumn(label: Text("大小")),
|
||||
@@ -290,19 +191,14 @@ class _TvDetailsPageState extends ConsumerState<TvDetailsPage> {
|
||||
DataCell(IconButton(
|
||||
icon: const Icon(Icons.download),
|
||||
onPressed: () async {
|
||||
await ref
|
||||
var f = 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"));
|
||||
.download(torrent).then((v) => showSnakeBar("开始下载:${torrent.name}"));
|
||||
showLoadingWithFuture(f);
|
||||
},
|
||||
))
|
||||
]);
|
||||
|
||||
@@ -34,13 +34,17 @@ class WelcomePage extends ConsumerWidget {
|
||||
Container(
|
||||
height: MediaQuery.of(context).size.height * 0.6,
|
||||
alignment: Alignment.center,
|
||||
child: const Text("啥都没有...", style: TextStyle(fontSize: 16),))
|
||||
child: const Text(
|
||||
"啥都没有...",
|
||||
style: TextStyle(fontSize: 16),
|
||||
))
|
||||
]
|
||||
: List.generate(value.length, (i) {
|
||||
var item = value[i];
|
||||
final item = value[i];
|
||||
return Card(
|
||||
margin: const EdgeInsets.all(4),
|
||||
//margin: const EdgeInsets.all(4),
|
||||
clipBehavior: Clip.hardEdge,
|
||||
elevation: 5,
|
||||
child: InkWell(
|
||||
//splashColor: Colors.blue.withAlpha(30),
|
||||
onTap: () {
|
||||
@@ -55,27 +59,32 @@ class WelcomePage extends ConsumerWidget {
|
||||
SizedBox(
|
||||
width: 140,
|
||||
height: 210,
|
||||
child: Image.network(
|
||||
child: Ink.image(
|
||||
image: NetworkImage(
|
||||
"${APIs.imagesUrl}/${item.id}/poster.jpg",
|
||||
fit: BoxFit.fill,
|
||||
headers: APIs.authHeaders,
|
||||
),
|
||||
)),
|
||||
),
|
||||
SizedBox(
|
||||
width: 140,
|
||||
child: LinearProgressIndicator(
|
||||
value: 1,
|
||||
color: item.status == "downloaded"
|
||||
? Colors.green
|
||||
: Colors.blue,
|
||||
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),
|
||||
),
|
||||
],
|
||||
)),
|
||||
Text(
|
||||
item.name!,
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.bold,
|
||||
height: 2.5),
|
||||
),
|
||||
],
|
||||
),
|
||||
));
|
||||
|
||||
132
ui/lib/widgets/detail_card.dart
Normal file
132
ui/lib/widgets/detail_card.dart
Normal file
@@ -0,0 +1,132 @@
|
||||
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/welcome_page.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> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
margin: const EdgeInsets.all(4),
|
||||
clipBehavior: Clip.hardEdge,
|
||||
child: Container(
|
||||
constraints:
|
||||
BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.4),
|
||||
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>[
|
||||
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(""),
|
||||
Row(
|
||||
children: [
|
||||
Text("${widget.details.resolution}"),
|
||||
const SizedBox(
|
||||
width: 30,
|
||||
),
|
||||
Text(
|
||||
"${widget.details.storage!.name} (${widget.details.storage!.implementation})"),
|
||||
const SizedBox(
|
||||
width: 30,
|
||||
),
|
||||
Text(
|
||||
"${widget.details.mediaType == "tv" ? widget.details.storage!.tvPath : widget.details.storage!.moviePath}"
|
||||
"${widget.details.targetDir}"),
|
||||
const SizedBox(
|
||||
width: 30,
|
||||
),
|
||||
widget.details.mediaType == 'tv'
|
||||
? (widget.details.downloadHistoryEpisodes ==
|
||||
true
|
||||
? const Text("下载所有剧集")
|
||||
: const Text("只下载更新剧集"))
|
||||
: const Text("")
|
||||
],
|
||||
),
|
||||
const Divider(thickness: 1, height: 1),
|
||||
Text(
|
||||
"${widget.details.name} ${widget.details.name != widget.details.originalName ? widget.details.originalName : ''} (${widget.details.airDate!.split("-")[0]})",
|
||||
style: const TextStyle(
|
||||
fontSize: 20, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const Text(""),
|
||||
Expanded(
|
||||
child: Text(
|
||||
overflow: TextOverflow.ellipsis,
|
||||
maxLines: 9,
|
||||
widget.details.overview ?? "",
|
||||
)),
|
||||
Row(
|
||||
children: [
|
||||
deleteIcon(),
|
||||
],
|
||||
)
|
||||
],
|
||||
)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget deleteIcon() {
|
||||
return Tooltip(
|
||||
message: widget.details.mediaType == "tv" ? "删除剧集" : "删除电影",
|
||||
child: IconButton(
|
||||
onPressed: () {
|
||||
var f = ref
|
||||
.read(
|
||||
mediaDetailsProvider(widget.details.id.toString()).notifier)
|
||||
.delete()
|
||||
.then((v) => context.go(widget.details.mediaType == "tv"
|
||||
? WelcomePage.routeTv
|
||||
: WelcomePage.routeMoivie));
|
||||
showLoadingWithFuture(f);
|
||||
},
|
||||
icon: const Icon(Icons.delete)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,9 @@ class Utils {
|
||||
);
|
||||
}
|
||||
|
||||
static showSnakeBar(String msg) {
|
||||
}
|
||||
|
||||
showSnakeBar(String msg) {
|
||||
final context = APIs.navigatorKey.currentContext;
|
||||
if (context != null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
@@ -42,17 +44,6 @@ class Utils {
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
extension FileFormatter on num {
|
||||
String readableFileSize({bool base1024 = true}) {
|
||||
final base = base1024 ? 1024 : 1000;
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:ui/providers/APIs.dart';
|
||||
|
||||
class Commons {
|
||||
static InputDecoration requiredTextFieldStyle({
|
||||
@@ -41,3 +42,47 @@ 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("正在处理,请稍后..."),
|
||||
)
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
112
ui/pubspec.lock
112
ui/pubspec.lock
@@ -89,22 +89,6 @@ packages:
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.3.1"
|
||||
ffi:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: ffi
|
||||
sha256: "493f37e7df1804778ff3a53bd691d8692ddf69702cf4c1c1096a2e41b4779e21"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.1.2"
|
||||
file:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file
|
||||
sha256: "5fc22d7c25582e38ad9a8515372cd9a93834027aacf1801cf01164dac0ffa08c"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "7.0.0"
|
||||
flutter:
|
||||
dependency: "direct main"
|
||||
description: flutter
|
||||
@@ -325,30 +309,6 @@ packages:
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.9.0"
|
||||
path_provider_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_linux
|
||||
sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.2.1"
|
||||
path_provider_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_platform_interface
|
||||
sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.1.2"
|
||||
path_provider_windows:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_windows
|
||||
sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.3.0"
|
||||
percent_indicator:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -365,14 +325,6 @@ packages:
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "8.3.0"
|
||||
platform:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: platform
|
||||
sha256: "9b71283fc13df574056616011fb138fd3b793ea47cc509c189a6c3fa5f8a1a65"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "3.1.5"
|
||||
plugin_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -405,62 +357,6 @@ packages:
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.5.1"
|
||||
shared_preferences:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: shared_preferences
|
||||
sha256: d3bbe5553a986e83980916ded2f0b435ef2e1893dfaa29d5a7a790d0eca12180
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.2.3"
|
||||
shared_preferences_android:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_android
|
||||
sha256: "93d0ec9dd902d85f326068e6a899487d1f65ffcd5798721a95330b26c8131577"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.2.3"
|
||||
shared_preferences_foundation:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_foundation
|
||||
sha256: "0a8a893bf4fd1152f93fec03a415d11c27c74454d96e2318a7ac38dd18683ab7"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.4.0"
|
||||
shared_preferences_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_linux
|
||||
sha256: "9f2cbcf46d4270ea8be39fa156d86379077c8a5228d9dfdb1164ae0bb93f1faa"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.3.2"
|
||||
shared_preferences_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_platform_interface
|
||||
sha256: "22e2ecac9419b4246d7c22bfbbda589e3acf5c0351137d87dd2939d984d37c3b"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.3.2"
|
||||
shared_preferences_web:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_web
|
||||
sha256: "9aee1089b36bd2aafe06582b7d7817fd317ef05fc30e6ba14bff247d0933042a"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.3.0"
|
||||
shared_preferences_windows:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_windows
|
||||
sha256: "841ad54f3c8381c480d0c9b508b89a34036f512482c407e6df7a9c4aa2ef8f59"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.3.2"
|
||||
sign_in_button:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -626,14 +522,6 @@ packages:
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "0.5.1"
|
||||
xdg_directories:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: xdg_directories
|
||||
sha256: faea9dee56b520b55a566385b84f2e8de55e7496104adada9962e0bd11bcff1d
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.0.4"
|
||||
sdks:
|
||||
dart: ">=3.4.3 <4.0.0"
|
||||
flutter: ">=3.22.0"
|
||||
|
||||
@@ -40,7 +40,6 @@ dependencies:
|
||||
flutter_riverpod: ^2.5.1
|
||||
quiver: ^3.2.1
|
||||
flutter_login: ^5.0.0
|
||||
shared_preferences: ^2.2.3
|
||||
percent_indicator: ^4.2.3
|
||||
intl: ^0.19.0
|
||||
flutter_adaptive_scaffold: ^0.1.11+1
|
||||
|
||||
Reference in New Issue
Block a user