Guest User

Untitled

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