def sample03(request):
    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')
    inputFile = request.POST.get('file')
    # Checking clientId and privateKey
    if IsNotNull(clientId) == False or IsNotNull(privateKey) == False:
        return render_to_response('__main__:templates/sample03.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
    api = StorageApi(apiClient)

    try:
        #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

        #Upload file to current user storage
        response = api.Upload(clientId, inputFile.filename, fs)
        #Generation of Embeded Viewer URL with uploaded file GuId
        iframe = '<iframe src="https://apps.groupdocs.com/document-viewer/embed/' + response.result.guid + '" frameborder="0" width="720" height="600""></iframe>'
        message = '<p>File was uploaded to GroupDocs. Here you can see your <strong>' + inputFile.filename + '</strong> file in the GroupDocs Embedded Viewer.</p>'
    except Exception, e:
        return render_to_response('__main__:templates/sample03.pt',
                                  { 'error' : str(e) })
Beispiel #2
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 #3
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)
def sample3(request):
    clientId = os.environ['GROUPDOCS_CID']
    privateKey = os.environ['GROUPDOCS_PKEY']
    #serviceUrl = os.environ['GROUPDOCS_URL']
    inputFile = request.POST.get('fileData')


    if inputFile == None:
        return render_to_response('__main__:templates/sample3.pt', { })
    elif IsNotNull(clientId) == False or IsNotNull(privateKey) == False:
        return render_to_response('__main__:templates/sample3.pt', { 'errmsg' : 'User id or Private key not found!' })

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

    try:
        # 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)
        response = api.Upload(clientId, inputFile.filename, fs)
    except Exception, e:
        return render_to_response('__main__:templates/sample3.pt', 
                                  { 'errmsg' : str(e) })
def sample27(request):
    clientId = request.POST.get('clientId')
    privateKey = request.POST.get('privateKey')
    inputFile = request.POST.get('file')
    fileId = request.POST.get('fileId')
    url = request.POST.get('url')
    basePath = request.POST.get('basePath')
    name = request.POST.get('name')
    sex = request.POST.get('sex')
    age = request.POST.get('age')
    sunrise = request.POST.get('sunrise')
    type = request.POST.get('type')
    fileGuId = None
    # Checking clientId and privateKey
    if not clientId or not privateKey:
        return render_to_response('__main__:templates/sample27.pt',
                                  dict(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
    merge = MergeApi(apiClient)
    #Create DocApi object
    doc = DocApi(apiClient)
    #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'
        #Set base path for api
    storage.basePath = basePath
    async.basePath = basePath
    merge.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, overrideMode=0)
            if upload.status == "Ok":
                #Get file guid
                fileGuId = upload.result.guid
        except Exception, e:
            return render_to_response('__main__:templates/sample27.pt',
                                      dict(error=str(e)))
def sample35(request):
    ####Check which form is now field. If not "guid" that first form.
    if request.POST.get('guid') == None or request.POST.get('guid') == '':
        #Get posted data
        clientId = request.POST.get('clientId')
        privateKey = request.POST.get('privateKey')
        inputFile = request.POST.get('file')
        fileId = request.POST.get('guidField')
        url = request.POST.get('url')
        basePath = request.POST.get('basePath')
        # Checking clientId and privateKey
        if not clientId or not privateKey:
            return render_to_response('__main__:templates/sample35.pt',
                dict(error='You do not enter your User Id or Private Key', newForm=""))
        #Create signer object
        signer = GroupDocsRequestSigner(privateKey)
        #Create apiClient object
        apiClient = ApiClient(signer)
        #Create Storage Api object
        storage = StorageApi(apiClient)
        #Create DocApi object
        doc = DocApi(apiClient)
        #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'
        #Set base path for api
        storage.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, overrideMode=0)
                if upload.status == "Ok":
                    #Get file guid
                    fileGuId = upload.result.guid
            except Exception, e:
                return render_to_response('__main__:templates/sample35.pt',
                    dict(error=str(e), newForm= ''))
        #If user choose upload file from web
        if url:
            try:
                # Upload file to current user storage using entered URl to the file
                uploadWeb = storage.UploadWeb(clientId, url)
                # Check if file uploaded successfully
                if uploadWeb.status == "Ok":
                    #Get file guid
                    fileGuId = uploadWeb.result.guid
            except Exception, e:
                return render_to_response('__main__:templates/sample35.pt',
                    dict(error=str(e), newForm= ''))
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)})
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) })
def sample44(request):
    clientId = request.POST.get('clientId')
    privateKey = request.POST.get('privateKey')
    inputFile = request.POST.get('file')
    basePath = request.POST.get('basePath')
    firstName = request.POST.get('firstName')
    gender = request.POST.get('gender')
    lastName = request.POST.get('lastName')
    firstEmail = request.POST.get('firstEmail')
    secondEmail = request.POST.get('secondEmail')
    fileGuId = None
    # Checking clientId and privateKey
    if not clientId or not privateKey or not firstEmail or not firstName or not secondEmail:
        return render_to_response('__main__:templates/sample44.pt',
                                  dict(error='Please enter all required data', url1=''))
    ####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
    merge = MergeApi(apiClient)
    #Create DocApi object
    doc = DocApi(apiClient)
    #Create Signature object
    signature = SignatureApi(apiClient)
    #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'
    #Set base path for api
    storage.basePath = basePath
    async.basePath = basePath
    merge.basePath = basePath
    doc.basePath = basePath
    signature.basePath = basePath
    #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, overrideMode=0)
        if upload.status == "Ok":
            #Get file guid
            fileGuId = upload.result.guid
    except Exception, e:
        return render_to_response('__main__:templates/sample44.pt',
                                  dict(error=str(e), url1=''))
def sample17(request):

    clientId = request.POST.get('client_id')
    privateKey = request.POST.get('private_key')
    inputFile = request.POST.get('file')

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

    ### Create Signer, ApiClient and StorageApi objects

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

    result = ''
    try:
        # 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)
        #~ import pdb;  pdb.set_trace()

        # upload file and get response
        response = api.Upload(clientId, inputFile.filename, fs)

        # compress file using upload response
        compress = api.Compress(clientId, response.result.id, "zip")
        if compress.status == "Ok":
            result = "Archive created and saved successfully"

    except Exception, e:
        return render_to_response('__main__:templates/sample17.pt',
            { 'error' : str(e) })
    def callAPI(self, apiServer, resourcePath, method, queryParams, postData,
                headerParams=None, returnType=str):
        if self.__debug and self.__logFilepath:
            stdOut = sys.stdout
            logFile = open(self.__logFilepath, 'a')
            sys.stdout = logFile

        url = apiServer + resourcePath
        
        headers = {}
        if self.headers:
            for param, value in self.headers.items():
                headers[param] = value
            
        if headerParams:
            for param, value in headerParams.items():
                headers[param] = value

        isFileUpload = False
        if not postData:
            headers['Content-type'] = 'text/html'
        elif isinstance(postData, FileStream):
            isFileUpload = True
            if postData.contentType:
                headers['Content-type'] = 'application/octet-stream'
            if postData.size: 
                headers['Content-Length'] = str(postData.size)
        else:
            headers['Content-type'] = 'application/json'

        if self.cookie:
            headers['Cookie'] = self.cookie

        data = None

        if queryParams:
            # Need to remove None values, these should not be sent
            sentQueryParams = {}
            for param, value in queryParams.items():
                if value != None:
                    sentQueryParams[param] = value
            if sentQueryParams:
                url = url + '?' + urllib.parse.urlencode(sentQueryParams)

        if method in ['POST', 'PUT', 'DELETE']:

            if isFileUpload:
                data = postData.inputStream
            elif not postData:
                data = ""
            elif type(postData) not in [str, int, float, bool]:
                data = self.signer.signContent(json.dumps(self.sanitizeForSerialization(postData)), headers)
            else: 
                data = self.signer.signContent(postData, headers)

        if self.__debug:
            http.client.HTTPConnection.debuglevel = 1
            
        if data and not isFileUpload:
            data = data.encode('utf-8')

        request = MethodRequest(method=method, url=self.encodeURI(self.signer.signUrl(url)), headers=headers,
                                data=data)

        try:
            # Make the request
            response = urllib.request.urlopen(request)
            
            if 'Set-Cookie' in response.headers:
                self.cookie = response.headers['Set-Cookie']
        
            if response.code == 200 or response.code == 201 or response.code == 202:
                if returnType == FileStream:
                    fs = FileStream.fromHttp(response)
                    if self.__debug: print("\n", "< Response Body:\n", ">>>stream info: fileName=%s contentType=%s size=%s" % (fs.fileName, fs.contentType, fs.size), "\n", sep="")
                    return fs if 'Transfer-Encoding' in response.headers or (fs.size != None and int(fs.size) > 0) else None
                else:
                    encoding = response.headers.get_content_charset()
                    if not encoding: encoding = 'iso-8859-1'
                    string = response.read().decode(encoding)
                    if self.__debug: print("\n", "< Response Body:\n", string, "\n", sep="")
                    try:
                        data = json.loads(string)
                    except ValueError:  # PUT requests don't return anything
                        data = None
                    return data
                
            elif response.code == 404:
                return None
            
            else:
                encoding = response.headers.get_content_charset()
                if not encoding: encoding = 'iso-8859-1'
                string = response.read().decode(encoding)                    
                try:
                    msg = json.loads(string)['error_message']
                except ValueError:
                    msg = string
                raise ApiException(response.code, msg)
        except urllib.error.HTTPError as e:
            raise ApiException(e.code, e.msg)
                
        finally:
            if isFileUpload:
                try:
                    postData.inputStream.close()
                except Exception as e:
                    pass
            if self.__debug:
                http.client.HTTPConnection.debuglevel = 0
                if self.__logFilepath:
                    sys.stdout = stdOut
                    logFile.close()
 def setUp(self):
     filePath = os.path.dirname(os.path.abspath(__file__)) + "/resources/test.doc"
     self.fs = FileStream.fromFile(filePath) 
Beispiel #13
0
            except Exception, e:
                return render_to_response('__main__:templates/sample03.pt',
                                          {'error': str(e)})

        except Exception, e:
            return render_to_response('__main__:templates/sample03.pt',
                                      {'error': str(e)})

    if inputFile != "":
        try:
            #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

            #Upload file to current user storage
            response = api.Upload(clientId, inputFile.filename, fs)
            guid = response.result.guid
            name = inputFile.filename
        except Exception, e:
            return render_to_response('__main__:templates/sample03.pt',
                                      {'error': str(e)})
    #Generation of Embeded Viewer URL with uploaded file GuId
    iframe = ''
    if basePath == "https://api.groupdocs.com/v2.0":
        iframe = 'https://apps.groupdocs.com/document-viewer/embed/' + guid
    #iframe to dev server
    elif basePath == "https://dev-api.groupdocs.com/v2.0":
    def callAPI(self, apiServer, resourcePath, method, queryParams, postData,
                headerParams=None, returnType=str):
        if self.__debug and self.__logFilepath:
            stdOut = sys.stdout
            logFile = open(self.__logFilepath, 'a')
            sys.stdout = logFile

        url = apiServer + resourcePath
        
        headers = {}
        if self.headers:
            for param, value in self.headers.iteritems():
                headers[param] = value
            
        if headerParams:
            for param, value in headerParams.iteritems():
                headers[param] = value

        isFileUpload = False
        if not postData:
            headers['Content-type'] = 'text/html'
        elif isinstance(postData, FileStream):
            isFileUpload = True
            if postData.contentType:
                headers['Content-type'] = postData.contentType
            if postData.size: 
                headers['Content-Length'] = str(postData.size)
        else:
            headers['Content-type'] = 'application/json'

        if self.cookie:
            headers['Cookie'] = self.cookie

        data = None

        if queryParams:
            # Need to remove None values, these should not be sent
            sentQueryParams = {}
            for param, value in queryParams.items():
                if value != None:
                    sentQueryParams[param] = value
            if sentQueryParams:
                url = url + '?' + urllib.urlencode(sentQueryParams)

        if method in ['POST', 'PUT', 'DELETE']:

            if isFileUpload:
                data = postData.inputStream
            elif not postData:
                data = ""
            elif type(postData) not in [unicode, int, float, bool]:
                data = self.signer.signContent(json.dumps(self.sanitizeForSerialization(postData)), headers)
            else: 
                data = self.signer.signContent(postData, headers)

        if self.__debug:
            handler = urllib2.HTTPSHandler(debuglevel=1) if url.lower().startswith('https') else urllib2.HTTPHandler(debuglevel=1)
            opener = urllib2.build_opener(handler)
            urllib2.install_opener(opener)

        request = MethodRequest(method=method, url=self.encodeURI(self.signer.signUrl(url)), headers=headers,
                                data=data)

        try:
            # Make the request
            response = urllib2.urlopen(request)
            
            if 'Set-Cookie' in response.headers:
                self.cookie = response.headers['Set-Cookie']
        
            if response.code == 200 or response.code == 201 or response.code == 202:
                if returnType == FileStream:
                    fs = FileStream.fromHttp(response)
                    if self.__debug: print(">>>stream info: fileName=%s contentType=%s size=%s" % (fs.fileName, fs.contentType, fs.size))
                    return fs if 'Transfer-Encoding' in response.headers or (fs.size != None and int(fs.size) > 0) else None
                else:                
                    string = response.read()
                    if self.__debug: print(string)
                    try:
                        data = json.loads(string)
                    except ValueError:  # PUT requests don't return anything
                        data = None
                    return data
                
            elif response.code == 404:
                return None
            
            else:
                string = response.read()
                try:
                    msg = json.loads(string)['error_message']
                except ValueError:
                    msg = string
                raise ApiException(response.code, msg)
        except urllib2.HTTPError, e:
            raise ApiException(e.code, e.msg)
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)})
Beispiel #16
0
                # Upload file to current user storage using entere URl to the file
                upload = api.UploadWeb(clientId, target_url)
                targetFileId = upload.result.guid

            except Exception, e:
                return render_to_response('__main__:templates/sample19.pt',
                    { 'error' : str(e) })
    if sourceFile != "" or targetFile != "":
        if sourceFile != "":
            try:
                #A hack to get uploaded file size
                sourceFile.file.seek(0, 2)
                fileSize = sourceFile.file.tell()
                sourceFile.file.seek(0)

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

                #Upload file to current user storage
                response = api.Upload(clientId, sourceFile.filename, fs)
                sourceFileId = response.result.guid

            except Exception, e:
                return render_to_response('__main__:templates/sample19.pt',
                    { 'error' : str(e) })
        if targetFile != "":
            try:
                #A hack to get uploaded file size
                targetFile.file.seek(0, 2)
                fileSize = targetFile.file.tell()
                targetFile.file.seek(0)
Beispiel #17
0
 def setUp(self):
     # TODO mock http response
     response = {} 
     response.closed = False
     self.fs = FileStream.fromHttp(response) 
            # 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) })

    if inputFile != "":
        try:
            #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

            #Upload file to current user storage
            response = api.Upload(clientId, inputFile.filename, fs)
            guid = response.result.guid
            fileId = ""
        except Exception, e:
            return render_to_response('__main__:templates/sample16.pt',
                { 'error' : str(e) })
    if fileId != '':
        guid = fileId

    try:
        convert = async.Convert(clientId, guid, new_type=targetType, callbackUrl = callbackUrl)
        # check request status
 def setUp(self):
     filePath = os.path.dirname(
         os.path.abspath(__file__)) + "/resources/test.doc"
     self.fs = FileStream.fromFile(filePath)