package service import ( "database/sql" "fmt" "os" "os/exec" "path/filepath" "strings" "time" "vidarchive/internal/config" "vidarchive/internal/models" "vidarchive/internal/repository" ) type DownloadService struct { repo *repository.DownloadRepository mediaRepo *repository.MediaRepository presetSvc *PresetService cfg *config.Config } func NewDownloadService(repo *repository.DownloadRepository, mediaRepo *repository.MediaRepository, presetSvc *PresetService, cfg *config.Config) *DownloadService { return &DownloadService{ repo: repo, mediaRepo: mediaRepo, presetSvc: presetSvc, cfg: cfg, } } func (s *DownloadService) Create(url string, presetID *int64, formatOverride, customFlags string) (*models.Download, error) { d := &models.Download{ URL: url, Status: "queued", FormatOverride: formatOverride, CustomFlags: customFlags, } if presetID != nil { d.PresetID = sqlNullInt64(*presetID) } if err := s.repo.Create(d); err != nil { return nil, err } return d, nil } func (s *DownloadService) GetByID(id int64) (*models.Download, error) { return s.repo.GetByID(id) } func (s *DownloadService) GetAll(status, sortBy string) ([]*models.Download, error) { return s.repo.GetAll(status, sortBy) } func (s *DownloadService) GetQueued(limit int) ([]*models.Download, error) { return s.repo.GetQueued(limit) } func (s *DownloadService) Delete(id int64) error { return s.repo.Delete(id) } func (s *DownloadService) ListFormats(url string) ([]*models.FormatInfo, error) { cmd := exec.Command(s.cfg.YTDLPPath, "-F", "--no-warnings", url) output, err := cmd.CombinedOutput() if err != nil { return nil, fmt.Errorf("yt-dlp -F failed: %w\nOutput: %s", err, string(output)) } return parseFormatList(string(output)), nil } func (s *DownloadService) ExecuteDownload(d *models.Download) error { if err := s.repo.MarkStarted(d.ID); err != nil { return err } var preset *models.Preset var err error if d.PresetID.Valid { preset, err = s.presetSvc.GetByID(d.PresetID.Int64) if err != nil { preset, _ = s.presetSvc.GetDefault() } } else { preset, _ = s.presetSvc.GetDefault() } if preset == nil { preset = &models.Preset{ OutputTemplate: "%(title)s [%(id)s].%(ext)s", } } args := s.presetSvc.BuildArgs(preset, d.FormatOverride, d.CustomFlags) args = append(args, "--newline", "--progress", "-P", s.cfg.DownloadDir) args = append(args, d.URL) cmd := exec.Command(s.cfg.YTDLPPath, args...) // Set up log capture var logBuilder strings.Builder // Start the command if err := cmd.Start(); err != nil { s.repo.MarkError(d.ID, err.Error()) return err } // TODO: In a real implementation, we'd parse stdout in real-time // For now, just wait and capture output output, err := cmd.CombinedOutput() logBuilder.Write(output) s.repo.UpdateLogs(d.ID, logBuilder.String()) if err != nil { s.repo.MarkError(d.ID, err.Error()) return err } // Mark as completed if err := s.repo.MarkCompleted(d.ID, "completed"); err != nil { return err } // Scan for new media files s.scanForNewMedia(d.URL) return nil } func (s *DownloadService) scanForNewMedia(url string) { // Simple scan - in production, parse yt-dlp output to know exactly what was downloaded time.Sleep(100 * time.Millisecond) // Give filesystem a moment // Walk download dir and add any new files filepath.Walk(s.cfg.DownloadDir, func(path string, info os.FileInfo, err error) error { if err != nil || info.IsDir() { return nil } relPath, _ := filepath.Rel(s.cfg.DownloadDir, path) relPath = filepath.ToSlash(relPath) _, err = s.mediaRepo.GetByRelativePath(relPath) if err == nil { return nil // already exists } ext := strings.ToLower(filepath.Ext(path)) isAudio := ext == ".mp3" || ext == ".m4a" || ext == ".ogg" || ext == ".wav" || ext == ".flac" || ext == ".aac" || ext == ".opus" isVideo := ext == ".mp4" || ext == ".webm" || ext == ".mkv" || ext == ".avi" || ext == ".mov" if !isAudio && !isVideo { return nil } basePath := strings.TrimSuffix(path, ext) infoJSONPath := basePath + ".info.json" if _, err := os.Stat(infoJSONPath); err != nil { infoJSONPath = "" } media := &models.Media{ URL: url, Filepath: path, RelativePath: relPath, IsAudio: isAudio, HasEmbeddedThumbnail: true, // yt-dlp usually embeds when requested InfoJSONPath: infoJSONPath, Title: strings.TrimSuffix(filepath.Base(path), ext), } s.mediaRepo.Create(media) return nil }) } func parseFormatList(output string) []*models.FormatInfo { // Simple parser for yt-dlp -F output // This is a basic implementation - yt-dlp format can vary lines := strings.Split(output, "\n") var formats []*models.FormatInfo inFormats := false for _, line := range lines { line = strings.TrimSpace(line) if line == "" { continue } // Look for the format table header if strings.Contains(line, "ID") && strings.Contains(line, "EXT") { inFormats = true continue } if !inFormats { continue } // Parse format line parts := strings.Fields(line) if len(parts) >= 4 { format := &models.FormatInfo{ ID: parts[0], Ext: parts[1], } // Try to extract resolution for i, part := range parts { if strings.Contains(part, "x") && !strings.Contains(part, "http") { format.Resolution = part if i+1 < len(parts) { format.FPS = parts[i+1] } break } } // Note is everything after resolution if len(parts) > 3 { format.Note = strings.Join(parts[3:], " ") } formats = append(formats, format) } } return formats } func sqlNullInt64(v int64) sql.NullInt64 { return sql.NullInt64{Int64: v, Valid: true} }