def get_current_location_option2():
    try:
        url = 'http://ip-api.com/json'
        ans = json.loads(comun.read_from_url(url))
        return ans['lat'], ans['lon']
    except Exception as e:
        print(e)
    return 0, 0
def find_city(longitude,latitude):
		url = URL_FIND_CITY%(latitude,longitude)
		json_string = read_from_url(url)
		if json_string:
			parsed_json = json.loads(json_string.decode())
			elist = parsed_json['list']
			if len(elist)>0:
				return elist[0]['id']
		return None
	def test_connection(self):
		try:
			json_string = read_from_url(URL%(self.key,self.latitude,self.longitude))
			if json_string.decode().find('error')!=-1:
				print('error found')
				return False
			return True
		except Exception as e:
			print(e)
		return False
def get_timezoneId(lat, lon):
    print('****** Requesting timezone identificacion')
    try:
        response = read_from_url('http://api.geonames.org/timezoneJSON?lat=\
                                 %s&lng=%s&username=atareao'
                                 % (lat, lon)).decode()
        json_response = json.loads(response)
        if json_response and 'timezoneId' in json_response.keys():
            return json_response['timezoneId']
    except Exception as e:
        print('Error requesting timezone identification: %s' % (str(e)))
    return 'Europe/London'
def get_directions(search_string):
    directions = []
    try:
        url = URLDIR_YAHOO2 % (LANG, search_string)
        print('Searching url: %s' % (url))
        yahooResponse = read_from_url(url)
        if sys.version_info[0] == 3:
            jsonResponse = json.loads(yahooResponse.decode())
        else:
            jsonResponse = json.loads(yahooResponse)
        print(jsonResponse)
        if int(jsonResponse['Found']) > 1:
            for ans in jsonResponse['Result']:
                directions.append(fromjson2direction(ans))
        else:
            ans = jsonResponse['Result']
            directions.append(fromjson2direction(ans))
    except Exception as e:
        print('Error:', e)
    return directions
	def get_hourly_weather(self):
		weatherdata=[]
		if self.id:
			url = URL_HOURLY_CITY_ID%self.id
		else:
			url = URL_HOURLY_CITY_LL%(self.latitude,self.longitude)
		print('OWMWeatherService Current Weather url:%s'%(url))
		json_string = read_from_url(url)
		parsed_json = json.loads(json_string.decode())
		for contador, data in enumerate(parsed_json['list']):				
			condition = CONDITION[data['weather'][0]['id']]
			temperature = fa2f(data['main']['temp'])
			cloudiness = data['clouds']['all']
			pressure = data['main']['pressure']
			humidity = data['main']['humidity']
			velocity = data['wind']['speed'] if 'wind' in data.keys() and 'speed' in data['wind'].keys() else 0.0
			t1 = fa2f(data['main']['temp_min'])
			t2 = fa2f(data['main']['temp_max'])
			direction = data['wind']['deg'] if 'wind' in data.keys() and 'deg' in data['wind'].keys() else 0.0
			if t1<t2:
				temp_min=str(t1)
				temp_max=str(t2)
			else:
				temp_min=str(t2)
				temp_max=str(t1)							
			wind_direction = weatherservice.degToCompass2(direction)					
			wdd = {}
			wdd['datetime']=datetime.fromtimestamp(data['dt'])
			wdd['condition'] = condition
			wdd['condition_text'] = weatherservice.get_condition(condition,'text')
			wdd['condition_image'] = weatherservice.get_condition(condition,'image')
			wdd['condition_icon'] = weatherservice.get_condition(condition,'icon-light')																	
			wdd['temperature'] = weatherservice.change_temperature(temperature,self.units.temperature).split(' ')[0]
			wdd['low'] = weatherservice.change_temperature(temp_min,self.units.temperature)
			wdd['high'] = weatherservice.change_temperature(temp_max,self.units.temperature)
			wdd['cloudiness'] = '%s'%(cloudiness)
			wdd['avehumidity'] = '%s'%(humidity)
			wdd['avewind'] = weatherservice.get_wind_condition2(velocity,wind_direction[0],self.units.wind)
			wdd['wind_icon'] = wind_direction[2]
			weatherdata.append(wdd)
		return weatherdata
def download_xml(url):
    url = unicode2html(url)
    url = url.replace(" ", "%20")
    print('URL: %s' % url)
    xml_response = read_from_url(url)
    return xml_response
def download_xml(url):
    print('URL: %s' % url)
    xml_response = read_from_url(url)
    return xml_response
	def get_weather(self):
		self.id = None
		weather_data = self.get_default_values()
		#try:
		if self.id:
			url = URL_CURRENT_CITY_ID%self.id
		else:
			url = URL_CURRENT_CITY_LL%(self.latitude,self.longitude)
		print('-------------------------------------------------------')
		print('-------------------------------------------------------')
		print('OpenWeatherMap Weather Service url:%s'%(url))
		print('-------------------------------------------------------')
		print('-------------------------------------------------------')			
		json_string = read_from_url(url)
		if json_string is None:
			return None
		parsed_json = json.loads(json_string.decode())
		if  'weather' not in parsed_json.keys() or 'main' not in parsed_json.keys() or 'wind' not in parsed_json.keys() or 'clouds' not in parsed_json.keys():
			return None
		if parsed_json['weather'][0]['id'] not in CONDITION.keys():
			condition = 'not available'
		else:
			condition = CONDITION[parsed_json['weather'][0]['id']]
		temperature = fa2f(parsed_json['main']['temp'])
		pressure = parsed_json['main']['pressure'] if 'pressure' in parsed_json['main'] else 0
		humidity = parsed_json['main']['humidity'] if 'humidity' in parsed_json['main'] else 0
		velocity = parsed_json['wind']['speed'] if 'speed' in parsed_json['wind'] else 0
		cloudiness = parsed_json['clouds']['all']
		if 'deg' in  parsed_json['wind'].keys():
			direction = parsed_json['wind']['deg']
		else:
			direction = 0
		wind_direction = weatherservice.degToCompass2(direction)
		weather_data['current_conditions']['condition'] = condition
		weather_data['current_conditions']['condition_text'] = weatherservice.get_condition(condition,'text')
		if weather_data['current_conditions']['isday']:
			weather_data['current_conditions']['condition_image'] = weatherservice.get_condition(condition,'image')
			weather_data['current_conditions']['condition_icon_dark'] = weatherservice.get_condition(condition,'icon-dark')
			weather_data['current_conditions']['condition_icon_light'] = weatherservice.get_condition(condition,'icon-light')
		else:
			weather_data['current_conditions']['condition_image'] = weatherservice.get_condition(condition,'image-night')
			weather_data['current_conditions']['condition_icon_dark'] = weatherservice.get_condition(condition,'icon-night-dark')
			weather_data['current_conditions']['condition_icon_light'] = weatherservice.get_condition(condition,'icon-night-light')
		weather_data['current_conditions']['temperature'] = weatherservice.change_temperature(temperature,self.units.temperature)
		weather_data['current_conditions']['pressure'] = weatherservice.change_pressure(pressure,self.units.pressure)
		weather_data['current_conditions']['humidity'] = '%s %%'%(humidity)
		weather_data['current_conditions']['dew_point'] = weatherservice.get_dew_point(humidity,temperature,self.units.temperature)
		weather_data['current_conditions']['wind_condition'] = weatherservice.get_wind_condition2(velocity,wind_direction[0],self.units.wind)
		weather_data['current_conditions']['wind_icon'] = wind_direction[2]
		weather_data['current_conditions']['heat_index'] = weatherservice.get_heat_index(temperature,humidity)
		weather_data['current_conditions']['windchill'] = weatherservice.get_wind_chill(temperature,velocity)
		weather_data['current_conditions']['feels_like'] = weatherservice.get_feels_like(temperature,humidity,velocity,self.units.temperature)
		weather_data['current_conditions']['visibility'] = None
		weather_data['current_conditions']['cloudiness'] = '%s %%'%(cloudiness)
		weather_data['current_conditions']['solarradiation'] = None
		weather_data['current_conditions']['UV'] = None
		weather_data['current_conditions']['precip_1hr'] = None
		weather_data['current_conditions']['precip_today'] = None			
		#
		
		#try:
		if self.id:
			url = URL_FORECAST_CITY_ID%self.id
		else:
			url = URL_FORECAST_CITY_LL%(self.latitude,self.longitude)
		json_string = read_from_url(url)
		if json_string is None:
			return weather_data
		parsed_json = json.loads(json_string.decode())
		for contador, data in enumerate(parsed_json['list']):
			condition = CONDITION[data['weather'][0]['id']]
			temperature = fa2f(data['temp']['day'])
			cloudiness = data['clouds'] if 'clouds' in data.keys() else 0
			pressure = data['pressure'] if 'pressure' in data.keys() else 0
			humidity = data['humidity'] if 'humidity' in data.keys() else 0
			velocity = data['speed'] if 'speed' in data.keys() else 0
			t1 = fa2f(data['temp']['min'])
			t2 = fa2f(data['temp']['max'])
			direction = data['deg']
			if t1<t2:
				temp_min=str(t1)
				temp_max=str(t2)
			else:
				temp_min=str(t2)
				temp_max=str(t1)							
			wind_direction = weatherservice.degToCompass2(direction)					
			weather_data['forecasts'][contador]['condition'] = condition
			weather_data['forecasts'][contador]['condition_text'] = weatherservice.get_condition(condition,'text')
			weather_data['forecasts'][contador]['condition_image'] = weatherservice.get_condition(condition,'image')
			weather_data['forecasts'][contador]['condition_icon'] = weatherservice.get_condition(condition,'icon-light')																	
			weather_data['forecasts'][contador]['low'] = weatherservice.change_temperature(temp_min,self.units.temperature)
			weather_data['forecasts'][contador]['high'] = weatherservice.change_temperature(temp_max,self.units.temperature)
			weather_data['forecasts'][contador]['cloudiness'] = '%s %%'%(cloudiness)
			weather_data['forecasts'][contador]['avehumidity'] = '%s %%'%(humidity)
			weather_data['forecasts'][contador]['avewind'] = weatherservice.get_wind_condition2(velocity,wind_direction[0],self.units.wind)
			weather_data['forecasts'][contador]['wind_icon'] = wind_direction[2]
			weather_data['forecasts'][contador]['qpf_allday'] = None
			weather_data['forecasts'][contador]['qpf_day'] = None
			weather_data['forecasts'][contador]['qpf_night'] = None
			weather_data['forecasts'][contador]['snow_allday'] = None
			weather_data['forecasts'][contador]['snow_day'] = None
			weather_data['forecasts'][contador]['snow_night'] = None
			weather_data['forecasts'][contador]['maxwind'] = None
			weather_data['forecasts'][contador]['maxhumidity'] = None
			weather_data['forecasts'][contador]['minhumidity'] = None					
		#except Exception as e:
		#	print(e)
		return weather_data
def get_ip():
    url = 'http://whatismyip.org'
    ans = comun.read_from_url(url)
    # print(ans)
    return re.compile(r'(\d+\.\d+\.\d+\.\d+)').search(ans).group(1)
Example #11
0
def download_xml(url):
    print("URL: %s" % url)
    xml_response = read_from_url(url)
    return xml_response
	def _get_weather(self):
		weather_data = self.get_default_values()
		print('-------------------------------------------------------')
		print('-------------------------------------------------------')
		print('Underground Weather Service url: %s'%URL%(self.key,self.latitude,self.longitude))
		print('-------------------------------------------------------')
		print('-------------------------------------------------------')		
		json_string = read_from_url(URL%(self.key,self.latitude,self.longitude))
		if json_string is None:
			return None
		parsed_json = json.loads(json_string.decode())
		condition = gvfco('weather',parsed_json).lower()
		#
		weather_data['current_conditions']['condition_text'] = weatherservice.get_condition(condition,'text')
		if weather_data['current_conditions']['isday']:
			weather_data['current_conditions']['condition_image'] = weatherservice.get_condition(condition,'image')
			weather_data['current_conditions']['condition_icon_dark'] = weatherservice.get_condition(condition,'icon-dark')
			weather_data['current_conditions']['condition_icon_light'] = weatherservice.get_condition(condition,'icon-light')
		else:
			weather_data['current_conditions']['condition_image'] = weatherservice.get_condition(condition,'image-night')
			weather_data['current_conditions']['condition_icon_dark'] = weatherservice.get_condition(condition,'icon-night-dark')
			weather_data['current_conditions']['condition_icon_light'] = weatherservice.get_condition(condition,'icon-night-light')
		temperature = weatherservice.s2f(gvfco('temp_f',parsed_json))
		weather_data['current_conditions']['temperature'] = weatherservice.change_temperature(temperature,self.units.temperature)
		pressure = weatherservice.s2f(gvfco('pressure_mb',parsed_json))
		weather_data['current_conditions']['pressure'] = weatherservice.change_pressure(pressure,self.units.pressure)
		humidity = weatherservice.s2f(gvfco('relative_humidity',parsed_json)[:-1])
		weather_data['current_conditions']['humidity'] = str(int(humidity))+' %'
		weather_data['current_conditions']['dew_point'] = weatherservice.get_dew_point(humidity,temperature,self.units.temperature)
		wind_velocity = weatherservice.s2f(gvfco('wind_mph',parsed_json))
		wind_direction = gvfco('wind_dir',parsed_json)
		print(wind_direction)
		weather_data['current_conditions']['wind_condition'] = weatherservice.get_wind_condition(wind_velocity,wind_direction,self.units.wind)
		weather_data['current_conditions']['wind_icon'] =weatherservice.get_wind_icon(wind_direction)
		#
		weather_data['current_conditions']['heat_index'] = weatherservice.get_heat_index(temperature,humidity)
		weather_data['current_conditions']['windchill'] = weatherservice.get_wind_chill(temperature,wind_velocity)
		#
		weather_data['current_conditions']['feels_like'] = weatherservice.get_feels_like(temperature,humidity,wind_velocity,self.units.temperature)
		#
		weather_data['current_conditions']['visibility'] = weatherservice.change_distance(gvfco('visibility_mi',parsed_json),self.units.visibility)
		weather_data['current_conditions']['solarradiation'] = gvfco('solarradiation',parsed_json)
		weather_data['current_conditions']['UV'] = gvfco('UV',parsed_json)
		weather_data['current_conditions']['precip_1hr'] = weatherservice.change_longitude(gvfco('precip_1hr_in',parsed_json),self.units.rain)
		weather_data['current_conditions']['precip_today'] = weatherservice.change_longitude(gvfco('precip_today_in',parsed_json),self.units.rain)
		for i in range(0,4):
			weather_data['forecasts'][i]['low'] = weatherservice.change_temperature(gvff('low',i,parsed_json)['fahrenheit'],self.units.temperature)
			weather_data['forecasts'][i]['high'] = weatherservice.change_temperature(gvff('high',i,parsed_json)['fahrenheit'],self.units.temperature)
			#
			weather_data['forecasts'][i]['qpf_allday'] = weatherservice.change_longitude(gvff('qpf_allday',i,parsed_json)['in'],self.units.rain)
			weather_data['forecasts'][i]['qpf_day'] = weatherservice.change_longitude(gvff('qpf_day',i,parsed_json)['in'],self.units.rain)
			weather_data['forecasts'][i]['qpf_night'] = weatherservice.change_longitude(gvff('qpf_night',i,parsed_json)['in'],self.units.rain)
			weather_data['forecasts'][i]['snow_allday'] = weatherservice.change_longitude(gvff('snow_allday',i,parsed_json)['in'],self.units.snow)
			weather_data['forecasts'][i]['snow_day'] = weatherservice.change_longitude(gvff('snow_day',i,parsed_json)['in'],self.units.snow)
			weather_data['forecasts'][i]['snow_night'] = weatherservice.change_longitude(gvff('snow_night',i,parsed_json)['in'],self.units.snow)
			wind = gvff('maxwind',i,parsed_json)
			weather_data['forecasts'][i]['maxwind'] = weatherservice.get_wind_condition(wind['mph'],wind['dir'],self.units.wind)
			wind = gvff('avewind',i,parsed_json)
			weather_data['forecasts'][i]['avewind'] = weatherservice.get_wind_condition(wind['mph'],wind['dir'],self.units.wind)
			weather_data['forecasts'][i]['avehumidity'] = '%s %%'%gvff('avehumidity',i,parsed_json)
			weather_data['forecasts'][i]['maxhumidity'] = '%s %%'%gvff('maxhumidity',i,parsed_json)
			weather_data['forecasts'][i]['minhumidity'] = '%s %%'%gvff('minhumidity',i,parsed_json)
			#
			condition = gvff('conditions',i,parsed_json).lower()
			weather_data['forecasts'][i]['condition'] = condition
			weather_data['forecasts'][i]['condition_text'] = weatherservice.get_condition(condition,'text')
			weather_data['forecasts'][i]['condition_image'] = weatherservice.get_condition(condition,'image')
			weather_data['forecasts'][i]['condition_icon'] = weatherservice.get_condition(condition,'icon-light')
		weather_data['forecast_information']['city'] = gvfi('city',parsed_json)
		weather_data['forecast_information']['postal_code'] = gvfi('zip',parsed_json)
		weather_data['forecast_information']['latitude_e6'] = gvfi('latitude',parsed_json)
		weather_data['forecast_information']['longitude_e6'] = gvfi('longitude',parsed_json)
		return weather_data
Example #13
0
	def _loader(self,uri):
		if uri != None:
			self.loading = True
			#try:
			print(uri,urls['wikipedia'][self.language])
			if urls['wikipedia'][self.language] is not None and uri.startswith(urls['wikipedia'][self.language]):
				code = read_from_url(uri).decode()
				doc = lh.document_fromstring(clean_html(code))
				result = lh.tostring(doc.get_element_by_id('bodyContent'),method = 'html').decode()
				#self.webview.load_string(result, 'text/html', 'utf-8', uri)
				self.webview.load_html(result, uri)
				self.text.set_text(uri.split(urls['wikipedia'][self.language])[1])
			elif uri.startswith(urls['wordreference'][self.language]):
				code = read_from_url(uri).decode()
				doc = lh.document_fromstring(clean_html(code))
				trans = doc.find_class('trans')
				if len(trans)>0:
					trans_tmp = ''
					for t in trans:
						trans_tmp = trans_tmp + lh.tostring(t,method = 'html').decode()
					self.webview.load_string(trans_tmp, 'text/html', 'utf-8', uri)
					self.text.set_text(uri.split(urls['wordreference'][self.language])[1])	
				else:
					raise HTTPError(uri, '404', '404', None, None)
			elif urls['dictionary.com']['es'] is not None and uri.startswith(urls['dictionary.com']['es']):
				code = read_from_url(uri).decode()
				doc = lh.document_fromstring(clean_html(code))
				body = doc.find_class('tab_contents tab_contents_active')
				if len(body)>0:
					body_tmp = ''
					for b in body:
						body_tmp = body_tmp + lh.tostring(b,method = 'html').decode()
					self.webview.load_string(body_tmp, 'text/html', 'utf-8', uri)
					self.text.set_text(uri.split(urls['dictionary.com'][self.language])[1])
			elif urls['dictionary.com']['en'] is not None and uri.startswith(urls['dictionary.com']['en']):
				code = read_from_url(uri).decode()
				doc = lh.document_fromstring(clean_html(code))
				body = doc.find_class('sep_top shd_hdr pb7')
				if len(body)>0:
					body_tmp = ''
					for b in body:
						body_tmp = body_tmp + lh.tostring(b,method = 'html').decode()
					self.webview.load_string(body_tmp, 'text/html', 'utf-8', uri)
					self.text.set_text(uri.split(urls['dictionary.com'][self.language])[1],encoding)
			elif urls['rae'][self.language] is not None and uri.startswith(urls['rae'][self.language]):
				searchfor = uri.replace(urls['rae'][self.language],'')
				body = self.search_in_rae(searchfor).decode()	
				body = clean_html(body)
				self.webview.load_string(body, 'text/html', 'utf-8', uri)
				self.text.set_text(uri.split(urls['rae'][self.language])[1])	
			elif uri.startswith('http://buscon.rae.es/draeI/search?id='):
				searchfor = uri.replace('http://buscon.rae.es/draeI/search?id=','')
				body = self.search_in_rae_id(searchfor).decode()				
				#pos = body.find('<span class="f"><b>')
				#body = body[pos:]
				body = clean_html(body)
				m = re.search(r'<span class="(.*?)</span>', body, flags=0)
				if m:
					ans = m.group()
					print(ans)
					ans = ans.replace('<b>','').replace('</b>','').replace('</a>','').replace('</span>','')
					ans = ans.split('>')[-1]
					print(ans)
					self.text.set_text(ans)
				self.webview.load_string(body, 'text/html', 'utf-8', uri)
			self.loading = False