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.

188 lines
7.0 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?://)?(?:\w+\.)?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'b2d849efcf7ee18917e4b4d9ff37cafe',
  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. request = compat_urllib_request.Request(url)
  47. response = compat_urllib_request.urlopen(request)
  48. redirecturl = response.geturl()
  49. rurlp = compat_urllib_parse_urlparse(redirecturl)
  50. file_id = compat_parse_qs(rurlp.fragment)['file'][0].rpartition('/')[2]
  51. url = 'http://blip.tv/a/a-' + file_id
  52. return self._real_extract(url)
  53. if '?' in url:
  54. cchar = '&'
  55. else:
  56. cchar = '?'
  57. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  58. request = compat_urllib_request.Request(json_url)
  59. request.add_header('User-Agent', 'iTunes/10.6.1')
  60. self.report_extraction(mobj.group(1))
  61. info = None
  62. try:
  63. urlh = compat_urllib_request.urlopen(request)
  64. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  65. basename = url.split('/')[-1]
  66. title,ext = os.path.splitext(basename)
  67. title = title.decode('UTF-8')
  68. ext = ext.replace('.', '')
  69. self.report_direct_download(title)
  70. info = {
  71. 'id': title,
  72. 'url': url,
  73. 'uploader': None,
  74. 'upload_date': None,
  75. 'title': title,
  76. 'ext': ext,
  77. 'urlhandle': urlh
  78. }
  79. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  80. raise ExtractorError(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  81. if info is None: # Regular URL
  82. try:
  83. json_code_bytes = urlh.read()
  84. json_code = json_code_bytes.decode('utf-8')
  85. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  86. raise ExtractorError(u'Unable to read video info webpage: %s' % compat_str(err))
  87. try:
  88. json_data = json.loads(json_code)
  89. if 'Post' in json_data:
  90. data = json_data['Post']
  91. else:
  92. data = json_data
  93. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  94. video_url = data['media']['url']
  95. umobj = re.match(self._URL_EXT, video_url)
  96. if umobj is None:
  97. raise ValueError('Can not determine filename extension')
  98. ext = umobj.group(1)
  99. info = {
  100. 'id': data['item_id'],
  101. 'url': video_url,
  102. 'uploader': data['display_name'],
  103. 'upload_date': upload_date,
  104. 'title': data['title'],
  105. 'ext': ext,
  106. 'format': data['media']['mimeType'],
  107. 'thumbnail': data['thumbnailUrl'],
  108. 'description': data['description'],
  109. 'player_url': data['embedUrl'],
  110. 'user_agent': 'iTunes/10.6.1',
  111. }
  112. except (ValueError,KeyError) as err:
  113. raise ExtractorError(u'Unable to parse video information: %s' % repr(err))
  114. return [info]
  115. class BlipTVUserIE(InfoExtractor):
  116. """Information Extractor for blip.tv users."""
  117. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  118. _PAGE_SIZE = 12
  119. IE_NAME = u'blip.tv:user'
  120. def _real_extract(self, url):
  121. # Extract username
  122. mobj = re.match(self._VALID_URL, url)
  123. if mobj is None:
  124. raise ExtractorError(u'Invalid URL: %s' % url)
  125. username = mobj.group(1)
  126. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  127. page = self._download_webpage(url, username, u'Downloading user page')
  128. mobj = re.search(r'data-users-id="([^"]+)"', page)
  129. page_base = page_base % mobj.group(1)
  130. # Download video ids using BlipTV Ajax calls. Result size per
  131. # query is limited (currently to 12 videos) so we need to query
  132. # page by page until there are no video ids - it means we got
  133. # all of them.
  134. video_ids = []
  135. pagenum = 1
  136. while True:
  137. url = page_base + "&page=" + str(pagenum)
  138. page = self._download_webpage(url, username,
  139. u'Downloading video ids from page %d' % pagenum)
  140. # Extract video identifiers
  141. ids_in_page = []
  142. for mobj in re.finditer(r'href="/([^"]+)"', page):
  143. if mobj.group(1) not in ids_in_page:
  144. ids_in_page.append(unescapeHTML(mobj.group(1)))
  145. video_ids.extend(ids_in_page)
  146. # A little optimization - if current page is not
  147. # "full", ie. does not contain PAGE_SIZE video ids then
  148. # we can assume that this page is the last one - there
  149. # are no more ids on further pages - no need to query
  150. # again.
  151. if len(ids_in_page) < self._PAGE_SIZE:
  152. break
  153. pagenum += 1
  154. urls = [u'http://blip.tv/%s' % video_id for video_id in video_ids]
  155. url_entries = [self.url_result(url, 'BlipTV') for url in urls]
  156. return [self.playlist_result(url_entries, playlist_title = username)]