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.

177 lines
6.4 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. from __future__ import unicode_literals
  2. import datetime
  3. import json
  4. import re
  5. import socket
  6. from .common import InfoExtractor
  7. from ..utils import (
  8. compat_http_client,
  9. compat_parse_qs,
  10. compat_str,
  11. compat_urllib_error,
  12. compat_urllib_parse_urlparse,
  13. compat_urllib_request,
  14. ExtractorError,
  15. unescapeHTML,
  16. )
  17. class BlipTVIE(InfoExtractor):
  18. """Information extractor for blip.tv"""
  19. _VALID_URL = r'^(?:https?://)?(?:www\.)?blip\.tv/((.+/)|(play/)|(api\.swf#))(.+)$'
  20. IE_NAME = 'blip.tv'
  21. _TEST = {
  22. 'url': 'http://blip.tv/cbr/cbr-exclusive-gotham-city-imposters-bats-vs-jokerz-short-3-5796352',
  23. 'file': '5779306.mov',
  24. 'md5': 'c6934ad0b6acf2bd920720ec888eb812',
  25. 'info_dict': {
  26. 'upload_date': '20111205',
  27. 'description': 'md5:9bc31f227219cde65e47eeec8d2dc596',
  28. 'uploader': 'Comic Book Resources - CBR TV',
  29. 'title': 'CBR EXCLUSIVE: "Gotham City Imposters" Bats VS Jokerz Short 3',
  30. }
  31. }
  32. def report_direct_download(self, title):
  33. """Report information extraction."""
  34. self.to_screen('%s: Direct download detected' % title)
  35. def _real_extract(self, url):
  36. mobj = re.match(self._VALID_URL, url)
  37. if mobj is None:
  38. raise ExtractorError('Invalid URL: %s' % url)
  39. # See https://github.com/rg3/youtube-dl/issues/857
  40. api_mobj = re.match(r'http://a\.blip\.tv/api\.swf#(?P<video_id>[\d\w]+)', url)
  41. if api_mobj is not None:
  42. url = 'http://blip.tv/play/g_%s' % api_mobj.group('video_id')
  43. urlp = compat_urllib_parse_urlparse(url)
  44. if urlp.path.startswith('/play/'):
  45. response = self._request_webpage(url, None, False)
  46. redirecturl = response.geturl()
  47. rurlp = compat_urllib_parse_urlparse(redirecturl)
  48. file_id = compat_parse_qs(rurlp.fragment)['file'][0].rpartition('/')[2]
  49. url = 'http://blip.tv/a/a-' + file_id
  50. return self._real_extract(url)
  51. if '?' in url:
  52. cchar = '&'
  53. else:
  54. cchar = '?'
  55. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  56. request = compat_urllib_request.Request(json_url)
  57. request.add_header('User-Agent', 'iTunes/10.6.1')
  58. self.report_extraction(mobj.group(1))
  59. urlh = self._request_webpage(request, None, False,
  60. 'unable to download video info webpage')
  61. try:
  62. json_code_bytes = urlh.read()
  63. json_code = json_code_bytes.decode('utf-8')
  64. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  65. raise ExtractorError('Unable to read video info webpage: %s' % compat_str(err))
  66. try:
  67. json_data = json.loads(json_code)
  68. if 'Post' in json_data:
  69. data = json_data['Post']
  70. else:
  71. data = json_data
  72. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  73. formats = []
  74. if 'additionalMedia' in data:
  75. for f in sorted(data['additionalMedia'], key=lambda f: int(f['media_height'])):
  76. if not int(f['media_width']): # filter m3u8
  77. continue
  78. formats.append({
  79. 'url': f['url'],
  80. 'format_id': f['role'],
  81. 'width': int(f['media_width']),
  82. 'height': int(f['media_height']),
  83. })
  84. else:
  85. formats.append({
  86. 'url': data['media']['url'],
  87. 'width': int(data['media']['width']),
  88. 'height': int(data['media']['height']),
  89. })
  90. self._sort_formats(formats)
  91. return {
  92. 'id': compat_str(data['item_id']),
  93. 'uploader': data['display_name'],
  94. 'upload_date': upload_date,
  95. 'title': data['title'],
  96. 'thumbnail': data['thumbnailUrl'],
  97. 'description': data['description'],
  98. 'user_agent': 'iTunes/10.6.1',
  99. 'formats': formats,
  100. }
  101. except (ValueError, KeyError) as err:
  102. raise ExtractorError('Unable to parse video information: %s' % repr(err))
  103. class BlipTVUserIE(InfoExtractor):
  104. """Information Extractor for blip.tv users."""
  105. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  106. _PAGE_SIZE = 12
  107. IE_NAME = 'blip.tv:user'
  108. def _real_extract(self, url):
  109. # Extract username
  110. mobj = re.match(self._VALID_URL, url)
  111. if mobj is None:
  112. raise ExtractorError('Invalid URL: %s' % url)
  113. username = mobj.group(1)
  114. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  115. page = self._download_webpage(url, username, 'Downloading user page')
  116. mobj = re.search(r'data-users-id="([^"]+)"', page)
  117. page_base = page_base % mobj.group(1)
  118. # Download video ids using BlipTV Ajax calls. Result size per
  119. # query is limited (currently to 12 videos) so we need to query
  120. # page by page until there are no video ids - it means we got
  121. # all of them.
  122. video_ids = []
  123. pagenum = 1
  124. while True:
  125. url = page_base + "&page=" + str(pagenum)
  126. page = self._download_webpage(url, username,
  127. 'Downloading video ids from page %d' % pagenum)
  128. # Extract video identifiers
  129. ids_in_page = []
  130. for mobj in re.finditer(r'href="/([^"]+)"', page):
  131. if mobj.group(1) not in ids_in_page:
  132. ids_in_page.append(unescapeHTML(mobj.group(1)))
  133. video_ids.extend(ids_in_page)
  134. # A little optimization - if current page is not
  135. # "full", ie. does not contain PAGE_SIZE video ids then
  136. # we can assume that this page is the last one - there
  137. # are no more ids on further pages - no need to query
  138. # again.
  139. if len(ids_in_page) < self._PAGE_SIZE:
  140. break
  141. pagenum += 1
  142. urls = ['http://blip.tv/%s' % video_id for video_id in video_ids]
  143. url_entries = [self.url_result(vurl, 'BlipTV') for vurl in urls]
  144. return [self.playlist_result(url_entries, playlist_title = username)]