Esempio n. 1
0
    def validate_response(self, response):
        try:
            response = json.loads(response)
        except ValueError:
            raise InvalidResponse('Response was not a valid JSON document')

        if not 'TwilioResponse' in response:
            raise InvalidResponse('Twilio Response was not included')

        if 'RestException' in response['TwilioResponse']:
            raise RestException(
                response['TwilioResponse']['RestException']['Message'])

        return self.validate(response)
Esempio n. 2
0
    def from_response(self, response:Response):

        if response.status_code != 200:
            raise InvalidResponse(f"Job {self.name} given an invalid response to parse")

        data = response.json()

        # builds we received from network
        for build in data['builds']:

            # extract the two id's we need to search
            build_id = build['number']
            queue_id = build['queueId']

            # try to get the instances of the build
            inst = self.find_instance(build_id=build_id, queue_id=queue_id)

            # we haven't created this object yet
            if not inst:
                # create the job instance
                inst = JobInstance(
                    job_name=self.name,
                    build_id=build_id,
                    queue_id=queue_id,
                    api=self.api
                )
                inst.update_from_json(build)
                self.instances.append(inst)
            else:
                if not inst.complete:
                    # update the instance
                    inst.update()
Esempio n. 3
0
    def __jobs_from_response(self, response:Response):
        if response.status_code != 200:
            raise InvalidResponse("Invalid Response")

        data = response.json()

        # get all of the job names that were given to us
        job_names = [x['name'] for x in data['jobs']]

        # figure out what to add and remove from jobs dict
        jobs_to_add     = list(set(job_names).difference(set(self.jobs.keys())))
        jobs_to_remove  = list(set(self.jobs.keys()).difference(set(job_names)))

        for job in jobs_to_remove:
            for c in self.job_change_listeners:
                c(job, False)
            del self.jobs[job]

        for job in jobs_to_add:
            # add the job to the queue
            self.jobs[job] = Job(
                name=job,
                api=self.api
            )
            for c in self.job_change_listeners:
                c(self.jobs[job], True)
Esempio n. 4
0
 async def get_favourites(self):
     async with self.session.get(
         self.url + 'user/' + str(self.id) + '/favourites?access_token=' + self.token.access_token
     ) as resp:
         if resp.status != 200:
             print('ERROR: AniListUser returned error code : ' + str(resp.status))
             raise InvalidResponse(resp.status, "user.get_activity did not receive status 200.")
         return await resp.json(loads=json.loads)
Esempio n. 5
0
 async def get_user(self, user: str):
     async with self.session.get(
         self.url + 'user/' + user + '?access_token=' + self.token.access_token
     ) as resp:
         if resp.status != 200:
             print('ERROR: AniListClient returned error code : ' + str(resp.status))
             raise InvalidResponse(resp.status, "Did not receive status 200.")
         response = await resp.json(loads=json.loads)
         return User(response, self.session)
Esempio n. 6
0
 async def get_notifications_count(self):
     """ Only Available using Authorization Code Grant """
     async with self.session.get(
         self.url + 'user/notifications/count?access_token=' + self.token.access_token,
     ) as resp:
         if resp.status != 200:
             print('ERROR: AniListClient returned error code : ' + str(resp.status))
             raise InvalidResponse(resp.status, "Did not receive status 200.")
         return await resp.json(loads=json.loads)
Esempio n. 7
0
 async def get_manga_list(self, raw=False):
     async with self.session.get(
         self.url + 'user/' + str(self.id) + '/mangalist' +
         ('/raw' if raw else '') + '?access_token=' + self.token.access_token
     ) as resp:
         if resp.status != 200:
             print('ERROR: AniListUser returned error code : ' + str(resp.status))
             raise InvalidResponse(resp.status, "user.get_activity did not receive status 200.")
         return await resp.json(loads=json.loads)
Esempio n. 8
0
 async def get_user_airing(self, limit=10):
     """ Only Available using Pin/Code Grant. """
     async with self.session.get(
         self.url + 'user/airing',
         params={
             'limit': limit,
             'access_token': self.token.access_token
         }
     ) as resp:
         if resp.status != 200:
             print('ERROR: AniListClient returned error code : ' + str(resp.status))
             raise InvalidResponse(resp.status, "Did not receive status 200.")
         return await resp.json(loads=json.loads)
Esempio n. 9
0
    async def search_users(self, query: str):
        """ Returns Array of User Objects."""
        async with self.session.get(
            self.url + 'user/search/' + query + '?access_token=' + self.token.access_token
        ) as resp:
            if resp.status != 200:
                print('ERROR: AniListClient returned error code : ' + str(resp.status))
                raise InvalidResponse(resp.status, "Did not receive status 200.")
            response = await resp.json(loads=json.loads)
            if response.get('error', False):
                return None
            users = []
            for x in response:
                users.append(User(x, self.session))

            return users
Esempio n. 10
0
    def from_build_response(self, response: Response):
        if response.status_code != 200:
            raise InvalidResponse("Invalid response")

        data = response.json()

        if not self.complete:
            self.building = data['building']
            self.complete = not self.building
            self.duration_in_ms = data['duration']
            self.result = data['result']

            self.__update_info()

            if self.complete:
                for c in self.update_listeners:
                    c(self)
Esempio n. 11
0
    def read_response(self):
        response = self._buffer.readline()
        if not response:
            raise ConnectionError("Socket closed on remote end")

        byte, response = byte_to_chr(response[0]), response[1:]

        if byte not in ('-', '+', ':', '$', '*'):
            raise InvalidResponse("Protocol Error: %s, %s" %
                                  (str(byte), str(response)))

        # server returned an error
        if byte == '-':
            response = nativestr(response)
            error = self.parse_error(response)
            # if the error is a ConnectionError, raise immediately so the user
            # is notified
            if isinstance(error, ConnectionError):
                raise error
            # otherwise, we're dealing with a ResponseError that might belong
            # inside a pipeline response. the connection's read_response()
            # and/or the pipeline's execute() will raise this error if
            # necessary, so just return the exception instance here.
            return error
        # single value
        elif byte == '+':
            pass
        # int value
        elif byte == ':':
            response = long(response)
        # bulk response
        elif byte == '$':
            length = int(response)
            if length == -1:
                return None
            response = self._buffer.read(length)
        # multi-bulk response
        elif byte == '*':
            length = int(response)
            if length == -1:
                return None
            response = [self.read_response() for i in xrange(length)]
        if isinstance(response, bytes) and self.encoding:
            response = response.decode(self.encoding)
        return response
Esempio n. 12
0
    def from_queue_response(self, response: Response):
        if response.status_code != 200:
            raise InvalidResponse("Invalid response")

        data = response.json()

        # this thing is no longer in the queue
        if self.in_queue:
            if 'why' in data and data['why'] is None and 'executable' in data:
                self.build_id = int(data['executable']['number'])
                self.in_queue = False

                self.__update_info()

                for c in self.update_listeners:
                    c(self)

        elif not self.in_queue:
            self.in_queue = True

            self.__update_info()

            for c in self.update_listeners:
                c(self)
Esempio n. 13
0
    def call(self, method, path, data=None, need_auth=True):
        """
        Lowest level call helper. If ``consumer_key`` is not ``None``, inject
        authentication headers and sign the request.

        Request signature is a sha1 hash on following fields, joined by '+'
         - application_secret
         - consumer_key
         - METHOD
         - full request url
         - body
         - server current time (takes time delta into account)

        :param str method: HTTP verb. Usualy one of GET, POST, PUT, DELETE
        :param str path: api entrypoint to call, relative to endpoint base path
        :param data: any json serializable data to send as request's body
        :param boolean need_auth: if False, bypass signature
        :raises HTTPError: when underlying request failed for network reason
        :raises InvalidResponse: when API response could not be decoded
        """
        body = ''
        target = self._endpoint + path
        headers = {'X-Ovh-Application': self._application_key}

        # include payload
        if data is not None:
            headers['Content-type'] = 'application/json'
            body = json.dumps(data)
            _logger.info('body before %s' % (body))

        # sign request. Never sign 'time' or will recuse infinitely
        if need_auth:
            if not self._application_secret:
                raise InvalidKey("Invalid ApplicationSecret '%s'" %
                                 self._application_secret)

            if not self._consumer_key:
                raise InvalidKey("Invalid ConsumerKey '%s'" %
                                 self._consumer_key)

            now = str(int(time.time()) + self.time_delta)
            signature = hashlib.sha1()
            signature.update("+".join([
                self._application_secret, self._consumer_key,
                method.upper(), target, body, now
            ]).encode('utf-8'))

            headers['X-Ovh-Consumer'] = self._consumer_key
            headers['X-Ovh-Timestamp'] = now
            headers['X-Ovh-Signature'] = "$1$" + signature.hexdigest()

        # attempt request
        try:
            result = self._session.request(method,
                                           target,
                                           headers=headers,
                                           data=body)
            _logger.info('status ovh result pure client %s' % (result))
        except RequestException as error:
            raise HTTPError("Low HTTP request failed error", error)

        status = result.status_code
        _logger.info('status ovh 1ere client %s' % (status))
        # attempt to decode and return the response
        try:
            json_result = result.json()
            _logger.info('status ovh ss json result client %s' % (result))
        except ValueError as error:
            raise InvalidResponse("Failed to decode API response", error)

        # error check
        if status >= 100 and status < 300:
            return json_result
        elif status == 404:
            raise ResourceNotFoundError(json_result.get('message'))
        elif status == 400:
            raise BadParametersError(json_result.get('message'))
        elif status == 409:
            raise ResourceConflictError(json_result.get('message'))
        elif status == 0:
            raise NetworkError()
        else:
            raise APIError(json_result.get('message'))
Esempio n. 14
0
    def validate(self, response):
        if not 'SMSMessage' in response['TwilioResponse']:
            raise InvalidResponse('SMS body was not included in the response')

        return response
Esempio n. 15
0
    def validate(self, response):
        if not 'Call' in response['TwilioResponse']:
            raise InvalidResponse('Call body was not included in the response')

        return response