Passed
Push — master ( e46764...ffcf7d )
by Darko
11:11
created

ReprocessMissingEpisodes   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 178
Duplicated Lines 0 %

Importance

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

2 Methods

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

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