contact.ts 21.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'
Z
zhaoic 已提交
43
import { MiniProgram }  from './mini-program'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
44

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

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

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

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

H
hcz 已提交
75 76
  /**
   * @private
77
   * About the Generic: https://stackoverflow.com/q/43003970/1123955
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
78
   *
L
lijiarui 已提交
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
      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 (李卓桓) 已提交
172
        log.verbose('Contact', 'find() confirm contact[#%d] with id=%d is valid result, return it.',
173 174 175
          n,
          contact.id,
        )
176 177 178
        return contact
      } else {
        log.verbose('Contact', 'find() confirm contact[#%d] with id=%d is INVALID result, try next',
179 180 181
          n,
          contact.id,
        )
182
      }
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
   * const bot = new Wechaty()
   * await bot.start()
203 204 205
   * 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']>> {
211
    log.verbose('Contact', 'findAll(%s)', JSON.stringify(query) || '')
L
lijiarui 已提交
212 213

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

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

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

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

        batchIndex++
      }

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

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

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

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

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

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

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

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

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

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

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

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

  /**
308 309 310
   * > Tips:
   * This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/Chatie/wechaty/wiki/Puppet#3-puppet-compatible-table)
   *
Z
zhaoic 已提交
311
   * @param {(string | Contact | FileBox | UrlLink | MiniProgram)} textOrContactOrFileOrUrlOrMini
L
lijiarui 已提交
312 313 314
   * 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 已提交
315
   * @example
L
lijiarui 已提交
316 317 318 319
   * 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 已提交
320
   * // 1. send text to contact
L
lijiarui 已提交
321 322 323
   *
   * await contact.say('welcome to wechaty!')
   *
L
lijiarui 已提交
324
   * // 2. send media file to contact
L
lijiarui 已提交
325 326 327
   *
   * import { FileBox }  from 'file-box'
   * const fileBox1 = FileBox.fromUrl('https://chatie.io/wechaty/images/bot-qr-code.png')
328
   * const fileBox2 = FileBox.fromFile('/tmp/text.txt')
L
lijiarui 已提交
329 330 331
   * await contact.say(fileBox1)
   * await contact.say(fileBox2)
   *
L
lijiarui 已提交
332
   * // 3. send contact card to contact
L
lijiarui 已提交
333 334 335
   *
   * const contactCard = bot.Contact.load('contactId')
   * await contact.say(contactCard)
336 337 338 339
   *
   * // 4. send url link to contact
   *
   * const urlLink = new UrlLink ({
L
linyimin 已提交
340 341 342 343
   *   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',
344 345
   * })
   * await contact.say(urlLink)
Z
zhaoic 已提交
346 347 348 349 350 351 352 353 354 355 356 357
   *
   * // 5. send mini program to contact
   *
   * const miniProgram = new MiniProgram ({
   *   username           : 'gh_xxxxxxx',     //get from mp.weixin.qq.com
   *   appid              : '',               //optional, get from mp.weixin.qq.com
   *   title              : '',               //optional
   *   pagepath           : '',               //optional
   *   description        : '',               //optional
   *   thumbnailurl       : '',               //optional
   * })
   * await contact.say(miniProgram)
L
lijiarui 已提交
358
   */
Z
zhaoic 已提交
359 360
  public async say (textOrContactOrFileOrUrlOrMini: string | Contact | FileBox | UrlLink | MiniProgram): Promise<void> {
    log.verbose('Contact', 'say(%s)', textOrContactOrFileOrUrlOrMini)
361

Z
zhaoic 已提交
362
    if (typeof textOrContactOrFileOrUrlOrMini === 'string') {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
363
      /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
364
       * 1. Text
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
365
       */
366 367
      await this.puppet.messageSendText({
        contactId: this.id,
Z
zhaoic 已提交
368 369
      }, textOrContactOrFileOrUrlOrMini)
    } else if (textOrContactOrFileOrUrlOrMini instanceof Contact) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
370
      /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
371
       * 2. Contact
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
372 373 374
       */
      await this.puppet.messageSendContact({
        contactId: this.id,
Z
zhaoic 已提交
375 376
      }, textOrContactOrFileOrUrlOrMini.id)
    } else if (textOrContactOrFileOrUrlOrMini instanceof FileBox) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
377
      /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
378
       * 3. File
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
379
       */
380 381
      await this.puppet.messageSendFile({
        contactId: this.id,
Z
zhaoic 已提交
382 383
      }, textOrContactOrFileOrUrlOrMini)
    } else if (textOrContactOrFileOrUrlOrMini instanceof UrlLink) {
384 385 386 387
      /**
       * 4. Link Message
       */
      await this.puppet.messageSendUrl({
388
        contactId : this.id,
Z
zhaoic 已提交
389 390 391 392 393 394 395 396
      }, textOrContactOrFileOrUrlOrMini.payload)
    } else if (textOrContactOrFileOrUrlOrMini instanceof MiniProgram) {
      /**
       * 5. Mini Program
       */
      await this.puppet.messageSendMiniProgram({
        contactId : this.id,
      }, textOrContactOrFileOrUrlOrMini.payload)
397
    } else {
Z
zhaoic 已提交
398
      throw new Error('unsupported arg: ' + textOrContactOrFileOrUrlOrMini)
399 400
    }
  }
L
lijiarui 已提交
401 402 403 404 405 406 407 408

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

413 414 415
  public async alias ()                  : Promise<null | string>
  public async alias (newAlias:  string) : Promise<void>
  public async alias (empty:     null)   : Promise<void>
L
lijiarui 已提交
416 417 418 419 420 421

  /**
   * 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
422 423 424
   * @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 已提交
425 426 427 428 429 430 431
   * 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 (李卓桓) 已提交
432 433
   * try {
   *   await contact.alias('lijiarui')
L
lijiarui 已提交
434
   *   console.log(`change ${contact.name()}'s alias successfully!`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
435
   * } catch (e) {
L
lijiarui 已提交
436 437 438 439
   *   console.log(`failed to change ${contact.name()} alias!`)
   * }
   *
   * @example <caption>DELETE the alias for a contact</caption>
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
440 441
   * try {
   *   const oldAlias = await contact.alias(null)
L
lijiarui 已提交
442
   *   console.log(`delete ${contact.name()}'s alias successfully!`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
443 444
   *   console.log('old alias is ${oldAlias}`)
   * } catch (e) {
L
lijiarui 已提交
445 446 447
   *   console.log(`failed to delete ${contact.name()}'s alias!`)
   * }
   */
448
  public async alias (newAlias?: null | string): Promise<null | string | void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
449
    log.silly('Contact', 'alias(%s)',
450 451 452 453
      newAlias === undefined
        ? ''
        : newAlias,
    )
454

455 456 457 458
    if (!this.payload) {
      throw new Error('no payload')
    }

459
    if (typeof newAlias === 'undefined') {
460
      return this.payload.alias || null
461 462
    }

463 464
    try {
      await this.puppet.contactAlias(this.id, newAlias)
465 466 467
      await this.puppet.contactPayloadDirty(this.id)
      this.payload = await this.puppet.contactPayload(this.id)
      if (newAlias && newAlias !== this.payload.alias) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
468
        log.warn('Contact', 'alias(%s) sync with server fail: set(%s) is not equal to get(%s)',
469 470 471
          newAlias,
          this.payload.alias,
        )
472
      }
473 474 475 476
    } catch (e) {
      log.error('Contact', 'alias(%s) rejected: %s', newAlias, e.message)
      Raven.captureException(e)
    }
477
  }
L
lijiarui 已提交
478

L
lijiarui 已提交
479 480
  /**
   *
L
lijiarui 已提交
481 482
   * @description
   * Should use {@link Contact#friend} instead
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
483
   *
L
lijiarui 已提交
484
   * @deprecated
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
485
   * @private
L
lijiarui 已提交
486
   */
487
  public stranger (): null | boolean {
488 489 490 491
    log.warn('Contact', 'stranger() DEPRECATED. use friend() instead.')
    if (!this.payload) return null
    return !this.friend()
  }
L
lijiarui 已提交
492

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
493 494 495
  /**
   * Check if contact is friend
   *
496 497 498
   * > 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 已提交
499 500 501 502
   * @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 (李卓桓) 已提交
503 504 505
   * @example
   * const isFriend = contact.friend()
   */
506
  public friend (): null | boolean {
507 508 509 510 511 512
    log.verbose('Contact', 'friend()')
    if (!this.payload) {
      return null
    }
    return this.payload.friend || null
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
513

J
Jas 已提交
514
  /**
L
lijiarui 已提交
515
   * @ignore
L
lijiarui 已提交
516 517
   * @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 已提交
518 519 520 521 522
   */
  /**
   * @description
   * Check if it's a offical account, should use {@link Contact#type} instead
   * @deprecated
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
523
   * @private
J
Jas 已提交
524
   */
525
  public official (): boolean {
526
    log.warn('Contact', 'official() DEPRECATED. use type() instead')
527
    return !!this.payload && (this.payload.type === ContactType.Official)
528
  }
J
Jas 已提交
529 530

  /**
L
lijiarui 已提交
531 532 533
   * @description
   * Check if it's a personal account, should use {@link Contact#type} instead
   * @deprecated
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
534
   * @private
J
Jas 已提交
535
   */
536
  public personal (): boolean {
537
    log.warn('Contact', 'personal() DEPRECATED. use type() instead')
538
    return !!this.payload && this.payload.type === ContactType.Personal
539
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
540

L
lijiarui 已提交
541 542 543 544 545 546 547 548
  /**
   * 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 (李卓桓) 已提交
549 550
  /**
   * Return the type of the Contact
L
lijiarui 已提交
551 552
   * > Tips: ContactType is enum here.</br>
   * @returns {ContactType.Unknown | ContactType.Personal | ContactType.Official}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
553 554
   *
   * @example
L
lijiarui 已提交
555 556 557
   * const bot = new Wechaty()
   * await bot.start()
   * const isOfficial = contact.type() === bot.Contact.Type.Official
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
558
   */
559 560 561 562 563
  public type (): ContactType {
    if (!this.payload) {
      throw new Error('no payload')
    }
    return this.payload.type
564
  }
J
Jas 已提交
565

L
lijiarui 已提交
566
  /**
L
lijiarui 已提交
567 568
   * @private
   * TODO
L
lijiarui 已提交
569 570
   * Check if the contact is star contact.
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
571
   * @returns {boolean | null} - True for star friend, False for no star friend.
L
lijiarui 已提交
572 573 574
   * @example
   * const isStar = contact.star()
   */
575
  public star (): null | boolean {
576 577 578 579 580 581 582
    if (!this.payload) {
      return null
    }
    return this.payload.star === undefined
      ? null
      : this.payload.star
  }
L
lijiarui 已提交
583

584 585
  /**
   * Contact gender
L
lijiarui 已提交
586
   * > Tips: ContactGender is enum here. </br>
L
lijiarui 已提交
587
   *
L
lijiarui 已提交
588
   * @returns {ContactGender.Unknown | ContactGender.Male | ContactGender.Female}
L
lijiarui 已提交
589
   * @example
L
lijiarui 已提交
590
   * const gender = contact.gender() === bot.Contact.Gender.Male
L
lijiarui 已提交
591
   */
592
  public gender (): ContactGender {
593 594
    return this.payload
      ? this.payload.gender
595
      : ContactGender.Unknown
596
  }
L
lijiarui 已提交
597 598 599 600

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

  /**
   * Get the region 'city' from a contact
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
612
   * @returns {string | null}
L
lijiarui 已提交
613 614 615
   * @example
   * const city = contact.city()
   */
616
  public city (): null | string {
617
    return (this.payload && this.payload.city) || null
618
  }
619 620 621

  /**
   * Get avatar picture file stream
L
lijiarui 已提交
622
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
623
   * @returns {Promise<FileBox>}
L
lijiarui 已提交
624
   * @example
L
lijiarui 已提交
625
   * // Save avatar to local file like `1-name.jpg`
L
lijiarui 已提交
626 627 628 629 630
   *
   * const file = await contact.avatar()
   * const name = file.name
   * await file.toFile(name, true)
   * console.log(`Contact: ${contact.name()} with avatar file: ${name}`)
631
   */
632
  public async avatar (): Promise<FileBox> {
633 634
    log.verbose('Contact', 'avatar()')

635 636 637 638 639 640 641
    try {
      const fileBox = await this.puppet.contactAvatar(this.id)
      return fileBox
    } catch (e) {
      log.error('Contact', 'avatar() exception: %s', e.message)
      return qrCodeForChatie()
    }
642
  }
643

L
lijiarui 已提交
644
  /**
L
lijiarui 已提交
645 646
   * @description
   * Force reload(re-ready()) data for Contact, use {@link Contact#sync} instead
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
647
   *
L
lijiarui 已提交
648
   * @deprecated
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
649
   * @private
L
lijiarui 已提交
650
   */
651
  public refresh (): Promise<void> {
652 653 654
    log.warn('Contact', 'refresh() DEPRECATED. use sync() instead.')
    return this.sync()
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
655 656

  /**
657
   * Force reload data for Contact, Sync data from lowlevel API again.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
658 659 660 661 662
   *
   * @returns {Promise<this>}
   * @example
   * await contact.sync()
   */
663
  public async sync (): Promise<void> {
664
    await this.ready(true)
665
  }
L
lijiarui 已提交
666

L
lijiarui 已提交
667
  /**
668 669 670 671 672
   * `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 已提交
673 674
   * @private
   */
675 676 677
  public async ready (
    forceSync = false,
  ): Promise<void> {
678
    log.silly('Contact', 'ready() @ %s', this.puppet)
679

680
    if (!forceSync && this.isReady()) { // already ready
681 682 683 684 685
      log.silly('Contact', 'ready() isReady() true')
      return
    }

    try {
686
      if (forceSync) {
687 688
        await this.puppet.contactPayloadDirty(this.id)
      }
689
      this.payload = await this.puppet.contactPayload(this.id)
690
      // log.silly('Contact', `ready() this.puppet.contactPayload(%s) resolved`, this)
691 692

    } catch (e) {
693
      log.verbose('Contact', `ready() this.puppet.contactPayload(%s) exception: %s`,
694 695 696
        this,
        e.message,
      )
697 698 699 700
      Raven.captureException(e)
      throw e
    }
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
701

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
702 703 704
  /**
   * @private
   */
705
  public isReady (): boolean {
706 707
    return !!(this.payload && this.payload.name)
  }
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
708

L
lijiarui 已提交
709 710 711 712 713 714 715
  /**
   * Check if contact is self
   *
   * @returns {boolean} True for contact is self, False for contact is others
   * @example
   * const isSelf = contact.self()
   */
716
  public self (): boolean {
717
    const userId = this.puppet.selfId()
718

719
    if (!userId) {
720 721 722
      return false
    }

723
    return this.id === userId
724
  }
725

L
lijiarui 已提交
726
  /**
L
lijiarui 已提交
727
   * Get the weixin number from a contact.
L
lijiarui 已提交
728
   *
L
lijiarui 已提交
729
   * Sometimes cannot get weixin number due to weixin security mechanism, not recommend.
L
lijiarui 已提交
730
   *
L
lijiarui 已提交
731 732
   * @private
   * @returns {string | null}
L
lijiarui 已提交
733
   * @example
L
lijiarui 已提交
734
   * const weixin = contact.weixin()
L
lijiarui 已提交
735
   */
736
  public weixin (): null | string {
737
    return (this.payload && this.payload.weixin) || null
738
  }
739

740
}