ruutu.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. import json
  2. import re
  3. import urllib.parse
  4. from .common import InfoExtractor
  5. from ..utils import (
  6. ExtractorError,
  7. determine_ext,
  8. find_xpath_attr,
  9. int_or_none,
  10. traverse_obj,
  11. try_call,
  12. unified_strdate,
  13. url_or_none,
  14. xpath_attr,
  15. xpath_text,
  16. )
  17. class RuutuIE(InfoExtractor):
  18. _VALID_URL = r'''(?x)
  19. https?://
  20. (?:
  21. (?:www\.)?(?:ruutu|supla)\.fi/(?:video|supla|audio)/|
  22. static\.nelonenmedia\.fi/player/misc/embed_player\.html\?.*?\bnid=
  23. )
  24. (?P<id>\d+)
  25. '''
  26. _TESTS = [
  27. {
  28. 'url': 'http://www.ruutu.fi/video/2058907',
  29. 'md5': 'ab2093f39be1ca8581963451b3c0234f',
  30. 'info_dict': {
  31. 'id': '2058907',
  32. 'ext': 'mp4',
  33. 'title': 'Oletko aina halunnut tietää mitä tapahtuu vain hetki ennen lähetystä? - Nyt se selvisi!',
  34. 'description': 'md5:cfc6ccf0e57a814360df464a91ff67d6',
  35. 'thumbnail': r're:^https?://.*\.jpg$',
  36. 'duration': 114,
  37. 'age_limit': 0,
  38. 'upload_date': '20150508',
  39. },
  40. },
  41. {
  42. 'url': 'http://www.ruutu.fi/video/2057306',
  43. 'md5': '065a10ae4d5b8cfd9d0c3d332465e3d9',
  44. 'info_dict': {
  45. 'id': '2057306',
  46. 'ext': 'mp4',
  47. 'title': 'Superpesis: katso koko kausi Ruudussa',
  48. 'description': 'md5:bfb7336df2a12dc21d18fa696c9f8f23',
  49. 'thumbnail': r're:^https?://.*\.jpg$',
  50. 'duration': 40,
  51. 'age_limit': 0,
  52. 'upload_date': '20150507',
  53. 'series': 'Superpesis',
  54. 'categories': ['Urheilu'],
  55. },
  56. },
  57. {
  58. 'url': 'http://www.supla.fi/supla/2231370',
  59. 'md5': 'df14e782d49a2c0df03d3be2a54ef949',
  60. 'info_dict': {
  61. 'id': '2231370',
  62. 'ext': 'mp4',
  63. 'title': 'Osa 1: Mikael Jungner',
  64. 'description': 'md5:7d90f358c47542e3072ff65d7b1bcffe',
  65. 'thumbnail': r're:^https?://.*\.jpg$',
  66. 'age_limit': 0,
  67. 'upload_date': '20151012',
  68. 'series': 'Läpivalaisu',
  69. },
  70. },
  71. # Episode where <SourceFile> is "NOT-USED", but has other
  72. # downloadable sources available.
  73. {
  74. 'url': 'http://www.ruutu.fi/video/3193728',
  75. 'only_matching': True,
  76. },
  77. {
  78. # audio podcast
  79. 'url': 'https://www.supla.fi/supla/3382410',
  80. 'md5': 'b9d7155fed37b2ebf6021d74c4b8e908',
  81. 'info_dict': {
  82. 'id': '3382410',
  83. 'ext': 'mp3',
  84. 'title': 'Mikä ihmeen poltergeist?',
  85. 'description': 'md5:bbb6963df17dfd0ecd9eb9a61bf14b52',
  86. 'thumbnail': r're:^https?://.*\.jpg$',
  87. 'age_limit': 0,
  88. 'upload_date': '20190320',
  89. 'series': 'Mysteeritarinat',
  90. 'duration': 1324,
  91. },
  92. 'expected_warnings': [
  93. 'HTTP Error 502: Bad Gateway',
  94. 'Failed to download m3u8 information',
  95. ],
  96. },
  97. {
  98. 'url': 'http://www.supla.fi/audio/2231370',
  99. 'only_matching': True,
  100. },
  101. {
  102. 'url': 'https://static.nelonenmedia.fi/player/misc/embed_player.html?nid=3618790',
  103. 'only_matching': True,
  104. },
  105. {
  106. # episode
  107. 'url': 'https://www.ruutu.fi/video/3401964',
  108. 'info_dict': {
  109. 'id': '3401964',
  110. 'ext': 'mp4',
  111. 'title': 'Temptation Island Suomi - Kausi 5 - Jakso 17',
  112. 'description': 'md5:87cf01d5e1e88adf0c8a2937d2bd42ba',
  113. 'thumbnail': r're:^https?://.*\.jpg$',
  114. 'duration': 2582,
  115. 'age_limit': 12,
  116. 'upload_date': '20190508',
  117. 'series': 'Temptation Island Suomi',
  118. 'season_number': 5,
  119. 'episode_number': 17,
  120. 'categories': ['Reality ja tositapahtumat', 'Kotimaiset suosikit', 'Romantiikka ja parisuhde'],
  121. },
  122. 'params': {
  123. 'skip_download': True,
  124. },
  125. },
  126. {
  127. # premium
  128. 'url': 'https://www.ruutu.fi/video/3618715',
  129. 'only_matching': True,
  130. },
  131. ]
  132. _API_BASE = 'https://gatling.nelonenmedia.fi'
  133. @classmethod
  134. def _extract_embed_urls(cls, url, webpage):
  135. # nelonen.fi
  136. settings = try_call(
  137. lambda: json.loads(re.search(
  138. r'jQuery\.extend\(Drupal\.settings, ({.+?})\);', webpage).group(1), strict=False))
  139. if settings:
  140. video_id = traverse_obj(settings, (
  141. 'mediaCrossbowSettings', 'file', 'field_crossbow_video_id', 'und', 0, 'value'))
  142. if video_id:
  143. return [f'http://www.ruutu.fi/video/{video_id}']
  144. # hs.fi and is.fi
  145. settings = try_call(
  146. lambda: json.loads(re.search(
  147. '(?s)<script[^>]+id=[\'"]__NEXT_DATA__[\'"][^>]*>([^<]+)</script>',
  148. webpage).group(1), strict=False))
  149. if settings:
  150. video_ids = set(traverse_obj(settings, (
  151. 'props', 'pageProps', 'page', 'assetData', 'splitBody', ..., 'video', 'sourceId')) or [])
  152. if video_ids:
  153. return [f'http://www.ruutu.fi/video/{v}' for v in video_ids]
  154. video_id = traverse_obj(settings, (
  155. 'props', 'pageProps', 'page', 'assetData', 'mainVideo', 'sourceId'))
  156. if video_id:
  157. return [f'http://www.ruutu.fi/video/{video_id}']
  158. def _real_extract(self, url):
  159. video_id = self._match_id(url)
  160. video_xml = self._download_xml(
  161. f'{self._API_BASE}/media-xml-cache', video_id,
  162. query={'id': video_id})
  163. formats = []
  164. processed_urls = []
  165. def extract_formats(node):
  166. for child in node:
  167. if child.tag.endswith('Files'):
  168. extract_formats(child)
  169. elif child.tag.endswith('File'):
  170. video_url = child.text
  171. if (not video_url or video_url in processed_urls
  172. or any(p in video_url for p in ('NOT_USED', 'NOT-USED'))):
  173. continue
  174. processed_urls.append(video_url)
  175. ext = determine_ext(video_url)
  176. auth_video_url = url_or_none(self._download_webpage(
  177. f'{self._API_BASE}/auth/access/v2', video_id,
  178. note=f'Downloading authenticated {ext} stream URL',
  179. fatal=False, query={'stream': video_url}))
  180. if auth_video_url:
  181. processed_urls.append(auth_video_url)
  182. video_url = auth_video_url
  183. if ext == 'm3u8':
  184. formats.extend(self._extract_m3u8_formats(
  185. video_url, video_id, 'mp4',
  186. entry_protocol='m3u8_native', m3u8_id='hls',
  187. fatal=False))
  188. elif ext == 'f4m':
  189. formats.extend(self._extract_f4m_formats(
  190. video_url, video_id, f4m_id='hds', fatal=False))
  191. elif ext == 'mpd':
  192. # video-only and audio-only streams are of different
  193. # duration resulting in out of sync issue
  194. continue
  195. formats.extend(self._extract_mpd_formats(
  196. video_url, video_id, mpd_id='dash', fatal=False))
  197. elif ext == 'mp3' or child.tag == 'AudioMediaFile':
  198. formats.append({
  199. 'format_id': 'audio',
  200. 'url': video_url,
  201. 'vcodec': 'none',
  202. })
  203. else:
  204. proto = urllib.parse.urlparse(video_url).scheme
  205. if not child.tag.startswith('HTTP') and proto != 'rtmp':
  206. continue
  207. preference = -1 if proto == 'rtmp' else 1
  208. label = child.get('label')
  209. tbr = int_or_none(child.get('bitrate'))
  210. format_id = f'{proto}-{label if label else tbr}' if label or tbr else proto
  211. if not self._is_valid_url(video_url, video_id, format_id):
  212. continue
  213. width, height = (int_or_none(x) for x in child.get('resolution', 'x').split('x')[:2])
  214. formats.append({
  215. 'format_id': format_id,
  216. 'url': video_url,
  217. 'width': width,
  218. 'height': height,
  219. 'tbr': tbr,
  220. 'preference': preference,
  221. })
  222. extract_formats(video_xml.find('./Clip'))
  223. def pv(name):
  224. value = try_call(lambda: find_xpath_attr(
  225. video_xml, './Clip/PassthroughVariables/variable', 'name', name).get('value'))
  226. if value != 'NA':
  227. return value or None
  228. if not formats:
  229. if (not self.get_param('allow_unplayable_formats')
  230. and xpath_text(video_xml, './Clip/DRM', default=None)):
  231. self.report_drm(video_id)
  232. ns_st_cds = pv('ns_st_cds')
  233. if ns_st_cds != 'free':
  234. raise ExtractorError(f'This video is {ns_st_cds}.', expected=True)
  235. themes = pv('themes')
  236. return {
  237. 'id': video_id,
  238. 'title': xpath_attr(video_xml, './/Behavior/Program', 'program_name', 'title', fatal=True),
  239. 'description': xpath_attr(video_xml, './/Behavior/Program', 'description', 'description'),
  240. 'thumbnail': xpath_attr(video_xml, './/Behavior/Startpicture', 'href', 'thumbnail'),
  241. 'duration': int_or_none(xpath_text(video_xml, './/Runtime', 'duration')) or int_or_none(pv('runtime')),
  242. 'age_limit': int_or_none(xpath_text(video_xml, './/AgeLimit', 'age limit')),
  243. 'upload_date': unified_strdate(pv('date_start')),
  244. 'series': pv('series_name'),
  245. 'season_number': int_or_none(pv('season_number')),
  246. 'episode_number': int_or_none(pv('episode_number')),
  247. 'categories': themes.split(',') if themes else None,
  248. 'formats': formats,
  249. }