tv2.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import re
  2. from .common import InfoExtractor
  3. from ..networking.exceptions import HTTPError
  4. from ..utils import (
  5. ExtractorError,
  6. determine_ext,
  7. float_or_none,
  8. int_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(f'https://api.sumo.tv2.no/play/{video_id}?stream={protocol}',
  51. video_id, 'Downloading playabck JSON',
  52. headers={'content-type': 'application/json'},
  53. data=b'{"device":{"id":"1-1-1","name":"Nettleser (HTML)"}}')['playback']
  54. except ExtractorError as e:
  55. if isinstance(e.cause, HTTPError) and e.cause.status == 401:
  56. error = self._parse_json(e.cause.response.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 = '{}-{}'.format(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': thumb_type,
  95. 'url': thumb_url,
  96. } for thumb_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(f'http://www.tv2.no/v/{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. _WORKING = False
  147. _VALID_URL = r'https?://(?:www\.)?(?:katsomo|mtv(uutiset)?)\.fi/(?:sarja/[0-9a-z-]+-\d+/[0-9a-z-]+-|(?:#!/)?jakso/(?:\d+/[^/]+/)?|video/prog)(?P<id>\d+)'
  148. _TESTS = [{
  149. 'url': 'https://www.mtv.fi/sarja/mtv-uutiset-live-33001002003/lahden-pelicans-teki-kovan-ratkaisun-ville-nieminen-pihalle-1181321',
  150. 'info_dict': {
  151. 'id': '1181321',
  152. 'ext': 'mp4',
  153. 'title': 'Lahden Pelicans teki kovan ratkaisun – Ville Nieminen pihalle',
  154. 'description': 'Päätöksen teki Pelicansin hallitus.',
  155. 'timestamp': 1575116484,
  156. 'upload_date': '20191130',
  157. 'duration': 37.12,
  158. 'view_count': int,
  159. 'categories': list,
  160. },
  161. 'params': {
  162. # m3u8 download
  163. 'skip_download': True,
  164. },
  165. }, {
  166. 'url': 'http://www.katsomo.fi/#!/jakso/33001005/studio55-fi/658521/jukka-kuoppamaki-tekee-yha-lauluja-vaikka-lentokoneessa',
  167. 'only_matching': True,
  168. }, {
  169. 'url': 'https://www.mtvuutiset.fi/video/prog1311159',
  170. 'only_matching': True,
  171. }, {
  172. 'url': 'https://www.katsomo.fi/#!/jakso/1311159',
  173. 'only_matching': True,
  174. }]
  175. _API_DOMAIN = 'api.katsomo.fi'
  176. _PROTOCOLS = ('HLS', 'MPD')
  177. _GEO_COUNTRIES = ['FI']
  178. def _real_extract(self, url):
  179. video_id = self._match_id(url)
  180. api_base = f'http://{self._API_DOMAIN}/api/web/asset/{video_id}'
  181. asset = self._download_json(
  182. api_base + '.json', video_id,
  183. 'Downloading metadata JSON')['asset']
  184. title = asset.get('subtitle') or asset['title']
  185. is_live = asset.get('live') is True
  186. formats = []
  187. format_urls = []
  188. for protocol in self._PROTOCOLS:
  189. try:
  190. data = self._download_json(
  191. api_base + f'/play.json?protocol={protocol}&videoFormat=SMIL+ISMUSP',
  192. video_id, 'Downloading play JSON')['playback']
  193. except ExtractorError as e:
  194. if isinstance(e.cause, HTTPError) and e.cause.status == 401:
  195. error = self._parse_json(e.cause.response.read().decode(), video_id)['error']
  196. error_code = error.get('code')
  197. if error_code == 'ASSET_PLAYBACK_INVALID_GEO_LOCATION':
  198. self.raise_geo_restricted(countries=self._GEO_COUNTRIES)
  199. elif error_code == 'SESSION_NOT_AUTHENTICATED':
  200. self.raise_login_required()
  201. raise ExtractorError(error['description'])
  202. raise
  203. items = try_get(data, lambda x: x['items']['item'])
  204. if not items:
  205. continue
  206. if not isinstance(items, list):
  207. items = [items]
  208. for item in items:
  209. if not isinstance(item, dict):
  210. continue
  211. video_url = item.get('url')
  212. if not video_url or video_url in format_urls:
  213. continue
  214. format_id = '{}-{}'.format(protocol.lower(), item.get('mediaFormat'))
  215. if not self._is_valid_url(video_url, video_id, format_id):
  216. continue
  217. format_urls.append(video_url)
  218. ext = determine_ext(video_url)
  219. if ext == 'f4m':
  220. formats.extend(self._extract_f4m_formats(
  221. video_url, video_id, f4m_id=format_id, fatal=False))
  222. elif ext == 'm3u8':
  223. if not data.get('drmProtected'):
  224. formats.extend(self._extract_m3u8_formats(
  225. video_url, video_id, 'mp4', live=is_live, m3u8_id=format_id, fatal=False))
  226. elif ext == 'mpd':
  227. formats.extend(self._extract_mpd_formats(
  228. video_url, video_id, format_id, fatal=False))
  229. elif ext == 'ism' or video_url.endswith('.ism/Manifest'):
  230. pass
  231. else:
  232. formats.append({
  233. 'url': video_url,
  234. 'format_id': format_id,
  235. 'tbr': int_or_none(item.get('bitrate')),
  236. 'filesize': int_or_none(item.get('fileSize')),
  237. })
  238. if not formats and data.get('drmProtected'):
  239. self.report_drm(video_id)
  240. thumbnails = [{
  241. 'id': thumbnail.get('@type'),
  242. 'url': thumbnail.get('url'),
  243. } for _, thumbnail in (asset.get('imageVersions') or {}).items()]
  244. return {
  245. 'id': video_id,
  246. 'url': video_url,
  247. 'title': title,
  248. 'description': strip_or_none(asset.get('description')),
  249. 'thumbnails': thumbnails,
  250. 'timestamp': parse_iso8601(asset.get('createTime')),
  251. 'duration': float_or_none(asset.get('accurateDuration') or asset.get('duration')),
  252. 'view_count': int_or_none(asset.get('views')),
  253. 'categories': asset.get('keywords', '').split(','),
  254. 'formats': formats,
  255. 'is_live': is_live,
  256. }
  257. class MTVUutisetArticleIE(InfoExtractor):
  258. _WORKING = False
  259. _VALID_URL = r'https?://(?:www\.)mtvuutiset\.fi/artikkeli/[^/]+/(?P<id>\d+)'
  260. _TESTS = [{
  261. 'url': 'https://www.mtvuutiset.fi/artikkeli/tallaisia-vaurioita-viking-amorellassa-on-useamman-osaston-alla-vetta/7931384',
  262. 'info_dict': {
  263. 'id': '1311159',
  264. 'ext': 'mp4',
  265. 'title': 'Viking Amorellan matkustajien evakuointi on alkanut – tältä operaatio näyttää laivalla',
  266. 'description': 'Viking Amorellan matkustajien evakuointi on alkanut – tältä operaatio näyttää laivalla',
  267. 'timestamp': 1600608966,
  268. 'upload_date': '20200920',
  269. 'duration': 153.7886666,
  270. 'view_count': int,
  271. 'categories': list,
  272. },
  273. 'params': {
  274. # m3u8 download
  275. 'skip_download': True,
  276. },
  277. }, {
  278. # multiple Youtube embeds
  279. 'url': 'https://www.mtvuutiset.fi/artikkeli/50-vuotta-subarun-vastaiskua/6070962',
  280. 'only_matching': True,
  281. }]
  282. def _real_extract(self, url):
  283. article_id = self._match_id(url)
  284. article = self._download_json(
  285. 'http://api.mtvuutiset.fi/mtvuutiset/api/json/' + article_id,
  286. article_id)
  287. def entries():
  288. for video in (article.get('videos') or []):
  289. video_type = video.get('videotype')
  290. video_url = video.get('url')
  291. if not (video_url and video_type in ('katsomo', 'youtube')):
  292. continue
  293. yield self.url_result(
  294. video_url, video_type.capitalize(), video.get('video_id'))
  295. return self.playlist_result(
  296. entries(), article_id, article.get('title'), article.get('description'))