|
1
|
|
|
import {PollState, taskEvent} from '../helpers/interfaces'; |
|
2
|
|
|
import {callMessageApi} from '../helpers/api'; |
|
3
|
|
|
import {getStateFromCardName} from '../helpers/state'; |
|
4
|
|
|
import PollCard from '../cards/PollCard'; |
|
5
|
|
|
|
|
6
|
|
|
export default class TaskHandler { |
|
7
|
|
|
event: taskEvent; |
|
8
|
|
|
|
|
9
|
|
|
public constructor(event: taskEvent) { |
|
10
|
|
|
this.event = event; |
|
11
|
|
|
} |
|
12
|
|
|
|
|
13
|
|
|
async process(): Promise<void> { |
|
14
|
|
|
switch (this.event.action) { |
|
15
|
|
|
case 'close_poll': |
|
16
|
|
|
const currentState = await this.getStateFromMessageId(); |
|
17
|
|
|
if (!currentState.closedTime || currentState.closedTime > Date.now()) { |
|
18
|
|
|
currentState.closedTime = Date.now(); |
|
19
|
|
|
} |
|
20
|
|
|
currentState.closedBy = 'scheduled auto-close'; |
|
21
|
|
|
const apiResponse = await this.updatePollMessage(currentState); |
|
22
|
|
|
if (apiResponse?.status !== 200) { |
|
23
|
|
|
throw new Error('Error when closing message'); |
|
24
|
|
|
} |
|
25
|
|
|
break; |
|
26
|
|
|
default: |
|
27
|
|
|
console.log('unknown task'); |
|
28
|
|
|
} |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
async getStateFromMessageId(): Promise<PollState> { |
|
32
|
|
|
const request = { |
|
33
|
|
|
name: this.event.id, |
|
34
|
|
|
}; |
|
35
|
|
|
const apiResponse = await callMessageApi('get', request); |
|
36
|
|
|
const currentState = getStateFromCardName(apiResponse.data!.cardsV2?.[0].card ?? {}); |
|
37
|
|
|
if (!currentState) { |
|
38
|
|
|
throw new Error('State not found'); |
|
39
|
|
|
} |
|
40
|
|
|
return JSON.parse(currentState) as PollState; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
async updatePollMessage(currentState: PollState) { |
|
44
|
|
|
const localeTimezone = {locale: 'en', offset: 0, id: 'UTC'}; |
|
45
|
|
|
const cardMessage = new PollCard(currentState, localeTimezone).createMessage(); |
|
46
|
|
|
const request = { |
|
47
|
|
|
name: this.event.id, |
|
48
|
|
|
requestBody: cardMessage, |
|
49
|
|
|
updateMask: 'cardsV2', |
|
50
|
|
|
}; |
|
51
|
|
|
return await callMessageApi('update', request); |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|