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};
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 client_type: ClientType::Cli,
36 };
37 logger::init();
38 lb_rs::service::logging::log_startup(&config);
39 let lb = Lb::init(config).await.unwrap();
40
41 let root = lb.root().await.map(|file| file.id).unwrap_or(Uuid::nil());
42
43 let data = Arc::default();
44
45 let fs = Self { lb, root, data };
46 fs.clone().monitor_lb().await;
47
48 fs
49 }
50
51 pub async fn import() -> CliResult<()> {
52 let drive = Self::init().await;
53
54 if io::stdin().is_terminal() {
55 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()));
56 }
57
58 let mut account_string = String::new();
59 io::stdin()
60 .read_line(&mut account_string)
61 .expect("failed to read from stdin");
62 account_string.retain(|c| !c.is_whitespace());
63
64 println!("importing account...");
65 drive
66 .lb
67 .import_account(&account_string, None)
68 .await
69 .unwrap();
70
71 drive.lb.sync().await.unwrap();
72
73 Ok(())
74 }
75
76 pub async fn mount() -> CliResult<()> {
77 let drive = Self::init().await;
78 drive.lb.sync().await.unwrap();
79 drive.fill_cache().await;
80 info!("registering sig handler");
81
82 tokio::spawn(async move {
84 tokio::signal::ctrl_c().await.unwrap();
85 let mut unmount_success = umount().await;
86 while !unmount_success {
87 error!("unmount failed, please close any apps using lb-fs! Retrying in 1s.");
88 time::sleep(Duration::from_secs(1)).await;
89 unmount_success = umount().await;
90 }
91 info!("cleaned up, goodbye!");
92 exit(0);
93 });
94
95 let syncer = drive.clone();
97 tokio::spawn(async move {
98 loop {
99 info!("will sync in 30 seconds");
100 tokio::time::sleep(Duration::from_secs(30)).await;
101 info!("syncing");
102 syncer.lb.sync().await.map_unexpected().log_and_ignore();
103 }
104 });
105
106 let event_handler = drive.clone();
108 tokio::spawn(async move {
109 let mut events = event_handler.lb.subscribe();
110 loop {
111 let event = events.recv().await.unwrap();
112
113 match event {
125 Event::MetadataChanged(Actor::Sync) | Event::IpcChangesApplied => {
126 event_handler.fill_cache().await;
127 }
128 Event::DocumentWritten(dirty_id, Actor::Sync) => {
129 let file = event_handler.lb.get_file_by_id(dirty_id).await.unwrap();
130 let size = if file.is_document() {
131 event_handler
132 .lb
133 .read_document(dirty_id, false)
134 .await
135 .unwrap()
136 .len()
137 } else {
138 0
139 };
140
141 let mut entry = FileEntry::from_file(file, size as u64);
142
143 let now = FileEntry::now();
144
145 entry.fattr.mtime = now;
146 entry.fattr.ctime = now;
147
148 event_handler
149 .data
150 .lock()
151 .await
152 .insert(entry.file.id.into(), entry);
153 }
154 _ => {}
155 }
156 }
157 });
158
159 info!("creating server");
161 let listener = NFSTcpListener::bind("127.0.0.1:11111", drive)
162 .await
163 .unwrap();
164
165 info!("mounting");
166 mount();
167
168 info!("ready");
169 listener.handle_forever().await.unwrap();
170 Ok(())
171 }
172
173 async fn monitor_lb(self) {
174 tokio::spawn(async move {
175 let mut sub = self.lb.subscribe();
176 loop {
177 if let Event::Sync(sync_increment) = sub.recv().await.unwrap() {
178 debug!("syncing: {sync_increment:?}")
179 }
180 }
181 });
182 }
183}