twitch.py 14 KB

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