ytclass.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. <?php
  2. class YTDownloader {
  3. private $cache_dir;
  4. private $cookie_dir;
  5. private $itag_info = array(
  6. // Full Video
  7. 18 => "MP4[640x360]",
  8. 22 => "HD MP4[1280x720]",
  9. 36 => "3GP[320x180]",
  10. 43 => "WEBM[640x360]",
  11. 17 => "3GP[176x144]",
  12. // DASH videos
  13. 137 => "(Video Only) MP4[1920x1080]",
  14. 248 => "(Video Only) WEBM[1920x1080]",
  15. 136 => "(Video Only) MP4[1280x720]",
  16. 247 => "(Video Only) WEBM[1280x720]",
  17. 135 => "(Video Only) MP4[854x480]",
  18. 244 => "(Video Only) WEBM[854x480]",
  19. 134 => "(Video Only) MP4[640x360]",
  20. 243 => "(Video Only) WEBM[640x360]",
  21. 133 => "(Video Only) MP4[320x240]",
  22. 242 => "(Video Only) WEBM[320x240]",
  23. 160 => "(Video Only) MP4[176x144]",
  24. 278 => "(Video Only) WEBM[176x144]",
  25. // Dash Audios
  26. 140 => "(Audio Only) M4A[128Kbps]",
  27. 171 => "(Audio Only) WEBM[128Kbps]",
  28. 249 => "(Audio Only) WEBM[50Kbps]",
  29. 250 => "(Audio Only) WEBM[70Kbps]",
  30. 251 => "(Audio Only) WEBM[160Kbps]"
  31. );
  32. private $itag_ext = array(
  33. // Full Video
  34. 18 => ".mp4",
  35. 22 => ".mp4",
  36. 36 => ".3gp",
  37. 43 => ".webm",
  38. 17 => ".3gp",
  39. // DASH videos
  40. 137 => ".mp4",
  41. 248 => ".webm",
  42. 136 => ".mp4",
  43. 247 => ".webm",
  44. 135 => ".mp4",
  45. 244 => ".webm",
  46. 134 => ".mp4",
  47. 243 => ".webm",
  48. 133 => ".mp4",
  49. 242 => ".webm",
  50. 160 => ".mp4",
  51. 278 => ".webm",
  52. // Dash Audios
  53. 140 => ".mp4",
  54. 171 => ".webm",
  55. 249 => ".webm",
  56. 250 => ".webm",
  57. 251 => ".webm"
  58. );
  59. function __construct(){
  60. $this->cache_dir = dirname(__FILE__).'/.cache';
  61. $this->cookie_dir = sys_get_temp_dir();
  62. if(!file_exists($this->cache_dir)) {
  63. mkdir($this->cache_dir,0755);
  64. }
  65. }
  66. public function getDownloadLinks($id) {
  67. $returnData = FALSE;
  68. $videoID = $this->extractId($id);
  69. $webPage = $this->curlGet('https://www.youtube.com/watch?v='.$videoID);
  70. $sts = null;
  71. if(preg_match('|"sts":([0-9]{4,}),"|i', $webPage, $matches)) {
  72. $sts = $matches[1];
  73. }
  74. foreach(array('vevo', 'embedded', 'detailpage') as $elKey) {
  75. $query = http_build_query(array(
  76. 'c' => 'web',
  77. 'el' => $elKey,
  78. 'hl' => 'en_US',
  79. 'sts' => $sts,
  80. 'cver' => 'html5',
  81. 'eurl' => "https://youtube.googleapis.com/v/{$videoID}",
  82. 'html5' => '1',
  83. 'iframe' => '1',
  84. 'authuser' => '1',
  85. 'video_id' => $videoID,
  86. ));
  87. if($this->is_Ok($videoData = $this->curlGet("http://www.youtube.com/get_video_info?{$query}"))) {
  88. parse_str($videoData, $videoData);
  89. break;
  90. }
  91. }
  92. if(isset($videoData['status']) && $videoData['status'] !== 'fail') {
  93. $vInfo['Title'] = $videoData['title'];
  94. $vInfo['ChannelName'] = $videoData['author'];
  95. $vInfo['ChannelId'] = $videoData['ucid'];
  96. $vInfo['Thumbnail'] = str_replace('default', 'maxresdefault', $videoData['thumbnail_url']);
  97. $vInfo['Duration'] = $videoData['length_seconds'];
  98. $vInfo['Rating'] = $videoData['avg_rating'];
  99. }
  100. if (isset($videoData['url_encoded_fmt_stream_map']) && isset($videoData['adaptive_fmts'])) {
  101. $draft1 = explode(',',$videoData['url_encoded_fmt_stream_map']);
  102. $draft2 = explode(',',$videoData['adaptive_fmts']);
  103. foreach ($draft1 as $key) {
  104. $draftLink[] = $key;
  105. }
  106. foreach ($draft2 as $key) {
  107. $draftLink[] = $key;
  108. }
  109. foreach($draftLink as $dlink) {
  110. parse_str($dlink,$mLink[]);
  111. }
  112. if (isset($mLink[0]['s'])) {
  113. $instructions = $this->get_instructions($webPage);
  114. }
  115. foreach($mLink as $linker) {
  116. if(isset($linker['s'])) {
  117. $linkData[] = array(
  118. 'url' => preg_replace('@(https\:\/\/)[^\.]+(\.googlevideo\.com)@', 'https://redirector$2', $linker['url']).'&signature='.$this->sig_decipher($linker['s'], $instructions).'&title='.$this->clean_name($videoData['title']),
  119. 'itag' => $linker['itag'],
  120. 'type' => isset($this->itag_info[$linker['itag']]) ? $this->itag_info[$linker['itag']] : 'Unknown'
  121. );
  122. } else {
  123. $linkData[] = array(
  124. 'url' => preg_replace('@(https\:\/\/)[^\.]+(\.googlevideo\.com)@', 'https://redirector$2', $linker['url']).'&title='.$this->clean_name($videoData['title']),
  125. 'itag' => $linker['itag'],
  126. 'type' => isset($this->itag_info[$linker['itag']]) ? $this->itag_info[$linker['itag']] : 'Unknown'
  127. );
  128. }
  129. }
  130. }
  131. if (!empty($vInfo)) {
  132. $returnData['info'] = $vInfo;
  133. }if (!empty($linkData)) {
  134. $returnData['dl'] = $linkData;
  135. }
  136. return $returnData;
  137. }
  138. protected function curlGet($url) {
  139. if(in_array('curl', get_loaded_extensions())){
  140. $appSettings = parse_ini_file('../config/config.ini',true);
  141. $ch = curl_init($url);
  142. curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0');
  143. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  144. curl_setopt($ch, CURLOPT_HEADER, 0);
  145. //curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  146. if($appSettings["Proxy"]["type"]) {
  147. curl_setopt($ch, CURLOPT_PROXY, $appSettings["Proxy"]["type"]."://".$appSettings["Proxy"]["domain"].":".$appSettings["Proxy"]["port"]);
  148. curl_setopt($ch, CURLOPT_PROXYUSERPWD, $appSettings["Proxy"]["username"].":".$appSettings["Proxy"]["password"]);
  149. }
  150. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  151. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  152. $result = curl_exec($ch);
  153. curl_close($ch);
  154. return $result;
  155. }
  156. return FALSE;
  157. }
  158. private function is_Ok($var) {
  159. if(!preg_match('|status=fail|i',$var)) {
  160. return true;
  161. }
  162. }
  163. private function extractId($str) {
  164. if(preg_match('/[a-z0-9_-]{11}/i', $str, $matches)){
  165. return $matches[0];
  166. }
  167. return FALSE;
  168. }
  169. private function get_instructions($html) {
  170. $playerPattern = '/"assets":.+?"js":\s*("[^"]+")/';
  171. if(preg_match($playerPattern, $html, $matches) && is_string($_player = json_decode($matches[1])) && strlen($_player) >= 1) {
  172. $playerLink = substr($_player, 0, 2) == '//' ? "https:{$_player}" : "https://www.youtube.com{$_player}";
  173. $cache_player = $this->cache_dir.'/.ht-'.md5($_player);
  174. if(file_exists($cache_player)) {
  175. return unserialize(file_get_contents($cache_player));
  176. } else {
  177. $js_code = $this->curlGet($playerLink);
  178. $instructions = $this->sig_js_decode($js_code);
  179. if($instructions){
  180. file_put_contents($cache_player, serialize($instructions));
  181. return $instructions;
  182. }
  183. }
  184. }
  185. return false;
  186. }
  187. private function clean_name($name) {
  188. $special_chars = array(".","?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", "%", "+", chr(0));
  189. $filename = str_replace($special_chars,' ',$name);
  190. $filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
  191. $filename = str_replace( array( '%20', '+', ' '), '-', $filename );
  192. $filename = preg_replace( '/[\r\n\t -]+/', '-', $filename );
  193. $filename = trim( $filename, '.-_' );
  194. return $filename;
  195. }
  196. private function sig_decipher($signature, $instructions) {
  197. foreach($instructions as $opt){
  198. $command = $opt[0];
  199. $value = $opt[1];
  200. if($command == 'swap'){
  201. $temp = $signature[0];
  202. $signature[0] = $signature[$value % strlen($signature)];
  203. $signature[$value] = $temp;
  204. } elseif($command == 'splice'){
  205. $signature = substr($signature, $value);
  206. } elseif($command == 'reverse'){
  207. $signature = strrev($signature);
  208. }
  209. }
  210. return trim($signature);
  211. }
  212. private function sig_js_decode($file){
  213. $script = $this->getBetween($file, 'a=a.split("");', ';return a.join("")');
  214. $script = str_replace(array("a,","\n"), array(',',''), $script);
  215. $script2= $this->getBetween($file, 'var ' . substr($script, 0, 2).'={', '};');
  216. $script2= str_replace('a,b', 'a', $script2);
  217. $script = str_replace(substr($script, 0, 2).'.', '', $script);
  218. $script = str_replace('(', '', $script);
  219. $script = str_replace(')', '', $script);
  220. $script_ex= explode(";", $script);
  221. $script2_ex = explode("\n", $script2);
  222. for($i = 0; $i < count($script2_ex); $i++) {
  223. $tmp = isset($script2_ex[$i]) ? explode(':', $script2_ex[$i]) : [];
  224. $n = isset($tmp[0]) ? $tmp[0] : '';
  225. $m = isset($tmp[1]) ? $tmp[1] : '';
  226. $tempS[$n] = $m;
  227. }
  228. for($i = 0; $i < count($script_ex); $i++) {
  229. $tmp = isset($script_ex[$i]) ? explode(',', $script_ex[$i]) : [];
  230. $a = isset($tmp[0]) ? $tmp[0] : '';
  231. $b = isset($tmp[1]) ? $tmp[1] : '';
  232. $deKey[] = $this->createCommad($a, $b, $tempS);
  233. }
  234. return $deKey;
  235. }
  236. private function createCommad($value, $num, $source) {
  237. $result = '';
  238. if (isset($source[$value]) && mb_strpos($source[$value], 'reverse')) {
  239. $result = array('reverse', '');
  240. } elseif (isset($source[$value]) && mb_strpos($source[$value], 'a.splice')) {
  241. $result = array('splice', $num);
  242. } else {
  243. $result = array('swap', $num);
  244. }
  245. return $result;
  246. }
  247. private function getBetween($content, $start, $end) {
  248. $r = explode($start, $content);
  249. if (isset($r[1])) {
  250. $r = explode($end, $r[1]);
  251. return $r[0];
  252. }
  253. return '';
  254. }
  255. }