-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathschedule-util.ts
240 lines (212 loc) · 6.17 KB
/
schedule-util.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
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
// Description:
// A collection of helper functions for creating scheduled tasks with hubot in flowdock
//
// Dependencies:
// "cron-parser" : "~1.0.1",
// "cronstrue" : "^1.68.0"
// "moment" : "^2.24.0",
// "node-schedule" : "~1.0.0",
//
// Configuration:
// HUBOT_SCHEDULE_DEBUG - set "1" for debug
// HUBOT_SCHEDULE_DONT_RECEIVE - set "1" if you don't want hubot to be processed by scheduled message
// HUBOT_SCHEDULE_DENY_EXTERNAL_CONTROL - set "1" if you want to deny scheduling from other rooms
// HUBOT_SCHEDULE_LIST_REPLACE_TEXT - set JSON object like '{"@":"[at]"}' to configure text replacement used when listing scheduled messages
//
// Author:
// kb0rg
//
// Inspired by, borrowed (and heavily modified) from the original code at
// https://github.com/matsukaz/hubot-schedule
// by matsukaz <[email protected]>
// configuration settings
import moment from "moment"
import cronstrue from "cronstrue"
import cronParser from "cron-parser"
import * as hubot from "hubot"
import {
getRoomInfoFromIdOrName,
getRoomNameFromId,
encodeThreadId,
matrixUrlFor,
} from "./adapter-util.ts"
import CONFIG, { RECURRING_JOB_STORAGE_KEY } from "./schedule-config.ts"
import {
MessageMetadata,
ScheduledJob,
ScheduledJobMap,
} from "./scheduled-jobs.ts"
function urlFor(roomId: string, serverName: string, eventId: string): string {
return matrixUrlFor(roomId, serverName, eventId)
}
function isCronPattern(pattern: string | Date) {
if (pattern instanceof Date) {
return false
}
const { errors } = cronParser.parseString(pattern)
return !Object.keys(errors).length
}
export function updateJobInBrain(
robotBrain: hubot.Brain<hubot.Adapter>,
storageKey: string,
job: ScheduledJob,
): ReturnType<ScheduledJob["serialize"]> {
const serializedJob = job.serialize()
const updatedJobs = {
...robotBrain.get(storageKey),
[job.id]: serializedJob,
}
robotBrain.set(storageKey, updatedJobs)
return updatedJobs
}
// TODO: pull formatters back into script, or out to a different lib
function formatJobForMessage(
robotAdapter: hubot.Adapter,
jobPattern: string,
isCron: boolean,
jobId: string,
jobMessage: string,
jobRoom: string,
metadata: MessageMetadata,
remindInThread: boolean,
): string {
let text = ""
let roomDisplayText = ""
let patternParsed = ""
let messageParsed = ""
let jobRoomDisplayName = ""
if (isCron) {
patternParsed = cronstrue.toString(jobPattern)
} else {
patternParsed = moment(jobPattern).format("llll Z")
}
jobRoomDisplayName = jobRoom
? getRoomNameFromId(robotAdapter, jobRoom) || jobRoom
: "Private Message"
roomDisplayText = `(to ${jobRoomDisplayName})`
if (metadata && jobRoom && remindInThread) {
const jobFlow = getRoomInfoFromIdOrName(robotAdapter, jobRoom)
if (jobFlow) {
const encodedId = encodeThreadId(metadata.threadId ?? metadata.messageId)
const reminderURL = urlFor(jobRoom, "thesis.co", encodedId)
roomDisplayText = `(to [thread in ${jobRoomDisplayName}](${reminderURL}))`
}
}
if (jobMessage.length) {
messageParsed = jobMessage
// Ignore for expediency.
// eslint-disable-next-line no-restricted-syntax
for (const orgText in CONFIG.list.replaceText) {
if (
Object.prototype.hasOwnProperty.call(CONFIG.list.replaceText, orgText)
) {
const replacedText = CONFIG.list.replaceText[orgText]
messageParsed = messageParsed.replace(
new RegExp(`${orgText}`, "g"),
replacedText,
)
}
}
}
text += `**${patternParsed}** (id: ${jobId}) ${roomDisplayText}:\n>${messageParsed}\n\n`
return text
}
export function logSerializedJobDetails(
logger: hubot.Log,
serializedJob: ReturnType<ScheduledJob["serialize"]>,
messagePrefix: string,
jobId: string,
) {
const [pattern, user, , metadata, remindInThread] = serializedJob
logger.debug(
`${messagePrefix} (${jobId}): pattern: ${pattern}, user: %o, message: (message redacted for privacy), metadata: %o, remindInThread: ${remindInThread}`,
user,
metadata,
)
}
function isRestrictedRoom(
targetRoom: string,
msg: hubot.Response<hubot.Adapter> | string,
) {
if (CONFIG.denyExternalControl === "1") {
if (typeof msg !== "string" && msg.message.user.room !== targetRoom) {
return true
}
}
return false
}
const isBlank = (s: string | undefined | null) => !(s ? s.trim() : undefined)
/**
* Given an object containing scheduled jobs currently in memory, an array of
* room ids, and optionally a usedId, returns:
* an array containing two arrays: the datetime jobs and the cron jobs
* scheduled for the given rooms, and visible to the given user.
*/
function getScheduledJobList(
jobsInMemory: ScheduledJobMap,
rooms: string[],
userIdForDMs: string | null = null,
) {
// split jobs into date and cron pattern jobs
const dateJobs: ScheduledJob[] = []
const cronJobs: ScheduledJob[] = []
Object.keys(jobsInMemory).forEach((id) => {
const job = jobsInMemory[id]
if (rooms.includes(job.user.room as string)) {
// Exclude DM from list unless job's user matches specified user.
if (
typeof job.user.room === "undefined" &&
job.user.id !== userIdForDMs
) {
return
}
if (!isCronPattern(job.pattern)) {
dateJobs.push(job)
} else {
cronJobs.push(job)
}
}
})
return [dateJobs, cronJobs]
}
function sortJobsByDate(jobs: ScheduledJob[]) {
jobs.sort(
(a, b) => new Date(a.pattern).getTime() - new Date(b.pattern).getTime(),
)
return jobs
}
function formatJobsForListMessage(
robotAdapter: hubot.Adapter,
jobs: ScheduledJob[],
isCron: boolean,
) {
let output = ""
if (!isCron) {
// eslint-disable-next-line no-param-reassign
jobs = sortJobsByDate(jobs)
}
jobs.forEach((job) => {
output += formatJobForMessage(
robotAdapter,
job.pattern,
isCron,
job.id,
job.message,
job.user.room as string,
job.metadata,
job.remindInThread,
)
})
return output
}
export {
CONFIG,
RECURRING_JOB_STORAGE_KEY,
isRestrictedRoom,
isBlank,
isCronPattern,
getScheduledJobList,
formatJobForMessage,
formatJobsForListMessage,
urlFor,
}