mtv.py 25 KB

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