livestream.py 14 KB

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