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
// Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

use crate::client::Client;
use crate::crypto::shared_secretbox;
use crate::err;
use crate::nfs::{data_map, File, NfsError, NfsFuture};
use crate::self_encryption_storage::SelfEncryptionStorage;
use crate::utils::FutureExt;
use futures::Future;
use log::{debug, trace};
use self_encryption::SelfEncryptor;

/// `Reader` is used to read contents of a `File`. It can read in chunks if the `File` happens to be
/// very large.
#[allow(dead_code)]
pub struct Reader<C: Client> {
    client: C,
    self_encryptor: SelfEncryptor<SelfEncryptionStorage<C>>,
}

impl<C: Client> Reader<C> {
    /// Create a new instance of `Reader`.
    pub fn new(
        client: C,
        storage: SelfEncryptionStorage<C>,
        file: &File,
        encryption_key: Option<shared_secretbox::Key>,
    ) -> Box<NfsFuture<Self>> {
        data_map::get(&client, file.data_address(), encryption_key)
            .and_then(move |data_map| {
                let self_encryptor = SelfEncryptor::new(storage, data_map)?;

                Ok(Self {
                    client,
                    self_encryptor,
                })
            })
            .into_box()
    }

    /// Returns the total size of the file/blob.
    pub fn size(&self) -> u64 {
        self.self_encryptor.len()
    }

    /// Read data from file/blob.
    pub fn read(&self, position: u64, length: u64) -> Box<NfsFuture<Vec<u8>>> {
        trace!(
            "Reader reading from pos: {} and size: {}.",
            position,
            length
        );

        if (position + length) > self.size() {
            err!(NfsError::InvalidRange)
        } else {
            debug!(
                "Reading {len} bytes of data from file starting at offset of {pos} bytes ...",
                len = length,
                pos = position
            );
            self.self_encryptor
                .read(position, length)
                .map_err(From::from)
                .into_box()
        }
    }
}