You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

274 lines
10 KiB

  1. from __future__ import unicode_literals
  2. import random
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import (
  6. compat_str,
  7. compat_urlparse,
  8. )
  9. from ..utils import (
  10. encode_data_uri,
  11. ExtractorError,
  12. int_or_none,
  13. float_or_none,
  14. mimetype2ext,
  15. str_or_none,
  16. )
  17. class UstreamIE(InfoExtractor):
  18. _VALID_URL = r'https?://(?:www\.)?ustream\.tv/(?P<type>recorded|embed|embed/recorded)/(?P<id>\d+)'
  19. IE_NAME = 'ustream'
  20. _TESTS = [{
  21. 'url': 'http://www.ustream.tv/recorded/20274954',
  22. 'md5': '088f151799e8f572f84eb62f17d73e5c',
  23. 'info_dict': {
  24. 'id': '20274954',
  25. 'ext': 'flv',
  26. 'title': 'Young Americans for Liberty February 7, 2012 2:28 AM',
  27. 'description': 'Young Americans for Liberty February 7, 2012 2:28 AM',
  28. 'timestamp': 1328577035,
  29. 'upload_date': '20120207',
  30. 'uploader': 'yaliberty',
  31. 'uploader_id': '6780869',
  32. },
  33. }, {
  34. # From http://sportscanada.tv/canadagames/index.php/week2/figure-skating/444
  35. # Title and uploader available only from params JSON
  36. 'url': 'http://www.ustream.tv/embed/recorded/59307601?ub=ff0000&lc=ff0000&oc=ffffff&uc=ffffff&v=3&wmode=direct',
  37. 'md5': '5a2abf40babeac9812ed20ae12d34e10',
  38. 'info_dict': {
  39. 'id': '59307601',
  40. 'ext': 'flv',
  41. 'title': '-CG11- Canada Games Figure Skating',
  42. 'uploader': 'sportscanadatv',
  43. },
  44. 'skip': 'This Pro Broadcaster has chosen to remove this video from the ustream.tv site.',
  45. }, {
  46. 'url': 'http://www.ustream.tv/embed/10299409',
  47. 'info_dict': {
  48. 'id': '10299409',
  49. },
  50. 'playlist_count': 3,
  51. }, {
  52. 'url': 'http://www.ustream.tv/recorded/91343263',
  53. 'info_dict': {
  54. 'id': '91343263',
  55. 'ext': 'mp4',
  56. 'title': 'GitHub Universe - General Session - Day 1',
  57. 'upload_date': '20160914',
  58. 'description': 'GitHub Universe - General Session - Day 1',
  59. 'timestamp': 1473872730,
  60. 'uploader': 'wa0dnskeqkr',
  61. 'uploader_id': '38977840',
  62. },
  63. 'params': {
  64. 'skip_download': True, # m3u8 download
  65. },
  66. }]
  67. def _get_stream_info(self, url, video_id, app_id_ver, extra_note=None):
  68. def num_to_hex(n):
  69. return hex(n)[2:]
  70. rnd = random.randrange
  71. if not extra_note:
  72. extra_note = ''
  73. conn_info = self._download_json(
  74. 'http://r%d-1-%s-recorded-lp-live.ums.ustream.tv/1/ustream' % (rnd(1e8), video_id),
  75. video_id, note='Downloading connection info' + extra_note,
  76. query={
  77. 'type': 'viewer',
  78. 'appId': app_id_ver[0],
  79. 'appVersion': app_id_ver[1],
  80. 'rsid': '%s:%s' % (num_to_hex(rnd(1e8)), num_to_hex(rnd(1e8))),
  81. 'rpin': '_rpin.%d' % rnd(1e15),
  82. 'referrer': url,
  83. 'media': video_id,
  84. 'application': 'recorded',
  85. })
  86. host = conn_info[0]['args'][0]['host']
  87. connection_id = conn_info[0]['args'][0]['connectionId']
  88. return self._download_json(
  89. 'http://%s/1/ustream?connectionId=%s' % (host, connection_id),
  90. video_id, note='Downloading stream info' + extra_note)
  91. def _get_streams(self, url, video_id, app_id_ver):
  92. # Sometimes the return dict does not have 'stream'
  93. for trial_count in range(3):
  94. stream_info = self._get_stream_info(
  95. url, video_id, app_id_ver,
  96. extra_note=' (try %d)' % (trial_count + 1) if trial_count > 0 else '')
  97. if 'stream' in stream_info[0]['args'][0]:
  98. return stream_info[0]['args'][0]['stream']
  99. return []
  100. def _parse_segmented_mp4(self, dash_stream_info):
  101. def resolve_dash_template(template, idx, chunk_hash):
  102. return template.replace('%', compat_str(idx), 1).replace('%', chunk_hash)
  103. formats = []
  104. for stream in dash_stream_info['streams']:
  105. # Use only one provider to avoid too many formats
  106. provider = dash_stream_info['providers'][0]
  107. fragments = [{
  108. 'url': resolve_dash_template(
  109. provider['url'] + stream['initUrl'], 0, dash_stream_info['hashes']['0'])
  110. }]
  111. for idx in range(dash_stream_info['videoLength'] // dash_stream_info['chunkTime']):
  112. fragments.append({
  113. 'url': resolve_dash_template(
  114. provider['url'] + stream['segmentUrl'], idx,
  115. dash_stream_info['hashes'][compat_str(idx // 10 * 10)])
  116. })
  117. content_type = stream['contentType']
  118. kind = content_type.split('/')[0]
  119. f = {
  120. 'format_id': '-'.join(filter(None, [
  121. 'dash', kind, str_or_none(stream.get('bitrate'))])),
  122. 'protocol': 'http_dash_segments',
  123. # TODO: generate a MPD doc for external players?
  124. 'url': encode_data_uri(b'<MPD/>', 'text/xml'),
  125. 'ext': mimetype2ext(content_type),
  126. 'height': stream.get('height'),
  127. 'width': stream.get('width'),
  128. 'fragments': fragments,
  129. }
  130. if kind == 'video':
  131. f.update({
  132. 'vcodec': stream.get('codec'),
  133. 'acodec': 'none',
  134. 'vbr': stream.get('bitrate'),
  135. })
  136. else:
  137. f.update({
  138. 'vcodec': 'none',
  139. 'acodec': stream.get('codec'),
  140. 'abr': stream.get('bitrate'),
  141. })
  142. formats.append(f)
  143. return formats
  144. def _real_extract(self, url):
  145. m = re.match(self._VALID_URL, url)
  146. video_id = m.group('id')
  147. # some sites use this embed format (see: https://github.com/rg3/youtube-dl/issues/2990)
  148. if m.group('type') == 'embed/recorded':
  149. video_id = m.group('id')
  150. desktop_url = 'http://www.ustream.tv/recorded/' + video_id
  151. return self.url_result(desktop_url, 'Ustream')
  152. if m.group('type') == 'embed':
  153. video_id = m.group('id')
  154. webpage = self._download_webpage(url, video_id)
  155. content_video_ids = self._parse_json(self._search_regex(
  156. r'ustream\.vars\.offAirContentVideoIds=([^;]+);', webpage,
  157. 'content video IDs'), video_id)
  158. return self.playlist_result(
  159. map(lambda u: self.url_result('http://www.ustream.tv/recorded/' + u, 'Ustream'), content_video_ids),
  160. video_id)
  161. params = self._download_json(
  162. 'https://api.ustream.tv/videos/%s.json' % video_id, video_id)
  163. error = params.get('error')
  164. if error:
  165. raise ExtractorError(
  166. '%s returned error: %s' % (self.IE_NAME, error), expected=True)
  167. video = params['video']
  168. title = video['title']
  169. filesize = float_or_none(video.get('file_size'))
  170. formats = [{
  171. 'id': video_id,
  172. 'url': video_url,
  173. 'ext': format_id,
  174. 'filesize': filesize,
  175. } for format_id, video_url in video['media_urls'].items() if video_url]
  176. if not formats:
  177. hls_streams = self._get_streams(url, video_id, app_id_ver=(11, 2))
  178. if hls_streams:
  179. # m3u8_native leads to intermittent ContentTooShortError
  180. formats.extend(self._extract_m3u8_formats(
  181. hls_streams[0]['url'], video_id, ext='mp4', m3u8_id='hls'))
  182. '''
  183. # DASH streams handling is incomplete as 'url' is missing
  184. dash_streams = self._get_streams(url, video_id, app_id_ver=(3, 1))
  185. if dash_streams:
  186. formats.extend(self._parse_segmented_mp4(dash_streams))
  187. '''
  188. self._sort_formats(formats)
  189. description = video.get('description')
  190. timestamp = int_or_none(video.get('created_at'))
  191. duration = float_or_none(video.get('length'))
  192. view_count = int_or_none(video.get('views'))
  193. uploader = video.get('owner', {}).get('username')
  194. uploader_id = video.get('owner', {}).get('id')
  195. thumbnails = [{
  196. 'id': thumbnail_id,
  197. 'url': thumbnail_url,
  198. } for thumbnail_id, thumbnail_url in video.get('thumbnail', {}).items()]
  199. return {
  200. 'id': video_id,
  201. 'title': title,
  202. 'description': description,
  203. 'thumbnails': thumbnails,
  204. 'timestamp': timestamp,
  205. 'duration': duration,
  206. 'view_count': view_count,
  207. 'uploader': uploader,
  208. 'uploader_id': uploader_id,
  209. 'formats': formats,
  210. }
  211. class UstreamChannelIE(InfoExtractor):
  212. _VALID_URL = r'https?://(?:www\.)?ustream\.tv/channel/(?P<slug>.+)'
  213. IE_NAME = 'ustream:channel'
  214. _TEST = {
  215. 'url': 'http://www.ustream.tv/channel/channeljapan',
  216. 'info_dict': {
  217. 'id': '10874166',
  218. },
  219. 'playlist_mincount': 17,
  220. }
  221. def _real_extract(self, url):
  222. m = re.match(self._VALID_URL, url)
  223. display_id = m.group('slug')
  224. webpage = self._download_webpage(url, display_id)
  225. channel_id = self._html_search_meta('ustream:channel_id', webpage)
  226. BASE = 'http://www.ustream.tv'
  227. next_url = '/ajax/socialstream/videos/%s/1.json' % channel_id
  228. video_ids = []
  229. while next_url:
  230. reply = self._download_json(
  231. compat_urlparse.urljoin(BASE, next_url), display_id,
  232. note='Downloading video information (next: %d)' % (len(video_ids) + 1))
  233. video_ids.extend(re.findall(r'data-content-id="(\d.*)"', reply['data']))
  234. next_url = reply['nextUrl']
  235. entries = [
  236. self.url_result('http://www.ustream.tv/recorded/' + vid, 'Ustream')
  237. for vid in video_ids]
  238. return {
  239. '_type': 'playlist',
  240. 'id': channel_id,
  241. 'display_id': display_id,
  242. 'entries': entries,
  243. }