]>
git.gir.st - subscriptionfeed.git/blob - app/common/common.py
10 from xml
. etree
import ElementTree
11 from configparser
import ConfigParser
12 from datetime
import datetime
, timezone
13 from urllib
. parse
import parse_qs
, urlparse
16 config_filename
= os
. environ
. get ( 'YT_CONFIG' , '/etc/yt/config.ini' )
17 cf
. read ( config_filename
)
18 if not 'global' in cf
: # todo: full config check
19 raise Exception ( "Configuration file not found or empty" )
21 # Note: currently expiring after 10 minutes. googlevideo-urls are valid for 5h59m, but this makes reddit very stale and premiere videos won't start. TODO: exipre when video is livestream/premiere/etc
22 requests_cache
. install_cache ( backend
= 'memory' , expire_after
= 10 * 60 , allowable_codes
=( 200 ,), allowable_methods
=( 'GET' , 'HEAD' , 'POST' ))
24 # Note: requests-cache doesn't use redis expiry, so we need this in all backends:
25 # https://github.com/reclosedev/requests-cache/issues/58#issuecomment-164537971
26 # TODO: only run for long-running processes, i.e. the frontend
27 from threading
import Timer
29 requests_cache
. remove_expired_responses ()
30 t
= Timer ( sec
, purge_cache
, args
=( sec
,))
35 # for debugging purposes, monkey patch requests session to store each requests-request in a flask-request's g object (url and response). we can then use a flask error_handler to include the request data in the error log.
36 # since we also call config from outside the flask appcontext, it is wrapped in a try-catch block.
39 from requests
import Session
as OriginalSession
40 class _NSASession ( OriginalSession
):
41 def request ( self
, method
, url
, params
= None , data
= None , ** kwargs
):
42 response
= super ( _NSASession
, self
). request (
43 method
, url
, params
, data
, ** kwargs
46 if 'api_requests' not in g
:
48 g
. api_requests
. append (( url
, params
, response
. text
))
49 except RuntimeError : pass # not within flask (e.g. utils.py)
51 requests
. Session
= requests
. sessions
. Session
= _NSASession
53 def fetch_xml ( feed_type
, feed_id
):
54 # TODO: handle requests.exceptions.ConnectionError
55 r
= requests
. get ( "https://www.youtube.com/feeds/videos.xml" , {
63 def parse_xml ( xmldata
):
65 'atom' : "http://www.w3.org/2005/Atom" ,
66 'yt' : "http://www.youtube.com/xml/schemas/2015" ,
67 'media' : "http://search.yahoo.com/mrss/" ,
68 'at' : "http://purl.org/atompub/tombstones/1.0" ,
71 feed
= ElementTree
. fromstring ( xmldata
)
73 if feed
. find ( 'at:deleted-entry' , ns
):
74 ( _
, _
, vid
) = feed
. find ( 'at:deleted-entry' , ns
). get ( 'ref' ). rpartition ( ':' )
75 return None , None , [{ 'deleted' : True , 'video_id' : vid
}], None , None
77 title
= feed
. find ( 'atom:title' , ns
). text
78 author
= feed
. find ( 'atom:author/atom:name' , ns
). text \
79 if feed
. find ( 'atom:author' , ns
) else None
80 # for /user/<> endpoint: find out UC-id:
81 # for playlists: this is who created the playlist:
82 try : channel_id
= feed
. find ( 'yt:channelId' , ns
). text
83 except : channel_id
= None # XXX: why does ternary not work!?
84 # for pullsub: if this exists, we're looking at a playlist:
85 try : playlist_id
= feed
. find ( 'yt:playlistId' , ns
). text
86 except : playlist_id
= None # XXX: why does ternary not work!?
88 for entry
in feed
. findall ( 'atom:entry' , ns
):
90 'video_id' : entry
. find ( 'yt:videoId' , ns
). text
,
91 'title' : entry
. find ( 'atom:title' , ns
). text
,
92 'published' : entry
. find ( 'atom:published' , ns
). text
,
93 'channel_id' : entry
. find ( 'yt:channelId' , ns
). text
,
94 'author' : entry
. find ( 'atom:author' , ns
). find ( 'atom:name' , ns
). text
,
95 # extra fields for pull_subs/webhook:
96 'updated' : entry
. find ( 'atom:updated' , ns
). text
,
99 return title
, author
, videos
, channel_id
, playlist_id
101 def update_channel ( db
, xmldata
, from_webhook
= False ):
102 if not xmldata
: return False
104 # Note: websub does not return global author, hence taking from first video
105 title
, author
, videos
, channel
, playlist
= parse_xml ( xmldata
)
108 for i
, video
in enumerate ( videos
):
109 if video
. get ( 'deleted' ):
110 # Note: Deletion events are not just fired for actual deletions,
111 # but also for unlisting videos and livestreams that just ended
112 # (even postLiveDVR ones). Hence, we don't follow it.
113 flask_logger ( f
"ignoring deleted/unlisted/ended video/stream {video['video_id']}" )
116 c
. execute ( "SELECT 1 FROM videos WHERE id=?" ,( video
[ 'video_id' ],))
117 new_video
= len ( c
. fetchall ()) < 1
119 # TODO: call store_video_metadata(video_id) here instead and pass video-fallback-metadata to it
120 _
, _
, meta
, _
, _
= get_video_info ( video
[ 'video_id' ], metaOnly
= True )
121 # The 'published' timestamp sent in websub POSTs are often wrong (e.g.:
122 # video gets uploaded as unlisted on day A and set to public on day B;
123 # the webhook is sent on day B, but 'published' says A. The video
124 # therefore looks like it's just an update to an older video).
125 # g_v_i gives is the date the video was published to viewers, so we
126 # prefer that. But since g_v_i only returns the date without time,
127 # we still use xmlfeed's date if it's the same date.
128 published
= dateutil
. parser
. parse ( video
[ 'published' ])
133 meta
= video_metadata ( meta
)
134 published2
= dateutil
. parser
. parse ( meta
[ 'published' ])
135 if published
< published2
: # g_v_i date is more accurate:
136 published
= published2
137 length
= meta
[ 'length' ]
138 livestream
= meta
[ 'livestream' ]
139 premiere
= meta
[ 'premiere' ]
141 now
= datetime
. now ( timezone
. utc
)
143 # we pretend that all videos uploaded this week were uploaded just
144 # now, so the user sees it at the top of the feed, and it doesn't
145 # get inserted somewhere further down.
146 if ( now
- published
). days
< 7 :
148 else : #, it's just an update to an older video.
149 timestamp
= published
152 INSERT OR IGNORE INTO videos
153 (id, channel_id, title, length, livestream, premiere, published, crawled)
154 VALUES (?, ?, ?, ?, ?, ?, datetime(?), datetime(?))
166 # update video title (everything else can't change)
168 UPDATE OR IGNORE videos
176 # for channels, this is obviously always the same, but playlists can
177 # consist of videos from different channels:
178 if i
== 0 or playlist
:
180 INSERT OR REPLACE INTO channels (id, name)
182 """ , ( video
[ 'channel_id' ], video
[ 'author' ]))
184 # keep track of which videos are in a playlist, so we can show the user
185 # why a video is in their feed:
188 INSERT OR IGNORE INTO playlist_videos (video_id, playlist_id)
190 """ , ( video
[ 'video_id' ], playlist
))
192 if playlist
and not from_webhook
: # Note: playlists can't get updated via websub
194 INSERT OR REPLACE INTO playlists (id, name, author)
196 """ , ( playlist
, title
, channel
))
198 INSERT OR REPLACE INTO channels (id, name)
200 """ , ( channel
, author
))
206 def get_video_info ( video_id
, *, metaOnly
= False , _embed
= True ):
208 returns: best-quality muxed video stream, stream map, player_response, error-type/mesage
209 error types: player, malformed, livestream, geolocked, agegated, no-url, exhausted
211 player_error
, metadata
= None , None # for 'exhausted'
212 with sqlite3
. connect ( cf
[ 'global' ][ 'database' ]) as conn
:
214 c
. execute ( "SELECT * FROM captcha_cookies" )
215 cookies
= dict ( c
. fetchall ())
216 today
= datetime
. now ( timezone
. utc
). strftime ( "%Y%m %d " )
217 # XXX: anticaptcha hasn't been adapted
218 # XXX: this is not cached any more!
219 key
= "AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8"
220 r
= requests
. post ( "https://www.youtube-nocookie.com/youtubei/v1/player" , params
={ 'key' : key
}, json
={
226 # ANDROID returns streams that are not throttled or cipher-scambled, but less metadata than WEB
227 'clientName' : 'ANDROID' if not metaOnly
else 'WEB' ,
228 'clientVersion' : f
'16.20' if not metaOnly
else f
'2. {today} .01.01' ,
229 **({ 'clientScreen' : 'EMBED' } if _embed
else {}),
231 'thirdParty' : { 'embedUrl' : 'https://google.com' }
235 if not r
or r
. status_code
== 429 :
236 return None , None , None , 'banned' , 'possible IP ban'
239 if "error" in metadata
:
240 return None , None , metadata
, "malformed" , metadata
. get ( "error" ,{}). get ( "message" , "" )
241 playabilityStatus
= metadata
[ 'playabilityStatus' ][ 'status' ]
242 if playabilityStatus
!= "OK" :
243 playabilityReason
= metadata
[ 'playabilityStatus' ]. get ( 'reason' ,
244 '//' . join ( metadata
[ 'playabilityStatus' ]. get ( 'messages' ,[])))
245 player_error
= f
" {playabilityStatus} : {playabilityReason} "
246 # "Watch on YouTube" button is visible => "Playback on other websites
247 # has been disabled by the video owner." => retry detailpage API
248 if ( playabilityStatus
== "UNPLAYABLE" and
249 'proceedButton' in metadata
[ 'playabilityStatus' ] \
250 . get ( 'errorScreen' ,{}). get ( 'playerErrorMessageRenderer' ,{})
251 and not metaOnly
# only need metadata (e.g. called from pubsubhubbub)
255 _
, _
, metadata_embed
, error_embed
, errormsg_embed
= get_video_info ( video_id
, _embed
= False )
256 if not error_embed
or error_embed
in ( 'livestream' , 'geolocked' ):
257 metadata
= metadata_embed
258 elif errormsg_embed
== "LOGIN_REQUIRED: Sign in to confirm your age" :
259 return None , None , metadata
, 'agegated' , player_error
261 return None , None , metadata
, error_embed
, errormsg_embed
263 # without videoDetails, there's only the error message
264 maybe_metadata
= metadata
if 'videoDetails' in metadata
else None
265 return None , None , maybe_metadata
, 'player' , player_error
267 # livestreams have no adaptive/muxed formats:
268 is_live
= metadata
[ 'videoDetails' ]. get ( 'isLive' , False )
270 if not 'formats' in metadata
[ 'streamingData' ] and not is_live
:
271 return None , None , metadata
, 'no-url' , player_error
273 formats
= metadata
[ 'streamingData' ]. get ( 'formats' ,[])
274 adaptive
= metadata
[ 'streamingData' ]. get ( 'adaptiveFormats' ,[])
276 'adaptive_video' : [ a
for a
in adaptive
if a
[ 'mimeType' ]. startswith ( 'video/' )],
277 'adaptive_audio' : [ a
for a
in adaptive
if a
[ 'mimeType' ]. startswith ( 'audio/' )],
279 'hlsManifestUrl' : metadata
[ 'streamingData' ]. get ( 'hlsManifestUrl' ),
283 url
= sorted ( formats
, key
= lambda k
: k
[ 'height' ], reverse
= True )[ 0 ][ 'url' ]
287 # ip-locked videos can be recovered if the proxy module is loaded:
288 is_geolocked
= 'gcr' in parse_qs ( urlparse ( url
). query
)
290 nonfatal
= 'livestream' if is_live \
291 else 'geolocked' if is_geolocked \
294 return url
, stream_map
, metadata
, nonfatal
, None
296 def video_metadata ( metadata
):
300 meta1
= metadata
[ 'videoDetails' ]
301 # With ANDROID player API, we don't get microformat => no publishDate!
302 meta2
= metadata
. get ( 'microformat' ,{}). get ( 'playerMicroformatRenderer' ,{})
304 # sometimes, we receive the notification so early that the length is not
305 # yet populated. Nothing we can do about it.
306 length
= int ( meta2
. get ( 'lengthSeconds' , 0 )) or int ( meta1
. get ( 'lengthSeconds' , 0 )) or None
308 scheduled_time
= metadata
. get ( 'playabilityStatus' ,{}) \
309 . get ( 'liveStreamability' ,{}). get ( 'liveStreamabilityRenderer' ,{}) \
310 . get ( 'offlineSlate' ,{}). get ( 'liveStreamOfflineSlateRenderer' ,{}) \
311 . get ( 'scheduledStartTime' )
313 scheduled_time
= datetime
. fromtimestamp ( int ( scheduled_time
)) \
314 . strftime ( "%Y-%m- %d T%H:%M:%SZ" )
316 meta2
. get ( 'liveBroadcastDetails' ,{}) . get ( 'startTimestamp' ) or
318 f
"{meta2.get('publishDate','1970-01-01')}T00:00:00Z"
321 # Note: 'premiere' videos have livestream=False and published= will be the
322 # start of the premiere.
324 'title' : meta1
[ 'title' ],
325 'author' : meta1
[ 'author' ],
326 'channel_id' : meta1
[ 'channelId' ],
327 'published' : published_at
,
328 'views' : int ( meta1
[ 'viewCount' ]),
330 'livestream' : meta1
[ 'isLiveContent' ],
331 'premiere' : meta1
. get ( 'isUpcoming' ) and not meta1
[ 'isLiveContent' ],
334 def store_video_metadata ( video_id
):
335 # check if we know about it, and if not, fetch and store video metadata
336 with sqlite3
. connect ( cf
[ 'global' ][ 'database' ]) as conn
:
338 c
. execute ( "SELECT 1 from videos where id = ?" , ( video_id
,))
339 new_video
= len ( c
. fetchall ()) < 1
341 _
, _
, meta
, _
, _
= get_video_info ( video_id
, metaOnly
= True )
343 meta
= video_metadata ( meta
)
345 INSERT OR IGNORE INTO videos (id, channel_id, title, length, livestream, premiere, published, crawled)
346 VALUES (?, ?, ?, ?, ?, ?, datetime(?), datetime(?))
358 INSERT OR REPLACE INTO channels (id, name)
360 """ , ( meta
[ 'channel_id' ], meta
[ 'author' ]))
362 def fetch_video_flags ( token
, video_ids
):
363 with sqlite3
. connect ( cf
[ 'global' ][ 'database' ]) as conn
:
366 SELECT video_id,display
369 AND display IS NOT NULL
371 -- AND display = 'pinned'
372 """ . format ( "," . join ([ "?" ]* len ( video_ids
))), ( token
,* video_ids
))
374 pinned
= [ video
for video
, disp
in flags
if disp
== 'pinned' ]
375 hidden
= [ video
for video
, disp
in flags
if disp
== 'hidden' ]
377 return pinned
, hidden
379 from werkzeug
. exceptions
import NotFound
380 class NoFallbackException ( NotFound
): pass
381 def fallback_route (* args
, ** kwargs
): # TODO: worthy as a flask-extension?
383 finds the next route that matches the current url rule, and executes it.
384 args, kwargs: pass all arguments of the current route
386 from flask
import current_app
, request
, g
388 # build a list of endpoints that match the current request's url rule:
391 for rule
in current_app
. url_map
. iter_rules ()
392 if rule
. rule
== request
. url_rule
. rule
394 current
= matching
. index ( request
. endpoint
)
396 # since we can't change request.endpoint, we always get the original
397 # endpoint back. so for repeated fall throughs, we use the g object to
398 # increment how often we want to fall through.
399 if not '_fallback_next' in g
:
401 g
._ fallback
_ next
+= 1
403 next_ep
= current
+ g
._ fallback
_ next
405 if next_ep
< len ( matching
):
406 return current_app
. view_functions
[ matching
[ next_ep
]](* args
, ** kwargs
)
408 raise NoFallbackException
410 def websub_url_hmac ( key
, feed_id
, timestamp
, nonce
):
411 """ generate sha1 hmac, as required by websub/pubsubhubbub """
412 sig_input
= f
" {feed_id} : {timestamp} : {nonce} " . encode ( 'ascii' )
413 return hmac
. new ( key
. encode ( 'ascii' ), sig_input
, hashlib
. sha1
). hexdigest ()
415 def websub_body_hmac ( key
, body
):
416 return hmac
. new ( key
. encode ( 'ascii' ), body
, hashlib
. sha1
). hexdigest ()
418 def flask_logger ( msg
, level
= "warning" ):
426 ). get ( level
. upper (), 0 )
428 from flask
import current_app
429 current_app
. logger
. log ( level
, msg
)
434 from pprint
import pprint
436 pprint ( args
, stream
= codecs
. getwriter ( "utf-8" )( sys
. stderr
. buffer ))