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.

281 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. @staticmethod
  68. def _extract_url(webpage):
  69. mobj = re.search(
  70. r'<iframe[^>]+?src=(["\'])(?P<url>http://www\.ustream\.tv/embed/.+?)\1', webpage)
  71. if mobj is not None:
  72. return mobj.group('url')
  73. def _get_stream_info(self, url, video_id, app_id_ver, extra_note=None):
  74. def num_to_hex(n):
  75. return hex(n)[2:]
  76. rnd = random.randrange
  77. if not extra_note:
  78. extra_note = ''
  79. conn_info = self._download_json(
  80. 'http://r%d-1-%s-recorded-lp-live.ums.ustream.tv/1/ustream' % (rnd(1e8), video_id),
  81. video_id, note='Downloading connection info' + extra_note,
  82. query={
  83. 'type': 'viewer',
  84. 'appId': app_id_ver[0],
  85. 'appVersion': app_id_ver[1],
  86. 'rsid': '%s:%s' % (num_to_hex(rnd(1e8)), num_to_hex(rnd(1e8))),
  87. 'rpin': '_rpin.%d' % rnd(1e15),
  88. 'referrer': url,
  89. 'media': video_id,
  90. 'application': 'recorded',
  91. })
  92. host = conn_info[0]['args'][0]['host']
  93. connection_id = conn_info[0]['args'][0]['connectionId']
  94. return self._download_json(
  95. 'http://%s/1/ustream?connectionId=%s' % (host, connection_id),
  96. video_id, note='Downloading stream info' + extra_note)
  97. def _get_streams(self, url, video_id, app_id_ver):
  98. # Sometimes the return dict does not have 'stream'
  99. for trial_count in range(3):
  100. stream_info = self._get_stream_info(
  101. url, video_id, app_id_ver,
  102. extra_note=' (try %d)' % (trial_count + 1) if trial_count > 0 else '')
  103. if 'stream' in stream_info[0]['args'][0]:
  104. return stream_info[0]['args'][0]['stream']
  105. return []
  106. def _parse_segmented_mp4(self, dash_stream_info):
  107. def resolve_dash_template(template, idx, chunk_hash):
  108. return template.replace('%', compat_str(idx), 1).replace('%', chunk_hash)
  109. formats = []
  110. for stream in dash_stream_info['streams']:
  111. # Use only one provider to avoid too many formats
  112. provider = dash_stream_info['providers'][0]
  113. fragments = [{
  114. 'url': resolve_dash_template(
  115. provider['url'] + stream['initUrl'], 0, dash_stream_info['hashes']['0'])
  116. }]
  117. for idx in range(dash_stream_info['videoLength'] // dash_stream_info['chunkTime']):
  118. fragments.append({
  119. 'url': resolve_dash_template(
  120. provider['url'] + stream['segmentUrl'], idx,
  121. dash_stream_info['hashes'][compat_str(idx // 10 * 10)])
  122. })
  123. content_type = stream['contentType']
  124. kind = content_type.split('/')[0]
  125. f = {
  126. 'format_id': '-'.join(filter(None, [
  127. 'dash', kind, str_or_none(stream.get('bitrate'))])),
  128. 'protocol': 'http_dash_segments',
  129. # TODO: generate a MPD doc for external players?
  130. 'url': encode_data_uri(b'<MPD/>', 'text/xml'),
  131. 'ext': mimetype2ext(content_type),
  132. 'height': stream.get('height'),
  133. 'width': stream.get('width'),
  134. 'fragments': fragments,
  135. }
  136. if kind == 'video':
  137. f.update({
  138. 'vcodec': stream.get('codec'),
  139. 'acodec': 'none',
  140. 'vbr': stream.get('bitrate'),
  141. })
  142. else:
  143. f.update({
  144. 'vcodec': 'none',
  145. 'acodec': stream.get('codec'),
  146. 'abr': stream.get('bitrate'),
  147. })
  148. formats.append(f)
  149. return formats
  150. def _real_extract(self, url):
  151. m = re.match(self._VALID_URL, url)
  152. video_id = m.group('id')
  153. # some sites use this embed format (see: https://github.com/rg3/youtube-dl/issues/2990)
  154. if m.group('type') == 'embed/recorded':
  155. video_id = m.group('id')
  156. desktop_url = 'http://www.ustream.tv/recorded/' + video_id
  157. return self.url_result(desktop_url, 'Ustream')
  158. if m.group('type') == 'embed':
  159. video_id = m.group('id')
  160. webpage = self._download_webpage(url, video_id)
  161. content_video_ids = self._parse_json(self._search_regex(
  162. r'ustream\.vars\.offAirContentVideoIds=([^;]+);', webpage,
  163. 'content video IDs'), video_id)
  164. return self.playlist_result(
  165. map(lambda u: self.url_result('http://www.ustream.tv/recorded/' + u, 'Ustream'), content_video_ids),
  166. video_id)
  167. params = self._download_json(
  168. 'https://api.ustream.tv/videos/%s.json' % video_id, video_id)
  169. error = params.get('error')
  170. if error:
  171. raise ExtractorError(
  172. '%s returned error: %s' % (self.IE_NAME, error), expected=True)
  173. video = params['video']
  174. title = video['title']
  175. filesize = float_or_none(video.get('file_size'))
  176. formats = [{
  177. 'id': video_id,
  178. 'url': video_url,
  179. 'ext': format_id,
  180. 'filesize': filesize,
  181. } for format_id, video_url in video['media_urls'].items() if video_url]
  182. if not formats:
  183. hls_streams = self._get_streams(url, video_id, app_id_ver=(11, 2))
  184. if hls_streams:
  185. # m3u8_native leads to intermittent ContentTooShortError
  186. formats.extend(self._extract_m3u8_formats(
  187. hls_streams[0]['url'], video_id, ext='mp4', m3u8_id='hls'))
  188. '''
  189. # DASH streams handling is incomplete as 'url' is missing
  190. dash_streams = self._get_streams(url, video_id, app_id_ver=(3, 1))
  191. if dash_streams:
  192. formats.extend(self._parse_segmented_mp4(dash_streams))
  193. '''
  194. self._sort_formats(formats)
  195. description = video.get('description')
  196. timestamp = int_or_none(video.get('created_at'))
  197. duration = float_or_none(video.get('length'))
  198. view_count = int_or_none(video.get('views'))
  199. uploader = video.get('owner', {}).get('username')
  200. uploader_id = video.get('owner', {}).get('id')
  201. thumbnails = [{
  202. 'id': thumbnail_id,
  203. 'url': thumbnail_url,
  204. } for thumbnail_id, thumbnail_url in video.get('thumbnail', {}).items()]
  205. return {
  206. 'id': video_id,
  207. 'title': title,
  208. 'description': description,
  209. 'thumbnails': thumbnails,
  210. 'timestamp': timestamp,
  211. 'duration': duration,
  212. 'view_count': view_count,
  213. 'uploader': uploader,
  214. 'uploader_id': uploader_id,
  215. 'formats': formats,
  216. }
  217. class UstreamChannelIE(InfoExtractor):
  218. _VALID_URL = r'https?://(?:www\.)?ustream\.tv/channel/(?P<slug>.+)'
  219. IE_NAME = 'ustream:channel'
  220. _TEST = {
  221. 'url': 'http://www.ustream.tv/channel/channeljapan',
  222. 'info_dict': {
  223. 'id': '10874166',
  224. },
  225. 'playlist_mincount': 17,
  226. }
  227. def _real_extract(self, url):
  228. m = re.match(self._VALID_URL, url)
  229. display_id = m.group('slug')
  230. webpage = self._download_webpage(url, display_id)
  231. channel_id = self._html_search_meta('ustream:channel_id', webpage)
  232. BASE = 'http://www.ustream.tv'
  233. next_url = '/ajax/socialstream/videos/%s/1.json' % channel_id
  234. video_ids = []
  235. while next_url:
  236. reply = self._download_json(
  237. compat_urlparse.urljoin(BASE, next_url), display_id,
  238. note='Downloading video information (next: %d)' % (len(video_ids) + 1))
  239. video_ids.extend(re.findall(r'data-content-id="(\d.*)"', reply['data']))
  240. next_url = reply['nextUrl']
  241. entries = [
  242. self.url_result('http://www.ustream.tv/recorded/' + vid, 'Ustream')
  243. for vid in video_ids]
  244. return {
  245. '_type': 'playlist',
  246. 'id': channel_id,
  247. 'display_id': display_id,
  248. 'entries': entries,
  249. }