const cookieStorage = "cookieStorage.json";
let myCookie = "";
function loadCookie() {
if (fs.existsSync(cookieStorage)) {
const dataCookie = JSON.parse(getFileContent(cookieStorage));
myCookie = dataCookieToString(dataCookie);
return true;
}
return false;
}
loadCookie();
function saveCookie(res) {
if (res.headers["set-cookie"] && cookieStorage) {
const dataCookie = mkdataCookie(res.headers["set-cookie"]);
setFileContent(cookieStorage, JSON.stringify(dataCookie, null, 4));
myCookie = dataCookieToString(dataCookie);
}
}
function get(option) {
option.method = "GET";
return ajax(option);
}
function post(option) {
option.method = "POST";
return ajax(option);
}
function ajax(option) {
const data = (option.data) ? querystring.stringify(option.data) : "",
context = (option.context) ? option.context : {};
const options = {
host: "zestedesavoir.com",
port: "443",
path: option.url,
method: (option.method == "GET") ? "GET" : "POST",
headers: {
"User-Agent": "NodeJS " + monApplication.title,
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
"Content-Length": data.length,
"Cookie": myCookie
}
};
const req = https.request(options, function(res) {
res.setEncoding("utf8");
let content = "";
res.on("data", function(chunk) {
content += chunk;
});
res.on("end", function() {
if (option.success) {
saveCookie(res);
option.success(res, content, context);
}
});
});
req.on("error", function(e) {
console.log("\033[91mProblème avec la requête : " + e.message + "\033[00m");
setTimeout(function() {
return ajax(option);
}, 1500);
});
req.write(data);
req.end();
}
function dataCookieToString(dataCookie) {
let t = "";
for (let x = 0; x < dataCookie.length; x++) {
t += ((t != "") ? "; " : "") + dataCookie[x].key + "=" + dataCookie[x].value;
}
return t;
}
function mkdataCookie(cookie) {
let t, j;
cookie = cookie.toString().replace(/,([^ ])/g, ",[12],$1").split(",[12],");
for (let x = 0, i; x < cookie.length; x++) {
cookie[x] = cookie[x].split("; ");
j = cookie[x][0].split("=");
t = {
key: j[0],
value: j[1]
};
if (t.value === "deleted") continue;
for (i = 1; i < cookie[x].length; i++) {
j = cookie[x][i].split("=");
t[j[0]] = j[1];
}
cookie[x] = t;
}
return cookie;
}