-
Notifications
You must be signed in to change notification settings - Fork 3
/
channel.ts
210 lines (185 loc) · 6.62 KB
/
channel.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
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
210
import { createHash, createHmac } from 'node:crypto'
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { ChatWebhookMessageRequest, ChatWebhookTypingRequest } from './webhook'
import EventEmitter from 'events'
import { Request } from 'express'
import { Chat } from './chat'
import { DTO } from '~/dto'
import { Client } from '~/integration'
import { AccountWith } from '~/integration/client/subsystems'
import { ChatEvents, filtersCheck, Subscribers } from './subscribers'
export type ChatCredential = {
/**
* Chat secret given at channel creation
*/
chatSecret: string,
/**
* Chat id given at channel creation
*/
chatId: string,
/**
* Default title for connectChannel method
*/
title: string,
}
type ChatRequestConfig<D> = AxiosRequestConfig<D> & { dto?: typeof DTO, mainDomain?: string }
/**
* Main Chat API
*/
export class Channel extends EventEmitter {
id: string
private secret: string
private subscribers: Subscribers = {}
public title: string
constructor(chatCredentials: ChatCredential) {
super()
const { chatId, chatSecret, title } = chatCredentials
this.id = chatId
this.secret = chatSecret
this.title = title
}
checkSignature(body: unknown, signature?: string): boolean {
if (!signature) return false
const { secret } = this
return createHmac('sha1', secret)
.update(JSON.stringify(body))
.digest('hex')
.toLowerCase() === signature
}
request<T = unknown, D = unknown>(config: ChatRequestConfig<D>): Promise<AxiosResponse<T, D>> {
const {
data: rawData,
headers = {},
method = 'POST',
url,
dto,
mainDomain = 'amocrm.ru',
...rest
} = config
const baseURL = `https://amojo.${mainDomain}`
const { secret } = this
const data = (dto && rawData) ? dto.process(rawData) : rawData
headers['Date'] = (new Date()).toUTCString()
headers['Content-Type'] = 'application/json'
headers['Content-MD5'] = createHash('md5')
.update(JSON.stringify(data || ''))
.digest('hex')
.toLowerCase()
headers['X-Signature'] = createHmac('sha1', secret)
.update(
[
method.toUpperCase(),
...(Object.keys(headers).sort().map(k => headers[k])),
url
].join('\n')
)
.digest('hex')
.toLowerCase()
return axios({ baseURL, headers, data, method, url, ...rest })
}
post<T = unknown, D = unknown>(config: ChatRequestConfig<D>): Promise<AxiosResponse<T, D>> {
return this.request({
...config,
method: 'POST'
})
}
delete<T = unknown, D = unknown>(config: ChatRequestConfig<D>): Promise<AxiosResponse<T, D>> {
return this.request({
...config,
method: 'DELETE'
})
}
/**
* Connect channel to account
* @param account Client or amojoId of account
* @param title? Channel title in account, default value this.title
* @returns Chat instance connected to the account
*/
async connect(account: Client, title?: string): Promise<Chat>
async connect(amojoId: string, title?: string): Promise<Chat>
async connect(account: string | Client, title?: string): Promise<Chat> {
const { id, title: defaultTitle } = this
if (!title) title = defaultTitle
const amojoId = (account instanceof Client) ?
(await account.account.getAccountInfo(AccountWith.amojoId)).amojoId :
account
const response = await this.post<{ scope_id: string }>(
{
url: `/v2/origin/custom/${id}/connect`,
data: {
account_id: amojoId,
title,
hook_api_version: 'v2'
},
}
)
return new Chat({
channel: this,
scopeId: response.data.scope_id,
title
})
}
async disconnect(account: Client): Promise<void>
async disconnect(amojoId: string): Promise<void>
async disconnect(account: string | Client): Promise<void> {
const { id } = this
const amojoId = (account instanceof Client) ?
(await account.account.getAccountInfo(AccountWith.amojoId)).amojoId :
account
await this.delete(
{
url: `/v2/origin/custom/${id}/disconnect`,
data: {
account_id: amojoId
},
}
)
}
processWebhook(req: Request) {
const urlParts = req.originalUrl.split('/')
const scopeId = urlParts[urlParts.length - 1]
if (!scopeId) return
const { body: data, headers } = req
const signature = headers['x-signature']
if (typeof signature !== 'string' || !this.checkSignature(data, signature)) return
const chat = new Chat({
channel: this,
scopeId
})
const { message, action } = data
// New message webhook
if (message) {
const messageRequest = ChatWebhookMessageRequest.import(data)
this.emit('message', chat, messageRequest)
}
// Typing webhook
if (action) {
const typingRequest = ChatWebhookTypingRequest.import(data)
this.emit('typing', chat, typingRequest)
}
}
override on<U extends keyof ChatEvents>(event: U, listener: ChatEvents[U]['cb'], filter?: ChatEvents[U]['filter']): this {
const listeners = this.subscribers[event] ?
this.subscribers[event] :
this.subscribers[event] = new Map() as Subscribers[U]
listeners?.set(listener, filter)
return this
}
override removeListener<U extends keyof ChatEvents>(event: U, listener: ChatEvents[U]['cb']): this {
const listeners = this.subscribers[event]
if (!listeners) return this
listeners.delete(listener)
return this
}
override emit<U extends keyof ChatEvents>(event: U, ...args: Parameters<ChatEvents[U]['cb']>): boolean {
const listeners = this.subscribers[event]
if (!listeners) return false
for (const [listener, filter] of listeners.entries()) {
if (filter && !filtersCheck[event](args, filter)) continue
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
listener(...args)
}
return true
}
}