-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPlugin.php
More file actions
874 lines (727 loc) · 31.2 KB
/
Plugin.php
File metadata and controls
874 lines (727 loc) · 31.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
<?php
namespace AppLocalPlugins\TvLogos;
use App\Models\Channel;
use App\Plugins\Contracts\ChannelProcessorPluginInterface;
use App\Plugins\Contracts\HookablePluginInterface;
use App\Plugins\Contracts\PluginInterface;
use App\Plugins\Support\PluginActionResult;
use App\Plugins\Support\PluginExecutionContext;
use Carbon\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Throwable;
class Plugin implements ChannelProcessorPluginInterface, HookablePluginInterface, PluginInterface
{
private const DEFAULT_GITHUB_REPO = 'tv-logo/tv-logos';
private const CACHE_FILE = 'plugin-data/tv-logos/matches.json';
private const LOG_BATCH_SIZE = 100;
private string $cdnBase;
private string $indexApiBase;
/**
* Maps ISO 3166-1 alpha-2 country codes to their folder names in the tv-logo/tv-logos repo.
*
* @var array<string, string>
*/
private const COUNTRY_FOLDERS = [
'al' => 'albania',
'dz' => 'algeria',
'ar' => 'argentina',
'au' => 'australia',
'at' => 'austria',
'be' => 'belgium',
'ba' => 'bosnia-and-herzegovina',
'br' => 'brazil',
'bg' => 'bulgaria',
'ca' => 'canada',
'cn' => 'china',
'hr' => 'croatia',
'cz' => 'czech-republic',
'dk' => 'denmark',
'eg' => 'egypt',
'ee' => 'estonia',
'fi' => 'finland',
'fr' => 'france',
'de' => 'germany',
'gr' => 'greece',
'hu' => 'hungary',
'in' => 'india',
'ie' => 'ireland',
'is' => 'iceland',
'il' => 'israel',
'it' => 'italy',
'jp' => 'japan',
'xk' => 'kosovo',
'lv' => 'latvia',
'lt' => 'lithuania',
'lu' => 'luxembourg',
'mk' => 'north-macedonia',
'me' => 'montenegro',
'mx' => 'mexico',
'nl' => 'netherlands',
'nz' => 'new-zealand',
'ng' => 'nigeria',
'no' => 'norway',
'pl' => 'poland',
'pt' => 'portugal',
'ro' => 'romania',
'ru' => 'russia',
'sa' => 'saudi-arabia',
'rs' => 'serbia',
'sk' => 'slovakia',
'si' => 'slovenia',
'za' => 'south-africa',
'kr' => 'south-korea',
'es' => 'spain',
'se' => 'sweden',
'ch' => 'switzerland',
'tr' => 'turkey',
'ua' => 'ukraine',
'ae' => 'united-arab-emirates',
'gb' => 'united-kingdom',
'us' => 'united-states',
];
public function runAction(string $action, array $payload, PluginExecutionContext $context): PluginActionResult
{
return match ($action) {
'health_check' => $this->healthCheck($context),
'enrich_logos' => $this->enrichFromAction($payload, $context),
default => PluginActionResult::failure("Unsupported action [{$action}]."),
};
}
public function runHook(string $hook, array $payload, PluginExecutionContext $context): PluginActionResult
{
if ($hook !== 'playlist.synced') {
return PluginActionResult::success("Hook [{$hook}] not handled by TV Logos.");
}
$playlistId = (int) ($payload['playlist_id'] ?? 0);
if ($playlistId === 0) {
return PluginActionResult::failure('Missing playlist_id in hook payload.');
}
$configured = $context->settings['default_playlist_id'] ?? null;
$watchedIds = array_map('intval', array_filter((array) $configured));
if ($watchedIds === []) {
return PluginActionResult::success('No default playlist(s) configured — skipping automatic enrichment.');
}
if (! in_array($playlistId, $watchedIds, true)) {
return PluginActionResult::success("Playlist #{$playlistId} is not in the configured defaults — skipping.");
}
return $this->processPlaylist($playlistId, $context);
}
/**
* Ping the CDN and report cache stats.
*/
private function healthCheck(PluginExecutionContext $context): PluginActionResult
{
$context->info('Checking tv-logos CDN reachability...');
$reachable = false;
try {
$response = Http::timeout(10)->head('https://cdn.jsdelivr.net/gh/'.self::DEFAULT_GITHUB_REPO.'@main/countries/united-states/espn-us.png');
$reachable = $response->successful();
} catch (Throwable) {
// CDN unreachable
}
$cacheEntries = 0;
try {
$cache = $this->loadCache(0);
$cacheEntries = count($cache['matches'] ?? []);
} catch (Throwable) {
// Cache unreadable
}
return PluginActionResult::success('Health check complete.', [
'cdn_reachable' => $reachable,
'cdn_base' => 'https://cdn.jsdelivr.net/gh/'.self::DEFAULT_GITHUB_REPO.'@main/countries',
'cached_entries' => $cacheEntries,
'supported_countries' => array_keys(self::COUNTRY_FOLDERS),
]);
}
/**
* Entry point for the manual enrich_logos action.
*
* Accepts optional overrides for overwrite_existing, skip_vod, and
* ignore_cache so the user can control these per run without changing
* the global plugin settings.
*/
private function enrichFromAction(array $payload, PluginExecutionContext $context): PluginActionResult
{
$playlistId = (int) ($payload['playlist_id'] ?? 0);
if ($playlistId === 0) {
return PluginActionResult::failure('Missing playlist_id in action payload.');
}
$overrides = [];
if (array_key_exists('overwrite_existing', $payload)) {
$overrides['overwrite_existing'] = (bool) $payload['overwrite_existing'];
}
if (array_key_exists('skip_vod', $payload)) {
$overrides['skip_vod'] = (bool) $payload['skip_vod'];
}
if (array_key_exists('ignore_cache', $payload)) {
$overrides['ignore_cache'] = (bool) $payload['ignore_cache'];
}
return $this->processPlaylist($playlistId, $context, $overrides);
}
/**
* Core enrichment logic — queries channels for the given playlist and attempts
* to match each one against a logo from the tv-logo/tv-logos CDN.
*
* @param array{overwrite_existing?: bool, skip_vod?: bool, ignore_cache?: bool} $overrides
*/
private function processPlaylist(int $playlistId, PluginExecutionContext $context, array $overrides = []): PluginActionResult
{
$settings = $context->settings;
$countryCode = strtolower(trim((string) ($settings['country_code'] ?? 'us')));
$overwriteExisting = (bool) ($overrides['overwrite_existing'] ?? $settings['overwrite_existing'] ?? false);
$skipVod = (bool) ($overrides['skip_vod'] ?? $settings['skip_vod'] ?? true);
$ignoreCache = (bool) ($overrides['ignore_cache'] ?? false);
$cacheTtlDays = (int) ($settings['cache_ttl_days'] ?? 7);
$isDryRun = $context->dryRun;
$normConfig = $this->buildNormalizationConfig($settings);
$repo = trim((string) ($settings['github_repo'] ?? self::DEFAULT_GITHUB_REPO));
if ($repo === '') {
$repo = self::DEFAULT_GITHUB_REPO;
}
$this->cdnBase = "https://cdn.jsdelivr.net/gh/{$repo}@main/countries";
$this->indexApiBase = "https://api.github.com/repos/{$repo}/contents/countries";
$countryFolder = self::COUNTRY_FOLDERS[$countryCode] ?? null;
if ($countryFolder === null) {
return PluginActionResult::failure(sprintf(
'Unknown country code [%s]. Supported codes: %s.',
$countryCode,
implode(', ', array_keys(self::COUNTRY_FOLDERS))
));
}
$cache = $this->loadCache($cacheTtlDays);
$cacheChanged = false;
$index = $this->fetchCountryIndex($countryCode, $countryFolder, $cache, $cacheChanged, $ignoreCache);
if ($index !== []) {
$context->info(sprintf('Loaded index of %d known logos for %s.', count($index), $countryFolder));
} else {
$context->info('Logo index unavailable — falling back to per-channel CDN HEAD checks (slower).');
}
$byBasename = $this->buildBasenameIndex($index);
$query = Channel::query()
->where('playlist_id', $playlistId)
->where('enabled', true)
->select(['id', 'title', 'title_custom', 'name', 'name_custom', 'logo']);
if ($skipVod) {
$query->where('is_vod', false);
}
if (! $overwriteExisting) {
$query->where(function ($q): void {
$q->whereNull('logo')->orWhere('logo', '');
});
}
$channels = $query->get();
$total = $channels->count();
if ($total === 0) {
return PluginActionResult::success('No channels require logo enrichment.', [
'matched' => 0,
'skipped' => 0,
'total' => 0,
]);
}
$context->info(sprintf(
'Processing %d channel(s) for playlist #%d [country=%s%s].',
$total,
$playlistId,
$countryCode,
$isDryRun ? ', dry_run' : ''
));
$matched = 0;
$unmatched = 0;
$cacheHits = 0;
$cacheMisses = 0;
$processed = 0;
$batchMatched = [];
$batchUnmatched = [];
$batchStart = 1;
foreach ($channels as $channel) {
$displayName = trim((string) ($channel->title_custom ?? $channel->title ?? $channel->name_custom ?? $channel->name ?? ''));
if ($displayName === '') {
continue;
}
$processed++;
$normalizedName = $this->normalizeChannelName($displayName, $normConfig);
$cacheKey = $countryCode.':'.mb_strtolower($normalizedName, 'UTF-8');
if (! $ignoreCache && array_key_exists($cacheKey, $cache['matches'])) {
$logoUrl = $cache['matches'][$cacheKey] ?: null;
$cacheHits++;
} else {
$logoUrl = $this->resolveLogoUrl($normalizedName, $countryCode, $countryFolder, $index, $byBasename);
$cache['matches'][$cacheKey] = $logoUrl ?? '';
$cacheChanged = true;
$cacheMisses++;
}
if ($logoUrl !== null) {
$matched++;
$batchMatched[$displayName] = $logoUrl;
if (! $isDryRun && ($channel->logo ?? '') !== $logoUrl) {
Channel::where('id', $channel->id)->update(['logo' => $logoUrl]);
}
} else {
$unmatched++;
$batchUnmatched[] = $displayName;
}
if ($processed % self::LOG_BATCH_SIZE === 0) {
$context->info(
sprintf('Channels %d–%d: %d matched, %d unmatched.', $batchStart, $processed, \count($batchMatched), \count($batchUnmatched)),
['matched' => $batchMatched, 'unmatched' => $batchUnmatched],
);
$batchMatched = [];
$batchUnmatched = [];
$batchStart = $processed + 1;
$context->heartbeat(progress: (int) (($processed / $total) * 100));
}
}
// Flush the final partial batch.
if ($batchMatched !== [] || $batchUnmatched !== []) {
$context->info(
sprintf('Channels %d–%d: %d matched, %d unmatched.', $batchStart, $processed, \count($batchMatched), \count($batchUnmatched)),
['matched' => $batchMatched, 'unmatched' => $batchUnmatched],
);
}
if ($cacheChanged && ! $isDryRun) {
$this->saveCache($cache);
}
$resultData = [
'matched' => $matched,
'unmatched' => $unmatched,
'total' => $total,
'cache_hits' => $cacheHits,
'cache_misses' => $cacheMisses,
'country_code' => $countryCode,
'dry_run' => $isDryRun,
'ignore_cache' => $ignoreCache,
];
return PluginActionResult::success(
sprintf('%d of %d channel(s) matched%s.', $matched, $total, $isDryRun ? ' (dry run — no changes written)' : ''),
$resultData
);
}
/**
* Attempt to resolve a CDN logo URL for the given channel name.
*
* When an index is available, performs a comprehensive filename-based search
* across ALL subfolders (hd/, sky-sport/hd/, custom/, etc.), preferring
* HD subfolders for HD-hinted channels.
* Falls back to sequential CDN HEAD checks only when the index is unavailable.
*
* @param array<string, true> $index Filename → true map; empty array triggers HEAD fallback.
* @param array<string, list<string>> $byBasename Pre-built basename lookup (built once per run).
*/
private function resolveLogoUrl(string $channelName, string $countryCode, string $countryFolder, array $index, array $byBasename): ?string
{
$slugs = array_values(array_unique(array_filter([
$this->slugify($channelName, false),
$this->slugify($channelName, true),
])));
if ($slugs === []) {
return null;
}
$filenames = $this->buildFilenamesForSlugs($slugs, $countryCode);
// When an index is available, search all subfolders by basename for best match.
if ($index !== []) {
$result = $this->resolveFromIndex($filenames, $channelName, $countryFolder, $byBasename);
if ($result !== null) {
return $result;
}
return $this->compactIndexMatch($slugs, $countryCode, $countryFolder, $channelName, $index);
}
// HEAD fallback when index is unavailable.
foreach ($this->preferredQualityFolders($channelName) as $folder) {
foreach ($filenames as $filename) {
$relativePath = $folder === '' ? $filename : "{$folder}/{$filename}";
$url = $this->cdnBase."/{$countryFolder}/{$relativePath}";
if ($this->urlExists($url)) {
return $url;
}
}
}
return null;
}
/**
* Build a basename → [relativePaths…] lookup from the index.
*
* Called once per run so that resolveFromIndex() can search by filename
* without iterating the full index on every channel.
*
* @param array<string, true> $index
* @return array<string, list<string>>
*/
private function buildBasenameIndex(array $index): array
{
$byBasename = [];
foreach ($index as $relativePath => $_) {
$bn = strtolower(basename($relativePath));
$byBasename[$bn][] = $relativePath;
}
return $byBasename;
}
/**
* Resolve a logo URL by searching the pre-fetched index across ALL subfolders.
*
* Uses a pre-built basename lookup so that files in nested subfolders like
* sky-sport/hd/ or custom/hd/ are found regardless of folder structure.
* When multiple paths match the same filename, prefers HD subfolders for
* HD-hinted channels.
*
* @param array<int, string> $filenames
* @param array<string, list<string>> $byBasename Pre-built basename → paths map.
*/
private function resolveFromIndex(array $filenames, string $channelName, string $countryFolder, array $byBasename): ?string
{
$hdPreferred = (bool) preg_match('/\b(hd|fhd|uhd|4k|8k|1080[pi]|720p)\b/iu', $channelName);
foreach ($filenames as $filename) {
$lowFilename = strtolower($filename);
if (! isset($byBasename[$lowFilename])) {
continue;
}
$paths = $byBasename[$lowFilename];
// Single match — return immediately.
if (count($paths) === 1) {
return $this->cdnBase."/{$countryFolder}/{$paths[0]}";
}
// Multiple matches — pick the best based on quality preference.
$hdMatch = null;
$rootMatch = null;
foreach ($paths as $path) {
$inHd = str_contains($path, '/hd/') || str_starts_with($path, 'hd/');
if ($inHd) {
$hdMatch ??= $path;
} elseif (! str_contains($path, '/')) {
$rootMatch ??= $path;
}
}
if ($hdPreferred && $hdMatch !== null) {
return $this->cdnBase."/{$countryFolder}/{$hdMatch}";
}
if ($rootMatch !== null) {
return $this->cdnBase."/{$countryFolder}/{$rootMatch}";
}
return $this->cdnBase."/{$countryFolder}/{$paths[0]}";
}
return null;
}
/**
* Build the ordered list of candidate filenames to probe for the given slugs.
*
* @param array<int, string> $slugs
* @return array<int, string>
*/
private function buildFilenamesForSlugs(array $slugs, string $countryCode): array
{
$filenames = [];
foreach ($slugs as $slug) {
$filenames[] = "{$slug}-{$countryCode}.png";
$filenames[] = "{$slug}.png";
$parts = explode('-', $slug);
$lastPart = end($parts);
$qualitySuffixes = ['hd', 'fhd', 'uhd', 'sd', '4k', '8k'];
if (count($parts) > 1 && ! ctype_digit($lastPart) && ! in_array($lastPart, $qualitySuffixes, true)) {
$shortened = implode('-', array_slice($parts, 0, -1));
if ($shortened !== '') {
$filenames[] = "{$shortened}-{$countryCode}.png";
}
}
}
return array_values(array_unique($filenames));
}
/**
* @return array<int, string>
*/
private function preferredQualityFolders(string $channelName): array
{
$hasHdHint = (bool) preg_match('/\b(hd|fhd|uhd|4k|8k|1080[pi]|720p)\b/iu', $channelName);
return $hasHdHint ? ['hd', ''] : ['', 'hd'];
}
/**
* Compact matching fallback — strips all hyphens from both the channel slug
* and index filenames so minor hyphenation differences still match
* (e.g. "sport1" vs "sport-1-de.png").
*
* @param array<int, string> $slugs
* @param array<string, true> $index
*/
private function compactIndexMatch(array $slugs, string $countryCode, string $countryFolder, string $channelName, array $index): ?string
{
$suffixes = ["-{$countryCode}.png", '.png'];
$qualityFolders = $this->preferredQualityFolders($channelName);
$compactChannelSlugs = array_map(fn (string $s): string => str_replace('-', '', $s), $slugs);
foreach ($qualityFolders as $preferredFolder) {
foreach ($index as $relativePath => $_) {
$basename = basename($relativePath);
$suffixLen = 0;
foreach ($suffixes as $suffix) {
if (str_ends_with($basename, $suffix)) {
$suffixLen = strlen($suffix);
break;
}
}
if ($suffixLen === 0) {
continue;
}
$folder = dirname($relativePath);
$folder = $folder === '.' ? '' : $folder;
$isHdPath = $folder === 'hd' || str_ends_with($folder, '/hd');
$wantsHd = $preferredFolder === 'hd';
if ($wantsHd !== $isHdPath) {
continue;
}
$indexSlug = str_replace('-', '', substr($basename, 0, -$suffixLen));
foreach ($compactChannelSlugs as $compact) {
if ($indexSlug === $compact) {
return $this->cdnBase."/{$countryFolder}/{$relativePath}";
}
}
}
}
return null;
}
/**
* Fetch the set of known logo filenames for a country folder from the
* GitHub Contents API and store it in the cache.
*
* Returns a map of lowercase relative path → true for O(1) lookups.
* Returns an empty array on failure so callers can fall back to HEAD checks.
*
* @param array<string, mixed> $cache
* @return array<string, true>
*/
private function fetchCountryIndex(string $countryCode, string $countryFolder, array &$cache, bool &$cacheChanged, bool $ignoreCache = false): array
{
$cacheKey = "index:{$countryCode}";
if (! $ignoreCache && array_key_exists($cacheKey, $cache) && is_array($cache[$cacheKey])) {
return $cache[$cacheKey];
}
$index = $this->collectPngIndexEntries($countryFolder);
if ($index !== []) {
$cache[$cacheKey] = $index;
$cacheChanged = true;
}
return $index;
}
/**
* Recursively collect PNG logo files from a country folder and its subfolders.
*
* @return array<string, true>
*/
private function collectPngIndexEntries(string $path, string $prefix = ''): array
{
try {
$response = Http::timeout(15)
->withHeaders([
'Accept' => 'application/vnd.github.v3+json',
'User-Agent' => 'tv-logos-plugin/1.0',
])
->get($this->indexApiBase.'/'.$path);
if (! $response->successful()) {
return [];
}
$entries = [];
foreach ((array) ($response->json() ?? []) as $item) {
if (! is_array($item)) {
continue;
}
$type = (string) ($item['type'] ?? '');
$name = (string) ($item['name'] ?? '');
if ($type === 'file' && str_ends_with($name, '.png')) {
$entries[strtolower($prefix.$name)] = true;
continue;
}
if ($type === 'dir' && $name !== '') {
$childPath = trim($path.'/'.$name, '/');
$childPrefix = $prefix.$name.'/';
$entries = [...$entries, ...$this->collectPngIndexEntries($childPath, $childPrefix)];
}
}
return $entries;
} catch (Throwable) {
return [];
}
}
private function urlExists(string $url): bool
{
try {
return Http::timeout(8)->head($url)->successful();
} catch (Throwable) {
return false;
}
}
/**
* Normalise a channel name into a hyphenated slug suitable for tv-logo filenames.
*
* Steps: lowercase → strip quality tags and bracket content → normalise & → strip
* non-alphanumeric → collapse whitespace → hyphenate.
*/
private function slugify(string $name, bool $stripQualityTags = true): string
{
// Split camelCase / PascalCase boundaries BEFORE lowercasing
// e.g. "ProSieben" → "Pro Sieben", "SportDeutschland" → "Sport Deutschland"
$name = preg_replace('/(?<=[a-z])(?=[A-Z])/', ' ', $name) ?? $name;
$name = mb_strtolower($name, 'UTF-8');
if ($stripQualityTags) {
// Strip quality suffixes and optional trailing modifiers (raw, low, high)
// e.g. "HDraw" → "", "FHD Low" → "", "HEVC" → ""
$name = preg_replace('/\b(hd|fhd|uhd|4k|8k|sd|1080[pi]|720p|hevc|h\.?264|h\.?265)\s*(raw|low|high)?\b/iu', '', $name) ?? $name;
}
// Strip common IPTV transport / source terms (always, regardless of quality tag stripping)
// Use negative lookahead so "sat" inside "SAT.1" is not stripped (sat followed by dot+digit).
$name = preg_replace('/\b(cable|sat(?:ellite)?(?![.\s]*\d)|terrestrial|dvb[tcsh]?|iptv|ott|fta|stream|linear)\b/iu', '', $name) ?? $name;
// Remove content inside any bracket type
$name = preg_replace('/[\(\[\{][^\)\]\}]*[\)\]\}]/', '', $name) ?? $name;
// Normalise ampersand early (before stripping non-alnum)
$name = str_replace('&', ' and ', $name);
// Treat dots as word separators (e.g. "SAT.1" → "SAT 1")
$name = str_replace('.', ' ', $name);
// Convert plus sign to word "plus" (e.g. "ANIXE+" → "ANIXE plus")
$name = str_replace('+', ' plus ', $name);
// Keep only unicode letters, digits, and spaces
$name = preg_replace('/[^\p{L}\p{N}\s]/u', '', $name) ?? $name;
// Collapse whitespace
$name = preg_replace('/\s+/', ' ', trim($name)) ?? $name;
// Hyphenate and collapse consecutive hyphens
$name = str_replace(' ', '-', $name);
$name = preg_replace('/-+/', '-', $name) ?? $name;
return trim($name, '-');
}
/**
* Load the match cache from storage.
*
* Returns an empty cache structure when the file is missing, malformed, or expired.
*
* @return array{version: int, cached_at: string, matches: array<string, string>}
*/
private function loadCache(int $cacheTtlDays): array
{
$empty = ['version' => 4, 'cached_at' => now()->toIso8601String(), 'matches' => []];
try {
if (! Storage::disk('local')->exists(self::CACHE_FILE)) {
return $empty;
}
$data = json_decode((string) Storage::disk('local')->get(self::CACHE_FILE), true);
if (! is_array($data) || ! isset($data['matches']) || ($data['version'] ?? 1) < 4) {
return $empty;
}
if ($cacheTtlDays > 0 && isset($data['cached_at'])) {
if (Carbon::parse($data['cached_at'])->diffInDays(now()) >= $cacheTtlDays) {
return $empty;
}
}
return $data;
} catch (Throwable) {
return $empty;
}
}
/**
* Persist the match cache to storage.
*/
private function saveCache(array $cache): void
{
try {
Storage::disk('local')->put(
self::CACHE_FILE,
json_encode($cache, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
);
} catch (Throwable) {
// Non-fatal — a missing cache means the next run re-checks the CDN.
}
}
/**
* Build the normalization configuration array from plugin settings.
*
* @param array<string, mixed> $settings
* @return array{enabled: bool, strip_unicode: bool, strip_raw: bool, strip_provider_info: bool, provider_terms: list<string>, strip_quality_extras: bool, custom_patterns: list<string>}
*/
private function buildNormalizationConfig(array $settings): array
{
$enabled = (bool) ($settings['normalize_channel_names'] ?? false);
$providerTerms = [];
$rawProviderTerms = trim((string) ($settings['normalize_provider_terms'] ?? ''));
if ($rawProviderTerms !== '') {
foreach (explode("\n", $rawProviderTerms) as $line) {
$line = trim($line);
if ($line !== '') {
$providerTerms[] = $line;
}
}
}
$customPatterns = [];
$rawPatterns = trim((string) ($settings['normalize_custom_patterns'] ?? ''));
if ($rawPatterns !== '') {
foreach (explode("\n", $rawPatterns) as $line) {
$line = trim($line);
if ($line !== '' && @preg_match($line, '') !== false) {
$customPatterns[] = $line;
}
}
}
return [
'enabled' => $enabled,
'strip_unicode' => $enabled && (bool) ($settings['normalize_strip_unicode'] ?? true),
'strip_raw' => $enabled && (bool) ($settings['normalize_strip_raw'] ?? true),
'strip_provider_info' => $enabled && (bool) ($settings['normalize_strip_provider_info'] ?? true),
'provider_terms' => $providerTerms,
'strip_quality_extras' => $enabled && (bool) ($settings['normalize_strip_quality_extras'] ?? true),
'custom_patterns' => $customPatterns,
];
}
/**
* Normalize a channel display name before slug generation.
*
* Applies enabled normalization rules in a fixed order to produce
* a cleaner name that maps more reliably to logo filenames.
*/
private function normalizeChannelName(string $name, array $config): string
{
if (! $config['enabled']) {
return $name;
}
// 1. Unicode → ASCII transliteration (superscripts, subscripts, small-caps)
if ($config['strip_unicode']) {
$unicodeMap = [
// Superscripts
'⁰' => '0', '¹' => '1', '²' => '2', '³' => '3', '⁴' => '4',
'⁵' => '5', '⁶' => '6', '⁷' => '7', '⁸' => '8', '⁹' => '9',
'⁺' => '+', '⁻' => '-',
// Subscripts
'₀' => '0', '₁' => '1', '₂' => '2', '₃' => '3', '₄' => '4',
'₅' => '5', '₆' => '6', '₇' => '7', '₈' => '8', '₉' => '9',
// Small-caps Latin
'ᴀ' => 'A', 'ʙ' => 'B', 'ᴄ' => 'C', 'ᴅ' => 'D', 'ᴇ' => 'E',
'ꜰ' => 'F', 'ɢ' => 'G', 'ʜ' => 'H', 'ɪ' => 'I', 'ᴊ' => 'J',
'ᴋ' => 'K', 'ʟ' => 'L', 'ᴍ' => 'M', 'ɴ' => 'N', 'ᴏ' => 'O',
'ᴘ' => 'P', 'ꞯ' => 'Q', 'ʀ' => 'R', 'ꜱ' => 'S', 'ᴛ' => 'T',
'ᴜ' => 'U', 'ᴠ' => 'V', 'ᴡ' => 'W', 'ʏ' => 'Y', 'ᴢ' => 'Z',
];
$name = strtr($name, $unicodeMap);
}
// 2. Strip "raw" / "RAW" appended to quality tags (e.g. "HDraw" → "HD")
if ($config['strip_raw']) {
$name = (string) preg_replace('/\b(HD|FHD|UHD|SD)\s*raw\b/iu', '$1', $name);
}
// 3. Strip common IPTV transport / source terms that are never part of a channel name
// Use negative lookahead so "Sat" inside "SAT.1" is not stripped (Sat followed by dot/space+digit).
if ($config['strip_provider_info']) {
$name = (string) preg_replace('/\b(Cable|Sat(?:ellite)?(?![.\s]*\d)|Terrestrial|DVB[TCSH]?|IPTV|OTT|FTA|Stream|Linear)\b/iu', '', $name);
}
// 4. Strip user-configured provider terms (one term per line in settings)
if ($config['strip_provider_info'] && $config['provider_terms'] !== []) {
$escapedTerms = array_map(fn (string $t): string => preg_quote($t, '/'), $config['provider_terms']);
$name = (string) preg_replace('/\b('.implode('|', $escapedTerms).')\b/iu', '', $name);
}
// 5. Strip extra quality descriptors that follow a quality tag
if ($config['strip_quality_extras']) {
// "HD Low" → "HD", "HD High" → "HD"
$name = (string) preg_replace('/\b(HD|FHD|UHD|SD)\s*(Low|High)\b/iu', '$1', $name);
}
// 6. Apply user-defined custom regex patterns (each pattern replaces match with empty string)
foreach ($config['custom_patterns'] as $pattern) {
$result = @preg_replace($pattern, '', $name);
if ($result !== null) {
$name = $result;
}
}
// Final cleanup: collapse whitespace, trim
$name = trim((string) preg_replace('/\s{2,}/', ' ', $name));
return $name;
}
}