-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathcli.js
executable file
·84 lines (70 loc) · 1.86 KB
/
cli.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
#!/usr/bin/env node
'use strict';
var readline = require('readline');
var chalk = require('chalk');
var WechatClient = require('./lib/wechat_client');
var logger = require('./lib/logger');
var commands = require('./lib/commands');
var notifier = require('node-notifier');
var wechat = new WechatClient();
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: true,
completer: completer,
});
wechat.on(WechatClient.EVENTS.ERROR, () => { rl.close(); });
wechat.on(WechatClient.EVENTS.CHAT_CHANGE, () => { updatePrompt(); });
wechat.on(WechatClient.EVENTS.LOGIN, () => { startConsole(); });
wechat.on(WechatClient.EVENTS.LOGOUT, () => {
logger.info('Logout.');
rl.close();
});
wechat.on(WechatClient.EVENTS.MESSAGE, (data) => {
rl.prompt(true);
notifier.notify({
title: data.from,
message: data.message,
});
});
wechat.login();
function startConsole() {
logger.info('Login successfully.');
updatePrompt();
rl.prompt(true);
rl.on('line', onUserInput)
.on('SIGINT', onPreExit)
.on('close', onExit);
}
function onUserInput(msg) {
rl.pause();
commands.parse(msg, wechat);
rl.prompt(true);
}
function onPreExit() {
rl.question('Are you sure you want to exit?(y/N)', (answer) => {
if (answer.match(/^y(es)?$/i)) {
rl.close();
} else {
rl.prompt(true);
}
});
}
function onExit() {
wechat.logout().then(() => { process.exit(0); });
}
function updatePrompt() {
var prompt = 'wechat';
if (wechat.isLogined()) {
prompt = chalk.bold.blue(wechat.getUser());
var chat = wechat.getChat();
if (chat) {
prompt += chalk.yellow(' => ') + chalk.bold.blue(chat);
}
}
rl.setPrompt(prompt + chalk.yellow('> '));
}
function completer(line) {
var hits = commands.ALL_CMD.filter((c) => { return c.indexOf(line) === 0; });
return [hits.length ? hits : commands.ALL_CMD, line];
}