YoutubeBridge.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. <?php
  2. /**
  3. * RssBridgeYoutube
  4. * Returns the newest videos
  5. * WARNING: to parse big playlists (over ~90 videos), you need to edit simple_html_dom.php:
  6. * change: define('MAX_FILE_SIZE', 600000);
  7. * into: define('MAX_FILE_SIZE', 900000); (or more)
  8. */
  9. class YoutubeBridge extends BridgeAbstract {
  10. const NAME = 'YouTube Bridge';
  11. const URI = 'https://www.youtube.com/';
  12. const CACHE_TIMEOUT = 10800; // 3h
  13. const DESCRIPTION = 'Returns the 10 newest videos by username/channel/playlist or search';
  14. const MAINTAINER = 'mitsukarenai';
  15. const PARAMETERS = array(
  16. 'By username' => array(
  17. 'u' => array(
  18. 'name' => 'username',
  19. 'exampleValue' => 'test',
  20. 'required' => true
  21. )
  22. ),
  23. 'By channel id' => array(
  24. 'c' => array(
  25. 'name' => 'channel id',
  26. 'exampleValue' => '15',
  27. 'required' => true
  28. )
  29. ),
  30. 'By playlist Id' => array(
  31. 'p' => array(
  32. 'name' => 'playlist id',
  33. 'exampleValue' => '15'
  34. )
  35. ),
  36. 'Search result' => array(
  37. 's' => array(
  38. 'name' => 'search keyword',
  39. 'exampleValue' => 'test'
  40. ),
  41. 'pa' => array(
  42. 'name' => 'page',
  43. 'type' => 'number',
  44. 'exampleValue' => 1
  45. )
  46. )
  47. );
  48. private function ytBridgeQueryVideoInfo($vid, &$author, &$desc, &$time){
  49. $html = $this->ytGetSimpleHTMLDOM(self::URI . "watch?v=$vid");
  50. // Skip unavailable videos
  51. if(!strpos($html->innertext, 'IS_UNAVAILABLE_PAGE')) {
  52. return;
  53. }
  54. foreach($html->find('script') as $script) {
  55. $data = trim($script->innertext);
  56. if(strpos($data, '{') !== 0)
  57. continue; // Wrong script
  58. $json = json_decode($data);
  59. if(!isset($json->itemListElement))
  60. continue; // Wrong script
  61. $author = $json->itemListElement[0]->item->name;
  62. }
  63. if(!is_null($html->find('#watch-description-text', 0)))
  64. $desc = $html->find('#watch-description-text', 0)->innertext;
  65. if(!is_null($html->find('meta[itemprop=datePublished]', 0)))
  66. $time = strtotime($html->find('meta[itemprop=datePublished]', 0)->getAttribute('content'));
  67. }
  68. private function ytBridgeAddItem($vid, $title, $author, $desc, $time){
  69. $item = array();
  70. $item['id'] = $vid;
  71. $item['title'] = $title;
  72. $item['author'] = $author;
  73. $item['timestamp'] = $time;
  74. $item['uri'] = self::URI . 'watch?v=' . $vid;
  75. $thumbnailUri = str_replace('/www.', '/img.', self::URI) . 'vi/' . $vid . '/0.jpg';
  76. $item['content'] = '<a href="' . $item['uri'] . '"><img src="' . $thumbnailUri . '" /></a><br />' . $desc;
  77. $this->items[] = $item;
  78. }
  79. private function ytBridgeParseXmlFeed($xml) {
  80. foreach($xml->find('entry') as $element) {
  81. $title = $this->ytBridgeFixTitle($element->find('title', 0)->plaintext);
  82. $author = $element->find('name', 0)->plaintext;
  83. $desc = $element->find('media:description', 0)->innertext;
  84. // Make sure the description is easy on the eye :)
  85. $desc = htmlspecialchars($desc);
  86. $desc = nl2br($desc);
  87. $desc = preg_replace('/(http[s]{0,1}\:\/\/[a-zA-Z0-9.\/\?\&=\-_]{4,})/ims',
  88. '<a href="$1" target="_blank">$1</a> ',
  89. $desc);
  90. $vid = str_replace('yt:video:', '', $element->find('id', 0)->plaintext);
  91. $time = strtotime($element->find('published', 0)->plaintext);
  92. if(strpos($vid, 'googleads') === false)
  93. $this->ytBridgeAddItem($vid, $title, $author, $desc, $time);
  94. }
  95. $this->feedName = $this->ytBridgeFixTitle($xml->find('feed > title', 0)->plaintext); // feedName will be used by getName()
  96. }
  97. private function ytBridgeParseHtmlListing($html, $element_selector, $title_selector, $add_parsed_items = true) {
  98. $limit = $add_parsed_items ? 10 : INF;
  99. $count = 0;
  100. foreach($html->find($element_selector) as $element) {
  101. if($count < $limit) {
  102. $author = '';
  103. $desc = '';
  104. $time = 0;
  105. $vid = str_replace('/watch?v=', '', $element->find('a', 0)->href);
  106. $vid = substr($vid, 0, strpos($vid, '&') ?: strlen($vid));
  107. $title = $this->ytBridgeFixTitle($element->find($title_selector, 0)->plaintext);
  108. if($title != '[Private Video]' && strpos($vid, 'googleads') === false) {
  109. if ($add_parsed_items) {
  110. $this->ytBridgeQueryVideoInfo($vid, $author, $desc, $time);
  111. $this->ytBridgeAddItem($vid, $title, $author, $desc, $time);
  112. }
  113. $count++;
  114. }
  115. }
  116. }
  117. return $count;
  118. }
  119. private function ytBridgeFixTitle($title) {
  120. // convert both &#1234; and &quot; to UTF-8
  121. return html_entity_decode($title, ENT_QUOTES, 'UTF-8');
  122. }
  123. private function ytGetSimpleHTMLDOM($url){
  124. return getSimpleHTMLDOM($url,
  125. $header = array(),
  126. $opts = array(),
  127. $lowercase = true,
  128. $forceTagsClosed = true,
  129. $target_charset = DEFAULT_TARGET_CHARSET,
  130. $stripRN = false,
  131. $defaultBRText = DEFAULT_BR_TEXT,
  132. $defaultSpanText = DEFAULT_SPAN_TEXT);
  133. }
  134. public function collectData(){
  135. $xml = '';
  136. $html = '';
  137. $url_feed = '';
  138. $url_listing = '';
  139. if($this->getInput('u')) { /* User and Channel modes */
  140. $this->request = $this->getInput('u');
  141. $url_feed = self::URI . 'feeds/videos.xml?user=' . urlencode($this->request);
  142. $url_listing = self::URI . 'user/' . urlencode($this->request) . '/videos';
  143. } elseif($this->getInput('c')) {
  144. $this->request = $this->getInput('c');
  145. $url_feed = self::URI . 'feeds/videos.xml?channel_id=' . urlencode($this->request);
  146. $url_listing = self::URI . 'channel/' . urlencode($this->request) . '/videos';
  147. }
  148. if(!empty($url_feed) && !empty($url_listing)) {
  149. if($xml = $this->ytGetSimpleHTMLDOM($url_feed)) {
  150. $this->ytBridgeParseXmlFeed($xml);
  151. } elseif($html = $this->ytGetSimpleHTMLDOM($url_listing)) {
  152. $this->ytBridgeParseHtmlListing($html, 'li.channels-content-item', 'h3');
  153. } else {
  154. returnServerError("Could not request YouTube. Tried:\n - $url_feed\n - $url_listing");
  155. }
  156. } elseif($this->getInput('p')) { /* playlist mode */
  157. $this->request = $this->getInput('p');
  158. $url_feed = self::URI . 'feeds/videos.xml?playlist_id=' . urlencode($this->request);
  159. $url_listing = self::URI . 'playlist?list=' . urlencode($this->request);
  160. $html = $this->ytGetSimpleHTMLDOM($url_listing)
  161. or returnServerError("Could not request YouTube. Tried:\n - $url_listing");
  162. $item_count = $this->ytBridgeParseHtmlListing($html, 'tr.pl-video', '.pl-video-title a', false);
  163. if ($item_count <= 15 && ($xml = $this->ytGetSimpleHTMLDOM($url_feed))) {
  164. $this->ytBridgeParseXmlFeed($xml);
  165. } else {
  166. $this->ytBridgeParseHtmlListing($html, 'tr.pl-video', '.pl-video-title a');
  167. }
  168. $this->feedName = 'Playlist: ' . str_replace(' - YouTube', '', $html->find('title', 0)->plaintext); // feedName will be used by getName()
  169. usort($this->items, function ($item1, $item2) {
  170. return $item2['timestamp'] - $item1['timestamp'];
  171. });
  172. } elseif($this->getInput('s')) { /* search mode */
  173. $this->request = $this->getInput('s');
  174. $page = 1;
  175. if($this->getInput('pa'))
  176. $page = (int)preg_replace('/[^0-9]/', '', $this->getInput('pa'));
  177. $url_listing = self::URI
  178. . 'results?search_query='
  179. . urlencode($this->request)
  180. . '&page='
  181. . $page
  182. . '&filters=video&search_sort=video_date_uploaded';
  183. $html = $this->ytGetSimpleHTMLDOM($url_listing)
  184. or returnServerError("Could not request YouTube. Tried:\n - $url_listing");
  185. $this->ytBridgeParseHtmlListing($html, 'div.yt-lockup', 'h3 > a');
  186. $this->feedName = 'Search: ' . str_replace(' - YouTube', '', $html->find('title', 0)->plaintext); // feedName will be used by getName()
  187. } else { /* no valid mode */
  188. returnClientError("You must either specify either:\n - YouTube
  189. username (?u=...)\n - Channel id (?c=...)\n - Playlist id (?p=...)\n - Search (?s=...)");
  190. }
  191. }
  192. public function getName(){
  193. // Name depends on queriedContext:
  194. switch($this->queriedContext) {
  195. case 'By username':
  196. case 'By channel id':
  197. case 'By playlist Id':
  198. case 'Search result':
  199. return $this->feedName . ' - YouTube'; // We already know it's a bridge, right?
  200. default:
  201. return parent::getName();
  202. }
  203. }
  204. }