contact.ts 21.6 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 {
21
  // config,
22
  Raven,
L
lijiarui 已提交
23
  Sayable,
24
  log,
25
}                       from './config'
M
Mukaiu 已提交
26 27 28
import {
  Message,
  MediaMessage,
29 30 31 32 33 34
}                       from './message'
import Misc             from './misc'
import PuppetAccessory  from './puppet-accessory'
import Wechaty          from './wechaty'

import PuppetWeb        from './puppet-web/'
35

36
export interface ContactObj {
L
lijiarui 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49
  address:    string,
  city:       string,
  id:         string,
  name:       string,
  province:   string,
  alias:      string|null,
  sex:        Gender,
  signature:  string,
  star:       boolean,
  stranger:   boolean,
  uin:        string,
  weixin:     string,
  avatar:     string,  // XXX URL of HeadImgUrl
J
Jas 已提交
50 51
  official:   boolean,
  special:    boolean,
52 53
}

54
export interface ContactRawObj {
L
lijiarui 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67
  Alias:        string,
  City:         string,
  NickName:     string,
  Province:     string,
  RemarkName:   string,
  Sex:          Gender,
  Signature:    string,
  StarFriend:   string,
  Uin:          string,
  UserName:     string,
  HeadImgUrl:   string,

  stranger:     string, // assign by injectio.js
J
Jas 已提交
68
  VerifyFlag:   number,
69 70
}

L
lijiarui 已提交
71 72
/**
 * Enum for Gender values.
L
lijiarui 已提交
73
 *
L
lijiarui 已提交
74
 * @enum {number}
L
lijiarui 已提交
75 76 77
 * @property {number} Unknown   - 0 for Unknown
 * @property {number} Male      - 1 for Male
 * @property {number} Female    - 2 for Female
L
lijiarui 已提交
78
 */
79 80 81 82 83 84
export enum Gender {
  Unknown = 0,
  Male    = 1,
  Female  = 2,
}

85
export interface ContactQueryFilter {
L
lijiarui 已提交
86 87
  name?:   string | RegExp,
  alias?:  string | RegExp,
88
  // remark is DEPRECATED
L
lijiarui 已提交
89
  remark?: string | RegExp,
90 91
}

J
Jas 已提交
92 93
/**
 * @see https://github.com/Chatie/webwx-app-tracker/blob/7c59d35c6ea0cff38426a4c5c912a086c4c512b2/formatted/webwxApp.js#L3848
L
lijiarui 已提交
94
 * @ignore
J
Jas 已提交
95 96 97 98 99 100 101 102
 */
const specialContactList: string[] = [
  'weibo', 'qqmail', 'fmessage', 'tmessage', 'qmessage', 'qqsync', 'floatbottle',
  'lbsapp', 'shakeapp', 'medianote', 'qqfriend', 'readerapp', 'blogapp', 'facebookapp',
  'masssendapp', 'meishiapp', 'feedsapp', 'voip', 'blogappweixin', 'weixin', 'brandsessionholder',
  'weixinreminder', 'wxid_novlwrv3lqwv11', 'gh_22b87fa7cb3c', 'officialaccounts', 'notification_messages',
]

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
103
/**
L
lijiarui 已提交
104
 * All wechat contacts(friend) will be encapsulated as a Contact.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
105
 *
L
lijiarui 已提交
106
 * `Contact` is `Sayable`,
107
 * [Examples/Contact-Bot]{@link https://github.com/Chatie/wechaty/blob/master/examples/contact-bot.ts}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
108
 */
109
export class Contact extends PuppetAccessory implements Sayable {
110 111
  private static pool = new Map<string, Contact>()

112
  public obj: ContactObj | null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
113
  // private dirtyObj: ContactObj | null
114 115
  private rawObj: ContactRawObj

H
hcz 已提交
116 117 118
  /**
   * @private
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
119 120 121
  constructor(
    public readonly id: string,
  ) {
122
    super()
123
    log.silly('Contact', `constructor(${id})`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
124

125 126 127
    if (typeof id !== 'string') {
      throw new Error('id must be string. found: ' + typeof id)
    }
128 129
  }

L
lijiarui 已提交
130 131 132
  /**
   * @private
   */
133 134
  public toString(): string {
    if (!this.obj) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
135
      return `Contact<this.id>`
136
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
137 138 139
    const obj  = this.obj
    const name = obj.alias || obj.name || this.id
    return `Contact<${name}>`
140 141
  }

L
lijiarui 已提交
142 143 144
  /**
   * @private
   */
145
  public toStringEx() { return `Contact(${this.obj && this.obj.name}[${this.id}])` }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
146

L
lijiarui 已提交
147 148 149
  /**
   * @private
   */
150
  private parse(rawObj: ContactRawObj): ContactObj | null {
151
    if (!rawObj || !rawObj.UserName) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
152 153 154
      log.warn('Contact', 'parse() got empty rawObj!')
      // config.puppetInstance().emit('error', e)
      return null
155 156
    }

157
    return !rawObj ? null : {
L
lijiarui 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
      id:         rawObj.UserName, // MMActualSender??? MMPeerUserName??? `getUserContact(message.MMActualSender,message.MMPeerUserName).HeadImgUrl`
      uin:        rawObj.Uin,    // stable id: 4763975 || getCookie("wxuin")
      weixin:     rawObj.Alias,  // Wechat ID
      name:       rawObj.NickName,
      alias:      rawObj.RemarkName,
      sex:        rawObj.Sex,
      province:   rawObj.Province,
      city:       rawObj.City,
      signature:  rawObj.Signature,

      address:    rawObj.Alias, // XXX: need a stable address for user

      star:       !!rawObj.StarFriend,
      stranger:   !!rawObj.stranger, // assign by injectio.js
      avatar:     rawObj.HeadImgUrl,
J
Jas 已提交
173 174 175
      /**
       * @see 1. https://github.com/Chatie/webwx-app-tracker/blob/7c59d35c6ea0cff38426a4c5c912a086c4c512b2/formatted/webwxApp.js#L3243
       * @see 2. https://github.com/Urinx/WeixinBot/blob/master/README.md
L
lijiarui 已提交
176
       * @ignore
J
Jas 已提交
177 178 179 180 181
       */
      // tslint:disable-next-line
      official:      !!rawObj.UserName && !rawObj.UserName.startsWith('@@') && !!(rawObj.VerifyFlag & 8),
      /**
       * @see 1. https://github.com/Chatie/webwx-app-tracker/blob/7c59d35c6ea0cff38426a4c5c912a086c4c512b2/formatted/webwxApp.js#L3246
L
lijiarui 已提交
182
       * @ignore
J
Jas 已提交
183 184
       */
      special:       specialContactList.indexOf(rawObj.UserName) > -1 || /@qqim$/.test(rawObj.UserName),
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
185 186
    }
  }
187

L
lijiarui 已提交
188
  /**
L
lijiarui 已提交
189
   * The way to search Contact
L
lijiarui 已提交
190
   *
L
lijiarui 已提交
191 192 193 194 195 196 197 198
   * @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 已提交
199
   *
L
lijiarui 已提交
200 201 202 203 204
   * 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 已提交
205
   * @example
L
lijiarui 已提交
206 207
   * const contactFindByName = await Contact.find({ name:"ruirui"} )
   * const contactFindByAlias = await Contact.find({ alias:"lijiarui"} )
L
lijiarui 已提交
208
   */
L
lijiarui 已提交
209 210 211
  public static async find(query: ContactQueryFilter): Promise<Contact | null> {
    log.verbose('Contact', 'find(%s)', JSON.stringify(query))

212
    const contactList = await this.findAll(query)
L
lijiarui 已提交
213 214
    if (!contactList || !contactList.length) {
      return null
215
    }
L
lijiarui 已提交
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282

    if (contactList.length > 1) {
      log.warn('Contact', 'function find(%s) get %d contacts, use the first one by default', JSON.stringify(query), contactList.length)
    }
    return contactList[0]
  }

  /**
   * 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
   * const contactList = await Contact.findAll()                    // get the contact list of the bot
   * const contactList = await Contact.findAll({name: 'ruirui'})    // find allof the contacts whose name is 'ruirui'
   * const contactList = await Contact.findAll({alias: 'lijiarui'}) // find all of the contacts whose alias is 'lijiarui'
   */
  public static async findAll(queryArg?: ContactQueryFilter): Promise<Contact[]> {
    let query: ContactQueryFilter
    if (queryArg) {
      if (queryArg.remark) {
        log.warn('Contact', 'Contact.findAll({remark:%s}) DEPRECATED, use Contact.findAll({alias:%s}) instead.', queryArg.remark, queryArg.remark)
        query = { alias: queryArg.remark}
      } else {
        query = queryArg
      }
    } else {
      query = { name: /.*/ }
    }

    // log.verbose('Cotnact', 'findAll({ name: %s })', query.name)
    log.verbose('Cotnact', 'findAll({ %s })',
                            Object.keys(query)
                                  .map(k => `${k}: ${query[k]}`)
                                  .join(', '),
              )

    if (Object.keys(query).length !== 1) {
      throw new Error('query only support one key. multi key support is not availble now.')
    }

    let filterKey                     = Object.keys(query)[0]
    let filterValue: string | RegExp  = query[filterKey]

    const keyMap = {
      name:   'NickName',
      alias:  'RemarkName',
    }

    filterKey = keyMap[filterKey]
    if (!filterKey) {
      throw new Error('unsupport filter key')
    }

    if (!filterValue) {
      throw new Error('filterValue not found')
    }

    /**
     * must be string because we need inject variable value
283
     * into code as variable namespecialContactList
L
lijiarui 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296
     */
    let filterFunction: string

    if (filterValue instanceof RegExp) {
      filterFunction = `(function (c) { return ${filterValue.toString()}.test(c.${filterKey}) })`
    } else if (typeof filterValue === 'string') {
      filterValue = filterValue.replace(/'/g, '\\\'')
      filterFunction = `(function (c) { return c.${filterKey} === '${filterValue}' })`
    } else {
      throw new Error('unsupport name type')
    }

    try {
297
      const contactList = await this.puppet // config.puppetInstance()
L
lijiarui 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
                                  .contactFind(filterFunction)

      await Promise.all(contactList.map(c => c.ready()))
      return contactList

    } catch (e) {
      log.error('Contact', 'findAll() rejected: %s', e.message)
      return [] // fail safe
    }
  }

  /**
   * Sent Text to contact
   *
   * @param {string} text
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
314
  public async say(text: string): Promise<boolean>
L
lijiarui 已提交
315 316 317 318 319 320 321

  /**
   * Send Media File to Contact
   *
   * @param {MediaMessage} mediaMessage
   * @memberof Contact
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
322
  public async say(mediaMessage: MediaMessage): Promise<boolean>
L
lijiarui 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357

  /**
   * Send Text or Media File to Contact.
   *
   * @param {(string | MediaMessage)} textOrMedia
   * @returns {Promise<boolean>}
   * @example
   * const contact = await Contact.find({name: 'lijiarui'})         // change 'lijiarui' to any of your contact name in wechat
   * await contact.say('welcome to wechaty!')
   * await contact.say(new MediaMessage(__dirname + '/wechaty.png') // put the filePath you want to send here
   */
  public async say(textOrMedia: string | MediaMessage): Promise<boolean> {
    const content = textOrMedia instanceof MediaMessage ? textOrMedia.filename() : textOrMedia
    log.verbose('Contact', 'say(%s)', content)

    const bot = Wechaty.instance()
    const user = bot.self()

    if (!user) {
      throw new Error('no user')
    }
    let m
    if (typeof textOrMedia === 'string') {
      m = new Message()
      m.content(textOrMedia)
    } else if (textOrMedia instanceof MediaMessage) {
      m = textOrMedia
    } else {
      throw new Error('not support args')
    }
    m.from(user)
    m.to(this)
    log.silly('Contact', 'say() from: %s to: %s content: %s', user.name(), this.name(), content)

    return await bot.send(m)
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
  public name()     { return Misc.plainText(this.obj && this.obj.name || '') }
L
lijiarui 已提交
368

L
lijiarui 已提交
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
  public alias(): string | null

  public alias(newAlias: string): Promise<boolean>

  public alias(empty: null): Promise<boolean>

  /**
   * 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>
   * const ret = await contact.alias('lijiarui')
   * if (ret) {
   *   console.log(`change ${contact.name()}'s alias successfully!`)
   * } else {
   *   console.log(`failed to change ${contact.name()} alias!`)
   * }
   *
   * @example <caption>DELETE the alias for a contact</caption>
   * const ret = await contact.alias(null)
   * if (ret) {
   *   console.log(`delete ${contact.name()}'s alias successfully!`)
   * } else {
   *   console.log(`failed to delete ${contact.name()}'s alias!`)
   * }
   */
  public alias(newAlias?: string|null): Promise<boolean> | string | null {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
406
    // log.silly('Contact', 'alias(%s)', newAlias || '')
L
lijiarui 已提交
407 408 409 410 411

    if (newAlias === undefined) {
      return this.obj && this.obj.alias || null
    }

412 413 414 415 416 417
    return this.puppet // config.puppetInstance()
                .contactAlias(this, newAlias)
                .then(ret => {
                  if (ret) {
                    if (this.obj) {
                      this.obj.alias = newAlias
L
lijiarui 已提交
418
                    } else {
419
                      log.error('Contact', 'alias() without this.obj?')
L
lijiarui 已提交
420
                    }
421 422 423 424 425 426 427 428 429 430
                  } else {
                    log.warn('Contact', 'alias(%s) fail', newAlias)
                  }
                  return ret
                })
                .catch(e => {
                  log.error('Contact', 'alias(%s) rejected: %s', newAlias, e.message)
                  Raven.captureException(e)
                  return false // fail safe
                })
L
lijiarui 已提交
431 432
  }

L
lijiarui 已提交
433 434 435
  /**
   * Check if contact is stranger
   *
L
lijiarui 已提交
436
   * @returns {boolean | null} - True for not friend of the bot, False for friend of the bot, null for unknown.
L
lijiarui 已提交
437 438 439 440 441 442 443 444
   * @example
   * const isStranger = contact.stranger()
   */
  public stranger(): boolean|null {
    if (!this.obj) return null
    return this.obj.stranger
  }

J
Jas 已提交
445 446 447
  /**
   * Check if it's a offical account
   *
L
lijiarui 已提交
448 449 450
   * @returns {boolean|null} - True for official account, Flase for contact is not a official account, null for unknown
   * @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}
J
Jas 已提交
451 452 453 454 455 456 457 458 459 460
   * @example
   * const isOfficial = contact.official()
   */
  public official(): boolean {
    return !!this.obj && this.obj.official
  }

  /**
   * Check if it's a special contact
   *
L
lijiarui 已提交
461 462 463 464 465
   * The contact who's id in following list will be identify as a special contact
   * `weibo`, `qqmail`, `fmessage`, `tmessage`, `qmessage`, `qqsync`, `floatbottle`,
   * `lbsapp`, `shakeapp`, `medianote`, `qqfriend`, `readerapp`, `blogapp`, `facebookapp`,
   * `masssendapp`, `meishiapp`, `feedsapp`, `voip`, `blogappweixin`, `weixin`, `brandsessionholder`,
   * `weixinreminder`, `wxid_novlwrv3lqwv11`, `gh_22b87fa7cb3c`, `officialaccounts`, `notification_messages`,
J
Jas 已提交
466
   *
L
lijiarui 已提交
467 468
   * @see {@link https://github.com/Chatie/webwx-app-tracker/blob/7c59d35c6ea0cff38426a4c5c912a086c4c512b2/formatted/webwxApp.js#L3848|webwxApp.js#L3848}
   * @see {@link https://github.com/Chatie/webwx-app-tracker/blob/7c59d35c6ea0cff38426a4c5c912a086c4c512b2/formatted/webwxApp.js#L3246|webwxApp.js#L3246}
J
Jas 已提交
469 470 471 472 473 474 475 476 477 478 479
   * @returns {boolean|null} True for brand, Flase for contact is not a brand
   * @example
   * const isSpecial = contact.special()
   */
  public special(): boolean {
    return !!this.obj && this.obj.special
  }

  /**
   * Check if it's a personal account
   *
L
lijiarui 已提交
480
   * @returns {boolean|null} - True for personal account, Flase for contact is not a personal account
J
Jas 已提交
481 482 483 484 485 486 487
   * @example
   * const isPersonal = contact.personal()
   */
  public personal(): boolean {
    return !this.official()
  }

L
lijiarui 已提交
488 489 490
  /**
   * Check if the contact is star contact.
   *
L
lijiarui 已提交
491
   * @returns {boolean} - True for star friend, False for no star friend.
L
lijiarui 已提交
492 493 494 495 496 497 498 499
   * @example
   * const isStar = contact.star()
   */
  public star(): boolean|null {
    if (!this.obj) return null
    return this.obj.star
  }

500 501
  /**
   * Contact gender
L
lijiarui 已提交
502
   *
L
lijiarui 已提交
503
   * @returns {Gender.Male(2)|Gender.Female(1)|Gender.Unknown(0)}
L
lijiarui 已提交
504 505 506 507 508 509 510 511 512 513 514
   * @example
   * const gender = contact.gender()
   */
  public gender(): Gender   { return this.obj ? this.obj.sex : Gender.Unknown }

  /**
   * Get the region 'province' from a contact
   *
   * @returns {string | undefined}
   * @example
   * const province = contact.province()
515 516
   */
  public province() { return this.obj && this.obj.province }
L
lijiarui 已提交
517 518 519 520 521 522 523 524

  /**
   * Get the region 'city' from a contact
   *
   * @returns {string | undefined}
   * @example
   * const city = contact.city()
   */
525 526 527 528
  public city()     { return this.obj && this.obj.city }

  /**
   * Get avatar picture file stream
L
lijiarui 已提交
529 530 531 532 533 534 535 536
   *
   * @returns {Promise<NodeJS.ReadableStream>}
   * @example
   * const avatarFileName = contact.name() + `.jpg`
   * const avatarReadStream = await contact.avatar()
   * const avatarWriteStream = createWriteStream(avatarFileName)
   * avatarReadStream.pipe(avatarWriteStream)
   * log.info('Bot', 'Contact: %s: %s with avatar file: %s', contact.weixin(), contact.name(), avatarFileName)
537 538
   */
  public async avatar(): Promise<NodeJS.ReadableStream> {
539 540
    log.verbose('Contact', 'avatar()')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
541 542 543 544
    if (!this.obj) {
      throw new Error('Can not get avatar: no this.obj!')
    } else if (!this.obj.avatar) {
      throw new Error('Can not get avatar: no this.obj.avatar!')
545 546 547
    }

    try {
548
      const hostname = await (/* config.puppetInstance() */ this.puppet as PuppetWeb ).hostname()
549
      const avatarUrl = `http://${hostname}${this.obj.avatar}&type=big` // add '&type=big' to get big image
550
      const cookies = await (/* config.puppetInstance() */ this.puppet as PuppetWeb).cookies()
551 552
      log.silly('Contact', 'avatar() url: %s', avatarUrl)

553
      return Misc.urlStream(avatarUrl, cookies)
554 555
    } catch (err) {
      log.warn('Contact', 'avatar() exception: %s', err.stack)
556
      Raven.captureException(err)
557
      throw err
558 559
    }
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
560

L
lijiarui 已提交
561 562 563
  /**
   * @private
   */
564
  public get(prop)  { return this.obj && this.obj[prop] }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
565

L
lijiarui 已提交
566 567 568
  /**
   * @private
   */
569
  public isReady(): boolean {
570
    return !!(this.obj && this.obj.id && this.obj.name)
571 572
  }

L
lijiarui 已提交
573 574 575 576 577 578 579
  /**
   * Force reload data for Contact
   *
   * @returns {Promise<this>}
   * @example
   * await contact.refresh()
   */
580
  public async refresh(): Promise<this> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
581 582 583 584
    // TODO: make sure the contact.* works when we are refreshing the data
    // if (this.isReady()) {
    //   this.dirtyObj = this.obj
    // }
585
    this.obj = null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
586 587
    await this.ready()
    return this
588 589
  }

L
lijiarui 已提交
590 591 592
  /**
   * @private
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
593
  public async ready(contactGetter?: (id: string) => Promise<ContactRawObj>): Promise<this> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
594
    // log.silly('Contact', 'ready(' + (contactGetter ? typeof contactGetter : '') + ')')
595
    if (!this.id) {
596 597
      const e = new Error('ready() call on an un-inited contact')
      throw e
598
    }
599

600
    if (this.isReady()) { // already ready
601 602
      return Promise.resolve(this)
    }
603 604

    if (!contactGetter) {
605 606 607
      log.silly('Contact', 'get contact via ' + /* config.puppetInstance() */ this.puppet.constructor.name)
      contactGetter = /* config.puppetInstance() */ this.puppet
                            .getContact.bind(/* config.puppetInstance() */ this.puppet)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
608
    }
609 610 611
    if (!contactGetter) {
      throw new Error('no contatGetter')
    }
612

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
613 614 615 616 617 618
    try {
      const rawObj = await contactGetter(this.id)
      log.silly('Contact', `contactGetter(${this.id}) resolved`)
      this.rawObj = rawObj
      this.obj    = this.parse(rawObj)
      return this
619

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
620 621
    } catch (e) {
      log.error('Contact', `contactGetter(${this.id}) exception: %s`, e.message)
622
      Raven.captureException(e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
623
      throw e
624 625 626
    }
  }

L
lijiarui 已提交
627 628 629
  /**
   * @private
   */
630
  public dumpRaw() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
631
    console.error('======= dump raw contact =======')
632
    Object.keys(this.rawObj).forEach(k => console.error(`${k}: ${this.rawObj[k]}`))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
633
  }
L
lijiarui 已提交
634

L
lijiarui 已提交
635 636 637
  /**
   * @private
   */
638
  public dump()    {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
639
    console.error('======= dump contact =======')
640 641 642
    if (!this.obj) {
      throw new Error('no this.obj')
    }
643
    Object.keys(this.obj).forEach(k => console.error(`${k}: ${this.obj && this.obj[k]}`))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
644
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
645

L
lijiarui 已提交
646 647 648 649 650 651 652
  /**
   * Check if contact is self
   *
   * @returns {boolean} True for contact is self, False for contact is others
   * @example
   * const isSelf = contact.self()
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
653
  public self(): boolean {
654 655
    const userId = this.puppet // config.puppetInstance()
                        .userId
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
656 657 658 659 660 661 662 663 664 665

    const selfId = this.id

    if (!userId || !selfId) {
      throw new Error('no user or no self id')
    }

    return selfId === userId
  }

L
lijiarui 已提交
666 667 668
  /**
   * @private
   */
ruiruibupt's avatar
#217  
ruiruibupt 已提交
669
  // function should be deprecated
670 671 672 673
  public remark(newRemark?: string|null): Promise<boolean> | string | null {
    log.warn('Contact', 'remark(%s) DEPRECATED, use alias(%s) instead.')
    log.silly('Contact', 'remark(%s)', newRemark || '')

ruiruibupt's avatar
2  
ruiruibupt 已提交
674 675 676 677 678 679 680
    switch (newRemark) {
      case undefined:
        return this.alias()
      case null:
        return this.alias(null)
      default:
        return this.alias(newRemark)
681 682 683
    }
  }

L
lijiarui 已提交
684
  /**
L
lijiarui 已提交
685
   * @private
L
lijiarui 已提交
686
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
687
  public static load(id: string): Contact {
688
    if (!id || typeof id !== 'string') {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
689
      throw new Error('Contact.load(): id not found')
690
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
691

692 693 694 695
    if (!(id in Contact.pool)) {
      Contact.pool[id] = new Contact(id)
    }
    return Contact.pool[id]
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
696
  }
697

L
lijiarui 已提交
698
  /**
L
lijiarui 已提交
699
   * Get the weixin number from a contact.
L
lijiarui 已提交
700
   *
L
lijiarui 已提交
701
   * Sometimes cannot get weixin number due to weixin security mechanism, not recommend.
L
lijiarui 已提交
702
   *
L
lijiarui 已提交
703 704
   * @private
   * @returns {string | null}
L
lijiarui 已提交
705
   * @example
L
lijiarui 已提交
706
   * const weixin = contact.weixin()
L
lijiarui 已提交
707
   */
L
lijiarui 已提交
708 709 710
  public weixin(): string | null {
    const wxId = this.obj && this.obj.weixin || null
    if (!wxId) {
711 712 713
      log.verbose('Contact', `weixin() is not able to always work, it's limited by Tencent API`)
      log.verbose('Contact', 'weixin() If you want to track a contact between sessions, see FAQ at')
      log.verbose('Contact', 'https://github.com/Chatie/wechaty/wiki/FAQ#1-how-to-get-the-permanent-id-for-a-contact')
M
Mukaiu 已提交
714
    }
L
lijiarui 已提交
715
    return wxId
716 717
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
718
}
719

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