def sample32(request):
    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')
    formGuid = request.POST.get('form_guid')
    templateGuid = request.POST.get('template_guid')
    callbackUrl = request.POST.get('callbackUrl')
    basePath = request.POST.get('server_type')
    email = request.POST.get('email')
    message = ""
    # Checking clientId, privateKey and file_Id
    if IsNotNull(clientId) == False or IsNotNull(privateKey) == False:
        return render_to_response('__main__:templates/sample32.pt',
                                  { 'error' : 'You do not enter all parameters' })

    #Get curent work directory
    currentDir = os.path.dirname(os.path.realpath(__file__))
    #Create text file
    fp = open(currentDir + '/../user_info.txt', 'w')
    #Write user info to text file
    fp.write(clientId + "\r\n" + privateKey + "\r\n" + email)
    fp.close()
    ####Create Signer, ApiClient and Storage Api objects

    #Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    #Create apiClient object
    apiClient = ApiClient(signer)
    #Create Storage Api object
    signatureApi = SignatureApi(apiClient)
    #Set base Path
    if basePath == "":
        basePath = "https://api.groupdocs.com/v2.0"
    signatureApi.basePath = basePath
    #Create webHook and set callback URL
    webHook = WebhookInfo()
    webHook.callbackUrl = callbackUrl
    ####Make a request to Signature API using clientId
    if formGuid != "":
        try:
            #Post form by entered form GUID
            postForm = signatureApi.PublishSignatureForm(clientId, formGuid, body=webHook)
            if postForm.status == "Ok":
                message = '<font color="green">Form is published successfully</font>'
                #Generate iframe url
                if basePath == "https://api.groupdocs.com/v2.0":
                    iframe = 'https://apps.groupdocs.com/signature2/forms/signembed/' + formGuid
                #iframe to dev server
                elif basePath == "https://dev-api.groupdocs.com/v2.0":
                    iframe = 'https://dev-apps.groupdocs.com/signature2/forms/signembed/' + formGuid
                #iframe to test server
                elif basePath == "https://stage-apps-groupdocs.dynabic.com/v2.0":
                    iframe = 'https://stage-apps-groupdocs.dynabic.com/signature2/forms/signembed/' + formGuid
                elif basePath == "http://realtime-api.groupdocs.com":
                    iframe = 'https://relatime-apps.groupdocs.com/signature2/forms/signembed/' + formGuid
                iframe = signer.signUrl(iframe)
            else:
                raise Exception(postForm.error_message)
        except Exception, e:
            return render_to_response('__main__:templates/sample32.pt',
                { 'error' : str(e) })
def sample29(request):
####Set variables and get POST data
    clientId = request.POST.get('clientId')
    privateKey = request.POST.get('privateKey')
    url = request.POST.get('url')
    basePath = request.POST.get('basePath')
    if IsNotNull(clientId) == False or IsNotNull(url) == False or IsNotNull(privateKey) == False:
        return render_to_response('__main__:templates/sample29.pt',
                                  { 'error' : 'You do not enter you User id or Private key' })
    # Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    ####Check base path
    if basePath == '':
        basePath = 'https://api.groupdocs.com/v2.0';
    ###Generate iframe url for chosen server

    if basePath == "https://api.groupdocs.com/v2.0":
        iframe = 'https://apps.groupdocs.com/document-viewer/embed?url=' + url + '&user_id=' + clientId
    ###iframe to dev server
    elif basePath == "https://dev-api.groupdocs.com/v2.0":
        iframe = 'https://dev-apps.groupdocs.com/document-viewer/embed?url=' + url + '&user_id=' + clientId

    ###iframe to test server
    elif basePath == "https://stage-api.groupdocs.com/v2.0":
        iframe = 'https://stage-apps.groupdocs.com/document-viewer/embed?url=' + url + '&user_id=' + clientId

    elif basePath == "http://realtime-api.groupdocs.com":
        iframe = 'http://realtime-apps.groupdocs.com/document-viewer/embed?url=' + url + '&user_id=' + clientId
    iframe = signer.signUrl(iframe)
    ###Create json string with result data
    result = json.dumps({ 'iframe' : iframe })
    return Response(body = result, content_type = 'application/json')
def sample29(request):
    ####Set variables and get POST data
    clientId = request.POST.get('clientId')
    privateKey = request.POST.get('privateKey')
    url = request.POST.get('url')
    basePath = request.POST.get('basePath')
    if IsNotNull(clientId) == False or IsNotNull(url) == False or IsNotNull(
            privateKey) == False:
        return render_to_response(
            '__main__:templates/sample29.pt',
            {'error': 'You do not enter you User id or Private key'})
    # Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    ####Check base path
    if basePath == '':
        basePath = 'https://api.groupdocs.com/v2.0'
    ###Generate iframe url for chosen server

    if basePath == "https://api.groupdocs.com/v2.0":
        iframe = 'https://apps.groupdocs.com/document-viewer/embed?url=' + url + '&user_id=' + clientId
    ###iframe to dev server
    elif basePath == "https://dev-api.groupdocs.com/v2.0":
        iframe = 'https://dev-apps.groupdocs.com/document-viewer/embed?url=' + url + '&user_id=' + clientId

    ###iframe to test server
    elif basePath == "https://stage-api.groupdocs.com/v2.0":
        iframe = 'https://stage-apps.groupdocs.com/document-viewer/embed?url=' + url + '&user_id=' + clientId

    elif basePath == "http://realtime-api.groupdocs.com":
        iframe = 'http://realtime-apps.groupdocs.com/document-viewer/embed?url=' + url + '&user_id=' + clientId
    iframe = signer.signUrl(iframe)
    ###Create json string with result data
    result = json.dumps({'iframe': iframe})
    return Response(body=result, content_type='application/json')
def sample28(request):
    clientId = request.POST.get('clientId')
    privateKey = request.POST.get('privateKey')
    fileGuId = request.POST.get('fileId')
    basePath = request.POST.get('basePath')
    #Check is base path entered
    if not basePath:
        #If base path empty set base path to the dev server
        basePath = 'https://api.groupdocs.com/v2.0'
    url = None
    message = None
    # Checking required parameters
    if not clientId or not privateKey or not fileGuId:
        return render_to_response('__main__:templates/sample28.pt',
                                  dict(error='You do not enter all parameters'))

    ### Create Signer, ApiClient and Annotation Api objects

    # Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    # Create apiClient object
    apiClient = ApiClient(signer)
    # Create Annotation object
    ant = AntApi(apiClient)
    ant.basePath = basePath
    try:
        # Make a request to Annotation API using clientId and fileGuId
        response = ant.ListAnnotations(clientId, fileGuId)
        if response.status == "Ok":
            if response.result.annotations:
                    for i in range(len(response.result.annotations)):
                        try:
                            #Delete annotation by it's guid
                            deleteAnnotation = ant.DeleteAnnotation(clientId, response.result.annotations[i].guid)
                            if deleteAnnotation.status == "Ok":
                                message = '<span style="color: red">There are no annotations</span>'
                                ### If request was successful
                                #Generation of iframe URL using $pageImage->result->guid
                                #iframe to production server
                                if basePath == "https://api.groupdocs.com/v2.0":
                                    url = 'https://apps.groupdocs.com/document-viewer/embed/' + fileGuId
                                #iframe to dev server
                                elif basePath == "https://dev-api.groupdocs.com/v2.0":
                                    url = 'https://dev-apps.groupdocs.com/document-viewer/embed/' + fileGuId
                                #iframe to test server
                                elif basePath == "https://stage-api.groupdocs.com/v2.0":
                                    url = 'https://stage-apps.groupdocs.com/document-viewer/embed/' + fileGuId
                                elif basePath == "http://realtime-api.groupdocs.com":
                                    url = 'http://realtime-apps.groupdocs.com/document-viewer/embed/' + fileGuId
                                url = signer.signUrl(url)
                        except Exception, e:
                            return render_to_response('__main__:templates/sample28.pt',
                                                      dict(error=str(e)))
            else:
                message = '<span style="color: red">There are no annotations in this document</span>'
    except Exception, e:
        return render_to_response('__main__:templates/sample28.pt',
                                  dict(error=str(e)))
def sample06(request):
    if request.content_type != 'application/json':
        return render_to_response('__main__:templates/sample06.pt', { })
        #Request to json

    jsonPostData = request.json_body
    #    import pdb; pdb.set_trace()
    #Get parameters
    clientId = jsonPostData["userId"]
    privateKey = jsonPostData["privateKey"]
    documents = jsonPostData['documents']
    signers = jsonPostData['signers']

    #Checking parameters

    if IsNotNull(clientId) == False or IsNotNull(privateKey) == False or IsNotNull(documents) == False or IsNotNull(signers) == False:
        return render_to_response('__main__:templates/sample06.pt',
            { 'error' : 'You do not enter you User id or Private key' })
        #Determination of placeSignatureOn parameter
    for i, signer in enumerate(signers):
        signers[i]['placeSignatureOn'] = ''
        ####Create Signer, ApiClient and Storage Api objects

    #Create signer object
    signerReq = GroupDocsRequestSigner(privateKey)
    #Create apiClient object
    apiClient = ApiClient(signerReq)
    #Create Signsture API object
    signatureApi = SignatureApi(apiClient)
    #Create setting variable for signature SignDocument method
    settings = SignatureSignDocumentSettingsInfo()
    settings.documents = documents
    settings.signers = signers
    ####Make a request to Signature Api for sign document
    #Sign document using current user id and sign settings
    response = signatureApi.SignDocument(clientId, body = settings)

    #If request was successfull - set variables for template
    error = ''
    if response.status == 'Ok':
        time.sleep(5)
        getDocumentStatus = signatureApi.GetSignDocumentStatus(clientId, response.result.jobId);
        if getDocumentStatus.status == "Ok":

            guid = getDocumentStatus.result.documents[0].documentId
            iframe = 'https://apps.groupdocs.com/document-viewer/embed/' + guid
            iframe = signerReq.signUrl(iframe)
            return_data = json.dumps({ 'responseCode' : 200, 'url' : iframe })
            return Response(body = return_data, content_type = 'application/json')
        else:
            error = getDocumentStatus.error_message
            return render_to_response('__main__:templates/sample06.pt',
                { 'error' : response.error_message })
    else:
        error = response.error_message
        return render_to_response('__main__:templates/sample06.pt',
            { 'error' : response.error_message })
def sample28(request):
    clientId = request.POST.get("client_id")
    privateKey = request.POST.get("private_key")
    fileGuId = request.POST.get("fileId")
    basePath = request.POST.get("server_type")
    # Check is base path entered
    if basePath == "":
        # If base path empty set base path to the dev server
        basePath = "https://api.groupdocs.com/v2.0"
    url = ""
    message = ""
    # Checking required parameters
    if IsNotNull(clientId) == False or IsNotNull(privateKey) == False or IsNotNull(fileGuId) == False:
        return render_to_response("__main__:templates/sample28.pt", {"error": "You do not enter all parameters"})

    ### Create Signer, ApiClient and Annotation Api objects

    # Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    # Create apiClient object
    apiClient = ApiClient(signer)
    # Create Annotation object
    ant = AntApi(apiClient)
    ant.basePath = basePath
    try:
        # Make a request to Annotation API using clientId and fileGuId
        response = ant.ListAnnotations(clientId, fileGuId)
        if response.status == "Ok":
            if response.result.annotations:
                i = 0
                for annotation in response.result.annotations:
                    try:
                        # Delete annotation by it's guid
                        deleteAnnot = ant.DeleteAnnotation(clientId, response.result.annotations[i].guid)
                        if deleteAnnot.status == "Ok":
                            message = '<span style="color: red">There are no annotations</span>'
                            ### If request was successfull
                            # Generation of iframe URL using $pageImage->result->guid
                            # iframe to prodaction server
                            if basePath == "https://api.groupdocs.com/v2.0":
                                url = "https://apps.groupdocs.com/document-viewer/embed/" + fileGuId
                            # iframe to dev server
                            elif basePath == "https://dev-api.groupdocs.com/v2.0":
                                url = "https://dev-apps.groupdocs.com/document-viewer/embed/" + fileGuId
                            # iframe to test server
                            elif basePath == "https://stage-api.groupdocs.com/v2.0":
                                url = "https://stage-apps.groupdocs.com/document-viewer/embed/" + fileGuId
                            elif basePath == "http://realtime-api.groupdocs.com":
                                url = "http://realtime-apps.groupdocs.com/document-viewer/embed/" + fileGuId
                            url = signer.signUrl(url)
                    except Exception, e:
                        return render_to_response("__main__:templates/sample28.pt", {"error": str(e)})
                    i = i + 1
            else:
                message = '<span style="color: red">There are no annotations in this document</span>'
    except Exception, e:
        return render_to_response("__main__:templates/sample28.pt", {"error": str(e)})
Beispiel #7
0
def sample12(request):
    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')
    fileGuId = request.POST.get('fileId')

    # Checking required parameters
    if IsNotNull(clientId) == False or IsNotNull(
            privateKey) == False or IsNotNull(fileGuId) == False:
        return render_to_response('__main__:templates/sample12.pt',
                                  {'error': 'You do not enter all parameters'})

    ### Create Signer, ApiClient and Annotation Api objects

    # Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    # Create apiClient object
    apiClient = ApiClient(signer)
    # Create Annotation object
    ant = AntApi(apiClient)

    try:
        # Make a request to Annotation API using clientId and fileGuId
        response = ant.ListAnnotations(clientId, fileGuId)
    except Exception, e:
        return render_to_response('__main__:templates/sample12.pt',
                                  {'error': str(e)})
def sample14(request):
    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')
    path = request.POST.get('path')

    # Checking required parameters
    if IsNotNull(clientId) == False or IsNotNull(
            privateKey) == False or IsNotNull(path) == False:
        return render_to_response('__main__:templates/sample14.pt',
                                  {'error': 'You do not enter all parameters'})

    ### Create Signer, ApiClient, StorageApi and Document Api objects

    # Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    # Create apiClient object
    apiClient = ApiClient(signer)
    # Create StorageApi object
    storageApi = StorageApi(apiClient)
    # Create DocApi object
    docApi = DocApi(apiClient)

    # initialization some variables
    folderId = None
    users = ""

    # parse input path
    pathList = path.split('/')
    if len(path) > 1:
        last = pathList[-1]
        del pathList[-1]
        newPath = "/".join(pathList)
    else:
        last = pathList.pop(0)
        newPath = ""

    try:
        #### Get folder ID by path

        # Make a request to Storage API
        list = storageApi.ListEntities(clientId, newPath)
        if list.status == "Ok":
            for folder in list.result.folders:
                if (folder.name == last):
                    folderId = folder.id

        ### Get list of shares
        if folderId is not None:
            # Make a request to Document API
            shares = docApi.GetFolderSharers(clientId, int(folderId))
            if shares.status == "Ok" and len(shares.result.shared_users) > 0:
                for x in xrange(len(shares.result.shared_users)):
                    # construct users list
                    users += str(shares.result.shared_users[x].nickname)
                    if x != len(shares.result.shared_users) - 1:
                        users += ", "

    except Exception, e:
        return render_to_response('__main__:templates/sample14.pt',
                                  {'error': str(e)})
Beispiel #9
0
def upload(request):
    client_id = request.POST['client_id']
    private_key = request.POST['private_key']

    input_file = request.POST['file']

    current_dir = os.path.dirname(os.path.realpath(__file__))

    # Using the filename like this without cleaning it is very
    # insecure so please keep that in mind when writing your own
    # file handling.
    file_path = os.path.join(current_dir, input_file.filename)
    output_file = open(file_path, 'wb')

    input_file.file.seek(0)
    while 1:
        data = input_file.file.read(2 << 16)
        if not data:
            break
        output_file.write(data)
    output_file.close()

    signer = GroupDocsRequestSigner(private_key)
    apiClient = ApiClient(signer)
    api = StorageApi(apiClient)

    fs = FileStream.fromFile(file_path)
    response = api.Upload(client_id, input_file.filename, fs)
    fs.inputStream.close()
    os.remove(file_path)
    return render_to_response('__main__:viewer.pt',
                              {'guid': response.result.guid},
                              request=request)
Beispiel #10
0
def sample26(request):
    login = request.POST.get('login')
    password = request.POST.get('password')

    if IsNotNull(login) == False or IsNotNull(password) == False:
        return render_to_response(
            '__main__:templates/sample26.pt',
            {'error': 'You do not enter you login or password'})
####Create Signer, ApiClient and Shared Api objects

#Create signer object
    signer = GroupDocsRequestSigner("123")
    #Create apiClient object
    apiClient = ApiClient(signer)
    #Create Management Api object
    api = SharedApi(apiClient)
    #Encode unicode to str
    encodedPassword = password.encode('utf-8')

    try:
        ####Make a request to Management API using clientId
        userInfo = api.LoginUser(login, encodedPassword)

    except Exception, e:
        return render_to_response('__main__:templates/sample26.pt',
                                  {'error': str(e)})
def sample16(request):
    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')
    inputFile = request.POST.get('file')
    url = request.POST.get('url')
    basePath = request.POST.get('server_type')
    fileId = request.POST.get('fileId')
    guid = ""
    iframe = ""
    # Checking required parameters
    if IsNotNull(clientId) == False or IsNotNull(privateKey) == False:
        return render_to_response('__main__:templates/sample16.pt',
                                  {'error': 'You do not enter all parameters'})

    ### Create Signer, ApiClient and Annotation Api objects

    # Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    # Create apiClient object
    apiClient = ApiClient(signer)
    # Create Storage object
    api = StorageApi(apiClient)
    if basePath == "":
        basePath = 'https://api.groupdocs.com/v2.0'
        #Set base path
    api.basePath = basePath
    if url != "":
        try:
            # Upload file to current user storage using entere URl to the file
            upload = api.UploadWeb(clientId, url)
            guid = upload.result.guid
            fileId = ""
        except Exception, e:
            return render_to_response('__main__:templates/sample16.pt',
                                      {'error': str(e)})
Beispiel #12
0
def sample02(request):
    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')

    if IsNotNull(clientId) == False or IsNotNull(privateKey) == False:
        return render_to_response('__main__:templates/sample02.pt',
                                  { 'error' : 'You do not enter you User id or Private key' })
####Create Signer, ApiClient and Storage Api objects

#Create signer object
    signer = GroupDocsRequestSigner(privateKey)
#Create apiClient object
    apiClient = ApiClient(signer)
#Create Storage Api object
    api = StorageApi(apiClient)

    try:
        ####Make a request to Storage API using clientId

        #Obtaining all Entities from current user
        files = api.ListEntities(userId = clientId, path = '', pageIndex = 0)
        #Obtaining file names
        names = ''
        for item in files.result.files:
        #selecting file names
           names += item.name + '<br>'

    except Exception, e:
        return render_to_response('__main__:templates/sample02.pt',
                                  { 'error' : str(e) })
def sample15(request):
    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')

    # Checking required parameters
    if IsNotNull(clientId) == False or IsNotNull(privateKey) == False:
        return render_to_response('__main__:templates/sample15.pt',
                                  {'error': 'You do not enter all parameters'})

    ### Create Signer, ApiClient, StorageApi and Document Api objects

    # Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    # Create apiClient object
    apiClient = ApiClient(signer)
    # Create DocApi object
    doc = DocApi(apiClient)

    # set total views
    views = 0

    try:
        # Make a request to Document API
        response = doc.GetDocumentViews(clientId)
        if response.status == "Ok":
            views = len(response.result.views)

    except Exception, e:
        return render_to_response('__main__:templates/sample15.pt',
                                  {'error': str(e)})
def sample24(request):
    clientId = request.POST.get('clientId')
    privateKey = request.POST.get('privateKey')
    url = request.POST.get('url')
    basePath = request.POST.get('basePath')
    iframe = None
    # Checking required parameters
    if not clientId or not privateKey or not url:
        return render_to_response('__main__:templates/sample24.pt',
                                  dict(error='You do not enter all parameters'))

    ### Create Signer, ApiClient and Storage Api objects

    # Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    # Create apiClient object
    apiClient = ApiClient(signer)
    # Create Storage Api object
    storage = StorageApi(apiClient)
    if not basePath:
        basePath = 'https://api.groupdocs.com/v2.0'
    storage.basePath = basePath
    # Upload file to current user storage using entered URl to the file
    upload = storage.UploadWeb(clientId, url)
    # Check if file uploaded successfully
    if upload.status == "Ok":
        # Generation of Embedded Viewer URL with uploaded file GuId
    # Generation of iframe URL using pageImage.result.guid
        if basePath == "https://api.groupdocs.com/v2.0":
            iframe = 'https://apps.groupdocs.com/document-viewer/embed/' + upload.result.guid
        elif basePath == "https://dev-api.groupdocs.com/v2.0":
            iframe = 'https://dev-apps.groupdocs.com/document-viewer/embed/' + upload.result.guid
        elif basePath == "https://stage-api.groupdocs.com/v2.0":
            iframe = 'https://stage-apps.groupdocs.com/document-viewer/embed/' + upload.result.guid
        iframe = signer.signUrl(iframe)


    # If request was successful - set variables for template
    return render_to_response('__main__:templates/sample24.pt',
        {
            'userId' : clientId,
            'privateKey' : privateKey,
            'url' : url,
            'iframe' : iframe,
        },
        request=request)
def sample05(request):
    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')
    inputFile = request.POST.get('file')
    url = request.POST.get('url')
    basePath = request.POST.get('server_type')
    fileId = request.POST.get('srcPath')
    ID = ""
    name = ''
    message = ''
    destPath = request.POST.get('destPath')
    copy = request.POST.get('copy')
    move = request.POST.get('move')

    ####Check clientId, privateKey and file Id
    if IsNotNull(clientId) == False or IsNotNull(
            privateKey) == False or IsNotNull(destPath) == False:
        return render_to_response('__main__:templates/sample05.pt',
                                  {'error': 'You do not enter all parameters'})

    ####Create Signer, ApiClient and Storage Api objects

    #Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    #Create apiClient object
    apiClient = ApiClient(signer)
    #Create Storage Api object
    api = StorageApi(apiClient)
    #Check base path
    if basePath == "":
        basePath = 'https://api.groupdocs.com/v2.0'
        #Set base path
    api.basePath = basePath
    if url != "":
        try:
            # Upload file to current user storage using entere URl to the file
            upload = api.UploadWeb(clientId, url)
            ID = upload.result.id

            try:
                ####Make a request to Storage API using clientId

                #Obtaining all Entities from current user
                files = api.ListEntities(userId=clientId,
                                         path='My Web Documents',
                                         pageIndex=0)
                #Obtaining file name
                for item in files.result.files:
                    #selecting file names
                    if item.guid == upload.result.guid:
                        name = item.name

            except Exception, e:
                return render_to_response('__main__:templates/sample05.pt',
                                          {'error': str(e)})
        except Exception, e:
            return render_to_response('__main__:templates/sample05.pt',
                                      {'error': str(e)})
def sample25(request):
    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')
    inputFile = request.POST.get('file')
    fileId = request.POST.get('fileId')
    url = request.POST.get('url')
    basePath = request.POST.get('server_type')
    fileGuId = ""

    # Checking clientId and privateKey
    if IsNotNull(clientId) == False or IsNotNull(privateKey) == False:
        return render_to_response(
            '__main__:templates/sample25.pt',
            {'error': 'You do not enter your User Id or Private Key'})
####Create Signer, ApiClient and Storage Api objects

#Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    #Create apiClient object
    apiClient = ApiClient(signer)
    #Create Storage Api object
    storage = StorageApi(apiClient)
    #Create AsyncApi object
    async = AsyncApi(apiClient)
    #Create MergeApi object
    merg = MergeApi(apiClient)
    #Create DocApi object
    doc = DocApi(apiClient)
    #Check is base path entered
    if basePath == "":
        #If base path empty set base path to the dev server
        basePath = 'https://api.groupdocs.com/v2.0'
#Set base path for api
    storage.basePath = basePath
    async .basePath = basePath
    merg.basePath = basePath
    doc.basePath = basePath
    #If user choose local file upload
    if inputFile.filename != "":

        #A hack to get uploaded file size
        inputFile.file.seek(0, 2)
        fileSize = inputFile.file.tell()
        inputFile.file.seek(0)

        fs = FileStream.fromStream(inputFile.file, fileSize)
        ####Make a request to Storage API using clientId
        try:

            #Upload file to current user storage
            upload = storage.Upload(clientId, inputFile.filename, fs)
            if upload.status == "Ok":
                #Get file guid
                fileGuId = upload.result.guid
        except Exception, e:
            return render_to_response('__main__:templates/sample25.pt',
                                      {'error': str(e)})
Beispiel #17
0
def sample24(request):
    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')
    url = request.POST.get('url')
    basePath = request.POST.get('server_type')
    # Checking required parameters
    if IsNotNull(clientId) == False or IsNotNull(
            privateKey) == False or IsNotNull(url) == False:
        return render_to_response('__main__:templates/sample24.pt',
                                  {'error': 'You do not enter all parameters'})

    ### Create Signer, ApiClient and Storage Api objects

    # Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    # Create apiClient object
    apiClient = ApiClient(signer)
    # Create Storage Api object
    storage = StorageApi(apiClient)
    if basePath == "":
        basePath = 'https://api.groupdocs.com/v2.0'
    storage.basePath = basePath
    # Upload file to current user storage using entere URl to the file
    upload = storage.UploadWeb(clientId, url)
    # Check if file uploaded successfully
    if upload.status == "Ok":
        # Generation of Embeded Viewer URL with uploaded file GuId
        # Generation of iframe URL using pageImage.result.guid
        if basePath == "https://api.groupdocs.com/v2.0":
            iframe = 'https://apps.groupdocs.com/document-viewer/embed/' + upload.result.guid
        elif basePath == "https://dev-api.groupdocs.com/v2.0":
            iframe = 'https://dev-apps.groupdocs.com/document-viewer/embed/' + upload.result.guid
        elif basePath == "https://stage-api.groupdocs.com/v2.0":
            iframe = 'https://stage-apps.groupdocs.com/document-viewer/embed/' + upload.result.guid
        iframe = signer.signUrl(iframe)

    # If request was successfull - set variables for template
    return render_to_response('__main__:templates/sample24.pt', {
        'userId': clientId,
        'privateKey': privateKey,
        'url': url,
        'iframe': iframe,
    },
                              request=request)
Beispiel #18
0
def sample04(request):
    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')
    
    file_id = request.POST.get('fileId')
    # Checking clientId, privateKey and file_Id
    if IsNotNull(clientId) == False or IsNotNull(privateKey) == False or IsNotNull(file_id) == False:
        return render_to_response('__main__:templates/sample04.pt',
                                  { 'error' : 'You do not enter all parameters' })

    ####Create Signer, ApiClient and Storage Api objects

    #Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    #Create apiClient object
    apiClient = ApiClient(signer)
    #Create Storage Api object
    api = StorageApi(apiClient)

    ####Make a request to Storage API using clientId

    try:
        #Obtaining all Entities from current user
        files = api.ListEntities(userId = clientId, path = '', pageIndex = 0)
        #Selecting file names
        for item in files.result.files: #selecting file names
            #Obtaining file name for entered file Id
           if item.guid == file_id:
               fileName = item.name

        ####Make a request to Storage Api for dowloading file

        #Obtaining file stream of downloading file and definition of folder where to download file
        currentDir = os.path.dirname(os.path.realpath(__file__))
        
        newpath = currentDir + "/../tmp/"
        if not os.path.exists(newpath):
            os.makedirs(newpath)
        #Downlaoding of file
        fs = api.GetFile(clientId, file_id);

        if fs:

            filePath = newpath + fileName
        
            with open(filePath, 'wb') as fp:
                shutil.copyfileobj(fs.inputStream, fp)
            
            message = '<font color="green">File was downloaded to the <font color="blue">' + filePath + '</font> folder</font> <br />';
        else:
			raise Exception('Wrong file ID!')
    except Exception, e:
        return render_to_response('__main__:templates/sample04.pt',
                                  { 'error' : str(e) })
def sample20(request):

    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')
    resultFileId = request.POST.get('resultFileId')
    basePath = request.POST.get('server_type')

    # Checking required parameters
    if IsNotNull(clientId) == False or IsNotNull(privateKey) == False or IsNotNull(resultFileId) == False:
        return render_to_response('__main__:templates/sample20.pt',
            { 'error' : 'You do not enter all parameters' })

    ### Create Signer, ApiClient and Annotation Api objects

    # Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    # Create apiClient object
    apiClient = ApiClient(signer)
    # Create ComparisonApi object
    compare = ComparisonApi(apiClient)
    if basePath == "":
        basePath = 'https://api.groupdocs.com/v2.0'
    compare.basePath = basePath

    # get changes
    info = compare.GetChanges(clientId, resultFileId)

    # construct table results
    result = ""
    if info.status == "Ok":
        result = "<table class='border'>"
        result += "<tr><td><font color='green'>Change Name</font></td><td><font color='green'>Change</font></td></tr>"
        if info.result.changes is not None:
            for item in info.result.changes:
                for key in item.__dict__:
                    if key != 'swaggerTypes':
                        if type(item.__dict__[key]).__name__ == 'instance':
                            for value in item.__dict__[key].__dict__:
                                if value != "swaggerTypes":
                                    result += "<tr><td>" + value + "</td><td>" + unicode(item.__dict__[key].__dict__[value]) + "</td></tr>"
                        else:
                            result += "<tr><td>" + key + "</td><td>" + unicode(item.__dict__[key]) + "</td></tr>"

                result += "<tr bgcolor='#808080'><td></td><td></td></tr>"
        result += "</table>"

    # If request was successfull - set variables for template
    return render_to_response('__main__:templates/sample20.pt',
        {'userId' : clientId,
         'privateKey' : privateKey,
         'resultFileId' : resultFileId,
         'result' : result},
        request=request)
def sample30(request):
    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')
    file_guid = ""
    message = ""
    file_name = request.POST.get('fileName')
    # Checking clientId, privateKey and file_Id
    if IsNotNull(clientId) == False or IsNotNull(
            privateKey) == False or IsNotNull(file_name) == False:
        return render_to_response('__main__:templates/sample30.pt',
                                  {'error': 'You do not enter all parameters'})

    ####Create Signer, ApiClient and Storage Api objects

    #Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    #Create apiClient object
    apiClient = ApiClient(signer)
    #Create Storage Api object
    api = StorageApi(apiClient)

    ####Make a request to Storage API using clientId
    try:
        #Get all files from account
        allFiles = api.ListEntities(clientId, "", extended=False)
        if allFiles.status == "Ok":
            for i in range(len(allFiles.result.files)):
                if allFiles.result.files[i].name == file_name:
                    file_guid = allFiles.result.files[i].guid
            try:
                if file_guid == "":
                    message = '<span style="color: red">This file is no longer available</span>'
                else:
                    #Delete file from GroupDocs account
                    delete = api.Delete(clientId, file_guid)
                    # Check delete dtatus.
                    if delete.status == "Ok":
                        #            If status Ok return successful message
                        message = '<span style="color: green">Done, file deleted from your GroupDocs Storage</span>'
                    else:
                        raise Exception(delete.error_message)
            except Exception, e:
                return render_to_response('__main__:templates/sample30.pt',
                                          {'error': str(e)})
        else:
def sample33(request):
    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')
    firstUrl = request.POST.get('url1')
    secondUrl = request.POST.get('url2')
    thirdUrl = request.POST.get('url3')
    basePath = request.POST.get('server_type')
    message = ""
    iframe = ""
    # Checking clientId, privateKey and file_Id
    if IsNotNull(clientId) == False or IsNotNull(privateKey) == False:
        return render_to_response('__main__:templates/sample33.pt',
                                  {'error': 'You do not enter all parameters'})

    ####Create Signer, ApiClient and Storage Api objects

    #Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    #Create apiClient object
    apiClient = ApiClient(signer)
    #Create Storage Api object
    storageApi = StorageApi(apiClient)
    #Create Async api object
    asyncApi = AsyncApi(apiClient)
    #Set base Path
    if basePath == "":
        basePath = "https://api.groupdocs.com/v2.0"
    storageApi.basePath = basePath
    asyncApi.basePath = basePath
    #Create list of URL's
    urlList = [firstUrl, secondUrl, thirdUrl]
    #Create empty list for uploaded files GUID's
    guidList = []
    for url in urlList:
        try:
            #Upload file
            upload = storageApi.UploadWeb(clientId, url)
            if upload.status == "Ok":
                #Add GUID of uploaded file to list
                guidList.append(upload.result.guid)
            else:
                raise Exception(upload.error_message)
        except Exception, e:
            return render_to_response('__main__:templates/sample33.pt',
                                      {'error': str(e)})
Beispiel #22
0
def publish_callback(request):
    currentDir = os.path.dirname(os.path.realpath(__file__))
    if os.path.exists(currentDir + '/../user_info.txt'):
        f = open(currentDir + '/../user_info.txt', "r")
        lines = f.readlines()
        f.close()
        lineArray = []
        lineArray = lines[0].split()
        clientId = lineArray[0]
        privateKey = lineArray[1]
        email = lineArray[2]

    if IsNotNull(request.json_body):
        jsonPostData = request.json_body
        formId = jsonPostData['SourceId']
        #Create signer object
        signer = GroupDocsRequestSigner(privateKey)
        # Create apiClient object
        apiClient = ApiClient(signer)
        # Create AsyncApi object
        signature = SignatureApi(apiClient)
        # Create Storage object
        getFileFromForm = signature.PublicGetSignatureFormDocuments(formId)
        if getFileFromForm.status == "Ok":
            documentName = getFileFromForm.result.documents[0].name
            out = "*****@*****.**"
            to = email
            msg = MIMEMultipart('alternative')
            msg['Subject'] = "Link"
            msg['From'] = out
            msg['To'] = to
            html = """\
                <html>
                  <head></head>
                  <body>
                    <p>Document""" + documentName + """ is signed</p>
                  </body>
                </html>
                """
            body = MIMEText(html, 'html')
            msg.attach(body)
            s = smtplib.SMTP('localhost')
            s.sendmail(out, to, msg.as_string())
            s.quit()
Beispiel #23
0
def sample34(request):
    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')
    folder = request.POST.get('folder')
    basePath = request.POST.get('server_type')
    # Checking clientId, privateKey and folder
    if IsNotNull(clientId) == False or IsNotNull(
            privateKey) == False or IsNotNull(folder) == False:
        return render_to_response('__main__:templates/sample34.pt',
                                  {'error': 'You do not enter all parameters'})
    #Remove tags and spaces from entered data
    clientId = re.sub('<[^>]*>', '', clientId.strip())
    privateKey = re.sub('<[^>]*>', '', privateKey.strip())
    folder = re.sub('<[^>]*>', '', folder.strip())
    if basePath == "":
        basePath = "https://api.groupdocs.com/v2.0"
    basePath = re.sub('<[^>]*>', '', basePath)
    ####Create Signer, ApiClient and Storage Api objects

    #Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    #Create apiClient object
    apiClient = ApiClient(signer)
    #Create Storage Api object
    storageApi = StorageApi(apiClient)
    storageApi.basePath = basePath
    ####Make a request to Storage API using clientId

    try:
        #Check entered path for propper slashes
        if folder.find("\\") != -1:
            folder = folder.replace("\\", "/")
        #Create folder
        createFolder = storageApi.Create(clientId, folder)
        #Check status
        if createFolder.status == "Ok":
            #If status Ok generate message with successful result
            message = '<span style="color:green">Folder was created ' + folder + '</span>'
        else:
            raise Exception(createFolder.error_message)
    except Exception, e:
        return render_to_response('__main__:templates/sample34.pt',
                                  {'error': str(e)})
def signature_callback(request):
    currentDir = os.path.dirname(os.path.realpath(__file__))
    if os.path.exists(currentDir + '/../user_info.txt'):
        f = open(currentDir + '/../user_info.txt')
        lines = f.readlines()
        f.close()
        clientId = lines[0].replace("\r\n", "")
        privateKey = lines[1]

    if IsNotNull(request.json_body):
        jsonPostData = request.json_body
        envelopId = jsonPostData['SourceId']
        # Create signer object
        signer = GroupDocsRequestSigner(privateKey)
        # Create apiClient object
        apiClient = ApiClient(signer)
        # Create AsyncApi object
        signature = SignatureApi(apiClient)
        # Create Storage object
        api = StorageApi(apiClient)
        if envelopId != '':
            time.sleep(5)
            print envelopId
            document = signature.GetSignatureEnvelopeDocuments(
                clientId, envelopId)
            if document.status == "Ok":
                guid = document.result.documents[0].documentId
                name = document.result.documents[0].name
                currentDir = os.path.dirname(os.path.realpath(__file__))
                downloadFolder = currentDir + '/../downloads/'
                if not os.path.isdir(downloadFolder):
                    os.makedirs(downloadFolder)

                #Downlaoding of file
                fs = api.GetFile(clientId, guid)

                if fs:

                    filePath = downloadFolder + name

                    with open(filePath, 'wb') as fp:
                        shutil.copyfileobj(fs.inputStream, fp)
def compare_callback(request):
    currentDir = os.path.dirname(os.path.realpath(__file__))
    if os.path.exists(currentDir + '/../user_info.txt'):
        f = open(currentDir + '/../user_info.txt')
        lines = f.readlines()
        f.close()
        clientId = lines[0].replace("\r\n", "")
        privateKey = lines[1]
    if IsNotNull(request.json_body):
        jsonPostData = request.json_body
        jobId = jsonPostData['SourceId']
        # Create signer object
        signer = GroupDocsRequestSigner(privateKey)
        # Create apiClient object
        apiClient = ApiClient(signer)
        # Create AsyncApi object
        async = AsyncApi(apiClient)
        # Create Storage object
        api = StorageApi(apiClient)
        if jobId != '':
            time.sleep(5)
            # Make request to api for get document info by job id
            jobs = async .GetJobDocuments(clientId, jobId)
            if jobs.status == 'Ok':
                # Get file guid
                resultGuid = jobs.result.outputs[0].guid
                name = jobs.result.outputs[0].name
            currentDir = os.path.dirname(os.path.realpath(__file__))
            downloadFolder = currentDir + '/../downloads/'
            if not os.path.isdir(downloadFolder):
                os.makedirs(downloadFolder)

            #Downlaoding of file
            fs = api.GetFile(clientId, resultGuid)

            if fs:

                filePath = downloadFolder + name

                with open(filePath, 'wb') as fp:
                    shutil.copyfileobj(fs.inputStream, fp)
Beispiel #26
0
def annotation(request):
    session = request.session
    signer = GroupDocsRequestSigner(session['private_key'])
    apiClient = ApiClient(signer)
    api = AntApi(apiClient)
    try:
        response = api.ListAnnotations(session['client_id'], session['guid'])
        #~ import pdb;  pdb.set_trace()
        if not response.result.annotations:
            return 'No annotations found.'
        output = ''
        for annotation in response.result.annotations:
            replies = []
            if annotation.replies:
                for reply in annotation.replies:
                    replies.append(reply.userName + ": " + reply.text)
            output += "Annotation Type: " + str(
                annotation.type) + " -- Replies: " + str(replies) + "<br/>"

    except Exception as e:
        return "Server error: " + str(e)

    return output
Beispiel #27
0
def sample01(request):
    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')

    if IsNotNull(clientId) == False or IsNotNull(privateKey) == False:
        return render_to_response(
            '__main__:templates/sample01.pt',
            {'error': 'You do not enter you User id or Private key'})
####Create Signer, ApiClient and Management Api objects

#Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    #Create apiClient object
    apiClient = ApiClient(signer)
    #Create Management Api object
    api = MgmtApi(apiClient)

    try:
        ####Make a request to Management API using clientId
        userInfo = api.GetUserProfile(clientId)

    except Exception, e:
        return render_to_response('__main__:templates/sample01.pt',
                                  {'error': str(e)})
def sample07(request):
    clientId = request.POST.get("client_id")
    privateKey = request.POST.get("private_key")
    #Checking parameters
    if IsNotNull(clientId) == False or IsNotNull(privateKey) == False:
        return render_to_response(
            '__main__:templates/sample07.pt',
            {'error': 'You do not enter you User id or Private key'})
    ####Create Signer, ApiClient and Storage Api objects

    #Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    #Create apiClient object
    apiClient = ApiClient(signer)
    #Create Storage Api object
    storageApi = StorageApi(apiClient)
    ####Make a request to Storage API using clientId

    try:
        #Obtaining all Entities from current user
        files = storageApi.ListEntities(clientId, "", extended=True)
    except Exception, e:
        return render_to_response('__main__:templates/sample07.pt',
                                  {'error': str(e)})
Beispiel #29
0
def sample06(request):
    if request.content_type != 'application/json':
        return render_to_response('__main__:templates/sample06.pt', {})
        #Request to json

    jsonPostData = request.json_body
    #    import pdb; pdb.set_trace()
    #Get parameters
    clientId = jsonPostData["userId"]
    privateKey = jsonPostData["privateKey"]
    documents = jsonPostData['documents']
    signers = jsonPostData['signers']

    #Checking parameters

    if IsNotNull(clientId) == False or IsNotNull(
            privateKey) == False or IsNotNull(documents) == False or IsNotNull(
                signers) == False:
        return render_to_response(
            '__main__:templates/sample06.pt',
            {'error': 'You do not enter you User id or Private key'})
        #Determination of placeSignatureOn parameter
    for i, signer in enumerate(signers):
        signers[i]['placeSignatureOn'] = ''
        ####Create Signer, ApiClient and Storage Api objects

    #Create signer object
    signerReq = GroupDocsRequestSigner(privateKey)
    #Create apiClient object
    apiClient = ApiClient(signerReq)
    #Create Signsture API object
    signatureApi = SignatureApi(apiClient)
    #Create setting variable for signature SignDocument method
    settings = SignatureSignDocumentSettingsInfo()
    settings.documents = documents
    settings.signers = signers
    ####Make a request to Signature Api for sign document
    #Sign document using current user id and sign settings
    response = signatureApi.SignDocument(clientId, body=settings)

    #If request was successfull - set variables for template
    error = ''
    if response.status == 'Ok':
        time.sleep(5)
        getDocumentStatus = signatureApi.GetSignDocumentStatus(
            clientId, response.result.jobId)
        if getDocumentStatus.status == "Ok":

            guid = getDocumentStatus.result.documents[0].documentId
            iframe = 'https://apps.groupdocs.com/document-viewer/embed/' + guid
            iframe = signerReq.signUrl(iframe)
            return_data = json.dumps({'responseCode': 200, 'url': iframe})
            return Response(body=return_data, content_type='application/json')
        else:
            error = getDocumentStatus.error_message
            return render_to_response('__main__:templates/sample06.pt',
                                      {'error': response.error_message})
    else:
        error = response.error_message
        return render_to_response('__main__:templates/sample06.pt',
                                  {'error': response.error_message})
    fp.close()
    #Clear downloads folder
    if os.path.isdir(currentDir + '/../downloads'):
        #Get list of files
        for the_file in os.listdir(currentDir + '/../downloads'):
            file_path = os.path.join(currentDir + '/../downloads', the_file)
            try:
                #Delete file from folder
                os.unlink(file_path)

            except Exception, e:
                print e
    ### Create Signer, ApiClient and AsyncApi objects

    # Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    # Create apiClient object
    apiClient = ApiClient(signer)
    # Create AsyncApi object
    async = AsyncApi(apiClient)
    # Create Storage object
    api = StorageApi(apiClient)
    if basePath == "":
        basePath = 'https://api.groupdocs.com/v2.0'
        #Set base path
    api.basePath = basePath
    async.basePath = basePath
    if url != "":
        try:
            # Upload file to current user storage using entere URl to the file
            upload = api.UploadWeb(clientId, url)
Beispiel #31
0
def sample28(request):
    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')
    fileGuId = request.POST.get('fileId')
    basePath = request.POST.get('server_type')
    #Check is base path entered
    if basePath == "":
        #If base path empty set base path to the dev server
        basePath = 'https://api.groupdocs.com/v2.0'
    url = ""
    message = ""
    # Checking required parameters
    if IsNotNull(clientId) == False or IsNotNull(
            privateKey) == False or IsNotNull(fileGuId) == False:
        return render_to_response('__main__:templates/sample28.pt',
                                  {'error': 'You do not enter all parameters'})

    ### Create Signer, ApiClient and Annotation Api objects

    # Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    # Create apiClient object
    apiClient = ApiClient(signer)
    # Create Annotation object
    ant = AntApi(apiClient)
    ant.basePath = basePath
    try:
        # Make a request to Annotation API using clientId and fileGuId
        response = ant.ListAnnotations(clientId, fileGuId)
        if response.status == "Ok":
            if response.result.annotations:
                i = 0
                for annotation in response.result.annotations:
                    try:
                        #Delete annotation by it's guid
                        deleteAnnot = ant.DeleteAnnotation(
                            clientId, response.result.annotations[i].guid)
                        if deleteAnnot.status == "Ok":
                            message = '<span style="color: red">There are no annotations</span>'
                            ### If request was successfull
                            #Generation of iframe URL using $pageImage->result->guid
                            #iframe to prodaction server
                            if basePath == "https://api.groupdocs.com/v2.0":
                                url = 'https://apps.groupdocs.com/document-viewer/embed/' + fileGuId
                            #iframe to dev server
                            elif basePath == "https://dev-api.groupdocs.com/v2.0":
                                url = 'https://dev-apps.groupdocs.com/document-viewer/embed/' + fileGuId
                            #iframe to test server
                            elif basePath == "https://stage-api.groupdocs.com/v2.0":
                                url = 'https://stage-apps.groupdocs.com/document-viewer/embed/' + fileGuId
                            elif basePath == "http://realtime-api.groupdocs.com":
                                url = 'http://realtime-apps.groupdocs.com/document-viewer/embed/' + fileGuId
                            url = signer.signUrl(url)
                    except Exception, e:
                        return render_to_response(
                            '__main__:templates/sample28.pt',
                            {'error': str(e)})
                    i = i + 1
            else:
                message = '<span style="color: red">There are no annotations in this document</span>'
    except Exception, e:
        return render_to_response('__main__:templates/sample28.pt',
                                  {'error': str(e)})
 def setUp(self):
     self.userId = config['clientId']
     self.apiClient = ApiClient(GroupDocsRequestSigner(
         config['privateKey']))
     self.apiClient.setDebug(True)
def sample39(request):
    #Check if data posted

    #Check is document should be signed with widget if email is not in post data - sign document with widget
    if request.content_type == 'application/json':
        #Get parameters
        jsonPostData = request.json_body
        clientId = jsonPostData["userId"]
        privateKey = jsonPostData["privateKey"]
        documents = jsonPostData['documents']
        signers = jsonPostData['signers']
        error = None
        #Checking parameters
        if not clientId or not privateKey or not documents or not signers:
           error = 'You do not enter you User id or Private key'
        #Determination of placeSignatureOn parameter
        for i, signer in enumerate(signers):
            signers[i]['placeSignatureOn'] = ''

        ####Create Signer, ApiClient and Storage Api objects

        #Create signer object
        signerReq = GroupDocsRequestSigner(privateKey)
        #Create apiClient object
        apiClient = ApiClient(signerReq)
        #Create Signature API object
        signatureApi = SignatureApi(apiClient)
        #Create setting variable for signature SignDocument method
        settings = SignatureSignDocumentSettingsInfo()
        settings.documents = documents
        settings.signers = signers
        ####Make a request to Signature Api for sign document
        #Sign document using current user id and sign settings
        response = signatureApi.SignDocument(clientId, body=settings)

        #If request was successful - set variables for template
        if response.status == 'Ok':
            time.sleep(5)
            #Get signature status
            getDocumentStatus = signatureApi.GetSignDocumentStatus(clientId, response.result.jobId)
            if getDocumentStatus.status == "Ok":
                #If document signed - get it's GUID
                guid = getDocumentStatus.result.documents[0].documentId
            else:
                error = response.error_message
        else:
            error = response.error_message
        #Create json string and return it to ajax request
        return_data = json.dumps({'responseCode': 200, 'guid': guid, 'clientId' : clientId, 'privateKey' : privateKey, 'error' : error})
        return Response(body=return_data, content_type='application/json')
    # If email in post data - sign document with out widget
    elif request.POST.get('email'):
        #Get post data
        clientId = request.POST.get('clientId')
        privateKey = request.POST.get('privateKey')
        email = request.POST.get('email')
        name = request.POST.get('name')
        lastName = request.POST.get('lastName')
        inputFile = request.POST.get('file')
        callbackUrl = request.POST.get('callbackUrl')
        guid = None
        fileName = None
        iframe = None
        # Checking required parameters
        if not clientId or not privateKey or not email or not name or not lastName:
            return render_to_response('__main__:templates/sample39.pt',
                dict(error='You do not enter all parameters'))
        #Get current work directory
        currentDir = os.path.dirname(os.path.realpath(__file__))
        #Create text file
        fp = open(currentDir + '/../user_info.txt', 'w')
        #Write user info to text file
        fp.write(clientId + "\r\n" + privateKey)
        fp.close()
        #Check is temporary file with callback info is exist
        if os.path.exists(currentDir + '/../callback_info.txt'):
            #If exist delete it
            os.remove(currentDir + '/../callback_info.txt')
        ### Create Signer, ApiClient and Annotation Api objects
        # Create signer object
        signer = GroupDocsRequestSigner(privateKey)
        # Create apiClient object
        apiClient = ApiClient(signer)
        # Create StorageApi object
        storage = StorageApi(apiClient)
        # Create SignatureApi object
        signature = SignatureApi(apiClient)
        try:
            #A hack to get uploaded file size
            inputFile.file.seek(0, 2)
            fileSize = inputFile.file.tell()
            inputFile.file.seek(0)
            #Get file stream
            fs = FileStream.fromStream(inputFile.file, fileSize)
            ####Make a request to Storage API using clientId

            #Upload file to current user storage
            response = storage.Upload(clientId, inputFile.filename,  fs, overrideMode=0)
            if response.status != "Ok":
                raise Exception(response.error_message)
            #Get uploaded file GUID
            guid = response.result.guid
            #Get uploaded file name
            fileName = inputFile.filename
        except Exception, e:
            return render_to_response('__main__:templates/sample39.pt',
                {'error': str(e)})
        try:
            # Create envelope using user id and entered by user name
            envelop = signature.CreateSignatureEnvelope(clientId, name=fileName)
            if envelop.status != "Ok":
                raise Exception(envelop.error_message)
            # Add uploaded document to envelope
            addDocument = signature.AddSignatureEnvelopeDocument(clientId, envelop.result.envelope.id, guid)
            if addDocument.status != "Ok":
                raise Exception(envelop.error_message)
                # Get role list for current user
            recipient = signature.GetRolesList(clientId)
            if recipient.status != "Ok":
                raise Exception(envelop.error_message)
            # Get id of role which can sign
            roleId = None
            for item in recipient.result.roles:
                if item.name == "Signer":
                    roleId = item.id
            # add recipient
            addRecipient = signature.AddSignatureEnvelopeRecipient(clientId, envelop.result.envelope.id, email, name, lastName, roleId)
            if addRecipient.status != "Ok":
                raise Exception(envelop.error_message)
            # Get recipient id
            getRecipient = signature.GetSignatureEnvelopeRecipients(clientId, envelop.result.envelope.id)
            if getRecipient.status != "Ok":
                raise Exception(envelop.error_message)
            recipientId = getRecipient.result.recipients[0].id
            #Create Web hook object (callback)
            webHook = WebhookInfo
            webHook.callbackUrl = callbackUrl or None
            #Get document from envelop
            getEnvelopDocument = signature.PublicGetEnvelopeDocuments(envelop.result.envelope.id, recipientId)
            if getEnvelopDocument.status != "Ok":
                raise Exception(envelop.error_message)
            rand = random.randint(0, 500)
            #Create signature field object (max value of locationX,Y can be 1.0)
            SignatureEnvelopeFieldSettings = SignatureEnvelopeFieldSettingsInfo
            SignatureEnvelopeFieldSettings.locationX = "0.15"
            SignatureEnvelopeFieldSettings.locationY = "0.73"
            SignatureEnvelopeFieldSettings.locationWidth = "150"
            SignatureEnvelopeFieldSettings.locationHeight = "50"
            SignatureEnvelopeFieldSettings.name = "test" + str(rand)
            SignatureEnvelopeFieldSettings.forceNewField = True
            SignatureEnvelopeFieldSettings.page = "1"
            #Add signature field to document
            addField = signature.AddSignatureEnvelopeField(clientId, envelop.result.envelope.id, getEnvelopDocument.result.documents[0].documentId, recipientId,
                "0545e589fb3e27c9bb7a1f59d0e3fcb9",
                body=SignatureEnvelopeFieldSettings)
            if addField.status != "Ok":
                raise Exception(envelop.error_message)
            #Send envelop to API
            send = signature.SignatureEnvelopeSend(clientId, envelop.result.envelope.id, body=webHook)
            if send.status != "Ok":
                raise Exception(envelop.error_message)
            # make result messages
            message = '<p>File was uploaded to GroupDocs. Here you can see your <strong>' + name +\
                      '</strong> file in the GroupDocs Embedded Viewer.</p>'
            # Generation of iframe URL using jobInfo.result.outputs[0].guid
            iframe = 'https://apps.groupdocs.com/signature2/signembed/' + envelop.result.envelope.id +\
                         '/' + recipientId
            #Sign iframe URL
            iframe = signer.signUrl(iframe)
        except Exception, e:
            return render_to_response('__main__:templates/sample39.pt',
                {'error': str(e)})
def sample40(request):
    clientId = request.POST.get('clientId')
    privateKey = request.POST.get('privateKey')
    formGuid = request.POST.get('formGuid')
    callbackUrl = request.POST.get('callbackUrl')
    basePath = request.POST.get('basePath')
    # Checking clientId, privateKey and form GUID
    if not clientId or not privateKey or not formGuid:
        return render_to_response('__main__:templates/sample40.pt',
                                  dict(error='You do not enter all parameters'))

    #Get current work directory
    currentDir = os.path.dirname(os.path.realpath(__file__))
    #Create temporary text file
    fp = open(currentDir + '/../user_info.txt', 'w')
    #Write user info to text file
    fp.write(clientId + "\r\n" + privateKey)
    fp.close()
    #Check is temporary file with callback info is exist
    if os.path.exists(currentDir + '/../callback_info.txt'):
        #If exist delete it
        os.remove(currentDir + '/../callback_info.txt')
    ####Create Signer, ApiClient and Storage Api objects
    #Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    #Create apiClient object
    apiClient = ApiClient(signer)
    #Create Storage Api object
    signatureApi = SignatureApi(apiClient)
    #Set base Path
    if not basePath:
        basePath = "https://api.groupdocs.com/v2.0"
    signatureApi.basePath = basePath
    #Create webHook and set callback URL
    webHook = WebhookInfo()
    webHook.callbackUrl = callbackUrl
    ####Make a request to Signature API using clientId
    #create random number
    rand = random.randint(0, 500)
    #Create string variable with new form name
    formName = 'test' + str(rand)
    try:
        #Copy form
        createForm = signatureApi.CreateSignatureForm(clientId, name=formName, formGuid=formGuid)
        if createForm.status == "Ok":
            try:
                #Publish created form
                postForm = signatureApi.PublishSignatureForm(clientId, createForm.result.form.id, body=webHook)
                if postForm.status == "Ok":
                    message = '<font color="green">Form is published successfully</font>'
                    iframe = None
                    #Generate iframe url
                    if basePath == "https://api.groupdocs.com/v2.0":
                        iframe = 'https://apps.groupdocs.com/signature2/forms/signembed/' + \
                                 createForm.result.form.id
                    #iframe to dev server
                    elif basePath == "https://dev-api-groupdocs.dynabic.com/v2.0":
                        iframe = 'https://dev-apps-groupdocs.dynabic.com/signature2/forms/signembed/' + \
                                 createForm.result.form.id
                    #iframe to test server
                    elif basePath == "https://stage-apps-groupdocs.dynabic.com/v2.0":
                        iframe = 'https://stage-apps-groupdocs.dynabic.com/signature2/forms/signembed/' + \
                                 createForm.result.form.id
                    elif basePath == "http://realtime-api-groupdocs.dynabic.com":
                        iframe = 'https://relatime-apps-groupdocs.dynabic.com/signature2/forms/signembed/' + \
                                 createForm.result.form.id
                    iframe = signer.signUrl(iframe)
                else:
                    raise Exception(postForm.error_message)
            except Exception, e:
                return render_to_response('__main__:templates/sample40.pt',
                                          dict(error=str(e)))
        else:
def sample42(request):
    clientId = request.POST.get("clientId")
    privateKey = request.POST.get("privateKey")
    fileId = request.POST.get("fileId")
    basePath = request.POST.get("basePath")
    iframe = None
    # Checking clientId, privateKey and fileId
    if not clientId or not privateKey or not fileId:
        return render_to_response("__main__:templates/sample42.pt", dict(error="You do not enter all parameters"))

    ####Create Signer, ApiClient and Storage Api objects

    # Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    # Create apiClient object
    apiClient = ApiClient(signer)
    # Create Ant Api object
    antApi = AntApi(apiClient)
    # Create Storage Api object
    storageApi = StorageApi(apiClient)
    # Create Async api object
    asyncApi = AsyncApi(apiClient)
    # Set base Path
    if not basePath:
        basePath = "https://api.groupdocs.com/v2.0"
    antApi.basePath = basePath
    asyncApi.basePath = basePath
    storageApi.basePath = basePath
    try:
        # Get all annotations from document
        getAllAnnotations = antApi.ListAnnotations(clientId, fileId)
        if getAllAnnotations.status == "Ok":
            # Create list of result document type
            convertType = ["pdf"]
            # Create JobInfo object and set attributes
            jobInfo = JobInfo()
            jobInfo.actions = "ImportAnnotations"
            jobInfo.out_formats = convertType
            jobInfo.status = "-1"
            jobInfo.email_results = True
            rand = random.randint(0, 500)
            jobInfo.name = "test" + str(rand)
            # Create job
            createJob = asyncApi.CreateJob(clientId, jobInfo)
            if createJob.status != "Ok":
                raise Exception(createJob.error_message)
            else:
                # Add document to the job
                addJobDocument = asyncApi.AddJobDocument(clientId, createJob.result.job_id, fileId, False)
                if addJobDocument.status != "Ok":
                    raise Exception(addJobDocument.error_message)
                else:
                    # Change job status
                    jobInfo.status = "0"
                    # Update job with new status
                    updateJob = asyncApi.UpdateJob(clientId, createJob.result.job_id, jobInfo)
                    if updateJob.status != "Ok":
                        raise Exception(updateJob.error_message)
                    time.sleep(5)
                    # Get result file from job by it's ID
                    getJobDocument = asyncApi.GetJobDocuments(clientId, createJob.result.job_id)

                    if getJobDocument.status != "Ok":
                        raise Exception(getJobDocument.error_message)
                    else:
                        # Get document GUID and Name from job
                        fileGuid = getJobDocument.result.inputs[0].outputs[0].guid
                        fileName = getJobDocument.result.inputs[0].outputs[0].name
                        # Obtaining file stream of downloading file and definition of folder where to download file
                        # Clear downloads folder
                        currentDir = os.path.dirname(os.path.realpath(__file__))
                        if os.path.isdir(currentDir + "/../downloads"):
                            # Get list of files
                            for the_file in os.listdir(currentDir + "/../downloads"):
                                file_path = os.path.join(currentDir + "/../downloads", the_file)
                                try:
                                    # Delete file from folder
                                    os.unlink(file_path)
                                except Exception, e:
                                    print e
                        # Set path to were file will be downloaded
                        newPath = currentDir + "/../downloads/"
                        if not os.path.exists(newPath):
                            os.makedirs(newPath)
                        # Downlaoding of file
                        fs = storageApi.GetFile(clientId, fileGuid)
                        if fs:
                            # Write file from stream to the downloads folder
                            filePath = newPath + fileName
                            with open(filePath, "wb") as fp:
                                shutil.copyfileobj(fs.inputStream, fp)
                            # Generate template message with link by clicking on which user can download file to he's local machine
                            message = (
                                '<p><span style="color:green">File with annotations was downloaded to server\'s local folder. You can download it from <a href="/download_file?FileName='
                                + fileName
                                + '">here</a></span></p>'
                            )
                            # Generation of iframe URL using $pageImage->result->guid
                            # iframe to production server
                            if basePath == "https://api.groupdocs.com/v2.0":
                                iframe = "https://apps.groupdocs.com/document-viewer/embed/" + fileGuid
                            # iframe to dev server
                            elif basePath == "https://dev-api.groupdocs.com/v2.0":
                                iframe = "https://dev-apps.groupdocs.com/document-viewer/embed/" + fileGuid
                            # iframe to test server
                            elif basePath == "https://stage-api.groupdocs.com/v2.0":
                                iframe = "https://stage-apps.groupdocs.com/document-viewer/embed/" + fileGuid
                            elif basePath == "http://realtime-api.groupdocs.com":
                                iframe = "http://realtime-apps.groupdocs.com/document-viewer/embed/" + fileGuid
                            iframe = signer.signUrl(iframe)
                        else:
                            raise Exception("Wrong file ID!")
        else:
    fp.close()
    #Clear downloads folder
    if os.path.isdir(currentDir + '/../downloads'):
        #Get list of files
        for the_file in os.listdir(currentDir + '/../downloads'):
            file_path = os.path.join(currentDir + '/../downloads', the_file)
            try:
                #Delete file from folder
                os.unlink(file_path)

            except Exception, e:
                print e
    ### Create Signer, ApiClient and Annotation Api objects

    # Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    # Create apiClient object
    apiClient = ApiClient(signer)
    # Create StorageApi object
    storage = StorageApi(apiClient)
    # Create SignatureApi object
    signature = SignatureApi(apiClient)
    docApi = DocApi(apiClient)
    mergeApi = MergeApi(apiClient)
    asyncApi = AsyncApi(apiClient)
    if basePath == "":
        basePath = 'https://api.groupdocs.com/v2.0'
    #Set base path
    storage.basePath = basePath
    signature.basePath = basePath
    docApi.basePath = basePath
def sample32(request):
    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')
    formGuid = request.POST.get('form_guid')
    templateGuid = request.POST.get('template_guid')
    callbackUrl = request.POST.get('callbackUrl')
    basePath = request.POST.get('server_type')
    email = request.POST.get('email')
    message = ""
    # Checking clientId, privateKey and file_Id
    if IsNotNull(clientId) == False or IsNotNull(privateKey) == False:
        return render_to_response('__main__:templates/sample32.pt',
                                  {'error': 'You do not enter all parameters'})

    #Get curent work directory
    currentDir = os.path.dirname(os.path.realpath(__file__))
    #Create text file
    fp = open(currentDir + '/../user_info.txt', 'w')
    #Write user info to text file
    fp.write(clientId + "\r\n" + privateKey + "\r\n" + email)
    fp.close()
    ####Create Signer, ApiClient and Storage Api objects

    #Create signer object
    signer = GroupDocsRequestSigner(privateKey)
    #Create apiClient object
    apiClient = ApiClient(signer)
    #Create Storage Api object
    signatureApi = SignatureApi(apiClient)
    #Set base Path
    if basePath == "":
        basePath = "https://api.groupdocs.com/v2.0"
    signatureApi.basePath = basePath
    #Create webHook and set callback URL
    webHook = WebhookInfo()
    webHook.callbackUrl = callbackUrl
    ####Make a request to Signature API using clientId
    if formGuid != "":
        try:
            #Post form by entered form GUID
            postForm = signatureApi.PublishSignatureForm(clientId,
                                                         formGuid,
                                                         body=webHook)
            if postForm.status == "Ok":
                message = '<font color="green">Form is published successfully</font>'
                #Generate iframe url
                if basePath == "https://api.groupdocs.com/v2.0":
                    iframe = 'https://apps.groupdocs.com/signature2/forms/signembed/' + formGuid
                #iframe to dev server
                elif basePath == "https://dev-api.groupdocs.com/v2.0":
                    iframe = 'https://dev-apps.groupdocs.com/signature2/forms/signembed/' + formGuid
                #iframe to test server
                elif basePath == "https://stage-apps-groupdocs.dynabic.com/v2.0":
                    iframe = 'https://stage-apps-groupdocs.dynabic.com/signature2/forms/signembed/' + formGuid
                elif basePath == "http://realtime-api.groupdocs.com":
                    iframe = 'https://relatime-apps.groupdocs.com/signature2/forms/signembed/' + formGuid
                iframe = signer.signUrl(iframe)
            else:
                raise Exception(postForm.error_message)
        except Exception, e:
            return render_to_response('__main__:templates/sample32.pt',
                                      {'error': str(e)})
Beispiel #38
0
 def setUp(self):
     self.signer = GroupDocsRequestSigner(
         "8d8a7d642a807a31c2741c101a60cef2")
     self.basePath = "https://api.groupdocs.com/v2.0/storage/2721ad21bcf0d71e/folders/test.docx?description="