padchat-rpc.ts 51.7 KB
Newer Older
1 2
import { EventEmitter } from 'events'

3 4 5
// import cuid        from 'cuid'
import WebSocket   from 'ws'

6 7 8 9 10
import Peer, {
  parse,
}           from 'json-rpc-peer'

// , {
11
  // JsonRpcPayload,
12
  // JsonRpcPayloadRequest,
13
  // JsonRpcPayloadNotification,
14
  // JsonRpcPayloadResponse,
15 16
  // JsonRpcPayloadError,
  // JsonRpcParamsSchemaByName,
17 18 19
  // JsonRpcParamsSchemaByPositional,
  // parse,
// }                                   from 'json-rpc-peer'
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

import {
  // PadchatContinue,
  // PadchatMsgType,
  // PadchatStatus,

  PadchatPayload,
  PadchatPayloadType,

  // PadchatContactMsgType,
  PadchatContactPayload,

  PadchatMessagePayload,

  PadchatRoomMemberPayload,
35
  PadchatRoomMemberListPayload,
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
  PadchatRoomPayload,
}                             from './padchat-schemas'

import {
  // AutoDataType,
  PadchatRpcRequest,
  InitType,
  WXGenerateWxDatType,
  WXGetQRCodeType,
  WXInitializeType,
  WXCheckQRCodePayload,
  WXHeartBeatType,
  WXGetLoginTokenType,
  WXAutoLoginType,
  WXLoginRequestType,
  WXSendMsgType,
  WXLoadWxDatType,
  WXQRCodeLoginType,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
54
  // WXCheckQRCodeStatus,
55 56
  StandardType,
  WXAddChatRoomMemberType,
ruiruibupt's avatar
ruiruibupt 已提交
57
  WXLogoutType,
58 59 60 61 62 63 64 65
}                             from './padchat-rpc.type'

import {
  PadchatPureFunctionHelper as pfHelper,
}                                           from './pure-function-helper'

import { log }          from '../config'

66 67
export class PadchatRpc extends EventEmitter {
  private socket?          : WebSocket
68
  private readonly jsonRpc : any // Peer
69

70 71 72
  constructor(
    protected endpoint : string,
    protected token    : string,
73
  ) {
74 75
    super() // for EventEmitter
    log.verbose('PadchatRpc', 'constructor(%s, %s)', endpoint, token)
76

77
    this.jsonRpc = new Peer()
78 79 80 81 82
  }

  public async start(): Promise<void> {
    log.verbose('PadchatRpc', 'start()')

83
    await this.initWebSocket()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
84 85
    await this.initJsonRpc()

86 87 88 89
    await this.init()
    await this.WXInitialize()
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
90 91
  protected async initJsonRpc(): Promise<void> {
    log.verbose('PadchatRpc', 'initJsonRpc()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
92

93 94 95 96
    if (!this.socket) {
      throw new Error('socket had not been opened yet!')
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
97
    this.jsonRpc.on('data', (buffer: string | Buffer) => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
98
      // log.silly('PadchatRpc', 'initJsonRpc() jsonRpc.on(data)')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
99

100 101 102 103
      if (!this.socket) {
        throw new Error('no web socket')
      }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
104
      const text = String(buffer)
105
      const payload = parse(text) // as JsonRpcPayloadRequest
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
106

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
107
      // log.silly('PadchatRpc', 'initJsonRpc() jsonRpc.on(data) buffer="%s"', text)
108

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
109 110 111 112 113 114 115
      /**
       * A Gateway at here:
       *
       *  1. Convert Payload format from JsonRpc to Padchat, then
       *  2. Send payload to padchat server
       *
       */
116 117
      // const encodedParam = (payload.params as JsonRpcParamsSchemaByPositional).map(encodeURIComponent)
      const encodedParam = payload.params.map(encodeURIComponent)
118 119 120 121 122 123 124 125

      const message: PadchatRpcRequest = {
        userId:   this.token,
        msgId:    payload.id as string,
        apiName:  payload.method,
        param:    encodedParam,
      }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
126
      // log.silly('PadchatRpc', 'initJsonRpc() jsonRpc.on(data) converted to padchat payload="%s"', JSON.stringify(message))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
127

128 129 130 131 132
      this.socket.send(JSON.stringify(message))
    })
  }

  protected async initWebSocket(): Promise<void> {
133 134
    log.verbose('PadchatRpc', 'initWebSocket()')

135
    if (this.socket) {
136
      throw new Error('socket had already been opened!')
137 138 139 140 141 142 143 144 145 146
    }

    const ws = new WebSocket(
      this.endpoint,
      { perMessageDeflate: true },
    )

    this.socket = ws

    ws.on('message', (data: string) => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
147
      // log.silly('PadchatRpc', 'initWebSocket() ws.on(message)')
148 149
      try {
        const payload: PadchatPayload = JSON.parse(data)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
150
        this.onSocket(payload)
151
      } catch (e) {
152
        log.warn('PadchatRpc', 'startJsonRpc() ws.on(message) exception: %s', e)
153 154
        this.emit('error', e)
      }
155 156 157 158 159 160 161 162
    })

    ws.on('error', err => this.emit('error', err))

    // TODO: add reconnect logic here when disconnected, or throw Error

    await new Promise((resolve, reject) => {
      ws.once('open', resolve)
163

164 165 166 167 168 169 170 171 172
      ws.once('error', reject)
      ws.once('close', reject)
    })
  }

  public stop(): void {
    log.verbose('PadchatRpc', 'stop()')

    if (!this.socket) {
173
      throw new Error('socket not exist')
174 175
    }

176 177 178
    this.jsonRpc.removeAllListeners()
    this.jsonRpc.end()

179 180 181 182 183 184
    this.socket.removeAllListeners()
    this.socket.close()

    this.socket = undefined
  }

185
  private async rpcCall(
186 187 188
    apiName   : string,
    ...params : string[]
  ): Promise<any> {
189
    log.silly('PadchatRpc', 'rpcCall(%s, %s)', apiName, JSON.stringify(params).substr(0, 500))
190
    return await this.jsonRpc.request(apiName, params)
191
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
192 193

  protected onSocket(payload: PadchatPayload) {
194
    // log.silly('PadchatRpc', 'onSocket(payload.length=%d)',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
195 196
    //                           JSON.stringify(payload).length,
    //             )
197

198 199
    // XXX
    console.log('server payload:', payload)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
200

201
    if (payload.type === PadchatPayloadType.Logout) {
202 203 204
      // {"type":-1,"msg":"掉线了"}
      log.verbose('PadchatRpc', 'onSocket(payload.type=%s) logout, payload=%s(%s)',
                                PadchatPayloadType[payload.type],
205 206 207
                                payload.type,
                                JSON.stringify(payload),
                  )
208
      this.emit('padchat-logout', payload.msg)
209 210 211
      return
    }

212
    if (!payload.msgId && !payload.data) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
213 214 215
      /**
       * Discard message that have neither msgId(Padchat API Call) nor data(Tencent Message)
       */
216
      log.silly('PadchatRpc', 'onSocket() discard payload without `msgId` and `data` for: %s', JSON.stringify(payload))
217 218 219
      return
    }

220
    if (payload.msgId) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
221 222 223 224 225 226 227 228 229 230
      // 1. Padchat Payload
      //
      // padchatPayload:
      // {
      //     "apiName": "WXHeartBeat",
      //     "data": "%7B%22status%22%3A0%2C%22message%22%3A%22ok%22%7D",
      //     "msgId": "abc231923912983",
      //     "userId": "test"
      // }
      this.onSocketPadchat(payload)
231
    } else {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
232 233 234 235 236 237 238 239 240 241
      // 2. Tencent Payload
      //
      // messagePayload:
      // {
      //   "apiName": "",
      //   "data": "XXXX",
      //   "msgId": "",
      //   "userId": "test"
      // }

242 243 244 245
      // https://stackoverflow.com/a/24417399/1123955
      const data = payload.data.replace(/\+/g, '%20')

      const tencentPayloadList: PadchatMessagePayload[] = JSON.parse(decodeURIComponent(data))
246

247 248
      if (!Array.isArray(tencentPayloadList)) {
        throw new Error('not array')
249 250
      }

251
      this.onSocketTencent(tencentPayloadList)
252
    }
253 254
  }

255
  protected onSocketPadchat(padchatPayload: PadchatPayload): void {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
256 257 258 259 260
    // log.verbose('PadchatRpc', 'onSocketPadchat({apiName="%s", msgId="%s", ...})',
    //                                     padchatPayload.apiName,
    //                                     padchatPayload.msgId,
    //             )
    // log.silly('PadchatRpc', 'onSocketPadchat(%s)', JSON.stringify(padchatPayload).substr(0, 500))
261

262 263 264 265 266
    // if (padchatPayload.type === PadchatPayloadType.Logout) {
    //   // this.emit('logout', this.selfId())
    //   console.log('onSocketPadchat: ', JSON.stringify(padchatPayload))
    //   this.emit('logout')
    // }
267

268 269
    let result: any

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
270
    if (padchatPayload.data) {
271 272 273 274
      // https://stackoverflow.com/a/24417399/1123955
      const data = padchatPayload.data.replace(/\+/g, '%20')

      result = JSON.parse(decodeURIComponent(data))
275
    } else {
276
      log.silly('PadchatRpc', 'onServerMessagePadchat() discard empty payload.data for apiName: %s', padchatPayload.apiName)
277
      result = {}
278 279
    }

280 281
    // const jsonRpcResponse: JsonRpcPayloadResponse = {
    const jsonRpcResponse = {
282 283 284 285
      id      : padchatPayload.msgId,
      jsonrpc : '2.0',
      result  : result,
      type    : 'response',
286 287
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
288
    const responseText = JSON.stringify(jsonRpcResponse)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
289
    // log.silly('PadchatRpc', 'onSocketPadchat() converted to JsonRpc payload="%s"', responseText.substr(0, 500))
290

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
291
    this.jsonRpc.write(responseText)
292 293 294 295
  }

  protected onSocketTencent(messagePayloadList: PadchatMessagePayload[]) {
    // console.log('tencent messagePayloadList:', messagePayloadList)
296

297 298 299 300 301 302 303 304 305 306 307 308
    for (const messagePayload of messagePayloadList) {
      if (!messagePayload.msg_id) {
        // {"continue":0,"msg_type":32768,"status":1,"uin":1928023446}
        log.silly('PadchatRpc', 'onSocketTencent() discard empty message msg_id payoad: %s',
                                JSON.stringify(messagePayload),
                  )
        continue
      }
      // log.silly('PadchatRpc', 'onSocketTencent() messagePayload: %s', JSON.stringify(messagePayload))

      this.emit('message', messagePayload)
    }
309 310 311 312 313
  }

  /**
   * Init with WebSocket Server
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
314
  protected async init(): Promise<InitType> {
315
    const result: InitType = await this.rpcCall('init')
316 317 318 319 320 321 322 323 324 325
    log.silly('PadchatRpc', 'init result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('cannot connect to WebSocket init')
    }
    return result
  }

  /**
   * Get WX block memory
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
326
  protected async WXInitialize(): Promise<WXInitializeType> {
327 328
    log.verbose('PadchatRpc', 'WXInitialize()')

329
    const result = await this.rpcCall('WXInitialize')
330
    log.silly('PadchatRpc', 'WXInitialize result: %s', JSON.stringify(result))
331

332 333 334 335 336 337
    if (!result || result.status !== 0) {
      throw Error('cannot connect to WebSocket WXInitialize')
    }
    return result
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
338
  protected async WXGetQRCode(): Promise<WXGetQRCodeType> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
339 340 341 342
    const result = await this.rpcCall('WXGetQRCode')
    // if (!result || !(result.qr_code)) {
    //   result = await this.WXGetQRCodeTwice()
    // }
343 344 345
    return result
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
346 347 348 349 350 351 352 353
  // private async WXGetQRCodeTwice(): Promise<WXGetQRCodeType> {
  //   await this.WXInitialize()
  //   const resultTwice = await this.rpcCall('WXGetQRCode')
  //   if (!resultTwice || !(resultTwice.qr_code)) {
  //     throw Error('WXGetQRCodeTwice error! canot get result from websocket server when calling WXGetQRCode after WXInitialize')
  //   }
  //   return resultTwice
  // }
354 355 356

  public async WXCheckQRCode(): Promise<WXCheckQRCodePayload> {
    // this.checkQrcode()
357
    const result = await this.rpcCall('WXCheckQRCode')
358 359 360 361 362 363 364
    log.silly('PadchatRpc', 'WXCheckQRCode result: %s', JSON.stringify(result))
    if (!result) {
      throw Error('cannot connect to WebSocket WXCheckQRCode')
    }
    return result
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
365 366
  public async WXHeartBeat(): Promise<WXHeartBeatType> {
    const result = await this.rpcCall('WXHeartBeat')
367 368 369 370 371 372 373 374 375 376 377 378
    log.silly('PadchatRpc', 'WXHeartBeat result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXHeartBeat error! canot get result from websocket server')
    }
    return result
  }

  /**
   * Load all Contact and Room
   * see issue https://github.com/lijiarui/test-ipad-puppet/issues/39
   * @returns {Promise<(PadchatRoomPayload | PadchatContactPayload)[]>}
   */
379 380
  public async WXSyncContact(): Promise<(PadchatRoomPayload | PadchatContactPayload)[]> {
    const result = await this.rpcCall('WXSyncContact')
381 382 383 384 385 386 387 388
    if (!result) {
      throw Error('WXSyncContact error! canot get result from websocket server')
    }
    return result
  }

  /**
   * Generate 62 data
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
389 390 391
   *
   * 1. Call multiple times in the same session, will return the same data
   * 2. Call multiple times between sessions with the same token, will return the same data
392
   */
393 394
  public async WXGenerateWxDat(): Promise<string> {
    const result: WXGenerateWxDatType = await this.rpcCall('WXGenerateWxDat')
395 396 397 398
    log.silly('PadchatRpc', 'WXGenerateWxDat result: %s', JSON.stringify(result))
    if (!result || !(result.data) || result.status !== 0) {
      throw Error('WXGenerateWxDat error! canot get result from websocket server')
    }
399
    // this.autoData.wxData = result.data
400
    return result.data
401 402 403 404 405 406 407
  }

  /**
   * Load 62 data
   * @param {string} wxData     autoData.wxData
   */
  public async WXLoadWxDat(wxData: string): Promise<WXLoadWxDatType> {
408
    const result = await this.rpcCall('WXLoadWxDat', wxData)
409 410 411 412 413 414
    if (!result || result.status !== 0) {
      throw Error('WXLoadWxDat error! canot get result from websocket server')
    }
    return result
  }

415 416
  public async WXGetLoginToken(): Promise<string> {
    const result: WXGetLoginTokenType = await this.rpcCall('WXGetLoginToken')
417 418 419 420
    log.silly('PadchatRpc', 'WXGetLoginToken result: %s', JSON.stringify(result))
    if (!result || !result.token || result.status !== 0) {
      throw Error('WXGetLoginToken error! canot get result from websocket server')
    }
421
    // this.autoData.token = result.token
422
    return result.token
423 424 425 426 427 428 429
  }

  /**
   * Login with token automatically
   * @param {string} token    autoData.token
   * @returns {string} user_name | ''
   */
430 431
  public async WXAutoLogin(token: string): Promise<undefined | WXAutoLoginType> {
    const result = await this.rpcCall('WXAutoLogin', token)
432 433 434 435 436 437 438 439
    log.silly('PadchatRpc', 'WXAutoLogin result: %s, type: %s', JSON.stringify(result), typeof result)
    return result
  }

  /**
   * Login with QRcode
   * @param {string} token    autoData.token
   */
440
  public async WXLoginRequest(token: string): Promise<undefined | WXLoginRequestType> {
441
    // TODO: should show result here
442
    const result = await this.rpcCall('WXLoginRequest', token)
443
    log.silly('PadchatRpc', 'WXLoginRequest result: %s, type: %s', JSON.stringify(result), typeof result)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
444 445 446 447 448 449 450 451
    // if (!result || result.status !== 0) {
    //   await this.WXGetQRCode()
    //   return
    // } else {
    //   // check qrcode status
    //   log.silly('PadchatRpc', 'WXLoginRequest begin to check whether user has clicked confirm login')
    //   this.checkQrcode()
    // }
452 453 454 455 456 457 458 459 460 461
    return result
  }

  /**
   * Send Text Message
   * @param {string} to       user_name
   * @param {string} content  text
   */
  public async WXSendMsg(to: string, content: string, at = ''): Promise<WXSendMsgType> {
    if (to) {
462
      const result = await this.rpcCall('WXSendMsg', to, content, at)
463 464 465 466 467 468 469 470 471 472 473 474 475 476
      if (!result || result.status !== 0) {
        throw Error('WXSendMsg error! canot get result from websocket server')
      }
      return result
    }
    throw Error('PadchatRpc, WXSendMsg error! no to!')
  }

  /**
   * Send Image Message
   * @param {string} to     user_name
   * @param {string} data   image_data
   */
  public WXSendImage(to: string, data: string): void {
477
    this.rpcCall('WXSendImage', to, data)
478 479 480 481 482 483
  }

  /**
   * Get contact by contact id
   * @param {any} id        user_name
   */
484 485
  public async WXGetContact(id: string): Promise<any> {
    const result = await this.rpcCall('WXGetContact', id)
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521

    if (!result) {
      throw Error('PadchatRpc, WXGetContact, cannot get result from websocket server!')
    }

    log.silly('PadchatRpc', 'WXGetContact(%s) result: %s', id, JSON.stringify(result))

    if (!result.user_name) {
      log.warn('PadchatRpc', 'WXGetContact cannot get user_name, id: %s', id)
    }
    return result
  }

  /**
   * Get contact by contact id
   * @param {any} id        user_name
   */
  public async WXGetContactPayload(id: string): Promise<PadchatContactPayload> {
    if (!pfHelper.isContactId(id)) { // /@chatroom$/.test(id)) {
      throw Error(`should use WXGetRoomPayload because get a room id :${id}`)
    }
    const result = await this.WXGetContact(id) as PadchatContactPayload
    return result
  }

  /**
   * Get contact by contact id
   * @param {any} id        user_name
   */
  public async WXGetRoomPayload(id: string): Promise<PadchatRoomPayload> {
    if (!pfHelper.isRoomId(id)) { // (/@chatroom$/.test(id))) {
      throw Error(`should use WXGetContactPayload because get a contact id :${id}`)
    }
    const result = await this.WXGetContact(id)

    if (result.member) {
522 523 524 525
      // https://stackoverflow.com/a/24417399/1123955
      const data = result.member.replace(/\+/g, '%20')

      result.member = JSON.parse(decodeURIComponent(data))
526 527 528 529 530 531
    }

    return result
  }

  /**
532 533
   * Get all member of a room by room id
   * @param {any} roomId        chatroom_id
534
   */
535 536
  public async WXGetChatRoomMember(roomId: string): Promise<PadchatRoomMemberListPayload> {
    const result = await this.rpcCall('WXGetChatRoomMember', roomId)
537 538 539 540
    if (!result) {
      throw Error('PadchatRpc, WXGetChatRoomMember, cannot get result from websocket server!')
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
541 542
    log.silly('PadchatRpc', 'WXGetChatRoomMember() result: %s', JSON.stringify(result).substr(0, 500))
    // console.log(result)
543

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
544
    // 00:40:44 SILL PadchatRpc WXGetChatRoomMember() result: {"chatroom_id":0,"count":0,"member":"null\n","message":"","status":0,"user_name":""}
545
    if (!result.user_name || !result.member) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
      /**
       * { chatroom_id: 0,
       *  count: 0,
       *  member: 'null\n',
       *  message: '',
       *  status: 0,
       *  user_name: '' }
       */
      // console.error(result)
      // throw new Error('WXGetChatRoomMember cannot get user_name or member!')
      log.warn('PadchatRpc', 'WXGetChatRoomMember(%s) cannot get user_name or member!', roomId)
      const emptyResult: PadchatRoomMemberListPayload = {
        chatroom_id : 0,
        count       : 0,
        member      : [],
        message     : '',
        status      : 0,
        user_name   : '',
      }
      return emptyResult
566 567
    }

568 569 570 571
    try {
      // tslint:disable-next-line:max-line-length
      // change '[{"big_head":"http://wx.qlogo.cn/mmhead/ver_1/DpS0ZssJ5s8tEpSr9JuPTRxEUrCK0USrZcR3PjOMfUKDwpnZLxWXlD4Q38bJpcXBtwXWwevsul1lJqwsQzwItQ/0","chatroom_nick_name":"","invited_by":"wxid_7708837087612","nick_name":"李佳芮","small_head":"http://wx.qlogo.cn/mmhead/ver_1/DpS0ZssJ5s8tEpSr9JuPTRxEUrCK0USrZcR3PjOMfUKDwpnZLxWXlD4Q38bJpcXBtwXWwevsul1lJqwsQzwItQ/132","user_name":"qq512436430"},{"big_head":"http://wx.qlogo.cn/mmhead/ver_1/kcBj3gSibfFd2I9vQ8PBFyQ77cpPIfqkFlpTdkFZzBicMT6P567yj9IO6xG68WsibhqdPuG82tjXsveFATSDiaXRjw/0","chatroom_nick_name":"","invited_by":"wxid_7708837087612","nick_name":"梦君君","small_head":"http://wx.qlogo.cn/mmhead/ver_1/kcBj3gSibfFd2I9vQ8PBFyQ77cpPIfqkFlpTdkFZzBicMT6P567yj9IO6xG68WsibhqdPuG82tjXsveFATSDiaXRjw/132","user_name":"mengjunjun001"},{"big_head":"http://wx.qlogo.cn/mmhead/ver_1/3CsKibSktDV05eReoAicV0P8yfmuHSowfXAMvRuU7HEy8wMcQ2eibcaO1ccS95PskZchEWqZibeiap6Gpb9zqJB1WmNc6EdD6nzQiblSx7dC1eGtA/0","chatroom_nick_name":"","invited_by":"wxid_7708837087612","nick_name":"苏轼","small_head":"http://wx.qlogo.cn/mmhead/ver_1/3CsKibSktDV05eReoAicV0P8yfmuHSowfXAMvRuU7HEy8wMcQ2eibcaO1ccS95PskZchEWqZibeiap6Gpb9zqJB1WmNc6EdD6nzQiblSx7dC1eGtA/132","user_name":"wxid_zj2cahpwzgie12"},{"big_head":"http://wx.qlogo.cn/mmhead/ver_1/piaHuicak41b6ibmcEVxoWKnnhgGDG5EbaD0hibwkrRvKeDs3gs7XQrkym3Q5MlUeSKY8vw2FRVVstialggUxf2zic2O8CvaEsicSJcghf41nibA940/0","chatroom_nick_name":"","invited_by":"wxid_zj2cahpwzgie12","nick_name":"王宁","small_head":"http://wx.qlogo.cn/mmhead/ver_1/piaHuicak41b6ibmcEVxoWKnnhgGDG5EbaD0hibwkrRvKeDs3gs7XQrkym3Q5MlUeSKY8vw2FRVVstialggUxf2zic2O8CvaEsicSJcghf41nibA940/132","user_name":"wxid_7708837087612"}]'
      // to Array (PadchatRoomRawMember[])
572 573

      // https://stackoverflow.com/a/24417399/1123955
574
      const data          = result.member && result.member.data && result.member.data.replace(/\+/g, '%20') || null
575 576 577 578
      const tryMemberList = JSON.parse(decodeURIComponent(data)) as PadchatRoomMemberPayload[]

      if (Array.isArray(tryMemberList)) {
        result.member = tryMemberList
579 580 581 582 583
      } else {
        log.warn('PadchatRpc', 'WXGetChatRoomMember(%s) member is not array: %s', roomId, JSON.stringify(result.member))
        // throw Error('faild to parse chatroom member!')
        result.member = []
      }
584

585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
    } catch (e) {
      // 18:27:54 SILL Puppet contactPayload(shanzhifeng644634) cache MISS
      // tslint:disable-next-line:max-line-length
      // 18:27:55 SILL PadchatRpc WXGetChatRoomMember() result: {"chatroom_id":700002836,"count":442,"member":"[{\"big_head\":\"http://wx.qlogo.cn/mmhead/ver_1/VCnC8c3icQpcsCpMeSq1w2MZm6Q3ZNqHINoOUhUic9icB3Tm6BK9hyyB9XiaFxjVNIHF0oO11zZTez0nictu2nRWLH7OaKcRkZQdiaz0UjjYlBeWk/0\",\"chatroom_nick_name\":\"宁杰+野生土蜂蜜\",\"invited_by\":\"\",\"nick_name\":\"宁杰¥野生土蜂蜜\",\"small_head\":\"http://wx.qlogo.cn/mmhead/ver_1/VCnC8c3icQpcsCpMeSq1w2MZm6Q3ZNqHINoOUhUic9icB3Tm6BK9hyyB9XiaFxjVNIHF0oO11zZTez0nictu2nRWLH7OaKcRkZQdiaz0UjjYlBeWk/132\",\"user_name\":\"jack_85802\"},{\"b
      // 18:27:55 ERR Config ###########################
      // 18:27:55 ERR Config unhandledRejection: URIError: URI malformed [object Promise]
      // 18:27:55 ERR Config ###########################
      // 18:27:55 ERR Config process.on(unhandledRejection) promise.catch(URI malformed)
      // Config URIError: URI malformed
      //     at decodeURIComponent (<anonymous>)
      //     at PadchatRpc.<anonymous> (/home/zixia/chatie/wechaty/src/puppet-padchat/padchat-rpc.ts:559:34)
      //     at Generator.next (<anonymous>)
      //     at fulfilled (/home/zixia/chatie/wechaty/src/puppet-padchat/padchat-rpc.ts:4:58)
      //     at process._tickCallback (internal/process/next_tick.js:68:7)
      // (node:22232) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 834)
      console.error(e)
      log.warn('PadchatRpc', 'WXGetChatRoomMember(%s) result.member decode error: %s', roomId, e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
602
      result.member = []
603 604 605 606 607 608
    }
    return result
  }

  /**
   * Login successfully by qrcode
609
   * @param {any} username        user_name
610 611
   * @param {any} password  password
   */
612 613
  public async WXQRCodeLogin(username: string, password: string): Promise<WXQRCodeLoginType> {
    const result = await this.rpcCall('WXQRCodeLogin', username, password)
614

615 616
    if (!result) {
      throw Error(`PadchatRpc, WXQRCodeLogin, unknown error, data: ${JSON.stringify(result)}`)
617 618
    }

619
    if (result.status === 0) {
620
      log.silly('PadchatRpc', 'WXQRCodeLogin, login successfully!')
621 622 623 624
      // this.username = result.user_name
      // this.nickname = result.nick_name
      // this.loginSucceed = true
      return result
625 626
    }

627 628 629
    if (result.status === -3) {
      throw Error('PadchatRpc, WXQRCodeLogin, wrong user_name or password')
    } else if (result.status === -301) {
630
      log.warn('PadchatRpc', 'WXQRCodeLogin, redirect 301')
631 632 633 634 635
      return this.WXQRCodeLogin(username, password)
      // if (!this.username || !this.password) {
      //   throw Error('PadchatRpc, WXQRCodeLogin, redirect 301 and cannot get username or password here, return!')
      // }
      // this.WXQRCodeLogin(this.username, this.password)
636
    }
637
    throw Error('PadchatRpc, WXQRCodeLogin, unknown status: ' + result.status)
638 639
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
640 641 642
  // public async checkQrcode(): Promise<void> {
  //   log.verbose('PadchatRpc', 'checkQrcode')
  //   const result = await this.WXCheckQRCode()
643

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
644 645
  //   if (result && result.status === WXCheckQRCodeStatus.WaitScan) {
  //     log.verbose('PadchatRpc', 'checkQrcode: Please scan the Qrcode!')
646

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
647 648 649
  //     setTimeout(() => {
  //       this.checkQrcode()
  //     }, 1000)
650

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
651 652
  //     return
  //   }
653

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
654 655
  //   if (result && result.status === WXCheckQRCodeStatus.WaitConfirm) {
  //     log.silly('PadchatRpc', 'checkQrcode: Had scan the Qrcode, but not Login!')
656

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
657 658 659
  //     setTimeout(() => {
  //       this.checkQrcode()
  //     }, 1000)
660

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
661 662
  //     return
  //   }
663

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
664 665
  //   if (result && result.status === WXCheckQRCodeStatus.Confirmed) {
  //     log.silly('PadchatRpc', 'checkQrcode: Trying to login... please wait')
666

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
667 668 669
  //     if (!result.user_name || !result.password) {
  //       throw Error('PadchatRpc, checkQrcode, cannot get username or password here, return!')
  //     }
670

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
671 672 673
  //     // this.username = result.user_name
  //     // this.nickname = result.nick_name
  //     // this.password = result.password
674

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
675 676 677
  //     // this.WXQRCodeLogin(this.username, this.password)
  //     return
  //   }
678

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
679 680 681 682
  //   if (result && result.status === WXCheckQRCodeStatus.Timeout) {
  //     log.silly('PadchatRpc', 'checkQrcode: Timeout')
  //     return
  //   }
683

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
684 685 686 687
  //   if (result && result.status === WXCheckQRCodeStatus.Cancel) {
  //     log.silly('PadchatRpc', 'checkQrcode: Cancel by user')
  //     return
  //   }
688

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
689 690 691
  //   log.warn('PadchatRpc', 'checkQrcode: not know the reason, return data: %s', JSON.stringify(result))
  //   return
  // }
692 693

  public async WXSetUserRemark(id: string, remark: string): Promise<StandardType> {
694
    const result = await this.rpcCall('WXSetUserRemark', id, remark)
695 696 697 698 699 700 701 702
    log.silly('PadchatRpc', 'WXSetUserRemark result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSetUserRemark error! canot get result from websocket server')
    }
    return result
  }

  public async WXDeleteChatRoomMember(roomId: string, contactId: string): Promise<StandardType> {
703
    const result = await this.rpcCall('WXDeleteChatRoomMember', roomId, contactId)
704 705 706 707 708 709 710
    log.silly('PadchatRpc', 'WXDeleteChatRoomMember result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXDeleteChatRoomMember error! canot get result from websocket server')
    }
    return result
  }

711 712
  public async WXAddChatRoomMember(roomId: string, contactId: string): Promise<number> {
    const result: WXAddChatRoomMemberType = await this.rpcCall('WXAddChatRoomMember', roomId, contactId)
713 714
    log.silly('PadchatRpc', 'WXAddChatRoomMember result: %s', JSON.stringify(result))

715
    if (!result) {
716 717 718
      throw Error('WXAddChatRoomMember error! canot get result from websocket server')
    }

719 720 721 722 723 724 725 726 727 728 729 730 731
    if (result.status === 0) {
      // see more in WXAddChatRoomMemberType
      if (/OK/i.test(result.message)) {
        return 0
      }
      log.warn('PadchatRpc', 'WXAddChatRoomMember() status = 0 but message is not OK: ' + result.message)
      return -1
    }

    if (result.status === -2028) {
      // result: {"message":"","status":-2028}
      // May be the owner has see not allow other people to join in the room (群聊邀请确认)
      log.warn('PadchatRpc', 'WXAddChatRoomMember failed! maybe owner open the should confirm first to invited others to join in the room.')
732
    }
733 734

    return result.status
735 736 737
  }

  public async WXSetChatroomName(roomId: string, topic: string): Promise<StandardType> {
738
    const result = await this.rpcCall('WXSetChatroomName', roomId, topic)
739 740 741 742 743 744 745 746
    log.silly('PadchatRpc', 'WXSetChatroomName result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSetChatroomName error! canot get result from websocket server')
    }
    return result
  }

  public async WXQuitChatRoom(roomId: string): Promise<StandardType> {
747
    const result = await this.rpcCall('WXQuitChatRoom', roomId)
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
    log.silly('PadchatRpc', 'WXQuitChatRoom result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXQuitChatRoom error! canot get result from websocket server')
    }
    return result
  }

  // friendRequestSend
  // type来源值:
  // 2                 -通过搜索邮箱
  // 3                  -通过微信号搜索
  // 5                  -通过朋友验证消息
  // 7                  -通过朋友验证消息(可回复)
  // 12                -通过QQ好友添加
  // 14                -通过群来源
  // 15                -通过搜索手机号
  // 16                -通过朋友验证消息
  // 17                -通过名片分享
  // 22                -通过摇一摇打招呼方式
  // 25                -通过漂流瓶
  // 30                -通过二维码方式
  public async WXAddUser(strangerV1: string, strangerV2: string, type: string, verify: string): Promise<any> {
    // TODO:
771 772
    // type = '14'
    // verify = 'hello'
773
    const result = await this.rpcCall('WXAddUser', strangerV1, strangerV2, type, verify)
774 775 776 777 778
    log.silly('PadchatRpc', 'WXAddUser result: %s', JSON.stringify(result))
    return result
  }

  public async WXAcceptUser(stranger: string, ticket: string): Promise<any> {
779
    const result = await this.rpcCall('WXAcceptUser', stranger, ticket)
780 781 782 783
    log.silly('PadchatRpc', 'WXAcceptUser result: %s', JSON.stringify(result))
    return result
  }

ruiruibupt's avatar
ruiruibupt 已提交
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
  public async WXLogout(): Promise<WXLogoutType> {
    const result = await this.rpcCall('WXLogout')
    log.silly('PadchatRpc', 'WXLogout result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXLogout error! canot get result from websocket server')
    }
    return result
  }

  // TODO: check any
  public async WXSendMoments(text: string): Promise<any> {
    const result = await this.rpcCall('WXSendMoments', text)
    log.silly('PadchatRpc', 'WXSendMoments result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSendMoments error! canot get result from websocket server')
    }
    return result
  }

  // Sync Chat Message
  public async WXSyncMessage(): Promise<any> {
    const result = await this.rpcCall('WXSyncMessage')
    log.silly('PadchatRpc', 'WXSyncMessage result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSyncMessage error! canot get result from websocket server')
    }
    return result
  }

  // TODO: check any
  // For add new friends by id
  public async WXSearchContact(): Promise<any> {
    const result = await this.rpcCall('WXSearchContact')
    log.silly('PadchatRpc', 'WXSearchContact result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSearchContact error! canot get result from websocket server')
    }
    return result
  }

  // TODO: check any
  // send hello to strange
  public async WXSayHello(stranger: string, text: string): Promise<any> {
    const result = await this.rpcCall('WXSayHello', stranger, text)
    log.silly('PadchatRpc', 'WXSayHello , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSayHello , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO: check any
  // delete friend
  public async WXDeleteUser(id: string): Promise<any> {
    const result = await this.rpcCall('WXDeleteUser', id)
    log.silly('PadchatRpc', 'WXDeleteUser , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXDeleteUser , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO: check any
  public async WXCreateChatRoom(userList: string[]): Promise<any> {
    const result = await this.rpcCall('WXCreateChatRoom', JSON.stringify(userList))
    log.silly('PadchatRpc', 'WXCreateChatRoom , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXCreateChatRoom , stranger,error! canot get result from websocket server')
    }
    return result
  }

ruiruibupt's avatar
ruiruibupt 已提交
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
  // TODO: check any
  // TODO: don't know the difference between WXAddChatRoomMember
  public async WXInviteChatRoomMember(roomId: string, contactId: string): Promise<any> {
    const result = await this.rpcCall('WXInviteChatRoomMember', roomId, contactId)
    log.silly('PadchatRpc', 'WXInviteChatRoomMember , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXInviteChatRoomMember , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO: check any
  // TODO: receive red-packet automatically
  // red_packet: see this from the recived message
  public async WXReceiveRedPacket(redPacket: string): Promise<any> {
    const result = await this.rpcCall('WXReceiveRedPacket', redPacket)
    log.silly('PadchatRpc', 'WXReceiveRedPacket , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXReceiveRedPacket , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO: check any
  // TODO: 查看红包
  public async WXQueryRedPacket(redPacket: string): Promise<any> {
    const result = await this.rpcCall('WXQueryRedPacket', redPacket)
    log.silly('PadchatRpc', 'WXQueryRedPacket , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXQueryRedPacket , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO: check any
  // TODO: 打开红包
  public async WXOpenRedPacket(redPacket: string): Promise<any> {
    const result = await this.rpcCall('WXOpenRedPacket', redPacket)
    log.silly('PadchatRpc', 'WXOpenRedPacket , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXOpenRedPacket , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO: check any
  // set user avatar, param image is the same as send [WXSendImage]
  public async WXSetHeadImage(image: string): Promise<any> {
    const result = await this.rpcCall('WXOpenRedPacket', image)
    log.silly('PadchatRpc', 'WXOpenRedPacket , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXOpenRedPacket , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO: check any
  // nick_name	昵称
  // signature	签名
  // sex			性别,1男,2女
  // country		国家,CN
  // provincia	地区,省,Zhejiang
  // city			城市,Hangzhou
  public async WXSetUserInfo(nickeName: string, signature: string, sex: string, country: string, provincia: string, city: string): Promise<any> {
    const result = await this.rpcCall('WXSetUserInfo', nickeName, signature, sex, country, provincia, city)
    log.silly('PadchatRpc', 'WXSetUserInfo , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSetUserInfo , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO: check any
  // 查看附近的人
  // longitude	浮点数,经度
  // latitude		浮点数,维度
  public async WXGetPeopleNearby(longitude: string, latitude: string): Promise<any> {
    const result = await this.rpcCall('WXGetPeopleNearby', longitude, latitude)
    log.silly('PadchatRpc', 'WXGetPeopleNearby , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXGetPeopleNearby , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO: check any
  // 获取公众号信息 id: gh_xxxx
  public async WXGetSubscriptionInfo(id: string): Promise<any> {
    const result = await this.rpcCall('WXGetSubscriptionInfo', id)
    log.silly('PadchatRpc', 'WXGetSubscriptionInfo , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXGetSubscriptionInfo , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO: check any
  // 执行公众号菜单操作
  // id			      公众号用户名
  // OrderId			菜单id,通过WXGetSubscriptionInfo获取, 原来叫id
  // OrderKey			菜单key,通过WXGetSubscriptionInfo获取, 原来叫key
  public async WXSubscriptionCommand(id: string, orderId: string, orderKey: string): Promise<any> {
    const result = await this.rpcCall('WXSubscriptionCommand', id, orderId, orderKey)
    log.silly('PadchatRpc', 'WXSubscriptionCommand , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSubscriptionCommand , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 公众号中获取url访问token, 给下面的函数使用[WXRequestUrl]
  // user			公众号用户名
  // url			访问的链接
  public async WXGetRequestToken(id: string, url: string): Promise<any> {
    const result = await this.rpcCall('WXGetRequestToken', id, url)
    log.silly('PadchatRpc', 'WXGetRequestToken , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXGetRequestToken , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 公众号中访问url
  // url			url地址
  // key			token中的key
  // uin		  token中的uin
  public async WXRequestUrl(url: string, key: string, uin: string): Promise<any> {
    const result = await this.rpcCall('WXRequestUrl', url, key, uin)
    log.silly('PadchatRpc', 'WXRequestUrl , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXRequestUrl , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 设置微信ID
  public async WXSetWeChatID(id: string): Promise<any> {
    const result = await this.rpcCall('WXSetWeChatID', id)
    log.silly('PadchatRpc', 'WXSetWeChatID , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSetWeChatID , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 查看转账信息
  // transfer		转账消息
  public async WXTransferQuery(transfer: string): Promise<any> {
    const result = await this.rpcCall('WXTransferQuery', transfer)
    log.silly('PadchatRpc', 'WXTransferQuery , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXTransferQuery , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 接受转账
  // transfer		转账消息
  public async WXTransferOperation(transfer: string): Promise<any> {
    const result = await this.rpcCall('WXTransferOperation', transfer)
    log.silly('PadchatRpc', 'WXTransferOperation , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXTransferOperation , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 获取消息图片 (应该是查看原图)
  // msg			收到的整个图片消息
  public async WXGetMsgImage(msg: string): Promise<any> {
    const result = await this.rpcCall('WXGetMsgImage', msg)
    log.silly('PadchatRpc', 'WXGetMsgImage , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXGetMsgImage , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 获取消息视频 (应该是查看视频)
  // msg			收到的整个视频消息
  public async WXGetMsgVideo(msg: string): Promise<any> {
    const result = await this.rpcCall('WXGetMsgVideo', msg)
    log.silly('PadchatRpc', 'WXGetMsgVideo , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXGetMsgVideo , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 获取消息语音(语音消息大于20秒时通过该接口获取)
  // msg			收到的整个视频消息
  public async WXGetMsgVoice(msg: string): Promise<any> {
    const result = await this.rpcCall('WXGetMsgVoice', msg)
    log.silly('PadchatRpc', 'WXGetMsgVoice , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXGetMsgVoice , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 搜索公众号
  // id			公众号用户名: gh_xxx
  public async WXWebSearch(id: string): Promise<any> {
    const result = await this.rpcCall('WXWebSearch', id)
    log.silly('PadchatRpc', 'WXWebSearch , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXWebSearch , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 分享名片
  // user			对方用户名
  // id			    名片的微信id
  // caption		名片的标题
  public async WXShareCard(user: string, id: string, caption: string): Promise<any> {
    const result = await this.rpcCall('WXShareCard', user, id, caption)
    log.silly('PadchatRpc', 'WXShareCard , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXShareCard , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 重置同步信息
  public async WXSyncReset(): Promise<any> {
    const result = await this.rpcCall('WXSyncReset')
    log.silly('PadchatRpc', 'WXSyncReset , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSyncReset , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 扫描二维码获取信息
  // path			本地二维码图片全路径
  public async WXQRCodeDecode(path: string): Promise<any> {
    const result = await this.rpcCall('WXQRCodeDecode', path)
    log.silly('PadchatRpc', 'WXQRCodeDecode , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXQRCodeDecode , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 朋友圈上传图片获取url
  // image			图片数据, 和发送消息的image 是一样的base64 串
  public async WXSnsUpload(image: string): Promise<any> {
    const result = await this.rpcCall('WXSnsUpload', image)
    log.silly('PadchatRpc', 'WXSnsUpload , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSnsUpload , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 获取朋友圈消息详情(例如评论)
  // id			朋友圈消息id
  public async WXSnsObjectDetail(id: string): Promise<any> {
    const result = await this.rpcCall('WXSnsObjectDetail', id)
    log.silly('PadchatRpc', 'WXSnsObjectDetail , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSnsObjectDetail , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 朋友圈操作(删除朋友圈,删除评论,取消赞)
  // id			       朋友圈消息id
  // type			     操作类型,1为删除朋友圈,4为删除评论,5为取消赞
  // comment		   当type为4时,对应删除评论的id,通过WXSnsObjectDetail接口获取。当type为其他值时,comment不可用,置为0。
  // commentType	 评论类型,当删除评论时可用,2或者3.(规律未知)
  public async WXSnsObjectOp(id: string, type: string, comment: string, commentType: string): Promise<any> {
    const result = await this.rpcCall('WXSnsObjectOp', id, type, comment, commentType)
    log.silly('PadchatRpc', 'WXSnsObjectOp , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSnsObjectOp , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 朋友圈消息评论
  // user			  对方用户名
  // id			    朋友圈消息id
  // content		评论内容
  // replyId		回复的id    //如果想回复某人的评论,就加上他的comment_id  否则就用0
  public async WXSnsComment(user: string, id: string, content: string, replyId: string): Promise<any> {
    const result = await this.rpcCall('WXSnsComment', user, id, content, replyId)
    log.silly('PadchatRpc', 'WXSnsComment , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSnsComment , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 获取好友朋友圈信息
  // user			对方用户名
  // id			    获取到的最后一次的id,第一次调用设置为空
  public async WXSnsUserPage(user: string, id: string): Promise<any> {
    const result = await this.rpcCall('WXSnsUserPage', user, id)
    log.silly('PadchatRpc', 'WXSnsUserPage , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSnsUserPage , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 获取朋友圈动态
  // id			    获取到的最后一次的id,第一次调用设置为空
  public async WXSnsTimeline(id: string): Promise<any> {
    const result = await this.rpcCall('WXSnsTimeline', id)
    log.silly('PadchatRpc', 'WXSnsTimeline , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSnsTimeline , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 发送APP消息(分享应用或者朋友圈链接等)
  // user			对方用户名
  // content		消息内容(整个消息结构<appmsg xxxxxxxxx>) 参考收到的MsgType
  public async WXSendAppMsg(user: string, content: string): Promise<any> {
    const result = await this.rpcCall('WXSendAppMsg', user, content)
    log.silly('PadchatRpc', 'WXSendAppMsg , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSendAppMsg , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 同步收藏消息(用户获取收藏对象的id)
  // key			同步的key,第一次调用设置为空。
  public async WXFavSync(key: string): Promise<any> {
    const result = await this.rpcCall('WXFavSync', key)
    log.silly('PadchatRpc', 'WXFavSync , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXFavSync , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 添加收藏
  // fav_object	收藏对象结构(<favitem type=5xxxxxx)
  public async WXFavAddItem(favObject: string): Promise<any> {
    const result = await this.rpcCall('WXFavAddItem', favObject)
    log.silly('PadchatRpc', 'WXFavAddItem , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXFavAddItem , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 获取收藏对象的详细信息
  // id			收藏对象id
  public async WXFavGetItem(id: string): Promise<any> {
    const result = await this.rpcCall('WXFavGetItem', id)
    log.silly('PadchatRpc', 'WXFavGetItem , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXFavGetItem , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 删除收藏对象
  // id			收藏对象id
  public async WXFavDeleteItem(id: string): Promise<any> {
    const result = await this.rpcCall('WXFavDeleteItem', id)
    log.silly('PadchatRpc', 'WXFavDeleteItem , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXFavDeleteItem , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 获取所有标签列表
  public async WXGetContactLabelList(): Promise<any> {
    const result = await this.rpcCall('WXGetContactLabelList')
    log.silly('PadchatRpc', 'WXGetContactLabelList , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXGetContactLabelList , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 添加标签到列表
  // label			标签内容
  public async WXAddContactLabel(label: string): Promise<any> {
    const result = await this.rpcCall('WXAddContactLabel', label)
    log.silly('PadchatRpc', 'WXAddContactLabel , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXAddContactLabel , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 从列表删除标签
  // id			标签id
  public async WXDeleteContactLabel(id: string): Promise<any> {
    const result = await this.rpcCall('WXDeleteContactLabel', id)
    log.silly('PadchatRpc', 'WXDeleteContactLabel , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXDeleteContactLabel , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 从列表删除标签
  // user			用户名
  // id			    标签id
  public async WXSetContactLabel(user: string, id: string): Promise<any> {
    const result = await this.rpcCall('WXSetContactLabel', user, id)
    log.silly('PadchatRpc', 'WXSetContactLabel , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSetContactLabel , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 获取用户二维码(自己或者已加入的群)
  // user			用户名
  // style			是否使用风格化二维码
1305 1306
  public async WXGetUserQRCode(user: string, style: number): Promise<any> {
    const result = await this.rpcCall('WXGetUserQRCode', user, String(style))
ruiruibupt's avatar
ruiruibupt 已提交
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
    log.silly('PadchatRpc', 'WXGetUserQRCode , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXGetUserQRCode , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // AppMsg上传数据
  // data			和发送图片的data 类似
  public async WXUploadAppAttach(data: string): Promise<any> {
    const result = await this.rpcCall('WXUploadAppAttach', data)
    log.silly('PadchatRpc', 'WXUploadAppAttach , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXUploadAppAttach , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 发送语音消息(微信silk格式语音)
  // user			对方用户名
  // voice_data	语音数据
  // voice_size	语音大小 (应该不需要)
  // voice_time	语音时间(毫秒,最大60 * 1000)
1332 1333
  public async WXSendVoice(user: string, data: string, time: number): Promise<any> {
    const result = await this.rpcCall('WXSendVoice', user, data, String(time))
ruiruibupt's avatar
ruiruibupt 已提交
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
    log.silly('PadchatRpc', 'WXSendVoice , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSendVoice , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 同步朋友圈动态(好友评论或点赞自己朋友圈的消息)
  // key		同步key
  public async WXSnsSync(key: string): Promise<any> {
    const result = await this.rpcCall('WXSnsSync', key)
    log.silly('PadchatRpc', 'WXSnsSync , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSnsSync , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 群发消息
  // user			用户名json数组 ["AB1","AC2","AD3"]
  // content		消息内容
  public async WXMassMessage(userList: string[], content: string): Promise<any> {
    const result = await this.rpcCall('WXMassMessage', JSON.stringify(userList), content)
    log.silly('PadchatRpc', 'WXMassMessage , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXMassMessage , stranger,error! canot get result from websocket server')
    }
    return result
  }

  // TODO check any
  // 设置群公告
  // chatroom	群id
  // content	    内容
  public async WXSetChatroomAnnouncement(chatroom: string, content: string): Promise<any> {
    const result = await this.rpcCall('WXSetChatroomAnnouncement', chatroom, content)
    log.silly('PadchatRpc', 'WXSetChatroomAnnouncement , stranger,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXSetChatroomAnnouncement , stranger,error! canot get result from websocket server')
    }
    return result
  }
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389

  // FIXME: does Get exist?
  // FIXME2: what's the structure of result? result.data???
  public async WXGetChatroomAnnouncement(chatroom: string): Promise<string> {
    const result = await this.rpcCall('WXGetChatroomAnnouncement', chatroom)
    log.silly('PadchatRpc', 'WXGetChatroomAnnouncement ,result: %s', JSON.stringify(result))
    if (!result || result.status !== 0) {
      throw Error('WXGetChatroomAnnouncement , error! canot get result from websocket server')
    }
    return result.data
  }

1390
}