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