friend-request.ts 6.0 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
 *   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
9
 *
10 11 12 13 14 15 16
 *       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 已提交
17
 *   @ignore
18 19 20
 *
 */

21 22 23
 /* tslint:disable:no-var-requires */
const retryPromise  = require('retry-promise').default

24
import { instanceToClass } from 'clone-class'
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
25

26 27 28
import { PuppetAccessory }  from './puppet-accessory'

import { Contact }          from './contact'
29

30 31
import {
  log,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
32
}                       from './config'
33

34
export enum FriendRequestType {
35 36 37 38
  Unknown = 0,
  Send,
  Receive,
  Confirm,
39 40
}

41 42 43 44 45 46 47
export interface FriendRequestPayload {
  contact? : Contact,
  hello?   : string,
  ticket?  : string
  type?    : FriendRequestType,
}

L
lijiarui 已提交
48 49 50 51 52 53 54
/**
 * Send, receive friend request, and friend confirmation events.
 *
 * 1. send request
 * 2. receive request(in friend event)
 * 3. confirmation friendship(friend event)
 *
55
 * [Examples/Friend-Bot]{@link https://github.com/Chatie/wechaty/blob/master/examples/friend-bot.ts}
L
lijiarui 已提交
56
 */
57
export class FriendRequest extends PuppetAccessory {
58

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
59 60 61
  // tslint:disable-next-line:variable-name
  public static Type = FriendRequestType

62 63 64 65 66 67 68 69 70 71
  public static createSend(
    contact : Contact,
    hello   : string,
    ): FriendRequest {
    log.verbose('PuppeteerFriendRequest', 'createSend(%s, %s)',
                                          contact,
                                          hello,
                )

    const sentRequest = new this({
72
      type: FriendRequestType.Send,
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
      contact,
      hello,
    })

    return sentRequest
  }

  public static createConfirm(
    contact: Contact,
  ): FriendRequest {
    log.verbose('PuppeteerFriendRequest', 'createConfirm(%s)',
                                          contact,
                )

    const confirmedRequest = new this({
88
      type: FriendRequestType.Confirm,
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
      contact,
    })

    return confirmedRequest
  }

  public static createReceive(
    contact : Contact,
    hello   : string,
    ticket  : string,
  ): FriendRequest {
    log.verbose('PuppeteerFriendRequest', 'createReceive(%s, %s, %s)',
                                          contact,
                                          hello,
                                          ticket,
                )

    const receivedRequest = new this({
107
      type: FriendRequestType.Receive,
108 109 110 111 112 113 114 115 116 117 118 119 120
      contact,
      hello,
      ticket,
    })

    return receivedRequest
  }

  /**
   *
   * Instance Properties
   *
   */
121
  constructor(
122 123 124 125
    protected payload?: FriendRequestPayload,
  ) {
    super()
    log.verbose('PuppeteerFriendRequest', 'constructor(%s)', payload)
126 127 128 129 130 131 132 133 134 135 136

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

    if (MyClass === FriendRequest) {
      throw new Error('FriendRequest class can not be instanciated directly! See: https://github.com/Chatie/wechaty/issues/1217')
    }

    if (!this.puppet) {
      throw new Error('FriendRequest class can not be instanciated without a puppet!')
    }
137 138 139 140 141 142 143
  }

  public async send(): Promise<void> {
    if (!this.payload) {
      throw new Error('no payload')
    } else if (!this.payload.contact) {
      throw new Error('no contact')
144
    } else if (this.payload.type !== FriendRequest.Type.Send) {
145 146 147 148 149
      throw new Error('not a send request')
    }
    log.verbose('PuppeteerFriendRequest', 'send() to %s', this.payload.contact)

    await this.puppet.friendRequestSend(
150
      this.payload.contact.id,
151 152 153 154 155 156 157 158 159 160 161
      this.payload.hello,
    )
  }

  public async accept(): Promise<void> {
    if (!this.payload) {
      throw new Error('no payload')
    } else if (!this.payload.contact) {
      throw new Error('no contact')
    } else if (!this.payload.ticket) {
      throw new Error('no ticket')
162
    } else if (this.payload.type !== FriendRequest.Type.Receive) {
163 164 165 166
      throw new Error('not a receive request, its a ' + FriendRequest.Type[this.payload.type!])
    }
    log.verbose('FriendRequest', 'accept() to %s', this.payload.contact)

167
    await this.puppet.friendRequestAccept(this.payload.contact.id, this.payload.ticket)
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209

    const max = 20
    const backoff = 300
    const timeout = max * (backoff * max) / 2
    // 20 / 300 => 63,000
    // max = (2*totalTime/backoff) ^ (1/2)
    // timeout = 11,250 for {max: 15, backoff: 100}

    // refresh to wait contact ready

    await retryPromise({ max: max, backoff: backoff }, async (attempt: number) => {
      log.silly('PuppeteerFriendRequest', 'accept() retryPromise() attempt %d with timeout %d', attempt, timeout)

      await this.contact().ready()

      if (this.contact().isReady()) {
        log.verbose('PuppeteerFriendRequest', 'accept() with contact %s ready()', this.contact().name())
        return
      }
      throw new Error('FriendRequest.accept() content.ready() not ready')

    }).catch((e: Error) => {
      log.warn('PuppeteerFriendRequest', 'accept() rejected for contact %s because %s', this.contact, e && e.message || e)
    })

  }

  public hello(): string {
    if (!this.payload) {
      throw new Error('no payload')
    }
    return this.payload.hello || ''
  }

  public contact(): Contact {
    if (!this.payload) {
      throw new Error('no payload')
    } else if (!this.payload.contact) {
      throw new Error('no contact')
    }
    return this.payload.contact
  }
210

211 212 213 214
  public async reject(): Promise<void> {
    log.warn('PuppeteerFriendRequest', 'reject() not necessary, NOP.')
    return
  }
215

216 217 218 219 220 221 222 223
  public type(): FriendRequestType {
    if (!this.payload) {
      throw new Error('no payload')
    } else if (!this.payload.type) {
      throw new Error('no type')
    }
    return this.payload.type
  }
224 225

}
Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
226 227

export default FriendRequest