Exemplo n.º 1
0
 def get(self):
     order_id = self.request.get('order_id', default_value='')
     output = ResponseOutput()
     output.set_viewer(self.current_user_email)
     try:
         output.set_data({'order_link': encrypt_order(order_id)})
         output.set_status(200)
     except Exception as e:
         output.set_status(500)
         output.set_error(e.message)
     self.response.write(output.get_serialized_output())
Exemplo n.º 2
0
 def post(self):
     key = PCH_SENSE_SN_KEY[self.device_type]
     current_cache = memcache.get(key=key)
     if current_cache is None:  # memcache has expired, i.e. can check device serial number now
         next_expiration_time = time.time() + THROTTLE_PERIOD
         memcache.add(key=key,
                      value=epoch_to_human(next_expiration_time),
                      time=next_expiration_time)
         self.check_sn()
     else:
         response_output = ResponseOutput()
         response_output.set_status(400)
         response_output.set_error(
             "You can't check {} serial number again until {}".format(
                 self.device_type, current_cache))
         self.response.write(response_output.get_serialized_output())
Exemplo n.º 3
0
    def get_tickets(self, page_limit=100000):
        """
        Grab tickets filed by a customer
        - input: user email (required)
        - auth params: domain, email_account, api_token (required by Zendesk)
        """
        output = ResponseOutput()
        user_email = self.request.get('email')

        zendesk_cred = self.zendesk_credentials
        if not zendesk_cred:
            self.error(500)

        tickets = []
        search_url = "{}/api/v2/search.json?query=type:ticket%20requester:{}&sort_by=created_at&sort_order=desc".format(
            zendesk_cred.domain, user_email)
        zen_auth = (zendesk_cred.email_account + '/token',
                    zendesk_cred.api_token)

        try:
            if not user_email:
                raise RuntimeError("Missing input: user email")
            zen_response = requests.get(search_url, auth=zen_auth)

            ticket_count = 0
            if zen_response.ok:
                tickets += zen_response.json().get('results', [])
                ticket_count = zen_response.json().get('count', 0)

            # Keep querying on as long as paginating is possible
            page_count = 1
            while zen_response.json().get(
                    'next_page') is not None and page_count < page_limit:
                zen_response = requests.get(
                    zen_response.json().get('next_page'), auth=zen_auth)
                if zen_response.ok:
                    tickets += zen_response.json().get('results', [])
                page_count += 1

            output.set_data({'count': ticket_count, 'tickets': tickets})
            output.set_status(200)

        except Exception as e:
            output.set_error(e.message)
            output.set_status(500)

        self.response.write(output.get_serialized_output())
Exemplo n.º 4
0
    def query(self, query_params, raw_output):
        output = ResponseOutput()
        query_string = PAPERTRAIL_ENDPOINT.format(query_params)

        papertrail_response = requests.get(
            query_string,
            headers={"X-Papertrail-Token": self.papertrail_credentials})

        output.set_status(papertrail_response.status_code)
        output.set_error(papertrail_response.reason)

        if papertrail_response.ok:
            output.set_data(json.loads(papertrail_response.content))
        if raw_output is False:
            self.response.write(output.get_serialized_output())
        else:
            return output
Exemplo n.º 5
0
    def get(self):
        limit = int(self.request.get("limit", default_value=10))
        output = ResponseOutput()
        max_id = 100000000

        while max_id > 1 and len(output.data) < limit:
            raw_output = self.hello_request(type="GET",
                                            api_url="account/paginate",
                                            raw_output=True,
                                            url_params={
                                                "limit": limit,
                                                "max_id": max_id
                                            } if limit else {})

            output.set_error(raw_output.error)
            output.set_status(raw_output.status)
            output.set_data(output.data + raw_output.data)
            max_id = int(raw_output.data[-1]["id"])
        self.response.write(output.get_serialized_output())
Exemplo n.º 6
0
    def get(self):
        hashed_firmware = self.request.get('version', default_value="")
        cached_hashed_firmware = memcache.get(hashed_firmware)

        if cached_hashed_firmware is None:
            output = self.hello_request(
                api_url="firmware/names/{}".format(hashed_firmware),
                type="GET",
                raw_output=True)
            stringified_unhashed_firmware = json.dumps(output.data)
            log.info("caching firmware {} - {}".format(
                hashed_firmware, stringified_unhashed_firmware))
            memcache.add(key=hashed_firmware,
                         value=stringified_unhashed_firmware,
                         time=24 * 3600)
        else:
            output = ResponseOutput()
            output.set_data(json.loads(cached_hashed_firmware))
            output.set_status(200)

        self.response.write(output.get_serialized_output())
Exemplo n.º 7
0
    def get(self):
        output = ResponseOutput()
        clearbit_token = ""
        try:
            clearbit_token = Clearbit.query().get().token
        except Exception as e:
            log.error("Failed to get clearbit token because {}", e.message)

        if not clearbit_token:
            output.set_error = "No clearbit token"
            output.set_status(401)
            self.response.write(output.get_serialized_output())
            return
        clearbit_response = requests.get(
            url="https://person.clearbit.com/v1/people/email/{}".format(
                self.request.get("email")),
            headers={"Authorization": "Bearer {}".format(clearbit_token)})
        if clearbit_response.ok:
            output.set_data(clearbit_response.json())
        output.set_status(clearbit_response.status_code)
        output.set_error(clearbit_response.reason)
        self.response.write(output.get_serialized_output())
Exemplo n.º 8
0
    def hello_request(self,
                      api_url,
                      body_data="",
                      url_params={},
                      type="GET",
                      raw_output=False,
                      filter_fields=[],
                      access_token=None,
                      api_info=None,
                      content_type='application/json'):
        """
        :param api_url: api URL
        :type api_url: str
        :param body_data: data to be sent with the request body
        :type body_data: str
        :param url_params: URL parameters
        :type url_params: dict
        :param type: http request type, one of ["GET", "POST", "PUT", "PATCH", "DELETE"]
        :type type: str
        :param access_token: optional token to represent a user
        :type access_token: str
        :param raw_output: boolean value to control output, if raw_ouput is True, return an object rather than a response
        :type raw_output: bool
        :param filter_fields: optional list of fields for filtering
        :type filter_fields: list
        :return a ResponseOutput object in test mode  or a string otherwise
        """
        if access_token is None:
            access_token = self.get_default_access_token()
        if api_info is None:
            api_info = self.suripu_admin

        output = ResponseOutput()
        output.set_viewer(self.current_user_email if self.
                          current_user is not None else "cron-bot")

        headers = {
            "Content-Type":
            content_type,
            "X-Hello-Admin":
            self.current_user_email,
            "X-Appengine-Country":
            self.request.headers.get("X-Appengine-Country", ""),
            "X-Appengine-Region":
            self.request.headers.get("X-Appengine-Region", ""),
            "X-Appengine-City":
            self.request.headers.get("X-Appengine-City", ""),
            "X-Appengine-CityLatLong":
            self.request.headers.get("X-Appengine-CityLatLong", ""),
            "Authorization":
            "Bearer %s" % access_token
        }

        verbs_to_methods = {
            "GET": urlfetch.GET,
            "POST": urlfetch.POST,
            "PUT": urlfetch.PUT,
            "PATCH": urlfetch.PATCH,
            "DELETE": urlfetch.DELETE,
        }

        method = verbs_to_methods[type]
        query_params = urllib.urlencode(url_params)
        url = api_info.domain + api_url
        if query_params:
            url = url + '?' + query_params
        response = urlfetch.fetch(url=url,
                                  payload=body_data,
                                  method=method,
                                  headers=headers)

        output.set_status(response.status_code)
        log.info("%s %s", response.status_code, url)

        content = response.content.decode('utf-8', "replace")
        try:
            log.info("%s %s", url, content)
        except Exception, e:
            log.error("%s", e)