提交 e418ccc8 编写于 作者: Huan (李卓桓)'s avatar Huan (李卓桓)

room.topic() from sync to async, with default values (#1295)

上级 70ac7b1e
...@@ -79,14 +79,14 @@ bot ...@@ -79,14 +79,14 @@ bot
}) })
.on('login' , user => log.info('Bot', `bot login: ${user}`)) .on('login' , user => log.info('Bot', `bot login: ${user}`))
.on('logout' , user => log.info('Bot', 'bot %s logout.', user)) .on('logout' , user => log.info('Bot', 'bot %s logout.', user))
.on('message', m => { .on('message', async m => {
if (m.self()) { return } if (m.self()) { return }
// co(function* () { // co(function* () {
// const msg = yield m.load() // const msg = yield m.load()
const room = m.room() const room = m.room()
if (room && /Wechaty/i.test(room.topic())) { if (room && /Wechaty/i.test(await room.topic())) {
log.info('Bot', 'talk: %s' , m) log.info('Bot', 'talk: %s' , m)
talk(m) talk(m)
} else { } else {
......
...@@ -33,7 +33,7 @@ export async function onMessage(this: Wechaty, message: Message): Promise<void> ...@@ -33,7 +33,7 @@ export async function onMessage(this: Wechaty, message: Message): Promise<void>
const sender = message.from() const sender = message.from()
const content = message.text() const content = message.text()
console.log((room ? '[' + room.topic() + ']' : '') console.log((room ? '[' + await room.topic() + ']' : '')
+ '<' + sender.name() + '>' + '<' + sender.name() + '>'
+ ':' + message, + ':' + message,
) )
......
...@@ -42,8 +42,8 @@ export async function onRoomJoin( ...@@ -42,8 +42,8 @@ export async function onRoomJoin(
* *
*/ */
if (room.topic() !== 'ding') { if (await room.topic() !== 'ding') {
await this.say('Room ' + room.topic() await this.say('Room ' + await room.topic()
+ ' got new memeber ' + inviteeName + ' got new memeber ' + inviteeName
+ ' invited by ' + inviter.name(), + ' invited by ' + inviter.name(),
) )
......
...@@ -21,7 +21,7 @@ exports = module.exports = async function onMessage (message) { ...@@ -21,7 +21,7 @@ exports = module.exports = async function onMessage (message) {
const sender = message.from(); const sender = message.from();
const content = message.text(); const content = message.text();
const topic = room ? '[' + room.topic() + ']' : ''; const topic = room ? '[' + await room.topic() + ']' : '';
console.log(`${topic} <${sender.name()}> : ${message.toStringDigest()}`); console.log(`${topic} <${sender.name()}> : ${message.toStringDigest()}`);
......
...@@ -35,7 +35,7 @@ export default async function onMessage (message) { ...@@ -35,7 +35,7 @@ export default async function onMessage (message) {
const room = message.room() const room = message.room()
const sender = message.from() const sender = message.from()
const content = message.text() const content = message.text()
const roomName = room ? `[${room.topic()}] ` : '' const roomName = room ? `[${await room.topic()}] ` : ''
process.stdout.write( process.stdout.write(
`${roomName}<${sender.name()}>(${message.type()}:${message.typeSub()}): `) `${roomName}<${sender.name()}>(${message.type()}:${message.typeSub()}): `)
......
...@@ -121,9 +121,9 @@ bot ...@@ -121,9 +121,9 @@ bot
/** /**
* Global Event: room-join * Global Event: room-join
*/ */
.on('room-join', function(this, room, inviteeList, inviter) { .on('room-join', async function(this, room, inviteeList, inviter) {
log.info( 'Bot', 'EVENT: room-join - Room %s got new member %s, invited by %s', log.info( 'Bot', 'EVENT: room-join - Room %s got new member %s, invited by %s',
room.topic(), await room.topic(),
inviteeList.map(c => c.name()).join(','), inviteeList.map(c => c.name()).join(','),
inviter.name(), inviter.name(),
) )
...@@ -132,9 +132,9 @@ bot ...@@ -132,9 +132,9 @@ bot
/** /**
* Global Event: room-leave * Global Event: room-leave
*/ */
.on('room-leave', function(this, room, leaverList) { .on('room-leave', async function(this, room, leaverList) {
log.info('Bot', 'EVENT: room-leave - Room %s lost member %s', log.info('Bot', 'EVENT: room-leave - Room %s lost member %s',
room.topic(), await room.topic(),
leaverList.map(c => c.name()).join(','), leaverList.map(c => c.name()).join(','),
) )
}) })
...@@ -163,7 +163,7 @@ bot ...@@ -163,7 +163,7 @@ bot
const sender = message.from() const sender = message.from()
const content = message.text() const content = message.text()
console.log((room ? '[' + room.topic() + ']' : '') console.log((room ? '[' + await room.topic() + ']' : '')
+ '<' + sender.name() + '>' + '<' + sender.name() + '>'
+ ':' + message, + ':' + message,
) )
...@@ -182,7 +182,7 @@ bot ...@@ -182,7 +182,7 @@ bot
* in-room message * in-room message
*/ */
if (room) { if (room) {
if (/^ding/i.test(room.topic())) { if (/^ding/i.test(await room.topic())) {
/** /**
* move contact out of room * move contact out of room
*/ */
...@@ -297,7 +297,7 @@ async function manageDingRoom() { ...@@ -297,7 +297,7 @@ async function manageDingRoom() {
async function checkRoomJoin(room: Room, inviteeList: Contact[], inviter: Contact) { async function checkRoomJoin(room: Room, inviteeList: Contact[], inviter: Contact) {
log.info('Bot', 'checkRoomJoin(%s, %s, %s)', log.info('Bot', 'checkRoomJoin(%s, %s, %s)',
room.topic(), await room.topic(),
inviteeList.map(c => c.name()).join(','), inviteeList.map(c => c.name()).join(','),
inviter.name(), inviter.name(),
) )
...@@ -315,7 +315,7 @@ async function checkRoomJoin(room: Room, inviteeList: Contact[], inviter: Contac ...@@ -315,7 +315,7 @@ async function checkRoomJoin(room: Room, inviteeList: Contact[], inviter: Contac
inviteeList, inviteeList,
) )
room.topic('ding - warn ' + inviter.name()) await room.topic('ding - warn ' + inviter.name())
setTimeout( setTimeout(
_ => inviteeList.forEach(c => room.del(c)), _ => inviteeList.forEach(c => room.del(c)),
10 * 1000, 10 * 1000,
...@@ -337,7 +337,7 @@ async function checkRoomJoin(room: Room, inviteeList: Contact[], inviter: Contac ...@@ -337,7 +337,7 @@ async function checkRoomJoin(room: Room, inviteeList: Contact[], inviter: Contac
} }
async function putInRoom(contact: Contact, room: Room) { async function putInRoom(contact: Contact, room: Room) {
log.info('Bot', 'putInRoom(%s, %s)', contact.name(), room.topic()) log.info('Bot', 'putInRoom(%s, %s)', contact.name(), await room.topic())
try { try {
await room.add(contact) await room.add(contact)
......
...@@ -96,26 +96,29 @@ bot ...@@ -96,26 +96,29 @@ bot
const from = msg.from() const from = msg.from()
// Room.findAll() // Room.findAll()
if (/^testRoom$/.test(text)) { if (/^testRoom$/i.test(text)) {
const roomList = await bot.Room.findAll() const roomList = await bot.Room.findAll()
const topicList = await Promise.all(
roomList.map(async room => await room.topic()),
)
let n = 0 let n = 0
from.say( await from.say(
roomList topicList
.map(room => room.topic()) .map(topic => ++n + '. ' + topic)
.map(topic => n++ + '. ' + topic)
.join('\n'), .join('\n'),
) )
return return
} }
// Contact.findAll() // Contact.findAll()
if (/^testContact$/.test(text)) { if (/^testContact$/i.test(text)) {
const contactList = await bot.Contact.findAll() const contactList = await bot.Contact.findAll()
let n = 0 let n = 0
from.say( await from.say(
contactList contactList
.map(contact => contact.name()) .map(contact => contact.name())
.map(name => n++ + '. ' + name) .map(name => ++n + '. ' + name)
.join('\n'), .join('\n'),
) )
return return
...@@ -131,14 +134,14 @@ bot ...@@ -131,14 +134,14 @@ bot
console.error('contact not found') console.error('contact not found')
return return
} }
msg.forward(contact) await msg.forward(contact)
return return
} }
if (/^froom$/.test(text)) { if (/^froom$/.test(text)) {
console.log('begin to check msg forward room') console.log('begin to check msg forward room')
const room = bot.Room.load('6350854677@chatroom') const room = bot.Room.load('6350854677@chatroom')
msg.forward(room) await msg.forward(room)
return return
} }
......
...@@ -156,7 +156,6 @@ export class Message extends Accessory implements Sayable { ...@@ -156,7 +156,6 @@ export class Message extends Accessory implements Sayable {
const msgStrList = [ const msgStrList = [
'Message', 'Message',
// `#${MessageDirection[this.direction]}`,
`#${MessageType[this.type()]}`, `#${MessageType[this.type()]}`,
'(', '(',
this.room() ? (this.room() + '') : '', this.room() ? (this.room() + '') : '',
...@@ -177,7 +176,11 @@ export class Message extends Accessory implements Sayable { ...@@ -177,7 +176,11 @@ export class Message extends Accessory implements Sayable {
} }
const filename = this.payload.filename const filename = this.payload.filename
if (!filename) { if (!filename) {
throw new Error('no file for message id: ' + this.id + ' with type: ' + this.payload.type) throw new Error(
'no file for message id: ' + this.id
+ ' with type: ' + Message.Type[this.payload.type]
+ '(' + this.payload.type + ')',
)
} }
msgStrList.push(`<${filename}>`) msgStrList.push(`<${filename}>`)
} }
......
...@@ -124,11 +124,19 @@ export class Bridge extends EventEmitter { ...@@ -124,11 +124,19 @@ export class Bridge extends EventEmitter {
await this.padchatRpc.start() await this.padchatRpc.start()
this.padchatRpc.on('message', messageRawPayload => { this.padchatRpc.on('message', messageRawPayload => {
log.silly('PuppetPadchatBridge', `start() padchatRpc.on('message')`) log.silly('PuppetPadchatBridge', 'start() padchatRpc.on(message)')
this.emit('message', messageRawPayload) this.emit('message', messageRawPayload)
}) })
this.padchatRpc.on('logout', data => {
log.silly('PuppetPadchatBridge', 'start() padchatRpc.on(logout, %s)', data)
if (this.selfId) {
this.selfId = undefined
this.emit('logout', data)
} else {
log.warn('PuppetPadchatBridge', 'start() padchatRpc.on(logout) received `logout` event when no `selfId`')
}
})
// TODO: 顺序变一下,要check user_name 的
await this.loadAutoData() await this.loadAutoData()
const restoreSucceed = await this.restoreLogin() const restoreSucceed = await this.restoreLogin()
...@@ -228,6 +236,8 @@ export class Bridge extends EventEmitter { ...@@ -228,6 +236,8 @@ export class Bridge extends EventEmitter {
if (result.expired_time && result.expired_time < 10) { if (result.expired_time && result.expired_time < 10) {
// result.expire_time is second // result.expire_time is second
// emit new qrcode before the old one expired // emit new qrcode before the old one expired
this.loginScanQrCode = undefined
this.loginScanStatus = undefined
waitUserResponse = false waitUserResponse = false
} }
...@@ -331,6 +341,24 @@ export class Bridge extends EventEmitter { ...@@ -331,6 +341,24 @@ export class Bridge extends EventEmitter {
* "user_name": "wxid_5zj4i5htp9ih22" * "user_name": "wxid_5zj4i5htp9ih22"
* } * }
*/ */
/**
* WXAutoLoginresult: {
* "email": "",
* "external": "",
* "long_link_server": "",
* "message": "\n�\u0002<e>\n<ShowType>1</ShowType>\n<Content><![CDATA[你已退出微信]]></Content>\n
* <Url><![CDATA[]]></Url>\n<DispSec>30</DispSec>\n<Title><![CDATA[]]></Title>\n<Action>4</Action>\n
* <DelayConnSec>0</DelayConnSec>\n<Countdown>0</Countdown>\n<Ok><![CDATA[]]></Ok>\n<Cancel><![CDATA[]]></Cancel>\n</e>\n",
* "nick_name": "",
* "phone_number": "",
* "qq": 0,
* "short_link_server": "",
* "status": -2023,
* "uin": 4763975,
* "user_name": "lizhuohuan"
* }
*/
const autoLoginResult = await this.padchatRpc.WXAutoLogin(this.autoData.token) const autoLoginResult = await this.padchatRpc.WXAutoLogin(this.autoData.token)
if (!autoLoginResult) { if (!autoLoginResult) {
...@@ -538,12 +566,10 @@ export class Bridge extends EventEmitter { ...@@ -538,12 +566,10 @@ export class Bridge extends EventEmitter {
continue continue
} }
log.verbose('PuppetPadchatBridge', 'syncContactsAndRooms() sync contact, got new/total: %d/%d', log.verbose('PuppetPadchatBridge', 'syncContactsAndRooms() adding new %d to Contact(%d) & Room(%d) ...',
syncContactList.length, syncContactList.length,
( Object.keys(this.cacheContactRawPayload).length,
Object.keys(this.cacheContactRawPayload).length Object.keys(this.cacheRoomRawPayload).length,
+ Object.keys(this.cacheRoomRawPayload).length
),
) )
for (const syncContact of syncContactList) { for (const syncContact of syncContactList) {
...@@ -555,16 +581,14 @@ export class Bridge extends EventEmitter { ...@@ -555,16 +581,14 @@ export class Bridge extends EventEmitter {
} }
if (syncContact.msg_type === PadchatContactMsgType.Contact) { if (syncContact.msg_type === PadchatContactMsgType.Contact) {
log.verbose('PuppetPadchatBridge', 'syncContactsAndRooms() sync for %s(%s)',
syncContact.nick_name,
syncContact.user_name,
)
if (pfHelper.isRoomId(syncContact.user_name)) { // /@chatroom$/.test(syncContact.user_name)) { if (pfHelper.isRoomId(syncContact.user_name)) { // /@chatroom$/.test(syncContact.user_name)) {
/** /**
* Room * Room
*/ */
// user_name or chatroom_id ? log.verbose('PuppetPadchatBridge', 'syncContactsAndRooms() sync Room %s(%s)',
syncContact.nick_name,
syncContact.user_name,
)
const roomId = syncContact.user_name const roomId = syncContact.user_name
const roomPayload = syncContact as PadchatRoomPayload const roomPayload = syncContact as PadchatRoomPayload
...@@ -575,6 +599,10 @@ export class Bridge extends EventEmitter { ...@@ -575,6 +599,10 @@ export class Bridge extends EventEmitter {
/** /**
* Contact * Contact
*/ */
log.verbose('PuppetPadchatBridge', 'syncContactsAndRooms() sync Contact %s(%s)',
syncContact.nick_name,
syncContact.user_name,
)
const contactPayload = syncContact as PadchatContactPayload const contactPayload = syncContact as PadchatContactPayload
const contactId = contactPayload.user_name const contactId = contactPayload.user_name
......
...@@ -188,7 +188,7 @@ export class PadchatRpc extends EventEmitter { ...@@ -188,7 +188,7 @@ export class PadchatRpc extends EventEmitter {
apiName : string, apiName : string,
...params : string[] ...params : string[]
): Promise<any> { ): Promise<any> {
log.silly('PadchatRpc', 'rpcCall(%s, %s)', apiName, JSON.stringify(params)) log.silly('PadchatRpc', 'rpcCall(%s, %s)', apiName, JSON.stringify(params).substr(0, 500))
return await this.jsonRpc.request(apiName, params) return await this.jsonRpc.request(apiName, params)
} }
...@@ -200,11 +200,13 @@ export class PadchatRpc extends EventEmitter { ...@@ -200,11 +200,13 @@ export class PadchatRpc extends EventEmitter {
// console.log('server payload:', payload) // console.log('server payload:', payload)
if (payload.type === PadchatPayloadType.Logout) { if (payload.type === PadchatPayloadType.Logout) {
log.verbose('PadchatRpc', 'onSocket(payload.type=%s) logout, payload=%s', // {"type":-1,"msg":"掉线了"}
log.verbose('PadchatRpc', 'onSocket(payload.type=%s) logout, payload=%s(%s)',
PadchatPayloadType[payload.type],
payload.type, payload.type,
JSON.stringify(payload), JSON.stringify(payload),
) )
this.emit('logout') this.emit('logout', payload.msg)
return return
} }
......
...@@ -135,6 +135,8 @@ export class PadchatPureFunctionHelper { ...@@ -135,6 +135,8 @@ export class PadchatPureFunctionHelper {
rawPayload: PadchatMessagePayload, rawPayload: PadchatMessagePayload,
): MessagePayload { ): MessagePayload {
console.log(rawPayload)
let type: MessageType let type: MessageType
switch (rawPayload.sub_type) { switch (rawPayload.sub_type) {
......
...@@ -106,7 +106,7 @@ test('Room smok testing', async t => { ...@@ -106,7 +106,7 @@ test('Room smok testing', async t => {
// t.is((r as any).payload[.('encryId') , EXPECTED.encryId, 'should set EncryChatRoomId') // t.is((r as any).payload[.('encryId') , EXPECTED.encryId, 'should set EncryChatRoomId')
t.is(room.topic(), ROOM_EXPECTED.topic, 'should set topic/NickName') t.is(await room.topic(), ROOM_EXPECTED.topic, 'should set topic/NickName')
const contact1 = new wechaty.Contact(ROOM_EXPECTED.memberId1) const contact1 = new wechaty.Contact(ROOM_EXPECTED.memberId1)
const alias1 = await room.alias(contact1) const alias1 = await room.alias(contact1)
......
...@@ -445,9 +445,9 @@ export abstract class Puppet extends EventEmitter implements Sayable { ...@@ -445,9 +445,9 @@ export abstract class Puppet extends EventEmitter implements Sayable {
const cachedPayload = this.cacheContactPayload.get(contactId) const cachedPayload = this.cacheContactPayload.get(contactId)
if (cachedPayload) { if (cachedPayload) {
log.silly('Puppet', 'contactPayload() cache HIT') log.silly('Puppet', 'contactPayload(%s) cache HIT', contactId)
} else { } else {
log.silly('Puppet', 'contactPayload() cache MISS') log.silly('Puppet', 'contactPayload(%s) cache MISS', contactId)
} }
return cachedPayload return cachedPayload
...@@ -508,9 +508,9 @@ export abstract class Puppet extends EventEmitter implements Sayable { ...@@ -508,9 +508,9 @@ export abstract class Puppet extends EventEmitter implements Sayable {
const cachedPayload = this.cacheFriendRequestPayload.get(friendRequestId) const cachedPayload = this.cacheFriendRequestPayload.get(friendRequestId)
if (cachedPayload) { if (cachedPayload) {
log.silly('Puppet', 'friendRequestPayload() cache HIT') log.silly('Puppet', 'friendRequestPayload(%s) cache HIT', friendRequestId)
} else { } else {
log.silly('Puppet', 'friendRequestPayload() cache MISS') log.silly('Puppet', 'friendRequestPayload(%s) cache MISS', friendRequestId)
} }
return cachedPayload return cachedPayload
...@@ -571,9 +571,9 @@ export abstract class Puppet extends EventEmitter implements Sayable { ...@@ -571,9 +571,9 @@ export abstract class Puppet extends EventEmitter implements Sayable {
} }
const cachedPayload = this.cacheMessagePayload.get(messageId) const cachedPayload = this.cacheMessagePayload.get(messageId)
if (cachedPayload) { if (cachedPayload) {
log.silly('Puppet', 'messagePayloadCache() cache HIT') log.silly('Puppet', 'messagePayloadCache(%s) cache HIT', messageId)
} else { } else {
log.silly('Puppet', 'messagePayloadCache() cache MISS') log.silly('Puppet', 'messagePayloadCache(%s) cache MISS', messageId)
} }
return cachedPayload return cachedPayload
...@@ -717,7 +717,6 @@ export abstract class Puppet extends EventEmitter implements Sayable { ...@@ -717,7 +717,6 @@ export abstract class Puppet extends EventEmitter implements Sayable {
id => this.roomPayload(id), id => this.roomPayload(id),
), ),
) )
console.log('roomPayload resolved.')
const filterFunction = this.roomQueryFilterFactory(query) const filterFunction = this.roomQueryFilterFactory(query)
...@@ -725,7 +724,7 @@ export abstract class Puppet extends EventEmitter implements Sayable { ...@@ -725,7 +724,7 @@ export abstract class Puppet extends EventEmitter implements Sayable {
.filter(filterFunction) .filter(filterFunction)
.map(payload => payload.id) .map(payload => payload.id)
console.log('roomIdList filtered. result length=' + roomIdList.length) log.silly('Puppet', 'roomSearch() roomIdList filtered. result length=%d', roomIdList.length)
return roomIdList return roomIdList
} }
...@@ -772,9 +771,9 @@ export abstract class Puppet extends EventEmitter implements Sayable { ...@@ -772,9 +771,9 @@ export abstract class Puppet extends EventEmitter implements Sayable {
} }
const cachedPayload = this.cacheRoomPayload.get(roomId) const cachedPayload = this.cacheRoomPayload.get(roomId)
if (cachedPayload) { if (cachedPayload) {
log.silly('Puppet', 'roomPayloadCache() cache HIT') log.silly('Puppet', 'roomPayloadCache(%s) cache HIT', roomId)
} else { } else {
log.silly('Puppet', 'roomPayloadCache() cache MISS') log.silly('Puppet', 'roomPayloadCache(%s) cache MISS', roomId)
} }
return cachedPayload return cachedPayload
......
...@@ -470,14 +470,14 @@ export class Room extends Accessory implements Sayable { ...@@ -470,14 +470,14 @@ export class Room extends Accessory implements Sayable {
await this.puppet.roomQuit(this.id) await this.puppet.roomQuit(this.id)
} }
public topic() : string public async topic() : Promise<string>
public topic(newTopic: string): Promise<void> public async topic(newTopic: string): Promise<void>
/** /**
* SET/GET topic from the room * SET/GET topic from the room
* *
* @param {string} [newTopic] If set this para, it will change room topic. * @param {string} [newTopic] If set this para, it will change room topic.
* @returns {(string | void)} * @returns {Promise<string | void>}
* *
* @example <caption>When you say anything in a room, it will get room topic. </caption> * @example <caption>When you say anything in a room, it will get room topic. </caption>
* const bot = Wechaty.instance() * const bot = Wechaty.instance()
...@@ -485,7 +485,7 @@ export class Room extends Accessory implements Sayable { ...@@ -485,7 +485,7 @@ export class Room extends Accessory implements Sayable {
* .on('message', async m => { * .on('message', async m => {
* const room = m.room() * const room = m.room()
* if (room) { * if (room) {
* const topic = room.topic() * const topic = await room.topic()
* console.log(`room topic is : ${topic}`) * console.log(`room topic is : ${topic}`)
* } * }
* }) * })
...@@ -502,7 +502,7 @@ export class Room extends Accessory implements Sayable { ...@@ -502,7 +502,7 @@ export class Room extends Accessory implements Sayable {
* } * }
* }) * })
*/ */
public topic(newTopic?: string): string | Promise<void> { public async topic(newTopic?: string): Promise<void | string> {
log.verbose('Room', 'topic(%s)', newTopic ? newTopic : '') log.verbose('Room', 'topic(%s)', newTopic ? newTopic : '')
if (!this.isReady()) { if (!this.isReady()) {
log.warn('Room', 'topic() room not ready') log.warn('Room', 'topic() room not ready')
...@@ -510,7 +510,20 @@ export class Room extends Accessory implements Sayable { ...@@ -510,7 +510,20 @@ export class Room extends Accessory implements Sayable {
} }
if (typeof newTopic === 'undefined') { if (typeof newTopic === 'undefined') {
return this.payload && this.payload.topic || '' if (this.payload && this.payload.topic) {
return this.payload.topic
} else {
const memberIdList = await this.puppet.roomMemberList(this.id)
const memberList = memberIdList
.filter(id => id !== this.puppet.selfId())
.map(id => this.wechaty.Contact.load(id))
let defaultTopic = memberList[0].name()
for (let i = 1; i < 3 && memberList[i]; i++) {
defaultTopic += ',' + memberList[i].name()
}
return defaultTopic
}
} }
const future = this.puppet const future = this.puppet
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册