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