2023-08-20 11:51:39 +01:00
|
|
|
import Cookie from './cookie.js';
|
|
|
|
import { readFile, writeFile } from 'fs/promises';
|
|
|
|
import { parse as parseSetCookie, splitCookiesString } from 'set-cookie-parser';
|
|
|
|
|
|
|
|
const WRITE_INTERVAL = 60000,
|
2023-08-20 11:58:04 +01:00
|
|
|
cookiePath = process.env.cookiePath,
|
2023-08-20 11:51:39 +01:00
|
|
|
COUNTER = Symbol('counter');
|
|
|
|
|
|
|
|
let cookies = {}, dirty = false, intervalId;
|
|
|
|
|
|
|
|
const setup = async () => {
|
|
|
|
try {
|
2023-08-20 11:58:04 +01:00
|
|
|
if (!cookiePath) return;
|
2023-08-20 11:51:39 +01:00
|
|
|
|
2023-08-20 11:58:04 +01:00
|
|
|
cookies = await readFile(cookiePath, 'utf8');
|
2023-08-20 11:51:39 +01:00
|
|
|
cookies = JSON.parse(cookies);
|
|
|
|
intervalId = setInterval(writeChanges, WRITE_INTERVAL)
|
|
|
|
} catch { /* no cookies for you */ }
|
|
|
|
}
|
|
|
|
|
|
|
|
setup();
|
|
|
|
|
|
|
|
function writeChanges() {
|
|
|
|
if (!dirty) return;
|
|
|
|
dirty = false;
|
|
|
|
|
2023-08-20 11:58:04 +01:00
|
|
|
writeFile(cookiePath, JSON.stringify(cookies, null, 4)).catch(() => {
|
2023-08-20 11:51:39 +01:00
|
|
|
clearInterval(intervalId)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
export function getCookie(service) {
|
|
|
|
if (!cookies[service] || !cookies[service].length) return;
|
|
|
|
|
|
|
|
let n;
|
|
|
|
if (cookies[service][COUNTER] === undefined) {
|
|
|
|
n = cookies[service][COUNTER] = 0
|
|
|
|
} else {
|
|
|
|
++cookies[service][COUNTER]
|
|
|
|
n = (cookies[service][COUNTER] %= cookies[service].length)
|
|
|
|
}
|
|
|
|
|
|
|
|
const cookie = cookies[service][n];
|
|
|
|
if (typeof cookie === 'string') cookies[service][n] = Cookie.fromString(cookie);
|
|
|
|
|
|
|
|
return cookies[service][n]
|
|
|
|
}
|
|
|
|
|
|
|
|
export function updateCookie(cookie, headers) {
|
2023-08-20 14:27:49 +01:00
|
|
|
if (!cookie) return;
|
|
|
|
|
2023-08-20 23:18:32 +01:00
|
|
|
const parsed = parseSetCookie(
|
|
|
|
splitCookiesString(headers.get('set-cookie')),
|
|
|
|
{ decodeValues: false }
|
|
|
|
), values = {}
|
2023-08-20 11:51:39 +01:00
|
|
|
|
|
|
|
cookie.unset(parsed.filter(c => c.expires < new Date()).map(c => c.name));
|
2023-08-20 23:31:16 +01:00
|
|
|
parsed.filter(c => !c.expires || c.expires > new Date()).forEach(c => values[c.name] = c.value);
|
2023-10-14 23:48:36 +01:00
|
|
|
updateCookieValues(cookie, values);
|
|
|
|
}
|
2023-08-20 11:51:39 +01:00
|
|
|
|
2023-10-14 23:48:36 +01:00
|
|
|
export function updateCookieValues(cookie, values) {
|
2023-08-20 11:51:39 +01:00
|
|
|
cookie.set(values);
|
|
|
|
if (Object.keys(values).length) dirty = true
|
|
|
|
}
|