summaryrefslogtreecommitdiff
path: root/src/repository/models.rs
blob: 5b7b445c618b145434fee8c50ef31529017b103d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
use crate::commit::models::Commit;
use crate::db::get_client;
use crate::email::models::{Email, EmailData};
use crate::errors::{AppError, AppErrorType};
use crate::git;
use crate::helpers::name_of_git_repository;

use chrono::NaiveDateTime;
use deadpool_postgres::{Client, Pool};
use serde::{Deserialize, Serialize};
use tokio_pg_mapper::FromTokioPostgresRow;
use tokio_pg_mapper_derive::PostgresMapper;
use uuid::Uuid;

use std::collections::HashSet;
use std::net::SocketAddr;

#[derive(Serialize, Deserialize, PostgresMapper)]
#[pg_mapper(table = "repository")]
/// Repository model
pub struct Repository {
    pub id: Uuid,
    pub url: String,
    pub created_at: NaiveDateTime,
    pub updated_at: NaiveDateTime,
    pub uploader_ip: String,
}

/// Struct used to create a new repository
#[derive(Serialize, Deserialize)]
pub struct RepositoryData {
    pub url: String,
}

impl Repository {
    /// Find all repositories inside the database.
    /// Make a select query and order the repositories by descrescent updated
    /// datetime
    pub async fn find_all(pool: Pool) -> Result<Vec<Repository>, AppError> {
        let client = get_client(pool.clone()).await.unwrap();
        let statement = client
            .prepare("SELECT * FROM repository ORDER BY updated_at DESC")
            .await?;

        let repos = client
            .query(&statement, &[])
            .await?
            .iter()
            .map(|row| Repository::from_row_ref(row).unwrap())
            .collect::<Vec<Repository>>();

        Ok(repos)
    }

    /// Find a repository with an `id` equals to an Uuid element
    pub async fn find(pool: Pool, id: &Uuid) -> Result<Repository, AppError> {
        let client = get_client(pool.clone()).await.unwrap();
        let statement = client
            .prepare("SELECT * FROM repository WHERE id = $1")
            .await?;

        let repo = client
            .query_opt(&statement, &[&id])
            .await?
            .map(|row| Repository::from_row_ref(&row).unwrap());

        match repo {
            Some(repo) => Ok(repo),
            None => Err(AppError {
                error_type: AppErrorType::NotFoundError,
                cause: None,
                message: Some("Repository not found".to_string()),
            }),
        }
    }

    /// Find a repository and delete it, but before check if "Authorization"
    /// matches with SECRET_KEY
    pub async fn delete(
        pool: Pool,
        id: &Uuid,
    ) -> Result<Repository, AppError> {
        let client = get_client(pool.clone()).await.unwrap();
        let statement = client
            .prepare(
                "
                DELETE FROM repository
                WHERE id=$1
                RETURNING *
                ",
            )
            .await?;

        let repo = client
            .query_opt(&statement, &[&id])
            .await?
            .map(|row| Repository::from_row_ref(&row).unwrap());

        match repo {
            Some(repo) => Ok(repo),
            None => Err(AppError {
                error_type: AppErrorType::NotFoundError,
                cause: None,
                message: Some("Repository not found".to_string()),
            }),
        }
    }

    /// Search a repository by its url
    async fn search(
        client: &Client,
        url: String,
    ) -> Result<Repository, AppError> {
        let statement = client
            .prepare("SELECT * FROM repository WHERE url=$1")
            .await?;

        let repo = client
            .query_opt(&statement, &[&url])
            .await?
            .map(|row| Repository::from_row_ref(&row).unwrap());

        match repo {
            Some(repo) => Ok(repo),
            None => Err(AppError {
                error_type: AppErrorType::NotFoundError,
                cause: None,
                message: Some("Repository not found".to_string()),
            }),
        }
    }

    /// Create a new repository. It uses RepositoryData as support struct
    pub async fn create(
        pool: Pool,
        data: &RepositoryData,
        uploader_ip: Option<SocketAddr>,
    ) -> Result<Repository, AppError> {
        let client = get_client(pool.clone()).await.unwrap();

        let repo_name: String = match name_of_git_repository(&data.url) {
            Some(path) => path,
            None => {
                return Err(AppError {
                    message: Some("Repository not found".to_string()),
                    cause: Some("".to_string()),
                    error_type: AppErrorType::NotFoundError,
                });
            }
        };

        // Search a repository that matches with that url, because if it's
        // exists, the server do not create a clone
        let repo_search = Repository::search(&client, repo_name.clone()).await;
        match repo_search {
            Ok(_) => {
                return Err(AppError {
                    message: Some("Repository already exists".to_string()),
                    cause: Some("".to_string()),
                    error_type: AppErrorType::AuthorizationError,
                });
            }
            Err(_) => {}
        };

        let statement = client
            .prepare("
                INSERT INTO repository(id, url, uploader_ip) VALUES($1, $2, $3) RETURNING *
            ").await?;

        // Create a new UUID v4
        let uuid = Uuid::new_v4();

        // Match the uploader ip
        let user_ip = match uploader_ip {
            Some(ip) => ip.to_string(),
            None => {
                return Err(AppError {
                    message: Some("Failed to fetch uploader ip".to_string()),
                    cause: Some("".to_string()),
                    error_type: AppErrorType::AuthorizationError,
                })
            }
        };

        let repo = client
            .query_opt(&statement, &[&uuid, &repo_name, &user_ip])
            .await?
            .map(|row| Repository::from_row_ref(&row).unwrap());

        match repo {
            Some(repo) => {
                let commits = match git::repo_commits(&repo_name) {
                    Ok(c) => c,
                    Err(e) => {
                        return Err(AppError {
                            message: Some(
                                format!(
                                    "Repository couldn't be created now: {:?}",
                                    e
                                )
                                .to_string(),
                            ),
                            cause: Some("Repository clone".to_string()),
                            error_type: AppErrorType::GitError,
                        })
                    }
                };

                let mut emails: HashSet<String> = HashSet::new();
                for commit in &commits {
                    emails.insert(commit.author_email.clone());
                    emails.insert(commit.committer_email.clone());
                }
                for email in emails {
                    if let Err(e) =
                        Email::create(pool.clone(), &EmailData { email }).await
                    {
                        if e.error_type == AppErrorType::DbError {
                            return Err(e);
                        }
                    }
                }

                let commits_result =
                    Commit::create(pool.clone(), commits).await;
                if let Err(e) = commits_result {
                    panic!("{}", e);
                }

                Ok(repo)
            }
            None => Err(AppError {
                message: Some("Error creating a new repository".to_string()),
                cause: Some("Unknown error".to_string()),
                error_type: AppErrorType::DbError,
            }),
        }
    }
}