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
|
const fs = require('fs')
const { homedir } = require('os')
const https = require('https')
const readline = require("readline")
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 filesPath = `${homedir}/.local/share/notes_cli`
const pr = t => process.stdout.write(t)
const cursor = {
hide: () => pr('\u001B[?25l'),
show: () => pr('\u001B[?25h')
}
const fixedStr = (s, l) => s.length < l ? s.padEnd(l) : s.substring(0, l)
const formatDate = d => d.replace('T',' ').replace(/\..*Z/, '')
/* Views */
const formatNote = note => {
const columns = process.stdout.columns
return columns > 72
? `${fixedStr(note.title, columns - 45)} ${formatDate(note.created_at)} ${formatDate(note.updated_at)}`
: fixedStr(note.title, columns - note.title.length-2)
}
const showList = (notes, status) => {
if (status !== 200) {
cls()
return login('Session error')
}
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
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]
switch(i){
case 0:
pr('╔'+'═'.repeat(columns - 2)+'╗')
break
case 1:
pr('║'+' '.repeat(dist(conf.email.length+12)[0])+`NOTES CLI (${conf.email})`.substring(0, columns-2)+' '.repeat(dist(conf.email.length+12)[1])+'║')
break
case 2:
pr('╠'+'═'.repeat(columns - 2) +'╣')
break
case 3:
pr('║'+(headers || ' '.repeat(columns-2))+'║')
break
case 4:
pr('╟'+'─'.repeat(columns - 2) +'╢')
break
case lines - 3:
pr('╠'+'═'.repeat(columns - 2) +'╣')
break
case lines - 2:
const menu = '[Q]uit [↓/j] Down [↑/k] Up [Enter/o] Open'
pr('║'+' '+menu.substring(0,columns-4)+' '.repeat(columns-menu.length-3 > 0 ? columns-menu.length-3 : 1)+'║')
break
default:
const max = Math.max(...(draw.v().map(el => el.length)))
if (draw.t === 'p') {
if (i === (Math.floor((lines - draw.v().length) / 2) - 2)){
pr('║'+' '.repeat(dist(max+4)[0])+'┌'+'─'.repeat(max+2)+'┐'+' '.repeat(dist(max+4)[1])+'║')
} else if (i === (Math.floor((lines + draw.v().length) / 2) + 1)) {
pr('║'+' '.repeat(dist(max+4)[0])+'└'+'─'.repeat(max+2)+'┘'+' '.repeat(dist(max+4)[1])+'║')
} else if (i === (Math.floor((lines - draw.v().length) / 2) - 1) || i === (Math.floor((lines + draw.v().length) / 2))) {
pr('║'+' '.repeat(dist(max+4)[0])+'│'+' '.repeat(max+2)+'│'+' '.repeat(dist(max+4)[1])+'║')
} else if (i < (Math.floor((lines - draw.v().length) / 2) - 1) || (i > (Math.floor((lines + draw.v().length) / 2)))) {
pr('║'+' '.repeat(columns - 2)+'║')
} else {
const n = i - (Math.floor((lines - draw.v().length) / 2))
const t = draw.v()[n]
const s = [Math.floor((max+2-t.length) / 2), Math.ceil((max+2-t.length) / 2)]
pr('║'+' '.repeat(dist(max+4)[0])+'│'+' '.repeat(s[0])+t+' '.repeat(s[1])+'│'+' '.repeat(dist(max+4)[1])+'║')
}
} else if (draw.t === 'l') {
const l = draw.v()[i-5+scroll] && draw.v()[i-5+scroll].substring(0,columns-4)
pr(l
? ('║'+(active===i-5+scroll?'\x1b[7m ':' ')+l+' '.repeat(columns-l.length-3)+'\x1b[0m║')
: ('║'+' '.repeat(columns - 2)+'║')
)
}
}
}
pr('╚'+'═'.repeat(columns - 2)+'╝')
}
// ============ GET KEY =================
const getKey = () => {
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
process.stdin.on('keypress', (_, key) => {
const lines = process.stdout.rows
switch(key.name) {
case 'up':
case 'k':
active > 0 && active--
active < scroll && scroll--
drawApp()
break
case 'down':
case 'j':
if (draw.t === 'l') {
active < draw.v().length - 1 && active++
active - scroll > lines - 7 && scroll++
drawApp()
}
break
case 'return':
case 'o':
fetchNote(notesList[active])
break
case 'q':
cursor.show()
cls()
pr('Bye!\n\n')
process.exit()
default:
}
})
}
/* Session */
const setSession = (c, callback) => {
if (!fs.existsSync(filesPath)){
fs.mkdirSync(filesPath, { recursive: true });
}
fs.writeFile(`${filesPath}/session`, JSON.stringify(c), function(err) {
if(err) {
cl(err, 32)
cl('Error writting session file', 32)
return null
}
conf = c
return callback()
})
}
const getSession = () => {
fs.readFile(`${filesPath}/session`, function(err, f){
if (err) {
return login()
}
try {
conf = JSON.parse(f.toString())
if (!conf.session || !conf.userId || !conf.email || !conf.list) {
return login('Session error')
}
fetchList()
} catch (e) {
return login('Session error')
}
})
}
/* Login */
const login = (error = '') => {
cl('\n Login to apps.pruss.it\n\n')
cl(' ┌'+'─'.repeat(50)+'┐\n'+' │'+' '.repeat(50)+'│\n'+' │ Account can be created on '+
'apps.pruss.it website. │\n'+' │ To quit type "q" and press enter.'+' '.repeat(16)+'│\n'+
' │'+' '.repeat(50)+'│\n'+' └'+'─'.repeat(50)+'┘\n', 32)
cl(' '+error+'\n', 31)
rl.resume()
rl.question(' Email: ', e => {
if (e === 'q') {
cl('\nExiting My Apps', 31)
rl.close()
process.exit(1)
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)) {
cls()
rl.pause()
return login('Not a valid email address, try again.')
}
rl.stdoutMuted = true
rl.question(' Password: ', p => {
if (p === 'q') {
cl('\nExiting My Apps', 31)
rl.close()
process.exit(1)
}
rl.pause()
post(
'/api/login',
{"email": e, "password": p},
(o, s, h) => {
if (!o || s !== 201) {
rl.pause()
cls()
rl.stdoutMuted = false
return login('Could not log in, try again')
}
const {_id, email, isVerified, noteList} = o
const session = h['set-cookie']
if (!_id || !email || !noteList) {
cl('Could not log in', 31)
process.exit(1)
} else if (!isVerified) {
cl('User not verified.\nPlease first verify the user using apps.pruss.it', 32)
return 1
}
const c = {userId: _id, email, list: noteList, session}
rl.resume()
setSession(c, getSession)
})
})
rl._writeToOutput = function _writeToOutput(stringToWrite) {
if (rl.stdoutMuted)
rl.output.write("*")
else
rl.output.write(stringToWrite)
};
rl.history = rl.history.slice(1)
})
}
/* API */
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 = '') => {
const options = {
hostname: 'apps.pruss.it',
port: 443,
path,
method: 'GET',
headers: {
'Cookie': cookie,
},
};
const req = https.request(options, res => {
let data = '';
res.on('data', chunk => {
data += chunk
});
res.on('end', () => callback(JSON.parse(data), res.statusCode, res.headers));
});
req.on('error', () => {
callback(null)
});
req.end();
}
const post = (path, data, callback, cookie = '', put = false) => {
const dataString = JSON.stringify(data)
const options = {
hostname: 'apps.pruss.it',
port: 443,
path,
method: put ? 'PUT' : 'POST',
headers: put ? {
'Cookie': cookie,
} : {
'Content-Type': 'application/json',
'Content-Length': dataString.length,
'Cookie': cookie,
},
timeout: 1000
};
const req = https.request(options, (res) => {
let data = '';
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => callback(JSON.parse(data), res.statusCode, res.headers));
}).on("error", () => {
callback(null)
});
req.write(dataString);
req.end();
}
const put = (...arg) => post(...arg, true)
cls()
getSession()
|