]> git.gir.st - subscriptionfeed.git/blob - app/common/innertube.py
ignore useless info message search result
[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 return list(filter(None, map(parse_playlist, unparsed))), more
113
114 def mkthumbs(thumbs):
115 output = {str(e['height']): e['url'] for e in thumbs}
116 largest=next(iter(sorted(output.keys(),reverse=True,key=int)),None)
117 return {**output, 'largest': largest}
118
119 def clean_url(url):
120 # externals URLs are redirected through youtube.com/redirect, but we
121 # may encounter internal URLs, too
122 return parse_qs(urlparse(url).query).get('q',[url])[0]
123
124 def toInt(s, fallback=0):
125 if s is None:
126 return fallback
127 try:
128 return int(''.join(filter(str.isdigit, s)))
129 except ValueError:
130 return fallback
131
132 # Remove left-/rightmost word from string:
133 delL = lambda s: s.partition(' ')[2]
134
135 def age(s):
136 if s is None: # missing from autogen'd music, some livestreams
137 return None
138 # Some livestreams have "Streamed 7 hours ago"
139 s = s.replace("Streamed ","")
140 # Now, everything should be in the form "1 year ago"
141 value, unit, _ = s.split(" ")
142 suffix = dict(
143 minute='min',
144 minutes='min',
145 ).get(unit, unit[0]) # first letter otherwise (e.g. year(s) => y)
146
147 return f"{value}{suffix}"
148
149 def log_unknown_card(data):
150 import json
151 try:
152 from flask import request
153 source = request.url
154 except: source = "unknown"
155 with open("/tmp/innertube.err", "a", encoding="utf-8", errors="backslashreplace") as f:
156 f.write(f"\n/***** {source} *****/\n")
157 json.dump(data, f, indent=2)
158
159 def parse_result_items(items):
160 # TODO: use .get() for most non-essential attributes
161 """
162 parses youtube search response into an easier to use format.
163 """
164 results = []
165 extras = []
166 for item in items:
167 key = next(iter(item.keys()), None)
168 content = item[key]
169 if key == 'videoRenderer':
170 results.append({'type': 'VIDEO', 'content': {
171 'video_id': content['videoId'],
172 'title': content['title']|G.text,
173 'author': content|G('longBylineText','shortBylineText')|G.text,
174 'channel_id': content|G('ownerText')|G('runs')|G(0) \
175 |G('navigationEndpoint')|G('browseEndpoint')|G('browseId'),
176 'length': content|G('lengthText')|G.text, # "44:07", "1:41:50"
177 'views': content|G('viewCountText')|G.text|A.int or 0, # "1,234 {views|watching}", absent on 0 views
178 'published': content|G('publishedTimeText')|G('simpleText')|A(age),
179 'live': content|G('badges')|Select('metadataBadgeRenderer')|G('style')=='BADGE_STYLE_TYPE_LIVE_NOW',
180 }})
181 elif key in ['playlistRenderer', 'radioRenderer', 'showRenderer']: # radio == "Mix" playlist, show == normal playlist, specially displayed
182 results.append({'type': 'PLAYLIST', 'content': {
183 'playlist_id': content['navigationEndpoint']|G('watchEndpoint')|G('playlistId'),
184 'video_id': content['navigationEndpoint']|G('watchEndpoint')|G('videoId'),
185 'title': content['title']|G.text,
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','promotedSparklesWebRenderer']: # 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 == 'infoPanelContentRenderer': # "These results may be new or changing quickly"
218 pass
219 elif key == 'didYouMeanRenderer' or key == 'showingResultsForRenderer':
220 extras.append({
221 'type': 'spelling',
222 'query': content['correctedQueryEndpoint']['searchEndpoint']['query'], # non-misspelled query
223 'autocorrected': key == 'showingResultsForRenderer',
224 })
225 elif key == 'messageRenderer': # "No more results"
226 extras.append({
227 'type': 'message',
228 'message': content|G('title','text')|G.text,
229 })
230 elif key == 'backgroundPromoRenderer': # e.g. "no results"
231 extras.append({
232 'type': content['icon']['iconType'],
233 'message': content['title']|G.text,
234 })
235 else:
236 log_unknown_card(item)
237 return results, extras
238
239 def parse_infocard(card):
240 """
241 parses a single infocard into a format that's easier to handle.
242 """
243 card = card['cardRenderer']
244 ctype = list(card['content'].keys())[0]
245 content = card['content'][ctype]
246 if ctype == "pollRenderer":
247 return {'type': "POLL", 'content': {
248 'question': content['question']['simpleText'],
249 'answers': [(a['text']['simpleText'],a['numVotes']) \
250 for a in content['choices']],
251 }}
252 elif ctype == "videoInfoCardContentRenderer":
253 is_live = content.get('badge',{}).get('liveBadgeRenderer') is not None
254 return {'type': "VIDEO", 'content': {
255 'video_id': content['action']['watchEndpoint']['videoId'],
256 'title': content['videoTitle']['simpleText'],
257 'author': delL(content['channelName']['simpleText']),
258 'length': content.get('lengthString',{}).get('simpleText') \
259 if not is_live else "LIVE", # "23:03"
260 'views': toInt(content.get('viewCountText',{}).get('simpleText')),
261 # XXX: views sometimes "Starts: July 31, 2020 at 1:30 PM"
262 }}
263 elif ctype == "playlistInfoCardContentRenderer":
264 return {'type': "PLAYLIST", 'content': {
265 'playlist_id': content['action']['watchEndpoint']['playlistId'],
266 'video_id': content['action']['watchEndpoint']['videoId'],
267 'title': content['playlistTitle']['simpleText'],
268 'author': delL(content['channelName']['simpleText']),
269 'n_videos': toInt(content['playlistVideoCount']['simpleText']),
270 }}
271 elif ctype == "simpleCardContentRenderer" and \
272 'urlEndpoint' in content['command']:
273 return {'type': "WEBSITE", 'content': {
274 'url': clean_url(content['command']['urlEndpoint']['url']),
275 'domain': content['displayDomain']['simpleText'],
276 'title': content['title']['simpleText'],
277 # XXX: no thumbnails for infocards
278 }}
279 elif ctype == "collaboratorInfoCardContentRenderer":
280 return {'type': "CHANNEL", 'content': {
281 'channel_id': content['endpoint']['browseEndpoint']['browseId'],
282 'title': content['channelName']['simpleText'],
283 'icons': mkthumbs(content['channelAvatar']['thumbnails']),
284 'subscribers': content.get('subscriberCountText',{}).get('simpleText',''), # "545K subscribers"
285 }}
286 else:
287 log_unknown_card(card)
288 return None
289
290 def parse_endcard(card):
291 """
292 parses a single endcard into a format that's easier to handle.
293 """
294 card = card.get('endscreenElementRenderer', card) #only sometimes nested
295 ctype = card['style']
296 if ctype == "CHANNEL":
297 return {'type': ctype, 'content': {
298 'channel_id': card['endpoint']['browseEndpoint']['browseId'],
299 'title': card['title']|G.text,
300 'icons': mkthumbs(card['image']['thumbnails']),
301 }}
302 elif ctype == "VIDEO":
303 if not 'endpoint' in card: return None # title == "This video is unavailable."
304 return {'type': ctype, 'content': {
305 'video_id': card['endpoint']['watchEndpoint']['videoId'],
306 'title': card['title']|G.text,
307 'length': card['videoDuration']|G.text, # '12:21'
308 'views': toInt(card['metadata']|G.text),
309 # XXX: no channel name
310 }}
311 elif ctype == "PLAYLIST":
312 return {'type': ctype, 'content': {
313 'playlist_id': card['endpoint']['watchEndpoint']['playlistId'],
314 'video_id': card['endpoint']['watchEndpoint']['videoId'],
315 'title': card['title']|G.text,
316 'author': delL(card['metadata']|G.text),
317 'n_videos': toInt(card['playlistLength']|G.text),
318 }}
319 elif ctype == "WEBSITE" or ctype == "CREATOR_MERCHANDISE":
320 url = clean_url(card['endpoint']['urlEndpoint']['url'])
321 return {'type': "WEBSITE", 'content': {
322 'url': url,
323 'domain': urlparse(url).netloc,
324 'title': card['title']|G.text,
325 'icons': mkthumbs(card['image']['thumbnails']),
326 }}
327 else:
328 log_unknown_card(card)
329 return None
330
331 def parse_channel_items(items, channel_id, author):
332 result = []
333 extra = []
334 for item in items:
335 key = next(iter(item.keys()), None)
336 content = item[key]
337 if key in ["gridVideoRenderer", "videoRenderer", "videoCardRenderer"]:
338 # only videoCardRenderer (topic channels) has author and channel, others fall back to supplied ones.
339 result.append({'type': 'VIDEO', 'content': {
340 'video_id': content['videoId'],
341 'title': content|G('title')|G.text,
342 'author': content|G('bylineText')|G.text or author,
343 'channel_id': (content|G('bylineText')|G('runs')
344 |Select('navigationEndpoint')
345 |G('browseEndpoint')|G('browseId') or channel_id),
346 'length': (content|G('lengthText')|G.text or # topic channel
347 content|G('thumbnailOverlays')
348 |Select('thumbnailOverlayTimeStatusRenderer')
349 |G('text')|G.text),
350 # topic channel: .metadataText.simpleText = "22M views \u00b7 2 months ago"
351 'views': content|G('viewCountText')|G.text|A.int,
352 'published': content|G('publishedTimeText')|G.text|A(age),
353 }})
354 elif key == "gridPlaylistRenderer" or key == "playlistRenderer":
355 result.append({'type': 'PLAYLIST', 'content': {
356 'playlist_id': content|G('navigationEndpoint')|G('watchEndpoint')|G('playlistId'),
357 'video_id': content|G('navigationEndpoint')|G('watchEndpoint')|G('videoId'),
358 'title': content|G('title')|G.text,
359 'author': author,
360 'channel_id': channel_id,
361 'n_videos': (content|G('videoCount')|A.int or # playlistRenderer
362 content|G('videoCountShortText','videoCountText')|G.text|A.int) # grid
363 }})
364 elif key == "showRenderer":
365 result.append({'type': 'PLAYLIST', 'content': {
366 'playlist_id': content['navigationEndpoint']['watchEndpoint']['playlistId'],
367 'video_id': content['navigationEndpoint']['watchEndpoint']['videoId'],
368 'title': content['title']['simpleText'],
369 'author': author,
370 'channel_id': channel_id,
371 'n_videos': None,
372 }})
373 elif key in ["gridShowRenderer"]:
374 result.append({'type': 'PLAYLIST', 'content': {
375 'playlist_id': (content|G('navigationEndpoint')
376 |G('browseEndpoint')|G('browseId'))[2:],
377 #^: playlistId prefixed with 'VL', which must be removed
378 'video_id': None,
379 'title': content|G('title')|G.text,
380 'author': author,
381 'channel_id': channel_id,
382 'n_videos': content|G('thumbnailOverlays')|G(0)
383 |G('thumbnailOverlayBottomPanelRenderer')|G('text')|G.text,
384 }})
385 elif key in ["itemSectionRenderer", "gridRenderer", "horizontalCardListRenderer", "horizontalListRenderer"]:
386 newkey = {
387 "itemSectionRenderer": 'contents',
388 "gridRenderer": 'items',
389 "horizontalCardListRenderer": 'cards',
390 "horizontalListRenderer": 'items',
391 }.get(key)
392 r, e = parse_channel_items(content[newkey], channel_id, author)
393 result.extend(r)
394 extra.extend(e)
395 elif key == "shelfRenderer":
396 r, e = parse_channel_items([content['content']], channel_id, author)
397 result.extend(r)
398 extra.extend(e)
399 elif key == "messageRenderer":
400 # e.g. {'messageRenderer': {'text': {'runs': [{'text': 'This channel has no playlists.'}]}}}
401 pass
402 elif key == "gameCardRenderer":
403 pass
404 elif key == "gridChannelRenderer":
405 pass # don't care; related channels, e.g. on UCMsgXPD3wzzt8RxHJmXH7hQ
406 else:
407 log_unknown_card(item)
408
409 return result, extra
410
411 def parse_playlist(item):
412 key = next(iter(item.keys()), None)
413 content = item[key]
414 if key == "playlistVideoRenderer":
415 if not content.get('isPlayable', False):
416 return None # private or deleted video
417
418 return {'type': 'VIDEO', 'content': {
419 'video_id': content['videoId'],
420 'title': (content['title'].get('simpleText') or # playable videos
421 content['title'].get('runs',[{}])[0].get('text')), # "[Private video]"
422 'playlist_id': content['navigationEndpoint']['watchEndpoint']['playlistId'],
423 'index': content['navigationEndpoint']['watchEndpoint'].get('index',0), #or int(content['index']['simpleText']) (absent on course intros; e.g. PL96C35uN7xGJu6skU4TBYrIWxggkZBrF5)
424 # rest is missing from unplayable videos:
425 'author': content.get('shortBylineText',{}).get('runs',[{}])[0].get('text'),
426 'channel_id':content.get('shortBylineText',{}).get('runs',[{}])[0].get('navigationEndpoint',{}).get('browseEndpoint',{}).get('browseId'),
427 'length': (content.get("lengthText",{}).get("simpleText") or # "8:51"
428 int(content.get("lengthSeconds", 0))), # "531"
429 'starttime': content['navigationEndpoint']['watchEndpoint'].get('startTimeSeconds'),
430 }}
431 else:
432 raise Exception(item) # XXX TODO
Imprint / Impressum