contact.ts 20.8 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 171 172 173 174 175 176 177 178 179 180 181
      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 已提交
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
    if (query && Object.keys(query).length !== 1) {
L
lijiarui 已提交
213 214 215 216
      throw new Error('query only support one key. multi key support is not availble now.')
    }

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

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

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

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

        batchIndex++
      }

243
      return contactList.filter(contact => !invalidDict[contact.id])
L
lijiarui 已提交
244 245

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

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

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

264 265
  public readonly id: string // Contact Id

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

275 276
    this.id = id

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

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

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

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

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

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

308
  public async say (text: string)     : Promise<void>
309 310
  public async say (file: FileBox)    : Promise<void>
  public async say (contact: Contact) : Promise<void>
311
  public async say (url: UrlLink)     : 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)
   *
317
   * @param {(string | Contact | FileBox | UrlLink)} textOrContactOrFileOrUrl
L
lijiarui 已提交
318 319 320
   * 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)
342 343 344 345 346 347 348 349 350 351
   *
   * // 4. send url link to contact
   *
   * const urlLink = new UrlLink ({
   *  description: 'this is url link description',
   *  thumbnailUrl: 'this is a thumbnail url',
   *  title: 'this is url link title',
   *  url: 'this is the url',
   * })
   * await contact.say(urlLink)
L
lijiarui 已提交
352
   */
353 354
  public async say (textOrContactOrFileOrUrl: string | Contact | FileBox | UrlLink): Promise<void> {
    log.verbose('Contact', 'say(%s)', textOrContactOrFileOrUrl)
355

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

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

400 401 402
  public async alias ()                  : Promise<null | string>
  public async alias (newAlias:  string) : Promise<void>
  public async alias (empty:     null)   : Promise<void>
L
lijiarui 已提交
403 404 405 406 407 408

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

442 443 444 445
    if (!this.payload) {
      throw new Error('no payload')
    }

446
    if (typeof newAlias === 'undefined') {
447
      return this.payload.alias || null
448 449
    }

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

L
lijiarui 已提交
466 467
  /**
   *
L
lijiarui 已提交
468 469
   * @description
   * Should use {@link Contact#friend} instead
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
470
   *
L
lijiarui 已提交
471
   * @deprecated
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
472
   * @private
L
lijiarui 已提交
473
   */
474
  public stranger (): null | boolean {
475 476 477 478
    log.warn('Contact', 'stranger() DEPRECATED. use friend() instead.')
    if (!this.payload) return null
    return !this.friend()
  }
L
lijiarui 已提交
479

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

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

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

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

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

571 572
  /**
   * Contact gender
L
lijiarui 已提交
573
   * > Tips: ContactGender is enum here. </br>
L
lijiarui 已提交
574
   *
L
lijiarui 已提交
575
   * @returns {ContactGender.Unknown | ContactGender.Male | ContactGender.Female}
L
lijiarui 已提交
576
   * @example
L
lijiarui 已提交
577
   * const gender = contact.gender() === bot.Contact.Gender.Male
L
lijiarui 已提交
578
   */
579
  public gender (): ContactGender {
580 581
    return this.payload
      ? this.payload.gender
582
      : ContactGender.Unknown
583
  }
L
lijiarui 已提交
584 585 586 587

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

  /**
   * Get the region 'city' from a contact
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
599
   * @returns {string | null}
L
lijiarui 已提交
600 601 602
   * @example
   * const city = contact.city()
   */
603
  public city (): null | string {
604 605
    return this.payload && this.payload.city || null
  }
606 607 608

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

622 623 624 625 626 627 628
    try {
      const fileBox = await this.puppet.contactAvatar(this.id)
      return fileBox
    } catch (e) {
      log.error('Contact', 'avatar() exception: %s', e.message)
      return qrCodeForChatie()
    }
629
  }
630

L
lijiarui 已提交
631
  /**
L
lijiarui 已提交
632 633
   * @description
   * Force reload(re-ready()) data for Contact, use {@link Contact#sync} instead
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
634
   *
L
lijiarui 已提交
635
   * @deprecated
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
636
   * @private
L
lijiarui 已提交
637
   */
638
  public refresh (): Promise<void> {
639 640 641
    log.warn('Contact', 'refresh() DEPRECATED. use sync() instead.')
    return this.sync()
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
642 643

  /**
644
   * Force reload data for Contact, Sync data from lowlevel API again.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
645 646 647 648 649
   *
   * @returns {Promise<this>}
   * @example
   * await contact.sync()
   */
650
  public async sync (): Promise<void> {
651
    await this.ready(true)
652
  }
L
lijiarui 已提交
653

L
lijiarui 已提交
654
  /**
655 656 657 658 659
   * `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 已提交
660 661
   * @private
   */
662 663 664
  public async ready (
    forceSync = false,
  ): Promise<void> {
665
    log.silly('Contact', 'ready() @ %s', this.puppet)
666

667
    if (!forceSync && this.isReady()) { // already ready
668 669 670 671 672
      log.silly('Contact', 'ready() isReady() true')
      return
    }

    try {
673
      if (forceSync) {
674 675
        await this.puppet.contactPayloadDirty(this.id)
      }
676
      this.payload = await this.puppet.contactPayload(this.id)
677
      // log.silly('Contact', `ready() this.puppet.contactPayload(%s) resolved`, this)
678 679

    } catch (e) {
680
      log.verbose('Contact', `ready() this.puppet.contactPayload(%s) exception: %s`,
681 682 683 684 685 686 687
                            this,
                            e.message,
                )
      Raven.captureException(e)
      throw e
    }
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
688

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
689 690 691
  /**
   * @private
   */
692
  public isReady (): boolean {
693 694
    return !!(this.payload && this.payload.name)
  }
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
695

L
lijiarui 已提交
696 697 698 699 700 701 702
  /**
   * Check if contact is self
   *
   * @returns {boolean} True for contact is self, False for contact is others
   * @example
   * const isSelf = contact.self()
   */
703
  public self (): boolean {
704
    const userId = this.puppet.selfId()
705

706
    if (!userId) {
707 708 709
      return false
    }

710
    return this.id === userId
711
  }
712

L
lijiarui 已提交
713
  /**
L
lijiarui 已提交
714
   * Get the weixin number from a contact.
L
lijiarui 已提交
715
   *
L
lijiarui 已提交
716
   * Sometimes cannot get weixin number due to weixin security mechanism, not recommend.
L
lijiarui 已提交
717
   *
L
lijiarui 已提交
718 719
   * @private
   * @returns {string | null}
L
lijiarui 已提交
720
   * @example
L
lijiarui 已提交
721
   * const weixin = contact.weixin()
L
lijiarui 已提交
722
   */
723
  public weixin (): null | string {
724 725
    return this.payload && this.payload.weixin || null
  }
726
}