diff --git a/db/db.go b/db/db.go index c7258ab..a7f3b8c 100644 --- a/db/db.go +++ b/db/db.go @@ -10,7 +10,7 @@ import ( "polaris/ent/episode" "polaris/ent/history" "polaris/ent/indexers" - "polaris/ent/series" + "polaris/ent/media" "polaris/ent/settings" "polaris/ent/storage" "polaris/log" @@ -19,7 +19,6 @@ import ( "time" "entgo.io/ent/dialect" - tmdb "github.com/cyruzin/golang-tmdb" _ "github.com/mattn/go-sqlite3" "github.com/pkg/errors" ) @@ -85,46 +84,45 @@ func (c *Client) GetLanguage() string { return lang } -func (c *Client) AddWatchlist(storageId int, nameCn, nameEn string, detail *tmdb.TVDetails, episodes []int, res ResolutionType) (*ent.Series, error) { - count := c.ent.Series.Query().Where(series.TmdbID(int(detail.ID))).CountX(context.Background()) +func (c *Client) AddMediaWatchlist(m *ent.Media, episodes []int) (*ent.Media, error) { + count := c.ent.Media.Query().Where(media.TmdbID(m.TmdbID)).CountX(context.Background()) if count > 0 { - return nil, fmt.Errorf("tv series %s already in watchlist", detail.Name) + return nil, fmt.Errorf("tv series %s already in watchlist", m.NameEn) } - if res == "" { - res = R1080p - } - if storageId == 0 { + + if m.StorageID == 0 { r, err := c.ent.Storage.Query().Where(storage.And(storage.Default(true), storage.Deleted(false))).First(context.TODO()) if err == nil { log.Infof("use default storage: %v", r.Name) - storageId = r.ID + m.StorageID = r.ID } } - targetDir := fmt.Sprintf("%s %s (%v)", nameCn, nameEn, strings.Split(detail.FirstAirDate, "-")[0]) - if !utils.IsChineseChar(nameCn) { - log.Warnf("name cn is not chinese name: %v", nameCn) - targetDir = fmt.Sprintf("%s (%v)", nameEn, strings.Split(detail.FirstAirDate, "-")[0]) + targetDir := fmt.Sprintf("%s %s (%v)", m.NameCn, m.NameEn, strings.Split(m.AirDate, "-")[0]) + if !utils.IsChineseChar(m.NameCn) { + log.Warnf("name cn is not chinese name: %v", m.NameCn) + targetDir = fmt.Sprintf("%s (%v)", m.NameEn, strings.Split(m.AirDate, "-")[0]) } - r, err := c.ent.Series.Create(). - SetTmdbID(int(detail.ID)). - SetStorageID(storageId). - SetOverview(detail.Overview). - SetNameCn(nameCn). - SetNameEn(nameEn). - SetOriginalName(detail.OriginalName). - SetPosterPath(detail.PosterPath). - SetAirDate(detail.FirstAirDate). - SetResolution(res.String()). + r, err := c.ent.Media.Create(). + SetTmdbID(m.TmdbID). + SetStorageID(m.StorageID). + SetOverview(m.Overview). + SetNameCn(m.NameCn). + SetNameEn(m.NameEn). + SetOriginalName(m.OriginalName). + SetMediaType(m.MediaType). + SetAirDate(m.AirDate). + SetResolution(m.Resolution). SetTargetDir(targetDir). AddEpisodeIDs(episodes...). Save(context.TODO()) return r, err + } -func (c *Client) GetWatchlist() []*ent.Series { - list, err := c.ent.Series.Query().All(context.TODO()) +func (c *Client) GetMediaWatchlist(mediaType media.MediaType) []*ent.Media { + list, err := c.ent.Media.Query().Where(media.MediaTypeEQ(mediaType)).All(context.TODO()) if err != nil { log.Infof("query wtach list error: %v", err) return nil @@ -132,34 +130,37 @@ func (c *Client) GetWatchlist() []*ent.Series { return list } -type SeriesDetails struct { - *ent.Series +type MediaDetails struct { + *ent.Media Episodes []*ent.Episode `json:"episodes"` } -func (c *Client) GetSeriesDetails(id int) *SeriesDetails { - se, err := c.ent.Series.Query().Where(series.ID(id)).First(context.TODO()) +func (c *Client) GetMediaDetails(id int) *MediaDetails { + se, err := c.ent.Media.Query().Where(media.ID(id)).First(context.TODO()) if err != nil { log.Errorf("get series %d: %v", id, err) return nil } - ep, err := se.QueryEpisodes().All(context.Background()) - if err != nil { - log.Errorf("get episodes %d: %v", id, err) - return nil + var md = &MediaDetails{ + Media: se, } - return &SeriesDetails{ - Series: se, - Episodes: ep, + if se.MediaType == media.MediaTypeTv { + ep, err := se.QueryEpisodes().All(context.Background()) + if err != nil { + log.Errorf("get episodes %d: %v", id, err) + return nil + } + md.Episodes = ep } + return md } -func (c *Client) DeleteSeries(id int) error { - _, err := c.ent.Episode.Delete().Where(episode.SeriesID(id)).Exec(context.TODO()) +func (c *Client) DeleteMedia(id int) error { + _, err := c.ent.Episode.Delete().Where(episode.MediaID(id)).Exec(context.TODO()) if err != nil { return err } - _, err = c.ent.Series.Delete().Where(series.ID(id)).Exec(context.TODO()) + _, err = c.ent.Media.Delete().Where(media.ID(id)).Exec(context.TODO()) return err } @@ -381,7 +382,7 @@ func (c *Client) SetDefaultStorageByName(name string) error { } func (c *Client) SaveHistoryRecord(h ent.History) (*ent.History, error) { - return c.ent.History.Create().SetSeriesID(h.SeriesID).SetEpisodeID(h.EpisodeID).SetDate(time.Now()). + return c.ent.History.Create().SetMediaID(h.MediaID).SetEpisodeID(h.EpisodeID).SetDate(time.Now()). SetStatus(h.Status).SetTargetDir(h.TargetDir).SetSourceTitle(h.SourceTitle).SetSaved(h.Saved).Save(context.TODO()) } @@ -398,7 +399,7 @@ func (c *Client) GetHistories() ent.Histories { } func (c *Client) GetRunningHistories() ent.Histories { - h, err := c.ent.History.Query().Where(history.Or(history.StatusEQ(history.StatusRunning), + h, err := c.ent.History.Query().Where(history.Or(history.StatusEQ(history.StatusRunning), history.StatusEQ(history.StatusUploading))).All(context.TODO()) if err != nil { return nil @@ -423,8 +424,8 @@ func (c *Client) GetDownloadDir() string { return r.Value } -func (c *Client) UpdateEpisodeFile(seriesID int, seasonNum, episodeNum int, file string) error { - ep, err := c.ent.Episode.Query().Where(episode.SeriesID(seriesID)).Where(episode.EpisodeNumber(episodeNum)). +func (c *Client) UpdateEpisodeFile(mediaID int, seasonNum, episodeNum int, file string) error { + ep, err := c.ent.Episode.Query().Where(episode.MediaID(mediaID)).Where(episode.EpisodeNumber(episodeNum)). Where(episode.SeasonNumber(seasonNum)).First(context.TODO()) if err != nil { return errors.Wrap(err, "finding episode") @@ -432,7 +433,6 @@ func (c *Client) UpdateEpisodeFile(seriesID int, seasonNum, episodeNum int, file return ep.Update().SetFileInStorage(file).Exec(context.TODO()) } - func (c *Client) SetEpisodeStatus(id int, status episode.Status) error { return c.ent.Episode.Update().Where(episode.ID(id)).SetStatus(status).Exec(context.TODO()) -} \ No newline at end of file +} diff --git a/ent/client.go b/ent/client.go index a0b4911..a81ed9d 100644 --- a/ent/client.go +++ b/ent/client.go @@ -15,7 +15,7 @@ import ( "polaris/ent/episode" "polaris/ent/history" "polaris/ent/indexers" - "polaris/ent/series" + "polaris/ent/media" "polaris/ent/settings" "polaris/ent/storage" @@ -38,8 +38,8 @@ type Client struct { History *HistoryClient // Indexers is the client for interacting with the Indexers builders. Indexers *IndexersClient - // Series is the client for interacting with the Series builders. - Series *SeriesClient + // Media is the client for interacting with the Media builders. + Media *MediaClient // Settings is the client for interacting with the Settings builders. Settings *SettingsClient // Storage is the client for interacting with the Storage builders. @@ -59,7 +59,7 @@ func (c *Client) init() { c.Episode = NewEpisodeClient(c.config) c.History = NewHistoryClient(c.config) c.Indexers = NewIndexersClient(c.config) - c.Series = NewSeriesClient(c.config) + c.Media = NewMediaClient(c.config) c.Settings = NewSettingsClient(c.config) c.Storage = NewStorageClient(c.config) } @@ -158,7 +158,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { Episode: NewEpisodeClient(cfg), History: NewHistoryClient(cfg), Indexers: NewIndexersClient(cfg), - Series: NewSeriesClient(cfg), + Media: NewMediaClient(cfg), Settings: NewSettingsClient(cfg), Storage: NewStorageClient(cfg), }, nil @@ -184,7 +184,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) Episode: NewEpisodeClient(cfg), History: NewHistoryClient(cfg), Indexers: NewIndexersClient(cfg), - Series: NewSeriesClient(cfg), + Media: NewMediaClient(cfg), Settings: NewSettingsClient(cfg), Storage: NewStorageClient(cfg), }, nil @@ -216,7 +216,7 @@ func (c *Client) Close() error { // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { for _, n := range []interface{ Use(...Hook) }{ - c.DownloadClients, c.Episode, c.History, c.Indexers, c.Series, c.Settings, + c.DownloadClients, c.Episode, c.History, c.Indexers, c.Media, c.Settings, c.Storage, } { n.Use(hooks...) @@ -227,7 +227,7 @@ func (c *Client) Use(hooks ...Hook) { // In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. func (c *Client) Intercept(interceptors ...Interceptor) { for _, n := range []interface{ Intercept(...Interceptor) }{ - c.DownloadClients, c.Episode, c.History, c.Indexers, c.Series, c.Settings, + c.DownloadClients, c.Episode, c.History, c.Indexers, c.Media, c.Settings, c.Storage, } { n.Intercept(interceptors...) @@ -245,8 +245,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.History.mutate(ctx, m) case *IndexersMutation: return c.Indexers.mutate(ctx, m) - case *SeriesMutation: - return c.Series.mutate(ctx, m) + case *MediaMutation: + return c.Media.mutate(ctx, m) case *SettingsMutation: return c.Settings.mutate(ctx, m) case *StorageMutation: @@ -497,15 +497,15 @@ func (c *EpisodeClient) GetX(ctx context.Context, id int) *Episode { return obj } -// QuerySeries queries the series edge of a Episode. -func (c *EpisodeClient) QuerySeries(e *Episode) *SeriesQuery { - query := (&SeriesClient{config: c.config}).Query() +// QueryMedia queries the media edge of a Episode. +func (c *EpisodeClient) QueryMedia(e *Episode) *MediaQuery { + query := (&MediaClient{config: c.config}).Query() query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := e.ID step := sqlgraph.NewStep( sqlgraph.From(episode.Table, episode.FieldID, id), - sqlgraph.To(series.Table, series.FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, episode.SeriesTable, episode.SeriesColumn), + sqlgraph.To(media.Table, media.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, episode.MediaTable, episode.MediaColumn), ) fromV = sqlgraph.Neighbors(e.driver.Dialect(), step) return fromV, nil @@ -804,107 +804,107 @@ func (c *IndexersClient) mutate(ctx context.Context, m *IndexersMutation) (Value } } -// SeriesClient is a client for the Series schema. -type SeriesClient struct { +// MediaClient is a client for the Media schema. +type MediaClient struct { config } -// NewSeriesClient returns a client for the Series from the given config. -func NewSeriesClient(c config) *SeriesClient { - return &SeriesClient{config: c} +// NewMediaClient returns a client for the Media from the given config. +func NewMediaClient(c config) *MediaClient { + return &MediaClient{config: c} } // Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `series.Hooks(f(g(h())))`. -func (c *SeriesClient) Use(hooks ...Hook) { - c.hooks.Series = append(c.hooks.Series, hooks...) +// A call to `Use(f, g, h)` equals to `media.Hooks(f(g(h())))`. +func (c *MediaClient) Use(hooks ...Hook) { + c.hooks.Media = append(c.hooks.Media, hooks...) } // Intercept adds a list of query interceptors to the interceptors stack. -// A call to `Intercept(f, g, h)` equals to `series.Intercept(f(g(h())))`. -func (c *SeriesClient) Intercept(interceptors ...Interceptor) { - c.inters.Series = append(c.inters.Series, interceptors...) +// A call to `Intercept(f, g, h)` equals to `media.Intercept(f(g(h())))`. +func (c *MediaClient) Intercept(interceptors ...Interceptor) { + c.inters.Media = append(c.inters.Media, interceptors...) } -// Create returns a builder for creating a Series entity. -func (c *SeriesClient) Create() *SeriesCreate { - mutation := newSeriesMutation(c.config, OpCreate) - return &SeriesCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +// Create returns a builder for creating a Media entity. +func (c *MediaClient) Create() *MediaCreate { + mutation := newMediaMutation(c.config, OpCreate) + return &MediaCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// CreateBulk returns a builder for creating a bulk of Series entities. -func (c *SeriesClient) CreateBulk(builders ...*SeriesCreate) *SeriesCreateBulk { - return &SeriesCreateBulk{config: c.config, builders: builders} +// CreateBulk returns a builder for creating a bulk of Media entities. +func (c *MediaClient) CreateBulk(builders ...*MediaCreate) *MediaCreateBulk { + return &MediaCreateBulk{config: c.config, builders: builders} } // MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates // a builder and applies setFunc on it. -func (c *SeriesClient) MapCreateBulk(slice any, setFunc func(*SeriesCreate, int)) *SeriesCreateBulk { +func (c *MediaClient) MapCreateBulk(slice any, setFunc func(*MediaCreate, int)) *MediaCreateBulk { rv := reflect.ValueOf(slice) if rv.Kind() != reflect.Slice { - return &SeriesCreateBulk{err: fmt.Errorf("calling to SeriesClient.MapCreateBulk with wrong type %T, need slice", slice)} + return &MediaCreateBulk{err: fmt.Errorf("calling to MediaClient.MapCreateBulk with wrong type %T, need slice", slice)} } - builders := make([]*SeriesCreate, rv.Len()) + builders := make([]*MediaCreate, rv.Len()) for i := 0; i < rv.Len(); i++ { builders[i] = c.Create() setFunc(builders[i], i) } - return &SeriesCreateBulk{config: c.config, builders: builders} + return &MediaCreateBulk{config: c.config, builders: builders} } -// Update returns an update builder for Series. -func (c *SeriesClient) Update() *SeriesUpdate { - mutation := newSeriesMutation(c.config, OpUpdate) - return &SeriesUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +// Update returns an update builder for Media. +func (c *MediaClient) Update() *MediaUpdate { + mutation := newMediaMutation(c.config, OpUpdate) + return &MediaUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} } // UpdateOne returns an update builder for the given entity. -func (c *SeriesClient) UpdateOne(s *Series) *SeriesUpdateOne { - mutation := newSeriesMutation(c.config, OpUpdateOne, withSeries(s)) - return &SeriesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +func (c *MediaClient) UpdateOne(m *Media) *MediaUpdateOne { + mutation := newMediaMutation(c.config, OpUpdateOne, withMedia(m)) + return &MediaUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} } // UpdateOneID returns an update builder for the given id. -func (c *SeriesClient) UpdateOneID(id int) *SeriesUpdateOne { - mutation := newSeriesMutation(c.config, OpUpdateOne, withSeriesID(id)) - return &SeriesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +func (c *MediaClient) UpdateOneID(id int) *MediaUpdateOne { + mutation := newMediaMutation(c.config, OpUpdateOne, withMediaID(id)) + return &MediaUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// Delete returns a delete builder for Series. -func (c *SeriesClient) Delete() *SeriesDelete { - mutation := newSeriesMutation(c.config, OpDelete) - return &SeriesDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +// Delete returns a delete builder for Media. +func (c *MediaClient) Delete() *MediaDelete { + mutation := newMediaMutation(c.config, OpDelete) + return &MediaDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } // DeleteOne returns a builder for deleting the given entity. -func (c *SeriesClient) DeleteOne(s *Series) *SeriesDeleteOne { - return c.DeleteOneID(s.ID) +func (c *MediaClient) DeleteOne(m *Media) *MediaDeleteOne { + return c.DeleteOneID(m.ID) } // DeleteOneID returns a builder for deleting the given entity by its id. -func (c *SeriesClient) DeleteOneID(id int) *SeriesDeleteOne { - builder := c.Delete().Where(series.ID(id)) +func (c *MediaClient) DeleteOneID(id int) *MediaDeleteOne { + builder := c.Delete().Where(media.ID(id)) builder.mutation.id = &id builder.mutation.op = OpDeleteOne - return &SeriesDeleteOne{builder} + return &MediaDeleteOne{builder} } -// Query returns a query builder for Series. -func (c *SeriesClient) Query() *SeriesQuery { - return &SeriesQuery{ +// Query returns a query builder for Media. +func (c *MediaClient) Query() *MediaQuery { + return &MediaQuery{ config: c.config, - ctx: &QueryContext{Type: TypeSeries}, + ctx: &QueryContext{Type: TypeMedia}, inters: c.Interceptors(), } } -// Get returns a Series entity by its id. -func (c *SeriesClient) Get(ctx context.Context, id int) (*Series, error) { - return c.Query().Where(series.ID(id)).Only(ctx) +// Get returns a Media entity by its id. +func (c *MediaClient) Get(ctx context.Context, id int) (*Media, error) { + return c.Query().Where(media.ID(id)).Only(ctx) } // GetX is like Get, but panics if an error occurs. -func (c *SeriesClient) GetX(ctx context.Context, id int) *Series { +func (c *MediaClient) GetX(ctx context.Context, id int) *Media { obj, err := c.Get(ctx, id) if err != nil { panic(err) @@ -912,44 +912,44 @@ func (c *SeriesClient) GetX(ctx context.Context, id int) *Series { return obj } -// QueryEpisodes queries the episodes edge of a Series. -func (c *SeriesClient) QueryEpisodes(s *Series) *EpisodeQuery { +// QueryEpisodes queries the episodes edge of a Media. +func (c *MediaClient) QueryEpisodes(m *Media) *EpisodeQuery { query := (&EpisodeClient{config: c.config}).Query() query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := s.ID + id := m.ID step := sqlgraph.NewStep( - sqlgraph.From(series.Table, series.FieldID, id), + sqlgraph.From(media.Table, media.FieldID, id), sqlgraph.To(episode.Table, episode.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, series.EpisodesTable, series.EpisodesColumn), + sqlgraph.Edge(sqlgraph.O2M, false, media.EpisodesTable, media.EpisodesColumn), ) - fromV = sqlgraph.Neighbors(s.driver.Dialect(), step) + fromV = sqlgraph.Neighbors(m.driver.Dialect(), step) return fromV, nil } return query } // Hooks returns the client hooks. -func (c *SeriesClient) Hooks() []Hook { - return c.hooks.Series +func (c *MediaClient) Hooks() []Hook { + return c.hooks.Media } // Interceptors returns the client interceptors. -func (c *SeriesClient) Interceptors() []Interceptor { - return c.inters.Series +func (c *MediaClient) Interceptors() []Interceptor { + return c.inters.Media } -func (c *SeriesClient) mutate(ctx context.Context, m *SeriesMutation) (Value, error) { +func (c *MediaClient) mutate(ctx context.Context, m *MediaMutation) (Value, error) { switch m.Op() { case OpCreate: - return (&SeriesCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + return (&MediaCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) case OpUpdate: - return (&SeriesUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + return (&MediaUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) case OpUpdateOne: - return (&SeriesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + return (&MediaUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) case OpDelete, OpDeleteOne: - return (&SeriesDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + return (&MediaDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) default: - return nil, fmt.Errorf("ent: unknown Series mutation op: %q", m.Op()) + return nil, fmt.Errorf("ent: unknown Media mutation op: %q", m.Op()) } } @@ -1222,11 +1222,10 @@ func (c *StorageClient) mutate(ctx context.Context, m *StorageMutation) (Value, // hooks and interceptors per client, for fast access. type ( hooks struct { - DownloadClients, Episode, History, Indexers, Series, Settings, - Storage []ent.Hook + DownloadClients, Episode, History, Indexers, Media, Settings, Storage []ent.Hook } inters struct { - DownloadClients, Episode, History, Indexers, Series, Settings, + DownloadClients, Episode, History, Indexers, Media, Settings, Storage []ent.Interceptor } ) diff --git a/ent/ent.go b/ent/ent.go index c83f041..26b05ea 100644 --- a/ent/ent.go +++ b/ent/ent.go @@ -10,7 +10,7 @@ import ( "polaris/ent/episode" "polaris/ent/history" "polaris/ent/indexers" - "polaris/ent/series" + "polaris/ent/media" "polaris/ent/settings" "polaris/ent/storage" "reflect" @@ -83,7 +83,7 @@ func checkColumn(table, column string) error { episode.Table: episode.ValidColumn, history.Table: history.ValidColumn, indexers.Table: indexers.ValidColumn, - series.Table: series.ValidColumn, + media.Table: media.ValidColumn, settings.Table: settings.ValidColumn, storage.Table: storage.ValidColumn, }) diff --git a/ent/episode.go b/ent/episode.go index 4173dfb..2227c16 100644 --- a/ent/episode.go +++ b/ent/episode.go @@ -5,7 +5,7 @@ package ent import ( "fmt" "polaris/ent/episode" - "polaris/ent/series" + "polaris/ent/media" "strings" "entgo.io/ent" @@ -17,8 +17,8 @@ type Episode struct { config `json:"-"` // ID of the ent. ID int `json:"id,omitempty"` - // SeriesID holds the value of the "series_id" field. - SeriesID int `json:"series_id,omitempty"` + // MediaID holds the value of the "media_id" field. + MediaID int `json:"media_id,omitempty"` // SeasonNumber holds the value of the "season_number" field. SeasonNumber int `json:"season_number"` // EpisodeNumber holds the value of the "episode_number" field. @@ -41,22 +41,22 @@ type Episode struct { // EpisodeEdges holds the relations/edges for other nodes in the graph. type EpisodeEdges struct { - // Series holds the value of the series edge. - Series *Series `json:"series,omitempty"` + // Media holds the value of the media edge. + Media *Media `json:"media,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. loadedTypes [1]bool } -// SeriesOrErr returns the Series value or an error if the edge +// MediaOrErr returns the Media value or an error if the edge // was not loaded in eager-loading, or loaded but was not found. -func (e EpisodeEdges) SeriesOrErr() (*Series, error) { - if e.Series != nil { - return e.Series, nil +func (e EpisodeEdges) MediaOrErr() (*Media, error) { + if e.Media != nil { + return e.Media, nil } else if e.loadedTypes[0] { - return nil, &NotFoundError{label: series.Label} + return nil, &NotFoundError{label: media.Label} } - return nil, &NotLoadedError{edge: "series"} + return nil, &NotLoadedError{edge: "media"} } // scanValues returns the types for scanning values from sql.Rows. @@ -64,7 +64,7 @@ func (*Episode) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) for i := range columns { switch columns[i] { - case episode.FieldID, episode.FieldSeriesID, episode.FieldSeasonNumber, episode.FieldEpisodeNumber: + case episode.FieldID, episode.FieldMediaID, episode.FieldSeasonNumber, episode.FieldEpisodeNumber: values[i] = new(sql.NullInt64) case episode.FieldTitle, episode.FieldOverview, episode.FieldAirDate, episode.FieldStatus, episode.FieldFileInStorage: values[i] = new(sql.NullString) @@ -89,11 +89,11 @@ func (e *Episode) assignValues(columns []string, values []any) error { return fmt.Errorf("unexpected type %T for field id", value) } e.ID = int(value.Int64) - case episode.FieldSeriesID: + case episode.FieldMediaID: if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field series_id", values[i]) + return fmt.Errorf("unexpected type %T for field media_id", values[i]) } else if value.Valid { - e.SeriesID = int(value.Int64) + e.MediaID = int(value.Int64) } case episode.FieldSeasonNumber: if value, ok := values[i].(*sql.NullInt64); !ok { @@ -150,9 +150,9 @@ func (e *Episode) Value(name string) (ent.Value, error) { return e.selectValues.Get(name) } -// QuerySeries queries the "series" edge of the Episode entity. -func (e *Episode) QuerySeries() *SeriesQuery { - return NewEpisodeClient(e.config).QuerySeries(e) +// QueryMedia queries the "media" edge of the Episode entity. +func (e *Episode) QueryMedia() *MediaQuery { + return NewEpisodeClient(e.config).QueryMedia(e) } // Update returns a builder for updating this Episode. @@ -178,8 +178,8 @@ func (e *Episode) String() string { var builder strings.Builder builder.WriteString("Episode(") builder.WriteString(fmt.Sprintf("id=%v, ", e.ID)) - builder.WriteString("series_id=") - builder.WriteString(fmt.Sprintf("%v", e.SeriesID)) + builder.WriteString("media_id=") + builder.WriteString(fmt.Sprintf("%v", e.MediaID)) builder.WriteString(", ") builder.WriteString("season_number=") builder.WriteString(fmt.Sprintf("%v", e.SeasonNumber)) diff --git a/ent/episode/episode.go b/ent/episode/episode.go index 1e0de93..1c720c9 100644 --- a/ent/episode/episode.go +++ b/ent/episode/episode.go @@ -14,8 +14,8 @@ const ( Label = "episode" // FieldID holds the string denoting the id field in the database. FieldID = "id" - // FieldSeriesID holds the string denoting the series_id field in the database. - FieldSeriesID = "series_id" + // FieldMediaID holds the string denoting the media_id field in the database. + FieldMediaID = "media_id" // FieldSeasonNumber holds the string denoting the season_number field in the database. FieldSeasonNumber = "season_number" // FieldEpisodeNumber holds the string denoting the episode_number field in the database. @@ -30,23 +30,23 @@ const ( FieldStatus = "status" // FieldFileInStorage holds the string denoting the file_in_storage field in the database. FieldFileInStorage = "file_in_storage" - // EdgeSeries holds the string denoting the series edge name in mutations. - EdgeSeries = "series" + // EdgeMedia holds the string denoting the media edge name in mutations. + EdgeMedia = "media" // Table holds the table name of the episode in the database. Table = "episodes" - // SeriesTable is the table that holds the series relation/edge. - SeriesTable = "episodes" - // SeriesInverseTable is the table name for the Series entity. - // It exists in this package in order to avoid circular dependency with the "series" package. - SeriesInverseTable = "series" - // SeriesColumn is the table column denoting the series relation/edge. - SeriesColumn = "series_id" + // MediaTable is the table that holds the media relation/edge. + MediaTable = "episodes" + // MediaInverseTable is the table name for the Media entity. + // It exists in this package in order to avoid circular dependency with the "media" package. + MediaInverseTable = "media" + // MediaColumn is the table column denoting the media relation/edge. + MediaColumn = "media_id" ) // Columns holds all SQL columns for episode fields. var Columns = []string{ FieldID, - FieldSeriesID, + FieldMediaID, FieldSeasonNumber, FieldEpisodeNumber, FieldTitle, @@ -101,9 +101,9 @@ func ByID(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldID, opts...).ToFunc() } -// BySeriesID orders the results by the series_id field. -func BySeriesID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldSeriesID, opts...).ToFunc() +// ByMediaID orders the results by the media_id field. +func ByMediaID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMediaID, opts...).ToFunc() } // BySeasonNumber orders the results by the season_number field. @@ -141,16 +141,16 @@ func ByFileInStorage(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldFileInStorage, opts...).ToFunc() } -// BySeriesField orders the results by series field. -func BySeriesField(field string, opts ...sql.OrderTermOption) OrderOption { +// ByMediaField orders the results by media field. +func ByMediaField(field string, opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newSeriesStep(), sql.OrderByField(field, opts...)) + sqlgraph.OrderByNeighborTerms(s, newMediaStep(), sql.OrderByField(field, opts...)) } } -func newSeriesStep() *sqlgraph.Step { +func newMediaStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.To(SeriesInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, SeriesTable, SeriesColumn), + sqlgraph.To(MediaInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, MediaTable, MediaColumn), ) } diff --git a/ent/episode/where.go b/ent/episode/where.go index 2acf3ef..909de91 100644 --- a/ent/episode/where.go +++ b/ent/episode/where.go @@ -54,9 +54,9 @@ func IDLTE(id int) predicate.Episode { return predicate.Episode(sql.FieldLTE(FieldID, id)) } -// SeriesID applies equality check predicate on the "series_id" field. It's identical to SeriesIDEQ. -func SeriesID(v int) predicate.Episode { - return predicate.Episode(sql.FieldEQ(FieldSeriesID, v)) +// MediaID applies equality check predicate on the "media_id" field. It's identical to MediaIDEQ. +func MediaID(v int) predicate.Episode { + return predicate.Episode(sql.FieldEQ(FieldMediaID, v)) } // SeasonNumber applies equality check predicate on the "season_number" field. It's identical to SeasonNumberEQ. @@ -89,34 +89,34 @@ func FileInStorage(v string) predicate.Episode { return predicate.Episode(sql.FieldEQ(FieldFileInStorage, v)) } -// SeriesIDEQ applies the EQ predicate on the "series_id" field. -func SeriesIDEQ(v int) predicate.Episode { - return predicate.Episode(sql.FieldEQ(FieldSeriesID, v)) +// MediaIDEQ applies the EQ predicate on the "media_id" field. +func MediaIDEQ(v int) predicate.Episode { + return predicate.Episode(sql.FieldEQ(FieldMediaID, v)) } -// SeriesIDNEQ applies the NEQ predicate on the "series_id" field. -func SeriesIDNEQ(v int) predicate.Episode { - return predicate.Episode(sql.FieldNEQ(FieldSeriesID, v)) +// MediaIDNEQ applies the NEQ predicate on the "media_id" field. +func MediaIDNEQ(v int) predicate.Episode { + return predicate.Episode(sql.FieldNEQ(FieldMediaID, v)) } -// SeriesIDIn applies the In predicate on the "series_id" field. -func SeriesIDIn(vs ...int) predicate.Episode { - return predicate.Episode(sql.FieldIn(FieldSeriesID, vs...)) +// MediaIDIn applies the In predicate on the "media_id" field. +func MediaIDIn(vs ...int) predicate.Episode { + return predicate.Episode(sql.FieldIn(FieldMediaID, vs...)) } -// SeriesIDNotIn applies the NotIn predicate on the "series_id" field. -func SeriesIDNotIn(vs ...int) predicate.Episode { - return predicate.Episode(sql.FieldNotIn(FieldSeriesID, vs...)) +// MediaIDNotIn applies the NotIn predicate on the "media_id" field. +func MediaIDNotIn(vs ...int) predicate.Episode { + return predicate.Episode(sql.FieldNotIn(FieldMediaID, vs...)) } -// SeriesIDIsNil applies the IsNil predicate on the "series_id" field. -func SeriesIDIsNil() predicate.Episode { - return predicate.Episode(sql.FieldIsNull(FieldSeriesID)) +// MediaIDIsNil applies the IsNil predicate on the "media_id" field. +func MediaIDIsNil() predicate.Episode { + return predicate.Episode(sql.FieldIsNull(FieldMediaID)) } -// SeriesIDNotNil applies the NotNil predicate on the "series_id" field. -func SeriesIDNotNil() predicate.Episode { - return predicate.Episode(sql.FieldNotNull(FieldSeriesID)) +// MediaIDNotNil applies the NotNil predicate on the "media_id" field. +func MediaIDNotNil() predicate.Episode { + return predicate.Episode(sql.FieldNotNull(FieldMediaID)) } // SeasonNumberEQ applies the EQ predicate on the "season_number" field. @@ -489,21 +489,21 @@ func FileInStorageContainsFold(v string) predicate.Episode { return predicate.Episode(sql.FieldContainsFold(FieldFileInStorage, v)) } -// HasSeries applies the HasEdge predicate on the "series" edge. -func HasSeries() predicate.Episode { +// HasMedia applies the HasEdge predicate on the "media" edge. +func HasMedia() predicate.Episode { return predicate.Episode(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, SeriesTable, SeriesColumn), + sqlgraph.Edge(sqlgraph.M2O, true, MediaTable, MediaColumn), ) sqlgraph.HasNeighbors(s, step) }) } -// HasSeriesWith applies the HasEdge predicate on the "series" edge with a given conditions (other predicates). -func HasSeriesWith(preds ...predicate.Series) predicate.Episode { +// HasMediaWith applies the HasEdge predicate on the "media" edge with a given conditions (other predicates). +func HasMediaWith(preds ...predicate.Media) predicate.Episode { return predicate.Episode(func(s *sql.Selector) { - step := newSeriesStep() + step := newMediaStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) diff --git a/ent/episode_create.go b/ent/episode_create.go index 5aafd7a..28a17bc 100644 --- a/ent/episode_create.go +++ b/ent/episode_create.go @@ -7,7 +7,7 @@ import ( "errors" "fmt" "polaris/ent/episode" - "polaris/ent/series" + "polaris/ent/media" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" @@ -20,16 +20,16 @@ type EpisodeCreate struct { hooks []Hook } -// SetSeriesID sets the "series_id" field. -func (ec *EpisodeCreate) SetSeriesID(i int) *EpisodeCreate { - ec.mutation.SetSeriesID(i) +// SetMediaID sets the "media_id" field. +func (ec *EpisodeCreate) SetMediaID(i int) *EpisodeCreate { + ec.mutation.SetMediaID(i) return ec } -// SetNillableSeriesID sets the "series_id" field if the given value is not nil. -func (ec *EpisodeCreate) SetNillableSeriesID(i *int) *EpisodeCreate { +// SetNillableMediaID sets the "media_id" field if the given value is not nil. +func (ec *EpisodeCreate) SetNillableMediaID(i *int) *EpisodeCreate { if i != nil { - ec.SetSeriesID(*i) + ec.SetMediaID(*i) } return ec } @@ -92,9 +92,9 @@ func (ec *EpisodeCreate) SetNillableFileInStorage(s *string) *EpisodeCreate { return ec } -// SetSeries sets the "series" edge to the Series entity. -func (ec *EpisodeCreate) SetSeries(s *Series) *EpisodeCreate { - return ec.SetSeriesID(s.ID) +// SetMedia sets the "media" edge to the Media entity. +func (ec *EpisodeCreate) SetMedia(m *Media) *EpisodeCreate { + return ec.SetMediaID(m.ID) } // Mutation returns the EpisodeMutation object of the builder. @@ -217,21 +217,21 @@ func (ec *EpisodeCreate) createSpec() (*Episode, *sqlgraph.CreateSpec) { _spec.SetField(episode.FieldFileInStorage, field.TypeString, value) _node.FileInStorage = value } - if nodes := ec.mutation.SeriesIDs(); len(nodes) > 0 { + if nodes := ec.mutation.MediaIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, Inverse: true, - Table: episode.SeriesTable, - Columns: []string{episode.SeriesColumn}, + Table: episode.MediaTable, + Columns: []string{episode.MediaColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt), + IDSpec: sqlgraph.NewFieldSpec(media.FieldID, field.TypeInt), }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } - _node.SeriesID = nodes[0] + _node.MediaID = nodes[0] _spec.Edges = append(_spec.Edges, edge) } return _node, _spec diff --git a/ent/episode_query.go b/ent/episode_query.go index 592a09e..fb003c4 100644 --- a/ent/episode_query.go +++ b/ent/episode_query.go @@ -7,8 +7,8 @@ import ( "fmt" "math" "polaris/ent/episode" + "polaris/ent/media" "polaris/ent/predicate" - "polaris/ent/series" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" @@ -22,7 +22,7 @@ type EpisodeQuery struct { order []episode.OrderOption inters []Interceptor predicates []predicate.Episode - withSeries *SeriesQuery + withMedia *MediaQuery // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -59,9 +59,9 @@ func (eq *EpisodeQuery) Order(o ...episode.OrderOption) *EpisodeQuery { return eq } -// QuerySeries chains the current query on the "series" edge. -func (eq *EpisodeQuery) QuerySeries() *SeriesQuery { - query := (&SeriesClient{config: eq.config}).Query() +// QueryMedia chains the current query on the "media" edge. +func (eq *EpisodeQuery) QueryMedia() *MediaQuery { + query := (&MediaClient{config: eq.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := eq.prepareQuery(ctx); err != nil { return nil, err @@ -72,8 +72,8 @@ func (eq *EpisodeQuery) QuerySeries() *SeriesQuery { } step := sqlgraph.NewStep( sqlgraph.From(episode.Table, episode.FieldID, selector), - sqlgraph.To(series.Table, series.FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, episode.SeriesTable, episode.SeriesColumn), + sqlgraph.To(media.Table, media.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, episode.MediaTable, episode.MediaColumn), ) fromU = sqlgraph.SetNeighbors(eq.driver.Dialect(), step) return fromU, nil @@ -273,21 +273,21 @@ func (eq *EpisodeQuery) Clone() *EpisodeQuery { order: append([]episode.OrderOption{}, eq.order...), inters: append([]Interceptor{}, eq.inters...), predicates: append([]predicate.Episode{}, eq.predicates...), - withSeries: eq.withSeries.Clone(), + withMedia: eq.withMedia.Clone(), // clone intermediate query. sql: eq.sql.Clone(), path: eq.path, } } -// WithSeries tells the query-builder to eager-load the nodes that are connected to -// the "series" edge. The optional arguments are used to configure the query builder of the edge. -func (eq *EpisodeQuery) WithSeries(opts ...func(*SeriesQuery)) *EpisodeQuery { - query := (&SeriesClient{config: eq.config}).Query() +// WithMedia tells the query-builder to eager-load the nodes that are connected to +// the "media" edge. The optional arguments are used to configure the query builder of the edge. +func (eq *EpisodeQuery) WithMedia(opts ...func(*MediaQuery)) *EpisodeQuery { + query := (&MediaClient{config: eq.config}).Query() for _, opt := range opts { opt(query) } - eq.withSeries = query + eq.withMedia = query return eq } @@ -297,12 +297,12 @@ func (eq *EpisodeQuery) WithSeries(opts ...func(*SeriesQuery)) *EpisodeQuery { // Example: // // var v []struct { -// SeriesID int `json:"series_id,omitempty"` +// MediaID int `json:"media_id,omitempty"` // Count int `json:"count,omitempty"` // } // // client.Episode.Query(). -// GroupBy(episode.FieldSeriesID). +// GroupBy(episode.FieldMediaID). // Aggregate(ent.Count()). // Scan(ctx, &v) func (eq *EpisodeQuery) GroupBy(field string, fields ...string) *EpisodeGroupBy { @@ -320,11 +320,11 @@ func (eq *EpisodeQuery) GroupBy(field string, fields ...string) *EpisodeGroupBy // Example: // // var v []struct { -// SeriesID int `json:"series_id,omitempty"` +// MediaID int `json:"media_id,omitempty"` // } // // client.Episode.Query(). -// Select(episode.FieldSeriesID). +// Select(episode.FieldMediaID). // Scan(ctx, &v) func (eq *EpisodeQuery) Select(fields ...string) *EpisodeSelect { eq.ctx.Fields = append(eq.ctx.Fields, fields...) @@ -370,7 +370,7 @@ func (eq *EpisodeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Epis nodes = []*Episode{} _spec = eq.querySpec() loadedTypes = [1]bool{ - eq.withSeries != nil, + eq.withMedia != nil, } ) _spec.ScanValues = func(columns []string) ([]any, error) { @@ -391,20 +391,20 @@ func (eq *EpisodeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Epis if len(nodes) == 0 { return nodes, nil } - if query := eq.withSeries; query != nil { - if err := eq.loadSeries(ctx, query, nodes, nil, - func(n *Episode, e *Series) { n.Edges.Series = e }); err != nil { + if query := eq.withMedia; query != nil { + if err := eq.loadMedia(ctx, query, nodes, nil, + func(n *Episode, e *Media) { n.Edges.Media = e }); err != nil { return nil, err } } return nodes, nil } -func (eq *EpisodeQuery) loadSeries(ctx context.Context, query *SeriesQuery, nodes []*Episode, init func(*Episode), assign func(*Episode, *Series)) error { +func (eq *EpisodeQuery) loadMedia(ctx context.Context, query *MediaQuery, nodes []*Episode, init func(*Episode), assign func(*Episode, *Media)) error { ids := make([]int, 0, len(nodes)) nodeids := make(map[int][]*Episode) for i := range nodes { - fk := nodes[i].SeriesID + fk := nodes[i].MediaID if _, ok := nodeids[fk]; !ok { ids = append(ids, fk) } @@ -413,7 +413,7 @@ func (eq *EpisodeQuery) loadSeries(ctx context.Context, query *SeriesQuery, node if len(ids) == 0 { return nil } - query.Where(series.IDIn(ids...)) + query.Where(media.IDIn(ids...)) neighbors, err := query.All(ctx) if err != nil { return err @@ -421,7 +421,7 @@ func (eq *EpisodeQuery) loadSeries(ctx context.Context, query *SeriesQuery, node for _, n := range neighbors { nodes, ok := nodeids[n.ID] if !ok { - return fmt.Errorf(`unexpected foreign-key "series_id" returned %v`, n.ID) + return fmt.Errorf(`unexpected foreign-key "media_id" returned %v`, n.ID) } for i := range nodes { assign(nodes[i], n) @@ -455,8 +455,8 @@ func (eq *EpisodeQuery) querySpec() *sqlgraph.QuerySpec { _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) } } - if eq.withSeries != nil { - _spec.Node.AddColumnOnce(episode.FieldSeriesID) + if eq.withMedia != nil { + _spec.Node.AddColumnOnce(episode.FieldMediaID) } } if ps := eq.predicates; len(ps) > 0 { diff --git a/ent/episode_update.go b/ent/episode_update.go index 761a025..9899c6c 100644 --- a/ent/episode_update.go +++ b/ent/episode_update.go @@ -7,8 +7,8 @@ import ( "errors" "fmt" "polaris/ent/episode" + "polaris/ent/media" "polaris/ent/predicate" - "polaris/ent/series" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" @@ -28,23 +28,23 @@ func (eu *EpisodeUpdate) Where(ps ...predicate.Episode) *EpisodeUpdate { return eu } -// SetSeriesID sets the "series_id" field. -func (eu *EpisodeUpdate) SetSeriesID(i int) *EpisodeUpdate { - eu.mutation.SetSeriesID(i) +// SetMediaID sets the "media_id" field. +func (eu *EpisodeUpdate) SetMediaID(i int) *EpisodeUpdate { + eu.mutation.SetMediaID(i) return eu } -// SetNillableSeriesID sets the "series_id" field if the given value is not nil. -func (eu *EpisodeUpdate) SetNillableSeriesID(i *int) *EpisodeUpdate { +// SetNillableMediaID sets the "media_id" field if the given value is not nil. +func (eu *EpisodeUpdate) SetNillableMediaID(i *int) *EpisodeUpdate { if i != nil { - eu.SetSeriesID(*i) + eu.SetMediaID(*i) } return eu } -// ClearSeriesID clears the value of the "series_id" field. -func (eu *EpisodeUpdate) ClearSeriesID() *EpisodeUpdate { - eu.mutation.ClearSeriesID() +// ClearMediaID clears the value of the "media_id" field. +func (eu *EpisodeUpdate) ClearMediaID() *EpisodeUpdate { + eu.mutation.ClearMediaID() return eu } @@ -166,9 +166,9 @@ func (eu *EpisodeUpdate) ClearFileInStorage() *EpisodeUpdate { return eu } -// SetSeries sets the "series" edge to the Series entity. -func (eu *EpisodeUpdate) SetSeries(s *Series) *EpisodeUpdate { - return eu.SetSeriesID(s.ID) +// SetMedia sets the "media" edge to the Media entity. +func (eu *EpisodeUpdate) SetMedia(m *Media) *EpisodeUpdate { + return eu.SetMediaID(m.ID) } // Mutation returns the EpisodeMutation object of the builder. @@ -176,9 +176,9 @@ func (eu *EpisodeUpdate) Mutation() *EpisodeMutation { return eu.mutation } -// ClearSeries clears the "series" edge to the Series entity. -func (eu *EpisodeUpdate) ClearSeries() *EpisodeUpdate { - eu.mutation.ClearSeries() +// ClearMedia clears the "media" edge to the Media entity. +func (eu *EpisodeUpdate) ClearMedia() *EpisodeUpdate { + eu.mutation.ClearMedia() return eu } @@ -261,28 +261,28 @@ func (eu *EpisodeUpdate) sqlSave(ctx context.Context) (n int, err error) { if eu.mutation.FileInStorageCleared() { _spec.ClearField(episode.FieldFileInStorage, field.TypeString) } - if eu.mutation.SeriesCleared() { + if eu.mutation.MediaCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, Inverse: true, - Table: episode.SeriesTable, - Columns: []string{episode.SeriesColumn}, + Table: episode.MediaTable, + Columns: []string{episode.MediaColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt), + IDSpec: sqlgraph.NewFieldSpec(media.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } - if nodes := eu.mutation.SeriesIDs(); len(nodes) > 0 { + if nodes := eu.mutation.MediaIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, Inverse: true, - Table: episode.SeriesTable, - Columns: []string{episode.SeriesColumn}, + Table: episode.MediaTable, + Columns: []string{episode.MediaColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt), + IDSpec: sqlgraph.NewFieldSpec(media.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -310,23 +310,23 @@ type EpisodeUpdateOne struct { mutation *EpisodeMutation } -// SetSeriesID sets the "series_id" field. -func (euo *EpisodeUpdateOne) SetSeriesID(i int) *EpisodeUpdateOne { - euo.mutation.SetSeriesID(i) +// SetMediaID sets the "media_id" field. +func (euo *EpisodeUpdateOne) SetMediaID(i int) *EpisodeUpdateOne { + euo.mutation.SetMediaID(i) return euo } -// SetNillableSeriesID sets the "series_id" field if the given value is not nil. -func (euo *EpisodeUpdateOne) SetNillableSeriesID(i *int) *EpisodeUpdateOne { +// SetNillableMediaID sets the "media_id" field if the given value is not nil. +func (euo *EpisodeUpdateOne) SetNillableMediaID(i *int) *EpisodeUpdateOne { if i != nil { - euo.SetSeriesID(*i) + euo.SetMediaID(*i) } return euo } -// ClearSeriesID clears the value of the "series_id" field. -func (euo *EpisodeUpdateOne) ClearSeriesID() *EpisodeUpdateOne { - euo.mutation.ClearSeriesID() +// ClearMediaID clears the value of the "media_id" field. +func (euo *EpisodeUpdateOne) ClearMediaID() *EpisodeUpdateOne { + euo.mutation.ClearMediaID() return euo } @@ -448,9 +448,9 @@ func (euo *EpisodeUpdateOne) ClearFileInStorage() *EpisodeUpdateOne { return euo } -// SetSeries sets the "series" edge to the Series entity. -func (euo *EpisodeUpdateOne) SetSeries(s *Series) *EpisodeUpdateOne { - return euo.SetSeriesID(s.ID) +// SetMedia sets the "media" edge to the Media entity. +func (euo *EpisodeUpdateOne) SetMedia(m *Media) *EpisodeUpdateOne { + return euo.SetMediaID(m.ID) } // Mutation returns the EpisodeMutation object of the builder. @@ -458,9 +458,9 @@ func (euo *EpisodeUpdateOne) Mutation() *EpisodeMutation { return euo.mutation } -// ClearSeries clears the "series" edge to the Series entity. -func (euo *EpisodeUpdateOne) ClearSeries() *EpisodeUpdateOne { - euo.mutation.ClearSeries() +// ClearMedia clears the "media" edge to the Media entity. +func (euo *EpisodeUpdateOne) ClearMedia() *EpisodeUpdateOne { + euo.mutation.ClearMedia() return euo } @@ -573,28 +573,28 @@ func (euo *EpisodeUpdateOne) sqlSave(ctx context.Context) (_node *Episode, err e if euo.mutation.FileInStorageCleared() { _spec.ClearField(episode.FieldFileInStorage, field.TypeString) } - if euo.mutation.SeriesCleared() { + if euo.mutation.MediaCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, Inverse: true, - Table: episode.SeriesTable, - Columns: []string{episode.SeriesColumn}, + Table: episode.MediaTable, + Columns: []string{episode.MediaColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt), + IDSpec: sqlgraph.NewFieldSpec(media.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } - if nodes := euo.mutation.SeriesIDs(); len(nodes) > 0 { + if nodes := euo.mutation.MediaIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, Inverse: true, - Table: episode.SeriesTable, - Columns: []string{episode.SeriesColumn}, + Table: episode.MediaTable, + Columns: []string{episode.MediaColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt), + IDSpec: sqlgraph.NewFieldSpec(media.FieldID, field.TypeInt), }, } for _, k := range nodes { diff --git a/ent/history.go b/ent/history.go index c71a591..1746587 100644 --- a/ent/history.go +++ b/ent/history.go @@ -17,8 +17,8 @@ type History struct { config `json:"-"` // ID of the ent. ID int `json:"id,omitempty"` - // SeriesID holds the value of the "series_id" field. - SeriesID int `json:"series_id,omitempty"` + // MediaID holds the value of the "media_id" field. + MediaID int `json:"media_id,omitempty"` // EpisodeID holds the value of the "episode_id" field. EpisodeID int `json:"episode_id,omitempty"` // SourceTitle holds the value of the "source_title" field. @@ -41,7 +41,7 @@ func (*History) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) for i := range columns { switch columns[i] { - case history.FieldID, history.FieldSeriesID, history.FieldEpisodeID, history.FieldSize: + case history.FieldID, history.FieldMediaID, history.FieldEpisodeID, history.FieldSize: values[i] = new(sql.NullInt64) case history.FieldSourceTitle, history.FieldTargetDir, history.FieldStatus, history.FieldSaved: values[i] = new(sql.NullString) @@ -68,11 +68,11 @@ func (h *History) assignValues(columns []string, values []any) error { return fmt.Errorf("unexpected type %T for field id", value) } h.ID = int(value.Int64) - case history.FieldSeriesID: + case history.FieldMediaID: if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field series_id", values[i]) + return fmt.Errorf("unexpected type %T for field media_id", values[i]) } else if value.Valid { - h.SeriesID = int(value.Int64) + h.MediaID = int(value.Int64) } case history.FieldEpisodeID: if value, ok := values[i].(*sql.NullInt64); !ok { @@ -152,8 +152,8 @@ func (h *History) String() string { var builder strings.Builder builder.WriteString("History(") builder.WriteString(fmt.Sprintf("id=%v, ", h.ID)) - builder.WriteString("series_id=") - builder.WriteString(fmt.Sprintf("%v", h.SeriesID)) + builder.WriteString("media_id=") + builder.WriteString(fmt.Sprintf("%v", h.MediaID)) builder.WriteString(", ") builder.WriteString("episode_id=") builder.WriteString(fmt.Sprintf("%v", h.EpisodeID)) diff --git a/ent/history/history.go b/ent/history/history.go index 76f9941..e386b85 100644 --- a/ent/history/history.go +++ b/ent/history/history.go @@ -13,8 +13,8 @@ const ( Label = "history" // FieldID holds the string denoting the id field in the database. FieldID = "id" - // FieldSeriesID holds the string denoting the series_id field in the database. - FieldSeriesID = "series_id" + // FieldMediaID holds the string denoting the media_id field in the database. + FieldMediaID = "media_id" // FieldEpisodeID holds the string denoting the episode_id field in the database. FieldEpisodeID = "episode_id" // FieldSourceTitle holds the string denoting the source_title field in the database. @@ -36,7 +36,7 @@ const ( // Columns holds all SQL columns for history fields. var Columns = []string{ FieldID, - FieldSeriesID, + FieldMediaID, FieldEpisodeID, FieldSourceTitle, FieldDate, @@ -94,9 +94,9 @@ func ByID(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldID, opts...).ToFunc() } -// BySeriesID orders the results by the series_id field. -func BySeriesID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldSeriesID, opts...).ToFunc() +// ByMediaID orders the results by the media_id field. +func ByMediaID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMediaID, opts...).ToFunc() } // ByEpisodeID orders the results by the episode_id field. diff --git a/ent/history/where.go b/ent/history/where.go index c4d6d06..fce2c37 100644 --- a/ent/history/where.go +++ b/ent/history/where.go @@ -54,9 +54,9 @@ func IDLTE(id int) predicate.History { return predicate.History(sql.FieldLTE(FieldID, id)) } -// SeriesID applies equality check predicate on the "series_id" field. It's identical to SeriesIDEQ. -func SeriesID(v int) predicate.History { - return predicate.History(sql.FieldEQ(FieldSeriesID, v)) +// MediaID applies equality check predicate on the "media_id" field. It's identical to MediaIDEQ. +func MediaID(v int) predicate.History { + return predicate.History(sql.FieldEQ(FieldMediaID, v)) } // EpisodeID applies equality check predicate on the "episode_id" field. It's identical to EpisodeIDEQ. @@ -89,44 +89,44 @@ func Saved(v string) predicate.History { return predicate.History(sql.FieldEQ(FieldSaved, v)) } -// SeriesIDEQ applies the EQ predicate on the "series_id" field. -func SeriesIDEQ(v int) predicate.History { - return predicate.History(sql.FieldEQ(FieldSeriesID, v)) +// MediaIDEQ applies the EQ predicate on the "media_id" field. +func MediaIDEQ(v int) predicate.History { + return predicate.History(sql.FieldEQ(FieldMediaID, v)) } -// SeriesIDNEQ applies the NEQ predicate on the "series_id" field. -func SeriesIDNEQ(v int) predicate.History { - return predicate.History(sql.FieldNEQ(FieldSeriesID, v)) +// MediaIDNEQ applies the NEQ predicate on the "media_id" field. +func MediaIDNEQ(v int) predicate.History { + return predicate.History(sql.FieldNEQ(FieldMediaID, v)) } -// SeriesIDIn applies the In predicate on the "series_id" field. -func SeriesIDIn(vs ...int) predicate.History { - return predicate.History(sql.FieldIn(FieldSeriesID, vs...)) +// MediaIDIn applies the In predicate on the "media_id" field. +func MediaIDIn(vs ...int) predicate.History { + return predicate.History(sql.FieldIn(FieldMediaID, vs...)) } -// SeriesIDNotIn applies the NotIn predicate on the "series_id" field. -func SeriesIDNotIn(vs ...int) predicate.History { - return predicate.History(sql.FieldNotIn(FieldSeriesID, vs...)) +// MediaIDNotIn applies the NotIn predicate on the "media_id" field. +func MediaIDNotIn(vs ...int) predicate.History { + return predicate.History(sql.FieldNotIn(FieldMediaID, vs...)) } -// SeriesIDGT applies the GT predicate on the "series_id" field. -func SeriesIDGT(v int) predicate.History { - return predicate.History(sql.FieldGT(FieldSeriesID, v)) +// MediaIDGT applies the GT predicate on the "media_id" field. +func MediaIDGT(v int) predicate.History { + return predicate.History(sql.FieldGT(FieldMediaID, v)) } -// SeriesIDGTE applies the GTE predicate on the "series_id" field. -func SeriesIDGTE(v int) predicate.History { - return predicate.History(sql.FieldGTE(FieldSeriesID, v)) +// MediaIDGTE applies the GTE predicate on the "media_id" field. +func MediaIDGTE(v int) predicate.History { + return predicate.History(sql.FieldGTE(FieldMediaID, v)) } -// SeriesIDLT applies the LT predicate on the "series_id" field. -func SeriesIDLT(v int) predicate.History { - return predicate.History(sql.FieldLT(FieldSeriesID, v)) +// MediaIDLT applies the LT predicate on the "media_id" field. +func MediaIDLT(v int) predicate.History { + return predicate.History(sql.FieldLT(FieldMediaID, v)) } -// SeriesIDLTE applies the LTE predicate on the "series_id" field. -func SeriesIDLTE(v int) predicate.History { - return predicate.History(sql.FieldLTE(FieldSeriesID, v)) +// MediaIDLTE applies the LTE predicate on the "media_id" field. +func MediaIDLTE(v int) predicate.History { + return predicate.History(sql.FieldLTE(FieldMediaID, v)) } // EpisodeIDEQ applies the EQ predicate on the "episode_id" field. diff --git a/ent/history_create.go b/ent/history_create.go index d9232cf..128b6d7 100644 --- a/ent/history_create.go +++ b/ent/history_create.go @@ -20,9 +20,9 @@ type HistoryCreate struct { hooks []Hook } -// SetSeriesID sets the "series_id" field. -func (hc *HistoryCreate) SetSeriesID(i int) *HistoryCreate { - hc.mutation.SetSeriesID(i) +// SetMediaID sets the "media_id" field. +func (hc *HistoryCreate) SetMediaID(i int) *HistoryCreate { + hc.mutation.SetMediaID(i) return hc } @@ -127,8 +127,8 @@ func (hc *HistoryCreate) defaults() { // check runs all checks and user-defined validators on the builder. func (hc *HistoryCreate) check() error { - if _, ok := hc.mutation.SeriesID(); !ok { - return &ValidationError{Name: "series_id", err: errors.New(`ent: missing required field "History.series_id"`)} + if _, ok := hc.mutation.MediaID(); !ok { + return &ValidationError{Name: "media_id", err: errors.New(`ent: missing required field "History.media_id"`)} } if _, ok := hc.mutation.EpisodeID(); !ok { return &ValidationError{Name: "episode_id", err: errors.New(`ent: missing required field "History.episode_id"`)} @@ -179,9 +179,9 @@ func (hc *HistoryCreate) createSpec() (*History, *sqlgraph.CreateSpec) { _node = &History{config: hc.config} _spec = sqlgraph.NewCreateSpec(history.Table, sqlgraph.NewFieldSpec(history.FieldID, field.TypeInt)) ) - if value, ok := hc.mutation.SeriesID(); ok { - _spec.SetField(history.FieldSeriesID, field.TypeInt, value) - _node.SeriesID = value + if value, ok := hc.mutation.MediaID(); ok { + _spec.SetField(history.FieldMediaID, field.TypeInt, value) + _node.MediaID = value } if value, ok := hc.mutation.EpisodeID(); ok { _spec.SetField(history.FieldEpisodeID, field.TypeInt, value) diff --git a/ent/history_query.go b/ent/history_query.go index dbf1edc..0cbb1df 100644 --- a/ent/history_query.go +++ b/ent/history_query.go @@ -261,12 +261,12 @@ func (hq *HistoryQuery) Clone() *HistoryQuery { // Example: // // var v []struct { -// SeriesID int `json:"series_id,omitempty"` +// MediaID int `json:"media_id,omitempty"` // Count int `json:"count,omitempty"` // } // // client.History.Query(). -// GroupBy(history.FieldSeriesID). +// GroupBy(history.FieldMediaID). // Aggregate(ent.Count()). // Scan(ctx, &v) func (hq *HistoryQuery) GroupBy(field string, fields ...string) *HistoryGroupBy { @@ -284,11 +284,11 @@ func (hq *HistoryQuery) GroupBy(field string, fields ...string) *HistoryGroupBy // Example: // // var v []struct { -// SeriesID int `json:"series_id,omitempty"` +// MediaID int `json:"media_id,omitempty"` // } // // client.History.Query(). -// Select(history.FieldSeriesID). +// Select(history.FieldMediaID). // Scan(ctx, &v) func (hq *HistoryQuery) Select(fields ...string) *HistorySelect { hq.ctx.Fields = append(hq.ctx.Fields, fields...) diff --git a/ent/history_update.go b/ent/history_update.go index 2774b94..223034a 100644 --- a/ent/history_update.go +++ b/ent/history_update.go @@ -28,24 +28,24 @@ func (hu *HistoryUpdate) Where(ps ...predicate.History) *HistoryUpdate { return hu } -// SetSeriesID sets the "series_id" field. -func (hu *HistoryUpdate) SetSeriesID(i int) *HistoryUpdate { - hu.mutation.ResetSeriesID() - hu.mutation.SetSeriesID(i) +// SetMediaID sets the "media_id" field. +func (hu *HistoryUpdate) SetMediaID(i int) *HistoryUpdate { + hu.mutation.ResetMediaID() + hu.mutation.SetMediaID(i) return hu } -// SetNillableSeriesID sets the "series_id" field if the given value is not nil. -func (hu *HistoryUpdate) SetNillableSeriesID(i *int) *HistoryUpdate { +// SetNillableMediaID sets the "media_id" field if the given value is not nil. +func (hu *HistoryUpdate) SetNillableMediaID(i *int) *HistoryUpdate { if i != nil { - hu.SetSeriesID(*i) + hu.SetMediaID(*i) } return hu } -// AddSeriesID adds i to the "series_id" field. -func (hu *HistoryUpdate) AddSeriesID(i int) *HistoryUpdate { - hu.mutation.AddSeriesID(i) +// AddMediaID adds i to the "media_id" field. +func (hu *HistoryUpdate) AddMediaID(i int) *HistoryUpdate { + hu.mutation.AddMediaID(i) return hu } @@ -221,11 +221,11 @@ func (hu *HistoryUpdate) sqlSave(ctx context.Context) (n int, err error) { } } } - if value, ok := hu.mutation.SeriesID(); ok { - _spec.SetField(history.FieldSeriesID, field.TypeInt, value) + if value, ok := hu.mutation.MediaID(); ok { + _spec.SetField(history.FieldMediaID, field.TypeInt, value) } - if value, ok := hu.mutation.AddedSeriesID(); ok { - _spec.AddField(history.FieldSeriesID, field.TypeInt, value) + if value, ok := hu.mutation.AddedMediaID(); ok { + _spec.AddField(history.FieldMediaID, field.TypeInt, value) } if value, ok := hu.mutation.EpisodeID(); ok { _spec.SetField(history.FieldEpisodeID, field.TypeInt, value) @@ -277,24 +277,24 @@ type HistoryUpdateOne struct { mutation *HistoryMutation } -// SetSeriesID sets the "series_id" field. -func (huo *HistoryUpdateOne) SetSeriesID(i int) *HistoryUpdateOne { - huo.mutation.ResetSeriesID() - huo.mutation.SetSeriesID(i) +// SetMediaID sets the "media_id" field. +func (huo *HistoryUpdateOne) SetMediaID(i int) *HistoryUpdateOne { + huo.mutation.ResetMediaID() + huo.mutation.SetMediaID(i) return huo } -// SetNillableSeriesID sets the "series_id" field if the given value is not nil. -func (huo *HistoryUpdateOne) SetNillableSeriesID(i *int) *HistoryUpdateOne { +// SetNillableMediaID sets the "media_id" field if the given value is not nil. +func (huo *HistoryUpdateOne) SetNillableMediaID(i *int) *HistoryUpdateOne { if i != nil { - huo.SetSeriesID(*i) + huo.SetMediaID(*i) } return huo } -// AddSeriesID adds i to the "series_id" field. -func (huo *HistoryUpdateOne) AddSeriesID(i int) *HistoryUpdateOne { - huo.mutation.AddSeriesID(i) +// AddMediaID adds i to the "media_id" field. +func (huo *HistoryUpdateOne) AddMediaID(i int) *HistoryUpdateOne { + huo.mutation.AddMediaID(i) return huo } @@ -500,11 +500,11 @@ func (huo *HistoryUpdateOne) sqlSave(ctx context.Context) (_node *History, err e } } } - if value, ok := huo.mutation.SeriesID(); ok { - _spec.SetField(history.FieldSeriesID, field.TypeInt, value) + if value, ok := huo.mutation.MediaID(); ok { + _spec.SetField(history.FieldMediaID, field.TypeInt, value) } - if value, ok := huo.mutation.AddedSeriesID(); ok { - _spec.AddField(history.FieldSeriesID, field.TypeInt, value) + if value, ok := huo.mutation.AddedMediaID(); ok { + _spec.AddField(history.FieldMediaID, field.TypeInt, value) } if value, ok := huo.mutation.EpisodeID(); ok { _spec.SetField(history.FieldEpisodeID, field.TypeInt, value) diff --git a/ent/hook/hook.go b/ent/hook/hook.go index bccf2a8..8b5ad13 100644 --- a/ent/hook/hook.go +++ b/ent/hook/hook.go @@ -56,16 +56,16 @@ func (f IndexersFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, er return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.IndexersMutation", m) } -// The SeriesFunc type is an adapter to allow the use of ordinary -// function as Series mutator. -type SeriesFunc func(context.Context, *ent.SeriesMutation) (ent.Value, error) +// The MediaFunc type is an adapter to allow the use of ordinary +// function as Media mutator. +type MediaFunc func(context.Context, *ent.MediaMutation) (ent.Value, error) // Mutate calls f(ctx, m). -func (f SeriesFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - if mv, ok := m.(*ent.SeriesMutation); ok { +func (f MediaFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.MediaMutation); ok { return f(ctx, mv) } - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SeriesMutation", m) + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.MediaMutation", m) } // The SettingsFunc type is an adapter to allow the use of ordinary diff --git a/ent/series.go b/ent/media.go similarity index 62% rename from ent/series.go rename to ent/media.go index 6c06f3b..5b93b57 100644 --- a/ent/series.go +++ b/ent/media.go @@ -4,7 +4,7 @@ package ent import ( "fmt" - "polaris/ent/series" + "polaris/ent/media" "strings" "time" @@ -12,8 +12,8 @@ import ( "entgo.io/ent/dialect/sql" ) -// Series is the model entity for the Series schema. -type Series struct { +// Media is the model entity for the Media schema. +type Media struct { config `json:"-"` // ID of the ent. ID int `json:"id,omitempty"` @@ -21,6 +21,8 @@ type Series struct { TmdbID int `json:"tmdb_id,omitempty"` // ImdbID holds the value of the "imdb_id" field. ImdbID string `json:"imdb_id,omitempty"` + // MediaType holds the value of the "media_type" field. + MediaType media.MediaType `json:"media_type,omitempty"` // NameCn holds the value of the "name_cn" field. NameCn string `json:"name_cn,omitempty"` // NameEn holds the value of the "name_en" field. @@ -29,8 +31,6 @@ type Series struct { OriginalName string `json:"original_name,omitempty"` // Overview holds the value of the "overview" field. Overview string `json:"overview,omitempty"` - // PosterPath holds the value of the "poster_path" field. - PosterPath string `json:"poster_path,omitempty"` // CreatedAt holds the value of the "created_at" field. CreatedAt time.Time `json:"created_at,omitempty"` // AirDate holds the value of the "air_date" field. @@ -42,13 +42,13 @@ type Series struct { // TargetDir holds the value of the "target_dir" field. TargetDir string `json:"target_dir,omitempty"` // Edges holds the relations/edges for other nodes in the graph. - // The values are being populated by the SeriesQuery when eager-loading is set. - Edges SeriesEdges `json:"edges"` + // The values are being populated by the MediaQuery when eager-loading is set. + Edges MediaEdges `json:"edges"` selectValues sql.SelectValues } -// SeriesEdges holds the relations/edges for other nodes in the graph. -type SeriesEdges struct { +// MediaEdges holds the relations/edges for other nodes in the graph. +type MediaEdges struct { // Episodes holds the value of the episodes edge. Episodes []*Episode `json:"episodes,omitempty"` // loadedTypes holds the information for reporting if a @@ -58,7 +58,7 @@ type SeriesEdges struct { // EpisodesOrErr returns the Episodes value or an error if the edge // was not loaded in eager-loading. -func (e SeriesEdges) EpisodesOrErr() ([]*Episode, error) { +func (e MediaEdges) EpisodesOrErr() ([]*Episode, error) { if e.loadedTypes[0] { return e.Episodes, nil } @@ -66,15 +66,15 @@ func (e SeriesEdges) EpisodesOrErr() ([]*Episode, error) { } // scanValues returns the types for scanning values from sql.Rows. -func (*Series) scanValues(columns []string) ([]any, error) { +func (*Media) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) for i := range columns { switch columns[i] { - case series.FieldID, series.FieldTmdbID, series.FieldStorageID: + case media.FieldID, media.FieldTmdbID, media.FieldStorageID: values[i] = new(sql.NullInt64) - case series.FieldImdbID, series.FieldNameCn, series.FieldNameEn, series.FieldOriginalName, series.FieldOverview, series.FieldPosterPath, series.FieldAirDate, series.FieldResolution, series.FieldTargetDir: + case media.FieldImdbID, media.FieldMediaType, media.FieldNameCn, media.FieldNameEn, media.FieldOriginalName, media.FieldOverview, media.FieldAirDate, media.FieldResolution, media.FieldTargetDir: values[i] = new(sql.NullString) - case series.FieldCreatedAt: + case media.FieldCreatedAt: values[i] = new(sql.NullTime) default: values[i] = new(sql.UnknownType) @@ -84,170 +84,170 @@ func (*Series) scanValues(columns []string) ([]any, error) { } // assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the Series fields. -func (s *Series) assignValues(columns []string, values []any) error { +// to the Media fields. +func (m *Media) assignValues(columns []string, values []any) error { if m, n := len(values), len(columns); m < n { return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) } for i := range columns { switch columns[i] { - case series.FieldID: + case media.FieldID: value, ok := values[i].(*sql.NullInt64) if !ok { return fmt.Errorf("unexpected type %T for field id", value) } - s.ID = int(value.Int64) - case series.FieldTmdbID: + m.ID = int(value.Int64) + case media.FieldTmdbID: if value, ok := values[i].(*sql.NullInt64); !ok { return fmt.Errorf("unexpected type %T for field tmdb_id", values[i]) } else if value.Valid { - s.TmdbID = int(value.Int64) + m.TmdbID = int(value.Int64) } - case series.FieldImdbID: + case media.FieldImdbID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field imdb_id", values[i]) } else if value.Valid { - s.ImdbID = value.String + m.ImdbID = value.String } - case series.FieldNameCn: + case media.FieldMediaType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field media_type", values[i]) + } else if value.Valid { + m.MediaType = media.MediaType(value.String) + } + case media.FieldNameCn: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field name_cn", values[i]) } else if value.Valid { - s.NameCn = value.String + m.NameCn = value.String } - case series.FieldNameEn: + case media.FieldNameEn: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field name_en", values[i]) } else if value.Valid { - s.NameEn = value.String + m.NameEn = value.String } - case series.FieldOriginalName: + case media.FieldOriginalName: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field original_name", values[i]) } else if value.Valid { - s.OriginalName = value.String + m.OriginalName = value.String } - case series.FieldOverview: + case media.FieldOverview: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field overview", values[i]) } else if value.Valid { - s.Overview = value.String + m.Overview = value.String } - case series.FieldPosterPath: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field poster_path", values[i]) - } else if value.Valid { - s.PosterPath = value.String - } - case series.FieldCreatedAt: + case media.FieldCreatedAt: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field created_at", values[i]) } else if value.Valid { - s.CreatedAt = value.Time + m.CreatedAt = value.Time } - case series.FieldAirDate: + case media.FieldAirDate: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field air_date", values[i]) } else if value.Valid { - s.AirDate = value.String + m.AirDate = value.String } - case series.FieldResolution: + case media.FieldResolution: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field resolution", values[i]) } else if value.Valid { - s.Resolution = value.String + m.Resolution = value.String } - case series.FieldStorageID: + case media.FieldStorageID: if value, ok := values[i].(*sql.NullInt64); !ok { return fmt.Errorf("unexpected type %T for field storage_id", values[i]) } else if value.Valid { - s.StorageID = int(value.Int64) + m.StorageID = int(value.Int64) } - case series.FieldTargetDir: + case media.FieldTargetDir: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field target_dir", values[i]) } else if value.Valid { - s.TargetDir = value.String + m.TargetDir = value.String } default: - s.selectValues.Set(columns[i], values[i]) + m.selectValues.Set(columns[i], values[i]) } } return nil } -// Value returns the ent.Value that was dynamically selected and assigned to the Series. +// Value returns the ent.Value that was dynamically selected and assigned to the Media. // This includes values selected through modifiers, order, etc. -func (s *Series) Value(name string) (ent.Value, error) { - return s.selectValues.Get(name) +func (m *Media) Value(name string) (ent.Value, error) { + return m.selectValues.Get(name) } -// QueryEpisodes queries the "episodes" edge of the Series entity. -func (s *Series) QueryEpisodes() *EpisodeQuery { - return NewSeriesClient(s.config).QueryEpisodes(s) +// QueryEpisodes queries the "episodes" edge of the Media entity. +func (m *Media) QueryEpisodes() *EpisodeQuery { + return NewMediaClient(m.config).QueryEpisodes(m) } -// Update returns a builder for updating this Series. -// Note that you need to call Series.Unwrap() before calling this method if this Series +// Update returns a builder for updating this Media. +// Note that you need to call Media.Unwrap() before calling this method if this Media // was returned from a transaction, and the transaction was committed or rolled back. -func (s *Series) Update() *SeriesUpdateOne { - return NewSeriesClient(s.config).UpdateOne(s) +func (m *Media) Update() *MediaUpdateOne { + return NewMediaClient(m.config).UpdateOne(m) } -// Unwrap unwraps the Series entity that was returned from a transaction after it was closed, +// Unwrap unwraps the Media entity that was returned from a transaction after it was closed, // so that all future queries will be executed through the driver which created the transaction. -func (s *Series) Unwrap() *Series { - _tx, ok := s.config.driver.(*txDriver) +func (m *Media) Unwrap() *Media { + _tx, ok := m.config.driver.(*txDriver) if !ok { - panic("ent: Series is not a transactional entity") + panic("ent: Media is not a transactional entity") } - s.config.driver = _tx.drv - return s + m.config.driver = _tx.drv + return m } // String implements the fmt.Stringer. -func (s *Series) String() string { +func (m *Media) String() string { var builder strings.Builder - builder.WriteString("Series(") - builder.WriteString(fmt.Sprintf("id=%v, ", s.ID)) + builder.WriteString("Media(") + builder.WriteString(fmt.Sprintf("id=%v, ", m.ID)) builder.WriteString("tmdb_id=") - builder.WriteString(fmt.Sprintf("%v", s.TmdbID)) + builder.WriteString(fmt.Sprintf("%v", m.TmdbID)) builder.WriteString(", ") builder.WriteString("imdb_id=") - builder.WriteString(s.ImdbID) + builder.WriteString(m.ImdbID) + builder.WriteString(", ") + builder.WriteString("media_type=") + builder.WriteString(fmt.Sprintf("%v", m.MediaType)) builder.WriteString(", ") builder.WriteString("name_cn=") - builder.WriteString(s.NameCn) + builder.WriteString(m.NameCn) builder.WriteString(", ") builder.WriteString("name_en=") - builder.WriteString(s.NameEn) + builder.WriteString(m.NameEn) builder.WriteString(", ") builder.WriteString("original_name=") - builder.WriteString(s.OriginalName) + builder.WriteString(m.OriginalName) builder.WriteString(", ") builder.WriteString("overview=") - builder.WriteString(s.Overview) - builder.WriteString(", ") - builder.WriteString("poster_path=") - builder.WriteString(s.PosterPath) + builder.WriteString(m.Overview) builder.WriteString(", ") builder.WriteString("created_at=") - builder.WriteString(s.CreatedAt.Format(time.ANSIC)) + builder.WriteString(m.CreatedAt.Format(time.ANSIC)) builder.WriteString(", ") builder.WriteString("air_date=") - builder.WriteString(s.AirDate) + builder.WriteString(m.AirDate) builder.WriteString(", ") builder.WriteString("resolution=") - builder.WriteString(s.Resolution) + builder.WriteString(m.Resolution) builder.WriteString(", ") builder.WriteString("storage_id=") - builder.WriteString(fmt.Sprintf("%v", s.StorageID)) + builder.WriteString(fmt.Sprintf("%v", m.StorageID)) builder.WriteString(", ") builder.WriteString("target_dir=") - builder.WriteString(s.TargetDir) + builder.WriteString(m.TargetDir) builder.WriteByte(')') return builder.String() } -// SeriesSlice is a parsable slice of Series. -type SeriesSlice []*Series +// MediaSlice is a parsable slice of Media. +type MediaSlice []*Media diff --git a/ent/series/series.go b/ent/media/media.go similarity index 81% rename from ent/series/series.go rename to ent/media/media.go index 2a9c2aa..c2f65d3 100644 --- a/ent/series/series.go +++ b/ent/media/media.go @@ -1,8 +1,9 @@ // Code generated by ent, DO NOT EDIT. -package series +package media import ( + "fmt" "time" "entgo.io/ent/dialect/sql" @@ -10,14 +11,16 @@ import ( ) const ( - // Label holds the string label denoting the series type in the database. - Label = "series" + // Label holds the string label denoting the media type in the database. + Label = "media" // FieldID holds the string denoting the id field in the database. FieldID = "id" // FieldTmdbID holds the string denoting the tmdb_id field in the database. FieldTmdbID = "tmdb_id" // FieldImdbID holds the string denoting the imdb_id field in the database. FieldImdbID = "imdb_id" + // FieldMediaType holds the string denoting the media_type field in the database. + FieldMediaType = "media_type" // FieldNameCn holds the string denoting the name_cn field in the database. FieldNameCn = "name_cn" // FieldNameEn holds the string denoting the name_en field in the database. @@ -26,8 +29,6 @@ const ( FieldOriginalName = "original_name" // FieldOverview holds the string denoting the overview field in the database. FieldOverview = "overview" - // FieldPosterPath holds the string denoting the poster_path field in the database. - FieldPosterPath = "poster_path" // FieldCreatedAt holds the string denoting the created_at field in the database. FieldCreatedAt = "created_at" // FieldAirDate holds the string denoting the air_date field in the database. @@ -40,27 +41,27 @@ const ( FieldTargetDir = "target_dir" // EdgeEpisodes holds the string denoting the episodes edge name in mutations. EdgeEpisodes = "episodes" - // Table holds the table name of the series in the database. - Table = "series" + // Table holds the table name of the media in the database. + Table = "media" // EpisodesTable is the table that holds the episodes relation/edge. EpisodesTable = "episodes" // EpisodesInverseTable is the table name for the Episode entity. // It exists in this package in order to avoid circular dependency with the "episode" package. EpisodesInverseTable = "episodes" // EpisodesColumn is the table column denoting the episodes relation/edge. - EpisodesColumn = "series_id" + EpisodesColumn = "media_id" ) -// Columns holds all SQL columns for series fields. +// Columns holds all SQL columns for media fields. var Columns = []string{ FieldID, FieldTmdbID, FieldImdbID, + FieldMediaType, FieldNameCn, FieldNameEn, FieldOriginalName, FieldOverview, - FieldPosterPath, FieldCreatedAt, FieldAirDate, FieldResolution, @@ -87,7 +88,30 @@ var ( DefaultResolution string ) -// OrderOption defines the ordering options for the Series queries. +// MediaType defines the type for the "media_type" enum field. +type MediaType string + +// MediaType values. +const ( + MediaTypeTv MediaType = "tv" + MediaTypeMovie MediaType = "movie" +) + +func (mt MediaType) String() string { + return string(mt) +} + +// MediaTypeValidator is a validator for the "media_type" field enum values. It is called by the builders before save. +func MediaTypeValidator(mt MediaType) error { + switch mt { + case MediaTypeTv, MediaTypeMovie: + return nil + default: + return fmt.Errorf("media: invalid enum value for media_type field: %q", mt) + } +} + +// OrderOption defines the ordering options for the Media queries. type OrderOption func(*sql.Selector) // ByID orders the results by the id field. @@ -105,6 +129,11 @@ func ByImdbID(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldImdbID, opts...).ToFunc() } +// ByMediaType orders the results by the media_type field. +func ByMediaType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMediaType, opts...).ToFunc() +} + // ByNameCn orders the results by the name_cn field. func ByNameCn(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldNameCn, opts...).ToFunc() @@ -125,11 +154,6 @@ func ByOverview(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldOverview, opts...).ToFunc() } -// ByPosterPath orders the results by the poster_path field. -func ByPosterPath(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldPosterPath, opts...).ToFunc() -} - // ByCreatedAt orders the results by the created_at field. func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() diff --git a/ent/media/where.go b/ent/media/where.go new file mode 100644 index 0000000..13540cb --- /dev/null +++ b/ent/media/where.go @@ -0,0 +1,839 @@ +// Code generated by ent, DO NOT EDIT. + +package media + +import ( + "polaris/ent/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Media { + return predicate.Media(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Media { + return predicate.Media(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Media { + return predicate.Media(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Media { + return predicate.Media(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Media { + return predicate.Media(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Media { + return predicate.Media(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Media { + return predicate.Media(sql.FieldLTE(FieldID, id)) +} + +// TmdbID applies equality check predicate on the "tmdb_id" field. It's identical to TmdbIDEQ. +func TmdbID(v int) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldTmdbID, v)) +} + +// ImdbID applies equality check predicate on the "imdb_id" field. It's identical to ImdbIDEQ. +func ImdbID(v string) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldImdbID, v)) +} + +// NameCn applies equality check predicate on the "name_cn" field. It's identical to NameCnEQ. +func NameCn(v string) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldNameCn, v)) +} + +// NameEn applies equality check predicate on the "name_en" field. It's identical to NameEnEQ. +func NameEn(v string) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldNameEn, v)) +} + +// OriginalName applies equality check predicate on the "original_name" field. It's identical to OriginalNameEQ. +func OriginalName(v string) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldOriginalName, v)) +} + +// Overview applies equality check predicate on the "overview" field. It's identical to OverviewEQ. +func Overview(v string) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldOverview, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldCreatedAt, v)) +} + +// AirDate applies equality check predicate on the "air_date" field. It's identical to AirDateEQ. +func AirDate(v string) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldAirDate, v)) +} + +// Resolution applies equality check predicate on the "resolution" field. It's identical to ResolutionEQ. +func Resolution(v string) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldResolution, v)) +} + +// StorageID applies equality check predicate on the "storage_id" field. It's identical to StorageIDEQ. +func StorageID(v int) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldStorageID, v)) +} + +// TargetDir applies equality check predicate on the "target_dir" field. It's identical to TargetDirEQ. +func TargetDir(v string) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldTargetDir, v)) +} + +// TmdbIDEQ applies the EQ predicate on the "tmdb_id" field. +func TmdbIDEQ(v int) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldTmdbID, v)) +} + +// TmdbIDNEQ applies the NEQ predicate on the "tmdb_id" field. +func TmdbIDNEQ(v int) predicate.Media { + return predicate.Media(sql.FieldNEQ(FieldTmdbID, v)) +} + +// TmdbIDIn applies the In predicate on the "tmdb_id" field. +func TmdbIDIn(vs ...int) predicate.Media { + return predicate.Media(sql.FieldIn(FieldTmdbID, vs...)) +} + +// TmdbIDNotIn applies the NotIn predicate on the "tmdb_id" field. +func TmdbIDNotIn(vs ...int) predicate.Media { + return predicate.Media(sql.FieldNotIn(FieldTmdbID, vs...)) +} + +// TmdbIDGT applies the GT predicate on the "tmdb_id" field. +func TmdbIDGT(v int) predicate.Media { + return predicate.Media(sql.FieldGT(FieldTmdbID, v)) +} + +// TmdbIDGTE applies the GTE predicate on the "tmdb_id" field. +func TmdbIDGTE(v int) predicate.Media { + return predicate.Media(sql.FieldGTE(FieldTmdbID, v)) +} + +// TmdbIDLT applies the LT predicate on the "tmdb_id" field. +func TmdbIDLT(v int) predicate.Media { + return predicate.Media(sql.FieldLT(FieldTmdbID, v)) +} + +// TmdbIDLTE applies the LTE predicate on the "tmdb_id" field. +func TmdbIDLTE(v int) predicate.Media { + return predicate.Media(sql.FieldLTE(FieldTmdbID, v)) +} + +// ImdbIDEQ applies the EQ predicate on the "imdb_id" field. +func ImdbIDEQ(v string) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldImdbID, v)) +} + +// ImdbIDNEQ applies the NEQ predicate on the "imdb_id" field. +func ImdbIDNEQ(v string) predicate.Media { + return predicate.Media(sql.FieldNEQ(FieldImdbID, v)) +} + +// ImdbIDIn applies the In predicate on the "imdb_id" field. +func ImdbIDIn(vs ...string) predicate.Media { + return predicate.Media(sql.FieldIn(FieldImdbID, vs...)) +} + +// ImdbIDNotIn applies the NotIn predicate on the "imdb_id" field. +func ImdbIDNotIn(vs ...string) predicate.Media { + return predicate.Media(sql.FieldNotIn(FieldImdbID, vs...)) +} + +// ImdbIDGT applies the GT predicate on the "imdb_id" field. +func ImdbIDGT(v string) predicate.Media { + return predicate.Media(sql.FieldGT(FieldImdbID, v)) +} + +// ImdbIDGTE applies the GTE predicate on the "imdb_id" field. +func ImdbIDGTE(v string) predicate.Media { + return predicate.Media(sql.FieldGTE(FieldImdbID, v)) +} + +// ImdbIDLT applies the LT predicate on the "imdb_id" field. +func ImdbIDLT(v string) predicate.Media { + return predicate.Media(sql.FieldLT(FieldImdbID, v)) +} + +// ImdbIDLTE applies the LTE predicate on the "imdb_id" field. +func ImdbIDLTE(v string) predicate.Media { + return predicate.Media(sql.FieldLTE(FieldImdbID, v)) +} + +// ImdbIDContains applies the Contains predicate on the "imdb_id" field. +func ImdbIDContains(v string) predicate.Media { + return predicate.Media(sql.FieldContains(FieldImdbID, v)) +} + +// ImdbIDHasPrefix applies the HasPrefix predicate on the "imdb_id" field. +func ImdbIDHasPrefix(v string) predicate.Media { + return predicate.Media(sql.FieldHasPrefix(FieldImdbID, v)) +} + +// ImdbIDHasSuffix applies the HasSuffix predicate on the "imdb_id" field. +func ImdbIDHasSuffix(v string) predicate.Media { + return predicate.Media(sql.FieldHasSuffix(FieldImdbID, v)) +} + +// ImdbIDIsNil applies the IsNil predicate on the "imdb_id" field. +func ImdbIDIsNil() predicate.Media { + return predicate.Media(sql.FieldIsNull(FieldImdbID)) +} + +// ImdbIDNotNil applies the NotNil predicate on the "imdb_id" field. +func ImdbIDNotNil() predicate.Media { + return predicate.Media(sql.FieldNotNull(FieldImdbID)) +} + +// ImdbIDEqualFold applies the EqualFold predicate on the "imdb_id" field. +func ImdbIDEqualFold(v string) predicate.Media { + return predicate.Media(sql.FieldEqualFold(FieldImdbID, v)) +} + +// ImdbIDContainsFold applies the ContainsFold predicate on the "imdb_id" field. +func ImdbIDContainsFold(v string) predicate.Media { + return predicate.Media(sql.FieldContainsFold(FieldImdbID, v)) +} + +// MediaTypeEQ applies the EQ predicate on the "media_type" field. +func MediaTypeEQ(v MediaType) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldMediaType, v)) +} + +// MediaTypeNEQ applies the NEQ predicate on the "media_type" field. +func MediaTypeNEQ(v MediaType) predicate.Media { + return predicate.Media(sql.FieldNEQ(FieldMediaType, v)) +} + +// MediaTypeIn applies the In predicate on the "media_type" field. +func MediaTypeIn(vs ...MediaType) predicate.Media { + return predicate.Media(sql.FieldIn(FieldMediaType, vs...)) +} + +// MediaTypeNotIn applies the NotIn predicate on the "media_type" field. +func MediaTypeNotIn(vs ...MediaType) predicate.Media { + return predicate.Media(sql.FieldNotIn(FieldMediaType, vs...)) +} + +// NameCnEQ applies the EQ predicate on the "name_cn" field. +func NameCnEQ(v string) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldNameCn, v)) +} + +// NameCnNEQ applies the NEQ predicate on the "name_cn" field. +func NameCnNEQ(v string) predicate.Media { + return predicate.Media(sql.FieldNEQ(FieldNameCn, v)) +} + +// NameCnIn applies the In predicate on the "name_cn" field. +func NameCnIn(vs ...string) predicate.Media { + return predicate.Media(sql.FieldIn(FieldNameCn, vs...)) +} + +// NameCnNotIn applies the NotIn predicate on the "name_cn" field. +func NameCnNotIn(vs ...string) predicate.Media { + return predicate.Media(sql.FieldNotIn(FieldNameCn, vs...)) +} + +// NameCnGT applies the GT predicate on the "name_cn" field. +func NameCnGT(v string) predicate.Media { + return predicate.Media(sql.FieldGT(FieldNameCn, v)) +} + +// NameCnGTE applies the GTE predicate on the "name_cn" field. +func NameCnGTE(v string) predicate.Media { + return predicate.Media(sql.FieldGTE(FieldNameCn, v)) +} + +// NameCnLT applies the LT predicate on the "name_cn" field. +func NameCnLT(v string) predicate.Media { + return predicate.Media(sql.FieldLT(FieldNameCn, v)) +} + +// NameCnLTE applies the LTE predicate on the "name_cn" field. +func NameCnLTE(v string) predicate.Media { + return predicate.Media(sql.FieldLTE(FieldNameCn, v)) +} + +// NameCnContains applies the Contains predicate on the "name_cn" field. +func NameCnContains(v string) predicate.Media { + return predicate.Media(sql.FieldContains(FieldNameCn, v)) +} + +// NameCnHasPrefix applies the HasPrefix predicate on the "name_cn" field. +func NameCnHasPrefix(v string) predicate.Media { + return predicate.Media(sql.FieldHasPrefix(FieldNameCn, v)) +} + +// NameCnHasSuffix applies the HasSuffix predicate on the "name_cn" field. +func NameCnHasSuffix(v string) predicate.Media { + return predicate.Media(sql.FieldHasSuffix(FieldNameCn, v)) +} + +// NameCnEqualFold applies the EqualFold predicate on the "name_cn" field. +func NameCnEqualFold(v string) predicate.Media { + return predicate.Media(sql.FieldEqualFold(FieldNameCn, v)) +} + +// NameCnContainsFold applies the ContainsFold predicate on the "name_cn" field. +func NameCnContainsFold(v string) predicate.Media { + return predicate.Media(sql.FieldContainsFold(FieldNameCn, v)) +} + +// NameEnEQ applies the EQ predicate on the "name_en" field. +func NameEnEQ(v string) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldNameEn, v)) +} + +// NameEnNEQ applies the NEQ predicate on the "name_en" field. +func NameEnNEQ(v string) predicate.Media { + return predicate.Media(sql.FieldNEQ(FieldNameEn, v)) +} + +// NameEnIn applies the In predicate on the "name_en" field. +func NameEnIn(vs ...string) predicate.Media { + return predicate.Media(sql.FieldIn(FieldNameEn, vs...)) +} + +// NameEnNotIn applies the NotIn predicate on the "name_en" field. +func NameEnNotIn(vs ...string) predicate.Media { + return predicate.Media(sql.FieldNotIn(FieldNameEn, vs...)) +} + +// NameEnGT applies the GT predicate on the "name_en" field. +func NameEnGT(v string) predicate.Media { + return predicate.Media(sql.FieldGT(FieldNameEn, v)) +} + +// NameEnGTE applies the GTE predicate on the "name_en" field. +func NameEnGTE(v string) predicate.Media { + return predicate.Media(sql.FieldGTE(FieldNameEn, v)) +} + +// NameEnLT applies the LT predicate on the "name_en" field. +func NameEnLT(v string) predicate.Media { + return predicate.Media(sql.FieldLT(FieldNameEn, v)) +} + +// NameEnLTE applies the LTE predicate on the "name_en" field. +func NameEnLTE(v string) predicate.Media { + return predicate.Media(sql.FieldLTE(FieldNameEn, v)) +} + +// NameEnContains applies the Contains predicate on the "name_en" field. +func NameEnContains(v string) predicate.Media { + return predicate.Media(sql.FieldContains(FieldNameEn, v)) +} + +// NameEnHasPrefix applies the HasPrefix predicate on the "name_en" field. +func NameEnHasPrefix(v string) predicate.Media { + return predicate.Media(sql.FieldHasPrefix(FieldNameEn, v)) +} + +// NameEnHasSuffix applies the HasSuffix predicate on the "name_en" field. +func NameEnHasSuffix(v string) predicate.Media { + return predicate.Media(sql.FieldHasSuffix(FieldNameEn, v)) +} + +// NameEnEqualFold applies the EqualFold predicate on the "name_en" field. +func NameEnEqualFold(v string) predicate.Media { + return predicate.Media(sql.FieldEqualFold(FieldNameEn, v)) +} + +// NameEnContainsFold applies the ContainsFold predicate on the "name_en" field. +func NameEnContainsFold(v string) predicate.Media { + return predicate.Media(sql.FieldContainsFold(FieldNameEn, v)) +} + +// OriginalNameEQ applies the EQ predicate on the "original_name" field. +func OriginalNameEQ(v string) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldOriginalName, v)) +} + +// OriginalNameNEQ applies the NEQ predicate on the "original_name" field. +func OriginalNameNEQ(v string) predicate.Media { + return predicate.Media(sql.FieldNEQ(FieldOriginalName, v)) +} + +// OriginalNameIn applies the In predicate on the "original_name" field. +func OriginalNameIn(vs ...string) predicate.Media { + return predicate.Media(sql.FieldIn(FieldOriginalName, vs...)) +} + +// OriginalNameNotIn applies the NotIn predicate on the "original_name" field. +func OriginalNameNotIn(vs ...string) predicate.Media { + return predicate.Media(sql.FieldNotIn(FieldOriginalName, vs...)) +} + +// OriginalNameGT applies the GT predicate on the "original_name" field. +func OriginalNameGT(v string) predicate.Media { + return predicate.Media(sql.FieldGT(FieldOriginalName, v)) +} + +// OriginalNameGTE applies the GTE predicate on the "original_name" field. +func OriginalNameGTE(v string) predicate.Media { + return predicate.Media(sql.FieldGTE(FieldOriginalName, v)) +} + +// OriginalNameLT applies the LT predicate on the "original_name" field. +func OriginalNameLT(v string) predicate.Media { + return predicate.Media(sql.FieldLT(FieldOriginalName, v)) +} + +// OriginalNameLTE applies the LTE predicate on the "original_name" field. +func OriginalNameLTE(v string) predicate.Media { + return predicate.Media(sql.FieldLTE(FieldOriginalName, v)) +} + +// OriginalNameContains applies the Contains predicate on the "original_name" field. +func OriginalNameContains(v string) predicate.Media { + return predicate.Media(sql.FieldContains(FieldOriginalName, v)) +} + +// OriginalNameHasPrefix applies the HasPrefix predicate on the "original_name" field. +func OriginalNameHasPrefix(v string) predicate.Media { + return predicate.Media(sql.FieldHasPrefix(FieldOriginalName, v)) +} + +// OriginalNameHasSuffix applies the HasSuffix predicate on the "original_name" field. +func OriginalNameHasSuffix(v string) predicate.Media { + return predicate.Media(sql.FieldHasSuffix(FieldOriginalName, v)) +} + +// OriginalNameEqualFold applies the EqualFold predicate on the "original_name" field. +func OriginalNameEqualFold(v string) predicate.Media { + return predicate.Media(sql.FieldEqualFold(FieldOriginalName, v)) +} + +// OriginalNameContainsFold applies the ContainsFold predicate on the "original_name" field. +func OriginalNameContainsFold(v string) predicate.Media { + return predicate.Media(sql.FieldContainsFold(FieldOriginalName, v)) +} + +// OverviewEQ applies the EQ predicate on the "overview" field. +func OverviewEQ(v string) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldOverview, v)) +} + +// OverviewNEQ applies the NEQ predicate on the "overview" field. +func OverviewNEQ(v string) predicate.Media { + return predicate.Media(sql.FieldNEQ(FieldOverview, v)) +} + +// OverviewIn applies the In predicate on the "overview" field. +func OverviewIn(vs ...string) predicate.Media { + return predicate.Media(sql.FieldIn(FieldOverview, vs...)) +} + +// OverviewNotIn applies the NotIn predicate on the "overview" field. +func OverviewNotIn(vs ...string) predicate.Media { + return predicate.Media(sql.FieldNotIn(FieldOverview, vs...)) +} + +// OverviewGT applies the GT predicate on the "overview" field. +func OverviewGT(v string) predicate.Media { + return predicate.Media(sql.FieldGT(FieldOverview, v)) +} + +// OverviewGTE applies the GTE predicate on the "overview" field. +func OverviewGTE(v string) predicate.Media { + return predicate.Media(sql.FieldGTE(FieldOverview, v)) +} + +// OverviewLT applies the LT predicate on the "overview" field. +func OverviewLT(v string) predicate.Media { + return predicate.Media(sql.FieldLT(FieldOverview, v)) +} + +// OverviewLTE applies the LTE predicate on the "overview" field. +func OverviewLTE(v string) predicate.Media { + return predicate.Media(sql.FieldLTE(FieldOverview, v)) +} + +// OverviewContains applies the Contains predicate on the "overview" field. +func OverviewContains(v string) predicate.Media { + return predicate.Media(sql.FieldContains(FieldOverview, v)) +} + +// OverviewHasPrefix applies the HasPrefix predicate on the "overview" field. +func OverviewHasPrefix(v string) predicate.Media { + return predicate.Media(sql.FieldHasPrefix(FieldOverview, v)) +} + +// OverviewHasSuffix applies the HasSuffix predicate on the "overview" field. +func OverviewHasSuffix(v string) predicate.Media { + return predicate.Media(sql.FieldHasSuffix(FieldOverview, v)) +} + +// OverviewEqualFold applies the EqualFold predicate on the "overview" field. +func OverviewEqualFold(v string) predicate.Media { + return predicate.Media(sql.FieldEqualFold(FieldOverview, v)) +} + +// OverviewContainsFold applies the ContainsFold predicate on the "overview" field. +func OverviewContainsFold(v string) predicate.Media { + return predicate.Media(sql.FieldContainsFold(FieldOverview, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Media { + return predicate.Media(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Media { + return predicate.Media(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Media { + return predicate.Media(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Media { + return predicate.Media(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Media { + return predicate.Media(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Media { + return predicate.Media(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Media { + return predicate.Media(sql.FieldLTE(FieldCreatedAt, v)) +} + +// AirDateEQ applies the EQ predicate on the "air_date" field. +func AirDateEQ(v string) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldAirDate, v)) +} + +// AirDateNEQ applies the NEQ predicate on the "air_date" field. +func AirDateNEQ(v string) predicate.Media { + return predicate.Media(sql.FieldNEQ(FieldAirDate, v)) +} + +// AirDateIn applies the In predicate on the "air_date" field. +func AirDateIn(vs ...string) predicate.Media { + return predicate.Media(sql.FieldIn(FieldAirDate, vs...)) +} + +// AirDateNotIn applies the NotIn predicate on the "air_date" field. +func AirDateNotIn(vs ...string) predicate.Media { + return predicate.Media(sql.FieldNotIn(FieldAirDate, vs...)) +} + +// AirDateGT applies the GT predicate on the "air_date" field. +func AirDateGT(v string) predicate.Media { + return predicate.Media(sql.FieldGT(FieldAirDate, v)) +} + +// AirDateGTE applies the GTE predicate on the "air_date" field. +func AirDateGTE(v string) predicate.Media { + return predicate.Media(sql.FieldGTE(FieldAirDate, v)) +} + +// AirDateLT applies the LT predicate on the "air_date" field. +func AirDateLT(v string) predicate.Media { + return predicate.Media(sql.FieldLT(FieldAirDate, v)) +} + +// AirDateLTE applies the LTE predicate on the "air_date" field. +func AirDateLTE(v string) predicate.Media { + return predicate.Media(sql.FieldLTE(FieldAirDate, v)) +} + +// AirDateContains applies the Contains predicate on the "air_date" field. +func AirDateContains(v string) predicate.Media { + return predicate.Media(sql.FieldContains(FieldAirDate, v)) +} + +// AirDateHasPrefix applies the HasPrefix predicate on the "air_date" field. +func AirDateHasPrefix(v string) predicate.Media { + return predicate.Media(sql.FieldHasPrefix(FieldAirDate, v)) +} + +// AirDateHasSuffix applies the HasSuffix predicate on the "air_date" field. +func AirDateHasSuffix(v string) predicate.Media { + return predicate.Media(sql.FieldHasSuffix(FieldAirDate, v)) +} + +// AirDateEqualFold applies the EqualFold predicate on the "air_date" field. +func AirDateEqualFold(v string) predicate.Media { + return predicate.Media(sql.FieldEqualFold(FieldAirDate, v)) +} + +// AirDateContainsFold applies the ContainsFold predicate on the "air_date" field. +func AirDateContainsFold(v string) predicate.Media { + return predicate.Media(sql.FieldContainsFold(FieldAirDate, v)) +} + +// ResolutionEQ applies the EQ predicate on the "resolution" field. +func ResolutionEQ(v string) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldResolution, v)) +} + +// ResolutionNEQ applies the NEQ predicate on the "resolution" field. +func ResolutionNEQ(v string) predicate.Media { + return predicate.Media(sql.FieldNEQ(FieldResolution, v)) +} + +// ResolutionIn applies the In predicate on the "resolution" field. +func ResolutionIn(vs ...string) predicate.Media { + return predicate.Media(sql.FieldIn(FieldResolution, vs...)) +} + +// ResolutionNotIn applies the NotIn predicate on the "resolution" field. +func ResolutionNotIn(vs ...string) predicate.Media { + return predicate.Media(sql.FieldNotIn(FieldResolution, vs...)) +} + +// ResolutionGT applies the GT predicate on the "resolution" field. +func ResolutionGT(v string) predicate.Media { + return predicate.Media(sql.FieldGT(FieldResolution, v)) +} + +// ResolutionGTE applies the GTE predicate on the "resolution" field. +func ResolutionGTE(v string) predicate.Media { + return predicate.Media(sql.FieldGTE(FieldResolution, v)) +} + +// ResolutionLT applies the LT predicate on the "resolution" field. +func ResolutionLT(v string) predicate.Media { + return predicate.Media(sql.FieldLT(FieldResolution, v)) +} + +// ResolutionLTE applies the LTE predicate on the "resolution" field. +func ResolutionLTE(v string) predicate.Media { + return predicate.Media(sql.FieldLTE(FieldResolution, v)) +} + +// ResolutionContains applies the Contains predicate on the "resolution" field. +func ResolutionContains(v string) predicate.Media { + return predicate.Media(sql.FieldContains(FieldResolution, v)) +} + +// ResolutionHasPrefix applies the HasPrefix predicate on the "resolution" field. +func ResolutionHasPrefix(v string) predicate.Media { + return predicate.Media(sql.FieldHasPrefix(FieldResolution, v)) +} + +// ResolutionHasSuffix applies the HasSuffix predicate on the "resolution" field. +func ResolutionHasSuffix(v string) predicate.Media { + return predicate.Media(sql.FieldHasSuffix(FieldResolution, v)) +} + +// ResolutionEqualFold applies the EqualFold predicate on the "resolution" field. +func ResolutionEqualFold(v string) predicate.Media { + return predicate.Media(sql.FieldEqualFold(FieldResolution, v)) +} + +// ResolutionContainsFold applies the ContainsFold predicate on the "resolution" field. +func ResolutionContainsFold(v string) predicate.Media { + return predicate.Media(sql.FieldContainsFold(FieldResolution, v)) +} + +// StorageIDEQ applies the EQ predicate on the "storage_id" field. +func StorageIDEQ(v int) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldStorageID, v)) +} + +// StorageIDNEQ applies the NEQ predicate on the "storage_id" field. +func StorageIDNEQ(v int) predicate.Media { + return predicate.Media(sql.FieldNEQ(FieldStorageID, v)) +} + +// StorageIDIn applies the In predicate on the "storage_id" field. +func StorageIDIn(vs ...int) predicate.Media { + return predicate.Media(sql.FieldIn(FieldStorageID, vs...)) +} + +// StorageIDNotIn applies the NotIn predicate on the "storage_id" field. +func StorageIDNotIn(vs ...int) predicate.Media { + return predicate.Media(sql.FieldNotIn(FieldStorageID, vs...)) +} + +// StorageIDGT applies the GT predicate on the "storage_id" field. +func StorageIDGT(v int) predicate.Media { + return predicate.Media(sql.FieldGT(FieldStorageID, v)) +} + +// StorageIDGTE applies the GTE predicate on the "storage_id" field. +func StorageIDGTE(v int) predicate.Media { + return predicate.Media(sql.FieldGTE(FieldStorageID, v)) +} + +// StorageIDLT applies the LT predicate on the "storage_id" field. +func StorageIDLT(v int) predicate.Media { + return predicate.Media(sql.FieldLT(FieldStorageID, v)) +} + +// StorageIDLTE applies the LTE predicate on the "storage_id" field. +func StorageIDLTE(v int) predicate.Media { + return predicate.Media(sql.FieldLTE(FieldStorageID, v)) +} + +// StorageIDIsNil applies the IsNil predicate on the "storage_id" field. +func StorageIDIsNil() predicate.Media { + return predicate.Media(sql.FieldIsNull(FieldStorageID)) +} + +// StorageIDNotNil applies the NotNil predicate on the "storage_id" field. +func StorageIDNotNil() predicate.Media { + return predicate.Media(sql.FieldNotNull(FieldStorageID)) +} + +// TargetDirEQ applies the EQ predicate on the "target_dir" field. +func TargetDirEQ(v string) predicate.Media { + return predicate.Media(sql.FieldEQ(FieldTargetDir, v)) +} + +// TargetDirNEQ applies the NEQ predicate on the "target_dir" field. +func TargetDirNEQ(v string) predicate.Media { + return predicate.Media(sql.FieldNEQ(FieldTargetDir, v)) +} + +// TargetDirIn applies the In predicate on the "target_dir" field. +func TargetDirIn(vs ...string) predicate.Media { + return predicate.Media(sql.FieldIn(FieldTargetDir, vs...)) +} + +// TargetDirNotIn applies the NotIn predicate on the "target_dir" field. +func TargetDirNotIn(vs ...string) predicate.Media { + return predicate.Media(sql.FieldNotIn(FieldTargetDir, vs...)) +} + +// TargetDirGT applies the GT predicate on the "target_dir" field. +func TargetDirGT(v string) predicate.Media { + return predicate.Media(sql.FieldGT(FieldTargetDir, v)) +} + +// TargetDirGTE applies the GTE predicate on the "target_dir" field. +func TargetDirGTE(v string) predicate.Media { + return predicate.Media(sql.FieldGTE(FieldTargetDir, v)) +} + +// TargetDirLT applies the LT predicate on the "target_dir" field. +func TargetDirLT(v string) predicate.Media { + return predicate.Media(sql.FieldLT(FieldTargetDir, v)) +} + +// TargetDirLTE applies the LTE predicate on the "target_dir" field. +func TargetDirLTE(v string) predicate.Media { + return predicate.Media(sql.FieldLTE(FieldTargetDir, v)) +} + +// TargetDirContains applies the Contains predicate on the "target_dir" field. +func TargetDirContains(v string) predicate.Media { + return predicate.Media(sql.FieldContains(FieldTargetDir, v)) +} + +// TargetDirHasPrefix applies the HasPrefix predicate on the "target_dir" field. +func TargetDirHasPrefix(v string) predicate.Media { + return predicate.Media(sql.FieldHasPrefix(FieldTargetDir, v)) +} + +// TargetDirHasSuffix applies the HasSuffix predicate on the "target_dir" field. +func TargetDirHasSuffix(v string) predicate.Media { + return predicate.Media(sql.FieldHasSuffix(FieldTargetDir, v)) +} + +// TargetDirIsNil applies the IsNil predicate on the "target_dir" field. +func TargetDirIsNil() predicate.Media { + return predicate.Media(sql.FieldIsNull(FieldTargetDir)) +} + +// TargetDirNotNil applies the NotNil predicate on the "target_dir" field. +func TargetDirNotNil() predicate.Media { + return predicate.Media(sql.FieldNotNull(FieldTargetDir)) +} + +// TargetDirEqualFold applies the EqualFold predicate on the "target_dir" field. +func TargetDirEqualFold(v string) predicate.Media { + return predicate.Media(sql.FieldEqualFold(FieldTargetDir, v)) +} + +// TargetDirContainsFold applies the ContainsFold predicate on the "target_dir" field. +func TargetDirContainsFold(v string) predicate.Media { + return predicate.Media(sql.FieldContainsFold(FieldTargetDir, v)) +} + +// HasEpisodes applies the HasEdge predicate on the "episodes" edge. +func HasEpisodes() predicate.Media { + return predicate.Media(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, EpisodesTable, EpisodesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasEpisodesWith applies the HasEdge predicate on the "episodes" edge with a given conditions (other predicates). +func HasEpisodesWith(preds ...predicate.Episode) predicate.Media { + return predicate.Media(func(s *sql.Selector) { + step := newEpisodesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Media) predicate.Media { + return predicate.Media(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Media) predicate.Media { + return predicate.Media(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Media) predicate.Media { + return predicate.Media(sql.NotPredicates(p)) +} diff --git a/ent/media_create.go b/ent/media_create.go new file mode 100644 index 0000000..e60eee3 --- /dev/null +++ b/ent/media_create.go @@ -0,0 +1,421 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "polaris/ent/episode" + "polaris/ent/media" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// MediaCreate is the builder for creating a Media entity. +type MediaCreate struct { + config + mutation *MediaMutation + hooks []Hook +} + +// SetTmdbID sets the "tmdb_id" field. +func (mc *MediaCreate) SetTmdbID(i int) *MediaCreate { + mc.mutation.SetTmdbID(i) + return mc +} + +// SetImdbID sets the "imdb_id" field. +func (mc *MediaCreate) SetImdbID(s string) *MediaCreate { + mc.mutation.SetImdbID(s) + return mc +} + +// SetNillableImdbID sets the "imdb_id" field if the given value is not nil. +func (mc *MediaCreate) SetNillableImdbID(s *string) *MediaCreate { + if s != nil { + mc.SetImdbID(*s) + } + return mc +} + +// SetMediaType sets the "media_type" field. +func (mc *MediaCreate) SetMediaType(mt media.MediaType) *MediaCreate { + mc.mutation.SetMediaType(mt) + return mc +} + +// SetNameCn sets the "name_cn" field. +func (mc *MediaCreate) SetNameCn(s string) *MediaCreate { + mc.mutation.SetNameCn(s) + return mc +} + +// SetNameEn sets the "name_en" field. +func (mc *MediaCreate) SetNameEn(s string) *MediaCreate { + mc.mutation.SetNameEn(s) + return mc +} + +// SetOriginalName sets the "original_name" field. +func (mc *MediaCreate) SetOriginalName(s string) *MediaCreate { + mc.mutation.SetOriginalName(s) + return mc +} + +// SetOverview sets the "overview" field. +func (mc *MediaCreate) SetOverview(s string) *MediaCreate { + mc.mutation.SetOverview(s) + return mc +} + +// SetCreatedAt sets the "created_at" field. +func (mc *MediaCreate) SetCreatedAt(t time.Time) *MediaCreate { + mc.mutation.SetCreatedAt(t) + return mc +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (mc *MediaCreate) SetNillableCreatedAt(t *time.Time) *MediaCreate { + if t != nil { + mc.SetCreatedAt(*t) + } + return mc +} + +// SetAirDate sets the "air_date" field. +func (mc *MediaCreate) SetAirDate(s string) *MediaCreate { + mc.mutation.SetAirDate(s) + return mc +} + +// SetNillableAirDate sets the "air_date" field if the given value is not nil. +func (mc *MediaCreate) SetNillableAirDate(s *string) *MediaCreate { + if s != nil { + mc.SetAirDate(*s) + } + return mc +} + +// SetResolution sets the "resolution" field. +func (mc *MediaCreate) SetResolution(s string) *MediaCreate { + mc.mutation.SetResolution(s) + return mc +} + +// SetNillableResolution sets the "resolution" field if the given value is not nil. +func (mc *MediaCreate) SetNillableResolution(s *string) *MediaCreate { + if s != nil { + mc.SetResolution(*s) + } + return mc +} + +// SetStorageID sets the "storage_id" field. +func (mc *MediaCreate) SetStorageID(i int) *MediaCreate { + mc.mutation.SetStorageID(i) + return mc +} + +// SetNillableStorageID sets the "storage_id" field if the given value is not nil. +func (mc *MediaCreate) SetNillableStorageID(i *int) *MediaCreate { + if i != nil { + mc.SetStorageID(*i) + } + return mc +} + +// SetTargetDir sets the "target_dir" field. +func (mc *MediaCreate) SetTargetDir(s string) *MediaCreate { + mc.mutation.SetTargetDir(s) + return mc +} + +// SetNillableTargetDir sets the "target_dir" field if the given value is not nil. +func (mc *MediaCreate) SetNillableTargetDir(s *string) *MediaCreate { + if s != nil { + mc.SetTargetDir(*s) + } + return mc +} + +// AddEpisodeIDs adds the "episodes" edge to the Episode entity by IDs. +func (mc *MediaCreate) AddEpisodeIDs(ids ...int) *MediaCreate { + mc.mutation.AddEpisodeIDs(ids...) + return mc +} + +// AddEpisodes adds the "episodes" edges to the Episode entity. +func (mc *MediaCreate) AddEpisodes(e ...*Episode) *MediaCreate { + ids := make([]int, len(e)) + for i := range e { + ids[i] = e[i].ID + } + return mc.AddEpisodeIDs(ids...) +} + +// Mutation returns the MediaMutation object of the builder. +func (mc *MediaCreate) Mutation() *MediaMutation { + return mc.mutation +} + +// Save creates the Media in the database. +func (mc *MediaCreate) Save(ctx context.Context) (*Media, error) { + mc.defaults() + return withHooks(ctx, mc.sqlSave, mc.mutation, mc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (mc *MediaCreate) SaveX(ctx context.Context) *Media { + v, err := mc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (mc *MediaCreate) Exec(ctx context.Context) error { + _, err := mc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (mc *MediaCreate) ExecX(ctx context.Context) { + if err := mc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (mc *MediaCreate) defaults() { + if _, ok := mc.mutation.CreatedAt(); !ok { + v := media.DefaultCreatedAt + mc.mutation.SetCreatedAt(v) + } + if _, ok := mc.mutation.AirDate(); !ok { + v := media.DefaultAirDate + mc.mutation.SetAirDate(v) + } + if _, ok := mc.mutation.Resolution(); !ok { + v := media.DefaultResolution + mc.mutation.SetResolution(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (mc *MediaCreate) check() error { + if _, ok := mc.mutation.TmdbID(); !ok { + return &ValidationError{Name: "tmdb_id", err: errors.New(`ent: missing required field "Media.tmdb_id"`)} + } + if _, ok := mc.mutation.MediaType(); !ok { + return &ValidationError{Name: "media_type", err: errors.New(`ent: missing required field "Media.media_type"`)} + } + if v, ok := mc.mutation.MediaType(); ok { + if err := media.MediaTypeValidator(v); err != nil { + return &ValidationError{Name: "media_type", err: fmt.Errorf(`ent: validator failed for field "Media.media_type": %w`, err)} + } + } + if _, ok := mc.mutation.NameCn(); !ok { + return &ValidationError{Name: "name_cn", err: errors.New(`ent: missing required field "Media.name_cn"`)} + } + if _, ok := mc.mutation.NameEn(); !ok { + return &ValidationError{Name: "name_en", err: errors.New(`ent: missing required field "Media.name_en"`)} + } + if _, ok := mc.mutation.OriginalName(); !ok { + return &ValidationError{Name: "original_name", err: errors.New(`ent: missing required field "Media.original_name"`)} + } + if _, ok := mc.mutation.Overview(); !ok { + return &ValidationError{Name: "overview", err: errors.New(`ent: missing required field "Media.overview"`)} + } + if _, ok := mc.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Media.created_at"`)} + } + if _, ok := mc.mutation.AirDate(); !ok { + return &ValidationError{Name: "air_date", err: errors.New(`ent: missing required field "Media.air_date"`)} + } + if _, ok := mc.mutation.Resolution(); !ok { + return &ValidationError{Name: "resolution", err: errors.New(`ent: missing required field "Media.resolution"`)} + } + return nil +} + +func (mc *MediaCreate) sqlSave(ctx context.Context) (*Media, error) { + if err := mc.check(); err != nil { + return nil, err + } + _node, _spec := mc.createSpec() + if err := sqlgraph.CreateNode(ctx, mc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + mc.mutation.id = &_node.ID + mc.mutation.done = true + return _node, nil +} + +func (mc *MediaCreate) createSpec() (*Media, *sqlgraph.CreateSpec) { + var ( + _node = &Media{config: mc.config} + _spec = sqlgraph.NewCreateSpec(media.Table, sqlgraph.NewFieldSpec(media.FieldID, field.TypeInt)) + ) + if value, ok := mc.mutation.TmdbID(); ok { + _spec.SetField(media.FieldTmdbID, field.TypeInt, value) + _node.TmdbID = value + } + if value, ok := mc.mutation.ImdbID(); ok { + _spec.SetField(media.FieldImdbID, field.TypeString, value) + _node.ImdbID = value + } + if value, ok := mc.mutation.MediaType(); ok { + _spec.SetField(media.FieldMediaType, field.TypeEnum, value) + _node.MediaType = value + } + if value, ok := mc.mutation.NameCn(); ok { + _spec.SetField(media.FieldNameCn, field.TypeString, value) + _node.NameCn = value + } + if value, ok := mc.mutation.NameEn(); ok { + _spec.SetField(media.FieldNameEn, field.TypeString, value) + _node.NameEn = value + } + if value, ok := mc.mutation.OriginalName(); ok { + _spec.SetField(media.FieldOriginalName, field.TypeString, value) + _node.OriginalName = value + } + if value, ok := mc.mutation.Overview(); ok { + _spec.SetField(media.FieldOverview, field.TypeString, value) + _node.Overview = value + } + if value, ok := mc.mutation.CreatedAt(); ok { + _spec.SetField(media.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := mc.mutation.AirDate(); ok { + _spec.SetField(media.FieldAirDate, field.TypeString, value) + _node.AirDate = value + } + if value, ok := mc.mutation.Resolution(); ok { + _spec.SetField(media.FieldResolution, field.TypeString, value) + _node.Resolution = value + } + if value, ok := mc.mutation.StorageID(); ok { + _spec.SetField(media.FieldStorageID, field.TypeInt, value) + _node.StorageID = value + } + if value, ok := mc.mutation.TargetDir(); ok { + _spec.SetField(media.FieldTargetDir, field.TypeString, value) + _node.TargetDir = value + } + if nodes := mc.mutation.EpisodesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: media.EpisodesTable, + Columns: []string{media.EpisodesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// MediaCreateBulk is the builder for creating many Media entities in bulk. +type MediaCreateBulk struct { + config + err error + builders []*MediaCreate +} + +// Save creates the Media entities in the database. +func (mcb *MediaCreateBulk) Save(ctx context.Context) ([]*Media, error) { + if mcb.err != nil { + return nil, mcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(mcb.builders)) + nodes := make([]*Media, len(mcb.builders)) + mutators := make([]Mutator, len(mcb.builders)) + for i := range mcb.builders { + func(i int, root context.Context) { + builder := mcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*MediaMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, mcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, mcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, mcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (mcb *MediaCreateBulk) SaveX(ctx context.Context) []*Media { + v, err := mcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (mcb *MediaCreateBulk) Exec(ctx context.Context) error { + _, err := mcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (mcb *MediaCreateBulk) ExecX(ctx context.Context) { + if err := mcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/media_delete.go b/ent/media_delete.go new file mode 100644 index 0000000..97d8156 --- /dev/null +++ b/ent/media_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "polaris/ent/media" + "polaris/ent/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// MediaDelete is the builder for deleting a Media entity. +type MediaDelete struct { + config + hooks []Hook + mutation *MediaMutation +} + +// Where appends a list predicates to the MediaDelete builder. +func (md *MediaDelete) Where(ps ...predicate.Media) *MediaDelete { + md.mutation.Where(ps...) + return md +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (md *MediaDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, md.sqlExec, md.mutation, md.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (md *MediaDelete) ExecX(ctx context.Context) int { + n, err := md.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (md *MediaDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(media.Table, sqlgraph.NewFieldSpec(media.FieldID, field.TypeInt)) + if ps := md.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, md.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + md.mutation.done = true + return affected, err +} + +// MediaDeleteOne is the builder for deleting a single Media entity. +type MediaDeleteOne struct { + md *MediaDelete +} + +// Where appends a list predicates to the MediaDelete builder. +func (mdo *MediaDeleteOne) Where(ps ...predicate.Media) *MediaDeleteOne { + mdo.md.mutation.Where(ps...) + return mdo +} + +// Exec executes the deletion query. +func (mdo *MediaDeleteOne) Exec(ctx context.Context) error { + n, err := mdo.md.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{media.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (mdo *MediaDeleteOne) ExecX(ctx context.Context) { + if err := mdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/media_query.go b/ent/media_query.go new file mode 100644 index 0000000..829364f --- /dev/null +++ b/ent/media_query.go @@ -0,0 +1,605 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + "polaris/ent/episode" + "polaris/ent/media" + "polaris/ent/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// MediaQuery is the builder for querying Media entities. +type MediaQuery struct { + config + ctx *QueryContext + order []media.OrderOption + inters []Interceptor + predicates []predicate.Media + withEpisodes *EpisodeQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the MediaQuery builder. +func (mq *MediaQuery) Where(ps ...predicate.Media) *MediaQuery { + mq.predicates = append(mq.predicates, ps...) + return mq +} + +// Limit the number of records to be returned by this query. +func (mq *MediaQuery) Limit(limit int) *MediaQuery { + mq.ctx.Limit = &limit + return mq +} + +// Offset to start from. +func (mq *MediaQuery) Offset(offset int) *MediaQuery { + mq.ctx.Offset = &offset + return mq +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (mq *MediaQuery) Unique(unique bool) *MediaQuery { + mq.ctx.Unique = &unique + return mq +} + +// Order specifies how the records should be ordered. +func (mq *MediaQuery) Order(o ...media.OrderOption) *MediaQuery { + mq.order = append(mq.order, o...) + return mq +} + +// QueryEpisodes chains the current query on the "episodes" edge. +func (mq *MediaQuery) QueryEpisodes() *EpisodeQuery { + query := (&EpisodeClient{config: mq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := mq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := mq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(media.Table, media.FieldID, selector), + sqlgraph.To(episode.Table, episode.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, media.EpisodesTable, media.EpisodesColumn), + ) + fromU = sqlgraph.SetNeighbors(mq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Media entity from the query. +// Returns a *NotFoundError when no Media was found. +func (mq *MediaQuery) First(ctx context.Context) (*Media, error) { + nodes, err := mq.Limit(1).All(setContextOp(ctx, mq.ctx, "First")) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{media.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (mq *MediaQuery) FirstX(ctx context.Context) *Media { + node, err := mq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Media ID from the query. +// Returns a *NotFoundError when no Media ID was found. +func (mq *MediaQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = mq.Limit(1).IDs(setContextOp(ctx, mq.ctx, "FirstID")); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{media.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (mq *MediaQuery) FirstIDX(ctx context.Context) int { + id, err := mq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Media entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Media entity is found. +// Returns a *NotFoundError when no Media entities are found. +func (mq *MediaQuery) Only(ctx context.Context) (*Media, error) { + nodes, err := mq.Limit(2).All(setContextOp(ctx, mq.ctx, "Only")) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{media.Label} + default: + return nil, &NotSingularError{media.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (mq *MediaQuery) OnlyX(ctx context.Context) *Media { + node, err := mq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Media ID in the query. +// Returns a *NotSingularError when more than one Media ID is found. +// Returns a *NotFoundError when no entities are found. +func (mq *MediaQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = mq.Limit(2).IDs(setContextOp(ctx, mq.ctx, "OnlyID")); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{media.Label} + default: + err = &NotSingularError{media.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (mq *MediaQuery) OnlyIDX(ctx context.Context) int { + id, err := mq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of MediaSlice. +func (mq *MediaQuery) All(ctx context.Context) ([]*Media, error) { + ctx = setContextOp(ctx, mq.ctx, "All") + if err := mq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Media, *MediaQuery]() + return withInterceptors[[]*Media](ctx, mq, qr, mq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (mq *MediaQuery) AllX(ctx context.Context) []*Media { + nodes, err := mq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Media IDs. +func (mq *MediaQuery) IDs(ctx context.Context) (ids []int, err error) { + if mq.ctx.Unique == nil && mq.path != nil { + mq.Unique(true) + } + ctx = setContextOp(ctx, mq.ctx, "IDs") + if err = mq.Select(media.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (mq *MediaQuery) IDsX(ctx context.Context) []int { + ids, err := mq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (mq *MediaQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, mq.ctx, "Count") + if err := mq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, mq, querierCount[*MediaQuery](), mq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (mq *MediaQuery) CountX(ctx context.Context) int { + count, err := mq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (mq *MediaQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, mq.ctx, "Exist") + switch _, err := mq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (mq *MediaQuery) ExistX(ctx context.Context) bool { + exist, err := mq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the MediaQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (mq *MediaQuery) Clone() *MediaQuery { + if mq == nil { + return nil + } + return &MediaQuery{ + config: mq.config, + ctx: mq.ctx.Clone(), + order: append([]media.OrderOption{}, mq.order...), + inters: append([]Interceptor{}, mq.inters...), + predicates: append([]predicate.Media{}, mq.predicates...), + withEpisodes: mq.withEpisodes.Clone(), + // clone intermediate query. + sql: mq.sql.Clone(), + path: mq.path, + } +} + +// WithEpisodes tells the query-builder to eager-load the nodes that are connected to +// the "episodes" edge. The optional arguments are used to configure the query builder of the edge. +func (mq *MediaQuery) WithEpisodes(opts ...func(*EpisodeQuery)) *MediaQuery { + query := (&EpisodeClient{config: mq.config}).Query() + for _, opt := range opts { + opt(query) + } + mq.withEpisodes = query + return mq +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// TmdbID int `json:"tmdb_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Media.Query(). +// GroupBy(media.FieldTmdbID). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (mq *MediaQuery) GroupBy(field string, fields ...string) *MediaGroupBy { + mq.ctx.Fields = append([]string{field}, fields...) + grbuild := &MediaGroupBy{build: mq} + grbuild.flds = &mq.ctx.Fields + grbuild.label = media.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// TmdbID int `json:"tmdb_id,omitempty"` +// } +// +// client.Media.Query(). +// Select(media.FieldTmdbID). +// Scan(ctx, &v) +func (mq *MediaQuery) Select(fields ...string) *MediaSelect { + mq.ctx.Fields = append(mq.ctx.Fields, fields...) + sbuild := &MediaSelect{MediaQuery: mq} + sbuild.label = media.Label + sbuild.flds, sbuild.scan = &mq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a MediaSelect configured with the given aggregations. +func (mq *MediaQuery) Aggregate(fns ...AggregateFunc) *MediaSelect { + return mq.Select().Aggregate(fns...) +} + +func (mq *MediaQuery) prepareQuery(ctx context.Context) error { + for _, inter := range mq.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, mq); err != nil { + return err + } + } + } + for _, f := range mq.ctx.Fields { + if !media.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if mq.path != nil { + prev, err := mq.path(ctx) + if err != nil { + return err + } + mq.sql = prev + } + return nil +} + +func (mq *MediaQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Media, error) { + var ( + nodes = []*Media{} + _spec = mq.querySpec() + loadedTypes = [1]bool{ + mq.withEpisodes != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Media).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Media{config: mq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, mq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := mq.withEpisodes; query != nil { + if err := mq.loadEpisodes(ctx, query, nodes, + func(n *Media) { n.Edges.Episodes = []*Episode{} }, + func(n *Media, e *Episode) { n.Edges.Episodes = append(n.Edges.Episodes, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (mq *MediaQuery) loadEpisodes(ctx context.Context, query *EpisodeQuery, nodes []*Media, init func(*Media), assign func(*Media, *Episode)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Media) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(episode.FieldMediaID) + } + query.Where(predicate.Episode(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(media.EpisodesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.MediaID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "media_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (mq *MediaQuery) sqlCount(ctx context.Context) (int, error) { + _spec := mq.querySpec() + _spec.Node.Columns = mq.ctx.Fields + if len(mq.ctx.Fields) > 0 { + _spec.Unique = mq.ctx.Unique != nil && *mq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, mq.driver, _spec) +} + +func (mq *MediaQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(media.Table, media.Columns, sqlgraph.NewFieldSpec(media.FieldID, field.TypeInt)) + _spec.From = mq.sql + if unique := mq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if mq.path != nil { + _spec.Unique = true + } + if fields := mq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, media.FieldID) + for i := range fields { + if fields[i] != media.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := mq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := mq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := mq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := mq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (mq *MediaQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(mq.driver.Dialect()) + t1 := builder.Table(media.Table) + columns := mq.ctx.Fields + if len(columns) == 0 { + columns = media.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if mq.sql != nil { + selector = mq.sql + selector.Select(selector.Columns(columns...)...) + } + if mq.ctx.Unique != nil && *mq.ctx.Unique { + selector.Distinct() + } + for _, p := range mq.predicates { + p(selector) + } + for _, p := range mq.order { + p(selector) + } + if offset := mq.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := mq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// MediaGroupBy is the group-by builder for Media entities. +type MediaGroupBy struct { + selector + build *MediaQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (mgb *MediaGroupBy) Aggregate(fns ...AggregateFunc) *MediaGroupBy { + mgb.fns = append(mgb.fns, fns...) + return mgb +} + +// Scan applies the selector query and scans the result into the given value. +func (mgb *MediaGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, mgb.build.ctx, "GroupBy") + if err := mgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*MediaQuery, *MediaGroupBy](ctx, mgb.build, mgb, mgb.build.inters, v) +} + +func (mgb *MediaGroupBy) sqlScan(ctx context.Context, root *MediaQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(mgb.fns)) + for _, fn := range mgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*mgb.flds)+len(mgb.fns)) + for _, f := range *mgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*mgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := mgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// MediaSelect is the builder for selecting fields of Media entities. +type MediaSelect struct { + *MediaQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (ms *MediaSelect) Aggregate(fns ...AggregateFunc) *MediaSelect { + ms.fns = append(ms.fns, fns...) + return ms +} + +// Scan applies the selector query and scans the result into the given value. +func (ms *MediaSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ms.ctx, "Select") + if err := ms.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*MediaQuery, *MediaSelect](ctx, ms.MediaQuery, ms, ms.inters, v) +} + +func (ms *MediaSelect) sqlScan(ctx context.Context, root *MediaQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(ms.fns)) + for _, fn := range ms.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*ms.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := ms.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/ent/media_update.go b/ent/media_update.go new file mode 100644 index 0000000..7d3903b --- /dev/null +++ b/ent/media_update.go @@ -0,0 +1,867 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "polaris/ent/episode" + "polaris/ent/media" + "polaris/ent/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// MediaUpdate is the builder for updating Media entities. +type MediaUpdate struct { + config + hooks []Hook + mutation *MediaMutation +} + +// Where appends a list predicates to the MediaUpdate builder. +func (mu *MediaUpdate) Where(ps ...predicate.Media) *MediaUpdate { + mu.mutation.Where(ps...) + return mu +} + +// SetTmdbID sets the "tmdb_id" field. +func (mu *MediaUpdate) SetTmdbID(i int) *MediaUpdate { + mu.mutation.ResetTmdbID() + mu.mutation.SetTmdbID(i) + return mu +} + +// SetNillableTmdbID sets the "tmdb_id" field if the given value is not nil. +func (mu *MediaUpdate) SetNillableTmdbID(i *int) *MediaUpdate { + if i != nil { + mu.SetTmdbID(*i) + } + return mu +} + +// AddTmdbID adds i to the "tmdb_id" field. +func (mu *MediaUpdate) AddTmdbID(i int) *MediaUpdate { + mu.mutation.AddTmdbID(i) + return mu +} + +// SetImdbID sets the "imdb_id" field. +func (mu *MediaUpdate) SetImdbID(s string) *MediaUpdate { + mu.mutation.SetImdbID(s) + return mu +} + +// SetNillableImdbID sets the "imdb_id" field if the given value is not nil. +func (mu *MediaUpdate) SetNillableImdbID(s *string) *MediaUpdate { + if s != nil { + mu.SetImdbID(*s) + } + return mu +} + +// ClearImdbID clears the value of the "imdb_id" field. +func (mu *MediaUpdate) ClearImdbID() *MediaUpdate { + mu.mutation.ClearImdbID() + return mu +} + +// SetMediaType sets the "media_type" field. +func (mu *MediaUpdate) SetMediaType(mt media.MediaType) *MediaUpdate { + mu.mutation.SetMediaType(mt) + return mu +} + +// SetNillableMediaType sets the "media_type" field if the given value is not nil. +func (mu *MediaUpdate) SetNillableMediaType(mt *media.MediaType) *MediaUpdate { + if mt != nil { + mu.SetMediaType(*mt) + } + return mu +} + +// SetNameCn sets the "name_cn" field. +func (mu *MediaUpdate) SetNameCn(s string) *MediaUpdate { + mu.mutation.SetNameCn(s) + return mu +} + +// SetNillableNameCn sets the "name_cn" field if the given value is not nil. +func (mu *MediaUpdate) SetNillableNameCn(s *string) *MediaUpdate { + if s != nil { + mu.SetNameCn(*s) + } + return mu +} + +// SetNameEn sets the "name_en" field. +func (mu *MediaUpdate) SetNameEn(s string) *MediaUpdate { + mu.mutation.SetNameEn(s) + return mu +} + +// SetNillableNameEn sets the "name_en" field if the given value is not nil. +func (mu *MediaUpdate) SetNillableNameEn(s *string) *MediaUpdate { + if s != nil { + mu.SetNameEn(*s) + } + return mu +} + +// SetOriginalName sets the "original_name" field. +func (mu *MediaUpdate) SetOriginalName(s string) *MediaUpdate { + mu.mutation.SetOriginalName(s) + return mu +} + +// SetNillableOriginalName sets the "original_name" field if the given value is not nil. +func (mu *MediaUpdate) SetNillableOriginalName(s *string) *MediaUpdate { + if s != nil { + mu.SetOriginalName(*s) + } + return mu +} + +// SetOverview sets the "overview" field. +func (mu *MediaUpdate) SetOverview(s string) *MediaUpdate { + mu.mutation.SetOverview(s) + return mu +} + +// SetNillableOverview sets the "overview" field if the given value is not nil. +func (mu *MediaUpdate) SetNillableOverview(s *string) *MediaUpdate { + if s != nil { + mu.SetOverview(*s) + } + return mu +} + +// SetCreatedAt sets the "created_at" field. +func (mu *MediaUpdate) SetCreatedAt(t time.Time) *MediaUpdate { + mu.mutation.SetCreatedAt(t) + return mu +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (mu *MediaUpdate) SetNillableCreatedAt(t *time.Time) *MediaUpdate { + if t != nil { + mu.SetCreatedAt(*t) + } + return mu +} + +// SetAirDate sets the "air_date" field. +func (mu *MediaUpdate) SetAirDate(s string) *MediaUpdate { + mu.mutation.SetAirDate(s) + return mu +} + +// SetNillableAirDate sets the "air_date" field if the given value is not nil. +func (mu *MediaUpdate) SetNillableAirDate(s *string) *MediaUpdate { + if s != nil { + mu.SetAirDate(*s) + } + return mu +} + +// SetResolution sets the "resolution" field. +func (mu *MediaUpdate) SetResolution(s string) *MediaUpdate { + mu.mutation.SetResolution(s) + return mu +} + +// SetNillableResolution sets the "resolution" field if the given value is not nil. +func (mu *MediaUpdate) SetNillableResolution(s *string) *MediaUpdate { + if s != nil { + mu.SetResolution(*s) + } + return mu +} + +// SetStorageID sets the "storage_id" field. +func (mu *MediaUpdate) SetStorageID(i int) *MediaUpdate { + mu.mutation.ResetStorageID() + mu.mutation.SetStorageID(i) + return mu +} + +// SetNillableStorageID sets the "storage_id" field if the given value is not nil. +func (mu *MediaUpdate) SetNillableStorageID(i *int) *MediaUpdate { + if i != nil { + mu.SetStorageID(*i) + } + return mu +} + +// AddStorageID adds i to the "storage_id" field. +func (mu *MediaUpdate) AddStorageID(i int) *MediaUpdate { + mu.mutation.AddStorageID(i) + return mu +} + +// ClearStorageID clears the value of the "storage_id" field. +func (mu *MediaUpdate) ClearStorageID() *MediaUpdate { + mu.mutation.ClearStorageID() + return mu +} + +// SetTargetDir sets the "target_dir" field. +func (mu *MediaUpdate) SetTargetDir(s string) *MediaUpdate { + mu.mutation.SetTargetDir(s) + return mu +} + +// SetNillableTargetDir sets the "target_dir" field if the given value is not nil. +func (mu *MediaUpdate) SetNillableTargetDir(s *string) *MediaUpdate { + if s != nil { + mu.SetTargetDir(*s) + } + return mu +} + +// ClearTargetDir clears the value of the "target_dir" field. +func (mu *MediaUpdate) ClearTargetDir() *MediaUpdate { + mu.mutation.ClearTargetDir() + return mu +} + +// AddEpisodeIDs adds the "episodes" edge to the Episode entity by IDs. +func (mu *MediaUpdate) AddEpisodeIDs(ids ...int) *MediaUpdate { + mu.mutation.AddEpisodeIDs(ids...) + return mu +} + +// AddEpisodes adds the "episodes" edges to the Episode entity. +func (mu *MediaUpdate) AddEpisodes(e ...*Episode) *MediaUpdate { + ids := make([]int, len(e)) + for i := range e { + ids[i] = e[i].ID + } + return mu.AddEpisodeIDs(ids...) +} + +// Mutation returns the MediaMutation object of the builder. +func (mu *MediaUpdate) Mutation() *MediaMutation { + return mu.mutation +} + +// ClearEpisodes clears all "episodes" edges to the Episode entity. +func (mu *MediaUpdate) ClearEpisodes() *MediaUpdate { + mu.mutation.ClearEpisodes() + return mu +} + +// RemoveEpisodeIDs removes the "episodes" edge to Episode entities by IDs. +func (mu *MediaUpdate) RemoveEpisodeIDs(ids ...int) *MediaUpdate { + mu.mutation.RemoveEpisodeIDs(ids...) + return mu +} + +// RemoveEpisodes removes "episodes" edges to Episode entities. +func (mu *MediaUpdate) RemoveEpisodes(e ...*Episode) *MediaUpdate { + ids := make([]int, len(e)) + for i := range e { + ids[i] = e[i].ID + } + return mu.RemoveEpisodeIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (mu *MediaUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, mu.sqlSave, mu.mutation, mu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (mu *MediaUpdate) SaveX(ctx context.Context) int { + affected, err := mu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (mu *MediaUpdate) Exec(ctx context.Context) error { + _, err := mu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (mu *MediaUpdate) ExecX(ctx context.Context) { + if err := mu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (mu *MediaUpdate) check() error { + if v, ok := mu.mutation.MediaType(); ok { + if err := media.MediaTypeValidator(v); err != nil { + return &ValidationError{Name: "media_type", err: fmt.Errorf(`ent: validator failed for field "Media.media_type": %w`, err)} + } + } + return nil +} + +func (mu *MediaUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := mu.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(media.Table, media.Columns, sqlgraph.NewFieldSpec(media.FieldID, field.TypeInt)) + if ps := mu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := mu.mutation.TmdbID(); ok { + _spec.SetField(media.FieldTmdbID, field.TypeInt, value) + } + if value, ok := mu.mutation.AddedTmdbID(); ok { + _spec.AddField(media.FieldTmdbID, field.TypeInt, value) + } + if value, ok := mu.mutation.ImdbID(); ok { + _spec.SetField(media.FieldImdbID, field.TypeString, value) + } + if mu.mutation.ImdbIDCleared() { + _spec.ClearField(media.FieldImdbID, field.TypeString) + } + if value, ok := mu.mutation.MediaType(); ok { + _spec.SetField(media.FieldMediaType, field.TypeEnum, value) + } + if value, ok := mu.mutation.NameCn(); ok { + _spec.SetField(media.FieldNameCn, field.TypeString, value) + } + if value, ok := mu.mutation.NameEn(); ok { + _spec.SetField(media.FieldNameEn, field.TypeString, value) + } + if value, ok := mu.mutation.OriginalName(); ok { + _spec.SetField(media.FieldOriginalName, field.TypeString, value) + } + if value, ok := mu.mutation.Overview(); ok { + _spec.SetField(media.FieldOverview, field.TypeString, value) + } + if value, ok := mu.mutation.CreatedAt(); ok { + _spec.SetField(media.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := mu.mutation.AirDate(); ok { + _spec.SetField(media.FieldAirDate, field.TypeString, value) + } + if value, ok := mu.mutation.Resolution(); ok { + _spec.SetField(media.FieldResolution, field.TypeString, value) + } + if value, ok := mu.mutation.StorageID(); ok { + _spec.SetField(media.FieldStorageID, field.TypeInt, value) + } + if value, ok := mu.mutation.AddedStorageID(); ok { + _spec.AddField(media.FieldStorageID, field.TypeInt, value) + } + if mu.mutation.StorageIDCleared() { + _spec.ClearField(media.FieldStorageID, field.TypeInt) + } + if value, ok := mu.mutation.TargetDir(); ok { + _spec.SetField(media.FieldTargetDir, field.TypeString, value) + } + if mu.mutation.TargetDirCleared() { + _spec.ClearField(media.FieldTargetDir, field.TypeString) + } + if mu.mutation.EpisodesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: media.EpisodesTable, + Columns: []string{media.EpisodesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := mu.mutation.RemovedEpisodesIDs(); len(nodes) > 0 && !mu.mutation.EpisodesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: media.EpisodesTable, + Columns: []string{media.EpisodesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := mu.mutation.EpisodesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: media.EpisodesTable, + Columns: []string{media.EpisodesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, mu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{media.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + mu.mutation.done = true + return n, nil +} + +// MediaUpdateOne is the builder for updating a single Media entity. +type MediaUpdateOne struct { + config + fields []string + hooks []Hook + mutation *MediaMutation +} + +// SetTmdbID sets the "tmdb_id" field. +func (muo *MediaUpdateOne) SetTmdbID(i int) *MediaUpdateOne { + muo.mutation.ResetTmdbID() + muo.mutation.SetTmdbID(i) + return muo +} + +// SetNillableTmdbID sets the "tmdb_id" field if the given value is not nil. +func (muo *MediaUpdateOne) SetNillableTmdbID(i *int) *MediaUpdateOne { + if i != nil { + muo.SetTmdbID(*i) + } + return muo +} + +// AddTmdbID adds i to the "tmdb_id" field. +func (muo *MediaUpdateOne) AddTmdbID(i int) *MediaUpdateOne { + muo.mutation.AddTmdbID(i) + return muo +} + +// SetImdbID sets the "imdb_id" field. +func (muo *MediaUpdateOne) SetImdbID(s string) *MediaUpdateOne { + muo.mutation.SetImdbID(s) + return muo +} + +// SetNillableImdbID sets the "imdb_id" field if the given value is not nil. +func (muo *MediaUpdateOne) SetNillableImdbID(s *string) *MediaUpdateOne { + if s != nil { + muo.SetImdbID(*s) + } + return muo +} + +// ClearImdbID clears the value of the "imdb_id" field. +func (muo *MediaUpdateOne) ClearImdbID() *MediaUpdateOne { + muo.mutation.ClearImdbID() + return muo +} + +// SetMediaType sets the "media_type" field. +func (muo *MediaUpdateOne) SetMediaType(mt media.MediaType) *MediaUpdateOne { + muo.mutation.SetMediaType(mt) + return muo +} + +// SetNillableMediaType sets the "media_type" field if the given value is not nil. +func (muo *MediaUpdateOne) SetNillableMediaType(mt *media.MediaType) *MediaUpdateOne { + if mt != nil { + muo.SetMediaType(*mt) + } + return muo +} + +// SetNameCn sets the "name_cn" field. +func (muo *MediaUpdateOne) SetNameCn(s string) *MediaUpdateOne { + muo.mutation.SetNameCn(s) + return muo +} + +// SetNillableNameCn sets the "name_cn" field if the given value is not nil. +func (muo *MediaUpdateOne) SetNillableNameCn(s *string) *MediaUpdateOne { + if s != nil { + muo.SetNameCn(*s) + } + return muo +} + +// SetNameEn sets the "name_en" field. +func (muo *MediaUpdateOne) SetNameEn(s string) *MediaUpdateOne { + muo.mutation.SetNameEn(s) + return muo +} + +// SetNillableNameEn sets the "name_en" field if the given value is not nil. +func (muo *MediaUpdateOne) SetNillableNameEn(s *string) *MediaUpdateOne { + if s != nil { + muo.SetNameEn(*s) + } + return muo +} + +// SetOriginalName sets the "original_name" field. +func (muo *MediaUpdateOne) SetOriginalName(s string) *MediaUpdateOne { + muo.mutation.SetOriginalName(s) + return muo +} + +// SetNillableOriginalName sets the "original_name" field if the given value is not nil. +func (muo *MediaUpdateOne) SetNillableOriginalName(s *string) *MediaUpdateOne { + if s != nil { + muo.SetOriginalName(*s) + } + return muo +} + +// SetOverview sets the "overview" field. +func (muo *MediaUpdateOne) SetOverview(s string) *MediaUpdateOne { + muo.mutation.SetOverview(s) + return muo +} + +// SetNillableOverview sets the "overview" field if the given value is not nil. +func (muo *MediaUpdateOne) SetNillableOverview(s *string) *MediaUpdateOne { + if s != nil { + muo.SetOverview(*s) + } + return muo +} + +// SetCreatedAt sets the "created_at" field. +func (muo *MediaUpdateOne) SetCreatedAt(t time.Time) *MediaUpdateOne { + muo.mutation.SetCreatedAt(t) + return muo +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (muo *MediaUpdateOne) SetNillableCreatedAt(t *time.Time) *MediaUpdateOne { + if t != nil { + muo.SetCreatedAt(*t) + } + return muo +} + +// SetAirDate sets the "air_date" field. +func (muo *MediaUpdateOne) SetAirDate(s string) *MediaUpdateOne { + muo.mutation.SetAirDate(s) + return muo +} + +// SetNillableAirDate sets the "air_date" field if the given value is not nil. +func (muo *MediaUpdateOne) SetNillableAirDate(s *string) *MediaUpdateOne { + if s != nil { + muo.SetAirDate(*s) + } + return muo +} + +// SetResolution sets the "resolution" field. +func (muo *MediaUpdateOne) SetResolution(s string) *MediaUpdateOne { + muo.mutation.SetResolution(s) + return muo +} + +// SetNillableResolution sets the "resolution" field if the given value is not nil. +func (muo *MediaUpdateOne) SetNillableResolution(s *string) *MediaUpdateOne { + if s != nil { + muo.SetResolution(*s) + } + return muo +} + +// SetStorageID sets the "storage_id" field. +func (muo *MediaUpdateOne) SetStorageID(i int) *MediaUpdateOne { + muo.mutation.ResetStorageID() + muo.mutation.SetStorageID(i) + return muo +} + +// SetNillableStorageID sets the "storage_id" field if the given value is not nil. +func (muo *MediaUpdateOne) SetNillableStorageID(i *int) *MediaUpdateOne { + if i != nil { + muo.SetStorageID(*i) + } + return muo +} + +// AddStorageID adds i to the "storage_id" field. +func (muo *MediaUpdateOne) AddStorageID(i int) *MediaUpdateOne { + muo.mutation.AddStorageID(i) + return muo +} + +// ClearStorageID clears the value of the "storage_id" field. +func (muo *MediaUpdateOne) ClearStorageID() *MediaUpdateOne { + muo.mutation.ClearStorageID() + return muo +} + +// SetTargetDir sets the "target_dir" field. +func (muo *MediaUpdateOne) SetTargetDir(s string) *MediaUpdateOne { + muo.mutation.SetTargetDir(s) + return muo +} + +// SetNillableTargetDir sets the "target_dir" field if the given value is not nil. +func (muo *MediaUpdateOne) SetNillableTargetDir(s *string) *MediaUpdateOne { + if s != nil { + muo.SetTargetDir(*s) + } + return muo +} + +// ClearTargetDir clears the value of the "target_dir" field. +func (muo *MediaUpdateOne) ClearTargetDir() *MediaUpdateOne { + muo.mutation.ClearTargetDir() + return muo +} + +// AddEpisodeIDs adds the "episodes" edge to the Episode entity by IDs. +func (muo *MediaUpdateOne) AddEpisodeIDs(ids ...int) *MediaUpdateOne { + muo.mutation.AddEpisodeIDs(ids...) + return muo +} + +// AddEpisodes adds the "episodes" edges to the Episode entity. +func (muo *MediaUpdateOne) AddEpisodes(e ...*Episode) *MediaUpdateOne { + ids := make([]int, len(e)) + for i := range e { + ids[i] = e[i].ID + } + return muo.AddEpisodeIDs(ids...) +} + +// Mutation returns the MediaMutation object of the builder. +func (muo *MediaUpdateOne) Mutation() *MediaMutation { + return muo.mutation +} + +// ClearEpisodes clears all "episodes" edges to the Episode entity. +func (muo *MediaUpdateOne) ClearEpisodes() *MediaUpdateOne { + muo.mutation.ClearEpisodes() + return muo +} + +// RemoveEpisodeIDs removes the "episodes" edge to Episode entities by IDs. +func (muo *MediaUpdateOne) RemoveEpisodeIDs(ids ...int) *MediaUpdateOne { + muo.mutation.RemoveEpisodeIDs(ids...) + return muo +} + +// RemoveEpisodes removes "episodes" edges to Episode entities. +func (muo *MediaUpdateOne) RemoveEpisodes(e ...*Episode) *MediaUpdateOne { + ids := make([]int, len(e)) + for i := range e { + ids[i] = e[i].ID + } + return muo.RemoveEpisodeIDs(ids...) +} + +// Where appends a list predicates to the MediaUpdate builder. +func (muo *MediaUpdateOne) Where(ps ...predicate.Media) *MediaUpdateOne { + muo.mutation.Where(ps...) + return muo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (muo *MediaUpdateOne) Select(field string, fields ...string) *MediaUpdateOne { + muo.fields = append([]string{field}, fields...) + return muo +} + +// Save executes the query and returns the updated Media entity. +func (muo *MediaUpdateOne) Save(ctx context.Context) (*Media, error) { + return withHooks(ctx, muo.sqlSave, muo.mutation, muo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (muo *MediaUpdateOne) SaveX(ctx context.Context) *Media { + node, err := muo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (muo *MediaUpdateOne) Exec(ctx context.Context) error { + _, err := muo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (muo *MediaUpdateOne) ExecX(ctx context.Context) { + if err := muo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (muo *MediaUpdateOne) check() error { + if v, ok := muo.mutation.MediaType(); ok { + if err := media.MediaTypeValidator(v); err != nil { + return &ValidationError{Name: "media_type", err: fmt.Errorf(`ent: validator failed for field "Media.media_type": %w`, err)} + } + } + return nil +} + +func (muo *MediaUpdateOne) sqlSave(ctx context.Context) (_node *Media, err error) { + if err := muo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(media.Table, media.Columns, sqlgraph.NewFieldSpec(media.FieldID, field.TypeInt)) + id, ok := muo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Media.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := muo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, media.FieldID) + for _, f := range fields { + if !media.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != media.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := muo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := muo.mutation.TmdbID(); ok { + _spec.SetField(media.FieldTmdbID, field.TypeInt, value) + } + if value, ok := muo.mutation.AddedTmdbID(); ok { + _spec.AddField(media.FieldTmdbID, field.TypeInt, value) + } + if value, ok := muo.mutation.ImdbID(); ok { + _spec.SetField(media.FieldImdbID, field.TypeString, value) + } + if muo.mutation.ImdbIDCleared() { + _spec.ClearField(media.FieldImdbID, field.TypeString) + } + if value, ok := muo.mutation.MediaType(); ok { + _spec.SetField(media.FieldMediaType, field.TypeEnum, value) + } + if value, ok := muo.mutation.NameCn(); ok { + _spec.SetField(media.FieldNameCn, field.TypeString, value) + } + if value, ok := muo.mutation.NameEn(); ok { + _spec.SetField(media.FieldNameEn, field.TypeString, value) + } + if value, ok := muo.mutation.OriginalName(); ok { + _spec.SetField(media.FieldOriginalName, field.TypeString, value) + } + if value, ok := muo.mutation.Overview(); ok { + _spec.SetField(media.FieldOverview, field.TypeString, value) + } + if value, ok := muo.mutation.CreatedAt(); ok { + _spec.SetField(media.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := muo.mutation.AirDate(); ok { + _spec.SetField(media.FieldAirDate, field.TypeString, value) + } + if value, ok := muo.mutation.Resolution(); ok { + _spec.SetField(media.FieldResolution, field.TypeString, value) + } + if value, ok := muo.mutation.StorageID(); ok { + _spec.SetField(media.FieldStorageID, field.TypeInt, value) + } + if value, ok := muo.mutation.AddedStorageID(); ok { + _spec.AddField(media.FieldStorageID, field.TypeInt, value) + } + if muo.mutation.StorageIDCleared() { + _spec.ClearField(media.FieldStorageID, field.TypeInt) + } + if value, ok := muo.mutation.TargetDir(); ok { + _spec.SetField(media.FieldTargetDir, field.TypeString, value) + } + if muo.mutation.TargetDirCleared() { + _spec.ClearField(media.FieldTargetDir, field.TypeString) + } + if muo.mutation.EpisodesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: media.EpisodesTable, + Columns: []string{media.EpisodesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := muo.mutation.RemovedEpisodesIDs(); len(nodes) > 0 && !muo.mutation.EpisodesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: media.EpisodesTable, + Columns: []string{media.EpisodesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := muo.mutation.EpisodesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: media.EpisodesTable, + Columns: []string{media.EpisodesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &Media{config: muo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, muo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{media.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + muo.mutation.done = true + return _node, nil +} diff --git a/ent/migrate/schema.go b/ent/migrate/schema.go index 550619e..f9d2f06 100644 --- a/ent/migrate/schema.go +++ b/ent/migrate/schema.go @@ -39,7 +39,7 @@ var ( {Name: "air_date", Type: field.TypeString}, {Name: "status", Type: field.TypeEnum, Enums: []string{"missing", "downloading", "downloaded"}, Default: "missing"}, {Name: "file_in_storage", Type: field.TypeString, Nullable: true}, - {Name: "series_id", Type: field.TypeInt, Nullable: true}, + {Name: "media_id", Type: field.TypeInt, Nullable: true}, } // EpisodesTable holds the schema information for the "episodes" table. EpisodesTable = &schema.Table{ @@ -48,9 +48,9 @@ var ( PrimaryKey: []*schema.Column{EpisodesColumns[0]}, ForeignKeys: []*schema.ForeignKey{ { - Symbol: "episodes_series_episodes", + Symbol: "episodes_media_episodes", Columns: []*schema.Column{EpisodesColumns[8]}, - RefColumns: []*schema.Column{SeriesColumns[0]}, + RefColumns: []*schema.Column{MediaColumns[0]}, OnDelete: schema.SetNull, }, }, @@ -58,7 +58,7 @@ var ( // HistoriesColumns holds the columns for the "histories" table. HistoriesColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, - {Name: "series_id", Type: field.TypeInt}, + {Name: "media_id", Type: field.TypeInt}, {Name: "episode_id", Type: field.TypeInt}, {Name: "source_title", Type: field.TypeString}, {Name: "date", Type: field.TypeTime}, @@ -88,27 +88,27 @@ var ( Columns: IndexersColumns, PrimaryKey: []*schema.Column{IndexersColumns[0]}, } - // SeriesColumns holds the columns for the "series" table. - SeriesColumns = []*schema.Column{ + // MediaColumns holds the columns for the "media" table. + MediaColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, {Name: "tmdb_id", Type: field.TypeInt}, {Name: "imdb_id", Type: field.TypeString, Nullable: true}, + {Name: "media_type", Type: field.TypeEnum, Enums: []string{"tv", "movie"}}, {Name: "name_cn", Type: field.TypeString}, {Name: "name_en", Type: field.TypeString}, {Name: "original_name", Type: field.TypeString}, {Name: "overview", Type: field.TypeString}, - {Name: "poster_path", Type: field.TypeString, Nullable: true}, {Name: "created_at", Type: field.TypeTime}, {Name: "air_date", Type: field.TypeString, Default: ""}, {Name: "resolution", Type: field.TypeString, Default: ""}, {Name: "storage_id", Type: field.TypeInt, Nullable: true}, {Name: "target_dir", Type: field.TypeString, Nullable: true}, } - // SeriesTable holds the schema information for the "series" table. - SeriesTable = &schema.Table{ - Name: "series", - Columns: SeriesColumns, - PrimaryKey: []*schema.Column{SeriesColumns[0]}, + // MediaTable holds the schema information for the "media" table. + MediaTable = &schema.Table{ + Name: "media", + Columns: MediaColumns, + PrimaryKey: []*schema.Column{MediaColumns[0]}, } // SettingsColumns holds the columns for the "settings" table. SettingsColumns = []*schema.Column{ @@ -143,12 +143,12 @@ var ( EpisodesTable, HistoriesTable, IndexersTable, - SeriesTable, + MediaTable, SettingsTable, StoragesTable, } ) func init() { - EpisodesTable.ForeignKeys[0].RefTable = SeriesTable + EpisodesTable.ForeignKeys[0].RefTable = MediaTable } diff --git a/ent/mutation.go b/ent/mutation.go index 8a9cd52..6339ef3 100644 --- a/ent/mutation.go +++ b/ent/mutation.go @@ -10,8 +10,8 @@ import ( "polaris/ent/episode" "polaris/ent/history" "polaris/ent/indexers" + "polaris/ent/media" "polaris/ent/predicate" - "polaris/ent/series" "polaris/ent/settings" "polaris/ent/storage" "sync" @@ -34,7 +34,7 @@ const ( TypeEpisode = "Episode" TypeHistory = "History" TypeIndexers = "Indexers" - TypeSeries = "Series" + TypeMedia = "Media" TypeSettings = "Settings" TypeStorage = "Storage" ) @@ -921,8 +921,8 @@ type EpisodeMutation struct { status *episode.Status file_in_storage *string clearedFields map[string]struct{} - series *int - clearedseries bool + media *int + clearedmedia bool done bool oldValue func(context.Context) (*Episode, error) predicates []predicate.Episode @@ -1026,53 +1026,53 @@ func (m *EpisodeMutation) IDs(ctx context.Context) ([]int, error) { } } -// SetSeriesID sets the "series_id" field. -func (m *EpisodeMutation) SetSeriesID(i int) { - m.series = &i +// SetMediaID sets the "media_id" field. +func (m *EpisodeMutation) SetMediaID(i int) { + m.media = &i } -// SeriesID returns the value of the "series_id" field in the mutation. -func (m *EpisodeMutation) SeriesID() (r int, exists bool) { - v := m.series +// MediaID returns the value of the "media_id" field in the mutation. +func (m *EpisodeMutation) MediaID() (r int, exists bool) { + v := m.media if v == nil { return } return *v, true } -// OldSeriesID returns the old "series_id" field's value of the Episode entity. +// OldMediaID returns the old "media_id" field's value of the Episode entity. // If the Episode object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *EpisodeMutation) OldSeriesID(ctx context.Context) (v int, err error) { +func (m *EpisodeMutation) OldMediaID(ctx context.Context) (v int, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldSeriesID is only allowed on UpdateOne operations") + return v, errors.New("OldMediaID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldSeriesID requires an ID field in the mutation") + return v, errors.New("OldMediaID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldSeriesID: %w", err) + return v, fmt.Errorf("querying old value for OldMediaID: %w", err) } - return oldValue.SeriesID, nil + return oldValue.MediaID, nil } -// ClearSeriesID clears the value of the "series_id" field. -func (m *EpisodeMutation) ClearSeriesID() { - m.series = nil - m.clearedFields[episode.FieldSeriesID] = struct{}{} +// ClearMediaID clears the value of the "media_id" field. +func (m *EpisodeMutation) ClearMediaID() { + m.media = nil + m.clearedFields[episode.FieldMediaID] = struct{}{} } -// SeriesIDCleared returns if the "series_id" field was cleared in this mutation. -func (m *EpisodeMutation) SeriesIDCleared() bool { - _, ok := m.clearedFields[episode.FieldSeriesID] +// MediaIDCleared returns if the "media_id" field was cleared in this mutation. +func (m *EpisodeMutation) MediaIDCleared() bool { + _, ok := m.clearedFields[episode.FieldMediaID] return ok } -// ResetSeriesID resets all changes to the "series_id" field. -func (m *EpisodeMutation) ResetSeriesID() { - m.series = nil - delete(m.clearedFields, episode.FieldSeriesID) +// ResetMediaID resets all changes to the "media_id" field. +func (m *EpisodeMutation) ResetMediaID() { + m.media = nil + delete(m.clearedFields, episode.FieldMediaID) } // SetSeasonNumber sets the "season_number" field. @@ -1380,31 +1380,31 @@ func (m *EpisodeMutation) ResetFileInStorage() { delete(m.clearedFields, episode.FieldFileInStorage) } -// ClearSeries clears the "series" edge to the Series entity. -func (m *EpisodeMutation) ClearSeries() { - m.clearedseries = true - m.clearedFields[episode.FieldSeriesID] = struct{}{} +// ClearMedia clears the "media" edge to the Media entity. +func (m *EpisodeMutation) ClearMedia() { + m.clearedmedia = true + m.clearedFields[episode.FieldMediaID] = struct{}{} } -// SeriesCleared reports if the "series" edge to the Series entity was cleared. -func (m *EpisodeMutation) SeriesCleared() bool { - return m.SeriesIDCleared() || m.clearedseries +// MediaCleared reports if the "media" edge to the Media entity was cleared. +func (m *EpisodeMutation) MediaCleared() bool { + return m.MediaIDCleared() || m.clearedmedia } -// SeriesIDs returns the "series" edge IDs in the mutation. +// MediaIDs returns the "media" edge IDs in the mutation. // Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// SeriesID instead. It exists only for internal usage by the builders. -func (m *EpisodeMutation) SeriesIDs() (ids []int) { - if id := m.series; id != nil { +// MediaID instead. It exists only for internal usage by the builders. +func (m *EpisodeMutation) MediaIDs() (ids []int) { + if id := m.media; id != nil { ids = append(ids, *id) } return } -// ResetSeries resets all changes to the "series" edge. -func (m *EpisodeMutation) ResetSeries() { - m.series = nil - m.clearedseries = false +// ResetMedia resets all changes to the "media" edge. +func (m *EpisodeMutation) ResetMedia() { + m.media = nil + m.clearedmedia = false } // Where appends a list predicates to the EpisodeMutation builder. @@ -1442,8 +1442,8 @@ func (m *EpisodeMutation) Type() string { // AddedFields(). func (m *EpisodeMutation) Fields() []string { fields := make([]string, 0, 8) - if m.series != nil { - fields = append(fields, episode.FieldSeriesID) + if m.media != nil { + fields = append(fields, episode.FieldMediaID) } if m.season_number != nil { fields = append(fields, episode.FieldSeasonNumber) @@ -1474,8 +1474,8 @@ func (m *EpisodeMutation) Fields() []string { // schema. func (m *EpisodeMutation) Field(name string) (ent.Value, bool) { switch name { - case episode.FieldSeriesID: - return m.SeriesID() + case episode.FieldMediaID: + return m.MediaID() case episode.FieldSeasonNumber: return m.SeasonNumber() case episode.FieldEpisodeNumber: @@ -1499,8 +1499,8 @@ func (m *EpisodeMutation) Field(name string) (ent.Value, bool) { // database failed. func (m *EpisodeMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case episode.FieldSeriesID: - return m.OldSeriesID(ctx) + case episode.FieldMediaID: + return m.OldMediaID(ctx) case episode.FieldSeasonNumber: return m.OldSeasonNumber(ctx) case episode.FieldEpisodeNumber: @@ -1524,12 +1524,12 @@ func (m *EpisodeMutation) OldField(ctx context.Context, name string) (ent.Value, // type. func (m *EpisodeMutation) SetField(name string, value ent.Value) error { switch name { - case episode.FieldSeriesID: + case episode.FieldMediaID: v, ok := value.(int) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetSeriesID(v) + m.SetMediaID(v) return nil case episode.FieldSeasonNumber: v, ok := value.(int) @@ -1637,8 +1637,8 @@ func (m *EpisodeMutation) AddField(name string, value ent.Value) error { // mutation. func (m *EpisodeMutation) ClearedFields() []string { var fields []string - if m.FieldCleared(episode.FieldSeriesID) { - fields = append(fields, episode.FieldSeriesID) + if m.FieldCleared(episode.FieldMediaID) { + fields = append(fields, episode.FieldMediaID) } if m.FieldCleared(episode.FieldFileInStorage) { fields = append(fields, episode.FieldFileInStorage) @@ -1657,8 +1657,8 @@ func (m *EpisodeMutation) FieldCleared(name string) bool { // error if the field is not defined in the schema. func (m *EpisodeMutation) ClearField(name string) error { switch name { - case episode.FieldSeriesID: - m.ClearSeriesID() + case episode.FieldMediaID: + m.ClearMediaID() return nil case episode.FieldFileInStorage: m.ClearFileInStorage() @@ -1671,8 +1671,8 @@ func (m *EpisodeMutation) ClearField(name string) error { // It returns an error if the field is not defined in the schema. func (m *EpisodeMutation) ResetField(name string) error { switch name { - case episode.FieldSeriesID: - m.ResetSeriesID() + case episode.FieldMediaID: + m.ResetMediaID() return nil case episode.FieldSeasonNumber: m.ResetSeasonNumber() @@ -1702,8 +1702,8 @@ func (m *EpisodeMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *EpisodeMutation) AddedEdges() []string { edges := make([]string, 0, 1) - if m.series != nil { - edges = append(edges, episode.EdgeSeries) + if m.media != nil { + edges = append(edges, episode.EdgeMedia) } return edges } @@ -1712,8 +1712,8 @@ func (m *EpisodeMutation) AddedEdges() []string { // name in this mutation. func (m *EpisodeMutation) AddedIDs(name string) []ent.Value { switch name { - case episode.EdgeSeries: - if id := m.series; id != nil { + case episode.EdgeMedia: + if id := m.media; id != nil { return []ent.Value{*id} } } @@ -1735,8 +1735,8 @@ func (m *EpisodeMutation) RemovedIDs(name string) []ent.Value { // ClearedEdges returns all edge names that were cleared in this mutation. func (m *EpisodeMutation) ClearedEdges() []string { edges := make([]string, 0, 1) - if m.clearedseries { - edges = append(edges, episode.EdgeSeries) + if m.clearedmedia { + edges = append(edges, episode.EdgeMedia) } return edges } @@ -1745,8 +1745,8 @@ func (m *EpisodeMutation) ClearedEdges() []string { // was cleared in this mutation. func (m *EpisodeMutation) EdgeCleared(name string) bool { switch name { - case episode.EdgeSeries: - return m.clearedseries + case episode.EdgeMedia: + return m.clearedmedia } return false } @@ -1755,8 +1755,8 @@ func (m *EpisodeMutation) EdgeCleared(name string) bool { // if that edge is not defined in the schema. func (m *EpisodeMutation) ClearEdge(name string) error { switch name { - case episode.EdgeSeries: - m.ClearSeries() + case episode.EdgeMedia: + m.ClearMedia() return nil } return fmt.Errorf("unknown Episode unique edge %s", name) @@ -1766,8 +1766,8 @@ func (m *EpisodeMutation) ClearEdge(name string) error { // It returns an error if the edge is not defined in the schema. func (m *EpisodeMutation) ResetEdge(name string) error { switch name { - case episode.EdgeSeries: - m.ResetSeries() + case episode.EdgeMedia: + m.ResetMedia() return nil } return fmt.Errorf("unknown Episode edge %s", name) @@ -1779,8 +1779,8 @@ type HistoryMutation struct { op Op typ string id *int - series_id *int - addseries_id *int + media_id *int + addmedia_id *int episode_id *int addepisode_id *int source_title *string @@ -1894,60 +1894,60 @@ func (m *HistoryMutation) IDs(ctx context.Context) ([]int, error) { } } -// SetSeriesID sets the "series_id" field. -func (m *HistoryMutation) SetSeriesID(i int) { - m.series_id = &i - m.addseries_id = nil +// SetMediaID sets the "media_id" field. +func (m *HistoryMutation) SetMediaID(i int) { + m.media_id = &i + m.addmedia_id = nil } -// SeriesID returns the value of the "series_id" field in the mutation. -func (m *HistoryMutation) SeriesID() (r int, exists bool) { - v := m.series_id +// MediaID returns the value of the "media_id" field in the mutation. +func (m *HistoryMutation) MediaID() (r int, exists bool) { + v := m.media_id if v == nil { return } return *v, true } -// OldSeriesID returns the old "series_id" field's value of the History entity. +// OldMediaID returns the old "media_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) OldSeriesID(ctx context.Context) (v int, err error) { +func (m *HistoryMutation) OldMediaID(ctx context.Context) (v int, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldSeriesID is only allowed on UpdateOne operations") + return v, errors.New("OldMediaID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldSeriesID requires an ID field in the mutation") + return v, errors.New("OldMediaID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldSeriesID: %w", err) + return v, fmt.Errorf("querying old value for OldMediaID: %w", err) } - return oldValue.SeriesID, nil + return oldValue.MediaID, nil } -// AddSeriesID adds i to the "series_id" field. -func (m *HistoryMutation) AddSeriesID(i int) { - if m.addseries_id != nil { - *m.addseries_id += i +// AddMediaID adds i to the "media_id" field. +func (m *HistoryMutation) AddMediaID(i int) { + if m.addmedia_id != nil { + *m.addmedia_id += i } else { - m.addseries_id = &i + m.addmedia_id = &i } } -// AddedSeriesID returns the value that was added to the "series_id" field in this mutation. -func (m *HistoryMutation) AddedSeriesID() (r int, exists bool) { - v := m.addseries_id +// AddedMediaID returns the value that was added to the "media_id" field in this mutation. +func (m *HistoryMutation) AddedMediaID() (r int, exists bool) { + v := m.addmedia_id if v == nil { return } return *v, true } -// ResetSeriesID resets all changes to the "series_id" field. -func (m *HistoryMutation) ResetSeriesID() { - m.series_id = nil - m.addseries_id = nil +// ResetMediaID resets all changes to the "media_id" field. +func (m *HistoryMutation) ResetMediaID() { + m.media_id = nil + m.addmedia_id = nil } // SetEpisodeID sets the "episode_id" field. @@ -2290,8 +2290,8 @@ func (m *HistoryMutation) Type() string { // AddedFields(). func (m *HistoryMutation) Fields() []string { fields := make([]string, 0, 8) - if m.series_id != nil { - fields = append(fields, history.FieldSeriesID) + if m.media_id != nil { + fields = append(fields, history.FieldMediaID) } if m.episode_id != nil { fields = append(fields, history.FieldEpisodeID) @@ -2322,8 +2322,8 @@ func (m *HistoryMutation) Fields() []string { // schema. func (m *HistoryMutation) Field(name string) (ent.Value, bool) { switch name { - case history.FieldSeriesID: - return m.SeriesID() + case history.FieldMediaID: + return m.MediaID() case history.FieldEpisodeID: return m.EpisodeID() case history.FieldSourceTitle: @@ -2347,8 +2347,8 @@ func (m *HistoryMutation) Field(name string) (ent.Value, bool) { // database failed. func (m *HistoryMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case history.FieldSeriesID: - return m.OldSeriesID(ctx) + case history.FieldMediaID: + return m.OldMediaID(ctx) case history.FieldEpisodeID: return m.OldEpisodeID(ctx) case history.FieldSourceTitle: @@ -2372,12 +2372,12 @@ func (m *HistoryMutation) OldField(ctx context.Context, name string) (ent.Value, // type. func (m *HistoryMutation) SetField(name string, value ent.Value) error { switch name { - case history.FieldSeriesID: + case history.FieldMediaID: v, ok := value.(int) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetSeriesID(v) + m.SetMediaID(v) return nil case history.FieldEpisodeID: v, ok := value.(int) @@ -2436,8 +2436,8 @@ func (m *HistoryMutation) SetField(name string, value ent.Value) error { // this mutation. func (m *HistoryMutation) AddedFields() []string { var fields []string - if m.addseries_id != nil { - fields = append(fields, history.FieldSeriesID) + if m.addmedia_id != nil { + fields = append(fields, history.FieldMediaID) } if m.addepisode_id != nil { fields = append(fields, history.FieldEpisodeID) @@ -2453,8 +2453,8 @@ func (m *HistoryMutation) AddedFields() []string { // was not set, or was not defined in the schema. func (m *HistoryMutation) AddedField(name string) (ent.Value, bool) { switch name { - case history.FieldSeriesID: - return m.AddedSeriesID() + case history.FieldMediaID: + return m.AddedMediaID() case history.FieldEpisodeID: return m.AddedEpisodeID() case history.FieldSize: @@ -2468,12 +2468,12 @@ func (m *HistoryMutation) AddedField(name string) (ent.Value, bool) { // type. func (m *HistoryMutation) AddField(name string, value ent.Value) error { switch name { - case history.FieldSeriesID: + case history.FieldMediaID: v, ok := value.(int) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.AddSeriesID(v) + m.AddMediaID(v) return nil case history.FieldEpisodeID: v, ok := value.(int) @@ -2525,8 +2525,8 @@ func (m *HistoryMutation) ClearField(name string) error { // It returns an error if the field is not defined in the schema. func (m *HistoryMutation) ResetField(name string) error { switch name { - case history.FieldSeriesID: - m.ResetSeriesID() + case history.FieldMediaID: + m.ResetMediaID() return nil case history.FieldEpisodeID: m.ResetEpisodeID() @@ -3179,8 +3179,8 @@ func (m *IndexersMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Indexers edge %s", name) } -// SeriesMutation represents an operation that mutates the Series nodes in the graph. -type SeriesMutation struct { +// MediaMutation represents an operation that mutates the Media nodes in the graph. +type MediaMutation struct { config op Op typ string @@ -3188,11 +3188,11 @@ type SeriesMutation struct { tmdb_id *int addtmdb_id *int imdb_id *string + media_type *media.MediaType name_cn *string name_en *string original_name *string overview *string - poster_path *string created_at *time.Time air_date *string resolution *string @@ -3204,21 +3204,21 @@ type SeriesMutation struct { removedepisodes map[int]struct{} clearedepisodes bool done bool - oldValue func(context.Context) (*Series, error) - predicates []predicate.Series + oldValue func(context.Context) (*Media, error) + predicates []predicate.Media } -var _ ent.Mutation = (*SeriesMutation)(nil) +var _ ent.Mutation = (*MediaMutation)(nil) -// seriesOption allows management of the mutation configuration using functional options. -type seriesOption func(*SeriesMutation) +// mediaOption allows management of the mutation configuration using functional options. +type mediaOption func(*MediaMutation) -// newSeriesMutation creates new mutation for the Series entity. -func newSeriesMutation(c config, op Op, opts ...seriesOption) *SeriesMutation { - m := &SeriesMutation{ +// newMediaMutation creates new mutation for the Media entity. +func newMediaMutation(c config, op Op, opts ...mediaOption) *MediaMutation { + m := &MediaMutation{ config: c, op: op, - typ: TypeSeries, + typ: TypeMedia, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -3227,20 +3227,20 @@ func newSeriesMutation(c config, op Op, opts ...seriesOption) *SeriesMutation { return m } -// withSeriesID sets the ID field of the mutation. -func withSeriesID(id int) seriesOption { - return func(m *SeriesMutation) { +// withMediaID sets the ID field of the mutation. +func withMediaID(id int) mediaOption { + return func(m *MediaMutation) { var ( err error once sync.Once - value *Series + value *Media ) - m.oldValue = func(ctx context.Context) (*Series, error) { + m.oldValue = func(ctx context.Context) (*Media, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().Series.Get(ctx, id) + value, err = m.Client().Media.Get(ctx, id) } }) return value, err @@ -3249,10 +3249,10 @@ func withSeriesID(id int) seriesOption { } } -// withSeries sets the old Series of the mutation. -func withSeries(node *Series) seriesOption { - return func(m *SeriesMutation) { - m.oldValue = func(context.Context) (*Series, error) { +// withMedia sets the old Media of the mutation. +func withMedia(node *Media) mediaOption { + return func(m *MediaMutation) { + m.oldValue = func(context.Context) (*Media, error) { return node, nil } m.id = &node.ID @@ -3261,7 +3261,7 @@ func withSeries(node *Series) seriesOption { // Client returns a new `ent.Client` from the mutation. If the mutation was // executed in a transaction (ent.Tx), a transactional client is returned. -func (m SeriesMutation) Client() *Client { +func (m MediaMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -3269,7 +3269,7 @@ func (m SeriesMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m SeriesMutation) Tx() (*Tx, error) { +func (m MediaMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("ent: mutation is not running in a transaction") } @@ -3280,7 +3280,7 @@ func (m SeriesMutation) Tx() (*Tx, error) { // ID returns the ID value in the mutation. Note that the ID is only available // if it was provided to the builder or after it was returned from the database. -func (m *SeriesMutation) ID() (id int, exists bool) { +func (m *MediaMutation) ID() (id int, exists bool) { if m.id == nil { return } @@ -3291,7 +3291,7 @@ func (m *SeriesMutation) ID() (id int, exists bool) { // That means, if the mutation is applied within a transaction with an isolation level such // as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated // or updated by the mutation. -func (m *SeriesMutation) IDs(ctx context.Context) ([]int, error) { +func (m *MediaMutation) IDs(ctx context.Context) ([]int, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -3300,20 +3300,20 @@ func (m *SeriesMutation) IDs(ctx context.Context) ([]int, error) { } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().Series.Query().Where(m.predicates...).IDs(ctx) + return m.Client().Media.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } // SetTmdbID sets the "tmdb_id" field. -func (m *SeriesMutation) SetTmdbID(i int) { +func (m *MediaMutation) SetTmdbID(i int) { m.tmdb_id = &i m.addtmdb_id = nil } // TmdbID returns the value of the "tmdb_id" field in the mutation. -func (m *SeriesMutation) TmdbID() (r int, exists bool) { +func (m *MediaMutation) TmdbID() (r int, exists bool) { v := m.tmdb_id if v == nil { return @@ -3321,10 +3321,10 @@ func (m *SeriesMutation) TmdbID() (r int, exists bool) { return *v, true } -// OldTmdbID returns the old "tmdb_id" field's value of the Series entity. -// If the Series object wasn't provided to the builder, the object is fetched from the database. +// OldTmdbID returns the old "tmdb_id" field's value of the Media entity. +// If the Media object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SeriesMutation) OldTmdbID(ctx context.Context) (v int, err error) { +func (m *MediaMutation) OldTmdbID(ctx context.Context) (v int, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldTmdbID is only allowed on UpdateOne operations") } @@ -3339,7 +3339,7 @@ func (m *SeriesMutation) OldTmdbID(ctx context.Context) (v int, err error) { } // AddTmdbID adds i to the "tmdb_id" field. -func (m *SeriesMutation) AddTmdbID(i int) { +func (m *MediaMutation) AddTmdbID(i int) { if m.addtmdb_id != nil { *m.addtmdb_id += i } else { @@ -3348,7 +3348,7 @@ func (m *SeriesMutation) AddTmdbID(i int) { } // AddedTmdbID returns the value that was added to the "tmdb_id" field in this mutation. -func (m *SeriesMutation) AddedTmdbID() (r int, exists bool) { +func (m *MediaMutation) AddedTmdbID() (r int, exists bool) { v := m.addtmdb_id if v == nil { return @@ -3357,18 +3357,18 @@ func (m *SeriesMutation) AddedTmdbID() (r int, exists bool) { } // ResetTmdbID resets all changes to the "tmdb_id" field. -func (m *SeriesMutation) ResetTmdbID() { +func (m *MediaMutation) ResetTmdbID() { m.tmdb_id = nil m.addtmdb_id = nil } // SetImdbID sets the "imdb_id" field. -func (m *SeriesMutation) SetImdbID(s string) { +func (m *MediaMutation) SetImdbID(s string) { m.imdb_id = &s } // ImdbID returns the value of the "imdb_id" field in the mutation. -func (m *SeriesMutation) ImdbID() (r string, exists bool) { +func (m *MediaMutation) ImdbID() (r string, exists bool) { v := m.imdb_id if v == nil { return @@ -3376,10 +3376,10 @@ func (m *SeriesMutation) ImdbID() (r string, exists bool) { return *v, true } -// OldImdbID returns the old "imdb_id" field's value of the Series entity. -// If the Series object wasn't provided to the builder, the object is fetched from the database. +// OldImdbID returns the old "imdb_id" field's value of the Media entity. +// If the Media object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SeriesMutation) OldImdbID(ctx context.Context) (v string, err error) { +func (m *MediaMutation) OldImdbID(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldImdbID is only allowed on UpdateOne operations") } @@ -3394,30 +3394,66 @@ func (m *SeriesMutation) OldImdbID(ctx context.Context) (v string, err error) { } // ClearImdbID clears the value of the "imdb_id" field. -func (m *SeriesMutation) ClearImdbID() { +func (m *MediaMutation) ClearImdbID() { m.imdb_id = nil - m.clearedFields[series.FieldImdbID] = struct{}{} + m.clearedFields[media.FieldImdbID] = struct{}{} } // ImdbIDCleared returns if the "imdb_id" field was cleared in this mutation. -func (m *SeriesMutation) ImdbIDCleared() bool { - _, ok := m.clearedFields[series.FieldImdbID] +func (m *MediaMutation) ImdbIDCleared() bool { + _, ok := m.clearedFields[media.FieldImdbID] return ok } // ResetImdbID resets all changes to the "imdb_id" field. -func (m *SeriesMutation) ResetImdbID() { +func (m *MediaMutation) ResetImdbID() { m.imdb_id = nil - delete(m.clearedFields, series.FieldImdbID) + delete(m.clearedFields, media.FieldImdbID) +} + +// SetMediaType sets the "media_type" field. +func (m *MediaMutation) SetMediaType(mt media.MediaType) { + m.media_type = &mt +} + +// MediaType returns the value of the "media_type" field in the mutation. +func (m *MediaMutation) MediaType() (r media.MediaType, exists bool) { + v := m.media_type + if v == nil { + return + } + return *v, true +} + +// OldMediaType returns the old "media_type" field's value of the Media entity. +// If the Media object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *MediaMutation) OldMediaType(ctx context.Context) (v media.MediaType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMediaType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMediaType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMediaType: %w", err) + } + return oldValue.MediaType, nil +} + +// ResetMediaType resets all changes to the "media_type" field. +func (m *MediaMutation) ResetMediaType() { + m.media_type = nil } // SetNameCn sets the "name_cn" field. -func (m *SeriesMutation) SetNameCn(s string) { +func (m *MediaMutation) SetNameCn(s string) { m.name_cn = &s } // NameCn returns the value of the "name_cn" field in the mutation. -func (m *SeriesMutation) NameCn() (r string, exists bool) { +func (m *MediaMutation) NameCn() (r string, exists bool) { v := m.name_cn if v == nil { return @@ -3425,10 +3461,10 @@ func (m *SeriesMutation) NameCn() (r string, exists bool) { return *v, true } -// OldNameCn returns the old "name_cn" field's value of the Series entity. -// If the Series object wasn't provided to the builder, the object is fetched from the database. +// OldNameCn returns the old "name_cn" field's value of the Media entity. +// If the Media object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SeriesMutation) OldNameCn(ctx context.Context) (v string, err error) { +func (m *MediaMutation) OldNameCn(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldNameCn is only allowed on UpdateOne operations") } @@ -3443,17 +3479,17 @@ func (m *SeriesMutation) OldNameCn(ctx context.Context) (v string, err error) { } // ResetNameCn resets all changes to the "name_cn" field. -func (m *SeriesMutation) ResetNameCn() { +func (m *MediaMutation) ResetNameCn() { m.name_cn = nil } // SetNameEn sets the "name_en" field. -func (m *SeriesMutation) SetNameEn(s string) { +func (m *MediaMutation) SetNameEn(s string) { m.name_en = &s } // NameEn returns the value of the "name_en" field in the mutation. -func (m *SeriesMutation) NameEn() (r string, exists bool) { +func (m *MediaMutation) NameEn() (r string, exists bool) { v := m.name_en if v == nil { return @@ -3461,10 +3497,10 @@ func (m *SeriesMutation) NameEn() (r string, exists bool) { return *v, true } -// OldNameEn returns the old "name_en" field's value of the Series entity. -// If the Series object wasn't provided to the builder, the object is fetched from the database. +// OldNameEn returns the old "name_en" field's value of the Media entity. +// If the Media object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SeriesMutation) OldNameEn(ctx context.Context) (v string, err error) { +func (m *MediaMutation) OldNameEn(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldNameEn is only allowed on UpdateOne operations") } @@ -3479,17 +3515,17 @@ func (m *SeriesMutation) OldNameEn(ctx context.Context) (v string, err error) { } // ResetNameEn resets all changes to the "name_en" field. -func (m *SeriesMutation) ResetNameEn() { +func (m *MediaMutation) ResetNameEn() { m.name_en = nil } // SetOriginalName sets the "original_name" field. -func (m *SeriesMutation) SetOriginalName(s string) { +func (m *MediaMutation) SetOriginalName(s string) { m.original_name = &s } // OriginalName returns the value of the "original_name" field in the mutation. -func (m *SeriesMutation) OriginalName() (r string, exists bool) { +func (m *MediaMutation) OriginalName() (r string, exists bool) { v := m.original_name if v == nil { return @@ -3497,10 +3533,10 @@ func (m *SeriesMutation) OriginalName() (r string, exists bool) { return *v, true } -// OldOriginalName returns the old "original_name" field's value of the Series entity. -// If the Series object wasn't provided to the builder, the object is fetched from the database. +// OldOriginalName returns the old "original_name" field's value of the Media entity. +// If the Media object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SeriesMutation) OldOriginalName(ctx context.Context) (v string, err error) { +func (m *MediaMutation) OldOriginalName(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldOriginalName is only allowed on UpdateOne operations") } @@ -3515,17 +3551,17 @@ func (m *SeriesMutation) OldOriginalName(ctx context.Context) (v string, err err } // ResetOriginalName resets all changes to the "original_name" field. -func (m *SeriesMutation) ResetOriginalName() { +func (m *MediaMutation) ResetOriginalName() { m.original_name = nil } // SetOverview sets the "overview" field. -func (m *SeriesMutation) SetOverview(s string) { +func (m *MediaMutation) SetOverview(s string) { m.overview = &s } // Overview returns the value of the "overview" field in the mutation. -func (m *SeriesMutation) Overview() (r string, exists bool) { +func (m *MediaMutation) Overview() (r string, exists bool) { v := m.overview if v == nil { return @@ -3533,10 +3569,10 @@ func (m *SeriesMutation) Overview() (r string, exists bool) { return *v, true } -// OldOverview returns the old "overview" field's value of the Series entity. -// If the Series object wasn't provided to the builder, the object is fetched from the database. +// OldOverview returns the old "overview" field's value of the Media entity. +// If the Media object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SeriesMutation) OldOverview(ctx context.Context) (v string, err error) { +func (m *MediaMutation) OldOverview(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldOverview is only allowed on UpdateOne operations") } @@ -3551,66 +3587,17 @@ func (m *SeriesMutation) OldOverview(ctx context.Context) (v string, err error) } // ResetOverview resets all changes to the "overview" field. -func (m *SeriesMutation) ResetOverview() { +func (m *MediaMutation) ResetOverview() { m.overview = nil } -// SetPosterPath sets the "poster_path" field. -func (m *SeriesMutation) SetPosterPath(s string) { - m.poster_path = &s -} - -// PosterPath returns the value of the "poster_path" field in the mutation. -func (m *SeriesMutation) PosterPath() (r string, exists bool) { - v := m.poster_path - if v == nil { - return - } - return *v, true -} - -// OldPosterPath returns the old "poster_path" field's value of the Series entity. -// If the Series 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 *SeriesMutation) OldPosterPath(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPosterPath is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPosterPath requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldPosterPath: %w", err) - } - return oldValue.PosterPath, nil -} - -// ClearPosterPath clears the value of the "poster_path" field. -func (m *SeriesMutation) ClearPosterPath() { - m.poster_path = nil - m.clearedFields[series.FieldPosterPath] = struct{}{} -} - -// PosterPathCleared returns if the "poster_path" field was cleared in this mutation. -func (m *SeriesMutation) PosterPathCleared() bool { - _, ok := m.clearedFields[series.FieldPosterPath] - return ok -} - -// ResetPosterPath resets all changes to the "poster_path" field. -func (m *SeriesMutation) ResetPosterPath() { - m.poster_path = nil - delete(m.clearedFields, series.FieldPosterPath) -} - // SetCreatedAt sets the "created_at" field. -func (m *SeriesMutation) SetCreatedAt(t time.Time) { +func (m *MediaMutation) SetCreatedAt(t time.Time) { m.created_at = &t } // CreatedAt returns the value of the "created_at" field in the mutation. -func (m *SeriesMutation) CreatedAt() (r time.Time, exists bool) { +func (m *MediaMutation) CreatedAt() (r time.Time, exists bool) { v := m.created_at if v == nil { return @@ -3618,10 +3605,10 @@ func (m *SeriesMutation) CreatedAt() (r time.Time, exists bool) { return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the Series entity. -// If the Series object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the Media entity. +// If the Media object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SeriesMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *MediaMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } @@ -3636,17 +3623,17 @@ func (m *SeriesMutation) OldCreatedAt(ctx context.Context) (v time.Time, err err } // ResetCreatedAt resets all changes to the "created_at" field. -func (m *SeriesMutation) ResetCreatedAt() { +func (m *MediaMutation) ResetCreatedAt() { m.created_at = nil } // SetAirDate sets the "air_date" field. -func (m *SeriesMutation) SetAirDate(s string) { +func (m *MediaMutation) SetAirDate(s string) { m.air_date = &s } // AirDate returns the value of the "air_date" field in the mutation. -func (m *SeriesMutation) AirDate() (r string, exists bool) { +func (m *MediaMutation) AirDate() (r string, exists bool) { v := m.air_date if v == nil { return @@ -3654,10 +3641,10 @@ func (m *SeriesMutation) AirDate() (r string, exists bool) { return *v, true } -// OldAirDate returns the old "air_date" field's value of the Series entity. -// If the Series object wasn't provided to the builder, the object is fetched from the database. +// OldAirDate returns the old "air_date" field's value of the Media entity. +// If the Media object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SeriesMutation) OldAirDate(ctx context.Context) (v string, err error) { +func (m *MediaMutation) OldAirDate(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldAirDate is only allowed on UpdateOne operations") } @@ -3672,17 +3659,17 @@ func (m *SeriesMutation) OldAirDate(ctx context.Context) (v string, err error) { } // ResetAirDate resets all changes to the "air_date" field. -func (m *SeriesMutation) ResetAirDate() { +func (m *MediaMutation) ResetAirDate() { m.air_date = nil } // SetResolution sets the "resolution" field. -func (m *SeriesMutation) SetResolution(s string) { +func (m *MediaMutation) SetResolution(s string) { m.resolution = &s } // Resolution returns the value of the "resolution" field in the mutation. -func (m *SeriesMutation) Resolution() (r string, exists bool) { +func (m *MediaMutation) Resolution() (r string, exists bool) { v := m.resolution if v == nil { return @@ -3690,10 +3677,10 @@ func (m *SeriesMutation) Resolution() (r string, exists bool) { return *v, true } -// OldResolution returns the old "resolution" field's value of the Series entity. -// If the Series object wasn't provided to the builder, the object is fetched from the database. +// OldResolution returns the old "resolution" field's value of the Media entity. +// If the Media object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SeriesMutation) OldResolution(ctx context.Context) (v string, err error) { +func (m *MediaMutation) OldResolution(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldResolution is only allowed on UpdateOne operations") } @@ -3708,18 +3695,18 @@ func (m *SeriesMutation) OldResolution(ctx context.Context) (v string, err error } // ResetResolution resets all changes to the "resolution" field. -func (m *SeriesMutation) ResetResolution() { +func (m *MediaMutation) ResetResolution() { m.resolution = nil } // SetStorageID sets the "storage_id" field. -func (m *SeriesMutation) SetStorageID(i int) { +func (m *MediaMutation) SetStorageID(i int) { m.storage_id = &i m.addstorage_id = nil } // StorageID returns the value of the "storage_id" field in the mutation. -func (m *SeriesMutation) StorageID() (r int, exists bool) { +func (m *MediaMutation) StorageID() (r int, exists bool) { v := m.storage_id if v == nil { return @@ -3727,10 +3714,10 @@ func (m *SeriesMutation) StorageID() (r int, exists bool) { return *v, true } -// OldStorageID returns the old "storage_id" field's value of the Series entity. -// If the Series object wasn't provided to the builder, the object is fetched from the database. +// OldStorageID returns the old "storage_id" field's value of the Media entity. +// If the Media object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SeriesMutation) OldStorageID(ctx context.Context) (v int, err error) { +func (m *MediaMutation) OldStorageID(ctx context.Context) (v int, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldStorageID is only allowed on UpdateOne operations") } @@ -3745,7 +3732,7 @@ func (m *SeriesMutation) OldStorageID(ctx context.Context) (v int, err error) { } // AddStorageID adds i to the "storage_id" field. -func (m *SeriesMutation) AddStorageID(i int) { +func (m *MediaMutation) AddStorageID(i int) { if m.addstorage_id != nil { *m.addstorage_id += i } else { @@ -3754,7 +3741,7 @@ func (m *SeriesMutation) AddStorageID(i int) { } // AddedStorageID returns the value that was added to the "storage_id" field in this mutation. -func (m *SeriesMutation) AddedStorageID() (r int, exists bool) { +func (m *MediaMutation) AddedStorageID() (r int, exists bool) { v := m.addstorage_id if v == nil { return @@ -3763,32 +3750,32 @@ func (m *SeriesMutation) AddedStorageID() (r int, exists bool) { } // ClearStorageID clears the value of the "storage_id" field. -func (m *SeriesMutation) ClearStorageID() { +func (m *MediaMutation) ClearStorageID() { m.storage_id = nil m.addstorage_id = nil - m.clearedFields[series.FieldStorageID] = struct{}{} + m.clearedFields[media.FieldStorageID] = struct{}{} } // StorageIDCleared returns if the "storage_id" field was cleared in this mutation. -func (m *SeriesMutation) StorageIDCleared() bool { - _, ok := m.clearedFields[series.FieldStorageID] +func (m *MediaMutation) StorageIDCleared() bool { + _, ok := m.clearedFields[media.FieldStorageID] return ok } // ResetStorageID resets all changes to the "storage_id" field. -func (m *SeriesMutation) ResetStorageID() { +func (m *MediaMutation) ResetStorageID() { m.storage_id = nil m.addstorage_id = nil - delete(m.clearedFields, series.FieldStorageID) + delete(m.clearedFields, media.FieldStorageID) } // SetTargetDir sets the "target_dir" field. -func (m *SeriesMutation) SetTargetDir(s string) { +func (m *MediaMutation) SetTargetDir(s string) { m.target_dir = &s } // TargetDir returns the value of the "target_dir" field in the mutation. -func (m *SeriesMutation) TargetDir() (r string, exists bool) { +func (m *MediaMutation) TargetDir() (r string, exists bool) { v := m.target_dir if v == nil { return @@ -3796,10 +3783,10 @@ func (m *SeriesMutation) TargetDir() (r string, exists bool) { return *v, true } -// OldTargetDir returns the old "target_dir" field's value of the Series entity. -// If the Series object wasn't provided to the builder, the object is fetched from the database. +// OldTargetDir returns the old "target_dir" field's value of the Media entity. +// If the Media object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SeriesMutation) OldTargetDir(ctx context.Context) (v string, err error) { +func (m *MediaMutation) OldTargetDir(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldTargetDir is only allowed on UpdateOne operations") } @@ -3814,25 +3801,25 @@ func (m *SeriesMutation) OldTargetDir(ctx context.Context) (v string, err error) } // ClearTargetDir clears the value of the "target_dir" field. -func (m *SeriesMutation) ClearTargetDir() { +func (m *MediaMutation) ClearTargetDir() { m.target_dir = nil - m.clearedFields[series.FieldTargetDir] = struct{}{} + m.clearedFields[media.FieldTargetDir] = struct{}{} } // TargetDirCleared returns if the "target_dir" field was cleared in this mutation. -func (m *SeriesMutation) TargetDirCleared() bool { - _, ok := m.clearedFields[series.FieldTargetDir] +func (m *MediaMutation) TargetDirCleared() bool { + _, ok := m.clearedFields[media.FieldTargetDir] return ok } // ResetTargetDir resets all changes to the "target_dir" field. -func (m *SeriesMutation) ResetTargetDir() { +func (m *MediaMutation) ResetTargetDir() { m.target_dir = nil - delete(m.clearedFields, series.FieldTargetDir) + delete(m.clearedFields, media.FieldTargetDir) } // AddEpisodeIDs adds the "episodes" edge to the Episode entity by ids. -func (m *SeriesMutation) AddEpisodeIDs(ids ...int) { +func (m *MediaMutation) AddEpisodeIDs(ids ...int) { if m.episodes == nil { m.episodes = make(map[int]struct{}) } @@ -3842,17 +3829,17 @@ func (m *SeriesMutation) AddEpisodeIDs(ids ...int) { } // ClearEpisodes clears the "episodes" edge to the Episode entity. -func (m *SeriesMutation) ClearEpisodes() { +func (m *MediaMutation) ClearEpisodes() { m.clearedepisodes = true } // EpisodesCleared reports if the "episodes" edge to the Episode entity was cleared. -func (m *SeriesMutation) EpisodesCleared() bool { +func (m *MediaMutation) EpisodesCleared() bool { return m.clearedepisodes } // RemoveEpisodeIDs removes the "episodes" edge to the Episode entity by IDs. -func (m *SeriesMutation) RemoveEpisodeIDs(ids ...int) { +func (m *MediaMutation) RemoveEpisodeIDs(ids ...int) { if m.removedepisodes == nil { m.removedepisodes = make(map[int]struct{}) } @@ -3863,7 +3850,7 @@ func (m *SeriesMutation) RemoveEpisodeIDs(ids ...int) { } // RemovedEpisodes returns the removed IDs of the "episodes" edge to the Episode entity. -func (m *SeriesMutation) RemovedEpisodesIDs() (ids []int) { +func (m *MediaMutation) RemovedEpisodesIDs() (ids []int) { for id := range m.removedepisodes { ids = append(ids, id) } @@ -3871,7 +3858,7 @@ func (m *SeriesMutation) RemovedEpisodesIDs() (ids []int) { } // EpisodesIDs returns the "episodes" edge IDs in the mutation. -func (m *SeriesMutation) EpisodesIDs() (ids []int) { +func (m *MediaMutation) EpisodesIDs() (ids []int) { for id := range m.episodes { ids = append(ids, id) } @@ -3879,21 +3866,21 @@ func (m *SeriesMutation) EpisodesIDs() (ids []int) { } // ResetEpisodes resets all changes to the "episodes" edge. -func (m *SeriesMutation) ResetEpisodes() { +func (m *MediaMutation) ResetEpisodes() { m.episodes = nil m.clearedepisodes = false m.removedepisodes = nil } -// Where appends a list predicates to the SeriesMutation builder. -func (m *SeriesMutation) Where(ps ...predicate.Series) { +// Where appends a list predicates to the MediaMutation builder. +func (m *MediaMutation) Where(ps ...predicate.Media) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the SeriesMutation builder. Using this method, +// WhereP appends storage-level predicates to the MediaMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *SeriesMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.Series, len(ps)) +func (m *MediaMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Media, len(ps)) for i := range ps { p[i] = ps[i] } @@ -3901,60 +3888,60 @@ func (m *SeriesMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *SeriesMutation) Op() Op { +func (m *MediaMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *SeriesMutation) SetOp(op Op) { +func (m *MediaMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (Series). -func (m *SeriesMutation) Type() string { +// Type returns the node type of this mutation (Media). +func (m *MediaMutation) Type() string { return m.typ } // Fields returns all fields that were changed during this mutation. Note that in // order to get all numeric fields that were incremented/decremented, call // AddedFields(). -func (m *SeriesMutation) Fields() []string { +func (m *MediaMutation) Fields() []string { fields := make([]string, 0, 12) if m.tmdb_id != nil { - fields = append(fields, series.FieldTmdbID) + fields = append(fields, media.FieldTmdbID) } if m.imdb_id != nil { - fields = append(fields, series.FieldImdbID) + fields = append(fields, media.FieldImdbID) + } + if m.media_type != nil { + fields = append(fields, media.FieldMediaType) } if m.name_cn != nil { - fields = append(fields, series.FieldNameCn) + fields = append(fields, media.FieldNameCn) } if m.name_en != nil { - fields = append(fields, series.FieldNameEn) + fields = append(fields, media.FieldNameEn) } if m.original_name != nil { - fields = append(fields, series.FieldOriginalName) + fields = append(fields, media.FieldOriginalName) } if m.overview != nil { - fields = append(fields, series.FieldOverview) - } - if m.poster_path != nil { - fields = append(fields, series.FieldPosterPath) + fields = append(fields, media.FieldOverview) } if m.created_at != nil { - fields = append(fields, series.FieldCreatedAt) + fields = append(fields, media.FieldCreatedAt) } if m.air_date != nil { - fields = append(fields, series.FieldAirDate) + fields = append(fields, media.FieldAirDate) } if m.resolution != nil { - fields = append(fields, series.FieldResolution) + fields = append(fields, media.FieldResolution) } if m.storage_id != nil { - fields = append(fields, series.FieldStorageID) + fields = append(fields, media.FieldStorageID) } if m.target_dir != nil { - fields = append(fields, series.FieldTargetDir) + fields = append(fields, media.FieldTargetDir) } return fields } @@ -3962,31 +3949,31 @@ func (m *SeriesMutation) Fields() []string { // Field returns the value of a field with the given name. The second boolean // return value indicates that this field was not set, or was not defined in the // schema. -func (m *SeriesMutation) Field(name string) (ent.Value, bool) { +func (m *MediaMutation) Field(name string) (ent.Value, bool) { switch name { - case series.FieldTmdbID: + case media.FieldTmdbID: return m.TmdbID() - case series.FieldImdbID: + case media.FieldImdbID: return m.ImdbID() - case series.FieldNameCn: + case media.FieldMediaType: + return m.MediaType() + case media.FieldNameCn: return m.NameCn() - case series.FieldNameEn: + case media.FieldNameEn: return m.NameEn() - case series.FieldOriginalName: + case media.FieldOriginalName: return m.OriginalName() - case series.FieldOverview: + case media.FieldOverview: return m.Overview() - case series.FieldPosterPath: - return m.PosterPath() - case series.FieldCreatedAt: + case media.FieldCreatedAt: return m.CreatedAt() - case series.FieldAirDate: + case media.FieldAirDate: return m.AirDate() - case series.FieldResolution: + case media.FieldResolution: return m.Resolution() - case series.FieldStorageID: + case media.FieldStorageID: return m.StorageID() - case series.FieldTargetDir: + case media.FieldTargetDir: return m.TargetDir() } return nil, false @@ -3995,119 +3982,119 @@ func (m *SeriesMutation) Field(name string) (ent.Value, bool) { // OldField returns the old value of the field from the database. An error is // returned if the mutation operation is not UpdateOne, or the query to the // database failed. -func (m *SeriesMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *MediaMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case series.FieldTmdbID: + case media.FieldTmdbID: return m.OldTmdbID(ctx) - case series.FieldImdbID: + case media.FieldImdbID: return m.OldImdbID(ctx) - case series.FieldNameCn: + case media.FieldMediaType: + return m.OldMediaType(ctx) + case media.FieldNameCn: return m.OldNameCn(ctx) - case series.FieldNameEn: + case media.FieldNameEn: return m.OldNameEn(ctx) - case series.FieldOriginalName: + case media.FieldOriginalName: return m.OldOriginalName(ctx) - case series.FieldOverview: + case media.FieldOverview: return m.OldOverview(ctx) - case series.FieldPosterPath: - return m.OldPosterPath(ctx) - case series.FieldCreatedAt: + case media.FieldCreatedAt: return m.OldCreatedAt(ctx) - case series.FieldAirDate: + case media.FieldAirDate: return m.OldAirDate(ctx) - case series.FieldResolution: + case media.FieldResolution: return m.OldResolution(ctx) - case series.FieldStorageID: + case media.FieldStorageID: return m.OldStorageID(ctx) - case series.FieldTargetDir: + case media.FieldTargetDir: return m.OldTargetDir(ctx) } - return nil, fmt.Errorf("unknown Series field %s", name) + return nil, fmt.Errorf("unknown Media field %s", name) } // SetField sets the value of a field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *SeriesMutation) SetField(name string, value ent.Value) error { +func (m *MediaMutation) SetField(name string, value ent.Value) error { switch name { - case series.FieldTmdbID: + case media.FieldTmdbID: v, ok := value.(int) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetTmdbID(v) return nil - case series.FieldImdbID: + case media.FieldImdbID: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetImdbID(v) return nil - case series.FieldNameCn: + case media.FieldMediaType: + v, ok := value.(media.MediaType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMediaType(v) + return nil + case media.FieldNameCn: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetNameCn(v) return nil - case series.FieldNameEn: + case media.FieldNameEn: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetNameEn(v) return nil - case series.FieldOriginalName: + case media.FieldOriginalName: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetOriginalName(v) return nil - case series.FieldOverview: + case media.FieldOverview: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetOverview(v) return nil - case series.FieldPosterPath: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetPosterPath(v) - return nil - case series.FieldCreatedAt: + case media.FieldCreatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetCreatedAt(v) return nil - case series.FieldAirDate: + case media.FieldAirDate: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetAirDate(v) return nil - case series.FieldResolution: + case media.FieldResolution: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetResolution(v) return nil - case series.FieldStorageID: + case media.FieldStorageID: v, ok := value.(int) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetStorageID(v) return nil - case series.FieldTargetDir: + case media.FieldTargetDir: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) @@ -4115,18 +4102,18 @@ func (m *SeriesMutation) SetField(name string, value ent.Value) error { m.SetTargetDir(v) return nil } - return fmt.Errorf("unknown Series field %s", name) + return fmt.Errorf("unknown Media field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *SeriesMutation) AddedFields() []string { +func (m *MediaMutation) AddedFields() []string { var fields []string if m.addtmdb_id != nil { - fields = append(fields, series.FieldTmdbID) + fields = append(fields, media.FieldTmdbID) } if m.addstorage_id != nil { - fields = append(fields, series.FieldStorageID) + fields = append(fields, media.FieldStorageID) } return fields } @@ -4134,11 +4121,11 @@ func (m *SeriesMutation) AddedFields() []string { // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *SeriesMutation) AddedField(name string) (ent.Value, bool) { +func (m *MediaMutation) AddedField(name string) (ent.Value, bool) { switch name { - case series.FieldTmdbID: + case media.FieldTmdbID: return m.AddedTmdbID() - case series.FieldStorageID: + case media.FieldStorageID: return m.AddedStorageID() } return nil, false @@ -4147,16 +4134,16 @@ func (m *SeriesMutation) AddedField(name string) (ent.Value, bool) { // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *SeriesMutation) AddField(name string, value ent.Value) error { +func (m *MediaMutation) AddField(name string, value ent.Value) error { switch name { - case series.FieldTmdbID: + case media.FieldTmdbID: v, ok := value.(int) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.AddTmdbID(v) return nil - case series.FieldStorageID: + case media.FieldStorageID: v, ok := value.(int) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) @@ -4164,113 +4151,107 @@ func (m *SeriesMutation) AddField(name string, value ent.Value) error { m.AddStorageID(v) return nil } - return fmt.Errorf("unknown Series numeric field %s", name) + return fmt.Errorf("unknown Media numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *SeriesMutation) ClearedFields() []string { +func (m *MediaMutation) ClearedFields() []string { var fields []string - if m.FieldCleared(series.FieldImdbID) { - fields = append(fields, series.FieldImdbID) + if m.FieldCleared(media.FieldImdbID) { + fields = append(fields, media.FieldImdbID) } - if m.FieldCleared(series.FieldPosterPath) { - fields = append(fields, series.FieldPosterPath) + if m.FieldCleared(media.FieldStorageID) { + fields = append(fields, media.FieldStorageID) } - if m.FieldCleared(series.FieldStorageID) { - fields = append(fields, series.FieldStorageID) - } - if m.FieldCleared(series.FieldTargetDir) { - fields = append(fields, series.FieldTargetDir) + if m.FieldCleared(media.FieldTargetDir) { + fields = append(fields, media.FieldTargetDir) } return fields } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *SeriesMutation) FieldCleared(name string) bool { +func (m *MediaMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } // ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. -func (m *SeriesMutation) ClearField(name string) error { +func (m *MediaMutation) ClearField(name string) error { switch name { - case series.FieldImdbID: + case media.FieldImdbID: m.ClearImdbID() return nil - case series.FieldPosterPath: - m.ClearPosterPath() - return nil - case series.FieldStorageID: + case media.FieldStorageID: m.ClearStorageID() return nil - case series.FieldTargetDir: + case media.FieldTargetDir: m.ClearTargetDir() return nil } - return fmt.Errorf("unknown Series nullable field %s", name) + return fmt.Errorf("unknown Media nullable field %s", name) } // ResetField resets all changes in the mutation for the field with the given name. // It returns an error if the field is not defined in the schema. -func (m *SeriesMutation) ResetField(name string) error { +func (m *MediaMutation) ResetField(name string) error { switch name { - case series.FieldTmdbID: + case media.FieldTmdbID: m.ResetTmdbID() return nil - case series.FieldImdbID: + case media.FieldImdbID: m.ResetImdbID() return nil - case series.FieldNameCn: + case media.FieldMediaType: + m.ResetMediaType() + return nil + case media.FieldNameCn: m.ResetNameCn() return nil - case series.FieldNameEn: + case media.FieldNameEn: m.ResetNameEn() return nil - case series.FieldOriginalName: + case media.FieldOriginalName: m.ResetOriginalName() return nil - case series.FieldOverview: + case media.FieldOverview: m.ResetOverview() return nil - case series.FieldPosterPath: - m.ResetPosterPath() - return nil - case series.FieldCreatedAt: + case media.FieldCreatedAt: m.ResetCreatedAt() return nil - case series.FieldAirDate: + case media.FieldAirDate: m.ResetAirDate() return nil - case series.FieldResolution: + case media.FieldResolution: m.ResetResolution() return nil - case series.FieldStorageID: + case media.FieldStorageID: m.ResetStorageID() return nil - case series.FieldTargetDir: + case media.FieldTargetDir: m.ResetTargetDir() return nil } - return fmt.Errorf("unknown Series field %s", name) + return fmt.Errorf("unknown Media field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *SeriesMutation) AddedEdges() []string { +func (m *MediaMutation) AddedEdges() []string { edges := make([]string, 0, 1) if m.episodes != nil { - edges = append(edges, series.EdgeEpisodes) + edges = append(edges, media.EdgeEpisodes) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *SeriesMutation) AddedIDs(name string) []ent.Value { +func (m *MediaMutation) AddedIDs(name string) []ent.Value { switch name { - case series.EdgeEpisodes: + case media.EdgeEpisodes: ids := make([]ent.Value, 0, len(m.episodes)) for id := range m.episodes { ids = append(ids, id) @@ -4281,19 +4262,19 @@ func (m *SeriesMutation) AddedIDs(name string) []ent.Value { } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *SeriesMutation) RemovedEdges() []string { +func (m *MediaMutation) RemovedEdges() []string { edges := make([]string, 0, 1) if m.removedepisodes != nil { - edges = append(edges, series.EdgeEpisodes) + edges = append(edges, media.EdgeEpisodes) } return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *SeriesMutation) RemovedIDs(name string) []ent.Value { +func (m *MediaMutation) RemovedIDs(name string) []ent.Value { switch name { - case series.EdgeEpisodes: + case media.EdgeEpisodes: ids := make([]ent.Value, 0, len(m.removedepisodes)) for id := range m.removedepisodes { ids = append(ids, id) @@ -4304,19 +4285,19 @@ func (m *SeriesMutation) RemovedIDs(name string) []ent.Value { } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *SeriesMutation) ClearedEdges() []string { +func (m *MediaMutation) ClearedEdges() []string { edges := make([]string, 0, 1) if m.clearedepisodes { - edges = append(edges, series.EdgeEpisodes) + edges = append(edges, media.EdgeEpisodes) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *SeriesMutation) EdgeCleared(name string) bool { +func (m *MediaMutation) EdgeCleared(name string) bool { switch name { - case series.EdgeEpisodes: + case media.EdgeEpisodes: return m.clearedepisodes } return false @@ -4324,21 +4305,21 @@ func (m *SeriesMutation) EdgeCleared(name string) bool { // ClearEdge clears the value of the edge with the given name. It returns an error // if that edge is not defined in the schema. -func (m *SeriesMutation) ClearEdge(name string) error { +func (m *MediaMutation) ClearEdge(name string) error { switch name { } - return fmt.Errorf("unknown Series unique edge %s", name) + return fmt.Errorf("unknown Media unique edge %s", name) } // ResetEdge resets all changes to the edge with the given name in this mutation. // It returns an error if the edge is not defined in the schema. -func (m *SeriesMutation) ResetEdge(name string) error { +func (m *MediaMutation) ResetEdge(name string) error { switch name { - case series.EdgeEpisodes: + case media.EdgeEpisodes: m.ResetEpisodes() return nil } - return fmt.Errorf("unknown Series edge %s", name) + return fmt.Errorf("unknown Media edge %s", name) } // SettingsMutation represents an operation that mutates the Settings nodes in the graph. diff --git a/ent/predicate/predicate.go b/ent/predicate/predicate.go index 9000e59..8a8db0b 100644 --- a/ent/predicate/predicate.go +++ b/ent/predicate/predicate.go @@ -18,8 +18,8 @@ type History func(*sql.Selector) // Indexers is the predicate function for indexers builders. type Indexers func(*sql.Selector) -// Series is the predicate function for series builders. -type Series func(*sql.Selector) +// Media is the predicate function for media builders. +type Media func(*sql.Selector) // Settings is the predicate function for settings builders. type Settings func(*sql.Selector) diff --git a/ent/runtime.go b/ent/runtime.go index 28b4b6c..19589ba 100644 --- a/ent/runtime.go +++ b/ent/runtime.go @@ -6,8 +6,8 @@ import ( "polaris/ent/downloadclients" "polaris/ent/history" "polaris/ent/indexers" + "polaris/ent/media" "polaris/ent/schema" - "polaris/ent/series" "polaris/ent/storage" "time" ) @@ -60,20 +60,20 @@ func init() { indexersDescEnableRss := indexersFields[3].Descriptor() // indexers.DefaultEnableRss holds the default value on creation for the enable_rss field. indexers.DefaultEnableRss = indexersDescEnableRss.Default.(bool) - seriesFields := schema.Series{}.Fields() - _ = seriesFields - // seriesDescCreatedAt is the schema descriptor for created_at field. - seriesDescCreatedAt := seriesFields[7].Descriptor() - // series.DefaultCreatedAt holds the default value on creation for the created_at field. - series.DefaultCreatedAt = seriesDescCreatedAt.Default.(time.Time) - // seriesDescAirDate is the schema descriptor for air_date field. - seriesDescAirDate := seriesFields[8].Descriptor() - // series.DefaultAirDate holds the default value on creation for the air_date field. - series.DefaultAirDate = seriesDescAirDate.Default.(string) - // seriesDescResolution is the schema descriptor for resolution field. - seriesDescResolution := seriesFields[9].Descriptor() - // series.DefaultResolution holds the default value on creation for the resolution field. - series.DefaultResolution = seriesDescResolution.Default.(string) + mediaFields := schema.Media{}.Fields() + _ = mediaFields + // mediaDescCreatedAt is the schema descriptor for created_at field. + mediaDescCreatedAt := mediaFields[7].Descriptor() + // media.DefaultCreatedAt holds the default value on creation for the created_at field. + media.DefaultCreatedAt = mediaDescCreatedAt.Default.(time.Time) + // mediaDescAirDate is the schema descriptor for air_date field. + mediaDescAirDate := mediaFields[8].Descriptor() + // media.DefaultAirDate holds the default value on creation for the air_date field. + media.DefaultAirDate = mediaDescAirDate.Default.(string) + // mediaDescResolution is the schema descriptor for resolution field. + mediaDescResolution := mediaFields[9].Descriptor() + // media.DefaultResolution holds the default value on creation for the resolution field. + media.DefaultResolution = mediaDescResolution.Default.(string) storageFields := schema.Storage{}.Fields() _ = storageFields // storageDescDeleted is the schema descriptor for deleted field. diff --git a/ent/schema/episode.go b/ent/schema/episode.go index 9ada290..dda8f58 100644 --- a/ent/schema/episode.go +++ b/ent/schema/episode.go @@ -14,7 +14,7 @@ type Episode struct { // Fields of the Episode. func (Episode) Fields() []ent.Field { return []ent.Field{ - field.Int("series_id").Optional(), + field.Int("media_id").Optional(), field.Int("season_number").StructTag("json:\"season_number\""), field.Int("episode_number").StructTag("json:\"episode_number\""), field.String("title"), @@ -28,10 +28,10 @@ func (Episode) Fields() []ent.Field { // Edges of the Episode. func (Episode) Edges() []ent.Edge { return []ent.Edge{ - edge.From("series", Series.Type). + edge.From("media", Media.Type). Ref("episodes"). Unique(). - Field("series_id"), + Field("media_id"), } } diff --git a/ent/schema/history.go b/ent/schema/history.go index 2f9d022..0b82b2e 100644 --- a/ent/schema/history.go +++ b/ent/schema/history.go @@ -13,8 +13,8 @@ type History struct { // Fields of the History. func (History) Fields() []ent.Field { return []ent.Field{ - field.Int("series_id"), - field.Int("episode_id"), + field.Int("media_id"), + field.Int("episode_id").Optional(), field.String("source_title"), field.Time("date"), field.String("target_dir"), diff --git a/ent/schema/series.go b/ent/schema/media.go similarity index 63% rename from ent/schema/series.go rename to ent/schema/media.go index 8402b85..759aac9 100644 --- a/ent/schema/series.go +++ b/ent/schema/media.go @@ -8,33 +8,32 @@ import ( "entgo.io/ent/schema/field" ) -// Series holds the schema definition for the Series entity. -type Series struct { +// Media holds the schema definition for the Media entity. +type Media struct { ent.Schema } -// Fields of the Series. -func (Series) Fields() []ent.Field { +// Fields of the Media. +func (Media) Fields() []ent.Field { return []ent.Field{ field.Int("tmdb_id"), field.String("imdb_id").Optional(), + field.Enum("media_type").Values("tv", "movie"), field.String("name_cn"), field.String("name_en"), field.String("original_name"), field.String("overview"), - field.String("poster_path").Optional(), field.Time("created_at").Default(time.Now()), field.String("air_date").Default(""), - field.String("resolution").Default(""), + field.Enum("resolution").Values("720p", "1080p", "4k").Default("1080p"), field.Int("storage_id").Optional(), field.String("target_dir").Optional(), } } -// Edges of the Series. -func (Series) Edges() []ent.Edge { +// Edges of the Media. +func (Media) Edges() []ent.Edge { return []ent.Edge{ edge.To("episodes", Episode.Type), } - } diff --git a/ent/series/where.go b/ent/series/where.go deleted file mode 100644 index 44bbf35..0000000 --- a/ent/series/where.go +++ /dev/null @@ -1,899 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package series - -import ( - "polaris/ent/predicate" - "time" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" -) - -// ID filters vertices based on their ID field. -func ID(id int) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldID, id)) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id int) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldID, id)) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id int) predicate.Series { - return predicate.Series(sql.FieldNEQ(FieldID, id)) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...int) predicate.Series { - return predicate.Series(sql.FieldIn(FieldID, ids...)) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...int) predicate.Series { - return predicate.Series(sql.FieldNotIn(FieldID, ids...)) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id int) predicate.Series { - return predicate.Series(sql.FieldGT(FieldID, id)) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id int) predicate.Series { - return predicate.Series(sql.FieldGTE(FieldID, id)) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id int) predicate.Series { - return predicate.Series(sql.FieldLT(FieldID, id)) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id int) predicate.Series { - return predicate.Series(sql.FieldLTE(FieldID, id)) -} - -// TmdbID applies equality check predicate on the "tmdb_id" field. It's identical to TmdbIDEQ. -func TmdbID(v int) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldTmdbID, v)) -} - -// ImdbID applies equality check predicate on the "imdb_id" field. It's identical to ImdbIDEQ. -func ImdbID(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldImdbID, v)) -} - -// NameCn applies equality check predicate on the "name_cn" field. It's identical to NameCnEQ. -func NameCn(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldNameCn, v)) -} - -// NameEn applies equality check predicate on the "name_en" field. It's identical to NameEnEQ. -func NameEn(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldNameEn, v)) -} - -// OriginalName applies equality check predicate on the "original_name" field. It's identical to OriginalNameEQ. -func OriginalName(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldOriginalName, v)) -} - -// Overview applies equality check predicate on the "overview" field. It's identical to OverviewEQ. -func Overview(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldOverview, v)) -} - -// PosterPath applies equality check predicate on the "poster_path" field. It's identical to PosterPathEQ. -func PosterPath(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldPosterPath, v)) -} - -// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. -func CreatedAt(v time.Time) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldCreatedAt, v)) -} - -// AirDate applies equality check predicate on the "air_date" field. It's identical to AirDateEQ. -func AirDate(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldAirDate, v)) -} - -// Resolution applies equality check predicate on the "resolution" field. It's identical to ResolutionEQ. -func Resolution(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldResolution, v)) -} - -// StorageID applies equality check predicate on the "storage_id" field. It's identical to StorageIDEQ. -func StorageID(v int) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldStorageID, v)) -} - -// TargetDir applies equality check predicate on the "target_dir" field. It's identical to TargetDirEQ. -func TargetDir(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldTargetDir, v)) -} - -// TmdbIDEQ applies the EQ predicate on the "tmdb_id" field. -func TmdbIDEQ(v int) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldTmdbID, v)) -} - -// TmdbIDNEQ applies the NEQ predicate on the "tmdb_id" field. -func TmdbIDNEQ(v int) predicate.Series { - return predicate.Series(sql.FieldNEQ(FieldTmdbID, v)) -} - -// TmdbIDIn applies the In predicate on the "tmdb_id" field. -func TmdbIDIn(vs ...int) predicate.Series { - return predicate.Series(sql.FieldIn(FieldTmdbID, vs...)) -} - -// TmdbIDNotIn applies the NotIn predicate on the "tmdb_id" field. -func TmdbIDNotIn(vs ...int) predicate.Series { - return predicate.Series(sql.FieldNotIn(FieldTmdbID, vs...)) -} - -// TmdbIDGT applies the GT predicate on the "tmdb_id" field. -func TmdbIDGT(v int) predicate.Series { - return predicate.Series(sql.FieldGT(FieldTmdbID, v)) -} - -// TmdbIDGTE applies the GTE predicate on the "tmdb_id" field. -func TmdbIDGTE(v int) predicate.Series { - return predicate.Series(sql.FieldGTE(FieldTmdbID, v)) -} - -// TmdbIDLT applies the LT predicate on the "tmdb_id" field. -func TmdbIDLT(v int) predicate.Series { - return predicate.Series(sql.FieldLT(FieldTmdbID, v)) -} - -// TmdbIDLTE applies the LTE predicate on the "tmdb_id" field. -func TmdbIDLTE(v int) predicate.Series { - return predicate.Series(sql.FieldLTE(FieldTmdbID, v)) -} - -// ImdbIDEQ applies the EQ predicate on the "imdb_id" field. -func ImdbIDEQ(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldImdbID, v)) -} - -// ImdbIDNEQ applies the NEQ predicate on the "imdb_id" field. -func ImdbIDNEQ(v string) predicate.Series { - return predicate.Series(sql.FieldNEQ(FieldImdbID, v)) -} - -// ImdbIDIn applies the In predicate on the "imdb_id" field. -func ImdbIDIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldIn(FieldImdbID, vs...)) -} - -// ImdbIDNotIn applies the NotIn predicate on the "imdb_id" field. -func ImdbIDNotIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldNotIn(FieldImdbID, vs...)) -} - -// ImdbIDGT applies the GT predicate on the "imdb_id" field. -func ImdbIDGT(v string) predicate.Series { - return predicate.Series(sql.FieldGT(FieldImdbID, v)) -} - -// ImdbIDGTE applies the GTE predicate on the "imdb_id" field. -func ImdbIDGTE(v string) predicate.Series { - return predicate.Series(sql.FieldGTE(FieldImdbID, v)) -} - -// ImdbIDLT applies the LT predicate on the "imdb_id" field. -func ImdbIDLT(v string) predicate.Series { - return predicate.Series(sql.FieldLT(FieldImdbID, v)) -} - -// ImdbIDLTE applies the LTE predicate on the "imdb_id" field. -func ImdbIDLTE(v string) predicate.Series { - return predicate.Series(sql.FieldLTE(FieldImdbID, v)) -} - -// ImdbIDContains applies the Contains predicate on the "imdb_id" field. -func ImdbIDContains(v string) predicate.Series { - return predicate.Series(sql.FieldContains(FieldImdbID, v)) -} - -// ImdbIDHasPrefix applies the HasPrefix predicate on the "imdb_id" field. -func ImdbIDHasPrefix(v string) predicate.Series { - return predicate.Series(sql.FieldHasPrefix(FieldImdbID, v)) -} - -// ImdbIDHasSuffix applies the HasSuffix predicate on the "imdb_id" field. -func ImdbIDHasSuffix(v string) predicate.Series { - return predicate.Series(sql.FieldHasSuffix(FieldImdbID, v)) -} - -// ImdbIDIsNil applies the IsNil predicate on the "imdb_id" field. -func ImdbIDIsNil() predicate.Series { - return predicate.Series(sql.FieldIsNull(FieldImdbID)) -} - -// ImdbIDNotNil applies the NotNil predicate on the "imdb_id" field. -func ImdbIDNotNil() predicate.Series { - return predicate.Series(sql.FieldNotNull(FieldImdbID)) -} - -// ImdbIDEqualFold applies the EqualFold predicate on the "imdb_id" field. -func ImdbIDEqualFold(v string) predicate.Series { - return predicate.Series(sql.FieldEqualFold(FieldImdbID, v)) -} - -// ImdbIDContainsFold applies the ContainsFold predicate on the "imdb_id" field. -func ImdbIDContainsFold(v string) predicate.Series { - return predicate.Series(sql.FieldContainsFold(FieldImdbID, v)) -} - -// NameCnEQ applies the EQ predicate on the "name_cn" field. -func NameCnEQ(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldNameCn, v)) -} - -// NameCnNEQ applies the NEQ predicate on the "name_cn" field. -func NameCnNEQ(v string) predicate.Series { - return predicate.Series(sql.FieldNEQ(FieldNameCn, v)) -} - -// NameCnIn applies the In predicate on the "name_cn" field. -func NameCnIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldIn(FieldNameCn, vs...)) -} - -// NameCnNotIn applies the NotIn predicate on the "name_cn" field. -func NameCnNotIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldNotIn(FieldNameCn, vs...)) -} - -// NameCnGT applies the GT predicate on the "name_cn" field. -func NameCnGT(v string) predicate.Series { - return predicate.Series(sql.FieldGT(FieldNameCn, v)) -} - -// NameCnGTE applies the GTE predicate on the "name_cn" field. -func NameCnGTE(v string) predicate.Series { - return predicate.Series(sql.FieldGTE(FieldNameCn, v)) -} - -// NameCnLT applies the LT predicate on the "name_cn" field. -func NameCnLT(v string) predicate.Series { - return predicate.Series(sql.FieldLT(FieldNameCn, v)) -} - -// NameCnLTE applies the LTE predicate on the "name_cn" field. -func NameCnLTE(v string) predicate.Series { - return predicate.Series(sql.FieldLTE(FieldNameCn, v)) -} - -// NameCnContains applies the Contains predicate on the "name_cn" field. -func NameCnContains(v string) predicate.Series { - return predicate.Series(sql.FieldContains(FieldNameCn, v)) -} - -// NameCnHasPrefix applies the HasPrefix predicate on the "name_cn" field. -func NameCnHasPrefix(v string) predicate.Series { - return predicate.Series(sql.FieldHasPrefix(FieldNameCn, v)) -} - -// NameCnHasSuffix applies the HasSuffix predicate on the "name_cn" field. -func NameCnHasSuffix(v string) predicate.Series { - return predicate.Series(sql.FieldHasSuffix(FieldNameCn, v)) -} - -// NameCnEqualFold applies the EqualFold predicate on the "name_cn" field. -func NameCnEqualFold(v string) predicate.Series { - return predicate.Series(sql.FieldEqualFold(FieldNameCn, v)) -} - -// NameCnContainsFold applies the ContainsFold predicate on the "name_cn" field. -func NameCnContainsFold(v string) predicate.Series { - return predicate.Series(sql.FieldContainsFold(FieldNameCn, v)) -} - -// NameEnEQ applies the EQ predicate on the "name_en" field. -func NameEnEQ(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldNameEn, v)) -} - -// NameEnNEQ applies the NEQ predicate on the "name_en" field. -func NameEnNEQ(v string) predicate.Series { - return predicate.Series(sql.FieldNEQ(FieldNameEn, v)) -} - -// NameEnIn applies the In predicate on the "name_en" field. -func NameEnIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldIn(FieldNameEn, vs...)) -} - -// NameEnNotIn applies the NotIn predicate on the "name_en" field. -func NameEnNotIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldNotIn(FieldNameEn, vs...)) -} - -// NameEnGT applies the GT predicate on the "name_en" field. -func NameEnGT(v string) predicate.Series { - return predicate.Series(sql.FieldGT(FieldNameEn, v)) -} - -// NameEnGTE applies the GTE predicate on the "name_en" field. -func NameEnGTE(v string) predicate.Series { - return predicate.Series(sql.FieldGTE(FieldNameEn, v)) -} - -// NameEnLT applies the LT predicate on the "name_en" field. -func NameEnLT(v string) predicate.Series { - return predicate.Series(sql.FieldLT(FieldNameEn, v)) -} - -// NameEnLTE applies the LTE predicate on the "name_en" field. -func NameEnLTE(v string) predicate.Series { - return predicate.Series(sql.FieldLTE(FieldNameEn, v)) -} - -// NameEnContains applies the Contains predicate on the "name_en" field. -func NameEnContains(v string) predicate.Series { - return predicate.Series(sql.FieldContains(FieldNameEn, v)) -} - -// NameEnHasPrefix applies the HasPrefix predicate on the "name_en" field. -func NameEnHasPrefix(v string) predicate.Series { - return predicate.Series(sql.FieldHasPrefix(FieldNameEn, v)) -} - -// NameEnHasSuffix applies the HasSuffix predicate on the "name_en" field. -func NameEnHasSuffix(v string) predicate.Series { - return predicate.Series(sql.FieldHasSuffix(FieldNameEn, v)) -} - -// NameEnEqualFold applies the EqualFold predicate on the "name_en" field. -func NameEnEqualFold(v string) predicate.Series { - return predicate.Series(sql.FieldEqualFold(FieldNameEn, v)) -} - -// NameEnContainsFold applies the ContainsFold predicate on the "name_en" field. -func NameEnContainsFold(v string) predicate.Series { - return predicate.Series(sql.FieldContainsFold(FieldNameEn, v)) -} - -// OriginalNameEQ applies the EQ predicate on the "original_name" field. -func OriginalNameEQ(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldOriginalName, v)) -} - -// OriginalNameNEQ applies the NEQ predicate on the "original_name" field. -func OriginalNameNEQ(v string) predicate.Series { - return predicate.Series(sql.FieldNEQ(FieldOriginalName, v)) -} - -// OriginalNameIn applies the In predicate on the "original_name" field. -func OriginalNameIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldIn(FieldOriginalName, vs...)) -} - -// OriginalNameNotIn applies the NotIn predicate on the "original_name" field. -func OriginalNameNotIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldNotIn(FieldOriginalName, vs...)) -} - -// OriginalNameGT applies the GT predicate on the "original_name" field. -func OriginalNameGT(v string) predicate.Series { - return predicate.Series(sql.FieldGT(FieldOriginalName, v)) -} - -// OriginalNameGTE applies the GTE predicate on the "original_name" field. -func OriginalNameGTE(v string) predicate.Series { - return predicate.Series(sql.FieldGTE(FieldOriginalName, v)) -} - -// OriginalNameLT applies the LT predicate on the "original_name" field. -func OriginalNameLT(v string) predicate.Series { - return predicate.Series(sql.FieldLT(FieldOriginalName, v)) -} - -// OriginalNameLTE applies the LTE predicate on the "original_name" field. -func OriginalNameLTE(v string) predicate.Series { - return predicate.Series(sql.FieldLTE(FieldOriginalName, v)) -} - -// OriginalNameContains applies the Contains predicate on the "original_name" field. -func OriginalNameContains(v string) predicate.Series { - return predicate.Series(sql.FieldContains(FieldOriginalName, v)) -} - -// OriginalNameHasPrefix applies the HasPrefix predicate on the "original_name" field. -func OriginalNameHasPrefix(v string) predicate.Series { - return predicate.Series(sql.FieldHasPrefix(FieldOriginalName, v)) -} - -// OriginalNameHasSuffix applies the HasSuffix predicate on the "original_name" field. -func OriginalNameHasSuffix(v string) predicate.Series { - return predicate.Series(sql.FieldHasSuffix(FieldOriginalName, v)) -} - -// OriginalNameEqualFold applies the EqualFold predicate on the "original_name" field. -func OriginalNameEqualFold(v string) predicate.Series { - return predicate.Series(sql.FieldEqualFold(FieldOriginalName, v)) -} - -// OriginalNameContainsFold applies the ContainsFold predicate on the "original_name" field. -func OriginalNameContainsFold(v string) predicate.Series { - return predicate.Series(sql.FieldContainsFold(FieldOriginalName, v)) -} - -// OverviewEQ applies the EQ predicate on the "overview" field. -func OverviewEQ(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldOverview, v)) -} - -// OverviewNEQ applies the NEQ predicate on the "overview" field. -func OverviewNEQ(v string) predicate.Series { - return predicate.Series(sql.FieldNEQ(FieldOverview, v)) -} - -// OverviewIn applies the In predicate on the "overview" field. -func OverviewIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldIn(FieldOverview, vs...)) -} - -// OverviewNotIn applies the NotIn predicate on the "overview" field. -func OverviewNotIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldNotIn(FieldOverview, vs...)) -} - -// OverviewGT applies the GT predicate on the "overview" field. -func OverviewGT(v string) predicate.Series { - return predicate.Series(sql.FieldGT(FieldOverview, v)) -} - -// OverviewGTE applies the GTE predicate on the "overview" field. -func OverviewGTE(v string) predicate.Series { - return predicate.Series(sql.FieldGTE(FieldOverview, v)) -} - -// OverviewLT applies the LT predicate on the "overview" field. -func OverviewLT(v string) predicate.Series { - return predicate.Series(sql.FieldLT(FieldOverview, v)) -} - -// OverviewLTE applies the LTE predicate on the "overview" field. -func OverviewLTE(v string) predicate.Series { - return predicate.Series(sql.FieldLTE(FieldOverview, v)) -} - -// OverviewContains applies the Contains predicate on the "overview" field. -func OverviewContains(v string) predicate.Series { - return predicate.Series(sql.FieldContains(FieldOverview, v)) -} - -// OverviewHasPrefix applies the HasPrefix predicate on the "overview" field. -func OverviewHasPrefix(v string) predicate.Series { - return predicate.Series(sql.FieldHasPrefix(FieldOverview, v)) -} - -// OverviewHasSuffix applies the HasSuffix predicate on the "overview" field. -func OverviewHasSuffix(v string) predicate.Series { - return predicate.Series(sql.FieldHasSuffix(FieldOverview, v)) -} - -// OverviewEqualFold applies the EqualFold predicate on the "overview" field. -func OverviewEqualFold(v string) predicate.Series { - return predicate.Series(sql.FieldEqualFold(FieldOverview, v)) -} - -// OverviewContainsFold applies the ContainsFold predicate on the "overview" field. -func OverviewContainsFold(v string) predicate.Series { - return predicate.Series(sql.FieldContainsFold(FieldOverview, v)) -} - -// PosterPathEQ applies the EQ predicate on the "poster_path" field. -func PosterPathEQ(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldPosterPath, v)) -} - -// PosterPathNEQ applies the NEQ predicate on the "poster_path" field. -func PosterPathNEQ(v string) predicate.Series { - return predicate.Series(sql.FieldNEQ(FieldPosterPath, v)) -} - -// PosterPathIn applies the In predicate on the "poster_path" field. -func PosterPathIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldIn(FieldPosterPath, vs...)) -} - -// PosterPathNotIn applies the NotIn predicate on the "poster_path" field. -func PosterPathNotIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldNotIn(FieldPosterPath, vs...)) -} - -// PosterPathGT applies the GT predicate on the "poster_path" field. -func PosterPathGT(v string) predicate.Series { - return predicate.Series(sql.FieldGT(FieldPosterPath, v)) -} - -// PosterPathGTE applies the GTE predicate on the "poster_path" field. -func PosterPathGTE(v string) predicate.Series { - return predicate.Series(sql.FieldGTE(FieldPosterPath, v)) -} - -// PosterPathLT applies the LT predicate on the "poster_path" field. -func PosterPathLT(v string) predicate.Series { - return predicate.Series(sql.FieldLT(FieldPosterPath, v)) -} - -// PosterPathLTE applies the LTE predicate on the "poster_path" field. -func PosterPathLTE(v string) predicate.Series { - return predicate.Series(sql.FieldLTE(FieldPosterPath, v)) -} - -// PosterPathContains applies the Contains predicate on the "poster_path" field. -func PosterPathContains(v string) predicate.Series { - return predicate.Series(sql.FieldContains(FieldPosterPath, v)) -} - -// PosterPathHasPrefix applies the HasPrefix predicate on the "poster_path" field. -func PosterPathHasPrefix(v string) predicate.Series { - return predicate.Series(sql.FieldHasPrefix(FieldPosterPath, v)) -} - -// PosterPathHasSuffix applies the HasSuffix predicate on the "poster_path" field. -func PosterPathHasSuffix(v string) predicate.Series { - return predicate.Series(sql.FieldHasSuffix(FieldPosterPath, v)) -} - -// PosterPathIsNil applies the IsNil predicate on the "poster_path" field. -func PosterPathIsNil() predicate.Series { - return predicate.Series(sql.FieldIsNull(FieldPosterPath)) -} - -// PosterPathNotNil applies the NotNil predicate on the "poster_path" field. -func PosterPathNotNil() predicate.Series { - return predicate.Series(sql.FieldNotNull(FieldPosterPath)) -} - -// PosterPathEqualFold applies the EqualFold predicate on the "poster_path" field. -func PosterPathEqualFold(v string) predicate.Series { - return predicate.Series(sql.FieldEqualFold(FieldPosterPath, v)) -} - -// PosterPathContainsFold applies the ContainsFold predicate on the "poster_path" field. -func PosterPathContainsFold(v string) predicate.Series { - return predicate.Series(sql.FieldContainsFold(FieldPosterPath, v)) -} - -// CreatedAtEQ applies the EQ predicate on the "created_at" field. -func CreatedAtEQ(v time.Time) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldCreatedAt, v)) -} - -// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. -func CreatedAtNEQ(v time.Time) predicate.Series { - return predicate.Series(sql.FieldNEQ(FieldCreatedAt, v)) -} - -// CreatedAtIn applies the In predicate on the "created_at" field. -func CreatedAtIn(vs ...time.Time) predicate.Series { - return predicate.Series(sql.FieldIn(FieldCreatedAt, vs...)) -} - -// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. -func CreatedAtNotIn(vs ...time.Time) predicate.Series { - return predicate.Series(sql.FieldNotIn(FieldCreatedAt, vs...)) -} - -// CreatedAtGT applies the GT predicate on the "created_at" field. -func CreatedAtGT(v time.Time) predicate.Series { - return predicate.Series(sql.FieldGT(FieldCreatedAt, v)) -} - -// CreatedAtGTE applies the GTE predicate on the "created_at" field. -func CreatedAtGTE(v time.Time) predicate.Series { - return predicate.Series(sql.FieldGTE(FieldCreatedAt, v)) -} - -// CreatedAtLT applies the LT predicate on the "created_at" field. -func CreatedAtLT(v time.Time) predicate.Series { - return predicate.Series(sql.FieldLT(FieldCreatedAt, v)) -} - -// CreatedAtLTE applies the LTE predicate on the "created_at" field. -func CreatedAtLTE(v time.Time) predicate.Series { - return predicate.Series(sql.FieldLTE(FieldCreatedAt, v)) -} - -// AirDateEQ applies the EQ predicate on the "air_date" field. -func AirDateEQ(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldAirDate, v)) -} - -// AirDateNEQ applies the NEQ predicate on the "air_date" field. -func AirDateNEQ(v string) predicate.Series { - return predicate.Series(sql.FieldNEQ(FieldAirDate, v)) -} - -// AirDateIn applies the In predicate on the "air_date" field. -func AirDateIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldIn(FieldAirDate, vs...)) -} - -// AirDateNotIn applies the NotIn predicate on the "air_date" field. -func AirDateNotIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldNotIn(FieldAirDate, vs...)) -} - -// AirDateGT applies the GT predicate on the "air_date" field. -func AirDateGT(v string) predicate.Series { - return predicate.Series(sql.FieldGT(FieldAirDate, v)) -} - -// AirDateGTE applies the GTE predicate on the "air_date" field. -func AirDateGTE(v string) predicate.Series { - return predicate.Series(sql.FieldGTE(FieldAirDate, v)) -} - -// AirDateLT applies the LT predicate on the "air_date" field. -func AirDateLT(v string) predicate.Series { - return predicate.Series(sql.FieldLT(FieldAirDate, v)) -} - -// AirDateLTE applies the LTE predicate on the "air_date" field. -func AirDateLTE(v string) predicate.Series { - return predicate.Series(sql.FieldLTE(FieldAirDate, v)) -} - -// AirDateContains applies the Contains predicate on the "air_date" field. -func AirDateContains(v string) predicate.Series { - return predicate.Series(sql.FieldContains(FieldAirDate, v)) -} - -// AirDateHasPrefix applies the HasPrefix predicate on the "air_date" field. -func AirDateHasPrefix(v string) predicate.Series { - return predicate.Series(sql.FieldHasPrefix(FieldAirDate, v)) -} - -// AirDateHasSuffix applies the HasSuffix predicate on the "air_date" field. -func AirDateHasSuffix(v string) predicate.Series { - return predicate.Series(sql.FieldHasSuffix(FieldAirDate, v)) -} - -// AirDateEqualFold applies the EqualFold predicate on the "air_date" field. -func AirDateEqualFold(v string) predicate.Series { - return predicate.Series(sql.FieldEqualFold(FieldAirDate, v)) -} - -// AirDateContainsFold applies the ContainsFold predicate on the "air_date" field. -func AirDateContainsFold(v string) predicate.Series { - return predicate.Series(sql.FieldContainsFold(FieldAirDate, v)) -} - -// ResolutionEQ applies the EQ predicate on the "resolution" field. -func ResolutionEQ(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldResolution, v)) -} - -// ResolutionNEQ applies the NEQ predicate on the "resolution" field. -func ResolutionNEQ(v string) predicate.Series { - return predicate.Series(sql.FieldNEQ(FieldResolution, v)) -} - -// ResolutionIn applies the In predicate on the "resolution" field. -func ResolutionIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldIn(FieldResolution, vs...)) -} - -// ResolutionNotIn applies the NotIn predicate on the "resolution" field. -func ResolutionNotIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldNotIn(FieldResolution, vs...)) -} - -// ResolutionGT applies the GT predicate on the "resolution" field. -func ResolutionGT(v string) predicate.Series { - return predicate.Series(sql.FieldGT(FieldResolution, v)) -} - -// ResolutionGTE applies the GTE predicate on the "resolution" field. -func ResolutionGTE(v string) predicate.Series { - return predicate.Series(sql.FieldGTE(FieldResolution, v)) -} - -// ResolutionLT applies the LT predicate on the "resolution" field. -func ResolutionLT(v string) predicate.Series { - return predicate.Series(sql.FieldLT(FieldResolution, v)) -} - -// ResolutionLTE applies the LTE predicate on the "resolution" field. -func ResolutionLTE(v string) predicate.Series { - return predicate.Series(sql.FieldLTE(FieldResolution, v)) -} - -// ResolutionContains applies the Contains predicate on the "resolution" field. -func ResolutionContains(v string) predicate.Series { - return predicate.Series(sql.FieldContains(FieldResolution, v)) -} - -// ResolutionHasPrefix applies the HasPrefix predicate on the "resolution" field. -func ResolutionHasPrefix(v string) predicate.Series { - return predicate.Series(sql.FieldHasPrefix(FieldResolution, v)) -} - -// ResolutionHasSuffix applies the HasSuffix predicate on the "resolution" field. -func ResolutionHasSuffix(v string) predicate.Series { - return predicate.Series(sql.FieldHasSuffix(FieldResolution, v)) -} - -// ResolutionEqualFold applies the EqualFold predicate on the "resolution" field. -func ResolutionEqualFold(v string) predicate.Series { - return predicate.Series(sql.FieldEqualFold(FieldResolution, v)) -} - -// ResolutionContainsFold applies the ContainsFold predicate on the "resolution" field. -func ResolutionContainsFold(v string) predicate.Series { - return predicate.Series(sql.FieldContainsFold(FieldResolution, v)) -} - -// StorageIDEQ applies the EQ predicate on the "storage_id" field. -func StorageIDEQ(v int) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldStorageID, v)) -} - -// StorageIDNEQ applies the NEQ predicate on the "storage_id" field. -func StorageIDNEQ(v int) predicate.Series { - return predicate.Series(sql.FieldNEQ(FieldStorageID, v)) -} - -// StorageIDIn applies the In predicate on the "storage_id" field. -func StorageIDIn(vs ...int) predicate.Series { - return predicate.Series(sql.FieldIn(FieldStorageID, vs...)) -} - -// StorageIDNotIn applies the NotIn predicate on the "storage_id" field. -func StorageIDNotIn(vs ...int) predicate.Series { - return predicate.Series(sql.FieldNotIn(FieldStorageID, vs...)) -} - -// StorageIDGT applies the GT predicate on the "storage_id" field. -func StorageIDGT(v int) predicate.Series { - return predicate.Series(sql.FieldGT(FieldStorageID, v)) -} - -// StorageIDGTE applies the GTE predicate on the "storage_id" field. -func StorageIDGTE(v int) predicate.Series { - return predicate.Series(sql.FieldGTE(FieldStorageID, v)) -} - -// StorageIDLT applies the LT predicate on the "storage_id" field. -func StorageIDLT(v int) predicate.Series { - return predicate.Series(sql.FieldLT(FieldStorageID, v)) -} - -// StorageIDLTE applies the LTE predicate on the "storage_id" field. -func StorageIDLTE(v int) predicate.Series { - return predicate.Series(sql.FieldLTE(FieldStorageID, v)) -} - -// StorageIDIsNil applies the IsNil predicate on the "storage_id" field. -func StorageIDIsNil() predicate.Series { - return predicate.Series(sql.FieldIsNull(FieldStorageID)) -} - -// StorageIDNotNil applies the NotNil predicate on the "storage_id" field. -func StorageIDNotNil() predicate.Series { - return predicate.Series(sql.FieldNotNull(FieldStorageID)) -} - -// TargetDirEQ applies the EQ predicate on the "target_dir" field. -func TargetDirEQ(v string) predicate.Series { - return predicate.Series(sql.FieldEQ(FieldTargetDir, v)) -} - -// TargetDirNEQ applies the NEQ predicate on the "target_dir" field. -func TargetDirNEQ(v string) predicate.Series { - return predicate.Series(sql.FieldNEQ(FieldTargetDir, v)) -} - -// TargetDirIn applies the In predicate on the "target_dir" field. -func TargetDirIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldIn(FieldTargetDir, vs...)) -} - -// TargetDirNotIn applies the NotIn predicate on the "target_dir" field. -func TargetDirNotIn(vs ...string) predicate.Series { - return predicate.Series(sql.FieldNotIn(FieldTargetDir, vs...)) -} - -// TargetDirGT applies the GT predicate on the "target_dir" field. -func TargetDirGT(v string) predicate.Series { - return predicate.Series(sql.FieldGT(FieldTargetDir, v)) -} - -// TargetDirGTE applies the GTE predicate on the "target_dir" field. -func TargetDirGTE(v string) predicate.Series { - return predicate.Series(sql.FieldGTE(FieldTargetDir, v)) -} - -// TargetDirLT applies the LT predicate on the "target_dir" field. -func TargetDirLT(v string) predicate.Series { - return predicate.Series(sql.FieldLT(FieldTargetDir, v)) -} - -// TargetDirLTE applies the LTE predicate on the "target_dir" field. -func TargetDirLTE(v string) predicate.Series { - return predicate.Series(sql.FieldLTE(FieldTargetDir, v)) -} - -// TargetDirContains applies the Contains predicate on the "target_dir" field. -func TargetDirContains(v string) predicate.Series { - return predicate.Series(sql.FieldContains(FieldTargetDir, v)) -} - -// TargetDirHasPrefix applies the HasPrefix predicate on the "target_dir" field. -func TargetDirHasPrefix(v string) predicate.Series { - return predicate.Series(sql.FieldHasPrefix(FieldTargetDir, v)) -} - -// TargetDirHasSuffix applies the HasSuffix predicate on the "target_dir" field. -func TargetDirHasSuffix(v string) predicate.Series { - return predicate.Series(sql.FieldHasSuffix(FieldTargetDir, v)) -} - -// TargetDirIsNil applies the IsNil predicate on the "target_dir" field. -func TargetDirIsNil() predicate.Series { - return predicate.Series(sql.FieldIsNull(FieldTargetDir)) -} - -// TargetDirNotNil applies the NotNil predicate on the "target_dir" field. -func TargetDirNotNil() predicate.Series { - return predicate.Series(sql.FieldNotNull(FieldTargetDir)) -} - -// TargetDirEqualFold applies the EqualFold predicate on the "target_dir" field. -func TargetDirEqualFold(v string) predicate.Series { - return predicate.Series(sql.FieldEqualFold(FieldTargetDir, v)) -} - -// TargetDirContainsFold applies the ContainsFold predicate on the "target_dir" field. -func TargetDirContainsFold(v string) predicate.Series { - return predicate.Series(sql.FieldContainsFold(FieldTargetDir, v)) -} - -// HasEpisodes applies the HasEdge predicate on the "episodes" edge. -func HasEpisodes() predicate.Series { - return predicate.Series(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, EpisodesTable, EpisodesColumn), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasEpisodesWith applies the HasEdge predicate on the "episodes" edge with a given conditions (other predicates). -func HasEpisodesWith(preds ...predicate.Episode) predicate.Series { - return predicate.Series(func(s *sql.Selector) { - step := newEpisodesStep() - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.Series) predicate.Series { - return predicate.Series(sql.AndPredicates(predicates...)) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.Series) predicate.Series { - return predicate.Series(sql.OrPredicates(predicates...)) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.Series) predicate.Series { - return predicate.Series(sql.NotPredicates(p)) -} diff --git a/ent/series_create.go b/ent/series_create.go deleted file mode 100644 index 70caad1..0000000 --- a/ent/series_create.go +++ /dev/null @@ -1,421 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - "polaris/ent/episode" - "polaris/ent/series" - "time" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// SeriesCreate is the builder for creating a Series entity. -type SeriesCreate struct { - config - mutation *SeriesMutation - hooks []Hook -} - -// SetTmdbID sets the "tmdb_id" field. -func (sc *SeriesCreate) SetTmdbID(i int) *SeriesCreate { - sc.mutation.SetTmdbID(i) - return sc -} - -// SetImdbID sets the "imdb_id" field. -func (sc *SeriesCreate) SetImdbID(s string) *SeriesCreate { - sc.mutation.SetImdbID(s) - return sc -} - -// SetNillableImdbID sets the "imdb_id" field if the given value is not nil. -func (sc *SeriesCreate) SetNillableImdbID(s *string) *SeriesCreate { - if s != nil { - sc.SetImdbID(*s) - } - return sc -} - -// SetNameCn sets the "name_cn" field. -func (sc *SeriesCreate) SetNameCn(s string) *SeriesCreate { - sc.mutation.SetNameCn(s) - return sc -} - -// SetNameEn sets the "name_en" field. -func (sc *SeriesCreate) SetNameEn(s string) *SeriesCreate { - sc.mutation.SetNameEn(s) - return sc -} - -// SetOriginalName sets the "original_name" field. -func (sc *SeriesCreate) SetOriginalName(s string) *SeriesCreate { - sc.mutation.SetOriginalName(s) - return sc -} - -// SetOverview sets the "overview" field. -func (sc *SeriesCreate) SetOverview(s string) *SeriesCreate { - sc.mutation.SetOverview(s) - return sc -} - -// SetPosterPath sets the "poster_path" field. -func (sc *SeriesCreate) SetPosterPath(s string) *SeriesCreate { - sc.mutation.SetPosterPath(s) - return sc -} - -// SetNillablePosterPath sets the "poster_path" field if the given value is not nil. -func (sc *SeriesCreate) SetNillablePosterPath(s *string) *SeriesCreate { - if s != nil { - sc.SetPosterPath(*s) - } - return sc -} - -// SetCreatedAt sets the "created_at" field. -func (sc *SeriesCreate) SetCreatedAt(t time.Time) *SeriesCreate { - sc.mutation.SetCreatedAt(t) - return sc -} - -// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. -func (sc *SeriesCreate) SetNillableCreatedAt(t *time.Time) *SeriesCreate { - if t != nil { - sc.SetCreatedAt(*t) - } - return sc -} - -// SetAirDate sets the "air_date" field. -func (sc *SeriesCreate) SetAirDate(s string) *SeriesCreate { - sc.mutation.SetAirDate(s) - return sc -} - -// SetNillableAirDate sets the "air_date" field if the given value is not nil. -func (sc *SeriesCreate) SetNillableAirDate(s *string) *SeriesCreate { - if s != nil { - sc.SetAirDate(*s) - } - return sc -} - -// SetResolution sets the "resolution" field. -func (sc *SeriesCreate) SetResolution(s string) *SeriesCreate { - sc.mutation.SetResolution(s) - return sc -} - -// SetNillableResolution sets the "resolution" field if the given value is not nil. -func (sc *SeriesCreate) SetNillableResolution(s *string) *SeriesCreate { - if s != nil { - sc.SetResolution(*s) - } - return sc -} - -// SetStorageID sets the "storage_id" field. -func (sc *SeriesCreate) SetStorageID(i int) *SeriesCreate { - sc.mutation.SetStorageID(i) - return sc -} - -// SetNillableStorageID sets the "storage_id" field if the given value is not nil. -func (sc *SeriesCreate) SetNillableStorageID(i *int) *SeriesCreate { - if i != nil { - sc.SetStorageID(*i) - } - return sc -} - -// SetTargetDir sets the "target_dir" field. -func (sc *SeriesCreate) SetTargetDir(s string) *SeriesCreate { - sc.mutation.SetTargetDir(s) - return sc -} - -// SetNillableTargetDir sets the "target_dir" field if the given value is not nil. -func (sc *SeriesCreate) SetNillableTargetDir(s *string) *SeriesCreate { - if s != nil { - sc.SetTargetDir(*s) - } - return sc -} - -// AddEpisodeIDs adds the "episodes" edge to the Episode entity by IDs. -func (sc *SeriesCreate) AddEpisodeIDs(ids ...int) *SeriesCreate { - sc.mutation.AddEpisodeIDs(ids...) - return sc -} - -// AddEpisodes adds the "episodes" edges to the Episode entity. -func (sc *SeriesCreate) AddEpisodes(e ...*Episode) *SeriesCreate { - ids := make([]int, len(e)) - for i := range e { - ids[i] = e[i].ID - } - return sc.AddEpisodeIDs(ids...) -} - -// Mutation returns the SeriesMutation object of the builder. -func (sc *SeriesCreate) Mutation() *SeriesMutation { - return sc.mutation -} - -// Save creates the Series in the database. -func (sc *SeriesCreate) Save(ctx context.Context) (*Series, error) { - sc.defaults() - return withHooks(ctx, sc.sqlSave, sc.mutation, sc.hooks) -} - -// SaveX calls Save and panics if Save returns an error. -func (sc *SeriesCreate) SaveX(ctx context.Context) *Series { - v, err := sc.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (sc *SeriesCreate) Exec(ctx context.Context) error { - _, err := sc.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (sc *SeriesCreate) ExecX(ctx context.Context) { - if err := sc.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (sc *SeriesCreate) defaults() { - if _, ok := sc.mutation.CreatedAt(); !ok { - v := series.DefaultCreatedAt - sc.mutation.SetCreatedAt(v) - } - if _, ok := sc.mutation.AirDate(); !ok { - v := series.DefaultAirDate - sc.mutation.SetAirDate(v) - } - if _, ok := sc.mutation.Resolution(); !ok { - v := series.DefaultResolution - sc.mutation.SetResolution(v) - } -} - -// check runs all checks and user-defined validators on the builder. -func (sc *SeriesCreate) check() error { - if _, ok := sc.mutation.TmdbID(); !ok { - return &ValidationError{Name: "tmdb_id", err: errors.New(`ent: missing required field "Series.tmdb_id"`)} - } - if _, ok := sc.mutation.NameCn(); !ok { - return &ValidationError{Name: "name_cn", err: errors.New(`ent: missing required field "Series.name_cn"`)} - } - if _, ok := sc.mutation.NameEn(); !ok { - return &ValidationError{Name: "name_en", err: errors.New(`ent: missing required field "Series.name_en"`)} - } - if _, ok := sc.mutation.OriginalName(); !ok { - return &ValidationError{Name: "original_name", err: errors.New(`ent: missing required field "Series.original_name"`)} - } - if _, ok := sc.mutation.Overview(); !ok { - return &ValidationError{Name: "overview", err: errors.New(`ent: missing required field "Series.overview"`)} - } - if _, ok := sc.mutation.CreatedAt(); !ok { - return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Series.created_at"`)} - } - if _, ok := sc.mutation.AirDate(); !ok { - return &ValidationError{Name: "air_date", err: errors.New(`ent: missing required field "Series.air_date"`)} - } - if _, ok := sc.mutation.Resolution(); !ok { - return &ValidationError{Name: "resolution", err: errors.New(`ent: missing required field "Series.resolution"`)} - } - return nil -} - -func (sc *SeriesCreate) sqlSave(ctx context.Context) (*Series, error) { - if err := sc.check(); err != nil { - return nil, err - } - _node, _spec := sc.createSpec() - if err := sqlgraph.CreateNode(ctx, sc.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - id := _spec.ID.Value.(int64) - _node.ID = int(id) - sc.mutation.id = &_node.ID - sc.mutation.done = true - return _node, nil -} - -func (sc *SeriesCreate) createSpec() (*Series, *sqlgraph.CreateSpec) { - var ( - _node = &Series{config: sc.config} - _spec = sqlgraph.NewCreateSpec(series.Table, sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt)) - ) - if value, ok := sc.mutation.TmdbID(); ok { - _spec.SetField(series.FieldTmdbID, field.TypeInt, value) - _node.TmdbID = value - } - if value, ok := sc.mutation.ImdbID(); ok { - _spec.SetField(series.FieldImdbID, field.TypeString, value) - _node.ImdbID = value - } - if value, ok := sc.mutation.NameCn(); ok { - _spec.SetField(series.FieldNameCn, field.TypeString, value) - _node.NameCn = value - } - if value, ok := sc.mutation.NameEn(); ok { - _spec.SetField(series.FieldNameEn, field.TypeString, value) - _node.NameEn = value - } - if value, ok := sc.mutation.OriginalName(); ok { - _spec.SetField(series.FieldOriginalName, field.TypeString, value) - _node.OriginalName = value - } - if value, ok := sc.mutation.Overview(); ok { - _spec.SetField(series.FieldOverview, field.TypeString, value) - _node.Overview = value - } - if value, ok := sc.mutation.PosterPath(); ok { - _spec.SetField(series.FieldPosterPath, field.TypeString, value) - _node.PosterPath = value - } - if value, ok := sc.mutation.CreatedAt(); ok { - _spec.SetField(series.FieldCreatedAt, field.TypeTime, value) - _node.CreatedAt = value - } - if value, ok := sc.mutation.AirDate(); ok { - _spec.SetField(series.FieldAirDate, field.TypeString, value) - _node.AirDate = value - } - if value, ok := sc.mutation.Resolution(); ok { - _spec.SetField(series.FieldResolution, field.TypeString, value) - _node.Resolution = value - } - if value, ok := sc.mutation.StorageID(); ok { - _spec.SetField(series.FieldStorageID, field.TypeInt, value) - _node.StorageID = value - } - if value, ok := sc.mutation.TargetDir(); ok { - _spec.SetField(series.FieldTargetDir, field.TypeString, value) - _node.TargetDir = value - } - if nodes := sc.mutation.EpisodesIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: series.EpisodesTable, - Columns: []string{series.EpisodesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges = append(_spec.Edges, edge) - } - return _node, _spec -} - -// SeriesCreateBulk is the builder for creating many Series entities in bulk. -type SeriesCreateBulk struct { - config - err error - builders []*SeriesCreate -} - -// Save creates the Series entities in the database. -func (scb *SeriesCreateBulk) Save(ctx context.Context) ([]*Series, error) { - if scb.err != nil { - return nil, scb.err - } - specs := make([]*sqlgraph.CreateSpec, len(scb.builders)) - nodes := make([]*Series, len(scb.builders)) - mutators := make([]Mutator, len(scb.builders)) - for i := range scb.builders { - func(i int, root context.Context) { - builder := scb.builders[i] - builder.defaults() - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*SeriesMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - var err error - nodes[i], specs[i] = builder.createSpec() - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, scb.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, scb.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - if specs[i].ID.Value != nil { - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) - } - mutation.done = true - return nodes[i], nil - }) - for i := len(builder.hooks) - 1; i >= 0; i-- { - mut = builder.hooks[i](mut) - } - mutators[i] = mut - }(i, ctx) - } - if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, scb.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (scb *SeriesCreateBulk) SaveX(ctx context.Context) []*Series { - v, err := scb.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (scb *SeriesCreateBulk) Exec(ctx context.Context) error { - _, err := scb.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (scb *SeriesCreateBulk) ExecX(ctx context.Context) { - if err := scb.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/ent/series_delete.go b/ent/series_delete.go deleted file mode 100644 index 676cd28..0000000 --- a/ent/series_delete.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "polaris/ent/predicate" - "polaris/ent/series" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// SeriesDelete is the builder for deleting a Series entity. -type SeriesDelete struct { - config - hooks []Hook - mutation *SeriesMutation -} - -// Where appends a list predicates to the SeriesDelete builder. -func (sd *SeriesDelete) Where(ps ...predicate.Series) *SeriesDelete { - sd.mutation.Where(ps...) - return sd -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (sd *SeriesDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, sd.sqlExec, sd.mutation, sd.hooks) -} - -// ExecX is like Exec, but panics if an error occurs. -func (sd *SeriesDelete) ExecX(ctx context.Context) int { - n, err := sd.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (sd *SeriesDelete) sqlExec(ctx context.Context) (int, error) { - _spec := sqlgraph.NewDeleteSpec(series.Table, sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt)) - if ps := sd.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - affected, err := sqlgraph.DeleteNodes(ctx, sd.driver, _spec) - if err != nil && sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - sd.mutation.done = true - return affected, err -} - -// SeriesDeleteOne is the builder for deleting a single Series entity. -type SeriesDeleteOne struct { - sd *SeriesDelete -} - -// Where appends a list predicates to the SeriesDelete builder. -func (sdo *SeriesDeleteOne) Where(ps ...predicate.Series) *SeriesDeleteOne { - sdo.sd.mutation.Where(ps...) - return sdo -} - -// Exec executes the deletion query. -func (sdo *SeriesDeleteOne) Exec(ctx context.Context) error { - n, err := sdo.sd.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{series.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (sdo *SeriesDeleteOne) ExecX(ctx context.Context) { - if err := sdo.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/ent/series_query.go b/ent/series_query.go deleted file mode 100644 index 09a7045..0000000 --- a/ent/series_query.go +++ /dev/null @@ -1,605 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "database/sql/driver" - "fmt" - "math" - "polaris/ent/episode" - "polaris/ent/predicate" - "polaris/ent/series" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// SeriesQuery is the builder for querying Series entities. -type SeriesQuery struct { - config - ctx *QueryContext - order []series.OrderOption - inters []Interceptor - predicates []predicate.Series - withEpisodes *EpisodeQuery - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the SeriesQuery builder. -func (sq *SeriesQuery) Where(ps ...predicate.Series) *SeriesQuery { - sq.predicates = append(sq.predicates, ps...) - return sq -} - -// Limit the number of records to be returned by this query. -func (sq *SeriesQuery) Limit(limit int) *SeriesQuery { - sq.ctx.Limit = &limit - return sq -} - -// Offset to start from. -func (sq *SeriesQuery) Offset(offset int) *SeriesQuery { - sq.ctx.Offset = &offset - return sq -} - -// Unique configures the query builder to filter duplicate records on query. -// By default, unique is set to true, and can be disabled using this method. -func (sq *SeriesQuery) Unique(unique bool) *SeriesQuery { - sq.ctx.Unique = &unique - return sq -} - -// Order specifies how the records should be ordered. -func (sq *SeriesQuery) Order(o ...series.OrderOption) *SeriesQuery { - sq.order = append(sq.order, o...) - return sq -} - -// QueryEpisodes chains the current query on the "episodes" edge. -func (sq *SeriesQuery) QueryEpisodes() *EpisodeQuery { - query := (&EpisodeClient{config: sq.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := sq.prepareQuery(ctx); err != nil { - return nil, err - } - selector := sq.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(series.Table, series.FieldID, selector), - sqlgraph.To(episode.Table, episode.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, series.EpisodesTable, series.EpisodesColumn), - ) - fromU = sqlgraph.SetNeighbors(sq.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// First returns the first Series entity from the query. -// Returns a *NotFoundError when no Series was found. -func (sq *SeriesQuery) First(ctx context.Context) (*Series, error) { - nodes, err := sq.Limit(1).All(setContextOp(ctx, sq.ctx, "First")) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{series.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (sq *SeriesQuery) FirstX(ctx context.Context) *Series { - node, err := sq.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first Series ID from the query. -// Returns a *NotFoundError when no Series ID was found. -func (sq *SeriesQuery) FirstID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = sq.Limit(1).IDs(setContextOp(ctx, sq.ctx, "FirstID")); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{series.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (sq *SeriesQuery) FirstIDX(ctx context.Context) int { - id, err := sq.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single Series entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when more than one Series entity is found. -// Returns a *NotFoundError when no Series entities are found. -func (sq *SeriesQuery) Only(ctx context.Context) (*Series, error) { - nodes, err := sq.Limit(2).All(setContextOp(ctx, sq.ctx, "Only")) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{series.Label} - default: - return nil, &NotSingularError{series.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (sq *SeriesQuery) OnlyX(ctx context.Context) *Series { - node, err := sq.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only Series ID in the query. -// Returns a *NotSingularError when more than one Series ID is found. -// Returns a *NotFoundError when no entities are found. -func (sq *SeriesQuery) OnlyID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = sq.Limit(2).IDs(setContextOp(ctx, sq.ctx, "OnlyID")); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{series.Label} - default: - err = &NotSingularError{series.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (sq *SeriesQuery) OnlyIDX(ctx context.Context) int { - id, err := sq.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of SeriesSlice. -func (sq *SeriesQuery) All(ctx context.Context) ([]*Series, error) { - ctx = setContextOp(ctx, sq.ctx, "All") - if err := sq.prepareQuery(ctx); err != nil { - return nil, err - } - qr := querierAll[[]*Series, *SeriesQuery]() - return withInterceptors[[]*Series](ctx, sq, qr, sq.inters) -} - -// AllX is like All, but panics if an error occurs. -func (sq *SeriesQuery) AllX(ctx context.Context) []*Series { - nodes, err := sq.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of Series IDs. -func (sq *SeriesQuery) IDs(ctx context.Context) (ids []int, err error) { - if sq.ctx.Unique == nil && sq.path != nil { - sq.Unique(true) - } - ctx = setContextOp(ctx, sq.ctx, "IDs") - if err = sq.Select(series.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (sq *SeriesQuery) IDsX(ctx context.Context) []int { - ids, err := sq.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (sq *SeriesQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, sq.ctx, "Count") - if err := sq.prepareQuery(ctx); err != nil { - return 0, err - } - return withInterceptors[int](ctx, sq, querierCount[*SeriesQuery](), sq.inters) -} - -// CountX is like Count, but panics if an error occurs. -func (sq *SeriesQuery) CountX(ctx context.Context) int { - count, err := sq.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (sq *SeriesQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, sq.ctx, "Exist") - switch _, err := sq.FirstID(ctx); { - case IsNotFound(err): - return false, nil - case err != nil: - return false, fmt.Errorf("ent: check existence: %w", err) - default: - return true, nil - } -} - -// ExistX is like Exist, but panics if an error occurs. -func (sq *SeriesQuery) ExistX(ctx context.Context) bool { - exist, err := sq.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the SeriesQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (sq *SeriesQuery) Clone() *SeriesQuery { - if sq == nil { - return nil - } - return &SeriesQuery{ - config: sq.config, - ctx: sq.ctx.Clone(), - order: append([]series.OrderOption{}, sq.order...), - inters: append([]Interceptor{}, sq.inters...), - predicates: append([]predicate.Series{}, sq.predicates...), - withEpisodes: sq.withEpisodes.Clone(), - // clone intermediate query. - sql: sq.sql.Clone(), - path: sq.path, - } -} - -// WithEpisodes tells the query-builder to eager-load the nodes that are connected to -// the "episodes" edge. The optional arguments are used to configure the query builder of the edge. -func (sq *SeriesQuery) WithEpisodes(opts ...func(*EpisodeQuery)) *SeriesQuery { - query := (&EpisodeClient{config: sq.config}).Query() - for _, opt := range opts { - opt(query) - } - sq.withEpisodes = query - return sq -} - -// GroupBy is used to group vertices by one or more fields/columns. -// It is often used with aggregate functions, like: count, max, mean, min, sum. -// -// Example: -// -// var v []struct { -// TmdbID int `json:"tmdb_id,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.Series.Query(). -// GroupBy(series.FieldTmdbID). -// Aggregate(ent.Count()). -// Scan(ctx, &v) -func (sq *SeriesQuery) GroupBy(field string, fields ...string) *SeriesGroupBy { - sq.ctx.Fields = append([]string{field}, fields...) - grbuild := &SeriesGroupBy{build: sq} - grbuild.flds = &sq.ctx.Fields - grbuild.label = series.Label - grbuild.scan = grbuild.Scan - return grbuild -} - -// Select allows the selection one or more fields/columns for the given query, -// instead of selecting all fields in the entity. -// -// Example: -// -// var v []struct { -// TmdbID int `json:"tmdb_id,omitempty"` -// } -// -// client.Series.Query(). -// Select(series.FieldTmdbID). -// Scan(ctx, &v) -func (sq *SeriesQuery) Select(fields ...string) *SeriesSelect { - sq.ctx.Fields = append(sq.ctx.Fields, fields...) - sbuild := &SeriesSelect{SeriesQuery: sq} - sbuild.label = series.Label - sbuild.flds, sbuild.scan = &sq.ctx.Fields, sbuild.Scan - return sbuild -} - -// Aggregate returns a SeriesSelect configured with the given aggregations. -func (sq *SeriesQuery) Aggregate(fns ...AggregateFunc) *SeriesSelect { - return sq.Select().Aggregate(fns...) -} - -func (sq *SeriesQuery) prepareQuery(ctx context.Context) error { - for _, inter := range sq.inters { - if inter == nil { - return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") - } - if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, sq); err != nil { - return err - } - } - } - for _, f := range sq.ctx.Fields { - if !series.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - } - if sq.path != nil { - prev, err := sq.path(ctx) - if err != nil { - return err - } - sq.sql = prev - } - return nil -} - -func (sq *SeriesQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Series, error) { - var ( - nodes = []*Series{} - _spec = sq.querySpec() - loadedTypes = [1]bool{ - sq.withEpisodes != nil, - } - ) - _spec.ScanValues = func(columns []string) ([]any, error) { - return (*Series).scanValues(nil, columns) - } - _spec.Assign = func(columns []string, values []any) error { - node := &Series{config: sq.config} - nodes = append(nodes, node) - node.Edges.loadedTypes = loadedTypes - return node.assignValues(columns, values) - } - for i := range hooks { - hooks[i](ctx, _spec) - } - if err := sqlgraph.QueryNodes(ctx, sq.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - if query := sq.withEpisodes; query != nil { - if err := sq.loadEpisodes(ctx, query, nodes, - func(n *Series) { n.Edges.Episodes = []*Episode{} }, - func(n *Series, e *Episode) { n.Edges.Episodes = append(n.Edges.Episodes, e) }); err != nil { - return nil, err - } - } - return nodes, nil -} - -func (sq *SeriesQuery) loadEpisodes(ctx context.Context, query *EpisodeQuery, nodes []*Series, init func(*Series), assign func(*Series, *Episode)) error { - fks := make([]driver.Value, 0, len(nodes)) - nodeids := make(map[int]*Series) - for i := range nodes { - fks = append(fks, nodes[i].ID) - nodeids[nodes[i].ID] = nodes[i] - if init != nil { - init(nodes[i]) - } - } - if len(query.ctx.Fields) > 0 { - query.ctx.AppendFieldOnce(episode.FieldSeriesID) - } - query.Where(predicate.Episode(func(s *sql.Selector) { - s.Where(sql.InValues(s.C(series.EpisodesColumn), fks...)) - })) - neighbors, err := query.All(ctx) - if err != nil { - return err - } - for _, n := range neighbors { - fk := n.SeriesID - node, ok := nodeids[fk] - if !ok { - return fmt.Errorf(`unexpected referenced foreign-key "series_id" returned %v for node %v`, fk, n.ID) - } - assign(node, n) - } - return nil -} - -func (sq *SeriesQuery) sqlCount(ctx context.Context) (int, error) { - _spec := sq.querySpec() - _spec.Node.Columns = sq.ctx.Fields - if len(sq.ctx.Fields) > 0 { - _spec.Unique = sq.ctx.Unique != nil && *sq.ctx.Unique - } - return sqlgraph.CountNodes(ctx, sq.driver, _spec) -} - -func (sq *SeriesQuery) querySpec() *sqlgraph.QuerySpec { - _spec := sqlgraph.NewQuerySpec(series.Table, series.Columns, sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt)) - _spec.From = sq.sql - if unique := sq.ctx.Unique; unique != nil { - _spec.Unique = *unique - } else if sq.path != nil { - _spec.Unique = true - } - if fields := sq.ctx.Fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, series.FieldID) - for i := range fields { - if fields[i] != series.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := sq.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := sq.ctx.Limit; limit != nil { - _spec.Limit = *limit - } - if offset := sq.ctx.Offset; offset != nil { - _spec.Offset = *offset - } - if ps := sq.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (sq *SeriesQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(sq.driver.Dialect()) - t1 := builder.Table(series.Table) - columns := sq.ctx.Fields - if len(columns) == 0 { - columns = series.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if sq.sql != nil { - selector = sq.sql - selector.Select(selector.Columns(columns...)...) - } - if sq.ctx.Unique != nil && *sq.ctx.Unique { - selector.Distinct() - } - for _, p := range sq.predicates { - p(selector) - } - for _, p := range sq.order { - p(selector) - } - if offset := sq.ctx.Offset; offset != nil { - // limit is mandatory for offset clause. We start - // with default value, and override it below if needed. - selector.Offset(*offset).Limit(math.MaxInt32) - } - if limit := sq.ctx.Limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// SeriesGroupBy is the group-by builder for Series entities. -type SeriesGroupBy struct { - selector - build *SeriesQuery -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (sgb *SeriesGroupBy) Aggregate(fns ...AggregateFunc) *SeriesGroupBy { - sgb.fns = append(sgb.fns, fns...) - return sgb -} - -// Scan applies the selector query and scans the result into the given value. -func (sgb *SeriesGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, sgb.build.ctx, "GroupBy") - if err := sgb.build.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*SeriesQuery, *SeriesGroupBy](ctx, sgb.build, sgb, sgb.build.inters, v) -} - -func (sgb *SeriesGroupBy) sqlScan(ctx context.Context, root *SeriesQuery, v any) error { - selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(sgb.fns)) - for _, fn := range sgb.fns { - aggregation = append(aggregation, fn(selector)) - } - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*sgb.flds)+len(sgb.fns)) - for _, f := range *sgb.flds { - columns = append(columns, selector.C(f)) - } - columns = append(columns, aggregation...) - selector.Select(columns...) - } - selector.GroupBy(selector.Columns(*sgb.flds...)...) - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := sgb.build.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// SeriesSelect is the builder for selecting fields of Series entities. -type SeriesSelect struct { - *SeriesQuery - selector -} - -// Aggregate adds the given aggregation functions to the selector query. -func (ss *SeriesSelect) Aggregate(fns ...AggregateFunc) *SeriesSelect { - ss.fns = append(ss.fns, fns...) - return ss -} - -// Scan applies the selector query and scans the result into the given value. -func (ss *SeriesSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, ss.ctx, "Select") - if err := ss.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*SeriesQuery, *SeriesSelect](ctx, ss.SeriesQuery, ss, ss.inters, v) -} - -func (ss *SeriesSelect) sqlScan(ctx context.Context, root *SeriesQuery, v any) error { - selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(ss.fns)) - for _, fn := range ss.fns { - aggregation = append(aggregation, fn(selector)) - } - switch n := len(*ss.selector.flds); { - case n == 0 && len(aggregation) > 0: - selector.Select(aggregation...) - case n != 0 && len(aggregation) > 0: - selector.AppendSelect(aggregation...) - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := ss.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/ent/series_update.go b/ent/series_update.go deleted file mode 100644 index 1fd8de3..0000000 --- a/ent/series_update.go +++ /dev/null @@ -1,859 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - "polaris/ent/episode" - "polaris/ent/predicate" - "polaris/ent/series" - "time" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// SeriesUpdate is the builder for updating Series entities. -type SeriesUpdate struct { - config - hooks []Hook - mutation *SeriesMutation -} - -// Where appends a list predicates to the SeriesUpdate builder. -func (su *SeriesUpdate) Where(ps ...predicate.Series) *SeriesUpdate { - su.mutation.Where(ps...) - return su -} - -// SetTmdbID sets the "tmdb_id" field. -func (su *SeriesUpdate) SetTmdbID(i int) *SeriesUpdate { - su.mutation.ResetTmdbID() - su.mutation.SetTmdbID(i) - return su -} - -// SetNillableTmdbID sets the "tmdb_id" field if the given value is not nil. -func (su *SeriesUpdate) SetNillableTmdbID(i *int) *SeriesUpdate { - if i != nil { - su.SetTmdbID(*i) - } - return su -} - -// AddTmdbID adds i to the "tmdb_id" field. -func (su *SeriesUpdate) AddTmdbID(i int) *SeriesUpdate { - su.mutation.AddTmdbID(i) - return su -} - -// SetImdbID sets the "imdb_id" field. -func (su *SeriesUpdate) SetImdbID(s string) *SeriesUpdate { - su.mutation.SetImdbID(s) - return su -} - -// SetNillableImdbID sets the "imdb_id" field if the given value is not nil. -func (su *SeriesUpdate) SetNillableImdbID(s *string) *SeriesUpdate { - if s != nil { - su.SetImdbID(*s) - } - return su -} - -// ClearImdbID clears the value of the "imdb_id" field. -func (su *SeriesUpdate) ClearImdbID() *SeriesUpdate { - su.mutation.ClearImdbID() - return su -} - -// SetNameCn sets the "name_cn" field. -func (su *SeriesUpdate) SetNameCn(s string) *SeriesUpdate { - su.mutation.SetNameCn(s) - return su -} - -// SetNillableNameCn sets the "name_cn" field if the given value is not nil. -func (su *SeriesUpdate) SetNillableNameCn(s *string) *SeriesUpdate { - if s != nil { - su.SetNameCn(*s) - } - return su -} - -// SetNameEn sets the "name_en" field. -func (su *SeriesUpdate) SetNameEn(s string) *SeriesUpdate { - su.mutation.SetNameEn(s) - return su -} - -// SetNillableNameEn sets the "name_en" field if the given value is not nil. -func (su *SeriesUpdate) SetNillableNameEn(s *string) *SeriesUpdate { - if s != nil { - su.SetNameEn(*s) - } - return su -} - -// SetOriginalName sets the "original_name" field. -func (su *SeriesUpdate) SetOriginalName(s string) *SeriesUpdate { - su.mutation.SetOriginalName(s) - return su -} - -// SetNillableOriginalName sets the "original_name" field if the given value is not nil. -func (su *SeriesUpdate) SetNillableOriginalName(s *string) *SeriesUpdate { - if s != nil { - su.SetOriginalName(*s) - } - return su -} - -// SetOverview sets the "overview" field. -func (su *SeriesUpdate) SetOverview(s string) *SeriesUpdate { - su.mutation.SetOverview(s) - return su -} - -// SetNillableOverview sets the "overview" field if the given value is not nil. -func (su *SeriesUpdate) SetNillableOverview(s *string) *SeriesUpdate { - if s != nil { - su.SetOverview(*s) - } - return su -} - -// SetPosterPath sets the "poster_path" field. -func (su *SeriesUpdate) SetPosterPath(s string) *SeriesUpdate { - su.mutation.SetPosterPath(s) - return su -} - -// SetNillablePosterPath sets the "poster_path" field if the given value is not nil. -func (su *SeriesUpdate) SetNillablePosterPath(s *string) *SeriesUpdate { - if s != nil { - su.SetPosterPath(*s) - } - return su -} - -// ClearPosterPath clears the value of the "poster_path" field. -func (su *SeriesUpdate) ClearPosterPath() *SeriesUpdate { - su.mutation.ClearPosterPath() - return su -} - -// SetCreatedAt sets the "created_at" field. -func (su *SeriesUpdate) SetCreatedAt(t time.Time) *SeriesUpdate { - su.mutation.SetCreatedAt(t) - return su -} - -// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. -func (su *SeriesUpdate) SetNillableCreatedAt(t *time.Time) *SeriesUpdate { - if t != nil { - su.SetCreatedAt(*t) - } - return su -} - -// SetAirDate sets the "air_date" field. -func (su *SeriesUpdate) SetAirDate(s string) *SeriesUpdate { - su.mutation.SetAirDate(s) - return su -} - -// SetNillableAirDate sets the "air_date" field if the given value is not nil. -func (su *SeriesUpdate) SetNillableAirDate(s *string) *SeriesUpdate { - if s != nil { - su.SetAirDate(*s) - } - return su -} - -// SetResolution sets the "resolution" field. -func (su *SeriesUpdate) SetResolution(s string) *SeriesUpdate { - su.mutation.SetResolution(s) - return su -} - -// SetNillableResolution sets the "resolution" field if the given value is not nil. -func (su *SeriesUpdate) SetNillableResolution(s *string) *SeriesUpdate { - if s != nil { - su.SetResolution(*s) - } - return su -} - -// SetStorageID sets the "storage_id" field. -func (su *SeriesUpdate) SetStorageID(i int) *SeriesUpdate { - su.mutation.ResetStorageID() - su.mutation.SetStorageID(i) - return su -} - -// SetNillableStorageID sets the "storage_id" field if the given value is not nil. -func (su *SeriesUpdate) SetNillableStorageID(i *int) *SeriesUpdate { - if i != nil { - su.SetStorageID(*i) - } - return su -} - -// AddStorageID adds i to the "storage_id" field. -func (su *SeriesUpdate) AddStorageID(i int) *SeriesUpdate { - su.mutation.AddStorageID(i) - return su -} - -// ClearStorageID clears the value of the "storage_id" field. -func (su *SeriesUpdate) ClearStorageID() *SeriesUpdate { - su.mutation.ClearStorageID() - return su -} - -// SetTargetDir sets the "target_dir" field. -func (su *SeriesUpdate) SetTargetDir(s string) *SeriesUpdate { - su.mutation.SetTargetDir(s) - return su -} - -// SetNillableTargetDir sets the "target_dir" field if the given value is not nil. -func (su *SeriesUpdate) SetNillableTargetDir(s *string) *SeriesUpdate { - if s != nil { - su.SetTargetDir(*s) - } - return su -} - -// ClearTargetDir clears the value of the "target_dir" field. -func (su *SeriesUpdate) ClearTargetDir() *SeriesUpdate { - su.mutation.ClearTargetDir() - return su -} - -// AddEpisodeIDs adds the "episodes" edge to the Episode entity by IDs. -func (su *SeriesUpdate) AddEpisodeIDs(ids ...int) *SeriesUpdate { - su.mutation.AddEpisodeIDs(ids...) - return su -} - -// AddEpisodes adds the "episodes" edges to the Episode entity. -func (su *SeriesUpdate) AddEpisodes(e ...*Episode) *SeriesUpdate { - ids := make([]int, len(e)) - for i := range e { - ids[i] = e[i].ID - } - return su.AddEpisodeIDs(ids...) -} - -// Mutation returns the SeriesMutation object of the builder. -func (su *SeriesUpdate) Mutation() *SeriesMutation { - return su.mutation -} - -// ClearEpisodes clears all "episodes" edges to the Episode entity. -func (su *SeriesUpdate) ClearEpisodes() *SeriesUpdate { - su.mutation.ClearEpisodes() - return su -} - -// RemoveEpisodeIDs removes the "episodes" edge to Episode entities by IDs. -func (su *SeriesUpdate) RemoveEpisodeIDs(ids ...int) *SeriesUpdate { - su.mutation.RemoveEpisodeIDs(ids...) - return su -} - -// RemoveEpisodes removes "episodes" edges to Episode entities. -func (su *SeriesUpdate) RemoveEpisodes(e ...*Episode) *SeriesUpdate { - ids := make([]int, len(e)) - for i := range e { - ids[i] = e[i].ID - } - return su.RemoveEpisodeIDs(ids...) -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (su *SeriesUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, su.sqlSave, su.mutation, su.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (su *SeriesUpdate) SaveX(ctx context.Context) int { - affected, err := su.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (su *SeriesUpdate) Exec(ctx context.Context) error { - _, err := su.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (su *SeriesUpdate) ExecX(ctx context.Context) { - if err := su.Exec(ctx); err != nil { - panic(err) - } -} - -func (su *SeriesUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := sqlgraph.NewUpdateSpec(series.Table, series.Columns, sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt)) - if ps := su.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := su.mutation.TmdbID(); ok { - _spec.SetField(series.FieldTmdbID, field.TypeInt, value) - } - if value, ok := su.mutation.AddedTmdbID(); ok { - _spec.AddField(series.FieldTmdbID, field.TypeInt, value) - } - if value, ok := su.mutation.ImdbID(); ok { - _spec.SetField(series.FieldImdbID, field.TypeString, value) - } - if su.mutation.ImdbIDCleared() { - _spec.ClearField(series.FieldImdbID, field.TypeString) - } - if value, ok := su.mutation.NameCn(); ok { - _spec.SetField(series.FieldNameCn, field.TypeString, value) - } - if value, ok := su.mutation.NameEn(); ok { - _spec.SetField(series.FieldNameEn, field.TypeString, value) - } - if value, ok := su.mutation.OriginalName(); ok { - _spec.SetField(series.FieldOriginalName, field.TypeString, value) - } - if value, ok := su.mutation.Overview(); ok { - _spec.SetField(series.FieldOverview, field.TypeString, value) - } - if value, ok := su.mutation.PosterPath(); ok { - _spec.SetField(series.FieldPosterPath, field.TypeString, value) - } - if su.mutation.PosterPathCleared() { - _spec.ClearField(series.FieldPosterPath, field.TypeString) - } - if value, ok := su.mutation.CreatedAt(); ok { - _spec.SetField(series.FieldCreatedAt, field.TypeTime, value) - } - if value, ok := su.mutation.AirDate(); ok { - _spec.SetField(series.FieldAirDate, field.TypeString, value) - } - if value, ok := su.mutation.Resolution(); ok { - _spec.SetField(series.FieldResolution, field.TypeString, value) - } - if value, ok := su.mutation.StorageID(); ok { - _spec.SetField(series.FieldStorageID, field.TypeInt, value) - } - if value, ok := su.mutation.AddedStorageID(); ok { - _spec.AddField(series.FieldStorageID, field.TypeInt, value) - } - if su.mutation.StorageIDCleared() { - _spec.ClearField(series.FieldStorageID, field.TypeInt) - } - if value, ok := su.mutation.TargetDir(); ok { - _spec.SetField(series.FieldTargetDir, field.TypeString, value) - } - if su.mutation.TargetDirCleared() { - _spec.ClearField(series.FieldTargetDir, field.TypeString) - } - if su.mutation.EpisodesCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: series.EpisodesTable, - Columns: []string{series.EpisodesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := su.mutation.RemovedEpisodesIDs(); len(nodes) > 0 && !su.mutation.EpisodesCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: series.EpisodesTable, - Columns: []string{series.EpisodesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := su.mutation.EpisodesIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: series.EpisodesTable, - Columns: []string{series.EpisodesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if n, err = sqlgraph.UpdateNodes(ctx, su.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{series.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return 0, err - } - su.mutation.done = true - return n, nil -} - -// SeriesUpdateOne is the builder for updating a single Series entity. -type SeriesUpdateOne struct { - config - fields []string - hooks []Hook - mutation *SeriesMutation -} - -// SetTmdbID sets the "tmdb_id" field. -func (suo *SeriesUpdateOne) SetTmdbID(i int) *SeriesUpdateOne { - suo.mutation.ResetTmdbID() - suo.mutation.SetTmdbID(i) - return suo -} - -// SetNillableTmdbID sets the "tmdb_id" field if the given value is not nil. -func (suo *SeriesUpdateOne) SetNillableTmdbID(i *int) *SeriesUpdateOne { - if i != nil { - suo.SetTmdbID(*i) - } - return suo -} - -// AddTmdbID adds i to the "tmdb_id" field. -func (suo *SeriesUpdateOne) AddTmdbID(i int) *SeriesUpdateOne { - suo.mutation.AddTmdbID(i) - return suo -} - -// SetImdbID sets the "imdb_id" field. -func (suo *SeriesUpdateOne) SetImdbID(s string) *SeriesUpdateOne { - suo.mutation.SetImdbID(s) - return suo -} - -// SetNillableImdbID sets the "imdb_id" field if the given value is not nil. -func (suo *SeriesUpdateOne) SetNillableImdbID(s *string) *SeriesUpdateOne { - if s != nil { - suo.SetImdbID(*s) - } - return suo -} - -// ClearImdbID clears the value of the "imdb_id" field. -func (suo *SeriesUpdateOne) ClearImdbID() *SeriesUpdateOne { - suo.mutation.ClearImdbID() - return suo -} - -// SetNameCn sets the "name_cn" field. -func (suo *SeriesUpdateOne) SetNameCn(s string) *SeriesUpdateOne { - suo.mutation.SetNameCn(s) - return suo -} - -// SetNillableNameCn sets the "name_cn" field if the given value is not nil. -func (suo *SeriesUpdateOne) SetNillableNameCn(s *string) *SeriesUpdateOne { - if s != nil { - suo.SetNameCn(*s) - } - return suo -} - -// SetNameEn sets the "name_en" field. -func (suo *SeriesUpdateOne) SetNameEn(s string) *SeriesUpdateOne { - suo.mutation.SetNameEn(s) - return suo -} - -// SetNillableNameEn sets the "name_en" field if the given value is not nil. -func (suo *SeriesUpdateOne) SetNillableNameEn(s *string) *SeriesUpdateOne { - if s != nil { - suo.SetNameEn(*s) - } - return suo -} - -// SetOriginalName sets the "original_name" field. -func (suo *SeriesUpdateOne) SetOriginalName(s string) *SeriesUpdateOne { - suo.mutation.SetOriginalName(s) - return suo -} - -// SetNillableOriginalName sets the "original_name" field if the given value is not nil. -func (suo *SeriesUpdateOne) SetNillableOriginalName(s *string) *SeriesUpdateOne { - if s != nil { - suo.SetOriginalName(*s) - } - return suo -} - -// SetOverview sets the "overview" field. -func (suo *SeriesUpdateOne) SetOverview(s string) *SeriesUpdateOne { - suo.mutation.SetOverview(s) - return suo -} - -// SetNillableOverview sets the "overview" field if the given value is not nil. -func (suo *SeriesUpdateOne) SetNillableOverview(s *string) *SeriesUpdateOne { - if s != nil { - suo.SetOverview(*s) - } - return suo -} - -// SetPosterPath sets the "poster_path" field. -func (suo *SeriesUpdateOne) SetPosterPath(s string) *SeriesUpdateOne { - suo.mutation.SetPosterPath(s) - return suo -} - -// SetNillablePosterPath sets the "poster_path" field if the given value is not nil. -func (suo *SeriesUpdateOne) SetNillablePosterPath(s *string) *SeriesUpdateOne { - if s != nil { - suo.SetPosterPath(*s) - } - return suo -} - -// ClearPosterPath clears the value of the "poster_path" field. -func (suo *SeriesUpdateOne) ClearPosterPath() *SeriesUpdateOne { - suo.mutation.ClearPosterPath() - return suo -} - -// SetCreatedAt sets the "created_at" field. -func (suo *SeriesUpdateOne) SetCreatedAt(t time.Time) *SeriesUpdateOne { - suo.mutation.SetCreatedAt(t) - return suo -} - -// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. -func (suo *SeriesUpdateOne) SetNillableCreatedAt(t *time.Time) *SeriesUpdateOne { - if t != nil { - suo.SetCreatedAt(*t) - } - return suo -} - -// SetAirDate sets the "air_date" field. -func (suo *SeriesUpdateOne) SetAirDate(s string) *SeriesUpdateOne { - suo.mutation.SetAirDate(s) - return suo -} - -// SetNillableAirDate sets the "air_date" field if the given value is not nil. -func (suo *SeriesUpdateOne) SetNillableAirDate(s *string) *SeriesUpdateOne { - if s != nil { - suo.SetAirDate(*s) - } - return suo -} - -// SetResolution sets the "resolution" field. -func (suo *SeriesUpdateOne) SetResolution(s string) *SeriesUpdateOne { - suo.mutation.SetResolution(s) - return suo -} - -// SetNillableResolution sets the "resolution" field if the given value is not nil. -func (suo *SeriesUpdateOne) SetNillableResolution(s *string) *SeriesUpdateOne { - if s != nil { - suo.SetResolution(*s) - } - return suo -} - -// SetStorageID sets the "storage_id" field. -func (suo *SeriesUpdateOne) SetStorageID(i int) *SeriesUpdateOne { - suo.mutation.ResetStorageID() - suo.mutation.SetStorageID(i) - return suo -} - -// SetNillableStorageID sets the "storage_id" field if the given value is not nil. -func (suo *SeriesUpdateOne) SetNillableStorageID(i *int) *SeriesUpdateOne { - if i != nil { - suo.SetStorageID(*i) - } - return suo -} - -// AddStorageID adds i to the "storage_id" field. -func (suo *SeriesUpdateOne) AddStorageID(i int) *SeriesUpdateOne { - suo.mutation.AddStorageID(i) - return suo -} - -// ClearStorageID clears the value of the "storage_id" field. -func (suo *SeriesUpdateOne) ClearStorageID() *SeriesUpdateOne { - suo.mutation.ClearStorageID() - return suo -} - -// SetTargetDir sets the "target_dir" field. -func (suo *SeriesUpdateOne) SetTargetDir(s string) *SeriesUpdateOne { - suo.mutation.SetTargetDir(s) - return suo -} - -// SetNillableTargetDir sets the "target_dir" field if the given value is not nil. -func (suo *SeriesUpdateOne) SetNillableTargetDir(s *string) *SeriesUpdateOne { - if s != nil { - suo.SetTargetDir(*s) - } - return suo -} - -// ClearTargetDir clears the value of the "target_dir" field. -func (suo *SeriesUpdateOne) ClearTargetDir() *SeriesUpdateOne { - suo.mutation.ClearTargetDir() - return suo -} - -// AddEpisodeIDs adds the "episodes" edge to the Episode entity by IDs. -func (suo *SeriesUpdateOne) AddEpisodeIDs(ids ...int) *SeriesUpdateOne { - suo.mutation.AddEpisodeIDs(ids...) - return suo -} - -// AddEpisodes adds the "episodes" edges to the Episode entity. -func (suo *SeriesUpdateOne) AddEpisodes(e ...*Episode) *SeriesUpdateOne { - ids := make([]int, len(e)) - for i := range e { - ids[i] = e[i].ID - } - return suo.AddEpisodeIDs(ids...) -} - -// Mutation returns the SeriesMutation object of the builder. -func (suo *SeriesUpdateOne) Mutation() *SeriesMutation { - return suo.mutation -} - -// ClearEpisodes clears all "episodes" edges to the Episode entity. -func (suo *SeriesUpdateOne) ClearEpisodes() *SeriesUpdateOne { - suo.mutation.ClearEpisodes() - return suo -} - -// RemoveEpisodeIDs removes the "episodes" edge to Episode entities by IDs. -func (suo *SeriesUpdateOne) RemoveEpisodeIDs(ids ...int) *SeriesUpdateOne { - suo.mutation.RemoveEpisodeIDs(ids...) - return suo -} - -// RemoveEpisodes removes "episodes" edges to Episode entities. -func (suo *SeriesUpdateOne) RemoveEpisodes(e ...*Episode) *SeriesUpdateOne { - ids := make([]int, len(e)) - for i := range e { - ids[i] = e[i].ID - } - return suo.RemoveEpisodeIDs(ids...) -} - -// Where appends a list predicates to the SeriesUpdate builder. -func (suo *SeriesUpdateOne) Where(ps ...predicate.Series) *SeriesUpdateOne { - suo.mutation.Where(ps...) - return suo -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (suo *SeriesUpdateOne) Select(field string, fields ...string) *SeriesUpdateOne { - suo.fields = append([]string{field}, fields...) - return suo -} - -// Save executes the query and returns the updated Series entity. -func (suo *SeriesUpdateOne) Save(ctx context.Context) (*Series, error) { - return withHooks(ctx, suo.sqlSave, suo.mutation, suo.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (suo *SeriesUpdateOne) SaveX(ctx context.Context) *Series { - node, err := suo.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (suo *SeriesUpdateOne) Exec(ctx context.Context) error { - _, err := suo.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (suo *SeriesUpdateOne) ExecX(ctx context.Context) { - if err := suo.Exec(ctx); err != nil { - panic(err) - } -} - -func (suo *SeriesUpdateOne) sqlSave(ctx context.Context) (_node *Series, err error) { - _spec := sqlgraph.NewUpdateSpec(series.Table, series.Columns, sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt)) - id, ok := suo.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Series.id" for update`)} - } - _spec.Node.ID.Value = id - if fields := suo.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, series.FieldID) - for _, f := range fields { - if !series.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - if f != series.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := suo.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := suo.mutation.TmdbID(); ok { - _spec.SetField(series.FieldTmdbID, field.TypeInt, value) - } - if value, ok := suo.mutation.AddedTmdbID(); ok { - _spec.AddField(series.FieldTmdbID, field.TypeInt, value) - } - if value, ok := suo.mutation.ImdbID(); ok { - _spec.SetField(series.FieldImdbID, field.TypeString, value) - } - if suo.mutation.ImdbIDCleared() { - _spec.ClearField(series.FieldImdbID, field.TypeString) - } - if value, ok := suo.mutation.NameCn(); ok { - _spec.SetField(series.FieldNameCn, field.TypeString, value) - } - if value, ok := suo.mutation.NameEn(); ok { - _spec.SetField(series.FieldNameEn, field.TypeString, value) - } - if value, ok := suo.mutation.OriginalName(); ok { - _spec.SetField(series.FieldOriginalName, field.TypeString, value) - } - if value, ok := suo.mutation.Overview(); ok { - _spec.SetField(series.FieldOverview, field.TypeString, value) - } - if value, ok := suo.mutation.PosterPath(); ok { - _spec.SetField(series.FieldPosterPath, field.TypeString, value) - } - if suo.mutation.PosterPathCleared() { - _spec.ClearField(series.FieldPosterPath, field.TypeString) - } - if value, ok := suo.mutation.CreatedAt(); ok { - _spec.SetField(series.FieldCreatedAt, field.TypeTime, value) - } - if value, ok := suo.mutation.AirDate(); ok { - _spec.SetField(series.FieldAirDate, field.TypeString, value) - } - if value, ok := suo.mutation.Resolution(); ok { - _spec.SetField(series.FieldResolution, field.TypeString, value) - } - if value, ok := suo.mutation.StorageID(); ok { - _spec.SetField(series.FieldStorageID, field.TypeInt, value) - } - if value, ok := suo.mutation.AddedStorageID(); ok { - _spec.AddField(series.FieldStorageID, field.TypeInt, value) - } - if suo.mutation.StorageIDCleared() { - _spec.ClearField(series.FieldStorageID, field.TypeInt) - } - if value, ok := suo.mutation.TargetDir(); ok { - _spec.SetField(series.FieldTargetDir, field.TypeString, value) - } - if suo.mutation.TargetDirCleared() { - _spec.ClearField(series.FieldTargetDir, field.TypeString) - } - if suo.mutation.EpisodesCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: series.EpisodesTable, - Columns: []string{series.EpisodesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := suo.mutation.RemovedEpisodesIDs(); len(nodes) > 0 && !suo.mutation.EpisodesCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: series.EpisodesTable, - Columns: []string{series.EpisodesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := suo.mutation.EpisodesIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: series.EpisodesTable, - Columns: []string{series.EpisodesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - _node = &Series{config: suo.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, suo.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{series.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - suo.mutation.done = true - return _node, nil -} diff --git a/ent/tx.go b/ent/tx.go index 7776517..f038106 100644 --- a/ent/tx.go +++ b/ent/tx.go @@ -20,8 +20,8 @@ type Tx struct { History *HistoryClient // Indexers is the client for interacting with the Indexers builders. Indexers *IndexersClient - // Series is the client for interacting with the Series builders. - Series *SeriesClient + // Media is the client for interacting with the Media builders. + Media *MediaClient // Settings is the client for interacting with the Settings builders. Settings *SettingsClient // Storage is the client for interacting with the Storage builders. @@ -161,7 +161,7 @@ func (tx *Tx) init() { tx.Episode = NewEpisodeClient(tx.config) tx.History = NewHistoryClient(tx.config) tx.Indexers = NewIndexersClient(tx.config) - tx.Series = NewSeriesClient(tx.config) + tx.Media = NewMediaClient(tx.config) tx.Settings = NewSettingsClient(tx.config) tx.Storage = NewStorageClient(tx.config) } diff --git a/pkg/tmdb/tmdb.go b/pkg/tmdb/tmdb.go index 479d30f..0ff06b9 100644 --- a/pkg/tmdb/tmdb.go +++ b/pkg/tmdb/tmdb.go @@ -2,6 +2,7 @@ package tmdb import ( "polaris/log" + "strconv" tmdb "github.com/cyruzin/golang-tmdb" "github.com/pkg/errors" @@ -26,11 +27,14 @@ func NewClient(apiKey string) (*Client, error) { func (c *Client) GetTvDetails(id int, language string) (*tmdb.TVDetails, error) { log.Infof("tv id %d, language %s", id, language) - language = wrapLanguage(language) d, err := c.tmdbClient.GetTVDetails(id, withLangOption(language)) return d, err } +func (c *Client) GetMovieDetails(id int, language string) (*tmdb.MovieDetails, error) { + return c.tmdbClient.GetMovieDetails(id, withLangOption(language)) +} + func (c *Client) SearchTvShow(query string, lang string) (*tmdb.SearchTVShows, error) { r, err := c.tmdbClient.GetSearchTVShow(query, withLangOption(lang)) if err != nil { @@ -39,6 +43,74 @@ func (c *Client) SearchTvShow(query string, lang string) (*tmdb.SearchTVShows, e return r, nil } +type SearchResult struct { + Page int `json:"page"` + Results []*SearchResultItem `json:"results"` + TotalResults int64 `json:"total_results"` + TotalPages int64 `json:"total_pages"` + +} + +type SearchResultItem struct { + PosterPath string `json:"poster_path,omitempty"` + ID int64 `json:"id"` + Overview string `json:"overview,omitempty"` + MediaType string `json:"media_type"` + FirstAirDate string `json:"first_air_date,omitempty"` + OriginCountry []string `json:"origin_country,omitempty"` + GenreIDs []int64 `json:"genre_ids,omitempty"` + OriginalLanguage string `json:"original_language,omitempty"` + Name string `json:"name,omitempty"` + OriginalName string `json:"original_name,omitempty"` + Adult bool `json:"adult,omitempty"` +} + +func (c *Client) SearchMedia(query string, lang string, page int) (*SearchResult, error) { + if page == 0 { + page = 1 + } + options := withLangOption(lang) + options["page"] = strconv.Itoa(page) + res, err := c.tmdbClient.GetSearchMulti(query, options) + if err != nil { + return nil, errors.Wrap(err, "query imdb") + } + + searchResult := &SearchResult{ + Page: res.Page, + TotalResults: res.TotalResults, + TotalPages: res.TotalPages, + } + + for _, r := range res.Results { + if r.MediaType != "tv" && r.MediaType != "movie" { + continue + } + item := &SearchResultItem{ + PosterPath: r.PosterPath, + ID: r.ID, + Overview: r.Overview, + MediaType: r.MediaType, + OriginCountry: r.OriginCountry, + OriginalLanguage: r.OriginalLanguage, + GenreIDs: r.GenreIDs, + Adult: r.Adult, + } + if r.MediaType == "tv" { + item.Name = r.Name + item.OriginalName = r.OriginalName + item.FirstAirDate = r.FirstAirDate + } else if r.MediaType == "movie" { + item.Name = r.Title + item.OriginalName = r.OriginalTitle + item.FirstAirDate = r.ReleaseDate + } + searchResult.Results = append(searchResult.Results, item) + + } + return searchResult, nil +} + func (c *Client) GetEposideDetail(id, seasonNumber, eposideNumber int, language string) (*tmdb.TVEpisodeDetails, error) { d, err := c.tmdbClient.GetTVEpisodeDetails(id, seasonNumber, eposideNumber, withLangOption(language)) return d, err diff --git a/pkg/transmission/transmission.go b/pkg/transmission/transmission.go index 3766590..f324b71 100644 --- a/pkg/transmission/transmission.go +++ b/pkg/transmission/transmission.go @@ -121,6 +121,10 @@ func (t *Torrent) Remove() error { }) } +func (t *Torrent) Size() int { + return int(t.getTorrent().TotalSize.Byte()) +} + func (t *Torrent) Save() string { d, _ := json.Marshal(*t) diff --git a/server/resources.go b/server/resources.go index a815788..a1ce6c8 100644 --- a/server/resources.go +++ b/server/resources.go @@ -17,8 +17,7 @@ import ( "github.com/pkg/errors" ) -func (s *Server) searchTvWithTorznab(name string, season, episode int) []torznab.Result { - q := fmt.Sprintf("%s S%02dE%02d", name, season, episode) +func (s *Server) searchWithTorznab(q string) []torznab.Result { var res []torznab.Result allTorznab := s.db.GetAllTorznabInfo() @@ -72,23 +71,25 @@ func (s *Server) GetAllIndexers(c *gin.Context) (interface{}, error) { return indexers, nil } -type searchAndDownloadIn struct { - ID int `json:"id"` - Season int `json:"season"` - Episode int `json:"episode"` -} -func (s *Server) searchAndDownload(seriesId, seasonNum, episodeNum int) (*string, error) { +func (s *Server) getDownloadClient() (*transmission.Client, error) { tr := s.db.GetTransmission() trc, err := transmission.NewClient(transmission.Config{ - URL: tr.URL, - User: tr.User, + URL: tr.URL, + User: tr.User, Password: tr.Password, }) if err != nil { return nil, errors.Wrap(err, "connect transmission") } - series := s.db.GetSeriesDetails(seriesId) + return trc, nil +} +func (s *Server) searchAndDownload(seriesId, seasonNum, episodeNum int) (*string, error) { + trc, err := s.getDownloadClient() + if err != nil { + return nil, errors.Wrap(err, "connect transmission") + } + series := s.db.GetMediaDetails(seriesId) if series == nil { return nil, fmt.Errorf("no tv series of id %v", seriesId) } @@ -102,11 +103,13 @@ func (s *Server) searchAndDownload(seriesId, seasonNum, episodeNum int) (*string return nil, errors.Errorf("no episode of season %d episode %d", seasonNum, episodeNum) } - res := s.searchTvWithTorznab(series.OriginalName, seasonNum, episodeNum) + q := fmt.Sprintf("%s S%02dE%02d", series.OriginalName, seasonNum, episodeNum) + + res := s.searchWithTorznab(q) if len(res) == 0 { return nil, fmt.Errorf("no resource found") } - r1 := s.findBestMatch(res, seasonNum, episodeNum, series) + r1 := s.findBestMatchTv(res, seasonNum, episodeNum, series) log.Infof("found resource to download: %v", r1) torrent, err := trc.Download(r1.Magnet, s.db.GetDownloadDir()) if err != nil { @@ -116,14 +119,14 @@ func (s *Server) searchAndDownload(seriesId, seasonNum, episodeNum int) (*string dir := fmt.Sprintf("%s/Season %02d", series.TargetDir, ep.SeasonNumber) - history, err :=s.db.SaveHistoryRecord(ent.History{ - SeriesID: ep.SeriesID, - EpisodeID: ep.ID, + 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(), + TargetDir: dir, + Status: history.StatusRunning, + Size: r1.Size, + Saved: torrent.Save(), }) s.db.SetEpisodeStatus(ep.ID, episode.StatusDownloading) if err != nil { @@ -135,10 +138,10 @@ func (s *Server) searchAndDownload(seriesId, seasonNum, episodeNum int) (*string return &r1.Name, nil } -func (s *Server) findBestMatch(resources []torznab.Result,season, episode int, series *db.SeriesDetails) torznab.Result { +func (s *Server) findBestMatchTv(resources []torznab.Result, season, episode int, series *db.MediaDetails) torznab.Result { var filtered []torznab.Result for _, r := range resources { - if !(series.NameEn != "" && strings.Contains(r.Name,series.NameEn)) && !strings.Contains(r.Name, series.OriginalName) { + if !(series.NameEn != "" && strings.Contains(r.Name, series.NameEn)) && !strings.Contains(r.Name, series.OriginalName) { //name not match continue } @@ -164,7 +167,13 @@ func (s *Server) findBestMatch(resources []torznab.Result,season, episode int, s return filtered[0] } -func (s *Server) SearchAndDownload(c *gin.Context) (interface{}, error) { +type searchAndDownloadIn struct { + ID int `json:"id" binding:"required"` + Season int `json:"season"` + Episode int `json:"episode"` +} + +func (s *Server) SearchTvAndDownload(c *gin.Context) (interface{}, error) { var in searchAndDownloadIn if err := c.ShouldBindJSON(&in); err != nil { return nil, errors.Wrap(err, "bind json") @@ -180,6 +189,105 @@ func (s *Server) SearchAndDownload(c *gin.Context) (interface{}, error) { }, nil } +type TorznabSearchResult struct { + Name string `json:"name"` + Size int `json:"size"` + Link string `json:"link"` + Seeders int `json:"seeders"` + Peers int `json:"peers"` +} + +func (s *Server) SearchAvailableMovies(c *gin.Context) (interface{}, error) { + ids := c.Param("id") + id, err := strconv.Atoi(ids) + if err != nil { + return nil, errors.Wrap(err, "convert") + } + + movieDetail := s.db.GetMediaDetails(id) + if movieDetail == nil { + return nil, errors.New("no media found of id " + ids) + } + + res := s.searchWithTorznab(movieDetail.NameEn) + + res1 := s.searchWithTorznab(movieDetail.NameCn) + res = append(res, res1...) + + if len(res) == 0 { + return nil, fmt.Errorf("no resource found") + } + + var searchResults []TorznabSearchResult + for _, r := range res { + + searchResults = append(searchResults, TorznabSearchResult{ + Name: r.Name, + Size: r.Size, + Seeders: r.Seeders, + Peers: r.Peers, + Link: r.Magnet, + }) + } + + return searchResults, nil + +} + +type downloadTorrentIn struct { + MediaID int `json:"media_id" binding:"required"` + Link string `json:"link" binding:"required"` +} +func (s *Server) DownloadMovieTorrent(c *gin.Context) (interface{}, error) { + var in downloadTorrentIn + if err := c.ShouldBindJSON(&in); err != nil { + return nil, errors.Wrap(err, "bind json") + } + log.Infof("download torrent input: %+v", in) + + trc, err := s.getDownloadClient() + if err != nil { + return nil, errors.Wrap(err, "connect transmission") + } + media := s.db.GetMediaDetails(in.MediaID) + if media == nil { + return nil, fmt.Errorf("no tv series of id %v", in.MediaID) + } + + torrent, err := trc.Download(in.Link, s.db.GetDownloadDir()) + if err != nil { + return nil, errors.Wrap(err, "downloading") + } + torrent.Start() + + go func () { + for { + if !torrent.Exists() { + continue + } + history, err := s.db.SaveHistoryRecord(ent.History{ + MediaID: media.ID, + SourceTitle: torrent.Name(), + TargetDir: "./", + Status: history.StatusRunning, + Size: torrent.Size(), + Saved: torrent.Save(), + }) + if err != nil { + log.Errorf("save history error: %v", err) + } + + s.tasks[history.ID] = &Task{Torrent: torrent} + + break + } + }() + + log.Infof("success add %s to download task", media.NameEn) + return media.NameEn, nil + +} + type downloadClientIn struct { Name string `json:"name"` URL string `json:"url"` @@ -215,4 +323,4 @@ func (s *Server) DeleteDownloadCLient(c *gin.Context) (interface{}, error) { } s.db.DeleteDownloadCLient(id) return "success", nil -} \ No newline at end of file +} diff --git a/server/scheduler.go b/server/scheduler.go index 7ee0ebb..ba8cea2 100644 --- a/server/scheduler.go +++ b/server/scheduler.go @@ -5,6 +5,7 @@ import ( "polaris/ent" "polaris/ent/episode" "polaris/ent/history" + "polaris/ent/media" storage1 "polaris/ent/storage" "polaris/log" "polaris/pkg" @@ -70,7 +71,7 @@ func (s *Server) moveCompletedTask(id int) (err error) { } }() - series := s.db.GetSeriesDetails(r.SeriesID) + series := s.db.GetMediaDetails(r.MediaID) if series == nil { return nil } @@ -107,7 +108,7 @@ func (s *Server) updateSeriesEpisodes(seriesId int) { } func (s *Server) checkAllFiles() { - var tvs = s.db.GetWatchlist() + var tvs = s.db.GetMediaWatchlist(media.MediaTypeTv) for _, se := range tvs { if err := s.checkFileExists(se); err != nil { log.Errorf("check files for %s error: %v", se.NameCn, err) @@ -115,7 +116,7 @@ func (s *Server) checkAllFiles() { } } -func (s *Server) checkFileExists(series *ent.Series) error { +func (s *Server) checkFileExists(series *ent.Media) error { log.Infof("check files in directory: %s", series.TargetDir) st := s.db.GetStorage(series.StorageID) diff --git a/server/server.go b/server/server.go index 287e00e..692e0f3 100644 --- a/server/server.go +++ b/server/server.go @@ -1,7 +1,10 @@ package server import ( + "fmt" "net/http" + "net/http/httputil" + "net/url" "polaris/db" "polaris/log" "polaris/pkg/tmdb" @@ -26,11 +29,11 @@ func NewServer(db *db.Client) *Server { } type Server struct { - r *gin.Engine - db *db.Client - cron *cron.Cron - language string - tasks map[int]*Task + r *gin.Engine + db *db.Client + cron *cron.Cron + language string + tasks map[int]*Task jwtSerect string } @@ -46,6 +49,7 @@ func (s *Server) Serve() error { api := s.r.Group("/api/v1") api.Use(s.authModdleware) api.StaticFS("/img", http.Dir(db.ImgPath)) + api.Any("/posters/*proxyPath", s.proxyPosters) setting := api.Group("/setting") { @@ -60,20 +64,24 @@ func (s *Server) Serve() error { activity.DELETE("/:id", HttpHandler(s.RemoveActivity)) } - tv := api.Group("/tv") + tv := api.Group("/media") { - tv.GET("/search", HttpHandler(s.SearchTvSeries)) - tv.POST("/watchlist", HttpHandler(s.AddWatchlist)) - tv.GET("/watchlist", HttpHandler(s.GetWatchlist)) - tv.GET("/series/:id", HttpHandler(s.GetTvDetails)) - tv.DELETE("/series/:id", HttpHandler(s.DeleteFromWatchlist)) + tv.GET("/search", HttpHandler(s.SearchMedia)) + tv.POST("/tv/watchlist", HttpHandler(s.AddTv2Watchlist)) + tv.GET("/tv/watchlist", HttpHandler(s.GetTvWatchlist)) + tv.POST("/movie/watchlist", HttpHandler(s.AddMovie2Watchlist)) + tv.GET("/movie/watchlist", HttpHandler(s.GetMovieWatchlist)) + tv.GET("/movie/resources/:id", HttpHandler(s.SearchAvailableMovies)) + tv.POST("/movie/resources/", HttpHandler(s.DownloadMovieTorrent)) + tv.GET("/record/:id", HttpHandler(s.GetMediaDetails)) + tv.DELETE("/record/:id", HttpHandler(s.DeleteFromWatchlist)) tv.GET("/resolutions", HttpHandler(s.GetAvailableResolutions)) } indexer := api.Group("/indexer") { indexer.GET("/", HttpHandler(s.GetAllIndexers)) indexer.POST("/add", HttpHandler(s.AddTorznabInfo)) - indexer.POST("/download", HttpHandler(s.SearchAndDownload)) + indexer.POST("/download", HttpHandler(s.SearchTvAndDownload)) indexer.DELETE("/del/:id", HttpHandler(s.DeleteTorznabInfo)) } @@ -125,3 +133,17 @@ func (s *Server) reloadTasks() { s.tasks[t.ID] = &Task{Torrent: torrent} } } + +func (s *Server) proxyPosters(c *gin.Context) { + remote, _ := url.Parse("https://image.tmdb.org") + proxy := httputil.NewSingleHostReverseProxy(remote) + + proxy.Director = func(req *http.Request) { + req.Header = c.Request.Header + req.Host = remote.Host + req.URL.Scheme = remote.Scheme + req.URL.Host = remote.Host + req.URL.Path = fmt.Sprintf("/t/p/w500/%v", c.Param("proxyPath")) + } + proxy.ServeHTTP(c.Writer, c.Request) +} diff --git a/server/watchlist.go b/server/watchlist.go index af39a13..7ea30d0 100644 --- a/server/watchlist.go +++ b/server/watchlist.go @@ -8,6 +8,7 @@ import ( "path/filepath" "polaris/db" "polaris/ent" + "polaris/ent/media" "polaris/log" "strconv" @@ -33,13 +34,27 @@ func (s *Server) SearchTvSeries(c *gin.Context) (interface{}, error) { return r, nil } -type addWatchlistIn struct { - TmdbID int `json:"tmdb_id" binding:"required"` - StorageID int `json:"storage_id" ` - Resolution db.ResolutionType `json:"resolution" binding:"required"` +func(s *Server) SearchMedia(c *gin.Context) (interface{}, error) { + var q searchTvParam + if err := c.ShouldBindQuery(&q); err != nil { + return nil, errors.Wrap(err, "bind query") + } + log.Infof("search media with keyword: %v", q.Query) + r, err := s.MustTMDB().SearchMedia(q.Query, s.language, 1) + if err != nil { + return nil, errors.Wrap(err, "search tv") + } + return r, nil + } -func (s *Server) AddWatchlist(c *gin.Context) (interface{}, error) { +type addWatchlistIn struct { + TmdbID int `json:"tmdb_id" binding:"required"` + StorageID int `json:"storage_id" ` + Resolution string `json:"resolution" binding:"required"` +} + +func (s *Server) AddTv2Watchlist(c *gin.Context) (interface{}, error) { var in addWatchlistIn if err := c.ShouldBindJSON(&in); err != nil { return nil, errors.Wrap(err, "bind query") @@ -53,7 +68,7 @@ func (s *Server) AddWatchlist(c *gin.Context) (interface{}, error) { detailEn, _ := s.MustTMDB().GetTvDetails(in.TmdbID, db.LanguageEN) var nameEn = detailEn.Name var detail *tmdb.TVDetails - if s.language == "" || s.language ==db.LanguageCN { + if s.language == "" || s.language == db.LanguageCN { detail = detailCn } else { detail = detailEn @@ -83,21 +98,80 @@ func (s *Server) AddWatchlist(c *gin.Context) (interface{}, error) { epIds = append(epIds, epid) } } - r, err := s.db.AddWatchlist(in.StorageID, nameCn, nameEn, detail, epIds, db.R1080p) + 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: string(in.Resolution), + StorageID: in.StorageID, + + }, epIds) if err != nil { return nil, errors.Wrap(err, "add to list") } - go func () { + go func() { if err := s.downloadPoster(detail.PosterPath, r.ID); err != nil { log.Errorf("download poster error: %v", err) - } + } }() log.Infof("add tv %s to watchlist success", detail.Name) return nil, nil } -func (s *Server) downloadPoster(path string, seriesId int) error{ +func (s *Server) AddMovie2Watchlist(c *gin.Context) (interface{}, error) { + var in addWatchlistIn + if err := c.ShouldBindJSON(&in); err != nil { + return nil, errors.Wrap(err, "bind query") + } + detailCn, err := s.MustTMDB().GetMovieDetails(in.TmdbID, db.LanguageCN) + if err != nil { + return nil, errors.Wrap(err, "get movie detail") + } + var nameCn = detailCn.Title + + detailEn, _ := s.MustTMDB().GetMovieDetails(in.TmdbID, db.LanguageEN) + var nameEn = detailEn.Title + var detail *tmdb.MovieDetails + if s.language == "" || s.language == db.LanguageCN { + detail = detailCn + } else { + detail = detailEn + } + log.Infof("find detail for movie id %d: %v", in.TmdbID, detail) + + + r, err := s.db.AddMediaWatchlist(&ent.Media{ + TmdbID: int(detail.ID), + MediaType: media.MediaTypeMovie, + NameCn: nameCn, + NameEn: nameEn, + OriginalName: detail.OriginalTitle, + Overview: detail.Overview, + AirDate: detail.ReleaseDate, + Resolution: string(in.Resolution), + StorageID: in.StorageID, + + }, nil) + if err != nil { + return nil, errors.Wrap(err, "add to list") + } + go func() { + if err := s.downloadPoster(detail.PosterPath, r.ID); err != nil { + log.Errorf("download poster error: %v", err) + } + }() + + log.Infof("add movie %s to watchlist success", detail.Title) + return nil, nil + +} + +func (s *Server) downloadPoster(path string, mediaID int) error { var tmdbImgBaseUrl = "https://image.tmdb.org/t/p/w500/" url := tmdbImgBaseUrl + path log.Infof("try to download poster: %v", url) @@ -105,10 +179,10 @@ func (s *Server) downloadPoster(path string, seriesId int) error{ if err != nil { return errors.Wrap(err, "http get") } - targetDir := fmt.Sprintf("%v/%d", db.ImgPath, seriesId) + targetDir := fmt.Sprintf("%v/%d", db.ImgPath, mediaID) os.MkdirAll(targetDir, 0777) ext := filepath.Ext(path) - targetFile := filepath.Join(targetDir, "poster"+ ext) + targetFile := filepath.Join(targetDir, "poster"+ext) f, err := os.Create(targetFile) if err != nil { return errors.Wrap(err, "new file") @@ -122,18 +196,24 @@ func (s *Server) downloadPoster(path string, seriesId int) error{ return nil } -func (s *Server) GetWatchlist(c *gin.Context) (interface{}, error) { - list := s.db.GetWatchlist() +func (s *Server) GetTvWatchlist(c *gin.Context) (interface{}, error) { + list := s.db.GetMediaWatchlist(media.MediaTypeTv) return list, nil } -func (s *Server) GetTvDetails(c *gin.Context) (interface{}, error) { +func (s *Server) GetMovieWatchlist(c *gin.Context) (interface{}, error) { + list := s.db.GetMediaWatchlist(media.MediaTypeMovie) + return list, nil +} + + +func (s *Server) GetMediaDetails(c *gin.Context) (interface{}, error) { ids := c.Param("id") id, err := strconv.Atoi(ids) if err != nil { return nil, errors.Wrap(err, "convert") } - detail := s.db.GetSeriesDetails(id) + detail := s.db.GetMediaDetails(id) return detail, nil } @@ -151,9 +231,9 @@ func (s *Server) DeleteFromWatchlist(c *gin.Context) (interface{}, error) { if err != nil { return nil, errors.Wrap(err, "convert") } - if err := s.db.DeleteSeries(id); err != nil { + if err := s.db.DeleteMedia(id); err != nil { return nil, errors.Wrap(err, "delete db") } os.RemoveAll(filepath.Join(db.ImgPath, ids)) //delete image related return "success", nil -} \ No newline at end of file +} diff --git a/ui/lib/login_page.dart b/ui/lib/login_page.dart index 6a75b13..7db2e4e 100644 --- a/ui/lib/login_page.dart +++ b/ui/lib/login_page.dart @@ -5,7 +5,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; import 'package:quiver/strings.dart'; import 'package:ui/providers/login.dart'; -import 'package:ui/weclome.dart'; +import 'package:ui/tv_watchlist.dart'; class LoginScreen extends ConsumerWidget { static const route = '/login'; @@ -30,7 +30,7 @@ class LoginScreen extends ConsumerWidget { ref.read(authSettingProvider.notifier).login(data.name, data.password); }, onSubmitAnimationCompleted: () { - context.go(WelcomePage.route); + context.go(TvWatchlistPage.route); }, onRecoverPassword: _recoverPassword, userValidator: (value) => isBlank(value)? "不能为空":null, diff --git a/ui/lib/main.dart b/ui/lib/main.dart index 818c78d..d8ecc20 100644 --- a/ui/lib/main.dart +++ b/ui/lib/main.dart @@ -4,12 +4,13 @@ import 'package:go_router/go_router.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:ui/activity.dart'; import 'package:ui/login_page.dart'; +import 'package:ui/movie_watchlist.dart'; import 'package:ui/navdrawer.dart'; import 'package:ui/providers/APIs.dart'; import 'package:ui/search.dart'; import 'package:ui/system_settings.dart'; import 'package:ui/tv_details.dart'; -import 'package:ui/weclome.dart'; +import 'package:ui/tv_watchlist.dart'; void main() { runApp(const MyApp()); @@ -76,11 +77,25 @@ class MyApp extends StatelessWidget { routes: [ GoRoute( path: "/", - redirect: (context, state) => WelcomePage.route, + redirect: (context, state) => TvWatchlistPage.route, ), GoRoute( - path: WelcomePage.route, - builder: (context, state) => const WelcomePage(), + path: TvWatchlistPage.route, + builder: (context, state) => const TvWatchlistPage(), + ), + GoRoute( + path: TvDetailsPage.route, + builder: (context, state) => + TvDetailsPage(seriesId: state.pathParameters['id']!), + ), + GoRoute( + path: MovieWatchlistPage.route, + builder: (context, state) => const MovieWatchlistPage(), + ), + GoRoute( + path: MovieDetailsPage.route, + builder: (context, state) => + MovieDetailsPage(id: state.pathParameters['id']!), ), GoRoute( path: SearchPage.route, @@ -90,11 +105,6 @@ class MyApp extends StatelessWidget { path: SystemSettingsPage.route, builder: (context, state) => const SystemSettingsPage(), ), - GoRoute( - path: TvDetailsPage.route, - builder: (context, state) => - TvDetailsPage(seriesId: state.pathParameters['id']!), - ), GoRoute( path: ActivityPage.route, builder: (context, state) => const ActivityPage(), @@ -104,7 +114,7 @@ class MyApp extends StatelessWidget { final _router = GoRouter( navigatorKey: APIs.navigatorKey, - initialLocation: WelcomePage.route, + initialLocation: TvWatchlistPage.route, routes: [ _shellRoute, GoRoute( diff --git a/ui/lib/movie_watchlist.dart b/ui/lib/movie_watchlist.dart new file mode 100644 index 0000000..9afe7a0 --- /dev/null +++ b/ui/lib/movie_watchlist.dart @@ -0,0 +1,203 @@ +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/providers/welcome_data.dart'; +import 'package:ui/utils.dart'; +import 'package:ui/widgets/progress_indicator.dart'; + +class MovieWatchlistPage extends ConsumerWidget { + static const route = "/movie"; + + const MovieWatchlistPage({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final data = ref.watch(movieWatchlistDataProvider); + + return switch (data) { + AsyncData(:final value) => GridView.builder( + padding: const EdgeInsets.all(30), + itemCount: value.length, + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 6), + itemBuilder: (context, i) { + var item = value[i]; + return Card( + margin: const EdgeInsets.all(4), + clipBehavior: Clip.hardEdge, + child: InkWell( + //splashColor: Colors.blue.withAlpha(30), + onTap: () { + context.go(MovieDetailsPage.toRoute(item.id!)); + //showDialog(context: context, builder: builder) + }, + child: Column( + children: [ + Flexible( + child: Image.network( + "${APIs.imagesUrl}/${item.id}/poster.jpg", + fit: BoxFit.contain, + headers: APIs.authHeaders, + ), + ), + Text( + item.name!, + style: const TextStyle( + fontSize: 14, fontWeight: FontWeight.bold), + ), + ], + ), + )); + }), + _ => const MyProgressIndicator(), + }; + } +} + +class MovieDetailsPage extends ConsumerStatefulWidget { + static const route = "/movie/:id"; + + static String toRoute(int id) { + return "/movie/$id"; + } + + final String id; + + const MovieDetailsPage({super.key, required this.id}); + + @override + ConsumerState createState() { + return _MovieDetailsPageState(id: id); + } +} + +class _MovieDetailsPageState extends ConsumerState { + final String id; + + _MovieDetailsPageState({required this.id}); + + @override + Widget build(BuildContext context) { + var seriesDetails = ref.watch(mediaDetailsProvider(id)); + var torrents = ref.watch(movieTorrentsDataProvider(id)); + var storage = ref.watch(storageSettingProvider); + + return seriesDetails.when( + data: (details) { + return ListView( + children: [ + Card( + margin: const EdgeInsets.all(4), + clipBehavior: Clip.hardEdge, + child: Padding( + padding: const EdgeInsets.all(10), + child: Row( + children: [ + Flexible( + flex: 1, + child: Padding( + padding: const EdgeInsets.all(10), + child: Image.network( + "${APIs.imagesUrl}/${details.id}/poster.jpg", + fit: BoxFit.contain, + headers: APIs.authHeaders, + ), + ), + ), + Expanded( + flex: 6, + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text("${details.resolution}"), + const SizedBox( + width: 30, + ), + storage.when( + data: (value) { + for (final s in value) { + if (s.id == details.storageId) { + return Text( + "${s.name}(${s.implementation})"); + } + } + return const Text("未知存储"); + }, + error: (error, stackTrace) => + Text("$error"), + loading: () => + const MyProgressIndicator()), + ], + ), + const Divider(thickness: 1, height: 1), + Text( + "${details.name} (${details.airDate!.split("-")[0]})", + style: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold), + ), + const Text(""), + Text( + details.overview!, + ), + ], + )), + Column( + children: [ + IconButton( + onPressed: () { + ref + .read( + mediaDetailsProvider(id).notifier) + .delete(); + context.go(MovieDetailsPage.route); + }, + icon: const Icon(Icons.delete)) + ], + ) + ], + ), + ), + ], + ), + ), + ), + torrents.when( + data: (v) { + return DataTable( + columns: const [ + DataColumn(label: Text("名称")), + DataColumn(label: Text("大小")), + DataColumn(label: Text("seeders")), + DataColumn(label: Text("peers")), + ], + rows: List.generate(v.length, (i) { + final torrent = v[i]; + return DataRow(cells: [ + DataCell(Text("${torrent.name}")), + DataCell(Text("${torrent.size?.readableFileSize()}")), + DataCell(Text("${torrent.seeders}")), + DataCell(Text("${torrent.peers}")), + ]); + }), + ); + }, + error: (error, trace) => Text("$error"), + loading: () => const MyProgressIndicator()), + ], + ); + }, + error: (err, trace) { + return Text("$err"); + }, + loading: () => const MyProgressIndicator()); + } +} diff --git a/ui/lib/navdrawer.dart b/ui/lib/navdrawer.dart index 1869b06..de95b35 100644 --- a/ui/lib/navdrawer.dart +++ b/ui/lib/navdrawer.dart @@ -1,9 +1,10 @@ import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:ui/activity.dart'; +import 'package:ui/movie_watchlist.dart'; import 'package:ui/search.dart'; import 'package:ui/system_settings.dart'; -import 'package:ui/weclome.dart'; +import 'package:ui/tv_watchlist.dart'; class NavDrawer extends StatefulWidget { const NavDrawer({super.key}); @@ -33,18 +34,24 @@ class _NavDrawerState extends State { _counter = value; }); if (value == 0) { - context.go(WelcomePage.route); + context.go(MovieWatchlistPage.route); } else if (value == 1) { - context.go(SearchPage.route); + context.go(TvWatchlistPage.route); } else if (value == 2) { - context.go(ActivityPage.route); + context.go(SearchPage.route); } else if (value == 3) { + context.go(ActivityPage.route); + } else if (value == 4) { context.go(SystemSettingsPage.route); } }, extended: MediaQuery.of(context).size.width >= 850, unselectedIconTheme: const IconThemeData(color: Colors.grey), destinations: const [ + NavigationRailDestination( + icon: Icon(Icons.movie), + label: Text('电影'), + ), NavigationRailDestination( icon: Icon(Icons.live_tv), label: Text('电视剧'), diff --git a/ui/lib/providers/APIs.dart b/ui/lib/providers/APIs.dart index b211ee3..44347a2 100644 --- a/ui/lib/providers/APIs.dart +++ b/ui/lib/providers/APIs.dart @@ -7,10 +7,12 @@ import 'package:shared_preferences/shared_preferences.dart'; class APIs { static final _baseUrl = baseUrl(); - static final searchUrl = "$_baseUrl/api/v1/tv/search"; + static final searchUrl = "$_baseUrl/api/v1/media/search"; static final settingsUrl = "$_baseUrl/api/v1/setting/do"; - static final watchlistUrl = "$_baseUrl/api/v1/tv/watchlist"; - static final seriesDetailUrl = "$_baseUrl/api/v1/tv/series/"; + static final watchlistTvUrl = "$_baseUrl/api/v1/media/tv/watchlist"; + static final watchlistMovieUrl = "$_baseUrl/api/v1/media/movie/watchlist"; + static final availableMoviesUrl = "$_baseUrl/api/v1/media/movie/resources/"; + static final seriesDetailUrl = "$_baseUrl/api/v1/media/record/"; static final searchAndDownloadUrl = "$_baseUrl/api/v1/indexer/download"; static final allIndexersUrl = "$_baseUrl/api/v1/indexer/"; static final addIndexerUrl = "$_baseUrl/api/v1/indexer/add"; @@ -24,7 +26,7 @@ class APIs { static final activityUrl = "$_baseUrl/api/v1/activity/"; static final imagesUrl = "$_baseUrl/api/v1/img"; - static const tmdbImgBaseUrl = "https://image.tmdb.org/t/p/w500/"; + static final tmdbImgBaseUrl = "$_baseUrl/api/v1/posters"; static const tmdbApiKey = "tmdb_api_key"; static const downloadDirKey = "download_dir"; diff --git a/ui/lib/providers/activity.dart b/ui/lib/providers/activity.dart index c9e8449..d40881d 100644 --- a/ui/lib/providers/activity.dart +++ b/ui/lib/providers/activity.dart @@ -40,7 +40,7 @@ class ActivityData extends AutoDisposeAsyncNotifier> { class Activity { Activity( {required this.id, - required this.seriesId, + required this.mediaId, required this.episodeId, required this.sourceTitle, required this.date, @@ -50,7 +50,7 @@ class Activity { required this.progress}); final int? id; - final int? seriesId; + final int? mediaId; final int? episodeId; final String? sourceTitle; final DateTime? date; @@ -62,7 +62,7 @@ class Activity { factory Activity.fromJson(Map json) { return Activity( id: json["id"], - seriesId: json["series_id"], + mediaId: json["media_id"], episodeId: json["episode_id"], sourceTitle: json["source_title"], date: DateTime.tryParse(json["date"] ?? ""), diff --git a/ui/lib/providers/series_details.dart b/ui/lib/providers/series_details.dart index 1e6e587..fad0219 100644 --- a/ui/lib/providers/series_details.dart +++ b/ui/lib/providers/series_details.dart @@ -4,7 +4,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:ui/providers/APIs.dart'; import 'package:ui/providers/server_response.dart'; -var seriesDetailsProvider = AsyncNotifierProvider.autoDispose +var mediaDetailsProvider = AsyncNotifierProvider.autoDispose .family(SeriesDetailData.new); class SeriesDetailData diff --git a/ui/lib/providers/welcome_data.dart b/ui/lib/providers/welcome_data.dart index 0047f10..22f68e1 100644 --- a/ui/lib/providers/welcome_data.dart +++ b/ui/lib/providers/welcome_data.dart @@ -4,23 +4,39 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:ui/providers/APIs.dart'; import 'package:ui/providers/server_response.dart'; -final welcomePageDataProvider = FutureProvider.autoDispose((ref) async { +final tvWatchlistDataProvider = FutureProvider.autoDispose((ref) async { final dio = await APIs.getDio(); - var resp = await dio.get(APIs.watchlistUrl); + var resp = await dio.get(APIs.watchlistTvUrl); var sp = ServerResponse.fromJson(resp.data); - List favList = List.empty(growable: true); + List favList = List.empty(growable: true); for (var item in sp.data as List) { - var tv = TvSeries.fromJson(item); + var tv = MediaDetail.fromJson(item); favList.add(tv); } return favList; }); -var searchPageDataProvider = AsyncNotifierProvider.autoDispose - >(SearchPageData.new); +final movieWatchlistDataProvider = FutureProvider.autoDispose((ref) async { + final dio = await APIs.getDio(); + var resp = await dio.get(APIs.watchlistMovieUrl); + var sp = ServerResponse.fromJson(resp.data); + List favList = List.empty(growable: true); + for (var item in sp.data as List) { + var tv = MediaDetail.fromJson(item); + favList.add(tv); + } + return favList; +}); + +var searchPageDataProvider = + AsyncNotifierProvider.autoDispose>( + SearchPageData.new); + +var movieTorrentsDataProvider = AsyncNotifierProvider.autoDispose + .family, String>( + MovieTorrentResource.new); class SearchPageData extends AutoDisposeAsyncNotifier> { - List list = List.empty(growable: true); @override @@ -28,19 +44,32 @@ class SearchPageData extends AutoDisposeAsyncNotifier> { return list; } - Future submit2Watchlist(int tmdbId, int storageId, String resolution) async { + Future submit2Watchlist( + int tmdbId, int storageId, String resolution, String mediaType) async { final dio = await APIs.getDio(); - var resp = await dio - .post(APIs.watchlistUrl, data: { - "tmdb_id": tmdbId, - "storage_id": storageId, - "resolution": resolution - }); - var sp = ServerResponse.fromJson(resp.data); - if (sp.code != 0) { - throw sp.message; + if (mediaType == "tv") { + var resp = await dio.post(APIs.watchlistTvUrl, data: { + "tmdb_id": tmdbId, + "storage_id": storageId, + "resolution": resolution + }); + var sp = ServerResponse.fromJson(resp.data); + if (sp.code != 0) { + throw sp.message; + } + ref.invalidate(tvWatchlistDataProvider); + } else { + var resp = await dio.post(APIs.watchlistMovieUrl, data: { + "tmdb_id": tmdbId, + "storage_id": storageId, + "resolution": resolution + }); + var sp = ServerResponse.fromJson(resp.data); + if (sp.code != 0) { + throw sp.message; + } + ref.invalidate(movieWatchlistDataProvider); } - ref.invalidate(welcomePageDataProvider); } Future queryResults(String q) async { @@ -65,78 +94,149 @@ class SearchPageData extends AutoDisposeAsyncNotifier> { } } -class SearchResult { - String? originalName; - int? id; - String? name; - int? voteCount; - double? voteAverage; - String? posterPath; - String? firstAirDate; - double? popularity; - List? genreIds; - String? originalLanguage; - String? backdropPath; - String? overview; - List? originCountry; - - SearchResult( - {this.originalName, - this.id, - this.name, - this.voteCount, - this.voteAverage, - this.posterPath, - this.firstAirDate, - this.popularity, - this.genreIds, - this.originalLanguage, - this.backdropPath, - this.overview, - this.originCountry}); - - SearchResult.fromJson(Map json) { - originalName = json['original_name']; - id = json['id']; - name = json['name']; - voteCount = json['vote_count']; - voteAverage = json['vote_average']; - posterPath = json['poster_path']; - firstAirDate = json['first_air_date']; - popularity = json['popularity']; - genreIds = json['genre_ids'].cast(); - originalLanguage = json['original_language']; - backdropPath = json['backdrop_path']; - overview = json['overview']; - originCountry = json['origin_country'].cast(); - } -} - -class TvSeries { +class MediaDetail { int? id; int? tmdbId; + String? mediaType; String? name; String? originalName; String? overview; - String? path; String? posterPath; + String? createdAt; + String? resolution; + int? storageId; + String? airDate; - TvSeries( - {this.id, - this.tmdbId, - this.name, - this.originalName, - this.overview, - this.path, - this.posterPath}); + MediaDetail({ + this.id, + this.tmdbId, + this.mediaType, + this.name, + this.originalName, + this.overview, + this.posterPath, + this.createdAt, + this.resolution, + this.storageId, + this.airDate, + }); - TvSeries.fromJson(Map json) { + MediaDetail.fromJson(Map json) { id = json['id']; tmdbId = json['tmdb_id']; + mediaType = json["media_type"]; name = json['name_cn']; originalName = json['original_name']; overview = json['overview']; - path = json['path']; - posterPath = json["poster_path"]; + posterPath = json['poster_path']; + createdAt = json['created_at']; + resolution = json["resolution"]; + storageId = json["storage_id"]; + airDate = json["air_date"]; + } +} + +class SearchResult { + SearchResult({ + required this.backdropPath, + required this.id, + required this.name, + required this.originalName, + required this.overview, + required this.posterPath, + required this.mediaType, + required this.adult, + required this.originalLanguage, + required this.genreIds, + required this.popularity, + required this.firstAirDate, + required this.voteAverage, + required this.voteCount, + required this.originCountry, + }); + + final String? backdropPath; + final int? id; + final String? name; + final String? originalName; + final String? overview; + final String? posterPath; + final String? mediaType; + final bool? adult; + final String? originalLanguage; + final List genreIds; + final double? popularity; + final DateTime? firstAirDate; + final double? voteAverage; + final int? voteCount; + final List originCountry; + + factory SearchResult.fromJson(Map json) { + return SearchResult( + backdropPath: json["backdrop_path"], + id: json["id"], + name: json["name"], + originalName: json["original_name"], + overview: json["overview"], + posterPath: json["poster_path"], + mediaType: json["media_type"], + adult: json["adult"], + originalLanguage: json["original_language"], + genreIds: json["genre_ids"] == null + ? [] + : List.from(json["genre_ids"]!.map((x) => x)), + popularity: json["popularity"], + firstAirDate: DateTime.tryParse(json["first_air_date"] ?? ""), + voteAverage: json["vote_average"], + voteCount: json["vote_count"], + originCountry: json["origin_country"] == null + ? [] + : List.from(json["origin_country"]!.map((x) => x)), + ); + } +} + +class MovieTorrentResource + extends AutoDisposeFamilyAsyncNotifier, String> { + String? mediaId; + @override + FutureOr> build(String id) async { + mediaId = id; + final dio = await APIs.getDio(); + var resp = await dio.get(APIs.availableMoviesUrl + id); + var rsp = ServerResponse.fromJson(resp.data); + if (rsp.code != 0) { + throw rsp.message; + } + return (resp.data as List).map((v) => TorrentResource.fromJson(v)).toList(); + } + + Future download(String link) async { + final dio = await APIs.getDio(); + var resp = await dio.post(APIs.availableMoviesUrl, + data: {"media_id": int.parse(mediaId!), "link": link}); + var rsp = ServerResponse.fromJson(resp.data); + if (rsp.code != 0) { + throw rsp.message; + } + } +} + +class TorrentResource { + TorrentResource({this.name, this.size, this.seeders, this.peers, this.link}); + + String? name; + int? size; + int? seeders; + int? peers; + String? link; + + factory TorrentResource.fromJson(Map json) { + return TorrentResource( + name: json["name"], + size: json["size"], + seeders: json["seeders"], + peers: json["peers"], + link: json["link"]); } } diff --git a/ui/lib/search.dart b/ui/lib/search.dart index 8adf9d8..af4234a 100644 --- a/ui/lib/search.dart +++ b/ui/lib/search.dart @@ -54,7 +54,7 @@ class _SearchPageState extends ConsumerState { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - "${item.name} (${item.firstAirDate?.split("-")[0]})", + "${item.name} (${item.firstAirDate?.year})", style: const TextStyle( fontSize: 14, fontWeight: FontWeight.bold), ), @@ -174,7 +174,7 @@ class _SearchPageState extends ConsumerState { ref .read(searchPageDataProvider.notifier) .submit2Watchlist( - item.id!, _storageSelected, _resSelected); + item.id!, _storageSelected, _resSelected, item.mediaType!); Navigator.of(context).pop(); }, ), diff --git a/ui/lib/tv_details.dart b/ui/lib/tv_details.dart index 626d140..0ca0e70 100644 --- a/ui/lib/tv_details.dart +++ b/ui/lib/tv_details.dart @@ -5,7 +5,7 @@ import 'package:ui/providers/APIs.dart'; import 'package:ui/providers/series_details.dart'; import 'package:ui/providers/settings.dart'; import 'package:ui/utils.dart'; -import 'package:ui/weclome.dart'; +import 'package:ui/tv_watchlist.dart'; import 'package:ui/widgets/progress_indicator.dart'; class TvDetailsPage extends ConsumerStatefulWidget { @@ -38,7 +38,7 @@ class _TvDetailsPageState extends ConsumerState { @override Widget build(BuildContext context) { - var seriesDetails = ref.watch(seriesDetailsProvider(seriesId)); + var seriesDetails = ref.watch(mediaDetailsProvider(seriesId)); var storage = ref.watch(storageSettingProvider); return FutureBuilder( // We listen to the pending operation, to update the UI accordingly. @@ -70,7 +70,7 @@ class _TvDetailsPageState extends ConsumerState { onPressed: () async { var f = ref .read( - seriesDetailsProvider(seriesId).notifier) + mediaDetailsProvider(seriesId).notifier) .searchAndDownload(seriesId, ep.seasonNumber!, ep.episodeNumber!); setState(() { @@ -189,11 +189,11 @@ class _TvDetailsPageState extends ConsumerState { IconButton( onPressed: () { ref - .read(seriesDetailsProvider( + .read(mediaDetailsProvider( seriesId) .notifier) .delete(); - context.go(WelcomePage.route); + context.go(TvWatchlistPage.route); }, icon: const Icon(Icons.delete)) ], diff --git a/ui/lib/weclome.dart b/ui/lib/tv_watchlist.dart similarity index 92% rename from ui/lib/weclome.dart rename to ui/lib/tv_watchlist.dart index b12277f..3b455d3 100644 --- a/ui/lib/weclome.dart +++ b/ui/lib/tv_watchlist.dart @@ -6,14 +6,16 @@ import 'package:ui/providers/welcome_data.dart'; import 'package:ui/tv_details.dart'; import 'package:ui/widgets/progress_indicator.dart'; -class WelcomePage extends ConsumerWidget { +class TvWatchlistPage + extends ConsumerWidget { static const route = "/series"; - const WelcomePage({super.key}); + const TvWatchlistPage + ({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { - final data = ref.watch(welcomePageDataProvider); + final data = ref.watch(tvWatchlistDataProvider); return switch (data) { AsyncData(:final value) => GridView.builder( diff --git a/ui/lib/utils.dart b/ui/lib/utils.dart index 33e1b19..3de65f6 100644 --- a/ui/lib/utils.dart +++ b/ui/lib/utils.dart @@ -1,4 +1,7 @@ +import 'dart:math'; + import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; class Utils { static Future showAlertDialog(BuildContext context, String msg) async { @@ -42,3 +45,14 @@ class Utils { return false; } } + + +extension FileFormatter on num { + String readableFileSize({bool base1024 = true}) { + final base = base1024 ? 1024 : 1000; + if (this <= 0) return "0"; + final units = ["B", "kB", "MB", "GB", "TB"]; + int digitGroups = (log(this) / log(base)).round(); + return "${NumberFormat("#,##0.#").format(this / pow(base, digitGroups))} ${units[digitGroups]}"; + } +} diff --git a/ui/pubspec.lock b/ui/pubspec.lock index e0cec14..cfb85ff 100644 --- a/ui/pubspec.lock +++ b/ui/pubspec.lock @@ -168,6 +168,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "4.0.2" + intl: + dependency: "direct main" + description: + name: intl + sha256: d6f56758b7d3014a48af9701c085700aac781a92a87a62b1333b46d8879661cf + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.19.0" intl_phone_number_input: dependency: transitive description: diff --git a/ui/pubspec.yaml b/ui/pubspec.yaml index 1ea8790..dfa184d 100644 --- a/ui/pubspec.yaml +++ b/ui/pubspec.yaml @@ -42,6 +42,7 @@ dependencies: flutter_login: ^5.0.0 shared_preferences: ^2.2.3 percent_indicator: ^4.2.3 + intl: ^0.19.0 dev_dependencies: flutter_test: