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

23 24 25 26 27 28 29
import {
  ContactGender,
  ContactPayload,
  ContactQueryFilter,
  ContactType,
}                         from 'wechaty-puppet'

30 31
import {
  Accessory,
32
}                   from '../accessory'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
33
import {
34
  log,
35
  qrCodeForChatie,
36
  Raven,
37
}                   from '../config'
38 39
import {
  Sayable,
40
}                   from '../types'
41

42
import { UrlLink }  from './url-link'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
43

44 45
export const POOL = Symbol('pool')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
46
/**
L
lijiarui 已提交
47
 * All wechat contacts(friend) will be encapsulated as a Contact.
L
lijiarui 已提交
48
 * [Examples/Contact-Bot]{@link https://github.com/Chatie/wechaty/blob/1523c5e02be46ebe2cc172a744b2fbe53351540e/examples/contact-bot.ts}
49 50 51
 *
 * @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 (李卓桓) 已提交
52
 */
53
export class Contact extends Accessory implements Sayable {
54

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

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

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

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

117
    this.pool.set(id, newContact)
118

119
    return newContact
120 121
  }

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

151
    const contactList = await this.findAll(query)
152 153 154 155 156

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

    if (contactList.length > 1) {
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
      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 已提交
183
    }
184 185
    log.warn('Contact', 'find() got %d contacts but no one is valid.', contactList.length)
    return null
L
lijiarui 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
  }

  /**
   * 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 已提交
201 202 203 204 205
   * 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 已提交
206
   */
207
  public static async findAll<T extends typeof Contact> (
208
    this  : T,
209
    query? : string | ContactQueryFilter,
210
  ): Promise<Array<T['prototype']>> {
ruiruibupt's avatar
ruiruibupt 已提交
211
    log.verbose('Contact', 'findAll(%s)', JSON.stringify(query))
L
lijiarui 已提交
212

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

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

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

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

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

        batchIndex++
      }

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

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

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

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

267 268
  public readonly id: string // Contact Id

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

278 279
    this.id = id

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

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

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

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

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

308 309 310
    return `Contact<${identity}>`
  }

311
  public async say (text: string)     : Promise<void>
312 313
  public async say (file: FileBox)    : Promise<void>
  public async say (contact: Contact) : Promise<void>
314
  public async say (url: UrlLink)     : Promise<void>
L
lijiarui 已提交
315 316

  /**
317 318 319
   * > Tips:
   * This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/Chatie/wechaty/wiki/Puppet#3-puppet-compatible-table)
   *
320
   * @param {(string | Contact | FileBox)} textOrContactOrFileOrUrl
L
lijiarui 已提交
321 322 323
   * 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 已提交
324
   * @example
L
lijiarui 已提交
325 326 327 328
   * 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 已提交
329
   * // 1. send text to contact
L
lijiarui 已提交
330 331 332
   *
   * await contact.say('welcome to wechaty!')
   *
L
lijiarui 已提交
333
   * // 2. send media file to contact
L
lijiarui 已提交
334 335 336
   *
   * import { FileBox }  from 'file-box'
   * const fileBox1 = FileBox.fromUrl('https://chatie.io/wechaty/images/bot-qr-code.png')
337
   * const fileBox2 = FileBox.fromFile('/tmp/text.txt')
L
lijiarui 已提交
338 339 340
   * await contact.say(fileBox1)
   * await contact.say(fileBox2)
   *
L
lijiarui 已提交
341
   * // 3. send contact card to contact
L
lijiarui 已提交
342 343 344
   *
   * const contactCard = bot.Contact.load('contactId')
   * await contact.say(contactCard)
L
lijiarui 已提交
345
   */
346 347
  public async say (textOrContactOrFileOrUrl: string | Contact | FileBox | UrlLink): Promise<void> {
    log.verbose('Contact', 'say(%s)', textOrContactOrFileOrUrl)
348

349
    if (typeof textOrContactOrFileOrUrl === 'string') {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
350
      /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
351
       * 1. Text
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
352
       */
353 354
      await this.puppet.messageSendText({
        contactId: this.id,
355 356
      }, textOrContactOrFileOrUrl)
    } else if (textOrContactOrFileOrUrl instanceof Contact) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
357
      /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
358
       * 2. Contact
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
359 360 361
       */
      await this.puppet.messageSendContact({
        contactId: this.id,
362 363
      }, textOrContactOrFileOrUrl.id)
    } else if (textOrContactOrFileOrUrl instanceof FileBox) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
364
      /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
365
       * 3. File
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
366
       */
367 368
      await this.puppet.messageSendFile({
        contactId: this.id,
369 370 371 372 373 374 375 376
      }, textOrContactOrFileOrUrl)
    } else if (textOrContactOrFileOrUrl instanceof UrlLink) {
      /**
       * 4. Link Message
       */
      await this.puppet.messageSendUrl({
        contactId : this.id
      }, textOrContactOrFileOrUrl.payload)
377
    } else {
378
      throw new Error('unsupported arg: ' + textOrContactOrFileOrUrl)
379 380
    }
  }
L
lijiarui 已提交
381 382 383 384 385 386 387 388

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

393 394 395
  public async alias ()                  : Promise<null | string>
  public async alias (newAlias:  string) : Promise<void>
  public async alias (empty:     null)   : Promise<void>
L
lijiarui 已提交
396 397 398 399 400 401

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

435 436 437 438
    if (!this.payload) {
      throw new Error('no payload')
    }

439
    if (typeof newAlias === 'undefined') {
440
      return this.payload.alias || null
441 442
    }

443 444
    try {
      await this.puppet.contactAlias(this.id, newAlias)
445 446 447
      await this.puppet.contactPayloadDirty(this.id)
      this.payload = await this.puppet.contactPayload(this.id)
      if (newAlias && newAlias !== this.payload.alias) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
448 449 450 451
        log.warn('Contact', 'alias(%s) sync with server fail: set(%s) is not equal to get(%s)',
                            newAlias,
                            this.payload.alias,
                )
452
      }
453 454 455 456
    } catch (e) {
      log.error('Contact', 'alias(%s) rejected: %s', newAlias, e.message)
      Raven.captureException(e)
    }
457
  }
L
lijiarui 已提交
458

L
lijiarui 已提交
459 460
  /**
   *
L
lijiarui 已提交
461 462
   * @description
   * Should use {@link Contact#friend} instead
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
463
   *
L
lijiarui 已提交
464
   * @deprecated
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
465
   * @private
L
lijiarui 已提交
466
   */
467
  public stranger (): null | boolean {
468 469 470 471
    log.warn('Contact', 'stranger() DEPRECATED. use friend() instead.')
    if (!this.payload) return null
    return !this.friend()
  }
L
lijiarui 已提交
472

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
473 474 475
  /**
   * Check if contact is friend
   *
476 477 478
   * > 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 已提交
479 480 481 482
   * @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 (李卓桓) 已提交
483 484 485
   * @example
   * const isFriend = contact.friend()
   */
486
  public friend (): null | boolean {
487 488 489 490 491 492
    log.verbose('Contact', 'friend()')
    if (!this.payload) {
      return null
    }
    return this.payload.friend || null
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
493

J
Jas 已提交
494
  /**
L
lijiarui 已提交
495
   * @ignore
L
lijiarui 已提交
496 497
   * @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 已提交
498 499 500 501 502
   */
  /**
   * @description
   * Check if it's a offical account, should use {@link Contact#type} instead
   * @deprecated
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
503
   * @private
J
Jas 已提交
504
   */
505
  public official (): boolean {
506
    log.warn('Contact', 'official() DEPRECATED. use type() instead')
507
    return !!this.payload && (this.payload.type === ContactType.Official)
508
  }
J
Jas 已提交
509 510

  /**
L
lijiarui 已提交
511 512 513
   * @description
   * Check if it's a personal account, should use {@link Contact#type} instead
   * @deprecated
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
514
   * @private
J
Jas 已提交
515
   */
516
  public personal (): boolean {
517
    log.warn('Contact', 'personal() DEPRECATED. use type() instead')
518
    return !!this.payload && this.payload.type === ContactType.Personal
519
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
520

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

L
lijiarui 已提交
546
  /**
L
lijiarui 已提交
547 548
   * @private
   * TODO
L
lijiarui 已提交
549 550
   * Check if the contact is star contact.
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
551
   * @returns {boolean | null} - True for star friend, False for no star friend.
L
lijiarui 已提交
552 553 554
   * @example
   * const isStar = contact.star()
   */
555
  public star (): null | boolean {
556 557 558 559 560 561 562
    if (!this.payload) {
      return null
    }
    return this.payload.star === undefined
      ? null
      : this.payload.star
  }
L
lijiarui 已提交
563

564 565
  /**
   * Contact gender
L
lijiarui 已提交
566
   * > Tips: ContactGender is enum here. </br>
L
lijiarui 已提交
567
   *
L
lijiarui 已提交
568
   * @returns {ContactGender.Unknown | ContactGender.Male | ContactGender.Female}
L
lijiarui 已提交
569
   * @example
L
lijiarui 已提交
570
   * const gender = contact.gender() === bot.Contact.Gender.Male
L
lijiarui 已提交
571
   */
572
  public gender (): ContactGender {
573 574
    return this.payload
      ? this.payload.gender
575
      : ContactGender.Unknown
576
  }
L
lijiarui 已提交
577 578 579 580

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

  /**
   * Get the region 'city' from a contact
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
592
   * @returns {string | null}
L
lijiarui 已提交
593 594 595
   * @example
   * const city = contact.city()
   */
596
  public city (): null | string {
597 598
    return this.payload && this.payload.city || null
  }
599 600 601

  /**
   * Get avatar picture file stream
L
lijiarui 已提交
602
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
603
   * @returns {Promise<FileBox>}
L
lijiarui 已提交
604
   * @example
L
lijiarui 已提交
605
   * // Save avatar to local file like `1-name.jpg`
L
lijiarui 已提交
606 607 608 609 610
   *
   * const file = await contact.avatar()
   * const name = file.name
   * await file.toFile(name, true)
   * console.log(`Contact: ${contact.name()} with avatar file: ${name}`)
611
   */
612
  public async avatar (): Promise<FileBox> {
613 614
    log.verbose('Contact', 'avatar()')

615 616 617 618 619 620 621
    try {
      const fileBox = await this.puppet.contactAvatar(this.id)
      return fileBox
    } catch (e) {
      log.error('Contact', 'avatar() exception: %s', e.message)
      return qrCodeForChatie()
    }
622
  }
623

L
lijiarui 已提交
624
  /**
L
lijiarui 已提交
625 626
   * @description
   * Force reload(re-ready()) data for Contact, use {@link Contact#sync} instead
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
627
   *
L
lijiarui 已提交
628
   * @deprecated
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
629
   * @private
L
lijiarui 已提交
630
   */
631
  public refresh (): Promise<void> {
632 633 634
    log.warn('Contact', 'refresh() DEPRECATED. use sync() instead.')
    return this.sync()
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
635 636

  /**
L
lijiarui 已提交
637
   * Force reload(re-ready()) data for Contact,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
638 639 640 641
   *
   * @returns {Promise<this>}
   * @example
   * await contact.sync()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
642
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
643
   */
644
  public async sync (): Promise<void> {
645
    await this.ready(true)
646
  }
L
lijiarui 已提交
647

L
lijiarui 已提交
648 649 650
  /**
   * @private
   */
651
  public async ready (noCache = false): Promise<void> {
652
    log.silly('Contact', 'ready() @ %s', this.puppet)
653 654 655 656 657 658 659

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

    try {
660
      if (noCache) {
661 662
        await this.puppet.contactPayloadDirty(this.id)
      }
663
      this.payload = await this.puppet.contactPayload(this.id)
664
      // log.silly('Contact', `ready() this.puppet.contactPayload(%s) resolved`, this)
665 666

    } catch (e) {
667
      log.verbose('Contact', `ready() this.puppet.contactPayload(%s) exception: %s`,
668 669 670 671 672 673 674
                            this,
                            e.message,
                )
      Raven.captureException(e)
      throw e
    }
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
675

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
676 677 678
  /**
   * @private
   */
679
  public isReady (): boolean {
680 681
    return !!(this.payload && this.payload.name)
  }
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
682

L
lijiarui 已提交
683 684 685 686 687 688 689
  /**
   * Check if contact is self
   *
   * @returns {boolean} True for contact is self, False for contact is others
   * @example
   * const isSelf = contact.self()
   */
690
  public self (): boolean {
691
    const userId = this.puppet.selfId()
692

693
    if (!userId) {
694 695 696
      return false
    }

697
    return this.id === userId
698
  }
699

L
lijiarui 已提交
700
  /**
L
lijiarui 已提交
701
   * Get the weixin number from a contact.
L
lijiarui 已提交
702
   *
L
lijiarui 已提交
703
   * Sometimes cannot get weixin number due to weixin security mechanism, not recommend.
L
lijiarui 已提交
704
   *
L
lijiarui 已提交
705 706
   * @private
   * @returns {string | null}
L
lijiarui 已提交
707
   * @example
L
lijiarui 已提交
708
   * const weixin = contact.weixin()
L
lijiarui 已提交
709
   */
710
  public weixin (): null | string {
711 712
    return this.payload && this.payload.weixin || null
  }
713
}