File size: 1,478 Bytes
c84aba8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c81826
c84aba8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import https from "https";

/**
 * Perform a GET request bypassing SSL verification strictly for observations.meteogate.eu
 */
export function fetchBypassSSL(url: string, timeoutMs: number = 30000): Promise<string> {
  return new Promise((resolve, reject) => {
    const isMeteoGate = url.includes("meteogate.eu");
    const agent = isMeteoGate ? new https.Agent({ rejectUnauthorized: false }) : undefined;

    const options: https.RequestOptions = {
      agent,
      headers: {
        "User-Agent": "EuroMeteo-NextJS/1.0",
      },
      timeout: timeoutMs,
    };

    const req = https.get(url, options, (res) => {
      if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
        // Handle redirection
        fetchBypassSSL(res.headers.location, timeoutMs).then(resolve).catch(reject);
        return;
      }

      res.setEncoding("utf8");
      let data = "";
      res.on("data", (chunk) => {
        data += chunk;
      });
      res.on("end", () => {
        if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
          resolve(data);
        } else {
          reject(new Error(`Request failed with status code ${res.statusCode}`));
        }
      });
      res.on("error", (err) => {
        reject(err);
      });
    });

    req.on("error", (err) => {
      reject(err);
    });

    req.on("timeout", () => {
      req.destroy();
      reject(new Error("Request timed out"));
    });
  });
}