summaryrefslogtreecommitdiff
path: root/libmateweather/weather-iwin.c
blob: e098354f4c52dcb7e44e65512cf6bab55cc67400 (plain)
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* weather-iwin.c - US National Weather Service IWIN forecast source
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see
 * <http://www.gnu.org/licenses/>.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <ctype.h>
#include <stdlib.h>
#include <string.h>

#include <libxml/parser.h>

#define MATEWEATHER_I_KNOW_THIS_IS_UNSTABLE
#include "weather.h"
#include "weather-priv.h"

/**
 *  Humans don't deal well with .MONDAY...SUNNY AND BLAH BLAH.TUESDAY...THEN THIS AND THAT.WEDNESDAY...RAINY BLAH BLAH.
 *  This function makes it easier to read.
 */
static gchar *
formatWeatherMsg (gchar *forecast)
{
    gchar *ptr = forecast;
    gchar *startLine = NULL;

    while (0 != *ptr) {
        if (ptr[0] == '\n' && ptr[1] == '.') {
          /* This removes the preamble by shifting the relevant data
           * down to the start of the buffer. */
            if (NULL == startLine) {
                memmove (forecast, ptr, strlen (ptr) + 1);
                ptr = forecast;
                ptr[0] = ' ';
            }
            ptr[1] = '\n';
            ptr += 2;
            startLine = ptr;
        } else if (ptr[0] == '.' && ptr[1] == '.' && ptr[2] == '.' && NULL != startLine) {
            memmove (startLine + 2, startLine, (ptr - startLine) * sizeof (gchar));
            startLine[0] = ' ';
            startLine[1] = '\n';
            ptr[2] = '\n';

            ptr += 3;

        } else if (ptr[0] == '$' && ptr[1] == '$') {
            ptr[0] = ptr[1] = ' ';

        } else {
            ptr++;
        }
    }

    return forecast;
}

static gboolean
hasAttr (xmlNode *node, const char *attr_name, const char *attr_value)
{
    xmlChar *attr;
    gboolean res = FALSE;

    if (!node)
        return res;

    attr = xmlGetProp (node, (const xmlChar *) attr_name);

    if (!attr)
        return res;

    res = g_str_equal ((const char *)attr, attr_value);

    xmlFree (attr);

    return res;
}

static GSList *
parseForecastXml (const char *buff, WeatherInfo *master_info)
{
    GSList *res = NULL;
    xmlDocPtr doc;
    xmlNode *root, *node;

    g_return_val_if_fail (master_info != NULL, NULL);

    if (!buff || !*buff)
        return NULL;

    #define XC (const xmlChar *)
    #define isElem(_node,_name) g_str_equal ((const char *)_node->name, _name)

    doc = xmlParseMemory (buff, strlen (buff));
    if (!doc)
        return NULL;

    /* Description at http://www.weather.gov/mdl/XML/Design/MDL_XML_Design.pdf */
    root = xmlDocGetRootElement (doc);
    for (node = root->xmlChildrenNode; node; node = node->next) {
        if (node->name == NULL || node->type != XML_ELEMENT_NODE)
            continue;

        if (isElem (node, "data")) {
            xmlNode *n;
            char *time_layout = NULL;
            time_t update_times[7] = {0};

            for (n = node->children; n; n = n->next) {
                if (!n->name)
                    continue;

                if (isElem (n, "time-layout")) {
                    if (!time_layout && hasAttr (n, "summarization", "24hourly")) {
                        xmlNode *c;
                        int count = 0;

                        for (c = n->children; c && (count < 7 || !time_layout); c = c->next) {
                            if (c->name && !time_layout && isElem (c, "layout-key")) {
                                xmlChar *val = xmlNodeGetContent (c);

                                if (val) {
                                    time_layout = g_strdup ((const char *)val);
                                    xmlFree (val);
                                }
                            } else if (c->name && isElem (c, "start-valid-time")) {
                                xmlChar *val = xmlNodeGetContent (c);

                                if (val) {
                                    GTimeVal tv;

                                    if (g_time_val_from_iso8601 ((const char *)val, &tv)) {
                                        update_times[count] = tv.tv_sec;
                                    } else {
                                        update_times[count] = 0;
                                    }

                                    count++;

                                    xmlFree (val);
                                }
                            }
                        }

                        if (count != 7) {
                            /* There can be more than one time-layout element, the other
                               with only few children, which is not the one to use. */
                            g_free (time_layout);
                            time_layout = NULL;
                        }
                    }
                } else if (isElem (n, "parameters")) {
                    xmlNode *p;

                    /* time-layout should be always before parameters */
                    if (!time_layout)
                        break;

                    if (!res) {
                        int i;

                        for (i = 0; i < 7;  i++) {
                            WeatherInfo *nfo = weather_info_clone (master_info);

                            if (nfo) {
                                nfo->valid = FALSE;
                                nfo->forecast_type = FORECAST_ZONE;
                                nfo->update = update_times [i];
                                nfo->sky = -1;
                                nfo->temperature_unit = TEMP_UNIT_FAHRENHEIT;
                                nfo->temp = -1000.0;
                                nfo->temp_min = -1000.0;
                                nfo->temp_max = -1000.0;
                                nfo->tempMinMaxValid = FALSE;
                                nfo->cond.significant = FALSE;
                                nfo->cond.phenomenon = PHENOMENON_NONE;
                                nfo->cond.qualifier = QUALIFIER_NONE;
                                nfo->dew = -1000.0;
                                nfo->wind = -1;
                                nfo->windspeed = -1;
                                nfo->pressure = -1.0;
                                nfo->visibility = -1.0;
                                nfo->sunriseValid = FALSE;
                                nfo->sunsetValid = FALSE;
                                nfo->sunrise = 0;
                                nfo->sunset = 0;
                                g_free (nfo->forecast);
                                nfo->forecast = NULL;
				nfo->session = NULL;
				nfo->requests_pending = 0;
				nfo->finish_cb = NULL;
				nfo->cb_data = NULL;
                                res = g_slist_append (res, nfo);
                            }
                        }
                    }

                    for (p = n->children; p; p = p->next) {
                        if (p->name && isElem (p, "temperature") && hasAttr (p, "time-layout", time_layout)) {
                            xmlNode *c;
                            GSList *at = res;
                            gboolean is_max = hasAttr (p, "type", "maximum");

                            if (!is_max && !hasAttr (p, "type", "minimum"))
                                break;

                            for (c = p->children; c && at; c = c->next) {
                                if (isElem (c, "value")) {
                                    WeatherInfo *nfo = (WeatherInfo *)at->data;
                                    xmlChar *val = xmlNodeGetContent (c);

                                    /* can pass some values as <value xsi:nil="true"/> */
                                    if (!val || !*val) {
                                        if (is_max)
                                            nfo->temp_max = nfo->temp_min;
                                        else
                                            nfo->temp_min = nfo->temp_max;
                                    } else {
                                        if (is_max)
                                            nfo->temp_max = atof ((const char *)val);
                                        else
                                            nfo->temp_min = atof ((const char *)val);
                                    }

                                    if (val)
                                        xmlFree (val);

                                    nfo->tempMinMaxValid = nfo->tempMinMaxValid || (nfo->temp_max > -999.0 && nfo->temp_min > -999.0);
                                    nfo->valid = nfo->tempMinMaxValid;

                                    at = at->next;
                                }
                            }
                        } else if (p->name && isElem (p, "weather") && hasAttr (p, "time-layout", time_layout)) {
                            xmlNode *c;
                            GSList *at = res;

                            for (c = p->children; c && at; c = c->next) {
                                if (c->name && isElem (c, "weather-conditions")) {
                                    WeatherInfo *nfo = at->data;
                                    xmlChar *val = xmlGetProp (c, XC "weather-summary");

                                    if (val && nfo) {
                                        /* Checking from top to bottom, if 'value' contains 'name', then that win,
                                           thus put longer (more precise) values to the top. */
                                        int i;
                                        struct _ph_list {
                                            const char *name;
                                            WeatherConditionPhenomenon ph;
                                        } ph_list[] = {
                                            { "Ice Crystals", PHENOMENON_ICE_CRYSTALS } ,
                                            { "Volcanic Ash", PHENOMENON_VOLCANIC_ASH } ,
                                            { "Blowing Sand", PHENOMENON_SANDSTORM } ,
                                            { "Blowing Dust", PHENOMENON_DUSTSTORM } ,
                                            { "Blowing Snow", PHENOMENON_FUNNEL_CLOUD } ,
                                            { "Drizzle", PHENOMENON_DRIZZLE } ,
                                            { "Rain", PHENOMENON_RAIN } ,
                                            { "Snow", PHENOMENON_SNOW } ,
                                            { "Fog", PHENOMENON_FOG } ,
                                            { "Smoke", PHENOMENON_SMOKE } ,
                                            { "Sand", PHENOMENON_SAND } ,
                                            { "Haze", PHENOMENON_HAZE } ,
                                            { "Dust", PHENOMENON_DUST } /*,
                                            { "", PHENOMENON_SNOW_GRAINS } ,
                                            { "", PHENOMENON_ICE_PELLETS } ,
                                            { "", PHENOMENON_HAIL } ,
                                            { "", PHENOMENON_SMALL_HAIL } ,
                                            { "", PHENOMENON_UNKNOWN_PRECIPITATION } ,
                                            { "", PHENOMENON_MIST } ,
                                            { "", PHENOMENON_SPRAY } ,
                                            { "", PHENOMENON_SQUALL } ,
                                            { "", PHENOMENON_TORNADO } ,
                                            { "", PHENOMENON_DUST_WHIRLS } */
                                        };
                                        struct _sky_list {
                                            const char *name;
                                            WeatherSky sky;
                                        } sky_list[] = {
                                            { "Mostly Sunny", SKY_BROKEN } ,
                                            { "Mostly Clear", SKY_BROKEN } ,
                                            { "Partly Cloudy", SKY_SCATTERED } ,
                                            { "Mostly Cloudy", SKY_FEW } ,
                                            { "Sunny", SKY_CLEAR } ,
                                            { "Clear", SKY_CLEAR } ,
                                            { "Cloudy", SKY_OVERCAST } ,
                                            { "Clouds", SKY_SCATTERED } ,
                                            { "Rain", SKY_SCATTERED } ,
                                            { "Snow", SKY_SCATTERED }
                                        };

                                        nfo->valid = TRUE;
                                        g_free (nfo->forecast);
                                        nfo->forecast = g_strdup ((const char *)val);

                                        for (i = 0; i < G_N_ELEMENTS (ph_list); i++) {
                                            if (strstr ((const char *)val, ph_list [i].name)) {
                                                nfo->cond.phenomenon = ph_list [i].ph;
                                                break;
                                            }
                                        }

                                        for (i = 0; i < G_N_ELEMENTS (sky_list); i++) {
                                            if (strstr ((const char *)val, sky_list [i].name)) {
                                                nfo->sky = sky_list [i].sky;
                                                break;
                                            }
                                        }
                                    }

                                    if (val)
                                        xmlFree (val);

                                    at = at->next;
                                }
                            }
                        }
                    }

                    if (res) {
                        gboolean have_any = FALSE;
                        GSList *r;

                        /* Remove invalid forecast data from the list.
                           They should be all valid or all invalid. */
                        for (r = res; r; r = r->next) {
                            WeatherInfo *nfo = r->data;

                            if (!nfo || !nfo->valid) {
                                if (r->data)
                                    weather_info_free (r->data);

                                r->data = NULL;
                            } else {
                                have_any = TRUE;

                                if (nfo->tempMinMaxValid)
                                    nfo->temp = (nfo->temp_min + nfo->temp_max) / 2.0;
                            }
                        }

                        if (!have_any) {
                            /* data members are freed already */
                            g_slist_free (res);
                            res = NULL;
                        }
                    }

                    break;
                }
            }

            g_free (time_layout);

            /* stop seeking XML */
            break;
        }
    }
    xmlFreeDoc (doc);

    #undef XC
    #undef isElem

    return res;
}

static void
iwin_finish (SoupSession *session, SoupMessage *msg, gpointer data)
{
    WeatherInfo *info = (WeatherInfo *)data;

    g_return_if_fail (info != NULL);

    if (!SOUP_STATUS_IS_SUCCESSFUL (msg->status_code)) {
        /* forecast data is not really interesting anyway ;) */
        g_warning ("Failed to get IWIN forecast data: %d %s\n",
                   msg->status_code, msg->reason_phrase);
        request_done (info, FALSE);
        return;
    }

    if (info->forecast_type == FORECAST_LIST)
        info->forecast_list = parseForecastXml (msg->response_body->data, info);
    else
        info->forecast = formatWeatherMsg (g_strdup (msg->response_body->data));

    request_done (info, TRUE);
}

/* Get forecast into newly alloc'ed string */
void
iwin_start_open (WeatherInfo *info)
{
    gchar *url, *state, *zone;
    WeatherLocation *loc;
    SoupMessage *msg;

    g_return_if_fail (info != NULL);
    loc = info->location;
    g_return_if_fail (loc != NULL);

    if (loc->zone[0] == '-' && (info->forecast_type != FORECAST_LIST || !loc->latlon_valid))
        return;

    if (info->forecast) {
        g_free (info->forecast);
        info->forecast = NULL;
    }

    free_forecast_list (info);    

    if (info->forecast_type == FORECAST_LIST) {
        /* see the description here: http://www.weather.gov/forecasts/xml/ */
        if (loc->latlon_valid) {
            struct tm tm;
            time_t now = time (NULL);

            localtime_r (&now, &tm);

            url = g_strdup_printf ("http://www.weather.gov/forecasts/xml/sample_products/browser_interface/ndfdBrowserClientByDay.php?&lat=%.02f&lon=%.02f&format=24+hourly&startDate=%04d-%02d-%02d&numDays=7",
                       RADIANS_TO_DEGREES (loc->latitude), RADIANS_TO_DEGREES (loc->longitude), 1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday);

            msg = soup_message_new ("GET", url);
            g_free (url);
            soup_session_queue_message (info->session, msg, iwin_finish, info);

            info->requests_pending++;
        }

        return;
    }

    if (loc->zone[0] == ':') {
        /* Met Office Region Names */
        metoffice_start_open (info);
        return;
    } else if (loc->zone[0] == '@') {
        /* Australian BOM forecasts */
        bom_start_open (info);
        return;
    }

    /* The zone for Pittsburgh (for example) is given as PAZ021 in the locations
    ** file (the PA stands for the state pennsylvania). The url used wants the state
    ** as pa, and the zone as lower case paz021.
    */
    zone = g_ascii_strdown (loc->zone, -1);
    state = g_strndup (zone, 2);

    url = g_strdup_printf ("http://weather.noaa.gov/pub/data/forecasts/zone/%s/%s.txt", state, zone);

    g_free (zone);
    g_free (state);
    
    msg = soup_message_new ("GET", url);
    g_free (url);
    soup_session_queue_message (info->session, msg, iwin_finish, info);

    info->requests_pending++;
}