mtv.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import (
  6. compat_str,
  7. compat_xpath,
  8. )
  9. from ..utils import (
  10. ExtractorError,
  11. find_xpath_attr,
  12. fix_xml_ampersands,
  13. float_or_none,
  14. HEADRequest,
  15. int_or_none,
  16. RegexNotFoundError,
  17. sanitized_Request,
  18. strip_or_none,
  19. timeconvert,
  20. try_get,
  21. unescapeHTML,
  22. update_url_query,
  23. url_basename,
  24. xpath_text,
  25. )
  26. def _media_xml_tag(tag):
  27. return '{http://search.yahoo.com/mrss/}%s' % tag
  28. class MTVServicesInfoExtractor(InfoExtractor):
  29. _MOBILE_TEMPLATE = None
  30. _LANG = None
  31. @staticmethod
  32. def _id_from_uri(uri):
  33. return uri.split(':')[-1]
  34. @staticmethod
  35. def _remove_template_parameter(url):
  36. # Remove the templates, like &device={device}
  37. return re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', url)
  38. def _get_feed_url(self, uri):
  39. return self._FEED_URL
  40. def _get_thumbnail_url(self, uri, itemdoc):
  41. search_path = '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail'))
  42. thumb_node = itemdoc.find(search_path)
  43. if thumb_node is None:
  44. return None
  45. return thumb_node.get('url') or thumb_node.text or None
  46. def _extract_mobile_video_formats(self, mtvn_id):
  47. webpage_url = self._MOBILE_TEMPLATE % mtvn_id
  48. req = sanitized_Request(webpage_url)
  49. # Otherwise we get a webpage that would execute some javascript
  50. req.add_header('User-Agent', 'curl/7')
  51. webpage = self._download_webpage(req, mtvn_id,
  52. 'Downloading mobile page')
  53. metrics_url = unescapeHTML(self._search_regex(r'<a href="(http://metrics.+?)"', webpage, 'url'))
  54. req = HEADRequest(metrics_url)
  55. response = self._request_webpage(req, mtvn_id, 'Resolving url')
  56. url = response.geturl()
  57. # Transform the url to get the best quality:
  58. url = re.sub(r'.+pxE=mp4', 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=0+_pxK=18639+_pxE=mp4', url, 1)
  59. return [{'url': url, 'ext': 'mp4'}]
  60. def _extract_video_formats(self, mdoc, mtvn_id, video_id):
  61. if re.match(r'.*/(error_country_block\.swf|geoblock\.mp4|copyright_error\.flv(?:\?geo\b.+?)?)$', mdoc.find('.//src').text) is not None:
  62. if mtvn_id is not None and self._MOBILE_TEMPLATE is not None:
  63. self.to_screen('The normal version is not available from your '
  64. 'country, trying with the mobile version')
  65. return self._extract_mobile_video_formats(mtvn_id)
  66. raise ExtractorError('This video is not available from your country.',
  67. expected=True)
  68. formats = []
  69. for rendition in mdoc.findall('.//rendition'):
  70. if rendition.get('method') == 'hls':
  71. hls_url = rendition.find('./src').text
  72. formats.extend(self._extract_m3u8_formats(
  73. hls_url, video_id, ext='mp4', entry_protocol='m3u8_native',
  74. m3u8_id='hls', fatal=False))
  75. else:
  76. # fms
  77. try:
  78. _, _, ext = rendition.attrib['type'].partition('/')
  79. rtmp_video_url = rendition.find('./src').text
  80. if 'error_not_available.swf' in rtmp_video_url:
  81. raise ExtractorError(
  82. '%s said: video is not available' % self.IE_NAME,
  83. expected=True)
  84. if rtmp_video_url.endswith('siteunavail.png'):
  85. continue
  86. formats.extend([{
  87. 'ext': 'flv' if rtmp_video_url.startswith('rtmp') else ext,
  88. 'url': rtmp_video_url,
  89. 'format_id': '-'.join(filter(None, [
  90. 'rtmp' if rtmp_video_url.startswith('rtmp') else None,
  91. rendition.get('bitrate')])),
  92. 'width': int(rendition.get('width')),
  93. 'height': int(rendition.get('height')),
  94. }])
  95. except (KeyError, TypeError):
  96. raise ExtractorError('Invalid rendition field.')
  97. if formats:
  98. self._sort_formats(formats)
  99. return formats
  100. def _extract_subtitles(self, mdoc, mtvn_id):
  101. subtitles = {}
  102. for transcript in mdoc.findall('.//transcript'):
  103. if transcript.get('kind') != 'captions':
  104. continue
  105. lang = transcript.get('srclang')
  106. for typographic in transcript.findall('./typographic'):
  107. sub_src = typographic.get('src')
  108. if not sub_src:
  109. continue
  110. ext = typographic.get('format')
  111. if ext == 'cea-608':
  112. ext = 'scc'
  113. subtitles.setdefault(lang, []).append({
  114. 'url': compat_str(sub_src),
  115. 'ext': ext
  116. })
  117. return subtitles
  118. def _get_video_info(self, itemdoc, use_hls=True):
  119. uri = itemdoc.find('guid').text
  120. video_id = self._id_from_uri(uri)
  121. self.report_extraction(video_id)
  122. content_el = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content')))
  123. mediagen_url = self._remove_template_parameter(content_el.attrib['url'])
  124. mediagen_url = mediagen_url.replace('device={device}', '')
  125. if 'acceptMethods' not in mediagen_url:
  126. mediagen_url += '&' if '?' in mediagen_url else '?'
  127. mediagen_url += 'acceptMethods='
  128. mediagen_url += 'hls' if use_hls else 'fms'
  129. mediagen_doc = self._download_xml(
  130. mediagen_url, video_id, 'Downloading video urls', fatal=False)
  131. if mediagen_doc is False:
  132. return None
  133. item = mediagen_doc.find('./video/item')
  134. if item is not None and item.get('type') == 'text':
  135. message = '%s returned error: ' % self.IE_NAME
  136. if item.get('code') is not None:
  137. message += '%s - ' % item.get('code')
  138. message += item.text
  139. raise ExtractorError(message, expected=True)
  140. description = strip_or_none(xpath_text(itemdoc, 'description'))
  141. timestamp = timeconvert(xpath_text(itemdoc, 'pubDate'))
  142. title_el = None
  143. if title_el is None:
  144. title_el = find_xpath_attr(
  145. itemdoc, './/{http://search.yahoo.com/mrss/}category',
  146. 'scheme', 'urn:mtvn:video_title')
  147. if title_el is None:
  148. title_el = itemdoc.find(compat_xpath('.//{http://search.yahoo.com/mrss/}title'))
  149. if title_el is None:
  150. title_el = itemdoc.find(compat_xpath('.//title'))
  151. if title_el.text is None:
  152. title_el = None
  153. title = title_el.text
  154. if title is None:
  155. raise ExtractorError('Could not find video title')
  156. title = title.strip()
  157. series = find_xpath_attr(
  158. itemdoc, './/{http://search.yahoo.com/mrss/}category',
  159. 'scheme', 'urn:mtvn:franchise')
  160. season = find_xpath_attr(
  161. itemdoc, './/{http://search.yahoo.com/mrss/}category',
  162. 'scheme', 'urn:mtvn:seasonN')
  163. episode = find_xpath_attr(
  164. itemdoc, './/{http://search.yahoo.com/mrss/}category',
  165. 'scheme', 'urn:mtvn:episodeN')
  166. series = series.text if series is not None else None
  167. season = season.text if season is not None else None
  168. episode = episode.text if episode is not None else None
  169. if season and episode:
  170. # episode number includes season, so remove it
  171. episode = re.sub(r'^%s' % season, '', episode)
  172. # This a short id that's used in the webpage urls
  173. mtvn_id = None
  174. mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
  175. 'scheme', 'urn:mtvn:id')
  176. if mtvn_id_node is not None:
  177. mtvn_id = mtvn_id_node.text
  178. formats = self._extract_video_formats(mediagen_doc, mtvn_id, video_id)
  179. # Some parts of complete video may be missing (e.g. missing Act 3 in
  180. # http://www.southpark.de/alle-episoden/s14e01-sexual-healing)
  181. if not formats:
  182. return None
  183. self._sort_formats(formats)
  184. return {
  185. 'title': title,
  186. 'formats': formats,
  187. 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
  188. 'id': video_id,
  189. 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
  190. 'description': description,
  191. 'duration': float_or_none(content_el.attrib.get('duration')),
  192. 'timestamp': timestamp,
  193. 'series': series,
  194. 'season_number': int_or_none(season),
  195. 'episode_number': int_or_none(episode),
  196. }
  197. def _get_feed_query(self, uri):
  198. data = {'uri': uri}
  199. if self._LANG:
  200. data['lang'] = self._LANG
  201. return data
  202. def _get_videos_info(self, uri, use_hls=True):
  203. video_id = self._id_from_uri(uri)
  204. feed_url = self._get_feed_url(uri)
  205. info_url = update_url_query(feed_url, self._get_feed_query(uri))
  206. return self._get_videos_info_from_url(info_url, video_id, use_hls)
  207. def _get_videos_info_from_url(self, url, video_id, use_hls=True):
  208. idoc = self._download_xml(
  209. url, video_id,
  210. 'Downloading info', transform_source=fix_xml_ampersands)
  211. title = xpath_text(idoc, './channel/title')
  212. description = xpath_text(idoc, './channel/description')
  213. entries = []
  214. for item in idoc.findall('.//item'):
  215. info = self._get_video_info(item, use_hls)
  216. if info:
  217. entries.append(info)
  218. # TODO: should be multi-video
  219. return self.playlist_result(
  220. entries, playlist_title=title, playlist_description=description)
  221. def _extract_triforce_mgid(self, webpage, data_zone=None, video_id=None):
  222. triforce_feed = self._parse_json(self._search_regex(
  223. r'triforceManifestFeed\s*=\s*({.+?})\s*;\s*\n', webpage,
  224. 'triforce feed', default='{}'), video_id, fatal=False)
  225. data_zone = self._search_regex(
  226. r'data-zone=(["\'])(?P<zone>.+?_lc_promo.*?)\1', webpage,
  227. 'data zone', default=data_zone, group='zone')
  228. feed_url = try_get(
  229. triforce_feed, lambda x: x['manifest']['zones'][data_zone]['feed'],
  230. compat_str)
  231. if not feed_url:
  232. return
  233. feed = self._download_json(feed_url, video_id, fatal=False)
  234. if not feed:
  235. return
  236. return try_get(feed, lambda x: x['result']['data']['id'], compat_str)
  237. @staticmethod
  238. def _extract_child_with_type(parent, t):
  239. for c in parent['children']:
  240. if c.get('type') == t:
  241. return c
  242. def _extract_mgid(self, webpage):
  243. try:
  244. # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
  245. # or http://media.mtvnservices.com/{mgid}
  246. og_url = self._og_search_video_url(webpage)
  247. mgid = url_basename(og_url)
  248. if mgid.endswith('.swf'):
  249. mgid = mgid[:-4]
  250. except RegexNotFoundError:
  251. mgid = None
  252. if mgid is None or ':' not in mgid:
  253. mgid = self._search_regex(
  254. [r'data-mgid="(.*?)"', r'swfobject\.embedSWF\(".*?(mgid:.*?)"'],
  255. webpage, 'mgid', default=None)
  256. if not mgid:
  257. sm4_embed = self._html_search_meta(
  258. 'sm4:video:embed', webpage, 'sm4 embed', default='')
  259. mgid = self._search_regex(
  260. r'embed/(mgid:.+?)["\'&?/]', sm4_embed, 'mgid', default=None)
  261. if not mgid:
  262. mgid = self._extract_triforce_mgid(webpage)
  263. if not mgid:
  264. data = self._parse_json(self._search_regex(
  265. r'__DATA__\s*=\s*({.+?});', webpage, 'data'), None)
  266. main_container = self._extract_child_with_type(data, 'MainContainer')
  267. ab_testing = self._extract_child_with_type(main_container, 'ABTesting')
  268. video_player = self._extract_child_with_type(ab_testing or main_container, 'VideoPlayer')
  269. mgid = video_player['props']['media']['video']['config']['uri']
  270. return mgid
  271. def _real_extract(self, url):
  272. title = url_basename(url)
  273. webpage = self._download_webpage(url, title)
  274. mgid = self._extract_mgid(webpage)
  275. videos_info = self._get_videos_info(mgid)
  276. return videos_info
  277. class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
  278. IE_NAME = 'mtvservices:embedded'
  279. _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
  280. _TEST = {
  281. # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
  282. 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
  283. 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
  284. 'info_dict': {
  285. 'id': '1043906',
  286. 'ext': 'mp4',
  287. 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
  288. 'description': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage as he tries summarizing "Game of Thrones" in under a minute.',
  289. 'timestamp': 1400126400,
  290. 'upload_date': '20140515',
  291. },
  292. }
  293. @staticmethod
  294. def _extract_url(webpage):
  295. mobj = re.search(
  296. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//media\.mtvnservices\.com/embed/.+?)\1', webpage)
  297. if mobj:
  298. return mobj.group('url')
  299. def _get_feed_url(self, uri):
  300. video_id = self._id_from_uri(uri)
  301. config = self._download_json(
  302. 'http://media.mtvnservices.com/pmt/e1/access/index.html?uri=%s&configtype=edge' % uri, video_id)
  303. return self._remove_template_parameter(config['feedWithQueryParams'])
  304. def _real_extract(self, url):
  305. mobj = re.match(self._VALID_URL, url)
  306. mgid = mobj.group('mgid')
  307. return self._get_videos_info(mgid)
  308. class MTVIE(MTVServicesInfoExtractor):
  309. IE_NAME = 'mtv'
  310. _VALID_URL = r'https?://(?:www\.)?mtv\.com/(?:video-clips|(?:full-)?episodes)/(?P<id>[^/?#.]+)'
  311. _FEED_URL = 'http://www.mtv.com/feeds/mrss/'
  312. _TESTS = [{
  313. 'url': 'http://www.mtv.com/video-clips/vl8qof/unlocking-the-truth-trailer',
  314. 'md5': '1edbcdf1e7628e414a8c5dcebca3d32b',
  315. 'info_dict': {
  316. 'id': '5e14040d-18a4-47c4-a582-43ff602de88e',
  317. 'ext': 'mp4',
  318. 'title': 'Unlocking The Truth|July 18, 2016|1|101|Trailer',
  319. 'description': '"Unlocking the Truth" premieres August 17th at 11/10c.',
  320. 'timestamp': 1468846800,
  321. 'upload_date': '20160718',
  322. },
  323. }, {
  324. 'url': 'http://www.mtv.com/full-episodes/94tujl/unlocking-the-truth-gates-of-hell-season-1-ep-101',
  325. 'only_matching': True,
  326. }, {
  327. 'url': 'http://www.mtv.com/episodes/g8xu7q/teen-mom-2-breaking-the-wall-season-7-ep-713',
  328. 'only_matching': True,
  329. }]
  330. class MTVJapanIE(MTVServicesInfoExtractor):
  331. IE_NAME = 'mtvjapan'
  332. _VALID_URL = r'https?://(?:www\.)?mtvjapan\.com/videos/(?P<id>[0-9a-z]+)'
  333. _TEST = {
  334. 'url': 'http://www.mtvjapan.com/videos/prayht/fresh-info-cadillac-escalade',
  335. 'info_dict': {
  336. 'id': 'bc01da03-6fe5-4284-8880-f291f4e368f5',
  337. 'ext': 'mp4',
  338. 'title': '【Fresh Info】Cadillac ESCALADE Sport Edition',
  339. },
  340. 'params': {
  341. 'skip_download': True,
  342. },
  343. }
  344. _GEO_COUNTRIES = ['JP']
  345. _FEED_URL = 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
  346. def _get_feed_query(self, uri):
  347. return {
  348. 'arcEp': 'mtvjapan.com',
  349. 'mgid': uri,
  350. }
  351. class MTVVideoIE(MTVServicesInfoExtractor):
  352. IE_NAME = 'mtv:video'
  353. _VALID_URL = r'''(?x)^https?://
  354. (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
  355. m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
  356. _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
  357. _TESTS = [
  358. {
  359. 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
  360. 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
  361. 'info_dict': {
  362. 'id': '853555',
  363. 'ext': 'mp4',
  364. 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
  365. 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
  366. 'timestamp': 1352610000,
  367. 'upload_date': '20121111',
  368. },
  369. },
  370. ]
  371. def _get_thumbnail_url(self, uri, itemdoc):
  372. return 'http://mtv.mtvnimages.com/uri/' + uri
  373. def _real_extract(self, url):
  374. mobj = re.match(self._VALID_URL, url)
  375. video_id = mobj.group('videoid')
  376. uri = mobj.groupdict().get('mgid')
  377. if uri is None:
  378. webpage = self._download_webpage(url, video_id)
  379. # Some videos come from Vevo.com
  380. m_vevo = re.search(
  381. r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
  382. if m_vevo:
  383. vevo_id = m_vevo.group(1)
  384. self.to_screen('Vevo video detected: %s' % vevo_id)
  385. return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
  386. uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
  387. return self._get_videos_info(uri)
  388. class MTVDEIE(MTVServicesInfoExtractor):
  389. IE_NAME = 'mtv.de'
  390. _VALID_URL = r'https?://(?:www\.)?mtv\.de/(?:musik/videoclips|folgen|news)/(?P<id>[0-9a-z]+)'
  391. _TESTS = [{
  392. 'url': 'http://www.mtv.de/musik/videoclips/2gpnv7/Traum',
  393. 'info_dict': {
  394. 'id': 'd5d472bc-f5b7-11e5-bffd-a4badb20dab5',
  395. 'ext': 'mp4',
  396. 'title': 'Traum',
  397. 'description': 'Traum',
  398. },
  399. 'params': {
  400. # rtmp download
  401. 'skip_download': True,
  402. },
  403. 'skip': 'Blocked at Travis CI',
  404. }, {
  405. # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97)
  406. 'url': 'http://www.mtv.de/folgen/6b1ylu/teen-mom-2-enthuellungen-S5-F1',
  407. 'info_dict': {
  408. 'id': '1e5a878b-31c5-11e7-a442-0e40cf2fc285',
  409. 'ext': 'mp4',
  410. 'title': 'Teen Mom 2',
  411. 'description': 'md5:dc65e357ef7e1085ed53e9e9d83146a7',
  412. },
  413. 'params': {
  414. # rtmp download
  415. 'skip_download': True,
  416. },
  417. 'skip': 'Blocked at Travis CI',
  418. }, {
  419. 'url': 'http://www.mtv.de/news/glolix/77491-mtv-movies-spotlight--pixels--teil-3',
  420. 'info_dict': {
  421. 'id': 'local_playlist-4e760566473c4c8c5344',
  422. 'ext': 'mp4',
  423. 'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1',
  424. 'description': 'MTV Movies Supercut',
  425. },
  426. 'params': {
  427. # rtmp download
  428. 'skip_download': True,
  429. },
  430. 'skip': 'Das Video kann zur Zeit nicht abgespielt werden.',
  431. }]
  432. _GEO_COUNTRIES = ['DE']
  433. _FEED_URL = 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
  434. def _get_feed_query(self, uri):
  435. return {
  436. 'arcEp': 'mtv.de',
  437. 'mgid': uri,
  438. }
  439. class MTVItaliaIE(MTVServicesInfoExtractor):
  440. IE_NAME = 'mtv.it'
  441. _VALID_URL = r'https?://(?:www\.)?mtv\.it/(?:episodi|video|musica)/(?P<id>[0-9a-z]+)'
  442. _TESTS = [{
  443. 'url': 'http://www.mtv.it/episodi/24bqab/mario-una-serie-di-maccio-capatonda-cavoli-amario-episodio-completo-S1-E1',
  444. 'info_dict': {
  445. 'id': '0f0fc78e-45fc-4cce-8f24-971c25477530',
  446. 'ext': 'mp4',
  447. 'title': 'Cavoli amario (episodio completo)',
  448. 'description': 'md5:4962bccea8fed5b7c03b295ae1340660',
  449. 'series': 'Mario - Una Serie Di Maccio Capatonda',
  450. 'season_number': 1,
  451. 'episode_number': 1,
  452. },
  453. 'params': {
  454. 'skip_download': True,
  455. },
  456. }]
  457. _GEO_COUNTRIES = ['IT']
  458. _FEED_URL = 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
  459. def _get_feed_query(self, uri):
  460. return {
  461. 'arcEp': 'mtv.it',
  462. 'mgid': uri,
  463. }
  464. class MTVItaliaProgrammaIE(MTVItaliaIE):
  465. IE_NAME = 'mtv.it:programma'
  466. _VALID_URL = r'https?://(?:www\.)?mtv\.it/(?:programmi|playlist)/(?P<id>[0-9a-z]+)'
  467. _TESTS = [{
  468. # program page: general
  469. 'url': 'http://www.mtv.it/programmi/s2rppv/mario-una-serie-di-maccio-capatonda',
  470. 'info_dict': {
  471. 'id': 'a6f155bc-8220-4640-aa43-9b95f64ffa3d',
  472. 'title': 'Mario - Una Serie Di Maccio Capatonda',
  473. 'description': 'md5:72fbffe1f77ccf4e90757dd4e3216153',
  474. },
  475. 'playlist_count': 2,
  476. 'params': {
  477. 'skip_download': True,
  478. },
  479. }, {
  480. # program page: specific season
  481. 'url': 'http://www.mtv.it/programmi/d9ncjf/mario-una-serie-di-maccio-capatonda-S2',
  482. 'info_dict': {
  483. 'id': '4deeb5d8-f272-490c-bde2-ff8d261c6dd1',
  484. 'title': 'Mario - Una Serie Di Maccio Capatonda - Stagione 2',
  485. },
  486. 'playlist_count': 34,
  487. 'params': {
  488. 'skip_download': True,
  489. },
  490. }, {
  491. # playlist page + redirect
  492. 'url': 'http://www.mtv.it/playlist/sexy-videos/ilctal',
  493. 'info_dict': {
  494. 'id': 'dee8f9ee-756d-493b-bf37-16d1d2783359',
  495. 'title': 'Sexy Videos',
  496. },
  497. 'playlist_mincount': 145,
  498. 'params': {
  499. 'skip_download': True,
  500. },
  501. }]
  502. _GEO_COUNTRIES = ['IT']
  503. _FEED_URL = 'http://www.mtv.it/feeds/triforce/manifest/v8'
  504. def _get_entries(self, title, url):
  505. while True:
  506. pg = self._search_regex(r'/(\d+)$', url, 'entries', '1')
  507. entries = self._download_json(url, title, 'page %s' % pg)
  508. url = try_get(
  509. entries, lambda x: x['result']['nextPageURL'], compat_str)
  510. entries = try_get(
  511. entries, (
  512. lambda x: x['result']['data']['items'],
  513. lambda x: x['result']['data']['seasons']),
  514. list)
  515. for entry in entries or []:
  516. if entry.get('canonicalURL'):
  517. yield self.url_result(entry['canonicalURL'])
  518. if not url:
  519. break
  520. def _real_extract(self, url):
  521. query = {'url': url}
  522. info_url = update_url_query(self._FEED_URL, query)
  523. video_id = self._match_id(url)
  524. info = self._download_json(info_url, video_id).get('manifest')
  525. redirect = try_get(
  526. info, lambda x: x['newLocation']['url'], compat_str)
  527. if redirect:
  528. return self.url_result(redirect)
  529. title = info.get('title')
  530. video_id = try_get(
  531. info, lambda x: x['reporting']['itemId'], compat_str)
  532. parent_id = try_get(
  533. info, lambda x: x['reporting']['parentId'], compat_str)
  534. playlist_url = current_url = None
  535. for z in (info.get('zones') or {}).values():
  536. if z.get('moduleName') in ('INTL_M304', 'INTL_M209'):
  537. info_url = z.get('feed')
  538. if z.get('moduleName') in ('INTL_M308', 'INTL_M317'):
  539. playlist_url = playlist_url or z.get('feed')
  540. if z.get('moduleName') in ('INTL_M300',):
  541. current_url = current_url or z.get('feed')
  542. if not info_url:
  543. raise ExtractorError('No info found')
  544. if video_id == parent_id:
  545. video_id = self._search_regex(
  546. r'([^\/]+)/[^\/]+$', info_url, 'video_id')
  547. info = self._download_json(info_url, video_id, 'Show infos')
  548. info = try_get(info, lambda x: x['result']['data'], dict)
  549. title = title or try_get(
  550. info, (
  551. lambda x: x['title'],
  552. lambda x: x['headline']),
  553. compat_str)
  554. description = try_get(info, lambda x: x['content'], compat_str)
  555. if current_url:
  556. season = try_get(
  557. self._download_json(playlist_url, video_id, 'Seasons info'),
  558. lambda x: x['result']['data'], dict)
  559. current = try_get(
  560. season, lambda x: x['currentSeason'], compat_str)
  561. seasons = try_get(
  562. season, lambda x: x['seasons'], list) or []
  563. if current in [s.get('eTitle') for s in seasons]:
  564. playlist_url = current_url
  565. title = re.sub(
  566. r'[-|]\s*(?:mtv\s*italia|programma|playlist)',
  567. '', title, flags=re.IGNORECASE).strip()
  568. return self.playlist_result(
  569. self._get_entries(title, playlist_url),
  570. video_id, title, description)