You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

280 lines
10 KiB

11 years ago
  1. from __future__ import unicode_literals
  2. import re
  3. import json
  4. import itertools
  5. from .common import InfoExtractor
  6. from ..compat import (
  7. compat_str,
  8. compat_urllib_parse_urlparse,
  9. compat_urlparse,
  10. )
  11. from ..utils import (
  12. ExtractorError,
  13. find_xpath_attr,
  14. int_or_none,
  15. orderedSet,
  16. xpath_with_ns,
  17. )
  18. class LivestreamIE(InfoExtractor):
  19. IE_NAME = 'livestream'
  20. _VALID_URL = r'https?://new\.livestream\.com/.*?/(?P<event_name>.*?)(/videos/(?P<id>[0-9]+)(?:/player)?)?/?(?:$|[?#])'
  21. _TESTS = [{
  22. 'url': 'http://new.livestream.com/CoheedandCambria/WebsterHall/videos/4719370',
  23. 'md5': '53274c76ba7754fb0e8d072716f2292b',
  24. 'info_dict': {
  25. 'id': '4719370',
  26. 'ext': 'mp4',
  27. 'title': 'Live from Webster Hall NYC',
  28. 'upload_date': '20121012',
  29. 'like_count': int,
  30. 'view_count': int,
  31. 'thumbnail': 're:^http://.*\.jpg$'
  32. }
  33. }, {
  34. 'url': 'http://new.livestream.com/tedx/cityenglish',
  35. 'info_dict': {
  36. 'title': 'TEDCity2.0 (English)',
  37. 'id': '2245590',
  38. },
  39. 'playlist_mincount': 4,
  40. }, {
  41. 'url': 'http://new.livestream.com/chess24/tatasteelchess',
  42. 'info_dict': {
  43. 'title': 'Tata Steel Chess',
  44. 'id': '3705884',
  45. },
  46. 'playlist_mincount': 60,
  47. }, {
  48. 'url': 'https://new.livestream.com/accounts/362/events/3557232/videos/67864563/player?autoPlay=false&height=360&mute=false&width=640',
  49. 'only_matching': True,
  50. }]
  51. def _parse_smil(self, video_id, smil_url):
  52. formats = []
  53. _SWITCH_XPATH = (
  54. './/{http://www.w3.org/2001/SMIL20/Language}body/'
  55. '{http://www.w3.org/2001/SMIL20/Language}switch')
  56. smil_doc = self._download_xml(
  57. smil_url, video_id,
  58. note='Downloading SMIL information',
  59. errnote='Unable to download SMIL information',
  60. fatal=False)
  61. if smil_doc is False: # Download failed
  62. return formats
  63. title_node = find_xpath_attr(
  64. smil_doc, './/{http://www.w3.org/2001/SMIL20/Language}meta',
  65. 'name', 'title')
  66. if title_node is None:
  67. self.report_warning('Cannot find SMIL id')
  68. switch_node = smil_doc.find(_SWITCH_XPATH)
  69. else:
  70. title_id = title_node.attrib['content']
  71. switch_node = find_xpath_attr(
  72. smil_doc, _SWITCH_XPATH, 'id', title_id)
  73. if switch_node is None:
  74. raise ExtractorError('Cannot find switch node')
  75. video_nodes = switch_node.findall(
  76. '{http://www.w3.org/2001/SMIL20/Language}video')
  77. for vn in video_nodes:
  78. tbr = int_or_none(vn.attrib.get('system-bitrate'))
  79. furl = (
  80. 'http://livestream-f.akamaihd.net/%s?v=3.0.3&fp=WIN%%2014,0,0,145' %
  81. (vn.attrib['src']))
  82. if 'clipBegin' in vn.attrib:
  83. furl += '&ssek=' + vn.attrib['clipBegin']
  84. formats.append({
  85. 'url': furl,
  86. 'format_id': 'smil_%d' % tbr,
  87. 'ext': 'flv',
  88. 'tbr': tbr,
  89. 'preference': -1000,
  90. })
  91. return formats
  92. def _extract_video_info(self, video_data):
  93. video_id = compat_str(video_data['id'])
  94. FORMAT_KEYS = (
  95. ('sd', 'progressive_url'),
  96. ('hd', 'progressive_url_hd'),
  97. )
  98. formats = [{
  99. 'format_id': format_id,
  100. 'url': video_data[key],
  101. 'quality': i + 1,
  102. } for i, (format_id, key) in enumerate(FORMAT_KEYS)
  103. if video_data.get(key)]
  104. smil_url = video_data.get('smil_url')
  105. if smil_url:
  106. formats.extend(self._parse_smil(video_id, smil_url))
  107. self._sort_formats(formats)
  108. return {
  109. 'id': video_id,
  110. 'formats': formats,
  111. 'title': video_data['caption'],
  112. 'thumbnail': video_data.get('thumbnail_url'),
  113. 'upload_date': video_data['updated_at'].replace('-', '')[:8],
  114. 'like_count': video_data.get('likes', {}).get('total'),
  115. 'view_count': video_data.get('views'),
  116. }
  117. def _extract_event(self, info):
  118. event_id = compat_str(info['id'])
  119. account = compat_str(info['owner_account_id'])
  120. root_url = (
  121. 'https://new.livestream.com/api/accounts/{account}/events/{event}/'
  122. 'feed.json'.format(account=account, event=event_id))
  123. def _extract_videos():
  124. last_video = None
  125. for i in itertools.count(1):
  126. if last_video is None:
  127. info_url = root_url
  128. else:
  129. info_url = '{root}?&id={id}&newer=-1&type=video'.format(
  130. root=root_url, id=last_video)
  131. videos_info = self._download_json(info_url, event_id, 'Downloading page {0}'.format(i))['data']
  132. videos_info = [v['data'] for v in videos_info if v['type'] == 'video']
  133. if not videos_info:
  134. break
  135. for v in videos_info:
  136. yield self._extract_video_info(v)
  137. last_video = videos_info[-1]['id']
  138. return self.playlist_result(_extract_videos(), event_id, info['full_name'])
  139. def _real_extract(self, url):
  140. mobj = re.match(self._VALID_URL, url)
  141. video_id = mobj.group('id')
  142. event_name = mobj.group('event_name')
  143. webpage = self._download_webpage(url, video_id or event_name)
  144. og_video = self._og_search_video_url(
  145. webpage, 'player url', fatal=False, default=None)
  146. if og_video is not None:
  147. query_str = compat_urllib_parse_urlparse(og_video).query
  148. query = compat_urlparse.parse_qs(query_str)
  149. if 'play_url' in query:
  150. api_url = query['play_url'][0].replace('.smil', '')
  151. info = json.loads(self._download_webpage(
  152. api_url, video_id, 'Downloading video info'))
  153. return self._extract_video_info(info)
  154. config_json = self._search_regex(
  155. r'window.config = ({.*?});', webpage, 'window config')
  156. info = json.loads(config_json)['event']
  157. def is_relevant(vdata, vid):
  158. result = vdata['type'] == 'video'
  159. if video_id is not None:
  160. result = result and compat_str(vdata['data']['id']) == vid
  161. return result
  162. if video_id is None:
  163. # This is an event page:
  164. return self._extract_event(info)
  165. else:
  166. videos = [self._extract_video_info(video_data['data'])
  167. for video_data in info['feed']['data']
  168. if is_relevant(video_data, video_id)]
  169. if not videos:
  170. raise ExtractorError('Cannot find video %s' % video_id)
  171. return videos[0]
  172. # The original version of Livestream uses a different system
  173. class LivestreamOriginalIE(InfoExtractor):
  174. IE_NAME = 'livestream:original'
  175. _VALID_URL = r'''(?x)https?://www\.livestream\.com/
  176. (?P<user>[^/]+)/(?P<type>video|folder)
  177. (?:\?.*?Id=|/)(?P<id>.*?)(&|$)
  178. '''
  179. _TESTS = [{
  180. 'url': 'http://www.livestream.com/dealbook/video?clipId=pla_8aa4a3f1-ba15-46a4-893b-902210e138fb',
  181. 'info_dict': {
  182. 'id': 'pla_8aa4a3f1-ba15-46a4-893b-902210e138fb',
  183. 'ext': 'flv',
  184. 'title': 'Spark 1 (BitCoin) with Cameron Winklevoss & Tyler Winklevoss of Winklevoss Capital',
  185. },
  186. 'params': {
  187. # rtmp
  188. 'skip_download': True,
  189. },
  190. }, {
  191. 'url': 'https://www.livestream.com/newplay/folder?dirId=a07bf706-d0e4-4e75-a747-b021d84f2fd3',
  192. 'info_dict': {
  193. 'id': 'a07bf706-d0e4-4e75-a747-b021d84f2fd3',
  194. },
  195. 'playlist_mincount': 4,
  196. }]
  197. def _extract_video(self, user, video_id):
  198. api_url = 'http://x{0}x.api.channel.livestream.com/2.0/clipdetails?extendedInfo=true&id={1}'.format(user, video_id)
  199. info = self._download_xml(api_url, video_id)
  200. item = info.find('channel').find('item')
  201. ns = {'media': 'http://search.yahoo.com/mrss'}
  202. thumbnail_url = item.find(xpath_with_ns('media:thumbnail', ns)).attrib['url']
  203. # Remove the extension and number from the path (like 1.jpg)
  204. path = self._search_regex(r'(user-files/.+)_.*?\.jpg$', thumbnail_url, 'path')
  205. return {
  206. 'id': video_id,
  207. 'title': item.find('title').text,
  208. 'url': 'rtmp://extondemand.livestream.com/ondemand',
  209. 'play_path': 'trans/dv15/mogulus-{0}'.format(path),
  210. 'player_url': 'http://static.livestream.com/chromelessPlayer/v21/playerapi.swf?hash=5uetk&v=0803&classid=D27CDB6E-AE6D-11cf-96B8-444553540000&jsEnabled=false&wmode=opaque',
  211. 'ext': 'flv',
  212. 'thumbnail': thumbnail_url,
  213. }
  214. def _extract_folder(self, url, folder_id):
  215. webpage = self._download_webpage(url, folder_id)
  216. paths = orderedSet(re.findall(
  217. r'''(?x)(?:
  218. <li\s+class="folder">\s*<a\s+href="|
  219. <a\s+href="(?=https?://livestre\.am/)
  220. )([^"]+)"''', webpage))
  221. return {
  222. '_type': 'playlist',
  223. 'id': folder_id,
  224. 'entries': [{
  225. '_type': 'url',
  226. 'url': compat_urlparse.urljoin(url, p),
  227. } for p in paths],
  228. }
  229. def _real_extract(self, url):
  230. mobj = re.match(self._VALID_URL, url)
  231. id = mobj.group('id')
  232. user = mobj.group('user')
  233. url_type = mobj.group('type')
  234. if url_type == 'folder':
  235. return self._extract_folder(url, id)
  236. else:
  237. return self._extract_video(user, id)
  238. # The server doesn't support HEAD request, the generic extractor can't detect
  239. # the redirection
  240. class LivestreamShortenerIE(InfoExtractor):
  241. IE_NAME = 'livestream:shortener'
  242. IE_DESC = False # Do not list
  243. _VALID_URL = r'https?://livestre\.am/(?P<id>.+)'
  244. def _real_extract(self, url):
  245. mobj = re.match(self._VALID_URL, url)
  246. id = mobj.group('id')
  247. webpage = self._download_webpage(url, id)
  248. return {
  249. '_type': 'url',
  250. 'url': self._og_search_url(webpage),
  251. }