Exemplo n.º 1
0
    def __init__(self, client_id, secret):

        self.client_id = client_id
        self.secret = secret

        self.token_generator = TokenGenerator(client_id, secret)
        self.json_converter = JsonConverter()
Exemplo n.º 2
0
    def __init__(self, token, apiurl):

        self.token = token
        self.json_converter = JsonConverter()
        self.url = "https://api.pdf4me.com/"
        if apiurl is not None and len(apiurl) != 0:
            self.url = apiurl
        self.userAgent = "pdf4me-python/0.8.24"
Exemplo n.º 3
0
    def check_response_for_errors(selfself, res):
        '''
        Checks document logs for error reports, in case an error is found a Pdf4meBackendException is thrown.
        :param res: content of response
        :type res: string
        :return: None
        '''

        jsonConverter = JsonConverter()

        if res is None:
            raise Pdf4meBackendException('Server Error')

        # check whether the res contains none, one or multiple documents
        one_doc = None
        multiple_docs = None
        docs = []

        try:
            one_doc = jsonConverter.load(res)['document']
        except KeyError:
            pass
        except ValueError:
            pass
        except TypeError:
            pass
        except JSONDecoder:
            pass

        try:
            multiple_docs = jsonConverter.load(res)['documents']
        except KeyError:
            pass
        except ValueError:
            pass
        except TypeError:
            pass
        except JSONDecoder:
            pass

        if one_doc is not None:
            docs = [one_doc]
        elif multiple_docs is not None:
            docs = multiple_docs
        # otw docs is empty

        # extract the logs
        doc_logs = []
        for i in range(len(docs)):
            doc_logs = doc_logs + docs[i]['doc_logs']

        # check all logs for errors
        for i in range(len(doc_logs)):
            current_doc_log = doc_logs[i]
            if (current_doc_log['doc_log_level'] == 3):
                raise Pdf4meBackendException(current_doc_log['message'])
    def split_recurring(self, page_nr, file):
        """Splits the PDF after the pageNr, this results in two smaller PDF documents.

        :param page_nr: determines after which page the split takes place
        :type page_nr: str:
        :param file: to split into two
        :type file: file handler, use the method get_file_handler from FileReader to obtain it
        :return: bytes of resulting file, can be directly written to file on disk
        """

        streams = [('file', file)]
        params = [('pageNr', page_nr)]

        res = self.pdf4me_client.custom_http.post_wrapper(
            octet_streams=streams,
            values=params,
            controller='Split/SplitRecurring')

        # get json
        res = JsonConverter().load(res)

        # extract the two documents
        pdfs = []
        for pdf in res:
            pdfs.append(base64.b64decode(pdf))
        # pdf_1 = base64.b64decode(res[0])
        # pdf_2 = base64.b64decode(res[1])

        return pdfs
    def create_thumbnails(self, width, page_nrs, image_format, file):
        """Produces a thumbnail of the page referenced by the pageNr. Be aware of the one-indexing of the page numbers.

        :param width: size of the produced thumbnail
        :type width: int
        :param page_nrs: number of the page which should be captured by the thumbnail
        :type page_nrs: str
        :param image_format: picture format of thumbnail, e.g. 'jpg'
        :type image_format: str
        :param file: file to capture thumbnails from
        :type file: file handler, use the method get_file_handler from FileReader to obtain it
        :return: bytes of produced thumbnail, can be directly written to image file on disk
        """

        streams = [('file', file)]
        params = [('width', width), ('pageNrs', page_nrs),
                  ('imageFormat', image_format)]

        res = self.pdf4me_client.custom_http.post_wrapper(
            octet_streams=streams,
            values=params,
            controller='Image/CreateThumbnails')

        # get json
        res = JsonConverter().load(res)

        # extract the two documents
        pdfs = []
        for pdf in res:
            pdfs.append(base64.b64decode(pdf))
        # pdf_1 = base64.b64decode(res[0])
        # pdf_2 = base64.b64decode(res[1])

        return pdfs
Exemplo n.º 6
0
class JobClientTest(unittest.TestCase):
    pdf4me_client = Pdf4meClient()
    job_client = JobClient(pdf4me_client)

    test_files = TestFiles()
    check = Check()
    file_reader = FileReader()
    json_converter = JsonConverter()
Exemplo n.º 7
0
    def metadata(self, file):
        """repairs selected pages of the document in given direction.

        :param file: to be repaired
        :type file: file handler, use the method get_file_handler from FileReader to obtain it
        :return: DocMetadata, can be directly written to file on disk
        """

        streams = [('file', file)]
        params = []

        res = self.pdf4me_client.custom_http.post_wrapper(
            octet_streams=streams, values=params, controller='PdfA/Metadata')

        # get json
        return JsonConverter().load(res)
Exemplo n.º 8
0
    def validate_document(self, file, pdf_compliance):
        """validates selected pages of the document in given direction.

        :param pdf_compliance: PDF/A compliance to check
        :type pdf_compliance: str
        :param file: to be validated
        :type file: file handler, use the method get_file_handler from FileReader to obtain it
        :return: bytes of resulting file, can be directly written to file on disk
        """

        streams = [('file', file)]
        params = [('pdfCompliance', pdf_compliance)]

        res = self.pdf4me_client.custom_http.post_wrapper(
            octet_streams=streams,
            values=params,
            controller='PdfA/ValidateDocument')
        # get json
        res = JsonConverter().load(res)

        return res
Exemplo n.º 9
0
    def read_barcodes_by_type(self, barcode_type, file):
        """Reads barcodes from the file based on the barcode type

        :param barcode_type: barcode type
        :type barcode_type: str: ( 'all','unknown','code11','code39','code93','code128','codabar','inter2of5',
                                'patchcode','ean8','upce','ean13','upca','plus2','plus5','pdf417','datamatrix','qrcode',
                                'postnet','planet','rm4scc','australiapost','intelligentmail','code39extended',
                                'microqrcode','all_2d','pharmacode','ucc128','rss14','rsslimited','rssexpanded','all_1d')
        :param file: to be read barcode form
        :type file: file handler, use the method get_file_handler from FileReader to obtain it
        :return: ReadBarcodeRes, contains the barcode
        """

        streams = [('file', file)]
        params = [('barcodeType', barcode_type)]

        res = self.pdf4me_client.custom_http.post_wrapper(octet_streams=streams, values=params,
                                                          controller='Barcode/ReadBarcodesByType')

        json_response = JsonConverter().load(res)

        return json_response
Exemplo n.º 10
0
class CustomHttp(object):
    def __init__(self, client_id, secret):

        self.client_id = client_id
        self.secret = secret

        self.token_generator = TokenGenerator(client_id, secret)
        self.json_converter = JsonConverter()

    def post_universal_object(self, universal_object, controller):
        """Sends a post request to the specified controller with the given
        universal_object as a body.

        :param universal_object: object to be sent
        :type universal_object: object
        :param controller: swagger controller
        :type controller: str
        :return: post response
        """

        # prepare post request
        token = self.token_generator.get_token()
        request_url = URL + controller
        headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
        }

        # convert body to json
        body = self.json_converter.dump(element=universal_object)

        # send request
        res = requests.post(request_url, data=body, headers=headers)

        # check status code
        self.__check_status_code(res)

        # check docLogs for error messages
        self.__check_docLogs_for_error_messages(res)

        # read content from response
        json_response = self.json_converter.load(res.text)

        return json_response

    def post_wrapper(self, octet_streams, values, controller):
        """Builds a post requests from the given parameters.

        :param octet_streams: (key: file identifier, value: open(fileName, 'rb'))) pairs
        :type octet_streams: list
        :param values: (key: identifier of value, value: content of value) pairs
        :type values: list
        :param controller: swagger controller
        :type controller: str
        :return: post response
        """

        # prepare post request
        token = self.token_generator.get_token()
        request_url = URL + controller
        header = {'Authorization': 'Bearer ' + token}

        # build files
        if len(octet_streams) != 0:
            files = {key: value for (key, value) in octet_streams}
        else:
            files = None

        # build values
        if len(values) != 0:
            data = {key: value for (key, value) in values}
        else:
            data = None

        # send request
        if files is None:
            if data is None:
                raise Pdf4meClientException(
                    "Please provide at least one value or an octet-stream.")
            else:
                res = requests.post(request_url, data=data, headers=header)
        else:
            if data is None:
                res = requests.post(request_url, files=files, headers=header)
            else:
                res = requests.post(request_url,
                                    files=files,
                                    data=data,
                                    headers=header)

        # check status code
        self.__check_status_code(res)

        # check docLogs for error messages
        self.__check_docLogs_for_error_messages(res)

        return res.content

    def __check_status_code(self, response):
        '''
        Checks whether the status code is either 200 or 204, otw. throws a Pdf4meBackendException.
        :param response: post response
        :type response: requests.Response
        :return: None
        '''

        status_code = response.status_code
        status_reason = response.reason

        if status_code == 500:
            server_error = self.json_converter.load(
                response.text)['error_message']
            raise Pdf4meBackendException('HTTP 500 ' + status_reason + " : " +
                                         server_error)
        elif status_code != 200 and status_code != 204:
            error = response.text
            raise Pdf4meBackendException('HTTP ' + status_code + ': ' +
                                         status_reason + " : " + error)

    def __check_docLogs_for_error_messages(self, response):
        '''
        Checks whether the HTTP response's docLogs contain any error message, in case of an error
         a Pdf4meBackendException is thrown.
        :param response: post response
        :type response: requests.Response
        :return: None
        '''

        ResponseChecker().check_response_for_errors(response.text)
Exemplo n.º 11
0
class CustomHttp(object):
    def __init__(self, token, apiurl):

        self.token = token
        self.json_converter = JsonConverter()
        self.url = "https://api.pdf4me.com/"
        if apiurl is not None and len(apiurl) != 0:
            self.url = apiurl
        self.userAgent = "pdf4me-python/0.8.24"

    def post_universal_object(self, universal_object, controller):
        """Sends a post request to the specified controller with the given
        universal_object as a body.

        :param universal_object: object to be sent
        :type universal_object: object
        :param controller: swagger controller
        :type controller: str
        :return: post response
        """

        # prepare post request
        request_url = self.url + controller
        headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': 'Basic ' + self.token,
            'User-Agent': self.userAgent
        }

        # convert body to json
        body = self.json_converter.dump(element=universal_object)

        # send request
        res = requests.post(request_url, data=body, headers=headers)

        # check status code
        self.__check_status_code(res)

        # check docLogs for error messages
        self.__check_docLogs_for_error_messages(res)

        # read content from response
        json_response = self.json_converter.load(res.text)

        return json_response

    def post_wrapper(self, octet_streams, values, controller):
        """Builds a post requests from the given parameters.

        :param octet_streams: (key: file identifier, value: open(fileName, 'rb'))) pairs
        :type octet_streams: list
        :param values: (key: identifier of value, value: content of value) pairs
        :type values: list
        :param controller: swagger controller
        :type controller: str
        :return: post response
        """

        # prepare post request
        request_url = self.url + controller
        header = {
            'Authorization': 'Basic ' + self.token,
            'User-Agent': self.userAgent
        }

        # build files
        if octet_streams is not None and len(octet_streams) != 0:
            files = {key: value for (key, value) in octet_streams}
        else:
            files = None

        # build values
        if len(values) != 0:
            data = {key: value for (key, value) in values}
        else:
            data = None

        # send request
        if files is None:
            if data is None:
                raise Pdf4meClientException(
                    "Please provide at least one value or an octet-stream.")
            else:
                res = requests.post(request_url, data=data, headers=header)
        else:
            if data is None:
                res = requests.post(request_url, files=files, headers=header)
            else:
                res = requests.post(request_url,
                                    files=files,
                                    data=data,
                                    headers=header)

        # check status code
        self.__check_status_code(res)

        # check docLogs for error messages
        self.__check_docLogs_for_error_messages(res)

        return res.content

    def get_object(self, query_strings, controller):
        """Sends a get request to the specified controller with the given query strings.

        :param query_strings: params to be sent
        :type query_strings: str
        :param controller: swagger controller
        :type controller: str
        :return: post response
        """

        # prepare post request
        request_url = self.url + controller
        headers = {
            'Authorization': 'Basic ' + self.token,
            'User-Agent': self.userAgent
        }

        # send request
        res = requests.get(request_url, data=query_strings, headers=headers)

        # check status code
        self.__check_status_code(res)

        # check docLogs for error messages
        self.__check_docLogs_for_error_messages(res)

        # read content from response
        json_response = self.json_converter.load(res.text)

        return json_response

    def get_wrapper(self, query_strings, controller):
        """Sends a get request to the specified controller with the given
        query string and returns a file

        :param query_strings: params to be sent
        :type query_strings: str
        :param controller: swagger controller
        :type controller: str
        :return: file
        """

        # prepare post request
        request_url = self.url + controller
        headers = {
            'Authorization': 'Basic ' + self.token,
            'User-Agent': self.userAgent
        }

        # send request
        res = requests.get(request_url, data=query_strings, headers=headers)

        # check status code
        self.__check_status_code(res)

        # check docLogs for error messages
        self.__check_docLogs_for_error_messages(res)

        return res.content

    def __check_status_code(self, response):
        '''
        Checks whether the status code is either 200 or 204, otw. throws a Pdf4meBackendException.
        :param response: post response
        :type response: requests.Response
        :return: None
        '''

        status_code = response.status_code
        status_reason = response.reason

        if status_code == 500:
            server_error = self.json_converter.load(
                response.text)['error_message']
            trace_id = self.json_converter.load(response.text)['trace_id']
            raise Pdf4meBackendException('HTTP 500 ' + status_reason +
                                         " : trace_id " + trace_id + " : " +
                                         server_error)
        elif status_code != 200 and status_code != 204:
            error = response.text
            raise Pdf4meBackendException('HTTP ' + str(status_code) + ': ' +
                                         status_reason + " : " + error)

    def __check_docLogs_for_error_messages(self, response):
        '''
        Checks whether the HTTP response's docLogs contain any error message, in case of an error
         a Pdf4meBackendException is thrown.
        :param response: post response
        :type response: requests.Response
        :return: None
        '''

        ResponseChecker().check_response_for_errors(response.text)