Debian Codegraph @

resources/scripts/scrapers/youtube-limit-length.py

raw symbols SCIP
1 # Use this as RSS Guard post-processing script.
2 #
3 # Example command line usage:
4 # curl 'PATH_TO_SOME_YOUTUBE_CHANNEL_RSS_FEED' | python 'youtube-limit-length.py'
5
6 import sys
7 import xml.etree.ElementTree as ET
8 import requests
9 import json
10 import isodate
11
12 sys.stdin.reconfigure(encoding="utf-8")
13 input_data = sys.stdin.read()
14
15 api_key = "YOUR_API_KEY_HERE"
16 min_required_length = 90 # In seconds.
17
18 youtube_query = (
19 "https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=VIDEO-ID&key="
20 + api_key
21 )
22 ns = {
23 "atom": "http://www.w3.org/2005/Atom",
24 "yt": "http://www.youtube.com/xml/schemas/2015",
25 }
26
27 tree = ET.fromstring(input_data)
28 entries = tree.findall("atom:entry", ns)
29
30 for entry in entries:
31 video_id = entry.find("yt:videoId", ns).text
32 youtube_query_specific = youtube_query.replace("VIDEO-ID", video_id)
33 api_response = requests.get(youtube_query_specific).text
34 response_json = json.loads(api_response)
35
36 try:
37 length_encoded = str(response_json["items"][0]["contentDetails"]["duration"])
38 except:
39 continue
40
41 length = isodate.parse_duration(length_encoded)
42
43 if length.seconds < min_required_length:
44 tree.remove(entry)
45
46 sys.stdout.buffer.write(ET.tostring(tree, encoding='utf-8', method='xml'))