Skip to content

Commit

Permalink
refactor: rename and move gitlab webhook methods and gitlab bot
Browse files Browse the repository at this point in the history
  • Loading branch information
mhkafadar committed Jan 21, 2024
1 parent c60d5a8 commit c65699a
Show file tree
Hide file tree
Showing 11 changed files with 187 additions and 177 deletions.
16 changes: 9 additions & 7 deletions src/bots/gitlab_bot.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use notifine::{create_webhook, get_webhook_url_or_create};
use notifine::get_webhook_url_or_create;
use std::env;
use teloxide::dispatching::dialogue;
use teloxide::dispatching::dialogue::InMemStorage;
Expand All @@ -13,8 +13,7 @@ type MyDialogue = Dialogue<State, InMemStorage<State>>;
pub async fn run_gitlab_bot() {
log::info!("Starting bot...");

let bot =
Bot::new(env::var("GITLAB_TELOXIDE_TOKEN").expect("GITLAB_TELOXIDE_TOKEN must be set"));
let bot = create_new_bot();

let command_handler =
filter_command::<Command, _>().branch(case![Command::Start].endpoint(handle_start_command));
Expand Down Expand Up @@ -126,10 +125,9 @@ async fn handle_my_chat_member_update(bot: Bot, update: ChatMemberUpdated) -> Re
Ok(())
}

pub async fn send_message(chat_id: i64, message: String) -> ResponseResult<()> {
pub async fn send_message_gitlab(chat_id: i64, message: String) -> ResponseResult<()> {
log::info!("Sending message to {}: {}", chat_id, message);
let bot =
Bot::new(env::var("GITLAB_TELOXIDE_TOKEN").expect("GITLAB_TELOXIDE_TOKEN must be set"));
let bot = create_new_bot();

let chat_id = ChatId(chat_id);

Expand Down Expand Up @@ -162,7 +160,11 @@ async fn handle_new_chat_and_start_command(telegram_chat_id: i64) -> ResponseRes
)
};

send_message(telegram_chat_id, message).await?;
send_message_gitlab(telegram_chat_id, message).await?;

Ok(())
}

fn create_new_bot() -> Bot {
Bot::new(env::var("GITLAB_TELOXIDE_TOKEN").expect("GITLAB_TELOXIDE_TOKEN must be set"))
}
163 changes: 4 additions & 159 deletions src/http_server.rs
Original file line number Diff line number Diff line change
@@ -1,101 +1,14 @@
use crate::webhook_handlers::issue::handle_issue_event;
use crate::webhook_handlers::note::handle_note_event;
use crate::webhook_handlers::push::handle_push_event;
use crate::webhook_handlers::tag_push::handle_tag_push_event;
use crate::webhook_handlers::unknown_event::handle_unknown_event;
use actix_web::{
get, middleware, post, web, App, HttpRequest, HttpResponse, HttpServer, Responder,
};
use notifine::{find_chat_by_id, find_webhook_by_webhook_url};
use serde::Deserialize;

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

#[derive(Debug, Deserialize)]
pub struct User {
pub name: String,
pub username: String,
pub email: String,
pub avatar_url: String,
}

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

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

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

#[derive(Debug, Deserialize)]
pub struct ObjectAttributes {
pub id: u32,
pub title: Option<String>,
pub action: Option<String>,
pub url: String,
}

#[derive(Debug, Deserialize)]
pub struct Author {
pub name: String,
pub email: String,
}
use crate::webhooks::gitlab::http_server::handle_gitlab_webhook;
use crate::webhooks::trello::http_server::handle_trello_callback;
use actix_web::{get, middleware, App, HttpResponse, HttpServer, Responder};

pub async fn run_http_server() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.wrap(middleware::Logger::default())
.service(health)
.service(handle_gitlab_webhook)
.service(handle_trello_callback)
})
.bind(("0.0.0.0", 8080))?
.run()
Expand All @@ -107,71 +20,3 @@ async fn health() -> impl Responder {
log::info!("Health check");
"I'm ok"
}

#[derive(Deserialize)]
struct GitlabWebhook {
webhook_url: String,
}

#[post("/gitlab/{webhook_url}")]
async fn handle_gitlab_webhook(
gitlab_webhook: web::Path<GitlabWebhook>,
gitlab_event: web::Json<GitlabEvent>,
) -> impl Responder {
log::info!("Event details: {:?}", &gitlab_event);
let event_name = &gitlab_event.object_kind;

// handle push, tag_push, issue, merge_request, note, pipeline, wiki_page, build
let message = match event_name.as_str() {
"push" => handle_push_event(&gitlab_event),
"tag_push" => handle_tag_push_event(&gitlab_event),
"issue" => handle_issue_event(&gitlab_event),
// "merge_request" => handle_merge_request_event(), // TODO implement
"note" => handle_note_event(&gitlab_event), // TODO implement
// "pipeline" => handle_pipeline_event(), // TODO implement
// "wiki_page" => handle_wiki_page_event(), // TODO implement
// "build" => handle_build_event(), // TODO implement
// TODO implement work_item (issue task list)
_ => handle_unknown_event(&gitlab_event),
};

// if message is empty, then we don't need to send it to telegram
if message.is_empty() {
return HttpResponse::Ok();
}

let webhook_url = &gitlab_webhook.webhook_url;
log::info!("webhook_url: {}", webhook_url);
let webhook = find_webhook_by_webhook_url(webhook_url);

if webhook.is_none() {
log::error!("Webhook not found");
return HttpResponse::NotFound();
}
let webhook = webhook.unwrap();

// log chat_id
log::info!("Webhook: {}", webhook.webhook_url);
let chat_id = webhook.chat_id.expect("Chat id must be set");
log::info!("Chat id: {}", chat_id);

let chat = find_chat_by_id(webhook.chat_id.expect("Chat id must be set"));

if chat.is_none() {
log::error!("Chat not found");
return HttpResponse::NotFound();
}
let chat = chat.unwrap();

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

log::info!("bot sent message");
HttpResponse::Ok() //
}
12 changes: 7 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
use crate::bots::gitlab_bot::run_gitlab_bot;
use crate::bots::trello_bot::run_trello_bot;
use crate::http_server::run_http_server;
use dotenv::dotenv;
use tokio::task;

pub mod bots;
pub mod http_server;
pub mod telegram_bot;
pub mod webhook_handlers;

use crate::{http_server::run_http_server, telegram_bot::run_telegram_bot};
pub mod webhooks;

#[tokio::main]
async fn main() {
dotenv().ok();
pretty_env_logger::init();

task::spawn(run_telegram_bot());
task::spawn(run_gitlab_bot());
task::spawn(run_trello_bot());
run_http_server().await.expect("Http server error");

log::info!("Main 2");
Expand Down
Loading

0 comments on commit c65699a

Please sign in to comment.