twitch.py 13 KB

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