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
use super::cmd::{create, delete, insert, select};
use super::sql;
use rusqlite::Connection;

use super::ssb;
use super::Cmd;
use super::CmdDelete;
use super::CmdInsert;
use super::CmdSearch;
use super::CmdSelect;
use super::Note;

extern crate serde_json;
extern crate time;

pub fn run(text: &str) -> String {
    if let Ok(cmd) = serde_json::from_str::<Cmd>(text) {
        process(cmd, text)
    } else {
        r#"{"error": "cmd json error"}"#.to_string()
    }
}

fn process(cmd: Cmd, text: &str) -> String {
    eprintln!("process cmd {:?}", cmd);
    let conn = ssb::get_sqlite_connection();
    create(&conn);

    match cmd.action.as_ref() {
        "insert" => {
            if let Ok(i) = serde_json::from_str::<CmdInsert>(text) {
                let created_at =
                    time::strftime("%Y-%m-%d %H:%M:%S:%f UTC", &time::now_utc()).unwrap();
                //eprintln!("created_at {}", created_at);
                let note = Note {
                    rowid: 0i64,
                    title: i.title,
                    url: i.url,
                    tags: i.tags,
                    description: i.description,
                    comments: i.comments,
                    annotations: i.annotations,
                    created_at,
                };
                insert(&conn, note);
                // make insert the only place with ssb dependency
                ssb::run_sync(&conn);
                // end ssb dependency
                do_select(&conn, &sql::select(i.limit, i.offset))
            } else {
                r#"{"error":"cmd insert json error"}"#.to_string()
            }
        }
        "delete" => {
            if let Ok(s) = serde_json::from_str::<CmdDelete>(text) {
                delete(&conn, s.rowid);
                do_select(&conn, &sql::search(s.limit, s.offset, &s.query))
            } else {
                r#"{"error":"cmd delete json error"}"#.to_string()
            }
        }
        "select" => {
            if let Ok(s) = serde_json::from_str::<CmdSelect>(text) {
                do_select(&conn, &sql::select(s.limit, s.offset))
            } else {
                r#"{"error":"cmd select json error"}"#.to_string()
            }
        }
        "search" => {
            if let Ok(s) = serde_json::from_str::<CmdSearch>(text) {
                do_select(&conn, &sql::search(s.limit, s.offset, &s.query))
            } else {
                r#"{"error":"cmd search json error"}"#.to_string()
            }
        }
        _ => r#"{"error": "cmd no match"}"#.to_string(),
    }
}

fn do_select(conn: &Connection, sql: &str) -> String {
    let j = select(&conn, sql);
    let msg = format!("{{\"notes\":{}}}", j);
    eprintln!("msg {}", msg);
    msg
}