def update_weather(self): if any(var.location_data): try: # get weather lat = str(var.location_data['latitude']) lon = str(var.location_data['longitude']) key = var.api_tokens['dark_sky_weather'] print 'lat' + str(lat) print 'long' + str(lon) print 'token!:' + str(key) weather_req_url = "https://api.darksky.net/forecast/%s/%s,%s" % (key, lat, lon) r = requests.get(weather_req_url) print '---------------------------------------' print r weather_obj = json.loads(r.text) print '--------------------------------------' print weather_obj if weather_obj is not None: var.weather_data = weather_obj varloader.save_data_to_json_file(var.weather_data, var.file_paths['weather']) except Exception as e: traceback.print_exc() print "Error: %s. Cannot get weather." % e if not any(var.weather_data): exit()
def update_location(self): # Gets IP information temp_ip = self.get_ip() # Gets Location information try: # Get location from web location_req_url = "http://freegeoip.net/json/%s" % temp_ip r = requests.get(location_req_url, timeout=10) # todo is point 5 long enough?? WHAT TO DO IF TIMEOUT SIGNAL FAIL??? location_obj = json.loads(r.text) lat = location_obj['latitude'] lon = location_obj['longitude'] print lat print lon if location_obj is not None: var.location_data = location_obj varloader.save_data_to_json_file(var.location_data, var.file_paths['location']) # Save to File except Exception as e: traceback.print_exc() print "Error: %s. Cannot get Location, " % e if not any(var.weather_data): exit()
def update_news(self): # Gets News information try: if var.country_code is None: headlines_url = "https://news.google.com/news?ned=us&output=rss" else: headlines_url = "https://news.google.com/news?ned=%s&output=rss" % var.country_code feed = feedparser.parse(headlines_url) if feed is not None: headlines = {} # Taking out only the headlines and links to those headlines links = {} # Converting data to Json print feed.entries[0].keys() counter = 0 for entry in feed.entries: headlines[str(counter)] = entry.title links[str(counter)] = entry.links counter += 1 var.news_data['headlines'] = headlines var.news_data['links'] = links var.news_data['number_of_headlines'] = counter varloader.save_data_to_json_file(var.news_data, var.file_paths['news']) print [field for field in feed] print (entry for entry in feed['entries']) except Exception as e: traceback.print_exc() print "Error: %s. Cannot get news." % e if not any(var.news_data): exit()
def update(self): if var.gmap is not None: gmap.get_travel_time() if var.stocks_list is not None: gstocks.get_stocks_data() gcalendar.get_calendar_events() # todo Check if this is enabled? Create a Boolean to enable?? UNCOMMENT self.update_location() self.update_weather() self.update_news() print 'UPDATING TIME BITCHES~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' var.last_updated = time.time() varloader.save_data_to_json_file(var.last_updated, var.file_paths['last_updated']) if var.weather_data is None or var.news_data is None: print "No instance of weather or news data. Quitting mirror" exit()
def get_calendar_events(): """Shows basic usage of the Google Calendar API. Creates a Google Calendar API service object and outputs a list of the next 10 events on the user's calendar. """ try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None credentials = get_credentials(flags) http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', 'v3', http=http) now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time print('Getting the upcoming 10 events') eventsResult = service.events().list( calendarId='primary', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute() events = eventsResult.get('items', []) var.calendar_data = {} counter = 0 if not events: print('No upcoming events found.') for event in events: print(event) start = event['start'].get('dateTime', event['start'].get('date')) print(start) summary_string = '--no title--' description_string = '--no description--' location_string = '--no location--' date_time_string = '' if 'summary' in event: summary_string = event['summary'] if 'description' in event: description_string = event['description'] if 'location' in event: location_string = event['location'] if 'start' in event: date_time_string = event['start']['date'] event_data = {} try: event_data['summary'] = summary_string except Exception as e: print(e) try: event_data['description'] = re.sub('\n', '', description_string) except Exception as e: print(e) try: event_data['location'] = location_string.split(',')[0] except Exception as e: print(e) try: event_data['date'] = date_time_string[0:10] except Exception as e: print(e) try: event_data['start_time'] = date_time_string[11:16] except Exception as e: print(e) var.calendar_data[str(counter)] = event_data counter += 1 varloader.save_data_to_json_file(var.calendar_data, var.file_paths['calendar_data'])
def get_travel_time(): # getting necessary data origin = var.gmap['origin'] destination = var.gmap['destination'] gmap_settings = var.gmap['settings'] # Getting Cords for Origin Location origin_address = origin['state_address'] + ',+' + origin[ 'city_address'] + ',+' + origin['state_address'] url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + origin_address + '&key=' + var.api_tokens[ 'google_geocode'] result = simplejson.load(urllib.urlopen(url)) print result origin_location = result['results'][0]['geometry']['location'] print origin_location # Getting Coords for Destination Location destination_address = destination['state_address'] + ',+' + destination[ 'city_address'] + ',+' + destination['state_address'] url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + destination_address + '&key=' + \ var.api_tokens['google_geocode'] result = simplejson.load(urllib.urlopen(url)) print result destination_location = result['results'][0]['geometry']['location'] print destination_location # Personal Settings for Origin to Destination origins = str(origin_location['lat']) + ',' + str(origin_location['lng']) destinations = str(destination_location['lat']) + ',' + str( destination_location['lng']) # Getting google map time to get from origin to destination print var.api_tokens['google_distance_matrix'] url = 'https://maps.googleapis.com/maps/api/distancematrix/json?' + \ 'origins=' + origins + \ '&destinations=' + destinations + \ '&departure_time=now' + \ '&mode=' + gmap_settings['mode'] + \ '&language=fr-FR' + \ '&key=' + var.api_tokens['google_distance_matrix'] # Checks for case that it was Transit if gmap_settings['mode'] == 'transit': url = url + '&transit_mode' + gmap_settings['transit_mode'] # Checks for case that it was avoid tolls if gmap_settings['avoid_tolls']: url += '&avoid=tolls' # Display Results result = simplejson.load(urllib.urlopen(url)) print result time_to_location = result['rows'][0]['elements'][0]['duration_in_traffic'][ 'text'] print time_to_location var.travel_data['main'] = time_to_location # Now Checking Local drive time if gmap_settings['avoid_tolls']: url += '|highways' else: url += '&avoid=highways' # Display Results result = simplejson.load(urllib.urlopen(url)) print result time_to_location_locally = result['rows'][0]['elements'][0][ 'duration_in_traffic']['text'] print time_to_location_locally var.travel_data['backup'] = time_to_location_locally varloader.save_data_to_json_file(var.travel_data, var.file_paths['travel_data'])
from googlefinance import getQuotes import json from project.resources import var, varloader def get_stocks_data(): try: for stock in var.stocks_list: data = json.dumps(getQuotes(str(stock)), indent=2) data = json.loads(data)[0] print data if data is not None: var.stock_data[stock] = data print 'Pulled ', stock except Exception, e: print 'Stocks Error', str(e) varloader.save_data_to_json_file(var.stock_data, var.file_paths['stock_data']) #sudo apt install python-pip # pip install demjson # sudo pip install googlefinance