550b45808b27f0627ebf235d17978028e9986827
[litoprism.git] / src / main.rs
1 use std::io::Cursor;
2 use std::fmt::Display;
3 use std::fmt;
4 use std::borrow::BorrowMut;
5 use num_traits::Zero;
6 use num_traits::cast::AsPrimitive;
7 use percent_encoding::percent_decode_str;
8 use actix_web::{get, web, App, HttpServer, HttpRequest, HttpResponse, Responder, ResponseError, Result};
9 use actix_web::body::BoxBody;
10 use actix_web::http::StatusCode;
11 use image::{ImageBuffer, ColorType, Rgb, RgbImage, write_buffer_with_format};
12 use image::ImageOutputFormat::Png;
13 use image::imageops::{FilterType, resize};
14
15
16 #[derive(Debug)]
17 struct ImageError(image::ImageError);
18
19 impl Display for ImageError {
20 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21 write!(f, "{}", &self.0)
22 }
23 }
24
25 impl ResponseError for ImageError {
26 fn status_code(&self) -> StatusCode {
27 StatusCode::INTERNAL_SERVER_ERROR
28 }
29
30 fn error_response(&self) -> HttpResponse<BoxBody> {
31 HttpResponse::InternalServerError().finish()
32 }
33 }
34
35 struct ToRgbIter<'a, T> where T: AsPrimitive<u8> {
36 iter: Box<&'a mut dyn Iterator<Item = T>>
37 }
38
39 impl<'a, T: AsPrimitive<u8>> ToRgbIter<'a, T> {
40 fn new(data: &'a mut (dyn Iterator<Item = T>)) -> ToRgbIter<T> {
41 ToRgbIter { iter: Box::new(data) }
42 }
43 }
44
45 impl<T: AsPrimitive<u8> + Zero> Iterator for ToRgbIter<'_, T> {
46 type Item = Rgb<u8>;
47 fn next(&mut self) -> Option<Rgb<u8>> {
48 if let Some(r) = self.iter.next() {
49 let g = self.iter.next().unwrap_or(T::zero());
50 let b = self.iter.next().unwrap_or(T::zero());
51 println!("{} {} {}", r.as_(), g.as_(), b.as_());
52 //Some(Rgb([r.unwrap_or(0) as u8, g.unwrap_or(0) as u8, b.unwrap_or(0) as u8]))
53 Some(Rgb([r.as_(), g.as_(), b.as_()]))
54 }
55 else {
56 None
57 }
58 }
59 }
60
61 fn to_imageresult<T> (result: Result<T, image::ImageError>) -> Result<T, ImageError> {
62 match result {
63 Ok(v) => Ok(v),
64 Err(e) => Err(ImageError(e))
65 }
66 }
67
68 #[get("/hello/{name}")]
69 async fn greet(name: web::Path<String>, req: HttpRequest) -> impl Responder {
70 println!("{:?}", req);
71 format!("Hello {name}!")
72 }
73
74 #[get("/gen/{data}")]
75 async fn img_gen(req: HttpRequest) -> Result<impl Responder> {
76 let mut cursor = Cursor::new(Vec::new());
77 let mut img: RgbImage = ImageBuffer::new(32, 32);
78 let mut pixels = img.pixels_mut();
79 let data = req.uri().path().split("/").skip(2).next().unwrap();
80
81 //println!("{:#?}\n{:#?}", req.uri().path().split("/").skip(2).next(), req.match_info().get("data"));
82
83 println!("{:?}", data);
84 //for sp in ToRgbIter::new(percent_decode(&RawOsString::from_string(data.into_inner()).as_raw_bytes()).into_iter().borrow_mut()) {
85 for sp in ToRgbIter::new(percent_decode_str(&data).into_iter().borrow_mut()) {
86 let mut dp = pixels.next().unwrap();
87 println!("{:?}", sp);
88 dp.0 = sp.0;
89 }
90
91 let img = resize(&img, 512, 512, FilterType::Nearest);
92 println!("Here!");
93 to_imageresult(write_buffer_with_format(&mut cursor, &img, 512, 512, ColorType::Rgb8, Png))?;
94 Ok(HttpResponse::build(StatusCode::OK)
95 .content_type("image/png")
96 .body(cursor.into_inner()))
97 }
98
99 #[actix_web::main] // or #[tokio::main]
100 async fn main() -> std::io::Result<()> {
101 HttpServer::new(|| {
102 App::new().service(greet).service(img_gen)
103 })
104 .bind(("127.0.0.1", 8080))?
105 .run()
106 .await
107 }