def __init__(self):
		if dbus.SessionBus().request_name('es.atareao.MyWeatherIndicator') != dbus.bus.REQUEST_NAME_REPLY_PRIMARY_OWNER:
			print("application already running")
			exit(0)		
		#
		self.last_notification = 0
		self.actualization_time = 0
		self.current_conditions = None
		self.current_conditions2 = None
		self.preferences_out = False
		self.forecast_out = False
		#
		self.notification = Notify.Notification.new('','', None)
		self.indicator = appindicator.Indicator.new('My-Weather-Indicator', 'My-Weather-Indicator', appindicator.IndicatorCategory.APPLICATION_STATUS)
		self.notification2 = Notify.Notification.new('','', None)
		self.indicator2 = appindicator.Indicator.new('My-Weather-Indicator2', 'My-Weather-Indicator', appindicator.IndicatorCategory.APPLICATION_STATUS)
		#
		self.create_menu()
		self.create_menu2()
		#
		while internet_on() == False:
			wait(1)
		print(comun.CONFIG_FILE,os.path.exists(comun.CONFIG_FILE))
		if not os.path.exists(comun.CONFIG_FILE):
			configuration = Configuration()
			configuration.reset()
			latitude,longitude = ipaddress.get_current_location()
			city = geocodeapi.get_inv_direction(latitude,longitude)
			configuration.set('latitude',latitude)
			configuration.set('longitude',longitude)
			if city is not None:
				configuration.set('location',city['city'])
			configuration.save()
			cm=preferences.CM()
			if cm.run() == Gtk.ResponseType.ACCEPT:
				cm.save_preferences()
			else:
				exit(0)
			cm.hide()
			cm.destroy()
		self.WW1 = None
		self.WW2 = None
		self.load_preferences()
		self.actualization_time = 0
		self.seclast = 60
		self.work()
		'''
		while(datetime.now().second !=0):
			wait(0.1)
		utcnow = datetime.utcnow()
		if self.WW1 is not None:
			self.WW1.set_datetime(utcnow)
		if self.WW2 is not None:
			self.WW2.set_datetime(utcnow)
		'''
		GLib.timeout_add(500, self.update_widgets)
		GLib.timeout_add(60000, self.work)		
 def looking_for_internet(self):
     print('*** Looking For Internet ***')
     if internet_on():
         print('*** Internet Found ***')
         self.stop_looking_for_internet()
         self.start_weather_updater()
         self.start_widgets_updater()
         return False
     print('*** Internet Not Found ***')
     self.stop_weather_updater()
     self.stop_widgets_updater()
     return True
 def looking_for_internet(self):
     print('*** Looking For Internet ***')
     if internet_on():
         print('*** Internet Found ***')
         self.stop_looking_for_internet()
         self.start_weather_updater()
         self.start_widgets_updater()
         return False
     print('*** Internet Not Found ***')
     self.stop_weather_updater()
     self.stop_widgets_updater()
     return True
	def work(self):
		ut = int(round((time.time()-self.actualization_time)/60.0,0))
		if self.actualization_time == 0:
			msg = _('Updated now')
		elif ut == 1:
			msg = _('Updated: 1 min ago')
		else:
			msg = _('Updated: %s mins ago'%ut)
		self.menu_refresh.set_label(_('Refresh weather')+
		' ('+msg+')')
		self.menu2_refresh.set_label(_('Refresh weather')+
		' ('+msg+')')
		'''
		utcnow = datetime.utcnow()
		if self.WW1 is not None:
			self.WW1.set_datetime(utcnow)
		if self.WW2 is not None:
			self.WW2.set_datetime(utcnow)
		'''
		print('///////////////////////////////////////////////////////')
		print('///////////////////////////////////////////////////////')
		print('time.time() = %s'%int(time.time()))
		print('self.actualization_time = %s'%int(self.actualization_time))
		print('(time.time()-self.actualization_time) = %s'%int((time.time()-self.actualization_time)))
		print('self.refresh*3600 = %s'%(int(self.refresh*3600)))
		print('///////////////////////////////////////////////////////')
		print('///////////////////////////////////////////////////////')
		if (time.time()-self.actualization_time) > self.refresh*3600:
			while internet_on() == False:
				wait(1)
				'''
				utcnow = datetime.utcnow()
				if self.WW1 is not None:
					self.WW1.set_datetime(utcnow)
				if self.WW2 is not None:
					self.WW2.set_datetime(utcnow)
				'''
			if self.main_location:
				self.set_menu()
				self.indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
			else:
				self.indicator.set_status(appindicator.IndicatorStatus.PASSIVE)
			if self.second_location:
				self.set_menu2()
				self.indicator2.set_status(appindicator.IndicatorStatus.ACTIVE)
			else:
				self.indicator2.set_status(appindicator.IndicatorStatus.PASSIVE)
			self.actualization_time = time.time()
		return True
def get_woeid(lat, lon):
    print('******* Adquiring woeids *******')
    tries = 3
    while (tries > 0 and internet_on()):
        try:
            url = URLINV_YAHOO2 % (LANG, lat, lon)
            jsonResponse = read_json_from_url(url)
            if int(jsonResponse['Found']) > 1:
                woeid = jsonResponse['Result'][0]['woeid']
            else:
                woeid = jsonResponse['Result']['woeid']
            return woeid
        except Exception as e:
            print('******* Error adquiring inv directions *******')
            print('Error:', e)
        tries -= 1
    return None
def get_woeid(lat, lon):
    print('******* Adquiring woeids *******')
    tries = 3
    while(tries > 0 and internet_on()):
        try:
            url = URLINV_YAHOO2 % (LANG, lat, lon)
            jsonResponse = read_json_from_url(url)
            if int(jsonResponse['Found']) > 1:
                woeid = jsonResponse['Result'][0]['woeid']
            else:
                woeid = jsonResponse['Result']['woeid']
            return woeid
        except Exception as e:
            print('******* Error adquiring inv directions *******')
            print('Error:', e)
        tries -= 1
    return None
    def update_menu(self, index):
        if not internet_on():
            print('--- Not internet connection ---')
            if self.icon_light:
                icon = os.path.join(
                    comun.ICONDIR,
                    weatherservice.CONDITIONS['not available']['icon-light'])
            else:
                icon = os.path.join(
                    comun.ICONDIR,
                    weatherservice.CONDITIONS['not available']['icon-dark'])
            self.indicators[index].set_icon(icon)
            self.indicators[index].set_label('', '')
            msg = weatherservice.CONDITIONS['not available']['text']
            msg += '\n' + _('Not Internet connection')
            image = os.path.join(
                comun.IMAGESDIR,
                weatherservice.CONDITIONS['not available']['image'])
            self.notifications[index].update(
                'My-Weather-Indicator',
                msg,
                image)
            self.notifications[index].show()
            return
        print('--- Updating data in location %s ---' % (index))
        if self.preferences[index]['autolocation']:
            lat, lon = ipaddress.get_current_location()
            location = geocodeapi.get_inv_direction(lat, lon)['city']
            if location is None:
                location = ''
            print(lat, lon, location)
            if self.preferences[index]['latitude'] != lat and\
                    self.preferences[index]['longitude'] != lon:
                self.preferences[index]['latitude'] = lat
                self.preferences[index]['longitude'] = lon
                self.preferences[index]['location'] = location
                if self.ws == 'worldweatheronline':
                    self.weatherservices[index] =\
                        worldweatheronlineapi.WorldWeatherOnlineService(
                            longitude=self.preferences[index]['longitude'],
                            latitude=self.preferences[index]['latitude'],
                            units=self.units,
                            key=self.key)
                    self.menus[index]['evolution'].hide()
                elif self.ws == 'openweathermap':
                    self.weatherservices[index] =\
                        wopenweathermapapi.OWMWeatherService(
                            longitude=self.preferences[index]['longitude'],
                            latitude=self.preferences[index]['latitude'],
                            units=self.units)
                    self.menus[index]['evolution'].show()
                elif self.ws == 'wunderground':
                    self.weatherservices[index] =\
                        wundergroundapi.UndergroundWeatherService(
                            longitude=self.preferences[index]['longitude'],
                            latitude=self.preferences[index]['latitude'],
                            units=self.units,
                            key=self.key)
                    self.menus[index]['evolution'].hide()
        print('****** Updating weather')
        weather = self.weatherservices[index].get_weather()
        print('****** Updated weather')
        print(self.weathers[index])
        if weather is None or (weather['ok'] is False and (
                self.weathers[index] is not None and
                self.weathers[index]['ok'] is True)):
            return
        temporal_current_conditions = weather['current_conditions']
        if len(temporal_current_conditions) != 0:
            self.current_conditions[index] = temporal_current_conditions
            self.weathers[index] = weather
            ########################################################
            if self.preferences[index]['location']:
                self.menus[index]['location'].set_label(
                    _('Location') + ': ' + self.preferences[index]['location'])
            self.menus[index]['temperature'].set_label(_('Temperature') + ': \
{0}{1:c}'.format(self.current_conditions[index]['temperature'], 176))
            self.menus[index]['humidity'].set_label(
                _('Humidity') + ': ' +
                self.current_conditions[index]['humidity'])
            self.menus[index]['feels_like'].set_label(_('Feels like') + ': \
{0}{1:c}'.format(self.current_conditions[index]['feels_like'], 176))
            self.menus[index]['dew_point'].set_label(_('Dew Point') + ': \
{0}{1:c}'.format(self.current_conditions[index]['dew_point'], 176))
            self.menus[index]['wind'].set_label(
                _('Wind') + ': ' +
                self.current_conditions[index]['wind_condition'])
            if self.current_conditions[index]['wind_icon']:
                image = Gtk.Image.new_from_file(
                    os.path.join(comun.IMAGESDIR,
                                 self.current_conditions[index]['wind_icon']))
                self.menus[index]['wind'].set_image(image)
            self.menus[index]['condition'].set_label(
                self.current_conditions[index]['condition_text'])
            self.menus[index]['condition'].set_image(
                Gtk.Image.new_from_file(os.path.join(
                    comun.IMAGESDIR,
                    self.current_conditions[index]['condition_image'])))
            if self.widgets[index] is not None:
                self.widgets[index].set_location(
                    self.preferences[index]['location'])
                self.widgets[index].set_weather(weather)
            self.menus[index]['dawn'].set_label(
                _('Dawn') + ': ' + self.current_conditions[index]['dawn'])
            self.menus[index]['sunrise'].set_label(
                _('Sunrise') + ': ' +
                self.current_conditions[index]['sunrise'])
            self.menus[index]['sunset'].set_label(
                _('Sunset') + ': ' + self.current_conditions[index]['sunset'])
            self.menus[index]['dusk'].set_label(
                _('Dusk') + ': ' + self.current_conditions[index]['dusk'])
            self.menus[index]['moon_phase'].set_label(
                self.current_conditions[index]['moon_phase'])
            self.menus[index]['moon_phase'].set_image(
                Gtk.Image.new_from_file(
                    os.path.join(comun.IMAGESDIR,
                                 self.current_conditions[index]['moon_icon'])))
            #
            pressure = (
                self.current_conditions[index]['pressure'] is not None)
            visibility = (
                self.current_conditions[index]['visibility'] is not None)
            cloudiness = (
                self.current_conditions[index]['cloudiness'] is not None)
            # solarradiation = (
            #    self.current_conditions[index]['solarradiation'] is not None)
            UV = (
                self.current_conditions[index]['UV'] is not None)
            precip_today = (
                self.current_conditions[index]['precip_today'] is not None)
            self.menus[index]['pressure'].set_visible(pressure)
            self.menus[index]['visibility'].set_visible(visibility)
            self.menus[index]['cloudiness'].set_visible(cloudiness)
            self.menus[index]['uv'].set_visible(UV)
            self.menus[index]['precipitation'].set_visible(precip_today)
            if pressure:
                self.menus[index]['pressure'].set_label(
                    ('%s: %s') % (_('Pressure'),
                                  self.current_conditions[index]['pressure']))
            if visibility:
                value = self.current_conditions[index]['visibility']
                self.menus[index]['visibility'].set_label(
                    ('%s: %s') % (_('Visibility'), value))
            if cloudiness:
                value = self.current_conditions[index]['cloudiness']
                self.menus[index]['cloudiness'].set_label(
                    ('%s: %s') % (_('Cloudiness'), value))
            if UV:
                value = self.current_conditions[index]['UV']
                self.menus[index]['uv'].set_label(
                    ('%s: %s') % (_('UV'), value))
            if precip_today:
                value = self.current_conditions[index]['precip_today']
                self.menus[index]['precipitation'].set_label(
                    ('%s: %s') % (_('Precipitation'), value))
            if self.preferences[index]['show-temperature'] is True:
                value = self.current_conditions[index]['temperature']
                self.indicators[index].set_label(
                    '{0}{1:c}'.format(value, 176), '')
            else:
                self.indicators[index].set_label('', '')
            if self.preferences[index]['show'] is True:
                self.indicators[index].set_status(
                    appindicator.IndicatorStatus.ACTIVE)
            else:
                self.indicators[index].set_status(
                    appindicator.IndicatorStatus.PASSIVE)
            if self.icon_light:
                icon = os.path.join(
                    comun.ICONDIR,
                    self.current_conditions[index]['condition_icon_light'])
            else:
                icon = os.path.join(
                    comun.ICONDIR,
                    self.current_conditions[index]['condition_icon_dark'])
            self.indicators[index].set_icon(icon)
            if self.preferences[index]['show-notifications'] is True:
                msg = _('Conditions in') + ' '
                msg += self.preferences[index]['location'] + '\n'
                msg += _('Temperature') + ': ' +\
                    self.current_conditions[index]['temperature'] + '\n'
                msg += _('Humidity') + ': ' + \
                    self.current_conditions[index]['humidity'] + '\n'
                msg += _('Wind') + ': ' +\
                    self.current_conditions[index]['wind_condition'] + '\n'
                msg += self.current_conditions[index]['condition_text']
                image = os.path.join(
                    comun.IMAGESDIR,
                    self.current_conditions[index]['condition_image'])
                self.notifications[index].update(
                    'My-Weather-Indicator',
                    msg,
                    image)
                self.notifications[index].show()
            while Gtk.events_pending():
                Gtk.main_iteration()
        print('--- End of updating data in location %s ---' % (index))
        self.last_update_time = time.time()
    def load_preferences(self):
        if not os.path.exists(comun.CONFIG_FILE):
            if internet_on():
                configuration = Configuration()
                configuration.reset()
                latitude, longitude = ipaddress.get_current_location()
                city = geocodeapi.get_inv_direction(
                    latitude, longitude)['city']
                if city is None:
                    city = ''
                configuration.set('latitude', latitude)
                configuration.set('longitude', longitude)
                configuration.set('location', city)
                configuration.save()
            cm = preferences.CM()
            if cm.run() == Gtk.ResponseType.ACCEPT:
                cm.save_preferences()
            else:
                exit(0)
            cm.hide()
            cm.destroy()
        configuration = Configuration()
        self.first_time = configuration.get('first-time')
        self.refresh = configuration.get('refresh')
        self.version = configuration.get('version')
        #
        self.preferences[0] = {}
        self.preferences[0]['show'] = configuration.get('main-location')
        self.preferences[0]['autolocation'] = configuration.get('autolocation')
        self.preferences[0]['location'] = configuration.get('location')
        self.preferences[0]['latitude'] = configuration.get('latitude')
        self.preferences[0]['longitude'] = configuration.get('longitude')
        self.preferences[0]['show-temperature'] =\
            configuration.get('show-temperature')
        self.preferences[0]['show-notifications'] =\
            configuration.get('show-notifications')
        self.preferences[0]['widget'] = configuration.get('widget1')
        #
        self.preferences[1] = {}
        self.preferences[1]['show'] = configuration.get('second-location')
        self.preferences[1]['autolocation'] = False
        self.preferences[1]['location'] = configuration.get('location2')
        self.preferences[1]['latitude'] = configuration.get('latitude2')
        self.preferences[1]['longitude'] = configuration.get('longitude2')
        self.preferences[1]['show-temperature'] =\
            configuration.get('show-temperature2')
        self.preferences[1]['show-notifications'] =\
            configuration.get('show-notifications2')
        self.preferences[1]['widget'] = configuration.get('widget2')
        #
        temperature = configuration.get('temperature')
        pressure = configuration.get('pressure')
        visibility = configuration.get('visibility')
        wind = configuration.get('wind')
        snow = configuration.get('snow')
        rain = configuration.get('rain')
        ampm = not configuration.get('24h')
        self.units = weatherservice.Units(temperature=temperature,
                                          wind=wind,
                                          pressure=pressure,
                                          visibility=visibility,
                                          snow=snow,
                                          rain=rain,
                                          ampm=ampm)
        self.ws = configuration.get('weather-service')
        if self.ws == 'yahoo':
            self.key = ''
            for i in range(INDICATORS):
                if self.preferences[i]['show']:
                    self.weatherservices[i] = wyahooapi.YahooWeatherService(
                        longitude=self.preferences[i]['longitude'],
                        latitude=self.preferences[i]['latitude'],
                        units=self.units)
                self.menus[i]['evolution'].hide()
        elif self.ws == 'worldweatheronline':
            self.key = configuration.get('wwo-key')
            for i in range(INDICATORS):
                if self.preferences[i]['show']:
                    self.weatherservices[i] =\
                        worldweatheronlineapi.WorldWeatherOnlineService(
                            longitude=self.preferences[i]['longitude'],
                            latitude=self.preferences[i]['latitude'],
                            units=self.units,
                            key=self.key)
                self.menus[i]['evolution'].hide()
        elif self.ws == 'openweathermap':
            self.key = ''
            for i in range(INDICATORS):
                if self.preferences[i]['show']:
                    self.weatherservices[i] =\
                        wopenweathermapapi.OWMWeatherService(
                            longitude=self.preferences[i]['longitude'],
                            latitude=self.preferences[i]['latitude'],
                            units=self.units)
                self.menus[i]['evolution'].show()
        elif self.ws == 'wunderground':
            self.key = configuration.get('wu-key')
            for i in range(INDICATORS):
                if self.preferences[i]['show']:
                    self.weatherservices[i] =\
                        wundergroundapi.UndergroundWeatherService(
                            longitude=self.preferences[i]['longitude'],
                            latitude=self.preferences[i]['latitude'],
                            units=self.units,
                            key=self.key)
                self.menus[i]['evolution'].hide()

        #
        self.icon_light = configuration.get('icon-light')
        #
        utcnow = datetime.utcnow()
        for i in range(INDICATORS):
            if self.preferences[i]['show'] and\
                    self.preferences[i]['widget']:
                if self.widgets[i] is not None:
                    self.widgets[i].hide()
                    self.widgets[i].destroy()
                    self.widgets[i] = None
                self.widgets[i] = WeatherWidget(self.indicators[i], i)
                self.widgets[i].set_datetime(utcnow)
                self.widgets[i].set_location(self.preferences[i]['location'])
                self.widgets[i].connect('pinit', self.on_pinit, i)
            elif self.widgets[i] is not None:
                self.widgets[i].hide()
                self.widgets[i].destroy()
                self.widgets[i] = None
        print(1)
        self.update_weather()
        self.start_looking_for_internet()
 def __init__(self):
     if dbus.SessionBus().request_name('es.atareao.MyWeatherIndicator') !=\
             dbus.bus.REQUEST_NAME_REPLY_PRIMARY_OWNER:
         print("application already running")
         exit(0)
     #
     self.weather_updater = 0
     self.widgets_updater = 0
     self.menus = []
     self.indicators = []
     self.notifications = []
     self.widgets = []
     self.weatherservices = []
     self.weathers = []
     self.current_conditions = []
     self.preferences = []
     # Iniciate variables
     for i in range(INDICATORS):
         self.menus.append(None)
         self.indicators.append(None)
         self.notifications.append(None)
         self.widgets.append(None)
         self.weatherservices.append(None)
         self.weathers.append(None)
         self.current_conditions.append(None)
         self.preferences.append(None)
     #
     status = appindicator.IndicatorCategory.APPLICATION_STATUS
     self.notifications[0] = Notify.Notification.new('', '', None)
     self.indicators[0] = appindicator.Indicator.new(
         'My-Weather-Indicator', 'My-Weather-Indicator', status)
     self.notifications[1] = Notify.Notification.new('', '', None)
     self.indicators[1] = appindicator.Indicator.new(
         'My-Weather-Indicator2', 'My-Weather-Indicator', status)
     #
     for i in range(INDICATORS):
         self.create_menu(i)
     #
     '''
     while internet_on() == False:
         print('Waiting for internet')
         time_start = time.time()
         time_end = (time_start + 1)
         while time_end > time.time():
             while Gtk.events_pending():
                 Gtk.main_iteration()
             time.sleep(0.3)
     '''
     if not os.path.exists(comun.CONFIG_FILE) and internet_on():
         configuration = Configuration()
         configuration.reset()
         latitude, longitude = ipaddress.get_current_location()
         city = geocodeapi.get_inv_direction(latitude, longitude)['city']
         if city is None:
             city = ''
         configuration.set('latitude', latitude)
         configuration.set('longitude', longitude)
         configuration.set('location', city)
         configuration.save()
         cm = preferences.CM()
         if cm.run() == Gtk.ResponseType.ACCEPT:
             cm.save_preferences()
         else:
             exit(0)
         cm.hide()
         cm.destroy()
     for i in range(INDICATORS):
         self.widgets[i] = None
     self.load_preferences()
    def update_menu(self, index):
        if not internet_on():
            if self.icon_light:
                icon = os.path.join(
                    comun.ICONDIR,
                    weatherservice.CONDITIONS['not available']['icon-light'])
            else:
                icon = os.path.join(
                    comun.ICONDIR,
                    weatherservice.CONDITIONS['not available']['icon-dark'])
            self.indicators[index].set_icon(icon)
            self.indicators[index].set_label('', '')
            msg = weatherservice.CONDITIONS['not available']['text']
            msg += '\n'+_('Not Internet connection')
            image = os.path.join(
                comun.IMAGESDIR,
                weatherservice.CONDITIONS['not available']['image'])
            self.notifications[index].update(
                'My-Weather-Indicator',
                msg,
                image)
            self.notifications[index].show()
            return
        print('--- Updating data in location %s ---' % (index))
        if self.preferences[index]['autolocation']:
            lat, lon = ipaddress.get_current_location()
            location = geocodeapi.get_inv_direction(lat, lon)['city']
            if location is None:
                location = ''
            print(lat, lon, location)
            if self.preferences[index]['latitude'] != lat and\
                    self.preferences[index]['longitude'] != lon:
                self.preferences[index]['latitude'] = lat
                self.preferences[index]['longitude'] = lon
                self.preferences[index]['location'] = location
                if self.ws == 'yahoo':
                    self.weatherservices[index] =\
                        wyahooapi.YahooWeatherService(
                        longitude=self.preferences[index]['longitude'],
                        latitude=self.preferences[index]['latitude'],
                        units=self.units)
                    self.menus[index]['evolution'].hide()
                elif self.ws == 'worldweatheronline':
                    self.weatherservices[index] =\
                        worldweatheronlineapi.WorldWeatherOnlineService(
                            longitude=self.preferences[index]['longitude'],
                            latitude=self.preferences[index]['latitude'],
                            units=self.units,
                            key=self.key)
                    self.menus[index]['evolution'].hide()
                elif self.ws == 'openweathermap':
                    self.weatherservices[index] =\
                        wopenweathermapapi.OWMWeatherService(
                            longitude=self.preferences[index]['longitude'],
                            latitude=self.preferences[index]['latitude'],
                            units=self.units)
                    self.menus[index]['evolution'].show()
                elif self.ws == 'wunderground':
                    self.weatherservices[index] =\
                        wundergroundapi.UndergroundWeatherService(
                            longitude=self.preferences[index]['longitude'],
                            latitude=self.preferences[index]['latitude'],
                            units=self.units,
                            key=self.key)
                    self.menus[index]['evolution'].hide()
        print('****** Updating weather')
        weather = self.weatherservices[index].get_weather()
        print('****** Updated weather')
        if weather is None:
            return
        temporal_current_conditions = weather['current_conditions']
        conditions_changed = False
        if len(temporal_current_conditions) != 0:
            self.current_conditions[index] = temporal_current_conditions
            self.weathers[index] = weather
            ########################################################
            if self.preferences[index]['location']:
                self.menus[index]['location'].set_label(
                    _('Location') + ': ' + self.preferences[index]['location'])
            self.menus[index]['temperature'].set_label(_('Temperature') + ': \
{0}{1:c}'.format(self.current_conditions[index]['temperature'], 176))
            self.menus[index]['humidity'].set_label(
                _('Humidity') + ': ' +
                self.current_conditions[index]['humidity'])
            self.menus[index]['feels_like'].set_label(_('Feels like')+': \
{0}{1:c}'.format(self.current_conditions[index]['feels_like'], 176))
            self.menus[index]['dew_point'].set_label(_('Dew Point') + ': \
{0}{1:c}'.format(self.current_conditions[index]['dew_point'], 176))
            self.menus[index]['wind'].set_label(
                _('Wind') + ':' +
                self.current_conditions[index]['wind_condition'])
            if self.current_conditions[index]['wind_icon']:
                image = Gtk.Image.new_from_file(
                    os.path.join(comun.IMAGESDIR,
                                 self.current_conditions[index]['wind_icon']))
                self.menus[index]['wind'].set_image(image)
            self.menus[index]['condition'].set_label(
                self.current_conditions[index]['condition_text'])
            afile = os.path.join(
                comun.IMAGESDIR,
                self.current_conditions[index]['condition_image'])
            self.menus[index]['condition'].set_image(
                Gtk.Image.new_from_file(os.path.join(
                    comun.IMAGESDIR,
                    self.current_conditions[index]['condition_image'])))
            filename = os.path.join(
                comun.WIMAGESDIR,
                self.current_conditions[index]['condition_image'])
            if self.widgets[index] is not None:
                self.widgets[index].set_location(
                    self.preferences[index]['location'])
                self.widgets[index].set_weather(weather)
            self.menus[index]['dawn'].set_label(
                _('Dawn')+': '+self.current_conditions[index]['dawn'])
            self.menus[index]['sunrise'].set_label(
                _('Sunrise')+': '+self.current_conditions[index]['sunrise'])
            self.menus[index]['sunset'].set_label(
                _('Sunset')+': '+self.current_conditions[index]['sunset'])
            self.menus[index]['dusk'].set_label(
                _('Dusk')+': '+self.current_conditions[index]['dusk'])
            self.menus[index]['moon_phase'].set_label(
                self.current_conditions[index]['moon_phase'])
            self.menus[index]['moon_phase'].set_image(
                Gtk.Image.new_from_file(
                    os.path.join(comun.IMAGESDIR,
                                 self.current_conditions[index]['moon_icon'])))
            #
            pressure = (
                self.current_conditions[index]['pressure'] is not None)
            visibility = (
                self.current_conditions[index]['visibility'] is not None)
            cloudiness = (
                self.current_conditions[index]['cloudiness'] is not None)
            solarradiation = (
                self.current_conditions[index]['solarradiation'] is not None)
            UV = (
                self.current_conditions[index]['UV'] is not None)
            precip_today = (
                self.current_conditions[index]['precip_today'] is not None)
            self.menus[index]['pressure'].set_visible(pressure)
            self.menus[index]['visibility'].set_visible(visibility)
            self.menus[index]['cloudiness'].set_visible(cloudiness)
            self.menus[index]['uv'].set_visible(UV)
            self.menus[index]['precipitation'].set_visible(precip_today)
            if pressure:
                self.menus[index]['pressure'].set_label(
                    ('%s: %s') % (_('Pressure'),
                                  self.current_conditions[index]['pressure']))
            if visibility:
                value = self.current_conditions[index]['visibility']
                self.menus[index]['visibility'].set_label(
                    ('%s: %s') % (_('Visibility'), value))
            if cloudiness:
                value = self.current_conditions[index]['cloudiness']
                self.menus[index]['cloudiness'].set_label(
                    ('%s: %s') % (_('Cloudiness'), value))
            if UV:
                value = self.current_conditions[index]['UV']
                self.menus[index]['uv'].set_label(
                    ('%s: %s') % (_('UV'), value))
            if precip_today:
                value = self.current_conditions[index]['precip_today']
                self.menus[index]['precipitation'].set_label(
                    ('%s: %s') % (_('Precipitation'), value))
            if self.preferences[index]['show-temperature'] is True:
                value = self.current_conditions[index]['temperature']
                self.indicators[index].set_label(
                    '{0}{1:c}'.format(value, 176), '')
            else:
                self.indicators[index].set_label('', '')
            if self.preferences[index]['show'] is True:
                self.indicators[index].set_status(
                    appindicator.IndicatorStatus.ACTIVE)
            else:
                self.indicators[index].set_status(
                    appindicator.IndicatorStatus.PASSIVE)
            if self.icon_light:
                icon = os.path.join(
                    comun.ICONDIR,
                    self.current_conditions[index]['condition_icon_light'])
            else:
                icon = os.path.join(
                    comun.ICONDIR,
                    self.current_conditions[index]['condition_icon_dark'])
            self.indicators[index].set_icon(icon)
            if self.preferences[index]['show-notifications'] is True:
                msg = _('Conditions in')+' '
                msg += self.preferences[index]['location'] + '\n'
                msg += _('Temperature')+': ' +\
                    self.current_conditions[index]['temperature'] + '\n'
                msg += _('Humidity') + ': ' + \
                    self.current_conditions[index]['humidity'] + '\n'
                msg += _('Wind') + ': ' +\
                    self.current_conditions[index]['wind_condition']+'\n'
                msg += self.current_conditions[index]['condition_text']
                image = os.path.join(
                    comun.IMAGESDIR,
                    self.current_conditions[index]['condition_image'])
                self.notifications[index].update(
                    'My-Weather-Indicator',
                    msg,
                    image)
                self.notifications[index].show()
            while Gtk.events_pending():
                Gtk.main_iteration()
        print('--- End of updating data in location %s ---' % (index))
 def __init__(self):
     if dbus.SessionBus().request_name('es.atareao.MyWeatherIndicator') !=\
             dbus.bus.REQUEST_NAME_REPLY_PRIMARY_OWNER:
         print("application already running")
         exit(0)
     #
     self.weather_updater = 0
     self.widgets_updater = 0
     self.menus = []
     self.indicators = []
     self.notifications = []
     self.widgets = []
     self.weatherservices = []
     self.weathers = []
     self.current_conditions = []
     self.preferences = []
     self.last_update_time = 0
     # Iniciate variables
     for i in range(INDICATORS):
         self.menus.append(None)
         self.indicators.append(None)
         self.notifications.append(None)
         self.widgets.append(None)
         self.weatherservices.append(None)
         self.weathers.append(None)
         self.current_conditions.append(None)
         self.preferences.append(None)
     #
     status = appindicator.IndicatorCategory.APPLICATION_STATUS
     self.notifications[0] = Notify.Notification.new('', '', None)
     self.indicators[0] = appindicator.Indicator.new(
         'My-Weather-Indicator', 'My-Weather-Indicator', status)
     self.notifications[1] = Notify.Notification.new('', '', None)
     self.indicators[1] = appindicator.Indicator.new(
         'My-Weather-Indicator2', 'My-Weather-Indicator', status)
     #
     for i in range(INDICATORS):
         self.create_menu(i)
     #
     if not os.path.exists(comun.CONFIG_FILE):
         if internet_on():
             configuration = Configuration()
             configuration.reset()
             latitude, longitude = ipaddress.get_current_location()
             city = geocodeapi.get_inv_direction(
                 latitude, longitude)['city']
             if city is None:
                 city = ''
             configuration.set('latitude', latitude)
             configuration.set('longitude', longitude)
             configuration.set('location', city)
             configuration.save()
         cm = preferences.CM()
         if cm.run() == Gtk.ResponseType.ACCEPT:
             cm.save_preferences()
         else:
             exit(0)
         cm.hide()
         cm.destroy()
     for i in range(INDICATORS):
         self.widgets[i] = None
     self.load_preferences()
    def load_preferences(self):
        if not os.path.exists(comun.CONFIG_FILE):
            if internet_on():
                configuration = Configuration()
                configuration.reset()
                latitude, longitude = ipaddress.get_current_location()
                city = geocodeapi.get_inv_direction(
                    latitude, longitude)['city']
                if city is None:
                    city = ''
                configuration.set('latitude', latitude)
                configuration.set('longitude', longitude)
                configuration.set('location', city)
                configuration.save()
            cm = preferences.CM()
            if cm.run() == Gtk.ResponseType.ACCEPT:
                cm.save_preferences()
            else:
                exit(0)
            cm.hide()
            cm.destroy()
        configuration = Configuration()
        self.first_time = configuration.get('first-time')
        self.refresh = configuration.get('refresh')
        self.version = configuration.get('version')
        #
        self.preferences[0] = {}
        self.preferences[0]['show'] = configuration.get('main-location')
        self.preferences[0]['autolocation'] = configuration.get('autolocation')
        self.preferences[0]['location'] = configuration.get('location')
        self.preferences[0]['latitude'] = configuration.get('latitude')
        self.preferences[0]['longitude'] = configuration.get('longitude')
        self.preferences[0]['show-temperature'] =\
            configuration.get('show-temperature')
        self.preferences[0]['show-notifications'] =\
            configuration.get('show-notifications')
        self.preferences[0]['widget'] = configuration.get('widget1')
        #
        self.preferences[1] = {}
        self.preferences[1]['show'] = configuration.get('second-location')
        self.preferences[1]['autolocation'] = False
        self.preferences[1]['location'] = configuration.get('location2')
        self.preferences[1]['latitude'] = configuration.get('latitude2')
        self.preferences[1]['longitude'] = configuration.get('longitude2')
        self.preferences[1]['show-temperature'] =\
            configuration.get('show-temperature2')
        self.preferences[1]['show-notifications'] =\
            configuration.get('show-notifications2')
        self.preferences[1]['widget'] = configuration.get('widget2')
        #
        temperature = configuration.get('temperature')
        pressure = configuration.get('pressure')
        visibility = configuration.get('visibility')
        wind = configuration.get('wind')
        snow = configuration.get('snow')
        rain = configuration.get('rain')
        ampm = not configuration.get('24h')
        self.units = weatherservice.Units(temperature=temperature,
                                          wind=wind,
                                          pressure=pressure,
                                          visibility=visibility,
                                          snow=snow,
                                          rain=rain,
                                          ampm=ampm)
        self.ws = configuration.get('weather-service')
        if self.ws == 'yahoo':
            self.key = ''
            for i in range(INDICATORS):
                if self.preferences[i]['show']:
                    self.weatherservices[i] = wyahooapi.YahooWeatherService(
                        longitude=self.preferences[i]['longitude'],
                        latitude=self.preferences[i]['latitude'],
                        units=self.units)
                self.menus[i]['evolution'].hide()
        elif self.ws == 'worldweatheronline':
            self.key = configuration.get('wwo-key')
            for i in range(INDICATORS):
                if self.preferences[i]['show']:
                    self.weatherservices[i] =\
                        worldweatheronlineapi.WorldWeatherOnlineService(
                            longitude=self.preferences[i]['longitude'],
                            latitude=self.preferences[i]['latitude'],
                            units=self.units,
                            key=self.key)
                self.menus[i]['evolution'].hide()
        elif self.ws == 'openweathermap':
            self.key = ''
            for i in range(INDICATORS):
                if self.preferences[i]['show']:
                    self.weatherservices[i] =\
                        wopenweathermapapi.OWMWeatherService(
                            longitude=self.preferences[i]['longitude'],
                            latitude=self.preferences[i]['latitude'],
                            units=self.units)
                self.menus[i]['evolution'].show()
        elif self.ws == 'wunderground':
            self.key = configuration.get('wu-key')
            for i in range(INDICATORS):
                if self.preferences[i]['show']:
                    self.weatherservices[i] =\
                        wundergroundapi.UndergroundWeatherService(
                            longitude=self.preferences[i]['longitude'],
                            latitude=self.preferences[i]['latitude'],
                            units=self.units,
                            key=self.key)
                self.menus[i]['evolution'].hide()

        #
        self.icon_light = configuration.get('icon-light')
        #
        utcnow = datetime.utcnow()
        for i in range(INDICATORS):
            if self.preferences[i]['show'] and\
                    self.preferences[i]['widget']:
                if self.widgets[i] is not None:
                    self.widgets[i].hide()
                    self.widgets[i].destroy()
                    self.widgets[i] = None
                self.widgets[i] = WeatherWidget(
                    self.indicators[i], i)
                self.widgets[i].set_datetime(utcnow)
                self.widgets[i].set_location(self.preferences[i]['location'])
                self.widgets[i].connect('pinit', self.on_pinit, i)
            elif self.widgets[i] is not None:
                    self.widgets[i].hide()
                    self.widgets[i].destroy()
                    self.widgets[i] = None
        print(1)
        self.update_weather()
        self.start_looking_for_internet()