contact.ts 17.3 KB
Newer Older
1
/**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
2
 *   Wechaty - https://github.com/chatie/wechaty
3
 *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
4
 *   @copyright 2016-2018 Huan LI <zixia@zixia.net>
5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 *   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.
 *
L
lijiarui 已提交
18
 *   @ignore
19
 */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
20
import { FileBox } from 'file-box'
21
import { instanceToClass } from 'clone-class'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
22

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
23
import {
24
  log,
25
  Raven,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
26
  Sayable,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
27
}                       from './config'
28
import { PuppetAccessory }  from './puppet-accessory'
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
29

30
// import Message          from './message'
31

L
lijiarui 已提交
32 33
/**
 * Enum for Gender values.
L
lijiarui 已提交
34
 *
L
lijiarui 已提交
35
 * @enum {number}
L
lijiarui 已提交
36 37 38
 * @property {number} Unknown   - 0 for Unknown
 * @property {number} Male      - 1 for Male
 * @property {number} Female    - 2 for Female
L
lijiarui 已提交
39
 */
40
export enum Gender {
41 42 43
  Unknown = 0,
  Male    = 1,
  Female  = 2,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
44 45 46
}

export enum ContactType {
47 48 49
  Unknown = 0,
  Personal,
  Official,
50 51
}

52
export interface ContactQueryFilter {
L
lijiarui 已提交
53 54
  name?:   string | RegExp,
  alias?:  string | RegExp,
55 56
}

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
export interface ContactPayload {
  gender:     Gender,
  type:       ContactType,

  address?:   string,
  alias?:     string | null,
  avatar?:    string,
  city?:      string,
  friend?:    boolean,
  name?:      string,
  province?:  string,
  signature?: string,
  star?:      boolean,
  weixin?:    string,
}

73 74
export const POOL = Symbol('pool')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
75
/**
L
lijiarui 已提交
76
 * All wechat contacts(friend) will be encapsulated as a Contact.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
77
 *
L
lijiarui 已提交
78
 * `Contact` is `Sayable`,
79
 * [Examples/Contact-Bot]{@link https://github.com/Chatie/wechaty/blob/master/examples/contact-bot.ts}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
80
 */
81
export class Contact extends PuppetAccessory implements Sayable {
82

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
83
  // tslint:disable-next-line:variable-name
84 85
  public static Type   = ContactType
  public static Gender = Gender
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
86

87 88 89 90 91 92 93 94 95 96 97 98 99
  protected static [POOL]: Map<string, Contact>
  protected static get pool() {
    return this[POOL]
  }
  protected static set pool(newPool: Map<string, Contact>) {
    if (this === Contact) {
      throw new Error(
        'The global Contact class can not be used directly!'
        + 'See: https://github.com/Chatie/wechaty/issues/1217',
      )
    }
    this[POOL] = newPool
  }
100

H
hcz 已提交
101 102
  /**
   * @private
103
   * About the Generic: https://stackoverflow.com/q/43003970/1123955
H
hcz 已提交
104
   */
105
  public static load<T extends typeof Contact>(
106 107
    this     : T,
    id       : string,
108 109
  ): T['prototype'] {
    if (!this.pool) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
110
      log.verbose('Contact', 'load(%s) init pool', id)
111 112
      this.pool = new Map<string, Contact>()
    }
113 114 115 116 117 118
    if (this === Contact) {
      throw new Error(
        'The lgobal Contact class can not be used directly!'
        + 'See: https://github.com/Chatie/wechaty/issues/1217',
      )
    }
119 120
    if (this.pool === Contact.pool) {
      throw new Error('the current pool is equal to the global pool error!')
121
    }
122 123
    const existingContact = this.pool.get(id)
    if (existingContact) {
124 125
      if (!existingContact.payload) {
        existingContact.payload = this.puppet.cacheContactPayload.get(id)
126
      }
127
      return existingContact
128
    }
129 130 131 132

    // when we call `load()`, `this` should already be extend-ed a child class.
    // so we force `this as any` at here to make the call.
    const newContact = new (this as any)(id)
133
    newContact.payload = this.puppet.cacheContactPayload.get(id)
134

135
    this.pool.set(id, newContact)
136

137
    return newContact
138 139
  }

L
lijiarui 已提交
140
  /**
L
lijiarui 已提交
141
   * The way to search Contact
L
lijiarui 已提交
142
   *
L
lijiarui 已提交
143 144 145 146 147 148 149 150
   * @typedef    ContactQueryFilter
   * @property   {string} name    - The name-string set by user-self, should be called name
   * @property   {string} alias   - The name-string set by bot for others, should be called alias
   * [More Detail]{@link https://github.com/Chatie/wechaty/issues/365}
   */

  /**
   * Try to find a contact by filter: {name: string | RegExp} / {alias: string | RegExp}
L
lijiarui 已提交
151
   *
L
lijiarui 已提交
152 153 154 155 156
   * Find contact by name or alias, if the result more than one, return the first one.
   *
   * @static
   * @param {ContactQueryFilter} query
   * @returns {(Promise<Contact | null>)} If can find the contact, return Contact, or return null
L
lijiarui 已提交
157
   * @example
L
lijiarui 已提交
158 159
   * const contactFindByName = await Contact.find({ name:"ruirui"} )
   * const contactFindByAlias = await Contact.find({ alias:"lijiarui"} )
L
lijiarui 已提交
160
   */
161 162 163 164
  public static async find<T extends typeof Contact>(
    this  : T,
    query : ContactQueryFilter,
  ): Promise<T['prototype'] | null> {
L
lijiarui 已提交
165 166
    log.verbose('Contact', 'find(%s)', JSON.stringify(query))

167
    const contactList = await this.findAll(query)
L
lijiarui 已提交
168 169
    if (!contactList || !contactList.length) {
      return null
170
    }
L
lijiarui 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194

    if (contactList.length > 1) {
      log.warn('Contact', 'function find(%s) get %d contacts, use the first one by default', JSON.stringify(query), contactList.length)
    }
    return contactList[0]
  }

  /**
   * Find contact by `name` or `alias`
   *
   * If use Contact.findAll() get the contact list of the bot.
   *
   * #### definition
   * - `name`   the name-string set by user-self, should be called name
   * - `alias`  the name-string set by bot for others, should be called alias
   *
   * @static
   * @param {ContactQueryFilter} [queryArg]
   * @returns {Promise<Contact[]>}
   * @example
   * const contactList = await Contact.findAll()                    // get the contact list of the bot
   * const contactList = await Contact.findAll({name: 'ruirui'})    // find allof the contacts whose name is 'ruirui'
   * const contactList = await Contact.findAll({alias: 'lijiarui'}) // find all of the contacts whose alias is 'lijiarui'
   */
195 196 197 198
  public static async findAll<T extends typeof Contact>(
    this  : T,
    query : ContactQueryFilter = { name: /.*/ },
  ): Promise<T['prototype'][]> {
L
lijiarui 已提交
199 200 201
    // log.verbose('Cotnact', 'findAll({ name: %s })', query.name)
    log.verbose('Cotnact', 'findAll({ %s })',
                            Object.keys(query)
202
                                  .map(k => `${k}: ${query[k as keyof ContactQueryFilter]}`)
L
lijiarui 已提交
203 204 205 206 207 208 209 210
                                  .join(', '),
              )

    if (Object.keys(query).length !== 1) {
      throw new Error('query only support one key. multi key support is not availble now.')
    }

    try {
211 212
      const contactIdList: string[] = await this.puppet.contactFindAll(query)
      const contactList = contactIdList.map(id => this.load(id))
L
lijiarui 已提交
213 214 215 216 217

      await Promise.all(contactList.map(c => c.ready()))
      return contactList

    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
218
      log.error('Contact', 'this.puppet.contactFindAll() rejected: %s', e.message)
L
lijiarui 已提交
219 220 221 222
      return [] // fail safe
    }
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
223
  /**
224
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
225
   * Instance properties
226
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
227 228 229
   */
  protected payload?: ContactPayload

230 231 232 233 234 235 236 237
  /**
   * @private
   */
  constructor(
    public readonly id: string,
  ) {
    super()
    log.silly('Contact', `constructor(${id})`)
238 239 240 241 242

    // tslint:disable-next-line:variable-name
    const MyClass = instanceToClass(this, Contact)

    if (MyClass === Contact) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
243 244 245 246
      throw new Error(
        'Contact class can not be instanciated directly!'
        + 'See: https://github.com/Chatie/wechaty/issues/1217',
      )
247 248 249 250 251
    }

    if (!this.puppet) {
      throw new Error('Contact class can not be instanciated without a puppet!')
    }
252 253 254 255 256 257
  }

  /**
   * @private
   */
  public toString(): string {
258 259 260
    if (!this.payload) {
      return this.constructor.name
    }
261
    const identity = this.alias() || this.name() || this.id
262
    return `Contact<${identity || 'Unknown'}>`
263 264
  }

L
lijiarui 已提交
265 266 267 268
  /**
   * Sent Text to contact
   *
   * @param {string} text
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
269 270 271 272 273 274 275
   * @example
   * const contact = await Contact.find({name: 'lijiarui'})         // change 'lijiarui' to any of your contact name in wechat
   * try {
   *   await contact.say('welcome to wechaty!')
   * } catch (e) {
   *   console.error(e)
   * }
L
lijiarui 已提交
276
   */
277
  public async say(text: string): Promise<void>
L
lijiarui 已提交
278 279 280 281

  /**
   * Send Media File to Contact
   *
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
282
   * @param {Message} Message
L
lijiarui 已提交
283 284
   * @example
   * const contact = await Contact.find({name: 'lijiarui'})         // change 'lijiarui' to any of your contact name in wechat
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
285
   * try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
286
   *   await contact.say(bot.Message.create(__dirname + '/wechaty.png') // put the filePath you want to send here
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
287 288 289
   * } catch (e) {
   *   console.error(e)
   * }
L
lijiarui 已提交
290
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
291
  public async say(file: FileBox): Promise<void>
292

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
293 294
  public async say(textOrFile: string | FileBox): Promise<void> {
    log.verbose('Contact', 'say(%s)', textOrFile)
295

296
    // let msg: Message
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
297
    if (typeof textOrFile === 'string') {
298 299 300 301 302 303 304
      await this.puppet.messageSendText({
        contactId: this.id,
      }, textOrFile)
      // msg = Message.createMO({
      //   text : textOrFile,
      //   to   : this,
      // })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
305
    } else if (textOrFile instanceof FileBox) {
306 307 308 309 310 311 312
      await this.puppet.messageSendFile({
        contactId: this.id,
      }, textOrFile)
      // msg = Message.createMO({
      //   to   : this,
      //   file : textOrFile,
      // })
313
    } else {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
314
      throw new Error('unsupported')
315
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
316

317 318 319 320 321 322
    // log.silly('Contact', 'say() from: %s to: %s content: %s',
    //                               this.puppet.userSelf(),
    //                               this,
    //                               msg,
    //           )
    // await this.puppet.messageSend(msg)
323
  }
L
lijiarui 已提交
324 325 326 327 328 329 330 331

  /**
   * Get the name from a contact
   *
   * @returns {string}
   * @example
   * const name = contact.name()
   */
332 333 334
  public name(): string {
    return this.payload && this.payload.name || ''
  }
L
lijiarui 已提交
335

336 337 338
  public alias()                  : null | string
  public alias(newAlias:  string) : Promise<void>
  public alias(empty:     null)   : Promise<void>
L
lijiarui 已提交
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354

  /**
   * GET / SET / DELETE the alias for a contact
   *
   * Tests show it will failed if set alias too frequently(60 times in one minute).
   * @param {(none | string | null)} newAlias
   * @returns {(string | null | Promise<boolean>)}
   * @example <caption> GET the alias for a contact, return {(string | null)}</caption>
   * const alias = contact.alias()
   * if (alias === null) {
   *   console.log('You have not yet set any alias for contact ' + contact.name())
   * } else {
   *   console.log('You have already set an alias for contact ' + contact.name() + ':' + alias)
   * }
   *
   * @example <caption>SET the alias for a contact</caption>
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
355 356
   * try {
   *   await contact.alias('lijiarui')
L
lijiarui 已提交
357
   *   console.log(`change ${contact.name()}'s alias successfully!`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
358
   * } catch (e) {
L
lijiarui 已提交
359 360 361 362
   *   console.log(`failed to change ${contact.name()} alias!`)
   * }
   *
   * @example <caption>DELETE the alias for a contact</caption>
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
363 364
   * try {
   *   const oldAlias = await contact.alias(null)
L
lijiarui 已提交
365
   *   console.log(`delete ${contact.name()}'s alias successfully!`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
366 367
   *   console.log('old alias is ${oldAlias}`)
   * } catch (e) {
L
lijiarui 已提交
368 369 370
   *   console.log(`failed to delete ${contact.name()}'s alias!`)
   * }
   */
371
  public alias(newAlias?: null | string): null | string | Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
372
    log.silly('Contact', 'alias(%s)',
373 374 375 376 377 378 379 380 381
                            newAlias === undefined
                              ? ''
                              : newAlias,
                )

    if (typeof newAlias === 'undefined') {
      return this.payload && this.payload.alias || null
    }

382
    const future = this.puppet.contactAlias(this.id, newAlias)
383 384 385 386 387 388 389 390 391 392

    future
      .then(() => this.payload!.alias = newAlias)
      .catch(e => {
        log.error('Contact', 'alias(%s) rejected: %s', newAlias, e.message)
        Raven.captureException(e)
      })

    return future
  }
L
lijiarui 已提交
393

L
lijiarui 已提交
394 395 396
  /**
   * Check if contact is stranger
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
397 398
   * @deprecated use friend() instead
   *
L
lijiarui 已提交
399
   * @returns {boolean | null} - True for not friend of the bot, False for friend of the bot, null for unknown.
L
lijiarui 已提交
400 401 402
   * @example
   * const isStranger = contact.stranger()
   */
403 404 405 406 407
  public stranger(): null | boolean {
    log.warn('Contact', 'stranger() DEPRECATED. use friend() instead.')
    if (!this.payload) return null
    return !this.friend()
  }
L
lijiarui 已提交
408

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
409 410 411 412 413 414 415
  /**
   * Check if contact is friend
   *
   * @returns {boolean | null} - True for friend of the bot, False for not friend of the bot, null for unknown.
   * @example
   * const isFriend = contact.friend()
   */
416 417 418 419 420 421 422
  public friend(): null | boolean {
    log.verbose('Contact', 'friend()')
    if (!this.payload) {
      return null
    }
    return this.payload.friend || null
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
423

J
Jas 已提交
424 425 426
  /**
   * Check if it's a offical account
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
427 428
   * @deprecated use type() instead
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
429
   * @returns {boolean | null} - True for official account, Flase for contact is not a official account, null for unknown
L
lijiarui 已提交
430 431
   * @see {@link https://github.com/Chatie/webwx-app-tracker/blob/7c59d35c6ea0cff38426a4c5c912a086c4c512b2/formatted/webwxApp.js#L3243|webwxApp.js#L324}
   * @see {@link https://github.com/Urinx/WeixinBot/blob/master/README.md|Urinx/WeixinBot/README}
J
Jas 已提交
432 433 434
   * @example
   * const isOfficial = contact.official()
   */
435 436
  public official(): boolean {
    log.warn('Contact', 'official() DEPRECATED. use type() instead')
437
    return !!this.payload && this.payload.type === ContactType.Official
438
  }
J
Jas 已提交
439 440 441 442

  /**
   * Check if it's a personal account
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
443 444 445
   * @deprecated use type() instead
   *
   * @returns {boolean} - True for personal account, Flase for contact is not a personal account
J
Jas 已提交
446 447 448
   * @example
   * const isPersonal = contact.personal()
   */
449 450 451 452
  public personal(): boolean {
    log.warn('Contact', 'personal() DEPRECATED. use type() instead')
    return !this.official()
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
453 454 455 456 457 458 459 460

  /**
   * Return the type of the Contact
   *
   * @returns ContactType - Contact.Type.PERSONAL for personal account, Contact.Type.OFFICIAL for official account
   * @example
   * const isOfficial = contact.type() === Contact.Type.OFFICIAL
   */
461 462 463
  public type(): ContactType {
    return this.payload!.type
  }
J
Jas 已提交
464

L
lijiarui 已提交
465 466 467
  /**
   * Check if the contact is star contact.
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
468
   * @returns {boolean | null} - True for star friend, False for no star friend.
L
lijiarui 已提交
469 470 471
   * @example
   * const isStar = contact.star()
   */
472 473 474 475 476 477 478 479
  public star(): null | boolean {
    if (!this.payload) {
      return null
    }
    return this.payload.star === undefined
      ? null
      : this.payload.star
  }
L
lijiarui 已提交
480

481 482
  /**
   * Contact gender
L
lijiarui 已提交
483
   *
484
   * @returns {Gender.Male(2)|Gender.Female(1)|Gender.Unknown(0)}
L
lijiarui 已提交
485 486 487
   * @example
   * const gender = contact.gender()
   */
488 489 490
  public gender(): Gender {
    return this.payload
      ? this.payload.gender
491
      : Gender.Unknown
492
  }
L
lijiarui 已提交
493 494 495 496

  /**
   * Get the region 'province' from a contact
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
497
   * @returns {string | null}
L
lijiarui 已提交
498 499
   * @example
   * const province = contact.province()
500
   */
501 502 503
  public province(): null | string {
    return this.payload && this.payload.province || null
  }
L
lijiarui 已提交
504 505 506 507

  /**
   * Get the region 'city' from a contact
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
508
   * @returns {string | null}
L
lijiarui 已提交
509 510 511
   * @example
   * const city = contact.city()
   */
512 513 514
  public city(): null | string {
    return this.payload && this.payload.city || null
  }
515 516 517

  /**
   * Get avatar picture file stream
L
lijiarui 已提交
518
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
519
   * @returns {Promise<FileBox>}
L
lijiarui 已提交
520 521
   * @example
   * const avatarFileName = contact.name() + `.jpg`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
522
   * const fileBox = await contact.avatar()
L
lijiarui 已提交
523
   * const avatarWriteStream = createWriteStream(avatarFileName)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
524
   * fileBox.pipe(avatarWriteStream)
L
lijiarui 已提交
525
   * log.info('Bot', 'Contact: %s: %s with avatar file: %s', contact.weixin(), contact.name(), avatarFileName)
526
   */
527
  // TODO: use File to replace ReadableStream
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
528
  public async avatar(): Promise<FileBox> {
529 530
    log.verbose('Contact', 'avatar()')

531
    return this.puppet.contactAvatar(this.id)
532
  }
533

L
lijiarui 已提交
534
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
535
   * Force reload(re-ready()) data for Contact
L
lijiarui 已提交
536
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
537 538
   * @deprecated use sync() instead
   *
L
lijiarui 已提交
539 540 541 542
   * @returns {Promise<this>}
   * @example
   * await contact.refresh()
   */
543 544 545 546
  public refresh(): Promise<void> {
    log.warn('Contact', 'refresh() DEPRECATED. use sync() instead.')
    return this.sync()
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
547 548 549 550 551 552 553 554

  /**
   * sycc data for Contact
   *
   * @returns {Promise<this>}
   * @example
   * await contact.sync()
   */
555 556 557 558 559 560 561 562
  public async sync(): Promise<void> {
    // TODO: make sure the contact.* works when we are refreshing the data
    // if (this.isReady()) {
    //   this.dirtyObj = this.obj
    // }
    this.payload = undefined
    await this.ready()
  }
L
lijiarui 已提交
563

L
lijiarui 已提交
564 565 566
  /**
   * @private
   */
567
  public async ready(): Promise<void> {
568
    log.silly('Contact', 'ready() @ %s', this.puppet)
569 570 571 572 573 574 575

    if (this.isReady()) { // already ready
      log.silly('Contact', 'ready() isReady() true')
      return
    }

    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
576
      this.payload = await this.puppet.contactPayload(this.id)
577 578 579 580 581 582 583 584 585 586 587 588
      log.silly('Contact', `ready() this.puppet.contactPayload(%s) resolved`, this)
      // console.log(this.payload)

    } catch (e) {
      log.error('Contact', `ready() this.puppet.contactPayload(%s) exception: %s`,
                            this,
                            e.message,
                )
      Raven.captureException(e)
      throw e
    }
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
589

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
590 591 592
  /**
   * @private
   */
593 594 595
  public isReady(): boolean {
    return !!(this.payload && this.payload.name)
  }
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
596

L
lijiarui 已提交
597 598 599 600 601 602 603
  /**
   * Check if contact is self
   *
   * @returns {boolean} True for contact is self, False for contact is others
   * @example
   * const isSelf = contact.self()
   */
604
  public self(): boolean {
605
    const userId = this.puppet.selfId()
606

607
    if (!userId) {
608 609 610
      return false
    }

611
    return this.id === userId
612
  }
613

L
lijiarui 已提交
614
  /**
L
lijiarui 已提交
615
   * Get the weixin number from a contact.
L
lijiarui 已提交
616
   *
L
lijiarui 已提交
617
   * Sometimes cannot get weixin number due to weixin security mechanism, not recommend.
L
lijiarui 已提交
618
   *
L
lijiarui 已提交
619 620
   * @private
   * @returns {string | null}
L
lijiarui 已提交
621
   * @example
L
lijiarui 已提交
622
   * const weixin = contact.weixin()
L
lijiarui 已提交
623
   */
624 625 626
  public weixin(): null | string {
    return this.payload && this.payload.weixin || null
  }
627

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
628
}
629

Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
630
export default Contact