bliptv.py 6.1 KB

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