bliptv.py 6.7 KB

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