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
use std::{io, fs};
use std::sync::Arc;

use oid::ObjectId;
use bson;

use db::{Database, ThreadDatabase};
use coll::Collection;
use coll::options::FindOptions;
use cursor::Cursor;
use error::Error::{self, ArgumentError};
use error::Result;

use self::file::{File, Mode};

pub mod file;

/// A default cursor wrapper that maps bson documents into GridFS file representations.
pub struct FileCursor {
    store: Store,
    cursor: Cursor,
    err: Option<Error>,
}

impl Iterator for FileCursor {
    type Item = File;

    fn next(&mut self) -> Option<File> {
        match self.cursor.next() {
            Some(Ok(bdoc)) => Some(File::with_doc(self.store.clone(), bdoc)),
            Some(Err(err)) => {
                self.err = Some(err);
                None
            }
            None => None,
        }
    }
}

impl FileCursor {
    /// Returns the next n files.
    pub fn next_n(&mut self, n: i32) -> Result<Vec<File>> {
        let docs = self.cursor.next_n(n)?;
        Ok(docs.into_iter()
            .map(|doc| File::with_doc(self.store.clone(), doc.clone()))
            .collect())
    }

    /// Returns the next batch of files.
    pub fn drain_current_batch(&mut self) -> Result<Vec<File>> {
        let docs = self.cursor.drain_current_batch()?;
        Ok(docs.into_iter()
            .map(|doc| File::with_doc(self.store.clone(), doc))
            .collect())
    }
}

/// Alias for a thread-safe GridFS instance.
pub type Store = Arc<StoreInner>;

/// Interfaces with a GridFS instance.
pub struct StoreInner {
    files: Collection,
    chunks: Collection,
}

pub trait ThreadedStore {
    /// A new GridFS store within the database with prefix 'fs'.
    fn with_db(db: Database) -> Store;
    /// A new GridFS store within the database with a specified prefix.
    fn with_prefix(db: Database, prefix: String) -> Store;
    /// Creates a new file.
    fn create(&self, name: String) -> Result<File>;
    /// Opens a file by filename.
    fn open(&self, name: String) -> Result<File>;
    /// Opens a file by object ID.
    fn open_id(&self, id: ObjectId) -> Result<File>;
    /// Returns a cursor to all file documents matching the provided filter.
    fn find(&self,
            filter: Option<bson::Document>,
            options: Option<FindOptions>)
            -> Result<FileCursor>;
    /// Removes a file from GridFS by filename.
    fn remove(&self, name: String) -> Result<()>;
    /// Removes a file from GridFS by object ID.
    fn remove_id(&self, id: ObjectId) -> Result<()>;
    /// Inserts a new file from local into GridFS.
    fn put(&self, name: String) -> Result<()>;
    /// Retrieves a file from GridFS into local storage.
    fn get(&self, name: String) -> Result<()>;
}

impl ThreadedStore for Store {
    fn with_db(db: Database) -> Store {
        Store::with_prefix(db, String::from("fs"))
    }

    fn with_prefix(db: Database, prefix: String) -> Store {
        Arc::new(StoreInner {
            files: db.collection(&format!("{}.files", prefix)[..]),
            chunks: db.collection(&format!("{}.chunks", prefix)[..]),
        })
    }

    fn create(&self, name: String) -> Result<File> {
        Ok(File::with_name(self.clone(), name, ObjectId::new()?, Mode::Write))
    }

    fn open(&self, name: String) -> Result<File> {
        let mut options = FindOptions::new();
        options.sort = Some(doc!{ "uploadDate" => 1 });

        match self.files.find_one(Some(doc!{ "filename" => name }), Some(options))? {
            Some(bdoc) => Ok(File::with_doc(self.clone(), bdoc)),
            None => Err(ArgumentError(String::from("File does not exist."))),
        }
    }

    fn open_id(&self, id: ObjectId) -> Result<File> {
        match self.files.find_one(Some(doc!{ "_id" => id }), None)? {
            Some(bdoc) => Ok(File::with_doc(self.clone(), bdoc)),
            None => Err(ArgumentError(String::from("File does not exist."))),
        }
    }

    fn find(&self, filter: Option<bson::Document>, options: Option<FindOptions>) -> Result<FileCursor> {
        Ok(FileCursor {
            store: self.clone(),
            cursor: self.files.find(filter, options)?,
            err: None,
        })
    }

    fn remove(&self, name: String) -> Result<()> {
        let mut options = FindOptions::new();
        options.projection = Some(doc!{ "_id" => 1 });

        let cursor = self.find(Some(doc!{ "filename" => name }), Some(options))?;
        for doc in cursor {
            self.remove_id(doc.id.clone())?;
        }

        Ok(())
    }

    fn remove_id(&self, id: ObjectId) -> Result<()> {
        self.files.delete_many(doc!{ "_id" => (id.clone()) }, None)?;
        self.chunks.delete_many(doc!{ "files_id" => (id.clone()) }, None)?;
        Ok(())
    }

    fn put(&self, name: String) -> Result<()> {
        let mut file = self.create(name.clone())?;
        let mut f = fs::File::open(name)?;
        io::copy(&mut f, &mut file)?;
        file.close()?;
        Ok(())
    }

    fn get(&self, name: String) -> Result<()> {
        let mut f = fs::File::create(name.clone())?;
        let mut file = self.open(name)?;
        io::copy(&mut file, &mut f)?;
        file.close()?;
        Ok(())
    }
}