rutube.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. import itertools
  5. from .common import InfoExtractor
  6. from ..compat import (
  7. compat_str,
  8. compat_parse_qs,
  9. compat_urllib_parse_urlparse,
  10. )
  11. from ..utils import (
  12. determine_ext,
  13. unified_timestamp,
  14. try_get,
  15. int_or_none,
  16. )
  17. class RutubeBaseIE(InfoExtractor):
  18. def _extract_video(self, video, video_id=None, require_title=True):
  19. title = video['title'] if require_title else video.get('title')
  20. age_limit = video.get('is_adult')
  21. if age_limit is not None:
  22. age_limit = 18 if age_limit is True else 0
  23. uploader_id = try_get(video, lambda x: x['author']['id'])
  24. category = try_get(video, lambda x: x['category']['name'])
  25. return {
  26. 'id': video.get('id') or video_id,
  27. 'title': title,
  28. 'description': video.get('description'),
  29. 'thumbnail': video.get('thumbnail_url'),
  30. 'duration': int_or_none(video.get('duration')),
  31. 'uploader': try_get(video, lambda x: x['author']['name']),
  32. 'uploader_id': compat_str(uploader_id) if uploader_id else None,
  33. 'timestamp': unified_timestamp(video.get('created_ts')),
  34. 'category': [category] if category else None,
  35. 'age_limit': age_limit,
  36. 'view_count': int_or_none(video.get('hits')),
  37. 'comment_count': int_or_none(video.get('comments_count')),
  38. 'is_live': video.get('is_livestream'),
  39. }
  40. class RutubeIE(RutubeBaseIE):
  41. IE_NAME = 'rutube'
  42. IE_DESC = 'Rutube videos'
  43. _VALID_URL = r'https?://rutube\.ru/(?:video|(?:play/)?embed)/(?P<id>[\da-z]{32})'
  44. _TESTS = [{
  45. 'url': 'http://rutube.ru/video/3eac3b4561676c17df9132a9a1e62e3e/',
  46. 'md5': '79938ade01294ef7e27574890d0d3769',
  47. 'info_dict': {
  48. 'id': '3eac3b4561676c17df9132a9a1e62e3e',
  49. 'ext': 'flv',
  50. 'title': 'Раненный кенгуру забежал в аптеку',
  51. 'description': 'http://www.ntdtv.ru ',
  52. 'duration': 80,
  53. 'uploader': 'NTDRussian',
  54. 'uploader_id': '29790',
  55. 'timestamp': 1381943602,
  56. 'upload_date': '20131016',
  57. 'age_limit': 0,
  58. },
  59. }, {
  60. 'url': 'http://rutube.ru/play/embed/a10e53b86e8f349080f718582ce4c661',
  61. 'only_matching': True,
  62. }, {
  63. 'url': 'http://rutube.ru/embed/a10e53b86e8f349080f718582ce4c661',
  64. 'only_matching': True,
  65. }, {
  66. 'url': 'http://rutube.ru/video/3eac3b4561676c17df9132a9a1e62e3e/?pl_id=4252',
  67. 'only_matching': True,
  68. }, {
  69. 'url': 'https://rutube.ru/video/10b3a03fc01d5bbcc632a2f3514e8aab/?pl_type=source',
  70. 'only_matching': True,
  71. }]
  72. @classmethod
  73. def suitable(cls, url):
  74. return False if RutubePlaylistIE.suitable(url) else super(RutubeIE, cls).suitable(url)
  75. @staticmethod
  76. def _extract_urls(webpage):
  77. return [mobj.group('url') for mobj in re.finditer(
  78. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//rutube\.ru/embed/[\da-z]{32}.*?)\1',
  79. webpage)]
  80. def _real_extract(self, url):
  81. video_id = self._match_id(url)
  82. video = self._download_json(
  83. 'http://rutube.ru/api/video/%s/?format=json' % video_id,
  84. video_id, 'Downloading video JSON')
  85. info = self._extract_video(video, video_id)
  86. options = self._download_json(
  87. 'http://rutube.ru/api/play/options/%s/?format=json' % video_id,
  88. video_id, 'Downloading options JSON')
  89. formats = []
  90. for format_id, format_url in options['video_balancer'].items():
  91. ext = determine_ext(format_url)
  92. if ext == 'm3u8':
  93. formats.extend(self._extract_m3u8_formats(
  94. format_url, video_id, 'mp4', m3u8_id=format_id, fatal=False))
  95. elif ext == 'f4m':
  96. formats.extend(self._extract_f4m_formats(
  97. format_url, video_id, f4m_id=format_id, fatal=False))
  98. else:
  99. formats.append({
  100. 'url': format_url,
  101. 'format_id': format_id,
  102. })
  103. self._sort_formats(formats)
  104. info['formats'] = formats
  105. return info
  106. class RutubeEmbedIE(InfoExtractor):
  107. IE_NAME = 'rutube:embed'
  108. IE_DESC = 'Rutube embedded videos'
  109. _VALID_URL = r'https?://rutube\.ru/(?:video|play)/embed/(?P<id>[0-9]+)'
  110. _TESTS = [{
  111. 'url': 'http://rutube.ru/video/embed/6722881?vk_puid37=&vk_puid38=',
  112. 'info_dict': {
  113. 'id': 'a10e53b86e8f349080f718582ce4c661',
  114. 'ext': 'flv',
  115. 'timestamp': 1387830582,
  116. 'upload_date': '20131223',
  117. 'uploader_id': '297833',
  118. 'description': 'Видео группы ★http://vk.com/foxkidsreset★ музей Fox Kids и Jetix<br/><br/> восстановлено и сделано в шикоформате subziro89 http://vk.com/subziro89',
  119. 'uploader': 'subziro89 ILya',
  120. 'title': 'Мистический городок Эйри в Индиан 5 серия озвучка subziro89',
  121. },
  122. 'params': {
  123. 'skip_download': True,
  124. },
  125. }, {
  126. 'url': 'http://rutube.ru/play/embed/8083783',
  127. 'only_matching': True,
  128. }]
  129. def _real_extract(self, url):
  130. embed_id = self._match_id(url)
  131. webpage = self._download_webpage(url, embed_id)
  132. canonical_url = self._html_search_regex(
  133. r'<link\s+rel="canonical"\s+href="([^"]+?)"', webpage,
  134. 'Canonical URL')
  135. return self.url_result(canonical_url, RutubeIE.ie_key())
  136. class RutubePlaylistBaseIE(RutubeBaseIE):
  137. def _next_page_url(self, page_num, playlist_id, *args, **kwargs):
  138. return self._PAGE_TEMPLATE % (playlist_id, page_num)
  139. def _entries(self, playlist_id, *args, **kwargs):
  140. next_page_url = None
  141. for pagenum in itertools.count(1):
  142. page = self._download_json(
  143. next_page_url or self._next_page_url(
  144. pagenum, playlist_id, *args, **kwargs),
  145. playlist_id, 'Downloading page %s' % pagenum)
  146. results = page.get('results')
  147. if not results or not isinstance(results, list):
  148. break
  149. for result in results:
  150. video_url = result.get('video_url')
  151. if not video_url or not isinstance(video_url, compat_str):
  152. continue
  153. entry = self._extract_video(result, require_title=False)
  154. entry.update({
  155. '_type': 'url',
  156. 'url': video_url,
  157. 'ie_key': RutubeIE.ie_key(),
  158. })
  159. yield entry
  160. next_page_url = page.get('next')
  161. if not next_page_url or not page.get('has_next'):
  162. break
  163. def _extract_playlist(self, playlist_id, *args, **kwargs):
  164. return self.playlist_result(
  165. self._entries(playlist_id, *args, **kwargs),
  166. playlist_id, kwargs.get('playlist_name'))
  167. def _real_extract(self, url):
  168. return self._extract_playlist(self._match_id(url))
  169. class RutubeChannelIE(RutubePlaylistBaseIE):
  170. IE_NAME = 'rutube:channel'
  171. IE_DESC = 'Rutube channels'
  172. _VALID_URL = r'https?://rutube\.ru/tags/video/(?P<id>\d+)'
  173. _TESTS = [{
  174. 'url': 'http://rutube.ru/tags/video/1800/',
  175. 'info_dict': {
  176. 'id': '1800',
  177. },
  178. 'playlist_mincount': 68,
  179. }]
  180. _PAGE_TEMPLATE = 'http://rutube.ru/api/tags/video/%s/?page=%s&format=json'
  181. class RutubeMovieIE(RutubePlaylistBaseIE):
  182. IE_NAME = 'rutube:movie'
  183. IE_DESC = 'Rutube movies'
  184. _VALID_URL = r'https?://rutube\.ru/metainfo/tv/(?P<id>\d+)'
  185. _TESTS = []
  186. _MOVIE_TEMPLATE = 'http://rutube.ru/api/metainfo/tv/%s/?format=json'
  187. _PAGE_TEMPLATE = 'http://rutube.ru/api/metainfo/tv/%s/video?page=%s&format=json'
  188. def _real_extract(self, url):
  189. movie_id = self._match_id(url)
  190. movie = self._download_json(
  191. self._MOVIE_TEMPLATE % movie_id, movie_id,
  192. 'Downloading movie JSON')
  193. return self._extract_playlist(
  194. movie_id, playlist_name=movie.get('name'))
  195. class RutubePersonIE(RutubePlaylistBaseIE):
  196. IE_NAME = 'rutube:person'
  197. IE_DESC = 'Rutube person videos'
  198. _VALID_URL = r'https?://rutube\.ru/video/person/(?P<id>\d+)'
  199. _TESTS = [{
  200. 'url': 'http://rutube.ru/video/person/313878/',
  201. 'info_dict': {
  202. 'id': '313878',
  203. },
  204. 'playlist_mincount': 37,
  205. }]
  206. _PAGE_TEMPLATE = 'http://rutube.ru/api/video/person/%s/?page=%s&format=json'
  207. class RutubePlaylistIE(RutubePlaylistBaseIE):
  208. IE_NAME = 'rutube:playlist'
  209. IE_DESC = 'Rutube playlists'
  210. _VALID_URL = r'https?://rutube\.ru/(?:video|(?:play/)?embed)/[\da-z]{32}/\?.*?\bpl_id=(?P<id>\d+)'
  211. _TESTS = [{
  212. 'url': 'https://rutube.ru/video/cecd58ed7d531fc0f3d795d51cee9026/?pl_id=3097&pl_type=tag',
  213. 'info_dict': {
  214. 'id': '3097',
  215. },
  216. 'playlist_count': 27,
  217. }, {
  218. 'url': 'https://rutube.ru/video/10b3a03fc01d5bbcc632a2f3514e8aab/?pl_id=4252&pl_type=source',
  219. 'only_matching': True,
  220. }]
  221. _PAGE_TEMPLATE = 'http://rutube.ru/api/playlist/%s/%s/?page=%s&format=json'
  222. @staticmethod
  223. def suitable(url):
  224. params = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
  225. return params.get('pl_type', [None])[0] and int_or_none(params.get('pl_id', [None])[0])
  226. def _next_page_url(self, page_num, playlist_id, item_kind):
  227. return self._PAGE_TEMPLATE % (item_kind, playlist_id, page_num)
  228. def _real_extract(self, url):
  229. qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
  230. playlist_kind = qs['pl_type'][0]
  231. playlist_id = qs['pl_id'][0]
  232. return self._extract_playlist(playlist_id, item_kind=playlist_kind)