diff options
Diffstat (limited to 'notes_cli.js')
-rwxr-xr-x | notes_cli.js | 158 |
1 files changed, 112 insertions, 46 deletions
diff --git a/notes_cli.js b/notes_cli.js index be427d8..46acde1 100755 --- a/notes_cli.js +++ b/notes_cli.js @@ -1,24 +1,18 @@ const fs = require('fs') const { homedir } = require('os') - -let conf - const https = require('https') const readline = require("readline") -// const spawn = require('child_process').spawn +const spawn = require('child_process').spawn const rl = readline.createInterface({ input: process.stdin, output: process.stdout }) +let conf, notesList = [], active = 0; scroll = 0; draw = { t: 'p', v: () => ['Loading NOTES CLI...'] } const cl = (m, c) => console.log(c ? `\x1b[${c}m${m}\x1b[0m` : m) const cls = () => console.clear() - -const configPath = `${homedir}/.local/share/notes_cli` - -// app view -let active = 0; scroll = 0; draw = { t: 'p', v: () => ['Loading NOTES CLI...'] }, headers = () => '' +const filesPath = `${homedir}/.local/share/notes_cli` const pr = t => process.stdout.write(t) const cursor = { hide: () => pr('\u001B[?25l'), @@ -41,27 +35,90 @@ const showList = (notes, status) => { cls() return login('Session error') } - headers = () => { - const columns = process.stdout.columns - return columns > 72 - ? `${fixedStr(' Title', columns - 44)} Created at${' '.repeat(10)} Updated at ${' '.repeat(9)}` - : ` Title ${' '.repeat(columns - 9)}` - } + + notesList = notes cursor.hide() + drawApp() process.stdout.on('resize', drawApp); draw = { t: 'l', v: () => notes.map(formatNote) } - drawApp() getKey() } +const saveTmpFile = (note, { content }) => { + const file = `${filesPath}/${note._id}.tmp` + fs.writeFile(file, JSON.stringify(content), function(err) { + if(err) { + cl(err, 32) + cl('Error creating tmp file', 32) + return null + } + + return editTmpFile(note) + }) +} + +const readTmpFile = (note) => { + const file =`${filesPath}/${note._id}.tmp` + fs.readFile(file, function(err, f){ + if (err) { + return login() + } + + try { + const content = JSON.parse(f.toString()) + + fs.unlink(file, () => {}) + + if (!content) { + return login('Error saving note') + } + + putNote(note, content) + } catch (e) { + return login('Session error') + } + }) +} + +const noteSaved = () => { + drawApp() + cursor.hide() + rl.resume() + fetchList() +} + +const editTmpFile = (note) => { + const file = `${filesPath}/${note._id}.tmp` + const child_process = require('child_process') + const editor = process.env.EDITOR || 'vi'; + rl.pause() + cursor.show() + const child = child_process.spawn(editor, [file], { stdio: 'inherit' }); + child.on('exit', function (e) { + if (e === 0) { + draw = { t: 'p', v: () => ['Saving changes...'] } + readTmpFile(note) + } else { + draw = { t: 'p', v: () => ['Changes not saved'] } + fs.unlink(file, () => {}) + drawApp() + cursor.hide() + rl.resume() + fetchList() + } + }); +} // =========== DRAW APP ============= const drawApp = () => { const lines = process.stdout.rows const columns = process.stdout.columns - // process.stdout.write('\x1Bc') + const headers = columns > 72 + ? `${fixedStr(' Title', columns - 44)} Created at${' '.repeat(10)} Updated at ${' '.repeat(9)}` + : ` Title ${' '.repeat(columns - 9)}` + cls() for (var i = 0; i < lines - 1; i++) { const dist = t => columns > t + 2 ? [Math.floor((columns - t) / 2), Math.ceil((columns - t) / 2) - 2] : [0, 0] @@ -76,8 +133,7 @@ const drawApp = () => { pr('╠'+'═'.repeat(columns - 2) +'╣') break case 3: - const h = headers() - pr('║'+(h || ' '.repeat(columns-2))+'║') + pr('║'+(headers || ' '.repeat(columns-2))+'║') break case 4: pr('╟'+'─'.repeat(columns - 2) +'╢') @@ -144,14 +200,11 @@ const getKey = () => { break case 'return': case 'o': - draw = { t: 'p', v: () => ['popup test', '', `This will display note nr ${active + 1}.`] } - drawApp() - // process.stdout.write(draw.v[active]); - // openNote(active) + fetchNote(notesList[active]) break case 'q': cursor.show() - console.clear() + cls() pr('Bye!\n\n') process.exit() default: @@ -159,14 +212,17 @@ const getKey = () => { }) } +/* Session */ -/* Configuration */ +const setSession = (c, callback) => { + if (!fs.existsSync(filesPath)){ + fs.mkdirSync(filesPath, { recursive: true }); + } -const setConf = (c, callback) => { - fs.writeFile(configPath, JSON.stringify(c), function(err) { + fs.writeFile(`${filesPath}/session`, JSON.stringify(c), function(err) { if(err) { cl(err, 32) - cl('Error writting configuration file', 32) + cl('Error writting session file', 32) return null } @@ -175,22 +231,22 @@ const setConf = (c, callback) => { }) } -const getConf = () => { - fs.readFile(configPath, function(err, f){ +const getSession = () => { + fs.readFile(`${filesPath}/session`, function(err, f){ if (err) { return login() } try { - const r = JSON.parse(f.toString()) + conf = JSON.parse(f.toString()) - if (!r.session || !r.userId || !r.email || !r.list) { - return login('Error parsing configuration') + if (!conf.session || !conf.userId || !conf.email || !conf.list) { + return login('Session error') } - fetchList(r) + fetchList() } catch (e) { - return login('Error reading configuration') + return login('Session error') } }) } @@ -250,10 +306,8 @@ const login = (error = '') => { const c = {userId: _id, email, list: noteList, session} - setConf(c, () => { - cl('Successfully saved configuration', 32) - cl('saved config: ', conf) - }) + rl.resume() + setSession(c, getSession) }) }) @@ -270,12 +324,20 @@ const login = (error = '') => { /* API */ -const fetchList = config => { - conf = config - drawApp() +const fetchList = () => { get('/api/notes', showList, conf.session) } +const fetchNote = note => { + draw = { t: 'p', v: () => ['Loading...'] } + drawApp() + get(`/api/notes/${note.noteId}`, (content) => saveTmpFile(note, content), conf.session) +} + +const putNote = ({ _id, noteId }, content) => { + put(`/api/notes/${_id}`, { noteId, content }, noteSaved, conf.session) +} + /* HTTPS METHODS */ const get = (path, callback, cookie = '') => { @@ -306,14 +368,16 @@ const get = (path, callback, cookie = '') => { req.end(); } -const post = (path, data, callback, cookie = '') => { +const post = (path, data, callback, cookie = '', put = false) => { const dataString = JSON.stringify(data) const options = { hostname: 'apps.pruss.it', port: 443, path, - method: 'POST', - headers: { + method: put ? 'PUT' : 'POST', + headers: put ? { + 'Cookie': cookie, + } : { 'Content-Type': 'application/json', 'Content-Length': dataString.length, 'Cookie': cookie, @@ -337,5 +401,7 @@ const post = (path, data, callback, cookie = '') => { req.end(); } +const put = (...arg) => post(...arg, true) + cls() -getConf() +getSession() |