]>
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 given a list of dicts, where one dict contains a given key, return said key.
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
))
21 null-coalescing version of dict.get() that also works on lists.
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.
26 def __init__ ( self
, * keys
):
28 def __ror__ ( self
, other
):
30 try : return other
[ key
]
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' )
39 """ |Select('foo') returns the first foo in list, |Select(all='foo') returns all foos. """
40 def __init__ ( self
, key
= None , *, all
= None ):
43 def __ror__ ( self
, other
):
44 try : items
= [ other
[ self
. key
] for other
in other
if self
. key
in other
. keys () ]
46 return items
if self
. all
else items|
G ( 0 )
49 def __init__ ( self
, f
, * args
):
52 def __ror__ ( self
, other
):
53 return self
. f ( other
, * self
. args
)
55 def __ror__ ( self
, other
):
56 try : return int ( '' . join ( filter ( str . isdigit
, other
)))
61 def prepare_searchresults ( yt_results
):
62 contents
= listfind ( yt_results
, 'response' ) \
64 . get ( 'twoColumnSearchResultsRenderer' ,{}) \
65 . get ( 'primaryContents' ,{}) \
66 . get ( 'sectionListRenderer' ,{}) \
68 contents
= flatten ([ c
. get ( 'contents' ,[]) for c
in contents|
Select ( all
= 'itemSectionRenderer' )])
70 return parse_result_items ( contents
)
72 def prepare_infocards ( metadata
):
73 cards
= metadata
. get ( 'cards' ,{}). get ( 'cardCollectionRenderer' ,{}). get ( 'cards' ,[])
74 return list ( filter ( None , map ( parse_infocard
, cards
)))
76 def prepare_endcards ( metadata
):
77 endsc
= metadata
. get ( 'endscreen' ,{}). get ( 'endscreenRenderer' ,{}). get ( 'elements' ,[])
78 return list ( filter ( None , map ( parse_endcard
, endsc
)))
80 def prepare_channel ( result
, channel_id
):
81 response
= listfind ( result
, 'response' )
83 if 'alerts' in response
: # possibly got an error back
84 from flask
import current_app
85 current_app
. logger
. error ([( alert
[ 'alertRenderer' ][ 'type' ], alert
[ 'alertRenderer' ][ 'text' ][ 'simpleText' ]) for alert
in response
[ 'alerts' ]])
86 return None , None ,[],[], False
88 meta1
= response
. get ( 'metadata' ,{}). get ( 'channelMetadataRenderer' ,{})
89 meta2
= response
. get ( 'microformat' ,{}). get ( 'microformatDataRenderer' ,{})
90 title
= meta1
. get ( 'title' , meta2
. get ( 'title' ))
91 descr
= meta1
. get ( 'description' , meta2
. get ( 'description' )) # meta2.description is capped at 160chars
92 thumb
= mkthumbs ( meta2
. get ( 'thumbnail' , meta1
. get ( 'avatar' ,{})). get ( 'thumbnails' ,{})) # .avatar ~ 900px
94 contents
= response
. get ( 'continuationContents' )
95 if not contents
: # overran end of list
96 return title
, descr
, thumb
, [], False
98 unparsed
= contents
. get ( 'gridContinuation' ,{}). get ( 'items' ) or \
99 contents
. get ( 'sectionListContinuation' ,{}). get ( 'contents' ) or []
100 items
, extra
= parse_channel_items ( unparsed
, channel_id
, title
)
101 has_more
= 'continuations' in ( contents
. get ( 'gridContinuation' ) or
102 contents
. get ( 'sectionListContinuation' ) or {})
104 return title
, descr
, thumb
, items
, has_more
106 def prepare_playlist ( result
):
107 contents
= listfind ( result
, 'response' )[ 'continuationContents' ]
108 unparsed
= contents
[ 'playlistVideoListContinuation' ]. get ( 'contents' ,[])
109 has_more
= 'continuations' in contents
. get ( 'playlistVideoListContinuation' )
111 return list ( filter ( None , map ( parse_playlist
, unparsed
))), has_more
113 def mkthumbs ( thumbs
):
114 output
= { str ( e
[ 'height' ]): e
[ 'url' ] for e
in thumbs
}
115 largest
= next ( iter ( sorted ( output
. keys (), reverse
= True , key
= int )), None )
116 return {** output
, 'largest' : largest
}
119 # externals URLs are redirected through youtube.com/redirect, but we
120 # may encounter internal URLs, too
121 return parse_qs ( urlparse ( url
). query
). get ( 'q' ,[ url
])[ 0 ]
123 def toInt ( s
, fallback
= 0 ):
127 return int ( '' . join ( filter ( str . isdigit
, s
)))
131 # Remove left-/rightmost word from string:
132 delL
= lambda s
: s
. partition ( ' ' )[ 2 ]
135 if s
is None : # missing from autogen'd music, some livestreams
137 # Some livestreams have "Streamed 7 hours ago"
138 s
= s
. replace ( "Streamed " , "" )
139 # Now, everything should be in the form "1 year ago"
140 value
, unit
, _
= s
. split ( " " )
144 ). get ( unit
, unit
[ 0 ]) # first letter otherwise (e.g. year(s) => y)
146 return f
" {value}{suffix} "
148 def log_unknown_card ( data
):
151 from flask
import request
153 except : source
= "unknown"
154 with
open ( "/tmp/innertube.err" , "a" ) as f
:
155 f
. write ( f
" \n /***** {source} *****/ \n " )
156 json
. dump ( data
, f
, indent
= 2 )
158 def parse_result_items ( items
):
159 # TODO: use .get() for most non-essential attributes
161 parses youtube search response into an easier to use format.
166 key
= next ( iter ( item
. keys ()), None )
168 if key
== 'videoRenderer' :
169 results
. append ({ 'type' : 'VIDEO' , 'content' : {
170 'video_id' : content
[ 'videoId' ],
171 'title' : content
[ 'title' ] |G
. text
,
172 'author' : content|
G ( 'longBylineText' , 'shortBylineText' ) |G
. text
,
173 'channel_id' : content|
G ( 'ownerText' ) |
G ( 'runs' ) |
G ( 0 ) \
174 |
G ( 'navigationEndpoint' ) |
G ( 'browseEndpoint' ) |
G ( 'browseId' ),
175 'length' : content|
G ( 'lengthText' ) |G
. text
, # "44:07", "1:41:50"
176 'views' : content|
G ( 'viewCountText' ) |G
. text|A
. int or 0 , # "1,234 {views|watching}", absent on 0 views
177 'published' : content|
G ( 'publishedTimeText' ) |
G ( 'simpleText' ) |
A ( age
),
178 'live' : content|
G ( 'badges' ) |
Select ( 'metadataBadgeRenderer' ) |
G ( 'style' )== 'BADGE_STYLE_TYPE_LIVE_NOW' ,
180 elif key
in [ 'playlistRenderer' , 'radioRenderer' , 'showRenderer' ]: # radio == "Mix" playlist, show == normal playlist, specially displayed
181 results
. append ({ 'type' : 'PLAYLIST' , 'content' : {
182 'playlist_id' : content
[ 'navigationEndpoint' ] |
G ( 'watchEndpoint' ) |
G ( 'playlistId' ) or \
183 content|
G ( 'playlistId' ), # COURSE/"learning playlist"
184 'video_id' : content
[ 'navigationEndpoint' ] |
G ( 'watchEndpoint' ) |
G ( 'videoId' ) or \
185 videoid_from_thumbnail ( content
), # learning playlist
186 'title' : content
[ 'title' ] |G
. text
,
187 # Note: learning playlists have no author/channel_id
188 'author' : content|
G ( 'longBylineText' , 'shortBylineText' ) |G
. text
,
189 'channel_id' : content|
G ( 'longBylineText' , 'shortBylineText' ) |
G ( 'runs' ) |
G ( 0 ) \
190 |
G ( 'navigationEndpoint' ) |
G ( 'browseEndpoint' ) |
G ( 'browseId' ),
191 'n_videos' : content|
G ( 'videoCount' ) |A
. int or \
192 content|
G ( 'videoCountShortText' , 'videoCountText' ) |G
. text
, # "Mix" playlists
194 elif key
== 'channelRenderer' :
195 results
. append ({ 'type' : 'CHANNEL' , 'content' : {
196 'channel_id' : content
[ 'channelId' ],
197 'title' : content
[ 'title' ] |G
. text
,
198 'icons' : content
[ 'thumbnail' ][ 'thumbnails' ] |
A ( mkthumbs
),
199 'subscribers' : content|
G ( 'subscriberCountText' ) |
G ( 'simpleText' ), # "2.47K subscribers"
201 elif key
== 'shelfRenderer' :
202 subkey
= next ( iter ( content
[ 'content' ]. keys ()), None ) #verticalListRenderer/horizontalMovieListRenderer
203 r
, e
= parse_result_items ( content
[ 'content' ][ subkey
][ 'items' ])
206 elif key
in [ 'movieRenderer' , 'gridMovieRenderer' ]: # movies to buy/rent
207 pass # gMR.{videoId,title.runs[].text,lengthText.simpleText}
208 elif key
in [ 'carouselAdRenderer' , 'searchPyvRenderer' , 'promotedSparklesTextSearchRenderer' ]: # haha, no.
210 elif key
== 'horizontalCardListRenderer' :
211 # suggested searches: .cards[].searchRefinementCardRenderer.query.runs[].text
213 elif key
== 'emergencyOneboxRenderer' : # suicide prevention hotline
215 elif key
in [ 'clarificationRenderer' , 'infoPanelContainerRenderer' ]: # COVID-19/conspiracy theory infos
217 elif key
== 'webAnswerRenderer' : # "Result from the web"
219 elif key
== 'didYouMeanRenderer' or key
== 'showingResultsForRenderer' :
222 'query' : content
[ 'correctedQueryEndpoint' ][ 'searchEndpoint' ][ 'query' ], # non-misspelled query
223 'autocorrected' : key
== 'showingResultsForRenderer' ,
225 elif key
== 'messageRenderer' : # "No more results"
228 'message' : content|
G ( 'title' , 'text' ) |G
. text
,
230 elif key
== 'backgroundPromoRenderer' : # e.g. "no results"
232 'type' : content
[ 'icon' ][ 'iconType' ],
233 'message' : content
[ 'title' ] |G
. text
,
236 log_unknown_card ( item
)
237 return results
, extras
239 def parse_infocard ( card
):
241 parses a single infocard into a format that's easier to handle.
243 card
= card
[ 'cardRenderer' ]
244 ctype
= list ( card
[ 'content' ]. keys ())[ 0 ]
245 content
= card
[ 'content' ][ ctype
]
246 if ctype
== "pollRenderer" :
247 return { 'type' : "POLL" , 'content' : {
248 'question' : content
[ 'question' ][ 'simpleText' ],
249 'answers' : [( a
[ 'text' ][ 'simpleText' ], a
[ 'numVotes' ]) \
250 for a
in content
[ 'choices' ]],
252 elif ctype
== "videoInfoCardContentRenderer" :
253 is_live
= content
. get ( 'badge' ,{}). get ( 'liveBadgeRenderer' ) is not None
254 return { 'type' : "VIDEO" , 'content' : {
255 'video_id' : content
[ 'action' ][ 'watchEndpoint' ][ 'videoId' ],
256 'title' : content
[ 'videoTitle' ][ 'simpleText' ],
257 'author' : delL ( content
[ 'channelName' ][ 'simpleText' ]),
258 'length' : content
. get ( 'lengthString' ,{}). get ( 'simpleText' ) \
259 if not is_live
else "LIVE" , # "23:03"
260 'views' : toInt ( content
. get ( 'viewCountText' ,{}). get ( 'simpleText' )),
261 # XXX: views sometimes "Starts: July 31, 2020 at 1:30 PM"
263 elif ctype
== "playlistInfoCardContentRenderer" :
264 return { 'type' : "PLAYLIST" , 'content' : {
265 'playlist_id' : content
[ 'action' ][ 'watchEndpoint' ][ 'playlistId' ],
266 'video_id' : content
[ 'action' ][ 'watchEndpoint' ][ 'videoId' ],
267 'title' : content
[ 'playlistTitle' ][ 'simpleText' ],
268 'author' : delL ( content
[ 'channelName' ][ 'simpleText' ]),
269 'n_videos' : toInt ( content
[ 'playlistVideoCount' ][ 'simpleText' ]),
271 elif ctype
== "simpleCardContentRenderer" and \
272 'urlEndpoint' in content
[ 'command' ]:
273 return { 'type' : "WEBSITE" , 'content' : {
274 'url' : clean_url ( content
[ 'command' ][ 'urlEndpoint' ][ 'url' ]),
275 'domain' : content
[ 'displayDomain' ][ 'simpleText' ],
276 'title' : content
[ 'title' ][ 'simpleText' ],
277 # XXX: no thumbnails for infocards
279 elif ctype
== "collaboratorInfoCardContentRenderer" :
280 return { 'type' : "CHANNEL" , 'content' : {
281 'channel_id' : content
[ 'endpoint' ][ 'browseEndpoint' ][ 'browseId' ],
282 'title' : content
[ 'channelName' ][ 'simpleText' ],
283 'icons' : mkthumbs ( content
[ 'channelAvatar' ][ 'thumbnails' ]),
284 'subscribers' : content
. get ( 'subscriberCountText' ,{}). get ( 'simpleText' , '' ), # "545K subscribers"
287 log_unknown_card ( card
)
290 def parse_endcard ( card
):
292 parses a single endcard into a format that's easier to handle.
294 card
= card
. get ( 'endscreenElementRenderer' , card
) #only sometimes nested
295 ctype
= card
[ 'style' ]
296 if ctype
== "CHANNEL" :
297 return { 'type' : ctype
, 'content' : {
298 'channel_id' : card
[ 'endpoint' ][ 'browseEndpoint' ][ 'browseId' ],
299 'title' : card
[ 'title' ][ 'simpleText' ],
300 'icons' : mkthumbs ( card
[ 'image' ][ 'thumbnails' ]),
302 elif ctype
== "VIDEO" :
303 if not 'endpoint' in card
: return None # title == "This video is unavailable."
304 return { 'type' : ctype
, 'content' : {
305 'video_id' : card
[ 'endpoint' ][ 'watchEndpoint' ][ 'videoId' ],
306 'title' : card
[ 'title' ][ 'simpleText' ],
307 'length' : card
[ 'videoDuration' ][ 'simpleText' ], # '12:21'
308 'views' : toInt ( card
[ 'metadata' ][ 'simpleText' ]),
309 # XXX: no channel name
311 elif ctype
== "PLAYLIST" :
312 return { 'type' : ctype
, 'content' : {
313 'playlist_id' : card
[ 'endpoint' ][ 'watchEndpoint' ][ 'playlistId' ],
314 'video_id' : card
[ 'endpoint' ][ 'watchEndpoint' ][ 'videoId' ],
315 'title' : card
[ 'title' ][ 'simpleText' ],
316 'author' : delL ( card
[ 'metadata' ][ 'simpleText' ]),
317 'n_videos' : toInt ( card
[ 'playlistLength' ][ 'simpleText' ]),
319 elif ctype
== "WEBSITE" or ctype
== "CREATOR_MERCHANDISE" :
320 url
= clean_url ( card
[ 'endpoint' ][ 'urlEndpoint' ][ 'url' ])
321 return { 'type' : "WEBSITE" , 'content' : {
323 'domain' : urlparse ( url
). netloc
,
324 'title' : card
[ 'title' ][ 'simpleText' ],
325 'icons' : mkthumbs ( card
[ 'image' ][ 'thumbnails' ]),
328 log_unknown_card ( card
)
331 def videoid_from_thumbnail ( content
):
332 # learning playlist; example: PL96C35uN7xGJu6skU4TBYrIWxggkZBrF5 (/user/enyay/playlists)
333 return re
. match ( r
"https?://i.ytimg.com/vi/([-_0-9a-zA-Z] {11} )|()" ,
334 listget ( listget ( content
. get ( 'thumbnails' ,[]), 0 ,{}). get ( 'thumbnails' ,[]), 0 ,{}). get ( 'url' , '' )
337 def parse_channel_items ( items
, channel_id
, author
):
341 key
= next ( iter ( item
. keys ()), None )
343 if key
in [ "gridVideoRenderer" , "videoRenderer" , "videoCardRenderer" ]:
344 # only videoCardRenderer (topic channels) has author and channel, others fall back to supplied ones.
345 result
. append ({ 'type' : 'VIDEO' , 'content' : {
346 'video_id' : content
[ 'videoId' ],
347 'title' : content
[ 'title' ]. get ( 'simpleText' ) or content
[ 'title' ]. get ( 'runs' ,[{}])[ 0 ]. get ( 'text' ),
348 'author' : content
. get ( 'bylineText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'text' ) or author
,
349 'channel_id' : content
. get ( 'bylineText' ,{}). get ( 'runs' ,[{}])[ 0 ] \
350 . get ( 'navigationEndpoint' ,{}). get ( 'browseEndpoint' ,{}). get ( 'browseId' ) or channel_id
,
351 'length' : ( content
. get ( 'lengthText' ,{}). get ( 'simpleText' ) or # topic channel
352 listfind ( content
. get ( 'thumbnailOverlays' ,[]), 'thumbnailOverlayTimeStatusRenderer' )
353 . get ( 'text' ,{}). get ( 'simpleText' )),
354 # topic channel: .metadataText.simpleText = "22M views \u00b7 2 months ago"
355 'views' : toInt ( content
. get ( 'viewCountText' ,{}). get ( 'simpleText' )),
356 'published' : age ( content
. get ( 'publishedTimeText' ,{}). get ( 'simpleText' )),
358 elif key
== "gridPlaylistRenderer" or key
== "playlistRenderer" :
359 result
. append ({ 'type' : 'PLAYLIST' , 'content' : {
360 'playlist_id' : content
[ 'navigationEndpoint' ]. get ( 'watchEndpoint' ,{}). get ( 'playlistId' ) or content
. get ( 'playlistId' ),
361 'video_id' : content
[ 'navigationEndpoint' ]. get ( 'watchEndpoint' ,{}). get ( 'videoId' ,{}) or videoid_from_thumbnail ( content
),
362 'title' : ( content
[ 'title' ]. get ( 'simpleText' ) or # playlistRenderer
363 content
[ 'title' ][ 'runs' ][ 0 ][ 'text' ]), # gridPlaylistRenderer
365 'channel_id' : channel_id
,
366 'n_videos' : toInt ( content
. get ( 'videoCount' ) or # playlistRenderer
367 content
. get ( 'videoCountShortText' ,{}). get ( 'simpleText' ) or # grid(1)
368 content
. get ( 'videoCountText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'text' )), # grid(2)
370 elif key
== "showRenderer" :
371 result
. append ({ 'type' : 'PLAYLIST' , 'content' : {
372 'playlist_id' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ][ 'playlistId' ],
373 'video_id' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ][ 'videoId' ],
374 'title' : content
[ 'title' ][ 'simpleText' ],
376 'channel_id' : channel_id
,
379 elif key
in [ "itemSectionRenderer" , "gridRenderer" , "horizontalCardListRenderer" ]:
381 "itemSectionRenderer" : 'contents' ,
382 "gridRenderer" : 'items' ,
383 "horizontalCardListRenderer" : 'cards' ,
385 r
, e
= parse_channel_items ( content
[ newkey
], channel_id
, author
)
388 elif key
== "shelfRenderer" :
389 r
, e
= parse_channel_items ([ content
[ 'content' ]], channel_id
, author
)
392 elif key
== "messageRenderer" :
393 # e.g. {'messageRenderer': {'text': {'runs': [{'text': 'This channel has no playlists.'}]}}}
395 elif key
== "gameCardRenderer" :
398 log_unknown_card ( item
)
402 def parse_playlist ( item
):
403 key
= next ( iter ( item
. keys ()), None )
405 if key
== "playlistVideoRenderer" :
406 if not content
. get ( 'isPlayable' , False ):
407 return None # private or deleted video
409 return { 'type' : 'VIDEO' , 'content' : {
410 'video_id' : content
[ 'videoId' ],
411 'title' : ( content
[ 'title' ]. get ( 'simpleText' ) or # playable videos
412 content
[ 'title' ]. get ( 'runs' ,[{}])[ 0 ]. get ( 'text' )), # "[Private video]"
413 'playlist_id' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ][ 'playlistId' ],
414 'index' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ]. get ( 'index' , 0 ), #or int(content['index']['simpleText']) (absent on course intros; e.g. PL96C35uN7xGJu6skU4TBYrIWxggkZBrF5)
415 # rest is missing from unplayable videos:
416 'author' : content
. get ( 'shortBylineText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'text' ),
417 'channel_id' : content
. get ( 'shortBylineText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'navigationEndpoint' ,{}). get ( 'browseEndpoint' ,{}). get ( 'browseId' ),
418 'length' : ( content
. get ( "lengthText" ,{}). get ( "simpleText" ) or # "8:51"
419 int ( content
. get ( "lengthSeconds" , 0 ))), # "531"
420 'starttime' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ]. get ( 'startTimeSeconds' ),
423 raise Exception ( item
) # XXX TODO