This repository has been archived by the owner on Dec 8, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path__init__.py
250 lines (204 loc) · 10.8 KB
/
__init__.py
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
#!/usr/bin/env python3
# Copyright (C) 2016 Sylvia van Os <iamsylvie@openmailbox.org>
#
# Pext OpenWeatherMap module 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 3 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/>.
import gettext
import json
import os
import time
from datetime import datetime
from urllib.request import urlopen
from urllib.error import URLError
from pext_base import ModuleBase
from pext_helpers import Action, SelectionType
class Module(ModuleBase):
def init(self, settings, q):
try:
lang = gettext.translation('pext_module_weather', localedir=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'locale'), languages=[settings['_locale']])
except FileNotFoundError:
lang = gettext.NullTranslations()
print("No {} translation available for pext_module_weather".format(settings['_locale']))
lang.install()
self.key = "c98d3515966557887e4e0c5b656b7001" if ("key" not in settings) else settings['key']
self.baseUrl = "http://api.openweathermap.org/data/2.5"
self.q = q
self.settings = settings
self.unit = "°C" if ("unit" not in settings) else settings["unit"]
self.entries = {}
self.context_entries = {}
self.cachedCities = {}
self.cachedForecasts = {}
self.scriptLocation = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
self._get_entries()
def _get_entries(self):
with open(os.path.join(self.scriptLocation, 'city.list.json'), encoding='utf-8') as f:
for line in f:
city = json.loads(line)
formattedCity = "{} ({})".format(city['name'], city['country'])
self.entries[formattedCity] = city
self.context_entries[formattedCity] = [_("Current weather"), _("Forecast")]
self._set_entries()
def _set_entries(self):
# While this goes against Pext's module development recommendation to
# at least show some entries as soon as possible, appending a list of
# this size using Action.add_entry one-by-one is simply too slow
self.q.put([Action.replace_entry_list, sorted(list(self.entries.keys()))])
if self.settings['_api_version'] >= [0, 5, 0]:
self.q.put([Action.replace_entry_context_dict, self.context_entries])
def _get_city_id(self, identifier):
return self.entries[identifier]['_id']
def _format_data(self, data):
return [
self._format_place_name(data),
self._format_temperature(data),
self._format_weather_description(data)
]
def _format_place_name(self, data):
return "{} ({})".format(data['name'], data["sys"]["country"])
def _format_temperature(self, data):
kelvin = data["main"]["temp"]
celcius = kelvin - 273.15
fahrenheit = kelvin * 9 / 5 - 459.67
return "{:.2f} °C".format(celcius) if (self.unit == "°C") else "{:.2f} °F".format(fahrenheit)
def _format_weather_description(self, data):
return data["weather"][0]["description"].capitalize()
def _show_weather(self, cityId):
# Get and cache the data if not in cache
if not cityId in self.cachedCities or self.cachedCities[cityId]["time"] < time.time() - 600:
try:
httpResponse = urlopen("{}/weather?id={}&appid={}".format(self.baseUrl, cityId, self.key))
except URLError as e:
self.q.put([Action.add_error, _("Failed to request weather data: {}").format(e)])
self.q.put([Action.set_selection, []])
return
responseData = httpResponse.read().decode("utf-8")
try:
data = json.loads(responseData)
except json.JSONDecodeError as e:
self.q.put([Action.add_error, _("Failed to decode weather data: {}").format(e)])
self.q.put([Action.set_selection, []])
return
if data['cod'] != 200:
self.q.put([Action.add_error, _("Failed to retrieve weather data: {} ({})").format(data['message'], data['cod'])])
self.q.put([Action.set_selection, []])
return
cache = {'time': time.time(), 'data': data}
self.cachedCities[cityId] = cache
# Retrieve from cache
data = self.cachedCities[cityId]["data"]
# Format and show
formattedData = [self._format_temperature(data),
self._format_weather_description(data)]
self.q.put([Action.set_header, self._format_place_name(data)])
self.q.put([Action.replace_command_list, []])
self.q.put([Action.replace_entry_list, formattedData])
def _show_forecast(self, cityId, timestamp):
for forecastEntry in self.cachedForecasts[cityId]["data"]["list"]:
if forecastEntry["dt"] == timestamp:
cityData = self.cachedForecasts[cityId]["data"]["city"]
formattedData = [self._format_temperature(forecastEntry),
self._format_weather_description(forecastEntry)]
self.q.put([Action.set_header, "{} ({})".format(cityData["name"], cityData["country"])])
self.q.put([Action.replace_entry_list, formattedData])
def _retrieve_forecast(self, cityId):
if not cityId in self.cachedForecasts or self.cachedForecasts[cityId]["time"] < time.time() - 600:
try:
httpResponse = urlopen("{}/forecast?id={}&appid={}".format(self.baseUrl, cityId, self.key))
except URLError as e:
self.q.put([Action.add_error, _("Failed to request weather data: {}").format(e)])
self.q.put([Action.set_selection, []])
return
responseData = httpResponse.read().decode("utf-8")
try:
data = json.loads(responseData)
except json.JSONDecodeError as e:
self.q.put([Action.add_error, _("Failed to decode weather data: {}").format(e)])
self.q.put([Action.set_selection, []])
return
cache = {'time': time.time(), 'data': data}
self.cachedForecasts[cityId] = cache
cityData = self.cachedForecasts[cityId]["data"]["city"]
self.q.put([Action.set_header, "{} ({})".format(cityData["name"], cityData["country"])])
self.q.put([Action.replace_command_list, []])
self.q.put([Action.replace_entry_list, []])
for forecastEntry in self.cachedForecasts[cityId]["data"]["list"]:
self.q.put([Action.add_entry, datetime.fromtimestamp(forecastEntry["dt"])])
def stop(self):
pass
def selection_made(self, selection):
if len(selection) == 0:
self._set_entries()
elif len(selection) == 1:
if self.settings['_api_version'] >= [0, 8, 0]:
command = selection[0]['value']
args = selection[0]['args'] if 'args' in selection[0] else []
else:
parts = selection[0]["value"].split(" ")
command = parts[0]
args = parts[1:]
if selection[0]['type'] == SelectionType.entry:
# Entry selected, act is if we called the weather/forecast function to
# reduce code repetition
if self.settings['_api_version'] >= [0, 4, 0]:
if selection[0]['context_option'] == _("Forecast"):
if self.settings['_api_version'] >= [0, 8, 0]:
self.q.put([Action.set_selection, [{'type': SelectionType.command, 'value': 'forecast', 'args': selection[0]['value'].split(" ")}]])
else:
self.q.put([Action.set_selection, [{'type': SelectionType.command, 'value': 'forecast {}'.format(" ".join(args))}]])
return
if self.settings['_api_version'] >= [0, 8, 0]:
self.q.put([Action.set_selection, [{'type': SelectionType.command, 'value': 'weather', 'args': selection[0]['value'].split(" ")}]])
else:
self.q.put([Action.set_selection, [{'type': SelectionType.command, 'value': 'weather {}'.format(" ".join(args))}]])
return
cityId = self._get_city_id(" ".join(args))
# Remove commands
self.q.put([Action.replace_command_list, []])
if command == "forecast":
self._retrieve_forecast(cityId)
elif command == "weather":
self._show_weather(cityId)
else:
self.q.put([Action.critical_error, _("Unexpected selection_made value: {}").format(selection)])
elif len(selection) == 2:
if selection[0]["type"] != SelectionType.command:
self.q.put([Action.critical_error, _("Unexpected selection_made value: {}").format(selection)])
if self.settings['_api_version'] >= [0, 8, 0]:
command = selection[0]['value']
args = selection[0]['args']
else:
parts = selection[0]["value"].split(" ")
command = parts[0]
args = parts[1:]
if command == "forecast":
try:
timestamp = selection[1]["value"].timestamp()
except AttributeError:
# The user selected the city name
self.q.put([Action.set_selection, selection[:-1]])
return
self._show_forecast(self._get_city_id(" ".join(args)), timestamp)
elif command == "weather":
self.q.put([Action.copy_to_clipboard, selection[1]["value"]])
self.q.put([Action.close])
else:
self.q.put([Action.critical_error, _("Unexpected selection_made value: {}").format(selection)])
elif len(selection) == 3:
# We can only get this deep if we use forecast, just copy the entry to the clipboard and close
self.q.put([Action.copy_to_clipboard, selection[2]["value"]])
self.q.put([Action.close])
else:
self.q.put([Action.critical_error, _("Unexpected selection_made value: {}").format(selection)])
def process_response(self, response):
pass