-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostHandler.js
102 lines (89 loc) · 1.9 KB
/
postHandler.js
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
'use strict';
const {
promisify: p
} = require('util');
const {
apiCall
} = require('./apiCall');
const {
confDirPath,
readConfig,
writeConfig,
readf,
removef,
} = require('./config');
const postHandler = async (argv) => {
const config = await readConfig();
const {
current
} = config
if (!current) {
console.log('No current channel FOUND.');
return false;
}
const {
id: room_id,
name: roomName
} = current;
const source = await getSource(argv);
console.log(source);
if (!source) {
return false
}
const lastPostInfo = await postMessage(room_id, source);
try {
config.last = lastPostInfo;
await writeConfig(config);
} catch (e) {
console.log(`FAILED to save latest post.`)
}
}
async function getSource(argv) {
if (argv._[1]) {
return Promise.resolve(argv._[1]);
}
const child_process = require('child_process');
const editor = argv.emacs ? 'emacs' : 'vim'
const timestamp = new Date().getTime()
const tmpFilePath = `${confDirPath}/tmp_${timestamp}`;
const wordProcessor = child_process.spawn(editor, [tmpFilePath], {
stdio: 'inherit'
});
return new Promise((resolve, reject) => {
wordProcessor.on('exit', async (e) => {
if (e) {
reject(e)
}
try {
const draft = await readf(tmpFilePath);
await removef(tmpFilePath);
resolve(draft);
} catch (e) {
console.log('ABORT posting.');
resolve('');
}
})
})
}
const postMessage = async (room_id, source) => {
try {
const {
message
} = await apiCall('/messages', 'POST', {
room_id,
source,
format: 'markdown',
})
const last = {
id: message.id,
created_at: message.created_at,
body: message.body,
raw: source,
room_id: message.room_id,
}
return last
} catch (e) {
console.log(e);
}
}
exports.postHandler = postHandler;