]>
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 if 'alerts' in response
: # possibly got an error back
82 from flask
import current_app
83 current_app
. logger
. error ([( alert
[ 'alertRenderer' ][ 'type' ], alert
[ 'alertRenderer' ][ 'text' ][ 'simpleText' ]) for alert
in response
[ 'alerts' ]])
84 return None , None ,[],[], False
86 meta1
= response
. get ( 'metadata' ,{}). get ( 'channelMetadataRenderer' ,{})
87 meta2
= response
. get ( 'microformat' ,{}). get ( 'microformatDataRenderer' ,{})
88 title
= meta1
. get ( 'title' , meta2
. get ( 'title' ))
89 descr
= meta1
. get ( 'description' , meta2
. get ( 'description' )) # meta2.description is capped at 160chars
90 thumb
= mkthumbs ( meta2
. get ( 'thumbnail' , meta1
. get ( 'avatar' ,{})). get ( 'thumbnails' ,{})) # .avatar ~ 900px
92 contents
= response
. get ( 'continuationContents' )
93 if not contents
: # overran end of list
94 return title
, descr
, thumb
, [], False
96 unparsed
= contents
. get ( 'gridContinuation' ,{}). get ( 'items' ) or \
97 contents
. get ( 'sectionListContinuation' ,{}). get ( 'contents' ) or []
98 items
, extra
= parse_channel_items ( unparsed
, channel_id
, title
)
99 has_more
= 'continuations' in ( contents
. get ( 'gridContinuation' ) or
100 contents
. get ( 'sectionListContinuation' ) or {})
102 return title
, descr
, thumb
, items
, has_more
104 def prepare_playlist ( result
):
105 contents
= result
[ 'continuationContents' ]
106 unparsed
= contents
[ 'playlistVideoListContinuation' ]. get ( 'contents' ,[])
107 has_more
= 'continuations' in contents
. get ( 'playlistVideoListContinuation' )
109 return list ( filter ( None , map ( parse_playlist
, unparsed
))), has_more
111 def mkthumbs ( thumbs
):
112 output
= { str ( e
[ 'height' ]): e
[ 'url' ] for e
in thumbs
}
113 largest
= next ( iter ( sorted ( output
. keys (), reverse
= True , key
= int )), None )
114 return {** output
, 'largest' : largest
}
117 # externals URLs are redirected through youtube.com/redirect, but we
118 # may encounter internal URLs, too
119 return parse_qs ( urlparse ( url
). query
). get ( 'q' ,[ url
])[ 0 ]
121 def toInt ( s
, fallback
= 0 ):
125 return int ( '' . join ( filter ( str . isdigit
, s
)))
129 # Remove left-/rightmost word from string:
130 delL
= lambda s
: s
. partition ( ' ' )[ 2 ]
133 if s
is None : # missing from autogen'd music, some livestreams
135 # Some livestreams have "Streamed 7 hours ago"
136 s
= s
. replace ( "Streamed " , "" )
137 # Now, everything should be in the form "1 year ago"
138 value
, unit
, _
= s
. split ( " " )
142 ). get ( unit
, unit
[ 0 ]) # first letter otherwise (e.g. year(s) => y)
144 return f
" {value}{suffix} "
146 def log_unknown_card ( data
):
149 from flask
import request
151 except : source
= "unknown"
152 with
open ( "/tmp/innertube.err" , "a" ) as f
:
153 f
. write ( f
" \n /***** {source} *****/ \n " )
154 json
. dump ( data
, f
, indent
= 2 )
156 def parse_result_items ( items
):
157 # TODO: use .get() for most non-essential attributes
159 parses youtube search response into an easier to use format.
164 key
= next ( iter ( item
. keys ()), None )
166 if key
== 'videoRenderer' :
167 results
. append ({ 'type' : 'VIDEO' , 'content' : {
168 'video_id' : content
[ 'videoId' ],
169 'title' : content
[ 'title' ] |G
. text
,
170 'author' : content|
G ( 'longBylineText' , 'shortBylineText' ) |G
. text
,
171 'channel_id' : content|
G ( 'ownerText' ) |
G ( 'runs' ) |
G ( 0 ) \
172 |
G ( 'navigationEndpoint' ) |
G ( 'browseEndpoint' ) |
G ( 'browseId' ),
173 'length' : content|
G ( 'lengthText' ) |G
. text
, # "44:07", "1:41:50"
174 'views' : content|
G ( 'viewCountText' ) |G
. text|A
. int or 0 , # "1,234 {views|watching}", absent on 0 views
175 'published' : content|
G ( 'publishedTimeText' ) |
G ( 'simpleText' ) |
A ( age
),
176 'live' : content|
G ( 'badges' ) |
Select ( 'metadataBadgeRenderer' ) |
G ( 'style' )== 'BADGE_STYLE_TYPE_LIVE_NOW' ,
178 elif key
in [ 'playlistRenderer' , 'radioRenderer' , 'showRenderer' ]: # radio == "Mix" playlist, show == normal playlist, specially displayed
179 results
. append ({ 'type' : 'PLAYLIST' , 'content' : {
180 'playlist_id' : content
[ 'navigationEndpoint' ] |
G ( 'watchEndpoint' ) |
G ( 'playlistId' ) or \
181 content|
G ( 'playlistId' ), # COURSE/"learning playlist"
182 'video_id' : content
[ 'navigationEndpoint' ] |
G ( 'watchEndpoint' ) |
G ( 'videoId' ) or \
183 videoid_from_thumbnail ( content
), # learning playlist
184 'title' : content
[ 'title' ] |G
. text
,
185 # Note: learning playlists have no author/channel_id
186 'author' : content|
G ( 'longBylineText' , 'shortBylineText' ) |G
. text
,
187 'channel_id' : content|
G ( 'longBylineText' , 'shortBylineText' ) |
G ( 'runs' ) |
G ( 0 ) \
188 |
G ( 'navigationEndpoint' ) |
G ( 'browseEndpoint' ) |
G ( 'browseId' ),
189 'n_videos' : content|
G ( 'videoCount' ) |A
. int or \
190 content|
G ( 'videoCountShortText' , 'videoCountText' ) |G
. text
, # "Mix" playlists
192 elif key
== 'channelRenderer' :
193 results
. append ({ 'type' : 'CHANNEL' , 'content' : {
194 'channel_id' : content
[ 'channelId' ],
195 'title' : content
[ 'title' ] |G
. text
,
196 'icons' : content
[ 'thumbnail' ][ 'thumbnails' ] |
A ( mkthumbs
),
197 'subscribers' : content|
G ( 'subscriberCountText' ) |
G ( 'simpleText' ), # "2.47K subscribers"
199 elif key
== 'shelfRenderer' :
200 subkey
= next ( iter ( content
[ 'content' ]. keys ()), None ) #verticalListRenderer/horizontalMovieListRenderer
201 r
, e
= parse_result_items ( content
[ 'content' ][ subkey
][ 'items' ])
204 elif key
in [ 'movieRenderer' , 'gridMovieRenderer' ]: # movies to buy/rent
205 pass # gMR.{videoId,title.runs[].text,lengthText.simpleText}
206 elif key
in [ 'carouselAdRenderer' , 'searchPyvRenderer' , 'promotedSparklesTextSearchRenderer' ]: # haha, no.
208 elif key
== 'horizontalCardListRenderer' :
209 # suggested searches: .cards[].searchRefinementCardRenderer.query.runs[].text
211 elif key
== 'emergencyOneboxRenderer' : # suicide prevention hotline
213 elif key
in [ 'clarificationRenderer' , 'infoPanelContainerRenderer' ]: # COVID-19/conspiracy theory infos
215 elif key
== 'webAnswerRenderer' : # "Result from the web"
217 elif key
== 'didYouMeanRenderer' or key
== 'showingResultsForRenderer' :
220 'query' : content
[ 'correctedQueryEndpoint' ][ 'searchEndpoint' ][ 'query' ], # non-misspelled query
221 'autocorrected' : key
== 'showingResultsForRenderer' ,
223 elif key
== 'messageRenderer' : # "No more results"
226 'message' : content|
G ( 'title' , 'text' ) |G
. text
,
228 elif key
== 'backgroundPromoRenderer' : # e.g. "no results"
230 'type' : content
[ 'icon' ][ 'iconType' ],
231 'message' : content
[ 'title' ] |G
. text
,
234 log_unknown_card ( item
)
235 return results
, extras
237 def parse_infocard ( card
):
239 parses a single infocard into a format that's easier to handle.
241 card
= card
[ 'cardRenderer' ]
242 ctype
= list ( card
[ 'content' ]. keys ())[ 0 ]
243 content
= card
[ 'content' ][ ctype
]
244 if ctype
== "pollRenderer" :
245 return { 'type' : "POLL" , 'content' : {
246 'question' : content
[ 'question' ][ 'simpleText' ],
247 'answers' : [( a
[ 'text' ][ 'simpleText' ], a
[ 'numVotes' ]) \
248 for a
in content
[ 'choices' ]],
250 elif ctype
== "videoInfoCardContentRenderer" :
251 is_live
= content
. get ( 'badge' ,{}). get ( 'liveBadgeRenderer' ) is not None
252 return { 'type' : "VIDEO" , 'content' : {
253 'video_id' : content
[ 'action' ][ 'watchEndpoint' ][ 'videoId' ],
254 'title' : content
[ 'videoTitle' ][ 'simpleText' ],
255 'author' : delL ( content
[ 'channelName' ][ 'simpleText' ]),
256 'length' : content
. get ( 'lengthString' ,{}). get ( 'simpleText' ) \
257 if not is_live
else "LIVE" , # "23:03"
258 'views' : toInt ( content
. get ( 'viewCountText' ,{}). get ( 'simpleText' )),
259 # XXX: views sometimes "Starts: July 31, 2020 at 1:30 PM"
261 elif ctype
== "playlistInfoCardContentRenderer" :
262 return { 'type' : "PLAYLIST" , 'content' : {
263 'playlist_id' : content
[ 'action' ][ 'watchEndpoint' ][ 'playlistId' ],
264 'video_id' : content
[ 'action' ][ 'watchEndpoint' ][ 'videoId' ],
265 'title' : content
[ 'playlistTitle' ][ 'simpleText' ],
266 'author' : delL ( content
[ 'channelName' ][ 'simpleText' ]),
267 'n_videos' : toInt ( content
[ 'playlistVideoCount' ][ 'simpleText' ]),
269 elif ctype
== "simpleCardContentRenderer" and \
270 'urlEndpoint' in content
[ 'command' ]:
271 return { 'type' : "WEBSITE" , 'content' : {
272 'url' : clean_url ( content
[ 'command' ][ 'urlEndpoint' ][ 'url' ]),
273 'domain' : content
[ 'displayDomain' ][ 'simpleText' ],
274 'title' : content
[ 'title' ][ 'simpleText' ],
275 # XXX: no thumbnails for infocards
277 elif ctype
== "collaboratorInfoCardContentRenderer" :
278 return { 'type' : "CHANNEL" , 'content' : {
279 'channel_id' : content
[ 'endpoint' ][ 'browseEndpoint' ][ 'browseId' ],
280 'title' : content
[ 'channelName' ][ 'simpleText' ],
281 'icons' : mkthumbs ( content
[ 'channelAvatar' ][ 'thumbnails' ]),
282 'subscribers' : content
. get ( 'subscriberCountText' ,{}). get ( 'simpleText' , '' ), # "545K subscribers"
285 log_unknown_card ( card
)
288 def parse_endcard ( card
):
290 parses a single endcard into a format that's easier to handle.
292 card
= card
. get ( 'endscreenElementRenderer' , card
) #only sometimes nested
293 ctype
= card
[ 'style' ]
294 if ctype
== "CHANNEL" :
295 return { 'type' : ctype
, 'content' : {
296 'channel_id' : card
[ 'endpoint' ][ 'browseEndpoint' ][ 'browseId' ],
297 'title' : card
[ 'title' ][ 'simpleText' ],
298 'icons' : mkthumbs ( card
[ 'image' ][ 'thumbnails' ]),
300 elif ctype
== "VIDEO" :
301 if not 'endpoint' in card
: return None # title == "This video is unavailable."
302 return { 'type' : ctype
, 'content' : {
303 'video_id' : card
[ 'endpoint' ][ 'watchEndpoint' ][ 'videoId' ],
304 'title' : card
[ 'title' ][ 'simpleText' ],
305 'length' : card
[ 'videoDuration' ][ 'simpleText' ], # '12:21'
306 'views' : toInt ( card
[ 'metadata' ][ 'simpleText' ]),
307 # XXX: no channel name
309 elif ctype
== "PLAYLIST" :
310 return { 'type' : ctype
, 'content' : {
311 'playlist_id' : card
[ 'endpoint' ][ 'watchEndpoint' ][ 'playlistId' ],
312 'video_id' : card
[ 'endpoint' ][ 'watchEndpoint' ][ 'videoId' ],
313 'title' : card
[ 'title' ][ 'simpleText' ],
314 'author' : delL ( card
[ 'metadata' ][ 'simpleText' ]),
315 'n_videos' : toInt ( card
[ 'playlistLength' ][ 'simpleText' ]),
317 elif ctype
== "WEBSITE" or ctype
== "CREATOR_MERCHANDISE" :
318 url
= clean_url ( card
[ 'endpoint' ][ 'urlEndpoint' ][ 'url' ])
319 return { 'type' : "WEBSITE" , 'content' : {
321 'domain' : urlparse ( url
). netloc
,
322 'title' : card
[ 'title' ][ 'simpleText' ],
323 'icons' : mkthumbs ( card
[ 'image' ][ 'thumbnails' ]),
326 log_unknown_card ( card
)
329 def videoid_from_thumbnail ( content
):
330 # learning playlist; example: PL96C35uN7xGJu6skU4TBYrIWxggkZBrF5 (/user/enyay/playlists)
331 return re
. match ( r
"https?://i.ytimg.com/vi/([-_0-9a-zA-Z] {11} )|()" ,
332 listget ( listget ( content
. get ( 'thumbnails' ,[]), 0 ,{}). get ( 'thumbnails' ,[]), 0 ,{}). get ( 'url' , '' )
335 def parse_channel_items ( items
, channel_id
, author
):
339 key
= next ( iter ( item
. keys ()), None )
341 if key
in [ "gridVideoRenderer" , "videoRenderer" , "videoCardRenderer" ]:
342 # only videoCardRenderer (topic channels) has author and channel, others fall back to supplied ones.
343 result
. append ({ 'type' : 'VIDEO' , 'content' : {
344 'video_id' : content
[ 'videoId' ],
345 'title' : content
[ 'title' ]. get ( 'simpleText' ) or content
[ 'title' ]. get ( 'runs' ,[{}])[ 0 ]. get ( 'text' ),
346 'author' : content
. get ( 'bylineText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'text' ) or author
,
347 'channel_id' : content
. get ( 'bylineText' ,{}). get ( 'runs' ,[{}])[ 0 ] \
348 . get ( 'navigationEndpoint' ,{}). get ( 'browseEndpoint' ,{}). get ( 'browseId' ) or channel_id
,
349 'length' : ( content
. get ( 'lengthText' ,{}). get ( 'simpleText' ) or # topic channel
350 listfind ( content
. get ( 'thumbnailOverlays' ,[]), 'thumbnailOverlayTimeStatusRenderer' )
351 . get ( 'text' ,{}). get ( 'simpleText' )),
352 # topic channel: .metadataText.simpleText = "22M views \u00b7 2 months ago"
353 'views' : toInt ( content
. get ( 'viewCountText' ,{}). get ( 'simpleText' )),
354 'published' : age ( content
. get ( 'publishedTimeText' ,{}). get ( 'simpleText' )),
356 elif key
== "gridPlaylistRenderer" or key
== "playlistRenderer" :
357 result
. append ({ 'type' : 'PLAYLIST' , 'content' : {
358 'playlist_id' : content
[ 'navigationEndpoint' ]. get ( 'watchEndpoint' ,{}). get ( 'playlistId' ) or content
. get ( 'playlistId' ),
359 'video_id' : content
[ 'navigationEndpoint' ]. get ( 'watchEndpoint' ,{}). get ( 'videoId' ,{}) or videoid_from_thumbnail ( content
),
360 'title' : ( content
[ 'title' ]. get ( 'simpleText' ) or # playlistRenderer
361 content
[ 'title' ][ 'runs' ][ 0 ][ 'text' ]), # gridPlaylistRenderer
363 'channel_id' : channel_id
,
364 'n_videos' : toInt ( content
. get ( 'videoCount' ) or # playlistRenderer
365 content
. get ( 'videoCountShortText' ,{}). get ( 'simpleText' ) or # grid(1)
366 content
. get ( 'videoCountText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'text' )), # grid(2)
368 elif key
== "showRenderer" :
369 result
. append ({ 'type' : 'PLAYLIST' , 'content' : {
370 'playlist_id' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ][ 'playlistId' ],
371 'video_id' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ][ 'videoId' ],
372 'title' : content
[ 'title' ][ 'simpleText' ],
374 'channel_id' : channel_id
,
377 elif key
in [ "itemSectionRenderer" , "gridRenderer" , "horizontalCardListRenderer" ]:
379 "itemSectionRenderer" : 'contents' ,
380 "gridRenderer" : 'items' ,
381 "horizontalCardListRenderer" : 'cards' ,
383 r
, e
= parse_channel_items ( content
[ newkey
], channel_id
, author
)
386 elif key
== "shelfRenderer" :
387 r
, e
= parse_channel_items ([ content
[ 'content' ]], channel_id
, author
)
390 elif key
== "messageRenderer" :
391 # e.g. {'messageRenderer': {'text': {'runs': [{'text': 'This channel has no playlists.'}]}}}
393 elif key
== "gameCardRenderer" :
396 log_unknown_card ( item
)
400 def parse_playlist ( item
):
401 key
= next ( iter ( item
. keys ()), None )
403 if key
== "playlistVideoRenderer" :
404 if not content
. get ( 'isPlayable' , False ):
405 return None # private or deleted video
407 return { 'type' : 'VIDEO' , 'content' : {
408 'video_id' : content
[ 'videoId' ],
409 'title' : ( content
[ 'title' ]. get ( 'simpleText' ) or # playable videos
410 content
[ 'title' ]. get ( 'runs' ,[{}])[ 0 ]. get ( 'text' )), # "[Private video]"
411 'playlist_id' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ][ 'playlistId' ],
412 'index' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ]. get ( 'index' , 0 ), #or int(content['index']['simpleText']) (absent on course intros; e.g. PL96C35uN7xGJu6skU4TBYrIWxggkZBrF5)
413 # rest is missing from unplayable videos:
414 'author' : content
. get ( 'shortBylineText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'text' ),
415 'channel_id' : content
. get ( 'shortBylineText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'navigationEndpoint' ,{}). get ( 'browseEndpoint' ,{}). get ( 'browseId' ),
416 'length' : ( content
. get ( "lengthText" ,{}). get ( "simpleText" ) or # "8:51"
417 int ( content
. get ( "lengthSeconds" , 0 ))), # "531"
418 'starttime' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ]. get ( 'startTimeSeconds' ),
421 raise Exception ( item
) # XXX TODO