| 167 | } |
| 168 | |
| 169 | export function xhrAction( |
| 170 | message: xhrI, |
| 171 | sender, |
| 172 | sendResponse, |
| 173 | environment, |
| 174 | retry = { try: 0, date: new Date() }, |
| 175 | ) { |
| 176 | let url; |
| 177 | const options: RequestInit = { |
| 178 | method: message.method, |
| 179 | headers: [] as [string, string][], |
| 180 | }; |
| 181 | |
| 182 | if (typeof message.url === 'object') { |
| 183 | url = message.url.url; |
| 184 | if (message.url.data) { |
| 185 | options.body = message.url.data; |
| 186 | } |
| 187 | for (const key in message.url.headers) { |
| 188 | (options.headers as [string, string][]).push([key, message.url.headers[key]]); |
| 189 | } |
| 190 | } else { |
| 191 | url = message.url; |
| 192 | } |
| 193 | |
| 194 | if (utils.isDomainMatching(url, 'malsync.moe') || utils.isDomainMatching(url, 'simkl.com')) { |
| 195 | (options.headers as [string, string][]).push(['version', api.storage.version()]); |
| 196 | (options.headers as [string, string][]).push(['type', 'addon']); |
| 197 | } |
| 198 | |
| 199 | if (environment === 'testing') { |
| 200 | (options.headers as [string, string][]).push(['X-MALSYNC-TEST', JSON.stringify(message)]); |
| 201 | } |
| 202 | |
| 203 | fetch(url, options) |
| 204 | .then(async response => { |
| 205 | if (response.status === 429) { |
| 206 | let limits: { timeout: number; tries: number; cutoff: number }; |
| 207 | if (environment === 'content') { |
| 208 | limits = { |
| 209 | timeout: 30000, |
| 210 | tries: 4, |
| 211 | cutoff: 180000, |
| 212 | }; |
| 213 | } else { |
| 214 | limits = { |
| 215 | timeout: 300000, |
| 216 | tries: 4, |
| 217 | cutoff: 30 * 60 * 1000, |
| 218 | }; |
| 219 | } |
| 220 | |
| 221 | if ( |
| 222 | retry.try < limits.tries && |
| 223 | !utils.rateLimitExclude.test(response.url) && |
| 224 | new Date().getTime() - retry.date.getTime() < limits.cutoff |
| 225 | ) { |
| 226 | con.error('RATE LIMIT'); |