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.

179 lines
7.2 KiB

  1. import re
  2. import xml.etree.ElementTree
  3. from .common import InfoExtractor
  4. from ..utils import (
  5. compat_str,
  6. compat_urllib_parse,
  7. ExtractorError,
  8. unified_strdate,
  9. )
  10. class ComedyCentralIE(InfoExtractor):
  11. """Information extractor for The Daily Show and Colbert Report """
  12. # urls can be abbreviations like :thedailyshow or :colbert
  13. # urls for episodes like:
  14. # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
  15. # or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
  16. # or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
  17. _VALID_URL = r"""^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
  18. |(https?://)?(www\.)?
  19. (?P<showname>thedailyshow|colbertnation)\.com/
  20. (full-episodes/(?P<episode>.*)|
  21. (?P<clip>
  22. (the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
  23. |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)))))
  24. $"""
  25. _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
  26. _video_extensions = {
  27. '3500': 'mp4',
  28. '2200': 'mp4',
  29. '1700': 'mp4',
  30. '1200': 'mp4',
  31. '750': 'mp4',
  32. '400': 'mp4',
  33. }
  34. _video_dimensions = {
  35. '3500': '1280x720',
  36. '2200': '960x540',
  37. '1700': '768x432',
  38. '1200': '640x360',
  39. '750': '512x288',
  40. '400': '384x216',
  41. }
  42. @classmethod
  43. def suitable(cls, url):
  44. """Receives a URL and returns True if suitable for this IE."""
  45. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  46. def _print_formats(self, formats):
  47. print('Available formats:')
  48. for x in formats:
  49. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'mp4'), self._video_dimensions.get(x, '???')))
  50. def _real_extract(self, url):
  51. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  52. if mobj is None:
  53. raise ExtractorError(u'Invalid URL: %s' % url)
  54. if mobj.group('shortname'):
  55. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  56. url = u'http://www.thedailyshow.com/full-episodes/'
  57. else:
  58. url = u'http://www.colbertnation.com/full-episodes/'
  59. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  60. assert mobj is not None
  61. if mobj.group('clip'):
  62. if mobj.group('showname') == 'thedailyshow':
  63. epTitle = mobj.group('tdstitle')
  64. else:
  65. epTitle = mobj.group('cntitle')
  66. dlNewest = False
  67. else:
  68. dlNewest = not mobj.group('episode')
  69. if dlNewest:
  70. epTitle = mobj.group('showname')
  71. else:
  72. epTitle = mobj.group('episode')
  73. self.report_extraction(epTitle)
  74. webpage,htmlHandle = self._download_webpage_handle(url, epTitle)
  75. if dlNewest:
  76. url = htmlHandle.geturl()
  77. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  78. if mobj is None:
  79. raise ExtractorError(u'Invalid redirected URL: ' + url)
  80. if mobj.group('episode') == '':
  81. raise ExtractorError(u'Redirected URL is still not specific: ' + url)
  82. epTitle = mobj.group('episode')
  83. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
  84. if len(mMovieParams) == 0:
  85. # The Colbert Report embeds the information in a without
  86. # a URL prefix; so extract the alternate reference
  87. # and then add the URL prefix manually.
  88. altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video).*?:.*?)"', webpage)
  89. if len(altMovieParams) == 0:
  90. raise ExtractorError(u'unable to find Flash URL in webpage ' + url)
  91. else:
  92. mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
  93. uri = mMovieParams[0][1]
  94. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
  95. indexXml = self._download_webpage(indexUrl, epTitle,
  96. u'Downloading show index',
  97. u'unable to download episode index')
  98. results = []
  99. idoc = xml.etree.ElementTree.fromstring(indexXml)
  100. itemEls = idoc.findall('.//item')
  101. for partNum,itemEl in enumerate(itemEls):
  102. mediaId = itemEl.findall('./guid')[0].text
  103. shortMediaId = mediaId.split(':')[-1]
  104. showId = mediaId.split(':')[-2].replace('.com', '')
  105. officialTitle = itemEl.findall('./title')[0].text
  106. officialDate = unified_strdate(itemEl.findall('./pubDate')[0].text)
  107. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  108. compat_urllib_parse.urlencode({'uri': mediaId}))
  109. configXml = self._download_webpage(configUrl, epTitle,
  110. u'Downloading configuration for %s' % shortMediaId)
  111. cdoc = xml.etree.ElementTree.fromstring(configXml)
  112. turls = []
  113. for rendition in cdoc.findall('.//rendition'):
  114. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  115. turls.append(finfo)
  116. if len(turls) == 0:
  117. self._downloader.report_error(u'unable to download ' + mediaId + ': No videos found')
  118. continue
  119. if self._downloader.params.get('listformats', None):
  120. self._print_formats([i[0] for i in turls])
  121. return
  122. # For now, just pick the highest bitrate
  123. format,rtmp_video_url = turls[-1]
  124. # Get the format arg from the arg stream
  125. req_format = self._downloader.params.get('format', None)
  126. # Select format if we can find one
  127. for f,v in turls:
  128. if f == req_format:
  129. format, rtmp_video_url = f, v
  130. break
  131. m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp.comedystor/.*)$', rtmp_video_url)
  132. if not m:
  133. raise ExtractorError(u'Cannot transform RTMP url')
  134. base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
  135. video_url = base + m.group('finalid')
  136. effTitle = showId + u'-' + epTitle + u' part ' + compat_str(partNum+1)
  137. info = {
  138. 'id': shortMediaId,
  139. 'url': video_url,
  140. 'uploader': showId,
  141. 'upload_date': officialDate,
  142. 'title': effTitle,
  143. 'ext': 'mp4',
  144. 'format': format,
  145. 'thumbnail': None,
  146. 'description': officialTitle,
  147. }
  148. results.append(info)
  149. return results