logo

youtube-dl

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

ceskatelevize.py (12068B)


  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. str_or_none,
  14. traverse_obj,
  15. urlencode_postdata,
  16. USER_AGENTS,
  17. )
  18. class CeskaTelevizeIE(InfoExtractor):
  19. _VALID_URL = r'https?://(?:www\.)?ceskatelevize\.cz/(?:ivysilani|porady|zive)/(?:[^/?#&]+/)*(?P<id>[^/#?]+)'
  20. _TESTS = [{
  21. 'url': 'http://www.ceskatelevize.cz/ivysilani/10441294653-hyde-park-civilizace/215411058090502/bonus/20641-bonus-01-en',
  22. 'info_dict': {
  23. 'id': '61924494877028507',
  24. 'ext': 'mp4',
  25. 'title': 'Bonus 01 - En - Hyde Park Civilizace',
  26. 'description': 'English Subtittles',
  27. 'thumbnail': r're:^https?://.*\.jpg',
  28. 'duration': 81.3,
  29. },
  30. 'params': {
  31. # m3u8 download
  32. 'skip_download': True,
  33. },
  34. }, {
  35. # live stream
  36. 'url': 'http://www.ceskatelevize.cz/zive/ct1/',
  37. 'info_dict': {
  38. 'id': '102',
  39. 'ext': 'mp4',
  40. 'title': r'ČT1 - živé vysílání online',
  41. 'description': 'Sledujte živé vysílání kanálu ČT1 online. Vybírat si můžete i z dalších kanálů České televize na kterémkoli z vašich zařízení.',
  42. 'is_live': True,
  43. },
  44. 'params': {
  45. # m3u8 download
  46. 'skip_download': True,
  47. },
  48. }, {
  49. # another
  50. 'url': 'http://www.ceskatelevize.cz/ivysilani/zive/ct4/',
  51. 'only_matching': True,
  52. 'info_dict': {
  53. 'id': 402,
  54. 'ext': 'mp4',
  55. 'title': r're:^ČT Sport \d{4}-\d{2}-\d{2} \d{2}:\d{2}$',
  56. 'is_live': True,
  57. },
  58. # 'skip': 'Georestricted to Czech Republic',
  59. }, {
  60. 'url': 'http://www.ceskatelevize.cz/ivysilani/embed/iFramePlayer.php?hash=d6a3e1370d2e4fa76296b90bad4dfc19673b641e&IDEC=217 562 22150/0004&channelID=1&width=100%25',
  61. 'only_matching': True,
  62. }, {
  63. # video with 18+ caution trailer
  64. 'url': 'http://www.ceskatelevize.cz/porady/10520528904-queer/215562210900007-bogotart/',
  65. 'info_dict': {
  66. 'id': '215562210900007-bogotart',
  67. 'title': 'Bogotart - Queer',
  68. 'description': 'Hlavní město Kolumbie v doprovodu queer umělců. Vroucí svět plný vášně, sebevědomí, ale i násilí a bolesti',
  69. },
  70. 'playlist': [{
  71. 'info_dict': {
  72. 'id': '61924494877311053',
  73. 'ext': 'mp4',
  74. 'title': 'Bogotart - Queer (Varování 18+)',
  75. 'duration': 11.9,
  76. },
  77. }, {
  78. 'info_dict': {
  79. 'id': '61924494877068022',
  80. 'ext': 'mp4',
  81. 'title': 'Bogotart - Queer (Queer)',
  82. 'thumbnail': r're:^https?://.*\.jpg',
  83. 'duration': 1558.3,
  84. },
  85. }],
  86. 'params': {
  87. # m3u8 download
  88. 'skip_download': True,
  89. },
  90. }, {
  91. # iframe embed
  92. 'url': 'http://www.ceskatelevize.cz/porady/10614999031-neviditelni/21251212048/',
  93. 'only_matching': True,
  94. }]
  95. def _search_nextjs_data(self, webpage, video_id, **kw):
  96. return self._parse_json(
  97. self._search_regex(
  98. r'(?s)<script[^>]+id=[\'"]__NEXT_DATA__[\'"][^>]*>([^<]+)</script>',
  99. webpage, 'next.js data', **kw),
  100. video_id, **kw)
  101. def _real_extract(self, url):
  102. playlist_id = self._match_id(url)
  103. webpage, urlh = self._download_webpage_handle(url, playlist_id)
  104. parsed_url = compat_urllib_parse_urlparse(urlh.geturl())
  105. site_name = self._og_search_property('site_name', webpage, fatal=False, default='Česká televize')
  106. playlist_title = self._og_search_title(webpage, default=None)
  107. if site_name and playlist_title:
  108. playlist_title = re.split(r'\s*[—|]\s*%s' % (site_name, ), playlist_title, 1)[0]
  109. playlist_description = self._og_search_description(webpage, default=None)
  110. if playlist_description:
  111. playlist_description = playlist_description.replace('\xa0', ' ')
  112. type_ = 'IDEC'
  113. if re.search(r'(^/porady|/zive)/', parsed_url.path):
  114. next_data = self._search_nextjs_data(webpage, playlist_id)
  115. if '/zive/' in parsed_url.path:
  116. idec = traverse_obj(next_data, ('props', 'pageProps', 'data', 'liveBroadcast', 'current', 'idec'), get_all=False)
  117. else:
  118. idec = traverse_obj(next_data, ('props', 'pageProps', 'data', ('show', 'mediaMeta'), 'idec'), get_all=False)
  119. if not idec:
  120. idec = traverse_obj(next_data, ('props', 'pageProps', 'data', 'videobonusDetail', 'bonusId'), get_all=False)
  121. if idec:
  122. type_ = 'bonus'
  123. if not idec:
  124. raise ExtractorError('Failed to find IDEC id')
  125. iframe_hash = self._download_webpage(
  126. 'https://www.ceskatelevize.cz/v-api/iframe-hash/',
  127. playlist_id, note='Getting IFRAME hash')
  128. query = {'hash': iframe_hash, 'origin': 'iVysilani', 'autoStart': 'true', type_: idec, }
  129. webpage = self._download_webpage(
  130. 'https://www.ceskatelevize.cz/ivysilani/embed/iFramePlayer.php',
  131. playlist_id, note='Downloading player', query=query)
  132. NOT_AVAILABLE_STRING = 'This content is not available at your territory due to limited copyright.'
  133. if '%s</p>' % NOT_AVAILABLE_STRING in webpage:
  134. self.raise_geo_restricted(NOT_AVAILABLE_STRING)
  135. if any(not_found in webpage for not_found in ('Neplatný parametr pro videopřehrávač', 'IDEC nebyl nalezen', )):
  136. raise ExtractorError('no video with IDEC available', video_id=idec, expected=True)
  137. type_ = None
  138. episode_id = None
  139. playlist = self._parse_json(
  140. self._search_regex(
  141. r'getPlaylistUrl\(\[({.+?})\]', webpage, 'playlist',
  142. default='{}'), playlist_id)
  143. if playlist:
  144. type_ = playlist.get('type')
  145. episode_id = playlist.get('id')
  146. if not type_:
  147. type_ = self._html_search_regex(
  148. r'getPlaylistUrl\(\[\{"type":"(.+?)","id":".+?"\}\],',
  149. webpage, 'type')
  150. if not episode_id:
  151. episode_id = self._html_search_regex(
  152. r'getPlaylistUrl\(\[\{"type":".+?","id":"(.+?)"\}\],',
  153. webpage, 'episode_id')
  154. data = {
  155. 'playlist[0][type]': type_,
  156. 'playlist[0][id]': episode_id,
  157. 'requestUrl': parsed_url.path,
  158. 'requestSource': 'iVysilani',
  159. }
  160. entries = []
  161. for user_agent in (None, USER_AGENTS['Safari']):
  162. req = sanitized_Request(
  163. 'https://www.ceskatelevize.cz/ivysilani/ajax/get-client-playlist/',
  164. data=urlencode_postdata(data))
  165. req.add_header('Content-type', 'application/x-www-form-urlencoded')
  166. req.add_header('x-addr', '127.0.0.1')
  167. req.add_header('X-Requested-With', 'XMLHttpRequest')
  168. if user_agent:
  169. req.add_header('User-Agent', user_agent)
  170. req.add_header('Referer', url)
  171. playlistpage = self._download_json(req, playlist_id, fatal=False)
  172. if not playlistpage:
  173. continue
  174. playlist_url = playlistpage['url']
  175. if playlist_url == 'error_region':
  176. raise ExtractorError(NOT_AVAILABLE_STRING, expected=True)
  177. req = sanitized_Request(compat_urllib_parse_unquote(playlist_url))
  178. req.add_header('Referer', url)
  179. playlist = self._download_json(req, playlist_id, fatal=False)
  180. if not playlist:
  181. continue
  182. playlist = playlist.get('playlist')
  183. if not isinstance(playlist, list):
  184. continue
  185. playlist_len = len(playlist)
  186. for num, item in enumerate(playlist):
  187. is_live = item.get('type') == 'LIVE'
  188. formats = []
  189. for format_id, stream_url in item.get('streamUrls', {}).items():
  190. if 'drmOnly=true' in stream_url:
  191. continue
  192. if 'playerType=flash' in stream_url:
  193. stream_formats = self._extract_m3u8_formats(
  194. stream_url, playlist_id, 'mp4', 'm3u8_native',
  195. m3u8_id='hls-%s' % format_id, fatal=False)
  196. else:
  197. stream_formats = self._extract_mpd_formats(
  198. stream_url, playlist_id,
  199. mpd_id='dash-%s' % format_id, fatal=False)
  200. # See https://github.com/ytdl-org/youtube-dl/issues/12119#issuecomment-280037031
  201. if format_id == 'audioDescription':
  202. for f in stream_formats:
  203. f['source_preference'] = -10
  204. formats.extend(stream_formats)
  205. if user_agent and len(entries) == playlist_len:
  206. entries[num]['formats'].extend(formats)
  207. continue
  208. item_id = str_or_none(item.get('id') or item['assetId'])
  209. title = item['title']
  210. duration = float_or_none(item.get('duration'))
  211. thumbnail = item.get('previewImageUrl')
  212. subtitles = {}
  213. if item.get('type') == 'VOD':
  214. subs = item.get('subtitles')
  215. if subs:
  216. subtitles = self.extract_subtitles(episode_id, subs)
  217. if playlist_len == 1:
  218. final_title = playlist_title or title
  219. else:
  220. final_title = '%s (%s)' % (playlist_title, title)
  221. entries.append({
  222. 'id': item_id,
  223. 'title': final_title,
  224. 'description': playlist_description if playlist_len == 1 else None,
  225. 'thumbnail': thumbnail,
  226. 'duration': duration,
  227. 'formats': formats,
  228. 'subtitles': subtitles,
  229. 'is_live': is_live,
  230. })
  231. for e in entries:
  232. self._sort_formats(e['formats'])
  233. if len(entries) == 1:
  234. return entries[0]
  235. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  236. def _get_subtitles(self, episode_id, subs):
  237. original_subtitles = self._download_webpage(
  238. subs[0]['url'], episode_id, 'Downloading subtitles')
  239. srt_subs = self._fix_subtitles(original_subtitles)
  240. return {
  241. 'cs': [{
  242. 'ext': 'srt',
  243. 'data': srt_subs,
  244. }]
  245. }
  246. @staticmethod
  247. def _fix_subtitles(subtitles):
  248. """ Convert millisecond-based subtitles to SRT """
  249. def _msectotimecode(msec):
  250. """ Helper utility to convert milliseconds to timecode """
  251. components = []
  252. for divider in [1000, 60, 60, 100]:
  253. components.append(msec % divider)
  254. msec //= divider
  255. return '{3:02}:{2:02}:{1:02},{0:03}'.format(*components)
  256. def _fix_subtitle(subtitle):
  257. for line in subtitle.splitlines():
  258. m = re.match(r'^\s*([0-9]+);\s*([0-9]+)\s+([0-9]+)\s*$', line)
  259. if m:
  260. yield m.group(1)
  261. start, stop = (_msectotimecode(int(t)) for t in m.groups()[1:])
  262. yield '{0} --> {1}'.format(start, stop)
  263. else:
  264. yield line
  265. return '\r\n'.join(_fix_subtitle(subtitles))