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