Merge branch 'fktv' of https://github.com/remitamine/youtube-dl into remitamine-fktv
[youtube-dl] / youtube_dl / extractor / nfl.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..compat import (
8     compat_urllib_parse_urlparse,
9 )
10 from ..utils import (
11     ExtractorError,
12     int_or_none,
13     remove_end,
14 )
15
16
17 class NFLIE(InfoExtractor):
18     IE_NAME = 'nfl.com'
19     _VALID_URL = r'''(?x)
20                     https?://
21                         (?P<host>
22                             (?:www\.)?
23                             (?:
24                                 (?:
25                                     nfl|
26                                     buffalobills|
27                                     miamidolphins|
28                                     patriots|
29                                     newyorkjets|
30                                     baltimoreravens|
31                                     bengals|
32                                     clevelandbrowns|
33                                     steelers|
34                                     houstontexans|
35                                     colts|
36                                     jaguars|
37                                     titansonline|
38                                     denverbroncos|
39                                     kcchiefs|
40                                     raiders|
41                                     chargers|
42                                     dallascowboys|
43                                     giants|
44                                     philadelphiaeagles|
45                                     redskins|
46                                     chicagobears|
47                                     detroitlions|
48                                     packers|
49                                     vikings|
50                                     atlantafalcons|
51                                     panthers|
52                                     neworleanssaints|
53                                     buccaneers|
54                                     azcardinals|
55                                     stlouisrams|
56                                     49ers|
57                                     seahawks
58                                 )\.com|
59                                 .+?\.clubs\.nfl\.com
60                             )
61                         )/
62                         (?:.+?/)*
63                         (?P<id>[^/#?&]+)
64                     '''
65     _TESTS = [{
66         'url': 'http://www.nfl.com/videos/nfl-game-highlights/0ap3000000398478/Week-3-Redskins-vs-Eagles-highlights',
67         'md5': '394ef771ddcd1354f665b471d78ec4c6',
68         'info_dict': {
69             'id': '0ap3000000398478',
70             'ext': 'mp4',
71             'title': 'Week 3: Redskins vs. Eagles highlights',
72             'description': 'md5:56323bfb0ac4ee5ab24bd05fdf3bf478',
73             'upload_date': '20140921',
74             'timestamp': 1411337580,
75             'thumbnail': 're:^https?://.*\.jpg$',
76         }
77     }, {
78         'url': 'http://prod.www.steelers.clubs.nfl.com/video-and-audio/videos/LIVE_Post_Game_vs_Browns/9d72f26a-9e2b-4718-84d3-09fb4046c266',
79         'md5': 'cf85bdb4bc49f6e9d3816d130c78279c',
80         'info_dict': {
81             'id': '9d72f26a-9e2b-4718-84d3-09fb4046c266',
82             'ext': 'mp4',
83             'title': 'LIVE: Post Game vs. Browns',
84             'description': 'md5:6a97f7e5ebeb4c0e69a418a89e0636e8',
85             'upload_date': '20131229',
86             'timestamp': 1388354455,
87             'thumbnail': 're:^https?://.*\.jpg$',
88         }
89     }, {
90         'url': 'http://www.nfl.com/news/story/0ap3000000467586/article/patriots-seahawks-involved-in-lategame-skirmish',
91         'info_dict': {
92             'id': '0ap3000000467607',
93             'ext': 'mp4',
94             'title': 'Frustrations flare on the field',
95             'description': 'Emotions ran high at the end of the Super Bowl on both sides of the ball after a dramatic finish.',
96             'timestamp': 1422850320,
97             'upload_date': '20150202',
98         },
99     }, {
100         'url': 'http://www.patriots.com/video/2015/09/18/10-days-gillette',
101         'md5': '4c319e2f625ffd0b481b4382c6fc124c',
102         'info_dict': {
103             'id': 'n-238346',
104             'ext': 'mp4',
105             'title': '10 Days at Gillette',
106             'description': 'md5:8cd9cd48fac16de596eadc0b24add951',
107             'timestamp': 1442618809,
108             'upload_date': '20150918',
109         },
110     }, {
111         'url': 'http://www.nfl.com/videos/nfl-network-top-ten/09000d5d810a6bd4/Top-10-Gutsiest-Performances-Jack-Youngblood',
112         'only_matching': True,
113     }, {
114         'url': 'http://www.buffalobills.com/video/videos/Rex_Ryan_Show_World_Wide_Rex/b1dcfab2-3190-4bb1-bfc0-d6e603d6601a',
115         'only_matching': True,
116     }]
117
118     @staticmethod
119     def prepend_host(host, url):
120         if not url.startswith('http'):
121             if not url.startswith('/'):
122                 url = '/%s' % url
123             url = 'http://{0:}{1:}'.format(host, url)
124         return url
125
126     @staticmethod
127     def format_from_stream(stream, protocol, host, path_prefix='',
128                            preference=0, note=None):
129         url = '{protocol:}://{host:}/{prefix:}{path:}'.format(
130             protocol=protocol,
131             host=host,
132             prefix=path_prefix,
133             path=stream.get('path'),
134         )
135         return {
136             'url': url,
137             'vbr': int_or_none(stream.get('rate', 0), 1000),
138             'preference': preference,
139             'format_note': note,
140         }
141
142     def _real_extract(self, url):
143         mobj = re.match(self._VALID_URL, url)
144         video_id, host = mobj.group('id'), mobj.group('host')
145
146         webpage = self._download_webpage(url, video_id)
147
148         config_url = NFLIE.prepend_host(host, self._search_regex(
149             r'(?:(?:config|configURL)\s*:\s*|<nflcs:avplayer[^>]+data-config\s*=\s*)(["\'])(?P<config>.+?)\1',
150             webpage, 'config URL', default='static/content/static/config/video/config.json',
151             group='config'))
152         # For articles, the id in the url is not the video id
153         video_id = self._search_regex(
154             r'(?:<nflcs:avplayer[^>]+data-contentId\s*=\s*|contentId\s*:\s*)(["\'])(?P<id>.+?)\1',
155             webpage, 'video id', default=video_id, group='id')
156         config = self._download_json(config_url, video_id, 'Downloading player config')
157         url_template = NFLIE.prepend_host(
158             host, '{contentURLTemplate:}'.format(**config))
159         video_data = self._download_json(
160             url_template.format(id=video_id), video_id)
161
162         formats = []
163         cdn_data = video_data.get('cdnData', {})
164         streams = cdn_data.get('bitrateInfo', [])
165         if cdn_data.get('format') == 'EXTERNAL_HTTP_STREAM':
166             parts = compat_urllib_parse_urlparse(cdn_data.get('uri'))
167             protocol, host = parts.scheme, parts.netloc
168             for stream in streams:
169                 formats.append(
170                     NFLIE.format_from_stream(stream, protocol, host))
171         else:
172             cdns = config.get('cdns')
173             if not cdns:
174                 raise ExtractorError('Failed to get CDN data', expected=True)
175
176             for name, cdn in cdns.items():
177                 # LimeLight streams don't seem to work
178                 if cdn.get('name') == 'LIMELIGHT':
179                     continue
180
181                 protocol = cdn.get('protocol')
182                 host = remove_end(cdn.get('host', ''), '/')
183                 if not (protocol and host):
184                     continue
185
186                 prefix = cdn.get('pathprefix', '')
187                 if prefix and not prefix.endswith('/'):
188                     prefix = '%s/' % prefix
189
190                 preference = 0
191                 if protocol == 'rtmp':
192                     preference = -2
193                 elif 'prog' in name.lower():
194                     preference = 1
195
196                 for stream in streams:
197                     formats.append(
198                         NFLIE.format_from_stream(stream, protocol, host,
199                                                  prefix, preference, name))
200
201         self._sort_formats(formats)
202
203         thumbnail = None
204         for q in ('xl', 'l', 'm', 's', 'xs'):
205             thumbnail = video_data.get('imagePaths', {}).get(q)
206             if thumbnail:
207                 break
208
209         return {
210             'id': video_id,
211             'title': video_data.get('headline'),
212             'formats': formats,
213             'description': video_data.get('caption'),
214             'duration': video_data.get('duration'),
215             'thumbnail': thumbnail,
216             'timestamp': int_or_none(video_data.get('posted'), 1000),
217         }