Compare commits

...

29 Commits

Author SHA1 Message Date
Simon Ding
9350e376f4 fix 2024-07-31 17:50:37 +08:00
Simon Ding
06f935871a chore: improve ui & fix 2024-07-31 17:43:42 +08:00
Simon Ding
001b850d8f feat: add imdbid to .plexmatch file 2024-07-31 17:01:50 +08:00
Simon Ding
1340305f2d feat: change progress display 2024-07-31 16:55:01 +08:00
Simon Ding
b337e40fcc feat: change name suggestting 2024-07-31 16:23:22 +08:00
Simon Ding
e94386e455 chore: better text display 2024-07-31 15:45:49 +08:00
Simon Ding
2b4fb99c89 chore: improve ui 2024-07-31 15:40:24 +08:00
Simon Ding
faa603d5df code refactor & improve search page 2024-07-31 15:26:34 +08:00
Simon Ding
9ba59a7d5a refactor code 2024-07-31 14:41:57 +08:00
Simon Ding
0ea1c040a2 chore: optimize log 2024-07-30 22:56:17 +08:00
Simon Ding
eba646f5db chore: delete not exist tasks 2024-07-30 22:11:41 +08:00
Simon Ding
ebcc0c32da fix: panic 2024-07-30 22:10:18 +08:00
Simon Ding
769f217506 feat: add option to control whether to deleted task 2024-07-30 21:55:54 +08:00
Simon Ding
3525d1bb83 feat: try hard link first 2024-07-30 21:15:35 +08:00
Simon Ding
2c3fd89f2a fix: plexmatch 2024-07-30 20:56:44 +08:00
Simon Ding
19ab8c65de chore: fixes 2024-07-30 20:37:42 +08:00
Simon Ding
979218f615 feat: season plexmatch file 2024-07-30 20:01:41 +08:00
Simon Ding
d4dd2da335 set umask to 0011 2024-07-30 19:22:17 +08:00
Simon Ding
000717fcd9 fix plexmatch 2024-07-30 17:22:28 +08:00
Simon Ding
300f9a478b chore: update readme 2024-07-30 16:35:59 +08:00
Simon Ding
88a554b186 fix: local storage dir 2024-07-30 16:12:10 +08:00
Simon Ding
6ef4bedebe feat: support generate .plexmatch 2024-07-30 15:51:54 +08:00
Simon Ding
233970ef39 feat: display loading animation 2024-07-30 14:02:24 +08:00
Simon Ding
e2bba8ec71 fix: target dir 2024-07-30 11:49:42 +08:00
Simon Ding
b7aeb9c3c6 fix: create file permission 2024-07-30 11:27:06 +08:00
Simon Ding
4a93d51fdc fix: chinese naming 2024-07-30 11:16:51 +08:00
Simon Ding
f158b74be6 fix: movie suggested naming 2024-07-30 11:11:07 +08:00
Simon Ding
2c8c715540 feat: movie also requires suggested dir 2024-07-30 10:50:40 +08:00
Simon Ding
ba532d406a feat: default to html render 2024-07-30 10:08:21 +08:00
52 changed files with 1731 additions and 781 deletions

View File

@@ -3,7 +3,7 @@ WORKDIR /app
COPY ./ui/pubspec.yaml ./ui/pubspec.lock ./
RUN flutter pub get
COPY ./ui/ ./
RUN flutter build web --no-web-resources-cdn
RUN flutter build web --no-web-resources-cdn --web-renderer html
# 打包依赖阶段使用golang作为基础镜像
FROM golang:1.22 as builder

View File

@@ -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
* 更好的中文支持

View File

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

View File

@@ -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"

View File

@@ -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())
@@ -335,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 {
@@ -344,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)
@@ -383,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())
@@ -392,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
@@ -413,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")
@@ -431,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 {
@@ -547,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())
}

View File

@@ -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(", ")

View File

@@ -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()

View File

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

View File

@@ -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

View File

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

View File

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

View File

@@ -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},
@@ -141,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},

View File

@@ -1705,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)
@@ -2113,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
@@ -2232,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)
}
@@ -2251,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)
}
@@ -2277,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:
@@ -2302,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:
@@ -2357,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 {
@@ -2388,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
}
@@ -2402,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
}
@@ -2432,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)
}
@@ -2443,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)
}
@@ -2463,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
@@ -2492,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
@@ -5220,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
@@ -5399,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
@@ -5554,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)
}
@@ -5582,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:
@@ -5601,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:
@@ -5630,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 {
@@ -5681,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)
}
@@ -5698,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
@@ -5715,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

View File

@@ -84,11 +84,11 @@ func init() {
storageFields := schema.Storage{}.Fields()
_ = storageFields
// storageDescDeleted is the schema descriptor for deleted field.
storageDescDeleted := storageFields[3].Descriptor()
storageDescDeleted := storageFields[5].Descriptor()
// storage.DefaultDeleted holds the default value on creation for the deleted field.
storage.DefaultDeleted = storageDescDeleted.Default.(bool)
// storageDescDefault is the schema descriptor for default field.
storageDescDefault := storageFields[4].Descriptor()
storageDescDefault := storageFields[6].Descriptor()
// storage.DefaultDefault holds the default value on creation for the default field.
storage.DefaultDefault = storageDescDefault.Default.(bool)
}

View File

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

View File

@@ -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"),

View File

@@ -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),

View File

@@ -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(", ")

View File

@@ -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()

View File

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

View File

@@ -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

View File

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

View File

@@ -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()

View File

@@ -13,7 +13,10 @@ import (
type Storage interface {
Move(src, dest string) error
Copy(src, dest string) error
ReadDir(dir string) ([]fs.FileInfo, error)
ReadFile(string) ([]byte, error)
WriteFile(string, []byte) error
}
func NewLocalStorage(dir string) (*LocalStorage, error) {
@@ -26,10 +29,20 @@ type LocalStorage struct {
dir string
}
func (l *LocalStorage) Move(src, dest string) error {
targetDir := filepath.Join(l.dir, dest)
os.MkdirAll(filepath.Dir(targetDir), os.ModePerm)
err := filepath.Walk(src, func(path string, info fs.FileInfo, err error) error {
func (l *LocalStorage) Copy(src, destDir string) error {
os.MkdirAll(filepath.Join(l.dir, destDir), os.ModePerm)
targetBase := filepath.Join(l.dir, destDir, filepath.Base(src)) //文件的场景,要加上文件名, move filename ./dir/
info, err := os.Stat(src)
if err != nil {
return errors.Wrap(err, "read source dir")
}
if info.IsDir() { //如果是路径,则只移动路径里面的文件,不管当前路径, 行为类似 move dirname/* target_dir/
targetBase = filepath.Join(l.dir, destDir)
}
log.Debugf("local storage target base dir is: %v", targetBase)
err = filepath.Walk(src, func(path string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
@@ -37,24 +50,28 @@ func (l *LocalStorage) Move(src, dest string) error {
if err != nil {
return errors.Wrapf(err, "relation between %s and %s", src, path)
}
destName := filepath.Join(targetDir, rel)
destName := filepath.Join(targetBase, rel)
if info.IsDir() {
os.Mkdir(destName, os.ModePerm)
} else { //is file
if writer, err := os.Create(destName); err != nil {
return errors.Wrapf(err, "create file %s", destName)
} else {
defer writer.Close()
if f, err := os.OpenFile(path, os.O_RDONLY, os.ModePerm); err != nil {
return errors.Wrapf(err, "read file %v", path)
} else { //open success
defer f.Close()
_, err := io.Copy(writer, f)
if err != nil {
return errors.Wrap(err, "transmitting data error")
if err := os.Link(path, destName); err != nil {
log.Warnf("hard link file error: %v, will try copy file, source: %s, dest: %s", err, path, destName)
if writer, err := os.OpenFile(destName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, os.ModePerm); err != nil {
return errors.Wrapf(err, "create file %s", destName)
} else {
defer writer.Close()
if f, err := os.OpenFile(path, os.O_RDONLY, os.ModePerm); err != nil {
return errors.Wrapf(err, "read file %v", path)
} else { //open success
defer f.Close()
_, err := io.Copy(writer, f)
if err != nil {
return errors.Wrap(err, "transmitting data error")
}
}
}
}
}
log.Infof("file copy complete: %v", destName)
@@ -63,10 +80,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)
}

View File

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

View File

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

View File

@@ -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
View 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"
}

View File

@@ -30,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")
}
@@ -54,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")
@@ -75,7 +76,7 @@ func (s *Server) downloadSeasonPackage(r1 torznab.Result, seriesId, seasonNum in
}
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")
}
@@ -101,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")
@@ -263,43 +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.sendMsg(fmt.Sprintf(message.BeginDownload, in.Name))
log.Infof("success add %s to download task", in.Name)
return in.Name, nil
s.tasks[history.ID] = &Task{Torrent: torrent}
s.db.SetEpisodeStatus(ep.ID, episode.StatusDownloading)
}()
s.sendMsg(fmt.Sprintf(message.BeginDownload, in.Name))
log.Infof("success add %s to download task", in.Name)
return in.Name, nil
}
}

View File

@@ -7,11 +7,9 @@ import (
"polaris/ent/episode"
"polaris/ent/history"
"polaris/ent/media"
storage1 "polaris/ent/storage"
"polaris/log"
"polaris/pkg"
"polaris/pkg/notifier/message"
"polaris/pkg/storage"
"polaris/pkg/utils"
"polaris/server/core"
"time"
@@ -41,6 +39,7 @@ 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())
@@ -64,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)
@@ -80,17 +85,11 @@ func (s *Server) moveCompletedTask(id int) (err1 error) {
s.db.SetSeasonAllEpisodeStatus(r.MediaID, seasonNum, episode.StatusMissing)
}
s.sendMsg(fmt.Sprintf(message.ProcessingFailed, err))
} else {
delete(s.tasks, r.ID)
s.db.SetHistoryStatus(r.ID, history.StatusSuccess)
if r.EpisodeID != 0 {
s.db.SetEpisodeStatus(r.EpisodeID, episode.StatusDownloaded)
} else {
s.db.SetSeasonAllEpisodeStatus(r.MediaID, seasonNum, episode.StatusDownloaded)
if downloadclient.RemoveFailedDownloads {
log.Debugf("task failed, remove failed torrent and files related")
delete(s.tasks, r.ID)
torrent.Remove()
}
s.sendMsg(fmt.Sprintf(message.ProcessingComplete, torrent.Name()))
torrent.Remove()
}
}()
@@ -100,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
}
@@ -151,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)
@@ -273,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")
}
@@ -292,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)

View File

@@ -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
@@ -92,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")
{

View File

@@ -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 {

View File

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

View File

@@ -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) {

View File

@@ -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/widgets/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);
};
}
}

View File

@@ -121,7 +121,7 @@ class _MyAppState extends ConsumerState<MyApp> {
return ProviderScope(
child: MaterialApp.router(
title: 'Polaris 影视追踪',
title: 'Polaris 影视追踪下载',
theme: ThemeData(
fontFamily: "NotoSansSC",
colorScheme: ColorScheme.fromSeed(
@@ -248,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: '系统',
),
],

View File

@@ -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/widgets/detail_card.dart';
import 'package:ui/widgets/utils.dart';
import 'package:ui/welcome_page.dart';
import 'package:ui/widgets/progress_indicator.dart';
import 'package:ui/widgets/widgets.dart';
class MovieDetailsPage extends ConsumerStatefulWidget {
static const route = "/movie/:id";
@@ -30,105 +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.cover,
opacity: 0.5,
image: NetworkImage(
"${APIs.imagesUrl}/${details.id}/backdrop.jpg",
))),
child: Padding(
padding: const EdgeInsets.all(10),
child: Row(
children: <Widget>[
Flexible(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(10),
child: Image.network(
"${APIs.imagesUrl}/${details.id}/poster.jpg",
fit: BoxFit.contain,
),
),
),
Expanded(
flex: 6,
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text("${details.resolution}"),
const SizedBox(
width: 30,
),
storage.when(
data: (value) {
for (final s in value) {
if (s.id == details.storageId) {
return Text(
"${s.name}(${s.implementation})");
}
}
return const Text("未知存储");
},
error: (error, stackTrace) =>
Text("$error"),
loading: () =>
const MyProgressIndicator()),
],
),
const Divider(thickness: 1, height: 1),
Text(
"${details.name} (${details.airDate!.split("-")[0]})",
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold),
),
const Text(""),
Text(
details.overview!,
),
],
)),
Column(
children: [
IconButton(
onPressed: () {
ref
.read(mediaDetailsProvider(
widget.id)
.notifier)
.delete()
.then((v) => context
.go(WelcomePage.routeMoivie))
.onError((error, trace) =>
Utils.showSnakeBar(
"删除失败:$error"));
},
icon: const Icon(Icons.delete))
],
)
],
),
),
],
),
)),
),
DetailCard(details: details),
NestedTabBar(
id: widget.id,
)
@@ -157,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
@@ -251,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);
},
))
]);

View File

@@ -14,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";

View File

@@ -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),

View File

@@ -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,
};

View File

@@ -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 {
);
}
}

View File

@@ -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/widgets/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});
@@ -30,13 +32,15 @@ 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),
))];
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) {
@@ -145,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>[
@@ -278,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;
});
},
),
],

View File

@@ -18,7 +18,7 @@ class AuthSettings extends ConsumerStatefulWidget {
}
class _AuthState extends ConsumerState<AuthSettings> {
final _formKey2 = GlobalKey<FormBuilderState>();
final _formKey2 = GlobalKey<FormBuilderState>();
bool? _enableAuth;
@override
@@ -84,12 +84,11 @@ class _AuthState extends ConsumerState<AuthSettings> {
var f = ref
.read(authSettingProvider.notifier)
.updateAuthSetting(_enableAuth!,
values["user"], values["password"]);
f.then((v) {
Utils.showSnakeBar("更新成功");
}).onError((e, s) {
Utils.showSnakeBar("更新失败:$e");
values["user"], values["password"])
.then((v) {
showSnakeBar("更新成功");
});
showLoadingWithFuture(f);
}
}))
],
@@ -98,5 +97,4 @@ class _AuthState extends ConsumerState<AuthSettings> {
error: (err, trace) => Text("$err"),
loading: () => const MyProgressIndicator());
}
}
}

View File

@@ -1,8 +1,13 @@
import 'package:flutter/material.dart';
import 'package:ui/widgets/utils.dart';
import 'package:ui/widgets/widgets.dart';
Future<void> showSettingDialog(BuildContext context,String title, bool showDelete, Widget body,
Future Function() onSubmit, Future Function() onDelete) {
Future<void> showSettingDialog(
BuildContext context,
String title,
bool showDelete,
Widget body,
Future Function() onSubmit,
Future Function() onDelete) {
return showDialog<void>(
context: context,
barrierDismissible: true,
@@ -19,13 +24,8 @@ Future<void> showSettingDialog(BuildContext context,String title, bool showDelet
showDelete
? TextButton(
onPressed: () {
final f = onDelete();
f.then((v) {
Utils.showSnakeBar("删除成功");
Navigator.of(context).pop();
}).onError((e, s) {
Utils.showSnakeBar("删除失败:$e");
});
final f = onDelete().then((v) => Navigator.of(context).pop());
showLoadingWithFuture(f);
},
child: const Text(
'删除',
@@ -38,15 +38,8 @@ Future<void> showSettingDialog(BuildContext context,String title, bool showDelet
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");
}
});
final f = onSubmit().then((v) => Navigator.of(context).pop());
showLoadingWithFuture(f);
},
),
],

View File

@@ -53,7 +53,9 @@ class _DownloaderState extends ConsumerState<DownloaderSettings> {
"url": client.url,
"user": client.user,
"password": client.password,
"impl": "transmission"
"impl": "transmission",
"remove_completed_downloads": client.removeCompletedDownloads,
"remove_failed_downloads": client.removeFailedDownloads,
},
child: Column(
children: [
@@ -82,6 +84,12 @@ class _DownloaderState extends ConsumerState<DownloaderSettings> {
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: FormBuilderValidators.required(),
),
FormBuilderSwitch(
name: "remove_completed_downloads",
title: const Text("任务完成后删除")),
FormBuilderSwitch(
name: "remove_failed_downloads",
title: const Text("任务失败后删除")),
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Column(
@@ -137,7 +145,9 @@ class _DownloaderState extends ConsumerState<DownloaderSettings> {
implementation: values["impl"],
url: values["url"],
user: _enableAuth ? values["user"] : null,
password: _enableAuth ? values["password"] : null));
password: _enableAuth ? values["password"] : null,
removeCompletedDownloads: values["remove_completed_downloads"],
removeFailedDownloads: values["remove_failed_downloads"]));
} else {
throw "validation_error";
}

View File

@@ -3,8 +3,8 @@ import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:ui/providers/settings.dart';
import 'package:ui/widgets/utils.dart';
import 'package:ui/widgets/progress_indicator.dart';
import 'package:ui/widgets/utils.dart';
import 'package:ui/widgets/widgets.dart';
class GeneralSettings extends ConsumerStatefulWidget {
@@ -17,9 +17,8 @@ class GeneralSettings extends ConsumerStatefulWidget {
}
}
class _GeneralState extends ConsumerState<GeneralSettings> {
final _formKey = GlobalKey<FormBuilderState>();
final _formKey = GlobalKey<FormBuilderState>();
@override
Widget build(BuildContext context) {
@@ -35,6 +34,7 @@ class _GeneralState extends ConsumerState<GeneralSettings> {
"download_dir": v.downloadDIr,
"log_level": v.logLevel,
"proxy": v.proxy,
"enable_plexmatch": v.enablePlexmatch
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -59,7 +59,7 @@ class _GeneralState extends ConsumerState<GeneralSettings> {
name: "proxy",
decoration: const InputDecoration(
labelText: "代理地址",
icon: Icon(Icons.folder),
icon: Icon(Icons.web),
helperText: "后台联网代理地址,留空表示不启用代理"),
),
SizedBox(
@@ -79,6 +79,11 @@ class _GeneralState extends ConsumerState<GeneralSettings> {
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),
@@ -96,12 +101,11 @@ class _GeneralState extends ConsumerState<GeneralSettings> {
tmdbApiKey: values["tmdb_api"],
downloadDIr: values["download_dir"],
logLevel: values["log_level"],
proxy: values["proxy"]));
f.then((v) {
Utils.showSnakeBar("更新成功");
}).onError((e, s) {
Utils.showSnakeBar("更新失败:$e");
});
proxy: values["proxy"],
enablePlexmatch:
values["enable_plexmatch"]))
.then((v) => showSnakeBar("更新成功"));
showLoadingWithFuture(f);
}
}),
),
@@ -113,5 +117,4 @@ class _GeneralState extends ConsumerState<GeneralSettings> {
error: (err, trace) => Text("$err"),
loading: () => const MyProgressIndicator());
}
}
}

View File

@@ -39,7 +39,7 @@ class _StorageState extends ConsumerState<StorageSettings> {
loading: () => const MyProgressIndicator());
}
Future<void> showStorageDetails(Storage s) {
Future<void> showStorageDetails(Storage s) {
final _formKey = GlobalKey<FormBuilderState>();
String selectImpl = s.implementation == null ? "local" : s.implementation!;
@@ -53,10 +53,9 @@ class _StorageState extends ConsumerState<StorageSettings> {
"impl": s.implementation == null ? "local" : s.implementation!,
"user": s.settings != null ? s.settings!["user"] ?? "" : "",
"password": s.settings != null ? s.settings!["password"] ?? "" : "",
"tv_path": s.settings != null ? s.settings!["tv_path"] ?? "" : "",
"tv_path": s.tvPath,
"url": s.settings != null ? s.settings!["url"] ?? "" : "",
"movie_path":
s.settings != null ? s.settings!["movie_path"] ?? "" : "",
"movie_path": s.moviePath,
"change_file_hash": s.settings != null
? s.settings!["change_file_hash"] == "true"
? true
@@ -147,9 +146,9 @@ class _StorageState extends ConsumerState<StorageSettings> {
return ref.read(storageSettingProvider.notifier).addStorage(Storage(
name: values["name"],
implementation: selectImpl,
tvPath: values["tv_path"],
moviePath: values["movie_path"],
settings: {
"tv_path": values["tv_path"],
"movie_path": values["movie_path"],
"url": values["url"],
"user": values["user"],
"password": values["password"],
@@ -168,7 +167,7 @@ class _StorageState extends ConsumerState<StorageSettings> {
return ref.read(storageSettingProvider.notifier).deleteStorage(s.id!);
}
return showSettingDialog(context,'存储', s.id != null, widgets, onSubmit, onDelete);
return showSettingDialog(
context, '存储', s.id != null, widgets, onSubmit, onDelete);
}
}

View File

@@ -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/widgets/detail_card.dart';
import 'package:ui/widgets/utils.dart';
import 'package:ui/welcome_page.dart';
import 'package:ui/widgets/progress_indicator.dart';
import 'package:ui/widgets/widgets.dart';
class TvDetailsPage extends ConsumerStatefulWidget {
static const route = "/series/:id";
@@ -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,98 +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.cover,
opacity: 0.5,
image: NetworkImage(
"${APIs.imagesUrl}/${details.id}/backdrop.jpg"))),
child: Padding(
padding: const EdgeInsets.all(10),
child: Row(
children: <Widget>[
Flexible(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(10),
child: Image.network(
"${APIs.imagesUrl}/${details.id}/poster.jpg",
fit: BoxFit.contain
),
),
),
Flexible(
flex: 6,
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text("${details.resolution}"),
const SizedBox(
width: 30,
),
storage.when(
data: (value) {
for (final s in value) {
if (s.id == details.storageId) {
return Text(
"${s.name}(${s.implementation})");
}
}
return const Text("未知存储");
},
error: (error, stackTrace) =>
Text("$error"),
loading: () => const Text("")),
],
),
const Divider(thickness: 1, height: 1),
Text(
"${details.name} ${details.name != details.originalName ? details.originalName : ''} (${details.airDate!.split("-")[0]})",
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold),
),
const Text(""),
Text(
details.overview ?? "",
),
],
)),
Column(
children: [
IconButton(
onPressed: () {
ref
.read(mediaDetailsProvider(
widget.seriesId)
.notifier)
.delete()
.then((v) =>
context.go(WelcomePage.routeTv))
.onError((error, trace) =>
Utils.showSnakeBar(
"删除失败: $error"));
},
icon: const Icon(Icons.delete))
],
)
],
),
),
],
),
),
),
),
DetailCard(details: details),
Column(
children: list,
),
@@ -263,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("大小")),
@@ -288,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);
},
))
]);

View File

@@ -40,10 +40,11 @@ class WelcomePage extends ConsumerWidget {
))
]
: 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: () {
@@ -58,25 +59,32 @@ class WelcomePage extends ConsumerWidget {
SizedBox(
width: 140,
height: 210,
child: Image.network(
"${APIs.imagesUrl}/${item.id}/poster.jpg",
fit: BoxFit.fill),
child: Ink.image(
image: NetworkImage(
"${APIs.imagesUrl}/${item.id}/poster.jpg",
)),
),
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),
),
],
),
));

View 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)),
);
}
}

View File

@@ -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;

View File

@@ -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("正在处理,请稍后..."),
)
],
),
);
}
});
},
);
}