[noco] Update tests
[youtube-dl] / youtube_dl / extractor / noco.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import time
6 import hashlib
7
8 from .common import InfoExtractor
9 from ..compat import (
10     compat_str,
11     compat_urllib_parse,
12     compat_urllib_request,
13 )
14 from ..utils import (
15     clean_html,
16     ExtractorError,
17     int_or_none,
18     float_or_none,
19     parse_iso8601,
20     unified_strdate,
21 )
22
23
24 class NocoIE(InfoExtractor):
25     _VALID_URL = r'http://(?:(?:www\.)?noco\.tv/emission/|player\.noco\.tv/\?idvideo=)(?P<id>\d+)'
26     _LOGIN_URL = 'http://noco.tv/do.php'
27     _API_URL_TEMPLATE = 'https://api.noco.tv/1.1/%s?ts=%s&tk=%s'
28     _SUB_LANG_TEMPLATE = '&sub_lang=%s'
29     _NETRC_MACHINE = 'noco'
30
31     _TESTS = [
32         {
33             'url': 'http://noco.tv/emission/11538/nolife/ami-ami-idol-hello-france/',
34             'md5': '0a993f0058ddbcd902630b2047ef710e',
35             'info_dict': {
36                 'id': '11538',
37                 'ext': 'mp4',
38                 'title': 'Ami Ami Idol - Hello! France',
39                 'description': 'md5:4eaab46ab68fa4197a317a88a53d3b86',
40                 'upload_date': '20140412',
41                 'uploader': 'Nolife',
42                 'uploader_id': 'NOL',
43                 'duration': 2851.2,
44             },
45             'skip': 'Requires noco account',
46         },
47         {
48             'url': 'http://noco.tv/emission/12610/lbl42/the-guild/s01e01-wake-up-call',
49             'md5': 'c190f1f48e313c55838f1f412225934d',
50             'info_dict': {
51                 'id': '12610',
52                 'ext': 'mp4',
53                 'title': 'The Guild #1 - Wake-Up Call',
54                 'timestamp': 1403863200,
55                 'upload_date': '20140627',
56                 'uploader': 'LBL42',
57                 'uploader_id': 'LBL',
58                 'duration': 233.023,
59             },
60             'skip': 'Requires noco account',
61         }
62     ]
63
64     def _real_initialize(self):
65         self._login()
66
67     def _login(self):
68         (username, password) = self._get_login_info()
69         if username is None:
70             return
71
72         login_form = {
73             'a': 'login',
74             'cookie': '1',
75             'username': username,
76             'password': password,
77         }
78         request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
79         request.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
80
81         login = self._download_json(request, None, 'Logging in as %s' % username)
82
83         if 'erreur' in login:
84             raise ExtractorError('Unable to login: %s' % clean_html(login['erreur']), expected=True)
85
86     def _call_api(self, path, video_id, note, sub_lang=None):
87         ts = compat_str(int(time.time() * 1000))
88         tk = hashlib.md5((hashlib.md5(ts.encode('ascii')).hexdigest() + '#8S?uCraTedap6a').encode('ascii')).hexdigest()
89         url = self._API_URL_TEMPLATE % (path, ts, tk)
90         if sub_lang:
91             url += self._SUB_LANG_TEMPLATE % sub_lang
92
93         resp = self._download_json(url, video_id, note)
94
95         if isinstance(resp, dict) and resp.get('error'):
96             self._raise_error(resp['error'], resp['description'])
97
98         return resp
99
100     def _raise_error(self, error, description):
101         raise ExtractorError(
102             '%s returned error: %s - %s' % (self.IE_NAME, error, description),
103             expected=True)
104
105     def _real_extract(self, url):
106         mobj = re.match(self._VALID_URL, url)
107         video_id = mobj.group('id')
108
109         medias = self._call_api(
110             'shows/%s/medias' % video_id,
111             video_id, 'Downloading video JSON')
112
113         show = self._call_api(
114             'shows/by_id/%s' % video_id,
115             video_id, 'Downloading show JSON')[0]
116
117         options = self._call_api(
118             'users/init', video_id,
119             'Downloading user options JSON')['options']
120         audio_lang_pref = options.get('audio_language') or options.get('language', 'fr')
121
122         if audio_lang_pref == 'original':
123             audio_lang_pref = show['original_lang']
124         if len(medias) == 1:
125             audio_lang_pref = list(medias.keys())[0]
126         elif audio_lang_pref not in medias:
127             audio_lang_pref = 'fr'
128
129         qualities = self._call_api(
130             'qualities',
131             video_id, 'Downloading qualities JSON')
132
133         formats = []
134
135         for audio_lang, audio_lang_dict in medias.items():
136             preference = 1 if audio_lang == audio_lang_pref else 0
137             for sub_lang, lang_dict in audio_lang_dict['video_list'].items():
138                 for format_id, fmt in lang_dict['quality_list'].items():
139                     format_id_extended = 'audio-%s_sub-%s_%s' % (audio_lang, sub_lang, format_id)
140
141                     video = self._call_api(
142                         'shows/%s/video/%s/%s' % (video_id, format_id.lower(), audio_lang),
143                         video_id, 'Downloading %s video JSON' % format_id_extended,
144                         sub_lang if sub_lang != 'none' else None)
145
146                     file_url = video['file']
147                     if not file_url:
148                         continue
149
150                     if file_url in ['forbidden', 'not found']:
151                         popmessage = video['popmessage']
152                         self._raise_error(popmessage['title'], popmessage['message'])
153
154                     formats.append({
155                         'url': file_url,
156                         'format_id': format_id_extended,
157                         'width': int_or_none(fmt.get('res_width')),
158                         'height': int_or_none(fmt.get('res_lines')),
159                         'abr': int_or_none(fmt.get('audiobitrate')),
160                         'vbr': int_or_none(fmt.get('videobitrate')),
161                         'filesize': int_or_none(fmt.get('filesize')),
162                         'format_note': qualities[format_id].get('quality_name'),
163                         'quality': qualities[format_id].get('priority'),
164                         'preference': preference,
165                     })
166
167         self._sort_formats(formats)
168
169         timestamp = parse_iso8601(show.get('online_date_start_utc'), ' ')
170         uploader = show.get('partner_name')
171         uploader_id = show.get('partner_key')
172         duration = float_or_none(show.get('duration_ms'), 1000)
173
174         thumbnails = []
175         for thumbnail_key, thumbnail_url in show.items():
176             m = re.search(r'^screenshot_(?P<width>\d+)x(?P<height>\d+)$', thumbnail_key)
177             if not m:
178                 continue
179             thumbnails.append({
180                 'url': thumbnail_url,
181                 'width': int(m.group('width')),
182                 'height': int(m.group('height')),
183             })
184
185         episode = show.get('show_TT') or show.get('show_OT')
186         family = show.get('family_TT') or show.get('family_OT')
187         episode_number = show.get('episode_number')
188
189         title = ''
190         if family:
191             title += family
192         if episode_number:
193             title += ' #' + compat_str(episode_number)
194         if episode:
195             title += ' - ' + episode
196
197         description = show.get('show_resume') or show.get('family_resume')
198
199         return {
200             'id': video_id,
201             'title': title,
202             'description': description,
203             'thumbnails': thumbnails,
204             'timestamp': timestamp,
205             'uploader': uploader,
206             'uploader_id': uploader_id,
207             'duration': duration,
208             'formats': formats,
209         }