This repository has been archived by the owner on Dec 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
indicator-weather
executable file
·265 lines (236 loc) · 11 KB
/
indicator-weather
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
#! /bin/sh
""":"
exec python $0 ${1+"$@"}
"""
# This file is part of indicator-weather.
# Indicator Weather is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3
# as published by the Free Software Foundation.
#
# Indicator Weather 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. <http://www.gnu.org/licenses/>
#
# Author(s):
# (C) 2015-2018 Kasra Madadipouya <kasra@madadipouya.com>
import sys
import urllib
import json
import gi
import string
import time
from preference import Dialog
from configuration import Configuration
from gi.repository import Gtk, GLib
gi.require_version('Gtk', '3.0')
gi.require_version('AppIndicator3', '0.1')
gi.require_version('Notify', '0.7')
from gi.repository import Notify as notification
from gi.repository import AppIndicator3 as appIndicator
from retrying import retry
PING_FREQUENCY_IN_SECONDS = 600 # 10 minutes
ICON_NAMES = {
"01d": "weather-clear",
"01n": "weather-clear-night",
"02d": "weather-few-clouds",
"02n": "weather-few-clouds-night",
"03d": "weather-clouds",
"03n": "weather-clouds-night",
"04d": "weather-overcast",
"09d": "weather-showers",
"10d": "weather-showers-scattered",
"11d": "weather-storm",
"13d": "weather-snow",
"50d": "weather-fog",
}
def get_local_icon_name(code):
if code in ICON_NAMES:
return ICON_NAMES[code]
else:
day_code = code[:2] + 'd'
return ICON_NAMES[day_code]
class WeatherIndicator:
def __init__(self):
self.configuration = Configuration()
self.indicator = appIndicator.Indicator.new(
"weather-indicator", "weather-indicator", appIndicator.IndicatorCategory.OTHER)
self.indicator.set_status(appIndicator.IndicatorStatus.ACTIVE)
self.indicator.set_icon("weather-clear")
self.menu_setup()
self.indicator.set_menu(self.menu)
self.init_weather_notification()
def menu_setup(self):
self.menu = Gtk.Menu()
self.temperature_item = Gtk.MenuItem("")
self.temperature_item.show()
self.menu.append(self.temperature_item)
self.menu.append(self.create_separator_menu_item())
# Weather Description
self.weather_description_item = Gtk.MenuItem("")
self.weather_description_item.show()
self.menu.append(self.weather_description_item)
# Feels Like
self.feels_like_temperature_item = Gtk.MenuItem("")
self.feels_like_temperature_item.show()
self.menu.append(self.feels_like_temperature_item)
# Maximum Temperature
self.maximum_temperature_item = Gtk.MenuItem("")
self.maximum_temperature_item.show()
self.menu.append(self.maximum_temperature_item)
# Minimum Temperature
self.minimum_temperature_item = Gtk.MenuItem("")
self.minimum_temperature_item.show()
self.menu.append(self.minimum_temperature_item)
# Humidity
self.humidity_item = Gtk.MenuItem("")
self.humidity_item.show()
self.menu.append(self.humidity_item)
# Wind
self.wind_item = Gtk.MenuItem("")
self.wind_item.show()
self.menu.append(self.wind_item)
# Cloudiness
self.cloudiness_item = Gtk.MenuItem("")
self.cloudiness_item.show()
self.menu.append(self.cloudiness_item)
# Pressure
self.pressure_item = Gtk.MenuItem("")
self.pressure_item.show()
self.menu.append(self.pressure_item)
# Visibility
self.visibility_item = Gtk.MenuItem("")
self.visibility_item.show()
self.menu.append(self.visibility_item)
# Last Update
self.last_update_item = Gtk.MenuItem("")
self.last_update_item.show()
self.menu.append(self.last_update_item)
self.menu.append(self.create_separator_menu_item())
self.preference_item = Gtk.MenuItem("Preferences")
self.preference_item.connect("activate", self.preference)
self.preference_item.show()
self.menu.append(self.preference_item)
self.refresh_item = Gtk.MenuItem(u"Refresh \u27F3")
self.refresh_item.connect("activate", self.refresh)
self.refresh_item.show()
self.menu.append(self.refresh_item)
self.quit_item = Gtk.MenuItem("Quit")
self.quit_item.connect("activate", self.quit)
self.quit_item.show()
self.menu.append(self.quit_item)
def init_weather_notification(self):
notification.init("Simple Weather Indicator")
self.weather_notification = notification.Notification.new("")
def main(self):
self.get_weather()
GLib.timeout_add_seconds(PING_FREQUENCY_IN_SECONDS, self.get_weather)
Gtk.main()
def quit(self, widget):
sys.exit(0)
def preference(self, widget):
preference_dialog = Dialog()
preference_dialog.main()
self.configuration.reload_configuration()
self.get_weather()
def refresh(self, widget):
self.get_weather()
def create_separator_menu_item(self):
separator = Gtk.SeparatorMenuItem()
separator.show()
return separator
def retry_if_result_none(result):
return result is None
@retry(stop_max_attempt_number=100, wait_exponential_multiplier=500, wait_exponential_max=60000, retry_on_result=retry_if_result_none)
def get_weather(self):
try:
if(self.configuration.get_temperature_scale()):
temperature_scale = 'true'
else:
temperature_scale = 'false'
if(self.configuration.is_automatic_location_detection()):
url_path = ('currentbyip?fahrenheit={}'.format(temperature_scale))
else:
latitude, longitude = self.configuration.get_coordinates()
url_path = ('current?lat={}&lon={}&fahrenheit={}'.format(latitude, longitude, temperature_scale))
weather_service_url = ('http://weather-api.madadipouya.com/v1/weather/{}'.format(url_path))
json_response = json.loads(urllib.urlopen(weather_service_url).read())
if self.is_weather_changed(json_response):
self.notify_user_on_weather_changes(json_response)
self.set_weather_metrics(json_response)
except:
return None
return True
def is_weather_changed(self, weather_json):
last_weather_description = self.weather_description_item.get_label()
last_location = self.temperature_item.get_label()
if self.is_not_blank(last_weather_description) and self.is_not_blank(last_location):
last_location = last_location.split(' ', 1)[1]
current_weather_description = string.capwords(weather_json['weather'][0]['description'])
current_location = self.get_city_name(weather_json['geoLocation'].strip().rsplit(",")[:2])
try:
last_location = unicode(last_location, 'utf-8')
current_location = unicode(current_location, 'utf-8')
except TypeError:
pass
return last_weather_description != current_weather_description or last_location != current_location
return False
def notify_user_on_weather_changes(self, weather_json):
icon = get_local_icon_name(weather_json['iconName'])
weather_description = string.capwords(weather_json['weather'][0]['description'])
self.weather_notification.update("Recent Weather Changes", weather_description, icon)
if self.configuration.get_notifications():
self.weather_notification.show()
def set_weather_metrics(self, json_response):
temperature = json_response['temperature']
feels_like_temperature = json_response['feelsLike']
maximum_temperature = json_response['main']['temp_max']
minimum_temperature = json_response['main']['temp_min']
temperature_symbol = self.configuration.get_temperature_symbol()
if(self.configuration.is_round_temperature()):
temperature = int(round(float(temperature)))
maximum_temperature = int(round(float(maximum_temperature)))
minimum_temperature = int(round(float(minimum_temperature)))
feels_like_temperature = int(round(float(feels_like_temperature)))
city = self.get_city_name(json_response['geoLocation'].strip().rsplit(",")[:2])
if(self.configuration.is_hide_location()):
label = u'{temperature}{temperature_symbol}'.format(**locals())
else:
label = u'{temperature}{temperature_symbol} {city}'.format(**locals())
self.indicator.set_label(label, label)
self.indicator.set_icon(get_local_icon_name(json_response['iconName']))
self.temperature_item.get_child().set_text(u'{temperature}{temperature_symbol} {city}'.format(**locals()))
self.weather_description_item.set_label(string.capwords(json_response['weather'][0]['description']))
feels_like_temperature = u'Feels Like: {feels_like_temperature}{temperature_symbol}'.format(**locals())
maximum_temperature = u'Maximum: {maximum_temperature}{temperature_symbol}'.format(**locals())
minimum_temperature = u'Minimum: {minimum_temperature}{temperature_symbol}'.format(**locals())
self.feels_like_temperature_item.set_label(feels_like_temperature)
self.maximum_temperature_item.set_label(maximum_temperature)
self.minimum_temperature_item.set_label(minimum_temperature)
humidity = 'Humidity: {}%'.format(json_response['main']['humidity'])
self.humidity_item.set_label(humidity)
wind_speed_unit = self.configuration.get_wind_speed_unit()
wind_speed = json_response['wind']['speed']
wind_speed = 'Wind: {wind_speed} {wind_speed_unit}'.format(**locals())
self.wind_item.set_label(wind_speed)
cloudiness = 'Cloudiness: {}%'.format(json_response['clouds']['all'])
self.cloudiness_item.set_label(cloudiness)
pressure = "Pressure: {} hPa".format(json_response['main']['pressure'])
self.pressure_item.set_label(pressure)
visibility = json_response['visibility']
visibility_unit = self.configuration.get_visibility_unit()
visibility = "Visibility: {visibility} {visibility_unit}".format(**locals())
self.visibility_item.set_label(visibility)
last_update = 'Last Update: ' + time.strftime("%I:%M:%S %p")
self.last_update_item.set_label(last_update)
def is_not_blank(self, string):
return bool(string and string.strip())
def get_city_name(self, location):
try: # If location[0] is number, then we will show location[1], which is street
city = int(location[0])
return location[1]
except:
return location[0]
if __name__ == "__main__":
indicator = WeatherIndicator()
indicator.main()