contact.ts 21.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/**
 *   Chatie - https://github.com/chatie
 *
 *   Copyright 2016-2017 Huan LI <zixia@zixia.net>
 *
 *   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.
 *
 */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
19
import {
L
lijiarui 已提交
20 21
  Config,
  Sayable,
22
  log,
23
}                     from './config'
M
Mukaiu 已提交
24 25 26 27
import {
  Message,
  MediaMessage,
}                     from './message'
28 29 30
import { PuppetWeb }  from './puppet-web'
import { UtilLib }    from './util-lib'
import { Wechaty }    from './wechaty'
31

32
export interface ContactObj {
L
lijiarui 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45
  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 已提交
46 47
  official:   boolean,
  special:    boolean,
48 49
}

50
export interface ContactRawObj {
L
lijiarui 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63
  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 已提交
64
  VerifyFlag:   number,
65 66
}

L
lijiarui 已提交
67 68 69 70
/**
 * Enum for Gender values.
 * @enum {number}
 */
71 72 73 74 75 76
export enum Gender {
  Unknown = 0,
  Male    = 1,
  Female  = 2,
}

77
export interface ContactQueryFilter {
L
lijiarui 已提交
78 79
  name?:   string | RegExp,
  alias?:  string | RegExp,
80
  // remark is DEPRECATED
L
lijiarui 已提交
81
  remark?: string | RegExp,
82 83
}

J
Jas 已提交
84 85 86 87 88 89 90 91 92 93
/**
 * @see https://github.com/Chatie/webwx-app-tracker/blob/7c59d35c6ea0cff38426a4c5c912a086c4c512b2/formatted/webwxApp.js#L3848
 */
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 (李卓桓) 已提交
94 95 96
/**
 * Class Contact
 *
L
lijiarui 已提交
97
 * `Contact` is `Sayable`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
98
 */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
99
export class Contact implements Sayable {
100 101
  private static pool = new Map<string, Contact>()

102
  public obj: ContactObj | null
103
  private dirtyObj: ContactObj | null
104 105
  private rawObj: ContactRawObj

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
106 107 108
  constructor(
    public readonly id: string,
  ) {
109
    log.silly('Contact', `constructor(${id})`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
110

111 112 113
    if (typeof id !== 'string') {
      throw new Error('id must be string. found: ' + typeof id)
    }
114 115
  }

116 117 118 119
  public toString(): string {
    if (!this.obj) {
      return this.id
    }
120
    return this.obj.alias || this.obj.name || this.id
121 122
  }

123
  public toStringEx() { return `Contact(${this.obj && this.obj.name}[${this.id}])` }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
124

125
  private parse(rawObj: ContactRawObj): ContactObj | null {
126
    if (!rawObj || !rawObj.UserName) {
127 128 129
      log.warn('Contact', 'parse() got empty rawObj!')
    }

130
    return !rawObj ? null : {
L
lijiarui 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
      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 已提交
146 147 148 149 150 151 152 153 154 155
      /**
       * @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
       */
      // 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
       */
      special:       specialContactList.indexOf(rawObj.UserName) > -1 || /@qqim$/.test(rawObj.UserName),
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
156 157
    }
  }
158

L
lijiarui 已提交
159 160 161 162 163 164 165 166 167 168
  /**
   * Get the weixin number from a contact
   * Sometimes cannot get weixin number due to weixin security mechanism, not recommend.
   * @returns {string | null}
   *
   * @example
   * ```ts
   * const weixin = contact.weixin()
   * ```
   */
169 170 171 172
  public weixin(): string | null {
    const wxId = this.obj && this.obj.weixin || null
    if (!wxId) {
      log.info('Contact', `weixin() is not able to always work, it's limited by Tencent API`)
173 174
      log.info('Contact', 'weixin() If you want to track a contact between sessions, see FAQ at')
      log.info('Contact', 'https://github.com/Chatie/wechaty/wiki/FAQ#1-how-to-get-the-permanent-id-for-a-contact')
175 176 177
    }
    return wxId
  }
L
lijiarui 已提交
178 179 180 181 182 183 184 185 186 187 188

  /**
   * Get the name from a contact
   *
   * @returns {string}
   *
   * @example
   * ```ts
   * const name = contact.name()
   * ```
   */
189
  public name()     { return UtilLib.plainText(this.obj && this.obj.name || '') }
L
lijiarui 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205

  /**
   * Check if contact is stranger
   *
   * @returns {boolean | null} True for not friend of the bot, False for friend of the bot, null for cannot get the info.
   *
   * @example
   * ```ts
   * const isStranger = contact.stranger()
   * ```
   */
  public stranger(): boolean|null {
    if (!this.obj) return null
    return this.obj.stranger
  }

J
Jas 已提交
206 207 208 209 210 211 212 213 214 215 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
  /**
   * Check if it's a offical account
   *
   * @returns {boolean|null} True for official account, Flase for contact is not a official account
   *
   * @example
   * ```ts
   * const isOfficial = contact.official()
   * ```
   */
  public official(): boolean {
    return !!this.obj && this.obj.official
  }

  /**
   * Check if it's a special contact
   *
   * the contact who's id in following list will be identify as a special contact
   *
   * ```ts
   * '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',
   * ```
   * @see https://github.com/Chatie/webwx-app-tracker/blob/7c59d35c6ea0cff38426a4c5c912a086c4c512b2/formatted/webwxApp.js#L3848
   *
   * @returns {boolean|null} True for brand, Flase for contact is not a brand
   *
   * @example
   * ```ts
   * const isSpecial = contact.special()
   * ```
   */
  public special(): boolean {
    return !!this.obj && this.obj.special
  }

  /**
   * Check if it's a personal account
   *
   * @returns {boolean|null} True for personal account, Flase for contact is not a personal account
   *
   * @example
   * ```ts
   * const isPersonal = contact.personal()
   * ```
   */
  public personal(): boolean {
    return !this.official()
  }

L
lijiarui 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
  /**
   * Check if the contact is star contact.
   *
   * @returns {boolean} True for star friend, False for no star friend, null for cannot get the info.
   *
   * @example
   * ```ts
   * const isStar = contact.star()
   * ```
   */
  public star(): boolean|null {
    if (!this.obj) return null
    return this.obj.star
  }

273 274
  /**
   * Contact gender
L
lijiarui 已提交
275
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
276
   * @returns Gender.Male(2) | Gender.Female(1) | Gender.Unknown(0)
L
lijiarui 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
   *
   * @example
   * ```ts
   * 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
   * ```ts
   * const province = contact.province()
   * ```
294 295
   */
  public province() { return this.obj && this.obj.province }
L
lijiarui 已提交
296 297 298 299 300 301 302 303 304 305 306

  /**
   * Get the region 'city' from a contact
   *
   * @returns {string | undefined}
   *
   * @example
   * ```ts
   * const city = contact.city()
   * ```
   */
307 308 309 310
  public city()     { return this.obj && this.obj.city }

  /**
   * Get avatar picture file stream
L
lijiarui 已提交
311 312 313 314 315 316 317 318 319 320 321
   *
   * @returns {Promise<NodeJS.ReadableStream>}
   *
   * @example
   * ```ts
   * 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)
   * ```
322 323
   */
  public async avatar(): Promise<NodeJS.ReadableStream> {
324 325
    log.verbose('Contact', 'avatar()')

326 327 328 329 330
    if (!this.obj || !this.obj.avatar) {
      throw new Error('Can not get avatar: not ready')
    }

    try {
331 332
      const hostname = (Config.puppetInstance() as PuppetWeb).browser.hostname
      const avatarUrl = `http://${hostname}${this.obj.avatar}`
333
      const cookies = await (Config.puppetInstance() as PuppetWeb).browser.readCookie()
334 335 336 337 338 339
      log.silly('Contact', 'avatar() url: %s', avatarUrl)

      return UtilLib.urlStream(avatarUrl, cookies)
    } catch (err) {
      log.warn('Contact', 'avatar() exception: %s', err.stack)
      throw err
340 341
    }
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
342

343
  public get(prop)  { return this.obj && this.obj[prop] }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
344

345
  public isReady(): boolean {
346
    return !!(this.obj && this.obj.id && this.obj.name)
347 348
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
349 350 351 352 353
  // public refresh() {
  //   log.warn('Contact', 'refresh() DEPRECATED. use reload() instead.')
  //   return this.reload()
  // }

L
lijiarui 已提交
354 355 356 357 358 359 360 361 362 363
  /**
   * Force reload data for Contact
   *
   * @returns {Promise<this>}
   *
   * @example
   * ```ts
   * await contact.refresh()
   * ```
   */
364 365 366 367 368 369 370 371
  public async refresh(): Promise<this> {
    if (this.isReady()) {
      this.dirtyObj = this.obj
    }
    this.obj = null
    return this.ready()
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
372 373 374 375 376
  // public ready() {
  //   log.warn('Contact', 'ready() DEPRECATED. use load() instead.')
  //   return this.load()
  // }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
377
  public async ready(contactGetter?: (id: string) => Promise<ContactRawObj>): Promise<this> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
378
    log.silly('Contact', 'ready(' + (contactGetter ? typeof contactGetter : '') + ')')
379
    if (!this.id) {
380 381
      const e = new Error('ready() call on an un-inited contact')
      throw e
382
    }
383

384
    if (this.isReady()) { // already ready
385 386
      return Promise.resolve(this)
    }
387 388

    if (!contactGetter) {
389 390
      log.silly('Contact', 'get contact via ' + Config.puppetInstance().constructor.name)
      contactGetter = Config.puppetInstance()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
391 392
                            .getContact.bind(Config.puppetInstance())
    }
393 394 395
    if (!contactGetter) {
      throw new Error('no contatGetter')
    }
396

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
397 398 399 400 401 402
    try {
      const rawObj = await contactGetter(this.id)
      log.silly('Contact', `contactGetter(${this.id}) resolved`)
      this.rawObj = rawObj
      this.obj    = this.parse(rawObj)
      return this
403

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
404 405 406
    } catch (e) {
      log.error('Contact', `contactGetter(${this.id}) exception: %s`, e.message)
      throw e
407 408 409
    }
  }

410
  public dumpRaw() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
411
    console.error('======= dump raw contact =======')
412
    Object.keys(this.rawObj).forEach(k => console.error(`${k}: ${this.rawObj[k]}`))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
413
  }
L
lijiarui 已提交
414

415
  public dump()    {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
416
    console.error('======= dump contact =======')
417
    Object.keys(this.obj).forEach(k => console.error(`${k}: ${this.obj && this.obj[k]}`))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
418
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
419

L
lijiarui 已提交
420 421 422 423 424 425 426 427 428 429
  /**
   * Check if contact is self
   *
   * @returns {boolean} True for contact is self, False for contact is others
   *
   * @example
   * ```ts
   * const isSelf = contact.self()
   * ```
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
430 431 432 433 434 435 436 437 438 439 440 441 442
  public self(): boolean {
    const userId = Config.puppetInstance()
                          .userId

    const selfId = this.id

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

    return selfId === userId
  }

443
  /**
444
   * find contact by `name` or `alias`
L
lijiarui 已提交
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
   *
   * 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
   * ```ts
   * // get the contact list of the bot
   * const contactList = await Contact.findAll()
   * // find allof the contacts whose name is 'ruirui'
   * const contactList = await Contact.findAll({name: 'ruirui'})
   * // find allof the contacts whose alias is 'lijiarui'
   * const contactList = await Contact.findAll({alias: 'lijiarui'})
   * ```
465
   */
ruiruibupt's avatar
3  
ruiruibupt 已提交
466
  public static async findAll(queryArg?: ContactQueryFilter): Promise<Contact[]> {
467 468
    let query: ContactQueryFilter
    if (queryArg) {
ruiruibupt's avatar
3  
ruiruibupt 已提交
469
      if (queryArg.remark) {
470
        log.warn('Contact', 'Contact.findAll({remark:%s}) DEPRECATED, use Contact.findAll({alias:%s}) instead.', queryArg.remark, queryArg.remark)
ruiruibupt's avatar
3  
ruiruibupt 已提交
471
        query = { alias: queryArg.remark}
ruiruibupt's avatar
#217  
ruiruibupt 已提交
472 473 474
      } else {
        query = queryArg
      }
475
    } else {
476 477
      query = { name: /.*/ }
    }
478

479
    // log.verbose('Cotnact', 'findAll({ name: %s })', query.name)
L
lijiarui 已提交
480 481
    log.verbose('Cotnact', 'findAll({ %s })',
                            Object.keys(query)
482
                                  .map(k => `${k}: ${query[k]}`)
L
lijiarui 已提交
483
                                  .join(', '),
484 485 486 487 488 489 490 491 492 493 494
              )

    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',
495
      alias:  'RemarkName',
496 497 498 499 500 501
    }

    filterKey = keyMap[filterKey]
    if (!filterKey) {
      throw new Error('unsupport filter key')
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
502

503 504
    if (!filterValue) {
      throw new Error('filterValue not found')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
505 506
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
507 508 509 510 511 512
    /**
     * must be string because we need inject variable value
     * into code as variable name
     */
    let filterFunction: string

513 514 515 516 517
    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}' })`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
518 519 520 521
    } else {
      throw new Error('unsupport name type')
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
522
    const contactList = await Config.puppetInstance()
523 524 525 526 527
                              .contactFind(filterFunction)
                              .catch(e => {
                                log.error('Contact', 'findAll() rejected: %s', e.message)
                                return [] // fail safe
                              })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
528
    await Promise.all(contactList.map(c => c.ready()))
529

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
530
    return contactList
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
531
  }
532

533
  /**
534
   * GET the alias for contact
L
lijiarui 已提交
535 536 537 538 539 540 541
   *
   * @returns {(string | null)}
   *
   * @example
   * ```ts
   * const alias = contact.alias()
   * ```
542
   */
543
  public alias(): string | null
L
lijiarui 已提交
544

545
  /**
546
   * SET the alias for contact
L
lijiarui 已提交
547 548 549 550 551 552 553 554
   *
   * tests show it will failed if set alias too frequently(60 times in one minute).
   *
   * @param {string} newAlias
   * @returns {Promise<boolean>} A promise to the result. true for success, false for failure
   *
   * @example
   * ```ts
555
   * const ret = await contact.alias('lijiarui')
L
lijiarui 已提交
556 557 558 559 560 561
   * if (ret) {
   *   console.log(`change ${contact.name()}'s alias successfully!`)
   * } else {
   *   console.error('failed to change ${contact.name()}'s alias!')
   * }
   * ```
562
   */
563
  public alias(newAlias: string): Promise<boolean>
L
lijiarui 已提交
564

565
  /**
566
   * DELETE the alias for a contact
L
lijiarui 已提交
567 568 569 570 571 572
   *
   * @param {null} empty
   * @returns {Promise<boolean>}
   *
   * @example
   * ```ts
573
   * const ret = await contact.alias(null)
L
lijiarui 已提交
574
   * if (ret) {
575
   *   console.log(`delete ${contact.name()}'s alias successfully!`)
L
lijiarui 已提交
576
   * } else {
577
   *   console.log(`failed to delete ${contact.name()}'s alias!`)
L
lijiarui 已提交
578 579
   * }
   * ```
580
   */
581
  public alias(empty: null): Promise<boolean>
582

583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
  /**
   * GET / SET / DELETE the alias for a contact
   *
   * @param {(none | string | null)} newAlias ,
   * @returns {(string | null | Promise<boolean>)}
   *
   * @example GET the alias for a contact
   * ```ts
   * 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 SET the alias for a contact
   * ```ts
   * const ret = await contact.alias('lijiarui')
   * if (ret) {
   *   console.log(`change ${contact.name()}'s alias successfully!`)
   * } else {
   *   console.error('failed to change ${contact.name()}'s alias!')
   * }
   * ```
   *
   * @example DELETE the alias for a contact
   * ```ts
   * 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!`)
   * }
   * ```
   */
619 620
  public alias(newAlias?: string|null): Promise<boolean> | string | null {
    log.silly('Contact', 'alias(%s)', newAlias || '')
621

622 623
    if (newAlias === undefined) {
      return this.obj && this.obj.alias || null
624 625 626
    }

    return Config.puppetInstance()
627
                  .contactAlias(this, newAlias)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
628 629 630
                  .then(ret => {
                    if (ret) {
                      if (this.obj) {
631
                        this.obj.alias = newAlias
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
632
                      } else {
633
                        log.error('Contact', 'alias() without this.obj?')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
634 635
                      }
                    } else {
636
                      log.warn('Contact', 'alias(%s) fail', newAlias)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
637 638 639
                    }
                    return ret
                  })
640
                  .catch(e => {
641
                    log.error('Contact', 'alias(%s) rejected: %s', newAlias, e.message)
642 643 644 645
                    return false // fail safe
                  })
  }

ruiruibupt's avatar
#217  
ruiruibupt 已提交
646
  // function should be deprecated
647 648 649 650
  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 已提交
651 652 653 654 655 656 657
    switch (newRemark) {
      case undefined:
        return this.alias()
      case null:
        return this.alias(null)
      default:
        return this.alias(newRemark)
658 659 660
    }
  }

661
  /**
662
   * try to find a contact by filter: {name: string | RegExp} / {alias: string | RegExp}
L
lijiarui 已提交
663 664
   * @description Find contact by name or alias, if the result more than one, return the first one.
   * @static
665
   * @param {ContactQueryFilter} query
L
lijiarui 已提交
666 667 668
   * @returns {(Promise<Contact | null>)} If can find the contact, return Contact, or return null
   *
   * @example
L
lijiarui 已提交
669
   * ```ts
L
lijiarui 已提交
670 671 672
   * const contactFindByName = await Contact.find({ name:"ruirui"} )
   * const contactFindByAlias = await Contact.find({ alias:"lijiarui"} )
   * ```
673
   */
674
  public static async find(query: ContactQueryFilter): Promise<Contact | null> {
ruiruibupt's avatar
1  
ruiruibupt 已提交
675
    log.verbose('Contact', 'find(%s)', JSON.stringify(query))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
676

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
677
    const contactList = await Contact.findAll(query)
678
    if (!contactList || !contactList.length) {
679
      return null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
680
    }
681 682 683 684

    if (contactList.length > 1) {
      log.warn('Contact', 'function find(%s) get %d contacts, use the first one by default', JSON.stringify(query), contactList.length)
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
685
    return contactList[0]
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
686 687
  }

L
lijiarui 已提交
688 689 690 691 692 693 694 695
  /**
   * Load data for Contact by id
   *
   * @static
   * @param {string} id
   * @returns {Contact}
   *
   * @example
L
lijiarui 已提交
696
   * ```ts
L
lijiarui 已提交
697 698 699 700
   * // fake: contactId = @0bb3e4dd746fdbd4a80546aef66f4085
   * const contact = Contact.load('@0bb3e4dd746fdbd4a80546aef66f4085')
   * ```
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
701
  public static load(id: string): Contact {
702
    if (!id || typeof id !== 'string') {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
703
      throw new Error('Contact.load(): id not found')
704
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
705

706 707 708 709
    if (!(id in Contact.pool)) {
      Contact.pool[id] = new Contact(id)
    }
    return Contact.pool[id]
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
710
  }
711

L
lijiarui 已提交
712 713 714 715 716 717 718
  /**
   * Say `content` to Contact
   *
   * @param {string} content
   * @returns {Promise<void>}
   *
   * @example
L
lijiarui 已提交
719
   * ```ts
L
lijiarui 已提交
720 721 722
   * await contact.say('welcome to wechaty!')
   * ```
   */
M
Mukaiu 已提交
723 724 725
  public async say(text: string)
  public async say(mediaMessage: MediaMessage)

726
  public async say(textOrMedia: string | MediaMessage): Promise<boolean> {
M
Mukaiu 已提交
727
    const content = textOrMedia instanceof MediaMessage ? textOrMedia.filename() : textOrMedia
728 729
    log.verbose('Contact', 'say(%s)', content)

730 731
    const bot = Wechaty.instance()
    const user = bot.self()
732

733 734 735
    if (!user) {
      throw new Error('no user')
    }
M
Mukaiu 已提交
736 737 738 739 740 741 742 743 744
    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')
    }
745 746 747 748
    m.from(user)
    m.to(this)
    log.silly('Contact', 'say() from: %s to: %s content: %s', user.name(), this.name(), content)

749
    return await bot.send(m)
750 751
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
752
}
753

754 755 756 757 758 759 760 761 762 763
// Contact.search = function(options) {
//   if (options.name) {
//     const regex = new RegExp(options.name)
//     return Object.keys(Contact.pool)
//     .filter(k => regex.test(Contact.pool[k].name()))
//     .map(k => Contact.pool[k])
//   }

//   return []
// }
Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
764 765

export default Contact