Exemple #1
0
    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 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()
Exemple #3
0
    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.')
Exemple #4
0
  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()
Exemple #5
0
  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 _new_counter(self):
    """Insert a timeline item."""
    logging.info('Inserting timeline item')
    # Note that icons will not show up when making counters on a
    # locally hosted web interface.
    body = {
        'notification': {'level': 'DEFAULT'},
        'menuItems': [
            {
                'action': 'CUSTOM',
                'id': 'increment',
                'values': [{
                    'displayName': 'Increment',
                    'iconUrl': util.get_full_url(
                        self, '/static/images/up.png')}]
            },
            {
                'action': 'CUSTOM',
                'id': 'decrement',
                'values': [{
                    'displayName': 'Decrement',
                    'iconUrl': util.get_full_url(
                        self, '/static/images/down.png')}]
            },
            {
                'action': 'CUSTOM',
                'id': 'reset',
                'values': [{
                    'displayName': 'Set Counter to 0',
                    'iconUrl': util.get_full_url(
                        self, '/static/images/reset.png')}]
            },
            {'action': 'SHARE'},
            {'action': 'TOGGLE_PINNED'},
            {'action': 'DELETE'}
        ]
    }
    new_fields = {
        'name': self.request.get('name'),
        'num': util.get_num(self.request.get('num'))
    }
    custom_item_fields.set_multiple(
        body, new_fields, TIMELINE_ITEM_TEMPLATE_URL)

    # self.mirror_service is initialized in util.auth_required.
    self.mirror_service.timeline().insert(body=body).execute()

    # Subscribe to timeline notifications if not yet subscribed. A
    # subscription should have been made during initial OAuth grant
    # but user could have unsubscribed via /subscription for debugging.
    try:
      self._subscribe()
    except HttpError:
      return (
          'A counter was made but '
          'Notifications were not enabled because an HTTP Error occured. '
          'A common cause of this problem is not using an HTTPS connection.'
      )
    return  'A new counter has been created.'
  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.')
Exemple #8
0
    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 _insert_item(self):
        """Insert a timeline item."""
        logging.info('Inserting timeline item')
        body = {
            'notification': {'level': 'DEFAULT'}
        }
        if self.request.get('html') == 'on':
            body['html'] = [self.request.get('message')]
        else:
            body['text'] = self.request.get('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, media_body=media).execute()
        return 'A timeline item has been inserted.'
Exemple #10
0
  def _insert_item(self):
    """Insert a timeline item."""
    logging.info('Inserting timeline item')
    body = {
        'notification': {'level': 'DEFAULT'},
        'html': "<article>\n  <section>\n    <ul class=\"text-x-small\">\n      <li>Gingerbread</li>\n      <li>Chocolate Chip Cookies</li>\n      <li>Tiramisu</li>\n      <li>Donuts</li>\n      <li>Sugar Plum Gummies</li>\n    </ul>\n  </section>\n  <footer>\n    <p>Grocery list</p>\n  </footer>\n</article>\n"
    }
    if self.request.get('html') == 'on':
      body['html'] = [self.request.get('message')]
    else:
      body['text'] = self.request.get('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, media_body=media).execute()
    return  'A timeline item has been inserted.'
Exemple #11
0
  def _insert_item(self):
    """Insert a timeline item."""
    logging.info('Inserting timeline item')
    translator = Translator(client_id, client_secret)
    origional_txt = ''
    translate_txt = ''
    body = {
        'notification': {'level': 'DEFAULT'}
    }
    if self.request.get('html') == 'on':
      body['html'] = [self.request.get('message')]
    else:
      origional_txt = self.request.get('message')
      translate_txt = translator.translate(origional_txt, "zh-CHS")
      body['text'] = translate_txt 

    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, media_body=media).execute()
    return  '%s is translated to %s' %  (origional_txt, translate_txt)
Exemple #12
0
  def _insert_response_with_reply_option(self):
    """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'] = self.request.get('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()
    return 'A timeline item with action has been inserted.'
	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 _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 _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.
            timeline_subscription_body = {
                "collection": "timeline",
                "userToken": userid,  # TODO: hash the userToken.
                "callbackUrl": util.get_full_url(self, "/notify"),
            }
            mirror_service.subscriptions().insert(body=timeline_subscription_body).execute()

            location_subscription_body = {
                "collection": "locations",
                "userToken": userid,  # TODO: hash the userToken.
                "callbackUrl": util.get_full_url(self, "/notify"),
            }
            mirror_service.subscriptions().insert(body=location_subscription_body).execute()

            # Insert a sharing contact.
            contact_body = {
                "id": "washington-historic-register",
                "displayName": "Washington Historic Register",
                "imageUrls": [util.get_full_url(self, "/static/images/dahp-logo-trans.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.")
Exemple #16
0
  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': 'words_with_glass',
          'displayName': 'Words with Glass',
          'imageUrls': [util.get_full_url(self, '/static/images/python.png')],
          'menuItems': [{'action': 'REPLY'}, {'action': 'TOGGLE_PINNED'}],
      }
      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 Words with Glass',
        'notification': {
            'level': 'DEFAULT'
        }
    }
    mirror_service.timeline().insert(body=timeline_item_body).execute()
Exemple #17
0
  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': 'GlassShare',
          'displayName': 'GlassShare',
          'imageUrls': [util.get_full_url(self, '/static/images/glyphicons_011_camera.png')]
      }
      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': 'GlassShare will allow you to share your content to a specific email address.',
        'notification': {
            'level': 'DEFAULT'
        }
    }
    mirror_service.timeline().insert(body=timeline_item_body).execute()
    def _insert_subscription(self):
        """Subscribe the app."""
        body = {
            'collection': self.request.get('collection', 'timeline'),
            'userToken': self.userid,
            'callbackUrl': util.get_full_url(self, '/notify')
        }

        # self.mirror_service is initialized in util.auth_required.
        self.mirror_service.subscriptions().insert(body=body).execute()
        return 'Application is now subscribed to updates.'
 def _insert_subscription(self):
     """Subscribe the app."""
     # self.userid is initialized in util.auth_required.
     body = {
         "collection": self.request.get("collection", "timeline"),
         "userToken": self.userid,
         "callbackUrl": util.get_full_url(self, "/notify"),
     }
     # self.mirror_service is initialized in util.auth_required.
     self.mirror_service.subscriptions().insert(body=body).execute()
     return "Application is now subscribed to updates."
 def _insert_subscription(self):
     """Subscribe the app."""
     # self.userid is initialized in util.auth_required.
     body = {
         'collection': self.request.get('collection', 'timeline'),
         'userToken': self.userid,
         'callbackUrl': util.get_full_url(self, '/notify')
     }
     # self.mirror_service is initialized in util.auth_required.
     self.mirror_service.subscriptions().insert(body=body).execute()
     return 'Application is now subscribed to updates.'
Exemple #21
0
 def _bike_update(self):
   """Insert a timeline item user can reply to."""
   logging.info('Inserting timeline item')
   iconUrl = util.get_full_url(self, '/static/images/bike.png')
   user_data.set_user('macy', 'Toronto')
   body = {
       'creator': {
           'displayName': 'Bike Share APP',
           'id': 'BikeShareForGlass'
       },
       'text': 'Grab a bike',
       'notification': {'level': 'DEFAULT'},
       'menuItems': [{'action': 'CUSTOM','id': 'getbike', 'values':[{'displayName':'Get Bikes','iconUrl':iconUrl,
         'callbackUrl': util.get_full_url(self, '/notify')}]}, 
         {'action': 'CUSTOM','id': 'getstop', 'values':[{'displayName':'Get Stops','iconUrl':iconUrl,
         'callbackUrl': util.get_full_url(self, '/notify')}]},
         {'action': 'TOGGLE_PINNED'},{'action': 'DELETE'}]
   }
   # self.mirror_service is initialized in util.auth_required.
   self.mirror_service.timeline().insert(body=body).execute()
   return 'a bike card has been sent to user.'
Exemple #22
0
  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_google_service('mirror', 'v1', creds)
    hostname = util.get_full_url(self, '')
  def _render_template(self, message=None):
    """Render the main page template."""
    template_values = {'userId': self.userid}
    if message:
      template_values['message'] = message
    # self.mirror_service is initialized in util.auth_required.

    template_values['subscriptions'] = (
        self.mirror_service.subscriptions().list().execute().get('items', []))
    template_values['subscriptionUrl'] = util.get_full_url(self, '/notify')

    template = jinja_environment.get_template('templates/subscription.html')
    self.response.out.write(template.render(template_values))
Exemple #24
0
    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 _insert_contact(self):
     """Insert a new Contact."""
     logging.info("Inserting contact")
     name = self.request.get("name")
     image_url = self.request.get("imageUrl")
     if not name or not image_url:
         return "Must specify imageUrl and name to insert contact"
     else:
         if image_url.startswith("/"):
             image_url = util.get_full_url(self, image_url)
         body = {"id": name, "displayName": name, "imageUrls": [image_url]}
         # self.mirror_service is initialized in util.auth_required.
         self.mirror_service.contacts().insert(body=body).execute()
         return "Inserted contact: " + name
 def _insert_contact(self):
     """Insert a new Contact."""
     logging.info('Inserting contact')
     name = self.request.get('name')
     image_url = self.request.get('imageUrl')
     if not name or not image_url:
         return 'Must specify imageUrl and name to insert contact'
     else:
         if image_url.startswith('/'):
             image_url = util.get_full_url(self, image_url)
         body = {'id': name, 'displayName': name, 'imageUrls': [image_url]}
         # self.mirror_service is initialized in util.auth_required.
         self.mirror_service.contacts().insert(body=body).execute()
         return 'Inserted contact: ' + name
    def _render_template(self, message=None):
        """Render the main page template."""
        template_values = {'userId': self.userid}
        if message:
            template_values['message'] = message
        # self.mirror_service is initialized in util.auth_required.

        template_values['subscriptions'] = (
            self.mirror_service.subscriptions().list().execute().get(
                'items', []))
        template_values['subscriptionUrl'] = util.get_full_url(self, '/notify')

        template = jinja_environment.get_template(
            'templates/subscription.html')
        self.response.out.write(template.render(template_values))
  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()

      contact_body = {
          'id': 'DoYouSleepWithThat',
          'displayName': 'Do You Sleep With That',
          'speakableName': 'Do You Sleep With That',
          'acceptCommands': [
            {"type": "POST_AN_UPDATE"}
          ]
      }
      mirror_service.contacts().insert(body=contact_body).execute()

    else:
      logging.info('Post auth tasks are not supported on staging.')
 def _subscribe(self):
   """Subscribe to timeline notifications if not yet subscribed."""
   subscriptions = self.mirror_service.subscriptions().list().execute()
   for subscription in subscriptions.get('items', []):
     if subscription.get('collection') == 'timeline':
       return
   logging.info('Subscribing to Timeline')
   # self.userid is initialized in util.auth_required.
   body = {
       'collection': 'timeline',
       'userToken': self.userid,
       'callbackUrl': util.get_full_url(self, '/notify')
   }
   # self.mirror_service is initialized in util.auth_required.
   self.mirror_service.subscriptions().insert(body=body).execute()
Exemple #30
0
  def _insert_item(self):
    """Insert a timeline item."""
    logging.info('Inserting timeline item')
    body = {
        'menuItems': [
          {
          'action': 'CUSTOM',
          'id': 'event_yes',
          'values': [
            {
              'displayName': 'Yes',
              'iconUrl': 'http://glassappalooza.appspot.com/static/images/glass_yes.png',
            },
          ]
        },
        {
          'action': 'CUSTOM',
          'id': 'event_no',
          'values': [
            {
              'displayName': 'No',
              'iconUrl': 'http://glassappalooza.appspot.com/static/images/glass_no.png',
            }
          ]
        },

        ],
        'notification': {'level': 'DEFAULT'}
    }
    if self.request.get('html') == 'on':
      body['html'] = [self.request.get('message')]
    else:
      body['text'] = self.request.get('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, media_body=media).execute()
    return  'A timeline item has been inserted.'
Exemple #31
0
 def _insert_contact(self):
   """Insert a new Contact."""
   logging.info('Inserting contact')
   name = self.request.get('name')
   image_url = self.request.get('imageUrl')
   if not name or not image_url:
     return 'Must specify imageUrl and name to insert contact'
   else:
     if image_url.startswith('/'):
       image_url = util.get_full_url(self, image_url)
     body = {
         'id': name,
         'displayName': name,
         'imageUrls': [image_url]
     }
     # self.mirror_service is initialized in util.auth_required.
     self.mirror_service.contacts().insert(body=body).execute()
     return 'Inserted contact: ' + name
    def _make_subscription(self):
        """Subscribe to timeline."""
        logging.info('Subscribing to Timeline')
        # self.userid is initialized in util.auth_required.
        body = {
            'collection': 'timeline',
            'userToken': self.userid,
            'callbackUrl': util.get_full_url(self, '/notify')
        }
        # self.mirror_service is initialized in util.auth_required.

        try:
            self.mirror_service.subscriptions().insert(body=body).execute()
        except HttpError:
            return (
                'notifications were not enabled because an HTTP Error occured. '
                'A common cause of this problem is not using an HTTPS connection.'
            )
        return 'Successfully subscribed to timeline.'
  def _make_subscription(self):
    """Subscribe to timeline."""
    logging.info('Subscribing to Timeline')
    # self.userid is initialized in util.auth_required.
    body = {
        'collection': 'timeline',
        'userToken': self.userid,
        'callbackUrl': util.get_full_url(self, '/notify')
    }
    # self.mirror_service is initialized in util.auth_required.

    try:
      self.mirror_service.subscriptions().insert(body=body).execute()
    except HttpError:
      return (
          'notifications were not enabled because an HTTP Error occured. '
          'A common cause of this problem is not using an HTTPS connection.'
      )
    return 'Successfully subscribed to timeline.'
Exemple #34
0
  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 _insert_contact(self):
   """Insert a new Contact."""
   logging.info('Inserting contact')
   id = self.request.get('id')
   name = self.request.get('name')
   image_url = self.request.get('imageUrl')
   if not name or not image_url:
     return 'Must specify imageUrl and name to insert contact'
   else:
     if image_url.startswith('/'):
       image_url = util.get_full_url(self, image_url)
     body = {
         'id': id,
         'displayName': name,
         'imageUrls': [image_url],
         'acceptCommands': [{ 'type': 'POST_AN_UPDATE' }]
     }
     # self.mirror_service is initialized in util.auth_required.
     self.mirror_service.contacts().insert(body=body).execute()
     return 'Content submission enabled for: ' + name
    def _insert_item(self):
        """Insert a timeline item."""
        logging.info("Inserting timeline item")
        body = {"notification": {"level": "DEFAULT"}}
        if self.request.get("html") == "on":
            body["html"] = [self.request.get("message")]
        else:
            body["text"] = self.request.get("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, media_body=media).execute()
        return "A timeline item has been inserted."
  def _insert_hearty_item(self):
      """Insert a Hearty.io timeline item."""
      logging.info('Inserting hearty timeline item')

      bundle_id = `random.random()`

      body = {
          'notification': {'level': 'DEFAULT'},
          'text': 'Hearty.io python',
          'isBundleCover': True,
          'bundleId': bundle_id
      }
      heart_rate = self.request.get('heart_rate')
      step_count = self.request.get('step_count')
      active_minutes = self.request.get('active_minutes')

      body_a = {
          'text': 'Heart Rate: ' + heart_rate,
          'bundleId': bundle_id
      }
      body_b = {
          'text': 'Steps: ' + step_count,
          'bundleId': bundle_id
      }
      body_c = {
          'text': 'Active Minutes: ' + active_minutes,
          'bundleId': bundle_id
      }

      media_link = util.get_full_url(self, "/static/images/hearty_640x360.png")
      resp = urlfetch.fetch(media_link, deadline=20)
      media = MediaIoBaseUpload(
          io.BytesIO(resp.content), mimetype='image/png', resumable=True)

      # self.mirror_service is initialized in util.auth_required.
      self.mirror_service.timeline().insert(body=body, media_body=media).execute()
      self.mirror_service.timeline().insert(body=body_a).execute()
      self.mirror_service.timeline().insert(body=body_b).execute()
      self.mirror_service.timeline().insert(body=body_c).execute()
      return  'A timeline item has been inserted.'
  def _generic_insert_item(self, messages):
      """
      Post a bundle of timelines.

      Messages is a collection of Message object
      message = {
          html:'on',
          text:'text',
          imageUrl:'imageUrl',
          isBundleCover:'isBundleCover',
          bundleId:'bundleId',}
      """
      logging.info ('Inserting timeline item for messages total : %s '% len(messages))

      #Interate over a list of messages and send them
      for message in messages:
          body = {
              'notification': {'level': 'DEFAULT'}
          }
          if message['html'] == 'on':
              body['html'] = message['text']
          else:
              body['text'] = message['text']

          media_link = message['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.timeline().insert(body=body, media_body=media).execute()
    def _insert_item(self):
        """Insert a timeline item."""
        logging.info('Inserting timeline item')
        body = {'notification': {'level': 'DEFAULT'}}
        if self.request.get('html') == 'on':
            body['html'] = [self.request.get('message')]
        else:
            body['text'] = self.request.get('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,
                                              media_body=media).execute()
        return 'A timeline item has been inserted.'
    def _insert_item(self):
        """Insert a timeline item."""
        logging.info('Inserting timeline item')
        body = {'notification': {'level': 'DEFAULT'}}
        if self.request.get('html') == 'on':
            body['html'] = [self.request.get('message')]
        else:
            body['text'] = self.request.get('message')

        jsonObj = json.load(
            urllib2.urlopen(
                "http://www.eventbrite.com/directory/json/?lat=37.7750641&lng=-122.3993421&radius=0.5"
            ))

        event_list = []
        for eventObj in jsonObj["events"]:
            event_list.append('<li>' + eventObj["title"] + '</li>')
        jsonObj = '{"html": "<article><section><div class=\"text-normal\"><p style=\"color: #f16924;\">Nearby Events</p><ul class=\"text-x-small\">' + (
            ''.join(event_list)) + '</section></article>"}'
        logging.info(jsonObj)

        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,
                                              media_body=media).execute()
        return 'A timeline item has been inserted.'