]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/tv2.py
New upstream version 2020.06.16.1
[youtubedl] / youtube_dl / extractor / tv2.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..compat import compat_HTTPError
8 from ..utils import (
9 determine_ext,
10 ExtractorError,
11 int_or_none,
12 float_or_none,
13 js_to_json,
14 parse_iso8601,
15 remove_end,
16 strip_or_none,
17 try_get,
18 )
19
20
21 class TV2IE(InfoExtractor):
22 _VALID_URL = r'https?://(?:www\.)?tv2\.no/v/(?P<id>\d+)'
23 _TEST = {
24 'url': 'http://www.tv2.no/v/916509/',
25 'info_dict': {
26 'id': '916509',
27 'ext': 'flv',
28 'title': 'Se Frode Gryttens hyllest av Steven Gerrard',
29 'description': 'TV 2 Sportens huspoet tar avskjed med Liverpools kaptein Steven Gerrard.',
30 'timestamp': 1431715610,
31 'upload_date': '20150515',
32 'duration': 156.967,
33 'view_count': int,
34 'categories': list,
35 },
36 }
37 _API_DOMAIN = 'sumo.tv2.no'
38 _PROTOCOLS = ('HDS', 'HLS', 'DASH')
39 _GEO_COUNTRIES = ['NO']
40
41 def _real_extract(self, url):
42 video_id = self._match_id(url)
43 api_base = 'http://%s/api/web/asset/%s' % (self._API_DOMAIN, video_id)
44
45 formats = []
46 format_urls = []
47 for protocol in self._PROTOCOLS:
48 try:
49 data = self._download_json(
50 api_base + '/play.json?protocol=%s&videoFormat=SMIL+ISMUSP' % protocol,
51 video_id, 'Downloading play JSON')['playback']
52 except ExtractorError as e:
53 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
54 error = self._parse_json(e.cause.read().decode(), video_id)['error']
55 error_code = error.get('code')
56 if error_code == 'ASSET_PLAYBACK_INVALID_GEO_LOCATION':
57 self.raise_geo_restricted(countries=self._GEO_COUNTRIES)
58 elif error_code == 'SESSION_NOT_AUTHENTICATED':
59 self.raise_login_required()
60 raise ExtractorError(error['description'])
61 raise
62 items = try_get(data, lambda x: x['items']['item'])
63 if not items:
64 continue
65 if not isinstance(items, list):
66 items = [items]
67 for item in items:
68 if not isinstance(item, dict):
69 continue
70 video_url = item.get('url')
71 if not video_url or video_url in format_urls:
72 continue
73 format_id = '%s-%s' % (protocol.lower(), item.get('mediaFormat'))
74 if not self._is_valid_url(video_url, video_id, format_id):
75 continue
76 format_urls.append(video_url)
77 ext = determine_ext(video_url)
78 if ext == 'f4m':
79 formats.extend(self._extract_f4m_formats(
80 video_url, video_id, f4m_id=format_id, fatal=False))
81 elif ext == 'm3u8':
82 if not data.get('drmProtected'):
83 formats.extend(self._extract_m3u8_formats(
84 video_url, video_id, 'mp4', entry_protocol='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
102 asset = self._download_json(
103 api_base + '.json', video_id,
104 'Downloading metadata JSON')['asset']
105 title = asset['title']
106
107 thumbnails = [{
108 'id': thumbnail.get('@type'),
109 'url': thumbnail.get('url'),
110 } for _, thumbnail in (asset.get('imageVersions') or {}).items()]
111
112 return {
113 'id': video_id,
114 'url': video_url,
115 'title': title,
116 'description': strip_or_none(asset.get('description')),
117 'thumbnails': thumbnails,
118 'timestamp': parse_iso8601(asset.get('createTime')),
119 'duration': float_or_none(asset.get('accurateDuration') or asset.get('duration')),
120 'view_count': int_or_none(asset.get('views')),
121 'categories': asset.get('keywords', '').split(','),
122 'formats': formats,
123 }
124
125
126 class TV2ArticleIE(InfoExtractor):
127 _VALID_URL = r'https?://(?:www\.)?tv2\.no/(?:a|\d{4}/\d{2}/\d{2}(/[^/]+)+)/(?P<id>\d+)'
128 _TESTS = [{
129 'url': 'http://www.tv2.no/2015/05/16/nyheter/alesund/krim/pingvin/6930542',
130 'info_dict': {
131 'id': '6930542',
132 'title': 'Russen hetses etter pingvintyveri - innrømmer å ha åpnet luken på buret',
133 'description': 'De fire siktede nekter fortsatt for å ha stjålet pingvinbabyene, men innrømmer å ha åpnet luken til de små kyllingene.',
134 },
135 'playlist_count': 2,
136 }, {
137 'url': 'http://www.tv2.no/a/6930542',
138 'only_matching': True,
139 }]
140
141 def _real_extract(self, url):
142 playlist_id = self._match_id(url)
143
144 webpage = self._download_webpage(url, playlist_id)
145
146 # Old embed pattern (looks unused nowadays)
147 assets = re.findall(r'data-assetid=["\'](\d+)', webpage)
148
149 if not assets:
150 # New embed pattern
151 for v in re.findall(r'(?s)TV2ContentboxVideo\(({.+?})\)', webpage):
152 video = self._parse_json(
153 v, playlist_id, transform_source=js_to_json, fatal=False)
154 if not video:
155 continue
156 asset = video.get('assetId')
157 if asset:
158 assets.append(asset)
159
160 entries = [
161 self.url_result('http://www.tv2.no/v/%s' % asset_id, 'TV2')
162 for asset_id in assets]
163
164 title = remove_end(self._og_search_title(webpage), ' - TV2.no')
165 description = remove_end(self._og_search_description(webpage), ' - TV2.no')
166
167 return self.playlist_result(entries, playlist_id, title, description)
168
169
170 class KatsomoIE(TV2IE):
171 _VALID_URL = r'https?://(?:www\.)?(?:katsomo|mtv)\.fi/(?:#!/)?(?:[^/]+/[0-9a-z-]+-\d+/[0-9a-z-]+-|[^/]+/\d+/[^/]+/)(?P<id>\d+)'
172 _TEST = {
173 'url': 'https://www.mtv.fi/sarja/mtv-uutiset-live-33001002003/lahden-pelicans-teki-kovan-ratkaisun-ville-nieminen-pihalle-1181321',
174 'info_dict': {
175 'id': '1181321',
176 'ext': 'mp4',
177 'title': 'MTV Uutiset Live',
178 'description': 'Päätöksen teki Pelicansin hallitus.',
179 'timestamp': 1575116484,
180 'upload_date': '20191130',
181 'duration': 37.12,
182 'view_count': int,
183 'categories': list,
184 },
185 'params': {
186 # m3u8 download
187 'skip_download': True,
188 },
189 }
190 _API_DOMAIN = 'api.katsomo.fi'
191 _PROTOCOLS = ('HLS', 'MPD')
192 _GEO_COUNTRIES = ['FI']