Example #1
0
    def post(self, test):
        """Callback for Timeline updates."""

        message = self.request.body
        data = json.loads(message)
        logging.info(data)

        self.response.status = 200

        gplus_id = data["userToken"]
        verifyToken = data["verifyToken"]
        if test is not None:
            user = ndb.Key("TestUser", gplus_id).get()
        else:
            user = ndb.Key("User", gplus_id).get()
        if user is None or user.verifyToken != verifyToken:
            logging.info("Wrong user")
            return

        if data["collection"] != "timeline":
            logging.info("Wrong collection")
            return

        service = get_auth_service(gplus_id, test)

        if service is None:
            logging.info("No valid credentials")
            return

        result = service.timeline().get(id=data["itemId"]).execute()
        logging.info(result)

        for demo_service in demo_services:
            if hasattr(demo_service, "handle_item"):
                demo_service.handle_item(result, data, service, test)
Example #2
0
    def post(self):
        """Callback for Timeline updates."""
        message = self.request.body
        data = json.loads(message)
        logging.info(data)

        self.response.status = 200

        gplus_id = data["userToken"]
        verifyToken = data["verifyToken"]
        user = ndb.Key("User", gplus_id).get()
        if user is None or user.verifyToken != verifyToken:
            logging.info("Wrong user")
            return

        if data["collection"] != "timeline":
            logging.info("Wrong collection")
            return

        service = get_auth_service(gplus_id)

        if service is None:
            logging.info("No valid credentials")
            return

        result = service.timeline().get(id=data["itemId"]).execute()
        logging.info(result)

        for demo_service in demo_services:
            if hasattr(demo_service, "handle_item"):
                (new_items, updated_items, deleted_items) = demo_service.handle_item(result)
                if new_items is not None:
                    for item in new_items:
                        new_result = service.timeline().insert(body=item).execute()
                        logging.info(new_result)
Example #3
0
    def post(self):
        """Create a new timeline card for the current user."""

        self.response.content_type = "application/json"

        gplus_id = self.session.get("gplus_id")
        service = get_auth_service(gplus_id)

        if service is None:
            self.response.status = 401
            self.response.out.write(utils.createError(401, "Current user not connected."))
            return

        message = self.request.body

        data = json.loads(message)

        body = {}
        body["text"] = data["text"]
        if "image" in data:
            body["attachments"] = [{"contentType": "image/*", "contentUrl": data["image"]}]
        body["menuItems"] = [{"action": "SHARE"}, {"action": "REPLY"}]

        try:
            # Insert timeline card and return as reponse
            result = service.timeline().insert(body=body).execute()
            self.response.status = 200
            self.response.out.write(json.dumps(result))
        except AccessTokenRefreshError:
            self.response.status = 500
            self.response.out.write(utils.createError(500, "Failed to refresh access token."))
Example #4
0
    def post(self, test):
        """Callback for Timeline updates."""

        message = self.request.body
        data = json.loads(message)
        logging.info(data)

        self.response.status = 200

        gplus_id = data["userToken"]
        verifyToken = data["verifyToken"]
        if test is not None:
            user = ndb.Key("TestUser", gplus_id).get()
        else:
            user = ndb.Key("User", gplus_id).get()
        if user is None or user.verifyToken != verifyToken:
            logging.info("Wrong user")
            return

        if data["collection"] != "timeline":
            logging.info("Wrong collection")
            return

        service = get_auth_service(gplus_id, test)

        if service is None:
            logging.info("No valid credentials")
            return

        result = service.timeline().get(id=data["itemId"]).execute()
        logging.info(result)
Example #5
0
    def post(self, test):
        """Create a new timeline card for the current user."""

        self.response.content_type = "application/json"

        gplus_id = self.session.get("gplus_id")
        service = get_auth_service(gplus_id, test)

        if service is None:
            self.response.status = 401
            self.response.out.write(
                utils.createError(401, "Current user not connected."))
            return

        message = self.request.body

        data = json.loads(message)

        body = {}
        body["text"] = data["text"]

        try:
            # Insert timeline card and return as reponse
            result = service.timeline().insert(body=body).execute()
            self.response.status = 200
            self.response.out.write(json.dumps(result))
        except AccessTokenRefreshError:
            self.response.status = 500
            self.response.out.write(
                utils.createError(500, "Failed to refresh access token."))
Example #6
0
    def get(self, test, timelineId, attachmentId):
        gplus_id = self.session.get("gplus_id")
        service = get_auth_service(gplus_id, test)
        if service is None:
            self.response.content_type = "application/json"
            self.response.status = 401
            self.response.out.write(
                utils.createError(401, "Invalid credentials."))
            return

        attachment_metadata = service.timeline().attachments().get(
            itemId=timelineId, attachmentId=attachmentId).execute()
        content_type = str(attachment_metadata.get("contentType"))
        content_url = attachment_metadata.get("contentUrl")
        resp, content = service._http.request(content_url)

        if resp.status == 200:
            self.response.content_type = content_type
            self.response.out.write(content)
        else:
            logging.info(resp)
            self.response.content_type = "application/json"
            self.response.status = resp.status
            self.response.out.write(
                utils.createError(resp.status,
                                  "Unable to retrieve attachment."))
Example #7
0
    def post(self, test):
        """Create a new timeline card for the current user."""

        self.response.content_type = "application/json"

        gplus_id = self.session.get("gplus_id")
        service = get_auth_service(gplus_id, test)

        if service is None:
            self.response.status = 401
            self.response.out.write(utils.createError(401, "Current user not connected."))
            return

        message = self.request.body

        data = json.loads(message)

        body = {}
        body["text"] = data["text"]

        try:
            # Insert timeline card and return as reponse
            result = service.timeline().insert(body=body).execute()
            self.response.status = 200
            self.response.out.write(json.dumps(result))
        except AccessTokenRefreshError:
            self.response.status = 500
            self.response.out.write(utils.createError(500, "Failed to refresh access token."))
Example #8
0
    def post(self):
        """Callback for Timeline updates."""
        message = self.request.body
        data = json.loads(message)
        logging.info(data)

        self.response.status = 200

        gplus_id = data["userToken"]
        verifyToken = data["verifyToken"]
        user = ndb.Key("User", gplus_id).get()
        if user is None or user.verifyToken != verifyToken:
            logging.info("Wrong user")
            return

        if data["operation"] != "UPDATE" or data["userActions"][0][
                "type"] != "SHARE":
            logging.info("Wrong operation")
            return

        service = get_auth_service(gplus_id)

        if service is None:
            logging.info("No valid credentials")
            return

        result = service.timeline().get(id=data["itemId"]).execute()
        logging.info(result)

        instaglass_sepia = False
        add_a_cat = False

        if "recipients" in result:
            for rec in result["recipients"]:
                if rec["id"] == "instaglass_sepia":
                    instaglass_sepia = True
                if rec["id"] == "add_a_cat":
                    add_a_cat = True

        if instaglass_sepia:
            new_item = instaglass_image(result, "sepia")
            if new_item is not None:
                result = service.timeline().insert(body=new_item).execute()
                logging.info(result)

        if add_a_cat:
            new_item = cat_image(result)
            if new_item is not None:
                result = service.timeline().insert(body=new_item).execute()
                logging.info(result)
Example #9
0
    def post(self):
        """Callback for Timeline updates."""
        message = self.request.body
        data = json.loads(message)
        logging.info(data)

        self.response.status = 200

        gplus_id = data["userToken"]
        verifyToken = data["verifyToken"]
        user = ndb.Key("User", gplus_id).get()
        if user is None or user.verifyToken != verifyToken:
            logging.info("Wrong user")
            return

        if data["operation"] != "UPDATE" or data["userActions"][0]["type"] != "SHARE":
            logging.info("Wrong operation")
            return

        service = get_auth_service(gplus_id)

        if service is None:
            logging.info("No valid credentials")
            return

        result = service.timeline().get(id=data["itemId"]).execute()
        logging.info(result)

        instaglass_sepia = False
        add_a_cat = False

        if "recipients" in result:
            for rec in result["recipients"]:
                if rec["id"] == "instaglass_sepia":
                    instaglass_sepia = True
                if rec["id"] == "add_a_cat":
                    add_a_cat = True

        if instaglass_sepia:
            new_item = instaglass_image(result, "sepia")
            if new_item is not None:
                result = service.timeline().insert(body=new_item).execute()
                logging.info(result)

        if add_a_cat:
            new_item = cat_image(result)
            if new_item is not None:
                result = service.timeline().insert(body=new_item).execute()
                logging.info(result)
Example #10
0
    def get(self, test, source_id):
        """
        Remove a Source for the user.
        Set Source.active = False if no users are tracking it anymore.
        """

        self.response.content_type = "application/json"

        gplus_id = self.session.get("gplus_id")
        service = get_auth_service(gplus_id, test)

        if service is None:
            self.response.status = 401
            self.response.out.write(utils.createError(401, "Current user not connected."))
            return
Example #11
0
    def get(self, test, source_id):
        """
        Remove a Source for the user.
        Set Source.active = False if no users are tracking it anymore.
        """

        self.response.content_type = "application/json"

        gplus_id = self.session.get("gplus_id")
        service = get_auth_service(gplus_id, test)

        if service is None:
            self.response.status = 401
            self.response.out.write(
                utils.createError(401, "Current user not connected."))
            return
Example #12
0
    def post(self, test):
        """Add a new source to be tracker."""

        self.response.content_type = "application/json"

        gplus_id = self.session.get("gplus_id")
        service = get_auth_service(gplus_id, test)

        if service is None:
            self.response.status = 401
            self.response.out.write(utils.createError(401, "Current user not connected."))
            return

        data = json.loads(self.request.body)

        # TODO
        logging.info(data)
Example #13
0
    def post(self, test):
        """Callback for Location updates."""

        message = self.request.body
        data = json.loads(message)

        self.response.status = 200

        gplus_id = data["userToken"]
        verifyToken = data["verifyToken"]
        if test is not None:
            user = ndb.Key("TestUser", gplus_id).get()
        else:
            user = ndb.Key("User", gplus_id).get()

        if user is None or user.verifyToken != verifyToken:
            logging.info("Wrong user")
            return

        if data["collection"] != "locations":
            logging.info("Wrong collection")
            return

        if data["operation"] != "UPDATE":
            logging.info("Wrong operation")
            return

        service = get_auth_service(gplus_id, test)

        if service is None:
            logging.info("No valid credentials")
            return

        result = service.locations().get(id=data["itemId"]).execute()
        logging.info(result)

        if "longitude" in result and "latitude" in result:
            user.longitude = result["longitude"]
            user.latitude = result["latitude"]
            user.locationUpdate = datetime.utcnow()
            user.put()

        for demo_service in demo_services:
            if hasattr(demo_service, "handle_location"):
                demo_service.handle_location(result, data, service, test)
Example #14
0
    def post(self, test):
        """Callback for Location updates."""

        message = self.request.body
        data = json.loads(message)

        self.response.status = 200

        gplus_id = data["userToken"]
        verifyToken = data["verifyToken"]
        if test is not None:
            user = ndb.Key("TestUser", gplus_id).get()
        else:
            user = ndb.Key("User", gplus_id).get()

        if user is None or user.verifyToken != verifyToken:
            logging.info("Wrong user")
            return

        if data["collection"] != "locations":
            logging.info("Wrong collection")
            return

        if data["operation"] != "UPDATE":
            logging.info("Wrong operation")
            return

        service = get_auth_service(gplus_id, test)

        if service is None:
            logging.info("No valid credentials")
            return

        result = service.locations().get(id=data["itemId"]).execute()
        logging.info(result)

        if "longitude" in result and "latitude" in result:
            user.longitude = result["longitude"]
            user.latitude = result["latitude"]
            user.locationUpdate = datetime.utcnow()
            user.put()

        for demo_service in demo_services:
            if hasattr(demo_service, "handle_location"):
                demo_service.handle_location(result, data, service, test)
Example #15
0
    def post(self, test):
        """Add a new source to be tracker."""

        self.response.content_type = "application/json"

        gplus_id = self.session.get("gplus_id")
        service = get_auth_service(gplus_id, test)

        if service is None:
            self.response.status = 401
            self.response.out.write(
                utils.createError(401, "Current user not connected."))
            return

        data = json.loads(self.request.body)

        # TODO
        logging.info(data)
Example #16
0
    def get(self):
        """Retrieve timeline cards for the current user."""

        self.response.content_type = "application/json"

        gplus_id = self.session.get("gplus_id")
        service = get_auth_service(gplus_id)

        if service is None:
            self.response.status = 401
            self.response.out.write(utils.createError(401, "Current user not connected."))
            return
        try:
            # Retrieve timeline cards and return as reponse
            result = service.timeline().list().execute()
            self.response.status = 200
            self.response.out.write(json.dumps(result))
        except AccessTokenRefreshError:
            self.response.status = 500
            self.response.out.write(utils.createError(500, "Failed to refresh access token."))
Example #17
0
    def get(self):
        """Retrieve timeline cards for the current user."""

        self.response.content_type = "application/json"

        gplus_id = self.session.get("gplus_id")
        service = get_auth_service(gplus_id)

        if service is None:
            self.response.status = 401
            self.response.out.write(
                utils.createError(401, "Current user not connected."))
            return
        try:
            # Retrieve timeline cards and return as reponse
            result = service.timeline().list().execute()
            self.response.status = 200
            self.response.out.write(json.dumps(result))
        except AccessTokenRefreshError:
            self.response.status = 500
            self.response.out.write(
                utils.createError(500, "Failed to refresh access token."))
Example #18
0
    def get(self, test, timelineId, attachmentId):
        gplus_id = self.session.get("gplus_id")
        service = get_auth_service(gplus_id, test)
        if service is None:
            self.response.content_type = "application/json"
            self.response.status = 401
            self.response.out.write(utils.createError(401, "Invalid credentials."))
            return

        attachment_metadata = service.timeline().attachments().get(
            itemId=timelineId, attachmentId=attachmentId).execute()
        content_type = str(attachment_metadata.get("contentType"))
        content_url = attachment_metadata.get("contentUrl")
        resp, content = service._http.request(content_url)

        if resp.status == 200:
            self.response.content_type = content_type
            self.response.out.write(content)
        else:
            logging.info(resp)
            self.response.content_type = "application/json"
            self.response.status = resp.status
            self.response.out.write(utils.createError(resp.status, "Unable to retrieve attachment."))
Example #19
0
    def post(self):
        """Create a new timeline card for the current user."""

        self.response.content_type = "application/json"

        gplus_id = self.session.get("gplus_id")
        service = get_auth_service(gplus_id)

        if service is None:
            self.response.status = 401
            self.response.out.write(
                utils.createError(401, "Current user not connected."))
            return

        message = self.request.body

        data = json.loads(message)

        body = {}
        body["text"] = data["text"]
        if "image" in data:
            body["attachments"] = [{
                "contentType": "image/*",
                "contentUrl": data["image"]
            }]
        body["menuItems"] = [{"action": "SHARE"}, {"action": "REPLY"}]

        try:
            # Insert timeline card and return as reponse
            result = service.timeline().insert(body=body).execute()
            self.response.status = 200
            self.response.out.write(json.dumps(result))
        except AccessTokenRefreshError:
            self.response.status = 500
            self.response.out.write(
                utils.createError(500, "Failed to refresh access token."))
Example #20
0
    def post(self):

        gplus_id = self.request.get("user")
        test = self.request.get("test")
        if test == "" or test == "None":
            test = None

        item_id = self.request.get("item")

        service = get_auth_service(gplus_id, test)

        if service is None:
            logging.error("No valid credentials")
            return

        if test is not None:
            user = ndb.Key("TestUser", gplus_id).get()
        else:
            user = ndb.Key("User", gplus_id).get()

        if user.currentTask is None:
            logging.info("User has no current task")
            return

        item = service.timeline().get(id=item_id).execute()

        imageId = None
        if "attachments" in item:
            for att in item["attachments"]:
                if att["contentType"].startswith("image/"):
                    imageId = att["id"]
                    break

        if imageId is None:
            logging.info("No suitable attachment")
            return

        attachment_metadata = service.timeline().attachments().get(
            itemId=item["id"], attachmentId=imageId).execute()
        content_url = attachment_metadata.get("contentUrl")
        content_type = attachment_metadata.get("contentType")
        resp, content = service._http.request(content_url)

        if resp.status != 200:
            logging.info("Couldn't fetch attachment")

        tempimg = cStringIO.StringIO(content)
        i = Image.open(tempimg).convert("RGB").resize((200, 200),
                                                      Image.ANTIALIAS)
        a = numpy.asarray(i, int)

        R, G, B = a.T

        m = numpy.min(a, 2).T
        M = numpy.max(a, 2).T

        #Chroma
        C = M - m
        Cmsk = C != 0

        # Hue
        H = numpy.zeros(R.shape, int)
        mask = (M == R) & Cmsk
        H[mask] = numpy.mod(60 * (G - B) / C, 360)[mask]
        mask = (M == G) & Cmsk
        H[mask] = (60 * (B - R) / C + 120)[mask]
        mask = (M == B) & Cmsk
        H[mask] = (60 * (R - G) / C + 240)[mask]

        # Value
        V = M

        # Saturation
        S = numpy.zeros(R.shape, int)
        S[Cmsk] = ((255 * C) / V)[Cmsk]

        mask = (V > 100) & (S > 100)

        count = {}
        for col in COLORS:
            count[col] = 0
            v1 = COLORS[col]["min"]
            v2 = COLORS[col]["max"]
            if (v1 < 0):
                col_mask = ((H < v2) | (H > 360 + v1)) & mask
            else:
                col_mask = ((H > v1) & (H < v2)) & mask
            Col = numpy.zeros(R.shape, int)
            Col[col_mask] = numpy.ones(R.shape, int)[col_mask]
            count[col] = numpy.count_nonzero(Col)

        sum = 0
        for col in count:
            if count[col] < 1000:
                count[col] = 0
            else:
                sum = sum + count[col]

        if sum == 0:
            item["text"] = "No colours recognized."
            service.timeline().update(id=item_id, body=item).execute()
            return

        recognized = []
        correct = False
        task = user.currentTask
        for col in count:
            count[col] = count[col] * 100 / sum
            if count[col] > 40:
                if col == task:
                    correct = True
                    break
                recognized.append(col)

        if correct:
            item["text"] = "Congratulations!"
            service.timeline().update(id=item_id, body=item).execute()
            user.currentTask = None
            user.put()

            # Insert submission
            file_name = files.blobstore.create(mime_type=content_type)
            with files.open(file_name, 'a') as f:
                f.write(content)
            files.finalize(file_name)
            blob_key = files.blobstore.get_blob_key(file_name)
            url = get_serving_url(blob_key, secure_url=True, size=640)

            submission = Submission(colour=task,
                                    hue=COLORS[task]["hue"],
                                    blobkey=blob_key,
                                    url=url,
                                    parent=user.key)
            submission.put()

            # TODO: Update scores/achievements

            # Create next task
            taskqueue.add(url="/tasks/createtask",
                          params={
                              "user": gplus_id,
                              "test": test
                          },
                          method="POST")

        else:
            if len(recognized) == 0:
                item["text"] = "No colours recognized."
            else:
                item["text"] = "Recognized " + ", ".join(
                    recognized
                ) + " but your current task is " + user.currentTask

            service.timeline().update(id=item_id, body=item).execute()
Example #21
0
    def post(self):

        gplus_id = self.request.get("user")
        test = self.request.get("test")
        if test == "" or test == "None":
            test = None

        item_id = self.request.get("item")

        service = get_auth_service(gplus_id, test)

        if service is None:
            logging.error("No valid credentials")
            return

        if test is not None:
            user = ndb.Key("TestUser", gplus_id).get()
        else:
            user = ndb.Key("User", gplus_id).get()            

        if user.currentTask is None:
            logging.info("User has no current task")
            return
            
        item = service.timeline().get(id=item_id).execute()

        imageId = None
        if "attachments" in item:
            for att in item["attachments"]:
                if att["contentType"].startswith("image/"):
                    imageId = att["id"]
                    break

        if imageId is None:
            logging.info("No suitable attachment")
            return

        attachment_metadata = service.timeline().attachments().get(
            itemId=item["id"], attachmentId=imageId).execute()
        content_url = attachment_metadata.get("contentUrl")
        content_type = attachment_metadata.get("contentType")
        resp, content = service._http.request(content_url)

        if resp.status != 200:
            logging.info("Couldn't fetch attachment")

        tempimg = cStringIO.StringIO(content)
        i = Image.open(tempimg).convert("RGB").resize((200, 200), Image.ANTIALIAS)
        a = numpy.asarray(i, int)

        R, G, B = a.T

        m = numpy.min(a, 2).T
        M = numpy.max(a, 2).T

        #Chroma
        C = M - m
        Cmsk = C != 0

        # Hue
        H = numpy.zeros(R.shape, int)
        mask = (M == R) & Cmsk
        H[mask] = numpy.mod(60*(G-B)/C, 360)[mask]
        mask = (M == G) & Cmsk
        H[mask] = (60*(B-R)/C + 120)[mask]
        mask = (M == B) & Cmsk
        H[mask] = (60*(R-G)/C + 240)[mask]

        # Value
        V = M

        # Saturation
        S = numpy.zeros(R.shape, int)
        S[Cmsk] = ((255*C)/V)[Cmsk]

        mask = (V > 100) & (S > 100)

        count = {}
        for col in COLORS:
            count[col] = 0
            v1 = COLORS[col]["min"]
            v2 = COLORS[col]["max"]
            if (v1 < 0):
                col_mask = ((H < v2) | (H > 360 + v1)) & mask
            else:
                col_mask = ((H > v1) & (H < v2)) & mask
            Col = numpy.zeros(R.shape, int)
            Col[col_mask] = numpy.ones(R.shape, int)[col_mask]
            count[col] = numpy.count_nonzero(Col)

        sum = 0
        for col in count:
            if count[col] < 1000:
                count[col] = 0
            else:
                sum = sum + count[col]
        
        if sum == 0:
            item["text"] = "No colours recognized."
            service.timeline().update(id=item_id, body=item).execute()
            return

        recognized = []
        correct = False
        task = user.currentTask
        for col in count:
            count[col] = count[col] * 100 / sum
            if count[col] > 40:
                if col == task:
                    correct = True
                    break
                recognized.append(col)

        if correct:
            item["text"] = "Congratulations!"
            service.timeline().update(id=item_id, body=item).execute()
            user.currentTask = None
            user.put()
            
            # Insert submission
            file_name = files.blobstore.create(mime_type=content_type)
            with files.open(file_name, 'a') as f:
                f.write(content)
            files.finalize(file_name)
            blob_key = files.blobstore.get_blob_key(file_name)
            url = get_serving_url(blob_key, secure_url=True, size=640)

            submission = Submission(colour=task,
                                    hue=COLORS[task]["hue"],
                                    blobkey=blob_key,
                                    url=url,
                                    parent=user.key)
            submission.put()
            
            # TODO: Update scores/achievements
            
            # Create next task
            taskqueue.add(url="/tasks/createtask",
                          params={"user": gplus_id, "test": test},
                          method="POST")
        
        else:
            if len(recognized) == 0:
                item["text"] = "No colours recognized."
            else:
                item["text"] = "Recognized " + ", ".join(recognized) + " but your current task is " + user.currentTask

            service.timeline().update(id=item_id, body=item).execute()
Example #22
0
    def post(self):

        gplus_id = self.request.get("user")
        test = self.request.get("test")
        if test == "" or test == "None":
            test = None

        service = get_auth_service(gplus_id, test)
        if service is None:
            logging.error("User not authenticated")
            return

        if test is not None:
            user = ndb.Key("TestUser", gplus_id).get()
        else:
            user = ndb.Key("User", gplus_id).get()

        if user is None:
            logging.error("User not found")
            return

        col = random.choice(COLORS.keys())

        user.currentTask = col
        user.put()

        card = {
            "html": ("<article class=\"photo\">"
                     "  <img src=\"" + base_url + "/images/" + col + ".png\" width=\"100%\" height=\"100%\">"
                     "  <div class=\"photo-overlay\"></div>"
                     "  <section>"
                     "    <p class=\"text-auto-size\">Current Task: " + COLORS[col]["name"] + "</p>"
                     "  </section>"
                     "</article>"),
            "menuItems": [
                {
                    "action": "CUSTOM",
                    "id": "giveup",
                    "values": [{
                        "displayName": "Give Up",
                        "iconUrl": "https://mirror-api.appspot.com/glass/images/error.png"
                    }]
                },
                {
                    "action": "TOGGLE_PINNED"
                }
            ],
            "sourceItemId": SOURCE_ITEM_ID
        }

        result = service.timeline().list(sourceItemId=SOURCE_ITEM_ID).execute()
        if "items" in result and len(result["items"]) > 0:
            request = service.timeline().update(id=result["items"][0]["id"], body=card)
        else:
            request = service.timeline().insert(body=card)

        try:
            request.execute()
        except AccessTokenRefreshError:
            logging.error("Failed to refresh access token.")
            return
        except HttpError as e:
            logging.error("Failed to execute request. %s" % e)
            return
Example #23
0
    def post(self):

        gplus_id = self.request.get("user")
        test = self.request.get("test")
        if test == "" or test == "None":
            test = None

        service = get_auth_service(gplus_id, test)
        if service is None:
            logging.error("User not authenticated")
            return

        if test is not None:
            user = ndb.Key("TestUser", gplus_id).get()
        else:
            user = ndb.Key("User", gplus_id).get()

        if user is None:
            logging.error("User not found")
            return

        col = random.choice(COLORS.keys())

        user.currentTask = col
        user.put()

        card = {
            "html": ("<article class=\"photo\">"
                     "  <img src=\"" + base_url + "/images/" + col +
                     ".png\" width=\"100%\" height=\"100%\">"
                     "  <div class=\"photo-overlay\"></div>"
                     "  <section>"
                     "    <p class=\"text-auto-size\">Current Task: " +
                     COLORS[col]["name"] + "</p>"
                     "  </section>"
                     "</article>"),
            "menuItems": [{
                "action":
                "CUSTOM",
                "id":
                "giveup",
                "values": [{
                    "displayName":
                    "Give Up",
                    "iconUrl":
                    "https://mirror-api.appspot.com/glass/images/error.png"
                }]
            }, {
                "action": "TOGGLE_PINNED"
            }],
            "sourceItemId":
            SOURCE_ITEM_ID
        }

        result = service.timeline().list(sourceItemId=SOURCE_ITEM_ID).execute()
        if "items" in result and len(result["items"]) > 0:
            request = service.timeline().update(id=result["items"][0]["id"],
                                                body=card)
        else:
            request = service.timeline().insert(body=card)

        try:
            request.execute()
        except AccessTokenRefreshError:
            logging.error("Failed to refresh access token.")
            return
        except HttpError as e:
            logging.error("Failed to execute request. %s" % e)
            return