twitch.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. _TESTS = [{
  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. # Untitled broadcast (title is None)
  182. 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
  183. 'info_dict': {
  184. 'id': 'v11230755',
  185. 'ext': 'mp4',
  186. 'title': 'Untitled Broadcast',
  187. 'thumbnail': 're:^https?://.*\.jpg$',
  188. 'duration': 1638,
  189. 'timestamp': 1439746708,
  190. 'upload_date': '20150816',
  191. 'uploader': 'BelkAO_o',
  192. 'uploader_id': 'belkao_o',
  193. 'view_count': int,
  194. },
  195. 'params': {
  196. # m3u8 download
  197. 'skip_download': True,
  198. },
  199. }]
  200. def _real_extract(self, url):
  201. item_id = self._match_id(url)
  202. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  203. access_token = self._download_json(
  204. '%s/api/vods/%s/access_token' % (self._API_BASE, item_id), item_id,
  205. 'Downloading %s access token' % self._ITEM_TYPE)
  206. formats = self._extract_m3u8_formats(
  207. '%s/vod/%s?nauth=%s&nauthsig=%s&allow_source=true'
  208. % (self._USHER_BASE, item_id, access_token['token'], access_token['sig']),
  209. item_id, 'mp4')
  210. self._prefer_source(formats)
  211. info['formats'] = formats
  212. parsed_url = compat_urllib_parse_urlparse(url)
  213. query = compat_parse_qs(parsed_url.query)
  214. if 't' in query:
  215. info['start_time'] = parse_duration(query['t'][0])
  216. return info
  217. class TwitchPlaylistBaseIE(TwitchBaseIE):
  218. _PLAYLIST_URL = '%s/kraken/channels/%%s/videos/?offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
  219. _PAGE_LIMIT = 100
  220. def _extract_playlist(self, channel_id):
  221. info = self._download_json(
  222. '%s/kraken/channels/%s' % (self._API_BASE, channel_id),
  223. channel_id, 'Downloading channel info JSON')
  224. channel_name = info.get('display_name') or info.get('name')
  225. entries = []
  226. offset = 0
  227. limit = self._PAGE_LIMIT
  228. for counter in itertools.count(1):
  229. response = self._download_json(
  230. self._PLAYLIST_URL % (channel_id, offset, limit),
  231. channel_id, 'Downloading %s videos JSON page %d' % (self._PLAYLIST_TYPE, counter))
  232. page_entries = self._extract_playlist_page(response)
  233. if not page_entries:
  234. break
  235. entries.extend(page_entries)
  236. offset += limit
  237. return self.playlist_result(
  238. [self.url_result(entry) for entry in set(entries)],
  239. channel_id, channel_name)
  240. def _extract_playlist_page(self, response):
  241. videos = response.get('videos')
  242. return [video['url'] for video in videos] if videos else []
  243. def _real_extract(self, url):
  244. return self._extract_playlist(self._match_id(url))
  245. class TwitchProfileIE(TwitchPlaylistBaseIE):
  246. IE_NAME = 'twitch:profile'
  247. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  248. _PLAYLIST_TYPE = 'profile'
  249. _TEST = {
  250. 'url': 'http://www.twitch.tv/vanillatv/profile',
  251. 'info_dict': {
  252. 'id': 'vanillatv',
  253. 'title': 'VanillaTV',
  254. },
  255. 'playlist_mincount': 412,
  256. }
  257. class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
  258. IE_NAME = 'twitch:past_broadcasts'
  259. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  260. _PLAYLIST_URL = TwitchPlaylistBaseIE._PLAYLIST_URL + '&broadcasts=true'
  261. _PLAYLIST_TYPE = 'past broadcasts'
  262. _TEST = {
  263. 'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
  264. 'info_dict': {
  265. 'id': 'spamfish',
  266. 'title': 'Spamfish',
  267. },
  268. 'playlist_mincount': 54,
  269. }
  270. class TwitchBookmarksIE(TwitchPlaylistBaseIE):
  271. IE_NAME = 'twitch:bookmarks'
  272. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/bookmarks/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  273. _PLAYLIST_URL = '%s/api/bookmark/?user=%%s&offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
  274. _PLAYLIST_TYPE = 'bookmarks'
  275. _TEST = {
  276. 'url': 'http://www.twitch.tv/ognos/profile/bookmarks',
  277. 'info_dict': {
  278. 'id': 'ognos',
  279. 'title': 'Ognos',
  280. },
  281. 'playlist_mincount': 3,
  282. }
  283. def _extract_playlist_page(self, response):
  284. entries = []
  285. for bookmark in response.get('bookmarks', []):
  286. video = bookmark.get('video')
  287. if not video:
  288. continue
  289. entries.append(video['url'])
  290. return entries
  291. class TwitchStreamIE(TwitchBaseIE):
  292. IE_NAME = 'twitch:stream'
  293. _VALID_URL = r'%s/(?P<id>[^/#?]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  294. _TESTS = [{
  295. 'url': 'http://www.twitch.tv/shroomztv',
  296. 'info_dict': {
  297. 'id': '12772022048',
  298. 'display_id': 'shroomztv',
  299. 'ext': 'mp4',
  300. 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  301. 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
  302. 'is_live': True,
  303. 'timestamp': 1421928037,
  304. 'upload_date': '20150122',
  305. 'uploader': 'ShroomzTV',
  306. 'uploader_id': 'shroomztv',
  307. 'view_count': int,
  308. },
  309. 'params': {
  310. # m3u8 download
  311. 'skip_download': True,
  312. },
  313. }, {
  314. 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
  315. 'only_matching': True,
  316. }]
  317. def _real_extract(self, url):
  318. channel_id = self._match_id(url)
  319. stream = self._download_json(
  320. '%s/kraken/streams/%s' % (self._API_BASE, channel_id), channel_id,
  321. 'Downloading stream JSON').get('stream')
  322. # Fallback on profile extraction if stream is offline
  323. if not stream:
  324. return self.url_result(
  325. 'http://www.twitch.tv/%s/profile' % channel_id,
  326. 'TwitchProfile', channel_id)
  327. # Channel name may be typed if different case than the original channel name
  328. # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
  329. # an invalid m3u8 URL. Working around by use of original channel name from stream
  330. # JSON and fallback to lowercase if it's not available.
  331. channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
  332. access_token = self._download_json(
  333. '%s/api/channels/%s/access_token' % (self._API_BASE, channel_id), channel_id,
  334. 'Downloading channel access token')
  335. query = {
  336. 'allow_source': 'true',
  337. 'p': random.randint(1000000, 10000000),
  338. 'player': 'twitchweb',
  339. 'segment_preference': '4',
  340. 'sig': access_token['sig'].encode('utf-8'),
  341. 'token': access_token['token'].encode('utf-8'),
  342. }
  343. formats = self._extract_m3u8_formats(
  344. '%s/api/channel/hls/%s.m3u8?%s'
  345. % (self._USHER_BASE, channel_id, compat_urllib_parse.urlencode(query)),
  346. channel_id, 'mp4')
  347. self._prefer_source(formats)
  348. view_count = stream.get('viewers')
  349. timestamp = parse_iso8601(stream.get('created_at'))
  350. channel = stream['channel']
  351. title = self._live_title(channel.get('display_name') or channel.get('name'))
  352. description = channel.get('status')
  353. thumbnails = []
  354. for thumbnail_key, thumbnail_url in stream['preview'].items():
  355. m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
  356. if not m:
  357. continue
  358. thumbnails.append({
  359. 'url': thumbnail_url,
  360. 'width': int(m.group('width')),
  361. 'height': int(m.group('height')),
  362. })
  363. return {
  364. 'id': compat_str(stream['_id']),
  365. 'display_id': channel_id,
  366. 'title': title,
  367. 'description': description,
  368. 'thumbnails': thumbnails,
  369. 'uploader': channel.get('display_name'),
  370. 'uploader_id': channel.get('name'),
  371. 'timestamp': timestamp,
  372. 'view_count': view_count,
  373. 'formats': formats,
  374. 'is_live': True,
  375. }