logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

naver.py (6598B)


  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..utils import (
  6. clean_html,
  7. dict_get,
  8. ExtractorError,
  9. int_or_none,
  10. parse_duration,
  11. try_get,
  12. update_url_query,
  13. )
  14. class NaverBaseIE(InfoExtractor):
  15. _CAPTION_EXT_RE = r'\.(?:ttml|vtt)'
  16. def _extract_video_info(self, video_id, vid, key):
  17. video_data = self._download_json(
  18. 'http://play.rmcnmv.naver.com/vod/play/v2.0/' + vid,
  19. video_id, query={
  20. 'key': key,
  21. })
  22. meta = video_data['meta']
  23. title = meta['subject']
  24. formats = []
  25. get_list = lambda x: try_get(video_data, lambda y: y[x + 's']['list'], list) or []
  26. def extract_formats(streams, stream_type, query={}):
  27. for stream in streams:
  28. stream_url = stream.get('source')
  29. if not stream_url:
  30. continue
  31. stream_url = update_url_query(stream_url, query)
  32. encoding_option = stream.get('encodingOption', {})
  33. bitrate = stream.get('bitrate', {})
  34. formats.append({
  35. 'format_id': '%s_%s' % (stream.get('type') or stream_type, dict_get(encoding_option, ('name', 'id'))),
  36. 'url': stream_url,
  37. 'width': int_or_none(encoding_option.get('width')),
  38. 'height': int_or_none(encoding_option.get('height')),
  39. 'vbr': int_or_none(bitrate.get('video')),
  40. 'abr': int_or_none(bitrate.get('audio')),
  41. 'filesize': int_or_none(stream.get('size')),
  42. 'protocol': 'm3u8_native' if stream_type == 'HLS' else None,
  43. })
  44. extract_formats(get_list('video'), 'H264')
  45. for stream_set in video_data.get('streams', []):
  46. query = {}
  47. for param in stream_set.get('keys', []):
  48. query[param['name']] = param['value']
  49. stream_type = stream_set.get('type')
  50. videos = stream_set.get('videos')
  51. if videos:
  52. extract_formats(videos, stream_type, query)
  53. elif stream_type == 'HLS':
  54. stream_url = stream_set.get('source')
  55. if not stream_url:
  56. continue
  57. formats.extend(self._extract_m3u8_formats(
  58. update_url_query(stream_url, query), video_id,
  59. 'mp4', 'm3u8_native', m3u8_id=stream_type, fatal=False))
  60. self._sort_formats(formats)
  61. replace_ext = lambda x, y: re.sub(self._CAPTION_EXT_RE, '.' + y, x)
  62. def get_subs(caption_url):
  63. if re.search(self._CAPTION_EXT_RE, caption_url):
  64. return [{
  65. 'url': replace_ext(caption_url, 'ttml'),
  66. }, {
  67. 'url': replace_ext(caption_url, 'vtt'),
  68. }]
  69. else:
  70. return [{'url': caption_url}]
  71. automatic_captions = {}
  72. subtitles = {}
  73. for caption in get_list('caption'):
  74. caption_url = caption.get('source')
  75. if not caption_url:
  76. continue
  77. sub_dict = automatic_captions if caption.get('type') == 'auto' else subtitles
  78. sub_dict.setdefault(dict_get(caption, ('locale', 'language')), []).extend(get_subs(caption_url))
  79. user = meta.get('user', {})
  80. return {
  81. 'id': video_id,
  82. 'title': title,
  83. 'formats': formats,
  84. 'subtitles': subtitles,
  85. 'automatic_captions': automatic_captions,
  86. 'thumbnail': try_get(meta, lambda x: x['cover']['source']),
  87. 'view_count': int_or_none(meta.get('count')),
  88. 'uploader_id': user.get('id'),
  89. 'uploader': user.get('name'),
  90. 'uploader_url': user.get('url'),
  91. }
  92. class NaverIE(NaverBaseIE):
  93. _VALID_URL = r'https?://(?:m\.)?tv(?:cast)?\.naver\.com/(?:v|embed)/(?P<id>\d+)'
  94. _GEO_BYPASS = False
  95. _TESTS = [{
  96. 'url': 'http://tv.naver.com/v/81652',
  97. 'info_dict': {
  98. 'id': '81652',
  99. 'ext': 'mp4',
  100. 'title': '[9월 모의고사 해설강의][수학_김상희] 수학 A형 16~20번',
  101. 'description': '메가스터디 수학 김상희 선생님이 9월 모의고사 수학A형 16번에서 20번까지 해설강의를 공개합니다.',
  102. 'timestamp': 1378200754,
  103. 'upload_date': '20130903',
  104. 'uploader': '메가스터디, 합격불변의 법칙',
  105. 'uploader_id': 'megastudy',
  106. },
  107. }, {
  108. 'url': 'http://tv.naver.com/v/395837',
  109. 'md5': '8a38e35354d26a17f73f4e90094febd3',
  110. 'info_dict': {
  111. 'id': '395837',
  112. 'ext': 'mp4',
  113. 'title': '9년이 지나도 아픈 기억, 전효성의 아버지',
  114. 'description': 'md5:eb6aca9d457b922e43860a2a2b1984d3',
  115. 'timestamp': 1432030253,
  116. 'upload_date': '20150519',
  117. 'uploader': '4가지쇼 시즌2',
  118. 'uploader_id': 'wrappinguser29',
  119. },
  120. 'skip': 'Georestricted',
  121. }, {
  122. 'url': 'http://tvcast.naver.com/v/81652',
  123. 'only_matching': True,
  124. }]
  125. def _real_extract(self, url):
  126. video_id = self._match_id(url)
  127. content = self._download_json(
  128. 'https://tv.naver.com/api/json/v/' + video_id,
  129. video_id, headers=self.geo_verification_headers())
  130. player_info_json = content.get('playerInfoJson') or {}
  131. current_clip = player_info_json.get('currentClip') or {}
  132. vid = current_clip.get('videoId')
  133. in_key = current_clip.get('inKey')
  134. if not vid or not in_key:
  135. player_auth = try_get(player_info_json, lambda x: x['playerOption']['auth'])
  136. if player_auth == 'notCountry':
  137. self.raise_geo_restricted(countries=['KR'])
  138. elif player_auth == 'notLogin':
  139. self.raise_login_required()
  140. raise ExtractorError('couldn\'t extract vid and key')
  141. info = self._extract_video_info(video_id, vid, in_key)
  142. info.update({
  143. 'description': clean_html(current_clip.get('description')),
  144. 'timestamp': int_or_none(current_clip.get('firstExposureTime'), 1000),
  145. 'duration': parse_duration(current_clip.get('displayPlayTime')),
  146. 'like_count': int_or_none(current_clip.get('recommendPoint')),
  147. 'age_limit': 19 if current_clip.get('adult') else None,
  148. })
  149. return info