Exemplo n.º 1
0
 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
Exemplo n.º 2
0
 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
Exemplo n.º 3
0
    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
Exemplo n.º 4
0
    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)
Exemplo n.º 5
0
	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
Exemplo n.º 6
0
	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)
Exemplo n.º 7
0
	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,
				}
Exemplo n.º 8
0
    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,
        }
Exemplo n.º 9
0
    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']
Exemplo n.º 10
0
    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)
Exemplo n.º 11
0
	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
Exemplo n.º 12
0
	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
Exemplo n.º 13
0
 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
Exemplo n.º 14
0
 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})))