2 from __future__
import unicode_literals
8 from .common
import InfoExtractor
12 compat_urllib_request
,
20 class TwitchBaseIE(InfoExtractor
):
21 _VALID_URL_BASE
= r
'https?://(?:www\.)?twitch\.tv'
23 _API_BASE
= 'https://api.twitch.tv'
24 _USHER_BASE
= 'http://usher.twitch.tv'
25 _LOGIN_URL
= 'https://secure.twitch.tv/user/login'
27 def _handle_error(self
, response
):
28 if not isinstance(response
, dict):
30 error
= response
.get('error')
33 '%s returned error: %s - %s' % (self
.IE_NAME
, error
, response
.get('message')),
36 def _download_json(self
, url
, video_id
, note
='Downloading JSON metadata'):
37 response
= super(TwitchBaseIE
, self
)._download
_json
(url
, video_id
, note
)
38 self
._handle
_error
(response
)
41 def _real_initialize(self
):
45 (username
, password
) = self
._get
_login
_info
()
49 login_page
= self
._download
_webpage
(
50 self
._LOGIN
_URL
, None, 'Downloading login page')
52 authenticity_token
= self
._search
_regex
(
53 r
'<input name="authenticity_token" type="hidden" value="([^"]+)"',
54 login_page
, 'authenticity token')
57 'utf8': '✓'.encode('utf-8'),
58 'authenticity_token': authenticity_token
,
59 'redirect_on_login': '',
60 'embed_form': 'false',
61 'mp_source_action': '',
63 'user[login]': username
,
64 'user[password]': password
,
67 request
= compat_urllib_request
.Request(
68 self
._LOGIN
_URL
, compat_urllib_parse
.urlencode(login_form
).encode('utf-8'))
69 request
.add_header('Referer', self
._LOGIN
_URL
)
70 response
= self
._download
_webpage
(
71 request
, None, 'Logging in as %s' % username
)
74 r
"id=([\"'])login_error_message\1[^>]*>(?P<msg>[^<]+)", response)
77 'Unable to login
: %s' % m.group('msg
').strip(), expected=True)
80 class TwitchItemBaseIE(TwitchBaseIE):
81 def _download_info(self, item, item_id):
82 return self._extract_info(self._download_json(
83 '%s/kraken
/videos
/%s%s' % (self._API_BASE, item, item_id), item_id,
84 'Downloading
%s info JSON
' % self._ITEM_TYPE))
86 def _extract_media(self, item_id):
87 info = self._download_info(self._ITEM_SHORTCUT, item_id)
88 response = self._download_json(
89 '%s/api
/videos
/%s%s' % (self._API_BASE, self._ITEM_SHORTCUT, item_id), item_id,
90 'Downloading
%s playlist JSON
' % self._ITEM_TYPE)
92 chunks = response['chunks
']
93 qualities = list(chunks.keys())
94 for num, fragment in enumerate(zip(*chunks.values()), start=1):
96 for fmt_num, fragment_fmt in enumerate(fragment):
97 format_id = qualities[fmt_num]
99 'url
': fragment_fmt['url
'],
100 'format_id
': format_id,
101 'quality
': 1 if format_id == 'live
' else 0,
103 m = re.search(r'^
(?P
<height
>\d
+)[Pp
]', format_id)
105 fmt['height
'] = int(m.group('height
'))
107 self._sort_formats(formats)
109 entry['id'] = '%s_%d' % (entry['id'], num)
110 entry['title
'] = '%s part
%d' % (entry['title
'], num)
111 entry['formats
'] = formats
112 entries.append(entry)
113 return self.playlist_result(entries, info['id'], info['title
'])
115 def _extract_info(self, info):
118 'title
': info['title
'],
119 'description
': info['description
'],
120 'duration
': info['length
'],
121 'thumbnail
': info['preview
'],
122 'uploader
': info['channel
']['display_name
'],
123 'uploader_id
': info['channel
']['name
'],
124 'timestamp
': parse_iso8601(info['recorded_at
']),
125 'view_count
': info['views
'],
128 def _real_extract(self, url):
129 return self._extract_media(self._match_id(url))
132 class TwitchVideoIE(TwitchItemBaseIE):
133 IE_NAME = 'twitch
:video
'
134 _VALID_URL = r'%s/[^
/]+/b
/(?P
<id>[^
/]+)' % TwitchBaseIE._VALID_URL_BASE
139 'url
': 'http
://www
.twitch
.tv
/riotgames
/b
/577357806',
142 'title
': 'Worlds Semifinals
- Star Horn Royal Club vs
. OMG
',
144 'playlist_mincount
': 12,
148 class TwitchChapterIE(TwitchItemBaseIE):
149 IE_NAME = 'twitch
:chapter
'
150 _VALID_URL = r'%s/[^
/]+/c
/(?P
<id>[^
/]+)' % TwitchBaseIE._VALID_URL_BASE
151 _ITEM_TYPE = 'chapter
'
155 'url
': 'http
://www
.twitch
.tv
/acracingleague
/c
/5285812',
158 'title
': 'ACRL Off Season
- Sports Cars
@ Nordschleife
',
160 'playlist_mincount
': 3,
162 'url
': 'http
://www
.twitch
.tv
/tsm_theoddone
/c
/2349361',
163 'only_matching
': True,
167 class TwitchVodIE(TwitchItemBaseIE):
168 IE_NAME = 'twitch
:vod
'
169 _VALID_URL = r'%s/[^
/]+/v
/(?P
<id>[^
/]+)' % TwitchBaseIE._VALID_URL_BASE
174 'url
': 'http
://www
.twitch
.tv
/ksptv
/v
/3622000',
178 'title
': '''KSPTV: Squadcast: "Everyone's on vacation so here
's Dahud" Edition!''',
179 'thumbnail
': 're
:^https?
://.*\
.jpg$
',
181 'timestamp
': 1419028564,
182 'upload_date
': '20141219',
184 'uploader_id
': 'ksptv
',
189 'skip_download
': True,
193 def _real_extract(self, url):
194 item_id = self._match_id(url)
195 info = self._download_info(self._ITEM_SHORTCUT, item_id)
196 access_token = self._download_json(
197 '%s/api
/vods
/%s/access_token
' % (self._API_BASE, item_id), item_id,
198 'Downloading
%s access token
' % self._ITEM_TYPE)
199 formats = self._extract_m3u8_formats(
200 '%s/vod
/%s?nauth
=%s&nauthsig
=%s'
201 % (self._USHER_BASE, item_id, access_token['token
'], access_token['sig
']),
203 info['formats
'] = formats
207 class TwitchPlaylistBaseIE(TwitchBaseIE):
208 _PLAYLIST_URL = '%s/kraken
/channels
/%%s/videos
/?offset
=%%d&limit
=%%d' % TwitchBaseIE._API_BASE
211 def _extract_playlist(self, channel_id):
212 info = self._download_json(
213 '%s/kraken
/channels
/%s' % (self._API_BASE, channel_id),
214 channel_id, 'Downloading channel info JSON
')
215 channel_name = info.get('display_name
') or info.get('name
')
218 limit = self._PAGE_LIMIT
219 for counter in itertools.count(1):
220 response = self._download_json(
221 self._PLAYLIST_URL % (channel_id, offset, limit),
222 channel_id, 'Downloading
%s videos JSON page
%d' % (self._PLAYLIST_TYPE, counter))
223 page_entries = self._extract_playlist_page(response)
226 entries.extend(page_entries)
228 return self.playlist_result(
229 [self.url_result(entry) for entry in set(entries)],
230 channel_id, channel_name)
232 def _extract_playlist_page(self, response):
233 videos = response.get('videos
')
234 return [video['url
'] for video in videos] if videos else []
236 def _real_extract(self, url):
237 return self._extract_playlist(self._match_id(url))
240 class TwitchProfileIE(TwitchPlaylistBaseIE):
241 IE_NAME = 'twitch
:profile
'
242 _VALID_URL = r'%s/(?P
<id>[^
/]+)/profile
/?
(?
:\
#.*)?$' % TwitchBaseIE._VALID_URL_BASE
243 _PLAYLIST_TYPE
= 'profile'
246 'url': 'http://www.twitch.tv/vanillatv/profile',
249 'title': 'VanillaTV',
251 'playlist_mincount': 412,
255 class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE
):
256 IE_NAME
= 'twitch:past_broadcasts'
257 _VALID_URL
= r
'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE
._VALID
_URL
_BASE
258 _PLAYLIST_URL
= TwitchPlaylistBaseIE
._PLAYLIST
_URL
+ '&broadcasts=true'
259 _PLAYLIST_TYPE
= 'past broadcasts'
262 'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
267 'playlist_mincount': 54,
271 class TwitchBookmarksIE(TwitchPlaylistBaseIE
):
272 IE_NAME
= 'twitch:bookmarks'
273 _VALID_URL
= r
'%s/(?P<id>[^/]+)/profile/bookmarks/?(?:\#.*)?$' % TwitchBaseIE
._VALID
_URL
_BASE
274 _PLAYLIST_URL
= '%s/api/bookmark/?user=%%s&offset=%%d&limit=%%d' % TwitchBaseIE
._API
_BASE
275 _PLAYLIST_TYPE
= 'bookmarks'
278 'url': 'http://www.twitch.tv/ognos/profile/bookmarks',
283 'playlist_mincount': 3,
286 def _extract_playlist_page(self
, response
):
288 for bookmark
in response
.get('bookmarks', []):
289 video
= bookmark
.get('video')
292 entries
.append(video
['url'])
296 class TwitchStreamIE(TwitchBaseIE
):
297 IE_NAME
= 'twitch:stream'
298 _VALID_URL
= r
'%s/(?P<id>[^/]+)/?(?:\#.*)?$' % TwitchBaseIE
._VALID
_URL
_BASE
301 'url': 'http://www.twitch.tv/shroomztv',
304 'display_id': 'shroomztv',
306 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
307 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
309 'timestamp': 1421928037,
310 'upload_date': '20150122',
311 'uploader': 'ShroomzTV',
312 'uploader_id': 'shroomztv',
317 'skip_download': True,
321 def _real_extract(self
, url
):
322 channel_id
= self
._match
_id
(url
)
324 stream
= self
._download
_json
(
325 '%s/kraken/streams/%s' % (self
._API
_BASE
, channel_id
), channel_id
,
326 'Downloading stream JSON').get('stream')
328 # Fallback on profile extraction if stream is offline
330 return self
.url_result(
331 'http://www.twitch.tv/%s/profile' % channel_id
,
332 'TwitchProfile', channel_id
)
334 access_token
= self
._download
_json
(
335 '%s/api/channels/%s/access_token' % (self
._API
_BASE
, channel_id
), channel_id
,
336 'Downloading channel access token')
339 'allow_source': 'true',
340 'p': random
.randint(1000000, 10000000),
341 'player': 'twitchweb',
342 'segment_preference': '4',
343 'sig': access_token
['sig'],
344 'token': access_token
['token'],
347 formats
= self
._extract
_m
3u8_formats
(
348 '%s/api/channel/hls/%s.m3u8?%s'
349 % (self
._USHER
_BASE
, channel_id
, compat_urllib_parse
.urlencode(query
).encode('utf-8')),
352 view_count
= stream
.get('viewers')
353 timestamp
= parse_iso8601(stream
.get('created_at'))
355 channel
= stream
['channel']
356 title
= self
._live
_title
(channel
.get('display_name') or channel
.get('name'))
357 description
= channel
.get('status')
360 for thumbnail_key
, thumbnail_url
in stream
['preview'].items():
361 m
= re
.search(r
'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key
)
365 'url': thumbnail_url
,
366 'width': int(m
.group('width')),
367 'height': int(m
.group('height')),
371 'id': compat_str(stream
['_id']),
372 'display_id': channel_id
,
374 'description': description
,
375 'thumbnails': thumbnails
,
376 'uploader': channel
.get('display_name'),
377 'uploader_id': channel
.get('name'),
378 'timestamp': timestamp
,
379 'view_count': view_count
,