422
Ib
i3wm-background-desktop-script / files
i3wm-background-desktop-script / nasa_feed_parser.py
1.6 KB
1import errno 2import re 3import feedparser 4import os 5import random 6from urllib.request import urlretrieve, urlopen 7 8# @TODO(sean): Create a cache... 9 10IMAGES_LOCATION = os.path.expanduser("~") + "/.backgrounds/" 11 12 13def use_NASA_image_of_the_day(): 14 """Use the NASA image of the day feed to get a background""" 15 16 NASA_IMAGES_URL = "https://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss" 17 18 feed = feedparser.parse(NASA_IMAGES_URL) 19 random_entry = random.choice(feed["entries"]) 20 random_entry_img = None 21 for link in random_entry["links"]: 22 if link["rel"] == "enclosure": 23 random_entry_img = link["href"] 24 25 urlretrieve(random_entry_img, f"{IMAGES_LOCATION}background.jpeg") 26 27 28def use_earth_observatory_image_of_the_day(): 29 """Use the observatory's image of the day feed""" 30 31 OBSERVATORY_IMAGES_URL = ( 32 "https://earthobservatory.nasa.gov/feeds/image-of-the-day.rss" 33 ) 34 35 feed = feedparser.parse(OBSERVATORY_IMAGES_URL) 36 random_item = random.choice(feed["entries"]) 37 resp = urlopen(random_item["link"]) 38 content = resp.read().decode("utf8") 39 40 random_item_img = re.findall( 41 r"(?P<jpg>https?://[^\s]+lrg\.jpg)", content 42 ) # Assume the first link is the correct one... 43 44 urlretrieve(random_item_img[0], f"{IMAGES_LOCATION}background.jpeg") 45 46 47def main(): 48 """Get the latest image from NASA Images.""" 49 50 try: 51 os.makedirs(IMAGES_LOCATION) 52 except OSError as e: 53 if e.errno != errno.EEXIST: 54 raise 55 56 image = use_NASA_image_of_the_day() 57 # image = use_earth_observatory_image_of_the_day() 58 59 60if __name__ == "__main__": 61 main()