twitch.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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_urlencode,
  11. compat_urllib_parse_urlparse,
  12. compat_urlparse,
  13. )
  14. from ..utils import (
  15. ExtractorError,
  16. int_or_none,
  17. js_to_json,
  18. orderedSet,
  19. parse_duration,
  20. parse_iso8601,
  21. urlencode_postdata,
  22. )
  23. class TwitchBaseIE(InfoExtractor):
  24. _VALID_URL_BASE = r'https?://(?:www\.)?twitch\.tv'
  25. _API_BASE = 'https://api.twitch.tv'
  26. _USHER_BASE = 'https://usher.ttvnw.net'
  27. _LOGIN_URL = 'http://www.twitch.tv/login'
  28. _NETRC_MACHINE = 'twitch'
  29. def _handle_error(self, response):
  30. if not isinstance(response, dict):
  31. return
  32. error = response.get('error')
  33. if error:
  34. raise ExtractorError(
  35. '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
  36. expected=True)
  37. def _call_api(self, path, item_id, note):
  38. headers = {
  39. 'Referer': 'http://api.twitch.tv/crossdomain/receiver.html?v=2',
  40. 'X-Requested-With': 'XMLHttpRequest',
  41. }
  42. for cookie in self._downloader.cookiejar:
  43. if cookie.name == 'api_token':
  44. headers['Twitch-Api-Token'] = cookie.value
  45. response = self._download_json(
  46. '%s/%s' % (self._API_BASE, path), item_id, note)
  47. self._handle_error(response)
  48. return response
  49. def _real_initialize(self):
  50. self._login()
  51. def _login(self):
  52. (username, password) = self._get_login_info()
  53. if username is None:
  54. return
  55. login_page, handle = self._download_webpage_handle(
  56. self._LOGIN_URL, None, 'Downloading login page')
  57. login_form = self._hidden_inputs(login_page)
  58. login_form.update({
  59. 'username': username,
  60. 'password': password,
  61. })
  62. redirect_url = handle.geturl()
  63. post_url = self._search_regex(
  64. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
  65. 'post url', default=redirect_url, group='url')
  66. if not post_url.startswith('http'):
  67. post_url = compat_urlparse.urljoin(redirect_url, post_url)
  68. response = self._download_webpage(
  69. post_url, None, 'Logging in as %s' % username,
  70. data=urlencode_postdata(login_form),
  71. headers={'Referer': redirect_url})
  72. error_message = self._search_regex(
  73. r'<div[^>]+class="subwindow_notice"[^>]*>([^<]+)</div>',
  74. response, 'error message', default=None)
  75. if error_message:
  76. raise ExtractorError(
  77. 'Unable to login. Twitch said: %s' % error_message, expected=True)
  78. if '>Reset your password<' in response:
  79. self.report_warning('Twitch asks you to reset your password, go to https://secure.twitch.tv/reset/submit')
  80. def _prefer_source(self, formats):
  81. try:
  82. source = next(f for f in formats if f['format_id'] == 'Source')
  83. source['preference'] = 10
  84. except StopIteration:
  85. pass # No Source stream present
  86. self._sort_formats(formats)
  87. class TwitchItemBaseIE(TwitchBaseIE):
  88. def _download_info(self, item, item_id):
  89. return self._extract_info(self._call_api(
  90. 'kraken/videos/%s%s' % (item, item_id), item_id,
  91. 'Downloading %s info JSON' % self._ITEM_TYPE))
  92. def _extract_media(self, item_id):
  93. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  94. response = self._call_api(
  95. 'api/videos/%s%s' % (self._ITEM_SHORTCUT, item_id), item_id,
  96. 'Downloading %s playlist JSON' % self._ITEM_TYPE)
  97. entries = []
  98. chunks = response['chunks']
  99. qualities = list(chunks.keys())
  100. for num, fragment in enumerate(zip(*chunks.values()), start=1):
  101. formats = []
  102. for fmt_num, fragment_fmt in enumerate(fragment):
  103. format_id = qualities[fmt_num]
  104. fmt = {
  105. 'url': fragment_fmt['url'],
  106. 'format_id': format_id,
  107. 'quality': 1 if format_id == 'live' else 0,
  108. }
  109. m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
  110. if m:
  111. fmt['height'] = int(m.group('height'))
  112. formats.append(fmt)
  113. self._sort_formats(formats)
  114. entry = dict(info)
  115. entry['id'] = '%s_%d' % (entry['id'], num)
  116. entry['title'] = '%s part %d' % (entry['title'], num)
  117. entry['formats'] = formats
  118. entries.append(entry)
  119. return self.playlist_result(entries, info['id'], info['title'])
  120. def _extract_info(self, info):
  121. return {
  122. 'id': info['_id'],
  123. 'title': info.get('title') or 'Untitled Broadcast',
  124. 'description': info.get('description'),
  125. 'duration': int_or_none(info.get('length')),
  126. 'thumbnail': info.get('preview'),
  127. 'uploader': info.get('channel', {}).get('display_name'),
  128. 'uploader_id': info.get('channel', {}).get('name'),
  129. 'timestamp': parse_iso8601(info.get('recorded_at')),
  130. 'view_count': int_or_none(info.get('views')),
  131. }
  132. def _real_extract(self, url):
  133. return self._extract_media(self._match_id(url))
  134. class TwitchVideoIE(TwitchItemBaseIE):
  135. IE_NAME = 'twitch:video'
  136. _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
  137. _ITEM_TYPE = 'video'
  138. _ITEM_SHORTCUT = 'a'
  139. _TEST = {
  140. 'url': 'http://www.twitch.tv/riotgames/b/577357806',
  141. 'info_dict': {
  142. 'id': 'a577357806',
  143. 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
  144. },
  145. 'playlist_mincount': 12,
  146. 'skip': 'HTTP Error 404: Not Found',
  147. }
  148. class TwitchChapterIE(TwitchItemBaseIE):
  149. IE_NAME = 'twitch:chapter'
  150. _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
  151. _ITEM_TYPE = 'chapter'
  152. _ITEM_SHORTCUT = 'c'
  153. _TESTS = [{
  154. 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
  155. 'info_dict': {
  156. 'id': 'c5285812',
  157. 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
  158. },
  159. 'playlist_mincount': 3,
  160. 'skip': 'HTTP Error 404: Not Found',
  161. }, {
  162. 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
  163. 'only_matching': True,
  164. }]
  165. class TwitchVodIE(TwitchItemBaseIE):
  166. IE_NAME = 'twitch:vod'
  167. _VALID_URL = r'%s/[^/]+/v/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
  168. _ITEM_TYPE = 'vod'
  169. _ITEM_SHORTCUT = 'v'
  170. _TESTS = [{
  171. 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
  172. 'info_dict': {
  173. 'id': 'v6528877',
  174. 'ext': 'mp4',
  175. 'title': 'LCK Summer Split - Week 6 Day 1',
  176. 'thumbnail': 're:^https?://.*\.jpg$',
  177. 'duration': 17208,
  178. 'timestamp': 1435131709,
  179. 'upload_date': '20150624',
  180. 'uploader': 'Riot Games',
  181. 'uploader_id': 'riotgames',
  182. 'view_count': int,
  183. 'start_time': 310,
  184. },
  185. 'params': {
  186. # m3u8 download
  187. 'skip_download': True,
  188. },
  189. }, {
  190. # Untitled broadcast (title is None)
  191. 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
  192. 'info_dict': {
  193. 'id': 'v11230755',
  194. 'ext': 'mp4',
  195. 'title': 'Untitled Broadcast',
  196. 'thumbnail': 're:^https?://.*\.jpg$',
  197. 'duration': 1638,
  198. 'timestamp': 1439746708,
  199. 'upload_date': '20150816',
  200. 'uploader': 'BelkAO_o',
  201. 'uploader_id': 'belkao_o',
  202. 'view_count': int,
  203. },
  204. 'params': {
  205. # m3u8 download
  206. 'skip_download': True,
  207. },
  208. }]
  209. def _real_extract(self, url):
  210. item_id = self._match_id(url)
  211. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  212. access_token = self._call_api(
  213. 'api/vods/%s/access_token' % item_id, item_id,
  214. 'Downloading %s access token' % self._ITEM_TYPE)
  215. formats = self._extract_m3u8_formats(
  216. '%s/vod/%s?%s' % (
  217. self._USHER_BASE, item_id,
  218. compat_urllib_parse_urlencode({
  219. 'allow_source': 'true',
  220. 'allow_audio_only': 'true',
  221. 'allow_spectre': 'true',
  222. 'player': 'twitchweb',
  223. 'nauth': access_token['token'],
  224. 'nauthsig': access_token['sig'],
  225. })),
  226. item_id, 'mp4', entry_protocol='m3u8_native')
  227. self._prefer_source(formats)
  228. info['formats'] = formats
  229. parsed_url = compat_urllib_parse_urlparse(url)
  230. query = compat_parse_qs(parsed_url.query)
  231. if 't' in query:
  232. info['start_time'] = parse_duration(query['t'][0])
  233. return info
  234. class TwitchPlaylistBaseIE(TwitchBaseIE):
  235. _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d'
  236. _PAGE_LIMIT = 100
  237. def _extract_playlist(self, channel_id):
  238. info = self._call_api(
  239. 'kraken/channels/%s' % channel_id,
  240. channel_id, 'Downloading channel info JSON')
  241. channel_name = info.get('display_name') or info.get('name')
  242. entries = []
  243. offset = 0
  244. limit = self._PAGE_LIMIT
  245. broken_paging_detected = False
  246. counter_override = None
  247. for counter in itertools.count(1):
  248. response = self._call_api(
  249. self._PLAYLIST_PATH % (channel_id, offset, limit),
  250. channel_id,
  251. 'Downloading %s videos JSON page %s'
  252. % (self._PLAYLIST_TYPE, counter_override or counter))
  253. page_entries = self._extract_playlist_page(response)
  254. if not page_entries:
  255. break
  256. total = int_or_none(response.get('_total'))
  257. # Since the beginning of March 2016 twitch's paging mechanism
  258. # is completely broken on the twitch side. It simply ignores
  259. # a limit and returns the whole offset number of videos.
  260. # Working around by just requesting all videos at once.
  261. # Upd: pagination bug was fixed by twitch on 15.03.2016.
  262. if not broken_paging_detected and total and len(page_entries) > limit:
  263. self.report_warning(
  264. 'Twitch pagination is broken on twitch side, requesting all videos at once',
  265. channel_id)
  266. broken_paging_detected = True
  267. offset = total
  268. counter_override = '(all at once)'
  269. continue
  270. entries.extend(page_entries)
  271. if broken_paging_detected or total and len(page_entries) >= total:
  272. break
  273. offset += limit
  274. return self.playlist_result(
  275. [self.url_result(entry) for entry in orderedSet(entries)],
  276. channel_id, channel_name)
  277. def _extract_playlist_page(self, response):
  278. videos = response.get('videos')
  279. return [video['url'] for video in videos] if videos else []
  280. def _real_extract(self, url):
  281. return self._extract_playlist(self._match_id(url))
  282. class TwitchProfileIE(TwitchPlaylistBaseIE):
  283. IE_NAME = 'twitch:profile'
  284. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  285. _PLAYLIST_TYPE = 'profile'
  286. _TEST = {
  287. 'url': 'http://www.twitch.tv/vanillatv/profile',
  288. 'info_dict': {
  289. 'id': 'vanillatv',
  290. 'title': 'VanillaTV',
  291. },
  292. 'playlist_mincount': 412,
  293. }
  294. class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
  295. IE_NAME = 'twitch:past_broadcasts'
  296. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  297. _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcasts=true'
  298. _PLAYLIST_TYPE = 'past broadcasts'
  299. _TEST = {
  300. 'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
  301. 'info_dict': {
  302. 'id': 'spamfish',
  303. 'title': 'Spamfish',
  304. },
  305. 'playlist_mincount': 54,
  306. }
  307. class TwitchStreamIE(TwitchBaseIE):
  308. IE_NAME = 'twitch:stream'
  309. _VALID_URL = r'%s/(?P<id>[^/#?]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  310. _TESTS = [{
  311. 'url': 'http://www.twitch.tv/shroomztv',
  312. 'info_dict': {
  313. 'id': '12772022048',
  314. 'display_id': 'shroomztv',
  315. 'ext': 'mp4',
  316. 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  317. 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
  318. 'is_live': True,
  319. 'timestamp': 1421928037,
  320. 'upload_date': '20150122',
  321. 'uploader': 'ShroomzTV',
  322. 'uploader_id': 'shroomztv',
  323. 'view_count': int,
  324. },
  325. 'params': {
  326. # m3u8 download
  327. 'skip_download': True,
  328. },
  329. }, {
  330. 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
  331. 'only_matching': True,
  332. }]
  333. def _real_extract(self, url):
  334. channel_id = self._match_id(url)
  335. stream = self._call_api(
  336. 'kraken/streams/%s' % channel_id, channel_id,
  337. 'Downloading stream JSON').get('stream')
  338. # Fallback on profile extraction if stream is offline
  339. if not stream:
  340. return self.url_result(
  341. 'http://www.twitch.tv/%s/profile' % channel_id,
  342. 'TwitchProfile', channel_id)
  343. # Channel name may be typed if different case than the original channel name
  344. # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
  345. # an invalid m3u8 URL. Working around by use of original channel name from stream
  346. # JSON and fallback to lowercase if it's not available.
  347. channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
  348. access_token = self._call_api(
  349. 'api/channels/%s/access_token' % channel_id, channel_id,
  350. 'Downloading channel access token')
  351. query = {
  352. 'allow_source': 'true',
  353. 'allow_audio_only': 'true',
  354. 'p': random.randint(1000000, 10000000),
  355. 'player': 'twitchweb',
  356. 'segment_preference': '4',
  357. 'sig': access_token['sig'].encode('utf-8'),
  358. 'token': access_token['token'].encode('utf-8'),
  359. }
  360. formats = self._extract_m3u8_formats(
  361. '%s/api/channel/hls/%s.m3u8?%s'
  362. % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)),
  363. channel_id, 'mp4')
  364. self._prefer_source(formats)
  365. view_count = stream.get('viewers')
  366. timestamp = parse_iso8601(stream.get('created_at'))
  367. channel = stream['channel']
  368. title = self._live_title(channel.get('display_name') or channel.get('name'))
  369. description = channel.get('status')
  370. thumbnails = []
  371. for thumbnail_key, thumbnail_url in stream['preview'].items():
  372. m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
  373. if not m:
  374. continue
  375. thumbnails.append({
  376. 'url': thumbnail_url,
  377. 'width': int(m.group('width')),
  378. 'height': int(m.group('height')),
  379. })
  380. return {
  381. 'id': compat_str(stream['_id']),
  382. 'display_id': channel_id,
  383. 'title': title,
  384. 'description': description,
  385. 'thumbnails': thumbnails,
  386. 'uploader': channel.get('display_name'),
  387. 'uploader_id': channel.get('name'),
  388. 'timestamp': timestamp,
  389. 'view_count': view_count,
  390. 'formats': formats,
  391. 'is_live': True,
  392. }
  393. class TwitchClipsIE(InfoExtractor):
  394. IE_NAME = 'twitch:clips'
  395. _VALID_URL = r'https?://clips\.twitch\.tv/(?:[^/]+/)*(?P<id>[^/?#&]+)'
  396. _TESTS = [{
  397. 'url': 'https://clips.twitch.tv/ea/AggressiveCobraPoooound',
  398. 'md5': '761769e1eafce0ffebfb4089cb3847cd',
  399. 'info_dict': {
  400. 'id': 'AggressiveCobraPoooound',
  401. 'ext': 'mp4',
  402. 'title': 'EA Play 2016 Live from the Novo Theatre',
  403. 'thumbnail': 're:^https?://.*\.jpg',
  404. 'creator': 'EA',
  405. 'uploader': 'stereotype_',
  406. 'uploader_id': 'stereotype_',
  407. },
  408. }, {
  409. # multiple formats
  410. 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
  411. 'only_matching': True,
  412. }]
  413. def _real_extract(self, url):
  414. video_id = self._match_id(url)
  415. webpage = self._download_webpage(url, video_id)
  416. clip = self._parse_json(
  417. self._search_regex(
  418. r'(?s)clipInfo\s*=\s*({.+?});', webpage, 'clip info'),
  419. video_id, transform_source=js_to_json)
  420. title = clip.get('channel_title') or self._og_search_title(webpage)
  421. formats = [{
  422. 'url': option['source'],
  423. 'format_id': option.get('quality'),
  424. 'height': int_or_none(option.get('quality')),
  425. } for option in clip.get('quality_options', []) if option.get('source')]
  426. if not formats:
  427. formats = [{
  428. 'url': clip['clip_video_url'],
  429. }]
  430. self._sort_formats(formats)
  431. return {
  432. 'id': video_id,
  433. 'title': title,
  434. 'thumbnail': self._og_search_thumbnail(webpage),
  435. 'creator': clip.get('broadcaster_display_name') or clip.get('broadcaster_login'),
  436. 'uploader': clip.get('curator_login'),
  437. 'uploader_id': clip.get('curator_display_name'),
  438. 'formats': formats,
  439. }