# coding: utf-8 from __future__ import unicode_literals import itertools import re import random from .common import InfoExtractor from ..compat import ( compat_parse_qs, compat_str, compat_urllib_parse_urlencode, compat_urllib_parse_urlparse, compat_urlparse, ) from ..utils import ( ExtractorError, int_or_none, js_to_json, orderedSet, parse_duration, parse_iso8601, urlencode_postdata, ) class TwitchBaseIE(InfoExtractor): _VALID_URL_BASE = r'https?://(?:www\.)?twitch\.tv' _API_BASE = 'https://api.twitch.tv' _USHER_BASE = 'https://usher.ttvnw.net' _LOGIN_URL = 'http://www.twitch.tv/login' _NETRC_MACHINE = 'twitch' def _handle_error(self, response): if not isinstance(response, dict): return error = response.get('error') if error: raise ExtractorError( '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')), expected=True) def _download_json(self, url, video_id, note='Downloading JSON metadata'): headers = { 'Referer': 'http://api.twitch.tv/crossdomain/receiver.html?v=2', 'X-Requested-With': 'XMLHttpRequest', } for cookie in self._downloader.cookiejar: if cookie.name == 'api_token': headers['Twitch-Api-Token'] = cookie.value response = super(TwitchBaseIE, self)._download_json( url, video_id, note, headers=headers) self._handle_error(response) return response def _real_initialize(self): self._login() def _login(self): (username, password) = self._get_login_info() if username is None: return login_page, handle = self._download_webpage_handle( self._LOGIN_URL, None, 'Downloading login page') login_form = self._hidden_inputs(login_page) login_form.update({ 'username': username, 'password': password, }) redirect_url = handle.geturl() post_url = self._search_regex( r'