]>
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
))
19 def prepare_searchresults ( yt_results
):
20 contents
= listfind ( yt_results
, 'response' ) \
22 . get ( 'twoColumnSearchResultsRenderer' ,{}) \
23 . get ( 'primaryContents' ,{}) \
24 . get ( 'sectionListRenderer' ,{}) \
26 contents
= flatten ([ c
. get ( 'contents' ,[]) for c
in findall ( contents
, 'itemSectionRenderer' )])
28 return parse_result_items ( contents
)
30 def prepare_infocards ( metadata
):
31 cards
= metadata
. get ( 'cards' ,{}). get ( 'cardCollectionRenderer' ,{}). get ( 'cards' ,[])
32 return list ( filter ( None , map ( parse_infocard
, cards
)))
34 def prepare_endcards ( metadata
):
35 endsc
= metadata
. get ( 'endscreen' ,{}). get ( 'endscreenRenderer' ,{}). get ( 'elements' ,[])
36 return list ( filter ( None , map ( parse_endcard
, endsc
)))
38 def prepare_channel ( result
, channel_id
):
39 response
= listfind ( result
, 'response' )
41 if 'alerts' in response
: # possibly got an error back
42 from flask
import current_app
43 current_app
. logger
. error ([( alert
[ 'alertRenderer' ][ 'type' ], alert
[ 'alertRenderer' ][ 'text' ][ 'simpleText' ]) for alert
in response
[ 'alerts' ]])
44 return None , None ,[],[], False
46 meta1
= response
. get ( 'metadata' ,{}). get ( 'channelMetadataRenderer' ,{})
47 meta2
= response
. get ( 'microformat' ,{}). get ( 'microformatDataRenderer' ,{})
48 title
= meta1
. get ( 'title' , meta2
. get ( 'title' ))
49 descr
= meta1
. get ( 'description' , meta2
. get ( 'description' )) # meta2.description is capped at 160chars
50 thumb
= mkthumbs ( meta2
. get ( 'thumbnail' , meta1
. get ( 'avatar' ,{})). get ( 'thumbnails' ,{})) # .avatar ~ 900px
52 contents
= response
. get ( 'continuationContents' )
53 if not contents
: # overran end of list
54 return title
, descr
, thumb
, [], False
56 unparsed
= contents
. get ( 'gridContinuation' ,{}). get ( 'items' ) or \
57 contents
. get ( 'sectionListContinuation' ,{}). get ( 'contents' ) or []
58 items
, extra
= parse_channel_items ( unparsed
, channel_id
, title
)
59 has_more
= 'continuations' in ( contents
. get ( 'gridContinuation' ) or
60 contents
. get ( 'sectionListContinuation' ) or {})
62 return title
, descr
, thumb
, items
, has_more
64 def prepare_playlist ( result
):
65 contents
= listfind ( result
, 'response' )[ 'continuationContents' ]
66 unparsed
= contents
[ 'playlistVideoListContinuation' ]. get ( 'contents' ,[])
67 has_more
= 'continuations' in contents
. get ( 'playlistVideoListContinuation' )
69 return list ( filter ( None , map ( parse_playlist
, unparsed
))), has_more
72 output
= { str ( e
[ 'height' ]): e
[ 'url' ] for e
in thumbs
}
73 largest
= next ( iter ( sorted ( output
. keys (), reverse
= True , key
= int )), None )
74 return {** output
, 'largest' : largest
}
77 # externals URLs are redirected through youtube.com/redirect, but we
78 # may encounter internal URLs, too
79 return parse_qs ( urlparse ( url
). query
). get ( 'q' ,[ url
])[ 0 ]
81 def toInt ( s
, fallback
= 0 ):
85 return int ( '' . join ( filter ( str . isdigit
, s
)))
89 # Remove left-/rightmost word from string:
90 delL
= lambda s
: s
. partition ( ' ' )[ 2 ]
93 if s
is None : # missing from autogen'd music, some livestreams
95 # Some livestreams have "Streamed 7 hours ago"
96 s
= s
. replace ( "Streamed " , "" )
97 # Now, everything should be in the form "1 year ago"
98 value
, unit
, _
= s
. split ( " " )
102 ). get ( unit
, unit
[ 0 ]) # first letter otherwise (e.g. year(s) => y)
104 return f
" {value}{suffix} "
106 def log_unknown_card ( data
):
109 from flask
import request
111 except : source
= "unknown"
112 with
open ( "/tmp/innertube.err" , "a" ) as f
:
113 f
. write ( f
" \n /***** {source} *****/ \n " )
114 json
. dump ( data
, f
, indent
= 2 )
116 def parse_result_items ( items
):
117 # TODO: use .get() for most non-essential attributes
119 parses youtube search response into an easier to use format.
124 key
= next ( iter ( item
. keys ()), None )
126 if key
== 'videoRenderer' :
127 is_live
= listfind ( content
. get ( 'badges' ,[]), 'metadataBadgeRenderer' ). get ( 'style' ) == 'BADGE_STYLE_TYPE_LIVE_NOW'
128 results
. append ({ 'type' : 'VIDEO' , 'content' : {
129 'video_id' : content
[ 'videoId' ],
130 'title' : content
[ 'title' ][ 'runs' ][ 0 ][ 'text' ],
131 'author' : content
[ 'longBylineText' ][ 'runs' ][ 0 ][ 'text' ] or \
132 content
[ 'shortBylineText' ][ 'runs' ][ 0 ][ 'text' ],
133 'channel_id' : content
[ 'ownerText' ][ 'runs' ][ 0 ] \
134 [ 'navigationEndpoint' ][ 'browseEndpoint' ][ 'browseId' ],
135 'length' : content
. get ( 'lengthText' ,{}). get ( 'simpleText' ) \
136 if not is_live
else 'LIVE' , # "44:07", "1:41:50"
137 'views' : toInt ( content
. get ( 'viewCountText' ,{}). get ( 'simpleText' ) or # "123,456 views", ...
138 listget ( content
. get ( 'viewCountText' ,{}). get ( 'runs' ,[]), 0 ,{}). get ( 'text' )) or 0 , # ... "1,234 watching", absent on 0 views
139 'published' : age ( content
. get ( 'publishedTimeText' ,{}). get ( 'simpleText' )),
141 elif key
== 'playlistRenderer' :
142 results
. append ({ 'type' : 'PLAYLIST' , 'content' : {
143 'playlist_id' : content
[ 'navigationEndpoint' ]. get ( 'watchEndpoint' ,{}). get ( 'playlistId' ) or \
144 content
. get ( 'playlistId' ), # COURSE/"learning playlist"
145 'video_id' : content
[ 'navigationEndpoint' ]. get ( 'watchEndpoint' ,{}). get ( 'videoId' ) or \
146 videoid_from_thumbnail ( content
), # learning playlist
147 'title' : content
[ 'title' ][ 'simpleText' ],
148 # Note: learning playlists have no author/channel_id
149 'author' : listget ( content
. get ( 'longBylineText' ,{}). get ( 'runs' ,[]), 0 ,{}). get ( 'text' ) or
150 listget ( content
. get ( 'shortBylineText' ,{}). get ( 'runs' ,[]), 0 ,{}). get ( 'text' ),
151 'channel_id' : listget ( content
. get ( 'longBylineText' ,{}). get ( 'runs' ,[]), 0 ,{}) \
152 . get ( 'navigationEndpoint' ,{}). get ( 'browseEndpoint' ,{}). get ( 'browseId' ), # OR .shortBylineText
153 'n_videos' : toInt ( content
[ 'videoCount' ]),
155 elif key
== 'radioRenderer' : # "Mix" playlists
156 results
. append ({ 'type' : 'PLAYLIST' , 'content' : {
157 'playlist_id' : content
[ 'playlistId' ],
158 'video_id' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ][ 'videoId' ],
159 'title' : content
[ 'title' ][ 'simpleText' ],
160 'author' : content
[ 'longBylineText' ][ 'simpleText' ] or \
161 content
[ 'shortBylineText' ][ 'simpleText' ] , # always "YouTube"
163 'n_videos' : content
[ 'videoCountShortText' ][ 'runs' ][ 0 ][ 'text' ] or \
164 content
[ 'videoCountText' ][ 'runs' ][ 0 ][ 'text' ],
165 # videoCountShortText: "50+"; videoCountText: "50+ videos"
167 elif key
== 'channelRenderer' :
168 results
. append ({ 'type' : 'CHANNEL' , 'content' : {
169 'channel_id' : content
[ 'channelId' ],
170 'title' : content
[ 'title' ][ 'simpleText' ],
171 'icons' : mkthumbs ( content
[ 'thumbnail' ][ 'thumbnails' ]),
172 'subscribers' : content
. get ( 'subscriberCountText' ,{}). get ( 'simpleText' ), # "2.47K subscribers"
174 elif key
== 'shelfRenderer' :
175 subkey
= next ( iter ( content
[ 'content' ]. keys ()), {}) #verticalListRenderer/horizontalMovieListRenderer
176 r
, e
= parse_result_items ( content
[ 'content' ][ subkey
][ 'items' ])
179 elif key
== 'movieRenderer' : # movies to buy/rent
181 elif key
in [ 'carouselAdRenderer' , 'searchPyvRenderer' , 'promotedSparklesTextSearchRenderer' ]: # haha, no.
183 elif key
== 'horizontalCardListRenderer' :
184 # suggested searches: .cards[].searchRefinementCardRenderer.query.runs[].text
186 elif key
== 'emergencyOneboxRenderer' : # suicide prevention hotline
188 elif key
== 'clarificationRenderer' : # COVID-19 infos
190 elif key
== 'didYouMeanRenderer' or key
== 'showingResultsForRenderer' :
193 'query' : content
[ 'correctedQueryEndpoint' ][ 'searchEndpoint' ][ 'query' ], # non-misspelled query
194 'autocorrected' : key
== 'showingResultsForRenderer' ,
196 elif key
== 'backgroundPromoRenderer' : # e.g. "no results"
198 'type' : content
[ 'icon' ][ 'iconType' ],
199 'message' : content
[ 'title' ][ 'runs' ][ 0 ][ 'text' ],
202 log_unknown_card ( item
)
203 return results
, extras
205 def parse_infocard ( card
):
207 parses a single infocard into a format that's easier to handle.
209 card
= card
[ 'cardRenderer' ]
210 ctype
= list ( card
[ 'content' ]. keys ())[ 0 ]
211 content
= card
[ 'content' ][ ctype
]
212 if ctype
== "pollRenderer" :
213 return { 'type' : "POLL" , 'content' : {
214 'question' : content
[ 'question' ][ 'simpleText' ],
215 'answers' : [( a
[ 'text' ][ 'simpleText' ], a
[ 'numVotes' ]) \
216 for a
in content
[ 'choices' ]],
218 elif ctype
== "videoInfoCardContentRenderer" :
219 is_live
= content
. get ( 'badge' ,{}). get ( 'liveBadgeRenderer' ) is not None
220 return { 'type' : "VIDEO" , 'content' : {
221 'video_id' : content
[ 'action' ][ 'watchEndpoint' ][ 'videoId' ],
222 'title' : content
[ 'videoTitle' ][ 'simpleText' ],
223 'author' : delL ( content
[ 'channelName' ][ 'simpleText' ]),
224 'length' : content
. get ( 'lengthString' ,{}). get ( 'simpleText' ) \
225 if not is_live
else "LIVE" , # "23:03"
226 'views' : toInt ( content
. get ( 'viewCountText' ,{}). get ( 'simpleText' )),
227 # XXX: views sometimes "Starts: July 31, 2020 at 1:30 PM"
229 elif ctype
== "playlistInfoCardContentRenderer" :
230 return { 'type' : "PLAYLIST" , 'content' : {
231 'playlist_id' : content
[ 'action' ][ 'watchEndpoint' ][ 'playlistId' ],
232 'video_id' : content
[ 'action' ][ 'watchEndpoint' ][ 'videoId' ],
233 'title' : content
[ 'playlistTitle' ][ 'simpleText' ],
234 'author' : delL ( content
[ 'channelName' ][ 'simpleText' ]),
235 'n_videos' : toInt ( content
[ 'playlistVideoCount' ][ 'simpleText' ]),
237 elif ctype
== "simpleCardContentRenderer" and \
238 'urlEndpoint' in content
[ 'command' ]:
239 return { 'type' : "WEBSITE" , 'content' : {
240 'url' : clean_url ( content
[ 'command' ][ 'urlEndpoint' ][ 'url' ]),
241 'domain' : content
[ 'displayDomain' ][ 'simpleText' ],
242 'title' : content
[ 'title' ][ 'simpleText' ],
243 # XXX: no thumbnails for infocards
245 elif ctype
== "collaboratorInfoCardContentRenderer" :
246 return { 'type' : "CHANNEL" , 'content' : {
247 'channel_id' : content
[ 'endpoint' ][ 'browseEndpoint' ][ 'browseId' ],
248 'title' : content
[ 'channelName' ][ 'simpleText' ],
249 'icons' : mkthumbs ( content
[ 'channelAvatar' ][ 'thumbnails' ]),
250 'subscribers' : content
. get ( 'subscriberCountText' ,{}). get ( 'simpleText' , '' ), # "545K subscribers"
253 log_unknown_card ( card
)
256 def parse_endcard ( card
):
258 parses a single endcard into a format that's easier to handle.
260 card
= card
. get ( 'endscreenElementRenderer' , card
) #only sometimes nested
261 ctype
= card
[ 'style' ]
262 if ctype
== "CHANNEL" :
263 return { 'type' : ctype
, 'content' : {
264 'channel_id' : card
[ 'endpoint' ][ 'browseEndpoint' ][ 'browseId' ],
265 'title' : card
[ 'title' ][ 'simpleText' ],
266 'icons' : mkthumbs ( card
[ 'image' ][ 'thumbnails' ]),
268 elif ctype
== "VIDEO" :
269 return { 'type' : ctype
, 'content' : {
270 'video_id' : card
[ 'endpoint' ][ 'watchEndpoint' ][ 'videoId' ],
271 'title' : card
[ 'title' ][ 'simpleText' ],
272 'length' : card
[ 'videoDuration' ][ 'simpleText' ], # '12:21'
273 'views' : toInt ( card
[ 'metadata' ][ 'simpleText' ]),
274 # XXX: no channel name
276 elif ctype
== "PLAYLIST" :
277 return { 'type' : ctype
, 'content' : {
278 'playlist_id' : card
[ 'endpoint' ][ 'watchEndpoint' ][ 'playlistId' ],
279 'video_id' : card
[ 'endpoint' ][ 'watchEndpoint' ][ 'videoId' ],
280 'title' : card
[ 'title' ][ 'simpleText' ],
281 'author' : delL ( card
[ 'metadata' ][ 'simpleText' ]),
282 'n_videos' : toInt ( card
[ 'playlistLength' ][ 'simpleText' ]),
284 elif ctype
== "WEBSITE" or ctype
== "CREATOR_MERCHANDISE" :
285 url
= clean_url ( card
[ 'endpoint' ][ 'urlEndpoint' ][ 'url' ])
286 return { 'type' : "WEBSITE" , 'content' : {
288 'domain' : urlparse ( url
). netloc
,
289 'title' : card
[ 'title' ][ 'simpleText' ],
290 'icons' : mkthumbs ( card
[ 'image' ][ 'thumbnails' ]),
293 log_unknown_card ( card
)
296 def videoid_from_thumbnail ( content
):
297 # learning playlist; example: PL96C35uN7xGJu6skU4TBYrIWxggkZBrF5 (/user/enyay/playlists)
298 return re
. match ( r
"https?://i.ytimg.com/vi/([-_0-9a-zA-Z] {11} )|()" ,
299 listget ( listget ( content
. get ( 'thumbnails' ,[]), 0 ,{}). get ( 'thumbnails' ,[]), 0 ,{}). get ( 'url' , '' )
302 def parse_channel_items ( items
, channel_id
, author
):
306 key
= next ( iter ( item
. keys ()), None )
308 if key
in [ "gridVideoRenderer" , "videoRenderer" , "videoCardRenderer" ]:
309 # only videoCardRenderer (topic channels) has author and channel, others fall back to supplied ones.
310 result
. append ({ 'type' : 'VIDEO' , 'content' : {
311 'video_id' : content
[ 'videoId' ],
312 'title' : content
[ 'title' ]. get ( 'simpleText' ) or content
[ 'title' ]. get ( 'runs' ,[{}])[ 0 ]. get ( 'text' ),
313 'author' : content
. get ( 'bylineText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'text' ) or author
,
314 'channel_id' : content
. get ( 'bylineText' ,{}). get ( 'runs' ,[{}])[ 0 ] \
315 . get ( 'navigationEndpoint' ,{}). get ( 'browseEndpoint' ,{}). get ( 'browseId' ) or channel_id
,
316 'length' : ( content
. get ( 'lengthText' ,{}). get ( 'simpleText' ) or # topic channel
317 listfind ( content
. get ( 'thumbnailOverlays' ,[]), 'thumbnailOverlayTimeStatusRenderer' )
318 . get ( 'text' ,{}). get ( 'simpleText' )),
319 # topic channel: .metadataText.simpleText = "22M views \u00b7 2 months ago"
320 'views' : toInt ( content
. get ( 'viewCountText' ,{}). get ( 'simpleText' )),
321 'published' : age ( content
. get ( 'publishedTimeText' ,{}). get ( 'simpleText' )),
323 elif key
== "gridPlaylistRenderer" or key
== "playlistRenderer" :
324 result
. append ({ 'type' : 'PLAYLIST' , 'content' : {
325 'playlist_id' : content
[ 'navigationEndpoint' ]. get ( 'watchEndpoint' ,{}). get ( 'playlistId' ) or content
. get ( 'playlistId' ),
326 'video_id' : content
[ 'navigationEndpoint' ]. get ( 'watchEndpoint' ,{}). get ( 'videoId' ,{}) or videoid_from_thumbnail ( content
),
327 'title' : ( content
[ 'title' ]. get ( 'simpleText' ) or # playlistRenderer
328 content
[ 'title' ][ 'runs' ][ 0 ][ 'text' ]), # gridPlaylistRenderer
330 'channel_id' : channel_id
,
331 'n_videos' : toInt ( content
. get ( 'videoCount' ) or # playlistRenderer
332 content
. get ( 'videoCountShortText' ,{}). get ( 'simpleText' ) or # grid(1)
333 content
. get ( 'videoCountText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'text' )), # grid(2)
335 elif key
in [ "itemSectionRenderer" , "gridRenderer" , "horizontalCardListRenderer" ]:
337 "itemSectionRenderer" : 'contents' ,
338 "gridRenderer" : 'items' ,
339 "horizontalCardListRenderer" : 'cards' ,
341 r
, e
= parse_channel_items ( content
[ newkey
], channel_id
, author
)
344 elif key
== "shelfRenderer" :
345 r
, e
= parse_channel_items ([ content
[ 'content' ]], channel_id
, author
)
348 elif key
== "messageRenderer" :
349 # e.g. {'messageRenderer': {'text': {'runs': [{'text': 'This channel has no playlists.'}]}}}
351 elif key
== "gameCardRenderer" :
354 log_unknown_card ( item
)
358 def parse_playlist ( item
):
359 key
= next ( iter ( item
. keys ()), None )
361 if key
== "playlistVideoRenderer" :
362 if not content
. get ( 'isPlayable' , False ):
363 return None # private or deleted video
365 return { 'type' : 'VIDEO' , 'content' : {
366 'video_id' : content
[ 'videoId' ],
367 'title' : ( content
[ 'title' ]. get ( 'simpleText' ) or # playable videos
368 content
[ 'title' ]. get ( 'runs' ,[{}])[ 0 ]. get ( 'text' )), # "[Private video]"
369 'playlist_id' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ][ 'playlistId' ],
370 'index' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ]. get ( 'index' , 0 ), #or int(content['index']['simpleText']) (absent on course intros; e.g. PL96C35uN7xGJu6skU4TBYrIWxggkZBrF5)
371 # rest is missing from unplayable videos:
372 'author' : content
. get ( 'shortBylineText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'text' ),
373 'channel_id' : content
. get ( 'shortBylineText' ,{}). get ( 'runs' ,[{}])[ 0 ]. get ( 'navigationEndpoint' ,{}). get ( 'browseEndpoint' ,{}). get ( 'browseId' ),
374 'length' : ( content
. get ( "lengthText" ,{}). get ( "simpleText" ) or # "8:51"
375 int ( content
. get ( "lengthSeconds" , 0 ))), # "531"
376 'starttime' : content
[ 'navigationEndpoint' ][ 'watchEndpoint' ]. get ( 'startTimeSeconds' ),
379 raise Exception ( item
) # XXX TODO