]>
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 ( response
, channel_id
):
81 meta1
= response|
G ( 'metadata' ) |
G ( 'channelMetadataRenderer' )
82 meta2
= response|
G ( 'microformat' ) |
G ( 'microformatDataRenderer' )
83 title
= meta1|
G ( 'title' ) or meta2|
G ( 'title' )
84 descr
= meta1|
G ( 'description' ) or meta2|
G ( 'description' ) # meta2.description is capped at 160chars
85 thumb
= mkthumbs (( meta2|
G ( 'thumbnail' ) or meta1|
G ( 'avatar' )) |
G ( 'thumbnails' ) or {}) # .avatar ~ 900px
87 contents
= response|
G ( 'continuationContents' )
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 items
, extra
= parse_channel_items ( unparsed
, channel_id
, title
)
94 has_more
= 'continuations' in \
95 ( contents|
G ( 'gridContinuation' , 'sectionListContinuation' ) or {})
97 return title
, descr
, thumb
, items
, has_more
99 def prepare_playlist ( result
):
100 contents
= result
[ 'continuationContents' ]
101 unparsed
= contents
[ 'playlistVideoListContinuation' ]. get ( 'contents' ,[])
102 has_more
= 'continuations' in contents
. get ( 'playlistVideoListContinuation' )
104 return list ( filter ( None , map ( parse_playlist
, unparsed
))), has_more
106 def mkthumbs ( thumbs
):
107 output
= { str ( e
[ 'height' ]): e
[ 'url' ] for e
in thumbs
}
108 largest
= next ( iter ( sorted ( output
. keys (), reverse
= True , key
= int )), None )
109 return {** output
, 'largest' : largest
}
112 # externals URLs are redirected through youtube.com/redirect, but we
113 # may encounter internal URLs, too
114 return parse_qs ( urlparse ( url
). query
). get ( 'q' ,[ url
])[ 0 ]
116 def toInt ( s
, fallback
= 0 ):
120 return int ( '' . join ( filter ( str . isdigit
, s
)))
124 # Remove left-/rightmost word from string:
125 delL
= lambda s
: s
. partition ( ' ' )[ 2 ]
128 if s
is None : # missing from autogen'd music, some livestreams
130 # Some livestreams have "Streamed 7 hours ago"
131 s
= s
. replace ( "Streamed " , "" )
132 # Now, everything should be in the form "1 year ago"
133 value
, unit
, _
= s
. split ( " " )
137 ). get ( unit
, unit
[ 0 ]) # first letter otherwise (e.g. year(s) => y)
139 return f
" {value}{suffix} "
141 def log_unknown_card ( data
):
144 from flask
import request
146 except : source
= "unknown"
147 with
open ( "/tmp/innertube.err" , "a" ) as f
:
148 f
. write ( f
" \n /***** {source} *****/ \n " )
149 json
. dump ( data
, f
, indent
= 2 )
151 def parse_result_items ( items
):
152 # TODO: use .get() for most non-essential attributes
154 parses youtube search response into an easier to use format.
159 key
= next ( iter ( item
. keys ()), None )
161 if key
== 'videoRenderer' :
162 results
. append ({ 'type' : 'VIDEO' , 'content' : {
163 'video_id' : content
[ 'videoId' ],
164 'title' : content
[ 'title' ] |G
. text
,
165 'author' : content|
G ( 'longBylineText' , 'shortBylineText' ) |G
. text
,
166 'channel_id' : content|
G ( 'ownerText' ) |
G ( 'runs' ) |
G ( 0 ) \
167 |
G ( 'navigationEndpoint' ) |
G ( 'browseEndpoint' ) |
G ( 'browseId' ),
168 'length' : content|
G ( 'lengthText' ) |G
. text
, # "44:07", "1:41:50"
169 'views' : content|
G ( 'viewCountText' ) |G
. text|A
. int or 0 , # "1,234 {views|watching}", absent on 0 views
170 'published' : content|
G ( 'publishedTimeText' ) |
G ( 'simpleText' ) |
A ( age
),
171 'live' : content|
G ( 'badges' ) |
Select ( 'metadataBadgeRenderer' ) |
G ( 'style' )== 'BADGE_STYLE_TYPE_LIVE_NOW' ,
173 elif key
in [ 'playlistRenderer' , 'radioRenderer' , 'showRenderer' ]: # radio == "Mix" playlist, show == normal playlist, specially displayed
174 results
. append ({ 'type' : 'PLAYLIST' , 'content' : {
175 'playlist_id' : content
[ 'navigationEndpoint' ] |
G ( 'watchEndpoint' ) |
G ( 'playlistId' ) or \
176 content|
G ( 'playlistId' ), # COURSE/"learning playlist"
177 'video_id' : content
[ 'navigationEndpoint' ] |
G ( 'watchEndpoint' ) |
G ( 'videoId' ) or \
178 videoid_from_thumbnail ( content
), # learning playlist
179 'title' : content
[ 'title' ] |G
. text
,
180 # Note: learning playlists have no author/channel_id
181 'author' : content|
G ( 'longBylineText' , 'shortBylineText' ) |G
. text
,
182 'channel_id' : content|
G ( 'longBylineText' , 'shortBylineText' ) |
G ( 'runs' ) |
G ( 0 ) \
183 |
G ( 'navigationEndpoint' ) |
G ( 'browseEndpoint' ) |
G ( 'browseId' ),
184 'n_videos' : content|
G ( 'videoCount' ) |A
. int or \
185 content|
G ( 'videoCountShortText' , 'videoCountText' ) |G
. text
, # "Mix" playlists
187 elif key
== 'channelRenderer' :
188 results
. append ({ 'type' : 'CHANNEL' , 'content' : {
189 'channel_id' : content
[ 'channelId' ],
190 'title' : content
[ 'title' ] |G
. text
,
191 'icons' : content
[ 'thumbnail' ][ 'thumbnails' ] |
A ( mkthumbs
),
192 'subscribers' : content|
G ( 'subscriberCountText' ) |
G ( 'simpleText' ), # "2.47K subscribers"
194 elif key
== 'shelfRenderer' :
195 subkey
= next ( iter ( content
[ 'content' ]. keys ()), None ) #verticalListRenderer/horizontalMovieListRenderer
196 r
, e
= parse_result_items ( content
[ 'content' ][ subkey
][ 'items' ])
199 elif key
in [ 'movieRenderer' , 'gridMovieRenderer' ]: # movies to buy/rent
200 pass # gMR.{videoId,title.runs[].text,lengthText.simpleText}
201 elif key
in [ 'carouselAdRenderer' , 'searchPyvRenderer' , 'promotedSparklesTextSearchRenderer' ]: # haha, no.
203 elif key
== 'horizontalCardListRenderer' :
204 # suggested searches: .cards[].searchRefinementCardRenderer.query.runs[].text
206 elif key
== 'emergencyOneboxRenderer' : # suicide prevention hotline
208 elif key
in [ 'clarificationRenderer' , 'infoPanelContainerRenderer' ]: # COVID-19/conspiracy theory infos
210 elif key
== 'webAnswerRenderer' : # "Result from the web"
212 elif key
== 'didYouMeanRenderer' or key
== 'showingResultsForRenderer' :
215 'query' : content
[ 'correctedQueryEndpoint' ][ 'searchEndpoint' ][ 'query' ], # non-misspelled query
216 'autocorrected' : key
== 'showingResultsForRenderer' ,
218 elif key
== 'messageRenderer' : # "No more results"
221 'message' : content|
G ( 'title' , 'text' ) |G
. text
,
223 elif key
== 'backgroundPromoRenderer' : # e.g. "no results"
225 'type' : content
[ 'icon' ][ 'iconType' ],
226 'message' : content
[ 'title' ] |G
. text
,
229 log_unknown_card ( item
)
230 return results
, extras
232 def parse_infocard ( card
):
234 parses a single infocard into a format that's easier to handle.
236 card
= card
[ 'cardRenderer' ]
237 ctype
= list ( card
[ 'content' ]. keys ())[ 0 ]
238 content
= card
[ 'content' ][ ctype
]
239 if ctype
== "pollRenderer" :
240 return { 'type' : "POLL" , 'content' : {
241 'question' : content
[ 'question' ][ 'simpleText' ],
242 'answers' : [( a
[ 'text' ][ 'simpleText' ], a
[ 'numVotes' ]) \
243 for a
in content
[ 'choices' ]],
245 elif ctype
== "videoInfoCardContentRenderer" :
246 is_live
= content
. get ( 'badge' ,{}). get ( 'liveBadgeRenderer' ) is not None
247 return { 'type' : "VIDEO" , 'content' : {
248 'video_id' : content
[ 'action' ][ 'watchEndpoint' ][ 'videoId' ],
249 'title' : content
[ 'videoTitle' ][ 'simpleText' ],
250 'author' : delL ( content
[ 'channelName' ][ 'simpleText' ]),
251 'length' : content
. get ( 'lengthString' ,{}). get ( 'simpleText' ) \
252 if not is_live
else "LIVE" , # "23:03"
253 'views' : toInt ( content
. get ( 'viewCountText' ,{}). get ( 'simpleText' )),
254 # XXX: views sometimes "Starts: July 31, 2020 at 1:30 PM"
256 elif ctype
== "playlistInfoCardContentRenderer" :
257 return { 'type' : "PLAYLIST" , 'content' : {
258 'playlist_id' : content
[ 'action' ][ 'watchEndpoint' ][ 'playlistId' ],
259 'video_id' : content
[ 'action' ][ 'watchEndpoint' ][ 'videoId' ],
260 'title' : content
[ 'playlistTitle' ][ 'simpleText' ],
261 'author' : delL ( content
[ 'channelName' ][ 'simpleText' ]),
262 'n_videos' : toInt ( content
[ 'playlistVideoCount' ][ 'simpleText' ]),
264 elif ctype
== "simpleCardContentRenderer" and \
265 'urlEndpoint' in content
[ 'command' ]:
266 return { 'type' : "WEBSITE" , 'content' : {
267 'url' : clean_url ( content
[ 'command' ][ 'urlEndpoint' ][ 'url' ]),
268 'domain' : content
[ 'displayDomain' ][ 'simpleText' ],
269 'title' : content
[ 'title' ][ 'simpleText' ],
270 # XXX: no thumbnails for infocards
272 elif ctype
== "collaboratorInfoCardContentRenderer" :
273 return { 'type' : "CHANNEL" , 'content' : {
274 'channel_id' : content
[ 'endpoint' ][ 'browseEndpoint' ][ 'browseId' ],
275 'title' : content
[ 'channelName' ][ 'simpleText' ],
276 'icons' : mkthumbs ( content
[ 'channelAvatar' ][ 'thumbnails' ]),
277 'subscribers' : content
. get ( 'subscriberCountText' ,{}). get ( 'simpleText' , '' ), # "545K subscribers"
280 log_unknown_card ( card
)
283 def parse_endcard ( card
):
285 parses a single endcard into a format that's easier to handle.
287 card
= card
. get ( 'endscreenElementRenderer' , card
) #only sometimes nested
288 ctype
= card
[ 'style' ]
289 if ctype
== "CHANNEL" :
290 return { 'type' : ctype
, 'content' : {
291 'channel_id' : card
[ 'endpoint' ][ 'browseEndpoint' ][ 'browseId' ],
292 'title' : card
[ 'title' ][ 'simpleText' ],
293 'icons' : mkthumbs ( card
[ 'image' ][ 'thumbnails' ]),
295 elif ctype
== "VIDEO" :
296 if not 'endpoint' in card
: return None # title == "This video is unavailable."
297 return { 'type' : ctype
, 'content' : {
298 'video_id' : card
[ 'endpoint' ][ 'watchEndpoint' ][ 'videoId' ],
299 'title' : card
[ 'title' ][ 'simpleText' ],
300 'length' : card
[ 'videoDuration' ][ 'simpleText' ], # '12:21'
301 'views' : toInt ( card
[ 'metadata' ][ 'simpleText' ]),
302 # XXX: no channel name
304 elif ctype
== "PLAYLIST" :
305 return { 'type' : ctype
, 'content' : {
306 'playlist_id' : card
[ 'endpoint' ][ 'watchEndpoint' ][ 'playlistId' ],
307 'video_id' : card
[ 'endpoint' ][ 'watchEndpoint' ][ 'videoId' ],
308 'title' : card
[ 'title' ][ 'simpleText' ],
309 'author' : delL ( card
[ 'metadata' ][ 'simpleText' ]),
310 'n_videos' : toInt ( card
[ 'playlistLength' ][ 'simpleText' ]),
312 elif ctype
== "WEBSITE" or ctype
== "CREATOR_MERCHANDISE" :
313 url
= clean_url ( card
[ 'endpoint' ][ 'urlEndpoint' ][ 'url' ])
314 return { 'type' : "WEBSITE" , 'content' : {
316 'domain' : urlparse ( url
). netloc
,
317 'title' : card
[ 'title' ][ 'simpleText' ],
318 'icons' : mkthumbs ( card
[ 'image' ][ 'thumbnails' ]),
321 log_unknown_card ( card
)
324 def videoid_from_thumbnail ( content
):
325 # learning playlist; example: PL96C35uN7xGJu6skU4TBYrIWxggkZBrF5 (/user/enyay/playlists)
326 return re
. match ( r
"https?://i.ytimg.com/vi/([-_0-9a-zA-Z] {11} )|()" ,
327 listget ( listget ( content
. get ( 'thumbnails' ,[]), 0 ,{}). get ( 'thumbnails' ,[]), 0 ,{}). get ( 'url' , '' )
330 def parse_channel_items ( items
, channel_id
, author
):
334 key
= next ( iter ( item
. keys ()), None )
336 if key
in [ "gridVideoRenderer" , "videoRenderer" , "videoCardRenderer" ]:
337 # only videoCardRenderer (topic channels) has author and channel, others fall back to supplied ones.
338 result
. append ({ 'type' : 'VIDEO' , 'content' : {
339 'video_id' : content
[ 'videoId' ],
340 'title' : content
[ 'title' ]. get ( 'simpleText' ) or content
[ 'title' ]. get ( 'runs' ,[{}])[ 0 ]. get ( 'text' ),
341 'author' : content
. get ( 'bylineText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'text' ) or author
,
342 'channel_id' : content
. get ( 'bylineText' ,{}). get ( 'runs' ,[{}])[ 0 ] \
343 . get ( 'navigationEndpoint' ,{}). get ( 'browseEndpoint' ,{}). get ( 'browseId' ) or channel_id
,
344 'length' : ( content
. get ( 'lengthText' ,{}). get ( 'simpleText' ) or # topic channel
345 listfind ( content
. get ( 'thumbnailOverlays' ,[]), 'thumbnailOverlayTimeStatusRenderer' )
346 . get ( 'text' ,{}). get ( 'simpleText' )),
347 # topic channel: .metadataText.simpleText = "22M views \u00b7 2 months ago"
348 'views' : toInt ( content
. get ( 'viewCountText' ,{}). get ( 'simpleText' )),
349 'published' : age ( content
. get ( 'publishedTimeText' ,{}). get ( 'simpleText' )),
351 elif key
== "gridPlaylistRenderer" or key
== "playlistRenderer" :
352 result
. append ({ 'type' : 'PLAYLIST' , 'content' : {
353 'playlist_id' : content
[ 'navigationEndpoint' ]. get ( 'watchEndpoint' ,{}). get ( 'playlistId' ) or content
. get ( 'playlistId' ),
354 'video_id' : content
[ 'navigationEndpoint' ]. get ( 'watchEndpoint' ,{}). get ( 'videoId' ,{}) or videoid_from_thumbnail ( content
),
355 'title' : ( content
[ 'title' ]. get ( 'simpleText' ) or # playlistRenderer
356 content
[ 'title' ][ 'runs' ][ 0 ][ 'text' ]), # gridPlaylistRenderer
358 'channel_id' : channel_id
,
359 'n_videos' : toInt ( content
. get ( 'videoCount' ) or # playlistRenderer
360 content
. get ( 'videoCountShortText' ,{}). get ( 'simpleText' ) or # grid(1)
361 content
. get ( 'videoCountText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'text' )), # grid(2)
363 elif key
== "showRenderer" :
364 result
. append ({ 'type' : 'PLAYLIST' , 'content' : {
365 'playlist_id' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ][ 'playlistId' ],
366 'video_id' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ][ 'videoId' ],
367 'title' : content
[ 'title' ][ 'simpleText' ],
369 'channel_id' : channel_id
,
372 elif key
in [ "gridShowRenderer" ]:
373 result
. append ({ 'type' : 'PLAYLIST' , 'content' : {
374 'playlist_id' : ( content|
G ( 'navigationEndpoint' )
375 |
G ( 'browseEndpoint' ) |
G ( 'browseId' ))[ 2 :],
376 #^: playlistId prefixed with 'VL', which must be removed
378 'title' : content|
G ( 'title' ) |G
. text
,
380 'channel_id' : channel_id
,
381 'n_videos' : content|
G ( 'thumbnailOverlays' ) |
G ( 0 )
382 |
G ( 'thumbnailOverlayBottomPanelRenderer' ) |
G ( 'text' ) |G
. text
,
384 elif key
in [ "itemSectionRenderer" , "gridRenderer" , "horizontalCardListRenderer" , "horizontalListRenderer" ]:
386 "itemSectionRenderer" : 'contents' ,
387 "gridRenderer" : 'items' ,
388 "horizontalCardListRenderer" : 'cards' ,
389 "horizontalListRenderer" : 'items' ,
391 r
, e
= parse_channel_items ( content
[ newkey
], channel_id
, author
)
394 elif key
== "shelfRenderer" :
395 r
, e
= parse_channel_items ([ content
[ 'content' ]], channel_id
, author
)
398 elif key
== "messageRenderer" :
399 # e.g. {'messageRenderer': {'text': {'runs': [{'text': 'This channel has no playlists.'}]}}}
401 elif key
== "gameCardRenderer" :
403 elif key
== "gridChannelRenderer" :
404 pass # don't care; related channels, e.g. on UCMsgXPD3wzzt8RxHJmXH7hQ
406 log_unknown_card ( item
)
410 def parse_playlist ( item
):
411 key
= next ( iter ( item
. keys ()), None )
413 if key
== "playlistVideoRenderer" :
414 if not content
. get ( 'isPlayable' , False ):
415 return None # private or deleted video
417 return { 'type' : 'VIDEO' , 'content' : {
418 'video_id' : content
[ 'videoId' ],
419 'title' : ( content
[ 'title' ]. get ( 'simpleText' ) or # playable videos
420 content
[ 'title' ]. get ( 'runs' ,[{}])[ 0 ]. get ( 'text' )), # "[Private video]"
421 'playlist_id' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ][ 'playlistId' ],
422 'index' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ]. get ( 'index' , 0 ), #or int(content['index']['simpleText']) (absent on course intros; e.g. PL96C35uN7xGJu6skU4TBYrIWxggkZBrF5)
423 # rest is missing from unplayable videos:
424 'author' : content
. get ( 'shortBylineText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'text' ),
425 'channel_id' : content
. get ( 'shortBylineText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'navigationEndpoint' ,{}). get ( 'browseEndpoint' ,{}). get ( 'browseId' ),
426 'length' : ( content
. get ( "lengthText" ,{}). get ( "simpleText" ) or # "8:51"
427 int ( content
. get ( "lengthSeconds" , 0 ))), # "531"
428 'starttime' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ]. get ( 'startTimeSeconds' ),
431 raise Exception ( item
) # XXX TODO