contact.ts 20.0 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
 */
20
import { instanceToClass } from 'clone-class'
21
import { FileBox } from 'file-box'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
22

23 24 25
import {
  Accessory,
}             from '../accessory'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
26
import {
27
  log,
28
  qrCodeForChatie,
29
  Raven,
30
}                   from '../config'
31 32 33
import {
  Sayable,
}             from '../types'
34

35
import {
36
  ContactGender,
37 38 39
  ContactPayload,
  ContactQueryFilter,
  ContactType,
40
}                         from 'wechaty-puppet'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
41

42 43
export const POOL = Symbol('pool')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
44
/**
L
lijiarui 已提交
45
 * All wechat contacts(friend) will be encapsulated as a Contact.
L
lijiarui 已提交
46
 * [Examples/Contact-Bot]{@link https://github.com/Chatie/wechaty/blob/1523c5e02be46ebe2cc172a744b2fbe53351540e/examples/contact-bot.ts}
47 48 49
 *
 * @property {string}  id               - Get Contact id.
 * This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/Chatie/wechaty/wiki/Puppet#3-puppet-compatible-table)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
50
 */
51
export class Contact extends Accessory implements Sayable {
52

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
53
  // tslint:disable-next-line:variable-name
54
  public static Type   = ContactType
55
  // tslint:disable-next-line:variable-name
56
  public static Gender = ContactGender
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
57

58
  protected static [POOL]: Map<string, Contact>
59
  protected static get pool () {
60 61
    return this[POOL]
  }
62
  protected static set pool (newPool: Map<string, Contact>) {
63 64 65 66 67 68 69 70
    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
  }
71

H
hcz 已提交
72 73
  /**
   * @private
74
   * About the Generic: https://stackoverflow.com/q/43003970/1123955
H
hcz 已提交
75
   */
L
lijiarui 已提交
76 77
  /**
   * Get Contact by id
78 79
   * > Tips:
   * This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/Chatie/wechaty/wiki/Puppet#3-puppet-compatible-table)
L
lijiarui 已提交
80 81 82 83 84 85 86 87 88
   *
   * @static
   * @param {string} id
   * @returns {Contact}
   * @example
   * const bot = new Wechaty()
   * await bot.start()
   * const contact = bot.Contact.load('contactId')
   */
89
  public static load<T extends typeof Contact> (
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
90 91
    this : T,
    id   : string,
92 93
  ): T['prototype'] {
    if (!this.pool) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
94
      log.verbose('Contact', 'load(%s) init pool', id)
95 96
      this.pool = new Map<string, Contact>()
    }
97 98 99 100 101 102
    if (this === Contact) {
      throw new Error(
        'The lgobal Contact class can not be used directly!'
        + 'See: https://github.com/Chatie/wechaty/issues/1217',
      )
    }
103 104
    if (this.pool === Contact.pool) {
      throw new Error('the current pool is equal to the global pool error!')
105
    }
106 107 108
    const existingContact = this.pool.get(id)
    if (existingContact) {
      return existingContact
109
    }
110 111 112

    // 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.
113
    const newContact = new (this as any)(id) as Contact
114

115
    this.pool.set(id, newContact)
116

117
    return newContact
118 119
  }

L
lijiarui 已提交
120
  /**
L
lijiarui 已提交
121
   * The way to search Contact
L
lijiarui 已提交
122
   *
L
lijiarui 已提交
123 124 125 126 127 128 129 130
   * @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 已提交
131
   *
L
lijiarui 已提交
132 133 134 135 136
   * 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 已提交
137
   * @example
L
lijiarui 已提交
138 139 140 141
   * const bot = new Wechaty()
   * await bot.start()
   * const contactFindByName = await bot.Contact.find({ name:"ruirui"} )
   * const contactFindByAlias = await bot.Contact.find({ alias:"lijiarui"} )
L
lijiarui 已提交
142
   */
143
  public static async find<T extends typeof Contact> (
144
    this  : T,
145
    query : string | ContactQueryFilter,
146
  ): Promise<T['prototype'] | null> {
L
lijiarui 已提交
147 148
    log.verbose('Contact', 'find(%s)', JSON.stringify(query))

149
    const contactList = await this.findAll(query)
150 151 152 153 154

    if (!contactList) {
      return null
    }
    if (contactList.length < 1) {
L
lijiarui 已提交
155
      return null
156
    }
L
lijiarui 已提交
157 158

    if (contactList.length > 1) {
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
      log.warn('Contact', 'find() got more than one(%d) result', contactList.length)
    }

    let n = 0
    for (n = 0; n < contactList.length; n++) {
      const contact = contactList[n]
      // use puppet.contactValidate() to confirm double confirm that this contactId is valid.
      // https://github.com/lijiarui/wechaty-puppet-padchat/issues/64
      // https://github.com/Chatie/wechaty/issues/1345
      const valid = await this.puppet.contactValidate(contact.id)
      if (valid) {
        log.verbose('Contact', 'find() confirm contact[#%d] with id=%d is vlaid result, return it.',
                            n,
                            contact.id,
                  )
        return contact
      } else {
        log.verbose('Contact', 'find() confirm contact[#%d] with id=%d is INVALID result, try next',
                            n,
                            contact.id,
                    )
      }
L
lijiarui 已提交
181
    }
182 183
    log.warn('Contact', 'find() got %d contacts but no one is valid.', contactList.length)
    return null
L
lijiarui 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
  }

  /**
   * 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
L
lijiarui 已提交
199 200 201 202 203
   * const bot = new Wechaty()
   * await bot.start()
   * const contactList = await bot.Contact.findAll()                    // get the contact list of the bot
   * const contactList = await bot.Contact.findAll({name: 'ruirui'})    // find allof the contacts whose name is 'ruirui'
   * const contactList = await bot.Contact.findAll({alias: 'lijiarui'}) // find all of the contacts whose alias is 'lijiarui'
L
lijiarui 已提交
204
   */
205
  public static async findAll<T extends typeof Contact> (
206
    this  : T,
207
    query? : string | ContactQueryFilter,
208
  ): Promise<Array<T['prototype']>> {
ruiruibupt's avatar
ruiruibupt 已提交
209
    log.verbose('Contact', 'findAll(%s)', JSON.stringify(query))
L
lijiarui 已提交
210

211
    if (query && Object.keys(query).length !== 1) {
L
lijiarui 已提交
212 213 214 215
      throw new Error('query only support one key. multi key support is not availble now.')
    }

    try {
216
      const contactIdList: string[] = await this.puppet.contactSearch(query)
217
      const contactList = contactIdList.map(id => this.load(id))
L
lijiarui 已提交
218

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
219
      const BATCH_SIZE = 16
220 221
      let   batchIndex = 0

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
222 223
      const invalidContactId: string[] = []

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
224
      while (batchIndex * BATCH_SIZE < contactList.length) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
225
        const batchContactList = contactList.slice(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
226 227
          BATCH_SIZE * batchIndex,
          BATCH_SIZE * (batchIndex + 1),
228 229
        )
        await Promise.all(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
230
          batchContactList.map(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
231 232 233 234 235 236 237
            c => {
              c.ready()
              .catch(e => {
                log.error('Contact', 'findAll() ready() exception: %s', e.message)
                invalidContactId.push(c.id)
              })
            },
238 239 240 241 242 243
          ),
        )

        batchIndex++
      }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
244
      return contactList.filter(contact => !(contact.id in invalidContactId))
L
lijiarui 已提交
245 246

    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
247
      log.error('Contact', 'this.puppet.contactFindAll() rejected: %s', e.message)
L
lijiarui 已提交
248 249 250 251
      return [] // fail safe
    }
  }

252
  // TODO
253
  public static async delete (contact: Contact): Promise<void> {
ruiruibupt's avatar
ruiruibupt 已提交
254
    log.verbose('Contact', 'static delete(%s)', contact.id)
255 256
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
257
  /**
258
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
259
   * Instance properties
L
lijiarui 已提交
260
   * @private
261
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
262
   */
263
  protected payload?: ContactPayload
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
264

265 266
  public readonly id: string // Contact Id

267 268 269
  /**
   * @private
   */
270
  constructor (
271
    id: string,
272 273 274
  ) {
    super()
    log.silly('Contact', `constructor(${id})`)
275

276 277
    this.id = id

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

    if (MyClass === Contact) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
282 283 284 285
      throw new Error(
        'Contact class can not be instanciated directly!'
        + 'See: https://github.com/Chatie/wechaty/issues/1217',
      )
286 287 288 289 290
    }

    if (!this.puppet) {
      throw new Error('Contact class can not be instanciated without a puppet!')
    }
291 292 293
  }

  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
294
   * @private
295
   */
296
  public toString (): string {
297 298 299 300 301 302 303 304 305
    if (!this.payload) {
      return this.constructor.name
    }

    const identity = this.payload.alias
                    || this.payload.name
                    || this.id
                    || 'loading...'

306 307 308
    return `Contact<${identity}>`
  }

309 310 311
  public async say (text: string): Promise<void>
  public async say (file: FileBox)    : Promise<void>
  public async say (contact: Contact) : Promise<void>
L
lijiarui 已提交
312 313

  /**
314 315 316
   * > Tips:
   * This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/Chatie/wechaty/wiki/Puppet#3-puppet-compatible-table)
   *
L
lijiarui 已提交
317 318 319 320
   * @param {(string | Contact | FileBox)} textOrContactOrFile
   * send text, Contact, or file to contact. </br>
   * You can use {@link https://www.npmjs.com/package/file-box|FileBox} to send file
   * @returns {Promise<void>}
L
lijiarui 已提交
321
   * @example
L
lijiarui 已提交
322 323 324 325
   * const bot = new Wechaty()
   * await bot.start()
   * const contact = await bot.Contact.find({name: 'lijiarui'})  // change 'lijiarui' to any of your contact name in wechat
   *
L
lijiarui 已提交
326
   * // 1. send text to contact
L
lijiarui 已提交
327 328 329
   *
   * await contact.say('welcome to wechaty!')
   *
L
lijiarui 已提交
330
   * // 2. send media file to contact
L
lijiarui 已提交
331 332 333
   *
   * import { FileBox }  from 'file-box'
   * const fileBox1 = FileBox.fromUrl('https://chatie.io/wechaty/images/bot-qr-code.png')
334
   * const fileBox2 = FileBox.fromFile('/tmp/text.txt')
L
lijiarui 已提交
335 336 337
   * await contact.say(fileBox1)
   * await contact.say(fileBox2)
   *
L
lijiarui 已提交
338
   * // 3. send contact card to contact
L
lijiarui 已提交
339 340 341
   *
   * const contactCard = bot.Contact.load('contactId')
   * await contact.say(contactCard)
L
lijiarui 已提交
342
   */
343
  public async say (textOrContactOrFile: string | Contact | FileBox): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
344
    log.verbose('Contact', 'say(%s)', textOrContactOrFile)
345

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
346 347
    if (typeof textOrContactOrFile === 'string') {
      /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
348
       * 1. Text
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
349
       */
350 351
      await this.puppet.messageSendText({
        contactId: this.id,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
352 353 354
      }, textOrContactOrFile)
    } else if (textOrContactOrFile instanceof Contact) {
      /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
355
       * 2. Contact
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
356 357 358 359 360 361
       */
      await this.puppet.messageSendContact({
        contactId: this.id,
      }, textOrContactOrFile.id)
    } else if (textOrContactOrFile instanceof FileBox) {
      /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
362
       * 3. File
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
363
       */
364 365
      await this.puppet.messageSendFile({
        contactId: this.id,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
366
      }, textOrContactOrFile)
367
    } else {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
368
      throw new Error('unsupported')
369 370
    }
  }
L
lijiarui 已提交
371 372 373 374 375 376 377 378

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

383 384 385
  public async alias ()                  : Promise<null | string>
  public async alias (newAlias:  string) : Promise<void>
  public async alias (empty:     null)   : Promise<void>
L
lijiarui 已提交
386 387 388 389 390 391

  /**
   * 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
392 393 394
   * @returns {(Promise<null | string | void>)}
   * @example <caption> GET the alias for a contact, return {(Promise<string | null>)}</caption>
   * const alias = await contact.alias()
L
lijiarui 已提交
395 396 397 398 399 400 401
   * 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 (李卓桓) 已提交
402 403
   * try {
   *   await contact.alias('lijiarui')
L
lijiarui 已提交
404
   *   console.log(`change ${contact.name()}'s alias successfully!`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
405
   * } catch (e) {
L
lijiarui 已提交
406 407 408 409
   *   console.log(`failed to change ${contact.name()} alias!`)
   * }
   *
   * @example <caption>DELETE the alias for a contact</caption>
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
410 411
   * try {
   *   const oldAlias = await contact.alias(null)
L
lijiarui 已提交
412
   *   console.log(`delete ${contact.name()}'s alias successfully!`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
413 414
   *   console.log('old alias is ${oldAlias}`)
   * } catch (e) {
L
lijiarui 已提交
415 416 417
   *   console.log(`failed to delete ${contact.name()}'s alias!`)
   * }
   */
418
  public async alias (newAlias?: null | string): Promise<null | string | void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
419
    log.silly('Contact', 'alias(%s)',
420 421 422 423 424
                            newAlias === undefined
                              ? ''
                              : newAlias,
                )

425 426 427 428
    if (!this.payload) {
      throw new Error('no payload')
    }

429
    if (typeof newAlias === 'undefined') {
430
      return this.payload.alias || null
431 432
    }

433 434
    try {
      await this.puppet.contactAlias(this.id, newAlias)
435 436 437
      await this.puppet.contactPayloadDirty(this.id)
      this.payload = await this.puppet.contactPayload(this.id)
      if (newAlias && newAlias !== this.payload.alias) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
438 439 440 441
        log.warn('Contact', 'alias(%s) sync with server fail: set(%s) is not equal to get(%s)',
                            newAlias,
                            this.payload.alias,
                )
442
      }
443 444 445 446
    } catch (e) {
      log.error('Contact', 'alias(%s) rejected: %s', newAlias, e.message)
      Raven.captureException(e)
    }
447
  }
L
lijiarui 已提交
448

L
lijiarui 已提交
449 450
  /**
   *
L
lijiarui 已提交
451 452
   * @description
   * Should use {@link Contact#friend} instead
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
453
   *
L
lijiarui 已提交
454
   * @deprecated
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
455
   * @private
L
lijiarui 已提交
456
   */
457
  public stranger (): null | boolean {
458 459 460 461
    log.warn('Contact', 'stranger() DEPRECATED. use friend() instead.')
    if (!this.payload) return null
    return !this.friend()
  }
L
lijiarui 已提交
462

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
463 464 465
  /**
   * Check if contact is friend
   *
466 467 468
   * > Tips:
   * This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/Chatie/wechaty/wiki/Puppet#3-puppet-compatible-table)
   *
L
lijiarui 已提交
469 470 471 472
   * @returns {boolean | null}
   *
   * <br>True for friend of the bot <br>
   * False for not friend of the bot, null for unknown.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
473 474 475
   * @example
   * const isFriend = contact.friend()
   */
476
  public friend (): null | boolean {
477 478 479 480 481 482
    log.verbose('Contact', 'friend()')
    if (!this.payload) {
      return null
    }
    return this.payload.friend || null
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
483

J
Jas 已提交
484
  /**
L
lijiarui 已提交
485
   * @ignore
L
lijiarui 已提交
486 487
   * @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}
L
lijiarui 已提交
488 489 490 491 492
   */
  /**
   * @description
   * Check if it's a offical account, should use {@link Contact#type} instead
   * @deprecated
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
493
   * @private
J
Jas 已提交
494
   */
495
  public official (): boolean {
496
    log.warn('Contact', 'official() DEPRECATED. use type() instead')
497
    return !!this.payload && (this.payload.type === ContactType.Official)
498
  }
J
Jas 已提交
499 500

  /**
L
lijiarui 已提交
501 502 503
   * @description
   * Check if it's a personal account, should use {@link Contact#type} instead
   * @deprecated
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
504
   * @private
J
Jas 已提交
505
   */
506
  public personal (): boolean {
507
    log.warn('Contact', 'personal() DEPRECATED. use type() instead')
508
    return !!this.payload && this.payload.type === ContactType.Personal
509
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
510

L
lijiarui 已提交
511 512 513 514 515 516 517 518
  /**
   * Enum for ContactType
   * @enum {number}
   * @property {number} Unknown    - ContactType.Unknown    (0) for Unknown
   * @property {number} Personal   - ContactType.Personal   (1) for Personal
   * @property {number} Official   - ContactType.Official   (2) for Official
   */

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
519 520
  /**
   * Return the type of the Contact
L
lijiarui 已提交
521 522
   * > Tips: ContactType is enum here.</br>
   * @returns {ContactType.Unknown | ContactType.Personal | ContactType.Official}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
523 524
   *
   * @example
L
lijiarui 已提交
525 526 527
   * const bot = new Wechaty()
   * await bot.start()
   * const isOfficial = contact.type() === bot.Contact.Type.Official
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
528
   */
529 530 531 532 533
  public type (): ContactType {
    if (!this.payload) {
      throw new Error('no payload')
    }
    return this.payload.type
534
  }
J
Jas 已提交
535

L
lijiarui 已提交
536
  /**
L
lijiarui 已提交
537 538
   * @private
   * TODO
L
lijiarui 已提交
539 540
   * Check if the contact is star contact.
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
541
   * @returns {boolean | null} - True for star friend, False for no star friend.
L
lijiarui 已提交
542 543 544
   * @example
   * const isStar = contact.star()
   */
545
  public star (): null | boolean {
546 547 548 549 550 551 552
    if (!this.payload) {
      return null
    }
    return this.payload.star === undefined
      ? null
      : this.payload.star
  }
L
lijiarui 已提交
553

554 555
  /**
   * Contact gender
L
lijiarui 已提交
556
   * > Tips: ContactGender is enum here. </br>
L
lijiarui 已提交
557
   *
L
lijiarui 已提交
558
   * @returns {ContactGender.Unknown | ContactGender.Male | ContactGender.Female}
L
lijiarui 已提交
559
   * @example
L
lijiarui 已提交
560
   * const gender = contact.gender() === bot.Contact.Gender.Male
L
lijiarui 已提交
561
   */
562
  public gender (): ContactGender {
563 564
    return this.payload
      ? this.payload.gender
565
      : ContactGender.Unknown
566
  }
L
lijiarui 已提交
567 568 569 570

  /**
   * Get the region 'province' from a contact
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
571
   * @returns {string | null}
L
lijiarui 已提交
572 573
   * @example
   * const province = contact.province()
574
   */
575
  public province (): null | string {
576 577
    return this.payload && this.payload.province || null
  }
L
lijiarui 已提交
578 579 580 581

  /**
   * Get the region 'city' from a contact
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
582
   * @returns {string | null}
L
lijiarui 已提交
583 584 585
   * @example
   * const city = contact.city()
   */
586
  public city (): null | string {
587 588
    return this.payload && this.payload.city || null
  }
589 590 591

  /**
   * Get avatar picture file stream
L
lijiarui 已提交
592
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
593
   * @returns {Promise<FileBox>}
L
lijiarui 已提交
594
   * @example
L
lijiarui 已提交
595
   * // Save avatar to local file like `1-name.jpg`
L
lijiarui 已提交
596 597 598 599 600
   *
   * const file = await contact.avatar()
   * const name = file.name
   * await file.toFile(name, true)
   * console.log(`Contact: ${contact.name()} with avatar file: ${name}`)
601
   */
602
  public async avatar (): Promise<FileBox> {
603 604
    log.verbose('Contact', 'avatar()')

605 606 607 608 609 610 611
    try {
      const fileBox = await this.puppet.contactAvatar(this.id)
      return fileBox
    } catch (e) {
      log.error('Contact', 'avatar() exception: %s', e.message)
      return qrCodeForChatie()
    }
612
  }
613

L
lijiarui 已提交
614
  /**
L
lijiarui 已提交
615 616
   * @description
   * Force reload(re-ready()) data for Contact, use {@link Contact#sync} instead
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
617
   *
L
lijiarui 已提交
618
   * @deprecated
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
619
   * @private
L
lijiarui 已提交
620
   */
621
  public refresh (): Promise<void> {
622 623 624
    log.warn('Contact', 'refresh() DEPRECATED. use sync() instead.')
    return this.sync()
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
625 626

  /**
L
lijiarui 已提交
627
   * Force reload(re-ready()) data for Contact,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
628 629 630 631
   *
   * @returns {Promise<this>}
   * @example
   * await contact.sync()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
632
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
633
   */
634
  public async sync (): Promise<void> {
635
    await this.ready(true)
636
  }
L
lijiarui 已提交
637

L
lijiarui 已提交
638 639 640
  /**
   * @private
   */
641
  public async ready (noCache = false): Promise<void> {
642
    log.silly('Contact', 'ready() @ %s', this.puppet)
643 644 645 646 647 648 649

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

    try {
650
      if (noCache) {
651 652
        await this.puppet.contactPayloadDirty(this.id)
      }
653
      this.payload = await this.puppet.contactPayload(this.id)
654
      // log.silly('Contact', `ready() this.puppet.contactPayload(%s) resolved`, this)
655 656 657 658 659 660 661 662 663 664

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

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
666 667 668
  /**
   * @private
   */
669
  public isReady (): boolean {
670 671
    return !!(this.payload && this.payload.name)
  }
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
672

L
lijiarui 已提交
673 674 675 676 677 678 679
  /**
   * Check if contact is self
   *
   * @returns {boolean} True for contact is self, False for contact is others
   * @example
   * const isSelf = contact.self()
   */
680
  public self (): boolean {
681
    const userId = this.puppet.selfId()
682

683
    if (!userId) {
684 685 686
      return false
    }

687
    return this.id === userId
688
  }
689

L
lijiarui 已提交
690
  /**
L
lijiarui 已提交
691
   * Get the weixin number from a contact.
L
lijiarui 已提交
692
   *
L
lijiarui 已提交
693
   * Sometimes cannot get weixin number due to weixin security mechanism, not recommend.
L
lijiarui 已提交
694
   *
L
lijiarui 已提交
695 696
   * @private
   * @returns {string | null}
L
lijiarui 已提交
697
   * @example
L
lijiarui 已提交
698
   * const weixin = contact.weixin()
L
lijiarui 已提交
699
   */
700
  public weixin (): null | string {
701 702
    return this.payload && this.payload.weixin || null
  }
703
}