-
Notifications
You must be signed in to change notification settings - Fork 0
/
wxwork-app-parseChatMsg.js
58 lines (53 loc) · 1.85 KB
/
wxwork-app-parseChatMsg.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
module.exports = function (RED) {
function WxworkAppParseChatMsg(n) {
RED.nodes.createNode(this, n);
const { decrypt } = require('./libs/crypto');
const { parseString } = require('xml2js');
const _ = require('lodash');
const util = require('util');
function convertChatXmlJsonToJsStyle(xmlJson) {
return _.fromPairs(
_.toPairs(xmlJson).map(([key, value]) => [
_.camelCase(key),
_.isArray(value) ? value[0] : value,
]),
);
}
// load from wxworkAppNode
const wxworkApp = RED.nodes.getNode(n.app);
const isAuthMode = n.mode === 'auth';
const node = this;
this.on('input', async (msg, send, done) => {
if (isAuthMode) {
try {
node.debug('[chat msg]enter auth mode');
const echostr = _.get(msg, 'req.query.echostr');
msg.payload = decrypt(wxworkApp.cryptoConfig, echostr);
send(msg);
done();
} catch (err) {
done(err);
}
return;
}
try {
const parseXmlPromise = util.promisify(parseString);
let requestContent = msg.payload;
if (_.isString(requestContent)) {
requestContent = await parseXmlPromise(msg.payload, { trim: true });
}
const encryptContent = _.get(requestContent, 'xml.Encrypt[0]');
const content = decrypt(wxworkApp.cryptoConfig, encryptContent);
node.debug(`[chat msg]enter parser mode, receive msg: ${content}`);
const xml = await parseXmlPromise(content, { trim: true });
msg.chatMsg = convertChatXmlJsonToJsStyle(_.get(xml, 'xml'));
// 用于自动回复消息,暂时都需要单独发请求回复消息
send(msg);
done();
} catch (err) {
done(err);
}
});
}
RED.nodes.registerType('wxwork-app-parseChatMsg', WxworkAppParseChatMsg, {});
};