ReprocessMissingEpisodes   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 175
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 20
eloc 103
c 1
b 0
f 0
dl 0
loc 175
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
F handle() 0 146 19
1
<?php
2
3
namespace App\Console\Commands;
4
5
use App\Models\Category;
6
use App\Models\Release;
7
use App\Services\TvProcessing\TvProcessingPipeline;
8
use Illuminate\Console\Command;
9
use Illuminate\Support\Facades\Log;
10
11
/**
12
 * Reprocess TV releases that have a matched show (videos_id > 0) but no matched episode (tv_episodes_id = 0).
13
 * This can happen when the show was found but episodes weren't in the local database at the time.
14
 */
15
class ReprocessMissingEpisodes extends Command
16
{
17
    /**
18
     * The name and signature of the console command.
19
     *
20
     * @var string
21
     */
22
    protected $signature = 'tv:reprocess-missing-episodes
23
                            {--limit=0 : Limit the number of releases to process (0 = no limit)}
24
                            {--video-id= : Process only releases for a specific video ID}
25
                            {--dry-run : Show how many releases would be processed without making changes}
26
                            {--debug : Show detailed debug information for each release}
27
                            {--sleep=0 : Sleep time in milliseconds between processing each release}';
28
29
    /**
30
     * The console command description.
31
     *
32
     * @var string
33
     */
34
    protected $description = 'Reprocess TV releases with matched shows but missing episode matches (videos_id > 0, tv_episodes_id = 0)';
35
36
    public function __construct()
37
    {
38
        parent::__construct();
39
    }
40
41
    /**
42
     * Execute the console command.
43
     */
44
    public function handle(): int
45
    {
46
        $limit = (int) $this->option('limit');
47
        $videoId = $this->option('video-id');
48
        $dryRun = (bool) $this->option('dry-run');
49
        $debug = (bool) $this->option('debug');
50
        $sleep = (int) $this->option('sleep');
51
52
        // Build query for TV releases with matched show but no episode match
53
        $query = Release::query()
54
            ->select(['id', 'guid', 'searchname', 'videos_id', 'tv_episodes_id', 'categories_id', 'adddate', 'postdate'])
55
            ->where('videos_id', '>', 0)
56
            ->where('tv_episodes_id', 0)
57
            ->whereBetween('categories_id', [Category::TV_ROOT, Category::TV_OTHER])
58
            ->orderBy('adddate', 'desc')
0 ignored issues
show
Bug introduced by
'adddate' of type string is incompatible with the type Closure|Illuminate\Datab...\Database\Query\Builder expected by parameter $column of Illuminate\Database\Query\Builder::orderBy(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

58
            ->orderBy(/** @scrutinizer ignore-type */ 'adddate', 'desc')
Loading history...
59
            ->orderBy('postdate', 'desc');
60
61
        if ($videoId !== null) {
0 ignored issues
show
introduced by
The condition $videoId !== null is always true.
Loading history...
62
            $query->where('videos_id', (int) $videoId);
63
            $this->info("Filtering by video ID: {$videoId}");
64
        }
65
66
        $totalCount = (clone $query)->count();
67
68
        if ($totalCount === 0) {
69
            $this->info('No TV releases with missing episode matches found.');
70
            return self::SUCCESS;
71
        }
72
73
        $this->info("Found {$totalCount} TV release(s) with missing episode matches.");
74
75
        if ($limit > 0) {
76
            $query->limit($limit);
77
            $processCount = min($limit, $totalCount);
78
            $this->info("Processing limited to {$processCount} release(s).");
79
        } else {
80
            $processCount = $totalCount;
81
        }
82
83
        if ($dryRun) {
84
            $this->line("[Dry Run] Would process {$processCount} TV release(s) with missing episode matches.");
85
86
            // Show sample of releases that would be processed
87
            $sample = (clone $query)->limit(15)->get();
88
            if ($sample->isNotEmpty()) {
89
                $this->newLine();
90
                $this->info('Sample of releases to be processed:');
91
                $rows = $sample->map(fn ($release) => [
92
                    $release->id,
93
                    $release->videos_id,
94
                    mb_substr($release->searchname, 0, 55) . (strlen($release->searchname) > 55 ? '...' : ''),
95
                ])->toArray();
96
                $this->table(['ID', 'Video ID', 'Search Name'], $rows);
97
            }
98
99
            return self::SUCCESS;
100
        }
101
102
        $this->info("Starting to process {$processCount} TV release(s) with missing episode matches...");
103
        $this->newLine();
104
105
        $bar = $this->output->createProgressBar($processCount);
106
        $bar->setFormat(' %current%/%max% [%bar%] %percent:3s%% | Matched: %matched% | Failed: %failed% | Elapsed: %elapsed:6s%');
107
        $bar->setMessage('0', 'matched');
108
        $bar->setMessage('0', 'failed');
109
        $bar->start();
110
111
        $matched = 0;
112
        $failed = 0;
113
        $processed = 0;
114
115
        try {
116
            $pipeline = TvProcessingPipeline::createDefault(echoOutput: false);
117
118
            // Use cursor to iterate without chunking issues when ordering by non-id columns
119
            $cursor = $query->cursor();
120
121
            foreach ($cursor as $release) {
122
                if ($limit > 0 && $processed >= $limit) {
123
                    break;
124
                }
125
126
                try {
127
                    $result = $pipeline->processRelease($release, $debug);
128
129
                    // Check if episode was matched (episode_id > 0)
130
                    $episodeMatched = isset($result['episode_id']) && $result['episode_id'] > 0;
131
132
                    if ($episodeMatched) {
133
                        $matched++;
134
                        if ($debug) {
135
                            $this->newLine();
136
                            cli()->primary("Episode matched: {$release->searchname}");
137
                            $this->info('  Provider: ' . ($result['provider'] ?? 'Unknown'));
138
                            $this->info('  Video ID: ' . ($result['video_id'] ?? 'N/A'));
139
                            $this->info('  Episode ID: ' . ($result['episode_id'] ?? 'N/A'));
140
                        }
141
                    } else {
142
                        $failed++;
143
                        if ($debug) {
144
                            $this->newLine();
145
                            cli()->warning("Episode not found: {$release->searchname}");
146
                        }
147
                    }
148
                } catch (\Throwable $e) {
149
                    $failed++;
150
                    Log::error("Error processing release {$release->guid}: " . $e->getMessage());
151
                    if ($debug) {
152
                        $this->newLine();
153
                        $this->error("Error processing {$release->searchname}: " . $e->getMessage());
154
                    }
155
                }
156
157
                $processed++;
158
                $bar->setMessage((string) $matched, 'matched');
159
                $bar->setMessage((string) $failed, 'failed');
160
                $bar->advance();
161
162
                if ($sleep > 0) {
163
                    usleep($sleep * 1000);
164
                }
165
            }
166
167
        } catch (\Throwable $e) {
168
            $bar->finish();
169
            $this->newLine();
170
            $this->error('Fatal error during processing: ' . $e->getMessage());
171
            Log::error('Fatal error in tv:reprocess-missing-episodes: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
172
            return self::FAILURE;
173
        }
174
175
        $bar->finish();
176
        $this->newLine(2);
177
178
        $this->info('Processing complete!');
179
        $this->table(
180
            ['Total Processed', 'Episodes Matched', 'Not Matched', 'Match Rate'],
181
            [[
182
                number_format($processed),
183
                number_format($matched),
184
                number_format($failed),
185
                $processed > 0 ? round(($matched / $processed) * 100, 2) . '%' : '0%',
186
            ]]
187
        );
188
189
        return self::SUCCESS;
190
    }
191
}
192
193