-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
240 lines (207 loc) · 8.33 KB
/
main.js
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
const express = require("express")
const axios = require("axios")
const logger = require("./logger")
const { loadConfig } = require("./configBuilder")
// Load configuration
const config = process.env.NODE_ENV !== "test" ? loadConfig() : ""
const debug = logger.isLevelEnabled("debug")
const app = express()
app.use(express.json())
const axiosInstance = axios.create({
baseURL: config.overseerr_url,
headers: {
accept: "application/json",
"X-Api-Key": config.overseerr_api_token,
"Content-Type": "application/json",
},
})
// Utility functions
const normalizeToArray = (value) => {
const values = Array.isArray(value) ? value : [value]
return values.map((x) => String(x).toLowerCase())
}
const isObject = (value) => typeof value === "object" && value !== null
const isObjectArray = (value) => Array.isArray(value) && value.some((item) => isObject(item))
const formatDebugLogEntry = (entry) => {
if (Array.isArray(entry)) {
return entry
.map((item) => (isObject(item) && item.name ? item.name : isObject(item) ? JSON.stringify(item) : item))
.join(", ")
}
if (isObject(entry)) {
if (entry.name) {
return entry.name
}
return Object.entries(entry)
.map(([key, value]) => `${key}: ${Array.isArray(value) ? `[${value.join(", ")}]` : value}`)
.join(", ")
}
return entry
}
const buildDebugLogMessage = (message, details = {}) => {
const formattedDetails = Object.entries(details)
.map(([key, value]) => `${key}: ${formatDebugLogEntry(value)}`)
.join("\n")
return `${message}\n${formattedDetails}`
}
// Main functions
const matchValue = (filterValue, dataValue) => {
const arrayValues = normalizeToArray(filterValue)
if (isObject(dataValue)) {
for (const [key, value] of Object.entries(dataValue)) {
if (isObjectArray(value)) {
if (
value.some((item) =>
arrayValues.some((filterVal) =>
Object.values(item).some((field) => String(field).toLowerCase().includes(filterVal))
)
)
) {
return true
}
} else {
if (arrayValues.some((filterVal) => String(value).toLowerCase().includes(filterVal))) {
return true
}
}
}
}
if (isObjectArray(dataValue)) {
return dataValue.some((item) =>
arrayValues.some((value) =>
Object.values(item).some((field) => String(field).toLowerCase().includes(value))
)
)
}
return arrayValues.some((value) => String(dataValue).toLowerCase().includes(value))
}
const findMatchingInstances = (webhook, data, filters) => {
try {
const matchingFilter = filters.find(({ media_type, conditions }) => {
if (media_type !== webhook.media?.media_type) return false
for (const [key, value] of Object.entries(conditions || {})) {
const requestValue = data[key] || webhook.request?.[key]
if (!requestValue) {
logger.debug(`Filter check skipped - Key "${key}" not found in webhook or data`)
return false
}
if (debug) {
logger.debug(
buildDebugLogMessage("Filter check:", {
Field: key,
"Filter value": value,
"Request value": requestValue,
})
)
}
if (value.exclude ? matchValue(value.exclude, requestValue) : !matchValue(value, requestValue)) {
logger.debug(`Filter check for key "${key}" did not match.`)
return false
}
}
return true
})
if (!matchingFilter) {
logger.info("No matching filter found for the current webhook")
return null
}
logger.info(`Found matching filter at index ${filters.indexOf(matchingFilter)}`)
return matchingFilter.apply
} catch (error) {
logger.error(`Error finding matching filter: ${error.message}`)
return null
}
}
const getPostData = (requestData) => {
const { media, extra = [] } = requestData
const postData = { mediaType: media.media_type }
if (media.media_type === "tv") {
const seasons = extra
.find((item) => item.name === "Requested Seasons")
?.value?.split(",")
.map(Number)
.filter(Number.isInteger)
if (seasons?.length > 0) {
postData["seasons"] = seasons
}
}
return postData
}
const applyConfig = async (requestId, postData) => await axiosInstance.put(`/api/v1/request/${requestId}`, postData)
const approveRequest = async (requestId) => await axiosInstance.post(`/api/v1/request/${requestId}/approve`)
const sendToInstances = async (instances, requestId, data) => {
const instancesArray = Array.isArray(instances) ? instances : [instances]
for (const item of instancesArray) {
try {
let postData = { ...data }
const instance = config.instances[item]
if (!instance) {
logger.warn(`Instance "${item}" not found in config`)
continue
}
postData.rootFolder = instance.root_folder
postData.serverId = instance.server_id
if (instance.quality_profile_id) postData.profileId = instance.quality_profile_id
if (debug)
logger.debug(buildDebugLogMessage("Sending configuration to instance:", { instance: item, postData }))
await applyConfig(requestId, postData)
logger.info(`Configuration applied for request ID ${requestId} on instance "${item}"`)
if (instance.approve ?? true) {
await approveRequest(requestId)
logger.info(`Request ID ${requestId} approved for instance "${item}"`)
}
} catch (error) {
logger.warn(`Failed to post request ID ${requestId} to instance "${item}": ${error.message}`)
}
}
}
// Webhook route
app.post("/webhook", async (req, res) => {
try {
const { notification_type, media, request } = req.body
if (notification_type === "TEST_NOTIFICATION") {
logger.info("Test notification received")
return res.status(200).send()
}
if (media.media_type === "music") {
logger.info("Received music request. Approving")
await approveRequest(request.request_id)
return res.status(200).send()
}
const { data } = await axiosInstance.get(`/api/v1/${media.media_type}/${media.tmdbId}`)
logger.info(
`Received request ID ${request.request_id} for ${media.media_type} "${data?.originalTitle || data?.originalName}"`
)
if (debug) {
const cleanMetadata = Object.fromEntries(
Object.entries(data).filter(
([key]) => !["credits", "relatedVideos", "networks", "watchProviders"].includes(key)
)
)
logger.debug(
buildDebugLogMessage("Request details:", {
webhook: JSON.stringify(req.body, null, 2),
metadata: JSON.stringify(cleanMetadata, null, 2),
})
)
}
const instances = findMatchingInstances(req.body, data, config.filters)
const postData = getPostData(req.body)
if (instances) await sendToInstances(instances, request.request_id, postData)
else if (config.approve_on_no_match) {
logger.info(`Approving unmatched request ID ${request.request_id}`)
await approveRequest(request.request_id)
}
return res.status(200).send()
} catch (error) {
const message = `Error handling webhook: ${error.message}`
logger.error(message)
return res.status(500).send({ error: message })
}
})
const PORT = process.env.PORT || 8481
const server = app.listen(PORT, () => {
logger.info(`Server is running on port ${PORT}`)
if (debug) logger.debug("Debug logs enabled")
})
module.exports = { findMatchingInstances, server }