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