logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

rutube.py (11470B)


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