Dashboard  2
Lot's of data
Loading...
Searching...
No Matches
weather_api.ts
Go to the documentation of this file.
1/*
2** EPITECH PROJECT, 2024
3** area-rattrapage
4** File description:
5** weather_api.ts
6*/
7
8import DB from "./db";
9
10// Import the list of cities for the weather api
11import CityList from "../ressources/city.list.min.json"
12// import CityList from "../ressources/city.list.tiny.json"
13
14
15export namespace WeatherApi {
16
17
18 export function get_location_coordinates() {
19 console.log("get_location_coordinates");
20
21 // console.log(`CityList: ${JSON.stringify(CityList)}: CityList`);
22
23 let coordinate_equivalence: Record<string, { lat: number; lon: number }> = Object();
24 for (let i = 0; i < CityList.length; i++) {
25 let city = CityList[i];
26 let keyName = "";
27 if (city.name) {
28 keyName += `${city.name}, `;
29 }
30 if (city.state) {
31 keyName += `${city.state}, `;
32 }
33 keyName += city.country;
34 coordinate_equivalence[String(keyName)] = { "lat": city.coord.lat, "lon": city.coord.lon };
35 }
36 // console.log(`Coordinate Equivalence: ${JSON.stringify(coordinate_equivalence)} : coodinate equivalence`);
37 return coordinate_equivalence;
38 }
39
40 export const coordinate_equivalence = get_location_coordinates();
41 export const available_cities = Object.keys(coordinate_equivalence);
42
43 export interface Coordinates {
44 coords: {
45 latitude: string;
46 longitude: string;
47 },
48 city: string
49 }
50
51 export async function getCountryCoordinates(country: string, database: DB, user_info: any, widget_index: Number): Promise<Coordinates | null> {
52 console.log("getCountryCoordinates");
53 let city = available_cities[Math.floor(Math.random() * available_cities.length - 1)];
54 let coords;
55 if (coordinate_equivalence.hasOwnProperty(country)) {
56 coords = coordinate_equivalence[country];
57 city = country
58 } else {
59 database.updateTable("user_widgets", ["widget_option"], [city], `widget_index='${widget_index}' AND user_id='${user_info.id}'`, []);
60 coords = coordinate_equivalence[city];
61 }
62 if (coords) {
63 return { coords: { latitude: String(coords.lat), longitude: String(coords.lon) }, city: city };
64 } else {
65 console.error("Error fetching coordinates: No results found for: ", country);
66 return null;
67 }
68 }
69
70 export async function getWeather(id: string, country: string, weatherKey: string, database: DB, user_info: any, widget_index: Number): Promise<{ html: String, location: String }> {
71 console.log("getWeather");
72 const coords = await getCountryCoordinates(country, database, user_info, widget_index);
73 let html = "";
74 let location = "";
75 if (coords) {
76 const { latitude, longitude } = coords.coords;
77 location = coords.city;
78 const weatherUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&mode=html&appid=${weatherKey}&units=metric&lang=en`;
79
80 // Create and inject the iframe dynamically
81 const width = 200;
82 const height = 150;
83
84 html = `<iframe src="${weatherUrl}" width="${width}" height="${height}" frameborder="0" scrolling="no" id="${id}" data-country="${country}"></iframe>`;
85 } else {
86 const msg = "Could not retrieve weather data.";
87 console.error(msg);
88 html = `<p id="${id}">${msg}</p>`;
89 }
90 return { html: html, location: location };
91 }
92
93 export async function get_weather_locations(dropdown_id: string, command: string, location: String) {
94 console.log("get_weather_locations");
95 let html = `<select id="${dropdown_id}" name="${dropdown_id}" onchange="${command}">`;
96 for (let i = 0; i < available_cities.length; i++) {
97 if (available_cities[i] === location) {
98 html += `<option value="${available_cities[i]}" selected>${available_cities[i]}</option>`;
99 } else {
100 html += `<option value="${available_cities[i]}">${available_cities[i]}</option>`;
101 }
102 }
103 html += "</select>";
104 return html;
105 }
106
107 export async function get_weather_widget(widget_name: string, index: number, user_info: any, database: DB) {
108 console.log("get_weather_widget");
109 var content = "";
110 const widget_id = `${widget_name}_${index}`;
111 const country = await database.getContentFromTable("user_widgets", ["widget_option"], `widget_index='${index}' AND user_id='${user_info.id}'`);
112 const apiKey = await database.getContentFromTable("widgets", ["api_key"], "widget_name='weather'");
113 if (!apiKey || apiKey.length == 0) {
114 return "<p>Widget gathering error, the content for the given widget could not be fetched successfully.</p>";
115 }
116 const weatherKey = apiKey[0].api_key || null;
117 // console.log("widget_id", widget_id);
118 // console.log("Country", country);
119 // console.log("Weather key", weatherKey);
120 let countryCleaned = country[0].widget_option;
121 if (countryCleaned === undefined || countryCleaned.length === 0 || !countryCleaned || countryCleaned === null) {
122 countryCleaned = "";
123 }
124 // console.log("Country cleaned", countryCleaned);
125 const weatherBody = await getWeather(`${widget_id}-iframe`, countryCleaned, weatherKey, database, user_info, index);
126 const weatherDropdown = await get_weather_locations(`${widget_id}-dropdown`, `getWeather('${widget_id}-iframe', this.value, this)`, weatherBody.location);
127 // console.log("Weather body", weatherBody);
128 // console.log("Weather dropdown", weatherDropdown);
129 content += `<div id="${widget_id}" data-country="${weatherBody.location}" data-id="${index}">`;
130 content += weatherDropdown;
131 content += weatherBody.html;
132 content += "</div>";
133 // console.log("Widget content:", content);
134 return content;
135 };
136};