X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=youtube_dl%2Fextractor%2Ffunimation.py;h=8bbedca269233b2ba4bdd02febf7d8e63007feb4;hb=HEAD;hp=4f382ea6f597a2737fa640b3c4e9ac66d0fdb2a0;hpb=9c163950da803b11f50bff4562b38effaa000cd0;p=youtube-dl diff --git a/youtube_dl/extractor/funimation.py b/youtube_dl/extractor/funimation.py index 4f382ea6f..8bbedca26 100644 --- a/youtube_dl/extractor/funimation.py +++ b/youtube_dl/extractor/funimation.py @@ -1,154 +1,154 @@ # coding: utf-8 from __future__ import unicode_literals -import re +import random +import string from .common import InfoExtractor -from ..compat import compat_urllib_request +from ..compat import compat_HTTPError from ..utils import ( - clean_html, determine_ext, - encode_dict, - sanitized_Request, + int_or_none, + js_to_json, ExtractorError, urlencode_postdata ) class FunimationIE(InfoExtractor): - _VALID_URL = r'https?://(?:www\.)?funimation\.com/shows/[^/]+/videos/official/(?P[^/?#&]+)' + _VALID_URL = r'https?://(?:www\.)?funimation(?:\.com|now\.uk)/shows/[^/]+/(?P[^/?#&]+)' - _TEST = { - 'url': 'http://www.funimation.com/shows/air/videos/official/breeze', + _NETRC_MACHINE = 'funimation' + _TOKEN = None + + _TESTS = [{ + 'url': 'https://www.funimation.com/shows/hacksign/role-play/', 'info_dict': { - 'id': '658', - 'display_id': 'breeze', + 'id': '91144', + 'display_id': 'role-play', 'ext': 'mp4', - 'title': 'Air - 1 - Breeze', - 'description': 'md5:1769f43cd5fc130ace8fd87232207892', - 'thumbnail': 're:https?://.*\.jpg', + 'title': '.hack//SIGN - Role Play', + 'description': 'md5:b602bdc15eef4c9bbb201bb6e6a4a2dd', + 'thumbnail': r're:https?://.*\.jpg', }, - } - - def _download_webpage(self, url_or_request, video_id, note='Downloading webpage'): - HEADERS = { - 'User-Agent': 'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0', - } - if isinstance(url_or_request, compat_urllib_request.Request): - for header, value in HEADERS.items(): - url_or_request.add_header(header, value) - else: - url_or_request = sanitized_Request(url_or_request, headers=HEADERS) - response = super(FunimationIE, self)._download_webpage(url_or_request, video_id, note) - return response + 'params': { + # m3u8 download + 'skip_download': True, + }, + }, { + 'url': 'https://www.funimation.com/shows/attack-on-titan-junior-high/broadcast-dub-preview/', + 'info_dict': { + 'id': '210051', + 'display_id': 'broadcast-dub-preview', + 'ext': 'mp4', + 'title': 'Attack on Titan: Junior High - Broadcast Dub Preview', + 'thumbnail': r're:https?://.*\.(?:jpg|png)', + }, + 'params': { + # m3u8 download + 'skip_download': True, + }, + }, { + 'url': 'https://www.funimationnow.uk/shows/puzzle-dragons-x/drop-impact/simulcast/', + 'only_matching': True, + }] def _login(self): - (username, password) = self._get_login_info() + username, password = self._get_login_info() if username is None: return - data = urlencode_postdata(encode_dict({ - 'email_field': username, - 'password_field': password, - })) - login_request = sanitized_Request('http://www.funimation.com/login', data, headers={ - 'Content-Type': 'application/x-www-form-urlencoded' - }) - login = self._download_webpage( - login_request, None, 'Logging in as %s' % username) - if re.search(r'', login) is not None: - raise ExtractorError('Unable to login, wrong username or password.', expected=True) + try: + data = self._download_json( + 'https://prod-api-funimationnow.dadcdigital.com/api/auth/login/', + None, 'Logging in', data=urlencode_postdata({ + 'username': username, + 'password': password, + })) + self._TOKEN = data['token'] + except ExtractorError as e: + if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401: + error = self._parse_json(e.cause.read().decode(), None)['error'] + raise ExtractorError(error, expected=True) + raise def _real_initialize(self): self._login() def _real_extract(self, url): display_id = self._match_id(url) - webpage = self._download_webpage(url, display_id) - items = self._parse_json( - self._search_regex( - r'var\s+playersData\s*=\s*(\[.+?\]);\n', - webpage, 'players data'), - display_id)[0]['playlist'][0]['items'] - - item = next(item for item in items if item.get('itemAK') == display_id) - - ERRORS_MAP = { - 'ERROR_MATURE_CONTENT_LOGGED_IN': 'matureContentLoggedIn', - 'ERROR_MATURE_CONTENT_LOGGED_OUT': 'matureContentLoggedOut', - 'ERROR_SUBSCRIPTION_LOGGED_OUT': 'subscriptionLoggedOut', - 'ERROR_VIDEO_EXPIRED': 'videoExpired', - 'ERROR_TERRITORY_UNAVAILABLE': 'territoryUnavailable', - 'SVODBASIC_SUBSCRIPTION_IN_PLAYER': 'basicSubscription', - 'SVODNON_SUBSCRIPTION_IN_PLAYER': 'nonSubscription', - 'ERROR_PLAYER_NOT_RESPONDING': 'playerNotResponding', - 'ERROR_UNABLE_TO_CONNECT_TO_CDN': 'unableToConnectToCDN', - 'ERROR_STREAM_NOT_FOUND': 'streamNotFound', - } + def _search_kane(name): + return self._search_regex( + r"KANE_customdimensions\.%s\s*=\s*'([^']+)';" % name, + webpage, name, default=None) + + title_data = self._parse_json(self._search_regex( + r'TITLE_DATA\s*=\s*({[^}]+})', + webpage, 'title data', default=''), + display_id, js_to_json, fatal=False) or {} + + video_id = title_data.get('id') or self._search_regex([ + r"KANE_customdimensions.videoID\s*=\s*'(\d+)';", + r']+src="/player/(\d+)', + ], webpage, 'video_id', default=None) + if not video_id: + player_url = self._html_search_meta([ + 'al:web:url', + 'og:video:url', + 'og:video:secure_url', + ], webpage, fatal=True) + video_id = self._search_regex(r'/player/(\d+)', player_url, 'video id') + + title = episode = title_data.get('title') or _search_kane('videoTitle') or self._og_search_title(webpage) + series = _search_kane('showName') + if series: + title = '%s - %s' % (series, title) + description = self._html_search_meta(['description', 'og:description'], webpage, fatal=True) + + try: + headers = {} + if self._TOKEN: + headers['Authorization'] = 'Token %s' % self._TOKEN + sources = self._download_json( + 'https://www.funimation.com/api/showexperience/%s/' % video_id, + video_id, headers=headers, query={ + 'pinst_id': ''.join([random.choice(string.digits + string.ascii_letters) for _ in range(8)]), + })['items'] + except ExtractorError as e: + if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403: + error = self._parse_json(e.cause.read(), video_id)['errors'][0] + raise ExtractorError('%s said: %s' % ( + self.IE_NAME, error.get('detail') or error.get('title')), expected=True) + raise - error_messages = {} - video_error_messages = self._search_regex( - r'var\s+videoErrorMessages\s*=\s*({.+?});\n', - webpage, 'error messages', default=None) - if video_error_messages: - error_messages_json = self._parse_json(video_error_messages, display_id, fatal=False) - if error_messages_json: - for _, error in error_messages_json.items(): - type_ = error.get('type') - description = error.get('description') - content = error.get('content') - if type_ == 'text' and description and content: - error_message = ERRORS_MAP.get(description) - if error_message: - error_messages[error_message] = content - - errors = [] formats = [] - for video in item['videoSet']: - auth_token = video.get('authToken') - if not auth_token: + for source in sources: + source_url = source.get('src') + if not source_url: continue - funimation_id = video.get('FUNImationID') or video.get('videoId') - if not auth_token.startswith('?'): - auth_token = '?%s' % auth_token - for quality in ('sd', 'hd', 'hd1080'): - format_url = video.get('%sUrl' % quality) - if not format_url: - continue - if not format_url.startswith(('http', '//')): - errors.append(format_url) - continue - if determine_ext(format_url) == 'm3u8': - m3u8_formats = self._extract_m3u8_formats( - format_url + auth_token, display_id, 'mp4', entry_protocol='m3u8_native', - m3u8_id=funimation_id or 'hls', fatal=False) - if m3u8_formats: - formats.extend(m3u8_formats) - else: - formats.append({ - 'url': format_url + auth_token, - }) - - if not formats and errors: - raise ExtractorError( - '%s returned error: %s' - % (self.IE_NAME, clean_html(error_messages.get(errors[0], errors[0]))), - expected=True) - - title = item['title'] - artist = item.get('artist') - if artist: - title = '%s - %s' % (artist, title) - description = self._og_search_description(webpage) or item.get('description') - thumbnail = self._og_search_thumbnail(webpage) or item.get('posterUrl') - video_id = item.get('itemId') or display_id + source_type = source.get('videoType') or determine_ext(source_url) + if source_type == 'm3u8': + formats.extend(self._extract_m3u8_formats( + source_url, video_id, 'mp4', + m3u8_id='hls', fatal=False)) + else: + formats.append({ + 'format_id': source_type, + 'url': source_url, + }) + self._sort_formats(formats) return { 'id': video_id, 'display_id': display_id, 'title': title, 'description': description, - 'thumbnail': thumbnail, + 'thumbnail': self._og_search_thumbnail(webpage), + 'series': series, + 'season_number': int_or_none(title_data.get('seasonNum') or _search_kane('season')), + 'episode_number': int_or_none(title_data.get('episodeNum')), + 'episode': episode, + 'season_id': title_data.get('seriesId'), 'formats': formats, }