Beispiel #1
0
def makeLinkView(fsPathString=''):
    """Generate-new-link route."""
    user = g.user
    form = EditLinkForm()
    db = dbGetDatabase()
    boxPath = splitPathString(fsPathString)
    request._onErrorUrl = url_for(
        'lsView',
        lsPathString='/'.join(boxPath[1:]),
    )
    parentBoxPath = boxPath
    parentBox = getBoxFromPath(db, parentBoxPath, user)
    if form.validate_on_submit():
        linkName = secure_filename(form.linkname.data)
        linkTitle = form.linktitle.data
        linkDescription = form.linkdescription.data
        linkTarget = form.linktarget.data
        openInNewWindow = form.openinnewwindow.data
        savingResult = makeLinkInParent(
            db=db,
            user=user,
            parentBox=parentBox,
            date=datetime.now(),
            linkName=linkName,
            linkTitle=linkTitle,
            linkDescription=linkDescription,
            linkTarget=linkTarget,
            linkOptions={
                'open_in_new_window': openInNewWindow,
            },
        )
        return redirect(url_for(
            'lsView',
            lsPathString=fsPathString,
        ))
    else:
        pathBCrumbs = makeBreadCrumbs(
            parentBoxPath,
            g,
            appendedItems=[{
                'kind': 'link',
                'target': None,
                'name': 'New link',
            }],
        )
        form.openinnewwindow.data = True
        return render_template(
            'editlink.html',
            form=form,
            user=user,
            breadCrumbs=pathBCrumbs,
            iconUrl=makeSettingImageUrl(g, 'app_images', 'external_link'),
            pageTitle='New link',
            pageSubtitle='Create a new link in "%s"' %
            (describeBoxTitle(parentBox)),
        )
Beispiel #2
0
def _resolveUponPermissions(db, richObject, user, mode, score):
    """ Verify and validate the input (rich-)box/file
        against permissions, and return either a similar structure
        or a None if permissions turn out to be blocking.

        (
            richObject has keys "path" and "box/file",
            mode = 'file' / 'box'
        )
    """
    pBox = getBoxFromPath(db, richObject['path'][:-1], user)
    if mode == 'box':
        nBox = getBoxFromPath(db, richObject['path'], user)
        if nBox is not None and pBox is not None:
            return {
                'path':
                richObject['path'][1:],
                'box':
                nBox,
                'actions':
                prepareBoxActions(db,
                                  nBox,
                                  richObject['path'][1:],
                                  pBox,
                                  user,
                                  prepareParentButton=True),
                'info':
                prepareBoxInfo(db, nBox),
                'parentInfo':
                'Parent box: "%s"' % (describeBoxTitle(pBox), ),
                'object_type':
                mode,
                'score':
                score,
            }
        else:
            return None
    elif mode == 'file':
        if pBox is not None:
            nFile = getFileFromParent(db, pBox, richObject['path'][-1], user)
            if nFile is not None:
                return {
                    'path':
                    richObject['path'][1:],
                    'file':
                    nFile,
                    'actions':
                    prepareFileActions(db,
                                       nFile,
                                       richObject['path'][1:],
                                       pBox,
                                       user,
                                       prepareParentButton=True),
                    'info':
                    prepareFileInfo(db, nFile),
                    'nice_size':
                    formatBytesSize(nFile.size),
                    'parentInfo':
                    'Container box: "%s"' % (describeBoxTitle(pBox), ),
                    'object_type':
                    mode,
                    'score':
                    score,
                }
            else:
                return None
        else:
            return None
    elif mode == 'link':
        if pBox is not None:
            nLink = getLinkFromParent(db, pBox, richObject['path'][-1], user)
            if nLink is not None:
                return {
                    'path':
                    richObject['path'][1:],
                    'link':
                    nLink,
                    'actions':
                    prepareLinkActions(db,
                                       nLink,
                                       richObject['path'][1:],
                                       pBox,
                                       user,
                                       prepareParentButton=True),
                    'info':
                    prepareLinkInfo(db, nLink),
                    'parentInfo':
                    'Container box: "%s"' % (describeBoxTitle(pBox), ),
                    'object_type':
                    mode,
                    'score':
                    score,
                }
            else:
                return None
        else:
            return None
    else:
        raise NotImplementedError('Unknown _resolveUponPermissions mode "%s"' %
                                  mode)
Beispiel #3
0
def fsMoveFileView(quotedFilePath):
    """Move-file, view 1/2: select destination box."""
    user = g.user
    db = dbGetDatabase()
    # first we find the file
    fsPathString = urllib.parse.unquote_plus(quotedFilePath)
    lsPath = splitPathString(fsPathString)
    boxPath, fileName = lsPath[:-1], lsPath[-1]
    parentBox = getBoxFromPath(db, boxPath, user)
    file = getFileFromParent(db, parentBox, fileName, user)
    # next we prepare the selectable destinations
    rootBox = getRootBox(db)

    def rbPredicate(richBox, idToAvoid=parentBox.box_id):
        return all((richBox['box'].box_id != idToAvoid,
                    userHasPermission(db, user, richBox['box'].permissions,
                                      'w')))

    dstBoxTree = collectTreeFromBox(
        db,
        rootBox,
        user,
        admitFiles=False,
        fileOrBoxEnricher=lambda richBox: {
            'obj_path': urllib.parse.quote_plus('/'.join(richBox['path'])),
        },
        predicate=rbPredicate,
    )
    #
    maxDepth = getMaxTreeDepth(dstBoxTree)
    colorShadeMap = prepareColorShadeMap(
        g.settings['color']['navigation_colors']['file']['value'],
        g.settings['color']['tree_shade_colors']['shade_treeview_pickbox']
        ['value'],
        numShades=1 + maxDepth,
    )
    destinationsExist = treeAny(
        dstBoxTree,
        property=lambda node: node['predicate'],
    )
    #
    return render_template(
        'dirtreeview.html',
        tree=dstBoxTree if destinationsExist else None,
        mode='file_move',
        object_quoted_path=quotedFilePath,
        colorShadeMap=colorShadeMap,
        user=user,
        iconUrl=makeSettingImageUrl(g, 'app_images', 'move'),
        pageTitle='Select file destination',
        pageSubtitle=(('Choose the box to which file "%s" shall '
                       'be moved from "%s"') % (
                           file.name,
                           describeBoxTitle(parentBox),
                       )),
        actions=None,
        backToUrl=None if destinationsExist else url_for(
            'lsView',
            lsPathString='/'.join(boxPath[1:]),
        ),
        breadCrumbs=makeBreadCrumbs(
            boxPath,
            g,
            appendedItems=[{
                'kind': 'file',
                'target': file,
            }, {
                'kind': 'link',
                'target': None,
                'name': 'Move file',
            }],
        ),
    )
Beispiel #4
0
def fsMoveBoxView(quotedSrcBox):
    """
        Move-box-phase-1 route: where the source box is selected
        (and then in offering the choose-dest-box it is put in the URL
        for calling phase two).
    """
    user = g.user
    db = dbGetDatabase()
    # first we find the box
    bxPathString = urllib.parse.unquote_plus(quotedSrcBox)
    boxPath = splitPathString(bxPathString)
    parentBox = getBoxFromPath(db, boxPath[:-1], user)
    request._onErrorUrl = url_for(
        'lsView',
        lsPathString='/'.join(boxPath[1:-1]),
    )
    box = getBoxFromPath(db, boxPath, user)
    if not canDeleteBox(db, box, parentBox, user):
        raise OstracionWarning('Cannot act on this object')
    # next we prepare the selectable destinations
    rootBox = getRootBox(db)

    def rbPredicate(richBox, _box=box, _srcBox=parentBox):
        _dstBox = richBox['box']
        if _box.parent_id != _dstBox.box_id:
            if all(userHasPermission(db, user, _dstBox.permissions, prm)
                    for prm in {'w', 'c'}):
                if not isNameUnderParentBox(db, _dstBox, _box.box_name):
                    if not isAncestorBoxOf(db, _box, _dstBox):
                        return True
        return False

    dstBoxTree = collectTreeFromBox(
        db,
        rootBox,
        user,
        admitFiles=False,
        fileOrBoxEnricher=lambda richBox: {
            'obj_path': urllib.parse.quote_plus('/'.join(richBox['path'])),
        },
        predicate=rbPredicate,
    )
    #
    maxDepth = getMaxTreeDepth(dstBoxTree)
    colorShadeMap = prepareColorShadeMap(
        g.settings['color']['navigation_colors']['box']['value'],
        g.settings['color']['tree_shade_colors'][
            'shade_treeview_pickbox']['value'],
        numShades=1 + maxDepth,
    )
    destinationsExist = treeAny(
        dstBoxTree,
        property=lambda node: node['predicate'],
    )
    #
    return render_template(
        'dirtreeview.html',
        tree=dstBoxTree if destinationsExist else None,
        mode='box_move',
        object_quoted_path=quotedSrcBox,
        colorShadeMap=colorShadeMap,
        user=user,
        iconUrl=makeSettingImageUrl(g, 'app_images', 'move'),
        pageTitle='Select box destination',
        pageSubtitle=('Choose the box to which box "%s" '
                      'shall be moved from "%s"') % (
                            describeBoxTitle(box),
                            describeBoxTitle(parentBox),
                     ),
        actions=None,
        backToUrl=(None
                   if destinationsExist
                   else url_for(
                        'lsView',
                        lsPathString='/'.join(boxPath[1:]))),
        breadCrumbs=makeBreadCrumbs(
            boxPath,
            g,
            appendedItems=[
                {
                    'kind': 'link',
                    'target': None,
                    'name': 'Move box',
                }
            ],
        ),
    )
Beispiel #5
0
def makeTicketBoxUploadView(boxPathString=''):
    """Make-upload-ticket (to a box) route."""
    user = g.user
    db = dbGetDatabase()
    boxPath = splitPathString(boxPathString)
    box = getBoxFromPath(db, boxPath, user)
    request._onErrorUrl = url_for(
        'lsView',
        lsPathString='/'.join(boxPath[1:]),
    )
    #
    if userHasPermission(db, user, box.permissions, 'w'):
        #
        pathBCrumbs = makeBreadCrumbs(
            boxPath,
            g,
            appendedItems=[
                {
                    'name': '(create upload ticket)',
                    'kind': 'link',
                    'target': url_for(
                        'makeTicketBoxUploadView',
                        boxPathString=boxPathString,
                    ),
                    'link': False,
                },
            ],
        )
        form = generateFsTicketForm(
            fileModePresent=False,
            settings=g.settings,
        )
        if form.validate_on_submit():
            magicLink = dbMakeUploadTicket(
                db=db,
                ticketName=form.name.data,
                validityHours=transformIfNotEmpty(
                    form.validityhours.data,
                    int,
                ),
                multiplicity=transformIfNotEmpty(
                    form.multiplicity.data,
                    int,
                ),
                ticketMessage=transformIfNotEmpty(
                    form.ticketmessage.data,
                ),
                box=box,
                boxPath=boxPath,
                user=user,
                urlRoot=request.url_root,
                settings=g.settings,
            )
            flashMessage(
                'Success',
                'Done',
                ('Upload ticket generated. Give the recipient '
                 'the following magic link:'),
                pillText=magicLink,
            )
            return redirect(url_for(
                'lsView',
                lsPathString='/'.join(boxPath[1:]),
            ))
        else:
            defaultName = 'Upload-To-%s' % (
                describeBoxName(box)
            )
            form.name.data = applyDefault(form.name.data, defaultName)
            form.ticketmessage.data = applyDefault(
                form.ticketmessage.data,
                'Please, upload files to this box',
            )
            maxValidityHours = g.settings['behaviour']['behaviour_tickets'][
                'max_ticket_validityhours']['value']
            form.validityhours.data = applyDefault(
                form.validityhours.data,
                str(maxValidityHours) if maxValidityHours is not None else '',
            )
            maxMultiplicity = g.settings['behaviour']['behaviour_tickets'][
                'max_ticket_multiplicity']['value']
            form.multiplicity.data = applyDefault(
                form.multiplicity.data,
                str(maxMultiplicity) if maxMultiplicity is not None else '',
            )
            return render_template(
                'fsticket.html',
                pageTitle='Create public upload ticket',
                pageSubtitle=('Recipient(s) of the ticket will be able to '
                              'upload to "%s", without an account, on '
                              'your behalf.') % (
                                    describeBoxTitle(box)
                               ),
                baseMultiplicityCaption='Number of granted file uploads',
                user=user,
                form=form,
                iconUrl=makeSettingImageUrl(g, 'app_images', 'upload_ticket'),
                showFileMode=False,
                breadCrumbs=pathBCrumbs,
            )
        #
    else:
        raise OstracionError('Insufficient permissions')
Beispiel #6
0
def makeTicketBoxGalleryView(boxPathString=''):
    """Make-gallery-ticket-of-box route."""
    user = g.user
    db = dbGetDatabase()
    boxPath = splitPathString(boxPathString)
    box = getBoxFromPath(db, boxPath, user)
    request._onErrorUrl = url_for('lsView', lsPathString='/'.join(boxPath[1:]))
    #
    pathBCrumbs = makeBreadCrumbs(
        boxPath,
        g,
        appendedItems=[
            {
                'name': '(create gallery ticket)',
                'kind': 'link',
                'target': url_for(
                    'makeTicketBoxGalleryView',
                    boxPathString=boxPathString,
                ),
                'link': False,
            },
        ],
    )
    form = generateFsTicketForm(
        fileModePresent=False,
        settings=g.settings,
    )
    if form.validate_on_submit():
        magicLink = dbMakeGalleryTicket(
            db=db,
            ticketName=form.name.data,
            validityHours=transformIfNotEmpty(
                form.validityhours.data,
                int
            ),
            multiplicity=transformIfNotEmpty(
                form.multiplicity.data,
                int
            ),
            ticketMessage=transformIfNotEmpty(
                form.ticketmessage.data
            ),
            box=box,
            boxPath=boxPath,
            user=user,
            urlRoot=request.url_root,
            settings=g.settings,
        )
        flashMessage(
            'Success',
            'Done',
            ('Gallery ticket generated. Give the recipient '
             'the following magic link:'),
            pillText=magicLink,
        )
        return redirect(url_for(
            'lsView',
            lsPathString='/'.join(boxPath[1:]),
        ))
    else:
        defaultName = 'Gallery-View-%s' % describeBoxName(box)
        form.name.data = applyDefault(form.name.data, defaultName)
        form.ticketmessage.data = applyDefault(
            form.ticketmessage.data,
            'Please, look at this gallery',
        )
        maxValidityHours = g.settings['behaviour']['behaviour_tickets'][
            'max_ticket_validityhours']['value']
        form.validityhours.data = applyDefault(
            form.validityhours.data,
            str(maxValidityHours) if maxValidityHours is not None else '',
        )
        maxMultiplicity = g.settings['behaviour']['behaviour_tickets'][
            'max_ticket_multiplicity']['value']
        form.multiplicity.data = applyDefault(
            form.multiplicity.data,
            str(maxMultiplicity) if maxMultiplicity is not None else '',
        )
        return render_template(
            'fsticket.html',
            pageTitle='Create public gallery-view ticket',
            pageSubtitle=('Recipient(s) of the ticket will be able to view '
                          'files (and not contained boxes) in "%s", without '
                          'an account, as a gallery. If setting a number of '
                          'accesses, keep in mind that every single-file view'
                          ' counts toward the total accesses.') % (
                describeBoxTitle(box)
            ),
            baseMultiplicityCaption='Number of granted accesses',
            user=user,
            form=form,
            iconUrl=makeSettingImageUrl(g, 'app_images', 'gallery_ticket'),
            showFileMode=False,
            breadCrumbs=pathBCrumbs,
        )
Beispiel #7
0
def makeBoxView(parentBoxPathString=''):
    """MKBOX-in-a-box- route."""
    user = g.user
    form = makeMakeBoxForm('Create')()
    db = dbGetDatabase()
    parentBoxPath = splitPathString(parentBoxPathString)
    parentBox = getBoxFromPath(db, parentBoxPath, user)
    boxNiceName = describeBoxTitle(parentBox)
    request._onErrorUrl = url_for(
        'lsView',
        lsPathString='/'.join(parentBoxPath),
    )
    if form.validate_on_submit():
        #
        boxName = form.boxname.data
        boxDescription = form.boxdescription.data
        boxTitle = form.boxtitle.data
        #
        newBox = Box(
            box_name=boxName,
            title=boxTitle,
            description=boxDescription,
            icon_file_id='',
            nature='box',
            parent_id=parentBox.box_id,
            date=datetime.now(),
            creator_username=user.username,
            icon_file_id_username=user.username,
            metadata_username=user.username,
        )
        makeBoxInParent(db, parentBox, newBox, user, skipCommit=True)
        if parentBox.box_id == '':
            # the new box is a direct child of root:
            # act according to the localhost-mode policy setting
            rootChildAnonPerms = g.settings['behaviour'][
                'behaviour_permissions'][
                'rootchild_box_anonymous_permissions']['value']
            rcPermSet = {
                k: 1 if rootChildAnonPerms[i] != '_' else 0
                for i, k in enumerate('rwc')
            }
            # the above is a bit of a hack which parses the char
            # of the setting 'r__', 'rwc', ...
            rootChildBRP = BoxRolePermission(
                box_id=newBox.box_id,
                role_class='system',
                role_id='anonymous',
                **rcPermSet,
            )
            dbInsertBoxRolePermission(
                db,
                rootChildBRP,
                user,
                skipCommit=True,
            )
        #
        db.commit()
        additionalLsItems = [boxName]
        #
        return redirect(url_for(
            'lsView',
            lsPathString='/'.join(parentBoxPath[1:] + additionalLsItems),
        ))
    else:
        pathBCrumbs = makeBreadCrumbs(
            parentBoxPath,
            g,
            appendedItems=[{
                'kind': 'link',
                'target': None,
                'name': 'Make box',
            }],
        )
        return render_template(
            'makebox.html',
            form=form,
            user=user,
            breadCrumbs=pathBCrumbs,
            iconUrl=makeSettingImageUrl(g, 'app_images', 'standard_box'),
            pageTitle='Create box in "%s"' % boxNiceName,
            pageSubtitle='Name and title are mandatory',
        )
Beispiel #8
0
def lsView(lsPathString=''):
    """LS-of-a-box route, additionally with 'tasks' if viewing root."""
    user = g.user
    lsPath = splitPathString(lsPathString)
    db = dbGetDatabase()
    thisBox = getBoxFromPath(db, lsPath, user)
    boxPath = lsPath[1:]
    #
    showBoxPermissionToAll = g.settings['behaviour']['behaviour_permissions'][
        'show_permission']['value']
    #
    if thisBox is not None:
        request._onErrorUrl = url_for('lsView')
        if thisBox.box_id == '':
            tasks = prepareRootTasks(db, g, user)
        else:
            tasks = []
        boxes = [
            {
                'box': box,
                'path': boxPath + [box.box_name],
                'info': prepareBoxInfo(db, box),
                'actions': prepareBoxActions(
                    db,
                    box,
                    boxPath + [box.box_name],
                    thisBox,
                    user
                ),
            }
            for box in sorted(
                (
                    b
                    for b in getBoxesFromParent(db, thisBox, user)
                    if b is not None
                ),
                key=lambda b: (b.box_name.lower(), b.box_name),
            )
            if box.box_id != ''
        ]
        files = [
            {
                'file': file,
                'path': boxPath + [file.name],
                'nice_size': formatBytesSize(file.size),
                'info': prepareFileInfo(db, file),
                'actions': prepareFileActions(
                    db,
                    file,
                    boxPath + [file.name],
                    thisBox,
                    user
                ),
            }
            for file in sorted(
                getFilesFromBox(db, thisBox),
                key=lambda f: (f.name.lower(), f.name),
            )
        ]
        links = [
            {
                'link': link,
                'path': boxPath + [link.name],
                'info': prepareLinkInfo(db, link),
                'actions': prepareLinkActions(
                    db,
                    link,
                    boxPath + [link.name],
                    thisBox,
                    user
                ),
            }
            for link in sorted(
                getLinksFromBox(db, thisBox),
                key=lambda l: (l.name.lower(), l.name),
            )
        ]
        #
        pathBCrumbs = makeBreadCrumbs(lsPath, g)
        boxNiceName = transformIfNotEmpty(thisBox.box_name)
        if thisBox.box_id == '':
            boxTitle, boxDescription = describeRootBoxCaptions(g)
        else:
            boxTitle = describeBoxTitle(thisBox)
            boxDescription = thisBox.description
        #
        boxActions = prepareBoxHeaderActions(
            db,
            thisBox,
            boxPath,
            user,
            g.settings,
            discardedActions=(
                set()
                if len(files) > 0
                else {'gallery_view', 'issue_gallery_ticket'}
            ),
        )
        showAdminToolsLink = userIsAdmin(db, user)
        if showBoxPermissionToAll or userIsAdmin(db, user):
            thisBoxPermissionAlgebra = calculateBoxPermissionAlgebra(
                thisBox.permissionHistory,
                thisBox.permissions,
            )
            #
            roleKeyToRoleMap = {
                r.roleKey(): r
                for r in dbGetAllRoles(db, user)
                if r.can_box != 0
            }
            structuredPermissionInfo = reformatBoxPermissionAlgebraIntoLists(
                thisBoxPermissionAlgebra,
                roleKeyToRoleMap,
            )
            #
            permissionInfo = {
                'powers': structuredPermissionInfo,
                'assignments': {
                    'edit_url': (
                        url_for(
                            'adminLsPermissionsView',
                            lsPathString='/'.join(boxPath),
                        )
                        if showAdminToolsLink
                        else None
                    ),
                    'native': [
                        {
                            'role_class': brp.role_class,
                            'role_id': brp.role_id,
                            'r': brp.r,
                            'w': brp.w,
                            'c': brp.c,
                            'role': roleKeyToRoleMap[(
                                brp.role_class,
                                brp.role_id,
                            )],
                        }
                        for brp in sorted(thisBox.listPermissions('native'))
                    ],
                    'inherited': [
                        {
                            'role_class': brp.role_class,
                            'role_id': brp.role_id,
                            'r': brp.r,
                            'w': brp.w,
                            'c': brp.c,
                            'role': roleKeyToRoleMap[(
                                brp.role_class,
                                brp.role_id,
                            )],
                        }
                        for brp in sorted(thisBox.listPermissions('inherited'))
                    ],
                },
            }
        else:
            permissionInfo = None
        #
        if len(boxes) + len(files) + len(links) > 0:
            foundCounts = [
                (len(boxes), 'box', 'boxes'),
                (len(files), 'file', 'files'),
                (len(links), 'link', 'links'),
            ]
            foundParts = pickSingularPluralSentences(
                foundCounts,
                keepZeroes=False,
            )
            boxChildrenCounter = colloquialJoinClauses(foundParts)
        else:
            boxChildrenCounter = 'no contents'
        #
        return render_template(
            'ls.html',
            user=user,
            thisBox=thisBox,
            boxTitle=boxTitle,
            boxNiceName=boxNiceName,
            boxDescription=boxDescription,
            pageTitle=boxNiceName,
            boxChildrenCounter=boxChildrenCounter,
            boxActions=boxActions,
            boxPath=boxPath,
            permissionInfo=permissionInfo,
            breadCrumbs=pathBCrumbs,
            tasks=tasks,
            boxes=boxes,
            files=files,
            links=links,
        )
    else:
        request._onErrorUrl = url_for(
            'lsView',
            lsPathString='/'.join(lsPath[1:-1]),
        )
        raise OstracionWarning(
            'Cannot access the specified box "%s"' % lsPath[-1]
        )
Beispiel #9
0
def makeTextFileView(fsPathString=''):
    """Generate-new-text-file route."""
    user = g.user
    form = MakeTextFileForm()
    db = dbGetDatabase()
    boxPath = splitPathString(fsPathString)
    request._onErrorUrl = url_for(
        'lsView',
        lsPathString='/'.join(boxPath[1:]),
    )
    fileStorageDirectory = g.settings['system']['system_directories'][
        'fs_directory']['value']
    parentBoxPath = boxPath
    parentBox = getBoxFromPath(db, parentBoxPath, user)
    if form.validate_on_submit():
        fileName = secure_filename(form.filename.data)
        savableFile = SavableTextFile('')
        filesToUpload = [
            {
                'box_id': parentBox.box_id,
                'name': fileName,
                'description': form.filedescription.data,
                'date': datetime.datetime.now(),
                'fileObject': savableFile,
            }
        ]
        makeThumbnails = g.settings['behaviour']['behaviour_appearance'][
            'extract_thumbnails']['value']
        savingResult = saveAndAnalyseFilesInBox(
            db=db,
            files=filesToUpload,
            parentBox=parentBox,
            user=user,
            fileStorageDirectory=fileStorageDirectory,
            thumbnailFormat='thumbnail' if makeThumbnails else None,
            pastActionVerbForm='created',
        )
        flashMessage('Success', 'Info', savingResult)
        return redirect(url_for(
            'editTextFileView',
            fsPathString='/'.join(parentBoxPath[1:] + [fileName]),
        ))
    else:
        pathBCrumbs = makeBreadCrumbs(
            parentBoxPath,
            g,
            appendedItems=[{
                'kind': 'link',
                'target': None,
                'name': 'New text',
            }],
        )
        return render_template(
            'maketextfile.html',
            form=form,
            user=user,
            breadCrumbs=pathBCrumbs,
            iconUrl=pickFileThumbnail('text/plain'),
            pageTitle='New text',
            pageSubtitle='Create a new text file in "%s"' % (
                describeBoxTitle(parentBox)
            ),
        )
Beispiel #10
0
def uploadMultipleFilesView(fsPathString=''):
    """Upload-several-files (to a box) route."""
    user = g.user
    form = UploadMultipleFilesForm()
    db = dbGetDatabase()
    boxPath = splitPathString(fsPathString)
    request._onErrorUrl = url_for(
        'lsView',
        lsPathString='/'.join(boxPath[1:]),
    )
    fileStorageDirectory = g.settings['system']['system_directories'][
        'fs_directory']['value']
    parentBoxPath = boxPath
    parentBox = getBoxFromPath(db, parentBoxPath, user)
    #
    if form.validate_on_submit():
        uploadedFiles = [
            uf
            for uf in request.files.getlist('files')
            if uf.filename != ''
        ]
        #
        filesToUpload = [
            {
                'box_id': parentBox.box_id,
                'name': secure_filename(uploadedFile.filename),
                'description': form.filesdescription.data,
                'date': datetime.datetime.now(),
                'fileObject': uploadedFile,
            }
            for uploadedFile in uploadedFiles
        ]
        makeThumbnails = g.settings['behaviour']['behaviour_appearance'][
            'extract_thumbnails']['value']
        savingResult = saveAndAnalyseFilesInBox(
            db=db,
            files=filesToUpload,
            parentBox=parentBox,
            user=user,
            fileStorageDirectory=fileStorageDirectory,
            thumbnailFormat='thumbnail' if makeThumbnails else None,
        )
        flashMessage('Success', 'Info', savingResult)
        return redirect(url_for(
            'lsView',
            lsPathString='/'.join(parentBoxPath[1:]),
        ))
    else:
        pathBCrumbs = makeBreadCrumbs(
            parentBoxPath,
            g,
            appendedItems=[{
                'kind': 'link',
                'target': None,
                'name': 'Multiple upload',
            }],
        )
        return render_template(
            'uploadmultiplefiles.html',
            form=form,
            user=user,
            breadCrumbs=pathBCrumbs,
            pageTitle='Upload new files',
            pageSubtitle='Upload new files to box "%s"' % (
                describeBoxTitle(parentBox)
            ),
            iconUrl=makeSettingImageUrl(g, 'app_images', 'multiple_upload')
        )