[tv2] Fix and improve extraction (closes #22787)
[youtube-dl] / 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 ..utils import (
8     determine_ext,
9     int_or_none,
10     float_or_none,
11     js_to_json,
12     parse_iso8601,
13     remove_end,
14     try_get,
15 )
16
17
18 class TV2IE(InfoExtractor):
19     _VALID_URL = r'https?://(?:www\.)?tv2\.no/v/(?P<id>\d+)'
20     _TEST = {
21         'url': 'http://www.tv2.no/v/916509/',
22         'info_dict': {
23             'id': '916509',
24             'ext': 'mp4',
25             'title': 'Se Frode Gryttens hyllest av Steven Gerrard',
26             'description': 'TV 2 Sportens huspoet tar avskjed med Liverpools kaptein Steven Gerrard.',
27             'timestamp': 1431715610,
28             'upload_date': '20150515',
29             'duration': 156.967,
30             'view_count': int,
31             'categories': list,
32         },
33         'params': {
34             # m3u8 download
35             'skip_download': True,
36         },
37     }
38
39     def _real_extract(self, url):
40         video_id = self._match_id(url)
41
42         formats = []
43         format_urls = []
44         for protocol in ('HDS', 'HLS'):
45             data = self._download_json(
46                 'http://sumo.tv2.no/api/web/asset/%s/play.json?protocol=%s&videoFormat=SMIL+ISMUSP' % (video_id, protocol),
47                 video_id, 'Downloading play JSON')['playback']
48             items = try_get(data, lambda x: x['items']['item'])
49             if not items:
50                 continue
51             if not isinstance(items, list):
52                 items = [items]
53             for item in items:
54                 if not isinstance(item, dict):
55                     continue
56                 video_url = item.get('url')
57                 if not video_url or video_url in format_urls:
58                     continue
59                 format_id = '%s-%s' % (protocol.lower(), item.get('mediaFormat'))
60                 if not self._is_valid_url(video_url, video_id, format_id):
61                     continue
62                 format_urls.append(video_url)
63                 ext = determine_ext(video_url)
64                 if ext == 'f4m':
65                     formats.extend(self._extract_f4m_formats(
66                         video_url, video_id, f4m_id=format_id, fatal=False))
67                 elif ext == 'm3u8':
68                     formats.extend(self._extract_m3u8_formats(
69                         video_url, video_id, 'mp4', entry_protocol='m3u8_native',
70                         m3u8_id=format_id, fatal=False))
71                 elif ext == 'ism' or video_url.endswith('.ism/Manifest'):
72                     pass
73                 else:
74                     formats.append({
75                         'url': video_url,
76                         'format_id': format_id,
77                         'tbr': int_or_none(item.get('bitrate')),
78                         'filesize': int_or_none(item.get('fileSize')),
79                     })
80         self._sort_formats(formats)
81
82         asset = self._download_json(
83             'http://sumo.tv2.no/api/web/asset/%s.json' % video_id,
84             video_id, 'Downloading metadata JSON')['asset']
85
86         title = asset['title']
87         description = asset.get('description')
88         timestamp = parse_iso8601(asset.get('createTime'))
89         duration = float_or_none(asset.get('accurateDuration') or asset.get('duration'))
90         view_count = int_or_none(asset.get('views'))
91         categories = asset.get('keywords', '').split(',')
92
93         thumbnails = [{
94             'id': thumbnail.get('@type'),
95             'url': thumbnail.get('url'),
96         } for _, thumbnail in asset.get('imageVersions', {}).items()]
97
98         return {
99             'id': video_id,
100             'url': video_url,
101             'title': title,
102             'description': description,
103             'thumbnails': thumbnails,
104             'timestamp': timestamp,
105             'duration': duration,
106             'view_count': view_count,
107             'categories': categories,
108             'formats': formats,
109         }
110
111
112 class TV2ArticleIE(InfoExtractor):
113     _VALID_URL = r'https?://(?:www\.)?tv2\.no/(?:a|\d{4}/\d{2}/\d{2}(/[^/]+)+)/(?P<id>\d+)'
114     _TESTS = [{
115         'url': 'http://www.tv2.no/2015/05/16/nyheter/alesund/krim/pingvin/6930542',
116         'info_dict': {
117             'id': '6930542',
118             'title': 'Russen hetses etter pingvintyveri - innrømmer å ha åpnet luken på buret',
119             'description': 'md5:339573779d3eea3542ffe12006190954',
120         },
121         'playlist_count': 2,
122     }, {
123         'url': 'http://www.tv2.no/a/6930542',
124         'only_matching': True,
125     }]
126
127     def _real_extract(self, url):
128         playlist_id = self._match_id(url)
129
130         webpage = self._download_webpage(url, playlist_id)
131
132         # Old embed pattern (looks unused nowadays)
133         assets = re.findall(r'data-assetid=["\'](\d+)', webpage)
134
135         if not assets:
136             # New embed pattern
137             for v in re.findall(r'TV2ContentboxVideo\(({.+?})\)', webpage):
138                 video = self._parse_json(
139                     v, playlist_id, transform_source=js_to_json, fatal=False)
140                 if not video:
141                     continue
142                 asset = video.get('assetId')
143                 if asset:
144                     assets.append(asset)
145
146         entries = [
147             self.url_result('http://www.tv2.no/v/%s' % asset_id, 'TV2')
148             for asset_id in assets]
149
150         title = remove_end(self._og_search_title(webpage), ' - TV2.no')
151         description = remove_end(self._og_search_description(webpage), ' - TV2.no')
152
153         return self.playlist_result(entries, playlist_id, title, description)