Skip to content

Commit

Permalink
fix router
Browse files Browse the repository at this point in the history
  • Loading branch information
lazhenyi committed Dec 17, 2024
1 parent a22fbad commit a785008
Show file tree
Hide file tree
Showing 17 changed files with 233 additions and 15 deletions.
12 changes: 11 additions & 1 deletion src/api/app_docs.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
use crate::api::handler::repos::info::__path_api_repo_info_get;
use crate::api::handler::users::starred::__path_api_users_starred;
use crate::api::handler::users::search::__path_api_users_search;
use crate::api::handler::repos::search::__path_api_repo_search;
use crate::api::handler::users::repos::__path_api_users_repos;
use crate::api::handler::users::follower::__path_api_users_following;
use crate::api::handler::users::follower::__path_api_users_followed;
Expand Down Expand Up @@ -63,6 +67,9 @@ use utoipa::OpenApi;
api_users_following,
api_users_followed,
api_users_repos,
api_users_search,
api_users_starred,
api_user_avatar,
api_user_avatar_upload,
Expand Down Expand Up @@ -104,7 +111,10 @@ use utoipa::OpenApi;
api_groups_labels,
api_groups_labels_create,
api_groups_labels_delete,
api_groups_labels_update
api_groups_labels_update,
api_repo_search,
api_repo_info_get,
),
)]
pub struct ApiDoc;
13 changes: 8 additions & 5 deletions src/api/app_routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ use crate::api::handler::groups::labels::{api_groups_labels, api_groups_labels_c
use crate::api::handler::groups::members::{api_groups_member_add, api_groups_member_remove, api_groups_members, api_user_groups};
use crate::api::handler::groups::repos::{api_groups_repo, api_groups_repo_create};
use crate::api::handler::groups::search::api_groups_search;
use crate::api::handler::repos::info::api_repo_info_get;
use crate::api::handler::repos::search::api_repo_search;
use crate::api::handler::user::avatar::{api_user_avatar, api_user_avatar_delete, api_user_avatar_upload};
use crate::api::handler::user::emails::{api_user_email, api_user_email_bind, api_user_email_unbind};
use crate::api::handler::user::follower::{api_user_follow, api_user_followed, api_user_follower, api_user_unfollow};
Expand All @@ -24,6 +26,8 @@ use crate::api::handler::users::login::{api_users_login_email, api_users_login_n
use crate::api::handler::users::logout::api_users_logout;
use crate::api::handler::users::repos::api_users_repos;
use crate::api::handler::users::reset::{api_user_reset_passwd_forget, api_user_reset_passwd_profile};
use crate::api::handler::users::search::api_users_search;
use crate::api::handler::users::starred::api_users_starred;

pub fn routes(cfg: &mut web::ServiceConfig){
cfg
Expand Down Expand Up @@ -88,14 +92,14 @@ pub fn routes(cfg: &mut web::ServiceConfig){
.route("/profile", web::post().to(api_user_reset_passwd_profile))
)
.route("/apply", web::post().to(api_users_apply))
.route("/search", web::get().to(||async { "TODO" }))
.route("/search", web::get().to(api_users_search))
.service(
web::scope("/once/{username}")
.route("/", web::get().to(api_users_info))
.route("/followers", web::get().to(api_users_followed))
.route("/following", web::get().to(api_users_following))
.route("/repos", web::get().to(api_users_repos))
.route("/starred", web::get().to(||async { "TODO" }))
.route("/starred", web::get().to(api_users_starred))
.route("/subscriptions", web::get().to(||async { "TODO" }))
.route("/groups", web::get().to(||async { "TODO" }))
.route("/groups/{group_name}/permissions", web::get().to(||async { "TODO" }))
Expand Down Expand Up @@ -134,13 +138,12 @@ pub fn routes(cfg: &mut web::ServiceConfig){
)
.service(
web::scope("/repos")
.route("/search", web::get().to(||async { "TODO" }))
.route("/search", web::get().to(api_repo_search))
.service(
web::scope("/{owner}/{repo}")
.route("/", web::get().to(||async { "TODO" }))
.route("/", web::get().to(api_repo_info_get))
.route("/", web::post().to(||async { "TODO" }))
.route("/", web::delete().to(||async { "TODO" }))
.route("/", web::patch().to(||async { "TODO" }))
.service(
web::scope("/avatar")
.route("/", web::get().to(||async { "TODO" }))
Expand Down
11 changes: 11 additions & 0 deletions src/api/dto/repo_dto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,17 @@ pub struct RepoCreate{
pub default_branch: String,
}

#[derive(Deserialize,Serialize,ToSchema)]
pub struct RepoSearch{
pub keywords: String,
pub page: u64,
pub size: u64,
}
#[derive(Deserialize,Serialize,ToSchema)]
pub struct RepoInfo{
pub owner: Uuid,
}

#[derive(Deserialize,Serialize, ToSchema)]
pub struct RepoBranchNew{
pub from: String,
Expand Down
1 change: 1 addition & 0 deletions src/api/handler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub mod health;
pub mod user;
pub mod users;
pub mod groups;
pub mod repos;

pub async fn check_session(session: Session) -> anyhow::Result<SessionModel>{
match session.get::<SessionModel>(SessionModelKey){
Expand Down
41 changes: 41 additions & 0 deletions src/api/handler/repos/info.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use crate::api::dto::repo_dto::RepoInfo;
use crate::metadata::service::MetaService;
use actix_web::{web, Responder};
use crate::api::app_write::AppWrite;


#[utoipa::path(
get,
tag = "repo",
path = "/api/v1/repo/info",
params(
("uid" = String, Query, description = "Repo Uid"),
),
responses(
(status = 200, description = "Success"),
(status = 400, description = "Bad Request")
)
)]
pub async fn api_repo_info_get(
service: web::Data<MetaService>,
path: web::Path<(String,String)>
) -> impl Responder
{
let (owner, repo) = path.into_inner();
let repo_id = match service.repo_service().owner_name_by_uid(owner,repo).await{
Ok(data) => {
data
}
Err(e) => {
return AppWrite::error(e.to_string())
}
};
match service.repo_service().info(repo_id).await{
Ok(data) => {
AppWrite::ok(data)
}
Err(e) => {
AppWrite::error(e.to_string())
}
}
}
2 changes: 2 additions & 0 deletions src/api/handler/repos/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod search;
pub mod info;
35 changes: 35 additions & 0 deletions src/api/handler/repos/search.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use crate::api::dto::repo_dto::RepoSearch;
use crate::metadata::service::MetaService;
use actix_web::{web, Responder};
use crate::api::app_write::AppWrite;

#[utoipa::path(
get,
tag = "search",
path = "/api/v1/search",
params(
("keywords" = String, Query, description = "Search Keywords"),
("page" = u64, Query, description = "Page"),
("size" = u64, Query, description = "Size"),
),
responses(
(status = 200, description = "Success"),
(status = 400, description = "Bad Request")
)
)]
pub async fn api_repo_search(
service: web::Data<MetaService>,
query: web::Query<RepoSearch>
)
-> impl Responder
{
let (keywords, page, size) = (query.keywords.clone(), query.page, query.size);
match service.repo_service().search(keywords,page,size).await{
Ok(data) => {
AppWrite::ok(data)
}
Err(e) => {
AppWrite::error(e.to_string())
}
}
}
3 changes: 2 additions & 1 deletion src/api/handler/users/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ pub mod login;
pub mod apply;
pub mod reset;
pub mod logout;
pub mod info;
pub mod info;
pub mod starred;
36 changes: 36 additions & 0 deletions src/api/handler/users/search.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use actix_web::{web, Responder};
use crate::api::app_write::AppWrite;
use crate::api::dto::repo_dto::RepoSearch;
use crate::api::dto::user_dto::UserOv;
use crate::metadata::service::MetaService;

#[utoipa::path(
get,
tag = "users",
path = "/api/v1/users/search",
params(
("keywords" = String, Query, description = "Search Keywords"),
("page" = u64, Query, description = "Page"),
("size" = u64, Query, description = "Size"),
),
responses(
(status = 200, description = "Success"),
(status = 400, description = "Bad Request")
)
)]
pub async fn api_users_search(
service: web::Data<MetaService>,
query: web::Query<RepoSearch>
)
-> impl Responder
{
let (keywords, page, size) = (query.keywords.clone(), query.page, query.size);
match service.user_service().search(keywords,page,size).await{
Ok(data) => {
AppWrite::<Vec<UserOv>>::ok(data)
}
Err(e) => {
AppWrite::error(e.to_string())
}
}
}
33 changes: 33 additions & 0 deletions src/api/handler/users/starred.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use actix_web::{web, Responder};
use crate::api::app_write::AppWrite;
use crate::metadata::service::MetaService;

#[utoipa::path(
get,
tag = "users",
path = "/api/v1/users/{username}/starred",
responses(
( status = 200, description = "Success" ),
( status = 400, description = "Bad Request" )
)
)]
pub async fn api_users_starred(
service: web::Data<MetaService>,
path: web::Path<String>
)
-> impl Responder
{
let username = path.into_inner();
let uid = match service.user_service().username_to_uid(username).await{
Ok(uid) => uid,
Err(e) => return AppWrite::error(e.to_string())
};
match service.user_service().star(uid).await{
Ok(data) => {
AppWrite::ok(data)
}
Err(e) => {
AppWrite::error(e.to_string())
}
}
}
2 changes: 2 additions & 0 deletions src/api/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use actix_web::{web, App, HttpServer};
use actix_web::web::scope;
use tracing::info;
use crate::api::app_error::Error;
use crate::api::app_routes;
use crate::api::handler::version::api_version;
use crate::api::middleware::service::ActixServer;
use crate::config::{init_config, CFG};
Expand All @@ -26,6 +27,7 @@ pub async fn init_api() -> Result<(), Error>{
.service(
scope("/api")
.route("/version", web::get().to(api_version))
.configure(app_routes::routes)
)
})
.bind(cfg.http.starter())?
Expand Down
1 change: 0 additions & 1 deletion src/http/config.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use actix_web::{HttpRequest, HttpResponse, Responder};
use tracing::info;
use crate::ROOT_PATH;

Expand Down
1 change: 1 addition & 0 deletions src/http/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,7 @@ pub async fn objects_pack(http_request: HttpRequest, path: web::Path<(String, St
map.insert("Date".to_string(), time.format(&format_description::parse("%a, %d %b %Y %H:%M:%S GMT").unwrap()).unwrap());
map.insert("Expires".to_string(), expires.format(&format_description::parse("%a, %d %b %Y %H:%M:%S GMT").unwrap()).unwrap());
map.insert("Cache-Control".to_string(), "public, max-age=86400".to_string());
#[allow(unused_assignments)]
let mut xtype = "application/x-git-loose-object".to_string();
if url.ends_with(".pack") {
xtype = "application/x-git-packed-objects".to_string();
Expand Down
21 changes: 21 additions & 0 deletions src/metadata/service/repos_service/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,25 @@ impl RepoService {
}
Ok(model.unwrap().uid)
}
pub async fn search(&self, keyword: String, page: u64, size: u64) -> anyhow::Result<Vec<repo::Model>>{
let models = repo::Entity::find()
.filter(repo::Column::Name.contains(keyword.clone()))
.filter(repo::Column::Description.contains(keyword.clone()))
.filter(repo::Column::Topic.contains(keyword))
.filter(repo::Column::Visible.eq(true))
.offset(page * size)
.limit(size)
.all(&self.db)
.await?;
Ok(models)
}
pub async fn info(&self, uid: Uuid) -> anyhow::Result<repo::Model>{
let model = repo::Entity::find_by_id(uid)
.one(&self.db)
.await?;
if model.is_none(){
return Err(anyhow::anyhow!("repo not found"))
}
Ok(model.unwrap())
}
}
1 change: 1 addition & 0 deletions src/metadata/service/users_service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub mod reset;
pub mod info;
pub mod check;
pub mod setting;
pub mod search;


#[derive(Clone)]
Expand Down
18 changes: 18 additions & 0 deletions src/metadata/service/users_service/search.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
use crate::api::dto::user_dto::UserOv;
use crate::metadata::model::users::users;
use crate::metadata::service::users_service::UserService;
use sea_orm::*;

impl UserService {
pub async fn search(&self, keywords: String, page: u64, size: u64) -> anyhow::Result<Vec<UserOv>>{
let models = users::Entity::find()
.filter(users::Column::Username.contains(keywords.clone()))
.filter(users::Column::Name.contains(keywords.clone()))
.filter(users::Column::Description.contains(keywords))
.offset(page * size)
.limit(size)
.all(&self.db)
.await?;
Ok(models.into_iter().map(|model| UserOv::from(model)).collect())
}
}
17 changes: 10 additions & 7 deletions src/ssh/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ impl SshHandler {
Ok(())
}

// Helper to validate and parse the repository path
fn parse_git_command(&self, git_shell_cmd: &str) -> Result<(GitService, String), anyhow::Error> {
async fn parse_git_command(&self, git_shell_cmd: &str) -> Result<(GitService, String), anyhow::Error> {
let (service, path) = if let Some(rec_pack_path) = git_shell_cmd.strip_prefix("git-receive-pack ") {
(GitService::ReceivePack, strip_apostrophes(rec_pack_path))
} else if let Some(upl_ref_path) = git_shell_cmd.strip_prefix("git-upload-pack ") {
Expand All @@ -69,14 +68,18 @@ impl SshHandler {
return Err(anyhow::anyhow!("Invalid repository path: {path}"));
}

let owner = path_segments[0];
let repo_name = path_segments[1].split('.').next().unwrap_or_default();
let owner = path_segments[0].to_string();
let repo_name = path_segments[1].split('.').next().unwrap_or_default().to_string();

if repo_name.is_empty() {
return Err(anyhow::anyhow!("Invalid repository name in path: {path}"));
}

Ok((service, format!("{}/{}", owner, repo_name)))
let repo = self.server.repo_service().owner_name_by_uid(owner.clone(), repo_name).await;
if repo.is_err() {
return Err(anyhow::anyhow!("Repository not found: {path}"));
}
let repo_path = repo?.to_string();
Ok((service, repo_path))
}
async fn forward<R, F, Fut>(
session_handle: Arc<Handle>,
Expand Down Expand Up @@ -148,7 +151,7 @@ impl Handler for SshHandler {
let git_shell_cmd = std::str::from_utf8(data).map_err(|_| anyhow::anyhow!("Invalid UTF-8 input"))?;
info!("Executing command: {git_shell_cmd}");

let (service, path) = self.parse_git_command(git_shell_cmd)?;
let (service, path) = self.parse_git_command(git_shell_cmd).await?;

let cmd = tokio::process::Command::new("git")
.arg(service.to_string())
Expand Down

0 comments on commit a785008

Please sign in to comment.