Created
March 10, 2022 17:20
-
-
Save hikilaka/83e3d240b243a5956193b4f7f5a39c4b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use async_std::{fs, path::Path, prelude::*}; | |
use rand::{prelude::*, thread_rng}; | |
use std::io::{Error, ErrorKind}; | |
use wallpaper; | |
const WALLPAPER_DIR: &'static str = "/home/zack/Pictures/Wallpapers"; | |
const ACCEPTED_EXTENSIONS: [&str; 3] = ["jpeg", "jpg", "png"]; | |
async fn read_wallpapers() -> Result<Vec<String>, Error> { | |
let base_path = Path::new(WALLPAPER_DIR); | |
let mut files = Vec::new(); | |
let mut entries = fs::read_dir(WALLPAPER_DIR).await?; | |
while let Some(entry) = entries.next().await { | |
let entry = entry?; | |
let file_name = entry.file_name().to_string_lossy().into_owned(); | |
if let Some(file_extension) = entry.path().extension() { | |
for extension in ACCEPTED_EXTENSIONS { | |
if !file_extension.eq(extension) { | |
continue; | |
} | |
} | |
} | |
files.push(base_path.join(file_name).to_string_lossy().into_owned()); | |
} | |
Ok(files) | |
} | |
async fn get_random_wallpaper(wallpapers: &mut Vec<String>) -> Result<String, Error> { | |
wallpapers.shuffle(&mut thread_rng()); | |
if let Some(entry) = wallpapers.first() { | |
Ok(entry.clone()) | |
} else { | |
Err(ErrorKind::NotFound.into()) | |
} | |
} | |
#[async_std::main] | |
async fn main() -> Result<(), Error> { | |
let mut wallpapers = read_wallpapers().await?; | |
let random_wallpaper = get_random_wallpaper(&mut wallpapers).await?; | |
wallpaper::set_from_path(random_wallpaper.as_str()) | |
.map_err(|_| -> Error { ErrorKind::Other.into() })?; | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment