Merge branch 'miaopai' of https://github.com/xyb/youtube-dl into xyb-miaopai
[youtube-dl] / youtube_dl / extractor / turner.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_str
8 from ..utils import (
9     xpath_text,
10     int_or_none,
11     determine_ext,
12     parse_duration,
13     xpath_attr,
14     update_url_query,
15     ExtractorError,
16 )
17
18
19 class TurnerBaseIE(InfoExtractor):
20     def _extract_timestamp(self, video_data):
21         return int_or_none(xpath_attr(video_data, 'dateCreated', 'uts'))
22
23     def _extract_cvp_info(self, data_src, video_id, path_data={}):
24         video_data = self._download_xml(data_src, video_id)
25         video_id = video_data.attrib['id']
26         title = xpath_text(video_data, 'headline', fatal=True)
27         content_id = xpath_text(video_data, 'contentId') or video_id
28         # rtmp_src = xpath_text(video_data, 'akamai/src')
29         # if rtmp_src:
30         #     splited_rtmp_src = rtmp_src.split(',')
31         #     if len(splited_rtmp_src) == 2:
32         #         rtmp_src = splited_rtmp_src[1]
33         # aifp = xpath_text(video_data, 'akamai/aifp', default='')
34
35         tokens = {}
36         urls = []
37         formats = []
38         rex = re.compile(
39             r'(?P<width>[0-9]+)x(?P<height>[0-9]+)(?:_(?P<bitrate>[0-9]+))?')
40         # Possible formats locations: files/file, files/groupFiles/files
41         # and maybe others
42         for video_file in video_data.findall('.//file'):
43             video_url = video_file.text.strip()
44             if not video_url:
45                 continue
46             ext = determine_ext(video_url)
47             if video_url.startswith('/mp4:protected/'):
48                 continue
49                 # TODO Correct extraction for these files
50                 # protected_path_data = path_data.get('protected')
51                 # if not protected_path_data or not rtmp_src:
52                 #     continue
53                 # protected_path = self._search_regex(
54                 #     r'/mp4:(.+)\.[a-z0-9]', video_url, 'secure path')
55                 # auth = self._download_webpage(
56                 #     protected_path_data['tokenizer_src'], query={
57                 #         'path': protected_path,
58                 #         'videoId': content_id,
59                 #         'aifp': aifp,
60                 #     })
61                 # token = xpath_text(auth, 'token')
62                 # if not token:
63                 #     continue
64                 # video_url = rtmp_src + video_url + '?' + token
65             elif video_url.startswith('/secure/'):
66                 secure_path_data = path_data.get('secure')
67                 if not secure_path_data:
68                     continue
69                 video_url = secure_path_data['media_src'] + video_url
70                 secure_path = self._search_regex(r'https?://[^/]+(.+/)', video_url, 'secure path') + '*'
71                 token = tokens.get(secure_path)
72                 if not token:
73                     auth = self._download_xml(
74                         secure_path_data['tokenizer_src'], video_id, query={
75                             'path': secure_path,
76                             'videoId': content_id,
77                         })
78                     error_msg = xpath_text(auth, 'error/msg')
79                     if error_msg:
80                         raise ExtractorError(error_msg, expected=True)
81                     token = xpath_text(auth, 'token')
82                     if not token:
83                         continue
84                     tokens[secure_path] = token
85                 video_url = video_url + '?hdnea=' + token
86             elif not re.match('https?://', video_url):
87                 base_path_data = path_data.get(ext, path_data.get('default', {}))
88                 media_src = base_path_data.get('media_src')
89                 if not media_src:
90                     continue
91                 video_url = media_src + video_url
92             if video_url in urls:
93                 continue
94             urls.append(video_url)
95             format_id = video_file.get('bitrate')
96             if ext == 'smil':
97                 formats.extend(self._extract_smil_formats(
98                     video_url, video_id, fatal=False))
99             elif ext == 'm3u8':
100                 formats.extend(self._extract_m3u8_formats(
101                     video_url, video_id, 'mp4',
102                     m3u8_id=format_id or 'hls', fatal=False))
103             elif ext == 'f4m':
104                 formats.extend(self._extract_f4m_formats(
105                     update_url_query(video_url, {'hdcore': '3.7.0'}),
106                     video_id, f4m_id=format_id or 'hds', fatal=False))
107             else:
108                 f = {
109                     'format_id': format_id,
110                     'url': video_url,
111                     'ext': ext,
112                 }
113                 mobj = rex.search(format_id + video_url)
114                 if mobj:
115                     f.update({
116                         'width': int(mobj.group('width')),
117                         'height': int(mobj.group('height')),
118                         'tbr': int_or_none(mobj.group('bitrate')),
119                     })
120                 elif isinstance(format_id, compat_str):
121                     if format_id.isdigit():
122                         f['tbr'] = int(format_id)
123                     else:
124                         mobj = re.match(r'ios_(audio|[0-9]+)$', format_id)
125                         if mobj:
126                             if mobj.group(1) == 'audio':
127                                 f.update({
128                                     'vcodec': 'none',
129                                     'ext': 'm4a',
130                                 })
131                             else:
132                                 f['tbr'] = int(mobj.group(1))
133                 formats.append(f)
134         self._sort_formats(formats)
135
136         subtitles = {}
137         for source in video_data.findall('closedCaptions/source'):
138             for track in source.findall('track'):
139                 track_url = track.get('url')
140                 if not isinstance(track_url, compat_str) or track_url.endswith('/big'):
141                     continue
142                 lang = track.get('lang') or track.get('label') or 'en'
143                 subtitles.setdefault(lang, []).append({
144                     'url': track_url,
145                     'ext': {
146                         'scc': 'scc',
147                         'webvtt': 'vtt',
148                         'smptett': 'tt',
149                     }.get(source.get('format'))
150                 })
151
152         thumbnails = [{
153             'id': image.get('cut'),
154             'url': image.text,
155             'width': int_or_none(image.get('width')),
156             'height': int_or_none(image.get('height')),
157         } for image in video_data.findall('images/image')]
158
159         return {
160             'id': video_id,
161             'title': title,
162             'formats': formats,
163             'subtitles': subtitles,
164             'thumbnails': thumbnails,
165             'description': xpath_text(video_data, 'description'),
166             'duration': parse_duration(xpath_text(video_data, 'length') or xpath_text(video_data, 'trt')),
167             'timestamp': self._extract_timestamp(video_data),
168             'upload_date': xpath_attr(video_data, 'metas', 'version'),
169             'series': xpath_text(video_data, 'showTitle'),
170             'season_number': int_or_none(xpath_text(video_data, 'seasonNumber')),
171             'episode_number': int_or_none(xpath_text(video_data, 'episodeNumber')),
172         }