bliptv.py 6.2 KB

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