UNPKG

7.39 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.IoClient = void 0;
4/**
5 * Wechaty Chatbot SDK - https://github.com/wechaty/wechaty
6 *
7 * @copyright 2016 Huan LI (李卓桓) <https://github.com/huan>, and
8 * Wechaty Contributors <https://github.com/wechaty>.
9 *
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
13 *
14 * http://www.apache.org/licenses/LICENSE-2.0
15 *
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS,
18 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
21 *
22 */
23/**
24 * DO NOT use `require('../')` here!
25 * because it will cause a LOOP require ERROR
26 */
27const wechaty_puppet_1 = require("wechaty-puppet");
28const wechaty_puppet_service_1 = require("wechaty-puppet-service");
29const config_1 = require("./config");
30const io_1 = require("./io");
31const DEFAULT_IO_CLIENT_OPTIONS = {
32 port: 8788,
33};
34class IoClient {
35 constructor(options) {
36 config_1.log.verbose('IoClient', 'constructor({%s})', Object.keys(options)
37 .map(key => {
38 return `${key}:${options[key]}`;
39 })
40 .reduce((acc, cur) => `${acc}, ${cur}`));
41 const normalizedOptions = {
42 ...DEFAULT_IO_CLIENT_OPTIONS,
43 ...options,
44 };
45 this.options = normalizedOptions;
46 this.state = new wechaty_puppet_1.StateSwitch('IoClient', { log: config_1.log });
47 }
48 async startPuppetServer() {
49 config_1.log.verbose('IoClient', 'startPuppetServer()');
50 if (this.puppetServer) {
51 throw new Error('puppet server exists');
52 }
53 const options = {
54 endpoint: '0.0.0.0:' + this.options.port,
55 puppet: this.options.wechaty.puppet,
56 token: this.options.token,
57 };
58 this.puppetServer = new wechaty_puppet_service_1.PuppetServer(options);
59 await this.puppetServer.start();
60 }
61 async stopPuppetServer() {
62 config_1.log.verbose('IoClient', 'stopPuppetService()');
63 if (!this.puppetServer) {
64 throw new Error('puppet server does not exist');
65 }
66 await this.puppetServer.stop();
67 this.puppetServer = undefined;
68 }
69 async start() {
70 config_1.log.verbose('IoClient', 'start()');
71 if (this.state.on()) {
72 config_1.log.warn('IoClient', 'start() with a on state, wait and return');
73 await this.state.ready('on');
74 return;
75 }
76 this.state.on('pending');
77 try {
78 await this.hookWechaty(this.options.wechaty);
79 await this.startIo();
80 await this.options.wechaty.start();
81 await this.startPuppetServer();
82 this.state.on(true);
83 }
84 catch (e) {
85 config_1.log.error('IoClient', 'start() exception: %s', e.message);
86 this.state.off(true);
87 throw e;
88 }
89 }
90 async hookWechaty(wechaty) {
91 config_1.log.verbose('IoClient', 'hookWechaty()');
92 if (this.state.off()) {
93 const e = new Error('state.off() is true, skipped');
94 config_1.log.warn('IoClient', 'initWechaty() %s', e.message);
95 throw e;
96 }
97 wechaty
98 .on('login', user => config_1.log.info('IoClient', `${user.name()} logged in`))
99 .on('logout', user => config_1.log.info('IoClient', `${user.name()} logged out`))
100 .on('message', msg => this.onMessage(msg))
101 .on('scan', (url, code) => {
102 config_1.log.info('IoClient', [
103 `[${code}] ${url}`,
104 `Online QR Code Image: https://wechaty.js.org/qrcode/${encodeURIComponent(url)}`,
105 ].join('\n'));
106 });
107 }
108 async startIo() {
109 config_1.log.verbose('IoClient', 'startIo() with token %s', this.options.token);
110 if (this.state.off()) {
111 const e = new Error('startIo() state.off() is true, skipped');
112 config_1.log.warn('IoClient', e.message);
113 throw e;
114 }
115 if (this.io) {
116 throw new Error('io exists');
117 }
118 this.io = new io_1.Io({
119 servicePort: this.options.port,
120 token: this.options.token,
121 wechaty: this.options.wechaty,
122 });
123 try {
124 await this.io.start();
125 }
126 catch (e) {
127 config_1.log.verbose('IoClient', 'startIo() init fail: %s', e.message);
128 throw e;
129 }
130 }
131 async stopIo() {
132 config_1.log.verbose('IoClient', 'stopIo()');
133 if (!this.io) {
134 config_1.log.warn('IoClient', 'stopIo() io does not exist');
135 return;
136 }
137 await this.io.stop();
138 this.io = undefined;
139 }
140 async onMessage(msg) {
141 config_1.log.verbose('IoClient', 'onMessage(%s)', msg);
142 // const from = m.from()
143 // const to = m.to()
144 // const content = m.toString()
145 // const room = m.room()
146 // log.info('Bot', '%s<%s>:%s'
147 // , (room ? '['+room.topic()+']' : '')
148 // , from.name()
149 // , m.toStringDigest()
150 // )
151 // if (/^wechaty|chatie|botie/i.test(m.text()) && !m.self()) {
152 // await m.say('https://www.chatie.io')
153 // .then(_ => log.info('Bot', 'REPLIED to magic word "chatie"'))
154 // }
155 }
156 async stop() {
157 config_1.log.verbose('IoClient', 'stop()');
158 this.state.off('pending');
159 await this.stopIo();
160 await this.stopPuppetServer();
161 await this.options.wechaty.stop();
162 this.state.off(true);
163 // XXX 20161026
164 // this.io = null
165 }
166 async restart() {
167 config_1.log.verbose('IoClient', 'restart()');
168 try {
169 await this.stop();
170 await this.start();
171 }
172 catch (e) {
173 config_1.log.error('IoClient', 'restart() exception %s', e.message);
174 throw e;
175 }
176 }
177 async quit() {
178 config_1.log.verbose('IoClient', 'quit()');
179 if (this.state.off() === 'pending') {
180 config_1.log.warn('IoClient', 'quit() with state.off() = `pending`, skipped');
181 throw new Error('quit() with state.off() = `pending`');
182 }
183 this.state.off('pending');
184 try {
185 if (this.options.wechaty) {
186 await this.options.wechaty.stop();
187 // this.wechaty = null
188 }
189 else {
190 config_1.log.warn('IoClient', 'quit() no this.wechaty');
191 }
192 if (this.io) {
193 await this.io.stop();
194 // this.io = null
195 }
196 else {
197 config_1.log.warn('IoClient', 'quit() no this.io');
198 }
199 }
200 catch (e) {
201 config_1.log.error('IoClient', 'exception: %s', e.message);
202 throw e;
203 }
204 finally {
205 this.state.off(true);
206 }
207 }
208}
209exports.IoClient = IoClient;
210//# sourceMappingURL=io-client.js.map
\No newline at end of file