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

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

32
// import Message          from './message'
33

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

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
43
/**
L
lijiarui 已提交
44
 * All wechat contacts(friend) will be encapsulated as a Contact.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
45
 *
46
 * [Examples/Contact-Bot]{@link https://github.com/Chatie/wechaty/blob/master/examples/contact-bot.ts}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
47
 */
48
export class Contact extends Accessory implements Sayable {
49

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

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

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

    // 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.
108 109
    const newContact = new (this as any)(id) as Contact
    // newContact.payload = this.puppet.cacheContactPayload.get(id)
110

111
    this.pool.set(id, newContact)
112

113
    return newContact
114 115
  }

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

145
    const contactList = await this.findAll(query)
146 147 148 149 150

    if (!contactList) {
      return null
    }
    if (contactList.length < 1) {
L
lijiarui 已提交
151
      return null
152
    }
L
lijiarui 已提交
153 154

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

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

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

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

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

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

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

        batchIndex++
      }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
240
      return contactList.filter(contact => !(contact.id in invalidContactId))
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 249
  // TODO
  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 get payload(): undefined | ContactPayload {
260 261 262
    if (!this.id) {
      return undefined
    }
263 264
    return this.puppet.contactPayloadCache(this.id)
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
265

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

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

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

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

  /**
   * @private
   */
  public toString(): string {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
294 295 296 297
    const identity = this.payload
      ? this.payload.alias || this.payload.name || this.id
      : this.id
    return `Contact<${identity}>`
298 299
  }

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

  /**
L
lijiarui 已提交
305 306 307 308
   * @param {(string | Contact | FileBox)} textOrContactOrFile
   * send text, Contact, or file to contact. </br>
   * You can use {@link https://www.npmjs.com/package/file-box|FileBox} to send file
   * @returns {Promise<void>}
L
lijiarui 已提交
309
   * @example
L
lijiarui 已提交
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
   * 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
   *
   * # 1. send text to contact
   *
   * await contact.say('welcome to wechaty!')
   *
   * # 2. send media file to contact
   *
   * import { FileBox }  from 'file-box'
   * const fileBox1 = FileBox.fromUrl('https://chatie.io/wechaty/images/bot-qr-code.png')
   * const fileBox2 = FileBox.fromLocal('/tmp/text.txt')
   * await contact.say(fileBox1)
   * await contact.say(fileBox2)
   *
   * # 3. send contact card to contact
   *
   * const contactCard = bot.Contact.load('contactId')
   * await contact.say(contactCard)
L
lijiarui 已提交
330
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
331 332
  public async say(textOrContactOrFile: string | Contact | FileBox): Promise<void> {
    log.verbose('Contact', 'say(%s)', textOrContactOrFile)
333

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
334 335
    if (typeof textOrContactOrFile === 'string') {
      /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
336
       * 1. Text
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
337
       */
338 339
      await this.puppet.messageSendText({
        contactId: this.id,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
340 341 342
      }, textOrContactOrFile)
    } else if (textOrContactOrFile instanceof Contact) {
      /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
343
       * 2. Contact
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
344 345 346 347 348 349
       */
      await this.puppet.messageSendContact({
        contactId: this.id,
      }, textOrContactOrFile.id)
    } else if (textOrContactOrFile instanceof FileBox) {
      /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
350
       * 3. File
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
351
       */
352 353
      await this.puppet.messageSendFile({
        contactId: this.id,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
354
      }, textOrContactOrFile)
355
    } else {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
356
      throw new Error('unsupported')
357 358
    }
  }
L
lijiarui 已提交
359 360 361 362 363 364 365 366

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

371 372 373
  public alias()                  : null | string
  public alias(newAlias:  string) : Promise<void>
  public alias(empty:     null)   : Promise<void>
L
lijiarui 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
413 414 415 416
    if (!this.payload) {
      throw new Error('no payload')
    }

417 418 419 420
    if (typeof newAlias === 'undefined') {
      return this.payload && this.payload.alias || null
    }

421
    const future = this.puppet.contactAlias(this.id, newAlias)
422 423

    future
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
424
      .then(() => this.payload!.alias = (newAlias || undefined))
425 426 427 428 429 430 431
      .catch(e => {
        log.error('Contact', 'alias(%s) rejected: %s', newAlias, e.message)
        Raven.captureException(e)
      })

    return future
  }
L
lijiarui 已提交
432

L
lijiarui 已提交
433 434
  /**
   *
L
lijiarui 已提交
435 436
   * @description
   * Should use {@link Contact#friend} instead
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
437
   *
L
lijiarui 已提交
438
   * @deprecated
L
lijiarui 已提交
439
   */
440 441 442 443 444
  public stranger(): null | boolean {
    log.warn('Contact', 'stranger() DEPRECATED. use friend() instead.')
    if (!this.payload) return null
    return !this.friend()
  }
L
lijiarui 已提交
445

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
446 447 448
  /**
   * Check if contact is friend
   *
L
lijiarui 已提交
449 450 451 452
   * @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 (李卓桓) 已提交
453 454 455
   * @example
   * const isFriend = contact.friend()
   */
456 457 458 459 460 461 462
  public friend(): null | boolean {
    log.verbose('Contact', 'friend()')
    if (!this.payload) {
      return null
    }
    return this.payload.friend || null
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
463

J
Jas 已提交
464
  /**
L
lijiarui 已提交
465
   * @ignore
L
lijiarui 已提交
466 467
   * @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 已提交
468 469 470 471 472 473
   */
  /**
   * @description
   * Check if it's a offical account, should use {@link Contact#type} instead
   * @deprecated
   *
J
Jas 已提交
474
   */
475 476
  public official(): boolean {
    log.warn('Contact', 'official() DEPRECATED. use type() instead')
477
    return !!this.payload && this.payload.type === ContactType.Official
478
  }
J
Jas 已提交
479 480

  /**
L
lijiarui 已提交
481 482 483
   * @description
   * Check if it's a personal account, should use {@link Contact#type} instead
   * @deprecated
J
Jas 已提交
484
   */
485 486 487 488
  public personal(): boolean {
    log.warn('Contact', 'personal() DEPRECATED. use type() instead')
    return !this.official()
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
489

L
lijiarui 已提交
490 491 492 493 494 495 496 497
  /**
   * 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 (李卓桓) 已提交
498 499
  /**
   * Return the type of the Contact
L
lijiarui 已提交
500 501
   * > Tips: ContactType is enum here.</br>
   * @returns {ContactType.Unknown | ContactType.Personal | ContactType.Official}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
502 503
   *
   * @example
L
lijiarui 已提交
504 505 506
   * const bot = new Wechaty()
   * await bot.start()
   * const isOfficial = contact.type() === bot.Contact.Type.Official
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
507
   */
508 509 510
  public type(): ContactType {
    return this.payload!.type
  }
J
Jas 已提交
511

L
lijiarui 已提交
512
  /**
L
lijiarui 已提交
513 514
   * @private
   * TODO
L
lijiarui 已提交
515 516
   * Check if the contact is star contact.
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
517
   * @returns {boolean | null} - True for star friend, False for no star friend.
L
lijiarui 已提交
518 519 520
   * @example
   * const isStar = contact.star()
   */
521 522 523 524 525 526 527 528
  public star(): null | boolean {
    if (!this.payload) {
      return null
    }
    return this.payload.star === undefined
      ? null
      : this.payload.star
  }
L
lijiarui 已提交
529

530 531
  /**
   * Contact gender
L
lijiarui 已提交
532
   * > Tips: ContactGender is enum here. </br>
L
lijiarui 已提交
533
   *
L
lijiarui 已提交
534
   * @returns {ContactGender.Unknown | ContactGender.Male | ContactGender.Female}
L
lijiarui 已提交
535
   * @example
L
lijiarui 已提交
536
   * const gender = contact.gender() === bot.Contact.Gender.Male
L
lijiarui 已提交
537
   */
538
  public gender(): ContactGender {
539 540
    return this.payload
      ? this.payload.gender
541
      : ContactGender.Unknown
542
  }
L
lijiarui 已提交
543 544 545 546

  /**
   * Get the region 'province' from a contact
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
547
   * @returns {string | null}
L
lijiarui 已提交
548 549
   * @example
   * const province = contact.province()
550
   */
551 552 553
  public province(): null | string {
    return this.payload && this.payload.province || null
  }
L
lijiarui 已提交
554 555 556 557

  /**
   * Get the region 'city' from a contact
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
558
   * @returns {string | null}
L
lijiarui 已提交
559 560 561
   * @example
   * const city = contact.city()
   */
562 563 564
  public city(): null | string {
    return this.payload && this.payload.city || null
  }
565 566 567

  /**
   * Get avatar picture file stream
L
lijiarui 已提交
568
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
569
   * @returns {Promise<FileBox>}
L
lijiarui 已提交
570
   * @example
L
lijiarui 已提交
571 572 573 574 575 576
   * # Save avatar to local file like `1-name.jpg`
   *
   * const file = await contact.avatar()
   * const name = file.name
   * await file.toFile(name, true)
   * console.log(`Contact: ${contact.name()} with avatar file: ${name}`)
577
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
578
  public async avatar(): Promise<FileBox> {
579 580
    log.verbose('Contact', 'avatar()')

581
    return this.puppet.contactAvatar(this.id)
582
  }
583

L
lijiarui 已提交
584
  /**
L
lijiarui 已提交
585 586
   * @description
   * Force reload(re-ready()) data for Contact, use {@link Contact#sync} instead
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
587
   *
L
lijiarui 已提交
588
   * @deprecated
L
lijiarui 已提交
589
   */
590 591 592 593
  public refresh(): Promise<void> {
    log.warn('Contact', 'refresh() DEPRECATED. use sync() instead.')
    return this.sync()
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
594 595

  /**
L
lijiarui 已提交
596
   * Force reload(re-ready()) data for Contact,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
597 598 599 600 601
   *
   * @returns {Promise<this>}
   * @example
   * await contact.sync()
   */
602
  public async sync(): Promise<void> {
603
    await this.ready(true)
604
  }
L
lijiarui 已提交
605

L
lijiarui 已提交
606 607 608
  /**
   * @private
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
609
  public async ready(dirty = false): Promise<void> {
610
    log.silly('Contact', 'ready() @ %s', this.puppet)
611 612 613 614 615 616 617

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

    try {
618 619 620 621
      if (dirty) {
        await this.puppet.contactPayloadDirty(this.id)
      }
      await this.puppet.contactPayload(this.id)
622
      // log.silly('Contact', `ready() this.puppet.contactPayload(%s) resolved`, this)
623 624 625 626 627 628 629 630 631 632

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

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
634 635 636
  /**
   * @private
   */
637 638 639
  public isReady(): boolean {
    return !!(this.payload && this.payload.name)
  }
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
640

L
lijiarui 已提交
641 642 643 644 645 646 647
  /**
   * Check if contact is self
   *
   * @returns {boolean} True for contact is self, False for contact is others
   * @example
   * const isSelf = contact.self()
   */
648
  public self(): boolean {
649
    const userId = this.puppet.selfId()
650

651
    if (!userId) {
652 653 654
      return false
    }

655
    return this.id === userId
656
  }
657

L
lijiarui 已提交
658
  /**
L
lijiarui 已提交
659
   * Get the weixin number from a contact.
L
lijiarui 已提交
660
   *
L
lijiarui 已提交
661
   * Sometimes cannot get weixin number due to weixin security mechanism, not recommend.
L
lijiarui 已提交
662
   *
L
lijiarui 已提交
663 664
   * @private
   * @returns {string | null}
L
lijiarui 已提交
665
   * @example
L
lijiarui 已提交
666
   * const weixin = contact.weixin()
L
lijiarui 已提交
667
   */
668 669 670
  public weixin(): null | string {
    return this.payload && this.payload.weixin || null
  }
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
}

export class ContactSelf extends Contact {
  constructor(
    id: string,
  ) {
    super(id)
  }

  public async avatar()              : Promise<FileBox>
  public async avatar(file: FileBox) : Promise<void>

  public async avatar(file?: FileBox): Promise<void | FileBox> {
    log.verbose('Contact', 'avatar(%s)', file ? file.name : '')

    if (!file) {
      return await super.avatar()
    }

    if (this.id !== this.puppet.selfId()) {
      throw new Error('set avatar only available for user self')
    }

    await this.puppet.contactAvatar(this.id, file)
  }
696

697 698 699
  public async qrcode(): Promise<string> {
    log.verbose('Contact', 'qrcode()')

700
    if (this.id !== this.puppet.selfId()) {
701 702 703
      throw new Error('only can get qrcode for the login userself')
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
704
    return await this.puppet.contactQrcode(this.id)
705 706
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
707
}
708

Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
709
export default Contact