ustream.py 10 KB

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