logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

tv2.py (9907B)


  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import compat_HTTPError
  6. from ..utils import (
  7. determine_ext,
  8. ExtractorError,
  9. int_or_none,
  10. float_or_none,
  11. js_to_json,
  12. parse_iso8601,
  13. remove_end,
  14. strip_or_none,
  15. try_get,
  16. )
  17. class TV2IE(InfoExtractor):
  18. _VALID_URL = r'https?://(?:www\.)?tv2\.no/v/(?P<id>\d+)'
  19. _TESTS = [{
  20. 'url': 'http://www.tv2.no/v/916509/',
  21. 'info_dict': {
  22. 'id': '916509',
  23. 'ext': 'flv',
  24. 'title': 'Se Frode Gryttens hyllest av Steven Gerrard',
  25. 'description': 'TV 2 Sportens huspoet tar avskjed med Liverpools kaptein Steven Gerrard.',
  26. 'timestamp': 1431715610,
  27. 'upload_date': '20150515',
  28. 'duration': 156.967,
  29. 'view_count': int,
  30. 'categories': list,
  31. },
  32. }]
  33. _API_DOMAIN = 'sumo.tv2.no'
  34. _PROTOCOLS = ('HDS', 'HLS', 'DASH')
  35. _GEO_COUNTRIES = ['NO']
  36. def _real_extract(self, url):
  37. video_id = self._match_id(url)
  38. api_base = 'http://%s/api/web/asset/%s' % (self._API_DOMAIN, video_id)
  39. asset = self._download_json(
  40. api_base + '.json', video_id,
  41. 'Downloading metadata JSON')['asset']
  42. title = asset.get('subtitle') or asset['title']
  43. is_live = asset.get('live') is True
  44. formats = []
  45. format_urls = []
  46. for protocol in self._PROTOCOLS:
  47. try:
  48. data = self._download_json(
  49. api_base + '/play.json?protocol=%s&videoFormat=SMIL+ISMUSP' % protocol,
  50. video_id, 'Downloading play JSON')['playback']
  51. except ExtractorError as e:
  52. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
  53. error = self._parse_json(e.cause.read().decode(), video_id)['error']
  54. error_code = error.get('code')
  55. if error_code == 'ASSET_PLAYBACK_INVALID_GEO_LOCATION':
  56. self.raise_geo_restricted(countries=self._GEO_COUNTRIES)
  57. elif error_code == 'SESSION_NOT_AUTHENTICATED':
  58. self.raise_login_required()
  59. raise ExtractorError(error['description'])
  60. raise
  61. items = try_get(data, lambda x: x['items']['item'])
  62. if not items:
  63. continue
  64. if not isinstance(items, list):
  65. items = [items]
  66. for item in items:
  67. if not isinstance(item, dict):
  68. continue
  69. video_url = item.get('url')
  70. if not video_url or video_url in format_urls:
  71. continue
  72. format_id = '%s-%s' % (protocol.lower(), item.get('mediaFormat'))
  73. if not self._is_valid_url(video_url, video_id, format_id):
  74. continue
  75. format_urls.append(video_url)
  76. ext = determine_ext(video_url)
  77. if ext == 'f4m':
  78. formats.extend(self._extract_f4m_formats(
  79. video_url, video_id, f4m_id=format_id, fatal=False))
  80. elif ext == 'm3u8':
  81. if not data.get('drmProtected'):
  82. formats.extend(self._extract_m3u8_formats(
  83. video_url, video_id, 'mp4',
  84. 'm3u8' if is_live else 'm3u8_native',
  85. m3u8_id=format_id, fatal=False))
  86. elif ext == 'mpd':
  87. formats.extend(self._extract_mpd_formats(
  88. video_url, video_id, format_id, fatal=False))
  89. elif ext == 'ism' or video_url.endswith('.ism/Manifest'):
  90. pass
  91. else:
  92. formats.append({
  93. 'url': video_url,
  94. 'format_id': format_id,
  95. 'tbr': int_or_none(item.get('bitrate')),
  96. 'filesize': int_or_none(item.get('fileSize')),
  97. })
  98. if not formats and data.get('drmProtected'):
  99. raise ExtractorError('This video is DRM protected.', expected=True)
  100. self._sort_formats(formats)
  101. thumbnails = [{
  102. 'id': thumbnail.get('@type'),
  103. 'url': thumbnail.get('url'),
  104. } for _, thumbnail in (asset.get('imageVersions') or {}).items()]
  105. return {
  106. 'id': video_id,
  107. 'url': video_url,
  108. 'title': self._live_title(title) if is_live else title,
  109. 'description': strip_or_none(asset.get('description')),
  110. 'thumbnails': thumbnails,
  111. 'timestamp': parse_iso8601(asset.get('createTime')),
  112. 'duration': float_or_none(asset.get('accurateDuration') or asset.get('duration')),
  113. 'view_count': int_or_none(asset.get('views')),
  114. 'categories': asset.get('keywords', '').split(','),
  115. 'formats': formats,
  116. 'is_live': is_live,
  117. }
  118. class TV2ArticleIE(InfoExtractor):
  119. _VALID_URL = r'https?://(?:www\.)?tv2\.no/(?:a|\d{4}/\d{2}/\d{2}(/[^/]+)+)/(?P<id>\d+)'
  120. _TESTS = [{
  121. 'url': 'http://www.tv2.no/2015/05/16/nyheter/alesund/krim/pingvin/6930542',
  122. 'info_dict': {
  123. 'id': '6930542',
  124. 'title': 'Russen hetses etter pingvintyveri - innrømmer å ha åpnet luken på buret',
  125. 'description': 'De fire siktede nekter fortsatt for å ha stjålet pingvinbabyene, men innrømmer å ha åpnet luken til de små kyllingene.',
  126. },
  127. 'playlist_count': 2,
  128. }, {
  129. 'url': 'http://www.tv2.no/a/6930542',
  130. 'only_matching': True,
  131. }]
  132. def _real_extract(self, url):
  133. playlist_id = self._match_id(url)
  134. webpage = self._download_webpage(url, playlist_id)
  135. # Old embed pattern (looks unused nowadays)
  136. assets = re.findall(r'data-assetid=["\'](\d+)', webpage)
  137. if not assets:
  138. # New embed pattern
  139. for v in re.findall(r'(?s)TV2ContentboxVideo\(({.+?})\)', webpage):
  140. video = self._parse_json(
  141. v, playlist_id, transform_source=js_to_json, fatal=False)
  142. if not video:
  143. continue
  144. asset = video.get('assetId')
  145. if asset:
  146. assets.append(asset)
  147. entries = [
  148. self.url_result('http://www.tv2.no/v/%s' % asset_id, 'TV2')
  149. for asset_id in assets]
  150. title = remove_end(self._og_search_title(webpage), ' - TV2.no')
  151. description = remove_end(self._og_search_description(webpage), ' - TV2.no')
  152. return self.playlist_result(entries, playlist_id, title, description)
  153. class KatsomoIE(TV2IE):
  154. _VALID_URL = r'https?://(?:www\.)?(?:katsomo|mtv(uutiset)?)\.fi/(?:sarja/[0-9a-z-]+-\d+/[0-9a-z-]+-|(?:#!/)?jakso/(?:\d+/[^/]+/)?|video/prog)(?P<id>\d+)'
  155. _TESTS = [{
  156. 'url': 'https://www.mtv.fi/sarja/mtv-uutiset-live-33001002003/lahden-pelicans-teki-kovan-ratkaisun-ville-nieminen-pihalle-1181321',
  157. 'info_dict': {
  158. 'id': '1181321',
  159. 'ext': 'mp4',
  160. 'title': 'Lahden Pelicans teki kovan ratkaisun – Ville Nieminen pihalle',
  161. 'description': 'Päätöksen teki Pelicansin hallitus.',
  162. 'timestamp': 1575116484,
  163. 'upload_date': '20191130',
  164. 'duration': 37.12,
  165. 'view_count': int,
  166. 'categories': list,
  167. },
  168. 'params': {
  169. # m3u8 download
  170. 'skip_download': True,
  171. },
  172. }, {
  173. 'url': 'http://www.katsomo.fi/#!/jakso/33001005/studio55-fi/658521/jukka-kuoppamaki-tekee-yha-lauluja-vaikka-lentokoneessa',
  174. 'only_matching': True,
  175. }, {
  176. 'url': 'https://www.mtvuutiset.fi/video/prog1311159',
  177. 'only_matching': True,
  178. }, {
  179. 'url': 'https://www.katsomo.fi/#!/jakso/1311159',
  180. 'only_matching': True,
  181. }]
  182. _API_DOMAIN = 'api.katsomo.fi'
  183. _PROTOCOLS = ('HLS', 'MPD')
  184. _GEO_COUNTRIES = ['FI']
  185. class MTVUutisetArticleIE(InfoExtractor):
  186. _VALID_URL = r'https?://(?:www\.)mtvuutiset\.fi/artikkeli/[^/]+/(?P<id>\d+)'
  187. _TESTS = [{
  188. 'url': 'https://www.mtvuutiset.fi/artikkeli/tallaisia-vaurioita-viking-amorellassa-on-useamman-osaston-alla-vetta/7931384',
  189. 'info_dict': {
  190. 'id': '1311159',
  191. 'ext': 'mp4',
  192. 'title': 'Viking Amorellan matkustajien evakuointi on alkanut – tältä operaatio näyttää laivalla',
  193. 'description': 'Viking Amorellan matkustajien evakuointi on alkanut – tältä operaatio näyttää laivalla',
  194. 'timestamp': 1600608966,
  195. 'upload_date': '20200920',
  196. 'duration': 153.7886666,
  197. 'view_count': int,
  198. 'categories': list,
  199. },
  200. 'params': {
  201. # m3u8 download
  202. 'skip_download': True,
  203. },
  204. }, {
  205. # multiple Youtube embeds
  206. 'url': 'https://www.mtvuutiset.fi/artikkeli/50-vuotta-subarun-vastaiskua/6070962',
  207. 'only_matching': True,
  208. }]
  209. def _real_extract(self, url):
  210. article_id = self._match_id(url)
  211. article = self._download_json(
  212. 'http://api.mtvuutiset.fi/mtvuutiset/api/json/' + article_id,
  213. article_id)
  214. def entries():
  215. for video in (article.get('videos') or []):
  216. video_type = video.get('videotype')
  217. video_url = video.get('url')
  218. if not (video_url and video_type in ('katsomo', 'youtube')):
  219. continue
  220. yield self.url_result(
  221. video_url, video_type.capitalize(), video.get('video_id'))
  222. return self.playlist_result(
  223. entries(), article_id, article.get('title'), article.get('description'))