You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

78 lines
2.1 KiB

extern crate openssl_probe;
extern crate reqwest;
extern crate serde;
use std::collections::HashMap;
use std::ops::Add;
use std::thread;
use std::time::Duration;
use reqwest::{get, Response, Result};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct XKCDResponse {
month: String,
num: u16,
link: String,
year: String,
news: String,
safe_title: String,
transcript: String,
alt: String,
img: String,
title: String,
day: String,
}
fn get_latest_xkcd() -> Result<XKCDResponse> {
let response: XKCDResponse = get("https://xkcd.com/info.0.json")?.json()?;
Ok(response)
}
fn send_xkcd(url: &str, num: u16) -> Result<Response> {
let mut map = HashMap::new();
map.insert("content", format!("https://xkcd.com/{}", num));
let client = reqwest::Client::new();
let response = client.post(url).json(&map).send()?;
Ok(response)
}
fn backoff(backofftime: &Duration) {
println!("Something went wrong getting the latest xkcd backing off for: {} seconds", backofftime.as_secs());
thread::sleep(backofftime.add(Duration::from_secs(30)));
}
fn main() {
openssl_probe::init_ssl_cert_env_vars();
println!("Started");
let mut backofftime = Duration::from_secs(30);
if let Ok(api_url) = std::env::var("API_URL") {
if let Ok(mut latest) = get_latest_xkcd() {
latest.num = 1;
loop {
if let Ok(current) = get_latest_xkcd() {
if current.num != latest.num {
if send_xkcd(&api_url, current.num).is_err() {
backoff(&backofftime);
}
}
latest = current;
backofftime = Duration::from_secs(30);
thread::sleep(Duration::from_secs(60));
} else {
backoff(&backofftime);
}
}
} else {
panic!("First time getting XKCD Failed")
}
} else {
panic!("API_URL Environment variable is not defined")
}
}