]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/nhl.py
New upstream version 2016.12.01
[youtubedl] / youtube_dl / extractor / nhl.py
1 from __future__ import unicode_literals
2
3 import re
4 import json
5 import os
6
7 from .common import InfoExtractor
8 from ..compat import (
9 compat_urlparse,
10 compat_urllib_parse_urlencode,
11 compat_urllib_parse_urlparse,
12 compat_str,
13 )
14 from ..utils import (
15 unified_strdate,
16 determine_ext,
17 int_or_none,
18 parse_iso8601,
19 parse_duration,
20 )
21
22
23 class NHLBaseInfoExtractor(InfoExtractor):
24 @staticmethod
25 def _fix_json(json_string):
26 return json_string.replace('\\\'', '\'')
27
28 def _real_extract_video(self, video_id):
29 vid_parts = video_id.split(',')
30 if len(vid_parts) == 3:
31 video_id = '%s0%s%s-X-h' % (vid_parts[0][:4], vid_parts[1], vid_parts[2].rjust(4, '0'))
32 json_url = 'http://video.nhl.com/videocenter/servlets/playlist?ids=%s&format=json' % video_id
33 data = self._download_json(
34 json_url, video_id, transform_source=self._fix_json)
35 return self._extract_video(data[0])
36
37 def _extract_video(self, info):
38 video_id = info['id']
39 self.report_extraction(video_id)
40
41 initial_video_url = info['publishPoint']
42 if info['formats'] == '1':
43 parsed_url = compat_urllib_parse_urlparse(initial_video_url)
44 filename, ext = os.path.splitext(parsed_url.path)
45 path = '%s_sd%s' % (filename, ext)
46 data = compat_urllib_parse_urlencode({
47 'type': 'fvod',
48 'path': compat_urlparse.urlunparse(parsed_url[:2] + (path,) + parsed_url[3:])
49 })
50 path_url = 'http://video.nhl.com/videocenter/servlets/encryptvideopath?' + data
51 path_doc = self._download_xml(
52 path_url, video_id, 'Downloading final video url')
53 video_url = path_doc.find('path').text
54 else:
55 video_url = initial_video_url
56
57 join = compat_urlparse.urljoin
58 ret = {
59 'id': video_id,
60 'title': info['name'],
61 'url': video_url,
62 'description': info['description'],
63 'duration': int(info['duration']),
64 'thumbnail': join(join(video_url, '/u/'), info['bigImage']),
65 'upload_date': unified_strdate(info['releaseDate'].split('.')[0]),
66 }
67 if video_url.startswith('rtmp:'):
68 mobj = re.match(r'(?P<tc_url>rtmp://[^/]+/(?P<app>[a-z0-9/]+))/(?P<play_path>mp4:.*)', video_url)
69 ret.update({
70 'tc_url': mobj.group('tc_url'),
71 'play_path': mobj.group('play_path'),
72 'app': mobj.group('app'),
73 'no_resume': True,
74 })
75 return ret
76
77
78 class NHLVideocenterIE(NHLBaseInfoExtractor):
79 IE_NAME = 'nhl.com:videocenter'
80 _VALID_URL = r'https?://video(?P<team>\.[^.]*)?\.nhl\.com/videocenter/(?:console|embed)?(?:\?(?:.*?[?&])?)(?:id|hlg|playlist)=(?P<id>[-0-9a-zA-Z,]+)'
81
82 _TESTS = [{
83 'url': 'http://video.canucks.nhl.com/videocenter/console?catid=6?id=453614',
84 'md5': 'db704a4ea09e8d3988c85e36cc892d09',
85 'info_dict': {
86 'id': '453614',
87 'ext': 'mp4',
88 'title': 'Quick clip: Weise 4-3 goal vs Flames',
89 'description': 'Dale Weise scores his first of the season to put the Canucks up 4-3.',
90 'duration': 18,
91 'upload_date': '20131006',
92 },
93 }, {
94 'url': 'http://video.nhl.com/videocenter/console?id=2014020024-628-h',
95 'md5': 'd22e82bc592f52d37d24b03531ee9696',
96 'info_dict': {
97 'id': '2014020024-628-h',
98 'ext': 'mp4',
99 'title': 'Alex Galchenyuk Goal on Ray Emery (14:40/3rd)',
100 'description': 'Home broadcast - Montreal Canadiens at Philadelphia Flyers - October 11, 2014',
101 'duration': 0,
102 'upload_date': '20141011',
103 },
104 }, {
105 'url': 'http://video.mapleleafs.nhl.com/videocenter/console?id=58665&catid=802',
106 'md5': 'c78fc64ea01777e426cfc202b746c825',
107 'info_dict': {
108 'id': '58665',
109 'ext': 'flv',
110 'title': 'Classic Game In Six - April 22, 1979',
111 'description': 'It was the last playoff game for the Leafs in the decade, and the last time the Leafs and Habs played in the playoffs. Great game, not a great ending.',
112 'duration': 400,
113 'upload_date': '20100129'
114 },
115 }, {
116 'url': 'http://video.flames.nhl.com/videocenter/console?id=630616',
117 'only_matching': True,
118 }, {
119 'url': 'http://video.nhl.com/videocenter/?id=736722',
120 'only_matching': True,
121 }, {
122 'url': 'http://video.nhl.com/videocenter/console?hlg=20142015,2,299&lang=en',
123 'md5': '076fcb88c255154aacbf0a7accc3f340',
124 'info_dict': {
125 'id': '2014020299-X-h',
126 'ext': 'mp4',
127 'title': 'Penguins at Islanders / Game Highlights',
128 'description': 'Home broadcast - Pittsburgh Penguins at New York Islanders - November 22, 2014',
129 'duration': 268,
130 'upload_date': '20141122',
131 }
132 }, {
133 'url': 'http://video.oilers.nhl.com/videocenter/console?id=691469&catid=4',
134 'info_dict': {
135 'id': '691469',
136 'ext': 'mp4',
137 'title': 'RAW | Craig MacTavish Full Press Conference',
138 'description': 'Oilers GM Craig MacTavish addresses the media at Rexall Place on Friday.',
139 'upload_date': '20141205',
140 },
141 'params': {
142 'skip_download': True, # Requires rtmpdump
143 }
144 }, {
145 'url': 'http://video.nhl.com/videocenter/embed?playlist=836127',
146 'only_matching': True,
147 }]
148
149 def _real_extract(self, url):
150 video_id = self._match_id(url)
151 return self._real_extract_video(video_id)
152
153
154 class NHLNewsIE(NHLBaseInfoExtractor):
155 IE_NAME = 'nhl.com:news'
156 IE_DESC = 'NHL news'
157 _VALID_URL = r'https?://(?:.+?\.)?nhl\.com/(?:ice|club)/news\.html?(?:\?(?:.*?[?&])?)id=(?P<id>[-0-9a-zA-Z]+)'
158
159 _TESTS = [{
160 'url': 'http://www.nhl.com/ice/news.htm?id=750727',
161 'md5': '4b3d1262e177687a3009937bd9ec0be8',
162 'info_dict': {
163 'id': '736722',
164 'ext': 'mp4',
165 'title': 'Cal Clutterbuck has been fined $2,000',
166 'description': 'md5:45fe547d30edab88b23e0dd0ab1ed9e6',
167 'duration': 37,
168 'upload_date': '20150128',
169 },
170 }, {
171 # iframe embed
172 'url': 'http://sabres.nhl.com/club/news.htm?id=780189',
173 'md5': '9f663d1c006c90ac9fb82777d4294e12',
174 'info_dict': {
175 'id': '836127',
176 'ext': 'mp4',
177 'title': 'Morning Skate: OTT vs. BUF (9/23/15)',
178 'description': "Brian Duff chats with Tyler Ennis prior to Buffalo's first preseason home game.",
179 'duration': 93,
180 'upload_date': '20150923',
181 },
182 }]
183
184 def _real_extract(self, url):
185 news_id = self._match_id(url)
186 webpage = self._download_webpage(url, news_id)
187 video_id = self._search_regex(
188 [r'pVid(\d+)', r"nlid\s*:\s*'(\d+)'",
189 r'<iframe[^>]+src=["\']https?://video.*?\.nhl\.com/videocenter/embed\?.*\bplaylist=(\d+)'],
190 webpage, 'video id')
191 return self._real_extract_video(video_id)
192
193
194 class NHLVideocenterCategoryIE(NHLBaseInfoExtractor):
195 IE_NAME = 'nhl.com:videocenter:category'
196 IE_DESC = 'NHL videocenter category'
197 _VALID_URL = r'https?://video\.(?P<team>[^.]*)\.nhl\.com/videocenter/(console\?[^(id=)]*catid=(?P<catid>[0-9]+)(?![&?]id=).*?)?$'
198 _TEST = {
199 'url': 'http://video.canucks.nhl.com/videocenter/console?catid=999',
200 'info_dict': {
201 'id': '999',
202 'title': 'Highlights',
203 },
204 'playlist_count': 12,
205 }
206
207 def _real_extract(self, url):
208 mobj = re.match(self._VALID_URL, url)
209 team = mobj.group('team')
210 webpage = self._download_webpage(url, team)
211 cat_id = self._search_regex(
212 [r'var defaultCatId = "(.+?)";',
213 r'{statusIndex:0,index:0,.*?id:(.*?),'],
214 webpage, 'category id')
215 playlist_title = self._html_search_regex(
216 r'tab0"[^>]*?>(.*?)</td>',
217 webpage, 'playlist title', flags=re.DOTALL).lower().capitalize()
218
219 data = compat_urllib_parse_urlencode({
220 'cid': cat_id,
221 # This is the default value
222 'count': 12,
223 'ptrs': 3,
224 'format': 'json',
225 })
226 path = '/videocenter/servlets/browse?' + data
227 request_url = compat_urlparse.urljoin(url, path)
228 response = self._download_webpage(request_url, playlist_title)
229 response = self._fix_json(response)
230 if not response.strip():
231 self._downloader.report_warning('Got an empty response, trying '
232 'adding the "newvideos" parameter')
233 response = self._download_webpage(request_url + '&newvideos=true',
234 playlist_title)
235 response = self._fix_json(response)
236 videos = json.loads(response)
237
238 return {
239 '_type': 'playlist',
240 'title': playlist_title,
241 'id': cat_id,
242 'entries': [self._extract_video(v) for v in videos],
243 }
244
245
246 class NHLIE(InfoExtractor):
247 IE_NAME = 'nhl.com'
248 _VALID_URL = r'https?://(?:www\.)?(?P<site>nhl|wch2016)\.com/(?:[^/]+/)*c-(?P<id>\d+)'
249 _SITES_MAP = {
250 'nhl': 'nhl',
251 'wch2016': 'wch',
252 }
253 _TESTS = [{
254 # type=video
255 'url': 'https://www.nhl.com/video/anisimov-cleans-up-mess/t-277752844/c-43663503',
256 'md5': '0f7b9a8f986fb4b4eeeece9a56416eaf',
257 'info_dict': {
258 'id': '43663503',
259 'ext': 'mp4',
260 'title': 'Anisimov cleans up mess',
261 'description': 'md5:a02354acdfe900e940ce40706939ca63',
262 'timestamp': 1461288600,
263 'upload_date': '20160422',
264 },
265 }, {
266 # type=article
267 'url': 'https://www.nhl.com/news/dennis-wideman-suspended/c-278258934',
268 'md5': '1f39f4ea74c1394dea110699a25b366c',
269 'info_dict': {
270 'id': '40784403',
271 'ext': 'mp4',
272 'title': 'Wideman suspended by NHL',
273 'description': 'Flames defenseman Dennis Wideman was banned 20 games for violation of Rule 40 (Physical Abuse of Officials)',
274 'upload_date': '20160204',
275 'timestamp': 1454544904,
276 },
277 }, {
278 # Some m3u8 URLs are invalid (https://github.com/rg3/youtube-dl/issues/10713)
279 'url': 'https://www.nhl.com/predators/video/poile-laviolette-on-subban-trade/t-277437416/c-44315003',
280 'md5': '50b2bb47f405121484dda3ccbea25459',
281 'info_dict': {
282 'id': '44315003',
283 'ext': 'mp4',
284 'title': 'Poile, Laviolette on Subban trade',
285 'description': 'General manager David Poile and head coach Peter Laviolette share their thoughts on acquiring P.K. Subban from Montreal (06/29/16)',
286 'timestamp': 1467242866,
287 'upload_date': '20160629',
288 },
289 }, {
290 'url': 'https://www.wch2016.com/video/caneur-best-of-game-2-micd-up/t-281230378/c-44983703',
291 'only_matching': True,
292 }, {
293 'url': 'https://www.wch2016.com/news/3-stars-team-europe-vs-team-canada/c-282195068',
294 'only_matching': True,
295 }]
296
297 def _real_extract(self, url):
298 mobj = re.match(self._VALID_URL, url)
299 tmp_id, site = mobj.group('id'), mobj.group('site')
300 video_data = self._download_json(
301 'https://nhl.bamcontent.com/%s/id/v1/%s/details/web-v1.json'
302 % (self._SITES_MAP[site], tmp_id), tmp_id)
303 if video_data.get('type') == 'article':
304 video_data = video_data['media']
305
306 video_id = compat_str(video_data['id'])
307 title = video_data['title']
308
309 formats = []
310 for playback in video_data.get('playbacks', []):
311 playback_url = playback.get('url')
312 if not playback_url:
313 continue
314 ext = determine_ext(playback_url)
315 if ext == 'm3u8':
316 m3u8_formats = self._extract_m3u8_formats(
317 playback_url, video_id, 'mp4', 'm3u8_native',
318 m3u8_id=playback.get('name', 'hls'), fatal=False)
319 self._check_formats(m3u8_formats, video_id)
320 formats.extend(m3u8_formats)
321 else:
322 height = int_or_none(playback.get('height'))
323 formats.append({
324 'format_id': playback.get('name', 'http' + ('-%dp' % height if height else '')),
325 'url': playback_url,
326 'width': int_or_none(playback.get('width')),
327 'height': height,
328 })
329 self._sort_formats(formats, ('preference', 'width', 'height', 'tbr', 'format_id'))
330
331 thumbnails = []
332 for thumbnail_id, thumbnail_data in video_data.get('image', {}).get('cuts', {}).items():
333 thumbnail_url = thumbnail_data.get('src')
334 if not thumbnail_url:
335 continue
336 thumbnails.append({
337 'id': thumbnail_id,
338 'url': thumbnail_url,
339 'width': int_or_none(thumbnail_data.get('width')),
340 'height': int_or_none(thumbnail_data.get('height')),
341 })
342
343 return {
344 'id': video_id,
345 'title': title,
346 'description': video_data.get('description'),
347 'timestamp': parse_iso8601(video_data.get('date')),
348 'duration': parse_duration(video_data.get('duration')),
349 'thumbnails': thumbnails,
350 'formats': formats,
351 }