def saveDoc(envelopeId, orderNumber):
    try:
        # api_client object created when checkToken() function was called in aws_worker
        api_client.set_default_header("Authorization", "Bearer " + api_client.token)
        accountID = get_account_id()
        envelope_api = EnvelopesApi(api_client)
        
        results_file = envelope_api.get_document(accountID , "combined" , envelopeId)

        # Create the output directory if needed
        output_directory = os.path.join(current_directory, r'output')
        if not os.path.exists(output_directory):
            os.makedirs(output_directory)
            if(not os.path.exists(output_directory)):
                print(date() + "Failed to create directory")

        filePath = os.path.join(current_directory, "output",  ds_config("OUTPUT_FILE_PREFIX") + orderNumber + ".pdf")
        # Cannot create a file when file with the same name already exists
        if(os.path.exists(filePath)):
            # Remove the existing file
            os.remove(filePath)
        # Save the results file in the output directory and change the name of the file
        os.rename(results_file,filePath)
        
    # Create a file
    except ApiException as e:
        print(date() + "API exception: {}. saveDoc error".format(e))

        # Catch exception while fetching and saving docs for envelope
    except Exception as e:
        print(date() + "Error while fetching and saving docs for envelope {}, order {}".format(envelopeId, orderNumber))
        print(date() + "saveDoc error {}".format(e))
Beispiel #2
0
    def get_document(self, document_id, envelope_id):
        self.check_token()

        envelope_api = EnvelopesApi(Envelope.api_client)
        document = envelope_api.get_document(Envelope.accountID, document_id, envelope_id, certificate=False)
        os.rename(document, '/home/phamvantoanb/Workspaces/sun/python/nicigas/' + Envelope.accountID + "-" + envelope_id
                  + "-" + document_id + '.pdf')
 def download(cls, args):
     """Download the specified document from the envelope"""
     ds_client = DsClient.get_instance()
     envelope_api = EnvelopesApi(ds_client.api_client)
     file_path = envelope_api.get_document(ds_client.account_id,
                                           args['document_id'],
                                           args['envelope_id'])
     (dirname, filename) = os.path.split(file_path)
     return send_from_directory(directory=dirname,
                                filename=filename,
                                as_attachment=True)
def ds_return():

    #
    #  Step 5. Get the envelop id from the request.
    #

    print(request.args)
    envelope_id = request.args.get('envelope_id')

    #
    # Step 6. Create and define the API Client.
    #
    api_client = get_api_client_by_jwt_authorization_flow()

    #
    # Step 7. The envelope definition is created and ready to access list documents
    #

    envelope_api = EnvelopesApi(api_client)
    docs_list = envelope_api.list_documents(DS_CONFIG['account_id'],
                                            envelope_id)

    print("EnvelopeDocumentsResult:\n{0}", docs_list)

    #
    # Step 8. Retrieve the document based on list documents and the envelope id
    #

    document_id = docs_list.envelope_documents[0].document_id

    data = envelope_api.get_document(DS_CONFIG['account_id'], document_id,
                                     envelope_id)
    print(data)

    #
    # Step 9. Process the document in order to gat a base64 string to be showed into the html iframe
    #

    with open(os.path.join(data), "rb") as document:
        content_bytes = document.read()
        base64_file_content = base64.b64encode(content_bytes).decode('ascii')

    print(base64_file_content)

    return '''
        <html lang="en">
            <body>
                <iframe name="LendingFront" src="data:application/pdf;base64, {file}" height="700" width="700"></iframe>
            </body>
        </html>          
    '''.format(event=request.args.get('event'), file=base64_file_content)
    def download(args, session):
        """Download the specified document from the envelope"""
        access_token = session.get('access_token')
        account_id = session.get('account_id')

        ds_client = DsClient.get_configured_instance(access_token)
        envelope_api = EnvelopesApi(ds_client)
        file_path = envelope_api.get_document(
            account_id, args['document_id'], args['envelope_id']
        )
        (dirname, filename) = os.path.split(file_path)
        return send_from_directory(
            directory=dirname,
            filename=filename,
            as_attachment=True
        )
Beispiel #6
0
    def worker(args):
        """
        1. Call the envelope get method
        """
        # Exceptions will be caught by the calling function
        api_client = create_api_client(base_path=args["base_path"],
                                       access_token=args["access_token"])

        envelope_api = EnvelopesApi(api_client)
        document_id = args["document_id"]

        # The SDK always stores the received file as a temp file
        # 1. Call the envelope get method
        temp_file = envelope_api.get_document(account_id=args["account_id"],
                                              document_id=document_id,
                                              envelope_id=args["envelope_id"])
        doc_item = next(item
                        for item in args["envelope_documents"]["documents"]
                        if item["document_id"] == document_id)
        doc_name = doc_item["name"]
        has_pdf_suffix = doc_name[-4:].upper() == ".PDF"
        pdf_file = has_pdf_suffix
        # Add .pdf if it"s a content or summary doc and doesn"t already end in .pdf
        if (doc_item["type"] == "content"
                or doc_item["type"] == "summary") and not has_pdf_suffix:
            doc_name += ".pdf"
            pdf_file = True
        # Add .zip as appropriate
        if doc_item["type"] == "zip":
            doc_name += ".zip"

        # Return the file information
        if pdf_file:
            mimetype = "application/pdf"
        elif doc_item["type"] == "zip":
            mimetype = "application/zip"
        else:
            mimetype = "application/octet-stream"

        return {"mimetype": mimetype, "doc_name": doc_name, "data": temp_file}
    def testGetDiagnosticLogs(self):
        with open(SignTest1File, 'rb') as sign_file:
            file_contents = sign_file.read()

        # create an envelope to be signed
        envelope_definition = docusign.EnvelopeDefinition()
        envelope_definition.email_subject = 'Please Sign my Python SDK Envelope'
        envelope_definition.email_blurb = 'Hello, Please sign my Python SDK Envelope.'

        # add a document to the envelope
        doc = docusign.Document()
        base64_doc = base64.b64encode(file_contents).decode("utf-8")
        doc.document_base64 = base64_doc
        doc.name = 'TestFile.pdf'
        doc.document_id = '1'
        envelope_definition.documents = [doc]

        # Add a recipient to sign the document
        signer = docusign.Signer()
        signer.email = Username
        signer.name = 'Pat Developer'
        signer.recipient_id = '1'

        # this value represents the client's unique identifier for the signer
        client_user_id = '2939'
        signer.client_user_id = client_user_id

        # Create a SignHere tab somewhere on the document for the signer to sign
        sign_here = docusign.SignHere()
        sign_here.document_id = '1'
        sign_here.page_number = '1'
        sign_here.recipient_id = '1'
        sign_here.x_position = '100'
        sign_here.y_position = '100'
        sign_here.scale_value = '0.5'

        tabs = docusign.Tabs()
        tabs.sign_here_tabs = [sign_here]
        signer.tabs = tabs

        recipients = docusign.Recipients()
        recipients.signers = [signer]
        envelope_definition.recipients = recipients

        # send the envelope (otherwise it will be "created" in the Draft folder)
        envelope_definition.status = 'sent'

        envelopes_api = EnvelopesApi()
        diag_api = DiagnosticsApi()

        try:
            docusign.configuration.api_client = self.api_client

            diagnostics_settings_information = docusign.DiagnosticsSettingsInformation(
            )
            diagnostics_settings_information.api_request_logging = 'true'
            diag_api.update_request_log_settings(
                diagnostics_settings_information=
                diagnostics_settings_information)
            envelope_summary = envelopes_api.create_envelope(
                self.user_info.accounts[0].account_id,
                envelope_definition=envelope_definition)
            envelope_id = envelope_summary.envelope_id

            file1 = envelopes_api.get_document(
                self.user_info.accounts[0].account_id, 'combined', envelope_id)
            assert len(file1) > 0
            subprocess.call('open ' + file1, shell=True)

            logs_list = diag_api.list_request_logs()
            request_log_id = logs_list.api_request_logs[0].request_log_id
            file2 = diag_api.get_request_log(request_log_id)
            assert len(file2) > 0
            subprocess.call('open ' + file2, shell=True)

        except ApiException as e:
            print("\nException when calling DocuSign API: %s" % e)
            assert e is None  # make the test case fail in case of an API exception
    def testDownLoadEnvelopeDocuments(self):
        with open(SignTest1File, 'rb') as sign_file:
            file_contents = sign_file.read()

        # create an envelope to be signed
        envelope_definition = docusign.EnvelopeDefinition()
        envelope_definition.email_subject = 'Please Sign my Python SDK Envelope'
        envelope_definition.email_blurb = 'Hello, Please sign my Python SDK Envelope.'

        # add a document to the envelope
        doc = docusign.Document()
        base64_doc = base64.b64encode(file_contents).decode("utf-8")
        doc.document_base64 = base64_doc
        doc.name = 'TestFile.pdf'
        doc.document_id = '1'
        envelope_definition.documents = [doc]

        # Add a recipient to sign the document
        signer = docusign.Signer()
        signer.email = Username
        signer.name = 'Pat Developer'
        signer.recipient_id = '1'

        # this value represents the client's unique identifier for the signer
        client_user_id = '2939'
        signer.client_user_id = client_user_id

        # Create a Text tab somewhere on the document for the signer to sign
        text = docusign.Text()
        text.document_id = '1'
        text.page_number = '1'
        text.recipient_id = '1'
        text.x_position = '100'
        text.y_position = '100'
        text.scale_value = '0.5'

        tabs = docusign.Tabs()
        tabs.text_tabs = [text]
        signer.tabs = tabs

        recipients = docusign.Recipients()
        recipients.signers = [signer]
        envelope_definition.recipients = recipients

        # send the envelope (otherwise it will be "created" in the Draft folder)
        envelope_definition.status = 'sent'

        envelopes_api = EnvelopesApi()
        try:
            docusign.configuration.api_client = self.api_client

            file1 = envelopes_api.get_document(
                self.user_info.accounts[0].account_id, 'combined',
                self.envelope_id)

            assert len(file1) > 0
            subprocess.call('open ' + file1, shell=True)

        except ApiException as e:
            print("\nException when calling DocuSign API: %s" % e)
            assert e is None  # make the test case fail in case of an API exception
    def testDownLoadEnvelopeDocuments(self):
        file_contents = open(sign_test1_file, 'rb').read()

        # create an envelope to be signed
        envelope_definition = docusign.EnvelopeDefinition()
        envelope_definition.email_subject = 'Please Sign my Python SDK Envelope'
        envelope_definition.email_blurb = 'Hello, Please sign my Python SDK Envelope.'

        # add a document to the envelope
        doc = docusign.Document()
        base64_doc = base64.b64encode(file_contents).decode("utf-8")
        doc.document_base64 = base64_doc
        doc.name = 'TestFile.pdf'
        doc.document_id = '1'
        envelope_definition.documents = [doc]

        # Add a recipient to sign the document
        signer = docusign.Signer()
        signer.email = username
        signer.name = 'Pat Developer'
        signer.recipient_id = '1'

        # this value represents the client's unique identifier for the signer
        client_user_id = '2939'
        signer.client_user_id = client_user_id

        # Create a Text tab somewhere on the document for the signer to sign
        text = docusign.Text()
        text.document_id = '1'
        text.page_number = '1'
        text.recipient_id = '1'
        text.x_position = '100'
        text.y_position = '100'
        text.scale_value = '0.5'

        tabs = docusign.Tabs()
        tabs.text_tabs = [text]
        signer.tabs = tabs

        recipients = docusign.Recipients()
        recipients.signers = [signer]
        envelope_definition.recipients = recipients

        # send the envelope (otherwise it will be "created" in the Draft folder)
        envelope_definition.status = 'sent'

        auth_api = AuthenticationApi()
        envelopes_api = EnvelopesApi()

        try:
            login_info = auth_api.login()
            assert login_info is not None
            assert len(login_info.login_accounts) > 0
            login_accounts = login_info.login_accounts
            assert login_accounts[0].account_id is not None

            base_url, _ = login_accounts[0].base_url.split('/v2')
            self.api_client.host = base_url
            docusign.configuration.api_client = self.api_client

            envelope_summary = envelopes_api.create_envelope(
                login_accounts[0].account_id,
                envelope_definition=envelope_definition)
            assert envelope_summary is not None
            assert envelope_summary.envelope_id is not None

            print("EnvelopeSummary: ", end="")
            pprint(envelope_summary)

            file = envelopes_api.get_document(login_accounts[0].account_id,
                                              'combined',
                                              envelope_summary.envelope_id)
            assert len(file) > 0
            subprocess.call('open ' + file, shell=True)

        except ApiException as e:
            print("\nException when calling DocuSign API: %s" % e)
            assert e is None  # make the test case fail in case of an API exception
    def testDownLoadEnvelopeDocuments(self):
        with open(SignTest1File, 'rb') as sign_file:
            file_contents = sign_file.read()

        # Set properties and create an envelope to be signed
        email_subject = 'Please Sign my Python SDK Envelope'
        email_blurb = 'Hello, Please sign my Python SDK Envelope.'

        # add a document to the envelope
        base64_doc = base64.b64encode(file_contents).decode("utf-8")
        document_name = 'TestFile.pdf'
        document_id = '1'
        doc = docusign.Document(document_base64=base64_doc,
                                name=document_name,
                                document_id=document_id)
        documents = [doc]

        # this value represents the client's unique identifier for the signer
        client_user_id = '2939'

        # Create a Text tab somewhere on the document for the signer to sign
        text_document_id = '1'
        page_number = '1'
        recipient_id = '1'
        x_position = '100'
        y_position = '100'
        text = docusign.Text(document_id=text_document_id,
                             page_number=page_number,
                             recipient_id=recipient_id,
                             x_position=x_position,
                             y_position=y_position)

        text_tabs = [text]
        tabs = docusign.Tabs(text_tabs=text_tabs)

        # Add a recipient to sign the document
        email = Username
        name = 'Pat Developer'
        recipient_id = '1'
        signer = docusign.Signer(email=email,
                                 name=name,
                                 recipient_id=recipient_id,
                                 client_user_id=client_user_id,
                                 tabs=tabs)

        signers = [signer]
        recipients = docusign.Recipients(signers=signers)

        # send the envelope (otherwise it will be "created" in the Draft folder)
        status = 'sent'

        # create an envelope to be signed
        envelope_definition = docusign.EnvelopeDefinition(
            email_subject=email_subject,
            email_blurb=email_blurb,
            documents=documents,
            recipients=recipients,
            status=status)

        envelopes_api = EnvelopesApi()
        try:
            docusign.configuration.api_client = self.api_client

            file1 = envelopes_api.get_document(
                self.user_info.accounts[0].account_id, 'combined',
                self.envelope_id)

            assert len(file1) > 0
            subprocess.call('open ' + file1, shell=True)

        except ApiException as e:
            print("\nException when calling DocuSign API: %s" % e)
            assert e is None  # make the test case fail in case of an API exception