tv2.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. import re
  2. from .common import InfoExtractor
  3. from ..compat import compat_HTTPError
  4. from ..utils import (
  5. determine_ext,
  6. ExtractorError,
  7. int_or_none,
  8. float_or_none,
  9. js_to_json,
  10. parse_iso8601,
  11. remove_end,
  12. strip_or_none,
  13. try_get,
  14. )
  15. class TV2IE(InfoExtractor):
  16. _VALID_URL = r'https?://(?:www\.)?tv2\.no/v(?:ideo)?\d*/(?:[^?#]+/)*(?P<id>\d+)'
  17. _TESTS = [{
  18. 'url': 'http://www.tv2.no/v/1791207/',
  19. 'info_dict': {
  20. 'id': '1791207',
  21. 'ext': 'mp4',
  22. 'title': 'Her kolliderer romsonden med asteroiden ',
  23. 'description': 'En romsonde har krasjet inn i en asteroide i verdensrommet. Kollisjonen skjedde klokken 01:14 natt til tirsdag 27. september norsk tid. \n\nNasa kaller det sitt første forsøk på planetforsvar.',
  24. 'timestamp': 1664238190,
  25. 'upload_date': '20220927',
  26. 'duration': 146,
  27. 'thumbnail': r're:^https://.*$',
  28. 'view_count': int,
  29. 'categories': list,
  30. },
  31. }, {
  32. 'url': 'http://www.tv2.no/v2/916509',
  33. 'only_matching': True,
  34. }, {
  35. 'url': 'https://www.tv2.no/video/nyhetene/her-kolliderer-romsonden-med-asteroiden/1791207/',
  36. 'only_matching': True,
  37. }]
  38. _PROTOCOLS = ('HLS', 'DASH')
  39. _GEO_COUNTRIES = ['NO']
  40. def _real_extract(self, url):
  41. video_id = self._match_id(url)
  42. asset = self._download_json('https://sumo.tv2.no/rest/assets/' + video_id, video_id,
  43. 'Downloading metadata JSON')
  44. title = asset['title']
  45. is_live = asset.get('live') is True
  46. formats = []
  47. format_urls = []
  48. for protocol in self._PROTOCOLS:
  49. try:
  50. data = self._download_json('https://api.sumo.tv2.no/play/%s?stream=%s' % (video_id, protocol),
  51. video_id, 'Downloading playabck JSON',
  52. headers={'content-type': 'application/json'},
  53. data='{"device":{"id":"1-1-1","name":"Nettleser (HTML)"}}'.encode())['playback']
  54. except ExtractorError as e:
  55. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
  56. error = self._parse_json(e.cause.read().decode(), video_id)['error']
  57. error_code = error.get('code')
  58. if error_code == 'ASSET_PLAYBACK_INVALID_GEO_LOCATION':
  59. self.raise_geo_restricted(countries=self._GEO_COUNTRIES)
  60. elif error_code == 'SESSION_NOT_AUTHENTICATED':
  61. self.raise_login_required()
  62. raise ExtractorError(error['description'])
  63. raise
  64. items = data.get('streams', [])
  65. for item in items:
  66. video_url = item.get('url')
  67. if not video_url or video_url in format_urls:
  68. continue
  69. format_id = '%s-%s' % (protocol.lower(), item.get('type'))
  70. if not self._is_valid_url(video_url, video_id, format_id):
  71. continue
  72. format_urls.append(video_url)
  73. ext = determine_ext(video_url)
  74. if ext == 'f4m':
  75. formats.extend(self._extract_f4m_formats(
  76. video_url, video_id, f4m_id=format_id, fatal=False))
  77. elif ext == 'm3u8':
  78. if not data.get('drmProtected'):
  79. formats.extend(self._extract_m3u8_formats(
  80. video_url, video_id, 'mp4', live=is_live, m3u8_id=format_id, fatal=False))
  81. elif ext == 'mpd':
  82. formats.extend(self._extract_mpd_formats(
  83. video_url, video_id, format_id, fatal=False))
  84. elif ext == 'ism' or video_url.endswith('.ism/Manifest'):
  85. pass
  86. else:
  87. formats.append({
  88. 'url': video_url,
  89. 'format_id': format_id,
  90. })
  91. if not formats and data.get('drmProtected'):
  92. self.report_drm(video_id)
  93. thumbnails = [{
  94. 'id': type,
  95. 'url': thumb_url,
  96. } for type, thumb_url in (asset.get('images') or {}).items()]
  97. return {
  98. 'id': video_id,
  99. 'url': video_url,
  100. 'title': title,
  101. 'description': strip_or_none(asset.get('description')),
  102. 'thumbnails': thumbnails,
  103. 'timestamp': parse_iso8601(asset.get('live_broadcast_time') or asset.get('update_time')),
  104. 'duration': float_or_none(asset.get('accurateDuration') or asset.get('duration')),
  105. 'view_count': int_or_none(asset.get('views')),
  106. 'categories': asset.get('tags', '').split(','),
  107. 'formats': formats,
  108. 'is_live': is_live,
  109. }
  110. class TV2ArticleIE(InfoExtractor):
  111. _VALID_URL = r'https?://(?:www\.)?tv2\.no/(?!v(?:ideo)?\d*/)[^?#]+/(?P<id>\d+)'
  112. _TESTS = [{
  113. 'url': 'https://www.tv2.no/underholdning/forraeder/katarina-flatland-angrer-etter-forraeder-exit/15095188/',
  114. 'info_dict': {
  115. 'id': '15095188',
  116. 'title': 'Katarina Flatland angrer etter Forræder-exit',
  117. 'description': 'SANDEFJORD (TV 2): Katarina Flatland (33) måtte følge i sine fars fotspor, da hun ble forvist fra Forræder.',
  118. },
  119. 'playlist_count': 2,
  120. }, {
  121. 'url': 'http://www.tv2.no/a/6930542',
  122. 'only_matching': True,
  123. }]
  124. def _real_extract(self, url):
  125. playlist_id = self._match_id(url)
  126. webpage = self._download_webpage(url, playlist_id)
  127. # Old embed pattern (looks unused nowadays)
  128. assets = re.findall(r'data-assetid=["\'](\d+)', webpage)
  129. if not assets:
  130. # New embed pattern
  131. for v in re.findall(r'(?s)(?:TV2ContentboxVideo|TV2\.TV2Video)\(({.+?})\)', webpage):
  132. video = self._parse_json(
  133. v, playlist_id, transform_source=js_to_json, fatal=False)
  134. if not video:
  135. continue
  136. asset = video.get('assetId')
  137. if asset:
  138. assets.append(asset)
  139. entries = [
  140. self.url_result('http://www.tv2.no/v/%s' % asset_id, 'TV2')
  141. for asset_id in assets]
  142. title = remove_end(self._og_search_title(webpage), ' - TV2.no')
  143. description = remove_end(self._og_search_description(webpage), ' - TV2.no')
  144. return self.playlist_result(entries, playlist_id, title, description)
  145. class KatsomoIE(InfoExtractor):
  146. _VALID_URL = r'https?://(?:www\.)?(?:katsomo|mtv(uutiset)?)\.fi/(?:sarja/[0-9a-z-]+-\d+/[0-9a-z-]+-|(?:#!/)?jakso/(?:\d+/[^/]+/)?|video/prog)(?P<id>\d+)'
  147. _TESTS = [{
  148. 'url': 'https://www.mtv.fi/sarja/mtv-uutiset-live-33001002003/lahden-pelicans-teki-kovan-ratkaisun-ville-nieminen-pihalle-1181321',
  149. 'info_dict': {
  150. 'id': '1181321',
  151. 'ext': 'mp4',
  152. 'title': 'Lahden Pelicans teki kovan ratkaisun – Ville Nieminen pihalle',
  153. 'description': 'Päätöksen teki Pelicansin hallitus.',
  154. 'timestamp': 1575116484,
  155. 'upload_date': '20191130',
  156. 'duration': 37.12,
  157. 'view_count': int,
  158. 'categories': list,
  159. },
  160. 'params': {
  161. # m3u8 download
  162. 'skip_download': True,
  163. },
  164. }, {
  165. 'url': 'http://www.katsomo.fi/#!/jakso/33001005/studio55-fi/658521/jukka-kuoppamaki-tekee-yha-lauluja-vaikka-lentokoneessa',
  166. 'only_matching': True,
  167. }, {
  168. 'url': 'https://www.mtvuutiset.fi/video/prog1311159',
  169. 'only_matching': True,
  170. }, {
  171. 'url': 'https://www.katsomo.fi/#!/jakso/1311159',
  172. 'only_matching': True,
  173. }]
  174. _API_DOMAIN = 'api.katsomo.fi'
  175. _PROTOCOLS = ('HLS', 'MPD')
  176. _GEO_COUNTRIES = ['FI']
  177. def _real_extract(self, url):
  178. video_id = self._match_id(url)
  179. api_base = 'http://%s/api/web/asset/%s' % (self._API_DOMAIN, video_id)
  180. asset = self._download_json(
  181. api_base + '.json', video_id,
  182. 'Downloading metadata JSON')['asset']
  183. title = asset.get('subtitle') or asset['title']
  184. is_live = asset.get('live') is True
  185. formats = []
  186. format_urls = []
  187. for protocol in self._PROTOCOLS:
  188. try:
  189. data = self._download_json(
  190. api_base + '/play.json?protocol=%s&videoFormat=SMIL+ISMUSP' % protocol,
  191. video_id, 'Downloading play JSON')['playback']
  192. except ExtractorError as e:
  193. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
  194. error = self._parse_json(e.cause.read().decode(), video_id)['error']
  195. error_code = error.get('code')
  196. if error_code == 'ASSET_PLAYBACK_INVALID_GEO_LOCATION':
  197. self.raise_geo_restricted(countries=self._GEO_COUNTRIES)
  198. elif error_code == 'SESSION_NOT_AUTHENTICATED':
  199. self.raise_login_required()
  200. raise ExtractorError(error['description'])
  201. raise
  202. items = try_get(data, lambda x: x['items']['item'])
  203. if not items:
  204. continue
  205. if not isinstance(items, list):
  206. items = [items]
  207. for item in items:
  208. if not isinstance(item, dict):
  209. continue
  210. video_url = item.get('url')
  211. if not video_url or video_url in format_urls:
  212. continue
  213. format_id = '%s-%s' % (protocol.lower(), item.get('mediaFormat'))
  214. if not self._is_valid_url(video_url, video_id, format_id):
  215. continue
  216. format_urls.append(video_url)
  217. ext = determine_ext(video_url)
  218. if ext == 'f4m':
  219. formats.extend(self._extract_f4m_formats(
  220. video_url, video_id, f4m_id=format_id, fatal=False))
  221. elif ext == 'm3u8':
  222. if not data.get('drmProtected'):
  223. formats.extend(self._extract_m3u8_formats(
  224. video_url, video_id, 'mp4', live=is_live, m3u8_id=format_id, fatal=False))
  225. elif ext == 'mpd':
  226. formats.extend(self._extract_mpd_formats(
  227. video_url, video_id, format_id, fatal=False))
  228. elif ext == 'ism' or video_url.endswith('.ism/Manifest'):
  229. pass
  230. else:
  231. formats.append({
  232. 'url': video_url,
  233. 'format_id': format_id,
  234. 'tbr': int_or_none(item.get('bitrate')),
  235. 'filesize': int_or_none(item.get('fileSize')),
  236. })
  237. if not formats and data.get('drmProtected'):
  238. self.report_drm(video_id)
  239. thumbnails = [{
  240. 'id': thumbnail.get('@type'),
  241. 'url': thumbnail.get('url'),
  242. } for _, thumbnail in (asset.get('imageVersions') or {}).items()]
  243. return {
  244. 'id': video_id,
  245. 'url': video_url,
  246. 'title': title,
  247. 'description': strip_or_none(asset.get('description')),
  248. 'thumbnails': thumbnails,
  249. 'timestamp': parse_iso8601(asset.get('createTime')),
  250. 'duration': float_or_none(asset.get('accurateDuration') or asset.get('duration')),
  251. 'view_count': int_or_none(asset.get('views')),
  252. 'categories': asset.get('keywords', '').split(','),
  253. 'formats': formats,
  254. 'is_live': is_live,
  255. }
  256. class MTVUutisetArticleIE(InfoExtractor):
  257. _VALID_URL = r'https?://(?:www\.)mtvuutiset\.fi/artikkeli/[^/]+/(?P<id>\d+)'
  258. _TESTS = [{
  259. 'url': 'https://www.mtvuutiset.fi/artikkeli/tallaisia-vaurioita-viking-amorellassa-on-useamman-osaston-alla-vetta/7931384',
  260. 'info_dict': {
  261. 'id': '1311159',
  262. 'ext': 'mp4',
  263. 'title': 'Viking Amorellan matkustajien evakuointi on alkanut – tältä operaatio näyttää laivalla',
  264. 'description': 'Viking Amorellan matkustajien evakuointi on alkanut – tältä operaatio näyttää laivalla',
  265. 'timestamp': 1600608966,
  266. 'upload_date': '20200920',
  267. 'duration': 153.7886666,
  268. 'view_count': int,
  269. 'categories': list,
  270. },
  271. 'params': {
  272. # m3u8 download
  273. 'skip_download': True,
  274. },
  275. }, {
  276. # multiple Youtube embeds
  277. 'url': 'https://www.mtvuutiset.fi/artikkeli/50-vuotta-subarun-vastaiskua/6070962',
  278. 'only_matching': True,
  279. }]
  280. def _real_extract(self, url):
  281. article_id = self._match_id(url)
  282. article = self._download_json(
  283. 'http://api.mtvuutiset.fi/mtvuutiset/api/json/' + article_id,
  284. article_id)
  285. def entries():
  286. for video in (article.get('videos') or []):
  287. video_type = video.get('videotype')
  288. video_url = video.get('url')
  289. if not (video_url and video_type in ('katsomo', 'youtube')):
  290. continue
  291. yield self.url_result(
  292. video_url, video_type.capitalize(), video.get('video_id'))
  293. return self.playlist_result(
  294. entries(), article_id, article.get('title'), article.get('description'))