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.

172 lines
6.2 KiB

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