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
use std::collections::HashSet;

use libsecp256k1::PublicKey;
use uuid::Uuid;

use crate::access_info::UserAccessMode;
use crate::account::Account;
use crate::file_like::FileLike;
use crate::file_metadata::{FileType, Owner};
use crate::lazy::LazyStaged1;
use crate::signed_file::SignedFile;
use crate::tree_like::{TreeLike, TreeLikeMut};
use crate::{symkey, validate, SharedErrorKind, SharedResult};

impl<Base, Local> LazyStaged1<Base, Local>
where
    Base: TreeLike<F = SignedFile>,
    Local: TreeLike<F = Base::F>,
{
    pub fn path_to_id(&mut self, path: &str, root: &Uuid, account: &Account) -> SharedResult<Uuid> {
        let mut current = *root;
        'path: for name in split_path(path) {
            let id = if let FileType::Link { target } = self.find(&current)?.file_type() {
                target
            } else {
                current
            };
            'child: for child in self.children(&id)? {
                if self.calculate_deleted(&child)? {
                    continue 'child;
                }

                if self.name_using_links(&child, account)? == name {
                    current = match self.find(&child)?.file_type() {
                        FileType::Link { target } => target,
                        _ => child,
                    };

                    continue 'path;
                }
            }

            return Err(SharedErrorKind::FileNonexistent.into());
        }

        Ok(current)
    }

    pub fn id_to_path(&mut self, id: &Uuid, account: &Account) -> SharedResult<String> {
        let meta = self.find(id)?;

        if meta.is_root() {
            return Ok("/".to_string());
        }

        let mut path = match meta.file_type() {
            FileType::Document => "",
            FileType::Folder => "/",
            FileType::Link { target } => match self.find(&target)?.file_type() {
                FileType::Document | FileType::Link { .. } => "",
                FileType::Folder => "/",
            },
        }
        .to_string();

        let mut current = *meta.id();
        loop {
            let current_meta = if let Some(link) = self.linked_by(&current)? {
                self.find(&link)?
            } else {
                self.find(&current)?
            };
            if self.maybe_find(current_meta.parent()).is_none() {
                return Err(SharedErrorKind::FileParentNonexistent.into());
            }
            if current_meta.is_root() {
                return Ok(path);
            }
            let next = *current_meta.parent();
            let current_name = self.name_using_links(&current, account)?;
            path = format!("/{}{}", current_name, path);
            current = next;
        }
    }

    pub fn list_paths(
        &mut self, filter: Option<Filter>, account: &Account,
    ) -> SharedResult<Vec<String>> {
        // Deal with filter
        let filtered = match filter {
            Some(Filter::DocumentsOnly) => {
                let mut ids = HashSet::new();
                for id in self.ids() {
                    if self.find(id)?.is_document() {
                        ids.insert(*id);
                    }
                }
                ids
            }
            Some(Filter::FoldersOnly) => {
                let mut ids = HashSet::new();
                for id in self.ids() {
                    if self.find(id)?.is_folder() {
                        ids.insert(*id);
                    }
                }
                ids
            }
            Some(Filter::LeafNodesOnly) => {
                let mut retained = self.owned_ids();
                for id in self.ids() {
                    retained.remove(self.find(id)?.parent());
                }
                retained
            }
            None => self.owned_ids(),
        };

        // remove deleted; include links not linked files
        let mut paths = vec![];
        for id in filtered.clone() {
            let id = match self.linked_by(&id)? {
                None => id,
                Some(link) => {
                    if filtered.contains(&link) {
                        continue;
                    }
                    link
                }
            };

            if !self.calculate_deleted(&id)? && !self.in_pending_share(&id)? {
                paths.push(self.id_to_path(&id, account)?);
            }
        }

        Ok(paths)
    }
}

impl<Base, Local> LazyStaged1<Base, Local>
where
    Base: TreeLike<F = SignedFile>,
    Local: TreeLikeMut<F = Base::F>,
{
    pub fn create_link_at_path(
        &mut self, path: &str, target_id: Uuid, root: &Uuid, account: &Account, pub_key: &PublicKey,
    ) -> SharedResult<Uuid> {
        validate::path(path)?;
        let file_type = FileType::Link { target: target_id };
        let path_components = split_path(path);
        self.create_at_path_helper(file_type, path_components, root, account, pub_key)
    }

    pub fn create_at_path(
        &mut self, path: &str, root: &Uuid, account: &Account, pub_key: &PublicKey,
    ) -> SharedResult<Uuid> {
        validate::path(path)?;
        let file_type = if path.ends_with('/') { FileType::Folder } else { FileType::Document };
        let path_components = split_path(path);
        self.create_at_path_helper(file_type, path_components, root, account, pub_key)
    }

    fn create_at_path_helper(
        &mut self, file_type: FileType, path_components: Vec<&str>, root: &Uuid, account: &Account,
        pub_key: &PublicKey,
    ) -> SharedResult<Uuid> {
        let mut current = *root;

        'path: for index in 0..path_components.len() {
            'child: for child in self.children(&current)? {
                if self.calculate_deleted(&child)? {
                    continue 'child;
                }

                if self.name_using_links(&child, account)? == path_components[index] {
                    if index == path_components.len() - 1 {
                        return Err(SharedErrorKind::PathTaken.into());
                    }

                    current = match self.find(&child)?.file_type() {
                        FileType::Document => {
                            return Err(SharedErrorKind::FileNotFolder.into());
                        }
                        FileType::Folder => child,
                        FileType::Link { target } => {
                            let current = self.find(&target)?;
                            if current.access_mode(&Owner(*pub_key)) < Some(UserAccessMode::Write) {
                                return Err(SharedErrorKind::InsufficientPermission.into());
                            }
                            *current.id()
                        }
                    };
                    continue 'path;
                }
            }

            // Child does not exist, create it
            let this_file_type =
                if index != path_components.len() - 1 { FileType::Folder } else { file_type };

            current = self.create(
                Uuid::new_v4(),
                symkey::generate_key(),
                &current,
                path_components[index],
                this_file_type,
                account,
            )?;
        }

        Ok(current)
    }
}

#[derive(Debug)]
pub enum Filter {
    DocumentsOnly,
    FoldersOnly,
    LeafNodesOnly,
}

fn split_path(path: &str) -> Vec<&str> {
    path.split('/')
        .collect::<Vec<&str>>()
        .into_iter()
        .filter(|s| !s.is_empty()) // Remove the trailing empty element in the case this is a folder
        .collect::<Vec<&str>>()
}