1use crate::cache::FileEntry;
2use crate::fs_impl::Drive;
3use crate::mount::{mount, umount};
4use cli_rs::cli_error::{CliError, CliResult};
5use lb_rs::model::core_config::{ClientType, Config, host_os_version};
6use lb_rs::model::errors::Unexpected;
7use lb_rs::service::events::{Actor, Event};
8use lb_rs::{Lb, Uuid};
9use nfs3_server::tcp::{NFSTcp, NFSTcpListener};
10use std::io;
11use std::io::IsTerminal;
12use std::process::exit;
13use std::sync::Arc;
14use std::time::Duration;
15use tokio::time;
16use tracing::{debug, error, info};
17
18pub mod cache;
19pub(crate) mod file_handle;
20pub mod fs_impl;
21pub mod logger;
22pub mod mount;
23pub mod utils;
24
25impl Drive {
26 pub async fn init() -> Self {
27 let config = Config {
28 writeable_path: Config::writeable_path("drive"),
29 background_work: false,
30 logs: false,
31 stdout_logs: false,
32 colored_logs: false,
33 client_name: "lb-fs".into(),
34 build_info: None,
35 os_version: host_os_version(),
36 client_type: ClientType::Cli,
37 ..Default::default()
38 };
39 logger::init();
40 lb_rs::service::logging::log_startup(&config);
41 let lb = Lb::init(config).await.unwrap();
42
43 let root = lb.root().await.map(|file| file.id).unwrap_or(Uuid::nil());
44
45 let data = Arc::default();
46
47 let fs = Self { lb, root, data };
48 fs.clone().monitor_lb().await;
49
50 fs
51 }
52
53 pub async fn import() -> CliResult<()> {
54 let drive = Self::init().await;
55
56 if io::stdin().is_terminal() {
57 return Err(CliError::from("to import an existing lockbook account, pipe your account string into this command, e.g.:\npbpaste | lb-fs import".to_string()));
58 }
59
60 let mut account_string = String::new();
61 io::stdin()
62 .read_line(&mut account_string)
63 .expect("failed to read from stdin");
64 account_string.retain(|c| !c.is_whitespace());
65
66 println!("importing account...");
67 drive
68 .lb
69 .import_account(&account_string, None)
70 .await
71 .unwrap();
72
73 drive.lb.sync().await.unwrap();
74
75 Ok(())
76 }
77
78 pub async fn mount() -> CliResult<()> {
79 let drive = Self::init().await;
80 drive.lb.sync().await.unwrap();
81 drive.fill_cache().await;
82 info!("registering sig handler");
83
84 tokio::spawn(async move {
86 tokio::signal::ctrl_c().await.unwrap();
87 let mut unmount_success = umount().await;
88 while !unmount_success {
89 error!("unmount failed, please close any apps using lb-fs! Retrying in 1s.");
90 time::sleep(Duration::from_secs(1)).await;
91 unmount_success = umount().await;
92 }
93 info!("cleaned up, goodbye!");
94 exit(0);
95 });
96
97 let syncer = drive.clone();
99 tokio::spawn(async move {
100 loop {
101 info!("will sync in 30 seconds");
102 tokio::time::sleep(Duration::from_secs(30)).await;
103 info!("syncing");
104 syncer.lb.sync().await.map_unexpected().log_and_ignore();
105 }
106 });
107
108 let event_handler = drive.clone();
110 tokio::spawn(async move {
111 let mut events = event_handler.lb.subscribe();
112 loop {
113 let event = events.recv().await.unwrap();
114
115 match event {
127 Event::MetadataChanged(Actor::Sync) | Event::IpcChangesApplied => {
128 event_handler.fill_cache().await;
129 }
130 Event::DocumentWritten(dirty_id, Actor::Sync) => {
131 let file = event_handler.lb.get_file_by_id(dirty_id).await.unwrap();
132 let size = if file.is_document() {
133 event_handler
134 .lb
135 .read_document(dirty_id, false)
136 .await
137 .unwrap()
138 .len()
139 } else {
140 0
141 };
142
143 let mut entry = FileEntry::from_file(file, size as u64);
144
145 let now = FileEntry::now();
146
147 entry.fattr.mtime = now;
148 entry.fattr.ctime = now;
149
150 event_handler
151 .data
152 .lock()
153 .await
154 .insert(entry.file.id.into(), entry);
155 }
156 _ => {}
157 }
158 }
159 });
160
161 info!("creating server");
163 let listener = NFSTcpListener::bind("127.0.0.1:11111", drive)
164 .await
165 .unwrap();
166
167 info!("mounting");
168 mount();
169
170 info!("ready");
171 listener.handle_forever().await.unwrap();
172 Ok(())
173 }
174
175 async fn monitor_lb(self) {
176 tokio::spawn(async move {
177 let mut sub = self.lb.subscribe();
178 loop {
179 if let Event::Sync(sync_increment) = sub.recv().await.unwrap() {
180 debug!("syncing: {sync_increment:?}")
181 }
182 }
183 });
184 }
185}