diff --git a/package.json b/package.json index fa5e6dc68..f2b779135 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@juzi/wechaty", - "version": "1.0.159", + "version": "1.0.160", "description": "Wechaty is a RPA SDK for Chatbot Makers.", "type": "module", "exports": { @@ -109,7 +109,7 @@ }, "homepage": "https://github.com/wechaty/", "dependencies": { - "@juzi/wechaty-puppet-service": "1.0.121", + "@juzi/wechaty-puppet-service": "1.0.124", "clone-class": "^1.1.1", "cmd-ts": "^0.10.0", "cockatiel": "^2.0.2", @@ -132,7 +132,7 @@ "@chatie/eslint-config": "^1.0.4", "@chatie/semver": "^0.4.7", "@chatie/tsconfig": "^4.6.3", - "@juzi/wechaty-puppet": "^1.0.146", + "@juzi/wechaty-puppet": "^1.0.148", "@juzi/wechaty-puppet-mock": "^1.0.1", "@swc/core": "1.3.44", "@swc/helpers": "^0.3.6", diff --git a/scripts/npm-pack-testing.sh b/scripts/npm-pack-testing.sh index 988536dc0..f5fd2fcef 100755 --- a/scripts/npm-pack-testing.sh +++ b/scripts/npm-pack-testing.sh @@ -23,7 +23,7 @@ cd $TMPDIR npm init -y npm install --production ./*-*.*.*.tgz \ - @types/node \ + '@types/node@^20' \ typescript@4.7.4 \ pkg-jq \ file-box@"$NPM_TAG" \ diff --git a/src/io.ts b/src/io.ts index a4a6f09de..0ed48cde0 100644 --- a/src/io.ts +++ b/src/io.ts @@ -125,7 +125,7 @@ export class Io { this.id = options.wechaty.id this.protocol = options.protocol + '|' + options.wechaty.id + '|' + config.serviceIp + '|' + options.servicePort - log.verbose('Io', 'instantiated with apihost[%s], token[%s], protocol[%s], cuid[%s]', + this.options.wechaty.log.verbose('Io', 'instantiated with apihost[%s], token[%s], protocol[%s], cuid[%s]', options.apihost, options.token, options.protocol, @@ -149,7 +149,7 @@ export class Io { } public async start (): Promise { - log.verbose('Io', 'start()') + this.options.wechaty.log.verbose('Io', 'start()') if (this.lifeTimer) { throw new Error('lifeTimer exist') @@ -176,7 +176,7 @@ export class Io { this.lifeTimer = setInterval(() => { if (this.ws && this.connected()) { - log.silly('Io', 'start() setInterval() ws.ping()') + this.options.wechaty.log.silly('Io', 'start() setInterval() ws.ping()') // TODO: check 'pong' event on ws this.ws.ping() } @@ -185,14 +185,14 @@ export class Io { this.state.active(true) } catch (e) { - log.warn('Io', 'start() exception: %s', (e as Error).message) + this.options.wechaty.log.warn('Io', 'start() exception: %s', (e as Error).message) this.state.inactive(true) throw e } } private initEventHook () { - log.verbose('Io', 'initEventHook()') + this.options.wechaty.log.verbose('Io', 'initEventHook()') const wechaty = this.options.wechaty wechaty.on('error', error => this.send({ name: 'error', payload: error })) @@ -207,7 +207,7 @@ export class Io { } private async initWebSocket (): Promise { - log.verbose('Io', 'initWebSocket()') + this.options.wechaty.log.verbose('Io', 'initWebSocket()') // this.state.current('on', false) // const auth = 'Basic ' + new Buffer(this.setting.token + ':X').toString('base64') @@ -243,10 +243,10 @@ export class Io { private wsOnOpen (ws: WebSocket): void { if (this.protocol !== ws.protocol) { - log.error('Io', 'wsOnOpen() require protocol[%s] failed', this.protocol) + this.options.wechaty.log.error('Io', 'wsOnOpen() require protocol[%s] failed', this.protocol) // XXX deal with error? } - log.verbose('Io', 'wsOnOpen() connected with protocol [%s]', ws.protocol) + this.options.wechaty.log.verbose('Io', 'wsOnOpen() connected with protocol [%s]', ws.protocol) // this.currentState('connected') // this.state.current('on') @@ -266,12 +266,12 @@ export class Io { } private wsOnMessage (data: WebSocket.Data): void { - log.silly('Io', 'wsOnMessage() ws.on(message): %s', data) + this.options.wechaty.log.silly('Io', 'wsOnMessage() ws.on(message): %s', data) this.wsOnMessageAsync(data).catch(console.error) } private async wsOnMessageAsync (data: WebSocket.Data): Promise { - log.silly('Io', 'wsOnMessageAsync() ws.on(message): %s', data) + this.options.wechaty.log.silly('Io', 'wsOnMessageAsync() ws.on(message): %s', data) // flags.binary will be set if a binary data is received. // flags.masked will be set if the data was masked. @@ -293,7 +293,7 @@ export class Io { ioEvent.name = obj.name ioEvent.payload = obj.payload } catch (e) { - log.verbose('Io', 'on(message) recv a non IoEvent data[%s]', data) + this.options.wechaty.log.verbose('Io', 'on(message) recv a non IoEvent data[%s]', data) } switch (ioEvent.name) { @@ -309,17 +309,17 @@ export class Io { const fn = new AsyncFunction(...args, source) this.onMessage = fn } else { - log.warn('Io', 'server pushed function is invalid. args: %s', JSON.stringify(args)) + this.options.wechaty.log.warn('Io', 'server pushed function is invalid. args: %s', JSON.stringify(args)) } } catch (e) { - log.warn('Io', 'server pushed function exception: %s', e) + this.options.wechaty.log.warn('Io', 'server pushed function exception: %s', e) this.options.wechaty.emitError(e) } } break case 'reset': - log.verbose('Io', 'on(reset): %s', ioEvent.payload) + this.options.wechaty.log.verbose('Io', 'on(reset): %s', ioEvent.payload) this.options.wechaty.emitError( new Error( 'reset by server: ' @@ -330,13 +330,13 @@ export class Io { break case 'shutdown': - log.info('Io', 'on(shutdown): %s', ioEvent.payload) + this.options.wechaty.log.info('Io', 'on(shutdown): %s', ioEvent.payload) process.exit(0) // eslint-disable-next-line break case 'update': - log.verbose('Io', 'on(update): %s', ioEvent.payload) + this.options.wechaty.log.verbose('Io', 'on(update): %s', ioEvent.payload) { const wechaty = this.options.wechaty if (wechaty.isLoggedIn) { @@ -365,17 +365,17 @@ export class Io { break case 'logout': - log.info('Io', 'on(logout): %s', ioEvent.payload) + this.options.wechaty.log.info('Io', 'on(logout): %s', ioEvent.payload) await this.options.wechaty.logout() break case 'jsonrpc': - log.info('Io', 'on(jsonrpc): %s', ioEvent.payload) + this.options.wechaty.log.info('Io', 'on(jsonrpc): %s', ioEvent.payload) try { const request = (ioEvent as IoEventJsonRpc).payload if (!isJsonRpcRequest(request)) { - log.warn('Io', 'on(jsonrpc) payload is not a jsonrpc request: %s', JSON.stringify(request)) + this.options.wechaty.log.warn('Io', 'on(jsonrpc) payload is not a jsonrpc request: %s', JSON.stringify(request)) return } @@ -385,7 +385,7 @@ export class Io { const response = await this.jsonRpc.exec(request) if (!response) { - log.warn('Io', 'on(jsonrpc) response is undefined.') + this.options.wechaty.log.warn('Io', 'on(jsonrpc) response is undefined.') return } const payload = jsonRpcPeer.parse(response) as jsonRpcPeer.JsonRpcPayloadResponse @@ -395,17 +395,17 @@ export class Io { payload, } - log.verbose('Io', 'on(jsonrpc) send(%s)', response) + this.options.wechaty.log.verbose('Io', 'on(jsonrpc) send(%s)', response) await this.send(jsonrpcEvent) } catch (e) { - log.error('Io', 'on(jsonrpc): %s', e) + this.options.wechaty.log.error('Io', 'on(jsonrpc): %s', e) } break default: - log.warn('Io', 'UNKNOWN on(%s): %s', ioEvent.name, ioEvent.payload) + this.options.wechaty.log.warn('Io', 'UNKNOWN on(%s): %s', ioEvent.name, ioEvent.payload) break } } @@ -413,23 +413,23 @@ export class Io { // FIXME: it seems the parameter `e` might be `undefined`. // @types/ws might has bug for `ws.on('error', e => this.wsOnError(e))` private wsOnError (e?: Error) { - log.warn('Io', 'wsOnError() error event[%s]', e && e.message) + this.options.wechaty.log.warn('Io', 'wsOnError() error event[%s]', e && e.message) if (!e) { return } if (!this.ws) { - log.error('Io', 'wsOnError() ws.on(error) this.ws is `undefined`', e.message) + this.options.wechaty.log.error('Io', 'wsOnError() ws.on(error) this.ws is `undefined`', e.message) return } if (this.ws.readyState === WebSocket.CONNECTING) { - log.error('Io', 'wsOnError() ws.on(error) ws.readyState is CONNECTING: %s', e.message) + this.options.wechaty.log.error('Io', 'wsOnError() ws.on(error) ws.readyState is CONNECTING: %s', e.message) return } if (this.ws.readyState === WebSocket.CLOSING) { - log.error('Io', 'wsOnError() ws.on(error) ws.readyState is CLOSING: %s', e.message) + this.options.wechaty.log.error('Io', 'wsOnError() ws.on(error) ws.readyState is CLOSING: %s', e.message) return } @@ -448,26 +448,26 @@ export class Io { message : string, ): void { if (this.state.active()) { - log.warn('Io', 'wsOnClose() close event[%d: %s]', code, message) + this.options.wechaty.log.warn('Io', 'wsOnClose() close event[%d: %s]', code, message) ws.close() this.reconnect() } } private reconnect () { - log.verbose('Io', 'reconnect()') + this.options.wechaty.log.verbose('Io', 'reconnect()') if (this.state.inactive()) { - log.warn('Io', 'reconnect() canceled because state.target() === offline') + this.options.wechaty.log.warn('Io', 'reconnect() canceled because state.target() === offline') return } if (this.connected()) { - log.warn('Io', 'reconnect() on a already connected io') + this.options.wechaty.log.warn('Io', 'reconnect() on a already connected io') return } if (this.reconnectTimer) { - log.warn('Io', 'reconnect() on a already re-connecting io') + this.options.wechaty.log.warn('Io', 'reconnect() on a already re-connecting io') return } @@ -477,7 +477,7 @@ export class Io { this.reconnectTimeout *= 3 } - log.warn('Io', 'reconnect() will reconnect after %d s', Math.floor(this.reconnectTimeout / 1000)) + this.options.wechaty.log.warn('Io', 'reconnect() will reconnect after %d s', Math.floor(this.reconnectTimeout / 1000)) this.reconnectTimer = setTimeout(() => { this.reconnectTimer = undefined this.initWebSocket().catch(console.error) @@ -492,12 +492,12 @@ export class Io { const ws = this.ws if (ioEvent) { - log.silly('Io', 'send(%s)', JSON.stringify(ioEvent)) + this.options.wechaty.log.silly('Io', 'send(%s)', JSON.stringify(ioEvent)) this.eventBuffer.push(ioEvent) - } else { log.silly('Io', 'send()') } + } else { this.options.wechaty.log.silly('Io', 'send()') } if (!this.connected()) { - log.verbose('Io', 'send() without a connected websocket, eventBuffer.length = %d', this.eventBuffer.length) + this.options.wechaty.log.verbose('Io', 'send() without a connected websocket, eventBuffer.length = %d', this.eventBuffer.length) return } @@ -522,13 +522,13 @@ export class Io { try { await Promise.all(list) } catch (e) { - log.error('Io', 'send() exception: %s', (e as Error).stack) + this.options.wechaty.log.error('Io', 'send() exception: %s', (e as Error).stack) throw e } } public async stop (): Promise { - log.verbose('Io', 'stop()') + this.options.wechaty.log.verbose('Io', 'stop()') if (!this.ws) { throw new Error('no ws') @@ -569,14 +569,14 @@ export class Io { * */ private async ioMessage (m: MessageInterface): Promise { - log.silly('Io', 'ioMessage() is a nop function before be overwritten from cloud') + this.options.wechaty.log.silly('Io', 'ioMessage() is a nop function before be overwritten from cloud') if (typeof this.onMessage === 'function') { await this.onMessage(m) } } protected async syncMessage (m: MessageInterface): Promise { - log.silly('Io', 'syncMessage(%s)', m) + this.options.wechaty.log.silly('Io', 'syncMessage(%s)', m) const messageEvent: IoEvent = { name : 'message', diff --git a/src/schemas/logger.ts b/src/schemas/logger.ts new file mode 100644 index 000000000..bb1da845c --- /dev/null +++ b/src/schemas/logger.ts @@ -0,0 +1 @@ +export type { LoggerLike } from '@juzi/wechaty-puppet' diff --git a/src/schemas/mod.ts b/src/schemas/mod.ts index 12c057bda..e1cff5172 100644 --- a/src/schemas/mod.ts +++ b/src/schemas/mod.ts @@ -18,11 +18,15 @@ import { import type { Accepter, } from './acceptable.js' +import type { + LoggerLike, +} from './logger.js' export type { Accepter, CallEventListeners, ContactEventListeners, + LoggerLike, RoomEventListeners, WechatyEventListeners, WechatyEventName, diff --git a/src/schemas/wechaty-options.ts b/src/schemas/wechaty-options.ts index 096af9231..eae933090 100644 --- a/src/schemas/wechaty-options.ts +++ b/src/schemas/wechaty-options.ts @@ -6,6 +6,9 @@ import type { import type { OfficialPuppetNpmName, } from '../puppet-config.js' +import type { + LoggerLike, +} from './logger.js' interface OptionsPuppetInstance { puppet?: PUPPET.impls.PuppetInterface, @@ -20,6 +23,24 @@ interface WechatyOptionsBase { memory? : MemoryCard, name? : string, ioToken? : string, + /** + * Pluggable logger. When provided: + * - the value is forwarded to the puppet via {@link PUPPET.PuppetOptions.logger} + * during Wechaty initialization (see puppet-mixin); + * - Wechaty exposes it (falling back to the built-in brolog) via + * `wechaty.log` and, transitively, on every wechatified user module + * via `Contact.log`, `Message.log`, ... + * + * Supply your own logger to route Wechaty and puppet output into your + * host process's logging pipeline (structured logs, sinks, sampling, ...). + * + * Scope note: this covers wechaty's own instance-level log calls and the + * puppet layer (once it is constructed). Third-party libraries embedded + * inside wechaty (e.g. `state-switch`, `memory-card`, `gerror`) still + * emit through the process-wide brolog and are not rerouted by this + * option. + */ + logger? : LoggerLike, } type WechatyOptionsPuppetInstance = diff --git a/src/user-mixins/wechatify.ts b/src/user-mixins/wechatify.ts index 25367417a..c27f87452 100644 --- a/src/user-mixins/wechatify.ts +++ b/src/user-mixins/wechatify.ts @@ -1,6 +1,7 @@ import { log } from '@juzi/wechaty-puppet' import type { Constructor } from 'clone-class' +import type { LoggerLike } from '../schemas/logger.js' import type { WechatyInterface } from '../wechaty/mod.js' const WECHATIFIED_PREFIX = 'Wechatified' @@ -50,6 +51,31 @@ const wechatifyMixin = (Base: TBase) => { static get wechaty (): WechatyInterface { return throwWechatifyError(this) } get wechaty (): WechatyInterface { return throwWechatifyError(this.constructor) } + /** + * Route a user module's log calls through the wechaty instance's effective + * logger (populated in puppet-mixin from `puppet.log`, brolog fallback). + * + * The try/catch guards two windows: (a) direct access on the un-wechatified + * base class (which throws) and (b) puppet-not-yet-ready inside init. In + * both cases we fall back to the module-imported brolog `log`, matching + * the historical behavior. + */ + static get log (): LoggerLike { + try { + return this.wechaty.log + } catch (_) { + return log + } + } + + get log (): LoggerLike { + try { + return this.wechaty.log + } catch (_) { + return log + } + } + constructor (...args: any[]) { super(...args) if (!isWechatified(this.constructor)) { diff --git a/src/user-modules/call.ts b/src/user-modules/call.ts index 98585f241..ae22a9d09 100644 --- a/src/user-modules/call.ts +++ b/src/user-modules/call.ts @@ -1,7 +1,6 @@ import * as PUPPET from '@juzi/wechaty-puppet' import type { Constructor } from 'clone-class' -import { log } from '../config.js' import { validationMixin } from '../user-mixins/validation.js' @@ -59,7 +58,7 @@ class CallMixin extends CallMixinBase { this.__direction = options.direction this.__status = options.status ?? (options.direction === 'outgoing' ? 'calling' : 'ringing') - log.verbose('Call', 'constructor(%s, dir=%s, status=%s)', this.id, this.__direction, this.__status) + this.log.verbose('Call', 'constructor(%s, dir=%s, status=%s)', this.id, this.__direction, this.__status) } direction (): CallDirection { return this.__direction } @@ -262,7 +261,7 @@ class CallMixin extends CallMixinBase { reason?: string, ): void { if (this.__status === 'ended') { - log.warn('Call', '__handleSignal(%s) ignored in ended state for callId=%s', signal, this.id) + this.log.warn('Call', '__handleSignal(%s) ignored in ended state for callId=%s', signal, this.id) return } @@ -310,7 +309,7 @@ class CallMixin extends CallMixinBase { break default: - log.warn('Call', '__handleSignal() unhandled signal: %s', signal) + this.log.warn('Call', '__handleSignal() unhandled signal: %s', signal) break } } @@ -351,7 +350,7 @@ class CallMixin extends CallMixinBase { } private __transitionTo (nextStatus: CallStatus): void { - log.verbose('Call', '__transitionTo(%s) from %s', nextStatus, this.__status) + this.log.verbose('Call', '__transitionTo(%s) from %s', nextStatus, this.__status) this.__status = nextStatus } @@ -386,7 +385,7 @@ export { class CallRecordMixin extends wechatifyMixinBase() { static async create (): Promise { - log.verbose('CallRecord', 'create()') + this.log.verbose('CallRecord', 'create()') const payload: PUPPET.payloads.CallRecord = { starter: 'todo', @@ -406,7 +405,7 @@ class CallRecordMixin extends wechatifyMixinBase() { public readonly payload: PUPPET.payloads.CallRecord, ) { super() - log.verbose('CallRecord', 'constructor()') + this.log.verbose('CallRecord', 'constructor()') } async starter (): Promise { diff --git a/src/user-modules/channel-card.ts b/src/user-modules/channel-card.ts index c3588bdcd..3c2336924 100644 --- a/src/user-modules/channel-card.ts +++ b/src/user-modules/channel-card.ts @@ -1,7 +1,6 @@ import type * as PUPPET from '@juzi/wechaty-puppet' import type { Constructor } from 'clone-class' -import { log } from '../config.js' import { validationMixin } from '../user-mixins/validation.js' @@ -17,7 +16,7 @@ class ChannelCardMixin extends wechatifyMixinBase() { * */ static async create (): Promise { - log.verbose('ChannelCard', 'create()') + this.log.verbose('ChannelCard', 'create()') // TODO: get appid and username from wechat const payload: PUPPET.payloads.ChannelCard = { @@ -39,7 +38,7 @@ class ChannelCardMixin extends wechatifyMixinBase() { public readonly payload: PUPPET.payloads.ChannelCard, ) { super() - log.verbose('ChannelCard', 'constructor()') + this.log.verbose('ChannelCard', 'constructor()') } avatar (): undefined | string { diff --git a/src/user-modules/channel.ts b/src/user-modules/channel.ts index 28e1b5d30..b3df3b600 100644 --- a/src/user-modules/channel.ts +++ b/src/user-modules/channel.ts @@ -1,7 +1,6 @@ import type * as PUPPET from '@juzi/wechaty-puppet' import type { Constructor } from 'clone-class' -import { log } from '../config.js' import { validationMixin } from '../user-mixins/validation.js' @@ -17,7 +16,7 @@ class ChannelMixin extends wechatifyMixinBase() { * */ static async create (): Promise { - log.verbose('Channel', 'create()') + this.log.verbose('Channel', 'create()') // TODO: get appid and username from wechat const payload: PUPPET.payloads.Channel = { @@ -41,7 +40,7 @@ class ChannelMixin extends wechatifyMixinBase() { public readonly payload: PUPPET.payloads.Channel, ) { super() - log.verbose('Channel', 'constructor()') + this.log.verbose('Channel', 'constructor()') } avatar (): undefined | string { diff --git a/src/user-modules/chat-history.ts b/src/user-modules/chat-history.ts index f8e49e264..60913ea73 100644 --- a/src/user-modules/chat-history.ts +++ b/src/user-modules/chat-history.ts @@ -1,7 +1,6 @@ import * as PUPPET from '@juzi/wechaty-puppet' import type { Constructor } from 'clone-class' -import { log } from '../config.js' import { validationMixin } from '../user-mixins/validation.js' @@ -19,7 +18,7 @@ type ChatHistoryMessageType = string | LocationInterface | MiniProgramInterface class ChatHistoryMixin extends wechatifyMixinBase() { static async create (): Promise { - log.verbose('ChatHistory', 'create()') + this.log.verbose('ChatHistory', 'create()') const payload: PUPPET.payloads.ChatHistory[] = [ { @@ -43,7 +42,7 @@ class ChatHistoryMixin extends wechatifyMixinBase() { public readonly payload: PUPPET.payloads.ChatHistory[], ) { super() - log.verbose('ChatHistory', 'constructor()') + this.log.verbose('ChatHistory', 'constructor()') } // avatar (): FileBoxInterface { diff --git a/src/user-modules/consult-card.ts b/src/user-modules/consult-card.ts index e094e3cd8..0104a1351 100644 --- a/src/user-modules/consult-card.ts +++ b/src/user-modules/consult-card.ts @@ -2,8 +2,6 @@ import type * as PUPPET from '@juzi/wechaty-puppet' import type { Constructor } from 'clone-class' -import { log } from '../config.js' - import { validationMixin } from '../user-mixins/validation.js' import { @@ -17,7 +15,7 @@ class ConsultCardMixin extends wechatifyMixinBase() { public readonly payload: PUPPET.payloads.ConsultCard, ) { super() - log.verbose('ConsultCard', 'constructor()') + this.log.verbose('ConsultCard', 'constructor()') } static async findAll (query: { @@ -27,7 +25,7 @@ class ConsultCardMixin extends wechatifyMixinBase() { page?: number, pageSize?: number }): Promise { - log.verbose('ConsultCard', 'findAll(%s)', JSON.stringify(query)) + this.log.verbose('ConsultCard', 'findAll(%s)', JSON.stringify(query)) const params = { cardType: query.cardType, @@ -54,7 +52,7 @@ class ConsultCardMixin extends wechatifyMixinBase() { cardType: number, id: string }): Promise { - log.verbose('ConsultCard', 'find(%s)', JSON.stringify(query)) + this.log.verbose('ConsultCard', 'find(%s)', JSON.stringify(query)) const consultCardList = await this.findAll({ cardType: query.cardType, diff --git a/src/user-modules/contact-self.ts b/src/user-modules/contact-self.ts index 62cb136f9..a4206e319 100644 --- a/src/user-modules/contact-self.ts +++ b/src/user-modules/contact-self.ts @@ -18,9 +18,6 @@ * */ import type * as PUPPET from '@juzi/wechaty-puppet' -import { - log, -} from '@juzi/wechaty-puppet' import type { FileBoxInterface, } from 'file-box' @@ -68,7 +65,7 @@ class ContactSelfMixin extends MixinBase { return contact as ContactSelfInterface } } catch (e) { - log.silly('ContactSelf', 'find() exception: %s', (e as Error).message) + this.log.silly('ContactSelf', 'find() exception: %s', (e as Error).message) } return undefined } @@ -104,7 +101,7 @@ class ContactSelfMixin extends MixinBase { * */ public override async avatar (file?: FileBoxInterface): Promise { - log.verbose('Contact', 'avatar(%s)', file ? file.name : '') + this.log.verbose('Contact', 'avatar(%s)', file ? file.name : '') if (!file) { const filebox = await super.avatar() @@ -133,7 +130,7 @@ class ContactSelfMixin extends MixinBase { * }) */ public async qrcode (): Promise { - log.verbose('Contact', 'qrcode()') + this.log.verbose('Contact', 'qrcode()') if (this.id !== this.wechaty.puppet.currentUserId) { throw new Error('only can get qrcode for the currentUser') } @@ -162,7 +159,7 @@ class ContactSelfMixin extends MixinBase { public override name (name: string): Promise public override name (name?: string): string | Promise { - log.verbose('ContactSelf', 'name(%s)', name || '') + this.log.verbose('ContactSelf', 'name(%s)', name || '') if (typeof name === 'undefined') { return super.name() @@ -179,7 +176,7 @@ class ContactSelfMixin extends MixinBase { public override realName (realName: string): Promise public override realName (realName?: string): string | Promise { - log.verbose('ContactSelf', 'realName(%s)', realName || '') + this.log.verbose('ContactSelf', 'realName(%s)', realName || '') if (typeof realName === 'undefined') { return super.realName() @@ -196,7 +193,7 @@ class ContactSelfMixin extends MixinBase { public override aka (aka: string): Promise public override aka (aka?: string): string | Promise { - log.verbose('ContactSelf', 'aka(%s)', aka || '') + this.log.verbose('ContactSelf', 'aka(%s)', aka || '') if (typeof aka === 'undefined') { return super.aka() @@ -225,7 +222,7 @@ class ContactSelfMixin extends MixinBase { * }) */ public async signature (signature: string): Promise { - log.verbose('ContactSelf', 'signature()') + this.log.verbose('ContactSelf', 'signature()') if (this.id !== this.wechaty.puppet.currentUserId) { throw new Error('only can change signature for user self') @@ -235,7 +232,7 @@ class ContactSelfMixin extends MixinBase { } public async roomAlias (room: RoomInterface, alias?: string): Promise { - log.verbose('ContactSelf', 'roomAlias()') + this.log.verbose('ContactSelf', 'roomAlias()') if (typeof alias === 'undefined') { return room.alias(this) diff --git a/src/user-modules/contact.ts b/src/user-modules/contact.ts index df63d5091..6f624a359 100644 --- a/src/user-modules/contact.ts +++ b/src/user-modules/contact.ts @@ -28,10 +28,6 @@ import type { Constructor, } from 'clone-class' -import { - log, -} from '../config.js' - import { ContactEventEmitter } from '../schemas/mod.js' import { @@ -98,7 +94,7 @@ class ContactMixin extends MixinBase implements SayableSayer { static async find ( query : string | PUPPET.filters.Contact, ): Promise { - log.silly('Contact', 'find(%s)', JSON.stringify(query, stringifyFilter)) + this.log.silly('Contact', 'find(%s)', JSON.stringify(query, stringifyFilter)) if (typeof query === 'object' && query.id) { let contact: ContactImpl @@ -129,7 +125,7 @@ class ContactMixin extends MixinBase implements SayableSayer { } if (contactList.length > 1) { - log.warn('Contact', 'find() got more than 1 result: %d total', contactList.length) + this.log.warn('Contact', 'find() got more than 1 result: %d total', contactList.length) } for (const [ idx, contact ] of contactList.entries()) { @@ -138,15 +134,15 @@ class ContactMixin extends MixinBase implements SayableSayer { // https://github.com/wechaty/wechaty/issues/1345 const valid = await this.wechaty.puppet.contactValidate(contact.id) if (valid) { - log.silly('Contact', 'find() contact is valid, return it', idx, contact.id) + this.log.silly('Contact', 'find() contact is valid, return it', idx, contact.id) return contact } else { - log.silly('Contact', 'find() contact is invalid, skip it', idx, contact.id) + this.log.silly('Contact', 'find() contact is invalid, skip it', idx, contact.id) } } - log.warn('Contact', 'find() all of %d contacts are invalid', contactList.length) + this.log.warn('Contact', 'find() all of %d contacts are invalid', contactList.length) return undefined } @@ -172,7 +168,7 @@ class ContactMixin extends MixinBase implements SayableSayer { static async findAll ( query? : string | PUPPET.filters.Contact, ): Promise { - log.verbose('Contact', 'findAll(%s)', JSON.stringify(query, stringifyFilter) || '') + this.log.verbose('Contact', 'findAll(%s)', JSON.stringify(query, stringifyFilter) || '') const contactIdList: string[] = await this.wechaty.puppet.contactSearch(query) @@ -242,7 +238,7 @@ class ContactMixin extends MixinBase implements SayableSayer { opts? : { batch?: number }, ): AsyncIterable { const batch = opts?.batch ?? 100 - log.verbose('Contact', 'findAllIter(%s, batch=%d)', JSON.stringify(query, stringifyFilter) || '', batch) + this.log.verbose('Contact', 'findAllIter(%s, batch=%d)', JSON.stringify(query, stringifyFilter) || '', batch) if (batch <= 0) { throw new Error(`Contact.findAllIter() batch must be positive, got ${batch}`) @@ -263,7 +259,7 @@ class ContactMixin extends MixinBase implements SayableSayer { for (const id of idChunk) { const payload = payloadMap.get(id) if (!payload) { - log.silly('Contact', 'findAllIter() payload missing for id=%s, skip', id) + this.log.silly('Contact', 'findAllIter() payload missing for id=%s, skip', id) continue } @@ -278,7 +274,7 @@ class ContactMixin extends MixinBase implements SayableSayer { if (contactChunk.length > 0) { yield contactChunk } else { - log.warn('Contact', 'findAllIter() batch all missing from payloadMap, idChunk=%j', idChunk) + this.log.warn('Contact', 'findAllIter() batch all missing from payloadMap, idChunk=%j', idChunk) } } } @@ -348,7 +344,7 @@ class ContactMixin extends MixinBase implements SayableSayer { // TODO // eslint-disable-next-line no-use-before-define static async delete (contact: ContactInterface): Promise { - log.verbose('Contact', 'static delete(%s)', contact.id) + this.log.verbose('Contact', 'static delete(%s)', contact.id) await this.wechaty.puppet.contactDelete(contact.id) } @@ -367,7 +363,7 @@ class ContactMixin extends MixinBase implements SayableSayer { public readonly id: string, ) { super() - log.silly('Contact', `constructor(${id})`) + this.log.silly('Contact', `constructor(${id})`) } /** @@ -458,10 +454,10 @@ class ContactMixin extends MixinBase implements SayableSayer { sayable: Sayable, options?: SayOptionsObject, ): Promise { - log.verbose('Contact', 'say(%s)', sayable) + this.log.verbose('Contact', 'say(%s)', sayable) if (options?.mentionList) { - log.warn('Contact', 'you cannot mention someone in private conversation!') + this.log.warn('Contact', 'you cannot mention someone in private conversation!') delete options.mentionList } @@ -488,7 +484,7 @@ class ContactMixin extends MixinBase implements SayableSayer { * call.on('ended', () => console.log('call ended')) */ async call (options?: { media?: PUPPET.types.CallMediaType }): Promise { - log.verbose('Contact', 'call(%s)', JSON.stringify(options ?? {})) + this.log.verbose('Contact', 'call(%s)', JSON.stringify(options ?? {})) return (this.wechaty as any).call([ this as unknown as ContactInterface ], options) } @@ -547,7 +543,7 @@ class ContactMixin extends MixinBase implements SayableSayer { * } */ async alias (newAlias?: null | string): Promise { - log.silly('Contact', 'alias(%s)', + this.log.silly('Contact', 'alias(%s)', newAlias === undefined ? '' : newAlias, @@ -594,7 +590,7 @@ class ContactMixin extends MixinBase implements SayableSayer { } } catch (e) { this.wechaty.emitError(e) - log.error('Contact', 'alias(%s) rejected: %s', newAlias, (e as Error).message) + this.log.error('Contact', 'alias(%s) rejected: %s', newAlias, (e as Error).message) } } @@ -623,7 +619,7 @@ class ContactMixin extends MixinBase implements SayableSayer { async phone (): Promise async phone (phoneList: string[]): Promise async phone (phoneList?: string[]): Promise { - log.silly('Contact', 'phone(%s)', phoneList === undefined ? '' : JSON.stringify(phoneList)) + this.log.silly('Contact', 'phone(%s)', phoneList === undefined ? '' : JSON.stringify(phoneList)) if (!this.payload) { throw new Error('no payload') @@ -639,14 +635,14 @@ class ContactMixin extends MixinBase implements SayableSayer { this.payload = await this.wechaty.puppet.contactPayload(this.id) } catch (e) { this.wechaty.emitError(e) - log.error('Contact', 'phone(%s) rejected: %s', JSON.stringify(phoneList), (e as Error).message) + this.log.error('Contact', 'phone(%s) rejected: %s', JSON.stringify(phoneList), (e as Error).message) } } async corporation (): Promise async corporation (remark: string | null): Promise async corporation (remark?: string | null): Promise { - log.silly('Contact', 'corporation(%s)', remark) + this.log.silly('Contact', 'corporation(%s)', remark) if (!this.payload) { throw new Error('no payload') @@ -666,14 +662,14 @@ class ContactMixin extends MixinBase implements SayableSayer { this.payload = await this.wechaty.puppet.contactPayload(this.id) } catch (e) { this.wechaty.emitError(e) - log.error('Contact', 'corporation(%s) rejected: %s', remark, (e as Error).message) + this.log.error('Contact', 'corporation(%s) rejected: %s', remark, (e as Error).message) } } async description (): Promise async description (newDescription: string | null): Promise async description (newDescription?: string | null): Promise { - log.silly('Contact', 'description(%s)', newDescription) + this.log.silly('Contact', 'description(%s)', newDescription) if (!this.payload) { throw new Error('no payload') @@ -689,7 +685,7 @@ class ContactMixin extends MixinBase implements SayableSayer { this.payload = await this.wechaty.puppet.contactPayload(this.id) } catch (e) { this.wechaty.emitError(e) - log.error('Contact', 'description(%s) rejected: %s', newDescription, (e as Error).message) + this.log.error('Contact', 'description(%s) rejected: %s', newDescription, (e as Error).message) } } @@ -723,7 +719,7 @@ class ContactMixin extends MixinBase implements SayableSayer { * const isFriend = contact.friend() */ friend (): undefined | boolean { - log.verbose('Contact', 'friend()') + this.log.verbose('Contact', 'friend()') return this.payload?.friend } @@ -813,7 +809,7 @@ class ContactMixin extends MixinBase implements SayableSayer { * console.log(`Contact: ${contact.name()} with avatar file: ${name}`) */ async avatar (): Promise { - log.verbose('Contact', 'avatar()') + this.log.verbose('Contact', 'avatar()') const fileBox = await this.wechaty.puppet.contactAvatar(this.id) return fileBox @@ -827,7 +823,7 @@ class ContactMixin extends MixinBase implements SayableSayer { * const tags = await contact.tags() */ async tags (): Promise { - log.verbose('Contact', 'tags() for %s', this) + this.log.verbose('Contact', 'tags() for %s', this) try { const tagPayloadList = this.payload?.tags || [] @@ -837,7 +833,7 @@ class ContactMixin extends MixinBase implements SayableSayer { return tagList.filter(tag => !!tag) as TagInterface[] } catch (e) { this.wechaty.emitError(e) - log.error('Contact', 'tags() exception: %s', (e as Error).message) + this.log.error('Contact', 'tags() exception: %s', (e as Error).message) return [] } } @@ -847,7 +843,7 @@ class ContactMixin extends MixinBase implements SayableSayer { */ async tag (tags: TagInterface | TagInterface[]): Promise { - log.verbose('Contact', 'tag(%s) for %s', JSON.stringify(tags), this) + this.log.verbose('Contact', 'tag(%s) for %s', JSON.stringify(tags), this) if (!Array.isArray(tags)) { tags = [ tags ] @@ -863,7 +859,7 @@ class ContactMixin extends MixinBase implements SayableSayer { */ async tagRemove (tags: TagInterface | TagInterface[]): Promise { - log.verbose('Contact', 'tagRemove(%s) for %s', JSON.stringify(tags), this) + this.log.verbose('Contact', 'tagRemove(%s) for %s', JSON.stringify(tags), this) if (!Array.isArray(tags)) { tags = [ tags ] @@ -898,20 +894,20 @@ class ContactMixin extends MixinBase implements SayableSayer { async ready ( forceSync = false, ): Promise { - log.silly('Contact', 'ready() @ %s with id="%s"', this.wechaty.puppet, this.id) + this.log.silly('Contact', 'ready() @ %s with id="%s"', this.wechaty.puppet, this.id) if (!forceSync && this.isReady()) { // already ready - log.silly('Contact', 'ready() isReady() true') + this.log.silly('Contact', 'ready() isReady() true') return } try { this.payload = await this.wechaty.puppet.contactPayload(this.id) - // log.silly('Contact', `ready() this.wechaty.puppet.contactPayload(%s) resolved`, this) + // this.log.silly('Contact', `ready() this.wechaty.puppet.contactPayload(%s) resolved`, this) } catch (e) { this.wechaty.emitError(e) - log.verbose('Contact', 'ready() this.wechaty.puppet.contactPayload(%s) exception: %s', + this.log.verbose('Contact', 'ready() this.wechaty.puppet.contactPayload(%s) exception: %s', this.id, (e as Error).message, ) @@ -941,7 +937,7 @@ class ContactMixin extends MixinBase implements SayableSayer { } } catch (e) { this.wechaty.emitError(e) - log.error('Contact', 'readMark() exception: %s', (e as Error).message) + this.log.error('Contact', 'readMark() exception: %s', (e as Error).message) } } @@ -950,7 +946,7 @@ class ContactMixin extends MixinBase implements SayableSayer { await this.wechaty.puppet.endConversation(this.id) } catch (e) { this.wechaty.emitError(e) - log.error('Contact', 'endConversation() exception: %s', (e as Error).message) + this.log.error('Contact', 'endConversation() exception: %s', (e as Error).message) } } @@ -994,7 +990,7 @@ class ContactMixin extends MixinBase implements SayableSayer { * @deprecated use `handle()` instead */ weixin (): undefined | string { - // log.warn('Contact', 'weixin() is deprecated, use `handle()` instead.') + // this.log.warn('Contact', 'weixin() is deprecated, use `handle()` instead.') // console.error(new Error().stack) return this.payload?.weixin } @@ -1005,7 +1001,7 @@ class ContactMixin extends MixinBase implements SayableSayer { try { additionalInfoObj = JSON.parse(this.payload.additionalInfo) } catch (e) { - log.warn('Contact', 'additionalInfo() parse failed, additionalInfo: %s', this.payload.additionalInfo) + this.log.warn('Contact', 'additionalInfo() parse failed, additionalInfo: %s', this.payload.additionalInfo) } } return additionalInfoObj diff --git a/src/user-modules/douyin-one-click-phone-collection.ts b/src/user-modules/douyin-one-click-phone-collection.ts index 398e5aa5f..59a8ba0ae 100644 --- a/src/user-modules/douyin-one-click-phone-collection.ts +++ b/src/user-modules/douyin-one-click-phone-collection.ts @@ -1,5 +1,4 @@ import type { Constructor } from 'clone-class' -import { log } from '../config.js' import { validationMixin } from '../user-mixins/validation.js' @@ -15,7 +14,7 @@ class DouyinOneClickPhoneCollectionMixin extends wechatifyMixinBase() { * */ static async create (): Promise { - log.verbose('DouyinOneClickPhoneCollection', 'create()') + this.log.verbose('DouyinOneClickPhoneCollection', 'create()') return new this({}) } @@ -27,7 +26,7 @@ class DouyinOneClickPhoneCollectionMixin extends wechatifyMixinBase() { public readonly payload: {}, ) { super() - log.verbose('DouyinOneClickPhoneCollection', 'constructor()') + this.log.verbose('DouyinOneClickPhoneCollection', 'constructor()') // Huan(202110): it is ok to create a raw one without wechaty instance // guardWechatifyClass.call(this, DouyinOneClickPhoneCollection) } diff --git a/src/user-modules/favorite.ts b/src/user-modules/favorite.ts index 8327b250b..5f7f9dfba 100644 --- a/src/user-modules/favorite.ts +++ b/src/user-modules/favorite.ts @@ -17,7 +17,6 @@ * limitations under the License. * */ -import { log } from '@juzi/wechaty-puppet' import type { Constructor } from 'clone-class' import { validationMixin } from '../user-mixins/validation.js' @@ -41,7 +40,7 @@ class FavoriteMixin extends wechatifyMixinBase() { * const tags = await wechaty.Favorite.tags() */ static async tags (): Promise { - log.verbose('Favorite', 'static tags() for %s', this) + this.log.verbose('Favorite', 'static tags() for %s', this) // TODO: // try { diff --git a/src/user-modules/friendship.ts b/src/user-modules/friendship.ts index 47d292a8a..e0acb34ae 100644 --- a/src/user-modules/friendship.ts +++ b/src/user-modules/friendship.ts @@ -19,7 +19,6 @@ */ import { EventEmitter } from 'events' import * as PUPPET from '@juzi/wechaty-puppet' -import { log } from '@juzi/wechaty-puppet' import type { Constructor } from 'clone-class' import { @@ -98,7 +97,7 @@ class FriendshipMixin extends MixinBase implements Accepter { queryFilter : PUPPET.filters.Friendship, type?: PUPPET.types.Contact, ): Promise { - log.verbose('Friendship', 'static search("%s")', + this.log.verbose('Friendship', 'static search("%s")', JSON.stringify(queryFilter), ) if (typeof (type) === 'undefined') { @@ -141,13 +140,13 @@ class FriendshipMixin extends MixinBase implements Accepter { contact : ContactInterface, options : FriendshipAddOptions, ): Promise { - log.verbose('Friendship', 'static add(%s, %s)', + this.log.verbose('Friendship', 'static add(%s, %s)', contact.id, typeof options === 'string' ? options : options.hello, ) if (typeof options === 'string') { - log.warn('Friendship', 'the params hello is deprecated in the next version, please put the attr hello into options object, e.g. { hello: "xxxx" }') + this.log.warn('Friendship', 'the params hello is deprecated in the next version, please put the attr hello into options object, e.g. { hello: "xxxx" }') await this.wechaty.puppet.friendshipAdd(contact.id, { hello: options }) } else { const friendOption: PUPPET.types.FriendshipAddOptions = { @@ -162,7 +161,7 @@ class FriendshipMixin extends MixinBase implements Accepter { static async del ( contact: ContactInterface, ): Promise { - log.verbose('Friendship', 'static del(%s)', contact.id) + this.log.verbose('Friendship', 'static del(%s)', contact.id) throw new Error('to be implemented') } @@ -184,7 +183,7 @@ class FriendshipMixin extends MixinBase implements Accepter { public readonly id: string, ) { super() - log.verbose('Friendship', 'constructor(id=%s)', id) + this.log.verbose('Friendship', 'constructor(id=%s)', id) } override toString () { @@ -254,7 +253,7 @@ class FriendshipMixin extends MixinBase implements Accepter { * .start() */ async accept (): Promise { - log.verbose('Friendship', 'accept()') + this.log.verbose('Friendship', 'accept()') if (!this.payload) { throw new Error('no payload') @@ -264,7 +263,7 @@ class FriendshipMixin extends MixinBase implements Accepter { throw new Error('accept() need type to be FriendshipType.Receive, but it got a ' + FriendshipImpl.Type[this.payload.type]) } - log.silly('Friendship', 'accept() to %s', this.payload.contactId) + this.log.silly('Friendship', 'accept() to %s', this.payload.contactId) await this.wechaty.puppet.friendshipAccept(this.id) @@ -276,14 +275,14 @@ class FriendshipMixin extends MixinBase implements Accepter { if (!contact.isReady()) { throw new Error('Friendship.accept() contact.ready() not ready') } - log.verbose('Friendship', 'accept() with contact %s ready()', contact.name()) + this.log.verbose('Friendship', 'accept() with contact %s ready()', contact.name()) } await retryPolicy.execute(doSync) } catch (e) { this.wechaty.emitError(e) - log.warn('Friendship', 'accept() contact %s not ready because of %s', contact, (e && (e as Error).message) || e) + this.log.warn('Friendship', 'accept() contact %s not ready because of %s', contact, (e && (e as Error).message) || e) // console.error(e) } @@ -384,7 +383,7 @@ class FriendshipMixin extends MixinBase implements Accepter { * .start() */ toJSON (): string { - log.verbose('Friendship', 'toJSON()') + this.log.verbose('Friendship', 'toJSON()') if (!this.isReady()) { throw new Error(`Friendship<${this.id}> needs to be ready. Please call ready() before toJSON()`) @@ -405,7 +404,7 @@ class FriendshipMixin extends MixinBase implements Accepter { static async fromJSON ( payload: string | PUPPET.payloads.Friendship, ): Promise { - log.verbose('Friendship', 'static fromJSON(%s)', + this.log.verbose('Friendship', 'static fromJSON(%s)', typeof payload === 'string' ? payload : JSON.stringify(payload), diff --git a/src/user-modules/im-specific.ts b/src/user-modules/im-specific.ts index fdb5b7cd6..b0929bae2 100644 --- a/src/user-modules/im-specific.ts +++ b/src/user-modules/im-specific.ts @@ -1,4 +1,3 @@ -import { log } from '@juzi/wechaty-puppet' import type { Constructor } from 'clone-class' import { validationMixin } from '../user-mixins/validation.js' @@ -36,7 +35,7 @@ class ImSpecificMixin extends wechatifyMixinBase() { */ constructor () { super() - log.verbose('ImSpecific', 'constructor()') + this.log.verbose('ImSpecific', 'constructor()') } } diff --git a/src/user-modules/image.ts b/src/user-modules/image.ts index 586b1ff5c..06bcf667a 100644 --- a/src/user-modules/image.ts +++ b/src/user-modules/image.ts @@ -23,7 +23,6 @@ import type { } from 'file-box' import type { Constructor } from 'clone-class' import { validationMixin } from '../user-mixins/validation.js' -import { log } from '../config.js' import { wechatifyMixinBase, @@ -32,7 +31,7 @@ import { class ImageMixin extends wechatifyMixinBase() { static create (id: string): ImageInterface { - log.verbose('Image', 'static create(%s)', id) + this.log.verbose('Image', 'static create(%s)', id) const image = new this(id) return image @@ -42,11 +41,11 @@ class ImageMixin extends wechatifyMixinBase() { public id: string, ) { super() - log.verbose('Image', 'constructor(%s)', id) + this.log.verbose('Image', 'constructor(%s)', id) } async thumbnail (): Promise { - log.verbose('Image', 'thumbnail() for id: "%s"', this.id) + this.log.verbose('Image', 'thumbnail() for id: "%s"', this.id) const fileBox = await this.wechaty.puppet.messageImage( this.id, PUPPET.types.Image.Thumbnail, @@ -55,7 +54,7 @@ class ImageMixin extends wechatifyMixinBase() { } async hd (): Promise { - log.verbose('Image', 'hd() for id: "%s"', this.id) + this.log.verbose('Image', 'hd() for id: "%s"', this.id) const fileBox = await this.wechaty.puppet.messageImage( this.id, PUPPET.types.Image.HD, @@ -64,7 +63,7 @@ class ImageMixin extends wechatifyMixinBase() { } async artwork (): Promise { - log.verbose('Image', 'artwork() for id: "%s"', this.id) + this.log.verbose('Image', 'artwork() for id: "%s"', this.id) const fileBox = await this.wechaty.puppet.messageImage( this.id, PUPPET.types.Image.Artwork, diff --git a/src/user-modules/location.ts b/src/user-modules/location.ts index 8bb7de670..0814cd783 100644 --- a/src/user-modules/location.ts +++ b/src/user-modules/location.ts @@ -19,7 +19,6 @@ */ import type * as PUPPET from '@juzi/wechaty-puppet' import type { Constructor } from 'clone-class' -import { log } from '../config.js' import { validationMixin } from '../user-mixins/validation.js' import { @@ -35,7 +34,7 @@ class LocationMixin extends wechatifyMixinBase() { * See: https://en.wikipedia.org/wiki/Point_of_interest */ static async create (poi: string): Promise { - log.verbose('Location', 'create(%s)', poi) + this.log.verbose('Location', 'create(%s)', poi) const payload: PUPPET.payloads.Location = { accuracy : 15, // in meters @@ -55,7 +54,7 @@ class LocationMixin extends wechatifyMixinBase() { public readonly payload: PUPPET.payloads.Location, ) { super() - log.verbose('Location', 'constructor()') + this.log.verbose('Location', 'constructor()') // Huan(202110): it is ok to create a raw one without wechaty instance // guardWechatifyClass.call(this, Location) } diff --git a/src/user-modules/message.ts b/src/user-modules/message.ts index 532b51157..22d3f66bf 100644 --- a/src/user-modules/message.ts +++ b/src/user-modules/message.ts @@ -30,7 +30,6 @@ import { escapeRegExp } from '../pure-functions/escape-regexp.js' import { timestampToDate } from '../pure-functions/timestamp-to-date.js' import { - log, AT_SEPARATOR_REGEX, } from '../config.js' import type { @@ -157,7 +156,7 @@ class MessageMixin extends MixinBase implements SayableSayer { static async find ( query : string | PUPPET.filters.Message, ): Promise { - log.verbose('Message', 'find(%s)', JSON.stringify(query)) + this.log.verbose('Message', 'find(%s)', JSON.stringify(query)) if (typeof query === 'object' && query.id) { const message = this.load(query.id) @@ -181,7 +180,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } if (messageList.length > 1) { - log.warn('Message', 'findAll() got more than one(%d) result', messageList.length) + this.log.warn('Message', 'findAll() got more than one(%d) result', messageList.length) } return messageList[0]! @@ -193,7 +192,7 @@ class MessageMixin extends MixinBase implements SayableSayer { static async findAll ( query? : PUPPET.filters.Message, ): Promise { - log.verbose('Message', 'findAll(%s)', JSON.stringify(query) || '') + this.log.verbose('Message', 'findAll(%s)', JSON.stringify(query) || '') // Huan(202111): { id } query has been optimized in the PuppetAbstract class @@ -206,7 +205,7 @@ class MessageMixin extends MixinBase implements SayableSayer { messageList.map( message => message.ready() .catch(e => { - log.warn('Room', 'findAll() message.ready() rejection: %s', e) + this.log.warn('Room', 'findAll() message.ready() rejection: %s', e) invalidDict[message.id] = true }), ), @@ -216,7 +215,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } catch (e) { this.wechaty.emitError(e) - log.warn('Message', 'findAll() rejected: %s', (e as Error).message) + this.log.warn('Message', 'findAll() rejected: %s', (e as Error).message) return [] // fail safe } } @@ -228,7 +227,7 @@ class MessageMixin extends MixinBase implements SayableSayer { * https://www.tatango.com/resources/video-lessons/video-mo-mt-sms-messaging/ */ static load (id: string): MessageImplInterface { - log.verbose('Message', 'static load(%s)', id) + this.log.verbose('Message', 'static load(%s)', id) /** * Must NOT use `Message` at here @@ -242,7 +241,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } static async getBroadcastTargets (): Promise<{ contacts: ContactInterface[]; rooms: RoomInterface[] }> { - log.verbose('Message', 'static getBroadcastTargets()') + this.log.verbose('Message', 'static getBroadcastTargets()') const { contactIds = [], roomIds = [] } = await this.wechaty.puppet.getMessageBroadcastTarget() @@ -319,7 +318,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } static async createBroadcast (targets: (ContactInterface | RoomInterface)[], post: PostInterface): Promise { - log.verbose('Message', 'static createBroadcast()') + this.log.verbose('Message', 'static createBroadcast()') const targetIds = targets.map(target => target.id) const type = post.payload.type || PUPPET.types.Post.Unspecified @@ -336,7 +335,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } static async batchSendMessage (targets: (ContactInterface | RoomInterface)[], post: PostInterface, sendBatchId: string): Promise { - log.verbose('Message', 'static batchSendMessage()') + this.log.verbose('Message', 'static batchSendMessage()') const targetIds = targets.map(target => target.id) @@ -452,7 +451,7 @@ class MessageMixin extends MixinBase implements SayableSayer { status: PUPPET.types.BroadcastTargetStatus, }[] }> { - log.verbose('Message', 'static getBroadcastStatus()') + this.log.verbose('Message', 'static getBroadcastStatus()') const postId = broadcast.id if (!postId) { @@ -522,7 +521,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } static async mergeForward (to: ContactInterface | RoomInterface, messageList: MessageInterface[]): Promise { - log.verbose('Message', `mergeForward(${messageList})`) + this.log.verbose('Message', `mergeForward(${messageList})`) try { const msgId = await this.wechaty.puppet.messageForward( to.id, @@ -533,7 +532,7 @@ class MessageMixin extends MixinBase implements SayableSayer { return msg } } catch (e) { - log.error('Message', 'forward(%s) exception: %s', to, e) + this.log.error('Message', 'forward(%s) exception: %s', to, e) throw e } } @@ -553,7 +552,7 @@ class MessageMixin extends MixinBase implements SayableSayer { public readonly id: string, ) { super() - log.verbose('Message', 'constructor(%s) for class %s', + this.log.verbose('Message', 'constructor(%s) for class %s', id || '', this.constructor.name, ) @@ -591,7 +590,7 @@ class MessageMixin extends MixinBase implements SayableSayer { ) { msgStrList.push(`\t${this.text().substr(0, 70)}`) } else { - log.silly('Message', 'toString() for message type: %s(%s)', PUPPET.types.Message[this.type()], this.type()) + this.log.silly('Message', 'toString() for message type: %s(%s)', PUPPET.types.Message[this.type()], this.type()) // if (!this.#payload) { // throw new Error('no payload') // } @@ -643,7 +642,7 @@ class MessageMixin extends MixinBase implements SayableSayer { throw new Error('no talkerId found for talker') } - log.warn('Message', 'talker() payload.talkerId not exist! See: https://github.com/wechaty/puppet/issues/187') + this.log.warn('Message', 'talker() payload.talkerId not exist! See: https://github.com/wechaty/puppet/issues/187') console.error('Puppet: %s@%s', this.wechaty.puppet.name(), this.wechaty.puppet.version()) console.error(new Error().stack) } @@ -662,7 +661,7 @@ class MessageMixin extends MixinBase implements SayableSayer { * https://github.com/wechaty/wechaty/issues/2094 */ from (): undefined | ContactInterface { - log.warn('Message', 'from() is deprecated, use talker() instead. Call stack: %s', + this.log.warn('Message', 'from() is deprecated, use talker() instead. Call stack: %s', new Error().stack, ) try { @@ -704,7 +703,7 @@ class MessageMixin extends MixinBase implements SayableSayer { */ listenerId = this.payload.toId - log.warn('Message', 'listener() payload.listenerId should be set! See: https://github.com/wechaty/puppet/issues/187') + this.log.warn('Message', 'listener() payload.listenerId should be set! See: https://github.com/wechaty/puppet/issues/187') console.error('Puppet: %s@%s', this.wechaty.puppet.name(), this.wechaty.puppet.version()) console.error(new Error().stack) } @@ -784,7 +783,7 @@ class MessageMixin extends MixinBase implements SayableSayer { const oldText = this.payload.text || '' const newText = (this.payload.textContent || []).map(item => item.text).join('') if (newText && oldText !== newText) { - log.warn('Message', `got different text, old: ${oldText}, new: ${newText}`) + this.log.warn('Message', `got different text, old: ${oldText}, new: ${newText}`) } // still use old text before we deprecate old text field @@ -821,7 +820,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } catch (e) { this.wechaty.emitError(e) - log.verbose(`Can not retrieve the recalled message with id ${originalMessageId}.`) + this.log.verbose(`Can not retrieve the recalled message with id ${originalMessageId}.`) } return undefined } @@ -918,7 +917,7 @@ class MessageMixin extends MixinBase implements SayableSayer { async say ( sayable: Sayable, ): Promise { - log.verbose('Message', 'say(%s)', sayable) + this.log.verbose('Message', 'say(%s)', sayable) const talker = this.talker() const room = this.room() @@ -939,7 +938,7 @@ class MessageMixin extends MixinBase implements SayableSayer { text: string, mentionList?: ContactInterface[], ): Promise { - log.verbose('Message', 'say(%s)', text) + this.log.verbose('Message', 'say(%s)', text) const talker = this.talker() const room = this.room() @@ -973,7 +972,7 @@ class MessageMixin extends MixinBase implements SayableSayer { */ async recall (): Promise { - log.verbose('Message', 'recall()') + this.log.verbose('Message', 'recall()') const isSuccess = await this.wechaty.puppet.messageRecall(this.id) return isSuccess } @@ -1021,7 +1020,7 @@ class MessageMixin extends MixinBase implements SayableSayer { return talker.id === this.wechaty.puppet.currentUserId } catch (e) { this.wechaty.emitError(e) - log.error('Message', 'self() rejection: %s', (e as Error).message) + this.log.error('Message', 'self() rejection: %s', (e as Error).message) return false } } @@ -1046,7 +1045,7 @@ class MessageMixin extends MixinBase implements SayableSayer { * console.log(contactList) */ async mentionList (): Promise { - log.verbose('Message', 'mentionList()') + this.log.verbose('Message', 'mentionList()') const room = this.room() if (this.type() !== PUPPET.types.Message.Text || !room) { @@ -1105,7 +1104,7 @@ class MessageMixin extends MixinBase implements SayableSayer { // filter blank string mentionNameList = mentionNameList.filter(s => !!s) - log.verbose('Message', 'mentionList() text = "%s", mentionNameList = "%s"', + this.log.verbose('Message', 'mentionList() text = "%s", mentionNameList = "%s"', this.text(), JSON.stringify(mentionNameList), ) @@ -1120,13 +1119,13 @@ class MessageMixin extends MixinBase implements SayableSayer { contactList = contactList.concat.apply([], contactListNested) if (contactList.length === 0) { - log.silly('Message', `message.mentionList() can not found member using room.member() from mentionList, mention string: ${JSON.stringify(mentionNameList)}`) + this.log.silly('Message', `message.mentionList() can not found member using room.member() from mentionList, mention string: ${JSON.stringify(mentionNameList)}`) } return contactList } isMentionAll (): boolean { - log.verbose('Message', 'isMentionAll()') + this.log.verbose('Message', 'isMentionAll()') const room = this.room() if (this.type() !== PUPPET.types.Message.Text || !room) { @@ -1147,7 +1146,7 @@ class MessageMixin extends MixinBase implements SayableSayer { * @deprecated mention() DEPRECATED. use mentionList() instead. */ async mention (): Promise { - log.warn('Message', 'mention() DEPRECATED. use mentionList() instead. Call stack: %s', + this.log.warn('Message', 'mention() DEPRECATED. use mentionList() instead. Call stack: %s', new Error().stack, ) return this.mentionList() @@ -1172,7 +1171,7 @@ class MessageMixin extends MixinBase implements SayableSayer { case PUPPET.types.TextContentType.At: return '' default: - log.warn(`got unknown type ${type} in text content`) + this.log.warn(`got unknown type ${type} in text content`) return '' } }).join('') @@ -1230,7 +1229,7 @@ class MessageMixin extends MixinBase implements SayableSayer { * @ignore */ async ready (forceSync = false): Promise { - log.verbose('Message', 'ready()') + this.log.verbose('Message', 'ready()') if (this.isReady() && !forceSync) { return @@ -1249,7 +1248,7 @@ class MessageMixin extends MixinBase implements SayableSayer { throw new Error('no talkerId found for talker') } - log.warn('Message', 'ready() payload.talkerId not exist! See: https://github.com/wechaty/puppet/issues/187') + this.log.warn('Message', 'ready() payload.talkerId not exist! See: https://github.com/wechaty/puppet/issues/187') console.error('Puppet: %s@%s', this.wechaty.puppet.name(), this.wechaty.puppet.version()) console.error(new Error().stack) } @@ -1263,7 +1262,7 @@ class MessageMixin extends MixinBase implements SayableSayer { */ listenerId = this.payload.toId - log.warn('Message', 'ready() payload.listenerId should be set! See: https://github.com/wechaty/puppet/issues/187') + this.log.warn('Message', 'ready() payload.listenerId should be set! See: https://github.com/wechaty/puppet/issues/187') console.error('Puppet: %s@%s', this.wechaty.puppet.name(), this.wechaty.puppet.version()) console.error(new Error().stack) } @@ -1303,7 +1302,7 @@ class MessageMixin extends MixinBase implements SayableSayer { // default: // const e = new Error('ready() unsupported typeApp(): ' + this.typeApp()) - // log.warn('PuppeteerMessage', e.message) + // this.log.warn('PuppeteerMessage', e.message) // throw e // } // break @@ -1333,7 +1332,7 @@ class MessageMixin extends MixinBase implements SayableSayer { * .start() */ async forward (to: RoomInterface | ContactInterface): Promise { - log.verbose('Message', 'forward(%s)', to) + this.log.verbose('Message', 'forward(%s)', to) // let roomId // let contactId @@ -1348,7 +1347,7 @@ class MessageMixin extends MixinBase implements SayableSayer { return msg } } catch (e) { - log.error('Message', 'forward(%s) exception: %s', to, e) + this.log.error('Message', 'forward(%s) exception: %s', to, e) throw e } } @@ -1393,7 +1392,7 @@ class MessageMixin extends MixinBase implements SayableSayer { * fileBox.toFile(fileName) */ async toFileBox (): Promise { - log.verbose('Message', 'toFileBox()') + this.log.verbose('Message', 'toFileBox()') if (this.type() === PUPPET.types.Message.Text) { throw new Error('text message no file') } @@ -1415,7 +1414,7 @@ class MessageMixin extends MixinBase implements SayableSayer { * fileBox.toFile(fileName) */ toImage (): ImageInterface { - log.verbose('Message', 'toImage() for message id: %s', this.id) + this.log.verbose('Message', 'toImage() for message id: %s', this.id) if (this.type() !== PUPPET.types.Message.Image) { throw new Error(`not a image type message. type: ${this.type()}`) } @@ -1436,7 +1435,7 @@ class MessageMixin extends MixinBase implements SayableSayer { * const { text, noSpeech } = await voice.text() */ toVoice (): VoiceInterface { - log.verbose('Message', 'toVoice() for message id: %s', this.id) + this.log.verbose('Message', 'toVoice() for message id: %s', this.id) if (this.type() !== PUPPET.types.Message.Audio) { throw new Error(`not a voice type message. type: ${this.type()}`) } @@ -1444,7 +1443,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } async toPreview (): Promise { - log.verbose('Message', 'toPreview() for message id: %s', this.id) + this.log.verbose('Message', 'toPreview() for message id: %s', this.id) if (!ALLOW_PREVIEW_TYPES.some(e => e === this.type())) { throw new Error(`cannot get preview for this type. type: ${this.type}`) } @@ -1460,7 +1459,7 @@ class MessageMixin extends MixinBase implements SayableSayer { * @returns {Promise} */ async toContact (): Promise { - log.verbose('Message', 'toContact()') + this.log.verbose('Message', 'toContact()') if (this.type() !== PUPPET.types.Message.Contact) { throw new Error('message not a ShareCard') @@ -1481,7 +1480,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } async toUrlLink (): Promise { - log.verbose('Message', 'toUrlLink()') + this.log.verbose('Message', 'toUrlLink()') if (!this.payload) { throw new Error('no payload') @@ -1497,7 +1496,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } async toMiniProgram (): Promise { - log.verbose('Message', 'toMiniProgram()') + this.log.verbose('Message', 'toMiniProgram()') if (!this.payload) { throw new Error('no payload') @@ -1513,7 +1512,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } async toLocation (): Promise { - log.verbose('Message', 'toLocation()') + this.log.verbose('Message', 'toLocation()') if (!this.payload) { throw new Error('no payload') @@ -1529,7 +1528,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } public async toPost (): Promise { - log.verbose('Message', 'toPost()') + this.log.verbose('Message', 'toPost()') if (!this.payload) { throw new Error('no payload') @@ -1545,7 +1544,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } public async toChannel (): Promise { - log.verbose('Message', 'toChannel()') + this.log.verbose('Message', 'toChannel()') if (!this.payload) { throw new Error('no payload') @@ -1560,7 +1559,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } public async toChannelCard (): Promise { - log.verbose('Message', 'toChannelCard()') + this.log.verbose('Message', 'toChannelCard()') if (!this.payload) { throw new Error('no payload') @@ -1575,7 +1574,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } public async toConsultCard (): Promise { - log.verbose('Message', 'toConsultCard()') + this.log.verbose('Message', 'toConsultCard()') if (!this.payload) { throw new Error('no payload') @@ -1590,7 +1589,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } public async toPremiumOnlineAppointmentCard (): Promise { - log.verbose('Message', 'toPremiumOnlineAppointmentCard()') + this.log.verbose('Message', 'toPremiumOnlineAppointmentCard()') if (!this.payload) { throw new Error('no payload') @@ -1605,7 +1604,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } public async toCallRecord (): Promise { - log.verbose('Message', 'toCallRecord()') + this.log.verbose('Message', 'toCallRecord()') if (!this.payload) { throw new Error('no payload') @@ -1620,7 +1619,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } public async toChatHistory (): Promise { - log.verbose('Message', 'toChatHistory()') + this.log.verbose('Message', 'toChatHistory()') if (!this.payload) { throw new Error('no payload') @@ -1635,7 +1634,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } public async toWxxdProduct (): Promise { - log.verbose('Message', 'toWxxdProduct()') + this.log.verbose('Message', 'toWxxdProduct()') if (!this.payload) { throw new Error('no payload') @@ -1652,7 +1651,7 @@ class MessageMixin extends MixinBase implements SayableSayer { } public async toWxxdOrder (): Promise { - log.verbose('Message', 'toWxxdOrder()') + this.log.verbose('Message', 'toWxxdOrder()') if (!this.payload) { throw new Error('no payload') @@ -1669,12 +1668,12 @@ class MessageMixin extends MixinBase implements SayableSayer { } async toSayable (): Promise { - log.verbose('Message', 'toSayable()') + this.log.verbose('Message', 'toSayable()') return messageToSayable(this) } async getQuotedMessage (): Promise { - log.verbose('Message', 'getQuotedMessage()') + this.log.verbose('Message', 'getQuotedMessage()') if (!this.payload) { throw new Error('no payload') } @@ -1692,7 +1691,7 @@ class MessageMixin extends MixinBase implements SayableSayer { try { additionalInfoObj = JSON.parse(this.payload.additionalInfo) } catch (e) { - log.warn('Message', 'additionalInfo() parse failed, additionalInfo: %s', this.payload.additionalInfo) + this.log.warn('Message', 'additionalInfo() parse failed, additionalInfo: %s', this.payload.additionalInfo) } } return additionalInfoObj diff --git a/src/user-modules/mini-program.ts b/src/user-modules/mini-program.ts index 0e22ab9c4..0c8b87cd0 100644 --- a/src/user-modules/mini-program.ts +++ b/src/user-modules/mini-program.ts @@ -20,7 +20,6 @@ import type * as PUPPET from '@juzi/wechaty-puppet' import type { Constructor } from 'clone-class' -import { log } from '../config.js' import { validationMixin } from '../user-mixins/validation.js' @@ -37,7 +36,7 @@ class MiniProgramMixin extends wechatifyMixinBase() { * */ static async create (): Promise { - log.verbose('MiniProgram', 'create()') + this.log.verbose('MiniProgram', 'create()') // TODO: get appid and username from wechat const payload: PUPPET.payloads.MiniProgram = { @@ -60,7 +59,7 @@ class MiniProgramMixin extends wechatifyMixinBase() { public readonly payload: PUPPET.payloads.MiniProgram, ) { super() - log.verbose('MiniProgram', 'constructor()') + this.log.verbose('MiniProgram', 'constructor()') // Huan(202110): it is ok to create a raw one without wechaty instance // guardWechatifyClass.call(this, MiniProgram) } diff --git a/src/user-modules/moment.ts b/src/user-modules/moment.ts index 74c2693ec..292a067da 100644 --- a/src/user-modules/moment.ts +++ b/src/user-modules/moment.ts @@ -17,7 +17,6 @@ * limitations under the License. * */ -import { log } from '@juzi/wechaty-puppet' import type { Constructor } from 'clone-class' import type { ContactInterface } from './contact.js' @@ -47,19 +46,19 @@ class MomentMixin extends wechatifyMixinBase() { } static async signature (signature?: string): Promise { - log.verbose('Moment', 'signature(%s)', signature) + this.log.verbose('Moment', 'signature(%s)', signature) return this.wechaty.puppet.momentSignature(signature) } static async coverage (coverage?: FileBoxInterface): Promise { - log.verbose('Moment', 'coverage(%s)', JSON.stringify(coverage)) + this.log.verbose('Moment', 'coverage(%s)', JSON.stringify(coverage)) return this.wechaty.puppet.momentCoverage(coverage) } static async visibleList (): Promise { - log.verbose('Moment', 'visibleList()') + this.log.verbose('Moment', 'visibleList()') try { const contactIdList: string[] = await this.wechaty.puppet.momentVisibleList() @@ -84,7 +83,7 @@ class MomentMixin extends wechatifyMixinBase() { } catch (e) { this.wechaty.emitError(e) - log.error('Moment', 'this.wechaty.puppet.momentVisibleList() rejected: %s', (e as Error).message) + this.log.error('Moment', 'this.wechaty.puppet.momentVisibleList() rejected: %s', (e as Error).message) return [] } } @@ -94,7 +93,7 @@ class MomentMixin extends wechatifyMixinBase() { */ constructor () { super() - log.verbose('Moment', 'constructor()') + this.log.verbose('Moment', 'constructor()') } } diff --git a/src/user-modules/post.ts b/src/user-modules/post.ts index f7f1db8cb..b7dd82692 100644 --- a/src/user-modules/post.ts +++ b/src/user-modules/post.ts @@ -135,13 +135,13 @@ class PostMixin extends wechatifyMixinBase() { static create ( payload: PUPPET.payloads.PostClient, ): PostInterface { - log.verbose('Post', 'create()') + this.log.verbose('Post', 'create()') return new this(payload) } static load (id: string): PostInterface { - log.verbose('Post', 'static load(%s)', id) + this.log.verbose('Post', 'static load(%s)', id) /** * Must NOT use `Post` at here @@ -157,7 +157,7 @@ class PostMixin extends wechatifyMixinBase() { static async find ( filter: PUPPET.filters.Post, ): Promise { - log.verbose('Post', 'find(%s)', + this.log.verbose('Post', 'find(%s)', JSON.stringify(filter), ) @@ -181,7 +181,7 @@ class PostMixin extends wechatifyMixinBase() { postList : PostInterface[], nextPageToken? : string, ]> { - log.verbose('Post', 'findAll(%s%s)', + this.log.verbose('Post', 'findAll(%s%s)', JSON.stringify(filter), pagination ? ', ' + JSON.stringify(pagination) : '', ) @@ -231,7 +231,7 @@ class PostMixin extends wechatifyMixinBase() { idOrPayload: string | PUPPET.payloads.Post, ) { super() - log.verbose('Post', 'constructor(%s)', + this.log.verbose('Post', 'constructor(%s)', typeof idOrPayload === 'string' ? idOrPayload : JSON.stringify(idOrPayload.id), @@ -255,7 +255,7 @@ class PostMixin extends wechatifyMixinBase() { } async author (): Promise { - log.silly('Post', 'author()') + this.log.silly('Post', 'author()') if (PUPPET.payloads.isPostClient(this.payload)) { return this.wechaty.currentUser @@ -269,7 +269,7 @@ class PostMixin extends wechatifyMixinBase() { } async root (): Promise { - log.silly('Post', 'root()') + this.log.silly('Post', 'root()') if (!this.payload.rootId) { return undefined @@ -281,7 +281,7 @@ class PostMixin extends wechatifyMixinBase() { } async parent (): Promise { - log.silly('Post', 'parent()') + this.log.silly('Post', 'parent()') if (!this.payload.parentId) { return undefined } @@ -292,7 +292,7 @@ class PostMixin extends wechatifyMixinBase() { } async sync (): Promise { - log.silly('Post', 'sync()') + this.log.silly('Post', 'sync()') if (!this.id) { throw new Error('no post id found') @@ -302,7 +302,7 @@ class PostMixin extends wechatifyMixinBase() { } async ready (): Promise { - log.silly('Post', 'ready()') + this.log.silly('Post', 'ready()') if (!this.id) { throw new Error('no post id found') @@ -316,7 +316,7 @@ class PostMixin extends wechatifyMixinBase() { } async * [Symbol.asyncIterator] (): AsyncIterableIterator { - log.verbose('Post', '[Symbol.asyncIterator]()') + this.log.verbose('Post', '[Symbol.asyncIterator]()') const payloadToSayable = payloadToSayableWechaty(this.wechaty) @@ -341,7 +341,7 @@ class PostMixin extends wechatifyMixinBase() { } async getSayableWithIndex (sayableIndex: number) { - log.verbose('Post', 'getSayableWithIndex(%s)', sayableIndex) + this.log.verbose('Post', 'getSayableWithIndex(%s)', sayableIndex) const payloadToSayable = payloadToSayableWechaty(this.wechaty) @@ -361,7 +361,7 @@ class PostMixin extends wechatifyMixinBase() { } async getSayableWithId (id: string) { - log.verbose('Post', 'getSayableWithId(%s)', id) + this.log.verbose('Post', 'getSayableWithId(%s)', id) if (PUPPET.payloads.isPostServer(this.payload)) { const payloadToSayable = payloadToSayableWechaty(this.wechaty) @@ -376,7 +376,7 @@ class PostMixin extends wechatifyMixinBase() { async * children ( filter: PUPPET.filters.Post = {}, ): AsyncIterableIterator { - log.verbose('Post', '*children(%s)', Object.keys(filter).length ? JSON.stringify(filter) : '') + this.log.verbose('Post', '*children(%s)', Object.keys(filter).length ? JSON.stringify(filter) : '') const pagination: PUPPET.filters.PaginationRequest = { pageSize: 100, @@ -413,7 +413,7 @@ class PostMixin extends wechatifyMixinBase() { async * descendants ( filter: PUPPET.filters.Post = {}, ): AsyncIterableIterator { - log.verbose('Post', '*descendants(%s)', Object.keys(filter).length ? JSON.stringify(filter) : '') + this.log.verbose('Post', '*descendants(%s)', Object.keys(filter).length ? JSON.stringify(filter) : '') for await (const post of this.children(filter)) { yield post @@ -424,7 +424,7 @@ class PostMixin extends wechatifyMixinBase() { async * likes ( filter: PUPPET.filters.Post = {}, ): AsyncIterableIterator { - log.verbose('Post', '*likes(%s)', Object.keys(filter).length ? JSON.stringify(filter) : '') + this.log.verbose('Post', '*likes(%s)', Object.keys(filter).length ? JSON.stringify(filter) : '') return this.taps({ ...filter, type: PUPPET.types.Tap.Like, @@ -434,7 +434,7 @@ class PostMixin extends wechatifyMixinBase() { async * taps ( filter: PUPPET.filters.Tap = {}, ): AsyncIterableIterator { - log.verbose('Post', '*taps(%s)', Object.keys(filter).length ? JSON.stringify(filter) : '') + this.log.verbose('Post', '*taps(%s)', Object.keys(filter).length ? JSON.stringify(filter) : '') const pagination: PUPPET.filters.PaginationRequest = {} @@ -463,7 +463,7 @@ class PostMixin extends wechatifyMixinBase() { | Exclude | Exclude[], ): Promise { - log.verbose('Post', 'reply(%s)', sayable) + this.log.verbose('Post', 'reply(%s)', sayable) if (!this.id) { console.error('You can only call `reply()` on received posts, but it seems that you are trying to call reply on a post created from local.') @@ -495,7 +495,7 @@ class PostMixin extends wechatifyMixinBase() { async like () : Promise async like (status?: boolean): Promise { - log.verbose('Post', 'like(%s)', typeof status === 'undefined' ? '' : status) + this.log.verbose('Post', 'like(%s)', typeof status === 'undefined' ? '' : status) if (typeof status === 'undefined') { return this.tap( @@ -519,7 +519,7 @@ class PostMixin extends wechatifyMixinBase() { type : PUPPET.types.Tap, status? : boolean, ): Promise { - log.verbose('Post', 'tap(%s%s)', + this.log.verbose('Post', 'tap(%s%s)', PUPPET.types.Tap[type], typeof status === 'undefined' ? '' @@ -540,7 +540,7 @@ class PostMixin extends wechatifyMixinBase() { tapList : Tap[], nextPageToken? : string, ]> { - log.verbose('Post', 'tapFind()') + this.log.verbose('Post', 'tapFind()') if (!this.id) { throw new Error('can not get tapFind for client created post') @@ -560,7 +560,7 @@ class PostMixin extends wechatifyMixinBase() { for (const [ i, contactId ] of data.contactId.entries()) { const contact = await this.wechaty.Contact.find({ id: contactId }) if (!contact) { - log.warn('Post', 'tapFind() contact not found for id: %s', contactId) + this.log.warn('Post', 'tapFind() contact not found for id: %s', contactId) continue } @@ -579,17 +579,17 @@ class PostMixin extends wechatifyMixinBase() { } location (): LocationInterface | undefined { - log.verbose('Post', 'location()') + this.log.verbose('Post', 'location()') if (!this.payload.location) { - log.warn('this post has no location info') + this.log.warn('this post has no location info') return } return new this.wechaty.Location(this.payload.location) } async visibleList (): Promise { - log.verbose('Post', 'visibleList()') + this.log.verbose('Post', 'visibleList()') if (!this.payload.visibleList) { return [] diff --git a/src/user-modules/premium-online-appointment-card.ts b/src/user-modules/premium-online-appointment-card.ts index 50b342d2c..4695432e8 100644 --- a/src/user-modules/premium-online-appointment-card.ts +++ b/src/user-modules/premium-online-appointment-card.ts @@ -1,7 +1,6 @@ import type * as PUPPET from '@juzi/wechaty-puppet' import type { Constructor } from 'clone-class' -import { log } from '../config.js' import { validationMixin } from '../user-mixins/validation.js' @@ -14,7 +13,7 @@ class PremiumOnlineAppointmentCardMixin extends wechatifyMixinBase() { public readonly payload: PUPPET.payloads.PremiumOnlineAppointmentCard, ) { super() - log.verbose('PremiumOnlineAppointmentCard', 'constructor()') + this.log.verbose('PremiumOnlineAppointmentCard', 'constructor()') } static async findAll (query: { @@ -22,7 +21,7 @@ class PremiumOnlineAppointmentCardMixin extends wechatifyMixinBase() { page?: number, pageSize?: number }): Promise { - log.verbose('PremiumOnlineAppointmentCard', 'findAll(%s)', JSON.stringify(query)) + this.log.verbose('PremiumOnlineAppointmentCard', 'findAll(%s)', JSON.stringify(query)) const params = { cardType: query.cardType || 'card', diff --git a/src/user-modules/room-invitation.ts b/src/user-modules/room-invitation.ts index 6e4f4e353..495f711d0 100644 --- a/src/user-modules/room-invitation.ts +++ b/src/user-modules/room-invitation.ts @@ -19,7 +19,6 @@ */ import type * as PUPPET from '@juzi/wechaty-puppet' -import { log } from '../config.js' import type { Constructor } from 'clone-class' import type { @@ -66,7 +65,7 @@ class RoomInvitationMixin extends wechatifyMixinBase() implements Accepter { public readonly id: string, ) { super() - log.verbose('RoomInvitation', 'constructor(id=%s)', id) + this.log.verbose('RoomInvitation', 'constructor(id=%s)', id) } override toString () { @@ -110,7 +109,7 @@ class RoomInvitationMixin extends wechatifyMixinBase() implements Accepter { * .start() */ async accept (): Promise { - log.verbose('RoomInvitation', 'accept()') + this.log.verbose('RoomInvitation', 'accept()') try { await this.wechaty.puppet.roomInvitationAccept(this.id) @@ -118,13 +117,13 @@ class RoomInvitationMixin extends wechatifyMixinBase() implements Accepter { const inviter = await this.inviter() const topic = await this.topic() - log.verbose('RoomInvitation', 'accept() with room(%s) & inviter(%s) ready()', + this.log.verbose('RoomInvitation', 'accept() with room(%s) & inviter(%s) ready()', topic, inviter, ) } catch (e) { this.wechaty.emitError(e) - log.warn('RoomInvitation', 'accept() rejection: %s', + this.log.warn('RoomInvitation', 'accept() rejection: %s', (e && (e as Error).message) || e, ) } @@ -144,7 +143,7 @@ class RoomInvitationMixin extends wechatifyMixinBase() implements Accepter { * .start() */ async inviter (): Promise { - log.verbose('RoomInvitation', 'inviter()') + this.log.verbose('RoomInvitation', 'inviter()') const payload = await this.wechaty.puppet.roomInvitationPayload(this.id) const inviter = await this.wechaty.Contact.find({ id: payload.inviterId }) @@ -174,7 +173,7 @@ class RoomInvitationMixin extends wechatifyMixinBase() implements Accepter { } async memberCount (): Promise { - log.verbose('RoomInvitation', 'memberCount()') + this.log.verbose('RoomInvitation', 'memberCount()') const payload = await this.wechaty.puppet.roomInvitationPayload(this.id) @@ -186,7 +185,7 @@ class RoomInvitationMixin extends wechatifyMixinBase() implements Accepter { * @ignore */ async memberList (): Promise { - log.verbose('RoomInvitation', 'roomMemberList()') + this.log.verbose('RoomInvitation', 'roomMemberList()') const payload = await this.wechaty.puppet.roomInvitationPayload(this.id) @@ -208,7 +207,7 @@ class RoomInvitationMixin extends wechatifyMixinBase() implements Accepter { * @returns {Promise} */ async date (): Promise { - log.verbose('RoomInvitation', 'date()') + this.log.verbose('RoomInvitation', 'date()') const payload = await this.wechaty.puppet.roomInvitationPayload(this.id) return timestampToDate(payload.timestamp) @@ -244,7 +243,7 @@ class RoomInvitationMixin extends wechatifyMixinBase() implements Accepter { static async fromJSON ( payload: string | PUPPET.payloads.RoomInvitation, ): Promise { - log.verbose('RoomInvitation', 'fromJSON(%s)', + this.log.verbose('RoomInvitation', 'fromJSON(%s)', typeof payload === 'string' ? payload : JSON.stringify(payload), @@ -273,7 +272,7 @@ class RoomInvitationMixin extends wechatifyMixinBase() implements Accepter { * .start() */ async toJSON (): Promise { - log.verbose('RoomInvitation', 'toJSON()') + this.log.verbose('RoomInvitation', 'toJSON()') const payload = await this.wechaty.puppet.roomInvitationPayload(this.id) return JSON.stringify(payload) } diff --git a/src/user-modules/room.ts b/src/user-modules/room.ts index d59faba55..0390a5ff6 100644 --- a/src/user-modules/room.ts +++ b/src/user-modules/room.ts @@ -26,7 +26,6 @@ import type { import { FOUR_PER_EM_SPACE, - log, } from '../config.js' import { wechatyCaptureException, @@ -98,7 +97,7 @@ class RoomMixin extends MixinBase implements SayableSayer { contactList : ContactInterface[], topic? : string, ): Promise { - log.verbose('Room', 'create(%s, %s)', contactList.join(','), topic) + this.log.verbose('Room', 'create(%s, %s)', contactList.join(','), topic) // if (contactList.length < 2) { // throw new Error('contactList need at least 2 contact to create a new room') @@ -112,7 +111,7 @@ class RoomMixin extends MixinBase implements SayableSayer { return room } catch (e) { this.wechaty.emitError(e) - log.error('Room', 'create() exception: %s', (e && (e as Error).stack) || (e as Error).message || (e as Error)) + this.log.error('Room', 'create() exception: %s', (e && (e as Error).stack) || (e as Error).message || (e as Error)) throw e } } @@ -123,7 +122,7 @@ class RoomMixin extends MixinBase implements SayableSayer { * @returns {Promise} */ static async parseDynamicQRCode (url: string): Promise { - log.info('Room', 'parseDynamicQRCode(%s)', url) + this.log.info('Room', 'parseDynamicQRCode(%s)', url) if (!url) { throw new Error('parseDynamicQRCode() url is required') } @@ -158,7 +157,7 @@ class RoomMixin extends MixinBase implements SayableSayer { static async findAll ( query? : PUPPET.filters.Room, ): Promise { - log.verbose('Room', 'findAll(%s)', JSON.stringify(query, stringifyFilter) || '') + this.log.verbose('Room', 'findAll(%s)', JSON.stringify(query, stringifyFilter) || '') const roomIdList = await this.wechaty.puppet.roomSearch(query) @@ -222,7 +221,7 @@ class RoomMixin extends MixinBase implements SayableSayer { static async find ( query : string | PUPPET.filters.Room, ): Promise { - log.silly('Room', 'find(%s)', JSON.stringify(query, stringifyFilter)) + this.log.silly('Room', 'find(%s)', JSON.stringify(query, stringifyFilter)) if (typeof query === 'string') { query = { topic: query } @@ -249,7 +248,7 @@ class RoomMixin extends MixinBase implements SayableSayer { } if (roomList.length > 1) { - log.warn('Room', 'find() got more than one(%d) result', roomList.length) + this.log.warn('Room', 'find() got more than one(%d) result', roomList.length) } for (const [ idx, room ] of roomList.entries()) { @@ -258,13 +257,13 @@ class RoomMixin extends MixinBase implements SayableSayer { // https://github.com/wechaty/wechaty/issues/1345 const valid = await this.wechaty.puppet.roomValidate(room.id) if (valid) { - log.verbose('Room', 'find() room is valid: return it', idx, room.id) + this.log.verbose('Room', 'find() room is valid: return it', idx, room.id) return room } else { - log.verbose('Room', 'find() room is invalid: skip it', idx, room.id) + this.log.verbose('Room', 'find() room is invalid: skip it', idx, room.id) } } - log.warn('Room', 'find() all %d rooms are invalid', roomList.length) + this.log.warn('Room', 'find() all %d rooms are invalid', roomList.length) return undefined } @@ -293,7 +292,7 @@ class RoomMixin extends MixinBase implements SayableSayer { opts? : { batch?: number }, ): AsyncIterable { const batch = opts?.batch ?? 100 - log.verbose('Room', 'findAllIter(%s, batch=%d)', JSON.stringify(query, stringifyFilter) || '', batch) + this.log.verbose('Room', 'findAllIter(%s, batch=%d)', JSON.stringify(query, stringifyFilter) || '', batch) if (batch <= 0) { throw new Error(`Room.findAllIter() batch must be positive, got ${batch}`) @@ -314,7 +313,7 @@ class RoomMixin extends MixinBase implements SayableSayer { for (const id of idChunk) { const payload = payloadMap.get(id) if (!payload) { - log.silly('Room', 'findAllIter() payload missing for id=%s, skip', id) + this.log.silly('Room', 'findAllIter() payload missing for id=%s, skip', id) continue } @@ -326,7 +325,7 @@ class RoomMixin extends MixinBase implements SayableSayer { if (roomChunk.length > 0) { yield roomChunk } else { - log.warn('Room', 'findAllIter() batch all missing from payloadMap, idChunk=%j', idChunk) + this.log.warn('Room', 'findAllIter() batch all missing from payloadMap, idChunk=%j', idChunk) } } } @@ -390,7 +389,7 @@ class RoomMixin extends MixinBase implements SayableSayer { public readonly id: string, ) { super() - log.silly('Room', `constructor(${id})`) + this.log.silly('Room', `constructor(${id})`) } /** @@ -443,7 +442,7 @@ class RoomMixin extends MixinBase implements SayableSayer { async ready ( forceSync = false, ): Promise { - log.silly('Room', 'ready()') + this.log.silly('Room', 'ready()') if (!forceSync && this.isReady()) { return @@ -576,7 +575,7 @@ class RoomMixin extends MixinBase implements SayableSayer { ...varList : unknown[] ): Promise { - log.verbose('Room', 'say(%s, %s)', + this.log.verbose('Room', 'say(%s, %s)', sayable, varList.join(', '), ) @@ -800,7 +799,7 @@ class RoomMixin extends MixinBase implements SayableSayer { * */ // public on (event: RoomEventName, listener: (...args: any[]) => any): this { - // log.verbose('Room', 'on(%s, %s)', event, typeof listener) + // this.log.verbose('Room', 'on(%s, %s)', event, typeof listener) // super.on(event, listener) // Room is `Sayable` // return this @@ -831,7 +830,7 @@ class RoomMixin extends MixinBase implements SayableSayer { * } */ async add (contact: ContactInterface, quoteIds?: string[]): Promise { - log.verbose('Room', 'add(%s)', contact) + this.log.verbose('Room', 'add(%s)', contact) await this.wechaty.puppet.roomAdd(this.id, contact.id, false, quoteIds) } @@ -840,7 +839,7 @@ class RoomMixin extends MixinBase implements SayableSayer { failList: ContactInterface[], failReasonList: string[], }> { - log.verbose('Room', 'addV2(%s)', contacts) + this.log.verbose('Room', 'addV2(%s)', contacts) const contactIds = contacts.map(c => c.id) try { const result = await this.wechaty.puppet.roomAddV2(this.id, contactIds, false, quoteIds) @@ -902,7 +901,7 @@ class RoomMixin extends MixinBase implements SayableSayer { * } */ async remove (contacts: ContactInterface | ContactInterface[]): Promise { - log.verbose('Room', 'del(%s)', contacts) + this.log.verbose('Room', 'del(%s)', contacts) let contactIds: string[] if (Array.isArray(contacts)) { @@ -919,7 +918,7 @@ class RoomMixin extends MixinBase implements SayableSayer { failList: ContactInterface[], failReasonList: string[], }> { - log.verbose('Room', 'addV2(%s)', contacts) + this.log.verbose('Room', 'addV2(%s)', contacts) const contactIds = contacts.map(c => c.id) try { const result = await this.wechaty.puppet.roomDelV2(this.id, contactIds) @@ -960,12 +959,12 @@ class RoomMixin extends MixinBase implements SayableSayer { * @deprecated use remove(contact) instead. */ async del (contact: ContactImpl | ContactImpl[]): Promise { - log.warn('Room', 'del() is DEPRECATED, use remove() instead.\n%s', new Error().stack) + this.log.warn('Room', 'del() is DEPRECATED, use remove() instead.\n%s', new Error().stack) return this.remove(contact) } async dismiss (): Promise { - log.verbose('Room', 'dismiss()') + this.log.verbose('Room', 'dismiss()') if (!this.owner()?.self()) { throw new Error('you cannot dismiss a room you don\'t own') @@ -975,7 +974,7 @@ class RoomMixin extends MixinBase implements SayableSayer { } // private delLocal(contact: Contact): void { - // log.verbose('Room', 'delLocal(%s)', contact) + // this.log.verbose('Room', 'delLocal(%s)', contact) // const memberIdList = this.payload && this.payload.memberIdList // if (memberIdList && memberIdList.length > 0) { @@ -999,7 +998,7 @@ class RoomMixin extends MixinBase implements SayableSayer { * await room.quit() */ async quit (): Promise { - log.verbose('Room', 'quit() %s', this) + this.log.verbose('Room', 'quit() %s', this) await this.wechaty.puppet.roomQuit(this.id) } @@ -1038,9 +1037,9 @@ class RoomMixin extends MixinBase implements SayableSayer { * .start() */ async topic (newTopic?: string): Promise { - log.verbose('Room', 'topic(%s)', newTopic || '') + this.log.verbose('Room', 'topic(%s)', newTopic || '') if (!this.isReady()) { - log.warn('Room', 'topic() room not ready') + this.log.warn('Room', 'topic() room not ready') throw new Error('not ready') } @@ -1064,7 +1063,7 @@ class RoomMixin extends MixinBase implements SayableSayer { const future = this.wechaty.puppet .roomTopic(this.id, newTopic) .catch(e => { - log.warn('Room', 'topic(newTopic=%s) exception: %s', + this.log.warn('Room', 'topic(newTopic=%s) exception: %s', newTopic, (e && e.message) || e, ) wechatyCaptureException(e) @@ -1103,7 +1102,7 @@ class RoomMixin extends MixinBase implements SayableSayer { * console.log(`room announce change from ${oldAnnounce} to ${room.announce()}`) */ async announce (text?: string): Promise { - log.verbose('Room', 'announce(%s)', + this.log.verbose('Room', 'announce(%s)', typeof text === 'undefined' ? '' : `"${text || ''}"`, @@ -1125,7 +1124,7 @@ class RoomMixin extends MixinBase implements SayableSayer { * @returns {Promise} */ async qrCode (): Promise { - log.verbose('Room', 'qrCode()') + this.log.verbose('Room', 'qrCode()') const qrcodeValue = await this.wechaty.puppet.roomQRCode(this.id) return guardQrCodeValue(qrcodeValue) } @@ -1201,7 +1200,7 @@ class RoomMixin extends MixinBase implements SayableSayer { } } catch (e) { this.wechaty.emitError(e) - log.error('Room', 'readMark() exception: %s', (e as Error).message) + this.log.error('Room', 'readMark() exception: %s', (e as Error).message) } } @@ -1210,7 +1209,7 @@ class RoomMixin extends MixinBase implements SayableSayer { await this.wechaty.puppet.endConversation(this.id) } catch (e) { this.wechaty.emitError(e) - log.error('Room', 'endConversation() exception: %s', (e as Error).message) + this.log.error('Room', 'endConversation() exception: %s', (e as Error).message) } } @@ -1278,7 +1277,7 @@ class RoomMixin extends MixinBase implements SayableSayer { async memberAll ( query?: string | PUPPET.filters.RoomMember, ): Promise { - log.silly('Room', 'memberAll(%s)', + this.log.silly('Room', 'memberAll(%s)', JSON.stringify(query) || '', ) @@ -1326,7 +1325,7 @@ class RoomMixin extends MixinBase implements SayableSayer { async member ( queryArg: string | PUPPET.filters.RoomMember, ): Promise { - log.verbose('Room', 'member(%s)', JSON.stringify(queryArg)) + this.log.verbose('Room', 'member(%s)', JSON.stringify(queryArg)) let memberList: ContactInterface[] // ISSUE #622 @@ -1342,7 +1341,7 @@ class RoomMixin extends MixinBase implements SayableSayer { } if (memberList.length > 1) { - log.warn('Room', 'member(%s) get %d contacts, use the first one by default', JSON.stringify(queryArg), memberList.length) + this.log.warn('Room', 'member(%s) get %d contacts, use the first one by default', JSON.stringify(queryArg), memberList.length) } return memberList[0]! } @@ -1359,12 +1358,12 @@ class RoomMixin extends MixinBase implements SayableSayer { * await room.memberList() */ protected async memberList (): Promise { - log.verbose('Room', 'memberList()') + this.log.verbose('Room', 'memberList()') const memberIdList = await this.wechaty.puppet.roomMemberList(this.id) // if (!memberIdList) { - // log.warn('Room', 'memberList() not ready') + // this.log.warn('Room', 'memberList() not ready') // return [] // } @@ -1382,7 +1381,7 @@ class RoomMixin extends MixinBase implements SayableSayer { * const owner = room.owner() */ owner (): undefined | ContactInterface { - log.verbose('Room', 'owner()') + this.log.verbose('Room', 'owner()') const ownerId = this.payload && this.payload.ownerId if (!ownerId) { @@ -1402,10 +1401,10 @@ class RoomMixin extends MixinBase implements SayableSayer { * const adminList = room.adminList() */ async adminList (): Promise { - log.verbose('Room', 'adminList()') + this.log.verbose('Room', 'adminList()') if (!this.isReady()) { - log.warn('Room', 'adminList() room not ready') + this.log.warn('Room', 'adminList() room not ready') return [] } @@ -1428,7 +1427,7 @@ class RoomMixin extends MixinBase implements SayableSayer { async avatar (): Promise async avatar (avatar: FileBoxInterface): Promise async avatar (avatar?: FileBoxInterface): Promise { - log.verbose('Room', 'avatar()') + this.log.verbose('Room', 'avatar()') if (!avatar && this.payload?.avatar) { return FileBox.fromUrl(this.payload.avatar) @@ -1443,7 +1442,7 @@ class RoomMixin extends MixinBase implements SayableSayer { try { additionalInfoObj = JSON.parse(this.payload.additionalInfo) } catch (e) { - log.warn('Room', 'additionalInfo() parse failed, additionalInfo: %s', this.payload.additionalInfo) + this.log.warn('Room', 'additionalInfo() parse failed, additionalInfo: %s', this.payload.additionalInfo) } } return additionalInfoObj @@ -1464,12 +1463,12 @@ class RoomMixin extends MixinBase implements SayableSayer { } async addAdmins (contactList: ContactInterface[]): Promise { - log.verbose('Room', 'addAdmins(%s)', contactList) + this.log.verbose('Room', 'addAdmins(%s)', contactList) await this.wechaty.puppet.roomAddAdmins(this.id, contactList.map(c => c.id)) } async delAdmins (contactList: ContactInterface[]): Promise { - log.verbose('Room', 'delAdmins(%s)', contactList) + this.log.verbose('Room', 'delAdmins(%s)', contactList) await this.wechaty.puppet.roomDelAdmins(this.id, contactList.map(c => c.id)) } diff --git a/src/user-modules/tag-group.ts b/src/user-modules/tag-group.ts index 6f778a189..783260366 100644 --- a/src/user-modules/tag-group.ts +++ b/src/user-modules/tag-group.ts @@ -22,7 +22,6 @@ import type { TagGroupQueryFilter } from '@juzi/wechaty-puppet/dist/esm/src/sche import type { Constructor } from 'clone-class' import { concurrencyExecuter } from 'rx-queue' -import { log } from '../config.js' import { poolifyMixin } from '../user-mixins/poolify.js' import { validationMixin } from '../user-mixins/validation.js' @@ -54,7 +53,7 @@ class TagGroupMixin extends MixinBase { public readonly id: string, ) { super() - log.silly('TagGroup', 'constructor()') + this.log.silly('TagGroup', 'constructor()') } name (): string { @@ -62,7 +61,7 @@ class TagGroupMixin extends MixinBase { } static async list (): Promise { - log.verbose('TagGroup', 'list()') + this.log.verbose('TagGroup', 'list()') try { const tagGroupIds = await this.wechaty.puppet.tagGroupList() @@ -103,13 +102,13 @@ class TagGroupMixin extends MixinBase { } catch (e) { this.wechaty.emitError(e) - log.error('TagGroup', 'list() exception: %s', (e as Error).message) + this.log.error('TagGroup', 'list() exception: %s', (e as Error).message) return [] } } static async createTagGroup (name: string): Promise { - log.verbose('TagGroup', 'createTagGroup(%s, %s)', name) + this.log.verbose('TagGroup', 'createTagGroup(%s, %s)', name) try { const groupId = await this.wechaty.puppet.tagGroupAdd(name) @@ -119,23 +118,23 @@ class TagGroupMixin extends MixinBase { } } catch (e) { this.wechaty.emitError(e) - log.error('Contact', 'createTag() exception: %s', (e as Error).message) + this.log.error('Contact', 'createTag() exception: %s', (e as Error).message) } } static async deleteTagGroup (tagGroup: TagGroupInterface): Promise { - log.verbose('TagGroup', 'deleteTagGroup(%s)', tagGroup) + this.log.verbose('TagGroup', 'deleteTagGroup(%s)', tagGroup) try { await this.wechaty.puppet.tagGroupDelete(tagGroup.id) } catch (e) { this.wechaty.emitError(e) - log.error('TagGroup', 'deleteTagGroup() exception: %s', (e as Error).message) + this.log.error('TagGroup', 'deleteTagGroup() exception: %s', (e as Error).message) } } async tags (): Promise { - log.verbose('TagGroup', 'tags(%s)', this) + this.log.verbose('TagGroup', 'tags(%s)', this) try { const tagIdList = await this.wechaty.puppet.tagGroupTagList(this.id) @@ -154,14 +153,14 @@ class TagGroupMixin extends MixinBase { } catch (e) { this.wechaty.emitError(e) - log.error('TagGroup', 'list() exception: %s', (e as Error).message) + this.log.error('TagGroup', 'list() exception: %s', (e as Error).message) return [] } } static async find (filter: TagGroupQueryFilter): Promise { - log.silly('TagGroup', 'find(%s)', JSON.stringify(filter)) + this.log.silly('TagGroup', 'find(%s)', JSON.stringify(filter)) if (filter.id) { const tagGroup = (this.wechaty.TagGroup as any as typeof TagGroupImpl).load(filter.id) @@ -216,10 +215,10 @@ class TagGroupMixin extends MixinBase { async ready ( forceSync = false, ): Promise { - log.silly('TagGroup', 'ready() @ %s with TagGroup="%s"', this.wechaty.puppet, this.id) + this.log.silly('TagGroup', 'ready() @ %s with TagGroup="%s"', this.wechaty.puppet, this.id) if (!forceSync && this.isReady()) { // already ready - log.silly('TagGroup', 'ready() isReady() true') + this.log.silly('TagGroup', 'ready() isReady() true') return } @@ -227,7 +226,7 @@ class TagGroupMixin extends MixinBase { this.payload = await this.wechaty.puppet.tagGroupPayload(this.id) } catch (e) { this.wechaty.emitError(e) - log.verbose('TagGroup', 'ready() this.wechaty.puppet.tagGroupPayload(%s) exception: %s', + this.log.verbose('TagGroup', 'ready() this.wechaty.puppet.tagGroupPayload(%s) exception: %s', this.id, (e as Error).message, ) diff --git a/src/user-modules/tag.ts b/src/user-modules/tag.ts index 02cca083f..7e9c49390 100644 --- a/src/user-modules/tag.ts +++ b/src/user-modules/tag.ts @@ -22,7 +22,6 @@ import type { TagQueryFilter } from '@juzi/wechaty-puppet/dist/esm/src/schemas/t import type { Constructor } from 'clone-class' import { concurrencyExecuter } from 'rx-queue' -import { log } from '../config.js' import { poolifyMixin } from '../user-mixins/poolify.js' import assert from 'assert' @@ -56,7 +55,7 @@ class TagMixin extends MixinBase { public readonly id: string, ) { super() - log.silly('Tag', 'constructor()') + this.log.silly('Tag', 'constructor()') } type (): PUPPET.types.Tag { @@ -76,7 +75,7 @@ class TagMixin extends MixinBase { } static async list (): Promise { - log.verbose('Tag', 'list()') + this.log.verbose('Tag', 'list()') const tagIdList = await this.wechaty.puppet.tagTagList() @@ -116,7 +115,7 @@ class TagMixin extends MixinBase { } static async find (filter: TagQueryFilter): Promise { - log.silly('Tag', 'find(%s)', JSON.stringify(filter)) + this.log.silly('Tag', 'find(%s)', JSON.stringify(filter)) if (filter.id) { const tag = (this.wechaty.Tag as any as typeof TagImpl).load(filter.id) @@ -142,7 +141,7 @@ class TagMixin extends MixinBase { } static async findMulti (filters: TagQueryFilter[]): Promise { - log.silly('Tag', 'find(%s)', JSON.stringify(filters)) + this.log.silly('Tag', 'find(%s)', JSON.stringify(filters)) const filterIdList = filters.filter(i => !!i.id).map(i => i.id) const filterNameList = filters.filter(i => !!i.name).map(i => i.name) @@ -213,10 +212,10 @@ class TagMixin extends MixinBase { async ready ( forceSync = false, ): Promise { - log.silly('Tag', 'ready() @ %s with Tag key="%s"', this.wechaty.puppet, this.id) + this.log.silly('Tag', 'ready() @ %s with Tag key="%s"', this.wechaty.puppet, this.id) if (!forceSync && this.isReady()) { // already ready - log.silly('Tag', 'ready() isReady() true') + this.log.silly('Tag', 'ready() isReady() true') return } @@ -225,7 +224,7 @@ class TagMixin extends MixinBase { } catch (e) { this.wechaty.emitError(e) - log.verbose('Tag', 'ready() this.wechaty.puppet.tagPayload(%s) exception: %s', + this.log.verbose('Tag', 'ready() this.wechaty.puppet.tagPayload(%s) exception: %s', this.id, (e as Error).message, ) @@ -234,7 +233,7 @@ class TagMixin extends MixinBase { } async contactList (): Promise { - log.verbose('Tag', 'contactList() for tag : %s', this) + this.log.verbose('Tag', 'contactList() for tag : %s', this) const contactIds = await this.wechaty.puppet.tagTagContactList(this.id) const contactPromises = contactIds.map(id => this.wechaty.Contact.find({ id })) @@ -242,7 +241,7 @@ class TagMixin extends MixinBase { } async tag (contacts: ContactInterface | ContactInterface[]): Promise { - log.verbose('Tag', 'tag(%s) for tag : %s', contacts, this) + this.log.verbose('Tag', 'tag(%s) for tag : %s', contacts, this) let contactIds: string[] if (Array.isArray(contacts)) { @@ -254,7 +253,7 @@ class TagMixin extends MixinBase { } static async createTag (name: string, tagGroup?: TagGroupInterface): Promise { - log.verbose('Tag', 'createTag(%s, %s)', tagGroup, name) + this.log.verbose('Tag', 'createTag(%s, %s)', tagGroup, name) try { const tagInfoList = await this.wechaty.puppet.tagTagAdd([ name ], tagGroup?.name()) @@ -267,12 +266,12 @@ class TagMixin extends MixinBase { } } catch (e) { this.wechaty.emitError(e) - log.error('Tag', 'createTag() exception: %s', (e as Error).message) + this.log.error('Tag', 'createTag() exception: %s', (e as Error).message) } } static async createMultiTag (nameList: string[], tagGroup?: TagGroupInterface): Promise { - log.verbose('Tag', 'createMultiTag(%s, %s)', tagGroup, nameList) + this.log.verbose('Tag', 'createMultiTag(%s, %s)', tagGroup, nameList) try { const tagInfoList = await this.wechaty.puppet.tagTagAdd(nameList, tagGroup?.name()) @@ -285,34 +284,34 @@ class TagMixin extends MixinBase { } } catch (e) { this.wechaty.emitError(e) - log.error('Tag', 'createMultiTag() exception: %s', (e as Error).message) + this.log.error('Tag', 'createMultiTag() exception: %s', (e as Error).message) } } static async deleteTag (tagInstance: TagInterface): Promise { - log.verbose('Tag', 'deleteTag(%s, %s)', tagInstance) + this.log.verbose('Tag', 'deleteTag(%s, %s)', tagInstance) try { await this.wechaty.puppet.tagTagDelete([ tagInstance.id ]) } catch (e) { this.wechaty.emitError(e) - log.error('Tag', 'deleteTag() exception: %s', (e as Error).message) + this.log.error('Tag', 'deleteTag() exception: %s', (e as Error).message) } } static async deleteMultiTag (tagInstances: TagInterface[]): Promise { - log.verbose('Tag', 'deleteMultiTag(%s, %s)', tagInstances) + this.log.verbose('Tag', 'deleteMultiTag(%s, %s)', tagInstances) try { await this.wechaty.puppet.tagTagDelete(tagInstances.map(i => i.id)) } catch (e) { this.wechaty.emitError(e) - log.error('Tag', 'deleteMultiTag() exception: %s', (e as Error).message) + this.log.error('Tag', 'deleteMultiTag() exception: %s', (e as Error).message) } } static async modifyTag (tagInstance: TagInterface, tagNewName: string): Promise { - log.verbose('Tag', 'modifyTag(%s, %s)', tagInstance) + this.log.verbose('Tag', 'modifyTag(%s, %s)', tagInstance) try { const tagNewInfo: PUPPET.types.TagInfo = { @@ -329,14 +328,14 @@ class TagMixin extends MixinBase { } } catch (e) { this.wechaty.emitError(e) - log.error('Tag', 'modifyTag() exception: %s', (e as Error).message) + this.log.error('Tag', 'modifyTag() exception: %s', (e as Error).message) } } static async modifyMultiTag ( tagInfos: Array<{ tag: TagInterface, newName: string }>, ): Promise { - log.verbose('Tag', 'modifyMultiTag(%o)', tagInfos) + this.log.verbose('Tag', 'modifyMultiTag(%o)', tagInfos) try { const tagNewInfoList: PUPPET.types.TagInfo[] = tagInfos.map(i => ({ @@ -353,7 +352,7 @@ class TagMixin extends MixinBase { } } catch (e) { this.wechaty.emitError(e) - log.error('Tag', 'modifyMultiTag() exception: %s', (e as Error).message) + this.log.error('Tag', 'modifyMultiTag() exception: %s', (e as Error).message) } } diff --git a/src/user-modules/url-link.ts b/src/user-modules/url-link.ts index a8d8eed0a..4d4711f9e 100644 --- a/src/user-modules/url-link.ts +++ b/src/user-modules/url-link.ts @@ -25,7 +25,6 @@ import type { Constructor } from 'clone-class' import { openGraph } from '../helper-functions/open-graph.js' import { validationMixin } from '../user-mixins/validation.js' import { wechatifyMixinBase } from '../user-mixins/wechatify.js' -import { log } from '../config.js' import type { FileBoxInterface } from 'file-box' class UrlLinkMixin extends wechatifyMixinBase() { @@ -44,7 +43,7 @@ class UrlLinkMixin extends wechatifyMixinBase() { > >, ): Promise { - log.verbose('UrlLink', 'create(%s)', url) + this.log.verbose('UrlLink', 'create(%s)', url) const meta = await openGraph(url) @@ -102,7 +101,7 @@ class UrlLinkMixin extends wechatifyMixinBase() { public readonly payload: PUPPET.payloads.UrlLink, ) { super() - log.verbose('UrlLink', 'constructor()') + this.log.verbose('UrlLink', 'constructor()') // Huan(202110): it is ok to create a raw one without wechaty instance // guardWechatifyClass.call(this, UrlLink) } diff --git a/src/user-modules/voice.ts b/src/user-modules/voice.ts index 6f93a1b66..7672cf528 100644 --- a/src/user-modules/voice.ts +++ b/src/user-modules/voice.ts @@ -23,7 +23,6 @@ import type { import type { Constructor } from 'clone-class' import type * as PUPPET from '@juzi/wechaty-puppet' import { validationMixin } from '../user-mixins/validation.js' -import { log } from '../config.js' import { wechatifyMixinBase, @@ -62,7 +61,7 @@ function isUnsupportedError (e: unknown): boolean { class VoiceMixin extends wechatifyMixinBase() { static create (id: string): VoiceInterface { - log.verbose('Voice', 'static create(%s)', id) + this.log.verbose('Voice', 'static create(%s)', id) const voice = new this(id) return voice @@ -72,7 +71,7 @@ class VoiceMixin extends wechatifyMixinBase() { public id: string, ) { super() - log.verbose('Voice', 'constructor(%s)', id) + this.log.verbose('Voice', 'constructor(%s)', id) } /** @@ -85,11 +84,11 @@ class VoiceMixin extends wechatifyMixinBase() { * path. A genuine runtime error from a working `messageVoice` is rethrown. */ async file (): Promise { - log.verbose('Voice', 'file() for id: "%s"', this.id) + this.log.verbose('Voice', 'file() for id: "%s"', this.id) const puppet = this.wechaty.puppet // puppet built against an old wechaty-puppet without the method at all if (typeof (puppet as { messageVoice?: unknown }).messageVoice !== 'function') { - log.verbose('Voice', 'file() messageVoice() absent, fallback to messageFile()') + this.log.verbose('Voice', 'file() messageVoice() absent, fallback to messageFile()') return puppet.messageFile(this.id) } try { @@ -99,7 +98,7 @@ class VoiceMixin extends wechatifyMixinBase() { if (!isUnsupportedError(e)) { throw e } - log.verbose('Voice', 'file() messageVoice() unsupported, fallback to messageFile(): %s', (e as Error).message) + this.log.verbose('Voice', 'file() messageVoice() unsupported, fallback to messageFile(): %s', (e as Error).message) const fileBox = await puppet.messageFile(this.id) return fileBox } @@ -119,11 +118,11 @@ class VoiceMixin extends wechatifyMixinBase() { * does not silently drop `noSpeech` and re-run its own paid ASR). */ async text (): Promise { - log.verbose('Voice', 'text() for id: "%s"', this.id) + this.log.verbose('Voice', 'text() for id: "%s"', this.id) const puppet = this.wechaty.puppet // puppet built against an old wechaty-puppet without the method at all if (typeof (puppet as { messageVoiceText?: unknown }).messageVoiceText !== 'function') { - log.verbose('Voice', 'text() messageVoiceText() absent, fallback to messagePayload().text') + this.log.verbose('Voice', 'text() messageVoiceText() absent, fallback to messagePayload().text') const payload = await puppet.messagePayload(this.id) return { text: payload.text || '', noSpeech: false } } @@ -134,7 +133,7 @@ class VoiceMixin extends wechatifyMixinBase() { if (!isUnsupportedError(e)) { throw e } - log.verbose('Voice', 'text() messageVoiceText() unsupported, fallback to messagePayload().text: %s', (e as Error).message) + this.log.verbose('Voice', 'text() messageVoiceText() unsupported, fallback to messagePayload().text: %s', (e as Error).message) const payload = await puppet.messagePayload(this.id) return { text: payload.text || '', noSpeech: false } } diff --git a/src/user-modules/wecom.ts b/src/user-modules/wecom.ts index e1a9b6638..446b4ab55 100644 --- a/src/user-modules/wecom.ts +++ b/src/user-modules/wecom.ts @@ -1,4 +1,4 @@ -import { log, types } from '@juzi/wechaty-puppet' +import type { types } from '@juzi/wechaty-puppet' import type { Constructor } from 'clone-class' import { validationMixin } from '../user-mixins/validation.js' @@ -41,7 +41,7 @@ class WecomMixin extends wechatifyMixinBase() { const filteredRoomIds = Array.from(rawRoomIdSet).filter(id => !actualRoomIdSet.has(id)) if (filteredRoomIds.length) { - log.warn(`these rooms cannot be applied with anti-spam strategy: ${filteredRoomIds}`) + this.log.warn(`these rooms cannot be applied with anti-spam strategy: ${filteredRoomIds}`) } if (actualRoomIdSet.size) { @@ -58,7 +58,7 @@ class WecomMixin extends wechatifyMixinBase() { */ constructor () { super() - log.verbose('Wecom', 'constructor()') + this.log.verbose('Wecom', 'constructor()') } } diff --git a/src/user-modules/wxxd-order.ts b/src/user-modules/wxxd-order.ts index 59a0794f8..e0afe8a18 100644 --- a/src/user-modules/wxxd-order.ts +++ b/src/user-modules/wxxd-order.ts @@ -2,7 +2,6 @@ import type { Constructor } from 'clone-class' import type { PaginationRequest } from '@juzi/wechaty-puppet/filters' import * as PUPPET from '@juzi/wechaty-puppet' -import { log } from '../config.js' import { poolifyMixin } from '../user-mixins/poolify.js' import { validationMixin } from '../user-mixins/validation.js' import { wechatifyMixin } from '../user-mixins/wechatify.js' @@ -26,14 +25,14 @@ class WxxdOrderMixin extends MixinBase { public readonly id: string, ) { super() - log.silly('WxxdOrder', 'constructor(%s)', id) + this.log.silly('WxxdOrder', 'constructor(%s)', id) } /** * List all orders */ static async list (query: PaginationRequest) { - log.verbose('WxxdOrder', 'list(%s)', JSON.stringify(query)) + this.log.verbose('WxxdOrder', 'list(%s)', JSON.stringify(query)) return await this.wechaty.puppet.listWxxdOrders(query) } @@ -44,7 +43,7 @@ class WxxdOrderMixin extends MixinBase { static async find ( query: string | { id: string }, ): Promise { - log.verbose('WxxdOrder', 'find(%s)', JSON.stringify(query)) + this.log.verbose('WxxdOrder', 'find(%s)', JSON.stringify(query)) const id = typeof query === 'string' ? query : query.id @@ -68,7 +67,7 @@ class WxxdOrderMixin extends MixinBase { * Send delivery for an order */ static async deliverySend (orderId: string, deliveryId: string, waybillId: string) { - log.verbose('WxxdOrder', 'deliverySend(%s, %s, %s)', orderId, deliveryId, waybillId) + this.log.verbose('WxxdOrder', 'deliverySend(%s, %s, %s)', orderId, deliveryId, waybillId) return this.wechaty.puppet.wxxdOrderDeliverySend({ orderId, deliveryId, waybillId }) } @@ -76,7 +75,7 @@ class WxxdOrderMixin extends MixinBase { * Generate after sale order */ static async genAfterSaleOrder (orderId: string, reason: string) { - log.verbose('WxxdOrder', 'genAfterSaleOrder(%s, %s)', orderId, reason) + this.log.verbose('WxxdOrder', 'genAfterSaleOrder(%s, %s)', orderId, reason) return this.wechaty.puppet.wxxdOrderGenAfterSaleOrder({ orderId, reason }) } @@ -84,7 +83,7 @@ class WxxdOrderMixin extends MixinBase { * Update order merchant notes */ static async updateWxxdMerchantnotes (orderId: string, merchantNotes: string) { - log.verbose('WxxdOrder', 'updateWxxdMerchantnotes(%s, %s)', orderId, merchantNotes) + this.log.verbose('WxxdOrder', 'updateWxxdMerchantnotes(%s, %s)', orderId, merchantNotes) return this.wechaty.puppet.updateWxxdMerchantnotes(orderId, merchantNotes) } @@ -93,10 +92,10 @@ class WxxdOrderMixin extends MixinBase { } async ready (forceSync = false): Promise { - log.silly('WxxdOrder', 'ready() @ %s with id="%s"', this.wechaty.puppet, this.id) + this.log.silly('WxxdOrder', 'ready() @ %s with id="%s"', this.wechaty.puppet, this.id) if (!forceSync && this.isReady()) { - log.silly('WxxdOrder', 'ready() isReady() true') + this.log.silly('WxxdOrder', 'ready() isReady() true') return } @@ -104,7 +103,7 @@ class WxxdOrderMixin extends MixinBase { this.payload = await this.wechaty.puppet.wxxdOrderPayload(this.id) } catch (e) { this.wechaty.emitError(e) - log.verbose('WxxdOrder', 'ready() this.wechaty.puppet.wxxdOrderPayload(%s) exception: %s', + this.log.verbose('WxxdOrder', 'ready() this.wechaty.puppet.wxxdOrderPayload(%s) exception: %s', this.id, (e as Error).message, ) diff --git a/src/user-modules/wxxd-product.ts b/src/user-modules/wxxd-product.ts index 046aba2b4..f146df0c9 100644 --- a/src/user-modules/wxxd-product.ts +++ b/src/user-modules/wxxd-product.ts @@ -2,7 +2,6 @@ import type { Constructor } from 'clone-class' import type { PaginationRequest } from '@juzi/wechaty-puppet/filters' import * as PUPPET from '@juzi/wechaty-puppet' -import { log } from '../config.js' import { poolifyMixin } from '../user-mixins/poolify.js' import { validationMixin } from '../user-mixins/validation.js' import { wechatifyMixin } from '../user-mixins/wechatify.js' @@ -26,14 +25,14 @@ class WxxdProductMixin extends MixinBase { public readonly id: string, ) { super() - log.silly('WxxdProduct', 'constructor(%s)', id) + this.log.silly('WxxdProduct', 'constructor(%s)', id) } /** * List all products */ static async list (query: PaginationRequest) { - log.verbose('WxxdProduct', 'list(%s)', JSON.stringify(query)) + this.log.verbose('WxxdProduct', 'list(%s)', JSON.stringify(query)) return await this.wechaty.puppet.listWxxdProducts(query) } @@ -44,7 +43,7 @@ class WxxdProductMixin extends MixinBase { static async find ( query: string | { id: string }, ): Promise { - log.verbose('WxxdProduct', 'find(%s)', JSON.stringify(query)) + this.log.verbose('WxxdProduct', 'find(%s)', JSON.stringify(query)) const id = typeof query === 'string' ? query : query.id @@ -69,10 +68,10 @@ class WxxdProductMixin extends MixinBase { } async ready (forceSync = false): Promise { - log.silly('WxxdProduct', 'ready() @ %s with id="%s"', this.wechaty.puppet, this.id) + this.log.silly('WxxdProduct', 'ready() @ %s with id="%s"', this.wechaty.puppet, this.id) if (!forceSync && this.isReady()) { - log.silly('WxxdProduct', 'ready() isReady() true') + this.log.silly('WxxdProduct', 'ready() isReady() true') return } @@ -80,7 +79,7 @@ class WxxdProductMixin extends MixinBase { this.payload = await this.wechaty.puppet.wxxdProductPayload(this.id) } catch (e) { this.wechaty.emitError(e) - log.verbose('WxxdProduct', 'ready() this.wechaty.puppet.wxxdProductPayload(%s) exception: %s', + this.log.verbose('WxxdProduct', 'ready() this.wechaty.puppet.wxxdProductPayload(%s) exception: %s', this.id, (e as Error).message, ) diff --git a/src/wechaty-mixins/io-mixin.ts b/src/wechaty-mixins/io-mixin.ts index ef50ef532..e279d4e6b 100644 --- a/src/wechaty-mixins/io-mixin.ts +++ b/src/wechaty-mixins/io-mixin.ts @@ -36,7 +36,7 @@ const ioMixin = (mixinB } override async start (): Promise { - log.verbose('WechatyIoMixin', 'start()') + this.log.verbose('WechatyIoMixin', 'start()') await super.start() @@ -48,13 +48,13 @@ const ioMixin = (mixinB * Clean the memory leak-ed io (?) */ if (this.__io) { - log.error('WechatyIoMixin', 'start() found existing io instance: stopping...') + this.log.error('WechatyIoMixin', 'start() found existing io instance: stopping...') try { await this.__io.stop() } catch (e) { this.emitError(e) } - log.error('WechatyIoMixin', 'start() found existing io instance: stopping... done') + this.log.error('WechatyIoMixin', 'start() found existing io instance: stopping... done') this.__io = undefined } @@ -66,13 +66,13 @@ const ioMixin = (mixinB wechaty : this as any, // <- FIXME: remove any, Huan(202111) }) - log.verbose('WechatyIoMixin', 'start() starting io ...') + this.log.verbose('WechatyIoMixin', 'start() starting io ...') await this.__io.start() - log.verbose('WechatyIoMixin', 'start() starting io ... done') + this.log.verbose('WechatyIoMixin', 'start() starting io ... done') } override async stop (): Promise { - log.verbose('WechatyIoMixin', 'stop()') + this.log.verbose('WechatyIoMixin', 'stop()') try { if (!this.__io) { @@ -83,9 +83,9 @@ const ioMixin = (mixinB this.__io = undefined try { - log.verbose('WechatyIoMixin', 'stop() starting io ...') + this.log.verbose('WechatyIoMixin', 'stop() starting io ...') await io.stop() - log.verbose('WechatyIoMixin', 'stop() starting io ... done') + this.log.verbose('WechatyIoMixin', 'stop() starting io ... done') } catch (e) { this.emitError(e) } diff --git a/src/wechaty-mixins/login-mixin.ts b/src/wechaty-mixins/login-mixin.ts index c70733b97..660e250cd 100644 --- a/src/wechaty-mixins/login-mixin.ts +++ b/src/wechaty-mixins/login-mixin.ts @@ -49,7 +49,7 @@ const loginMixin = { - log.verbose('WechatyLoginMixin', 'init()') + this.log.verbose('WechatyLoginMixin', 'init()') await super.init() if (this.__loginMixinInited) { @@ -80,7 +80,7 @@ const loginMixin = { - log.verbose('WechatyLoginMixin', 'logout()') + this.log.verbose('WechatyLoginMixin', 'logout()') await this.puppet.logout(reason) } @@ -88,7 +88,7 @@ const loginMixin = uninstallerList.forEach(uninstaller => { - log.verbose('WechatyPluginMixin', 'use() uninstalling Plugin %s on Wechaty %s ...', uninstaller.name, this.name()) + this.log.verbose('WechatyPluginMixin', 'use() uninstalling Plugin %s on Wechaty %s ...', uninstaller.name, this.name()) uninstaller() - log.verbose('WechatyPluginMixin', 'use() uninstalling Plugin %s on Wechaty %s ... done', uninstaller.name, this.name()) + this.log.verbose('WechatyPluginMixin', 'use() uninstalling Plugin %s on Wechaty %s ... done', uninstaller.name, this.name()) }) } diff --git a/src/wechaty-mixins/puppet-mixin.ts b/src/wechaty-mixins/puppet-mixin.ts index 4083760ec..bcdb7abf3 100644 --- a/src/wechaty-mixins/puppet-mixin.ts +++ b/src/wechaty-mixins/puppet-mixin.ts @@ -1,5 +1,5 @@ import * as PUPPET from '@juzi/wechaty-puppet' -import { log } from '@juzi/wechaty-puppet' +import { log, type LoggerLike } from '@juzi/wechaty-puppet' import { GError, timeoutPromise, @@ -81,11 +81,11 @@ const puppetMixin = { - log.verbose('WechatyPuppetMixin', 'start()') + this.log.verbose('WechatyPuppetMixin', 'start()') - log.verbose('WechatyPuppetMixin', 'start() super.start() ...') + this.log.verbose('WechatyPuppetMixin', 'start() super.start() ...') await super.start() - log.verbose('WechatyPuppetMixin', 'start() super.start() ... done') + this.log.verbose('WechatyPuppetMixin', 'start() super.start() ... done') try { /** @@ -97,12 +97,12 @@ const puppetMixin = { - log.verbose('WechatyPuppetMixin', 'stop()') + this.log.verbose('WechatyPuppetMixin', 'stop()') try { - log.verbose('WechatyPuppetMixin', 'stop() stopping puppet ...') + this.log.verbose('WechatyPuppetMixin', 'stop() stopping puppet ...') await timeoutPromise( this.puppet.stop(), 15 * 1000, // 15 seconds timeout ) - log.verbose('WechatyPuppetMixin', 'stop() stopping puppet ... done') + this.log.verbose('WechatyPuppetMixin', 'stop() stopping puppet ... done') } catch (e) { if (e instanceof TimeoutPromiseGError) { - log.warn('WechatyPuppetMixin', 'stop() stopping puppet ... timeout') - log.warn('WechatyPuppetMixin', 'stop() puppet info: %s', this.puppet) + this.log.warn('WechatyPuppetMixin', 'stop() stopping puppet ... timeout') + this.log.warn('WechatyPuppetMixin', 'stop() puppet info: %s', this.puppet) } this.emitError(e) } - log.verbose('WechatyPuppetMixin', 'stop() super.stop() ...') + this.log.verbose('WechatyPuppetMixin', 'stop() super.stop() ...') await super.stop() - log.verbose('WechatyPuppetMixin', 'stop() super.stop() ... done') + this.log.verbose('WechatyPuppetMixin', 'stop() super.stop() ... done') this.__callPool.clear() } async ready (): Promise { - log.verbose('WechatyPuppetMixin', 'ready()') + this.log.verbose('WechatyPuppetMixin', 'ready()') await this.__readyState.stable('active') - log.silly('WechatyPuppetMixin', 'ready() this.readyState.stable(on) resolved') + this.log.silly('WechatyPuppetMixin', 'ready() this.readyState.stable(on) resolved') } override async init (): Promise { - log.verbose('WechatyPuppetMixin', 'init()') + this.log.verbose('WechatyPuppetMixin', 'init()') await super.init() if (this.__puppetMixinInited) { - log.verbose('WechatyPuppetMixin', 'init() skipped because this puppet has already been inited before.') + this.log.verbose('WechatyPuppetMixin', 'init() skipped because this puppet has already been inited before.') return } this.__puppetMixinInited = true - log.verbose('WechatyPuppetMixin', 'init() instanciating puppet instance ...') + this.log.verbose('WechatyPuppetMixin', 'init() instanciating puppet instance ...') + /** + * Forward `WechatyOptions.logger` down into `PuppetOptions.logger` so + * that the puppet layer emits logs through the same logger the caller + * supplied to Wechaty. + */ + const basePuppetOptions = 'puppetOptions' in this.__options + ? this.__options.puppetOptions + : undefined + const mergedPuppetOptions = this.__options.logger + ? { ...(basePuppetOptions ?? {}), logger: this.__options.logger } + : basePuppetOptions const puppetInstance = await PUPPET.helpers.resolvePuppet({ puppet: this.__options.puppet || config.systemPuppetName(), - puppetOptions: 'puppetOptions' in this.__options - ? this.__options.puppetOptions - : undefined, + puppetOptions: mergedPuppetOptions, }) - log.verbose('WechatyPuppetMixin', 'init() instanciating puppet instance ... done') + + /** + * Adopt the puppet's effective logger onto the Wechaty side, so that + * `wechaty.log` and, via the accessory chain, every user module + * (`Contact.log`, `Message.log`, ...) route through it. `PuppetInterface` + * hides `log` (via `PuppetSkeletonProtectedProperty`), so a structural + * cast is required. The `??` guards third-party puppets that never + * adopted the pluggable logger — those fall back to the brolog `log` + * already assigned in WechatySkeleton. + * + * Adopted immediately after `resolvePuppet` so the rest of init() — + * setMemory / setupPuppetEvents / the sync `emit('puppet')` listeners — + * all route through the caller-supplied logger, not brolog. + */ + const puppetLog = (puppetInstance as unknown as { log?: LoggerLike }).log + if (puppetLog) { + this.__log = puppetLog + } + + this.log.verbose('WechatyPuppetMixin', 'init() instanciating puppet instance ... done') /** * Plug the Memory Card to Puppet */ - log.verbose('WechatyPuppetMixin', 'init() setting memory ...') + this.log.verbose('WechatyPuppetMixin', 'init() setting memory ...') const puppetMemory = this.memory.multiplex(PUPPET_MEMORY_NAME) puppetInstance.setMemory(puppetMemory) - log.verbose('WechatyPuppetMixin', 'init() setting memory ... done') + this.log.verbose('WechatyPuppetMixin', 'init() setting memory ... done') /** * Propagate Puppet Events to Wechaty */ - log.verbose('WechatyPuppetMixin', 'init() setting up events ...') + this.log.verbose('WechatyPuppetMixin', 'init() setting up events ...') this.__setupPuppetEvents(puppetInstance) - log.verbose('WechatyPuppetMixin', 'init() setting up events ... done') + this.log.verbose('WechatyPuppetMixin', 'init() setting up events ... done') /** * Private Event * - Huan(202005): emit puppet when set * - Huan(202110): @see https://github.com/wechaty/redux/blob/16af0ae01f72e37f0ee286b49fa5ccf69850323d/src/wechaty-redux.ts#L82-L98 */ - log.verbose('WechatyPuppetMixin', 'init() emitting "puppet" event ...') + this.log.verbose('WechatyPuppetMixin', 'init() emitting "puppet" event ...') ;(this.emit as any)('puppet', puppetInstance) - log.verbose('WechatyPuppetMixin', 'init() emitting "puppet" event ... done') + this.log.verbose('WechatyPuppetMixin', 'init() emitting "puppet" event ... done') this.__puppet = puppetInstance } __setupPuppetEvents (puppet: PUPPET.impls.PuppetInterface): void { - log.verbose('WechatyPuppetMixin', '__setupPuppetEvents(%s)', puppet) + this.log.verbose('WechatyPuppetMixin', '__setupPuppetEvents(%s)', puppet) const eventNameList: PUPPET.types.PuppetEventName[] = Object.keys(PUPPET.types.PUPPET_EVENT_DICT) as PUPPET.types.PuppetEventName[] for (const eventName of eventNameList) { - log.verbose('PuppetMixin', + this.log.verbose('PuppetMixin', '__setupPuppetEvents() puppet.on(%s) (listenerCount:%s) registering...', eventName, puppet.listenerCount(eventName), @@ -289,7 +317,7 @@ const puppetMixin = { - log.silly('WechatyPuppetMixin', '__setupPuppetEvents() puppet.on(ready)') + this.log.silly('WechatyPuppetMixin', '__setupPuppetEvents() puppet.on(ready)') // ready event should be emitted 15s after login let onceLogout: () => void @@ -415,7 +443,7 @@ const puppetMixin = (mix get WxxdOrder () : WxxdOrderConstructor { return guardWechatify(this.__wechatifiedWxxdOrder) } override async init (): Promise { - log.verbose('WechatifyUserModuleMixin', 'init()') + this.log.verbose('WechatifyUserModuleMixin', 'init()') await super.init() /** * Skip if already wechatified */ if (this.__wechatifiedMessage) { - log.verbose('WechatifyUserModuleMixin', 'init() Wechaty User Module (WUM)s have already wechatified: skip') + this.log.verbose('WechatifyUserModuleMixin', 'init() Wechaty User Module (WUM)s have already wechatified: skip') return } - log.verbose('WechatifyUserModuleMixin', 'init() initializing Wechaty User Module (WUM) ...') + this.log.verbose('WechatifyUserModuleMixin', 'init() initializing Wechaty User Module (WUM) ...') /** * Wechatify User Classes @@ -182,7 +182,7 @@ const wechatifyUserModuleMixin = (mix this.__wechatifiedWxxdProduct = wechatifyUserModule(WxxdProductImpl)(this as any) this.__wechatifiedWxxdOrder = wechatifyUserModule(WxxdOrderImpl)(this as any) - log.verbose('WechatifyUserModuleMixin', 'init() initializing Wechaty User Module (WUM) ... done') + this.log.verbose('WechatifyUserModuleMixin', 'init() initializing Wechaty User Module (WUM) ... done') } } diff --git a/src/wechaty/wechaty-base.ts b/src/wechaty/wechaty-base.ts index 6e053507d..c22960d8b 100644 --- a/src/wechaty/wechaty-base.ts +++ b/src/wechaty/wechaty-base.ts @@ -169,41 +169,41 @@ class WechatyBase extends mixinBase implements SayableSayer { override __options: WechatyOptions = {}, ) { super(__options) - log.verbose('Wechaty', 'constructor()') + this.log.verbose('Wechaty', 'constructor()') this.__memory = this.__options.memory this.wechaty = this } override async start (): Promise { - log.verbose('Wechaty', 'start()') + this.log.verbose('Wechaty', 'start()') await this.init() return super.start() } override async onStart (): Promise { - log.verbose('Wechaty', 'onStart()') + this.log.verbose('Wechaty', 'onStart()') - log.verbose('Wechaty', '<%s>(%s) onStart() v%s is starting...', + this.log.verbose('Wechaty', '<%s>(%s) onStart() v%s is starting...', this.__options.puppet || config.systemPuppetName(), this.__options.name || '', this.version(), ) - log.verbose('Wechaty', 'id: %s', this.id) + this.log.verbose('Wechaty', 'id: %s', this.id) const lifeTimer = setInterval(() => { - log.silly('Wechaty', 'onStart() setInterval() this timer is to keep Wechaty running...') + this.log.silly('Wechaty', 'onStart() setInterval() this timer is to keep Wechaty running...') }, 1000 * 60 * 60) this._stopCallbackList.push(() => clearInterval(lifeTimer)) this.emit('start') - log.verbose('Wechaty', 'onStart() ... done') + this.log.verbose('Wechaty', 'onStart() ... done') } override async onStop (): Promise { - log.verbose('Wechaty', 'onStop()') + this.log.verbose('Wechaty', 'onStop()') - log.verbose('Wechaty', '<%s> onStop() v%s is stopping ...', + this.log.verbose('Wechaty', '<%s> onStop() v%s is stopping ...', this.__options.puppet || config.systemPuppetName(), this.version(), ) @@ -213,7 +213,7 @@ class WechatyBase extends mixinBase implements SayableSayer { this._stopCallbackList.length = 0 this.emit('stop') - log.verbose('Wechaty', 'onStop() ... done') + this.log.verbose('Wechaty', 'onStop() ... done') } /** @@ -273,7 +273,7 @@ class WechatyBase extends mixinBase implements SayableSayer { async say ( sayable: Sayable, ): Promise { - log.verbose('Wechaty', 'say(%s)', sayable) + this.log.verbose('Wechaty', 'say(%s)', sayable) await this.currentUser.say(sayable) } @@ -294,7 +294,7 @@ class WechatyBase extends mixinBase implements SayableSayer { contacts: ContactInterface[], options?: { media?: PUPPET.types.CallMediaType }, ): Promise { - log.verbose('Wechaty', 'call(%d contacts, %s)', contacts.length, JSON.stringify(options ?? {})) + this.log.verbose('Wechaty', 'call(%d contacts, %s)', contacts.length, JSON.stringify(options ?? {})) if (contacts.length === 0) { throw new Error('Wechaty.call() requires at least one contact') @@ -317,7 +317,7 @@ class WechatyBase extends mixinBase implements SayableSayer { async publish ( post: PostInterface, ): Promise { - log.verbose('Wechaty', 'publish(%s)', + this.log.verbose('Wechaty', 'publish(%s)', (post.payload.sayableList as PUPPET.payloads.Sayable[]) .map(s => s.type).join(','), ) @@ -331,7 +331,7 @@ class WechatyBase extends mixinBase implements SayableSayer { async unpublish ( post: PostInterface, ): Promise { - log.verbose('Wechaty', 'unpublish(%s)', post.id) + this.log.verbose('Wechaty', 'unpublish(%s)', post.id) if (!post.id) { throw new Error('cannot unpublish a post without id') @@ -346,7 +346,7 @@ class WechatyBase extends mixinBase implements SayableSayer { id: string, code: string, ): Promise { - log.verbose('Wechaty', 'enterVerifyCode(%s, %s)', id, code) + this.log.verbose('Wechaty', 'enterVerifyCode(%s, %s)', id, code) return this.puppet.enterVerifyCode(id, code) } @@ -354,14 +354,14 @@ class WechatyBase extends mixinBase implements SayableSayer { async cancelVerifyCode ( id: string, ): Promise { - log.verbose('Wechaty', 'cancelVerifyCode(%s)', id) + this.log.verbose('Wechaty', 'cancelVerifyCode(%s)', id) return this.puppet.cancelVerifyCode(id) } async refreshQrCode ( ): Promise { - log.verbose('Wechaty', 'refreshQrCode(%s)') + this.log.verbose('Wechaty', 'refreshQrCode(%s)') if (this.isLoggedIn) { throw new Error('cannot refresh qr because bot is logged in') diff --git a/src/wechaty/wechaty-skeleton.ts b/src/wechaty/wechaty-skeleton.ts index 5ebbfd01f..e77b9d69c 100644 --- a/src/wechaty/wechaty-skeleton.ts +++ b/src/wechaty/wechaty-skeleton.ts @@ -20,19 +20,31 @@ import { MemoryCard } from 'memory-card' import { log } from '@juzi/wechaty-puppet' import * as UUID from 'uuid' -import type { Loggable } from 'brolog' import { WechatyEventEmitter, WechatyEventName, } from '../schemas/mod.js' +import type { LoggerLike } from '../schemas/logger.js' import type { WechatyOptions } from '../schemas/wechaty-options.js' abstract class WechatySkeleton extends WechatyEventEmitter { - static readonly log: Loggable = log - readonly log: Loggable = log + static readonly log: LoggerLike = log + + /** + * Effective logger for this Wechaty instance. + * + * Populated in the following order (see puppet-mixin): + * 1. `puppet.log` — the logger the puppet ended up using + * (which, when {@link WechatyOptions.logger} is supplied, is + * the caller's logger). + * 2. the built-in brolog `log` — hard fallback for the pre-init + * window and for puppets that have not adopted `puppet.log`. + */ + __log: LoggerLike = log + get log (): LoggerLike { return this.__log } /** * the UUID of the Wechaty @@ -77,20 +89,20 @@ abstract class WechatySkeleton extends WechatyEventEmitter { * by skipping the second time initialization. */ async init (): Promise { - log.verbose('WechatySkeleton', 'init()') + this.log.verbose('WechatySkeleton', 'init()') if (!this.__memory) { this.__memory = new MemoryCard(this.__options.name) try { await this.__memory.load() } catch (_) { - log.silly('WechatySkeleton', 'onStart() memory.load() had already loaded') + this.log.silly('WechatySkeleton', 'onStart() memory.load() had already loaded') } } } async start (): Promise { - log.verbose('WechatySkeleton', 'start()') + this.log.verbose('WechatySkeleton', 'start()') // no super.start() /** @@ -100,12 +112,12 @@ abstract class WechatySkeleton extends WechatyEventEmitter { } async stop (): Promise { - log.verbose('WechatySkeleton', 'stop()') + this.log.verbose('WechatySkeleton', 'stop()') // no super.stop() } override on (event: WechatyEventName, listener: (...args: any[]) => any): this { - log.verbose('WechatySkeleton', 'on(%s, listener) registering... listenerCount: %s', + this.log.verbose('WechatySkeleton', 'on(%s, listener) registering... listenerCount: %s', event, this.listenerCount(event), ) @@ -117,6 +129,7 @@ abstract class WechatySkeleton extends WechatyEventEmitter { type WechatySkeletonProtectedProperty = | '__events' + | '__log' | '__memory' | '__options' | 'memory'