twitch.py 14 KB

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