puppet-padchat.ts 34.1 KB
Newer Older
ruiruibupt's avatar
init  
ruiruibupt 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/**
 *   Wechaty - https://github.com/chatie/wechaty
 *
 *   @copyright 2016-2018 Huan LI <zixia@zixia.net>
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

20
import path  from 'path'
21 22
// import fs    from 'fs'
// import cuid from 'cuid'
ruiruibupt's avatar
init  
ruiruibupt 已提交
23

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
24 25
import LRU      from 'lru-cache'
import flatten  from 'array-flatten'
26

ruiruibupt's avatar
init  
ruiruibupt 已提交
27 28
import {
  FileBox,
29
}               from 'file-box'
ruiruibupt's avatar
init  
ruiruibupt 已提交
30

31 32
import Misc from '../misc'

ruiruibupt's avatar
init  
ruiruibupt 已提交
33
import {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
34 35
  ContactPayload,

36 37
  MessagePayload,
  MessageType,
ruiruibupt's avatar
init  
ruiruibupt 已提交
38 39

  RoomPayload,
40
  RoomMemberPayload,
ruiruibupt's avatar
init  
ruiruibupt 已提交
41 42 43

  Puppet,
  PuppetOptions,
44

ruiruibupt's avatar
init  
ruiruibupt 已提交
45
  Receiver,
46

47 48
  FriendshipPayload,
  FriendshipPayloadReceive,
49
}                                 from '../puppet/'
ruiruibupt's avatar
init  
ruiruibupt 已提交
50

51
import {
52
  contactRawPayloadParser,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
53

54
  fileBoxToQrcode,
55
  // friendRequestEventMessageParser,
56
  friendshipRawPayloadParser,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
57 58 59 60

  isStrangerV1,
  isStrangerV2,

61
  messageRawPayloadParser,
62 63 64

  roomRawPayloadParser,

65 66 67
  roomJoinEventMessageParser,
  roomLeaveEventMessageParser,
  roomTopicEventMessageParser,
68 69 70 71

  friendshipConfirmEventMessageParser,
  friendshipReceiveEventMessageParser,
  friendshipVerifyEventMessageParser,
72
}                                         from './pure-function-helpers'
73

ruiruibupt's avatar
init  
ruiruibupt 已提交
74 75
import {
  log,
76 77
  qrCodeForChatie,
}                   from '../config'
ruiruibupt's avatar
init  
ruiruibupt 已提交
78

79
import {
80
  padchatToken,
81 82 83
  WECHATY_PUPPET_PADCHAT_ENDPOINT,
}                                   from './config'

ruiruibupt's avatar
init  
ruiruibupt 已提交
84
import {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
85 86
  PadchatManager,
}                       from './padchat-manager'
ruiruibupt's avatar
init  
ruiruibupt 已提交
87 88

import {
89
  PadchatContactPayload,
90
  PadchatMessagePayload,
91
  PadchatRoomPayload,
92
  PadchatRoomMemberPayload,
93
  PadchatMessageType,
94
}                           from './padchat-schemas'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
95

E
Egg 已提交
96 97 98 99
import {
  WXSearchContactType,
  WXSearchContactTypeStatus,
}                           from './padchat-rpc.type'
ruiruibupt's avatar
init  
ruiruibupt 已提交
100 101

export class PuppetPadchat extends Puppet {
102

103
  // private readonly cachePadchatContactPayload       : LRU.Cache<string, PadchatContactRawPayload>
104
  // private readonly cachePadchatFriendshipPayload : LRU.Cache<string, PadchatMessagePayload>
105
  private readonly cachePadchatMessagePayload    : LRU.Cache<string, PadchatMessagePayload>
106
  // private readonly cachePadchatRoomPayload          : LRU.Cache<string, PadchatRoomRawPayload>
107

108
  public padchatManager?:  PadchatManager
ruiruibupt's avatar
init  
ruiruibupt 已提交
109 110 111 112

  constructor(
    public options: PuppetOptions,
  ) {
113 114 115 116
    super({
      timeout: 60 * 4,  // Default set timeout to 4 minutes
      ...options,
    })
ruiruibupt's avatar
init  
ruiruibupt 已提交
117

118 119 120
    const lruOptions: LRU.Options = {
      max: 1000,
      // length: function (n) { return n * 2},
121
      dispose: function (key: string, val: any) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
122
        log.silly('PuppetPadchat', 'constructor() lruOptions.dispose(%s, %s)', key, JSON.stringify(val))
123 124 125 126
      },
      maxAge: 1000 * 60 * 60,
    }

127
    // this.cachePadchatContactPayload       = new LRU<string, PadchatContactRawPayload>(lruOptions)
128
    // this.cachePadchatFriendshipPayload = new LRU<string, PadchatMessagePayload>(lruOptions)
129
    this.cachePadchatMessagePayload       = new LRU<string, PadchatMessagePayload>(lruOptions)
130
    // this.cachePadchatRoomPayload          = new LRU<string, PadchatRoomRawPayload>(lruOptions)
ruiruibupt's avatar
init  
ruiruibupt 已提交
131 132 133
  }

  public toString() {
134
    return `PuppetPadchat<${this.options.memory.name}>`
ruiruibupt's avatar
init  
ruiruibupt 已提交
135 136 137 138 139 140
  }

  public ding(data?: any): Promise<string> {
    return data
  }

ruiruibupt's avatar
ruiruibupt 已提交
141
  public startWatchdog(): void {
142
    log.verbose('PuppetPadchat', 'startWatchdog()')
ruiruibupt's avatar
init  
ruiruibupt 已提交
143

144
    if (!this.padchatManager) {
145 146
      throw new Error('no bridge')
    }
ruiruibupt's avatar
init  
ruiruibupt 已提交
147

ruiruibupt's avatar
ruiruibupt 已提交
148 149 150
    // clean the dog because this could be re-inited
    this.watchdog.removeAllListeners()

151
    /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
152
     * Use bridge's heartbeat to feed dog
153
     */
154
    this.padchatManager.on('heartbeat', (data: string) => {
155 156 157 158 159
      log.silly('PuppetPadchat', 'startWatchdog() bridge.on(heartbeat)')
      this.watchdog.feed({
        data,
      })
    })
ruiruibupt's avatar
ruiruibupt 已提交
160
    this.watchdog.on('feed', async food => {
161
      log.silly('PuppetPadchat', 'startWatchdog() watchdog.on(feed, food={type=%s, data=%s})', food.type, food.data)
ruiruibupt's avatar
ruiruibupt 已提交
162 163
    })

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
164
    this.watchdog.on('reset', async (food, timeout) => {
165 166 167 168 169
      log.warn('PuppetPadchat', 'startWatchdog() dog.on(reset) last food:%s, timeout:%s',
                                food.data,
                                timeout,
              )
      await this.restart('watchdog.on(reset)')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
170
    })
ruiruibupt's avatar
ruiruibupt 已提交
171 172 173 174 175

    this.emit('watchdog', {
      data: 'inited',
    })

ruiruibupt's avatar
ruiruibupt 已提交
176
  }
ruiruibupt's avatar
init  
ruiruibupt 已提交
177 178

  public async start(): Promise<void> {
ruiruibupt's avatar
ruiruibupt 已提交
179
    log.verbose('PuppetPadchat', `start() with ${this.options.memory.name}`)
ruiruibupt's avatar
init  
ruiruibupt 已提交
180

181 182 183 184 185 186
    if (this.state.on()) {
      log.warn('PuppetPadchat', 'start() already on(pending)?')
      await this.state.ready('on')
      return
    }

ruiruibupt's avatar
ruiruibupt 已提交
187 188 189 190 191 192 193
    /**
     * state has two main state: ON / OFF
     * ON (pending)
     * OFF (pending)
     */
    this.state.on('pending')

194
    const bridge = this.padchatManager = new PadchatManager({
195 196 197 198 199 200
      memory   : this.options.memory,
      token    : padchatToken(),
      endpoint : WECHATY_PUPPET_PADCHAT_ENDPOINT,
    })

    await this.startBridge(bridge)
ruiruibupt's avatar
ruiruibupt 已提交
201
    await this.startWatchdog()
ruiruibupt's avatar
ruiruibupt 已提交
202

ruiruibupt's avatar
ruiruibupt 已提交
203
    this.state.on(true)
204
    this.emit('start')
205
  }
ruiruibupt's avatar
init  
ruiruibupt 已提交
206

207
  protected async login(selfId: string): Promise<void> {
208
    if (!this.padchatManager) {
209 210
      throw new Error('no bridge')
    }
211
    await super.login(selfId)
212
    this.padchatManager.syncContactsAndRooms()
ruiruibupt's avatar
init  
ruiruibupt 已提交
213 214
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
215
  public async startBridge(bridge: PadchatManager): Promise<void> {
ruiruibupt's avatar
ruiruibupt 已提交
216
    log.verbose('PuppetPadchat', 'startBridge()')
ruiruibupt's avatar
ruiruibupt 已提交
217 218

    if (this.state.off()) {
219
      throw new Error('startBridge() state is off')
ruiruibupt's avatar
ruiruibupt 已提交
220 221
    }

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
    bridge.removeAllListeners()
    // bridge.on('ding'     , Event.onDing.bind(this))
    // bridge.on('error'    , e => this.emit('error', e))
    // bridge.on('log'      , Event.onLog.bind(this))
    bridge.on('scan',    (qrcode: string, status: number, data?: string) => this.emit('scan', qrcode, status, data))
    bridge.on('login',   (userId: string)                                => this.login(userId))
    bridge.on('message', (rawPayload: PadchatMessagePayload)             => this.onPadchatMessage(rawPayload))
    bridge.on('logout',  ()                                              => this.logout())

    bridge.on('destroy', reason => {
      log.warn('PuppetPadchat', 'startBridge() bridge.on(destroy) for %s. Restarting PuppetPadchat ... ', reason)
      this.restart(reason)
    })

    await bridge.start()
  }

  protected async restart(reason: string): Promise<void> {
    log.verbose('PuppetPadchat', 'restart(%s)', reason)

    await this.stop()
    await this.start()
ruiruibupt's avatar
init  
ruiruibupt 已提交
244 245 246

  }

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
247
  protected async onPadchatMessage(rawPayload: PadchatMessagePayload): Promise<void> {
248 249 250 251 252
    log.verbose('PuppetPadchat', 'onPadchatMessage({id=%s, type=%s(%s)})',
                                rawPayload.msg_id,
                                PadchatMessageType[rawPayload.sub_type],
                                rawPayload.msg_type,
              )
253 254 255 256 257 258 259 260
    /**
     * 0. Discard messages when not logged in
     */
    if (!this.id) {
      log.warn('PuppetPadchat', 'onPadchatMessage({id=%s, type=%s(%s)}) discarded message because puppet is not logged-in')
      return
    }

ruiruibupt's avatar
ruiruibupt 已提交
261
    /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
262
     * 1. Sometimes will get duplicated same messages from rpc, drop the same message from here.
ruiruibupt's avatar
ruiruibupt 已提交
263 264
     */
    if (this.cachePadchatMessagePayload.has(rawPayload.msg_id)) {
265 266 267 268
      log.warn('PuppetPadchat', 'onPadchatMessage(id=%s) duplicate message: %s',
                                rawPayload.msg_id,
                                JSON.stringify(rawPayload).substr(0, 500),
              )
ruiruibupt's avatar
ruiruibupt 已提交
269 270 271
      return
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
272 273 274 275 276 277 278 279
    /**
     * 2. Save message for future usage
     */
    this.cachePadchatMessagePayload.set(
      rawPayload.msg_id,
      rawPayload,
    )

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
280 281
    console.log('rawPayload:', rawPayload)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
282 283 284
    /**
     * 3. Check for Different Message Types
     */
285 286
    switch (rawPayload.sub_type) {
      case PadchatMessageType.VerifyMsg:
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
287
        this.emit('friendship', rawPayload.msg_id)
288 289
        break

290 291 292 293 294 295 296
      case PadchatMessageType.Recalled:
        /**
         * When someone joined the room invited by Bot,
         * the bot will receive a `recall-able` message for room event
         *
         * { content: '12740017638@chatroom:\n<sysmsg type="delchatroommember">\n\t<delchatroommember>\n\t\t<plain>
         *            <![CDATA[You invited 卓桓、Zhuohuan, 太阁_传话助手, 桔小秘 to the group chat.   ]]></plain>...,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
297
         *  sub_type: 10002}
298 299
         */
        await Promise.all([
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
300
          this.onPadchatMessageRoomEventJoin(rawPayload),
301 302
        ])
        break
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
303
      case PadchatMessageType.Sys:
304 305
        await Promise.all([
          this.onPadchatMessageFriendshipEvent(rawPayload),
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
306 307 308 309
          ////////////////////////////////////////////////
          this.onPadchatMessageRoomEventJoin(rawPayload),
          this.onPadchatMessageRoomEventLeave(rawPayload),
          this.onPadchatMessageRoomEventTopic(rawPayload),
310
        ])
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
311 312
        break

313 314 315 316 317 318
      case PadchatMessageType.App:
      case PadchatMessageType.Emoticon:
      case PadchatMessageType.Image:
      case PadchatMessageType.MicroVideo:
      case PadchatMessageType.Video:
      case PadchatMessageType.Voice:
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
319
        // TODO: the above types are filel type
320

321 322 323 324 325 326
      default:
        this.emit('message', rawPayload.msg_id)
        break
    }
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
327 328 329 330 331 332
  /**
   * Look for room join event
   */
  protected async onPadchatMessageRoomEventJoin(rawPayload: PadchatMessagePayload): Promise<void> {
    log.verbose('PuppetPadchat', 'onPadchatMessageRoomEventJoin({id=%s})', rawPayload.msg_id)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
333 334 335 336 337 338
    const roomJoinEvent = roomJoinEventMessageParser(rawPayload)

    if (roomJoinEvent) {
      const inviteeNameList = roomJoinEvent.inviteeNameList
      const inviterName     = roomJoinEvent.inviterName
      const roomId          = roomJoinEvent.roomId
339
      log.silly('PuppetPadchat', 'onPadchatMessageRoomEventJoin() roomJoinEvent="%s"', JSON.stringify(roomJoinEvent))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
340

341 342 343 344 345 346 347 348
      const inviteeIdList = await Misc.retry(async (retry, attempt) => {
        log.verbose('PuppetPadchat', 'onPadchatMessageRoomEvent({id=%s}) roomJoin retry(attempt=%d)', attempt)

        const tryIdList = flatten<string>(
          await Promise.all(
            inviteeNameList.map(
              inviteeName => this.roomMemberSearch(roomId, inviteeName),
            ),
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
349
          ),
350 351 352 353 354 355
        )

        if (tryIdList.length) {
          return tryIdList
        }

356
        if (!this.padchatManager) {
357 358 359 360
          throw new Error('no manager')
        }

        /**
361
         * Dirty Cache
362
         */
363
        this.roomMemberPayloadDirty(roomId)
364 365 366 367 368 369 370 371

        return retry(new Error('roomMemberSearch() not found'))

      }).catch(e => {
        log.warn('PuppetPadchat', 'onPadchatMessageRoomEvent({id=%s}) roomJoin retry() fail: %s', e.message)
        return [] as string[]
      })

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
372
      const inviterIdList = await this.roomMemberSearch(roomId, inviterName)
373

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
374 375 376
      if (inviterIdList.length < 1) {
        throw new Error('no inviterId found')
      } else if (inviterIdList.length > 1) {
377
        log.warn('PuppetPadchat', 'onPadchatMessageRoomEvent() case PadchatMesssageSys: inviterId found more than 1, use the first one.')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
378
      }
379

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
380 381
      const inviterId = inviterIdList[0]

382
      this.emit('room-join', roomId, inviteeIdList,  inviterId)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
383
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
384 385 386 387 388 389 390 391
  }

  /**
   * Look for room leave event
   */
  protected async onPadchatMessageRoomEventLeave(rawPayload: PadchatMessagePayload): Promise<void> {
    log.verbose('PuppetPadchat', 'onPadchatMessageRoomEventLeave({id=%s})', rawPayload.msg_id)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
392 393 394 395 396 397
    const roomLeaveEvent = roomLeaveEventMessageParser(rawPayload)

    if (roomLeaveEvent) {
      const leaverNameList = roomLeaveEvent.leaverNameList
      const removerName    = roomLeaveEvent.removerName
      const roomId         = roomLeaveEvent.roomId
398
      log.silly('PuppetPadchat', 'onPadchatMessageRoomEventLeave() roomLeaveEvent="%s"', JSON.stringify(roomLeaveEvent))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414

      const leaverIdList = flatten<string>(
        await Promise.all(
          leaverNameList.map(
            leaverName => this.roomMemberSearch(roomId, leaverName),
          ),
        ),
      )
      const removerIdList = await this.roomMemberSearch(roomId, removerName)
      if (removerIdList.length < 1) {
        throw new Error('no removerId found')
      } else if (removerIdList.length > 1) {
        log.warn('PuppetPadchat', 'onPadchatMessage() case PadchatMesssageSys: removerId found more than 1, use the first one.')
      }
      const removerId = removerIdList[0]

415 416 417 418 419
      if (!this.padchatManager) {
        throw new Error('no padchatManager')
      }

      /**
420
       * Dirty Cache
421
       */
422
      this.roomMemberPayloadDirty(roomId)
423

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
424 425
      this.emit('room-leave',  roomId, leaverIdList, removerId)
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
426 427 428 429 430 431 432 433
  }

  /**
   * Look for room topic event
   */
  protected async onPadchatMessageRoomEventTopic(rawPayload: PadchatMessagePayload): Promise<void> {
    log.verbose('PuppetPadchat', 'onPadchatMessageRoomEventTopic({id=%s})', rawPayload.msg_id)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
434 435 436 437 438 439
    const roomTopicEvent = roomTopicEventMessageParser(rawPayload)

    if (roomTopicEvent) {
      const changerName = roomTopicEvent.changerName
      const newTopic    = roomTopicEvent.topic
      const roomId      = roomTopicEvent.roomId
440
      log.silly('PuppetPadchat', 'onPadchatMessageRoomEventTopic() roomTopicEvent="%s"', JSON.stringify(roomTopicEvent))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
441 442 443 444 445 446 447 448 449 450 451 452

      const roomPayload = await this.roomPayload(roomId)
      const oldTopic = roomPayload.topic

      const changerIdList = await this.roomMemberSearch(roomId, changerName)
      if (changerIdList.length < 1) {
        throw new Error('no changerId found')
      } else if (changerIdList.length > 1) {
        log.warn('PuppetPadchat', 'onPadchatMessage() case PadchatMesssageSys: changerId found more than 1, use the first one.')
      }
      const changerId = changerIdList[0]

453 454 455 456 457 458 459 460 461
      if (!this.padchatManager) {
        throw new Error('no padchatManager')
      }
      /**
       * Update Room Payload to new Topic
       */
      const updateRoomPayload = await this.roomPayload(roomId)
      updateRoomPayload.topic = newTopic
      this.cacheRoomPayload.set(roomId, updateRoomPayload)
462 463

      this.roomPayloadDirty(roomId)
464

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
465 466
      this.emit('room-topic',  roomId, newTopic, oldTopic, changerId)
    }
467 468 469
  }

  protected async onPadchatMessageFriendshipEvent(rawPayload: PadchatMessagePayload): Promise<void> {
470
    log.verbose('PuppetPadchat', 'onPadchatMessageFriendshipEvent({id=%s})', rawPayload.msg_id)
471
    /**
472
     * 1. Look for friendship confirm event
473
     */
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
    const friendshipConfirmContactId = friendshipConfirmEventMessageParser(rawPayload)
    /**
     * 2. Look for friendship receive event
     */
    const friendshipReceiveContactId = friendshipReceiveEventMessageParser(rawPayload)
    /**
     * 3. Look for friendship verify event
     */
    const friendshipVerifyContactId = friendshipVerifyEventMessageParser(rawPayload)

    if (   friendshipConfirmContactId
        || friendshipReceiveContactId
        || friendshipVerifyContactId
    ) {
      this.emit('friendship', rawPayload.msg_id)
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
490 491
  }

ruiruibupt's avatar
init  
ruiruibupt 已提交
492
  public async stop(): Promise<void> {
493 494
    log.verbose('PuppetPadchat', 'stop()')

495
    if (!this.padchatManager) {
496 497
      throw new Error('no bridge')
    }
ruiruibupt's avatar
init  
ruiruibupt 已提交
498 499

    if (this.state.off()) {
500
      log.warn('PuppetPadchat', 'stop() is called on a OFF puppet. await ready(off) and return.')
ruiruibupt's avatar
init  
ruiruibupt 已提交
501 502 503 504 505
      await this.state.ready('off')
      return
    }

    this.state.off('pending')
ruiruibupt's avatar
ruiruibupt 已提交
506 507 508

    this.watchdog.sleep()
    await this.logout()
ruiruibupt's avatar
ruiruibupt 已提交
509

510 511
    setImmediate(() => this.padchatManager && this.padchatManager.removeAllListeners())
    await this.padchatManager.stop()
ruiruibupt's avatar
ruiruibupt 已提交
512

ruiruibupt's avatar
init  
ruiruibupt 已提交
513 514
    // await some tasks...
    this.state.off(true)
515
    this.emit('stop')
ruiruibupt's avatar
init  
ruiruibupt 已提交
516 517
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
518
  public async logout(): Promise<void> {
ruiruibupt's avatar
init  
ruiruibupt 已提交
519 520
    log.verbose('PuppetPadchat', 'logout()')

521
    if (!this.id) {
522 523 524 525 526
      log.warn('PuppetPadchat', 'logout() this.id not exist')
      // throw new Error('logout before login?')
      return
    }

527
    if (!this.padchatManager) {
528
      throw new Error('no bridge')
ruiruibupt's avatar
init  
ruiruibupt 已提交
529 530
    }

531 532
    this.emit('logout', this.id) // becore we will throw above by logonoff() when this.user===undefined
    this.id = undefined
ruiruibupt's avatar
init  
ruiruibupt 已提交
533

534 535 536 537
    // if (!passive) {
    //   await this.bridge.WXLogout()
    // }

538
    await this.padchatManager.logout()
ruiruibupt's avatar
init  
ruiruibupt 已提交
539 540 541 542 543 544 545 546 547 548 549 550 551 552
  }

  /**
   *
   * Contact
   *
   */
  public contactAlias(contactId: string)                      : Promise<string>
  public contactAlias(contactId: string, alias: string | null): Promise<void>

  public async contactAlias(contactId: string, alias?: string|null): Promise<void | string> {
    log.verbose('PuppetPadchat', 'contactAlias(%s, %s)', contactId, alias)

    if (typeof alias === 'undefined') {
ruiruibupt's avatar
ruiruibupt 已提交
553
      const payload = await this.contactPayload(contactId)
ruiruibupt's avatar
ruiruibupt 已提交
554
      return payload.alias || ''
ruiruibupt's avatar
init  
ruiruibupt 已提交
555
    }
ruiruibupt's avatar
ruiruibupt 已提交
556

557
    if (!this.padchatManager) {
558 559 560
      throw new Error('no bridge')
    }

561
    await this.padchatManager.WXSetUserRemark(contactId, alias || '')
ruiruibupt's avatar
ruiruibupt 已提交
562

ruiruibupt's avatar
init  
ruiruibupt 已提交
563 564 565
    return
  }

566 567
  public async contactList(): Promise<string[]> {
    log.verbose('PuppetPadchat', 'contactList()')
ruiruibupt's avatar
init  
ruiruibupt 已提交
568

569
    if (!this.padchatManager) {
570 571 572
      throw new Error('no bridge')
    }

573
    const contactIdList = this.padchatManager.getContactIdList()
ruiruibupt's avatar
ruiruibupt 已提交
574 575 576 577

    return contactIdList
  }

578 579
  public async contactAvatar(contactId: string)                : Promise<FileBox>
  public async contactAvatar(contactId: string, file: FileBox) : Promise<void>
ruiruibupt's avatar
init  
ruiruibupt 已提交
580

581
  public async contactAvatar(contactId: string, file?: FileBox): Promise<void | FileBox> {
582 583 584 585
    log.verbose('PuppetPadchat', 'contactAvatar(%s%s)',
                                  contactId,
                                  file ? (', ' + file.name) : '',
                )
586 587 588 589 590 591 592 593

    /**
     * 1. set avatar for user self
     */
    if (file) {
      if (contactId !== this.selfId()) {
        throw new Error('can not set avatar for others')
      }
594
      if (!this.padchatManager) {
595 596
        throw new Error('no bridge')
      }
597
      await this.padchatManager.WXSetHeadImage(await file.toBase64())
598 599 600 601 602 603
      return
    }

    /**
     * 2. get avatar
     */
ruiruibupt's avatar
ruiruibupt 已提交
604 605 606 607 608 609
    const payload = await this.contactPayload(contactId)

    if (!payload.avatar) {
      throw new Error('no avatar')
    }

610 611 612 613
    const fileBox = FileBox.fromUrl(
      payload.avatar,
      `wechaty-contact-avatar-${payload.name}.jpg`,
    )
614 615 616
    return fileBox
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
617
  public async contactQrcode(contactId: string): Promise<string> {
618 619 620
    if (contactId !== this.selfId()) {
      throw new Error('can not set avatar for others')
    }
621
    if (!this.padchatManager) {
622 623
      throw new Error('no bridge')
    }
624
    const base64 = await this.padchatManager.WXGetUserQRCode(contactId, 0)
625
    const qrcode = await fileBoxToQrcode(base64)
626
    return qrcode
ruiruibupt's avatar
init  
ruiruibupt 已提交
627 628
  }

629 630 631 632 633 634 635 636 637 638
  public async contactPayloadDirty(contactId: string): Promise<void> {
    log.verbose('PuppetPadchat', 'contactPayloadDirty(%s)', contactId)

    if (this.padchatManager) {
      this.padchatManager.contactRawPayloadDirty(contactId)
    }

    super.contactPayloadDirty(contactId)
  }

639
  public async contactRawPayload(contactId: string): Promise<PadchatContactPayload> {
640
    log.silly('PuppetPadchat', 'contactRawPayload(%s)', contactId)
ruiruibupt's avatar
ruiruibupt 已提交
641

642
    if (!this.padchatManager) {
643 644
      throw new Error('no bridge')
    }
645
    const rawPayload = await this.padchatManager.contactRawPayload(contactId)
ruiruibupt's avatar
init  
ruiruibupt 已提交
646 647 648
    return rawPayload
  }

649
  public async contactRawPayloadParser(rawPayload: PadchatContactPayload): Promise<ContactPayload> {
650
    log.silly('PuppetPadchat', 'contactRawPayloadParser({user_name="%s"})', rawPayload.user_name)
ruiruibupt's avatar
init  
ruiruibupt 已提交
651

652
    const payload: ContactPayload = contactRawPayloadParser(rawPayload)
ruiruibupt's avatar
init  
ruiruibupt 已提交
653 654 655 656 657 658 659 660
    return payload
  }

  /**
   *
   * Message
   *
   */
ruiruibupt's avatar
ruiruibupt 已提交
661

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
662
  public async messageFile(messageId: string): Promise<FileBox> {
663
    log.warn('PuppetPadchat', 'messageFile(%s) not fully implemented yet, PR is welcome!', messageId)
ruiruibupt's avatar
ruiruibupt 已提交
664

ruiruibupt's avatar
ruiruibupt 已提交
665 666
    // TODO

667
    if (!this.padchatManager) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
668 669 670 671 672 673
      throw new Error('no bridge')
    }

    const rawPayload = await this.messageRawPayload(messageId)
    const payload    = await this.messagePayload(messageId)

674 675
    const rawText        = JSON.stringify(rawPayload)
    const attachmentName = payload.filename || payload.id
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
676 677 678 679 680 681 682 683

    let result

    switch (payload.type) {
      case MessageType.Attachment:
        break

      case MessageType.Audio:
684
        result = await this.padchatManager.WXGetMsgVoice(rawText)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
685
        console.log(result)
686
        return FileBox.fromBase64(result.voice, `${attachmentName}.slk`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
687 688

      case MessageType.Emoticon:
689
        result = await this.padchatManager.WXGetMsgEmoticon(rawText)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
690
        console.log(result)
691
        return FileBox.fromBase64(result.image, `${attachmentName}.gif`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
692 693

      case MessageType.Image:
694
        result = await this.padchatManager.WXGetMsgImage(rawText)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
695
        console.log(result)
696
        return FileBox.fromBase64(result.image, `${attachmentName}.jpg`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
697 698

      case MessageType.Video:
699
        result = await this.padchatManager.WXGetMsgVideo(rawText)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
700
        console.log(result)
701
        return FileBox.fromBase64(result.video, `${attachmentName}.mp4`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
702 703 704 705 706

      default:
        throw new Error('unsupport type: ' + PadchatMessageType[rawPayload.sub_type] + ':' + rawPayload.sub_type)
    }

ruiruibupt's avatar
ruiruibupt 已提交
707
    const base64 = 'cRH9qeL3XyVnaXJkppBuH20tf5JlcG9uFX1lL2IvdHRRRS9kMMQxOPLKNYIzQQ=='
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
708
    const filename = 'test-' + messageId + '.txt'
ruiruibupt's avatar
ruiruibupt 已提交
709

710
    const file = FileBox.fromBase64(
ruiruibupt's avatar
ruiruibupt 已提交
711 712 713 714 715 716 717
      base64,
      filename,
    )

    return file
  }

718 719 720 721 722 723 724 725 726 727
  public async messagePayloadDirty(messageId: string): Promise<void> {
    log.verbose('PuppetPadchat', 'messagePayloadDirty(%s)', messageId)

    if (this.padchatManager) {
      // this.padchatManager.messageRawPayloadDirty(messageId)
    }

    super.messagePayloadDirty(messageId)
  }

728
  public async messageRawPayload(id: string): Promise<PadchatMessagePayload> {
729 730 731 732 733
    // throw Error('should not call messageRawPayload: ' + id)

    /**
     * Issue #1249
     */
ruiruibupt's avatar
ruiruibupt 已提交
734 735 736 737 738

    // this.cachePadchatMessageRawPayload.set(id, {
    //   id: 'xxx',
    //   data: 'xxx',
    // } as any)
739

740
    const rawPayload = this.cachePadchatMessagePayload.get(id)
741 742 743 744 745 746

    if (!rawPayload) {
      throw new Error('no rawPayload')
    }

    return rawPayload
ruiruibupt's avatar
init  
ruiruibupt 已提交
747 748
  }

749
  public async messageRawPayloadParser(rawPayload: PadchatMessagePayload): Promise<MessagePayload> {
750
    log.verbose('PuppetPadChat', 'messageRawPayloadParser({msg_id="%s"})', rawPayload.msg_id)
751

752
    const payload: MessagePayload = messageRawPayloadParser(rawPayload)
ruiruibupt's avatar
ruiruibupt 已提交
753

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
754
    log.silly('PuppetPadchat', 'messagePayload(%s)', JSON.stringify(payload))
ruiruibupt's avatar
init  
ruiruibupt 已提交
755 756 757 758 759 760 761
    return payload
  }

  public async messageSendText(
    receiver : Receiver,
    text     : string,
  ): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
762
    log.verbose('PuppetPadchat', 'messageSend(%s, %s)', JSON.stringify(receiver), text)
763 764 765 766

    // roomId first, contactId second.
    const id = receiver.roomId || receiver.contactId

ruiruibupt's avatar
ruiruibupt 已提交
767
    if (!id) {
768
      throw Error('no id')
ruiruibupt's avatar
ruiruibupt 已提交
769
    }
770
    if (!this.padchatManager) {
771 772
      throw new Error('no bridge')
    }
773
    await this.padchatManager.WXSendMsg(id, text)
ruiruibupt's avatar
init  
ruiruibupt 已提交
774 775 776 777 778 779
  }

  public async messageSendFile(
    receiver : Receiver,
    file     : FileBox,
  ): Promise<void> {
780
    log.verbose('PuppetPadchat', 'messageSend("%s", %s)', JSON.stringify(receiver), file)
ruiruibupt's avatar
ruiruibupt 已提交
781

782 783 784
    // roomId first, contactId second.
    const id = receiver.roomId || receiver.contactId

ruiruibupt's avatar
ruiruibupt 已提交
785 786 787 788
    if (!id) {
      throw new Error('no id!')
    }

789
    if (!this.padchatManager) {
790 791 792
      throw new Error('no bridge')
    }

793 794 795 796
    const type = file.mimeType || path.extname(file.name)
    switch (type) {
      case '.slk':
        // 发送语音消息(微信silk格式语音)
797
        await this.padchatManager.WXSendVoice(
798 799 800 801 802 803 804
          id,
          await file.toBase64(),
          60,
        )
        break

      default:
805
        await this.padchatManager.WXSendImage(
806 807 808 809 810
          id,
          await file.toBase64(),
        )
        break
    }
ruiruibupt's avatar
init  
ruiruibupt 已提交
811 812
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
813 814 815 816 817 818
  public async messageSendContact(
    receiver  : Receiver,
    contactId : string,
  ): Promise<void> {
    log.verbose('PuppetPadchat', 'messageSend("%s", %s)', JSON.stringify(receiver), contactId)

819
    if (!this.padchatManager) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
820 821 822
      throw new Error('no bridge')
    }

823 824 825
    // roomId first, contactId second.
    const id = receiver.roomId || receiver.contactId

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
826 827 828 829 830 831
    if (!id) {
      throw Error('no id')
    }

    const payload = await this.contactPayload(contactId)
    const title = payload.name + '名片'
832
    await this.padchatManager.WXShareCard(id, contactId, title)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
833 834
  }

ruiruibupt's avatar
init  
ruiruibupt 已提交
835 836 837 838 839
  public async messageForward(
    receiver  : Receiver,
    messageId : string,
  ): Promise<void> {
    log.verbose('PuppetPadchat', 'messageForward(%s, %s)',
840
                              JSON.stringify(receiver),
ruiruibupt's avatar
init  
ruiruibupt 已提交
841 842
                              messageId,
              )
843
    const payload = await this.messagePayload(messageId)
ruiruibupt's avatar
ruiruibupt 已提交
844

845 846 847 848
    if (payload.type === MessageType.Text) {
      if (!payload.text) {
        throw new Error('no text')
      }
ruiruibupt's avatar
ruiruibupt 已提交
849 850
      await this.messageSendText(
        receiver,
851
        payload.text,
ruiruibupt's avatar
ruiruibupt 已提交
852 853 854 855
      )
    } else {
      await this.messageSendFile(
        receiver,
856
        await this.messageFile(messageId),
ruiruibupt's avatar
ruiruibupt 已提交
857 858
      )
    }
ruiruibupt's avatar
init  
ruiruibupt 已提交
859 860 861 862 863 864 865
  }

  /**
   *
   * Room
   *
   */
866 867 868 869 870 871 872 873 874 875
  public async roomMemberPayloadDirty(roomId: string) {
    log.silly('PuppetPadchat', 'roomMemberRawPayloadDirty(%s)', roomId)

    if (this.padchatManager) {
      await this.padchatManager.roomMemberRawPayloadDirty(roomId)
    }

    super.roomMemberPayloadDirty(roomId)
  }

876 877 878 879 880
  public async roomMemberRawPayload(
    roomId    : string,
    contactId : string,
  ): Promise<PadchatRoomMemberPayload> {
    log.silly('PuppetPadchat', 'roomMemberRawPayload(%s)', roomId)
ruiruibupt's avatar
ruiruibupt 已提交
881

882
    if (!this.padchatManager) {
883 884 885
      throw new Error('no bridge')
    }

886 887 888
    const memberDictRawPayload = await this.padchatManager.roomMemberRawPayload(roomId)

    return memberDictRawPayload[contactId]
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
  }

  public async roomMemberRawPayloadParser(
    rawPayload: PadchatRoomMemberPayload,
  ): Promise<RoomMemberPayload> {
    log.silly('PuppetPadchat', 'roomMemberRawPayloadParser(%s)', rawPayload)

    const payload: RoomMemberPayload = {
      id        : rawPayload.user_name,
      inviterId : rawPayload.invited_by,
      roomAlias : rawPayload.chatroom_nick_name,
    }

    return payload
  }

905 906 907 908 909 910 911 912 913 914
  public async roomPayloadDirty(roomId: string): Promise<void> {
    log.verbose('PuppetPadchat', 'roomPayloadDirty(%s)', roomId)

    if (this.padchatManager) {
      this.padchatManager.roomRawPayloadDirty(roomId)
    }

    super.roomPayloadDirty(roomId)
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
915 916 917
  public async roomRawPayload(
    roomId: string,
  ): Promise<PadchatRoomPayload> {
918 919
    log.verbose('PuppetPadchat', 'roomRawPayload(%s)', roomId)

920
    if (!this.padchatManager) {
921 922 923
      throw new Error('no bridge')
    }

924
    const rawPayload = await this.padchatManager.roomRawPayload(roomId)
ruiruibupt's avatar
init  
ruiruibupt 已提交
925 926 927
    return rawPayload
  }

928
  public async roomRawPayloadParser(rawPayload: PadchatRoomPayload): Promise<RoomPayload> {
929
    log.verbose('PuppetPadchat', 'roomRawPayloadParser(rawPayload.user_name="%s")', rawPayload.user_name)
ruiruibupt's avatar
init  
ruiruibupt 已提交
930

931
    const payload: RoomPayload = roomRawPayloadParser(rawPayload)
ruiruibupt's avatar
init  
ruiruibupt 已提交
932 933 934
    return payload
  }

935 936 937
  public async roomMemberList(roomId: string): Promise<string[]> {
    log.verbose('PuppetPadchat', 'roomMemberList(%s)', roomId)

938
    if (!this.padchatManager) {
939 940 941
      throw new Error('no bridge')
    }

942
    const memberIdList = await this.padchatManager.getRoomMemberIdList(roomId)
943 944 945 946 947
    log.silly('PuppetPadchat', 'roomMemberList()=%d', memberIdList.length)

    return memberIdList
  }

948
  public async roomList(): Promise<string[]> {
ruiruibupt's avatar
ruiruibupt 已提交
949
    log.verbose('PuppetPadchat', 'roomList()')
950

951
    if (!this.padchatManager) {
952 953 954
      throw new Error('no bridge')
    }

955
    const roomIdList = await this.padchatManager.getRoomIdList()
956
    log.silly('PuppetPadchat', 'roomList()=%d', roomIdList.length)
ruiruibupt's avatar
ruiruibupt 已提交
957

ruiruibupt's avatar
ruiruibupt 已提交
958
    return roomIdList
ruiruibupt's avatar
init  
ruiruibupt 已提交
959 960 961 962 963 964 965
  }

  public async roomDel(
    roomId    : string,
    contactId : string,
  ): Promise<void> {
    log.verbose('PuppetPadchat', 'roomDel(%s, %s)', roomId, contactId)
ruiruibupt's avatar
ruiruibupt 已提交
966

967
    if (!this.padchatManager) {
968 969 970
      throw new Error('no bridge')
    }

971
    // Should check whether user is in the room. WXDeleteChatRoomMember won't check if user in the room automatically
972
    await this.padchatManager.WXDeleteChatRoomMember(roomId, contactId)
973
    await this.roomMemberPayloadDirty(roomId)
ruiruibupt's avatar
init  
ruiruibupt 已提交
974 975
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
976
  public async roomQrcode(roomId: string): Promise<string> {
977 978 979 980 981 982 983 984
    log.verbose('PuppetPadchat', 'roomQrCode(%s)', roomId)

    // TODO

    throw new Error('not support')

  }

985 986 987 988 989 990 991 992 993 994 995 996 997
  public async roomAvatar(roomId: string): Promise<FileBox> {
    log.verbose('PuppetPadchat', 'roomAvatar(%s)', roomId)

    const payload = await this.roomPayload(roomId)

    if (payload.avatar) {
      return FileBox.fromUrl(payload.avatar)
    }
    log.warn('PuppetPadchat', 'roomAvatar() avatar not found, use the chatie default.')

    return qrCodeForChatie()
  }

ruiruibupt's avatar
init  
ruiruibupt 已提交
998 999 1000 1001 1002
  public async roomAdd(
    roomId    : string,
    contactId : string,
  ): Promise<void> {
    log.verbose('PuppetPadchat', 'roomAdd(%s, %s)', roomId, contactId)
1003

1004
    if (!this.padchatManager) {
1005 1006 1007
      throw new Error('no bridge')
    }

1008 1009 1010 1011
    // XXX: did there need to calc the total number of the members in this room?
    // if n <= 40 then add() else invite() ?
    try {
      log.verbose('PuppetPadchat', 'roomAdd(%s, %s) try to Add', roomId, contactId)
1012
      await this.padchatManager.WXAddChatRoomMember(roomId, contactId)
1013 1014 1015 1016 1017
    } catch (e) {
      // FIXME
      console.error(e)
      log.warn('PuppetPadchat', 'roomAdd(%s, %s) Add exception: %s', e)
      log.verbose('PuppetPadchat', 'roomAdd(%s, %s) try to Invite', roomId, contactId)
1018
      await this.padchatManager.WXInviteChatRoomMember(roomId, contactId)
1019
    }
1020
    await this.roomMemberPayloadDirty(roomId)
ruiruibupt's avatar
init  
ruiruibupt 已提交
1021 1022
  }

1023 1024 1025
  public async roomTopic(roomId: string)                : Promise<string>
  public async roomTopic(roomId: string, topic: string) : Promise<void>

ruiruibupt's avatar
init  
ruiruibupt 已提交
1026 1027 1028 1029 1030 1031 1032
  public async roomTopic(
    roomId: string,
    topic?: string,
  ): Promise<void | string> {
    log.verbose('PuppetPadchat', 'roomTopic(%s, %s)', roomId, topic)

    if (typeof topic === 'undefined') {
ruiruibupt's avatar
ruiruibupt 已提交
1033
      const payload = await this.roomPayload(roomId)
ruiruibupt's avatar
ruiruibupt 已提交
1034
      return payload.topic
ruiruibupt's avatar
init  
ruiruibupt 已提交
1035
    }
ruiruibupt's avatar
ruiruibupt 已提交
1036

1037
    if (!this.padchatManager) {
1038 1039 1040
      throw new Error('no bridge')
    }

1041
    await this.padchatManager.WXSetChatroomName(roomId, topic)
1042
    await this.roomPayloadDirty(roomId)
ruiruibupt's avatar
ruiruibupt 已提交
1043

ruiruibupt's avatar
init  
ruiruibupt 已提交
1044 1045 1046 1047 1048 1049 1050 1051 1052
    return
  }

  public async roomCreate(
    contactIdList : string[],
    topic         : string,
  ): Promise<string> {
    log.verbose('PuppetPadchat', 'roomCreate(%s, %s)', contactIdList, topic)

1053
    if (!this.padchatManager) {
1054 1055 1056
      throw new Error('no bridge')
    }

1057
    const roomId = await this.padchatManager.WXCreateChatRoom(contactIdList)
1058

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1059 1060
    // Load new created room payload
    await this.roomPayload(roomId)
1061

1062
    return roomId
ruiruibupt's avatar
init  
ruiruibupt 已提交
1063 1064 1065 1066
  }

  public async roomQuit(roomId: string): Promise<void> {
    log.verbose('PuppetPadchat', 'roomQuit(%s)', roomId)
1067

1068
    if (!this.padchatManager) {
1069 1070 1071
      throw new Error('no bridge')
    }

1072
    await this.padchatManager.WXQuitChatRoom(roomId)
ruiruibupt's avatar
init  
ruiruibupt 已提交
1073 1074
  }

1075 1076 1077 1078 1079
  public async roomAnnounce(roomId: string)             : Promise<string>
  public async roomAnnounce(roomId: string, text: string) : Promise<void>

  public async roomAnnounce(roomId: string, text?: string): Promise<void | string> {
    log.verbose('PuppetPadchat', 'roomAnnounce(%s, %s)', roomId, text ? text : '')
1080

1081
    if (!this.padchatManager) {
1082 1083 1084
      throw new Error('no bridge')
    }

1085
    if (text) {
1086
      await this.padchatManager.WXSetChatroomAnnouncement(roomId, text)
1087
    } else {
1088
      return await this.padchatManager.WXGetChatroomAnnouncement(roomId)
1089 1090 1091
    }
  }

ruiruibupt's avatar
init  
ruiruibupt 已提交
1092 1093
  /**
   *
1094
   * Friendship
ruiruibupt's avatar
init  
ruiruibupt 已提交
1095 1096
   *
   */
1097
  public async friendshipVerify(
ruiruibupt's avatar
init  
ruiruibupt 已提交
1098 1099 1100
    contactId : string,
    hello     : string,
  ): Promise<void> {
1101
    log.verbose('PuppetPadchat', 'friendshipVerify(%s, %s)', contactId, hello)
ruiruibupt's avatar
ruiruibupt 已提交
1102

1103
    if (!this.padchatManager) {
E
Egg 已提交
1104 1105
      throw new Error('no bridge')
    }
ruiruibupt's avatar
ruiruibupt 已提交
1106

1107
    const rawSearchPayload: WXSearchContactType = await this.padchatManager.WXSearchContact(contactId)
1108

E
Egg 已提交
1109 1110 1111
    /**
     * If the contact is not stranger, than ussing WXSearchContact can get user_name
     */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1112
    if (rawSearchPayload.user_name !== '' && !isStrangerV1(rawSearchPayload.user_name) && !isStrangerV2(rawSearchPayload.user_name)) {
E
Egg 已提交
1113 1114 1115
      log.warn('PuppetPadchat', 'friendRequestSend %s has been friend with bot, no need to send friend request!', contactId)
      return
    }
ruiruibupt's avatar
ruiruibupt 已提交
1116

E
Egg 已提交
1117 1118
    let strangerV1
    let strangerV2
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1119
    if (isStrangerV1(rawSearchPayload.stranger)) {
E
Egg 已提交
1120 1121
      strangerV1 = rawSearchPayload.stranger
      strangerV2 = rawSearchPayload.user_name
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1122
    } else if (isStrangerV2(rawSearchPayload.stranger)) {
E
Egg 已提交
1123 1124 1125 1126
      strangerV2 = rawSearchPayload.stranger
      strangerV1 = rawSearchPayload.user_name
    } else {
      throw new Error('stranger neither v1 nor v2!')
1127 1128
    }

E
Egg 已提交
1129
    // Issue #1252 : what's wrong here?, Trying to fix now...
1130

1131
    await this.padchatManager.WXAddUser(
E
Egg 已提交
1132 1133 1134
      strangerV1 || '',
      strangerV2 || '',
      WXSearchContactTypeStatus.WXID, // default
ruiruibupt's avatar
ruiruibupt 已提交
1135 1136
      hello,
    )
ruiruibupt's avatar
init  
ruiruibupt 已提交
1137 1138
  }

1139 1140
  public async friendshipAccept(
    friendshipId : string,
ruiruibupt's avatar
init  
ruiruibupt 已提交
1141
  ): Promise<void> {
1142
    log.verbose('PuppetPadchat', 'friendshipAccept(%s)', friendshipId)
ruiruibupt's avatar
ruiruibupt 已提交
1143

1144
    const payload = await this.friendshipPayload(friendshipId) as FriendshipPayloadReceive
ruiruibupt's avatar
ruiruibupt 已提交
1145

1146
    console.log('friendshipAccept: ', payload)
1147

1148 1149 1150
    if (!payload.ticket) {
      throw new Error('no ticket')
    }
1151 1152 1153
    if (!payload.stranger) {
      throw new Error('no stranger')
    }
ruiruibupt's avatar
ruiruibupt 已提交
1154

1155
    if (!this.padchatManager) {
1156 1157 1158
      throw new Error('no bridge')
    }

1159
    await this.padchatManager.WXAcceptUser(
1160
      payload.stranger,
1161 1162
      payload.ticket,
    )
ruiruibupt's avatar
init  
ruiruibupt 已提交
1163 1164
  }

1165 1166
  public async friendshipRawPayloadParser(rawPayload: PadchatMessagePayload) : Promise<FriendshipPayload> {
    log.verbose('PuppetPadchat', 'friendshipRawPayloadParser({id=%s})', rawPayload.msg_id)
ruiruibupt's avatar
ruiruibupt 已提交
1167

1168
    const payload: FriendshipPayload = await friendshipRawPayloadParser(rawPayload)
1169
    return payload
ruiruibupt's avatar
ruiruibupt 已提交
1170 1171
  }

1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
  public async friendshipPayloadDirty(friendshipId: string): Promise<void> {
    log.verbose('PuppetPadchat', 'friendshipPayloadDirty(%s)', friendshipId)

    if (this.padchatManager) {
      // this.padchatManager.friendshipRawPayloadDirty(friendshipId)
    }

    this.friendshipPayloadDirty(friendshipId)
  }

1182 1183
  public async friendshipRawPayload(friendshipId: string): Promise<PadchatMessagePayload> {
    log.verbose('PuppetPadchat', 'friendshipRawPayload(%s)', friendshipId)
ruiruibupt's avatar
ruiruibupt 已提交
1184

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1185 1186 1187
    /**
     * Friendship shares Cache with the Message RawPayload
     */
1188
    const rawPayload = this.cachePadchatMessagePayload.get(friendshipId)
1189
    if (!rawPayload) {
1190
      throw new Error('no rawPayload for id ' + friendshipId)
1191
    }
ruiruibupt's avatar
ruiruibupt 已提交
1192

1193
    return rawPayload
ruiruibupt's avatar
ruiruibupt 已提交
1194 1195
  }

ruiruibupt's avatar
init  
ruiruibupt 已提交
1196 1197 1198
}

export default PuppetPadchat