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