]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/tvplay.py
Improve URL extraction
[yt-dlp.git] / youtube_dl / extractor / tvplay.py
CommitLineData
1220352f
S
1# coding: utf-8
2from __future__ import unicode_literals
3
4import re
5
6from .common import InfoExtractor
f0d31c62 7from ..compat import (
3859ebee 8 compat_HTTPError,
f0d31c62
S
9 compat_str,
10 compat_urlparse,
11)
1220352f 12from ..utils import (
3859ebee
S
13 determine_ext,
14 ExtractorError,
15 int_or_none,
1220352f
S
16 parse_iso8601,
17 qualities,
dc76eef0 18 smuggle_url,
502d87c5 19 try_get,
dc76eef0 20 unsmuggle_url,
4a7a5e41 21 update_url_query,
3052a30d 22 url_or_none,
1220352f
S
23)
24
25
26class TVPlayIE(InfoExtractor):
6e7e4a6e
S
27 IE_NAME = 'mtg'
28 IE_DESC = 'MTG services'
29 _VALID_URL = r'''(?x)
30 (?:
31 mtg:|
32 https?://
33 (?:www\.)?
34 (?:
35 tvplay(?:\.skaties)?\.lv/parraides|
36 (?:tv3play|play\.tv3)\.lt/programos|
37 tv3play(?:\.tv3)?\.ee/sisu|
38 (?:tv(?:3|6|8|10)play|viafree)\.se/program|
39 (?:(?:tv3play|viasat4play|tv6play|viafree)\.no|(?:tv3play|viafree)\.dk)/programmer|
40 play\.novatv\.bg/programi
41 )
42 /(?:[^/]+/)+
43 )
44 (?P<id>\d+)
45 '''
1220352f
S
46 _TESTS = [
47 {
48 'url': 'http://www.tvplay.lv/parraides/vinas-melo-labak/418113?autostart=true',
4a7a5e41 49 'md5': 'a1612fe0849455423ad8718fe049be21',
1220352f
S
50 'info_dict': {
51 'id': '418113',
4a7a5e41 52 'ext': 'mp4',
1220352f
S
53 'title': 'Kādi ir īri? - Viņas melo labāk',
54 'description': 'Baiba apsmej īrus, kādi tie ir un ko viņi dara.',
5ca968d0
S
55 'series': 'Viņas melo labāk',
56 'season': '2.sezona',
57 'season_number': 2,
1220352f
S
58 'duration': 25,
59 'timestamp': 1406097056,
60 'upload_date': '20140723',
61 },
1220352f 62 },
eef93b09 63 {
22d36283 64 'url': 'http://play.tv3.lt/programos/moterys-meluoja-geriau/409229?autostart=true',
eef93b09
NJ
65 'info_dict': {
66 'id': '409229',
67 'ext': 'flv',
68 'title': 'Moterys meluoja geriau',
69 'description': 'md5:9aec0fc68e2cbc992d2a140bd41fa89e',
5ca968d0
S
70 'series': 'Moterys meluoja geriau',
71 'episode_number': 47,
72 'season': '1 sezonas',
73 'season_number': 1,
eef93b09
NJ
74 'duration': 1330,
75 'timestamp': 1403769181,
76 'upload_date': '20140626',
77 },
78 'params': {
79 # rtmp download
80 'skip_download': True,
81 },
82 },
83 {
84 'url': 'http://www.tv3play.ee/sisu/kodu-keset-linna/238551?autostart=true',
85 'info_dict': {
86 'id': '238551',
87 'ext': 'flv',
88 'title': 'Kodu keset linna 398537',
89 'description': 'md5:7df175e3c94db9e47c0d81ffa5d68701',
90 'duration': 1257,
91 'timestamp': 1292449761,
92 'upload_date': '20101215',
93 },
94 'params': {
95 # rtmp download
96 'skip_download': True,
97 },
98 },
99 {
100 'url': 'http://www.tv3play.se/program/husraddarna/395385?autostart=true',
101 'info_dict': {
102 'id': '395385',
4a7a5e41 103 'ext': 'mp4',
eef93b09
NJ
104 'title': 'Husräddarna S02E07',
105 'description': 'md5:f210c6c89f42d4fc39faa551be813777',
106 'duration': 2574,
107 'timestamp': 1400596321,
108 'upload_date': '20140520',
109 },
110 'params': {
eef93b09
NJ
111 'skip_download': True,
112 },
113 },
114 {
115 'url': 'http://www.tv6play.se/program/den-sista-dokusapan/266636?autostart=true',
116 'info_dict': {
117 'id': '266636',
4a7a5e41 118 'ext': 'mp4',
eef93b09
NJ
119 'title': 'Den sista dokusåpan S01E08',
120 'description': 'md5:295be39c872520221b933830f660b110',
121 'duration': 1492,
122 'timestamp': 1330522854,
123 'upload_date': '20120229',
b1ac38fa 124 'age_limit': 18,
eef93b09
NJ
125 },
126 'params': {
eef93b09
NJ
127 'skip_download': True,
128 },
129 },
130 {
131 'url': 'http://www.tv8play.se/program/antikjakten/282756?autostart=true',
132 'info_dict': {
133 'id': '282756',
4a7a5e41 134 'ext': 'mp4',
eef93b09
NJ
135 'title': 'Antikjakten S01E10',
136 'description': 'md5:1b201169beabd97e20c5ad0ad67b13b8',
137 'duration': 2646,
138 'timestamp': 1348575868,
139 'upload_date': '20120925',
140 },
141 'params': {
eef93b09
NJ
142 'skip_download': True,
143 },
144 },
145 {
146 'url': 'http://www.tv3play.no/programmer/anna-anka-soker-assistent/230898?autostart=true',
147 'info_dict': {
148 'id': '230898',
4a7a5e41 149 'ext': 'mp4',
eef93b09
NJ
150 'title': 'Anna Anka søker assistent - Ep. 8',
151 'description': 'md5:f80916bf5bbe1c5f760d127f8dd71474',
152 'duration': 2656,
153 'timestamp': 1277720005,
154 'upload_date': '20100628',
155 },
156 'params': {
eef93b09
NJ
157 'skip_download': True,
158 },
159 },
160 {
161 'url': 'http://www.viasat4play.no/programmer/budbringerne/21873?autostart=true',
162 'info_dict': {
163 'id': '21873',
4a7a5e41 164 'ext': 'mp4',
eef93b09
NJ
165 'title': 'Budbringerne program 10',
166 'description': 'md5:4db78dc4ec8a85bb04fd322a3ee5092d',
167 'duration': 1297,
168 'timestamp': 1254205102,
169 'upload_date': '20090929',
170 },
171 'params': {
eef93b09
NJ
172 'skip_download': True,
173 },
174 },
175 {
176 'url': 'http://www.tv6play.no/programmer/hotelinspektor-alex-polizzi/361883?autostart=true',
177 'info_dict': {
178 'id': '361883',
4a7a5e41 179 'ext': 'mp4',
eef93b09
NJ
180 'title': 'Hotelinspektør Alex Polizzi - Ep. 10',
181 'description': 'md5:3ecf808db9ec96c862c8ecb3a7fdaf81',
182 'duration': 2594,
183 'timestamp': 1393236292,
184 'upload_date': '20140224',
185 },
186 'params': {
eef93b09
NJ
187 'skip_download': True,
188 },
189 },
755a9d3d
NJ
190 {
191 'url': 'http://play.novatv.bg/programi/zdravei-bulgariya/624952?autostart=true',
192 'info_dict': {
193 'id': '624952',
194 'ext': 'flv',
195 'title': 'Здравей, България (12.06.2015 г.) ',
196 'description': 'md5:99f3700451ac5bb71a260268b8daefd7',
197 'duration': 8838,
198 'timestamp': 1434100372,
199 'upload_date': '20150612',
200 },
201 'params': {
202 # rtmp download
203 'skip_download': True,
204 },
205 },
4a7a5e41
RA
206 {
207 'url': 'http://tvplay.skaties.lv/parraides/vinas-melo-labak/418113?autostart=true',
208 'only_matching': True,
209 },
502d87c5
S
210 {
211 # views is null
212 'url': 'http://tvplay.skaties.lv/parraides/tv3-zinas/760183',
213 'only_matching': True,
214 },
4a7a5e41
RA
215 {
216 'url': 'http://tv3play.tv3.ee/sisu/kodu-keset-linna/238551?autostart=true',
217 'only_matching': True,
6e7e4a6e
S
218 },
219 {
220 'url': 'http://www.viafree.se/program/underhallning/i-like-radio-live/sasong-1/676869',
221 'only_matching': True,
222 },
223 {
224 'url': 'mtg:418113',
225 'only_matching': True,
4a7a5e41 226 }
1220352f
S
227 ]
228
229 def _real_extract(self, url):
dc76eef0 230 url, smuggled_data = unsmuggle_url(url, {})
5f95927a
S
231 self._initialize_geo_bypass({
232 'countries': smuggled_data.get('geo_countries'),
233 })
dc76eef0 234
73689daf 235 video_id = self._match_id(url)
be61efdf
RA
236 geo_country = self._search_regex(
237 r'https?://[^/]+\.([a-z]{2})', url,
238 'geo country', default=None)
239 if geo_country:
5f95927a 240 self._initialize_geo_bypass({'countries': [geo_country.upper()]})
1220352f 241 video = self._download_json(
6e7e4a6e 242 'http://playapi.mtgx.tv/v3/videos/%s' % video_id, video_id, 'Downloading video JSON')
1220352f 243
4a7a5e41
RA
244 title = video['title']
245
3859ebee
S
246 try:
247 streams = self._download_json(
6e7e4a6e 248 'http://playapi.mtgx.tv/v3/videos/stream/%s' % video_id,
3859ebee
S
249 video_id, 'Downloading streams JSON')
250 except ExtractorError as e:
251 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
252 msg = self._parse_json(e.cause.read().decode('utf-8'), video_id)
253 raise ExtractorError(msg['msg'], expected=True)
254 raise
1220352f
S
255
256 quality = qualities(['hls', 'medium', 'high'])
257 formats = []
4a7a5e41 258 for format_id, video_url in streams.get('streams', {}).items():
3052a30d
S
259 video_url = url_or_none(video_url)
260 if not video_url:
1220352f 261 continue
4a7a5e41
RA
262 ext = determine_ext(video_url)
263 if ext == 'f4m':
73689daf 264 formats.extend(self._extract_f4m_formats(
4a7a5e41
RA
265 update_url_query(video_url, {
266 'hdcore': '3.5.0',
267 'plugin': 'aasp-3.5.0.151.81'
268 }), video_id, f4m_id='hds', fatal=False))
269 elif ext == 'm3u8':
270 formats.extend(self._extract_m3u8_formats(
271 video_url, video_id, 'mp4', 'm3u8_native',
272 m3u8_id='hls', fatal=False))
1220352f 273 else:
4a7a5e41
RA
274 fmt = {
275 'format_id': format_id,
276 'quality': quality(format_id),
277 'ext': ext,
278 }
279 if video_url.startswith('rtmp'):
47e2a9bc
S
280 if smuggled_data.get('skip_rtmp'):
281 continue
f0d31c62
S
282 m = re.search(
283 r'^(?P<url>rtmp://[^/]+/(?P<app>[^/]+))/(?P<playpath>.+)$', video_url)
4a7a5e41
RA
284 if not m:
285 continue
286 fmt.update({
287 'ext': 'flv',
288 'url': m.group('url'),
289 'app': m.group('app'),
290 'play_path': m.group('playpath'),
291 })
292 else:
293 fmt.update({
294 'url': video_url,
295 })
296 formats.append(fmt)
3859ebee
S
297
298 if not formats and video.get('is_geo_blocked'):
299 self.raise_geo_restricted(
300 'This content might not be available in your country due to copyright reasons')
301
1220352f
S
302 self._sort_formats(formats)
303
f0d31c62
S
304 # TODO: webvtt in m3u8
305 subtitles = {}
306 sami_path = video.get('sami_path')
307 if sami_path:
308 lang = self._search_regex(
309 r'_([a-z]{2})\.xml', sami_path, 'lang',
310 default=compat_urlparse.urlparse(url).netloc.rsplit('.', 1)[-1])
311 subtitles[lang] = [{
312 'url': sami_path,
313 }]
314
5ca968d0
S
315 series = video.get('format_title')
316 episode_number = int_or_none(video.get('format_position', {}).get('episode'))
317 season = video.get('_embedded', {}).get('season', {}).get('title')
318 season_number = int_or_none(video.get('format_position', {}).get('season'))
319
1220352f
S
320 return {
321 'id': video_id,
4a7a5e41
RA
322 'title': title,
323 'description': video.get('description'),
5ca968d0
S
324 'series': series,
325 'episode_number': episode_number,
326 'season': season,
327 'season_number': season_number,
4a7a5e41
RA
328 'duration': int_or_none(video.get('duration')),
329 'timestamp': parse_iso8601(video.get('created_at')),
502d87c5 330 'view_count': try_get(video, lambda x: x['views']['total'], int),
4a7a5e41 331 'age_limit': int_or_none(video.get('age_limit', 0)),
1220352f 332 'formats': formats,
f0d31c62 333 'subtitles': subtitles,
1220352f 334 }
b35b0d73
S
335
336
337class ViafreeIE(InfoExtractor):
338 _VALID_URL = r'''(?x)
339 https?://
340 (?:www\.)?
341 viafree\.
342 (?:
343 (?:dk|no)/programmer|
344 se/program
345 )
346 /(?:[^/]+/)+(?P<id>[^/?#&]+)
347 '''
348 _TESTS = [{
349 'url': 'http://www.viafree.se/program/livsstil/husraddarna/sasong-2/avsnitt-2',
350 'info_dict': {
351 'id': '395375',
352 'ext': 'mp4',
353 'title': 'Husräddarna S02E02',
354 'description': 'md5:4db5c933e37db629b5a2f75dfb34829e',
355 'series': 'Husräddarna',
356 'season': 'Säsong 2',
357 'season_number': 2,
358 'duration': 2576,
359 'timestamp': 1400596321,
360 'upload_date': '20140520',
361 },
362 'params': {
363 'skip_download': True,
364 },
365 'add_ie': [TVPlayIE.ie_key()],
155bc674
S
366 }, {
367 # with relatedClips
368 'url': 'http://www.viafree.se/program/reality/sommaren-med-youtube-stjarnorna/sasong-1/avsnitt-1',
369 'info_dict': {
370 'id': '758770',
371 'ext': 'mp4',
372 'title': 'Sommaren med YouTube-stjärnorna S01E01',
373 'description': 'md5:2bc69dce2c4bb48391e858539bbb0e3f',
374 'series': 'Sommaren med YouTube-stjärnorna',
375 'season': 'Säsong 1',
376 'season_number': 1,
377 'duration': 1326,
378 'timestamp': 1470905572,
379 'upload_date': '20160811',
380 },
381 'params': {
382 'skip_download': True,
383 },
384 'add_ie': [TVPlayIE.ie_key()],
2cb93afc
S
385 }, {
386 # Different og:image URL schema
b690ea15 387 'url': 'http://www.viafree.se/program/reality/sommaren-med-youtube-stjarnorna/sasong-1/avsnitt-2',
2cb93afc 388 'only_matching': True,
b35b0d73
S
389 }, {
390 'url': 'http://www.viafree.no/programmer/underholdning/det-beste-vorspielet/sesong-2/episode-1',
391 'only_matching': True,
392 }, {
393 'url': 'http://www.viafree.dk/programmer/reality/paradise-hotel/saeson-7/episode-5',
394 'only_matching': True,
395 }]
396
397 @classmethod
398 def suitable(cls, url):
399 return False if TVPlayIE.suitable(url) else super(ViafreeIE, cls).suitable(url)
400
401 def _real_extract(self, url):
402 video_id = self._match_id(url)
403
404 webpage = self._download_webpage(url, video_id)
405
2cb93afc
S
406 data = self._parse_json(
407 self._search_regex(
408 r'(?s)window\.App\s*=\s*({.+?})\s*;\s*</script',
409 webpage, 'data', default='{}'),
410 video_id, transform_source=lambda x: re.sub(
411 r'(?s)function\s+[a-zA-Z_][\da-zA-Z_]*\s*\([^)]*\)\s*{[^}]*}\s*',
412 'null', x), fatal=False)
413
155bc674
S
414 video_id = None
415
2cb93afc
S
416 if data:
417 video_id = try_get(
418 data, lambda x: x['context']['dispatcher']['stores'][
419 'ContentPageProgramStore']['currentVideo']['id'],
420 compat_str)
421
422 # Fallback #1 (extract from og:image URL schema)
423 if not video_id:
424 thumbnail = self._og_search_thumbnail(webpage, default=None)
425 if thumbnail:
426 video_id = self._search_regex(
427 # Patterns seen:
428 # http://cdn.playapi.mtgx.tv/imagecache/600x315/cloud/content-images/inbox/765166/a2e95e5f1d735bab9f309fa345cc3f25.jpg
429 # http://cdn.playapi.mtgx.tv/imagecache/600x315/cloud/content-images/seasons/15204/758770/4a5ba509ca8bc043e1ebd1a76131cdf2.jpg
430 r'https?://[^/]+/imagecache/(?:[^/]+/)+(\d{6,})/',
431 thumbnail, 'video id', default=None)
155bc674 432
2cb93afc
S
433 # Fallback #2. Extract from raw JSON string.
434 # May extract wrong video id if relatedClips is present.
155bc674
S
435 if not video_id:
436 video_id = self._search_regex(
437 r'currentVideo["\']\s*:\s*.+?["\']id["\']\s*:\s*["\'](\d{6,})',
438 webpage, 'video id')
b35b0d73 439
dc76eef0
S
440 return self.url_result(
441 smuggle_url(
442 'mtg:%s' % video_id,
47e2a9bc
S
443 {
444 'geo_countries': [
445 compat_urlparse.urlparse(url).netloc.rsplit('.', 1)[-1]],
446 # rtmp host mtgfs.fplive.net for viafree is unresolvable
447 'skip_rtmp': True,
448 }),
dc76eef0 449 ie=TVPlayIE.ie_key(), video_id=video_id)