]> git.gir.st - subscriptionfeed.git/blob - app/common/innertube.py
switch browse endpoint from browse_ajax to youtubei/v1/browse
[subscriptionfeed.git] / app / common / innertube.py
1 # functions that deal with parsing data from youtube's internal API ("innertube")
2
3 from urllib.parse import parse_qs, urlparse
4 import re
5
6 def findall(obj, key):
7 """
8 given a list of dicts, where one dict contains a given key, return said key.
9 """
10 if obj is None: return []
11 return [ obj[key] for obj in obj if key in obj.keys() ]
12 def listget(obj, index, fallback=None):
13 if obj is None: return fallback
14 return next(iter(obj[index:]), fallback)
15 flatten = lambda l: [item for sublist in l for item in sublist] # https://stackoverflow.com/a/952952
16 first = lambda l: next(iter(l),{})
17 listfind = lambda obj,key: first(findall(obj,key))
18
19 class G:
20 """
21 null-coalescing version of dict.get() that also works on lists.
22
23 the | operator is overloaded to achieve similar looking code to jq(1) filters.
24 the first found key is used: dict(foo=1)|G('bar','foo') returns 1.
25 """
26 def __init__(self, *keys):
27 self.keys = keys
28 def __ror__(self, other):
29 for key in self.keys:
30 try: return other[key]
31 except: continue
32 return None
33 class _Text:
34 """ parses youtube's .runs[].text and .simpleText variants """
35 def __ror__(self, other): # Note: only returning runs[0], not concat'ing all!
36 return other|G('simpleText') or other|G('runs')|G(0)|G('text')
37 text = _Text()
38 class Select:
39 """ |Select('foo') returns the first foo in list, |Select(all='foo') returns all foos. """
40 def __init__(self, key=None, *, all=None):
41 self.key = key or all
42 self.all = all
43 def __ror__(self, other):
44 try: items = [ other[self.key] for other in other if self.key in other.keys() ]
45 except: items = []
46 return items if self.all else items|G(0)
47 class A:
48 """ apply """
49 def __init__(self, f, *args):
50 self.f = f
51 self.args = args
52 def __ror__(self, other):
53 return self.f(other, *self.args)
54 class _Int:
55 def __ror__(self, other):
56 try: return int(''.join(filter(str.isdigit, other)))
57 except: return None
58 int = _Int()
59
60
61 def prepare_searchresults(yt_results):
62 contents = listfind(yt_results, 'response') \
63 .get('contents',{})\
64 .get('twoColumnSearchResultsRenderer',{})\
65 .get('primaryContents',{})\
66 .get('sectionListRenderer',{})\
67 .get('contents',[])
68 contents = flatten([c.get('contents',[]) for c in contents|Select(all='itemSectionRenderer')])
69
70 return parse_result_items(contents)
71
72 def prepare_infocards(metadata):
73 cards = metadata.get('cards',{}).get('cardCollectionRenderer',{}).get('cards',[])
74 return list(filter(None, map(parse_infocard, cards)))
75
76 def prepare_endcards(metadata):
77 endsc = metadata.get('endscreen',{}).get('endscreenRenderer',{}).get('elements',[])
78 return list(filter(None, map(parse_endcard, endsc)))
79
80 def prepare_channel(response, channel_id):
81 if 'alerts' in response: # possibly got an error back
82 from flask import current_app
83 current_app.logger.error([(alert['alertRenderer']['type'],alert['alertRenderer']['text']['simpleText']) for alert in response['alerts']])
84 return None,None,[],[],False
85
86 meta1 = response.get('metadata',{}).get('channelMetadataRenderer',{})
87 meta2 = response.get('microformat',{}).get('microformatDataRenderer',{})
88 title = meta1.get('title', meta2.get('title'))
89 descr = meta1.get('description', meta2.get('description')) # meta2.description is capped at 160chars
90 thumb = mkthumbs(meta2.get('thumbnail',meta1.get('avatar',{})).get('thumbnails',{})) # .avatar ~ 900px
91
92 contents = response.get('continuationContents')
93 if not contents: # overran end of list
94 return title, descr, thumb, [], False
95
96 unparsed = contents.get('gridContinuation',{}).get('items') or \
97 contents.get('sectionListContinuation',{}).get('contents') or []
98 items, extra = parse_channel_items(unparsed, channel_id, title)
99 has_more = 'continuations' in (contents.get('gridContinuation') or
100 contents.get('sectionListContinuation') or {})
101
102 return title, descr, thumb, items, has_more
103
104 def prepare_playlist(result):
105 contents = result['continuationContents']
106 unparsed = contents['playlistVideoListContinuation'].get('contents',[])
107 has_more = 'continuations' in contents.get('playlistVideoListContinuation')
108
109 return list(filter(None, map(parse_playlist, unparsed))), has_more
110
111 def mkthumbs(thumbs):
112 output = {str(e['height']): e['url'] for e in thumbs}
113 largest=next(iter(sorted(output.keys(),reverse=True,key=int)),None)
114 return {**output, 'largest': largest}
115
116 def clean_url(url):
117 # externals URLs are redirected through youtube.com/redirect, but we
118 # may encounter internal URLs, too
119 return parse_qs(urlparse(url).query).get('q',[url])[0]
120
121 def toInt(s, fallback=0):
122 if s is None:
123 return fallback
124 try:
125 return int(''.join(filter(str.isdigit, s)))
126 except ValueError:
127 return fallback
128
129 # Remove left-/rightmost word from string:
130 delL = lambda s: s.partition(' ')[2]
131
132 def age(s):
133 if s is None: # missing from autogen'd music, some livestreams
134 return None
135 # Some livestreams have "Streamed 7 hours ago"
136 s = s.replace("Streamed ","")
137 # Now, everything should be in the form "1 year ago"
138 value, unit, _ = s.split(" ")
139 suffix = dict(
140 minute='min',
141 minutes='min',
142 ).get(unit, unit[0]) # first letter otherwise (e.g. year(s) => y)
143
144 return f"{value}{suffix}"
145
146 def log_unknown_card(data):
147 import json
148 try:
149 from flask import request
150 source = request.url
151 except: source = "unknown"
152 with open("/tmp/innertube.err", "a") as f:
153 f.write(f"\n/***** {source} *****/\n")
154 json.dump(data, f, indent=2)
155
156 def parse_result_items(items):
157 # TODO: use .get() for most non-essential attributes
158 """
159 parses youtube search response into an easier to use format.
160 """
161 results = []
162 extras = []
163 for item in items:
164 key = next(iter(item.keys()), None)
165 content = item[key]
166 if key == 'videoRenderer':
167 results.append({'type': 'VIDEO', 'content': {
168 'video_id': content['videoId'],
169 'title': content['title']|G.text,
170 'author': content|G('longBylineText','shortBylineText')|G.text,
171 'channel_id': content|G('ownerText')|G('runs')|G(0) \
172 |G('navigationEndpoint')|G('browseEndpoint')|G('browseId'),
173 'length': content|G('lengthText')|G.text, # "44:07", "1:41:50"
174 'views': content|G('viewCountText')|G.text|A.int or 0, # "1,234 {views|watching}", absent on 0 views
175 'published': content|G('publishedTimeText')|G('simpleText')|A(age),
176 'live': content|G('badges')|Select('metadataBadgeRenderer')|G('style')=='BADGE_STYLE_TYPE_LIVE_NOW',
177 }})
178 elif key in ['playlistRenderer', 'radioRenderer', 'showRenderer']: # radio == "Mix" playlist, show == normal playlist, specially displayed
179 results.append({'type': 'PLAYLIST', 'content': {
180 'playlist_id': content['navigationEndpoint']|G('watchEndpoint')|G('playlistId') or \
181 content|G('playlistId'), # COURSE/"learning playlist"
182 'video_id': content['navigationEndpoint']|G('watchEndpoint')|G('videoId') or \
183 videoid_from_thumbnail(content), # learning playlist
184 'title': content['title']|G.text,
185 # Note: learning playlists have no author/channel_id
186 'author': content|G('longBylineText','shortBylineText')|G.text,
187 'channel_id': content|G('longBylineText','shortBylineText')|G('runs')|G(0) \
188 |G('navigationEndpoint')|G('browseEndpoint')|G('browseId'),
189 'n_videos': content|G('videoCount')|A.int or \
190 content|G('videoCountShortText','videoCountText')|G.text, # "Mix" playlists
191 }})
192 elif key == 'channelRenderer':
193 results.append({'type': 'CHANNEL', 'content': {
194 'channel_id': content['channelId'],
195 'title': content['title']|G.text,
196 'icons': content['thumbnail']['thumbnails']|A(mkthumbs),
197 'subscribers': content|G('subscriberCountText')|G('simpleText'), # "2.47K subscribers"
198 }})
199 elif key == 'shelfRenderer':
200 subkey = next(iter(content['content'].keys()), None) #verticalListRenderer/horizontalMovieListRenderer
201 r, e = parse_result_items(content['content'][subkey]['items'])
202 results.extend(r)
203 extras.extend(e)
204 elif key in ['movieRenderer', 'gridMovieRenderer']: # movies to buy/rent
205 pass # gMR.{videoId,title.runs[].text,lengthText.simpleText}
206 elif key in ['carouselAdRenderer','searchPyvRenderer','promotedSparklesTextSearchRenderer']: # haha, no.
207 pass
208 elif key == 'horizontalCardListRenderer':
209 # suggested searches: .cards[].searchRefinementCardRenderer.query.runs[].text
210 pass
211 elif key == 'emergencyOneboxRenderer': # suicide prevention hotline
212 pass
213 elif key in ['clarificationRenderer', 'infoPanelContainerRenderer']: # COVID-19/conspiracy theory infos
214 pass
215 elif key == 'webAnswerRenderer': # "Result from the web"
216 pass
217 elif key == 'didYouMeanRenderer' or key == 'showingResultsForRenderer':
218 extras.append({
219 'type': 'spelling',
220 'query': content['correctedQueryEndpoint']['searchEndpoint']['query'], # non-misspelled query
221 'autocorrected': key == 'showingResultsForRenderer',
222 })
223 elif key == 'messageRenderer': # "No more results"
224 extras.append({
225 'type': 'message',
226 'message': content|G('title','text')|G.text,
227 })
228 elif key == 'backgroundPromoRenderer': # e.g. "no results"
229 extras.append({
230 'type': content['icon']['iconType'],
231 'message': content['title']|G.text,
232 })
233 else:
234 log_unknown_card(item)
235 return results, extras
236
237 def parse_infocard(card):
238 """
239 parses a single infocard into a format that's easier to handle.
240 """
241 card = card['cardRenderer']
242 ctype = list(card['content'].keys())[0]
243 content = card['content'][ctype]
244 if ctype == "pollRenderer":
245 return {'type': "POLL", 'content': {
246 'question': content['question']['simpleText'],
247 'answers': [(a['text']['simpleText'],a['numVotes']) \
248 for a in content['choices']],
249 }}
250 elif ctype == "videoInfoCardContentRenderer":
251 is_live = content.get('badge',{}).get('liveBadgeRenderer') is not None
252 return {'type': "VIDEO", 'content': {
253 'video_id': content['action']['watchEndpoint']['videoId'],
254 'title': content['videoTitle']['simpleText'],
255 'author': delL(content['channelName']['simpleText']),
256 'length': content.get('lengthString',{}).get('simpleText') \
257 if not is_live else "LIVE", # "23:03"
258 'views': toInt(content.get('viewCountText',{}).get('simpleText')),
259 # XXX: views sometimes "Starts: July 31, 2020 at 1:30 PM"
260 }}
261 elif ctype == "playlistInfoCardContentRenderer":
262 return {'type': "PLAYLIST", 'content': {
263 'playlist_id': content['action']['watchEndpoint']['playlistId'],
264 'video_id': content['action']['watchEndpoint']['videoId'],
265 'title': content['playlistTitle']['simpleText'],
266 'author': delL(content['channelName']['simpleText']),
267 'n_videos': toInt(content['playlistVideoCount']['simpleText']),
268 }}
269 elif ctype == "simpleCardContentRenderer" and \
270 'urlEndpoint' in content['command']:
271 return {'type': "WEBSITE", 'content': {
272 'url': clean_url(content['command']['urlEndpoint']['url']),
273 'domain': content['displayDomain']['simpleText'],
274 'title': content['title']['simpleText'],
275 # XXX: no thumbnails for infocards
276 }}
277 elif ctype == "collaboratorInfoCardContentRenderer":
278 return {'type': "CHANNEL", 'content': {
279 'channel_id': content['endpoint']['browseEndpoint']['browseId'],
280 'title': content['channelName']['simpleText'],
281 'icons': mkthumbs(content['channelAvatar']['thumbnails']),
282 'subscribers': content.get('subscriberCountText',{}).get('simpleText',''), # "545K subscribers"
283 }}
284 else:
285 log_unknown_card(card)
286 return None
287
288 def parse_endcard(card):
289 """
290 parses a single endcard into a format that's easier to handle.
291 """
292 card = card.get('endscreenElementRenderer', card) #only sometimes nested
293 ctype = card['style']
294 if ctype == "CHANNEL":
295 return {'type': ctype, 'content': {
296 'channel_id': card['endpoint']['browseEndpoint']['browseId'],
297 'title': card['title']['simpleText'],
298 'icons': mkthumbs(card['image']['thumbnails']),
299 }}
300 elif ctype == "VIDEO":
301 if not 'endpoint' in card: return None # title == "This video is unavailable."
302 return {'type': ctype, 'content': {
303 'video_id': card['endpoint']['watchEndpoint']['videoId'],
304 'title': card['title']['simpleText'],
305 'length': card['videoDuration']['simpleText'], # '12:21'
306 'views': toInt(card['metadata']['simpleText']),
307 # XXX: no channel name
308 }}
309 elif ctype == "PLAYLIST":
310 return {'type': ctype, 'content': {
311 'playlist_id': card['endpoint']['watchEndpoint']['playlistId'],
312 'video_id': card['endpoint']['watchEndpoint']['videoId'],
313 'title': card['title']['simpleText'],
314 'author': delL(card['metadata']['simpleText']),
315 'n_videos': toInt(card['playlistLength']['simpleText']),
316 }}
317 elif ctype == "WEBSITE" or ctype == "CREATOR_MERCHANDISE":
318 url = clean_url(card['endpoint']['urlEndpoint']['url'])
319 return {'type': "WEBSITE", 'content': {
320 'url': url,
321 'domain': urlparse(url).netloc,
322 'title': card['title']['simpleText'],
323 'icons': mkthumbs(card['image']['thumbnails']),
324 }}
325 else:
326 log_unknown_card(card)
327 return None
328
329 def videoid_from_thumbnail(content):
330 # learning playlist; example: PL96C35uN7xGJu6skU4TBYrIWxggkZBrF5 (/user/enyay/playlists)
331 return re.match(r"https?://i.ytimg.com/vi/([-_0-9a-zA-Z]{11})|()",
332 listget(listget(content.get('thumbnails',[]),0,{}).get('thumbnails',[]),0,{}).get('url','')
333 ).group(1)
334
335 def parse_channel_items(items, channel_id, author):
336 result = []
337 extra = []
338 for item in items:
339 key = next(iter(item.keys()), None)
340 content = item[key]
341 if key in ["gridVideoRenderer", "videoRenderer", "videoCardRenderer"]:
342 # only videoCardRenderer (topic channels) has author and channel, others fall back to supplied ones.
343 result.append({'type': 'VIDEO', 'content': {
344 'video_id': content['videoId'],
345 'title': content['title'].get('simpleText') or content['title'].get('runs',[{}])[0].get('text'),
346 'author': content.get('bylineText',{}).get('runs',[{}])[0].get('text') or author,
347 'channel_id': content.get('bylineText',{}).get('runs',[{}])[0] \
348 .get('navigationEndpoint',{}).get('browseEndpoint',{}).get('browseId') or channel_id,
349 'length': (content.get('lengthText',{}).get('simpleText') or # topic channel
350 listfind(content.get('thumbnailOverlays',[]),'thumbnailOverlayTimeStatusRenderer')
351 .get('text',{}).get('simpleText')),
352 # topic channel: .metadataText.simpleText = "22M views \u00b7 2 months ago"
353 'views': toInt(content.get('viewCountText',{}).get('simpleText')),
354 'published': age(content.get('publishedTimeText',{}).get('simpleText')),
355 }})
356 elif key == "gridPlaylistRenderer" or key == "playlistRenderer":
357 result.append({'type': 'PLAYLIST', 'content': {
358 'playlist_id': content['navigationEndpoint'].get('watchEndpoint',{}).get('playlistId') or content.get('playlistId'),
359 'video_id': content['navigationEndpoint'].get('watchEndpoint',{}).get('videoId',{}) or videoid_from_thumbnail(content),
360 'title': (content['title'].get('simpleText') or # playlistRenderer
361 content['title']['runs'][0]['text']), # gridPlaylistRenderer
362 'author': author,
363 'channel_id': channel_id,
364 'n_videos': toInt(content.get('videoCount') or # playlistRenderer
365 content.get('videoCountShortText',{}).get('simpleText') or # grid(1)
366 content.get('videoCountText',{}).get('runs',[{}])[0].get('text')), # grid(2)
367 }})
368 elif key == "showRenderer":
369 result.append({'type': 'PLAYLIST', 'content': {
370 'playlist_id': content['navigationEndpoint']['watchEndpoint']['playlistId'],
371 'video_id': content['navigationEndpoint']['watchEndpoint']['videoId'],
372 'title': content['title']['simpleText'],
373 'author': author,
374 'channel_id': channel_id,
375 'n_videos': None,
376 }})
377 elif key in ["itemSectionRenderer", "gridRenderer", "horizontalCardListRenderer"]:
378 newkey = {
379 "itemSectionRenderer": 'contents',
380 "gridRenderer": 'items',
381 "horizontalCardListRenderer": 'cards',
382 }.get(key)
383 r, e = parse_channel_items(content[newkey], channel_id, author)
384 result.extend(r)
385 extra.extend(e)
386 elif key == "shelfRenderer":
387 r, e = parse_channel_items([content['content']], channel_id, author)
388 result.extend(r)
389 extra.extend(e)
390 elif key == "messageRenderer":
391 # e.g. {'messageRenderer': {'text': {'runs': [{'text': 'This channel has no playlists.'}]}}}
392 pass
393 elif key == "gameCardRenderer":
394 pass
395 else:
396 log_unknown_card(item)
397
398 return result, extra
399
400 def parse_playlist(item):
401 key = next(iter(item.keys()), None)
402 content = item[key]
403 if key == "playlistVideoRenderer":
404 if not content.get('isPlayable', False):
405 return None # private or deleted video
406
407 return {'type': 'VIDEO', 'content': {
408 'video_id': content['videoId'],
409 'title': (content['title'].get('simpleText') or # playable videos
410 content['title'].get('runs',[{}])[0].get('text')), # "[Private video]"
411 'playlist_id': content['navigationEndpoint']['watchEndpoint']['playlistId'],
412 'index': content['navigationEndpoint']['watchEndpoint'].get('index',0), #or int(content['index']['simpleText']) (absent on course intros; e.g. PL96C35uN7xGJu6skU4TBYrIWxggkZBrF5)
413 # rest is missing from unplayable videos:
414 'author': content.get('shortBylineText',{}).get('runs',[{}])[0].get('text'),
415 'channel_id':content.get('shortBylineText',{}).get('runs',[{}])[0].get('navigationEndpoint',{}).get('browseEndpoint',{}).get('browseId'),
416 'length': (content.get("lengthText",{}).get("simpleText") or # "8:51"
417 int(content.get("lengthSeconds", 0))), # "531"
418 'starttime': content['navigationEndpoint']['watchEndpoint'].get('startTimeSeconds'),
419 }}
420 else:
421 raise Exception(item) # XXX TODO
Imprint / Impressum