This file is indexed.

/usr/share/avant-window-navigator/applets/weather/weather.py is in awn-applet-weather 0.4.1~bzr1507-0ubuntu7.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
#!/usr/bin/python
# Copyright (C) 2007, 2008:
#   Mike Rooney (launchpad.net/~michael) <mrooney@gmail.com>
#   Mike (mosburger) Desjardins <desjardinsmike@gmail.com>
#     Please do not email the above person for support. The 
#     email address is only there for license/copyright purposes.
# Copyright (C) 2009 - 2010  onox <denkpadje@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import with_statement

from contextlib import closing, contextmanager
import os
import re
import urllib2
from xml.dom import minidom

import pygtk
pygtk.require("2.0")
import gtk

from awn.extras import _, awnlib, __version__
from awn.extras.threadqueue import ThreadQueue, async_method
from awn import OverlayText, OverlayThrobber, OverlayThemedIcon

import cairo
import glib

applet_name = _("Weather")
applet_description = _("Applet to display current weather and forecast")

# Applet's themed icon, also shown in the GTK About dialog
applet_logo = "weather-few-clouds"

# Interval in minutes between updating conditions, forecast, and map
update_interval = 30

# Timeout in seconds of network operations
socket_timeout = 20

# Import socket to set the default timeout, it is unlimited by default!
import socket
socket.setdefaulttimeout(socket_timeout)

ui_file = os.path.join(os.path.dirname(__file__), "weather.ui")

temperature_units = [_("Celsius"), _("Fahrenheit")]
font_sizes = (15.0, 18.0, 23.0)

system_theme_name = _("System theme")

theme_dir = "/usr/share/icons"

icon_states = ["twc-logo", "weather-clear", "weather-few-clouds", "weather-overcast",
"weather-snow-and-rain", "weather-showers", "weather-showers-scattered",
"weather-snow", "weather-fog", "weather-storm", "weather-severe-alert",
"weather-clear-night", "weather-few-clouds-night"]

network_error_message = _("Could not retrieve weather data. You may be experiencing connectivity issues.")

import forecast

disconnect_counter = {}
throbber_counter = {}

overlay_fsm = None


class OverlayStateMachine:

    def __init__(self, disconnect, throbber):
        self.disconnect_overlay = disconnect
        self.throbber_overlay = throbber

        # Set initial state
        self.set_next(IdleState)

    def set_next(self, state):
        self.__state = state(self)

    def evaluate(self):
        glib.idle_add(self.__state.evaluate)


class BaseState:

    def __init__(self, handler, throbber, disconnect):
        self.handler = handler

        self.handler.throbber_overlay.props.active = throbber
        self.handler.disconnect_overlay.props.active = disconnect

    def evaluate(self):
        disconnected = any(disconnect_counter.values())
        busy = any(throbber_counter.values())

        if busy and disconnected:
            self.handler.set_next(RefreshAndErrorState)
        elif busy and not disconnected:
            self.handler.set_next(RefreshState)
        elif not busy and disconnected:
            self.handler.set_next(ErrorState)
        else:
            self.handler.set_next(IdleState)


class IdleState(BaseState):

    def __init__(self, handler):
        BaseState.__init__(self, handler, False, False)


class RefreshState(BaseState):

    def __init__(self, handler):
        BaseState.__init__(self, handler, True, False)


class ErrorState(BaseState):

    def __init__(self, handler):
        BaseState.__init__(self, handler, False, True)


class RefreshAndErrorState(BaseState):

    def __init__(self, handler):
        BaseState.__init__(self, handler, True, False)


def with_overlays(func):
    """Makes the throbber visible while refreshing and
    the 'disconnect' icon if an error has occurred.

    """
    throbber_counter[func] = False
    disconnect_counter[func] = False
    def activate_throbber(do_show):
        throbber_counter[func] = do_show
        overlay_fsm.evaluate()
    def active_icon(is_error):
        disconnect_counter[func] = is_error
        overlay_fsm.evaluate()
    def bound_func(obj, *args, **kwargs):
        activate_throbber(True)
        try:
            result = func(obj, *args, **kwargs)
            active_icon(False)
            return result
        except:
            active_icon(True)
            raise
        finally:
            activate_throbber(False)
    return bound_func


@contextmanager
def unlink_xml(socket):
    xmldoc = minidom.parse(socket)
    try:
        yield xmldoc
    finally:
        xmldoc.unlink()


class NetworkException(Exception):
    pass


def network_exception(func):
    def bound_func(obj, *args, **kwargs):
        try:
            return func(obj, *args, **kwargs)
        except IOError, e:
            raise NetworkException("error in %s: %s" % (func.__name__, e))
        except StandardError:
            raise
        except Exception, e:
            raise NetworkException("error in %s: %s" % (func.__name__, e))
    return bound_func


class WeatherApplet:

    def __init__(self, applet):
        self.applet = applet

        self.weather_fail = [False, False, False]
        self.reset_weather_data()

        self.network_handler = self.NetworkHandler()
        self.notification = applet.notification.create(_("Network error in Weather"), network_error_message, "dialog-warning", 20)

        self.setup_context_menu()

        self.forecaster = forecast.Forecast(self)

        # Set default icons/titles/dialogs so the applet is informative without data
        self.set_icon()
        self.applet.tooltip.set("%s %s..."%(_("Fetching conditions for"), self.applet.settings['location']))

        # Overlays
        self.__temp_overlay = OverlayText()
        self.__temp_overlay.props.gravity = gtk.gdk.GRAVITY_SOUTH
        applet.add_overlay(self.__temp_overlay)

        disconnect_overlay = OverlayThemedIcon("gtk-disconnect")
        disconnect_overlay.props.alpha = 1.0
        throbber_overlay = OverlayThrobber()

        for i in (disconnect_overlay, throbber_overlay):
            i.props.scale = 0.5
            i.props.gravity = gtk.gdk.GRAVITY_SOUTH_EAST
            i.props.apply_effects = False
            applet.add_overlay(i)

        global overlay_fsm
        overlay_fsm = OverlayStateMachine(disconnect_overlay, throbber_overlay)

        # Set up the timer which will refresh the conditions, forecast, and weather map
        applet.timing.register(self.activate_refresh_cb, update_interval * 60)
        applet.timing.delay(self.activate_refresh_cb, 1.0)

    def network_error_cb(self, e, tb):
        if type(e) is NetworkException:
            print "Error in Weather:", e
            self.notification.show()

            if all(self.weather_fail):
                # Clean up weather map
                self.map_item.set_sensitive(False)
                if self.map_dialog is not None:
                    self.applet.dialog.unregister("secondary")
                self.reset_weather_data()

                # Clean up forecast dialog
                self.forecaster.finalize_dialog()

                # Clean up conditions (icon)
                self.__temp_overlay.props.active = False
                self.set_icon()
                self.applet.tooltip.set("%s %s..."%(_("Fetching conditions for"), self.applet.settings['location']))
        else:
            self.applet.errors.set_error_icon_and_click_to_restart()
            self.applet.errors.general(e, traceback=tb, callback=gtk.main_quit)

    def reset_weather_data(self):
        self.cached_conditions = None
        self.map_dialog = None
        self.map_vbox = None
        self.map_pixbuf = None

    def setup_context_menu(self):
        """Add "refresh" to the context menu and setup the preferences.

        """
        menu = self.applet.dialog.menu
        menu_index = len(menu) - 1

        self.map_item = gtk.MenuItem(_("Show _Map"))
        self.map_item.connect("activate", self.activate_map_cb)
        menu.insert(self.map_item, menu_index)
        self.map_item.set_sensitive(False)

        refresh_item = gtk.ImageMenuItem(stock_id=gtk.STOCK_REFRESH)
        refresh_item.connect("activate", self.activate_refresh_cb)
        menu.insert(refresh_item, menu_index + 1)

        menu.insert(gtk.SeparatorMenuItem(), menu_index + 2)

        prefs = gtk.Builder()
        prefs.add_from_file(ui_file)

        preferences_vbox = self.applet.dialog.new("preferences").vbox
        prefs.get_object("dialog-vbox").reparent(preferences_vbox)

        self.setup_preferences(prefs)

    def setup_preferences(self, prefs):
        refresh_dialog = lambda v: self.refresh_icon_and_forecast()
        def refresh_curved_dialog(value):
            self.forecaster.setup_forecast_dialog()
            refresh_dialog(None)  # dummy value
        refresh_map = lambda v: self.set_map_pixbuf(self.map_pixbuf)

        # Only use themes that are likely to provide all the files
        def filter_theme(theme):
            return os.path.isfile(os.path.join(theme_dir, theme, "scalable/status/weather-clear.svg")) \
                or os.path.isfile(os.path.join(theme_dir, theme, "48x48/status/weather-clear.png")) \
                or os.path.isfile(os.path.join(theme_dir, theme, "48x48/status/weather-clear.svg"))
        themes = sorted(filter(filter_theme, os.listdir(theme_dir)))
        self.themes = [system_theme_name] + themes + ["moonbeam"]

        def refresh_theme_and_dialog(value):
            self.setup_theme()
            refresh_dialog(None)

        self.setup_theme()

        """ General preferences """
        self.search_window = prefs.get_object("locations-search-dialog")
        def response_event_cb(widget, response):
            if response < 0:
                self.search_window.hide()
        self.search_window.connect("response", response_event_cb)
        self.search_window.connect("delete_event", lambda w, e: True)
        def location_button_clicked_cb(widget):
            self.init_search_window()
            self.search_list.append([_("No records found"), None])
            self.search_window.show_all()
        prefs.get_object("button-location").connect("clicked", location_button_clicked_cb)

        unit_combobox = prefs.get_object("combobox-temperature-unit")
        awnlib.add_cell_renderer_text(unit_combobox)
        for i in temperature_units:
            unit_combobox.append_text(i)

        theme_combobox = prefs.get_object("combobox-theme")
        awnlib.add_cell_renderer_text(theme_combobox)
        for i in self.themes:
            theme_combobox.append_text(i)
        if self.applet.settings["theme"] not in self.themes:
            self.applet.settings["theme"] = self.themes[0]

        tempicon_checkbutton = prefs.get_object("checkbutton-temperature-icon")
        fontsize_hbox = prefs.get_object("hbox-font-size")
        fontsize_hbox.set_sensitive(tempicon_checkbutton.get_active())
        tempicon_checkbutton.connect("toggled", lambda w: fontsize_hbox.set_sensitive(w.get_active()))

        self.location_label = prefs.get_object("locationLabel")
        self.location_label.set_markup("<b>%s</b>" % self.applet.settings["location"])

        binder = self.applet.settings.get_binder(prefs)
        binder.bind("show-temperature-icon", "checkbutton-temperature-icon", key_callback=self.refresh_icon)
        binder.bind("temperature-font-size", "combobox-font-size", key_callback=self.refresh_icon)
        binder.bind("temperature-unit", "combobox-temperature-unit", key_callback=refresh_dialog)
        binder.bind("theme", "combobox-theme", key_callback=refresh_theme_and_dialog)
        binder.bind("curved_dialog", "curvedCheckbutton", key_callback=refresh_curved_dialog)
        binder.bind("map_maxwidth", "mapWidthSpinbutton", key_callback=refresh_map)
        self.applet.settings.load_bindings(binder)

        """ Location search window """
        self.search_list = gtk.ListStore(str, str)

        self.treeview = prefs.get_object("location-treeview")
        self.treeview.set_model(self.search_list)
        self.treeview.append_column(gtk.TreeViewColumn("Location", gtk.CellRendererText(), text=0))

        self.ok_button = prefs.get_object("location-ok-button")
        self.ok_button.connect("clicked", self.ok_button_clicked_cb)

        self.treeview.connect("cursor-changed", lambda w: self.ok_button.set_sensitive(True))
        self.treeview.connect("row-activated", lambda v, p, c: self.ok_button_clicked_cb())

        find_button = prefs.get_object("location-find-button")

        self.location_entry = prefs.get_object("location-entry")
        def location_entry_changed_cb(widget):
            find_button.set_sensitive(len(self.location_entry.get_text()) > 0)
        self.location_entry.connect("changed", location_entry_changed_cb)

        self.location_entry.connect("activate", self.search_locations_cb)
        find_button.connect("clicked", self.search_locations_cb)

    def refresh_icon_and_forecast(self):
        self.refresh_icon()
        self.forecaster.refresh_unit()

    def init_search_window(self):
        self.search_list.clear()
        self.treeview.set_sensitive(False)
        self.ok_button.set_sensitive(False)

    def search_locations_cb(self, widget):
        text = self.location_entry.get_text()
        if len(text) > 0:
            self.init_search_window()
            self.search_list.append([_("Searching..."), None])

            def cb(locations):
                self.search_list.clear()
                if len(locations) > 0:
                    self.treeview.set_sensitive(True)
                    for i in locations:
                        self.search_list.append(i)
                else:
                    self.search_list.append([_("No records found"), None])
            self.network_handler.get_locations(text, callback=cb, error=self.network_error_cb)

    def ok_button_clicked_cb(self, widget=None):
        (model, iter) = self.treeview.get_selection().get_selected()
        self.applet.settings["location_code"] = model.get_value(iter, 1)
        self.applet.settings["location"] = model.get_value(iter, 0)

        self.location_label.set_markup("<b>%s</b>" % self.applet.settings["location"])
        self.activate_refresh_cb()

        self.search_window.hide()

    def activate_map_cb(self, widget):
        if self.map_dialog is not None:
            self.map_dialog.show_all()

    def activate_refresh_cb(self, widget=None, map=True):
        """Refresh the icon, forecast, and map data. Called by the
        "Refresh" option in the context menu.

        """
        self.refresh_conditions()
        self.forecaster.refresh_forecast()
        if map:
            self.fetch_weather_map()

    def setup_theme(self):
        def refresh_theme():
            states_names = {}
            for i in icon_states:
                states_names[i] = i
            self.applet.theme.set_states(states_names)

            theme = self.applet.settings["theme"] if self.applet.settings["theme"] != system_theme_name else None
            self.applet.theme.theme(theme)
        glib.idle_add(refresh_theme)

    def set_icon(self, hint="twc"):
        def refresh_overlay():
            state = self.get_icon_name(hint, self.applet.settings["theme"])
            self.applet.theme.icon(state)

            if hint != 'twc':
                self.__temp_overlay.props.font_sizing = font_sizes[self.applet.settings['temperature-font-size']]
                self.__temp_overlay.props.text = tempText = self.convert_temperature(self.cached_conditions['TEMP']) + u"\u00B0"
                self.__temp_overlay.props.active = bool(self.applet.settings["show-temperature-icon"])
        glib.idle_add(refresh_overlay)

    def refresh_conditions(self, retries=3):
        """Download the current weather conditions. If this fails, or the
        conditions are unchanged, don't do anything. Refresh the applet's
        title and icon if the conditions have changed.

        """
        def cb(conditions):
            self.weather_fail[0] = False
            if conditions != self.cached_conditions:
                self.cached_conditions = conditions
                self.refresh_icon()
        def error_cb(e, tb):
            if type(e) is NetworkException and retries > 0:
                print "Warning in Weather:", e
                delay_seconds = 10.0
                print "Reattempt (%d retries remaining) in %d seconds" % (retries, delay_seconds)
                self.applet.timing.delay(lambda: self.refresh_conditions(retries - 1), delay_seconds)
            else:
                self.weather_fail[0] = True
                self.network_error_cb(e, tb)
        self.network_handler.get_conditions(self.applet.settings['location_code'], callback=cb, error=error_cb)

    def refresh_icon(self, dummy_value=None):
        if self.cached_conditions is not None:
            unit = self.get_temperature_unit()
            temp = self.convert_temperature(self.cached_conditions['TEMP'])
            title = "%s: %s, %s" % (self.cached_conditions['CITY'], _(self.cached_conditions['DESCRIPTION']), temp + u" \u00B0" + unit)
            # display the "Feels Like" temperature in parens, if it is different from the actual temperature
            if self.cached_conditions['TEMP'] != self.cached_conditions['FEELSLIKE']:
                feels_like = self.convert_temperature(self.cached_conditions['FEELSLIKE'])
                if feels_like != "N/A" and feels_like != temp:
                    title += " (%s)" % (feels_like + u" \u00B0" + unit)
    
            self.applet.tooltip.set(title)
            self.set_icon(self.cached_conditions["CODE"])

    def fetch_forecast(self, forecast_cb, retries=3):
        """Use weather.com's XML service to download the latest 5-day
        forecast.

        """
        def cb(forecast):
            self.weather_fail[1] = False
            forecast_cb(forecast)
        def error_cb(e, tb):
            if type(e) is NetworkException and retries > 0:
                print "Warning in Weather:", e
                delay_seconds = 10.0
                print "Reattempt (%d retries remaining) in %d seconds" % (retries, delay_seconds)
                self.applet.timing.delay(lambda: self.fetch_forecast(cb, retries - 1), delay_seconds)
            else:
                self.weather_fail[1] = True
                self.network_error_cb(e, tb)
        self.network_handler.get_forecast(self.applet.settings['location_code'], callback=cb, error=error_cb)

    def fetch_weather_map(self, retries=3):
        """Download the latest weather map from weather.com, storing it
        as a pixbuf, and create a dialog with the new map.

        """
        def cb(pixbuf):
            self.weather_fail[2] = False
            self.set_map_pixbuf(pixbuf)
        def error_cb(e, tb):
            if type(e) is NetworkException and retries > 0:
                print "Warning in Weather:", e
                delay_seconds = 10.0
                print "Reattempt (%d retries remaining) in %d seconds" % (retries, delay_seconds)
                self.applet.timing.delay(lambda: self.fetch_weather_map(retries - 1), delay_seconds)
            else:
                self.weather_fail[2] = True
                self.network_error_cb(e, tb)
        self.network_handler.get_weather_map(self.applet.settings['location_code'], callback=cb, error=error_cb)

    def set_map_pixbuf(self, pixbuf):
        """Create a map dialog from the current already-downloaded map
        image. Note that this does not show the dialog, it simply
        creates it. awnlib handles the rest.

        """
        if pixbuf is None:
            return
        if self.map_dialog is None or self.map_vbox is None:
            self.map_dialog = self.applet.dialog.new("secondary", title=self.applet.settings['location'])
            self.map_vbox = gtk.VBox()
            self.map_dialog.add(self.map_vbox)
        else:
            for i in self.map_vbox.get_children():
                self.map_vbox.remove(i)
            self.map_dialog.set_title(self.applet.settings['location'])

        self.map_pixbuf = pixbuf

        map_size = pixbuf.get_width(), pixbuf.get_height()

        # resize if necessary as defined by map_maxwidth
        ratio = float(self.applet.settings['map_maxwidth']) / map_size[0]
        if ratio < 1:
            width, height = [int(ratio * dim) for dim in map_size]
            pixbuf = pixbuf.scale_simple(width, height, gtk.gdk.INTERP_BILINEAR)

        self.map_vbox.add(gtk.image_new_from_pixbuf(pixbuf))
        self.map_item.set_sensitive(True)

    def convert_temperature(self, value):
        unit = temperature_units[self.applet.settings["temperature-unit"]]
        try:
            value = float(value)
        except ValueError:
            return "N/A"

        if _("Fahrenheit") == unit:
            converted_value = value
        elif _("Celsius") == unit:
            converted_value = 5.0 * (value - 32.0) / 9.0
        return str(int(round(converted_value)))

    def get_temperature_unit(self):
    	if temperature_units[self.applet.settings["temperature-unit"]] == _("Celsius"):
    	    return "C"
    	else:
    	    return "F"

    def get_icon_name(self, hint, theme):
        if hint == "twc":
            return "twc-logo"

        hint = int(hint)

        if hint in (32, 34, 36):
            return "weather-clear"
        elif hint in (23, 24, 25, 28, 30, 44):
            return "weather-few-clouds"
        elif hint in (26, ):
            return "weather-overcast"
        elif hint in (5, 6, 7, 8, 9, 10, 11, 12, 39, 45):
            # Special conditional for the extreme weather in moonbeam's Ottawa
            if theme == "moonbeam" and hint in (5, 6, 7):
                return "weather-snow-and-rain"
            return "weather-showers"
        elif hint in (40, ):
            return "weather-showers-scattered"
        elif hint in (13, 14, 15, 16, 17, 18, 41, 42, 43, 46):
            return "weather-snow"
        elif hint in (19, 20, 21, 22):
            return "weather-fog"
        elif hint in (4, 35, 37, 38, 47):
            return "weather-storm"
        elif hint in (0, 1, 2, 3):
            return "weather-severe-alert"
        elif hint in (31, 33):
            return "weather-clear-night"
        elif hint in (27, 29):
            return "weather-few-clouds-night"

    class NetworkHandler(ThreadQueue):

        __ws_key = "&prod=xoap&par=1048871467&key=12daac2f3a67cb39&link=xoap"

        def dict_from_xml(self, rootNode, keys, paths):
            """Given an XML node, iterate over keys and paths, grabbing the
            value from each path and putting it into the dictionary as the
            given key.

            """
            return_dict = {}
            for key, path in zip(keys, paths):
                items = path.split('/')
                cnode = rootNode
                for item in items:
                    cnode = cnode.getElementsByTagName(item)[0]
                return_dict[key] = "".join([node.data for node in cnode.childNodes if node.nodeType == node.TEXT_NODE])
            return return_dict

        @async_method
        @network_exception
        def get_locations(self, text):
            url = "http://xoap.weather.com/search/search?where=" + urllib2.quote(text)
            with closing(urllib2.urlopen(url)) as usock:
                with unlink_xml(usock) as xmldoc:
                    locations_list = []
                    for i in xmldoc.getElementsByTagName("loc"):
                        city = i.childNodes[0].data
                        code = i.getAttribute("id")
                        locations_list.append([city, code])
                    return locations_list

        @async_method
        @with_overlays
        @network_exception
        def get_conditions(self, location_code):
            url = "http://xoap.weather.com/weather/local/" + location_code + "?cc=*" + self.__ws_key
            with closing(urllib2.urlopen(url)) as usock:
                with unlink_xml(usock) as xmldoc:
                    names = ['CITY', 'SUNRISE', 'SUNSET', 'DESCRIPTION', 'CODE', 'TEMP', 'FEELSLIKE', 'BAR', 'BARDESC', 'WINDSPEED', 'WINDGUST', 'WINDDIR', 'HUMIDITY', 'MOONPHASE']
                    paths = ['weather/loc/dnam', 'sunr', 'suns', 'cc/t', 'cc/icon', 'cc/tmp', 'cc/flik', 'cc/bar/r', 'cc/bar/d', 'cc/wind/s', 'cc/wind/gust', 'cc/wind/d', 'cc/hmid', 'cc/moon/t']
                    try:
                        return self.dict_from_xml(xmldoc, names, paths)
                    except IndexError, e:
                        raise NetworkException("Couldn't parse conditions: %s" % e)

        @async_method
        @network_exception
        def get_weather_map(self, location_code):
            map_url = "http://www.weather.com/outlook/travel/businesstraveler/map/%s" % location_code
            with closing(urllib2.urlopen(map_url)) as usock:
                mapExp = """<IMG NAME="mapImg" SRC="([^\"]+)" WIDTH=([0-9]+) HEIGHT=([0-9]+) BORDER"""
                result = re.findall(mapExp, usock.read())
                if not result or len(result) != 1:
                    raise NetworkException("Couldn't parse weather map")
                with closing(urllib2.urlopen(result[0][0])) as raw_image:
                    try:
                        with closing(gtk.gdk.PixbufLoader()) as loader:
                            loader.write(raw_image.read())
                            return loader.get_pixbuf()
                    except glib.GError, e:
                        raise NetworkException("Couldn't parse weather map: %s" % e)

        @async_method
        @with_overlays
        @network_exception
        def get_forecast(self, location_code):
            url = "http://xoap.weather.com/weather/local/" + location_code + "?dayf=5" + self.__ws_key
            with closing(urllib2.urlopen(url)) as usock:
                with unlink_xml(usock) as xmldoc:
                    try:
                        forecast = {'DAYS': []} #, 'CITY': cachedConditions['CITY']}
                        cityNode = xmldoc.getElementsByTagName('loc')[0].getElementsByTagName('dnam')[0]
                        forecast['CITY'] = ''.join([node.data for node in cityNode.childNodes if node.nodeType == node.TEXT_NODE])

                        dayNodes = xmldoc.getElementsByTagName('dayf')[0].getElementsByTagName('day')
                        for dayNode in dayNodes:
                            names = ['HIGH', 'LOW', 'CODE', 'DESCRIPTION', 'PRECIP', 'HUMIDITY', 'WSPEED', 'WDIR', 'WGUST']
                            paths = ['hi', 'low', 'part/icon', 'part/t', 'part/ppcp', 'part/hmid', 'part/wind/s', 'part/wind/t', 'part/wind/gust']
                            day = self.dict_from_xml(dayNode, names, paths)
                            day.update({'WEEKDAY': dayNode.getAttribute('t'), 'YEARDAY': dayNode.getAttribute('dt')})
                            forecast['DAYS'].append(day)
                        return forecast
                    except IndexError, e:
                        raise NetworkException("Couldn't parse forecast: %s" % e)


if __name__ == "__main__":
    awnlib.init_start(WeatherApplet, {
        "name": applet_name, "short": "weather",
        "description": applet_description,
        "version": __version__,
        "author": "onox, Mike Desjardins, Mike Rooney",
        "copyright-year": "2007 - 2009",
        "theme": applet_logo,
        "authors": ["Mike Desjardins", "Mike Rooney", "Isaac J.", "onox <denkpadje@gmail.com>"],
        "artists": ["Wojciech Grzanka", "Mike Desjardins"]})