noco.py 8.3 KB

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