Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358use log::info;use redis::aio::ConnectionManager;use redis::AsyncCommands;use std::time::Duration;use std::{ env, sync::{ atomic::{AtomicBool, Ordering}, Arc, },};use tokio::time;use warp::{http::Response, hyper::StatusCode, reply, Filter};
mod count_image;use count_image::CountImage;
mod image_cache;use image_cache::ImageCache;
mod const_image;mod gallery_dl;mod season_images;
const IMAGE_SOURCES: [&str; 15] = [ "nekos.life", "nekos.best", "nekosapi.com", "nekosia.cat", "pic.re", "purrbot", "shibe.online", "catboys", "waifu.im", "waifu.pics", "dog_ceo", "the_cat_api", "twitter_search", "twitter_user_timeline", "testing",];
lazy_static::lazy_static! { // Cache of images static ref IMAGE_CACHE: ImageCache = ImageCache::new();}
pub async fn init(port: u16) { // Create Logger if env::var_os("RUST_LOG").is_none() { env::set_var("RUST_LOG", "neko_server=info"); } if env::var_os("RUST_LOG_STYLE").is_none() { env::set_var("RUST_LOG_STYLE", "never"); } env_logger::builder() .format_timestamp(None) .target(env_logger::Target::Stdout) .init();
// Database connection let redis_url: &str = &env::var("REDIS_URL").expect("REDIS_URL must be set"); let redis_client = redis::Client::open(redis_url).expect("Incorrect Redis URL"); let redis = ConnectionManager::new(redis_client) .await .unwrap_or_else(|_| panic!("Failed to connect to Redis at: {}", redis_url)); { let mut conn = redis.clone(); let check: Result<(), _> = conn.set("auth_test", "success").await; check.expect("Failed to execute redis commands"); }
// Update the image from the database let mut redis_clone = redis.clone(); let update_task = tokio::spawn(async move { let mut interval = time::interval(image_cache::UPDATE_INTERVAL); loop { interval.tick().await;
let mut pipe = redis::pipe(); pipe.atomic(); for source in IMAGE_SOURCES.iter() { pipe.get(*source); } let results = pipe.query_async::<Vec<Option<u64>>>(&mut redis_clone).await;
if results.is_err() { log::error!("Failed to get image count from Redis"); continue; } let sum: u64 = results.unwrap().into_iter().flatten().sum();
IMAGE_CACHE.update_total_image(sum as u128).await; } });
// Save historical data let mut redis_clone = redis.clone(); let history_task = tokio::spawn(async move { let mut interval = time::interval(Duration::from_secs(60 * 60)); // 1 hours loop { interval.tick().await;
// Get current sum let mut pipe = redis::pipe(); pipe.atomic(); for source in IMAGE_SOURCES.iter() { pipe.get(*source); } let results = pipe.query_async::<Vec<Option<u64>>>(&mut redis_clone).await;
if results.is_err() { log::error!(target: "history", "Failed to get image count from Redis"); continue; } let sum: u64 = results.unwrap().into_iter().flatten().sum();
// Get Date and Key name let date = chrono::Utc::now().format("%Y%m%d").to_string(); let key_name = format!("history:{}", date);
// Save to Redis let result: Result<(), redis::RedisError> = redis_clone.set(key_name, sum).await; if result.is_err() { log::error!(target: "history", "Failed to save history to Redis"); continue; }
log::info!(target: "history", "Saved history of {} downloads on {} to Redis", sum, date); } });
// Print current season info!("Current Season: {}", season_images::seasonal_name());
// Create a filter for each Imagesource let add_routes = IMAGE_SOURCES .iter() .map(|name| { info!("Adding route for {}", name); // Add the path /add/<name_snake>/:count warp::path("add") .and(warp::path(name)) .and(warp::post()) .and(warp::path::param()) .and(warp::header::optional::<String>("User-Agent")) .and(with_redis(redis.clone())) .and_then(move |count, agent, redis| add(name, count, agent, redis)) .or(warp::path("add") .and(warp::path(name)) .and(warp::post()) .and_then(|| async { Ok::<_, warp::Rejection>( Response::builder() .status(StatusCode::NOT_ACCEPTABLE) .body("Number to large".to_string()) .unwrap(), ) })) .boxed() }) .reduce(|acc, item| acc.or(item).unify().boxed()) .expect("No routes were created");
// Add error message let add_routes = add_routes.or(warp::path("add").map(|| { Response::builder() .status(StatusCode::NOT_ACCEPTABLE) .body("Unknown Source".to_string()) .unwrap() }));
// Create a filter to get the total count image let get_image = warp::path("count_total") .and(warp::get()) .and_then(get_total_image);
// Create a filter to get the image for a specific count let get_count = warp::path("count") .and(warp::get()) .and(warp::path::param()) .and_then(get_count_image);
// Create a filter for the favicon let favicon = warp::path("favicon.ico") .and(warp::get()) .and_then(get_favicon);
// Create a guarded gallery-dl JSON query endpoint let gallery_query = warp::path("gallery") .and(warp::path("query")) .and(warp::post()) .and(warp::body::content_length_limit(16 * 1024)) .and(warp::body::json()) .and(with_redis(redis.clone())) .and_then(gallery_dl::query);
// Add a default route to display server verison let index = warp::path::end().map(|| { reply::html(format!( r#"<!DOCTYPE html><html> <head> <title>Neko Server</title> </head> <body style="font-family: helvetica;"> <img src="favicon.ico" style=" position: absolute;top: 50%;transform: translate(0, -50%);margin: 0;width: 20vw;"> <div style="position: absolute;transform: translate(20vw,-50%);top: 50%;width: 78vw;"> <h1 style="text-align: center;font-size:12vw;margin: 0;">Neko Server</h1> <p style="text-align: center;font-size:3vw;margin: 0;">version: {}</p> </div> </body></html>"#, env!("CARGO_PKG_VERSION") )) });
// Combine all Filters let routes = get_image .or(add_routes) .or(get_count) .or(gallery_query) .or(index) .or(favicon);
// Add logger let routes = routes.with(warp::log::custom(|info| { // Look for the `x-forwarded-for` header, and if it's not present, fall back to x-real-ip, and if that's not present, fall back to the remote addr. let ip: String = info .request_headers() .get("x-forwarded-for") .or_else(|| info.request_headers().get("x-real-ip")) .map(|ip| ip.to_str().unwrap_or("Invalid Header")) .unwrap_or_else(|| "Unknown") .to_owned();
log::info!( "{} {} - Status: {} - IP: {} - Agent: {} - Time: {:?}", info.method(), info.path(), info.status(), ip, info.user_agent().unwrap_or("no agent"), info.elapsed() ); }));
// Default route let error_log = warp::log::custom(|info| { // Header to list let mut headers = String::new(); for (key, value) in info.request_headers().iter() { headers.push_str(&format!( "{}: {}\n", key, value.to_str().unwrap_or("[empty]") )); } log::info!( "SUS REQUEST: {} {} - Status: {} - Agent: {} - Time: {:?} - Headers: \n{}", info.method(), info.path(), info.status(), info.user_agent().unwrap_or("no agent"), info.elapsed(), headers.trim_end() ); }); let routes = routes.or(warp::any() .map(|| { Response::builder() .status(StatusCode::NOT_FOUND) .body("Not Found. This incident will be reported.".to_string()) .unwrap() }) .with(error_log));
// Run the server info!( "Starting nekoserver version {} on port {}", env!("CARGO_PKG_VERSION"), port ); let server = tokio::spawn(warp::serve(routes).run(([0, 0, 0, 0], port)));
// Wait for termination signal let term = Arc::new(AtomicBool::new(false)); for sig in signal_hook::consts::TERM_SIGNALS { signal_hook::flag::register(*sig, Arc::clone(&term)) .expect("Failed to register signal handler"); } while !term.load(Ordering::Relaxed) { time::sleep(Duration::from_secs(1)).await; }
// Shutdown the server info!("Shutting down");
// Cleanup update_task.abort(); history_task.abort(); server.abort();}
async fn add( name: &str, count: u8, agent: Option<String>, mut redis: ConnectionManager,) -> Result<impl warp::Reply, warp::Rejection> { // Check for correct header match agent { Some(agent) if agent.contains("NekoFans") => (), _ => { return Ok(reply::with_status( "Valid request, but unauthorized", StatusCode::UNAUTHORIZED, )); } }
// Increment the count let r: Result<(), redis::RedisError> = redis.incr(name, count.to_string()).await;
match r { Ok(_) => Ok(reply::with_status("OK", StatusCode::OK)), Err(_) => Ok(reply::with_status("", StatusCode::NOT_MODIFIED)), }}
async fn get_total_image() -> Result<impl warp::Reply, warp::Rejection> { Ok(Response::builder() .header("Content-Type", "image/png") .header("Cache-Control", "no-cache") .body(IMAGE_CACHE.get_total().await.get_image()))}
async fn get_favicon() -> Result<impl warp::Reply, warp::Rejection> { Ok(Response::builder() .header("Content-Type", "image/png") .body(unsafe { // SAFETY: We dont care that this is not a valid utf8 string, its binary data String::from_utf8_unchecked(include_bytes!("../assets/favicon.png").to_vec()) }))}
async fn get_count_image(count: u128) -> Result<impl warp::Reply, warp::Rejection> { Ok(Response::builder() .header("Content-Type", "image/png") .body(IMAGE_CACHE.get_count(count).await.get_image()))}
fn with_redis( connection: ConnectionManager,) -> impl Filter<Extract = (ConnectionManager,), Error = std::convert::Infallible> + Clone { warp::any().map(move || connection.clone())}