[nhl] Partial support for hlg id (fixes #4285)
[youtube-dl] / 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,
11     compat_urllib_parse_urlparse
12 )
13 from ..utils import (
14     unified_strdate,
15 )
16
17
18 class NHLBaseInfoExtractor(InfoExtractor):
19     @staticmethod
20     def _fix_json(json_string):
21         return json_string.replace('\\\'', '\'')
22
23     def _real_extract_video(self, video_id):
24         vid_parts = video_id.split(',')
25         if len(vid_parts) == 3:
26             video_id = '%s0%s%s-X-h' % (vid_parts[0][:4], vid_parts[1], vid_parts[2].rjust(4, '0'))
27         json_url = 'http://video.nhl.com/videocenter/servlets/playlist?ids=%s&format=json' % video_id
28         data = self._download_json(
29             json_url, video_id, transform_source=self._fix_json)
30         return self._extract_video(data[0])
31
32     def _extract_video(self, info):
33         video_id = info['id']
34         self.report_extraction(video_id)
35
36         initial_video_url = info['publishPoint']
37         if info['formats'] == '1':
38             parsed_url = compat_urllib_parse_urlparse(initial_video_url)
39             filename, ext = os.path.splitext(parsed_url.path)
40             path = '%s_sd%s' % (filename, ext)
41             data = compat_urllib_parse.urlencode({
42                 'type': 'fvod',
43                 'path': compat_urlparse.urlunparse(parsed_url[:2] + (path,) + parsed_url[3:])
44             })
45             path_url = 'http://video.nhl.com/videocenter/servlets/encryptvideopath?' + data
46             path_doc = self._download_xml(
47                 path_url, video_id, 'Downloading final video url')
48             video_url = path_doc.find('path').text
49         else:
50             video_url = initial_video_url
51
52         join = compat_urlparse.urljoin
53         return {
54             'id': video_id,
55             'title': info['name'],
56             'url': video_url,
57             'description': info['description'],
58             'duration': int(info['duration']),
59             'thumbnail': join(join(video_url, '/u/'), info['bigImage']),
60             'upload_date': unified_strdate(info['releaseDate'].split('.')[0]),
61         }
62
63
64 class NHLIE(NHLBaseInfoExtractor):
65     IE_NAME = 'nhl.com'
66     _VALID_URL = r'https?://video(?P<team>\.[^.]*)?\.nhl\.com/videocenter/(?:console)?(?:\?(?:.*?[?&])?)(?:id|hlg)=(?P<id>[-0-9a-zA-Z,]+)'
67
68     _TESTS = [{
69         'url': 'http://video.canucks.nhl.com/videocenter/console?catid=6?id=453614',
70         'md5': 'db704a4ea09e8d3988c85e36cc892d09',
71         'info_dict': {
72             'id': '453614',
73             'ext': 'mp4',
74             'title': 'Quick clip: Weise 4-3 goal vs Flames',
75             'description': 'Dale Weise scores his first of the season to put the Canucks up 4-3.',
76             'duration': 18,
77             'upload_date': '20131006',
78         },
79     }, {
80         'url': 'http://video.nhl.com/videocenter/console?id=2014020024-628-h',
81         'md5': 'd22e82bc592f52d37d24b03531ee9696',
82         'info_dict': {
83             'id': '2014020024-628-h',
84             'ext': 'mp4',
85             'title': 'Alex Galchenyuk Goal on Ray Emery (14:40/3rd)',
86             'description': 'Home broadcast - Montreal Canadiens at Philadelphia Flyers - October 11, 2014',
87             'duration': 0,
88             'upload_date': '20141011',
89         },
90     }, {
91         'url': 'http://video.mapleleafs.nhl.com/videocenter/console?id=58665&catid=802',
92         'md5': 'c78fc64ea01777e426cfc202b746c825',
93         'info_dict': {
94             'id': '58665',
95             'ext': 'flv',
96             'title': 'Classic Game In Six - April 22, 1979',
97             '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.',
98             'duration': 400,
99             'upload_date': '20100129'
100         },
101     }, {
102         'url': 'http://video.flames.nhl.com/videocenter/console?id=630616',
103         'only_matching': True,
104     }, {
105         'url': 'http://video.nhl.com/videocenter/?id=736722',
106         'only_matching': True,
107     }, {
108         'url': 'http://video.nhl.com/videocenter/console?hlg=20142015,2,299&lang=en',
109         'md5': '076fcb88c255154aacbf0a7accc3f340',
110         'info_dict': {
111             'id': '2014020299-X-h',
112             'ext': 'mp4',
113             'title': 'Penguins at Islanders / Game Highlights',
114             'description': 'Home broadcast - Pittsburgh Penguins at New York Islanders - November 22, 2014',
115             'duration': 268,
116             'upload_date': '20141122',
117         }
118     }]
119
120     def _real_extract(self, url):
121         video_id = self._match_id(url)
122         return self._real_extract_video(video_id)
123
124
125 class NHLNewsIE(NHLBaseInfoExtractor):
126     IE_NAME = 'nhl.com:news'
127     IE_DESC = 'NHL news'
128     _VALID_URL = r'https?://(?:www\.)?nhl\.com/ice/news\.html?(?:\?(?:.*?[?&])?)id=(?P<id>[-0-9a-zA-Z]+)'
129
130     _TEST = {
131         'url': 'http://www.nhl.com/ice/news.htm?id=750727',
132         'md5': '4b3d1262e177687a3009937bd9ec0be8',
133         'info_dict': {
134             'id': '736722',
135             'ext': 'mp4',
136             'title': 'Cal Clutterbuck has been fined $2,000',
137             'description': 'md5:45fe547d30edab88b23e0dd0ab1ed9e6',
138             'duration': 37,
139             'upload_date': '20150128',
140         },
141     }
142
143     def _real_extract(self, url):
144         news_id = self._match_id(url)
145         webpage = self._download_webpage(url, news_id)
146         video_id = self._search_regex(
147             [r'pVid(\d+)', r"nlid\s*:\s*'(\d+)'"],
148             webpage, 'video id')
149         return self._real_extract_video(video_id)
150
151
152 class NHLVideocenterIE(NHLBaseInfoExtractor):
153     IE_NAME = 'nhl.com:videocenter'
154     IE_DESC = 'NHL videocenter category'
155     _VALID_URL = r'https?://video\.(?P<team>[^.]*)\.nhl\.com/videocenter/(console\?[^(id=)]*catid=(?P<catid>[0-9]+)(?![&?]id=).*?)?$'
156     _TEST = {
157         'url': 'http://video.canucks.nhl.com/videocenter/console?catid=999',
158         'info_dict': {
159             'id': '999',
160             'title': 'Highlights',
161         },
162         'playlist_count': 12,
163     }
164
165     def _real_extract(self, url):
166         mobj = re.match(self._VALID_URL, url)
167         team = mobj.group('team')
168         webpage = self._download_webpage(url, team)
169         cat_id = self._search_regex(
170             [r'var defaultCatId = "(.+?)";',
171              r'{statusIndex:0,index:0,.*?id:(.*?),'],
172             webpage, 'category id')
173         playlist_title = self._html_search_regex(
174             r'tab0"[^>]*?>(.*?)</td>',
175             webpage, 'playlist title', flags=re.DOTALL).lower().capitalize()
176
177         data = compat_urllib_parse.urlencode({
178             'cid': cat_id,
179             # This is the default value
180             'count': 12,
181             'ptrs': 3,
182             'format': 'json',
183         })
184         path = '/videocenter/servlets/browse?' + data
185         request_url = compat_urlparse.urljoin(url, path)
186         response = self._download_webpage(request_url, playlist_title)
187         response = self._fix_json(response)
188         if not response.strip():
189             self._downloader.report_warning('Got an empty reponse, trying '
190                                             'adding the "newvideos" parameter')
191             response = self._download_webpage(request_url + '&newvideos=true',
192                                               playlist_title)
193             response = self._fix_json(response)
194         videos = json.loads(response)
195
196         return {
197             '_type': 'playlist',
198             'title': playlist_title,
199             'id': cat_id,
200             'entries': [self._extract_video(v) for v in videos],
201         }