// Package service — RSS subscriptions for automated downloads. // // SubscriptionService periodically polls every Subscription row, fetches // the configured RSS / Atom feed, and queues new items into the // DownloadService. Items are deduplicated by GUID stored as a Setting key // "subscription..last_guid" so the same episode is never re-queued. package service import ( "context" "errors" "fmt" "strings" "time" "go.uber.org/zap" "gorm.io/gorm" "github.com/ShukeBta/MediaStationGo/internal/config" "github.com/ShukeBta/MediaStationGo/internal/model" "github.com/ShukeBta/MediaStationGo/internal/repository" ) // SubscriptionService runs the polling loop. type SubscriptionService struct { cfg *config.Config log *zap.Logger repo *repository.Container downloads *DownloadService site *SiteService scraper *ScraperService hub *Hub notify *NotifyChannelService stop chan struct{} } // NewSubscriptionService is the constructor. func NewSubscriptionService(cfg *config.Config, log *zap.Logger, repo *repository.Container, downloads *DownloadService, site *SiteService, hub *Hub) *SubscriptionService { return &SubscriptionService{ cfg: cfg, log: log, repo: repo, downloads: downloads, site: site, hub: hub, stop: make(chan struct{}), } } func (s *SubscriptionService) SetScraper(scraper *ScraperService) { s.scraper = scraper } func (s *SubscriptionService) SetNotifyChannels(notify *NotifyChannelService) { s.notify = notify } // Start runs the polling loop in the background. func (s *SubscriptionService) Start(ctx context.Context) { go s.loop(ctx) } // Stop shuts the loop down. func (s *SubscriptionService) Stop() { close(s.stop) } // Create persists a new subscription. func (s *SubscriptionService) Create(ctx context.Context, sub *model.Subscription) error { if sub.Name == "" || sub.FeedURL == "" { return errors.New("name and feed_url required") } normalizeSubscriptionDefaults(sub) enabled := sub.Enabled if err := s.repo.Subscription.Create(ctx, sub); err != nil { return err } if !enabled { if err := s.repo.DB.WithContext(ctx).Model(sub).Update("enabled", false).Error; err != nil { return err } sub.Enabled = false } return nil } func normalizeSubscriptionDefaults(sub *model.Subscription) { if strings.TrimSpace(sub.SearchMode) == "" { sub.SearchMode = "keyword" } if strings.TrimSpace(sub.Resolution) == "" { sub.Resolution = "best" } if strings.TrimSpace(sub.WashPriority) == "" { sub.WashPriority = "balanced" } if sub.Priority == 0 { sub.Priority = 50 } } // List returns every subscription rule. func (s *SubscriptionService) List(ctx context.Context) ([]model.Subscription, error) { return s.repo.Subscription.List(ctx) } // Delete removes a subscription. func (s *SubscriptionService) Delete(ctx context.Context, id string) error { var sub model.Subscription if err := s.repo.DB.WithContext(ctx).Where("id = ?", id).First(&sub).Error; err != nil { if !errors.Is(err, gorm.ErrRecordNotFound) { return err } return s.repo.DB.WithContext(ctx).Where("id = ?", id).Delete(&model.Subscription{}).Error } if err := s.deleteSubscriptionDownloads(ctx, &sub); err != nil { return err } if s.repo.Setting != nil { _ = s.repo.Setting.Delete(ctx, fmt.Sprintf("subscription.%s.seen", id)) } return s.repo.DB.Where("id = ?", id).Delete(&model.Subscription{}).Error } // RunNow forces a poll for one subscription, ignoring its schedule. Used // by the admin UI's "test now" button. func (s *SubscriptionService) RunNow(ctx context.Context, id string) (int, error) { var sub model.Subscription if err := s.repo.DB.Where("id = ?", id).First(&sub).Error; err != nil { return 0, err } if sub.ArchivedAt != nil { return 0, nil } return s.runOne(ctx, &sub) } // loop polls every 10 minutes. func (s *SubscriptionService) loop(ctx context.Context) { t := time.NewTicker(10 * time.Minute) defer t.Stop() // First run shortly after startup. first := time.NewTimer(30 * time.Second) defer first.Stop() for { select { case <-ctx.Done(): return case <-s.stop: return case <-first.C: case <-t.C: } s.runAll(ctx) } } func (s *SubscriptionService) runAll(ctx context.Context) { subs, err := s.repo.Subscription.List(ctx) if err != nil { s.log.Warn("subscription list failed", zap.Error(err)) return } for i := range subs { if !subs[i].Enabled { continue } if n, err := s.runOne(ctx, &subs[i]); err != nil { s.log.Warn("subscription run failed", zap.String("name", subs[i].Name), zap.Error(err)) } else if n > 0 { s.log.Info("subscription queued items", zap.String("name", subs[i].Name), zap.Int("count", n)) } } } func (s *SubscriptionService) runOne(ctx context.Context, sub *model.Subscription) (int, error) { if strings.HasPrefix(strings.ToLower(strings.TrimSpace(sub.FeedURL)), "site-search://") { return s.runSiteSearch(ctx, sub) } feed, err := s.fetch(ctx, sub.FeedURL) if err != nil { return 0, err } filter := compileFilter(sub.Filter) guidKey := fmt.Sprintf("subscription.%s.seen", sub.ID) seenRaw, _ := s.repo.Setting.Get(ctx, guidKey) seen := splitNonEmpty(seenRaw) seenSet := make(map[string]struct{}, len(seen)) for _, g := range seen { seenSet[g] = struct{}{} } washOff := !sub.WashEnabled s.updateSubscriptionTotalEpisodes(ctx, sub, s.resolveSubscriptionTotalEpisodes(ctx, sub, inferRSSTotalEpisodes(feed.Channel.Items, sub, filter))) availQuery := availabilityQuery(subscriptionName(sub), subscriptionFilter(sub)) // RSS 和站点搜索统一使用候选规划:先按订阅规则过滤,再按洗版优先级/集数去重择优。 // 非洗版订阅成功下载一次即满足,媒体库与下载中任务会作为可用性输入避免重复下载。 avail := mergeLocalAvailability( SubscriptionLocalAvailability(ctx, s.repo, sub), s.pendingDownloadAvailability(ctx, sub), ) candidates := selectRSSSubscriptionCandidates(feed.Channel.Items, sub, filter, seenSet, avail) queued := 0 for _, candidate := range candidates { item := candidate.Item guid := candidate.GUID download := candidate.Download mediaType, mediaCategory := s.classifySubscriptionItem(ctx, sub, item.Title, "") savePath := s.resolveSubscriptionSavePath(ctx, sub, mediaType, mediaCategory) if s.downloadPathHasCandidate(ctx, sub, item.Title, savePath) { if washOff { addAvailabilityTitle(item.Title, availQuery, &avail) } continue } if _, err := s.downloads.AddDownloadWithMeta(ctx, sub.UserID, download, savePath, DownloadTaskMeta{ SubscriptionID: sub.ID, Title: firstNonEmpty(item.Title, sub.Name), PosterURL: sub.PosterURL, BackdropURL: sub.BackdropURL, Overview: sub.Overview, MediaType: mediaType, MediaCategory: mediaCategory, AllowExistingLibrary: sub.WashEnabled, }); err != nil { if IsDownloadDedupError(err) { if washOff { addAvailabilityTitle(item.Title, availQuery, &avail) } seen = append(seen, guid) seenSet[guid] = struct{}{} continue } s.log.Warn("subscription enqueue failed", zap.String("title", item.Title), zap.String("media_type", mediaType), zap.String("media_category", mediaCategory), zap.String("save_path", savePath), zap.Error(err)) continue } if washOff { addAvailabilityTitle(item.Title, availQuery, &avail) } queued++ seen = append(seen, guid) seenSet[guid] = struct{}{} } avail = s.finalizePendingAvailability(sub, avail) // Remember the last 200 GUIDs so the seen set doesn't grow forever. if len(seen) > 200 { seen = seen[len(seen)-200:] } _ = s.repo.Setting.Set(ctx, guidKey, strings.Join(seen, "\n")) now := time.Now() _ = s.repo.DB.Model(sub).Updates(map[string]any{"last_run_at": &now}).Error _ = s.archiveCompletedSubscription(ctx, sub, avail) if queued > 0 { s.hub.Publish("subscription", map[string]any{ "id": sub.ID, "name": sub.Name, "queued": queued, }) s.notifySubscriptionHit(sub, queued, nil) } return queued, nil }