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.

170 lines
6.2 KiB

  1. import datetime
  2. import json
  3. import re
  4. import socket
  5. from .common import InfoExtractor
  6. from ..utils import (
  7. compat_http_client,
  8. compat_parse_qs,
  9. compat_str,
  10. compat_urllib_error,
  11. compat_urllib_parse_urlparse,
  12. compat_urllib_request,
  13. ExtractorError,
  14. unescapeHTML,
  15. )
  16. class BlipTVIE(InfoExtractor):
  17. """Information extractor for blip.tv"""
  18. _VALID_URL = r'^(?:https?://)?(?:www\.)?blip\.tv/((.+/)|(play/)|(api\.swf#))(.+)$'
  19. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  20. IE_NAME = u'blip.tv'
  21. _TEST = {
  22. u'url': u'http://blip.tv/cbr/cbr-exclusive-gotham-city-imposters-bats-vs-jokerz-short-3-5796352',
  23. u'file': u'5779306.m4v',
  24. u'md5': u'80baf1ec5c3d2019037c1c707d676b9f',
  25. u'info_dict': {
  26. u"upload_date": u"20111205",
  27. u"description": u"md5:9bc31f227219cde65e47eeec8d2dc596",
  28. u"uploader": u"Comic Book Resources - CBR TV",
  29. u"title": u"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(u'%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(u'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. u'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(u'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. if 'additionalMedia' in data:
  74. formats = sorted(data['additionalMedia'], key=lambda f: int(f['media_height']))
  75. best_format = formats[-1]
  76. video_url = best_format['url']
  77. else:
  78. video_url = data['media']['url']
  79. umobj = re.match(self._URL_EXT, video_url)
  80. if umobj is None:
  81. raise ValueError('Can not determine filename extension')
  82. ext = umobj.group(1)
  83. return {
  84. 'id': compat_str(data['item_id']),
  85. 'url': video_url,
  86. 'uploader': data['display_name'],
  87. 'upload_date': upload_date,
  88. 'title': data['title'],
  89. 'ext': ext,
  90. 'format': data['media']['mimeType'],
  91. 'thumbnail': data['thumbnailUrl'],
  92. 'description': data['description'],
  93. 'player_url': data['embedUrl'],
  94. 'user_agent': 'iTunes/10.6.1',
  95. }
  96. except (ValueError, KeyError) as err:
  97. raise ExtractorError(u'Unable to parse video information: %s' % repr(err))
  98. class BlipTVUserIE(InfoExtractor):
  99. """Information Extractor for blip.tv users."""
  100. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  101. _PAGE_SIZE = 12
  102. IE_NAME = u'blip.tv:user'
  103. def _real_extract(self, url):
  104. # Extract username
  105. mobj = re.match(self._VALID_URL, url)
  106. if mobj is None:
  107. raise ExtractorError(u'Invalid URL: %s' % url)
  108. username = mobj.group(1)
  109. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  110. page = self._download_webpage(url, username, u'Downloading user page')
  111. mobj = re.search(r'data-users-id="([^"]+)"', page)
  112. page_base = page_base % mobj.group(1)
  113. # Download video ids using BlipTV Ajax calls. Result size per
  114. # query is limited (currently to 12 videos) so we need to query
  115. # page by page until there are no video ids - it means we got
  116. # all of them.
  117. video_ids = []
  118. pagenum = 1
  119. while True:
  120. url = page_base + "&page=" + str(pagenum)
  121. page = self._download_webpage(url, username,
  122. u'Downloading video ids from page %d' % pagenum)
  123. # Extract video identifiers
  124. ids_in_page = []
  125. for mobj in re.finditer(r'href="/([^"]+)"', page):
  126. if mobj.group(1) not in ids_in_page:
  127. ids_in_page.append(unescapeHTML(mobj.group(1)))
  128. video_ids.extend(ids_in_page)
  129. # A little optimization - if current page is not
  130. # "full", ie. does not contain PAGE_SIZE video ids then
  131. # we can assume that this page is the last one - there
  132. # are no more ids on further pages - no need to query
  133. # again.
  134. if len(ids_in_page) < self._PAGE_SIZE:
  135. break
  136. pagenum += 1
  137. urls = [u'http://blip.tv/%s' % video_id for video_id in video_ids]
  138. url_entries = [self.url_result(vurl, 'BlipTV') for vurl in urls]
  139. return [self.playlist_result(url_entries, playlist_title = username)]