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