1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Jackal\Downloader\Ext\Youtube\Filter; |
4
|
|
|
|
5
|
|
|
use Jackal\Downloader\Ext\Youtube\Exception\YoutubeDownloaderException; |
6
|
|
|
use Jackal\Downloader\Ext\Youtube\Validator\ValidatorInterface; |
7
|
|
|
|
8
|
|
|
class VideoResultFilter |
9
|
|
|
{ |
10
|
|
|
protected $allowNoAudio; |
11
|
|
|
|
12
|
|
|
public function __construct($allowNoAudio = false) |
13
|
|
|
{ |
14
|
|
|
$this->allowNoAudio = $allowNoAudio; |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
protected $validator; |
18
|
|
|
|
19
|
|
|
public function setValidator(ValidatorInterface $validator) |
20
|
|
|
{ |
21
|
|
|
$this->validator = $validator; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
protected function hasValidator() : bool |
25
|
|
|
{ |
26
|
|
|
return isset($this->validator); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
protected function getValidator() : ?ValidatorInterface |
30
|
|
|
{ |
31
|
|
|
return $this->validator; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function filter(array $videos, array $selectedFormats = []) : array |
35
|
|
|
{ |
36
|
|
|
$outVideos = []; |
37
|
|
|
sort($selectedFormats, SORT_NUMERIC); |
38
|
|
|
|
39
|
|
|
foreach ($videos as $video) { |
40
|
|
|
if (isset($video['format'])) { |
41
|
|
|
$formatFound = $this->checkContainsAudioAndVideoFormat($video['format']); |
42
|
|
|
if (isset($formatFound)) { |
43
|
|
|
if (array_key_exists($formatFound, $outVideos)) { |
44
|
|
|
continue; |
45
|
|
|
} |
46
|
|
|
if ($this->hasValidator()) { |
47
|
|
|
if ($this->getValidator()->isValid($video['url'])) { |
48
|
|
|
$outVideos[$formatFound] = $video['url']; |
49
|
|
|
} |
50
|
|
|
} else { |
51
|
|
|
$outVideos[$formatFound] = $video['url']; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
if($selectedFormats != []) { |
55
|
|
|
foreach ($selectedFormats as $selectedFormat) { |
56
|
|
|
if (array_key_exists($selectedFormat, $outVideos)) { |
57
|
|
|
return [$selectedFormat => $outVideos[$selectedFormat]]; |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
if ($outVideos == []) { |
66
|
|
|
throw YoutubeDownloaderException::videoURLsNotFound(); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
ksort($outVideos, SORT_NUMERIC); |
70
|
|
|
|
71
|
|
|
return $outVideos; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
public function checkContainsAudioAndVideoFormat($string) : ?string |
75
|
|
|
{ |
76
|
|
|
foreach (['audio', 'video'] as $elem) { |
77
|
|
|
if (strpos($string, $elem) === false) { |
78
|
|
|
if(!$this->allowNoAudio) { |
79
|
|
|
return null; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
preg_match('/([0-9]{2,4})p/', $string, $match); |
84
|
|
|
|
85
|
|
|
return $match[1] ?? null; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|