logo

youtube-dl

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

ceskatelevize.py (10657B)


  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import (
  6. compat_urllib_parse_unquote,
  7. compat_urllib_parse_urlparse,
  8. )
  9. from ..utils import (
  10. ExtractorError,
  11. float_or_none,
  12. sanitized_Request,
  13. unescapeHTML,
  14. update_url_query,
  15. urlencode_postdata,
  16. USER_AGENTS,
  17. )
  18. class CeskaTelevizeIE(InfoExtractor):
  19. _VALID_URL = r'https?://(?:www\.)?ceskatelevize\.cz/ivysilani/(?:[^/?#&]+/)*(?P<id>[^/#?]+)'
  20. _TESTS = [{
  21. 'url': 'http://www.ceskatelevize.cz/ivysilani/ivysilani/10441294653-hyde-park-civilizace/214411058091220',
  22. 'info_dict': {
  23. 'id': '61924494877246241',
  24. 'ext': 'mp4',
  25. 'title': 'Hyde Park Civilizace: Život v Grónsku',
  26. 'description': 'md5:3fec8f6bb497be5cdb0c9e8781076626',
  27. 'thumbnail': r're:^https?://.*\.jpg',
  28. 'duration': 3350,
  29. },
  30. 'params': {
  31. # m3u8 download
  32. 'skip_download': True,
  33. },
  34. }, {
  35. 'url': 'http://www.ceskatelevize.cz/ivysilani/10441294653-hyde-park-civilizace/215411058090502/bonus/20641-bonus-01-en',
  36. 'info_dict': {
  37. 'id': '61924494877028507',
  38. 'ext': 'mp4',
  39. 'title': 'Hyde Park Civilizace: Bonus 01 - En',
  40. 'description': 'English Subtittles',
  41. 'thumbnail': r're:^https?://.*\.jpg',
  42. 'duration': 81.3,
  43. },
  44. 'params': {
  45. # m3u8 download
  46. 'skip_download': True,
  47. },
  48. }, {
  49. # live stream
  50. 'url': 'http://www.ceskatelevize.cz/ivysilani/zive/ct4/',
  51. 'info_dict': {
  52. 'id': 402,
  53. 'ext': 'mp4',
  54. 'title': r're:^ČT Sport \d{4}-\d{2}-\d{2} \d{2}:\d{2}$',
  55. 'is_live': True,
  56. },
  57. 'params': {
  58. # m3u8 download
  59. 'skip_download': True,
  60. },
  61. 'skip': 'Georestricted to Czech Republic',
  62. }, {
  63. 'url': 'http://www.ceskatelevize.cz/ivysilani/embed/iFramePlayer.php?hash=d6a3e1370d2e4fa76296b90bad4dfc19673b641e&IDEC=217 562 22150/0004&channelID=1&width=100%25',
  64. 'only_matching': True,
  65. }]
  66. def _real_extract(self, url):
  67. playlist_id = self._match_id(url)
  68. webpage = self._download_webpage(url, playlist_id)
  69. NOT_AVAILABLE_STRING = 'This content is not available at your territory due to limited copyright.'
  70. if '%s</p>' % NOT_AVAILABLE_STRING in webpage:
  71. raise ExtractorError(NOT_AVAILABLE_STRING, expected=True)
  72. type_ = None
  73. episode_id = None
  74. playlist = self._parse_json(
  75. self._search_regex(
  76. r'getPlaylistUrl\(\[({.+?})\]', webpage, 'playlist',
  77. default='{}'), playlist_id)
  78. if playlist:
  79. type_ = playlist.get('type')
  80. episode_id = playlist.get('id')
  81. if not type_:
  82. type_ = self._html_search_regex(
  83. r'getPlaylistUrl\(\[\{"type":"(.+?)","id":".+?"\}\],',
  84. webpage, 'type')
  85. if not episode_id:
  86. episode_id = self._html_search_regex(
  87. r'getPlaylistUrl\(\[\{"type":".+?","id":"(.+?)"\}\],',
  88. webpage, 'episode_id')
  89. data = {
  90. 'playlist[0][type]': type_,
  91. 'playlist[0][id]': episode_id,
  92. 'requestUrl': compat_urllib_parse_urlparse(url).path,
  93. 'requestSource': 'iVysilani',
  94. }
  95. entries = []
  96. for user_agent in (None, USER_AGENTS['Safari']):
  97. req = sanitized_Request(
  98. 'https://www.ceskatelevize.cz/ivysilani/ajax/get-client-playlist',
  99. data=urlencode_postdata(data))
  100. req.add_header('Content-type', 'application/x-www-form-urlencoded')
  101. req.add_header('x-addr', '127.0.0.1')
  102. req.add_header('X-Requested-With', 'XMLHttpRequest')
  103. if user_agent:
  104. req.add_header('User-Agent', user_agent)
  105. req.add_header('Referer', url)
  106. playlistpage = self._download_json(req, playlist_id, fatal=False)
  107. if not playlistpage:
  108. continue
  109. playlist_url = playlistpage['url']
  110. if playlist_url == 'error_region':
  111. raise ExtractorError(NOT_AVAILABLE_STRING, expected=True)
  112. req = sanitized_Request(compat_urllib_parse_unquote(playlist_url))
  113. req.add_header('Referer', url)
  114. playlist_title = self._og_search_title(webpage, default=None)
  115. playlist_description = self._og_search_description(webpage, default=None)
  116. playlist = self._download_json(req, playlist_id, fatal=False)
  117. if not playlist:
  118. continue
  119. playlist = playlist.get('playlist')
  120. if not isinstance(playlist, list):
  121. continue
  122. playlist_len = len(playlist)
  123. for num, item in enumerate(playlist):
  124. is_live = item.get('type') == 'LIVE'
  125. formats = []
  126. for format_id, stream_url in item.get('streamUrls', {}).items():
  127. if 'drmOnly=true' in stream_url:
  128. continue
  129. if 'playerType=flash' in stream_url:
  130. stream_formats = self._extract_m3u8_formats(
  131. stream_url, playlist_id, 'mp4', 'm3u8_native',
  132. m3u8_id='hls-%s' % format_id, fatal=False)
  133. else:
  134. stream_formats = self._extract_mpd_formats(
  135. stream_url, playlist_id,
  136. mpd_id='dash-%s' % format_id, fatal=False)
  137. # See https://github.com/ytdl-org/youtube-dl/issues/12119#issuecomment-280037031
  138. if format_id == 'audioDescription':
  139. for f in stream_formats:
  140. f['source_preference'] = -10
  141. formats.extend(stream_formats)
  142. if user_agent and len(entries) == playlist_len:
  143. entries[num]['formats'].extend(formats)
  144. continue
  145. item_id = item.get('id') or item['assetId']
  146. title = item['title']
  147. duration = float_or_none(item.get('duration'))
  148. thumbnail = item.get('previewImageUrl')
  149. subtitles = {}
  150. if item.get('type') == 'VOD':
  151. subs = item.get('subtitles')
  152. if subs:
  153. subtitles = self.extract_subtitles(episode_id, subs)
  154. if playlist_len == 1:
  155. final_title = playlist_title or title
  156. if is_live:
  157. final_title = self._live_title(final_title)
  158. else:
  159. final_title = '%s (%s)' % (playlist_title, title)
  160. entries.append({
  161. 'id': item_id,
  162. 'title': final_title,
  163. 'description': playlist_description if playlist_len == 1 else None,
  164. 'thumbnail': thumbnail,
  165. 'duration': duration,
  166. 'formats': formats,
  167. 'subtitles': subtitles,
  168. 'is_live': is_live,
  169. })
  170. for e in entries:
  171. self._sort_formats(e['formats'])
  172. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  173. def _get_subtitles(self, episode_id, subs):
  174. original_subtitles = self._download_webpage(
  175. subs[0]['url'], episode_id, 'Downloading subtitles')
  176. srt_subs = self._fix_subtitles(original_subtitles)
  177. return {
  178. 'cs': [{
  179. 'ext': 'srt',
  180. 'data': srt_subs,
  181. }]
  182. }
  183. @staticmethod
  184. def _fix_subtitles(subtitles):
  185. """ Convert millisecond-based subtitles to SRT """
  186. def _msectotimecode(msec):
  187. """ Helper utility to convert milliseconds to timecode """
  188. components = []
  189. for divider in [1000, 60, 60, 100]:
  190. components.append(msec % divider)
  191. msec //= divider
  192. return '{3:02}:{2:02}:{1:02},{0:03}'.format(*components)
  193. def _fix_subtitle(subtitle):
  194. for line in subtitle.splitlines():
  195. m = re.match(r'^\s*([0-9]+);\s*([0-9]+)\s+([0-9]+)\s*$', line)
  196. if m:
  197. yield m.group(1)
  198. start, stop = (_msectotimecode(int(t)) for t in m.groups()[1:])
  199. yield '{0} --> {1}'.format(start, stop)
  200. else:
  201. yield line
  202. return '\r\n'.join(_fix_subtitle(subtitles))
  203. class CeskaTelevizePoradyIE(InfoExtractor):
  204. _VALID_URL = r'https?://(?:www\.)?ceskatelevize\.cz/porady/(?:[^/?#&]+/)*(?P<id>[^/#?]+)'
  205. _TESTS = [{
  206. # video with 18+ caution trailer
  207. 'url': 'http://www.ceskatelevize.cz/porady/10520528904-queer/215562210900007-bogotart/',
  208. 'info_dict': {
  209. 'id': '215562210900007-bogotart',
  210. 'title': 'Queer: Bogotart',
  211. 'description': 'Alternativní průvodce současným queer světem',
  212. },
  213. 'playlist': [{
  214. 'info_dict': {
  215. 'id': '61924494876844842',
  216. 'ext': 'mp4',
  217. 'title': 'Queer: Bogotart (Varování 18+)',
  218. 'duration': 10.2,
  219. },
  220. }, {
  221. 'info_dict': {
  222. 'id': '61924494877068022',
  223. 'ext': 'mp4',
  224. 'title': 'Queer: Bogotart (Queer)',
  225. 'thumbnail': r're:^https?://.*\.jpg',
  226. 'duration': 1558.3,
  227. },
  228. }],
  229. 'params': {
  230. # m3u8 download
  231. 'skip_download': True,
  232. },
  233. }, {
  234. # iframe embed
  235. 'url': 'http://www.ceskatelevize.cz/porady/10614999031-neviditelni/21251212048/',
  236. 'only_matching': True,
  237. }]
  238. def _real_extract(self, url):
  239. video_id = self._match_id(url)
  240. webpage = self._download_webpage(url, video_id)
  241. data_url = update_url_query(unescapeHTML(self._search_regex(
  242. (r'<span[^>]*\bdata-url=(["\'])(?P<url>(?:(?!\1).)+)\1',
  243. r'<iframe[^>]+\bsrc=(["\'])(?P<url>(?:https?:)?//(?:www\.)?ceskatelevize\.cz/ivysilani/embed/iFramePlayer\.php.*?)\1'),
  244. webpage, 'iframe player url', group='url')), query={
  245. 'autoStart': 'true',
  246. })
  247. return self.url_result(data_url, ie=CeskaTelevizeIE.ie_key())