Skip to content

Commit

Permalink
feat: add http_server module with actix
Browse files Browse the repository at this point in the history
  • Loading branch information
mhkafadar committed Jan 21, 2024
1 parent fc2a4f3 commit 598c542
Show file tree
Hide file tree
Showing 7 changed files with 156 additions and 30 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
CHAT_ID=
8 changes: 8 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@ log = "0.4"
pretty_env_logger = "0.4"
tokio = { version = "1.8", features = ["rt-multi-thread", "macros"] }
actix-web = "4"
serde = { version = "1.0", features = ["derive"] }
dotenv = "0.15.0"
11 changes: 0 additions & 11 deletions src/handler.rs

This file was deleted.

96 changes: 96 additions & 0 deletions src/http_server.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
use actix_web::{get, post, App, HttpResponse, HttpServer, middleware, Responder, web};
use serde::{Deserialize};

#[derive(Debug, Deserialize)]
struct GitlabEvent {
object_kind: String,
event_name: String,
before: String,
after: String,
r#ref: String,
checkout_sha: String,
message: Option<String>,
user_id: u32,
user_name: String,
user_username: String,
user_email: String,
user_avatar: String,
project_id: u32,
project: Project,
repository: Repository,
commits: Vec<Commit>,
total_commits_count: u32,
}

#[derive(Debug, Deserialize)]
struct Project {
id: u32,
name: String,
description: String,
web_url: String,
avatar_url: Option<String>,
git_ssh_url: String,
git_http_url: String,
namespace: String,
visibility_level: u32,
path_with_namespace: String,
default_branch: String,
ci_config_path: Option<String>,
homepage: String,
url: String,
ssh_url: String,
http_url: String,
}

#[derive(Debug, Deserialize)]
struct Repository {
name: String,
url: String,
description: String,
homepage: String,
}

#[derive(Debug, Deserialize)]
struct Commit {
id: String,
message: String,
timestamp: String,
url: String,
}

pub async fn run_http_server() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.wrap(middleware::Logger::default())
.service(health)
.service(handle_gitlab_webhook)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}

#[get("/health")]
async fn health() -> impl Responder {
log::info!("Health check");
"I'm ok"
}

#[post("/gitlab")]
async fn handle_gitlab_webhook(gitlab_event: web::Json<GitlabEvent>) -> impl Responder {
let branch_ref = &gitlab_event.r#ref;
let branch_name = branch_ref.split('/').last().unwrap();
let project_name = &gitlab_event.project.name;
let commit_message = &gitlab_event.commits[0].message;
let commit_url = &gitlab_event.commits[0].url;

let message = format!("{}: {} - {} - {}", project_name, branch_name, commit_message, commit_url);

// TODO: chat_id should be dynamic (after adding database)
let chat_id = std::env::var("CHAT_ID").expect("CHAT_ID must be set.");

crate::telegram_bot::send_message(chat_id.parse::<i64>().expect("CHAT_ID must be an integer"), message).await.unwrap();

log::info!("bot sent message");
HttpResponse::Ok() // <- send response
}
30 changes: 11 additions & 19 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,30 +1,22 @@
use teloxide::prelude::*;
use tokio::task;
use dotenv::dotenv;

pub mod handler;
pub mod telegram_bot;
pub mod http_server;

use crate::{
handler::handle,
telegram_bot::run_telegram_bot,
http_server::run_http_server,
};

#[tokio::main]
async fn main() {
pretty_env_logger::init();
run().await;
}

async fn run() {
log::info!("Starting bot...");
dotenv().ok();

let bot = Bot::from_env();

let handler = dptree::entry()
.branch(Update::filter_message().endpoint(handle));
pretty_env_logger::init();

Dispatcher::builder(bot, handler)
.enable_ctrlc_handler()
.build()
.dispatch()
.await;
task::spawn(run_telegram_bot());
run_http_server().await.expect("Http server error");

log::info!("Closing bot... Goodbye!");
log::info!("Main 2");
}
38 changes: 38 additions & 0 deletions src/telegram_bot.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use teloxide::prelude::*;

pub async fn run_telegram_bot() {
log::info!("Starting bot...");

let bot = Bot::from_env();

let handler = dptree::entry()
.branch(Update::filter_message().endpoint(handle));

Dispatcher::builder(bot, handler)
.enable_ctrlc_handler()
.build()
.dispatch()
.await;

log::info!("Closing bot... Goodbye!");
}


async fn handle(bot: Bot, message: Message) -> ResponseResult<()> {
let chat_id = message.chat.id.0;
log::info!("Received a message from {}: {}", chat_id, message.text().unwrap());
Ok(())
}

pub async fn send_message(chat_id: i64, message: String) -> ResponseResult<()> {
log::info!("Sending message to {}: {}", chat_id, message);
let bot = Bot::from_env();

let chat_id = ChatId(chat_id);

bot.send_message(chat_id, message)
.send()
.await?;
Ok(())
}

0 comments on commit 598c542

Please sign in to comment.