mtv.py 25 KB

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