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