]>
git.gir.st - subscriptionfeed.git/blob - app/common/innertube.py
1 # functions that deal with parsing data from youtube's internal API ("innertube")
3 from urllib
. parse
import parse_qs
, urlparse
8 null-coalescing version of dict.get() that also works on lists.
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.
13 def __init__ ( self
, * keys
):
15 def __ror__ ( self
, other
):
17 try : return other
[ key
]
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' )
26 """ |Select('foo') returns the first foo in list, |Select(all='foo') returns all foos. """
27 def __init__ ( self
, key
= None , *, all
= None ):
30 def __ror__ ( self
, other
):
31 try : items
= [ other
[ self
. key
] for other
in other
if self
. key
in other
. keys () ]
33 return items
if self
. all
else items|
G ( 0 )
36 def __init__ ( self
, f
, * args
):
39 def __ror__ ( self
, other
):
40 return self
. f ( other
, * self
. args
)
42 def __ror__ ( self
, other
):
43 try : return int ( '' . join ( filter ( str . isdigit
, other
)))
48 def prepare_searchresults ( yt_results
):
49 contents
= ( # from continuation token
51 |
G ( 'onResponseReceivedCommands' )
52 |
Select ( 'appendContinuationItemsAction' )
53 |
G ( 'continuationItems' )
57 |
G ( 'twoColumnSearchResultsRenderer' )
59 |
G ( 'sectionListRenderer' )
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" )
67 return items
, extra
, more
69 def prepare_infocards ( metadata
):
70 cards
= metadata
. get ( 'cards' ,{}). get ( 'cardCollectionRenderer' ,{}). get ( 'cards' ,[])
71 return list ( filter ( None , map ( parse_infocard
, cards
)))
73 def prepare_endcards ( metadata
):
74 endsc
= metadata
. get ( 'endscreen' ,{}). get ( 'endscreenRenderer' ,{}). get ( 'elements' ,[])
75 return list ( filter ( None , map ( parse_endcard
, endsc
)))
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
85 response|
G ( 'continuationContents' ) or
86 response|
G ( 'onResponseReceivedActions' )
88 if not contents
: # overran end of list
89 return title
, descr
, thumb
, [], False
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
)
98 |
G ( 'gridContinuation' , 'sectionListContinuation' )
100 |
Select ( 'nextContinuationData' )
106 ( contents|
G ( 'richGridContinuation' ) |
G ( 'contents' )) or
107 ( contents|
Select ( 'appendContinuationItemsAction' ) |
G ( 'continuationItems' ))
109 |
Select ( 'continuationItemRenderer' )
110 |
G ( 'continuationEndpoint' )
111 |
G ( 'continuationCommand' )
115 return title
, descr
, thumb
, items
, more
117 def prepare_playlist ( result
):
118 contents
= result
[ 'continuationContents' ]
119 unparsed
= contents
[ 'playlistVideoListContinuation' ]. get ( 'contents' ,[])
122 |
G ( 'playlistVideoListContinuation' )
124 |
Select ( 'nextContinuationData' )
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' )
136 return title
, author
, channel_id
, list ( filter ( None , map ( parse_playlist
, unparsed
))), more
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
}
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 ]
148 def toInt ( s
, fallback
= 0 ):
152 return int ( '' . join ( filter ( str . isdigit
, s
)))
156 # Remove left-/rightmost word from string:
157 delL
= lambda s
: s
. partition ( ' ' )[ 2 ]
160 if s
is None : # missing from autogen'd music, some livestreams
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 ( " " )
169 ). get ( unit
, unit
[ 0 ]) # first letter otherwise (e.g. year(s) => y)
171 return f
" {value}{suffix} "
173 def log_unknown_card ( data
):
176 from flask
import request
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 )
183 def parse_result_items ( items
):
184 # TODO: use .get() for most non-essential attributes
186 parses youtube search response into an easier to use format.
191 key
= next ( iter ( item
. keys ()), None )
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' ,
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
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"
223 elif key
== 'shelfRenderer' :
224 subkey
= next ( iter ( content
[ 'content' ]. keys ()), None ) #verticalListRenderer/horizontalMovieListRenderer
225 r
, e
= parse_result_items ( content
[ 'content' ][ subkey
][ 'items' ])
228 elif key
== 'reelShelfRenderer' : # XXX: seems to be Shorts only
230 elif key
in [ 'movieRenderer' , 'gridMovieRenderer' ]: # movies to buy/rent
231 pass # gMR.{videoId,title.runs[].text,lengthText.simpleText}
232 elif key
in [ 'carouselAdRenderer' , 'searchPyvRenderer' , 'promotedSparklesTextSearchRenderer' ,
233 'promotedSparklesWebRenderer' , 'compactPromotedItemRenderer' ]: # haha, no.
235 elif key
== 'horizontalCardListRenderer' :
236 # suggested searches: .cards[].searchRefinementCardRenderer.query.runs[].text
238 elif key
== 'emergencyOneboxRenderer' : # suicide prevention hotline
240 elif key
in [ 'clarificationRenderer' , 'infoPanelContainerRenderer' ]: # COVID-19/conspiracy theory infos
242 elif key
== 'webAnswerRenderer' : # "Result from the web"
244 elif key
== 'infoPanelContentRenderer' : # "These results may be new or changing quickly"
246 elif key
== 'hashtagTileRenderer' : # link to '/hashtag/<search_query>'
248 elif key
in [ 'didYouMeanRenderer' , 'showingResultsForRenderer' , 'includingResultsForRenderer' ]:
251 'query' : content
[ 'correctedQueryEndpoint' ][ 'searchEndpoint' ][ 'query' ], # non-misspelled query
252 'autocorrected' : key
in [ 'showingResultsForRenderer' , 'includingResultsForRenderer' ],
254 elif key
== 'messageRenderer' : # "No more results"
257 'message' : content|
G ( 'title' , 'text' ) |G
. text
,
259 elif key
== 'backgroundPromoRenderer' : # e.g. "no results"
261 'type' : content
[ 'icon' ][ 'iconType' ],
262 'message' : content
[ 'title' ] |G
. text
,
265 log_unknown_card ( item
)
266 return results
, extras
268 def parse_infocard ( card
):
270 parses a single infocard into a format that's easier to handle.
272 card
= card
[ 'cardRenderer' ]
273 if not 'content' in card
:
274 return None # probably the "View corrections" card, ignore.
275 ctype
= list ( card
[ 'content' ]. keys ())[ 0 ]
276 content
= card
[ 'content' ][ ctype
]
277 if ctype
== "pollRenderer" :
278 return { 'type' : "POLL" , 'content' : {
279 'question' : content
[ 'question' ][ 'simpleText' ],
280 'answers' : [( a
[ 'text' ][ 'simpleText' ], a
[ 'numVotes' ]) \
281 for a
in content
[ 'choices' ]],
283 elif ctype
== "videoInfoCardContentRenderer" :
284 is_live
= content
. get ( 'badge' ,{}). get ( 'liveBadgeRenderer' ) is not None
285 return { 'type' : "VIDEO" , 'content' : {
286 'video_id' : content
[ 'action' ][ 'watchEndpoint' ][ 'videoId' ],
287 'title' : content
[ 'videoTitle' ][ 'simpleText' ],
288 'author' : delL ( content
[ 'channelName' ][ 'simpleText' ]),
289 'length' : content
. get ( 'lengthString' ,{}). get ( 'simpleText' ) \
290 if not is_live
else "LIVE" , # "23:03"
291 'views' : toInt ( content
. get ( 'viewCountText' ,{}). get ( 'simpleText' )),
292 # XXX: views sometimes "Starts: July 31, 2020 at 1:30 PM"
294 elif ctype
== "playlistInfoCardContentRenderer" :
295 return { 'type' : "PLAYLIST" , 'content' : {
296 'playlist_id' : content
[ 'action' ][ 'watchEndpoint' ][ 'playlistId' ],
297 'video_id' : content
[ 'action' ][ 'watchEndpoint' ][ 'videoId' ],
298 'title' : content
[ 'playlistTitle' ][ 'simpleText' ],
299 'author' : delL ( content
[ 'channelName' ][ 'simpleText' ]),
300 'n_videos' : toInt ( content
[ 'playlistVideoCount' ][ 'simpleText' ]),
302 elif ctype
== "simpleCardContentRenderer" and \
303 'urlEndpoint' in content
[ 'command' ]:
304 return { 'type' : "WEBSITE" , 'content' : {
305 'url' : clean_url ( content
[ 'command' ][ 'urlEndpoint' ][ 'url' ]),
306 'domain' : content
[ 'displayDomain' ][ 'simpleText' ],
307 'title' : content
[ 'title' ][ 'simpleText' ],
308 # XXX: no thumbnails for infocards
310 elif ctype
== "collaboratorInfoCardContentRenderer" :
311 return { 'type' : "CHANNEL" , 'content' : {
312 'channel_id' : content
[ 'endpoint' ][ 'browseEndpoint' ][ 'browseId' ],
313 'title' : content
[ 'channelName' ][ 'simpleText' ],
314 'icons' : mkthumbs ( content
[ 'channelAvatar' ][ 'thumbnails' ]),
315 'subscribers' : content
. get ( 'subscriberCountText' ,{}). get ( 'simpleText' , '' ), # "545K subscribers"
318 log_unknown_card ( card
)
321 def parse_endcard ( card
):
323 parses a single endcard into a format that's easier to handle.
325 card
= card
. get ( 'endscreenElementRenderer' , card
) #only sometimes nested
326 ctype
= card
[ 'style' ]
327 if ctype
== "CHANNEL" :
328 return { 'type' : ctype
, 'content' : {
329 'channel_id' : card
[ 'endpoint' ][ 'browseEndpoint' ][ 'browseId' ],
330 'title' : card
[ 'title' ] |G
. text
,
331 'icons' : mkthumbs ( card
[ 'image' ][ 'thumbnails' ]),
333 elif ctype
== "VIDEO" :
334 if not 'endpoint' in card
: return None # title == "This video is unavailable."
335 return { 'type' : ctype
, 'content' : {
336 'video_id' : card
[ 'endpoint' ][ 'watchEndpoint' ][ 'videoId' ],
337 'title' : card
[ 'title' ] |G
. text
,
338 'length' : card|
G ( 'videoDuration' ) |G
. text
, # '12:21'
339 'views' : toInt ( card
[ 'metadata' ] |G
. text
),
340 # XXX: no channel name
342 elif ctype
== "PLAYLIST" :
343 return { 'type' : ctype
, 'content' : {
344 'playlist_id' : card
[ 'endpoint' ][ 'watchEndpoint' ][ 'playlistId' ],
345 'video_id' : card
[ 'endpoint' ][ 'watchEndpoint' ][ 'videoId' ],
346 'title' : card
[ 'title' ] |G
. text
,
347 'author' : delL ( card
[ 'metadata' ] |G
. text
),
348 'n_videos' : toInt ( card
[ 'playlistLength' ] |G
. text
),
350 elif ctype
== "WEBSITE" or ctype
== "CREATOR_MERCHANDISE" :
351 url
= clean_url ( card
[ 'endpoint' ][ 'urlEndpoint' ][ 'url' ])
352 return { 'type' : "WEBSITE" , 'content' : {
354 'domain' : urlparse ( url
). netloc
,
355 'title' : card
[ 'title' ] |G
. text
,
356 'icons' : mkthumbs ( card
[ 'image' ][ 'thumbnails' ]),
359 log_unknown_card ( card
)
362 def parse_channel_items ( items
, channel_id
, author
):
366 key
= next ( iter ( item
. keys ()), None )
368 if key
in [ "gridVideoRenderer" , "videoRenderer" , "videoCardRenderer" ]:
369 # only videoCardRenderer (topic channels) has author and channel, others fall back to supplied ones.
370 result
. append ({ 'type' : 'VIDEO' , 'content' : {
371 'video_id' : content
[ 'videoId' ],
372 'title' : content|
G ( 'title' ) |G
. text
,
373 'author' : content|
G ( 'bylineText' ) |G
. text
or author
,
374 'channel_id' : ( content|
G ( 'bylineText' ) |
G ( 'runs' )
375 |
Select ( 'navigationEndpoint' )
376 |
G ( 'browseEndpoint' ) |
G ( 'browseId' ) or channel_id
),
377 'length' : ( content|
G ( 'lengthText' ) |G
. text
or # topic channel
378 content|
G ( 'thumbnailOverlays' )
379 |
Select ( 'thumbnailOverlayTimeStatusRenderer' )
381 # topic channel: .metadataText.simpleText = "22M views \u00b7 2 months ago"
382 'views' : content|
G ( 'viewCountText' ) |G
. text|A
. int ,
383 'published' : content|
G ( 'publishedTimeText' ) |G
. text|
A ( age
),
385 elif key
in [ "gridPlaylistRenderer" , "playlistRenderer" , "gridRadioRenderer" ]:
386 result
. append ({ 'type' : 'PLAYLIST' , 'content' : {
387 'playlist_id' : content|
G ( 'navigationEndpoint' ) |
G ( 'watchEndpoint' ) |
G ( 'playlistId' ),
388 'video_id' : content|
G ( 'navigationEndpoint' ) |
G ( 'watchEndpoint' ) |
G ( 'videoId' ),
389 'title' : content|
G ( 'title' ) |G
. text
,
390 'author' : author
, # Note: gridRadioRenderer is by 'Youtube' without channel_id, ignoring that.
391 'channel_id' : channel_id
,
392 'n_videos' : ( content|
G ( 'videoCount' ) |A
. int or # playlistRenderer
393 content|
G ( 'videoCountShortText' , 'videoCountText' ) |G
. text|A
. int ) # grid
395 elif key
== "showRenderer" :
396 result
. append ({ 'type' : 'PLAYLIST' , 'content' : {
397 'playlist_id' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ][ 'playlistId' ],
398 'video_id' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ][ 'videoId' ],
399 'title' : content
[ 'title' ][ 'simpleText' ],
401 'channel_id' : channel_id
,
404 elif key
in [ "gridShowRenderer" ]:
405 result
. append ({ 'type' : 'PLAYLIST' , 'content' : {
406 'playlist_id' : ( content|
G ( 'navigationEndpoint' )
407 |
G ( 'browseEndpoint' ) |
G ( 'browseId' ))[ 2 :],
408 #^: playlistId prefixed with 'VL', which must be removed
410 'title' : content|
G ( 'title' ) |G
. text
,
412 'channel_id' : channel_id
,
413 'n_videos' : content|
G ( 'thumbnailOverlays' ) |
G ( 0 )
414 |
G ( 'thumbnailOverlayBottomPanelRenderer' ) |
G ( 'text' ) |G
. text
,
416 elif key
in [ "itemSectionRenderer" , "gridRenderer" , "horizontalCardListRenderer" , "horizontalListRenderer" ]:
418 "itemSectionRenderer" : 'contents' ,
419 "gridRenderer" : 'items' ,
420 "horizontalCardListRenderer" : 'cards' ,
421 "horizontalListRenderer" : 'items' ,
423 r
, e
= parse_channel_items ( content
[ newkey
], channel_id
, author
)
426 elif key
in [ "shelfRenderer" , "richItemRenderer" ]:
427 r
, e
= parse_channel_items ([ content
[ 'content' ]], channel_id
, author
)
430 elif key
== "messageRenderer" :
431 # e.g. {'messageRenderer': {'text': {'runs': [{'text': 'This channel has no playlists.'}]}}}
433 elif key
== "gameCardRenderer" :
435 elif key
== "gridChannelRenderer" :
436 pass # don't care; related channels, e.g. on UCMsgXPD3wzzt8RxHJmXH7hQ
438 log_unknown_card ( item
)
442 def parse_playlist ( item
):
443 key
= next ( iter ( item
. keys ()), None )
445 if key
== "playlistVideoRenderer" :
446 if not content
. get ( 'isPlayable' , False ):
447 return None # private or deleted video
449 return { 'type' : 'VIDEO' , 'content' : {
450 'video_id' : content
[ 'videoId' ],
451 'title' : ( content
[ 'title' ]. get ( 'simpleText' ) or # playable videos
452 content
[ 'title' ]. get ( 'runs' ,[{}])[ 0 ]. get ( 'text' )), # "[Private video]"
453 'playlist_id' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ][ 'playlistId' ],
454 'index' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ]. get ( 'index' , 0 ), #or int(content['index']['simpleText']) (absent on course intros; e.g. PL96C35uN7xGJu6skU4TBYrIWxggkZBrF5)
455 # rest is missing from unplayable videos:
456 'author' : content
. get ( 'shortBylineText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'text' ),
457 'channel_id' : content
. get ( 'shortBylineText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'navigationEndpoint' ,{}). get ( 'browseEndpoint' ,{}). get ( 'browseId' ),
458 'length' : ( content
. get ( "lengthText" ,{}). get ( "simpleText" ) or # "8:51"
459 int ( content
. get ( "lengthSeconds" , 0 ))), # "531"
460 'starttime' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ]. get ( 'startTimeSeconds' ),
463 raise Exception ( item
) # XXX TODO