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.

170 lines
6.5 KiB

10 years ago
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import base64
  4. import binascii
  5. import re
  6. import json
  7. from .common import InfoExtractor
  8. from ..utils import (
  9. ExtractorError,
  10. qualities,
  11. determine_ext,
  12. )
  13. from ..compat import compat_ord
  14. class TeamcocoIE(InfoExtractor):
  15. _VALID_URL = r'http://teamcoco\.com/video/(?P<video_id>[0-9]+)?/?(?P<display_id>.*)'
  16. _TESTS = [
  17. {
  18. 'url': 'http://teamcoco.com/video/80187/conan-becomes-a-mary-kay-beauty-consultant',
  19. 'md5': '3f7746aa0dc86de18df7539903d399ea',
  20. 'info_dict': {
  21. 'id': '80187',
  22. 'ext': 'mp4',
  23. 'title': 'Conan Becomes A Mary Kay Beauty Consultant',
  24. 'description': 'Mary Kay is perhaps the most trusted name in female beauty, so of course Conan is a natural choice to sell their products.',
  25. 'duration': 504,
  26. 'age_limit': 0,
  27. }
  28. }, {
  29. 'url': 'http://teamcoco.com/video/louis-ck-interview-george-w-bush',
  30. 'md5': 'cde9ba0fa3506f5f017ce11ead928f9a',
  31. 'info_dict': {
  32. 'id': '19705',
  33. 'ext': 'mp4',
  34. 'description': 'Louis C.K. got starstruck by George W. Bush, so what? Part one.',
  35. 'title': 'Louis C.K. Interview Pt. 1 11/3/11',
  36. 'duration': 288,
  37. 'age_limit': 0,
  38. }
  39. }, {
  40. 'url': 'http://teamcoco.com/video/timothy-olyphant-drinking-whiskey',
  41. 'info_dict': {
  42. 'id': '88748',
  43. 'ext': 'mp4',
  44. 'title': 'Timothy Olyphant Raises A Toast To “Justified”',
  45. 'description': 'md5:15501f23f020e793aeca761205e42c24',
  46. },
  47. 'params': {
  48. 'skip_download': True, # m3u8 downloads
  49. }
  50. }, {
  51. 'url': 'http://teamcoco.com/video/full-episode-mon-6-1-joel-mchale-jake-tapper-and-musical-guest-courtney-barnett?playlist=x;eyJ0eXBlIjoidGFnIiwiaWQiOjl9',
  52. 'info_dict': {
  53. 'id': '89341',
  54. 'ext': 'mp4',
  55. 'title': 'Full Episode - Mon. 6/1 - Joel McHale, Jake Tapper, And Musical Guest Courtney Barnett',
  56. 'description': 'Guests: Joel McHale, Jake Tapper, And Musical Guest Courtney Barnett',
  57. },
  58. 'params': {
  59. 'skip_download': True, # m3u8 downloads
  60. }
  61. }
  62. ]
  63. _VIDEO_ID_REGEXES = (
  64. r'"eVar42"\s*:\s*(\d+)',
  65. r'Ginger\.TeamCoco\.openInApp\("video",\s*"([^"]+)"',
  66. r'"id_not"\s*:\s*(\d+)'
  67. )
  68. def _real_extract(self, url):
  69. mobj = re.match(self._VALID_URL, url)
  70. display_id = mobj.group('display_id')
  71. webpage, urlh = self._download_webpage_handle(url, display_id)
  72. if 'src=expired' in urlh.geturl():
  73. raise ExtractorError('This video is expired.', expected=True)
  74. video_id = mobj.group('video_id')
  75. if not video_id:
  76. video_id = self._html_search_regex(
  77. self._VIDEO_ID_REGEXES, webpage, 'video id')
  78. data = None
  79. preload_codes = self._html_search_regex(
  80. r'(function.+)setTimeout\(function\(\)\{playlist',
  81. webpage, 'preload codes')
  82. base64_fragments = re.findall(r'"([a-zA-z0-9+/=]+)"', preload_codes)
  83. base64_fragments.remove('init')
  84. def _check_sequence(cur_fragments):
  85. if not cur_fragments:
  86. return
  87. for i in range(len(cur_fragments)):
  88. cur_sequence = (''.join(cur_fragments[i:] + cur_fragments[:i])).encode('ascii')
  89. try:
  90. raw_data = base64.b64decode(cur_sequence)
  91. if compat_ord(raw_data[0]) == compat_ord('{'):
  92. return json.loads(raw_data.decode('utf-8'))
  93. except (TypeError, binascii.Error, UnicodeDecodeError, ValueError):
  94. continue
  95. def _check_data():
  96. for i in range(len(base64_fragments) + 1):
  97. for j in range(i, len(base64_fragments) + 1):
  98. data = _check_sequence(base64_fragments[:i] + base64_fragments[j:])
  99. if data:
  100. return data
  101. self.to_screen('Try to compute possible data sequence. This may take some time.')
  102. data = _check_data()
  103. if not data:
  104. raise ExtractorError(
  105. 'Preload information could not be extracted', expected=True)
  106. formats = []
  107. get_quality = qualities(['500k', '480p', '1000k', '720p', '1080p'])
  108. for filed in data['files']:
  109. if determine_ext(filed['url']) == 'm3u8':
  110. # compat_urllib_parse.urljoin does not work here
  111. if filed['url'].startswith('/'):
  112. m3u8_url = 'http://ht.cdn.turner.com/tbs/big/teamcoco' + filed['url']
  113. else:
  114. m3u8_url = filed['url']
  115. m3u8_formats = self._extract_m3u8_formats(
  116. m3u8_url, video_id, ext='mp4')
  117. for m3u8_format in m3u8_formats:
  118. if m3u8_format not in formats:
  119. formats.append(m3u8_format)
  120. elif determine_ext(filed['url']) == 'f4m':
  121. # TODO Correct f4m extraction
  122. continue
  123. else:
  124. if filed['url'].startswith('/mp4:protected/'):
  125. # TODO Correct extraction for these files
  126. continue
  127. m_format = re.search(r'(\d+(k|p))\.mp4', filed['url'])
  128. if m_format is not None:
  129. format_id = m_format.group(1)
  130. else:
  131. format_id = filed['bitrate']
  132. tbr = (
  133. int(filed['bitrate'])
  134. if filed['bitrate'].isdigit()
  135. else None)
  136. formats.append({
  137. 'url': filed['url'],
  138. 'ext': 'mp4',
  139. 'tbr': tbr,
  140. 'format_id': format_id,
  141. 'quality': get_quality(format_id),
  142. })
  143. self._sort_formats(formats)
  144. return {
  145. 'id': video_id,
  146. 'display_id': display_id,
  147. 'formats': formats,
  148. 'title': data['title'],
  149. 'thumbnail': data.get('thumb', {}).get('href'),
  150. 'description': data.get('teaser'),
  151. 'duration': data.get('duration'),
  152. 'age_limit': self._family_friendly_search(webpage),
  153. }