def compute_state(self, location_query): url = self.get_request_url(location_query) # bug fix for powerline segment: # if urlopen fails (for example, if you don't have an internet connection), # then weather segment should silently fail try: raw_response = urllib_read(url) except Exception: raw_response = None if not raw_response: return None response = json.loads(raw_response) try: condition = response['query']['results']['weather']['rss']['channel']['item']['condition'] condition_code = int(condition['code']) temp = float(condition['temp']) except (KeyError, ValueError): self.exception('Yahoo returned malformed or unexpected response: {0}', repr(raw_response)) return None try: icon_names = weather_conditions_codes[condition_code] except IndexError: if condition_code == 3200: icon_names = ('not_available',) self.warn('Weather is not available for location {0}', self.location) else: icon_names = ('unknown',) self.error('Unknown condition code: {0}', condition_code) return (temp, icon_names)
def compute_state(self, key): #raw_res = urllib_read('http://127.0.0.1:18080') raw_res = urllib_read('http://172.23.90.57:18080') if not raw_res: self.pl.error('Failed to get response') return res = json.loads(raw_res) data = res['battery'] if data['charging']: status = key.charging remain = '' elif not data['charging']: if data['percent'] == 100: status = key.charged remain = '' else: status = key.discharging remain = key.remain.format(data['remain']) return { 'percent': data['percent'], 'status': status, 'remain': remain, }
def get_request_url(self, location_query): try: return self.location_urls[location_query] except KeyError: if location_query is None: location_data = json.loads( urllib_read('http://geoip.nekudo.com/api/')) location = ','.join( (location_data['city'], location_data['country']['name'], location_data['country']['code'])) self.info('Location returned by nekudo is {0}', location) else: location = location_query query_data = { 'q': 'use "https://raw.githubusercontent.com/yql/yql-tables/master/weather/weather.bylocation.xml" as we;' 'select * from weather.forecast where woeid in' ' (select woeid from geo.places(1) where text="{0}") and u="c"' .format(location).encode('utf-8'), 'format': 'json', } self.location_urls[location_query] = url = ( 'http://query.yahooapis.com/v1/public/yql?' + urllib_urlencode(query_data)) return url
def compute_state(self, location_query): url = self.get_request_url(location_query) raw_response = urllib_read(url) if not raw_response: self.error('Failed to get response') return None response = json.loads(raw_response) try: condition = response['query']['results']['weather']['rss']['channel']['item']['condition'] condition_code = int(condition['code']) temp = float(condition['temp']) except (KeyError, ValueError): self.exception('Yahoo returned malformed or unexpected response: {0}', repr(raw_response)) return None try: icon_names = weather_conditions_codes[condition_code] except IndexError: if condition_code == 3200: icon_names = ('not_available',) self.warn('Weather is not available for location {0}', self.location) else: icon_names = ('unknown',) self.error('Unknown condition code: {0}', condition_code) return (temp, icon_names)
def compute_state(self, location_query): url = self.get_request_url(location_query) raw_response = urllib_read(url) if not raw_response: self.error('Failed to get response') return None response = json.loads(raw_response) try: condition = response['query']['results']['weather']['rss'][ 'channel']['item']['condition'] condition_code = int(condition['code']) temp = float(condition['temp']) except (KeyError, ValueError): self.exception( 'Yahoo returned malformed or unexpected response: {0}', repr(raw_response)) return None try: icon_names = weather_conditions_codes[condition_code] except IndexError: if condition_code == 3200: icon_names = ('not_available', ) self.warn('Weather is not available for location {0}', self.location) else: icon_names = ('unknown', ) self.error('Unknown condition code: {0}', condition_code) return (temp, icon_names)
def compute_state(self, key): #raw_res = urllib_read('http://127.0.0.1:18080') raw_res = urllib_read('http://172.23.90.57:18080') if not raw_res: self.pl.error('Failed to response') return res = json.loads(raw_res) message = res['message'] body = message['body'] filename = '/tmp/last-message-history.log' last_message = (self.get_last_line(filename, 1))[0] s = re.split(r',', last_message.decode('utf-8')) last_time = s[0] if len(s) else None last_body = ''.join(s[1:]).rstrip() if len(s) else None now = time.strftime(key.time_format) if body != last_body: with open(filename, 'a') as f: f.write('{0},{1}\n'.format(now, body.encode('utf-8'))) return { 'now': last_time if last_time else now, 'body': body[:key.max_length], }
def get_request_url(self, location_query): try: return self.location_urls[location_query] except KeyError: if location_query is None: location_data = json.loads( urllib_read('http://freegeoip.net/json/')) location = ','.join( (location_data['city'], location_data['region_name'], location_data['country_code'])) self.info('Location returned by freegeoip is {0}', location) else: location = location_query query_data = { 'q': 'use "https://raw.githubusercontent.com/yql/yql-tables/master/weather/weather.bylocation.xml" as we;' 'select * from we where location="{0}" and unit="c"'.format( location).encode('utf-8'), 'format': 'json', } self.location_urls[location_query] = url = ( 'http://query.yahooapis.com/v1/public/yql?' + urllib_urlencode(query_data)) return url
def weather(pl, city='bellevue', state='wa'): if (os.path.exists(PATH_CONFIG) and time.time() - os.path.getmtime(PATH_CONFIG) < 1800): with open(PATH_CONFIG, 'r') as r: contents = r.read() else: location_data = json.loads( urllib_read('https://vocabulary-master-1987.appspot.com/weather/' + city + '/' + state)) weather_condition = location_data['current_observation']['condition'] weather_astronomy = location_data['current_observation']['astronomy'] day_or_night = check_day_or_night(weather_astronomy['sunrise'], weather_astronomy['sunset']) weather_location = location_data['location'] condition = weather_condition['text'].lower().replace(' ', '_') if condition in weather_conditions_mapping: condition = weather_conditions_mapping[condition] contents = weather_conditions_icons[day_or_night][condition] + ' ' + str(weather_condition['temperature']) + '°F ' \ + weather_location['city'] + '/' \ + weather_location['region'].replace(' ', '') + " " with open(PATH_CONFIG, 'w') as w: w.write(contents) return [{ 'contents': contents, 'highlight_groups': ['weather'], 'divider_highlight_group': None }]
def compute_state(self, location_query): url = self.get_request_url(location_query) raw_response = urllib_read(url) if not raw_response: self.error("Failed to get response") return None response = json.loads(raw_response) try: condition = response["query"]["results"]["weather"]["rss"]["channel"]["item"]["condition"] condition_code = int(condition["code"]) temp = float(condition["temp"]) except (KeyError, ValueError): self.exception("Yahoo returned malformed or unexpected response: {0}", repr(raw_response)) return None try: icon_names = weather_conditions_codes[condition_code] except IndexError: if condition_code == 3200: icon_names = ("not_available",) self.warn("Weather is not available for location {0}", self.location) else: icon_names = ("unknown",) self.error("Unknown condition code: {0}", condition_code) return (temp, icon_names)
def update(self, old_weather): import json if not self.url: # Do not lock attribute assignments in this branch: they are used # only in .update() if not self.location: location_data = json.loads( urllib_read('http://freegeoip.net/json/')) self.location = ','.join([ location_data['city'], location_data['region_code'], location_data['country_code'] ]) query_data = { 'q': 'use "http://github.com/yql/yql-tables/raw/master/weather/weather.bylocation.xml" as we;' 'select * from we where location="{0}" and unit="c"'.format( self.location).encode('utf-8'), 'format': 'json', } self.url = 'http://query.yahooapis.com/v1/public/yql?' + urllib_urlencode( query_data) raw_response = urllib_read(self.url) if not raw_response: self.error('Failed to get response') return response = json.loads(raw_response) condition = response['query']['results']['weather']['rss']['channel'][ 'item']['condition'] condition_code = int(condition['code']) temp = float(condition['temp']) try: icon_names = weather_conditions_codes[condition_code] except IndexError: if condition_code == 3200: icon_names = ('not_available', ) self.warn('Weather is not available for location {0}', self.location) else: icon_names = ('unknown', ) self.error('Unknown condition code: {0}', condition_code) return (temp, icon_names)
def compute_state(self, location_query): url = self.get_request_url(location_query) raw_response = urllib_read(url) if not raw_response: self.error('Failed to get response') return None return raw_response
def update(self, old_weather): import json if not self.url: # Do not lock attribute assignments in this branch: they are used # only in .update() if not self.location: location_data = json.loads(urllib_read('http://freegeoip.net/json/')) self.location = ','.join(( location_data['city'], location_data['region_code'], location_data['country_code'] )) query_data = { 'q': 'use "https://raw.githubusercontent.com/yql/yql-tables/master/weather/weather.bylocation.xml" as we;' 'select * from we where location="{0}" and unit="c"'.format(self.location).encode('utf-8'), 'format': 'json', } self.url = 'http://query.yahooapis.com/v1/public/yql?' + urllib_urlencode(query_data) raw_response = urllib_read(self.url) if not raw_response: self.error('Failed to get response') return response = json.loads(raw_response) condition = response['query']['results']['weather']['rss']['channel']['item']['condition'] condition_code = int(condition['code']) temp = float(condition['temp']) try: icon_names = weather_conditions_codes[condition_code] except IndexError: if condition_code == 3200: icon_names = ('not_available',) self.warn('Weather is not available for location {0}', self.location) else: icon_names = ('unknown',) self.error('Unknown condition code: {0}', condition_code) return (temp, icon_names)
def get_prayer_times(self, prayer_tuple): timestamp = long(math.ceil(time.time())) getPrayers = False if not self.prayer_times: getPrayers = True else: if not ((datetime.fromtimestamp(timestamp) - self.current_date_time).days == 0): getPrayers = True if not getPrayers: return self.prayer_times geometry = self.get_geometry(prayer_tuple[0]) if geometry is not None: geometry = geometry.split(',') else: return None query_data = { 'latitude': geometry[0], 'longitude': geometry[1], 'timezonestring': prayer_tuple[1], 'method': prayer_tuple[2] } raw_response = urllib_read( 'http://api.aladhan.com/timings/{0}?'.format(timestamp) + urllib_urlencode(query_data)) if not raw_response: self.error('Failed to get response') return None response = json.loads(raw_response) try: for prayer, rtime in response['data']['timings'].iteritems(): ptime = datetime.strptime(rtime, '%H:%M') self.prayer_times[prayer] = ptime.replace( self.current_date_time.year, self.current_date_time.month, self.current_date_time.day) except (KeyError, ValueError): self.exception( 'Al Adhan returned a malformed or unrexpected response: {0}', repr(raw_response)) return None self.prayer_times = sorted(self.prayer_times.items(), key=operator.itemgetter(1)) return self.prayer_times
def update(self, old_weather): import json if not self.url: # Do not lock attribute assignments in this branch: they are used # only in .update() if not self.location: location_data = json.loads(urllib_read("http://freegeoip.net/json/")) self.location = ",".join( [location_data["city"], location_data["region_code"], location_data["country_code"]] ) query_data = { "q": 'use "http://github.com/yql/yql-tables/raw/master/weather/weather.bylocation.xml" as we;' 'select * from we where location="{0}" and unit="c"'.format(self.location).encode("utf-8"), "format": "json", } self.url = "http://query.yahooapis.com/v1/public/yql?" + urllib_urlencode(query_data) raw_response = urllib_read(self.url) if not raw_response: self.error("Failed to get response") return response = json.loads(raw_response) condition = response["query"]["results"]["weather"]["rss"]["channel"]["item"]["condition"] condition_code = int(condition["code"]) temp = float(condition["temp"]) try: icon_names = weather_conditions_codes[condition_code] except IndexError: if condition_code == 3200: icon_names = ("not_available",) self.warn("Weather is not available for location {0}", self.location) else: icon_names = ("unknown",) self.error("Unknown condition code: {0}", condition_code) return (temp, icon_names)
def get_request_url(self, weather_key): try: return self.location_urls[weather_key] except KeyError: query_data = { "appid": weather_key.weather_api_key } location_query = weather_key.location_query if location_query is None: location_data = json.loads(urllib_read('https://freegeoip.app/json/')) query_data["lat"] = location_data["latitude"] query_data["lon"] = location_data["longitude"] else: query_data["q"] = location_query self.location_urls[location_query] = url = ( "https://api.openweathermap.org/data/2.5/weather?" + urllib_urlencode(query_data)) return url
def compute_state(self, location_query): url = self.get_request_url(location_query) #print("+"*80, url) raw_response = urllib_read(url) if not raw_response: self.error('Failed to get response') return None response = json.loads(raw_response) try: condition = response['main'] temp = float(str(condition['temp'])) feels_like = float(str(condition['feels_like'])) sunrise = int(str(response['sys']['sunrise'])) sunset = int(str(response['sys']['sunset'])) condition_code = str(response['weather'][0]['main']).lower() if condition_code == 'clear': if (time.time() > sunrise and time.time() < sunset): condition_code = 'clear_day' else: condition_code = 'clear_night' except (KeyError, ValueError): self.exception( 'Weather query returned malformed or unexpected response: {0}', repr(raw_response)) return None try: condition_from_code = weather_conditions_codes[ condition_code].lower() icon_names = (condition_from_code, ) except IndexError: if condition_code == 3200: icon_names = ('not_available', ) self.warn('Weather is not available for location {0}', self.location) else: icon_names = ('unknown', ) self.error('Unknown condition code: {0}', condition_code) return (temp, feels_like, icon_names)
def get_request_url(self, location_query): try: return self.location_urls[location_query] except KeyError: if location_query is None: location_data = json.loads(urllib_read("http://freegeoip.net/json/")) location = ",".join( (location_data["city"], location_data["region_name"], location_data["country_code"]) ) self.info("Location returned by freegeoip is {0}", location) else: location = location_query query_data = { "q": 'use "https://raw.githubusercontent.com/yql/yql-tables/master/weather/weather.bylocation.xml" as we;' 'select * from we where location="{0}" and unit="c"'.format(location).encode("utf-8"), "format": "json", } self.location_urls[location_query] = url = "http://query.yahooapis.com/v1/public/yql?" + urllib_urlencode( query_data ) return url
def player(self, key): query_data = { 'method': 'user.getrecenttracks', 'format': 'json', 'user': key.username, 'api_key': key.api_key, 'nowplaying': 'true', } url = 'http://ws.audioscrobbler.com/2.0/?' + \ urllib_urlencode(query_data) raw_response = urllib_read(url) if not raw_response: self.error('Failed to get response') return response = json.loads(raw_response) track_info = response['recenttracks']['track'] track_info_type = type(track_info) if track_info_type == types.ListType: track = track_info[0] status = 'play' elif track_info_type == types.DictType: track = track_info[1] else: self.error('Invalid response') status = 'fallback' return artist = track['artist']['#text'] if self.shorten_artist: artist = self.shorten_artist(artist) title = track['name'] if self.shorten_title: title = self.shorten_title(title) return { 'artist': artist, 'title': title, 'playing': status, }
def get_geometry(self, location_query): try: return self.location_geometries[location_query] except KeyError: if location_query is None: self.error('No location specified') else: location = location_query.split(',') query_data = { 'address': location[0], 'region': location[1], 'sensor': 'false' } try: location_data = json.loads( urllib_read( 'http://maps.google.com/maps/api/geocode/json?' + urllib_urlencode(query_data))) if location_data['results']: location = ','.join( (str(location_data['results'][0]['geometry'] ['location']['lat']), str(location_data['results'][0]['geometry'] ['location']['lng']))) self.location_geometries[ location_query] = geometry = location return geometry else: self.location_geometries[ 'cairo, eg'] = geometry = '30.0444196,31.2357116' return geometry except: self.warn( "Something went wrong while calculating location") self.location_geometries[ 'cairo, eg'] = geometry = '30.0444196,31.2357116' return self.location_geometries['cairo, eg']
def compute_state(self, weather_key): url = self.get_request_url(weather_key) raw_response = urllib_read(url) if not raw_response: self.error('Failed to get response') return None response = json.loads(raw_response) try: condition = response['weather'][0] condition_code = int(condition['id']) temp = float(response['main']['temp']) except (KeyError, ValueError): self.exception('OpenWeatherMap returned malformed or unexpected response: {0}', repr(raw_response)) return None try: icon_names = weather_conditions_codes[condition_code] except IndexError: icon_names = ('unknown',) self.error('Unknown condition code: {0}', condition_code) return (temp, icon_names)
def get_request_url(self, location_query): try: return self.location_urls[location_query] except KeyError: if location_query is None: location_data = json.loads(urllib_read('http://freegeoip.net/json/')) location = ','.join(( location_data['city'], location_data['region_name'], location_data['country_code'] )) self.info('Location returned by freegeoip is {0}', location) else: location = location_query query_data = { 'q': 'use "https://raw.githubusercontent.com/yql/yql-tables/master/weather/weather.bylocation.xml" as we;' 'select * from we where location="{0}" and unit="c"'.format(location).encode('utf-8'), 'format': 'json', } self.location_urls[location_query] = url = ( 'http://query.yahooapis.com/v1/public/yql?' + urllib_urlencode(query_data)) return url
def get_request_url(self, location_query): try: return self.location_urls[location_query] except KeyError: if location_query is None: location_data = json.loads(urllib_read('http://geoip.nekudo.com/api/')) location = ','.join(( location_data['city'], location_data['country']['name'], location_data['country']['code'] )) self.info('Location returned by nekudo is {0}', location) else: location = location_query format_ = "%c||+%l:+%t" self.location_urls[location_query] = url = ( 'http://wttr.in/{location}?format={format_}&{units}'.format( location=location, units=self.get_unit(), format_=format_ ) ) return url
def compute_state(self, location_query): url = self.get_request_url(location_query) # bug fix for powerline segment: # if urlopen fails (for example, if you don't have an internet connection), # then weather segment should silently fail try: raw_response = urllib_read(url) except Exception: raw_response = None if not raw_response: return None response = json.loads(raw_response) try: condition = response['query']['results']['weather']['rss'][ 'channel']['item']['condition'] condition_code = int(condition['code']) temp = float(condition['temp']) except (KeyError, ValueError): self.exception( 'Yahoo returned malformed or unexpected response: {0}', repr(raw_response)) return None try: icon_names = weather_conditions_codes[condition_code] except IndexError: if condition_code == 3200: icon_names = ('not_available', ) self.warn('Weather is not available for location {0}', self.location) else: icon_names = ('unknown', ) self.error('Unknown condition code: {0}', condition_code) return (temp, icon_names)
def get_request_url(self, location_query): try: return self.location_urls[location_query] except KeyError: if location_query is None: location_data = json.loads(urllib_read('http://geoip.nekudo.com/api/')) location = ','.join(( location_data['city'], location_data['country']['name'], location_data['country']['code'] )) self.info('Location returned by nekudo is {0}', location) else: location = location_query query_data = { 'q': 'use "https://raw.githubusercontent.com/yql/yql-tables/master/weather/weather.bylocation.xml" as we;' 'select * from weather.forecast where woeid in' ' (select woeid from geo.places(1) where text="{0}") and u="c"'.format(location).encode('utf-8'), 'format': 'json', } self.location_urls[location_query] = url = ( 'http://query.yahooapis.com/v1/public/yql?' + urllib_urlencode(query_data)) return url
def _external_ip(query_url='http://ipv4.icanhazip.com/'): return urllib_read(query_url).strip()
def compute_state(self, key): if key.locations == None: self.warn('No location provided') return urllib_read(base_url % (':'.join( key.locations), urllib_urlencode({'format': key.format})))
#!/usr/bin/env python3 import json import socket from powerline.lib.url import urllib_read # Providers ipify = ('ipify', 'https://api.ipify.org/?format=json') httpbin = ('httpbin', 'http://httpbin.org/ip') jsonip = ('jsonip', 'http://ipv4.jsonip.com') ip42 = ('ip42', 'http://ip.42.pl/raw') local = (socket.gethostname(), '') # IP Dictionary IPs = {} IPs[ipify[0]] = json.loads(urllib_read(ipify[1]))['ip'] IPs[httpbin[0]] = json.loads(urllib_read(httpbin[1]))['origin'] IPs[jsonip[0]] = json.loads(urllib_read(jsonip[1]))['ip'] IPs[ip42[0]] = urllib_read(ip42[1]) IPs['local'] = socket.gethostbyname(local[0]) print(""" %(ipify)s %(httpbin)s %(jsonip)s %(ip42)s %(local)s """ % (IPs))