twitch.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import itertools
  4. import re
  5. import random
  6. from .common import InfoExtractor
  7. from ..compat import (
  8. compat_parse_qs,
  9. compat_str,
  10. compat_urllib_parse,
  11. compat_urllib_parse_urlparse,
  12. compat_urllib_request,
  13. )
  14. from ..utils import (
  15. ExtractorError,
  16. int_or_none,
  17. parse_duration,
  18. parse_iso8601,
  19. )
  20. class TwitchBaseIE(InfoExtractor):
  21. _VALID_URL_BASE = r'https?://(?:www\.)?twitch\.tv'
  22. _API_BASE = 'https://api.twitch.tv'
  23. _USHER_BASE = 'http://usher.twitch.tv'
  24. _LOGIN_URL = 'https://secure.twitch.tv/login'
  25. _LOGIN_POST_URL = 'https://passport.twitch.tv/authorize'
  26. _NETRC_MACHINE = 'twitch'
  27. def _handle_error(self, response):
  28. if not isinstance(response, dict):
  29. return
  30. error = response.get('error')
  31. if error:
  32. raise ExtractorError(
  33. '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
  34. expected=True)
  35. def _download_json(self, url, video_id, note='Downloading JSON metadata'):
  36. headers = {
  37. 'Referer': 'http://api.twitch.tv/crossdomain/receiver.html?v=2',
  38. 'X-Requested-With': 'XMLHttpRequest',
  39. }
  40. for cookie in self._downloader.cookiejar:
  41. if cookie.name == 'api_token':
  42. headers['Twitch-Api-Token'] = cookie.value
  43. request = compat_urllib_request.Request(url, headers=headers)
  44. response = super(TwitchBaseIE, self)._download_json(request, video_id, note)
  45. self._handle_error(response)
  46. return response
  47. def _real_initialize(self):
  48. self._login()
  49. def _login(self):
  50. (username, password) = self._get_login_info()
  51. if username is None:
  52. return
  53. login_page = self._download_webpage(
  54. self._LOGIN_URL, None, 'Downloading login page')
  55. login_form = self._hidden_inputs(login_page)
  56. login_form.update({
  57. 'login': username.encode('utf-8'),
  58. 'password': password.encode('utf-8'),
  59. })
  60. request = compat_urllib_request.Request(
  61. self._LOGIN_POST_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
  62. request.add_header('Referer', self._LOGIN_URL)
  63. response = self._download_webpage(
  64. request, None, 'Logging in as %s' % username)
  65. error_message = self._search_regex(
  66. r'<div[^>]+class="subwindow_notice"[^>]*>([^<]+)</div>',
  67. response, 'error message', default=None)
  68. if error_message:
  69. raise ExtractorError(
  70. 'Unable to login. Twitch said: %s' % error_message, expected=True)
  71. if '>Reset your password<' in response:
  72. self.report_warning('Twitch asks you to reset your password, go to https://secure.twitch.tv/reset/submit')
  73. def _prefer_source(self, formats):
  74. try:
  75. source = next(f for f in formats if f['format_id'] == 'Source')
  76. source['preference'] = 10
  77. except StopIteration:
  78. pass # No Source stream present
  79. self._sort_formats(formats)
  80. class TwitchItemBaseIE(TwitchBaseIE):
  81. def _download_info(self, item, item_id):
  82. return self._extract_info(self._download_json(
  83. '%s/kraken/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
  84. 'Downloading %s info JSON' % self._ITEM_TYPE))
  85. def _extract_media(self, item_id):
  86. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  87. response = self._download_json(
  88. '%s/api/videos/%s%s' % (self._API_BASE, self._ITEM_SHORTCUT, item_id), item_id,
  89. 'Downloading %s playlist JSON' % self._ITEM_TYPE)
  90. entries = []
  91. chunks = response['chunks']
  92. qualities = list(chunks.keys())
  93. for num, fragment in enumerate(zip(*chunks.values()), start=1):
  94. formats = []
  95. for fmt_num, fragment_fmt in enumerate(fragment):
  96. format_id = qualities[fmt_num]
  97. fmt = {
  98. 'url': fragment_fmt['url'],
  99. 'format_id': format_id,
  100. 'quality': 1 if format_id == 'live' else 0,
  101. }
  102. m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
  103. if m:
  104. fmt['height'] = int(m.group('height'))
  105. formats.append(fmt)
  106. self._sort_formats(formats)
  107. entry = dict(info)
  108. entry['id'] = '%s_%d' % (entry['id'], num)
  109. entry['title'] = '%s part %d' % (entry['title'], num)
  110. entry['formats'] = formats
  111. entries.append(entry)
  112. return self.playlist_result(entries, info['id'], info['title'])
  113. def _extract_info(self, info):
  114. return {
  115. 'id': info['_id'],
  116. 'title': info.get('title') or 'Untitled Broadcast',
  117. 'description': info.get('description'),
  118. 'duration': int_or_none(info.get('length')),
  119. 'thumbnail': info.get('preview'),
  120. 'uploader': info.get('channel', {}).get('display_name'),
  121. 'uploader_id': info.get('channel', {}).get('name'),
  122. 'timestamp': parse_iso8601(info.get('recorded_at')),
  123. 'view_count': int_or_none(info.get('views')),
  124. }
  125. def _real_extract(self, url):
  126. return self._extract_media(self._match_id(url))
  127. class TwitchVideoIE(TwitchItemBaseIE):
  128. IE_NAME = 'twitch:video'
  129. _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
  130. _ITEM_TYPE = 'video'
  131. _ITEM_SHORTCUT = 'a'
  132. _TEST = {
  133. 'url': 'http://www.twitch.tv/riotgames/b/577357806',
  134. 'info_dict': {
  135. 'id': 'a577357806',
  136. 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
  137. },
  138. 'playlist_mincount': 12,
  139. }
  140. class TwitchChapterIE(TwitchItemBaseIE):
  141. IE_NAME = 'twitch:chapter'
  142. _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
  143. _ITEM_TYPE = 'chapter'
  144. _ITEM_SHORTCUT = 'c'
  145. _TESTS = [{
  146. 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
  147. 'info_dict': {
  148. 'id': 'c5285812',
  149. 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
  150. },
  151. 'playlist_mincount': 3,
  152. }, {
  153. 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
  154. 'only_matching': True,
  155. }]
  156. class TwitchVodIE(TwitchItemBaseIE):
  157. IE_NAME = 'twitch:vod'
  158. _VALID_URL = r'%s/[^/]+/v/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
  159. _ITEM_TYPE = 'vod'
  160. _ITEM_SHORTCUT = 'v'
  161. _TEST = {
  162. 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
  163. 'info_dict': {
  164. 'id': 'v6528877',
  165. 'ext': 'mp4',
  166. 'title': 'LCK Summer Split - Week 6 Day 1',
  167. 'thumbnail': 're:^https?://.*\.jpg$',
  168. 'duration': 17208,
  169. 'timestamp': 1435131709,
  170. 'upload_date': '20150624',
  171. 'uploader': 'Riot Games',
  172. 'uploader_id': 'riotgames',
  173. 'view_count': int,
  174. 'start_time': 310,
  175. },
  176. 'params': {
  177. # m3u8 download
  178. 'skip_download': True,
  179. },
  180. }
  181. def _real_extract(self, url):
  182. item_id = self._match_id(url)
  183. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  184. access_token = self._download_json(
  185. '%s/api/vods/%s/access_token' % (self._API_BASE, item_id), item_id,
  186. 'Downloading %s access token' % self._ITEM_TYPE)
  187. formats = self._extract_m3u8_formats(
  188. '%s/vod/%s?nauth=%s&nauthsig=%s&allow_source=true'
  189. % (self._USHER_BASE, item_id, access_token['token'], access_token['sig']),
  190. item_id, 'mp4')
  191. self._prefer_source(formats)
  192. info['formats'] = formats
  193. parsed_url = compat_urllib_parse_urlparse(url)
  194. query = compat_parse_qs(parsed_url.query)
  195. if 't' in query:
  196. info['start_time'] = parse_duration(query['t'][0])
  197. return info
  198. class TwitchPlaylistBaseIE(TwitchBaseIE):
  199. _PLAYLIST_URL = '%s/kraken/channels/%%s/videos/?offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
  200. _PAGE_LIMIT = 100
  201. def _extract_playlist(self, channel_id):
  202. info = self._download_json(
  203. '%s/kraken/channels/%s' % (self._API_BASE, channel_id),
  204. channel_id, 'Downloading channel info JSON')
  205. channel_name = info.get('display_name') or info.get('name')
  206. entries = []
  207. offset = 0
  208. limit = self._PAGE_LIMIT
  209. for counter in itertools.count(1):
  210. response = self._download_json(
  211. self._PLAYLIST_URL % (channel_id, offset, limit),
  212. channel_id, 'Downloading %s videos JSON page %d' % (self._PLAYLIST_TYPE, counter))
  213. page_entries = self._extract_playlist_page(response)
  214. if not page_entries:
  215. break
  216. entries.extend(page_entries)
  217. offset += limit
  218. return self.playlist_result(
  219. [self.url_result(entry) for entry in set(entries)],
  220. channel_id, channel_name)
  221. def _extract_playlist_page(self, response):
  222. videos = response.get('videos')
  223. return [video['url'] for video in videos] if videos else []
  224. def _real_extract(self, url):
  225. return self._extract_playlist(self._match_id(url))
  226. class TwitchProfileIE(TwitchPlaylistBaseIE):
  227. IE_NAME = 'twitch:profile'
  228. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  229. _PLAYLIST_TYPE = 'profile'
  230. _TEST = {
  231. 'url': 'http://www.twitch.tv/vanillatv/profile',
  232. 'info_dict': {
  233. 'id': 'vanillatv',
  234. 'title': 'VanillaTV',
  235. },
  236. 'playlist_mincount': 412,
  237. }
  238. class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
  239. IE_NAME = 'twitch:past_broadcasts'
  240. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  241. _PLAYLIST_URL = TwitchPlaylistBaseIE._PLAYLIST_URL + '&broadcasts=true'
  242. _PLAYLIST_TYPE = 'past broadcasts'
  243. _TEST = {
  244. 'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
  245. 'info_dict': {
  246. 'id': 'spamfish',
  247. 'title': 'Spamfish',
  248. },
  249. 'playlist_mincount': 54,
  250. }
  251. class TwitchBookmarksIE(TwitchPlaylistBaseIE):
  252. IE_NAME = 'twitch:bookmarks'
  253. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/bookmarks/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  254. _PLAYLIST_URL = '%s/api/bookmark/?user=%%s&offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
  255. _PLAYLIST_TYPE = 'bookmarks'
  256. _TEST = {
  257. 'url': 'http://www.twitch.tv/ognos/profile/bookmarks',
  258. 'info_dict': {
  259. 'id': 'ognos',
  260. 'title': 'Ognos',
  261. },
  262. 'playlist_mincount': 3,
  263. }
  264. def _extract_playlist_page(self, response):
  265. entries = []
  266. for bookmark in response.get('bookmarks', []):
  267. video = bookmark.get('video')
  268. if not video:
  269. continue
  270. entries.append(video['url'])
  271. return entries
  272. class TwitchStreamIE(TwitchBaseIE):
  273. IE_NAME = 'twitch:stream'
  274. _VALID_URL = r'%s/(?P<id>[^/#?]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  275. _TESTS = [{
  276. 'url': 'http://www.twitch.tv/shroomztv',
  277. 'info_dict': {
  278. 'id': '12772022048',
  279. 'display_id': 'shroomztv',
  280. 'ext': 'mp4',
  281. 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  282. 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
  283. 'is_live': True,
  284. 'timestamp': 1421928037,
  285. 'upload_date': '20150122',
  286. 'uploader': 'ShroomzTV',
  287. 'uploader_id': 'shroomztv',
  288. 'view_count': int,
  289. },
  290. 'params': {
  291. # m3u8 download
  292. 'skip_download': True,
  293. },
  294. }, {
  295. 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
  296. 'only_matching': True,
  297. }]
  298. def _real_extract(self, url):
  299. channel_id = self._match_id(url)
  300. stream = self._download_json(
  301. '%s/kraken/streams/%s' % (self._API_BASE, channel_id), channel_id,
  302. 'Downloading stream JSON').get('stream')
  303. # Fallback on profile extraction if stream is offline
  304. if not stream:
  305. return self.url_result(
  306. 'http://www.twitch.tv/%s/profile' % channel_id,
  307. 'TwitchProfile', channel_id)
  308. # Channel name may be typed if different case than the original channel name
  309. # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
  310. # an invalid m3u8 URL. Working around by use of original channel name from stream
  311. # JSON and fallback to lowercase if it's not available.
  312. channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
  313. access_token = self._download_json(
  314. '%s/api/channels/%s/access_token' % (self._API_BASE, channel_id), channel_id,
  315. 'Downloading channel access token')
  316. query = {
  317. 'allow_source': 'true',
  318. 'p': random.randint(1000000, 10000000),
  319. 'player': 'twitchweb',
  320. 'segment_preference': '4',
  321. 'sig': access_token['sig'].encode('utf-8'),
  322. 'token': access_token['token'].encode('utf-8'),
  323. }
  324. formats = self._extract_m3u8_formats(
  325. '%s/api/channel/hls/%s.m3u8?%s'
  326. % (self._USHER_BASE, channel_id, compat_urllib_parse.urlencode(query)),
  327. channel_id, 'mp4')
  328. self._prefer_source(formats)
  329. view_count = stream.get('viewers')
  330. timestamp = parse_iso8601(stream.get('created_at'))
  331. channel = stream['channel']
  332. title = self._live_title(channel.get('display_name') or channel.get('name'))
  333. description = channel.get('status')
  334. thumbnails = []
  335. for thumbnail_key, thumbnail_url in stream['preview'].items():
  336. m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
  337. if not m:
  338. continue
  339. thumbnails.append({
  340. 'url': thumbnail_url,
  341. 'width': int(m.group('width')),
  342. 'height': int(m.group('height')),
  343. })
  344. return {
  345. 'id': compat_str(stream['_id']),
  346. 'display_id': channel_id,
  347. 'title': title,
  348. 'description': description,
  349. 'thumbnails': thumbnails,
  350. 'uploader': channel.get('display_name'),
  351. 'uploader_id': channel.get('name'),
  352. 'timestamp': timestamp,
  353. 'view_count': view_count,
  354. 'formats': formats,
  355. 'is_live': True,
  356. }