my_public_ip_server/
api.rs1use actix_web::{error::BlockingError, get, put, web, HttpRequest, HttpResponse};
2
3use my_public_ip_lib::{Reader, Writer};
4
5use crate::{ConfigKeys, Error, Result, Store};
6
7#[derive(Clone)]
8pub struct ApiState {
9 config: ConfigKeys,
10 store: Store,
11}
12
13impl ApiState {
14 pub fn new(config: ConfigKeys, store: Store) -> ApiState {
15 ApiState { config, store }
16 }
17}
18
19#[get("/")]
20pub async fn list_ips(api_state: web::Data<ApiState>, req: HttpRequest) -> Result<HttpResponse> {
21 let (api_key, ip) = get_api_key_and_ip(&req)?;
22
23 let api_state = api_state.into_inner();
24 let reader = Reader {
25 ip,
26 updated_at: time::OffsetDateTime::now_utc().unix_timestamp(),
27 };
28
29 wrap_block_res(
30 web::block(move || crate::list_ips(&api_state.config, &api_state.store, &api_key, &reader))
31 .await,
32 )
33}
34
35#[put("/")]
36pub async fn update_ip(api_state: web::Data<ApiState>, req: HttpRequest) -> Result<HttpResponse> {
37 let (api_key, ip) = get_api_key_and_ip(&req)?;
38
39 let api_state = api_state.into_inner();
40 let writer = Writer {
41 ip,
42 updated_at: time::OffsetDateTime::now_utc().unix_timestamp(),
43 };
44
45 wrap_block_res(
46 web::block(move || {
47 crate::update_ip(&api_state.config, &api_state.store, &api_key, &writer)
48 })
49 .await,
50 )
51}
52
53fn wrap_block_res<T: serde::Serialize>(
54 res: std::result::Result<T, BlockingError<Error>>,
55) -> Result<HttpResponse> {
56 res.map(|res| HttpResponse::Ok().json(res))
57 .map_err(Into::into)
58}
59
60fn get_api_key_and_ip(req: &HttpRequest) -> Result<(String, String)> {
61 let api_key = req
62 .headers()
63 .get("APIKEY")
64 .ok_or(Error::InvalidReaderKey)?
65 .to_str()?
66 .to_string();
67
68 let ip = req
69 .peer_addr()
70 .ok_or(Error::ReadIpAddrError)?
71 .ip()
72 .to_string();
73
74 Ok((api_key, ip))
75}