ceskatelevize.py 11 KB

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