1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 //! This file implements de file operations.
17 
18 use asset_definition::{log_throw_error, ErrCode, Result};
19 use asset_log::logi;
20 use std::{fs, path::Path};
21 
22 use crate::common::{get_user_dbs, is_file_exist};
23 
construct_user_de_path(user_id: i32) -> String24 fn construct_user_de_path(user_id: i32) -> String {
25     format!("data/service/el1/public/asset_service/{}", user_id)
26 }
27 
is_user_de_dir_exist(user_id: i32) -> Result<bool>28 fn is_user_de_dir_exist(user_id: i32) -> Result<bool> {
29     let path_str = construct_user_de_path(user_id);
30     is_file_exist(&path_str)
31 }
32 
33 /// Create user de directory.
create_user_de_dir(user_id: i32) -> Result<()>34 pub fn create_user_de_dir(user_id: i32) -> Result<()> {
35     if is_user_de_dir_exist(user_id)? {
36         return Ok(());
37     }
38 
39     logi!("[INFO]User DE directory does not exist, create it...");
40     let path_str = construct_user_de_path(user_id);
41     let path: &Path = Path::new(&path_str);
42     match fs::create_dir(path) {
43         Ok(_) => Ok(()),
44         Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
45         Err(e) => {
46             log_throw_error!(
47                 ErrCode::FileOperationError,
48                 "[FATAL][SA]Create user DE directory failed! error is [{}]",
49                 e
50             )
51         },
52     }
53 }
54 
55 /// Delete user de directory.
delete_user_de_dir(user_id: i32) -> Result<()>56 pub fn delete_user_de_dir(user_id: i32) -> Result<()> {
57     if !is_user_de_dir_exist(user_id)? {
58         return Ok(());
59     }
60 
61     let path_str = construct_user_de_path(user_id);
62     let path: &Path = Path::new(&path_str);
63     match fs::remove_dir_all(path) {
64         Ok(_) => Ok(()),
65         Err(e) if e.kind() != std::io::ErrorKind::NotFound => Ok(()),
66         Err(e) => {
67             log_throw_error!(
68                 ErrCode::FileOperationError,
69                 "[FATAL][SA]Delete user DE directory failed! error is [{}]",
70                 e
71             )
72         },
73     }
74 }
75 
76 /// Obtain de user dbs
get_de_user_dbs(user_id: i32) -> Result<Vec<String>>77 pub fn get_de_user_dbs(user_id: i32) -> Result<Vec<String>> {
78     get_user_dbs(&construct_user_de_path(user_id))
79 }
80