示例#1
0
def fsDeleteFileView(fsPathString=''):
    """ Delete-file view.
        Permission checks are performed by the deleteFile filesystem call.
    """
    user = g.user
    db = dbGetDatabase()
    fileStorageDirectory = g.settings['system']['system_directories'][
        'fs_directory']['value']
    lsPath = splitPathString(fsPathString)
    boxPath, fileName = lsPath[:-1], lsPath[-1]
    parentBox = getBoxFromPath(db, boxPath, user)
    request._onErrorUrl = url_for(
        'lsView',
        lsPathString='/'.join(boxPath[1:]),
    )
    file = getFileFromParent(db, parentBox, fileName, user)
    fsDeleteQueue = deleteFile(
        db,
        parentBox,
        file,
        user,
        fileStorageDirectory=fileStorageDirectory,
    )
    flushFsDeleteQueue(fsDeleteQueue)
    return redirect(url_for(
        'lsView',
        lsPathString='/'.join(boxPath[1:]),
    ))
示例#2
0
def deleteBoxView(boxPathString=''):
    """RMBOX route."""
    user = g.user
    db = dbGetDatabase()
    fileStorageDirectory = g.settings['system']['system_directories'][
        'fs_directory']['value']
    boxPath = splitPathString(boxPathString)
    box = getBoxFromPath(db, boxPath, user)
    parentBox = getBoxFromPath(db, boxPath[:-1], user)
    request._onErrorUrl = url_for(
        'lsView',
        lsPathString='/'.join(boxPath[1:-1]),
    )
    #
    canDelete = canDeleteBox(db, box, parentBox, user)
    #
    if canDelete:
        if parentBox is None:
            # deletee box was root
            raise OstracionError('Cannot act on this object')
        else:
            if box is not None:
                fsDeleteQueue = deleteBox(
                    db,
                    box,
                    parentBox,
                    user,
                    fileStorageDirectory=fileStorageDirectory,
                )
                flushFsDeleteQueue(fsDeleteQueue)
            else:
                raise OstracionError('Box not accessible')
    else:
        raise OstracionError('Cannot delete this box')
    return redirect(url_for(
        'lsView',
        lsPathString='/'.join(boxPath[1:-1]),
    ))
示例#3
0
def calendarMakerGenerateCalendar():
    """
        Calendar actual generation view.
        Handles everything:
            building temporary image files
            driving the engine functions to make the pdf
            inserting the pdf in the box
            removing temporary files
    """
    user = g.user
    db = dbGetDatabase()
    request._onErrorUrl = url_for('calendarMakerIndexView', )
    #
    destBoxString = request.cookies.get('apps_calendarmaker_destbox')
    currentCalendar = cookiesToCurrentCalendar(request.cookies)
    coverImagePathString = currentCalendar.get('cover_image_path_string')
    calendarImagePaths = currentCalendar.get('image_path_strings', [])
    cProps = currentCalendar.get('properties', {})
    #
    if destBoxString is None:
        destBox = None
    else:
        destBoxPath = splitPathString(destBoxString)
        destBox = getBoxFromPath(db, destBoxPath, user)
    if coverImagePathString is None:
        coverImageFileObject = None
    else:
        coverImageFileObject = pathToFileStructure(
            db,
            user,
            coverImagePathString,
        )
    #
    calendarImages = [
        pathToFileStructure(db, user, imgPath)
        for imgPath in calendarImagePaths
    ]
    numRequiredImages = countMonths(
        cProps.get('year0'),
        cProps.get('month0'),
        cProps.get('year1'),
        cProps.get('month1'),
    )
    if (destBox is None or coverImageFileObject is None
            or any([ci is None
                    for ci in calendarImages]) or numRequiredImages is None
            or numRequiredImages > len(calendarImages)):
        raise OstracionError('Cannot generate calendar')
    else:
        fileStorageDirectory = g.settings['system']['system_directories'][
            'fs_directory']['value']
        # proceed with generation
        tempFileDirectory = g.settings['system']['system_directories'][
            'temp_directory']['value']
        mkDirP(tempFileDirectory)
        texImageCoverPath = duplicateImageForCalendar(
            fileIdToPath(
                coverImageFileObject['file'].file_id,
                fileStorageDirectory=fileStorageDirectory,
            ),
            os.path.join(
                tempFileDirectory, '%s.%s' % (
                    uuid4().hex,
                    admittedImageMimeTypeToExtension[
                        coverImageFileObject['file'].mime_type],
                )),
        )
        texImagePaths = [
            duplicateImageForCalendar(
                fileIdToPath(
                    imageFile['file'].file_id,
                    fileStorageDirectory=fileStorageDirectory,
                ),
                os.path.join(
                    tempFileDirectory, '%s.%s' % (
                        uuid4().hex,
                        admittedImageMimeTypeToExtension[
                            imageFile['file'].mime_type],
                    )),
            ) for imageFile in calendarImages
        ]
        #
        fsDeletionQueue = [texImageCoverPath] + texImagePaths
        createdPdfTitle = uuid4().hex
        createdFile, creationToDelete = makeCalendarPdf(
            cProps,
            texImagePaths,
            texImageCoverPath,
            tempFileDirectory,
            createdPdfTitle,
        )
        #
        if createdFile is not None:
            # name and description
            calDescription = 'Calendar %i/%i - %i/%i' % (
                cProps['month0'],
                cProps['year0'],
                cProps['month1'],
                cProps['year1'],
            )
            calFileName = findFirstAvailableObjectNameInBox(
                db,
                destBox,
                'calendar_',
                '.pdf',
            )
            # place the pdf in the box
            placeFSFileInBox(
                db,
                user,
                fileStorageDirectory,
                destBox,
                createdFile,
                calFileName,
                calDescription,
            )
            # flushing the delete queue
            flushFsDeleteQueue(fsDeletionQueue + creationToDelete +
                               [createdFile])
            # messaging the user
            successMessage = ('Calendar generated. Please find the file '
                              '"%s" in the destination box.') % calFileName
            flashMessage('Success', 'Info', successMessage)
            # redirecting user to box
            return redirect(url_for('lsView', lsPathString=destBoxString))
        else:
            # flushing the delete queue
            flushFsDeleteQueue(
                fsDeletionQueue + creationToDelete + [createdFile], )
            # messaging the user
            flashMessage('Error', 'Error', 'Could not generate the calendar')
            return redirect(url_for('calendarMakerIndexView'))
示例#4
0
def saveAndAnalyseFilesInBox(db,
                             files,
                             parentBox,
                             user,
                             thumbnailFormat,
                             fileStorageDirectory,
                             pastActionVerbForm='uploaded'):
    """ Save files and enrich them with type/mimetype,
        unless something fails - this handles overwrites
        (file-on-file) and blockades (file has same name as box)
    """
    #
    # checking for name clashes with boxes
    if any(
            isBoxNameUnderParentBox(db, parentBox, fName)
            for fName in (fObj['name'] for fObj in files)):
        raise OstracionError('Files cannot have the name of existing boxes')
    else:
        if not userHasPermission(db, user, parentBox.permissions, 'w'):
            raise OstracionError('User has no write permission on this box')
        else:
            userName = user.username
            fsDeletionQueue = []
            numReplacements = 0
            #
            for file in files:
                newFile = File(**recursivelyMergeDictionaries(
                    {k: v
                     for k, v in file.items() if k != 'fileObject'},
                    defaultMap={
                        'creator_username': userName,
                        'icon_file_id_username': userName,
                        'metadata_username': userName,
                        'editor_username': userName,
                        'textual_mode': 'plain',
                    },
                ))
                # are we overwriting a file?
                if isFileNameUnderParentBox(db, parentBox, newFile.name):
                    # delete the old file entry
                    # AND mark the file and its thumbnail
                    # (if any) for later deletion
                    prevFile = getFileFromParent(
                        db,
                        parentBox,
                        newFile.name,
                        user,
                    )
                    fsDeletionQueue += deleteFile(
                        db,
                        parentBox,
                        prevFile,
                        user,
                        fileStorageDirectory=fileStorageDirectory,
                        skipCommit=True,
                    )
                    numReplacements += 1
                #
                filePath = fileIdToPath(
                    newFile.file_id,
                    fileStorageDirectory=fileStorageDirectory,
                )
                file['fileObject'].save(filePath)
                #
                fileProperties = determineFileProperties(filePath)
                newFile.mime_type = fileProperties['file_mime_type']
                newFile.type = fileProperties['file_type']
                newFile.size = fileProperties['file_size']
                #
                if (thumbnailFormat is not None
                        and isImageMimeType(newFile.mime_type)):
                    # thumbnail preparation
                    fileThumbnailId, fileThumbnailMimeType = makeFileThumbnail(
                        newFile.file_id,
                        newFile.mime_type,
                        thumbnailFormat=thumbnailFormat,
                        fileStorageDirectory=fileStorageDirectory,
                    )
                    if fileThumbnailId is not None:
                        newFile.icon_file_id = fileThumbnailId
                        newFile.icon_mime_type = fileThumbnailMimeType
                #
                makeFileInParent(db, parentBox=parentBox, newFile=newFile)
            flushFsDeleteQueue(fsDeletionQueue)
            db.commit()
            return '%i file%s %s successfully%s.' % (
                len(files), '' if len(files) == 1 else 's', pastActionVerbForm,
                '' if numReplacements == 0 else
                (' (%i replaced)' % numReplacements))
示例#5
0
def storeFileAsThumbnail(db, fileToSave, mode, thumbnailFormat, targetItem,
                         parentBox, user, tempFileDirectory,
                         fileStorageDirectory):
    """ Handle setting/unsetting of thumbnail for various items
        (box,file,user,setting,user-as-admin).

        If a file to save is provided:
            store the file on the temp dir
            and if it is a valid thumbnail deal with its preparation
            and setting on the item, including possibly deletion of
            the previous thumbnail if necessary.
        if None is passed:
            simply delete any previous thumbnail if present

        Return True iff the (un/)setting is successful
    """
    # permission checks
    if mode == 'b':
        if not userHasPermission(db, user, targetItem.permissions, 'w'):
            raise OstracionError('User has no icon permission on this item')
    elif mode == 'f':
        if not userHasPermission(db, user, parentBox.permissions, 'w'):
            raise OstracionError('User has no icon permission on this item')
    elif mode == 'l':
        if not userHasPermission(db, user, parentBox.permissions, 'w'):
            raise OstracionError('User has no icon permission on this item')
    elif mode == 'u':
        if user.username != targetItem.username:
            raise OstracionError('Insufficient permissions')
    elif mode == 'au':
        if not userIsAdmin(db, user):
            raise OstracionError('Insufficient permissions')
    elif mode == 's':
        if not userIsAdmin(db, user):
            raise OstracionError('Insufficient permissions')
    #
    if fileToSave is not None:
        tempFileName = temporaryFileName(tempFileDirectory=tempFileDirectory)
        fileToSave.save(tempFileName)
        fileProperties = determineFileProperties(tempFileName)
    else:
        tempFileName = None
    #
    failures = False
    if tempFileName is None:
        thumbnailId = None
        thbMimeType = None
    else:
        if isImageMimeType(fileProperties['file_mime_type']):
            # make thumbnail and get the new ID
            thumbnailId, thbMimeType = makeTempFileIntoThumbnail(
                tempFileName,
                thumbnailFormat=thumbnailFormat,
                fileStorageDirectory=fileStorageDirectory,
            )
        else:
            failures = True
    if not failures:
        # un/set the icon ID
        if mode == 'f':
            fsDeleteQueue = updateFileThumbnail(
                db,
                targetItem,
                thumbnailId,
                thbMimeType,
                user,
                fileStorageDirectory=fileStorageDirectory)
        elif mode == 'l':
            fsDeleteQueue = updateLinkThumbnail(
                db,
                targetItem,
                thumbnailId,
                thbMimeType,
                user,
                fileStorageDirectory=fileStorageDirectory)
        elif mode == 'b':
            fsDeleteQueue = updateBoxThumbnail(
                db,
                targetItem,
                thumbnailId,
                thbMimeType,
                user,
                fileStorageDirectory=fileStorageDirectory)
        elif mode in {'u', 'au'}:
            fsDeleteQueue = updateUserThumbnail(
                db,
                targetItem,
                thumbnailId,
                thbMimeType,
                user,
                fileStorageDirectory=fileStorageDirectory)
        elif mode == 's':
            fsDeleteQueue = updateSettingThumbnail(
                db,
                targetItem,
                thumbnailId,
                thbMimeType,
                user,
                fileStorageDirectory=fileStorageDirectory)
        else:
            raise NotImplementedError('Unhandled storeFileAsThumbnail mode')
        flushFsDeleteQueue(fsDeleteQueue)
    #
    return not failures