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
use crate::{bucket::GridFSBucket, GridFSError};
use bson::{doc, oid::ObjectId};
use futures::{Stream, StreamExt};
use mongodb::options::{FindOneOptions, FindOptions, SelectionCriteria};

impl GridFSBucket {
    /**
     Opens a Stream from which the application can read the contents of the stored file
     specified by @id.
     [Spec](https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst#file-download)

     Returns a [`Stream`].

     # Examples

     ```rust
     use futures::stream::StreamExt;
     # use mongodb::Client;
     # use mongodb::Database;
     use mongodb_gridfs::{options::GridFSBucketOptions, GridFSBucket, GridFSError};
     # use uuid::Uuid;
     # fn db_name_new() -> String {
     #     "test_".to_owned()
     #         + Uuid::new_v4()
     #             .to_hyphenated()
     #             .encode_lower(&mut Uuid::encode_buffer())
     # }
     #
     # #[tokio::main]
     # async fn main() -> Result<(), GridFSError> {
     #     let client = Client::with_uri_str(
     #         &std::env::var("MONGO_URI").unwrap_or("mongodb://localhost:27017/".to_string()),
     #     )
     #     .await?;
     #     let dbname = db_name_new();
     #     let db: Database = client.database(&dbname);
     let bucket = GridFSBucket::new(db.clone(), Some(GridFSBucketOptions::default()));
     #     let id = bucket
     #         .clone()
     #         .upload_from_stream("test.txt", "test data".as_bytes(), None)
     #         .await?;
     #     println!("{}", id);
     #
     let mut cursor = bucket.open_download_stream(id).await?;
     let buffer = cursor.next().await.unwrap();
     #     println!("{:?}", buffer);
     #
     #     db.drop(None).await?;
     #     Ok(())
     # }
     ```

     # Errors

     Raise [`GridFSError::FileNotFound`] when the requested id doesn't exists.
    */
    pub async fn open_download_stream(
        &self,
        id: ObjectId,
    ) -> Result<impl Stream<Item = Vec<u8>>, GridFSError> {
        let dboptions = self.options.clone().unwrap_or_default();
        let bucket_name = dboptions.bucket_name;
        let file_collection = bucket_name.clone() + ".files";
        let files = self.db.collection(&file_collection);
        let chunk_collection = bucket_name + ".chunks";
        let chunks = self.db.collection(&chunk_collection);

        let mut find_one_options = FindOneOptions::default();
        let mut find_options = FindOptions::builder().sort(doc! {"n":1}).build();

        if let Some(read_concern) = dboptions.read_concern {
            find_one_options.read_concern = Some(read_concern.clone());
            find_options.read_concern = Some(read_concern);
        }
        if let Some(read_preference) = dboptions.read_preference {
            find_one_options.selection_criteria =
                Some(SelectionCriteria::ReadPreference(read_preference.clone()));
            find_options.selection_criteria =
                Some(SelectionCriteria::ReadPreference(read_preference));
        }

        /*
        Drivers must first retrieve the files collection document for this
        file. If there is no files collection document, the file either never
        existed, is in the process of being deleted, or has been corrupted,
        and the driver MUST raise an error.
        */
        let file = files
            .find_one(doc! {"_id":id.clone()}, find_one_options)
            .await?;

        if file.is_none() {
            return Err(GridFSError::FileNotFound());
        }

        Ok(chunks
            .find(doc! {"files_id":id}, find_options.clone())
            .await
            .unwrap()
            .map(|item| {
                let i = item.unwrap();
                i.get_binary_generic("data").unwrap().clone()
            }))
    }
}

#[cfg(test)]
mod tests {
    use super::GridFSBucket;
    use crate::{options::GridFSBucketOptions, GridFSError};
    use bson::oid::ObjectId;
    use futures::stream::StreamExt;
    use mongodb::Client;
    use mongodb::Database;
    use uuid::Uuid;
    fn db_name_new() -> String {
        "test_".to_owned()
            + Uuid::new_v4()
                .to_hyphenated()
                .encode_lower(&mut Uuid::encode_buffer())
    }

    #[tokio::test]
    async fn open_download_stream() -> Result<(), GridFSError> {
        let client = Client::with_uri_str(
            &std::env::var("MONGO_URI").unwrap_or("mongodb://localhost:27017/".to_string()),
        )
        .await?;
        let dbname = db_name_new();
        let db: Database = client.database(&dbname);
        let bucket = &GridFSBucket::new(db.clone(), Some(GridFSBucketOptions::default()));
        let id = bucket
            .clone()
            .upload_from_stream("test.txt", "test data".as_bytes(), None)
            .await?;

        assert_eq!(id.to_hex(), id.to_hex());

        let mut cursor = bucket.open_download_stream(id).await?;
        let buffer = cursor.next().await.unwrap();
        assert_eq!(buffer, [116, 101, 115, 116, 32, 100, 97, 116, 97]);
        db.drop(None).await?;
        Ok(())
    }
    #[tokio::test]
    async fn open_download_stream_chunk_size() -> Result<(), GridFSError> {
        let client = Client::with_uri_str(
            &std::env::var("MONGO_URI").unwrap_or("mongodb://localhost:27017/".to_string()),
        )
        .await?;
        let dbname = db_name_new();
        let db: Database = client.database(&dbname);
        let bucket = &GridFSBucket::new(
            db.clone(),
            Some(GridFSBucketOptions::builder().chunk_size_bytes(4).build()),
        );
        let id = bucket
            .clone()
            .upload_from_stream("test.txt", "test data".as_bytes(), None)
            .await?;

        assert_eq!(id.to_hex(), id.to_hex());

        let mut cursor = bucket.open_download_stream(id).await?;
        let buffer = cursor.next().await.unwrap();
        assert_eq!(buffer, [116, 101, 115, 116]);

        let buffer = cursor.next().await.unwrap();
        assert_eq!(buffer, [32, 100, 97, 116]);

        let buffer = cursor.next().await.unwrap();
        assert_eq!(buffer, [97]);

        let buffer = cursor.next().await;
        assert_eq!(buffer, None);

        db.drop(None).await?;
        Ok(())
    }

    #[tokio::test]
    async fn open_download_stream_not_existing_file() -> Result<(), GridFSError> {
        let client = Client::with_uri_str(
            &std::env::var("MONGO_URI").unwrap_or("mongodb://localhost:27017/".to_string()),
        )
        .await?;
        let dbname = db_name_new();
        let db: Database = client.database(&dbname);
        let bucket = &GridFSBucket::new(db.clone(), Some(GridFSBucketOptions::default()));
        let id = ObjectId::new();

        let cursor = bucket.open_download_stream(id).await;
        assert!(cursor.is_err());

        db.drop(None).await?;
        Ok(())
    }
}