ceskatelevize.py 11 KB

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