logo

youtube-dl

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

ustream.py (10766B)


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