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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//
// Wildland Project
//
// Copyright © 2022 Golem Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use derivative::Derivative;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use wildland_corex::catlib_service::entities::PubKey;
use wildland_corex::catlib_service::error::CatlibError;
use wildland_corex::catlib_service::CatLibService;
use wildland_corex::{
    ContainerManager,
    ContainerManagerError,
    CoreXError,
    ErrContext,
    Forest,
    StorageTemplate,
};

use super::cargo_lib::DfsApi;
use super::container::{CargoContainer, CargoContainerFilter, MountState, SharingMessage};
use super::foundation_storage::{FoundationStorageApi, FreeTierProcessHandle, FsaError};
use crate::multidevice_state::error::MultideviceStateError;
use crate::multidevice_state::user_state::UserMultideviceState;

/// Structure representing a User.
///
/// It gives access to:
/// - user's forest and containers,
/// - Foundation Storage API which includes the following methods:
///     - [`Self::request_free_tier_storage()`]
///     - [`Self::verify_email()`]
#[derive(Clone, Derivative)]
#[derivative(Debug)]
pub struct CargoUser {
    this_device: String,
    all_devices: Vec<String>,
    forest: Forest,

    #[derivative(Debug = "ignore")]
    services: CargoUserServices,
}

#[derive(Debug, Deserialize, Serialize)]
struct CargoContainerMetadata {
    pub encrypted: bool,
}

impl TryFrom<&[u8]> for CargoContainerMetadata {
    type Error = CatlibError;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        serde_json::from_slice(value).map_err(|e| {
            CatlibError::InvalidDataError(format!("Malformed container's metadata record: {e}"))
        })
    }
}

impl TryFrom<&CargoContainerMetadata> for Vec<u8> {
    type Error = CatlibError;

    fn try_from(value: &CargoContainerMetadata) -> Result<Self, Self::Error> {
        serde_json::to_vec(value).map_err(|e| {
            CatlibError::InvalidDataError(format!("Container's metadata cannot be serialized: {e}"))
        })
    }
}

#[derive(Clone)]
pub struct CargoUserServices {
    catlib_service: CatLibService,
    fsa_api: FoundationStorageApi,
    container_manager: ContainerManager,
    multi_device_state: UserMultideviceState,
    dfs_api: DfsApi,
}

impl CargoUserServices {
    pub fn new(
        catlib_service: CatLibService,
        fsa_api: FoundationStorageApi,
        container_manager: ContainerManager,
        multi_device_state: UserMultideviceState,
        dfs_api: DfsApi,
    ) -> Self {
        Self {
            catlib_service,
            fsa_api,
            container_manager,
            multi_device_state,
            dfs_api,
        }
    }
}

#[derive(Debug, Error, PartialEq, Eq, Clone)]
pub enum AutomountError {
    #[error("Cannot perform automount when any container is mounted")]
    MountedContainersDetected,
    #[error("Cannot retrieve information about users automounted containers: {0}")]
    MultideviceStateError(#[from] MultideviceStateError),
    #[error("Error while mounting one of automounted containers: {0}")]
    ContainerManagerError(#[from] ContainerManagerError),
    #[error("Error while finding user's containers in CatLib: {0}")]
    CatlibError(#[from] CatlibError),
}

#[derive(Error, Debug, Clone)]
#[repr(C)]
pub enum SharingError {
    #[error("Sharing Generic Error: {0}")]
    Generic(String),
}

impl CargoUser {
    pub fn new(
        this_device: String,
        all_devices: Vec<String>,
        forest: Forest,
        services: CargoUserServices,
    ) -> Self {
        Self {
            this_device,
            all_devices,
            forest,
            services,
        }
    }

    /// Tries to mount containers that are set to be mounted automatically.
    ///
    /// Containers can be set as automounted in local (device) or global (user's) context.
    /// During automount records from both contexts are taken into account and ordered by time of
    /// creation.
    ///
    /// This method can be called only if the application is in clean state - no containers have
    /// been mounted yet.
    pub fn automount(&self) -> Result<(), AutomountError> {
        if !self.find_containers(None, MountState::Mounted)?.is_empty() {
            return Err(AutomountError::MountedContainersDetected);
        }

        let automounted_containers = self
            .services
            .multi_device_state
            .get_automounted_containers()?
            .collect::<Vec<_>>();
        let filters = automounted_containers
            .iter()
            .map(|(uuid, _context)| CargoContainerFilter::has_uuid(*uuid));

        let found_containers = self.find_containers(
            Some(CargoContainerFilter::any(filters.collect())),
            MountState::MountedOrUnmounted,
        )?;

        automounted_containers
            .into_iter()
            .filter_map(|(uuid, persistency)| {
                found_containers
                    .iter()
                    .find(|c| c.uuid() == uuid)
                    .map(|c| (c, persistency))
            })
            .try_for_each(|(container, persistency)| container.mount(Some(persistency)))?;

        Ok(())
    }

    /// Returns string representation of a [`CargoUser`]
    pub fn stringify(&self) -> String {
        let CargoUser {
            this_device,
            all_devices,
            ..
        } = &self;
        let all_devices_str = all_devices
            .iter()
            .map(|d| format!("    {d}"))
            .collect::<Vec<_>>()
            .join("\n");
        format!(
            "
This device: {this_device}
All devices:
{all_devices_str}
"
        )
    }

    /// Returns vector of handles to containers found in the user's forest.
    ///
    /// # Args:
    /// - `filter`: filter that is passed to catlib, so the query to database could be optimized
    /// - `mount_state`: specifies whether to include mounted, unmounted or all containers in results.
    ///
    /// ## Example
    ///
    /// ```
    /// # use wildland_cargo_lib::api::CargoConfig;
    /// # use wildland_cargo_lib::api::container::*;
    /// # use wildland_cargo_lib::api::cargo_lib::create_cargo_lib;
    /// # use wildland_storage_backend::lfs::template::LocalFilesystemStorageTemplate;
    /// # use wildland_corex::StorageTemplate;
    /// # use wildland_corex::LocalSecureStorage;
    /// # use std::sync::RwLock;
    /// # use std::collections::HashMap;
    /// # use wildland_corex::LssResult;
    /// #
    /// # let tmpdir = tempfile::tempdir().unwrap().into_path();
    /// #
    /// # let config_str = r#"{
    /// #     "log_level": "trace",
    /// #     "log_use_ansi": false,
    /// #     "log_file_enabled": true,
    /// #     "log_file_path": "cargo_lib_log",
    /// #     "log_file_rotate_directory": ".",
    /// #     "evs_url": "some_url",
    /// #     "gql_url": "http://localhost:8000/graphql/",
    /// #     "redis_connection_string": "redis://127.0.0.1/0"
    /// # }"#;
    /// # let cfg: CargoConfig = serde_json::from_str(config_str).unwrap();
    /// #
    /// # fn lss_stub() -> Box<dyn LocalSecureStorage> {
    /// #     #[derive(Default)]
    /// #     struct LssStub {
    /// #         storage: RwLock<HashMap<String, String>>,
    /// #     }
    /// #
    /// #     impl LocalSecureStorage for LssStub {
    /// #         fn insert(&self, key: String, value: String) -> LssResult<Option<String>> {
    /// #             Ok(self.storage.write().unwrap().insert(key, value))
    /// #         }
    /// #
    /// #         fn get(&self, key: String) -> LssResult<Option<String>> {
    /// #             Ok(self.storage.read().unwrap().get(&key).cloned())
    /// #         }
    /// #
    /// #         fn contains_key(&self, key: String) -> LssResult<bool> {
    /// #             Ok(self.storage.read().unwrap().contains_key(&key))
    /// #         }
    /// #
    /// #         fn keys(&self) -> LssResult<Vec<String>> {
    /// #             Ok(self.storage.read().unwrap().keys().cloned().collect())
    /// #         }
    /// #
    /// #         fn keys_starting_with(&self, prefix: String) -> LssResult<Vec<String>> {
    /// #             Ok(self
    /// #                 .storage
    /// #                 .read().unwrap()
    /// #                 .keys()
    /// #                 .filter(|key| key.starts_with(&prefix))
    /// #                 .cloned()
    /// #                 .collect())
    /// #         }
    /// #
    /// #         fn remove(&self, key: String) -> LssResult<Option<String>> {
    /// #             Ok(self.storage.write().unwrap().remove(&key))
    /// #         }
    /// #
    /// #         fn len(&self) -> LssResult<usize> {
    /// #             Ok(self.storage.read().unwrap().len())
    /// #         }
    /// #
    /// #         fn is_empty(&self) -> LssResult<bool> {
    /// #             Ok(self.storage.read().unwrap().is_empty())
    /// #         }
    /// #     }
    /// #     Box::<LssStub>::default()
    /// # }
    /// #
    /// #
    /// # let lss_stub = lss_stub();
    /// #
    /// # let cargo_lib = create_cargo_lib(lss_stub, cfg);
    /// # let cargo_lib = cargo_lib.unwrap();
    /// # let cargo_lib = cargo_lib.lock().unwrap();
    /// # let user_api = cargo_lib.user_api();
    /// # let mnemonic = user_api.generate_mnemonic().unwrap();
    /// # let user = user_api
    /// #     .create_user_from_mnemonic(&mnemonic, "device_name".to_string())
    /// #     .unwrap();
    ///
    /// let containers = user
    ///     .find_containers(
    ///         Some(CargoContainerFilter::or(
    ///             CargoContainerFilter::has_exact_path("/some/path".into()),
    ///             CargoContainerFilter::has_path_starting_with("/some/other/".into()),
    ///         )),
    ///         MountState::MountedOrUnmounted,
    ///     )
    ///     .unwrap();
    /// ```
    #[tracing::instrument(skip(self), level = "trace")]
    pub fn find_containers(
        &self,
        filter: Option<CargoContainerFilter>,
        mount_state: MountState,
    ) -> Result<Vec<CargoContainer>, CatlibError> {
        Ok(self
            .forest
            .find_containers(filter.map(Into::into))?
            .into_iter()
            .map(|corex_container| {
                let metadata: CargoContainerMetadata =
                    corex_container.metadata()?.as_slice().try_into()?;
                Ok(CargoContainer::new(
                    self.services.container_manager.clone(),
                    corex_container,
                    metadata.encrypted,
                    self.services.multi_device_state.clone(),
                    self.services.dfs_api.clone(),
                ))
            })
            .collect::<Result<Vec<_>, _>>()?
            .into_iter()
            .filter(|container| match mount_state {
                MountState::Mounted => container.is_mounted(),
                MountState::Unmounted => !container.is_mounted(),
                MountState::MountedOrUnmounted => true,
            })
            .collect())
    }

    /// Creates a new container within user's forest and returns its handle
    ///
    /// ## Example
    /// ```
    /// # use wildland_cargo_lib::api::CargoConfig;
    /// # use wildland_cargo_lib::api::cargo_lib::create_cargo_lib;
    /// # use wildland_storage_backend::lfs::template::LocalFilesystemStorageTemplate;
    /// # use wildland_storage_backend::lfs::template::LOCAL_FILESYSTEM_KEY;
    /// # use wildland_corex::StorageTemplate;
    /// # use wildland_corex::LocalSecureStorage;
    /// # use std::sync::RwLock;
    /// # use std::collections::HashMap;
    /// # use wildland_corex::LssResult;
    /// #
    /// # let tmpdir = tempfile::tempdir().unwrap().into_path();
    /// #
    /// # let config_str = r#"{
    /// #     "log_level": "trace",
    /// #     "log_use_ansi": false,
    /// #     "log_file_enabled": true,
    /// #     "log_file_path": "cargo_lib_log",
    /// #     "log_file_rotate_directory": ".",
    /// #     "evs_url": "some_url",
    /// #     "gql_url": "http://localhost:8000/graphql/",
    /// #     "redis_connection_string": "redis://127.0.0.1:6379/0"
    /// # }"#;
    /// # let cfg: CargoConfig = serde_json::from_str(config_str).unwrap();
    /// #
    /// # fn lss_stub() -> Box<dyn LocalSecureStorage> {
    /// #     #[derive(Default)]
    /// #     struct LssStub {
    /// #         storage: RwLock<HashMap<String, String>>,
    /// #     }
    /// #
    /// #     impl LocalSecureStorage for LssStub {
    /// #         fn insert(&self, key: String, value: String) -> LssResult<Option<String>> {
    /// #             Ok(self.storage.write().unwrap().insert(key, value))
    /// #         }
    /// #
    /// #         fn get(&self, key: String) -> LssResult<Option<String>> {
    /// #             Ok(self.storage.read().unwrap().get(&key).cloned())
    /// #         }
    /// #
    /// #         fn contains_key(&self, key: String) -> LssResult<bool> {
    /// #             Ok(self.storage.read().unwrap().contains_key(&key))
    /// #         }
    /// #
    /// #         fn keys(&self) -> LssResult<Vec<String>> {
    /// #             Ok(self.storage.read().unwrap().keys().cloned().collect())
    /// #         }
    /// #
    /// #         fn keys_starting_with(&self, prefix: String) -> LssResult<Vec<String>> {
    /// #             Ok(self
    /// #                 .storage
    /// #                 .read().unwrap()
    /// #                 .keys()
    /// #                 .filter(|key| key.starts_with(&prefix))
    /// #                 .cloned()
    /// #                 .collect())
    /// #         }
    /// #
    /// #         fn remove(&self, key: String) -> LssResult<Option<String>> {
    /// #             Ok(self.storage.write().unwrap().remove(&key))
    /// #         }
    /// #
    /// #         fn len(&self) -> LssResult<usize> {
    /// #             Ok(self.storage.read().unwrap().len())
    /// #         }
    /// #
    /// #         fn is_empty(&self) -> LssResult<bool> {
    /// #             Ok(self.storage.read().unwrap().is_empty())
    /// #         }
    /// #     }
    /// #     Box::<LssStub>::default()
    /// # }
    /// #
    /// # let lss_stub = lss_stub();
    /// #
    /// # let cargo_lib = create_cargo_lib(lss_stub, cfg);
    /// # let cargo_lib = cargo_lib.unwrap();
    /// # let cargo_lib = cargo_lib.lock().unwrap();
    /// # let user_api = cargo_lib.user_api();
    /// # let mnemonic = user_api.generate_mnemonic().unwrap();
    /// # let user = user_api
    /// #     .create_user_from_mnemonic(&mnemonic, "device_name".to_string())
    /// #     .unwrap();
    ///
    /// let template = LocalFilesystemStorageTemplate {
    ///     local_dir: tmpdir.clone(),
    ///     container_dir: "{{ CONTAINER_NAME }}".to_owned(),
    /// };
    /// let container = user
    ///     .create_container(
    ///         "C1".to_owned(),
    ///         &template.into(),
    ///         "/some/path/".to_owned(),
    ///         false
    ///     )
    ///     .unwrap();
    /// ```
    #[tracing::instrument(level = "debug", skip_all)]
    pub fn create_container(
        &self,
        name: String,
        template: &StorageTemplate,
        path: String,
        encrypted: bool,
    ) -> Result<CargoContainer, CoreXError> {
        let serialized_metadata = Vec::try_from(&CargoContainerMetadata { encrypted })
            .context("Could not serialize container's metadata")?;

        let corex_container = self
            .forest
            .create_container(name, template, path.into(), encrypted, serialized_metadata)
            .context("Creating container in CargoUser failed")?;

        Ok(CargoContainer::new(
            self.services.container_manager.clone(),
            corex_container,
            encrypted,
            self.services.multi_device_state.clone(),
            self.services.dfs_api.clone(),
        ))
    }

    pub fn this_device(&self) -> &str {
        &self.this_device
    }

    pub fn all_devices(&self) -> &[String] {
        self.all_devices.as_slice()
    }

    /// Returns vector of user's storage templates
    ///
    #[tracing::instrument(level = "debug", skip_all)]
    pub fn get_storage_templates(&self) -> Result<Vec<StorageTemplate>, CatlibError> {
        self.forest.get_storage_templates()
    }

    /// Save StorageTemplate data in CatLib.
    ///
    #[tracing::instrument(level = "debug", skip_all)]
    pub fn save_storage_template(&self, tpl: &mut StorageTemplate) -> Result<String, CatlibError> {
        let (template_uuid, _saved_template) = self.forest.save_storage_template(tpl.clone())?;
        tpl.set_catlib_uuid(template_uuid);

        Ok(template_uuid.to_string())
    }

    /// Starts process of granting Free Tier Foundation Storage.
    ///
    /// `CargoUser` encapsulates `FoundationStorageApi` functionalities in order to avoid requesting
    /// Free Foundation Tier outside of the user context.
    ///
    /// Returns `FreeTierProcessHandle` structure which can be used to verify an email address and
    /// finalize the process.
    #[tracing::instrument(level = "debug", skip_all)]
    pub fn request_free_tier_storage(
        &self,
        email: String,
    ) -> Result<FreeTierProcessHandle, FsaError> {
        self.services.fsa_api.request_free_tier_storage(email)
    }

    /// Finishes process of granting Free Tier Foundation Storage.
    ///
    /// After successful server verification it saves Storage Template in LSS
    /// and saves information that storage has been granted in forest's metadata in CatLib.
    ///
    /// Returns the same storage template which is saved in LSS.
    #[tracing::instrument(level = "debug", skip_all)]
    pub fn verify_email(
        &self,
        process_handle: &FreeTierProcessHandle,
        token: String,
    ) -> Result<StorageTemplate, FsaError> {
        let storage_template = process_handle.verify_email(token)?;
        let (_, saved_template) = self.forest.save_storage_template(storage_template)?;
        self.services
            .catlib_service
            .mark_free_storage_granted(&self.forest.forest_manifest())?;
        Ok(saved_template)
    }

    pub fn is_free_storage_granted(&self) -> Result<bool, CatlibError> {
        self.services
            .catlib_service
            .is_free_storage_granted(&self.forest.forest_manifest())
    }

    pub fn get_user_public_key(&self) -> Vec<u8> {
        self.forest.owner().get_pub_key().to_vec()
    }

    /// Creates a new shared container (or re-use one if it is already created) for the given path
    /// and target user's public key. Returns a sharing message containing all the information
    /// needed to re-create the shared container on the target side.
    ///
    /// Returns [`SharingMessage`].
    ///
    /// ## Errors
    /// - Returns [`SharingError::Generic`]
    ///
    #[tracing::instrument(level = "debug", skip(self))]
    pub fn share(
        &self,
        wildland_object_id: String,
        pub_key: PubKey,
    ) -> Result<SharingMessage, SharingError> {
        // TODO: CARGO-355 - CargoLib can create a new shared container
        Err(SharingError::Generic("Not implemented".into()))
    }

    /// Re-creates the shared container based on the [`SharingMessage`] and mounts it in
    /// the target path
    ///
    /// ## Errors
    /// - Returns [`SharingError::Generic`]
    ///
    #[tracing::instrument(level = "debug", skip(self))]
    pub fn add_shared_container(
        &self,
        _sharing_message: SharingMessage,
        _path: String,
    ) -> Result<(), SharingError> {
        // TODO: CARGO-328 - Consume SharingMessage
        Err(SharingError::Generic("Not implemented".into()))
    }

    /// Takes the Wildland object ID and the public key and tries to revoke access to the resource
    /// for the given user.
    ///
    /// ## Errors
    /// - Returns [`SharingError::Generic`]
    ///  
    #[tracing::instrument(level = "debug", skip(self))]
    pub fn revoke_sharing(
        &self,
        wildland_object_id: String,
        _pub_key: PubKey,
    ) -> Result<(), SharingError> {
        // TODO: CARGO-329 - Revoke sharing for a given user
        Err(SharingError::Generic("Not implemented".into()))
    }

    /// Takes the Wildland object ID and returns collection of PubKeys for which the given
    /// resource has been shared with.
    ///
    /// Returns vector of [`PubKey`] related to users who has access to the given resource
    ///
    /// ## Errors
    /// - Returns [`SharingError::Generic`]
    ///  
    #[tracing::instrument(level = "debug", skip(self))]
    pub fn get_pubkeys_having_access_to_object(
        &self,
        wildland_object_id: String,
    ) -> Result<Vec<PubKey>, SharingError> {
        // TODO: CARGO-355 - CargoLib can create a new shared container
        Err(SharingError::Generic("Not implemented".into()))
    }
}