]> git.gir.st - subscriptionfeed.git/blob - app/common/innertube.py
convert all search result types to use pipe framework
[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(result, channel_id):
81 response = listfind(result,'response')
82
83 if 'alerts' in response: # possibly got an error back
84 from flask import current_app
85 current_app.logger.error([(alert['alertRenderer']['type'],alert['alertRenderer']['text']['simpleText']) for alert in response['alerts']])
86 return None,None,[],[],False
87
88 meta1 = response.get('metadata',{}).get('channelMetadataRenderer',{})
89 meta2 = response.get('microformat',{}).get('microformatDataRenderer',{})
90 title = meta1.get('title', meta2.get('title'))
91 descr = meta1.get('description', meta2.get('description')) # meta2.description is capped at 160chars
92 thumb = mkthumbs(meta2.get('thumbnail',meta1.get('avatar',{})).get('thumbnails',{})) # .avatar ~ 900px
93
94 contents = response.get('continuationContents')
95 if not contents: # overran end of list
96 return title, descr, thumb, [], False
97
98 unparsed = contents.get('gridContinuation',{}).get('items') or \
99 contents.get('sectionListContinuation',{}).get('contents') or []
100 items, extra = parse_channel_items(unparsed, channel_id, title)
101 has_more = 'continuations' in (contents.get('gridContinuation') or
102 contents.get('sectionListContinuation') or {})
103
104 return title, descr, thumb, items, has_more
105
106 def prepare_playlist(result):
107 contents = listfind(result,'response')['continuationContents']
108 unparsed = contents['playlistVideoListContinuation'].get('contents',[])
109 has_more = 'continuations' in contents.get('playlistVideoListContinuation')
110
111 return list(filter(None, map(parse_playlist, unparsed))), has_more
112
113 def mkthumbs(thumbs):
114 output = {str(e['height']): e['url'] for e in thumbs}
115 largest=next(iter(sorted(output.keys(),reverse=True,key=int)),None)
116 return {**output, 'largest': largest}
117
118 def clean_url(url):
119 # externals URLs are redirected through youtube.com/redirect, but we
120 # may encounter internal URLs, too
121 return parse_qs(urlparse(url).query).get('q',[url])[0]
122
123 def toInt(s, fallback=0):
124 if s is None:
125 return fallback
126 try:
127 return int(''.join(filter(str.isdigit, s)))
128 except ValueError:
129 return fallback
130
131 # Remove left-/rightmost word from string:
132 delL = lambda s: s.partition(' ')[2]
133
134 def age(s):
135 if s is None: # missing from autogen'd music, some livestreams
136 return None
137 # Some livestreams have "Streamed 7 hours ago"
138 s = s.replace("Streamed ","")
139 # Now, everything should be in the form "1 year ago"
140 value, unit, _ = s.split(" ")
141 suffix = dict(
142 month='mn',
143 months='mn',
144 ).get(unit, unit[0]) # first letter otherwise (e.g. year(s) => y)
145
146 return f"{value}{suffix}"
147
148 def log_unknown_card(data):
149 import json
150 try:
151 from flask import request
152 source = request.url
153 except: source = "unknown"
154 with open("/tmp/innertube.err", "a") as f:
155 f.write(f"\n/***** {source} *****/\n")
156 json.dump(data, f, indent=2)
157
158 def parse_result_items(items):
159 # TODO: use .get() for most non-essential attributes
160 """
161 parses youtube search response into an easier to use format.
162 """
163 results = []
164 extras = []
165 for item in items:
166 key = next(iter(item.keys()), None)
167 content = item[key]
168 if key == 'videoRenderer':
169 results.append({'type': 'VIDEO', 'content': {
170 'video_id': content['videoId'],
171 'title': content['title']|G.text,
172 'author': content|G('longBylineText','shortBylineText')|G.text,
173 'channel_id': content|G('ownerText')|G('runs')|G(0) \
174 |G('navigationEndpoint')|G('browseEndpoint')|G('browseId'),
175 'length': content|G('lengthText')|G.text, # "44:07", "1:41:50"
176 'views': content|G('viewCountText')|G.text|A.int or 0, # "1,234 {views|watching}", absent on 0 views
177 'published': content|G('publishedTimeText')|G('simpleText')|A(age),
178 'live': content|G('badges')|Select('metadataBadgeRenderer')|G('style')=='BADGE_STYLE_TYPE_LIVE_NOW',
179 }})
180 elif key in ['playlistRenderer', 'radioRenderer', 'showRenderer']: # radio == "Mix" playlist, show == normal playlist, specially displayed
181 results.append({'type': 'PLAYLIST', 'content': {
182 'playlist_id': content['navigationEndpoint']|G('watchEndpoint')|G('playlistId') or \
183 content|G('playlistId'), # COURSE/"learning playlist"
184 'video_id': content['navigationEndpoint']|G('watchEndpoint')|G('videoId') or \
185 videoid_from_thumbnail(content), # learning playlist
186 'title': content['title']|G.text,
187 # Note: learning playlists have no author/channel_id
188 'author': content|G('longBylineText','shortBylineText')|G.text,
189 'channel_id': content|G('longBylineText','shortBylineText')|G('runs')|G(0) \
190 |G('navigationEndpoint')|G('browseEndpoint')|G('browseId'),
191 'n_videos': content|G('videoCount')|A.int or \
192 content|G('videoCountShortText','videoCountText')|G.text, # "Mix" playlists
193 }})
194 elif key == 'channelRenderer':
195 results.append({'type': 'CHANNEL', 'content': {
196 'channel_id': content['channelId'],
197 'title': content['title']|G.text,
198 'icons': content['thumbnail']['thumbnails']|A(mkthumbs),
199 'subscribers': content|G('subscriberCountText')|G('simpleText'), # "2.47K subscribers"
200 }})
201 elif key == 'shelfRenderer':
202 subkey = next(iter(content['content'].keys()), None) #verticalListRenderer/horizontalMovieListRenderer
203 r, e = parse_result_items(content['content'][subkey]['items'])
204 results.extend(r)
205 extras.extend(e)
206 elif key in ['movieRenderer', 'gridMovieRenderer']: # movies to buy/rent
207 pass # gMR.{videoId,title.runs[].text,lengthText.simpleText}
208 elif key in ['carouselAdRenderer','searchPyvRenderer','promotedSparklesTextSearchRenderer']: # haha, no.
209 pass
210 elif key == 'horizontalCardListRenderer':
211 # suggested searches: .cards[].searchRefinementCardRenderer.query.runs[].text
212 pass
213 elif key == 'emergencyOneboxRenderer': # suicide prevention hotline
214 pass
215 elif key in ['clarificationRenderer', 'infoPanelContainerRenderer']: # COVID-19/conspiracy theory infos
216 pass
217 elif key == 'webAnswerRenderer': # "Result from the web"
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']['simpleText'],
300 'icons': mkthumbs(card['image']['thumbnails']),
301 }}
302 elif ctype == "VIDEO":
303 return {'type': ctype, 'content': {
304 'video_id': card['endpoint']['watchEndpoint']['videoId'],
305 'title': card['title']['simpleText'],
306 'length': card['videoDuration']['simpleText'], # '12:21'
307 'views': toInt(card['metadata']['simpleText']),
308 # XXX: no channel name
309 }}
310 elif ctype == "PLAYLIST":
311 return {'type': ctype, 'content': {
312 'playlist_id': card['endpoint']['watchEndpoint']['playlistId'],
313 'video_id': card['endpoint']['watchEndpoint']['videoId'],
314 'title': card['title']['simpleText'],
315 'author': delL(card['metadata']['simpleText']),
316 'n_videos': toInt(card['playlistLength']['simpleText']),
317 }}
318 elif ctype == "WEBSITE" or ctype == "CREATOR_MERCHANDISE":
319 url = clean_url(card['endpoint']['urlEndpoint']['url'])
320 return {'type': "WEBSITE", 'content': {
321 'url': url,
322 'domain': urlparse(url).netloc,
323 'title': card['title']['simpleText'],
324 'icons': mkthumbs(card['image']['thumbnails']),
325 }}
326 else:
327 log_unknown_card(card)
328 return None
329
330 def videoid_from_thumbnail(content):
331 # learning playlist; example: PL96C35uN7xGJu6skU4TBYrIWxggkZBrF5 (/user/enyay/playlists)
332 return re.match(r"https?://i.ytimg.com/vi/([-_0-9a-zA-Z]{11})|()",
333 listget(listget(content.get('thumbnails',[]),0,{}).get('thumbnails',[]),0,{}).get('url','')
334 ).group(1)
335
336 def parse_channel_items(items, channel_id, author):
337 result = []
338 extra = []
339 for item in items:
340 key = next(iter(item.keys()), None)
341 content = item[key]
342 if key in ["gridVideoRenderer", "videoRenderer", "videoCardRenderer"]:
343 # only videoCardRenderer (topic channels) has author and channel, others fall back to supplied ones.
344 result.append({'type': 'VIDEO', 'content': {
345 'video_id': content['videoId'],
346 'title': content['title'].get('simpleText') or content['title'].get('runs',[{}])[0].get('text'),
347 'author': content.get('bylineText',{}).get('runs',[{}])[0].get('text') or author,
348 'channel_id': content.get('bylineText',{}).get('runs',[{}])[0] \
349 .get('navigationEndpoint',{}).get('browseEndpoint',{}).get('browseId') or channel_id,
350 'length': (content.get('lengthText',{}).get('simpleText') or # topic channel
351 listfind(content.get('thumbnailOverlays',[]),'thumbnailOverlayTimeStatusRenderer')
352 .get('text',{}).get('simpleText')),
353 # topic channel: .metadataText.simpleText = "22M views \u00b7 2 months ago"
354 'views': toInt(content.get('viewCountText',{}).get('simpleText')),
355 'published': age(content.get('publishedTimeText',{}).get('simpleText')),
356 }})
357 elif key == "gridPlaylistRenderer" or key == "playlistRenderer":
358 result.append({'type': 'PLAYLIST', 'content': {
359 'playlist_id': content['navigationEndpoint'].get('watchEndpoint',{}).get('playlistId') or content.get('playlistId'),
360 'video_id': content['navigationEndpoint'].get('watchEndpoint',{}).get('videoId',{}) or videoid_from_thumbnail(content),
361 'title': (content['title'].get('simpleText') or # playlistRenderer
362 content['title']['runs'][0]['text']), # gridPlaylistRenderer
363 'author': author,
364 'channel_id': channel_id,
365 'n_videos': toInt(content.get('videoCount') or # playlistRenderer
366 content.get('videoCountShortText',{}).get('simpleText') or # grid(1)
367 content.get('videoCountText',{}).get('runs',[{}])[0].get('text')), # grid(2)
368 }})
369 elif key == "showRenderer":
370 result.append({'type': 'PLAYLIST', 'content': {
371 'playlist_id': content['navigationEndpoint']['watchEndpoint']['playlistId'],
372 'video_id': content['navigationEndpoint']['watchEndpoint']['videoId'],
373 'title': content['title']['simpleText'],
374 'author': author,
375 'channel_id': channel_id,
376 'n_videos': None,
377 }})
378 elif key in ["itemSectionRenderer", "gridRenderer", "horizontalCardListRenderer"]:
379 newkey = {
380 "itemSectionRenderer": 'contents',
381 "gridRenderer": 'items',
382 "horizontalCardListRenderer": 'cards',
383 }.get(key)
384 r, e = parse_channel_items(content[newkey], channel_id, author)
385 result.extend(r)
386 extra.extend(e)
387 elif key == "shelfRenderer":
388 r, e = parse_channel_items([content['content']], channel_id, author)
389 result.extend(r)
390 extra.extend(e)
391 elif key == "messageRenderer":
392 # e.g. {'messageRenderer': {'text': {'runs': [{'text': 'This channel has no playlists.'}]}}}
393 pass
394 elif key == "gameCardRenderer":
395 pass
396 else:
397 log_unknown_card(item)
398
399 return result, extra
400
401 def parse_playlist(item):
402 key = next(iter(item.keys()), None)
403 content = item[key]
404 if key == "playlistVideoRenderer":
405 if not content.get('isPlayable', False):
406 return None # private or deleted video
407
408 return {'type': 'VIDEO', 'content': {
409 'video_id': content['videoId'],
410 'title': (content['title'].get('simpleText') or # playable videos
411 content['title'].get('runs',[{}])[0].get('text')), # "[Private video]"
412 'playlist_id': content['navigationEndpoint']['watchEndpoint']['playlistId'],
413 'index': content['navigationEndpoint']['watchEndpoint'].get('index',0), #or int(content['index']['simpleText']) (absent on course intros; e.g. PL96C35uN7xGJu6skU4TBYrIWxggkZBrF5)
414 # rest is missing from unplayable videos:
415 'author': content.get('shortBylineText',{}).get('runs',[{}])[0].get('text'),
416 'channel_id':content.get('shortBylineText',{}).get('runs',[{}])[0].get('navigationEndpoint',{}).get('browseEndpoint',{}).get('browseId'),
417 'length': (content.get("lengthText",{}).get("simpleText") or # "8:51"
418 int(content.get("lengthSeconds", 0))), # "531"
419 'starttime': content['navigationEndpoint']['watchEndpoint'].get('startTimeSeconds'),
420 }}
421 else:
422 raise Exception(item) # XXX TODO
Imprint / Impressum