Skip to main content

revolt_database/models/file_hashes/ops/
reference.rs

1use revolt_result::Result;
2
3use crate::{FileHash, Metadata, ReferenceDb};
4
5use super::AbstractAttachmentHashes;
6
7#[async_trait]
8impl AbstractAttachmentHashes for ReferenceDb {
9    /// Insert a new attachment hash into the database.
10    async fn insert_attachment_hash(&self, hash: &FileHash) -> Result<()> {
11        let mut hashes = self.file_hashes.lock().await;
12        if hashes.contains_key(&hash.id) {
13            Err(create_database_error!("insert", "attachment"))
14        } else {
15            hashes.insert(hash.id.to_string(), hash.clone());
16            Ok(())
17        }
18    }
19
20    /// Fetch an attachment hash entry by sha256 hash.
21    async fn fetch_attachment_hash(&self, hash_value: &str) -> Result<FileHash> {
22        let hashes = self.file_hashes.lock().await;
23        hashes
24            .values()
25            .find(|&hash| hash.id == hash_value || hash.processed_hash == hash_value)
26            .cloned()
27            .ok_or(create_error!(NotFound))
28    }
29
30    /// Update an attachment hash nonce value.
31    async fn set_attachment_hash_nonce(&self, hash: &str, nonce: &str) -> Result<()> {
32        let mut hashes = self.file_hashes.lock().await;
33        if let Some(file) = hashes.get_mut(hash) {
34            file.iv = nonce.to_owned();
35            Ok(())
36        } else {
37            Err(create_error!(NotFound))
38        }
39    }
40
41    /// Updates the attachments animated metadata value.
42    ///
43    /// The primary use for this is to update the metadata for existing uploaded files, this
44    /// can only be used for images.
45    async fn set_attachment_hash_animated(&self, hash: &str, animated: bool) -> Result<()> {
46        let mut hashes = self.file_hashes.lock().await;
47        if let Some(FileHash {
48            metadata:
49                Metadata::Image {
50                    animated: Some(animated_metadata),
51                    ..
52                },
53            ..
54        }) = hashes.get_mut(hash)
55        {
56            *animated_metadata = animated;
57
58            Ok(())
59        } else {
60            Err(create_error!(NotFound))
61        }
62    }
63
64    /// Delete attachment hash by id.
65    async fn delete_attachment_hash(&self, id: &str) -> Result<()> {
66        let mut file_hashes = self.file_hashes.lock().await;
67        if file_hashes.remove(id).is_some() {
68            Ok(())
69        } else {
70            Err(create_error!(NotFound))
71        }
72    }
73}