def track(request): filename = request.GET['filename'] usAddr = request.GET['userAddress'] response = {} try: body = json.loads(request.body) if jwtManager.isEnabled(): token = body.get('token') if (not token): token = request.headers.get('Authorization') if token: token = token[len('Bearer '):] if (not token): raise Exception('Expected JWT') body = jwtManager.decode(token) if (body.get('payload')): body = body['payload'] status = body['status'] download = body.get('url') if (status == 2) | (status == 3): # mustsave, corrupted path = docManager.getStoragePath(filename, usAddr) histDir = historyManager.getHistoryDir(path) versionDir = historyManager.getNextVersionDir(histDir) changesUri = body.get('changesurl') os.rename( path, historyManager.getPrevFilePath(versionDir, fileUtils.getFileExt(filename))) docManager.saveFileFromUri(download, path) docManager.saveFileFromUri( changesUri, historyManager.getChangesZipPath(versionDir)) hist = None hist = body.get('changeshistory') if (not hist) & ('history' in body): hist = json.dumps(body.get('history')) if hist: historyManager.writeFile( historyManager.getChangesHistoryPath(versionDir), hist) historyManager.writeFile(historyManager.getKeyPath(versionDir), body.get('key')) except Exception as e: response.setdefault('error', 1) response.setdefault('message', e.args[0]) response.setdefault('error', 0) return HttpResponse(json.dumps(response), content_type='application/json', status=200 if response['error'] == 0 else 500)
def downloadhistory(request): try: fileName = fileUtils.getFileName( request.GET['fileName']) # get the file name userAddress = request.GET.get('userAddress') if request.GET.get( 'userAddress') else request file = fileUtils.getFileName(request.GET['file']) version = fileUtils.getFileName(request.GET['ver']) isEmbedded = request.GET.get('dmode') if (jwtManager.isEnabled() and isEmbedded == None): jwtHeader = 'Authorization' if config.DOC_SERV_JWT_HEADER is None or config.DOC_SERV_JWT_HEADER == '' else config.DOC_SERV_JWT_HEADER token = request.headers.get(jwtHeader) if token: token = token[len('Bearer '):] try: body = jwtManager.decode(token) except Exception: return HttpResponse('JWT validation failed', status=403) else: return HttpResponse('JWT validation failed', status=403) filePath = docManager.getHistoryPath(fileName, file, version, userAddress) response = docManager.download(filePath) # download this file return response except Exception: response = {} response.setdefault('error', 'File not found') return HttpResponse(json.dumps(response), content_type='application/json', status=404)
def getHistoryObject(storagePath, filename, docKey, docUrl, req): histDir = getHistoryDir(storagePath) version = getFileVersion(histDir) if version > 0: hist = [] histData = {} for i in range(1, version + 1): obj = {} dataObj = {} prevVerDir = getVersionDir(histDir, i - 1) verDir = getVersionDir(histDir, i) try: key = docKey if i == version else readFile(getKeyPath(verDir)) obj['key'] = key obj['version'] = i dataObj['key'] = key dataObj['version'] = i if i == 1: meta = getMeta(storagePath) if meta: obj['created'] = meta['created'] obj['user'] = { 'id': meta['uid'], 'name': meta['uname'] } dataObj['url'] = docUrl if i == version else getPrevUri( filename, i, fileUtils.getFileExt(filename), req) if i > 1: changes = json.loads( readFile(getChangesHistoryPath(prevVerDir))) change = changes['changes'][0] obj['changes'] = changes['changes'] obj['serverVersion'] = changes['serverVersion'] obj['created'] = change['created'] obj['user'] = change['user'] prev = histData[str(i - 2)] prevInfo = {'key': prev['key'], 'url': prev['url']} dataObj['previous'] = prevInfo dataObj['changesUrl'] = getZipUri(filename, i - 1, req) if jwtManager.isEnabled(): dataObj['token'] = jwtManager.encode(dataObj) hist.append(obj) histData[str(i - 1)] = dataObj except Exception: return {} histObj = {'currentVersion': version, 'history': hist} return {'history': histObj, 'historyData': histData} return {}
def getHistoryObject(storagePath, filename, docKey, docUrl, req): histDir = getHistoryDir(storagePath) version = getFileVersion(histDir) if version > 0: # if the file was modified (the file version is greater than 0) hist = [] histData = {} for i in range(1, version + 1): # run through all the file versions obj = {} dataObj = {} prevVerDir = getVersionDir( histDir, i - 1) # get the path to the previous file version verDir = getVersionDir(histDir, i) # get the path to the given file version try: key = docKey if i == version else readFile( getKeyPath(verDir)) # get document key obj['key'] = key obj['version'] = i dataObj['fileType'] = fileUtils.getFileExt(filename)[1:] dataObj['key'] = key dataObj['version'] = i if i == 1: # check if the version number is equal to 1 meta = getMeta(storagePath) # get meta data of this file if meta: # write meta information to the object (user information and creation date) obj['created'] = meta['created'] obj['user'] = { 'id': meta['uid'], 'name': meta['uname'] } dataObj['url'] = docUrl if i == version else getPublicHistUri( filename, i, "prev" + fileUtils.getFileExt(filename), req) # write file url to the data object if i > 1: # check if the version number is greater than 1 (the file was modified) changes = json.loads( readFile(getChangesHistoryPath(prevVerDir)) ) # get the path to the changes.json file change = changes['changes'][0] obj['changes'] = changes[ 'changes'] if change else None # write information about changes to the object obj['serverVersion'] = changes['serverVersion'] obj['created'] = change['created'] if change else None obj['user'] = change['user'] if change else None prev = histData[str( i - 2 )] # get the history data from the previous file version prevInfo = { # write key and url information about previous file version 'fileType': prev['fileType'], 'key': prev['key'], 'url': prev['url'] } dataObj[ 'previous'] = prevInfo # write information about previous file version to the data object dataObj['changesUrl'] = getPublicHistUri( filename, i - 1, "diff.zip", req ) # write the path to the diff.zip archive with differences in this file version if jwtManager.isEnabled(): dataObj['token'] = jwtManager.encode(dataObj) hist.append(obj) # add object dictionary to the hist list histData[str( i - 1 )] = dataObj # write data object information to the history data except Exception: return {} histObj = { # write history information about the current file version to the history object 'currentVersion': version, 'history': hist } return {'history': histObj, 'historyData': histData} return {}
def edit(request): filename = request.GET['filename'] ext = fileUtils.getFileExt(filename) fileUri = docManager.getFileUri(filename, request) docKey = docManager.generateFileKey(filename, request) fileType = fileUtils.getFileType(filename) user = users.getUserFromReq(request) edMode = request.GET.get('mode') if request.GET.get('mode') else 'edit' canEdit = docManager.isCanEdit(ext) mode = 'edit' if canEdit & (edMode != 'view') else 'view' edType = request.GET.get('type') if request.GET.get('type') else 'desktop' lang = request.COOKIES.get('ulang') if request.COOKIES.get( 'ulang') else 'en' storagePath = docManager.getStoragePath(filename, request) meta = historyManager.getMeta(storagePath) infObj = None if (meta): infObj = {'author': meta['uname'], 'created': meta['created']} else: infObj = { 'author': 'Me', 'created': datetime.today().strftime('%d.%m.%Y %H:%M:%S') } edConfig = { 'type': edType, 'documentType': fileType, 'document': { 'title': filename, 'url': fileUri, 'fileType': ext[1:], 'key': docKey, 'info': infObj, 'permissions': { 'comment': (edMode != 'view') & (edMode != 'fillForms') & (edMode != 'embedded') & (edMode != "blockcontent"), 'download': True, 'edit': canEdit & ((edMode == 'edit') | (edMode == 'filter') | (edMode == "blockcontent")), 'fillForms': (edMode != 'view') & (edMode != 'comment') & (edMode != 'embedded') & (edMode != "blockcontent"), 'modifyFilter': edMode != 'filter', 'modifyContentControl': edMode != "blockcontent", 'review': (edMode == 'edit') | (edMode == 'review') } }, 'editorConfig': { 'mode': mode, 'lang': lang, 'callbackUrl': docManager.getCallbackUrl(filename, request), 'user': { 'id': user['uid'], 'name': user['uname'] }, 'embedded': { 'saveUrl': fileUri, 'embedUrl': fileUri, 'shareUrl': fileUri, 'toolbarDocked': 'top' }, 'customization': { 'about': True, 'feedback': True, 'goback': { 'url': config.EXAMPLE_DOMAIN } } } } if jwtManager.isEnabled(): edConfig['token'] = jwtManager.encode(edConfig) hist = historyManager.getHistoryObject(storagePath, filename, docKey, fileUri, request) context = { 'cfg': json.dumps(edConfig), 'history': json.dumps(hist['history']) if 'history' in hist else None, 'historyData': json.dumps(hist['historyData']) if 'historyData' in hist else None, 'fileType': fileType, 'apiUrl': config.DOC_SERV_API_URL } return render(request, 'editor.html', context)
def edit(request): filename = fileUtils.getFileName(request.GET['filename']) ext = fileUtils.getFileExt(filename) fileUri = docManager.getFileUri(filename, True, request) fileUriUser = docManager.getDownloadUrl( filename, request) + "&dmode=emb" if os.path.isabs( config.STORAGE_PATH) else docManager.getFileUri( filename, False, request) docKey = docManager.generateFileKey(filename, request) fileType = fileUtils.getFileType(filename) user = users.getUserFromReq(request) # get user edMode = request.GET.get('mode') if request.GET.get( 'mode' ) else 'edit' # get the editor mode: view/edit/review/comment/fillForms/embedded (the default mode is edit) canEdit = docManager.isCanEdit( ext) # check if the file with this extension can be edited if (((not canEdit) and edMode == 'edit') or edMode == 'fillForms') and docManager.isCanFillForms(ext): edMode = 'fillForms' canEdit = True submitForm = edMode == 'fillForms' and user.id == 'uid-1' and False # if the Submit form button is displayed or hidden mode = 'edit' if canEdit & ( edMode != 'view' ) else 'view' # if the file can't be edited, the mode is view types = ['desktop', 'mobile', 'embedded'] edType = request.GET.get('type') if request.GET.get( 'type' ) in types else 'desktop' # get the editor type: embedded/mobile/desktop (the default type is desktop) lang = request.COOKIES.get('ulang') if request.COOKIES.get( 'ulang' ) else 'en' # get the editor language (the default language is English) storagePath = docManager.getStoragePath(filename, request) meta = historyManager.getMeta(storagePath) # get the document meta data infObj = None actionData = request.GET.get( 'actionLink' ) # get the action data that will be scrolled to (comment or bookmark) actionLink = json.loads(actionData) if actionData else None templatesImageUrl = docManager.getTemplateImageUrl( fileType, request) # templates image url in the "From Template" section createUrl = docManager.getCreateUrl(edType, request) templates = [{ 'image': '', 'title': 'Blank', 'url': createUrl }, { 'image': templatesImageUrl, 'title': 'With sample content', 'url': createUrl + '&sample=true' }] if (meta): # if the document meta data exists, infObj = { # write author and creation time parameters to the information object 'owner': meta['uname'], 'uploaded': meta['created'] } else: # otherwise, write current meta information to this object infObj = { 'owner': 'Me', 'uploaded': datetime.today().strftime('%d.%m.%Y %H:%M:%S') } infObj['favorite'] = user.favorite # specify the document config edConfig = { 'type': edType, 'documentType': fileType, 'document': { 'title': filename, 'url': docManager.getDownloadUrl(filename, request), 'fileType': ext[1:], 'key': docKey, 'info': infObj, 'permissions': { # the permission for the document to be edited and downloaded or not 'comment': (edMode != 'view') & (edMode != 'fillForms') & (edMode != 'embedded') & (edMode != "blockcontent"), 'copy': 'copy' not in user.deniedPermissions, 'download': 'download' not in user.deniedPermissions, 'edit': canEdit & ((edMode == 'edit') | (edMode == 'view') | (edMode == 'filter') | (edMode == "blockcontent")), 'print': 'print' not in user.deniedPermissions, 'fillForms': (edMode != 'view') & (edMode != 'comment') & (edMode != 'embedded') & (edMode != "blockcontent"), 'modifyFilter': edMode != 'filter', 'modifyContentControl': edMode != "blockcontent", 'review': canEdit & ((edMode == 'edit') | (edMode == 'review')), 'reviewGroups': user.reviewGroups, 'commentGroups': user.commentGroups, 'userInfoGroups': user.userInfoGroups } }, 'editorConfig': { 'actionLink': actionLink, 'mode': mode, 'lang': lang, 'callbackUrl': docManager.getCallbackUrl( filename, request), # absolute URL to the document storage service 'createUrl': createUrl if user.id != 'uid-0' else None, 'templates': templates if user.templates else None, 'user': { # the user currently viewing or editing the document 'id': user.id if user.id != 'uid-0' else None, 'name': user.name, 'group': user.group }, 'embedded': { # the parameters for the embedded document type 'saveUrl': fileUriUser, # the absolute URL that will allow the document to be saved onto the user personal computer 'embedUrl': fileUriUser, # the absolute URL to the document serving as a source file for the document embedded into the web page 'shareUrl': fileUriUser, # the absolute URL that will allow other users to share this document 'toolbarDocked': 'top' # the place for the embedded viewer toolbar (top or bottom) }, 'customization': { # the parameters for the editor interface 'about': True, # the About section display 'comments': True, 'feedback': True, # the Feedback & Support menu button display 'forcesave': False, # adds the request for the forced file saving to the callback handler 'submitForm': submitForm, # if the Submit form button is displayed or not 'goback': { # settings for the Open file location menu button and upper right corner button 'url': docManager.getServerUrl( False, request ) # the absolute URL to the website address which will be opened when clicking the Open file location menu button } } } } # an image which will be inserted into the document dataInsertImage = { 'fileType': 'png', 'url': docManager.getServerUrl(True, request) + 'static/images/logo.png' } # a document which will be compared with the current document dataCompareFile = { 'fileType': 'docx', 'url': docManager.getServerUrl(True, request) + 'static/sample.docx' } # recipient data for mail merging dataMailMergeRecipients = { 'fileType': 'csv', 'url': docManager.getServerUrl(True, request) + 'csv' } # users data for mentions usersForMentions = users.getUsersForMentions(user.id) if jwtManager.isEnabled(): # if the secret key to generate token exists edConfig['token'] = jwtManager.encode( edConfig) # encode the edConfig object into a token dataInsertImage['token'] = jwtManager.encode( dataInsertImage) # encode the dataInsertImage object into a token dataCompareFile['token'] = jwtManager.encode( dataCompareFile) # encode the dataCompareFile object into a token dataMailMergeRecipients['token'] = jwtManager.encode( dataMailMergeRecipients ) # encode the dataMailMergeRecipients object into a token hist = historyManager.getHistoryObject(storagePath, filename, docKey, fileUri, request) # get the document history context = { # the data that will be passed to the template 'cfg': json.dumps(edConfig), # the document config in json format 'history': json.dumps(hist['history']) if 'history' in hist else None, # the information about the current version 'historyData': json.dumps(hist['historyData']) if 'historyData' in hist else None, # the information about the previous document versions if they exist 'fileType': fileType, # the file type of the document (text, spreadsheet or presentation) 'apiUrl': config.DOC_SERV_SITE_URL + config.DOC_SERV_API_URL, # the absolute URL to the api 'dataInsertImage': json.dumps(dataInsertImage) [1:len(json.dumps(dataInsertImage)) - 1], # the image which will be inserted into the document 'dataCompareFile': dataCompareFile, # document which will be compared with the current document 'dataMailMergeRecipients': json.dumps(dataMailMergeRecipients), # recipient data for mail merging 'usersForMentions': json.dumps(usersForMentions) if user.id != 'uid-0' else None } return render( request, 'editor.html', context) # execute the "editor.html" template with context data
def edit(request): filename = fileUtils.getFileName(request.GET['filename']) ext = fileUtils.getFileExt(filename) fileUri = docManager.getFileUri(filename, True, request) fileUriUser = docManager.getFileUri(filename, False, request) docKey = docManager.generateFileKey(filename, request) fileType = fileUtils.getFileType(filename) user = users.getUserFromReq(request) userGroup = None reviewGroups = None if (user['uid'] == 'uid-2'): userGroup = 'group-2' reviewGroups = ['group-2', ''] if (user['uid'] == 'uid-3'): userGroup = 'group-3' reviewGroups = ['group-2'] edMode = request.GET.get('mode') if request.GET.get('mode') else 'edit' canEdit = docManager.isCanEdit(ext) submitForm = canEdit & ((edMode == 'edit') | (edMode == 'fillForms')) mode = 'edit' if canEdit & (edMode != 'view') else 'view' edType = request.GET.get('type') if request.GET.get('type') else 'desktop' lang = request.COOKIES.get('ulang') if request.COOKIES.get( 'ulang') else 'en' storagePath = docManager.getStoragePath(filename, request) meta = historyManager.getMeta(storagePath) infObj = None actionData = request.GET.get('actionLink') actionLink = json.loads(actionData) if actionData else None if (meta): infObj = {'owner': meta['uname'], 'uploaded': meta['created']} else: infObj = { 'owner': 'Me', 'uploaded': datetime.today().strftime('%d.%m.%Y %H:%M:%S') } infObj['favorite'] = request.COOKIES.get( 'uid') == 'uid-2' if request.COOKIES.get('uid') else None edConfig = { 'type': edType, 'documentType': fileType, 'document': { 'title': filename, 'url': fileUri, 'fileType': ext[1:], 'key': docKey, 'info': infObj, 'permissions': { 'comment': (edMode != 'view') & (edMode != 'fillForms') & (edMode != 'embedded') & (edMode != "blockcontent"), 'download': True, 'edit': canEdit & ((edMode == 'edit') | (edMode == 'filter') | (edMode == "blockcontent")), 'fillForms': (edMode != 'view') & (edMode != 'comment') & (edMode != 'embedded') & (edMode != "blockcontent"), 'modifyFilter': edMode != 'filter', 'modifyContentControl': edMode != "blockcontent", 'review': (edMode == 'edit') | (edMode == 'review'), 'reviewGroups': reviewGroups } }, 'editorConfig': { 'actionLink': actionLink, 'mode': mode, 'lang': lang, 'callbackUrl': docManager.getCallbackUrl(filename, request), 'user': { 'id': user['uid'], 'name': None if user['uid'] == 'uid-0' else user['uname'], 'group': userGroup }, 'embedded': { 'saveUrl': fileUriUser, 'embedUrl': fileUriUser, 'shareUrl': fileUriUser, 'toolbarDocked': 'top' }, 'customization': { 'about': True, 'feedback': True, 'forcesave': False, 'submitForm': submitForm, 'goback': { 'url': docManager.getServerUrl(False, request) } } } } dataInsertImage = { 'fileType': 'png', 'url': docManager.getServerUrl(True, request) + 'static/images/logo.png' } dataCompareFile = { 'fileType': 'docx', 'url': docManager.getServerUrl(True, request) + 'static/sample.docx' } dataMailMergeRecipients = { 'fileType': 'csv', 'url': docManager.getServerUrl(True, request) + 'csv' } if jwtManager.isEnabled(): edConfig['token'] = jwtManager.encode(edConfig) dataInsertImage['token'] = jwtManager.encode(dataInsertImage) dataCompareFile['token'] = jwtManager.encode(dataCompareFile) dataMailMergeRecipients['token'] = jwtManager.encode( dataMailMergeRecipients) hist = historyManager.getHistoryObject(storagePath, filename, docKey, fileUri, request) context = { 'cfg': json.dumps(edConfig), 'history': json.dumps(hist['history']) if 'history' in hist else None, 'historyData': json.dumps(hist['historyData']) if 'historyData' in hist else None, 'fileType': fileType, 'apiUrl': config.DOC_SERV_SITE_URL + config.DOC_SERV_API_URL, 'dataInsertImage': json.dumps(dataInsertImage)[1:len(json.dumps(dataInsertImage)) - 1], 'dataCompareFile': dataCompareFile, 'dataMailMergeRecipients': json.dumps(dataMailMergeRecipients) } return render(request, 'editor.html', context)