-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
166 lines (144 loc) · 4.78 KB
/
api.js
File metadata and controls
166 lines (144 loc) · 4.78 KB
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
const http = require("http");
const https = require("https");
const { URL } = require("url");
const KEY = "AFDsa%1!!2341R%#!$$";
function xorDecrypt(inputBuffer, key) {
const output = Buffer.alloc(inputBuffer.length);
for (let i = 0; i < inputBuffer.length; i++) {
output[i] = inputBuffer[i] ^ key.charCodeAt(i % key.length);
}
return output;
}
function normalizeCity(city) {
return city
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/[ÔÇÖ']/g, "")
.toUpperCase()
.trim();
}
function getTypeDescription(typeCode) {
switch (typeCode) {
case 1:
return "Feriado Nacional";
case 2:
return "Feriado Estadual";
case 3:
return "Feriado Municipal";
case 4:
return "Ponto Facultativo";
case 9:
return "Data Comemorativa";
default:
return "Outro";
}
}
function parseXML(xml) {
const events = [];
const eventRegex = /<event>([\s\S]*?)<\/event>/g;
let match;
while ((match = eventRegex.exec(xml)) !== null) {
const content = match[1];
const dateMatch = content.match(/<date>(.*?)<\/date>/);
const nameMatch = content.match(/<name>(.*?)<\/name>/);
const typeMatch = content.match(/<type_code>(.*?)<\/type_code>/);
const descMatch = content.match(/<description>(.*?)<\/description>/);
if (dateMatch && nameMatch && typeMatch) {
const [d, m, y] = dateMatch[1].split("/");
const typeCode = parseInt(typeMatch[1]);
events.push({
date: `${y}-${m}-${d}`,
name: nameMatch[1],
type: getTypeDescription(typeCode),
description: descMatch ? descMatch[1] : "",
});
}
}
return events;
}
function fetchHolidays(year, state, city) {
const params = new URLSearchParams({ ano: year });
if (state) params.append("estado", state);
if (city) params.append("cidade", normalizeCity(city));
const url = `https://calendario.com.br/api/data.php?${params.toString()}`;
const options = {
headers: {
Referer: "https://feriados.com.br/",
Origin: "https://feriados.com.br",
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
},
};
return new Promise((resolve, reject) => {
const req = https.get(url, options, (res) => {
if (res.statusCode !== 200) {
reject(new Error(`API responded with status code: ${res.statusCode}`));
return;
}
let data = "";
res.on("data", (chunk) => (data += chunk));
res.on("end", () => {
try {
const buffer = Buffer.from(data, "base64");
const decrypted = xorDecrypt(buffer, KEY);
const xmlText = decrypted.toString("utf-8");
const holidays = parseXML(xmlText);
resolve(holidays);
} catch (e) {
reject(new Error("Failed to parse response: " + e.message));
}
});
});
req.on("error", (err) => reject(err));
req.end();
});
}
const server = http.createServer(async (req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET");
const url = new URL(req.url, `http://${req.headers.host}`);
const params = url.searchParams;
// Se não houver parâmetros, exibe a página de ajuda
if (Array.from(params.keys()).length === 0) {
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(`
<div style="font-family: sans-serif; max-width: 800px; margin: 20px auto;">
<h1>API de Feriados</h1>
<p>Bem-vindo! Utilize os parâmetros abaixo para consultar feriados.</p>
<h3>Parâmetros:</h3>
<ul>
<li><strong>estado</strong>: Sigla do estado (ex: SP, RJ). /?estado=SP</li>
<li><strong>cidade</strong>: (Opcional) Nome da cidade (ex: Sao Paulo). /?estado=SP&cidade=Sao Paulo</li>
<li><strong>ano</strong>: (Opcional) Ano da consulta. /?estado=SP&cidade=Sao Paulo&ano=2026</li>
</ul>
</div>
`);
return;
}
res.setHeader("Content-Type", "application/json; charset=utf-8");
const year = params.get("ano") || new Date().getFullYear();
const state = params.get("estado");
const city = params.get("cidade");
if (city && !state) {
res.writeHead(400);
res.end(
JSON.stringify({
error: "Ao especificar uma cidade, o estado também deve ser fornecido.",
})
);
return;
}
try {
const holidays = await fetchHolidays(year, state, city);
res.writeHead(200);
res.end(JSON.stringify(holidays, null, 2));
} catch (error) {
console.error("Error serving request:", error);
res.writeHead(500);
res.end(JSON.stringify({ error: error.message }));
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});