twitch.py 12 KB

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