def _perform_post_auth_tasks(self, userid, creds): """Perform common post authorization tasks. Subscribes the service to notifications for the user. Creates tasks service and oauths it in. Args: userid: ID of the current user. creds: Credentials for the current user. """ mirror_service = util.create_service('mirror', 'v1', creds) tasks_service = util.create_service('tasks', 'v1', creds) hostname = util.get_full_url(self, '') # Only do the post auth tasks when deployed. if hostname.startswith('https://'): # Insert a subscription. subscription_body = { 'collection': 'timeline', # TODO: hash the userToken. 'userToken': userid, 'callbackUrl': util.get_full_url(self, '/notify') } mirror_service.subscriptions().insert(body=subscription_body).execute()
def post(self): """Handles notification pings.""" logging.info('Got a notification with payload %s', self.request.body) data = json.loads(self.request.body) userid = data['userToken'] # TODO: Check that the userToken is a valid userToken. self.mirror_service = util.create_service( 'mirror', 'v1', StorageByKeyName(Credentials, userid, 'credentials').get()) self.calendar_service = util.create_service( 'calendar', 'v3', StorageByKeyName(Credentials, userid, 'credentials').get()) if data.get('collection') == 'timeline': self._handle_timeline_notification(data)
def post(self): xmpp_addr=self.request.get('xmpp_addr') msg=self.request.get('msg') logging.info('post test') #logging.info("ImagestoreHandler#post %s", self.request.path) fileupload = self.request.POST.get("file",None) if fileupload is None : return self.error(400) # it doesn't seem possible for webob to get the Content-Type header for the individual part, # so we'll infer it from the file name. contentType = getContentType( fileupload.filename ) if contentType is None: self.error(400) self.response.headers['Content-Type'] = 'text/plain' self.response.out.write( "Unsupported image type: " + fileupload.filename ) return logging.info( "File upload: %s, mime type: %s", fileupload.filename, contentType ) file_data= fileupload.file.read() self.response.out.write('Got a '+str(len(file_data))+' bytes file\n') if xmpp_addr: self.response.out.write('XMPP address: '+xmpp_addr+'\n') id=XMPP_addr_access.get_id_from_addr(xmpp_addr) if id is not None: creds=StorageByKeyName(Credentials, id, 'credentials').get() mirror_service = util.create_service('mirror', 'v1', creds) logging.info('insert IMG') body = {'notification': {'level': 'DEFAULT'}} if msg is not None: body['text'] = msg media = MediaIoBaseUpload(io.BytesIO(file_data), mimetype='image/jpeg', resumable=True) mirror_service.timeline().insert(body=body, media_body=media).execute() else: self.response.out.write('no XMPP address')
def get(self): """ handle code exchange """ code = self.request.get('code') if not code: return None oauth_flow = self.create_oauth_flow() # perform the exchange of the code. if there is a failure with the exchange, return None try: creds = oauth_flow.step2_exchange(code) except FlowExchangeError: return None users_service = util.create_service('oauth2', 'v2', creds) user = users_service.userinfo().get().execute() userid = user.get('id') # store the credentials in the data store using the 'userid' as the key. StorageByKeyName(Credentials, userid, 'credentials').put(creds) logging.info('Successfully stored credentials for user: %s', userid) util.store_userid(self, userid) self.perform_post_auth_tasks(userid, creds) self.redirect('/')
def _perform_post_auth_tasks(self, userid, creds): """Perform commong post authorization tasks. Subscribes the service to notifications for the user. Args: userid: ID of the current user. creds: Credentials for the current user. """ mirror_service = util.create_service('mirror', 'v1', creds) hostname = util.get_full_url(self, '') # Only do the post auth tasks when deployed. if hostname.startswith('https://'): # Insert a subscription. subscription_body = { 'collection': 'timeline', # TODO: hash the userToken. 'userToken': userid, 'callbackUrl': util.get_full_url(self, '/notify') } mirror_service.subscriptions().insert( body=subscription_body).execute() else: logging.info('Post auth tasks are not supported on staging.')
def post(self): userid = self.request.get('userid') drive_service = util.create_service( 'drive', 'v2', StorageByKeyName(Credentials, userid, 'credentials').get()) id = self.request.get('id') logging.info(id) fileid = self.request.get('fileid') file_data = drive_service.files().get(fileId=fileid).execute() logging.debug(file_data) if (file_data.get('exportLinks')): download_url = file_data.get('exportLinks').get('text/plain') else: download_url = file_data['downloadUrl'] resp, content = drive_service._http.request(download_url) if resp.status == 200: retry_params = gcs.RetryParams(backoff_factor=1.1) out = gcs.open('/original_text/' + id, 'w', retry_params=retry_params) out.write(content) out.close() taskqueue.add(url='/postprocess', params={'id': id, 'userid': userid}) else: logging.error(resp)
def _select_tasklist(self): # selects tasklist, assigns to TASKLIST_NAME userid, creds = util.load_session_credentials(self) tasks_service = util.create_service('tasks', 'v1', creds) tasklist_id = self.request.get('select') logging.info("select") logging.info(self.request.get('select')) if tasklist_id == '': return "Please select a tasklist before trying to add it." else: #set name/id to db my_tasklist = TasklistStore(owner=self.userid) my_tasklist.my_id = tasklist_id #TASKLIST_NAMES.append(tasklist_title) tasklists = tasks_service.tasklists().list().execute() for tasklist in tasklists['items']: if tasklist_id == tasklist['id']: my_tasklist.my_name = tasklist['title'] #TASKLIST_IDS[tasklist_title] = tasklist['id'] my_tasklist.put() return my_tasklist.my_name + " selected successfully"
def get(self): video_url = self.request.get("url") """Render the main page.""" logging.info('Inserting timeline item to all users') users = Credentials.all() total_users = users.count() if total_users > 10: return 'Total user count is %d. Aborting broadcast to save your quota' % ( total_users) body = { 'notification': {'level': 'DEFAULT'}, 'text': video_url, } if 'youtube' in video_url: body['menuItems'] = [{'action' : 'PLAY_VIDEO', 'payload' : video_url}] batch_responses = _BatchCallback() batch = BatchHttpRequest(callback=batch_responses.callback) for user in users: creds = StorageByKeyName( Credentials, user.key().name(), 'credentials').get() mirror_service = util.create_service('mirror', 'v1', creds) timeline = retrieve_all_timeline_items(mirror_service) batch.add( mirror_service.timeline().insert(body=body), request_id=user.key().name()) batch.execute(httplib2.Http()) self._render_template('')
def _insert_item_all_users(self): """Insert a timeline item to all authorized users.""" logging.info('Inserting timeline item to all users') users = Credentials.all() total_users = users.count() if total_users > 10: return 'Total user count is %d. Aborting broadcast to save your quota' % ( total_users) body = { 'text': 'Hello Everyone!', 'notification': { 'level': 'DEFAULT' } } batch_responses = _BatchCallback() batch = BatchHttpRequest(callback=batch_responses.callback) for user in users: creds = StorageByKeyName(Credentials, user.key().name(), 'credentials').get() mirror_service = util.create_service('mirror', 'v1', creds) batch.add(mirror_service.timeline().insert(body=body), request_id=user.key().name()) batch.execute(httplib2.Http()) return 'Successfully sent cards to %d users (%d failed).' % ( batch_responses.success, batch_responses.failure)
def _perform_post_auth_tasks(self, userid, creds): """Perform commong post authorization tasks. Subscribes the service to notifications for the user and add one sharing contact. Args: userid: ID of the current user. creds: Credentials for the current user. """ mirror_service = util.create_service('mirror', 'v1', creds) hostname = util.get_full_url(self, '') subscription_body = { 'collection': 'timeline', # TODO: hash the userToken. 'userToken': userid, 'callbackUrl': util.get_full_url(self, '/notify') } # Only do the post auth tasks when deployed. if hostname.startswith('https://'): # Insert a subscription. logging.info('Inserting subscription in depoloyed mode') mirror_service.subscriptions().insert( body=subscription_body).execute() glassfit.contact.create_contact(mirror_service) else: logging.info("Supposed to create contact ...") logging.info('Creating a subscription using a proxy - LOCAL') subscription_body['callbackUrl'] = get_proxy_url('/notify') mirror_service.subscriptions().insert( body=subscription_body).execute()
def get(self): """Handle code exchange.""" code = self.request.get('code') if not code: # TODO: Display error. return None oauth_flow = self.create_oauth_flow() # Perform the exchange of the code. If there is a failure with exchanging # the code, return None. try: creds = oauth_flow.step2_exchange(code) except FlowExchangeError: # TODO: Display error. return None users_service = util.create_service('oauth2', 'v2', creds) # TODO: Check for errors. user = users_service.userinfo().get().execute() userid = user.get('id') # Store the credentials in the data store using the userid as the key. # TODO: Hash the userid the same way the userToken is. StorageByKeyName(Credentials, userid, 'credentials').put(creds) logging.info('Successfully stored credentials for user: %s', userid) util.store_userid(self, userid) self._perform_post_auth_tasks(userid, creds) self.redirect('http://www.glasseats.com/thank-you/')
def post(self): data = json.loads(self.request.body) actions = data.get('userActions', []) for action in actions: if 'payload' in action: credentials = StorageByKeyName(Credentials, data['userToken'], 'credentials').get() token = self._get_auth_token(data['userToken']) if credentials and token: mirror_service = util.create_service('mirror', 'v1', credentials) timeline_item = mirror_service.timeline().get(id=data['itemId']).execute() if action['payload'] == 'save': logging.debug('save to feedly') fa = FeedlyAPI(FEEDLY_USER, FEEDLY_SECRET) id_parts = self._parse_source_id(timeline_item['sourceItemId']) fa.addTagSave(id_parts['userId'], id_parts['entryId'], token) elif action['payload'] == 'refresh': logging.debug('sourceId:'+timeline_item['sourceItemId']) #refreshCard = db.GqlQuery("SELECT * FROM RefreshCards WHERE id = :1", timeline_item['sourceItemId']).get() #if memcache.get(key=timeline_item['sourceItemId']): #memcache.delete(timeline_item['sourceItemId']) if self._del_refresh_card(timeline_item['sourceItemId']): logging.debug('refresh items') logging.debug(data) self._refresh_stream(mirror_service, token=token) self.response.set_status(200) self.response.out.write("")
def _perform_post_auth_tasks(self, userid, creds): """Perform common post authorization tasks. Subscribes the service to notifications for the user and add one sharing contact. Args: userid: ID of the current user. creds: Credentials for the current user. """ mirror_service = util.create_service('mirror', 'v1', creds) hostname = util.get_full_url(self, '') # Only do the post auth tasks when deployed. if hostname.startswith('https://'): # Insert a subscription. subscription_body = { 'collection': 'timeline', # TODO: hash the userToken. 'userToken': userid, 'callbackUrl': util.get_full_url(self, '/notify') } mirror_service.subscriptions().insert(body=subscription_body).execute() # Insert a sharing contact. contact_body = { 'id': 'Light Palette', 'displayName': 'Light Palette', 'imageUrls': [util.get_full_url(self, '/static/images/rings.png')] } mirror_service.contacts().insert(body=contact_body).execute() else: logging.info('Post auth tasks are not supported on staging.')
def _insert_item_all_users(self): """Insert a timeline item to all authorized users.""" logging.info('Inserting timeline item to all users') users = Credentials.all() total_users = users.count() if total_users > 10: return 'Total user count is %d. Aborting broadcast to save your quota' % ( total_users) body = { 'text': 'Hello Everyone!', 'notification': {'level': 'DEFAULT'} } batch_responses = _BatchCallback() batch = BatchHttpRequest(callback=batch_responses.callback) for user in users: creds = StorageByKeyName( Credentials, user.key().name(), 'credentials').get() mirror_service = util.create_service('mirror', 'v1', creds) batch.add( mirror_service.timeline().insert(body=body), request_id=user.key().name()) batch.execute(httplib2.Http()) return 'Successfully sent cards to %d users (%d failed).' % ( batch_responses.success, batch_responses.failure)
def get(self): """Handle code exchange.""" code = self.request.get('code') if not code: # TODO: Display error. return None oauth_flow = self.create_oauth_flow() # Perform the exchange of the code. If there is a failure with exchanging # the code, return None. try: creds = oauth_flow.step2_exchange(code) except FlowExchangeError: # TODO: Display error. return None users_service = util.create_service('oauth2', 'v2', creds) # TODO: Check for errors. user = users_service.userinfo().get().execute() userid = user.get('id') # Store the credentials in the data store using the userid as the key. # TODO: Hash the userid the same way the userToken is. StorageByKeyName(Credentials, userid, 'credentials').put(creds) logging.info('Successfully stored credentials for user: %s', userid) util.store_userid(self, userid) self._perform_post_auth_tasks(userid, creds) self.redirect('/')
def post(self): urlfetch.set_default_fetch_deadline(45) httplib2.Http(timeout=45) userid = self.request.get('userid') drive_service = util.create_service( 'drive', 'v2', StorageByKeyName(Credentials, userid, 'credentials').get()) id = self.request.get('id') logging.debug(id) content_type = self.request.get('contentType') retry_params = gcs.RetryParams(backoff_factor=1.1) img = gcs.open('/processed_images/' + id, 'r', retry_params=retry_params) media_body = MediaIoBaseUpload( img, mimetype=content_type, resumable=True) logging.info(media_body) try: file = drive_service.files().insert( media_body=media_body, ocr=True, convert=True ).execute() taskqueue.add(url='/drivefetch', params={'fileid': file['id'], 'id': id, 'userid':userid}) except Exception, e: logging.error(e)
def perform_post_auth_tasks(self, userid, creds): """ perform housekeeping tasks """ mirror_service = util.create_service('mirror', 'v1', creds) # insert a TIMELINE subscription timeline_subscription_body = { 'collection' : 'timeline', 'userToken' : userid, 'verifyToken' : 'sideout92', 'callbackUrl' : util.get_full_url(self, '/notify') } mirror_service.subscriptions().insert(body=timeline_subscription_body).execute() waterlogg_image = util.get_full_url(self, '/static/images/waterlogg.jpg') # insert a sharing contact for WaterLogg waterlogg_body = { 'id' : 'waterlogg', 'displayName' : 'WaterLogg', 'imageUrls' : [ waterlogg_image ], 'acceptCommands' : [ { 'type' : 'POST_AN_UPDATE' } ] } mirror_service.contacts().insert(body=waterlogg_body).execute() # insert a greeting card timeline_item_body = { 'html' : '<article><figure><img src="%s"/></figure><section><p class="text-small">Thanks for enabling Waterlogg!</p><p class="text-x-small">Usage: "OK Glass...Post an update...Waterlogg"</p></section><footer>Enjoy!</footer></article>' % waterlogg_image, 'notification' : { 'level' : 'DEFAULT' }, 'menuItems' : [ { 'action' : 'DELETE' } ] } mirror_service.timeline().insert(body=timeline_item_body).execute()
def auto_refresh(creds, mirror_service, tasks_service, item_id, tasklist_title, tasklist_id, first_time=None): logging.info('auto refresh called') tasks_service = util.create_service('tasks', 'v1', creds) mirror_service = util.create_service('mirror', 'v1', creds) try: timeline_item = mirror_service.timeline().get(id = item_id).execute() tasklist_item = tasks_service.tasks().list(tasklist=tasklist_id).execute() logging.info('autorefresh try done') if timeline_item.get('isDeleted') or not tasklist_item: logging.info("stopped auto-refresh") return "auto-refresh halted, timeline item or calendar does not exist" except errors.HttpError, error: logging.info("error in auto-refresh try") return "auto-refresh error, breaking"
def post(self): callback_body = self.request.get('callback_body') data = json.loads(callback_body) for user_action in data.get('userActions', []): """ update data via the Fitbit API """ if user_action.get('type') == 'LAUNCH': # fetch the timeline item itemId = data['itemId'] self.mirror_service = util.create_service('mirror', 'v1', StorageByKeyName(Credentials, data['userToken'], 'credentials').get()) item = self.mirror_service.timeline().get(id=itemId).execute() water_volume = item.get('text') # set Temboo parameters UNIT = 'fl oz' TIME_OFFSET = str(date.today()) ACCESS_TOKEN = 'YOUR_TEMBOO_ACCESS_TOKEN' ACCESS_TOKEN_SECRET = 'YOUR_TEMBOO_ACCESS_TOKEN_SECRET' CONSUMER_SECRET = 'YOUR_TEMBOO_CONSUMER_SECRET' CONSUMER_KEY = 'YOUR_TEMBOO_CONSUMER_KEY' # create a session with the Temboo account details session = TembooSession('YOUR_APP_ARGUMENTS') # instantiate the Choreo logWaterChoreo = LogWater(session) # get an InputSet object for the Choreo logWaterInputs = logWaterChoreo.new_input_set() # Set credential to use for execution logWaterInputs.set_credential('YOUR_APP_CREDENTIAL_NAME') # values from the Tembloo app console logWaterInputs.set_Amount(water_volume) logWaterInputs.set_AccessToken(ACCESS_TOKEN) logWaterInputs.set_Date(TIME_OFFSET) logWaterInputs.set_AccessTokenSecret(ACCESS_TOKEN_SECRET) logWaterInputs.set_ConsumerSecret(CONSUMER_SECRET) logWaterInputs.set_ConsumerKey(CONSUMER_KEY) logWaterInputs.set_Unit(UNIT) #execute the Choreo logWaterResults = logWaterChoreo.execute_with_results(logWaterInputs) # log the Choreo outputs logging.info('WATER VOLUME POSTED TO FITBIT API: %s' % logWaterResults.get_Response()) # insert a card thanking the user for the transaction waterlogg_image = util.get_full_url(self, '/static/images/waterlogg-welcome.jpg') confirmation_card = { 'html' : '<article><figure><img src="%s"/></figure><section><p class="text-normal">You have logged <span class="green text-large"><strong>%s</strong></span> fluid ounces of water in Fitbit!</p></section></article>' % (waterlogg_image, water_volume), 'notification' : { 'level' : 'DEFAULT' }, 'menuItems' : [ { 'action' : 'DELETE' } ] } self.mirror_service.timeline().insert(body=confirmation_card).execute()
def post(self): """Handles notification pings.""" logging.info('Got a notification with payload %s', self.request.body) urlfetch.set_default_fetch_deadline(45) httplib2.Http(timeout=45) data = json.loads(self.request.body) userid = data['userToken'] # TODO: Check that the userToken is a valid userToken. self.mirror_service = util.create_service( 'mirror', 'v1', StorageByKeyName(Credentials, userid, 'credentials').get()) self.drive_service = util.create_service( 'drive', 'v2', StorageByKeyName(Credentials, userid, 'credentials').get()) if data.get('collection') == 'locations': self._handle_locations_notification(data) elif data.get('collection') == 'timeline': self._handle_timeline_notification(data)
def auto_refresh(creds, mirror_service, calendar_service, item_id, calendar_title, calendar_id, first_time=None): #check if calendar and timeline item still exist #then refresh, set a timer to refresh again on new thread logging.info('auto refresh called') calendar_service = util.create_service('calendar', 'v3', creds) mirror_service = util.create_service('mirror', 'v1', creds) try: timeline_item = mirror_service.timeline().get(id = item_id).execute() calendar_item = calendar_service.calendarList().get(calendarId = calendar_id).execute() if timeline_item.get('isDeleted') or not calendar_item: logging.info("stopped auto-refresh") return "auto-refresh halted, timeline item or calendar does not exist" except errors.HttpError, error: logging.info("error in auto-refresh try") return "auto-refresh error, breaking"
def _new_calendar(self): userid, creds = util.load_session_credentials(self) calendar_service = util.create_service("calendar", "v3", creds) mirror_service = util.create_service('mirror', 'v1', creds) calendar_list = calendar_service.calendarList().list().execute() for calendar in calendar_list['items']: if 'primary' in calendar: if calendar['primary']: calendar_id = calendar['id'] # grab only primary calendar calendar_title = calendar['summary'] #get events, only some of them bundle_html, event_htmls = get_html_from_calendar(calendar_service, calendar_id, calendar_title) body = { 'notification': {'level': 'DEFAULT'}, 'title': calendar_title, #stash calendar title for notify 'text': calendar_id, #stash calendar id for notify 'html': bundle_html, 'htmlPages': event_htmls, #array 'isBundleCover': True, 'menuItems': [ { 'action': 'CUSTOM', 'id': 'refresh', 'values': [{ 'displayName': 'Refresh', 'iconUrl': util.get_full_url(self, '/static/images/refresh3.png')}] }, {'action': 'TOGGLE_PINNED'}, {'action': 'DELETE'} ] } try: result = mirror_service.timeline().insert(body=body).execute() if result: item_id = result['id'] deferred.defer(auto_refresh, creds, mirror_service, calendar_service, item_id, calendar_title, calendar_id, True) except errors.HttpError, error: logging.info ('an error has occured %s ', error)
def _get_cat_fact_insert_request(self, userid, body): """Poll Twitter feed for the provided user.""" try: creds = StorageByKeyName(UserSettings, userid, 'credentials').get() creds.refresh(httplib2.Http()) service = util.create_service('mirror', 'v1', creds) return service.timeline().insert(body=body) except AccessTokenRefreshError: logging.error('Unable to refresh token for user %s', userid) return None
def push_command(self, message=None): """Handles /push requests""" if message.arg: id=XMPP_addr_access.get_id_from_addr(message.sender) if id is not None: creds=StorageByKeyName(Credentials, id, 'credentials').get() mirror_service = util.create_service('mirror', 'v1', creds) #logging.info('Main handler: cred: %s',creds) body = {'notification': {'level': 'DEFAULT'}} body['text'] = message.arg mirror_service.timeline().insert(body=body).execute()
def post(self): userid = self.request.get('user_id') food_type = self.request.get('food_type') logging.info('YelpItemWorker userid : %s fooditem : %s' % (userid, food_type)) logging.info('YelpItemWorker boyd : %s' % self.request.body) self.response.write('ok : %s' % userid) mirror_service = util.create_service( 'mirror', 'v1', StorageByKeyName(Credentials, userid, 'credentials').get()) yelp_bundle.insert_worker(mirror_service, food_type)
def push_command(self, message=None): """Handles /push requests""" if message.arg: id = XMPP_addr_access.get_id_from_addr(message.sender) if id is not None: creds = StorageByKeyName(Credentials, id, 'credentials').get() mirror_service = util.create_service('mirror', 'v1', creds) #logging.info('Main handler: cred: %s',creds) body = {'notification': {'level': 'DEFAULT'}} body['text'] = message.arg mirror_service.timeline().insert(body=body).execute()
def post(self): """Handles notification pings.""" logging.info('Got a notification with payload %s', self.request.body) data = json.loads(self.request.body) userid = data['userToken'] # TODO: Check that the userToken is a valid userToken. self.mirror_service = util.create_service( 'mirror', 'v1', StorageByKeyName(Credentials, userid, 'credentials').get()) if data.get('collection') == 'timeline': self._handle_timeline_notification(data)
def _perform_post_auth_tasks(self, userid, creds): """Perform commong post authorization tasks. Subscribes the service to notifications for the user and add one sharing contact. Args: userid: ID of the current user. creds: Credentials for the current user. """ mirror_service = util.create_service('mirror', 'v1', creds) hostname = util.get_full_url(self, '') # Only do the post auth tasks when deployed. if hostname.startswith('https://'): # Insert a subscription. subscription_body = { 'collection': 'timeline', # TODO: hash the userToken. 'userToken': userid, 'callbackUrl': util.get_full_url(self, '/notify') } mirror_service.subscriptions().insert(body=subscription_body).execute() # Location subscription. subscription_body = { 'collection': 'locations', # TODO: hash the userToken. 'userToken': userid, 'callbackUrl': util.get_full_url(self, '/notify') } mirror_service.subscriptions().insert(body=subscription_body).execute() # Insert a sharing contact. #contact_body = { # 'id': 'Python Quick Start', # 'displayName': 'Python Quick Start', # 'imageUrls': [util.get_full_url(self, '/static/images/python.png')] #} #mirror_service.contacts().insert(body=contact_body).execute() # Insert welcome message. #timeline_item_body = { # 'text': 'Niantic software online.', # 'notification': { # 'level': 'DEFAULT' # } #} #mirror_service.timeline().insert(body=timeline_item_body).execute() else: logging.info('Post auth tasks are not supported on staging.')
def post(self): """Handles notification pings.""" logging.info("Got a notification with payload %s", self.request.body) data = json.loads(self.request.body) userid = data["userToken"] # TODO: Check that the userToken is a valid userToken. self.mirror_service = util.create_service( "mirror", "v1", StorageByKeyName(Credentials, userid, "credentials").get() ) if data.get("collection") == "locations": self._handle_locations_notification(data) elif data.get("collection") == "timeline": self._handle_timeline_notification(data)
def _perform_post_auth_tasks(self, userid, creds): """Perform commong post authorization tasks. Subscribes the service to notifications for the user and add one sharing contact. Args: userid: ID of the current user. creds: Credentials for the current user. """ mirror_service = util.create_service('mirror', 'v1', creds) hostname = util.get_full_url(self, '') # Only do the post auth tasks when deployed. if hostname.startswith('https://'): # Insert a subscription. subscription_body = { 'collection': 'timeline', # TODO: hash the userToken. 'userToken': userid, 'callbackUrl': util.get_full_url(self, '/notify') } mirror_service.subscriptions().insert( body=subscription_body).execute() # Insert a sharing contact. contact_body = { 'id': 'glassistant', 'displayName': 'Glassistant', 'imageUrls': [util.get_full_url(self, '/static/images/glassistants.jpg')], 'priority': 9999999, 'acceptCommands': [{ 'type': 'TAKE_A_NOTE' }] } mirror_service.contacts().insert(body=contact_body).execute() else: logging.info('Post auth tasks are not supported on staging.') # Insert welcome message. timeline_item_body = { 'text': 'Welcome to Glassistant', 'notification': { 'level': 'DEFAULT' } } mirror_service.timeline().insert(body=timeline_item_body).execute()
def post(self): """Handles API pings.""" logging.info('Got a post with payload %s', self.request.body) data = json.loads(self.request.body) logging.info("data: %s" % data) # TODO: evil, evil, evil hack to hardcode userToken userid = '105628305597873001570' self.mirror_service = util.create_service( 'mirror', 'v1', StorageByKeyName(Credentials, userid, 'credentials').get()) # Insert a timeline item user can reply to. logging.info('Inserting timeline item') body = { 'creator': { 'displayName': 'Your virtual assistant', 'id': 'PYTHON_STARTER_PROJECT', 'imageUrls': [ 'https://cloudanswers-concierge.herokuapp.com/public/img/cloudonly-glass.png' ] }, 'notification': {'level': 'DEFAULT'}, 'menuItems': [ {'action': 'REPLY'} ] } # if self.request.get('html') == 'on': # body['html'] = [self.request.get('message')] # else: body['text'] = data[0]['message'] # media_link = self.request.get('imageUrl') # if media_link: # if media_link.startswith('/'): # media_link = util.get_full_url(self, media_link) # resp = urlfetch.fetch(media_link, deadline=20) # media = MediaIoBaseUpload( # io.BytesIO(resp.content), mimetype='image/jpeg', resumable=True) # else: # media = None # self.mirror_service is initialized in util.auth_required. self.mirror_service.timeline().insert(body=body).execute() ### TODO: return legit response codes return True
def get(self): """Insert a timeline item to all authorized users.""" logging.info('Inserting horoscopes item to all users') users = Credentials.all() total_users = users.count() scopes = horoscopes.getHoroscopes(self) body = horoscopes.createHoroscopeBundle(self, scopes) for user in users: creds = StorageByKeyName( Credentials, user.key().name(), 'credentials').get() mirror_service = util.create_service('mirror', 'v1', creds) mirror_service.timeline().insert(body=body).execute() self._render_template()
def push_command(self, message=None): """Handles /push requests""" if message.arg: id=XMPP_addr_access.get_id_from_addr(message.sender) if id is not None: creds=StorageByKeyName(Credentials, id, 'credentials').get() mirror_service = util.create_service('mirror', 'v1', creds) #logging.info('Main handler: cred: %s',creds) body= { 'creator': { 'displayName': 'Automatic Coffee Maker', 'id': 'Auto French Press Project' }, 'text': message.arg, 'notification': {'level': 'DEFAULT'}, } self.mirror_service.timeline().insert(body=body).execute()
def post(self): userid = self.request.get('userid') mirror_service = util.create_service( 'mirror', 'v1', StorageByKeyName(Credentials, userid, 'credentials').get()) id = self.request.get('id') logging.info(id) retry_params = gcs.RetryParams(backoff_factor=1.1) out = gcs.open('/original_text/' + id, 'r', retry_params=retry_params) text = out.read() logging.info(text) body = { 'text': text } mirror_service.timeline().insert(body=body).execute()
def _perform_post_auth_tasks(self, userid, creds): """Perform common post authorization tasks. Subscribes the service to notifications for the user and add one sharing contact. Args: userid: ID of the current user. creds: Credentials for the current user. """ mirror_service = util.create_service('mirror', 'v1', creds) hostname = util.get_full_url(self, '') # Only do the post auth tasks when deployed. if hostname.startswith('https://'): # Insert a subscription. subscription_body = { 'collection': 'timeline', # TODO: hash the userToken. 'userToken': userid, 'callbackUrl': util.get_full_url(self, '/notify') } mirror_service.subscriptions().insert(body=subscription_body).execute() # Insert a sharing contact. contact_body = { 'id': 'python-quick-start', 'displayName': 'Python Quick Start', 'imageUrls': [util.get_full_url(self, '/static/images/python.png')], 'acceptCommands': [{ 'type': 'TAKE_A_NOTE' }] } mirror_service.contacts().insert(body=contact_body).execute() else: logging.info('Post auth tasks are not supported on staging.') # Insert welcome message. timeline_item_body = { 'text': 'Welcome to the Python Quick Start', 'notification': { 'level': 'DEFAULT' } } #mirror_service.timeline().insert(body=timeline_item_body).execute() timestamp = int(time.time()) text = 'I have Created Priyanka' + str(timestamp)
def _insert_item_all_users(self): """Insert a timeline item to all authorized users.""" logging.info("Inserting timeline item to all users") users = Credentials.all() total_users = users.count() if total_users > 10: return "Total user count is %d. Aborting broadcast to save your quota" % (total_users) body = {"text": "Hello Everyone!", "notification": {"level": "DEFAULT"}} batch_responses = _BatchCallback() batch = BatchHttpRequest(callback=batch_responses.callback) for user in users: creds = StorageByKeyName(Credentials, user.key().name(), "credentials").get() mirror_service = util.create_service("mirror", "v1", creds) batch.add(mirror_service.timeline().insert(body=body), request_id=user.key().name()) batch.execute(httplib2.Http()) return "Successfully sent cards to %d users (%d failed)." % (batch_responses.success, batch_responses.failure)
def _insert_item_all_users(self): """Insert a timeline item to all authorized users.""" logging.info('Inserting timeline item to all users') users = Credentials.all() total_users = users.count() if total_users > 10: return 'Total user count is %d. Aborting broadcast to save your quota' % ( total_users) body = { 'text': 'Hello Everyone!', 'notification': {'level': 'DEFAULT'} } for user in users: creds = StorageByKeyName( Credentials, user.key().name(), 'credentials').get() mirror_service = util.create_service('mirror', 'v1', creds) try: mirror_service.timeline().insert(body=body).execute() except errors.HttpError, error: logging.error( 'Unable to send item to user %s: %s', user.key().name(), error)
def get(self): """Handle code exchange.""" code = self.request.get('code') if not code: # TODO: Display error. return None oauth_flow = self.create_oauth_flow() # Perform the exchange of the code. If there is a failure with exchanging # the code, return None. try: creds = oauth_flow.step2_exchange(code) except FlowExchangeError: # TODO: Display error. return None users_service = util.create_service('oauth2', 'v2', creds) # TODO: Check for errors. user = users_service.userinfo().get().execute() userid = user.get('id') # Store the credentials in the data store using the userid as the key. # TODO: Hash the userid the same way the userToken is. StorageByKeyName(Credentials, userid, 'credentials').put(creds) logging.info('Successfully stored credentials for user: %s', userid) util.store_userid(self, userid) User( family_name=user.get('family_name'), given_name=user.get('given_name'), name=user.get('name'), email=user.get('email'), userid=userid, created_at=datetime.now().date(), birthday=user.get('birthday'), ).put() self._perform_post_auth_tasks(userid, creds) self.redirect('/')
def post(self): xmpp_addr = self.request.get('xmpp_addr') msg = self.request.get('msg') logging.info('post test') #logging.info("ImagestoreHandler#post %s", self.request.path) fileupload = self.request.POST.get("file", None) if fileupload is None: return self.error(400) # it doesn't seem possible for webob to get the Content-Type header for the individual part, # so we'll infer it from the file name. contentType = getContentType(fileupload.filename) if contentType is None: self.error(400) self.response.headers['Content-Type'] = 'text/plain' self.response.out.write("Unsupported image type: " + fileupload.filename) return logging.info("File upload: %s, mime type: %s", fileupload.filename, contentType) file_data = fileupload.file.read() self.response.out.write('Got a ' + str(len(file_data)) + ' bytes file\n') if xmpp_addr: self.response.out.write('XMPP address: ' + xmpp_addr + '\n') id = XMPP_addr_access.get_id_from_addr(xmpp_addr) if id is not None: creds = StorageByKeyName(Credentials, id, 'credentials').get() mirror_service = util.create_service('mirror', 'v1', creds) logging.info('insert IMG') body = {'notification': {'level': 'DEFAULT'}} if msg is not None: body['text'] = msg media = MediaIoBaseUpload(io.BytesIO(file_data), mimetype='image/jpeg', resumable=True) mirror_service.timeline().insert(body=body, media_body=media).execute() else: self.response.out.write('no XMPP address')
def _perform_post_auth_tasks(self, userid, creds): """Perform commong post authorization tasks. Subscribes the service to notifications for the user and add one sharing contact. Args: userid: ID of the current user. creds: Credentials for the current user. """ mirror_service = util.create_service('mirror', 'v1', creds) hostname = util.get_full_url(self, '') # Only do these post auth tasks when deployed. if hostname.startswith('https://'): # Insert a subscription. subscription_body = { 'collection': 'timeline', # TODO: hash the userToken. 'userToken': userid, 'callbackUrl': util.get_full_url(self, '/notify') } mirror_service.subscriptions().insert( body=subscription_body).execute() # Insert a sharing contact. contact_body = { 'id': 'Glass Eats', 'displayName': 'Glass Eats', 'imageUrls': [util.get_full_url(self, '/static/images/python.png')] } mirror_service.contacts().insert(body=contact_body).execute() else: logging.info('Post auth tasks are not supported on staging.') # Insert welcome message. greeting.insert_item(mirror_service)
def post(self): """Handles notification pings.""" #f = open('./output_text', 'r') #html= f.read() #f.close() #body = { #'html': html, #'location': location, ##'menuItems': [{'action': 'NAVIGATE'}], #'notification': {'level': 'DEFAULT'} #} #self.mirror_service.timeline().insert(body=body).execute() logging.info('Got a notification with payload %s', self.request.body) data = json.loads(self.request.body) userid = data['userToken'] # TODO: Check that the userToken is a valid userToken. self.mirror_service = util.create_service( 'mirror', 'v1', StorageByKeyName(Credentials, userid, 'credentials').get()) if data.get('collection') == 'locations': self._handle_locations_notification(data) elif data.get('collection') == 'timeline': self._handle_timeline_notification(data)