[teamcoco] Rewrite preload data extraction
[youtube-dl] / youtube_dl / extractor / teamcoco.py
1 # -*- coding: utf-8 -*-
2 from __future__ import unicode_literals
3
4 import base64
5 import binascii
6 import re
7 import json
8
9 from .common import InfoExtractor
10 from ..utils import (
11     ExtractorError,
12     qualities,
13 )
14 from ..compat import compat_ord
15
16
17 class TeamcocoIE(InfoExtractor):
18     _VALID_URL = r'http://teamcoco\.com/video/(?P<video_id>[0-9]+)?/?(?P<display_id>.*)'
19     _TESTS = [
20         {
21             'url': 'http://teamcoco.com/video/80187/conan-becomes-a-mary-kay-beauty-consultant',
22             'md5': '3f7746aa0dc86de18df7539903d399ea',
23             'info_dict': {
24                 'id': '80187',
25                 'ext': 'mp4',
26                 'title': 'Conan Becomes A Mary Kay Beauty Consultant',
27                 'description': 'Mary Kay is perhaps the most trusted name in female beauty, so of course Conan is a natural choice to sell their products.',
28                 'duration': 504,
29                 'age_limit': 0,
30             }
31         }, {
32             'url': 'http://teamcoco.com/video/louis-ck-interview-george-w-bush',
33             'md5': 'cde9ba0fa3506f5f017ce11ead928f9a',
34             'info_dict': {
35                 'id': '19705',
36                 'ext': 'mp4',
37                 'description': 'Louis C.K. got starstruck by George W. Bush, so what? Part one.',
38                 'title': 'Louis C.K. Interview Pt. 1 11/3/11',
39                 'duration': 288,
40                 'age_limit': 0,
41             }
42         }, {
43             'url': 'http://teamcoco.com/video/timothy-olyphant-drinking-whiskey',
44             'info_dict': {
45                 'id': '88748',
46                 'ext': 'mp4',
47                 'title': 'Timothy Olyphant Raises A Toast To “Justified”',
48                 'description': 'md5:15501f23f020e793aeca761205e42c24',
49             },
50             'params': {
51                 'skip_download': True,  # m3u8 downloads
52             }
53         }
54     ]
55     _VIDEO_ID_REGEXES = (
56         r'"eVar42"\s*:\s*(\d+)',
57         r'Ginger\.TeamCoco\.openInApp\("video",\s*"([^"]+)"',
58         r'"id_not"\s*:\s*(\d+)'
59     )
60
61     def _real_extract(self, url):
62         mobj = re.match(self._VALID_URL, url)
63
64         display_id = mobj.group('display_id')
65         webpage = self._download_webpage(url, display_id)
66
67         video_id = mobj.group('video_id')
68         if not video_id:
69             video_id = self._html_search_regex(
70                 self._VIDEO_ID_REGEXES, webpage, 'video id')
71
72         data = None
73
74         preload_codes = self._html_search_regex(
75             r'(function.+)setTimeout\(function\(\)\{playlist',
76             webpage, 'preload codes')
77         base64_fragments = re.findall(r'"([a-zA-z0-9+/=]+)"', preload_codes)
78         base64_fragments.remove('init')
79
80         def _check_sequence(cur_fragments):
81             if not cur_fragments:
82                 return
83             for i in range(len(cur_fragments)):
84                 cur_sequence = (''.join(cur_fragments[i:] + cur_fragments[:i])).encode('ascii')
85                 try:
86                     raw_data = base64.b64decode(cur_sequence)
87                     if compat_ord(raw_data[0]) == compat_ord('{'):
88                         return json.loads(raw_data.decode('utf-8'))
89                 except (TypeError, binascii.Error, UnicodeDecodeError, ValueError):
90                     continue
91
92         def _check_data():
93             for i in range(len(base64_fragments) + 1):
94                 for j in range(i, len(base64_fragments) + 1):
95                     data = _check_sequence(base64_fragments[:i] + base64_fragments[j:])
96                     if data:
97                         return data
98
99         self.to_screen('Try to compute possible data sequence. This may take some time.')
100         data = _check_data()
101
102         if not data:
103             raise ExtractorError(
104                 'Preload information could not be extracted', expected=True)
105
106         formats = []
107         get_quality = qualities(['500k', '480p', '1000k', '720p', '1080p'])
108         for filed in data['files']:
109             if filed['type'] == 'hls':
110                 formats.extend(self._extract_m3u8_formats(
111                     filed['url'], video_id, ext='mp4'))
112             else:
113                 m_format = re.search(r'(\d+(k|p))\.mp4', filed['url'])
114                 if m_format is not None:
115                     format_id = m_format.group(1)
116                 else:
117                     format_id = filed['bitrate']
118                 tbr = (
119                     int(filed['bitrate'])
120                     if filed['bitrate'].isdigit()
121                     else None)
122
123                 formats.append({
124                     'url': filed['url'],
125                     'ext': 'mp4',
126                     'tbr': tbr,
127                     'format_id': format_id,
128                     'quality': get_quality(format_id),
129                 })
130
131         self._sort_formats(formats)
132
133         return {
134             'id': video_id,
135             'display_id': display_id,
136             'formats': formats,
137             'title': data['title'],
138             'thumbnail': data.get('thumb', {}).get('href'),
139             'description': data.get('teaser'),
140             'duration': data.get('duration'),
141             'age_limit': self._family_friendly_search(webpage),
142         }