ustream.py 10 KB

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