[nhl] Simplify
[youtube-dl] / youtube_dl / extractor / nhl.py
1 from __future__ import unicode_literals
2
3 import re
4 import json
5
6 from .common import InfoExtractor
7 from ..compat import (
8     compat_urlparse,
9     compat_urllib_parse,
10     compat_urllib_parse_urlparse
11 )
12 from ..utils import (
13     unified_strdate,
14 )
15
16
17 class NHLBaseInfoExtractor(InfoExtractor):
18     @staticmethod
19     def _fix_json(json_string):
20         return json_string.replace('\\\'', '\'')
21
22     def _extract_video(self, info):
23         video_id = info['id']
24         self.report_extraction(video_id)
25
26         initial_video_url = info['publishPoint']
27         if info['formats'] == '1':
28             parsed_url = compat_urllib_parse_urlparse(initial_video_url)
29             path = parsed_url.path.replace('.', '_sd.', 1)
30             data = compat_urllib_parse.urlencode({
31                 'type': 'fvod',
32                 'path': compat_urlparse.urlunparse(parsed_url[:2] + (path,) + parsed_url[3:])
33             })
34             path_url = 'http://video.nhl.com/videocenter/servlets/encryptvideopath?' + data
35             path_doc = self._download_xml(
36                 path_url, video_id, 'Downloading final video url')
37             video_url = path_doc.find('path').text
38         else:
39             video_url = initial_video_url
40
41         join = compat_urlparse.urljoin
42         return {
43             'id': video_id,
44             'title': info['name'],
45             'url': video_url,
46             'description': info['description'],
47             'duration': int(info['duration']),
48             'thumbnail': join(join(video_url, '/u/'), info['bigImage']),
49             'upload_date': unified_strdate(info['releaseDate'].split('.')[0]),
50         }
51
52
53 class NHLIE(NHLBaseInfoExtractor):
54     IE_NAME = 'nhl.com'
55     _VALID_URL = r'https?://video(?P<team>\.[^.]*)?\.nhl\.com/videocenter/console(?:\?(?:.*?[?&])?)id=(?P<id>[0-9a-z-]+)'
56
57     _TESTS = [{
58         'url': 'http://video.canucks.nhl.com/videocenter/console?catid=6?id=453614',
59         'md5': 'db704a4ea09e8d3988c85e36cc892d09',
60         'info_dict': {
61             'id': '453614',
62             'ext': 'mp4',
63             'title': 'Quick clip: Weise 4-3 goal vs Flames',
64             'description': 'Dale Weise scores his first of the season to put the Canucks up 4-3.',
65             'duration': 18,
66             'upload_date': '20131006',
67         },
68     }, {
69         'url': 'http://video.nhl.com/videocenter/console?id=2014020024-628-h',
70         'md5': 'd22e82bc592f52d37d24b03531ee9696',
71         'info_dict': {
72             'id': '2014020024-628-h',
73             'ext': 'mp4',
74             'title': 'Alex Galchenyuk Goal on Ray Emery (14:40/3rd)',
75             'description': 'Home broadcast - Montreal Canadiens at Philadelphia Flyers - October 11, 2014',
76             'duration': 0,
77             'upload_date': '20141011',
78         },
79     }, {
80         'url': 'http://video.mapleleafs.nhl.com/videocenter/console?id=58665&catid=802',
81         'md5': 'c78fc64ea01777e426cfc202b746c825',
82         'info_dict': {
83             'id': '58665',
84             'ext': 'flv',
85             'title': 'Classic Game In Six - April 22, 1979',
86             '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.',
87             'duration': 400,
88             'upload_date': '20100129'
89         },
90     }, {
91         'url': 'http://video.flames.nhl.com/videocenter/console?id=630616',
92         'only_matching': True,
93     }]
94
95     def _real_extract(self, url):
96         mobj = re.match(self._VALID_URL, url)
97         video_id = mobj.group('id')
98         json_url = 'http://video.nhl.com/videocenter/servlets/playlist?ids=%s&format=json' % video_id
99         data = self._download_json(
100             json_url, video_id, transform_source=self._fix_json)
101         return self._extract_video(data[0])
102
103
104 class NHLVideocenterIE(NHLBaseInfoExtractor):
105     IE_NAME = 'nhl.com:videocenter'
106     IE_DESC = 'NHL videocenter category'
107     _VALID_URL = r'https?://video\.(?P<team>[^.]*)\.nhl\.com/videocenter/(console\?[^(id=)]*catid=(?P<catid>[0-9]+)(?![&?]id=).*?)?$'
108     _TEST = {
109         'url': 'http://video.canucks.nhl.com/videocenter/console?catid=999',
110         'info_dict': {
111             'id': '999',
112             'title': 'Highlights',
113         },
114         'playlist_count': 12,
115     }
116
117     def _real_extract(self, url):
118         mobj = re.match(self._VALID_URL, url)
119         team = mobj.group('team')
120         webpage = self._download_webpage(url, team)
121         cat_id = self._search_regex(
122             [r'var defaultCatId = "(.+?)";',
123              r'{statusIndex:0,index:0,.*?id:(.*?),'],
124             webpage, 'category id')
125         playlist_title = self._html_search_regex(
126             r'tab0"[^>]*?>(.*?)</td>',
127             webpage, 'playlist title', flags=re.DOTALL).lower().capitalize()
128
129         data = compat_urllib_parse.urlencode({
130             'cid': cat_id,
131             # This is the default value
132             'count': 12,
133             'ptrs': 3,
134             'format': 'json',
135         })
136         path = '/videocenter/servlets/browse?' + data
137         request_url = compat_urlparse.urljoin(url, path)
138         response = self._download_webpage(request_url, playlist_title)
139         response = self._fix_json(response)
140         if not response.strip():
141             self._downloader.report_warning('Got an empty reponse, trying '
142                                             'adding the "newvideos" parameter')
143             response = self._download_webpage(request_url + '&newvideos=true',
144                                               playlist_title)
145             response = self._fix_json(response)
146         videos = json.loads(response)
147
148         return {
149             '_type': 'playlist',
150             'title': playlist_title,
151             'id': cat_id,
152             'entries': [self._extract_video(v) for v in videos],
153         }