lockbook 26.9.18

CLI for interacting with your lockbook.net. Use your favorite text editor to edit your notes!
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
mod account;
mod debug;
mod edit;
mod imex;
mod input;
mod lb_fs;
mod list;
mod migrate;
mod share;
mod stream;

use std::env;
use std::path::PathBuf;
use std::str::FromStr;

use account::ApiUrl;
use cli_rs::arg::Arg;
use cli_rs::cli_error::{CliError, CliResult, Exit};
use cli_rs::command::Command;
use cli_rs::flag::Flag;
use cli_rs::parser::Cmd;
use colored::Colorize;
use input::find_file;
use lb_rs::model::core_config::Config;
use lb_rs::model::errors::LbErrKind;
use lb_rs::model::path_ops::Filter;
use lb_rs::service::events::{Event, SyncIncrement};
use lb_rs::{Lb, Uuid};

fn run() -> CliResult<()> {
    Command::name("lockbook")
        .description("The private, polished note-taking platform.")
        .version(env!("CARGO_PKG_VERSION"))
        .subcommand(
            Command::name("account")
                .description("account management commands")
                .subcommand(
                    Command::name("new")
                        .input(Arg::str("username").description("your desired username."))
                        .input(Flag::<ApiUrl>::new("api_url")
                            .description("location of the lockbook server you're trying to use. If not provided will check the API_URL env var, and then fall back to https://app.lockbook.net"))
                        .handler(|username, api_url| {
                            account::new(username.get(), api_url.get())
                        })
                )
                .subcommand(
                    Command::name("import").description("import an existing account from a key or phrase")
                        .input(Flag::<ApiUrl>::new("api_url")
                        .description("location of the lockbook server you're trying to use. If not provided will check the API_URL env var, and then fall back to https://app.lockbook.net"))

                        .handler(|api_url| {
                            account::import(api_url.get())
                        })
                )
                .subcommand(
                    Command::name("export").description("reveal your account key or account phrase")
                        .input(Flag::bool("skip-check").description("don't ask for confirmation to reveal the secret"))
                        .input(Flag::bool("phrase").description("export the 24-word account phrase instead of the compact account key"))
                        .handler(|skip_check, phrase| account::export(skip_check.get(), phrase.get()))
                )
                .subcommand(
                    Command::name("subscribe").description("start a monthly subscription for massively increased storage")
                        .handler(account::subscribe)
                )
                .subcommand(
                    Command::name("unsubscribe").description("cancel an existing subscription")
                        .handler(account::unsubscribe)
                )
                .subcommand(
                    Command::name("status").description("show your account status")
                        .handler(account::status)
                )
        )
        .subcommand(
            Command::name("import").description("import files from your file system into lockbook")
                .input(Arg::<PathBuf>::name("disk-path").description("path of file on disk"))
                .input(Arg::str("dest")
                       .description("the path or id of a folder within lockbook to place the file.")
                       .completor(|prompt| input::file_completor(prompt, Some(Filter::FoldersOnly))))
                .handler(|disk, parent| imex::import(disk.get(), parent.get()))
        )
        .subcommand(
            Command::name("debug").description("investigative commands")
                .subcommand(
                    Command::name("validate").description("helps find invalid states within your lockbook")
                        .handler(debug::validate)
                )
                .subcommand(
                    Command::name("info").description("print metadata associated with a file")
                        .input(Arg::str("target").description("id or path of file to debug")
                            .completor(|prompt| input::file_completor(prompt, None)))
                        .handler(|target| debug::info(target.get()))
                )
                .subcommand(
                    Command::name("whoami").description("print who is logged into this lockbook")
                        .handler(debug::whoami)
                )
                .subcommand(
                    Command::name("whereami").description("print information about where this lockbook is stored and it's server url")
                        .handler(debug::whereami)
                )
                .subcommand(
                    Command::name("debuginfo").description("retrieve the debug-info string to help a lockbook engineer diagnose a problem")
                        .handler(debug::debug_info)
                )
        )
        .subcommand(
            Command::name("delete").description("delete a file")
                .input(Flag::bool("force"))
                .input(Arg::str("target").description("path of id of file to delete")
                            .completor(|prompt| input::file_completor(prompt, None)))
                .handler(|force, target| delete(force.get(), target.get()))
        )
        .subcommand(
            Command::name("duplicate").description("duplicate a document in place (same folder, auto-named copy)")
                .input(Arg::str("target").description("path or id of document to duplicate")
                            .completor(|prompt| input::file_completor(prompt, None)))
                .handler(|target| duplicate(target.get()))
        )
        .subcommand(
            Command::name("edit").description("edit a document")
                .input(edit::editor_flag())
                .input(Arg::str("target").description("path or id of file to edit")
                            .completor(|prompt| input::file_completor(prompt, None)))
                .handler(|editor, target| edit::edit(editor.get(), target.get()))
        )
        .subcommand(
            Command::name("export").description("export a lockbook file to your file system")
                .input(Arg::str("target")
                            .completor(|prompt| input::file_completor(prompt, None)))
                .input(Arg::<PathBuf>::name("dest").description("directory, or file path when exporting a single document"))
                .input(Flag::bool("force").description("overwrite existing files on disk"))
                .input(Flag::bool("contents").description("when exporting a folder, place its children in dest (rsync src/ semantics) instead of dest/<folder-name>"))
                .handler(|target, dest, force, contents| {
                    imex::export(target.get(), dest.get(), force.get(), contents.get())
                })
        )
        .subcommand(
            Command::name("fs")
                .description("use your lockbook files with your local filesystem by mounting an NFS drive to /tmp/lockbook")
                .handler(lb_fs::mount)
        )
        .subcommand(
            Command::name("list").description("list files and file information")
                .input(Flag::bool("long").description("long listing: id, type, size, modified time, and share info (short: -l)"))
                .input(Flag::bool("recursive").description("include all children recursively; implies --paths (short: -r/-R)"))
                .input(Flag::bool("paths").description("display the full path of each entry (short: -p)"))
                .input(Arg::str("target").description("file path location whose files will be listed")
                            .completor(|prompt| input::file_completor(prompt, Some(Filter::FoldersOnly)))
                            .default("/".to_string()))
                .handler(|long, recur, paths, target| list::list(long.get(), recur.get(), paths.get(), target.get()))
        )
        .subcommand(
            Command::name("move").description("move a file to a new parent")
                .input(Arg::str("src-target").description("lockbook file path or ID of the file to move")
                            .completor(|prompt| input::file_completor(prompt, None)))
                .input(Arg::str("dest").description("lockbook file path or ID of the new parent folder")
                            .completor(|prompt| input::file_completor(prompt, Some(Filter::FoldersOnly))))
                .handler(|src, dst| move_file(src.get(), dst.get()))
        )
        .subcommand(
            Command::name("new").description("create a new file at the given path or do nothing if it exists")
                .input(Arg::str("path").description("create a new file at the given path or do nothing if it exists")
                            .completor(|prompt| input::file_completor(prompt, Some(Filter::FoldersOnly))))
                .handler(|target| create_file(target.get()))
        )
        .subcommand(
            Command::name("cat")
                .description("print a document to stdout")
                .input(Arg::str("target").description("lockbook file path or ID")
                    .completor(|prompt| input::file_completor(prompt, None)))
                .handler(|target| stream::stdout(target.get()))
        )
        .subcommand(
            Command::name("write")
                .description("write stdin to a document, creating it if it does not exist")
                .input(Arg::str("target").description("lockbook file path or ID")
                    .completor(|prompt| input::file_completor(prompt, None)))
                .input(Flag::bool("append").description("don't overwrite the specified lb file, append to it"))
                .handler(|target, append| stream::stdin(target.get(), append.get()))
        )
        .subcommand(
            Command::name("rename").description("rename a file")
                .input(Arg::str("target").description("lockbook file path or ID of file to rename")
                            .completor(|prompt| input::file_completor(prompt, None)))
                .input(Arg::str("new_name"))
                .handler(|target, new_name| rename(target.get(), new_name.get()))
        )
        .subcommand(
            Command::name("share").description("sharing related commands")
                .subcommand(
                    Command::name("new").description("share a file with someone")
                        .input(Arg::str("target").description("lockbook file path or ID of file to rename")
                            .completor(|prompt| input::file_completor(prompt, None)))
                        .input(Arg::str("username")
                            .completor(input::username_completor))
                        .input(Flag::bool("read-only"))
                        .handler(|target, username, ro| share::new(target.get(), username.get(), ro.get()))
                )
                .subcommand(
                    Command::name("pending").description("list pending shares")
                        .handler(share::pending)
                )
                .subcommand(
                    Command::name("accept").description("accept a pending share by adding it to your file tree")
                        .input(Arg::<Uuid>::name("pending-share-id").description("ID of pending share")
                                    .completor(share::pending_share_completor))
                        .input(Arg::str("target").description("lockbook file path or ID of the folder you want to place this shared file")
                            .completor(|prompt| input::file_completor(prompt, Some(Filter::FoldersOnly))))
                        .handler(|id, dest| share::accept(&id.get(), dest.get()))
                )
                .subcommand(
                    Command::name("delete").description("delete a pending share")
                        .input(Arg::<Uuid>::name("share-id").description("ID of pending share to delete")
                               .completor(share::pending_share_completor))
                        .handler(|target| share::delete(target.get()))
                )
        )
        .subcommand(
            Command::name("search").description("search file paths and document contents")
                .input(Arg::str("query"))
                .handler(|query| search(&query.get()))
        )
        .subcommand(
            Command::name("migrate-from").description("transfer files from an existing platform")
                .subcommand(
                    Command::name("bear").description("migrate your files from https://bear.app/ Export as md and using the 'export attachments' option.")
                        .input(Arg::<PathBuf>::name("disk-path").description("location of a bear export of files."))
                        .handler(|path| migrate::bear(path.get()))
                )
        )
        .subcommand(
            Command::name("sync").description("sync your local changes back to lockbook servers") // todo also back
                .handler(sync)
        )
        .with_completions()
        .parse()
}

fn main() {
    run().exit();
}

pub async fn core() -> CliResult<Lb> {
    Lb::init(Config::cli_config("cli"))
        .await
        .map_err(|err| CliError::from(err.to_string()))
}

fn search(query: &str) -> CliResult<()> {
    let lb = lb_rs::blocking::Lb::init(Config::cli_config("cli"))
        .map_err(|err| CliError::from(err.to_string()))?;
    lb.get_account()
        .map_err(|err| CliError::from(err.to_string()))?;

    let mut path_searcher = lb.path_searcher();
    path_searcher.query(query);
    let path_results = path_searcher.results();

    println!("{}", "Files".bold().underline());
    if path_results.is_empty() {
        println!("  no matches");
    }
    for result in path_results.iter().take(10) {
        println!("  {}", full_path(&result.parent_path, &result.filename).green());
    }
    println!();

    let mut content_searcher = lb.content_searcher();
    content_searcher.query(query);
    let content_results = content_searcher.results();

    println!("{}", "Content".bold().underline());
    if content_results.is_empty() {
        println!("  no matches");
    }
    for result in content_results.iter().take(10) {
        println!(
            "  {}",
            full_path(&result.parent_path, &result.filename)
                .bold()
                .blue()
        );
        for content_match in result.content_matches.iter().take(3) {
            if let Some((prefix, matched, suffix)) =
                content_searcher.snippet(result.id, &content_match.range, 40)
            {
                println!(
                    "    …{}{}{}…",
                    one_line(prefix),
                    one_line(matched).underline(),
                    one_line(suffix)
                );
            }
        }
    }

    Ok(())
}

fn full_path(parent_path: &str, filename: &str) -> String {
    if parent_path == "/" || parent_path.is_empty() {
        format!("/{filename}")
    } else {
        format!("{parent_path}/{filename}")
    }
}

fn one_line(s: &str) -> String {
    s.chars()
        .map(|c| if c == '\n' || c == '\r' { ' ' } else { c })
        .collect()
}

#[tokio::main]
async fn sync() -> CliResult<()> {
    let lb = &core().await?;
    ensure_account(lb)?;
    let mut receiver = lb.subscribe();

    let monitor_lb = lb.clone();
    let monitor = tokio::spawn(async move {
        let get_name = async |id| {
            monitor_lb
                .get_file_by_id(id)
                .await
                .map(|file| file.name)
                .unwrap_or(format!("{id} (new file)"))
        };

        loop {
            let event = receiver.recv().await.unwrap();
            if let Event::Sync(sync_increment) = event {
                match sync_increment {
                    SyncIncrement::SyncStarted => println!("Sync Started!"),
                    SyncIncrement::PullingDocument(uuid, true) => {
                        println!("Downloading {}", get_name(uuid).await)
                    }
                    SyncIncrement::PullingDocument(uuid, false) => {
                        println!("Downloaded {}", get_name(uuid).await)
                    }
                    SyncIncrement::PushingDocument(uuid, true) => {
                        println!("Uploading {}", get_name(uuid).await)
                    }
                    SyncIncrement::PushingDocument(uuid, false) => {
                        println!("Uploaded {}", get_name(uuid).await)
                    }
                    SyncIncrement::SyncFinished(lb_err_kind) => {
                        match lb_err_kind {
                            Some(err) => eprintln!("Sync completed with an error: {err}"),
                            None => println!("Sync successful"),
                        };
                        return;
                    }
                }
            }
        }
    });

    lb.sync().await?;
    monitor.await?;
    Ok(())
}

#[tokio::main]
async fn delete(force: bool, target: String) -> Result<(), CliError> {
    let lb = &core().await?;
    ensure_account_and_root(lb).await?;

    let f = find_file(lb, &target).await?;

    if !force {
        let mut phrase = format!("delete '{target}'");

        if f.is_folder() {
            let count = lb
                .get_and_get_children_recursively(&f.id)
                .await
                .unwrap_or_default()
                .len() as u64
                - 1;
            match count {
                0 => {}
                1 => phrase = format!("{phrase} and its 1 child"),
                _ => phrase = format!("{phrase} and its {count} children"),
            };
        }

        let answer: String = input::std_in(format!("are you sure you want to {phrase}? [y/n]: "))?;
        if answer != "y" && answer != "Y" {
            println!("aborted.");
            return Ok(());
        }
    }

    lb.delete(&f.id).await?;
    Ok(())
}

#[tokio::main]
async fn move_file(src: String, dest: String) -> CliResult<()> {
    let lb = &core().await?;
    ensure_account_and_root(lb).await?;

    let src = find_file(lb, &src).await?;
    let dest = find_file(lb, &dest).await?;
    lb.move_file(&src.id, &dest.id).await?;
    Ok(())
}

#[tokio::main]
async fn create_file(path: String) -> CliResult<()> {
    let lb = &core().await?;
    ensure_account_and_root(lb).await?;

    if Uuid::from_str(&path).is_ok() {
        return Err(CliError::from("cannot create a file using ids"));
    }

    match lb.get_by_path(&path).await {
        Ok(_f) => Ok(()),
        Err(err) => match err.kind {
            LbErrKind::FileNonexistent => match lb.create_at_path(&path).await {
                Ok(_f) => Ok(()),
                Err(err) => Err(err.into()),
            },
            _ => Err(err.into()),
        },
    }
}

#[tokio::main]
async fn rename(target: String, new_name: String) -> Result<(), CliError> {
    let lb = &core().await?;
    ensure_account_and_root(lb).await?;

    let id = find_file(lb, &target).await?.id;
    lb.rename_file(&id, &new_name).await?;
    Ok(())
}

#[tokio::main]
async fn duplicate(target: String) -> CliResult<()> {
    let lb = &core().await?;
    ensure_account_and_root(lb).await?;

    let f = find_file(lb, &target).await?;
    let copy = lb.duplicate_file(&f.id).await?;
    let path = lb.get_path_by_id(copy.id).await?;
    println!("duplicated to {path}");
    Ok(())
}

fn ensure_account(lb: &Lb) -> CliResult<()> {
    if let Err(e) = lb.get_account() {
        if e.kind == LbErrKind::AccountNonexistent {
            return Err(CliError::from("no account found, run lockbook account import"));
        }
    }

    Ok(())
}

async fn ensure_account_and_root(lb: &Lb) -> CliResult<()> {
    ensure_account(lb)?;
    if let Err(e) = lb.root().await {
        if e.kind == LbErrKind::RootNonexistent {
            return Err(CliError::from("no root found, have you synced yet?"));
        }
    }

    Ok(())
}