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

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

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

118
    return newContact
119 120
  }

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

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

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

    if (contactList.length > 1) {
160 161 162 163 164 165 166 167 168 169 170
      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) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
171
        log.verbose('Contact', 'find() confirm contact[#%d] with id=%d is valid result, return it.',
172 173 174
          n,
          contact.id,
        )
175 176 177
        return contact
      } else {
        log.verbose('Contact', 'find() confirm contact[#%d] with id=%d is INVALID result, try next',
178 179 180
          n,
          contact.id,
        )
181
      }
L
lijiarui 已提交
182
    }
183 184
    log.warn('Contact', 'find() got %d contacts but no one is valid.', contactList.length)
    return null
L
lijiarui 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
  }

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

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
216
      const BATCH_SIZE = 16
217 218
      let   batchIndex = 0

219
      const invalidDict: { [id: string]: true } = {}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
220

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

        batchIndex++
      }

239
      return contactList.filter(contact => !invalidDict[contact.id])
L
lijiarui 已提交
240 241

    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
242
      log.error('Contact', 'this.puppet.contactFindAll() rejected: %s', e.message)
L
lijiarui 已提交
243 244 245 246
      return [] // fail safe
    }
  }

247
  // TODO
248
  public static async delete (contact: Contact): Promise<void> {
ruiruibupt's avatar
ruiruibupt 已提交
249
    log.verbose('Contact', 'static delete(%s)', contact.id)
250 251
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
252
  /**
253
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
254
   * Instance properties
L
lijiarui 已提交
255
   * @private
256
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
257
   */
258
  protected payload?: ContactPayload
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
259

260 261 262
  /**
   * @private
   */
263
  constructor (
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
264
    public readonly id: string,
265 266 267
  ) {
    super()
    log.silly('Contact', `constructor(${id})`)
268 269 270 271 272

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

    if (MyClass === Contact) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
273 274 275 276
      throw new Error(
        'Contact class can not be instanciated directly!'
        + 'See: https://github.com/Chatie/wechaty/issues/1217',
      )
277 278 279 280 281
    }

    if (!this.puppet) {
      throw new Error('Contact class can not be instanciated without a puppet!')
    }
282 283 284
  }

  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
285
   * @private
286
   */
287
  public toString (): string {
288 289 290 291 292 293 294 295 296
    if (!this.payload) {
      return this.constructor.name
    }

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

297 298 299
    return `Contact<${identity}>`
  }

300
  public async say (text: string)     : Promise<void>
301 302
  public async say (file: FileBox)    : Promise<void>
  public async say (contact: Contact) : Promise<void>
303
  public async say (url: UrlLink)     : Promise<void>
L
lijiarui 已提交
304 305

  /**
306 307 308
   * > Tips:
   * This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/Chatie/wechaty/wiki/Puppet#3-puppet-compatible-table)
   *
309
   * @param {(string | Contact | FileBox | UrlLink)} textOrContactOrFileOrUrl
L
lijiarui 已提交
310 311 312
   * 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 已提交
313
   * @example
L
lijiarui 已提交
314 315 316 317
   * 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 已提交
318
   * // 1. send text to contact
L
lijiarui 已提交
319 320 321
   *
   * await contact.say('welcome to wechaty!')
   *
L
lijiarui 已提交
322
   * // 2. send media file to contact
L
lijiarui 已提交
323 324 325
   *
   * import { FileBox }  from 'file-box'
   * const fileBox1 = FileBox.fromUrl('https://chatie.io/wechaty/images/bot-qr-code.png')
326
   * const fileBox2 = FileBox.fromFile('/tmp/text.txt')
L
lijiarui 已提交
327 328 329
   * await contact.say(fileBox1)
   * await contact.say(fileBox2)
   *
L
lijiarui 已提交
330
   * // 3. send contact card to contact
L
lijiarui 已提交
331 332 333
   *
   * const contactCard = bot.Contact.load('contactId')
   * await contact.say(contactCard)
334 335 336 337
   *
   * // 4. send url link to contact
   *
   * const urlLink = new UrlLink ({
L
linyimin 已提交
338 339 340 341
   *   description : 'WeChat Bot SDK for Individual Account, Powered by TypeScript, Docker, and Love',
   *   thumbnailUrl: 'https://avatars0.githubusercontent.com/u/25162437?s=200&v=4',
   *   title       : 'Welcome to Wechaty',
   *   url         : 'https://github.com/chatie/wechaty',
342 343
   * })
   * await contact.say(urlLink)
L
lijiarui 已提交
344
   */
345 346
  public async say (textOrContactOrFileOrUrl: string | Contact | FileBox | UrlLink): Promise<void> {
    log.verbose('Contact', 'say(%s)', textOrContactOrFileOrUrl)
347

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

L
lijiarui 已提交
646
  /**
647 648 649 650 651
   * `ready()` is For FrameWork ONLY!
   *
   * Please not to use `ready()` at the user land.
   * If you want to sync data, uyse `sync()` instead.
   *
L
lijiarui 已提交
652 653
   * @private
   */
654 655 656
  public async ready (
    forceSync = false,
  ): Promise<void> {
657
    log.silly('Contact', 'ready() @ %s', this.puppet)
658

659
    if (!forceSync && this.isReady()) { // already ready
660 661 662 663 664
      log.silly('Contact', 'ready() isReady() true')
      return
    }

    try {
665
      if (forceSync) {
666 667
        await this.puppet.contactPayloadDirty(this.id)
      }
668
      this.payload = await this.puppet.contactPayload(this.id)
669
      // log.silly('Contact', `ready() this.puppet.contactPayload(%s) resolved`, this)
670 671

    } catch (e) {
672
      log.verbose('Contact', `ready() this.puppet.contactPayload(%s) exception: %s`,
673 674 675
        this,
        e.message,
      )
676 677 678 679
      Raven.captureException(e)
      throw e
    }
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
680

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
681 682 683
  /**
   * @private
   */
684
  public isReady (): boolean {
685 686
    return !!(this.payload && this.payload.name)
  }
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
687

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

698
    if (!userId) {
699 700 701
      return false
    }

702
    return this.id === userId
703
  }
704

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

719
}