livestream.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. import re
  2. import itertools
  3. from .common import InfoExtractor
  4. from ..compat import (
  5. compat_str,
  6. compat_urlparse,
  7. )
  8. from ..utils import (
  9. find_xpath_attr,
  10. xpath_attr,
  11. xpath_with_ns,
  12. xpath_text,
  13. orderedSet,
  14. update_url_query,
  15. int_or_none,
  16. float_or_none,
  17. parse_iso8601,
  18. determine_ext,
  19. )
  20. class LivestreamIE(InfoExtractor):
  21. IE_NAME = 'livestream'
  22. _VALID_URL = r'https?://(?:new\.)?livestream\.com/(?:accounts/(?P<account_id>\d+)|(?P<account_name>[^/]+))/(?:events/(?P<event_id>\d+)|(?P<event_name>[^/]+))(?:/videos/(?P<id>\d+))?'
  23. _EMBED_REGEX = [r'<iframe[^>]+src="(?P<url>https?://(?:new\.)?livestream\.com/[^"]+/player[^"]+)"']
  24. _TESTS = [{
  25. 'url': 'http://new.livestream.com/CoheedandCambria/WebsterHall/videos/4719370',
  26. 'md5': '53274c76ba7754fb0e8d072716f2292b',
  27. 'info_dict': {
  28. 'id': '4719370',
  29. 'ext': 'mp4',
  30. 'title': 'Live from Webster Hall NYC',
  31. 'timestamp': 1350008072,
  32. 'upload_date': '20121012',
  33. 'duration': 5968.0,
  34. 'like_count': int,
  35. 'view_count': int,
  36. 'thumbnail': r're:^http://.*\.jpg$'
  37. }
  38. }, {
  39. 'url': 'http://new.livestream.com/tedx/cityenglish',
  40. 'info_dict': {
  41. 'title': 'TEDCity2.0 (English)',
  42. 'id': '2245590',
  43. },
  44. 'playlist_mincount': 4,
  45. }, {
  46. 'url': 'http://new.livestream.com/chess24/tatasteelchess',
  47. 'info_dict': {
  48. 'title': 'Tata Steel Chess',
  49. 'id': '3705884',
  50. },
  51. 'playlist_mincount': 60,
  52. }, {
  53. 'url': 'https://new.livestream.com/accounts/362/events/3557232/videos/67864563/player?autoPlay=false&height=360&mute=false&width=640',
  54. 'only_matching': True,
  55. }, {
  56. 'url': 'http://livestream.com/bsww/concacafbeachsoccercampeonato2015',
  57. 'only_matching': True,
  58. }]
  59. _API_URL_TEMPLATE = 'http://livestream.com/api/accounts/%s/events/%s'
  60. def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  61. base_ele = find_xpath_attr(
  62. smil, self._xpath_ns('.//meta', namespace), 'name', 'httpBase')
  63. base = base_ele.get('content') if base_ele is not None else 'http://livestreamvod-f.akamaihd.net/'
  64. formats = []
  65. video_nodes = smil.findall(self._xpath_ns('.//video', namespace))
  66. for vn in video_nodes:
  67. tbr = int_or_none(vn.attrib.get('system-bitrate'), 1000)
  68. furl = (
  69. update_url_query(compat_urlparse.urljoin(base, vn.attrib['src']), {
  70. 'v': '3.0.3',
  71. 'fp': 'WIN% 14,0,0,145',
  72. }))
  73. if 'clipBegin' in vn.attrib:
  74. furl += '&ssek=' + vn.attrib['clipBegin']
  75. formats.append({
  76. 'url': furl,
  77. 'format_id': 'smil_%d' % tbr,
  78. 'ext': 'flv',
  79. 'tbr': tbr,
  80. 'preference': -1000, # Strictly inferior than all other formats?
  81. })
  82. return formats
  83. def _extract_video_info(self, video_data):
  84. video_id = compat_str(video_data['id'])
  85. FORMAT_KEYS = (
  86. ('sd', 'progressive_url'),
  87. ('hd', 'progressive_url_hd'),
  88. )
  89. formats = []
  90. for format_id, key in FORMAT_KEYS:
  91. video_url = video_data.get(key)
  92. if video_url:
  93. ext = determine_ext(video_url)
  94. if ext == 'm3u8':
  95. continue
  96. bitrate = int_or_none(self._search_regex(
  97. r'(\d+)\.%s' % ext, video_url, 'bitrate', default=None))
  98. formats.append({
  99. 'url': video_url,
  100. 'format_id': format_id,
  101. 'tbr': bitrate,
  102. 'ext': ext,
  103. })
  104. smil_url = video_data.get('smil_url')
  105. if smil_url:
  106. formats.extend(self._extract_smil_formats(smil_url, video_id, fatal=False))
  107. m3u8_url = video_data.get('m3u8_url')
  108. if m3u8_url:
  109. formats.extend(self._extract_m3u8_formats(
  110. m3u8_url, video_id, 'mp4', 'm3u8_native',
  111. m3u8_id='hls', fatal=False))
  112. f4m_url = video_data.get('f4m_url')
  113. if f4m_url:
  114. formats.extend(self._extract_f4m_formats(
  115. f4m_url, video_id, f4m_id='hds', fatal=False))
  116. comments = [{
  117. 'author_id': comment.get('author_id'),
  118. 'author': comment.get('author', {}).get('full_name'),
  119. 'id': comment.get('id'),
  120. 'text': comment['text'],
  121. 'timestamp': parse_iso8601(comment.get('created_at')),
  122. } for comment in video_data.get('comments', {}).get('data', [])]
  123. return {
  124. 'id': video_id,
  125. 'formats': formats,
  126. 'title': video_data['caption'],
  127. 'description': video_data.get('description'),
  128. 'thumbnail': video_data.get('thumbnail_url'),
  129. 'duration': float_or_none(video_data.get('duration'), 1000),
  130. 'timestamp': parse_iso8601(video_data.get('publish_at')),
  131. 'like_count': video_data.get('likes', {}).get('total'),
  132. 'comment_count': video_data.get('comments', {}).get('total'),
  133. 'view_count': video_data.get('views'),
  134. 'comments': comments,
  135. }
  136. def _extract_stream_info(self, stream_info):
  137. broadcast_id = compat_str(stream_info['broadcast_id'])
  138. is_live = stream_info.get('is_live')
  139. formats = []
  140. smil_url = stream_info.get('play_url')
  141. if smil_url:
  142. formats.extend(self._extract_smil_formats(smil_url, broadcast_id))
  143. m3u8_url = stream_info.get('m3u8_url')
  144. if m3u8_url:
  145. formats.extend(self._extract_m3u8_formats(
  146. m3u8_url, broadcast_id, 'mp4', 'm3u8_native',
  147. m3u8_id='hls', fatal=False))
  148. rtsp_url = stream_info.get('rtsp_url')
  149. if rtsp_url:
  150. formats.append({
  151. 'url': rtsp_url,
  152. 'format_id': 'rtsp',
  153. })
  154. return {
  155. 'id': broadcast_id,
  156. 'formats': formats,
  157. 'title': stream_info['stream_title'],
  158. 'thumbnail': stream_info.get('thumbnail_url'),
  159. 'is_live': is_live,
  160. }
  161. def _extract_event(self, event_data):
  162. event_id = compat_str(event_data['id'])
  163. account_id = compat_str(event_data['owner_account_id'])
  164. feed_root_url = self._API_URL_TEMPLATE % (account_id, event_id) + '/feed.json'
  165. stream_info = event_data.get('stream_info')
  166. if stream_info:
  167. return self._extract_stream_info(stream_info)
  168. last_video = None
  169. entries = []
  170. for i in itertools.count(1):
  171. if last_video is None:
  172. info_url = feed_root_url
  173. else:
  174. info_url = '{root}?&id={id}&newer=-1&type=video'.format(
  175. root=feed_root_url, id=last_video)
  176. videos_info = self._download_json(
  177. info_url, event_id, 'Downloading page {0}'.format(i))['data']
  178. videos_info = [v['data'] for v in videos_info if v['type'] == 'video']
  179. if not videos_info:
  180. break
  181. for v in videos_info:
  182. v_id = compat_str(v['id'])
  183. entries.append(self.url_result(
  184. 'http://livestream.com/accounts/%s/events/%s/videos/%s' % (account_id, event_id, v_id),
  185. 'Livestream', v_id, v.get('caption')))
  186. last_video = videos_info[-1]['id']
  187. return self.playlist_result(entries, event_id, event_data['full_name'])
  188. def _real_extract(self, url):
  189. mobj = self._match_valid_url(url)
  190. video_id = mobj.group('id')
  191. event = mobj.group('event_id') or mobj.group('event_name')
  192. account = mobj.group('account_id') or mobj.group('account_name')
  193. api_url = self._API_URL_TEMPLATE % (account, event)
  194. if video_id:
  195. video_data = self._download_json(
  196. api_url + '/videos/%s' % video_id, video_id)
  197. return self._extract_video_info(video_data)
  198. else:
  199. event_data = self._download_json(api_url, video_id)
  200. return self._extract_event(event_data)
  201. # The original version of Livestream uses a different system
  202. class LivestreamOriginalIE(InfoExtractor):
  203. IE_NAME = 'livestream:original'
  204. _VALID_URL = r'''(?x)https?://original\.livestream\.com/
  205. (?P<user>[^/\?#]+)(?:/(?P<type>video|folder)
  206. (?:(?:\?.*?Id=|/)(?P<id>.*?)(&|$))?)?
  207. '''
  208. _TESTS = [{
  209. 'url': 'http://original.livestream.com/dealbook/video?clipId=pla_8aa4a3f1-ba15-46a4-893b-902210e138fb',
  210. 'info_dict': {
  211. 'id': 'pla_8aa4a3f1-ba15-46a4-893b-902210e138fb',
  212. 'ext': 'mp4',
  213. 'title': 'Spark 1 (BitCoin) with Cameron Winklevoss & Tyler Winklevoss of Winklevoss Capital',
  214. 'duration': 771.301,
  215. 'view_count': int,
  216. },
  217. }, {
  218. 'url': 'https://original.livestream.com/newplay/folder?dirId=a07bf706-d0e4-4e75-a747-b021d84f2fd3',
  219. 'info_dict': {
  220. 'id': 'a07bf706-d0e4-4e75-a747-b021d84f2fd3',
  221. },
  222. 'playlist_mincount': 4,
  223. }, {
  224. # live stream
  225. 'url': 'http://original.livestream.com/znsbahamas',
  226. 'only_matching': True,
  227. }]
  228. def _extract_video_info(self, user, video_id):
  229. api_url = 'http://x%sx.api.channel.livestream.com/2.0/clipdetails?extendedInfo=true&id=%s' % (user, video_id)
  230. info = self._download_xml(api_url, video_id)
  231. item = info.find('channel').find('item')
  232. title = xpath_text(item, 'title')
  233. media_ns = {'media': 'http://search.yahoo.com/mrss'}
  234. thumbnail_url = xpath_attr(
  235. item, xpath_with_ns('media:thumbnail', media_ns), 'url')
  236. duration = float_or_none(xpath_attr(
  237. item, xpath_with_ns('media:content', media_ns), 'duration'))
  238. ls_ns = {'ls': 'http://api.channel.livestream.com/2.0'}
  239. view_count = int_or_none(xpath_text(
  240. item, xpath_with_ns('ls:viewsCount', ls_ns)))
  241. return {
  242. 'id': video_id,
  243. 'title': title,
  244. 'thumbnail': thumbnail_url,
  245. 'duration': duration,
  246. 'view_count': view_count,
  247. }
  248. def _extract_video_formats(self, video_data, video_id):
  249. formats = []
  250. progressive_url = video_data.get('progressiveUrl')
  251. if progressive_url:
  252. formats.append({
  253. 'url': progressive_url,
  254. 'format_id': 'http',
  255. })
  256. m3u8_url = video_data.get('httpUrl')
  257. if m3u8_url:
  258. formats.extend(self._extract_m3u8_formats(
  259. m3u8_url, video_id, 'mp4', 'm3u8_native',
  260. m3u8_id='hls', fatal=False))
  261. rtsp_url = video_data.get('rtspUrl')
  262. if rtsp_url:
  263. formats.append({
  264. 'url': rtsp_url,
  265. 'format_id': 'rtsp',
  266. })
  267. return formats
  268. def _extract_folder(self, url, folder_id):
  269. webpage = self._download_webpage(url, folder_id)
  270. paths = orderedSet(re.findall(
  271. r'''(?x)(?:
  272. <li\s+class="folder">\s*<a\s+href="|
  273. <a\s+href="(?=https?://livestre\.am/)
  274. )([^"]+)"''', webpage))
  275. entries = [{
  276. '_type': 'url',
  277. 'url': compat_urlparse.urljoin(url, p),
  278. } for p in paths]
  279. return self.playlist_result(entries, folder_id)
  280. def _real_extract(self, url):
  281. mobj = self._match_valid_url(url)
  282. user = mobj.group('user')
  283. url_type = mobj.group('type')
  284. content_id = mobj.group('id')
  285. if url_type == 'folder':
  286. return self._extract_folder(url, content_id)
  287. else:
  288. # this url is used on mobile devices
  289. stream_url = 'http://x%sx.api.channel.livestream.com/3.0/getstream.json' % user
  290. info = {}
  291. if content_id:
  292. stream_url += '?id=%s' % content_id
  293. info = self._extract_video_info(user, content_id)
  294. else:
  295. content_id = user
  296. webpage = self._download_webpage(url, content_id)
  297. info = {
  298. 'title': self._og_search_title(webpage),
  299. 'description': self._og_search_description(webpage),
  300. 'thumbnail': self._search_regex(r'channelLogo\.src\s*=\s*"([^"]+)"', webpage, 'thumbnail', None),
  301. }
  302. video_data = self._download_json(stream_url, content_id)
  303. is_live = video_data.get('isLive')
  304. info.update({
  305. 'id': content_id,
  306. 'title': info['title'],
  307. 'formats': self._extract_video_formats(video_data, content_id),
  308. 'is_live': is_live,
  309. })
  310. return info
  311. # The server doesn't support HEAD request, the generic extractor can't detect
  312. # the redirection
  313. class LivestreamShortenerIE(InfoExtractor):
  314. IE_NAME = 'livestream:shortener'
  315. IE_DESC = False # Do not list
  316. _VALID_URL = r'https?://livestre\.am/(?P<id>.+)'
  317. def _real_extract(self, url):
  318. mobj = self._match_valid_url(url)
  319. id = mobj.group('id')
  320. webpage = self._download_webpage(url, id)
  321. return self.url_result(self._og_search_url(webpage))