[jwplatform] Extract height from label
[youtube-dl] / youtube_dl / extractor / jwplatform.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 compat_urlparse
8 from ..utils import (
9     determine_ext,
10     float_or_none,
11     int_or_none,
12     mimetype2ext,
13 )
14
15
16 class JWPlatformBaseIE(InfoExtractor):
17     @staticmethod
18     def _find_jwplayer_data(webpage):
19         # TODO: Merge this with JWPlayer-related codes in generic.py
20
21         mobj = re.search(
22             'jwplayer\((?P<quote>[\'"])[^\'" ]+(?P=quote)\)\.setup\((?P<options>[^)]+)\)',
23             webpage)
24         if mobj:
25             return mobj.group('options')
26
27     def _extract_jwplayer_data(self, webpage, video_id, *args, **kwargs):
28         jwplayer_data = self._parse_json(
29             self._find_jwplayer_data(webpage), video_id)
30         return self._parse_jwplayer_data(
31             jwplayer_data, video_id, *args, **kwargs)
32
33     def _parse_jwplayer_data(self, jwplayer_data, video_id=None, require_title=True, m3u8_id=None, rtmp_params=None, base_url=None):
34         # JWPlayer backward compatibility: flattened playlists
35         # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/api/config.js#L81-L96
36         if 'playlist' not in jwplayer_data:
37             jwplayer_data = {'playlist': [jwplayer_data]}
38
39         entries = []
40         for video_data in jwplayer_data['playlist']:
41             # JWPlayer backward compatibility: flattened sources
42             # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/playlist/item.js#L29-L35
43             if 'sources' not in video_data:
44                 video_data['sources'] = [video_data]
45
46             this_video_id = video_id or video_data['mediaid']
47
48             formats = []
49             for source in video_data['sources']:
50                 source_url = self._proto_relative_url(source['file'])
51                 if base_url:
52                     source_url = compat_urlparse.urljoin(base_url, source_url)
53                 source_type = source.get('type') or ''
54                 ext = mimetype2ext(source_type) or determine_ext(source_url)
55                 if source_type == 'hls' or ext == 'm3u8':
56                     formats.extend(self._extract_m3u8_formats(
57                         source_url, this_video_id, 'mp4', 'm3u8_native', m3u8_id=m3u8_id, fatal=False))
58                 # https://github.com/jwplayer/jwplayer/blob/master/src/js/providers/default.js#L67
59                 elif source_type.startswith('audio') or ext in ('oga', 'aac', 'mp3', 'mpeg', 'vorbis'):
60                     formats.append({
61                         'url': source_url,
62                         'vcodec': 'none',
63                         'ext': ext,
64                     })
65                 else:
66                     height = int_or_none(source.get('height'))
67                     if height is None:
68                         # Often no height is provided but there is a label in
69                         # format like 1080p.
70                         height = int_or_none(self._search_regex(
71                             r'^(\d{3,})[pP]$', source.get('label') or '',
72                             'height', default=None))
73                     a_format = {
74                         'url': source_url,
75                         'width': int_or_none(source.get('width')),
76                         'height': height,
77                         'ext': ext,
78                     }
79                     if source_url.startswith('rtmp'):
80                         a_format['ext'] = 'flv'
81
82                         # See com/longtailvideo/jwplayer/media/RTMPMediaProvider.as
83                         # of jwplayer.flash.swf
84                         rtmp_url_parts = re.split(
85                             r'((?:mp4|mp3|flv):)', source_url, 1)
86                         if len(rtmp_url_parts) == 3:
87                             rtmp_url, prefix, play_path = rtmp_url_parts
88                             a_format.update({
89                                 'url': rtmp_url,
90                                 'play_path': prefix + play_path,
91                             })
92                         if rtmp_params:
93                             a_format.update(rtmp_params)
94                     formats.append(a_format)
95             self._sort_formats(formats)
96
97             subtitles = {}
98             tracks = video_data.get('tracks')
99             if tracks and isinstance(tracks, list):
100                 for track in tracks:
101                     if track.get('file') and track.get('kind') == 'captions':
102                         subtitles.setdefault(track.get('label') or 'en', []).append({
103                             'url': self._proto_relative_url(track['file'])
104                         })
105
106             entries.append({
107                 'id': this_video_id,
108                 'title': video_data['title'] if require_title else video_data.get('title'),
109                 'description': video_data.get('description'),
110                 'thumbnail': self._proto_relative_url(video_data.get('image')),
111                 'timestamp': int_or_none(video_data.get('pubdate')),
112                 'duration': float_or_none(jwplayer_data.get('duration')),
113                 'subtitles': subtitles,
114                 'formats': formats,
115             })
116         if len(entries) == 1:
117             return entries[0]
118         else:
119             return self.playlist_result(entries)
120
121
122 class JWPlatformIE(JWPlatformBaseIE):
123     _VALID_URL = r'(?:https?://content\.jwplatform\.com/(?:feeds|players|jw6)/|jwplatform:)(?P<id>[a-zA-Z0-9]{8})'
124     _TEST = {
125         'url': 'http://content.jwplatform.com/players/nPripu9l-ALJ3XQCI.js',
126         'md5': 'fa8899fa601eb7c83a64e9d568bdf325',
127         'info_dict': {
128             'id': 'nPripu9l',
129             'ext': 'mov',
130             'title': 'Big Buck Bunny Trailer',
131             'description': 'Big Buck Bunny is a short animated film by the Blender Institute. It is made using free and open source software.',
132             'upload_date': '20081127',
133             'timestamp': 1227796140,
134         }
135     }
136
137     @staticmethod
138     def _extract_url(webpage):
139         mobj = re.search(
140             r'<script[^>]+?src=["\'](?P<url>(?:https?:)?//content.jwplatform.com/players/[a-zA-Z0-9]{8})',
141             webpage)
142         if mobj:
143             return mobj.group('url')
144
145     def _real_extract(self, url):
146         video_id = self._match_id(url)
147         json_data = self._download_json('http://content.jwplatform.com/feeds/%s.json' % video_id, video_id)
148         return self._parse_jwplayer_data(json_data, video_id)