aboutsummaryrefslogtreecommitdiff
path: root/src/db/models/attachment.rs
blob: 58f893bce517b0d45dcdec7c4cfb6acb47182efd (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
use serde_json::Value;

use super::Cipher;
use crate::CONFIG;

#[derive(Debug, Identifiable, Queryable, Insertable, Associations, AsChangeset)]
#[table_name = "attachments"]
#[changeset_options(treat_none_as_null="true")]
#[belongs_to(Cipher, foreign_key = "cipher_uuid")]
#[primary_key(id)]
pub struct Attachment {
    pub id: String,
    pub cipher_uuid: String,
    pub file_name: String,
    pub file_size: i32,
    pub akey: Option<String>,
}

/// Local methods
impl Attachment {
    pub const fn new(id: String, cipher_uuid: String, file_name: String, file_size: i32) -> Self {
        Self {
            id,
            cipher_uuid,
            file_name,
            file_size,
            akey: None,
        }
    }

    pub fn get_file_path(&self) -> String {
        format!("{}/{}/{}", CONFIG.attachments_folder(), self.cipher_uuid, self.id)
    }

    pub fn to_json(&self, host: &str) -> Value {
        use crate::util::get_display_size;

        let web_path = format!("{}/attachments/{}/{}", host, self.cipher_uuid, self.id);
        let display_size = get_display_size(self.file_size);

        json!({
            "Id": self.id,
            "Url": web_path,
            "FileName": self.file_name,
            "Size": self.file_size.to_string(),
            "SizeName": display_size,
            "Key": self.akey,
            "Object": "attachment"
        })
    }
}

use crate::db::schema::{attachments, ciphers};
use crate::db::DbConn;
use diesel::prelude::*;

use crate::api::EmptyResult;
use crate::error::MapResult;

/// Database methods
impl Attachment {
    #[cfg(feature = "postgresql")]
    pub fn save(&self, conn: &DbConn) -> EmptyResult {
        diesel::insert_into(attachments::table)
            .values(self)
            .on_conflict(attachments::id)
            .do_update()
            .set(self)
            .execute(&**conn)
            .map_res("Error saving attachment")
    }

    #[cfg(not(feature = "postgresql"))]
    pub fn save(&self, conn: &DbConn) -> EmptyResult {
        diesel::replace_into(attachments::table)
            .values(self)
            .execute(&**conn)
            .map_res("Error saving attachment")
    }

    pub fn delete(self, conn: &DbConn) -> EmptyResult {
        crate::util::retry(
            || diesel::delete(attachments::table.filter(attachments::id.eq(&self.id))).execute(&**conn),
            10,
        )
        .map_res("Error deleting attachment")?;

        crate::util::delete_file(&self.get_file_path())?;
        Ok(())
    }

    pub fn delete_all_by_cipher(cipher_uuid: &str, conn: &DbConn) -> EmptyResult {
        for attachment in Attachment::find_by_cipher(&cipher_uuid, &conn) {
            attachment.delete(&conn)?;
        }
        Ok(())
    }

    pub fn find_by_id(id: &str, conn: &DbConn) -> Option<Self> {
        let id = id.to_lowercase();

        attachments::table
            .filter(attachments::id.eq(id))
            .first::<Self>(&**conn)
            .ok()
    }

    pub fn find_by_cipher(cipher_uuid: &str, conn: &DbConn) -> Vec<Self> {
        attachments::table
            .filter(attachments::cipher_uuid.eq(cipher_uuid))
            .load::<Self>(&**conn)
            .expect("Error loading attachments")
    }

    pub fn find_by_ciphers(cipher_uuids: Vec<String>, conn: &DbConn) -> Vec<Self> {
        attachments::table
            .filter(attachments::cipher_uuid.eq_any(cipher_uuids))
            .load::<Self>(&**conn)
            .expect("Error loading attachments")
    }

    pub fn size_by_user(user_uuid: &str, conn: &DbConn) -> i64 {
        let result: Option<i64> = attachments::table
            .left_join(ciphers::table.on(ciphers::uuid.eq(attachments::cipher_uuid)))
            .filter(ciphers::user_uuid.eq(user_uuid))
            .select(diesel::dsl::sum(attachments::file_size))
            .first(&**conn)
            .expect("Error loading user attachment total size");

        result.unwrap_or(0)
    }

    pub fn count_by_user(user_uuid: &str, conn: &DbConn) -> i64 {
        attachments::table
            .left_join(ciphers::table.on(ciphers::uuid.eq(attachments::cipher_uuid)))
            .filter(ciphers::user_uuid.eq(user_uuid))
            .count()
            .first::<i64>(&**conn)
            .ok()
            .unwrap_or(0)
    }

    pub fn size_by_org(org_uuid: &str, conn: &DbConn) -> i64 {
        let result: Option<i64> = attachments::table
            .left_join(ciphers::table.on(ciphers::uuid.eq(attachments::cipher_uuid)))
            .filter(ciphers::organization_uuid.eq(org_uuid))
            .select(diesel::dsl::sum(attachments::file_size))
            .first(&**conn)
            .expect("Error loading user attachment total size");

        result.unwrap_or(0)
    }
}