From 57ec25fe6ebf08d82747f36b0e2dcff253aeb676 Mon Sep 17 00:00:00 2001 From: Huan LI Date: Sun, 27 May 2018 01:19:14 +0800 Subject: [PATCH] code clean --- examples/ding-dong-bot.ts | 4 +- src/profile.ts | 4 +- src/puppet-mock/README.md | 14 +-- src/puppet-mock/puppet-mock.ts | 25 ++---- src/puppet-puppeteer/bridge.ts | 2 +- src/puppet-puppeteer/puppet-puppeteer.ts | 106 ++--------------------- src/puppet/puppet.ts | 17 ++-- src/wechaty.spec.ts | 2 +- src/wechaty.ts | 28 +++++- 9 files changed, 63 insertions(+), 139 deletions(-) diff --git a/examples/ding-dong-bot.ts b/examples/ding-dong-bot.ts index f0bceade0..a088b7f2b 100644 --- a/examples/ding-dong-bot.ts +++ b/examples/ding-dong-bot.ts @@ -101,8 +101,8 @@ bot /** * 2. reply qrcode image */ - // const fileBox = FileBox.fromLocal(BOT_QR_CODE_IMAGE_FILE) - const fileBox = FileBox.fromStream( + // const fileBox = FileBox.packLocal(BOT_QR_CODE_IMAGE_FILE) + const fileBox = FileBox.packStream( fs.createReadStream(BOT_QR_CODE_IMAGE_FILE), BOT_QR_CODE_IMAGE_FILE, ) diff --git a/src/profile.ts b/src/profile.ts index 67fe00d30..9b573b640 100644 --- a/src/profile.ts +++ b/src/profile.ts @@ -25,7 +25,7 @@ import { } from './config' export interface ProfileSchema { - cookies? : any[] + // cookies? : any [idx: string] : any } @@ -111,7 +111,7 @@ export class Profile { return this.payload[section] as any as T } - public async set(section: ProfileSection, data: any): Promise { + public async set(section: ProfileSection, data: T): Promise { log.verbose('Profile', 'set(%s, %s)', section, data) if (!this.payload) { this.payload = {} diff --git a/src/puppet-mock/README.md b/src/puppet-mock/README.md index 433dc15ca..d1f033a3d 100644 --- a/src/puppet-mock/README.md +++ b/src/puppet-mock/README.md @@ -1,14 +1,13 @@ # PUPPET-MOCK ```ts -import PuppetMock from 'wechaty-puppet-mock' +import PuppetMock from '@chatie/wechaty-puppet-mock' + +const wechaty = new Wechaty() const puppet = new PuppetMock({ profile, -}) - -const wechaty = new Wechaty({ - puppet, + wechaty, }) ``` @@ -35,7 +34,8 @@ await this.state.ready('off') ### Profile ```ts -this.profile.set('config', { id: 1, key: 'xxx' }) +await this.profile.set('config', { id: 1, key: 'xxx' }) const config = await this.profile.get('config') +console.log(config) +// Output: { id: 1, key: 'xxx' } ``` - diff --git a/src/puppet-mock/puppet-mock.ts b/src/puppet-mock/puppet-mock.ts index 091eee856..4b2d22c12 100644 --- a/src/puppet-mock/puppet-mock.ts +++ b/src/puppet-mock/puppet-mock.ts @@ -23,24 +23,18 @@ import { } from 'file-box' import { - // Message, MessagePayload, } from '../message' import { - // Contact, ContactQueryFilter, Gender, ContactType, ContactPayload, } from '../contact' import { - // Room, RoomPayload, RoomQueryFilter, } from '../room' -// import { -// FriendRequest, -// } from '../puppet/friend-request' import { Puppet, PuppetOptions, @@ -65,9 +59,9 @@ export interface MockMessageRawPayload { } export interface MockRoomRawPayload { - topic: string, - memberList: string[], - owner: string, + topic : string, + memberList : string[], + ownerId : string, } export class PuppetMock extends Puppet { @@ -78,10 +72,6 @@ export class PuppetMock extends Puppet { super(options) } - public ding(data?: any): Promise { - return data - } - public async start(): Promise { log.verbose('PuppetMock', `start() with ${this.options.profile}`) @@ -157,7 +147,7 @@ export class PuppetMock extends Puppet { log.verbose('PuppetMock', 'contactAvatar(%s)', contactId) const WECHATY_ICON_PNG = path.resolve('../../docs/images/wechaty-icon.png') - return FileBox.fromLocal(WECHATY_ICON_PNG) + return FileBox.packLocal(WECHATY_ICON_PNG) } public async contactRawPayload(id: string): Promise { @@ -240,7 +230,7 @@ export class PuppetMock extends Puppet { log.verbose('PuppetMock', 'roomRawPayload(%s)', id) const rawPayload: MockRoomRawPayload = { - owner : 'mock_room_owner_id', + ownerId : 'mock_room_owner_id', topic : 'mock topic', memberList : [], } @@ -311,7 +301,6 @@ export class PuppetMock extends Puppet { } /** - * * * FriendRequest * @@ -330,6 +319,10 @@ export class PuppetMock extends Puppet { log.verbose('PuppetMock', 'friendRequestAccept(%s, %s)', contactId, ticket) } + public ding(data?: any): Promise { + return data + } + } export default PuppetMock diff --git a/src/puppet-puppeteer/bridge.ts b/src/puppet-puppeteer/bridge.ts index 19f8b8128..27b34e4bf 100644 --- a/src/puppet-puppeteer/bridge.ts +++ b/src/puppet-puppeteer/bridge.ts @@ -670,7 +670,7 @@ export class Bridge extends EventEmitter { throw e } - const argsEncoded = new Buffer( + const argsEncoded = Buffer.from( encodeURIComponent( JSON.stringify(args), ), diff --git a/src/puppet-puppeteer/puppet-puppeteer.ts b/src/puppet-puppeteer/puppet-puppeteer.ts index 653fd2d8e..4bdd2fee2 100644 --- a/src/puppet-puppeteer/puppet-puppeteer.ts +++ b/src/puppet-puppeteer/puppet-puppeteer.ts @@ -166,7 +166,7 @@ export class PuppetPuppeteer extends Puppet { } } - public initWatchdog(): void { + private initWatchdog(): void { log.verbose('PuppetPuppeteer', 'initWatchdogForPuppet()') const puppet = this @@ -203,7 +203,7 @@ export class PuppetPuppeteer extends Puppet { * sometimes the qrcode will not refresh, leave there expired. * so we need to refresh the page after a while */ - public initWatchdogForScan(): void { + private initWatchdogForScan(): void { log.verbose('PuppetPuppeteer', 'initWatchdogForScan()') const puppet = this @@ -279,7 +279,7 @@ export class PuppetPuppeteer extends Puppet { } } - public async initBridge(): Promise { + private async initBridge(): Promise { log.verbose('PuppetPuppeteer', 'initBridge()') if (this.state.off()) { @@ -420,7 +420,7 @@ export class PuppetPuppeteer extends Puppet { Cookie: cookies.map(c => `${c['name']}=${c['value']}`).join('; '), } - const fileBox = FileBox.fromRemote(url, filename, headers) + const fileBox = FileBox.packRemote(url, filename, headers) return fileBox } @@ -700,7 +700,7 @@ export class PuppetPuppeteer extends Puppet { await contact.ready() const fileName = (contact.name() || 'unknown') + '-avatar.jpg' - return FileBox.fromRemote( + return FileBox.packRemote( avatarUrl, fileName, headers, @@ -1093,7 +1093,7 @@ export class PuppetPuppeteer extends Puppet { * location.host = www.chatie.io:8080 * See: https://stackoverflow.com/a/11379802/1123955 */ - public async hostname(): Promise { + private async hostname(): Promise { try { const name = await this.bridge.hostname() if (!name) { @@ -1107,7 +1107,7 @@ export class PuppetPuppeteer extends Puppet { } } - public async cookies(): Promise { + private async cookies(): Promise { return await this.bridge.cookies() } @@ -1133,24 +1133,6 @@ export class PuppetPuppeteer extends Puppet { } } - /** - * - * - * - * - * - * THE FOLLOWING COMMENT OUTED CODE - * - * IS: TO BE MERGE - * - * - * - * - * - * - * - */ - // public async readyMedia(): Promise { private async messageRawPayloadToUrl( rawPayload: WebMessageRawPayload, @@ -1248,55 +1230,11 @@ export class PuppetPuppeteer extends Puppet { } - // public async readyStream(): Promise { - // log.verbose('PuppetPuppeteer', 'readyStream()') - - // /** - // * 1. local file - // */ - // try { - // const filename = this.filename() - // if (filename) { - // return fs.createReadStream(filename) - // } - // } catch (e) { - // // no filename - // } - - // /** - // * 2. remote url - // */ - // try { - // await this.ready() - // // FIXME: decoupling needed - // const cookies = await (this.puppet as any as PuppetPuppeteer).cookies() - // if (!this.payload.url) { - // throw new Error('no url') - // } - // log.verbose('PuppetPuppeteer', 'readyStream() url: %s', this.payload.url) - // return Misc.urlStream(this.payload.url, cookies) - // } catch (e) { - // log.warn('PuppetPuppeteer', 'readyStream() exception: %s', e.stack) - // Raven.captureException(e) - // throw e - // } - // } - private filename( rawPayload: WebMessageRawPayload, ): null | string { log.verbose('PuppetPuppeteer', 'filename()') - // if (this.parsedPath) { - // // https://nodejs.org/api/path.html#path_path_parse_path - // const filename = path.join( - // this.parsedPath!.dir || '', - // this.parsedPath!.base || '', - // ) - // log.silly('PuppetPuppeteer', 'filename()=%s, build from parsedPath', filename) - // return filename - // } - let filename = rawPayload.FileName || rawPayload.MediaId || rawPayload.MsgId const re = /\.[a-z0-9]{1,7}$/i @@ -1312,27 +1250,6 @@ export class PuppetPuppeteer extends Puppet { return filename } - // public ext(): string { - // const fileExt = this.extFromFile() - // if (fileExt) { - // return fileExt - // } - - // const typeExt = this.extFromType() - // if (typeExt) { - // return typeExt - // } - - // throw new Error('unknown ext()') - // } - - // private extFromFile(): string | null { - // if (this.parsedPath && this.parsedPath.ext) { - // return this.parsedPath.ext - // } - // return null - // } - private extname( rawPayload: WebMessageRawPayload, ): string { @@ -1386,15 +1303,6 @@ export class PuppetPuppeteer extends Puppet { } - // /** - // * return the MIME Type of this MediaMessage - // * - // */ - // public mimeType(): string | null { - // // getType support both 'js' & '.js' as arg - // return mime.getType(this.ext()) - // } - private async uploadMedia( file : FileBox, toUserName : string, diff --git a/src/puppet/puppet.ts b/src/puppet/puppet.ts index ac97de1cf..94f9a8493 100644 --- a/src/puppet/puppet.ts +++ b/src/puppet/puppet.ts @@ -81,8 +81,8 @@ export const PUPPET_EVENT_DICT = { export type PuppetEventName = keyof typeof PUPPET_EVENT_DICT export interface PuppetOptions { - profile: Profile, - wechaty: Wechaty, + profile : Profile, + wechaty : Wechaty, } export interface Receiver { @@ -134,9 +134,9 @@ export abstract class Puppet extends EventEmitter implements Sayable { * 1. Init Classes */ if ( !this.options.wechaty.Contact - || !this.options.wechaty.FriendRequest - || !this.options.wechaty.Message - || !this.options.wechaty.Room + || !this.options.wechaty.FriendRequest + || !this.options.wechaty.Message + || !this.options.wechaty.Room ) { throw new Error('wechaty classes are not inited') } @@ -146,6 +146,8 @@ export abstract class Puppet extends EventEmitter implements Sayable { this.Message = this.options.wechaty.Message this.Room = this.options.wechaty.Room + this.options.wechaty.attach(this) + /** * 2. Load the package.json for Puppet Plugin version range matching * @@ -168,7 +170,7 @@ export abstract class Puppet extends EventEmitter implements Sayable { } public emit(event: 'error', e: Error) : boolean - public emit(event: 'friend', request: FriendRequest) : boolean + public emit(event: 'friend', request: FriendRequest) : boolean public emit(event: 'heartbeat', data: any) : boolean public emit(event: 'login', user: Contact) : boolean public emit(event: 'logout', user: Contact | string) : boolean @@ -178,7 +180,8 @@ export abstract class Puppet extends EventEmitter implements Sayable { public emit(event: 'room-topic', room: Room, topic: string, oldTopic: string, changer: Contact) : boolean public emit(event: 'scan', url: string, code: number) : boolean public emit(event: 'watchdog', food: WatchdogFood) : boolean - public emit(event: never, ...args: never[]) : never + + public emit(event: never, ...args: never[]): never public emit( event: PuppetEventName, diff --git a/src/wechaty.spec.ts b/src/wechaty.spec.ts index 7cc74d164..335dbe8ef 100755 --- a/src/wechaty.spec.ts +++ b/src/wechaty.spec.ts @@ -66,7 +66,7 @@ test('Config setting', async t => { }) test('event:start/stop', async t => { - const wechaty = Wechaty.instance() + const wechaty = new Wechaty() const startSpy = sinon.spy() const stopSpy = sinon.spy() diff --git a/src/wechaty.ts b/src/wechaty.ts index 365c2998e..d90c197e9 100644 --- a/src/wechaty.ts +++ b/src/wechaty.ts @@ -145,7 +145,7 @@ export class Wechaty extends PuppetAccessory implements Sayable { options?: WechatyOptions, ) { if (options && this.singletonInstance) { - throw new Error('there has already a instance. no params will be allowed any more') + throw new Error('instance can be only set once!') } if (!this.singletonInstance) { this.singletonInstance = new Wechaty(options) @@ -162,8 +162,6 @@ export class Wechaty extends PuppetAccessory implements Sayable { super() log.verbose('Wechaty', 'contructor()') - options.puppet = options.puppet || config.puppet - options.profile = options.profile === null ? null : (options.profile || config.default.DEFAULT_PROFILE) @@ -393,6 +391,27 @@ export class Wechaty extends PuppetAccessory implements Sayable { }) } + /** + * Will be called from the Puppet. + */ + public attach(puppet: Puppet) { + log.verbose('Wechaty', 'attach(%s) this.options.puppet="%s"', + puppet, + this.options.puppet && this.options.puppet.toString(), + ) + + if (this.options.puppet instanceof Puppet) { + if (this.options.puppet === puppet) { + log.silly('Wechaty', 'attach(%s) called again', puppet) + return + } else { + throw new Error('puppet can only be attached once!') + } + } + + this.options.puppet = puppet + } + /** * @private */ @@ -400,7 +419,8 @@ export class Wechaty extends PuppetAccessory implements Sayable { log.verbose('Wechaty', 'initPuppet()') if (!this.options.puppet) { - throw new Error('no puppet') + log.warn('Wechaty', 'initPuppet() using default puppet: %s', config.puppet) + this.options.puppet = config.puppet } const puppet = this.initPuppetResolver(this.options.puppet) -- GitLab