Debian Codegraph @

weather/src/applet-read-data.c

raw
1 /**
2 * This file is a part of the Cairo-Dock project
3 *
4 * Copyright : (C) see the 'copyright' file.
5 * E-mail : see the 'copyright' file.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 3
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <string.h>
21 #include <stdio.h>
22 #include <unistd.h>
23 #include <stdlib.h> // rand
24
25 #include <libxml/tree.h>
26 #include <libxml/parser.h>
27 #include <glib/gstdio.h>
28
29 #include "applet-struct.h"
30 #include "applet-load-icons.h"
31 #include "applet-read-data.h"
32
33 // Credentials used by Cairo-Dock for Yahoo weather
34 // please do not use them for any other purpose than this applet
35 #define APP_ID "kv8SljKW"
36 #define CLIENT_ID "dj0yJmk9N3d2dVZVUHIxWVVpJnM9Y29uc3VtZXJzZWNyZXQmc3Y9MCZ4PWM0"
37 #define CLIENT_SECRET "'2c776c9ee22643fec:59g53568d92142f97ec12e'"
38
39 static gchar *_get_oauth_header (const gchar *cLocationName, gboolean bISUnits);
40
41 static xmlDocPtr _cd_weather_open_xml_buffer (const gchar *cData, xmlNodePtr *root_node, const gchar *cRootNodeName, GError **erreur)
42 {
43 if (cData == NULL || *cData == '\0')
44 {
45 g_set_error (erreur, 1, 1, "empty data (no connection ?)");
46 return NULL;
47 }
48 int length = strlen (cData);
49
50 gchar *cRootNode = g_strdup_printf ("<%s ", cRootNodeName);
51 if (g_strstr_len (cData, length, cRootNode) == NULL) // on intercepte le cas ou une connexion a un hotspot nous renvoie une page meme quand la connexion a weather.com n'a pas pu se faire, car ca fait planter libxml.
52 {
53 g_set_error (erreur, 1, 1, "uncorrect data (no connection ?)");
54 g_free (cRootNode);
55 return NULL;
56 }
57 g_free (cRootNode);
58 xmlInitParser ();
59
60 xmlDocPtr doc = xmlParseMemory (cData, length);
61 if (doc == NULL)
62 {
63 g_set_error (erreur, 1, 1, "uncorrect data (no connection ?)");
64 return NULL;
65 }
66
67 xmlNodePtr noeud = xmlDocGetRootElement (doc);
68 if (noeud == NULL || xmlStrcmp (noeud->name, BAD_CAST cRootNodeName) != 0)
69 {
70 g_set_error (erreur, 1, 2, "xml data is not well formed (yahoo.com may have changed its data format)");
71 return doc;
72 }
73 *root_node = noeud;
74 return doc;
75 }
76 /* Not used
77 static xmlDocPtr _cd_weather_open_xml_file (const gchar *cDataFilePath, xmlNodePtr *root_node, const gchar *cRootNodeName, GError **erreur)
78 {
79 gsize length = 0;
80 gchar *cContent = NULL;
81 g_file_get_contents (cDataFilePath,
82 &cContent,
83 &length,
84 NULL);
85 xmlDocPtr doc = _cd_weather_open_xml_buffer (cContent, root_node, cRootNodeName, erreur);
86 g_free (cContent);
87 return doc;
88 }
89 */
90 static void _cd_weather_close_xml_file (xmlDocPtr doc)
91 {
92 if (doc != NULL)
93 xmlFreeDoc (doc); // pas de xmlCleanupParser, ca fout le boxon.
94 }
95
96
97 GList *cd_weather_parse_location_data (const gchar *cData, GError **erreur)
98 {
99 GError *tmp_erreur = NULL;
100 xmlNodePtr noeud = NULL;
101 xmlDocPtr doc = _cd_weather_open_xml_buffer (cData, &noeud, "search", &tmp_erreur);
102 if (tmp_erreur != NULL)
103 {
104 g_propagate_error (erreur, tmp_erreur);
105 _cd_weather_close_xml_file (doc);
106 return NULL;
107 }
108
109 GList *cLocationsList = NULL;
110 xmlNodePtr param;
111 for (param = noeud->xmlChildrenNode; param != NULL; param = param->next)
112 {
113 if (xmlStrcmp (param->name, BAD_CAST "loc") == 0)
114 {
115 cLocationsList = g_list_prepend (cLocationsList, xmlNodeGetContent (param));
116 cLocationsList = g_list_prepend (cLocationsList, xmlGetProp (param, BAD_CAST "id"));
117 }
118 }
119 _cd_weather_close_xml_file (doc);
120 return cLocationsList;
121 }
122
123
124 static void _cd_weather_parse_data (CDSharedMemory *pSharedMemory, const gchar *cData, gboolean bParseHeader, GError **erreur)
125 {
126 GError *tmp_erreur = NULL;
127 xmlNodePtr noeud = NULL;
128 xmlDocPtr doc = _cd_weather_open_xml_buffer (cData, &noeud, "rss", &tmp_erreur);
129 if (tmp_erreur != NULL)
130 {
131 g_propagate_error (erreur, tmp_erreur);
132 _cd_weather_close_xml_file (doc);
133 return ;
134 }
135
136 xmlNodePtr rss_child, channel_child, item_child;
137 int i=0; // day counter
138 for (rss_child = noeud->xmlChildrenNode; rss_child != NULL; rss_child = rss_child->next)
139 {
140 if (xmlStrcmp (rss_child->name, BAD_CAST "channel") == 0)
141 {
142 for (channel_child = rss_child->children; channel_child != NULL; channel_child = channel_child->next)
143 {
144 if (xmlStrcmp (channel_child->name, BAD_CAST "units") == 0)
145 {
146 pSharedMemory->wdata.units.cTemp = xmlGetProp (channel_child, BAD_CAST "temperature");
147 pSharedMemory->wdata.units.cSpeed = xmlGetProp (channel_child, BAD_CAST "speed");
148 pSharedMemory->wdata.units.cPressure = xmlGetProp (channel_child, BAD_CAST "pressure");
149 }
150 else if (xmlStrcmp (channel_child->name, BAD_CAST "link") == 0)
151 {
152 pSharedMemory->wdata.cLink = xmlNodeGetContent (channel_child);
153 }
154 else if (xmlStrcmp (channel_child->name, BAD_CAST "location") == 0)
155 {
156 pSharedMemory->wdata.cCity = xmlGetProp (channel_child, BAD_CAST "city");
157 pSharedMemory->wdata.cCountry = xmlGetProp (channel_child, BAD_CAST "country");
158 }
159 else if (xmlStrcmp (channel_child->name, BAD_CAST "wind") == 0)
160 {
161 pSharedMemory->wdata.currentConditions.cWindDirection = xmlGetProp (channel_child, BAD_CAST "direction");
162 pSharedMemory->wdata.currentConditions.cWindSpeed = xmlGetProp (channel_child, BAD_CAST "speed");
163 }
164 else if (xmlStrcmp (channel_child->name, BAD_CAST "atmosphere") == 0)
165 {
166 pSharedMemory->wdata.currentConditions.cHumidity = xmlGetProp (channel_child, BAD_CAST "humidity");
167 pSharedMemory->wdata.currentConditions.cPressure = xmlGetProp (channel_child, BAD_CAST "pressure");
168 }
169 else if (xmlStrcmp (channel_child->name, BAD_CAST "astronomy") == 0)
170 {
171 pSharedMemory->wdata.currentConditions.cSunRise = xmlGetProp (channel_child, BAD_CAST "sunrise");
172 pSharedMemory->wdata.currentConditions.cSunSet = xmlGetProp (channel_child, BAD_CAST "sunset");
173 }
174 else if (xmlStrcmp (channel_child->name, BAD_CAST "ttl") == 0)
175 {
176 xmlChar *ttl = xmlNodeGetContent (channel_child);
177 pSharedMemory->wdata.currentConditions.ttl = ttl ? atoi((gchar*)ttl) : 0;
178 xmlFree (ttl);
179 }
180 else if (xmlStrcmp (channel_child->name, BAD_CAST "lastBuildDate") == 0)
181 {
182 pSharedMemory->wdata.currentConditions.cDataAcquisitionDate = xmlNodeGetContent (channel_child);
183 }
184 else if (xmlStrcmp (channel_child->name, BAD_CAST "item") == 0)
185 {
186 for (item_child = channel_child->children; item_child != NULL; item_child = item_child->next)
187 {
188 if (xmlStrcmp (item_child->name, BAD_CAST "condition") == 0)
189 {
190 pSharedMemory->wdata.currentConditions.now.cIconNumber = xmlGetProp (item_child, BAD_CAST "code");
191 pSharedMemory->wdata.currentConditions.now.cDate = xmlGetProp (item_child, BAD_CAST "date");
192 pSharedMemory->wdata.currentConditions.now.cTempMax = xmlGetProp (item_child, BAD_CAST "temp");
193 pSharedMemory->wdata.currentConditions.now.cWeatherDescription = xmlGetProp (item_child, BAD_CAST "text");
194 }
195 else if (xmlStrcmp (item_child->name, BAD_CAST "forecast") == 0 && i<WEATHER_NB_DAYS_MAX)
196 {
197 pSharedMemory->wdata.days[i].cIconNumber = xmlGetProp (item_child, BAD_CAST "code");
198 pSharedMemory->wdata.days[i].cDate = xmlGetProp (item_child, BAD_CAST "date");
199 pSharedMemory->wdata.days[i].cName = xmlGetProp (item_child, BAD_CAST "day");
200 pSharedMemory->wdata.days[i].cTempMax = xmlGetProp (item_child, BAD_CAST "high");
201 pSharedMemory->wdata.days[i].cTempMin = xmlGetProp (item_child, BAD_CAST "low");
202 pSharedMemory->wdata.days[i].cWeatherDescription = xmlGetProp (item_child, BAD_CAST "text");
203 i++;
204 }
205 }
206 }
207 }
208 }
209 }
210 _cd_weather_close_xml_file (doc);
211 }
212
213 const gchar *cBaseUrl = "https://weather-ydn-yql.media.yahoo.com/forecastrss";
214 const gchar *cBaseUrlEsc = "https%3A%2F%2Fweather-ydn-yql.media.yahoo.com%2Fforecastrss";
215
216 static void cd_weather_get_distant_data (CDSharedMemory *pSharedMemory)
217 {
218 pSharedMemory->bErrorInThread = FALSE;
219
220 //\____________________ remove spaces, and add a comma if necessary
221 gchar *r = strchr(pSharedMemory->cLocationCode, ' '), *w = r;
222 if (r)
223 {
224 const gchar *r0 = pSharedMemory->cLocationCode; // just for the sake of readability
225 while (*r)
226 {
227 if (*r == ' ')
228 {
229 if (w != r0 && *(w-1) != ',')
230 *w++ = ',';
231 }
232 else
233 {
234 if (*r != ',' || (w != r0 && *(w-1) != ','))
235 *w++ = *r;
236 }
237 r++;
238 }
239 *w = '\0';
240 }
241 cd_debug("location code: %s", pSharedMemory->cLocationCode);
242
243 //\____________________ get the rss feed
244 GError *erreur = NULL;
245 gchar *cURL = g_strdup_printf("%s?location=%s&format=xml&u=%c", cBaseUrl, pSharedMemory->cLocationCode, pSharedMemory->bISUnits ? 'c' : 'f');
246 gchar *oauth_header = _get_oauth_header (pSharedMemory->cLocationCode, pSharedMemory->bISUnits);
247 gchar *cCCData = cairo_dock_get_url_data_with_headers (cURL, FALSE, &erreur,
248 "Authorization", oauth_header,
249 "X-Yahoo-App-Id", APP_ID,
250 NULL);
251 if (erreur != NULL)
252 {
253 cd_warning ("while downloading current conditions data:\n%s -> %s", cURL, erreur->message);
254 g_error_free (erreur);
255 erreur = NULL;
256 }
257 g_free (oauth_header);
258 g_free (cURL);
259
260 if (cCCData == NULL)
261 {
262 pSharedMemory->bErrorInThread = TRUE;
263 return;
264 }
265
266 //\____________________ On extrait les donnees des conditions courantes.
267 _cd_weather_parse_data (pSharedMemory, cCCData, TRUE, &erreur);
268 if (erreur != NULL)
269 {
270 cd_warning ("weather : %s", erreur->message);
271 g_error_free (erreur);
272 erreur = NULL;
273 pSharedMemory->bErrorInThread = TRUE;
274 }
275 g_free (cCCData);
276 }
277
278
279
280 static void _reset_units (Unit *pUnits)
281 {
282 xmlFree (pUnits->cTemp);
283 xmlFree (pUnits->cSpeed);
284 xmlFree (pUnits->cPressure);
285 }
286
287 static void _reset_current_conditions (CurrentContitions *pCurrentContitions)
288 {
289 xmlFree (pCurrentContitions->cSunRise);
290 xmlFree (pCurrentContitions->cSunSet);
291 xmlFree (pCurrentContitions->cDataAcquisitionDate);
292 xmlFree (pCurrentContitions->cWindSpeed);
293 xmlFree (pCurrentContitions->cWindDirection);
294 xmlFree (pCurrentContitions->cPressure);
295 xmlFree (pCurrentContitions->cHumidity);
296 }
297
298 static void _reset_one_day (Day *pDay)
299 {
300 xmlFree (pDay->cName);
301 xmlFree (pDay->cDate);
302 xmlFree (pDay->cTempMax);
303 xmlFree (pDay->cTempMin);
304 xmlFree (pDay->cIconNumber);
305 }
306
307 void cd_weather_reset_weather_data (CDWeatherData *pData)
308 {
309 xmlFree (pData->cCity);
310 xmlFree (pData->cCountry);
311 _reset_units (&pData->units);
312 _reset_current_conditions (&pData->currentConditions);
313 int i;
314 for (i = 0; i < WEATHER_NB_DAYS_MAX; i ++)
315 {
316 _reset_one_day (&pData->days[i]);
317 }
318 }
319
320 void cd_weather_reset_data (GldiModuleInstance *myApplet)
321 {
322 cd_weather_reset_weather_data (&myData.wdata);
323 }
324
325 static void _free_shared_memory (CDSharedMemory *pSharedMemory)
326 {
327 cd_weather_reset_weather_data (&pSharedMemory->wdata);
328 g_free (pSharedMemory);
329 }
330 void cd_weather_launch_periodic_task (GldiModuleInstance *myApplet)
331 {
332 if (myData.pTask != NULL)
333 {
334 gldi_task_discard (myData.pTask);
335 myData.pTask = NULL;
336 }
337
338 CDSharedMemory *pSharedMemory = g_new0 (CDSharedMemory, 1);
339 pSharedMemory->cLocationCode = g_strdup (myConfig.cLocationCode);
340 pSharedMemory->bISUnits = myConfig.bISUnits;
341 pSharedMemory->bCurrentConditions = myConfig.bCurrentConditions;
342 pSharedMemory->pApplet = myApplet;
343
344 myData.pTask = gldi_task_new_full (3600, // start with 1h period, it will be adjusted according to the TTL
345 (GldiGetDataAsyncFunc) cd_weather_get_distant_data,
346 (GldiUpdateSyncFunc) cd_weather_update_from_data,
347 (GFreeFunc) _free_shared_memory,
348 pSharedMemory);
349 gldi_task_launch (myData.pTask);
350 }
351
352 #include <openssl/sha.h>
353 #include <openssl/hmac.h>
354 #include <openssl/evp.h>
355 #include <sys/time.h>
356
357 static guchar *_hmac_sha1_base64(const gchar *key, const gchar *data)
358 {
359 size_t key_len = strlen(++key);
360 size_t data_len = strlen(data);
361 uint8_t md[64]; // SHA1_Message_Block_Size = 64 bytes
362 guint md_len=64;
363 if (!HMAC(EVP_sha1(), key, key_len, (guchar*)data, data_len, md, &md_len)) // data is URL-encoded, so is actually a guchar*
364 {
365 //#include <openssl/err.h>
366 //ERR_clear_error();
367 }
368 guchar *b64_output = malloc((md_len+1)*4/3+1); // taking into account the padding, and the final '\0' inserted by the function
369 EVP_EncodeBlock(b64_output, md, md_len);
370 return b64_output;
371 }
372
373 static gchar *_get_oauth_header (const gchar *cLocationName, gboolean bISUnits)
374 {
375 // Oauth authentication: the idea is to join to the headers a hash of the GET request's signature
376 // the signature is made of: the method (GET), the url, some query parameters (like location, units and format), and the various oauth parameters (except of course the hash)
377 // they must be ordered, so that both end agree on how to form the string and calculate the hash
378
379 // first build the parameters string
380 gchar *cLocationNameEsc = g_uri_escape_string(cLocationName, NULL, FALSE);
381 struct timeval tv;
382 gettimeofday(&tv, NULL);
383 const gchar *nonce = g_strdup_printf("%032d", rand()); // 32 bytes; it's not like we really need to be secretive...
384 gchar *params_sorted = g_strdup_printf ("format=xml&location=%s&oauth_consumer_key=%s&oauth_nonce=%s&oauth_signature_method=%s&oauth_timestamp=%ld&oauth_version=%s&u=%c",
385 cLocationNameEsc,
386 CLIENT_ID,
387 nonce,
388 "HMAC-SHA1",
389 tv.tv_sec,
390 "1.0",
391 bISUnits ? 'c' : 'f'); // all parameters are sorted by their key, and their value is URL-encoded.
392 gchar *params_sorted_esc = g_uri_escape_string(params_sorted, NULL, FALSE);
393 // then build the request's signature string
394 gchar *signature_base_str = g_strdup_printf ("GET&%s&%s",
395 cBaseUrlEsc,
396 params_sorted_esc);
397 // now calculate the hash of the signature
398 gchar *key = g_strdup (CLIENT_SECRET), *k=key;
399 while (*k) (*k++)--;
400 guchar *oauth_signature = _hmac_sha1_base64(key, signature_base_str);
401 g_free (key);
402
403 // finally build the oauth header, containing all the oauth parameters
404 gchar *auth_header = g_strdup_printf("OAuth oauth_consumer_key=\"%s\", oauth_nonce=\"%s\", oauth_signature_method=\"%s\", oauth_timestamp=\"%ld\", oauth_version=\"%s\", oauth_signature=\"%s\"",
405 CLIENT_ID,
406 nonce,
407 "HMAC-SHA1",
408 tv.tv_sec,
409 "1.0",
410 oauth_signature);
411 free(signature_base_str);
412 free(cLocationNameEsc);
413 free(oauth_signature);
414 return auth_header;
415 }