puppet-padchat.ts 32.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 50

  WATCHDOG_TIMEOUT,
51
}                                 from '../puppet/'
ruiruibupt's avatar
init  
ruiruibupt 已提交
52

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

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

  isStrangerV1,
  isStrangerV2,

63
  messageRawPayloadParser,
64 65 66

  roomRawPayloadParser,

67 68 69
  roomJoinEventMessageParser,
  roomLeaveEventMessageParser,
  roomTopicEventMessageParser,
70 71 72 73

  friendshipConfirmEventMessageParser,
  friendshipReceiveEventMessageParser,
  friendshipVerifyEventMessageParser,
74
}                                         from './pure-function-helpers'
75

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

81
import {
82
  padchatToken,
83 84 85
  WECHATY_PUPPET_PADCHAT_ENDPOINT,
}                                   from './config'

ruiruibupt's avatar
init  
ruiruibupt 已提交
86
import {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
87
  PadchatManager,
88
  // resolverDict,
ruiruibupt's avatar
ruiruibupt 已提交
89
  // AutoDataType,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
90
}                       from './padchat-manager'
ruiruibupt's avatar
init  
ruiruibupt 已提交
91 92

import {
93
  // PadchatPayload,
94
  PadchatContactPayload,
95
  PadchatMessagePayload,
96
  PadchatRoomPayload,
97 98
  // PadchatRoomMemberListPayload,
  PadchatRoomMemberPayload,
99
  PadchatMessageType,
100

101
  // PadchatMessageType,
102 103 104 105
  // PadchatContinue,
  // PadchatMsgType,
  // PadchatStatus,
  // PadchatPayloadType,
106
  // PadchatRoomRawMember,
107
}                           from './padchat-schemas'
E
Egg 已提交
108 109 110 111
import {
  WXSearchContactType,
  WXSearchContactTypeStatus,
}                           from './padchat-rpc.type'
ruiruibupt's avatar
init  
ruiruibupt 已提交
112 113 114 115 116

export type PuppetFoodType = 'scan' | 'ding'
export type ScanFoodType   = 'scan' | 'login' | 'logout'

export class PuppetPadchat extends Puppet {
117

118 119 120
  // in seconds, 4 minute for padchat
  protected [WATCHDOG_TIMEOUT] = 4 * 60

121
  // private readonly cachePadchatContactPayload       : LRU.Cache<string, PadchatContactRawPayload>
122 123
  private readonly cachePadchatFriendshipPayload : LRU.Cache<string, PadchatMessagePayload>
  private readonly cachePadchatMessagePayload    : LRU.Cache<string, PadchatMessagePayload>
124
  // private readonly cachePadchatRoomPayload          : LRU.Cache<string, PadchatRoomRawPayload>
125

126
  public padchatManager?:  PadchatManager
ruiruibupt's avatar
init  
ruiruibupt 已提交
127 128 129 130 131 132

  constructor(
    public options: PuppetOptions,
  ) {
    super(options)

133 134 135
    const lruOptions: LRU.Options = {
      max: 1000,
      // length: function (n) { return n * 2},
136
      dispose: function (key: string, val: any) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
137
        log.silly('PuppetPadchat', 'constructor() lruOptions.dispose(%s, %s)', key, JSON.stringify(val))
138 139 140 141
      },
      maxAge: 1000 * 60 * 60,
    }

142
    // this.cachePadchatContactPayload       = new LRU<string, PadchatContactRawPayload>(lruOptions)
143
    this.cachePadchatFriendshipPayload = new LRU<string, PadchatMessagePayload>(lruOptions)
144
    this.cachePadchatMessagePayload       = new LRU<string, PadchatMessagePayload>(lruOptions)
145
    // this.cachePadchatRoomPayload          = new LRU<string, PadchatRoomRawPayload>(lruOptions)
ruiruibupt's avatar
init  
ruiruibupt 已提交
146 147 148
  }

  public toString() {
149
    return `PuppetPadchat<${this.options.memory.name}>`
ruiruibupt's avatar
init  
ruiruibupt 已提交
150 151 152 153 154 155
  }

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

ruiruibupt's avatar
ruiruibupt 已提交
156
  public startWatchdog(): void {
ruiruibupt's avatar
ruiruibupt 已提交
157
    log.verbose('PuppetPadchat', 'initWatchdogForPuppet()')
ruiruibupt's avatar
init  
ruiruibupt 已提交
158

159
    if (!this.padchatManager) {
160 161
      throw new Error('no bridge')
    }
ruiruibupt's avatar
init  
ruiruibupt 已提交
162

ruiruibupt's avatar
ruiruibupt 已提交
163 164 165
    // clean the dog because this could be re-inited
    this.watchdog.removeAllListeners()

166
    /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
167
     * Use bridge's heartbeat to feed dog
168
     */
169
    this.padchatManager.on('heartbeat', (data: string) => {
170 171 172 173 174
      log.silly('PuppetPadchat', 'startWatchdog() bridge.on(heartbeat)')
      this.watchdog.feed({
        data,
      })
    })
ruiruibupt's avatar
ruiruibupt 已提交
175
    this.watchdog.on('feed', async food => {
176
      log.silly('PuppetPadchat', 'startWatchdog() watchdog.on(feed, food={type=%s, data=%s})', food.type, food.data)
ruiruibupt's avatar
ruiruibupt 已提交
177 178
    })

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
179
    this.watchdog.on('reset', async (food, timeout) => {
180 181 182 183 184
      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 (李卓桓) 已提交
185
    })
ruiruibupt's avatar
ruiruibupt 已提交
186 187 188 189 190

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

ruiruibupt's avatar
ruiruibupt 已提交
191
  }
ruiruibupt's avatar
init  
ruiruibupt 已提交
192 193

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

196 197 198 199 200 201
    if (this.state.on()) {
      log.warn('PuppetPadchat', 'start() already on(pending)?')
      await this.state.ready('on')
      return
    }

ruiruibupt's avatar
ruiruibupt 已提交
202 203 204 205 206 207 208
    /**
     * state has two main state: ON / OFF
     * ON (pending)
     * OFF (pending)
     */
    this.state.on('pending')

209
    const bridge = this.padchatManager = new PadchatManager({
210 211 212 213 214 215
      memory   : this.options.memory,
      token    : padchatToken(),
      endpoint : WECHATY_PUPPET_PADCHAT_ENDPOINT,
    })

    await this.startBridge(bridge)
ruiruibupt's avatar
ruiruibupt 已提交
216
    await this.startWatchdog()
ruiruibupt's avatar
ruiruibupt 已提交
217

ruiruibupt's avatar
ruiruibupt 已提交
218
    this.state.on(true)
219
    this.emit('start')
220
  }
ruiruibupt's avatar
init  
ruiruibupt 已提交
221

222
  protected async login(selfId: string): Promise<void> {
223
    if (!this.padchatManager) {
224 225
      throw new Error('no bridge')
    }
226
    await super.login(selfId)
227
    this.padchatManager.syncContactsAndRooms()
ruiruibupt's avatar
init  
ruiruibupt 已提交
228 229
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
230
  public async startBridge(bridge: PadchatManager): Promise<void> {
ruiruibupt's avatar
ruiruibupt 已提交
231
    log.verbose('PuppetPadchat', 'startBridge()')
ruiruibupt's avatar
ruiruibupt 已提交
232 233

    if (this.state.off()) {
234
      throw new Error('startBridge() state is off')
ruiruibupt's avatar
ruiruibupt 已提交
235 236
    }

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    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 已提交
259 260 261

  }

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
262
  protected async onPadchatMessage(rawPayload: PadchatMessagePayload): Promise<void> {
263 264 265 266 267
    log.verbose('PuppetPadchat', 'onPadchatMessage({id=%s, type=%s(%s)})',
                                rawPayload.msg_id,
                                PadchatMessageType[rawPayload.sub_type],
                                rawPayload.msg_type,
              )
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
268 269
    console.log('rawPayload:', rawPayload)

270 271
    switch (rawPayload.sub_type) {
      case PadchatMessageType.VerifyMsg:
272
        this.cachePadchatFriendshipPayload.set(
273 274 275
          rawPayload.msg_id,
          rawPayload,
        )
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
276
        this.emit('friendship', rawPayload.msg_id)
277 278
        break

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
      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>...,
         *  continue: 1,
         *  description: '',
         *  from_user: '12740017638@chatroom',
         *  msg_id: '232220931339852872',
         *  msg_source: '',
         *  msg_type: 5,
         *  status: 1,
         *  sub_type: 10002,
         *  timestamp: 1528831349,
         *  to_user: 'wxid_zj2cahpwzgie12',
         *  uin: 324216852 }
         */
        await Promise.all([
          this.onPadchatMessageRoomEvent(rawPayload),
        ])
        break
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
302
      case PadchatMessageType.Sys:
303 304 305 306
        await Promise.all([
          this.onPadchatMessageFriendshipEvent(rawPayload),
          this.onPadchatMessageRoomEvent(rawPayload),
        ])
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
307 308
        break

309 310 311 312 313 314 315 316
      case PadchatMessageType.App:
      case PadchatMessageType.Emoticon:
      case PadchatMessageType.Image:
      case PadchatMessageType.MicroVideo:
      case PadchatMessageType.Video:
      case PadchatMessageType.Voice:
         // TODO: the above types are filel type

317 318 319 320 321 322 323 324 325 326
      default:
        this.cachePadchatMessagePayload.set(
          rawPayload.msg_id,
          rawPayload,
        )
        this.emit('message', rawPayload.msg_id)
        break
    }
  }

327
  protected async onPadchatMessageRoomEvent(rawPayload: PadchatMessagePayload): Promise<void> {
328
    log.verbose('PuppetPadchat', 'onPadchatMessageRoomEvent({id=%s})', rawPayload.msg_id)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
329 330 331 332 333 334 335 336 337
    /**
     * 1. Look for room join event
     */
    const roomJoin = roomJoinEventMessageParser(rawPayload)
    if (roomJoin) {
      const inviteeNameList = roomJoin.inviteeNameList
      const inviterName     = roomJoin.inviterName
      const roomId          = roomJoin.roomId

338 339 340 341 342 343 344 345
      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 (李卓桓) 已提交
346
          ),
347 348 349 350 351 352
        )

        if (tryIdList.length) {
          return tryIdList
        }

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

        /**
         * PURGE Cache and Reload
         */
360
        this.padchatManager.purgeRoomMemberIdList(roomId)
361 362 363 364 365 366 367 368

        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 (李卓桓) 已提交
369
      const inviterIdList = await this.roomMemberSearch(roomId, inviterName)
370

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

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

379
      this.emit('room-join', roomId, inviteeIdList,  inviterId)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
    }
    /**
     * 2. Look for room leave event
     */
    const roomLeave = roomLeaveEventMessageParser(rawPayload)
    if (roomLeave) {
      const leaverNameList = roomLeave.leaverNameList
      const removerName    = roomLeave.removerName
      const roomId         = roomLeave.roomId

      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]

405 406 407 408 409 410 411 412 413 414
      if (!this.padchatManager) {
        throw new Error('no padchatManager')
      }

      /**
       * Update L1 Cache & PURGE L2 Cache
       */
      this.cacheRoomMemberPayload.del(roomId)
      this.padchatManager.purgeRoomMemberIdList(roomId)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
      this.emit('room-leave',  roomId, leaverIdList, removerId)
    }
    /**
     * 3. Look for room topic event
     */
    const roomTopic = roomTopicEventMessageParser(rawPayload)
    if (roomTopic) {
      const changerName = roomTopic.changerName
      const newTopic    = roomTopic.topic
      const roomId      = roomTopic.roomId

      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]

437 438 439 440 441 442 443 444 445 446 447
      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)
      this.padchatManager.purgeRoomMemberIdList(roomId)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
448 449
      this.emit('room-topic',  roomId, newTopic, oldTopic, changerId)
    }
450 451 452
  }

  protected async onPadchatMessageFriendshipEvent(rawPayload: PadchatMessagePayload): Promise<void> {
453
    log.verbose('PuppetPadchat', 'onPadchatMessageFriendshipEvent({id=%s})', rawPayload.msg_id)
454
    /**
455
     * 1. Look for friendship confirm event
456
     */
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
    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 (李卓桓) 已提交
473 474
  }

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

478
    if (!this.padchatManager) {
479 480
      throw new Error('no bridge')
    }
ruiruibupt's avatar
init  
ruiruibupt 已提交
481 482

    if (this.state.off()) {
483
      log.warn('PuppetPadchat', 'stop() is called on a OFF puppet. await ready(off) and return.')
ruiruibupt's avatar
init  
ruiruibupt 已提交
484 485 486 487 488
      await this.state.ready('off')
      return
    }

    this.state.off('pending')
ruiruibupt's avatar
ruiruibupt 已提交
489 490 491

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

493 494
    setImmediate(() => this.padchatManager && this.padchatManager.removeAllListeners())
    await this.padchatManager.stop()
ruiruibupt's avatar
ruiruibupt 已提交
495

ruiruibupt's avatar
init  
ruiruibupt 已提交
496 497
    // await some tasks...
    this.state.off(true)
498
    this.emit('stop')
ruiruibupt's avatar
init  
ruiruibupt 已提交
499 500
  }

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

504
    if (!this.id) {
505 506 507 508 509
      log.warn('PuppetPadchat', 'logout() this.id not exist')
      // throw new Error('logout before login?')
      return
    }

510
    if (!this.padchatManager) {
511
      throw new Error('no bridge')
ruiruibupt's avatar
init  
ruiruibupt 已提交
512 513
    }

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

517 518 519 520
    // if (!passive) {
    //   await this.bridge.WXLogout()
    // }

521
    await this.padchatManager.logout()
ruiruibupt's avatar
init  
ruiruibupt 已提交
522 523 524 525 526 527 528 529 530 531 532 533 534 535
  }

  /**
   *
   * 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 已提交
536
      const payload = await this.contactPayload(contactId)
ruiruibupt's avatar
ruiruibupt 已提交
537
      return payload.alias || ''
ruiruibupt's avatar
init  
ruiruibupt 已提交
538
    }
ruiruibupt's avatar
ruiruibupt 已提交
539

540
    if (!this.padchatManager) {
541 542 543
      throw new Error('no bridge')
    }

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

ruiruibupt's avatar
init  
ruiruibupt 已提交
546 547 548
    return
  }

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

552
    if (!this.padchatManager) {
553 554 555
      throw new Error('no bridge')
    }

556
    const contactIdList = this.padchatManager.getContactIdList()
ruiruibupt's avatar
ruiruibupt 已提交
557 558 559 560

    return contactIdList
  }

561 562
  public async contactAvatar(contactId: string)                : Promise<FileBox>
  public async contactAvatar(contactId: string, file: FileBox) : Promise<void>
ruiruibupt's avatar
init  
ruiruibupt 已提交
563

564
  public async contactAvatar(contactId: string, file?: FileBox): Promise<void | FileBox> {
565 566 567 568
    log.verbose('PuppetPadchat', 'contactAvatar(%s%s)',
                                  contactId,
                                  file ? (', ' + file.name) : '',
                )
569 570 571 572 573 574 575 576

    /**
     * 1. set avatar for user self
     */
    if (file) {
      if (contactId !== this.selfId()) {
        throw new Error('can not set avatar for others')
      }
577
      if (!this.padchatManager) {
578 579
        throw new Error('no bridge')
      }
580
      await this.padchatManager.WXSetHeadImage(await file.toBase64())
581 582 583 584 585 586
      return
    }

    /**
     * 2. get avatar
     */
ruiruibupt's avatar
ruiruibupt 已提交
587 588 589 590 591 592
    const payload = await this.contactPayload(contactId)

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

593 594 595 596
    const fileBox = FileBox.fromUrl(
      payload.avatar,
      `wechaty-contact-avatar-${payload.name}.jpg`,
    )
597 598 599
    return fileBox
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
600
  public async contactQrcode(contactId: string): Promise<string> {
601 602 603
    if (contactId !== this.selfId()) {
      throw new Error('can not set avatar for others')
    }
604
    if (!this.padchatManager) {
605 606
      throw new Error('no bridge')
    }
607
    const base64 = await this.padchatManager.WXGetUserQRCode(contactId, 0)
608
    const qrcode = await fileBoxToQrcode(base64)
609
    return qrcode
ruiruibupt's avatar
init  
ruiruibupt 已提交
610 611
  }

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

615
    if (!this.padchatManager) {
616 617
      throw new Error('no bridge')
    }
618
    const rawPayload = await this.padchatManager.contactRawPayload(contactId)
ruiruibupt's avatar
init  
ruiruibupt 已提交
619 620 621
    return rawPayload
  }

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

625
    const payload: ContactPayload = contactRawPayloadParser(rawPayload)
ruiruibupt's avatar
init  
ruiruibupt 已提交
626 627 628 629 630 631 632 633
    return payload
  }

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
635 636
  public async messageFile(messageId: string): Promise<FileBox> {
    log.warn('PuppetPadchat', 'messageFile(%s) not implemented yet', messageId)
637

ruiruibupt's avatar
ruiruibupt 已提交
638 639
    // const rawPayload = await this.messageRawPayload(id)

ruiruibupt's avatar
ruiruibupt 已提交
640 641
    // TODO

642
    if (!this.padchatManager) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
      throw new Error('no bridge')
    }

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

    const rawText = JSON.stringify(rawPayload)

    let result

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

      case MessageType.Audio:
658
        result = await this.padchatManager.WXGetMsgVoice(rawText)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
659 660 661 662
        console.log(result)
        return FileBox.fromBase64(result.data.image, 'test.slk')

      case MessageType.Emoticon:
663
        result = await this.padchatManager.WXGetMsgImage(rawText)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
664 665 666 667
        console.log(result)
        return FileBox.fromBase64(result.data.image, 'test.gif')

      case MessageType.Image:
668
        result = await this.padchatManager.WXGetMsgImage(rawText)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
669 670 671 672
        console.log(result)
        return FileBox.fromBase64(result.data.image, 'test.jpg')

      case MessageType.Video:
673
        result = await this.padchatManager.WXGetMsgVideo(rawText)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
674 675 676 677 678 679 680
        console.log(result)
        return FileBox.fromBase64(result.data.image, 'test.mp4')

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

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

684
    const file = FileBox.fromBase64(
ruiruibupt's avatar
ruiruibupt 已提交
685 686 687 688 689 690 691
      base64,
      filename,
    )

    return file
  }

692
  public async messageRawPayload(id: string): Promise<PadchatMessagePayload> {
693 694 695 696 697
    // throw Error('should not call messageRawPayload: ' + id)

    /**
     * Issue #1249
     */
ruiruibupt's avatar
ruiruibupt 已提交
698 699 700 701 702

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

704
    const rawPayload = this.cachePadchatMessagePayload.get(id)
705 706 707 708 709 710

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

    return rawPayload
ruiruibupt's avatar
init  
ruiruibupt 已提交
711 712
  }

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

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
718
    log.silly('PuppetPadchat', 'messagePayload(%s)', JSON.stringify(payload))
ruiruibupt's avatar
init  
ruiruibupt 已提交
719 720 721 722 723 724 725
    return payload
  }

  public async messageSendText(
    receiver : Receiver,
    text     : string,
  ): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
726
    log.verbose('PuppetPadchat', 'messageSend(%s, %s)', JSON.stringify(receiver), text)
727 728 729 730

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

ruiruibupt's avatar
ruiruibupt 已提交
731
    if (!id) {
732
      throw Error('no id')
ruiruibupt's avatar
ruiruibupt 已提交
733
    }
734
    if (!this.padchatManager) {
735 736
      throw new Error('no bridge')
    }
737
    await this.padchatManager.WXSendMsg(id, text)
ruiruibupt's avatar
init  
ruiruibupt 已提交
738 739 740 741 742 743
  }

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

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

ruiruibupt's avatar
ruiruibupt 已提交
749 750 751 752
    if (!id) {
      throw new Error('no id!')
    }

753
    if (!this.padchatManager) {
754 755 756
      throw new Error('no bridge')
    }

757 758 759 760
    const type = file.mimeType || path.extname(file.name)
    switch (type) {
      case '.slk':
        // 发送语音消息(微信silk格式语音)
761
        await this.padchatManager.WXSendVoice(
762 763 764 765 766 767 768
          id,
          await file.toBase64(),
          60,
        )
        break

      default:
769
        await this.padchatManager.WXSendImage(
770 771 772 773 774
          id,
          await file.toBase64(),
        )
        break
    }
ruiruibupt's avatar
init  
ruiruibupt 已提交
775 776
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
777 778 779 780 781 782
  public async messageSendContact(
    receiver  : Receiver,
    contactId : string,
  ): Promise<void> {
    log.verbose('PuppetPadchat', 'messageSend("%s", %s)', JSON.stringify(receiver), contactId)

783
    if (!this.padchatManager) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
784 785 786
      throw new Error('no bridge')
    }

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
790 791 792 793 794 795
    if (!id) {
      throw Error('no id')
    }

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

ruiruibupt's avatar
init  
ruiruibupt 已提交
799 800 801 802 803
  public async messageForward(
    receiver  : Receiver,
    messageId : string,
  ): Promise<void> {
    log.verbose('PuppetPadchat', 'messageForward(%s, %s)',
804
                              JSON.stringify(receiver),
ruiruibupt's avatar
init  
ruiruibupt 已提交
805 806
                              messageId,
              )
807
    const payload = await this.messagePayload(messageId)
ruiruibupt's avatar
ruiruibupt 已提交
808

809 810 811 812
    if (payload.type === MessageType.Text) {
      if (!payload.text) {
        throw new Error('no text')
      }
ruiruibupt's avatar
ruiruibupt 已提交
813 814
      await this.messageSendText(
        receiver,
815
        payload.text,
ruiruibupt's avatar
ruiruibupt 已提交
816 817 818 819
      )
    } else {
      await this.messageSendFile(
        receiver,
820
        await this.messageFile(messageId),
ruiruibupt's avatar
ruiruibupt 已提交
821 822
      )
    }
ruiruibupt's avatar
init  
ruiruibupt 已提交
823 824 825 826 827 828 829
  }

  /**
   *
   * Room
   *
   */
830 831 832 833 834
  public async roomMemberRawPayload(
    roomId    : string,
    contactId : string,
  ): Promise<PadchatRoomMemberPayload> {
    log.silly('PuppetPadchat', 'roomMemberRawPayload(%s)', roomId)
ruiruibupt's avatar
ruiruibupt 已提交
835

836
    if (!this.padchatManager) {
837 838 839
      throw new Error('no bridge')
    }

840
    const rawPayload = await this.padchatManager.roomMemberRawPayload(roomId, contactId)
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
    return rawPayload
  }

  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
  }

  public async roomRawPayload(roomId: string): Promise<PadchatRoomPayload> {
    log.verbose('PuppetPadchat', 'roomRawPayload(%s)', roomId)

861
    if (!this.padchatManager) {
862 863 864
      throw new Error('no bridge')
    }

865
    const rawPayload = await this.padchatManager.roomRawPayload(roomId)
ruiruibupt's avatar
init  
ruiruibupt 已提交
866 867 868
    return rawPayload
  }

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

872 873
    // const memberIdList = await this.bridge.getRoomMemberIdList()
    //  WXGetChatRoomMember(rawPayload.user_name)
874

875
    const payload: RoomPayload = roomRawPayloadParser(rawPayload)
ruiruibupt's avatar
init  
ruiruibupt 已提交
876 877 878 879

    return payload
  }

880 881 882
  public async roomMemberList(roomId: string): Promise<string[]> {
    log.verbose('PuppetPadchat', 'roomMemberList(%s)', roomId)

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

887
    const memberIdList = await this.padchatManager.getRoomMemberIdList(roomId)
888 889 890 891 892
    log.silly('PuppetPadchat', 'roomMemberList()=%d', memberIdList.length)

    return memberIdList
  }

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

896
    if (!this.padchatManager) {
897 898 899
      throw new Error('no bridge')
    }

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

ruiruibupt's avatar
ruiruibupt 已提交
903
    return roomIdList
ruiruibupt's avatar
init  
ruiruibupt 已提交
904 905 906 907 908 909 910
  }

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

912
    if (!this.padchatManager) {
913 914 915
      throw new Error('no bridge')
    }

916
    // Should check whether user is in the room. WXDeleteChatRoomMember won't check if user in the room automatically
917
    await this.padchatManager.WXDeleteChatRoomMember(roomId, contactId)
ruiruibupt's avatar
init  
ruiruibupt 已提交
918 919
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
920
  public async roomQrcode(roomId: string): Promise<string> {
921 922 923 924 925 926 927 928
    log.verbose('PuppetPadchat', 'roomQrCode(%s)', roomId)

    // TODO

    throw new Error('not support')

  }

929 930 931 932 933 934 935 936 937 938 939 940 941
  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 已提交
942 943 944 945 946
  public async roomAdd(
    roomId    : string,
    contactId : string,
  ): Promise<void> {
    log.verbose('PuppetPadchat', 'roomAdd(%s, %s)', roomId, contactId)
947

948
    if (!this.padchatManager) {
949 950 951
      throw new Error('no bridge')
    }

952 953 954 955
    // 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)
956
      await this.padchatManager.WXAddChatRoomMember(roomId, contactId)
957 958 959 960 961
    } 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)
962
      await this.padchatManager.WXInviteChatRoomMember(roomId, contactId)
963
    }
ruiruibupt's avatar
init  
ruiruibupt 已提交
964 965
  }

966 967 968
  public async roomTopic(roomId: string)                : Promise<string>
  public async roomTopic(roomId: string, topic: string) : Promise<void>

ruiruibupt's avatar
init  
ruiruibupt 已提交
969 970 971 972 973 974 975
  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 已提交
976
      const payload = await this.roomPayload(roomId)
ruiruibupt's avatar
ruiruibupt 已提交
977
      return payload.topic
ruiruibupt's avatar
init  
ruiruibupt 已提交
978
    }
ruiruibupt's avatar
ruiruibupt 已提交
979

980
    if (!this.padchatManager) {
981 982 983
      throw new Error('no bridge')
    }

984
    await this.padchatManager.WXSetChatroomName(roomId, topic)
ruiruibupt's avatar
ruiruibupt 已提交
985

ruiruibupt's avatar
init  
ruiruibupt 已提交
986 987 988 989 990 991 992 993 994
    return
  }

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

995
    if (!this.padchatManager) {
996 997 998
      throw new Error('no bridge')
    }

999
    const roomId = await this.padchatManager.WXCreateChatRoom(contactIdList)
1000

Huan (李卓桓)'s avatar
lint  
Huan (李卓桓) 已提交
1001
    await Misc.retry(async (retry, attempt) => {
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
      log.verbose('PuppetPadchat', 'roomCreate() roomId=%s retry attempt=%d', roomId, attempt)

      try {
        const tryRoomPayload = await this.roomPayload(roomId)
        if (tryRoomPayload) {
          return tryRoomPayload
        } else {
          return retry(new Error('room create payload not ready'))
        }
      } catch (e) {
        return retry(e)
      }
    })

1016
    return roomId
ruiruibupt's avatar
init  
ruiruibupt 已提交
1017 1018 1019 1020
  }

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

1022
    if (!this.padchatManager) {
1023 1024 1025
      throw new Error('no bridge')
    }

1026
    await this.padchatManager.WXQuitChatRoom(roomId)
ruiruibupt's avatar
init  
ruiruibupt 已提交
1027 1028
  }

1029 1030 1031 1032 1033
  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 : '')
1034

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

1039
    if (text) {
1040
      await this.padchatManager.WXSetChatroomAnnouncement(roomId, text)
1041
    } else {
1042
      return await this.padchatManager.WXGetChatroomAnnouncement(roomId)
1043 1044 1045
    }
  }

ruiruibupt's avatar
init  
ruiruibupt 已提交
1046 1047
  /**
   *
1048
   * Friendship
ruiruibupt's avatar
init  
ruiruibupt 已提交
1049 1050
   *
   */
1051
  public async friendshipVerify(
ruiruibupt's avatar
init  
ruiruibupt 已提交
1052 1053 1054
    contactId : string,
    hello     : string,
  ): Promise<void> {
1055
    log.verbose('PuppetPadchat', 'friendshipVerify(%s, %s)', contactId, hello)
ruiruibupt's avatar
ruiruibupt 已提交
1056

1057
    if (!this.padchatManager) {
E
Egg 已提交
1058 1059
      throw new Error('no bridge')
    }
ruiruibupt's avatar
ruiruibupt 已提交
1060

1061
    const rawSearchPayload: WXSearchContactType = await this.padchatManager.WXSearchContact(contactId)
1062

E
Egg 已提交
1063 1064 1065
    /**
     * If the contact is not stranger, than ussing WXSearchContact can get user_name
     */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1066
    if (rawSearchPayload.user_name !== '' && !isStrangerV1(rawSearchPayload.user_name) && !isStrangerV2(rawSearchPayload.user_name)) {
E
Egg 已提交
1067 1068 1069
      log.warn('PuppetPadchat', 'friendRequestSend %s has been friend with bot, no need to send friend request!', contactId)
      return
    }
ruiruibupt's avatar
ruiruibupt 已提交
1070

E
Egg 已提交
1071 1072
    let strangerV1
    let strangerV2
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1073
    if (isStrangerV1(rawSearchPayload.stranger)) {
E
Egg 已提交
1074 1075
      strangerV1 = rawSearchPayload.stranger
      strangerV2 = rawSearchPayload.user_name
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1076
    } else if (isStrangerV2(rawSearchPayload.stranger)) {
E
Egg 已提交
1077 1078 1079 1080
      strangerV2 = rawSearchPayload.stranger
      strangerV1 = rawSearchPayload.user_name
    } else {
      throw new Error('stranger neither v1 nor v2!')
1081 1082
    }

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

1085
    await this.padchatManager.WXAddUser(
E
Egg 已提交
1086 1087 1088
      strangerV1 || '',
      strangerV2 || '',
      WXSearchContactTypeStatus.WXID, // default
ruiruibupt's avatar
ruiruibupt 已提交
1089 1090
      hello,
    )
ruiruibupt's avatar
init  
ruiruibupt 已提交
1091 1092
  }

1093 1094
  public async friendshipAccept(
    friendshipId : string,
ruiruibupt's avatar
init  
ruiruibupt 已提交
1095
  ): Promise<void> {
1096
    log.verbose('PuppetPadchat', 'friendshipAccept(%s)', friendshipId)
ruiruibupt's avatar
ruiruibupt 已提交
1097

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

1100
    console.log('friendshipAccept: ', payload)
1101

1102 1103 1104
    if (!payload.ticket) {
      throw new Error('no ticket')
    }
1105 1106 1107
    if (!payload.stranger) {
      throw new Error('no stranger')
    }
ruiruibupt's avatar
ruiruibupt 已提交
1108

1109
    if (!this.padchatManager) {
1110 1111 1112
      throw new Error('no bridge')
    }

1113
    await this.padchatManager.WXAcceptUser(
1114
      payload.stranger,
1115 1116
      payload.ticket,
    )
ruiruibupt's avatar
init  
ruiruibupt 已提交
1117 1118
  }

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

1122
    const payload: FriendshipPayload = await friendshipRawPayloadParser(rawPayload)
1123
    return payload
ruiruibupt's avatar
ruiruibupt 已提交
1124 1125
  }

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

1129
    const rawPayload = this.cachePadchatFriendshipPayload.get(friendshipId)
1130
    if (!rawPayload) {
1131
      throw new Error('no rawPayload for id ' + friendshipId)
1132
    }
ruiruibupt's avatar
ruiruibupt 已提交
1133

1134
    return rawPayload
ruiruibupt's avatar
ruiruibupt 已提交
1135 1136
  }

ruiruibupt's avatar
init  
ruiruibupt 已提交
1137 1138 1139
}

export default PuppetPadchat