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