Skip to main content

revolt_database/models/file_hashes/ops/
mongodb.rs

1use revolt_result::Result;
2
3use crate::FileHash;
4use crate::MongoDb;
5
6use super::AbstractAttachmentHashes;
7
8static COL: &str = "attachment_hashes";
9
10#[async_trait]
11impl AbstractAttachmentHashes for MongoDb {
12    /// Insert a new attachment hash into the database.
13    async fn insert_attachment_hash(&self, hash: &FileHash) -> Result<()> {
14        query!(self, insert_one, COL, &hash).map(|_| ())
15    }
16
17    /// Fetch an attachment hash entry by sha256 hash.
18    async fn fetch_attachment_hash(&self, hash: &str) -> Result<FileHash> {
19        query!(
20            self,
21            find_one,
22            COL,
23            doc! {
24                "$or": [
25                    {"_id": hash},
26                    {"processed_hash": hash}
27                ]
28            }
29        )?
30        .ok_or_else(|| create_error!(NotFound))
31    }
32
33    /// Update an attachment hash nonce value.
34    async fn set_attachment_hash_nonce(&self, hash: &str, nonce: &str) -> Result<()> {
35        self.col::<FileHash>(COL)
36            .update_one(
37                doc! {
38                    "_id": hash
39                },
40                doc! {
41                    "$set": {
42                        "iv": nonce
43                    }
44                },
45            )
46            .await
47            .map(|_| ())
48            .map_err(|_| create_database_error!("update_one", COL))
49    }
50
51    /// Updates the attachments animated metadata value.
52    ///
53    /// The primary use for this is to update the metadata for existing uploaded files, this
54    /// can only be used for images.
55    async fn set_attachment_hash_animated(&self, hash: &str, animated: bool) -> Result<()> {
56        self.col::<FileHash>(COL)
57            .update_one(
58                doc! {
59                    "_id": hash,
60                    "metadata.type": "Image",
61                    "metadata.animated": { "$exists": false },
62                },
63                doc! {
64                    "$set": {
65                        "metadata.animated": animated
66                    }
67                },
68            )
69            .await
70            .map(|_| ())
71            .map_err(|_| create_database_error!("update_one", COL))
72    }
73
74    /// Delete attachment hash by id.
75    async fn delete_attachment_hash(&self, id: &str) -> Result<()> {
76        query!(self, delete_one_by_id, COL, id).map(|_| ())
77    }
78}