001/*
002 * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Antoine Taillefer <ataillefer@nuxeo.com>
018 */
019package org.nuxeo.drive.hierarchy.permission.adapter;
020
021import java.util.ArrayList;
022import java.util.Collections;
023import java.util.Iterator;
024import java.util.List;
025import java.util.Map;
026import java.util.Set;
027
028import org.apache.commons.logging.Log;
029import org.apache.commons.logging.LogFactory;
030import org.nuxeo.drive.adapter.FileSystemItem;
031import org.nuxeo.drive.adapter.FolderItem;
032import org.nuxeo.drive.adapter.ScrollFileSystemItemList;
033import org.nuxeo.drive.adapter.impl.DocumentBackedFolderItem;
034import org.nuxeo.drive.service.NuxeoDriveManager;
035import org.nuxeo.drive.service.SynchronizationRoots;
036import org.nuxeo.ecm.core.api.CloseableCoreSession;
037import org.nuxeo.ecm.core.api.CoreInstance;
038import org.nuxeo.ecm.core.api.CoreSession;
039import org.nuxeo.ecm.core.api.DocumentModel;
040import org.nuxeo.ecm.core.api.IdRef;
041import org.nuxeo.ecm.core.api.security.SecurityConstants;
042import org.nuxeo.runtime.api.Framework;
043
044/**
045 * User workspace based implementation of the parent {@link FolderItem} of the user's synchronization roots.
046 *
047 * @author Antoine Taillefer
048 */
049public class UserSyncRootParentFolderItem extends DocumentBackedFolderItem {
050
051    private static final long serialVersionUID = 1L;
052
053    private static final Log log = LogFactory.getLog(UserSyncRootParentFolderItem.class);
054
055    protected boolean isUserWorkspaceSyncRoot = false;
056
057    public UserSyncRootParentFolderItem(String factoryName, DocumentModel doc, FolderItem parentItem, String folderName) {
058        this(factoryName, doc, parentItem, folderName, false);
059    }
060
061    public UserSyncRootParentFolderItem(String factoryName, DocumentModel doc, FolderItem parentItem,
062            String folderName, boolean relaxSyncRootConstraint) {
063        this(factoryName, doc, parentItem, folderName, relaxSyncRootConstraint, true);
064    }
065
066    public UserSyncRootParentFolderItem(String factoryName, DocumentModel doc, FolderItem parentItem,
067            String folderName, boolean relaxSyncRootConstraint, boolean getLockInfo) {
068        super(factoryName, parentItem, doc, relaxSyncRootConstraint, getLockInfo);
069        name = folderName;
070        canRename = false;
071        canDelete = false;
072        isUserWorkspaceSyncRoot = isUserWorkspaceSyncRoot(doc);
073        canCreateChild = isUserWorkspaceSyncRoot;
074        canScrollDescendants = isUserWorkspaceSyncRoot;
075    }
076
077    protected UserSyncRootParentFolderItem() {
078        // Needed for JSON deserialization
079    }
080
081    @Override
082    public void rename(String name) {
083        throw new UnsupportedOperationException("Cannot rename a virtual folder item.");
084    }
085
086    @Override
087    public void delete() {
088        throw new UnsupportedOperationException("Cannot delete a virtual folder item.");
089    }
090
091    @Override
092    public FileSystemItem move(FolderItem dest) {
093        throw new UnsupportedOperationException("Cannot move a virtual folder item.");
094    }
095
096    @Override
097    public List<FileSystemItem> getChildren() {
098
099        if (isUserWorkspaceSyncRoot) {
100            return super.getChildren();
101        } else {
102            List<FileSystemItem> children = new ArrayList<FileSystemItem>();
103            Map<String, SynchronizationRoots> syncRootsByRepo = Framework.getService(NuxeoDriveManager.class)
104                                                                         .getSynchronizationRoots(principal);
105            for (String repositoryName : syncRootsByRepo.keySet()) {
106                try (CloseableCoreSession session = CoreInstance.openCoreSession(repositoryName, principal)) {
107                    Set<IdRef> syncRootRefs = syncRootsByRepo.get(repositoryName).getRefs();
108                    Iterator<IdRef> syncRootRefsIt = syncRootRefs.iterator();
109                    while (syncRootRefsIt.hasNext()) {
110                        IdRef idRef = syncRootRefsIt.next();
111                        // TODO: ensure sync roots cache is up-to-date if ACL
112                        // change, for now need to check permission
113                        // See https://jira.nuxeo.com/browse/NXP-11146
114                        if (!session.hasPermission(idRef, SecurityConstants.READ)) {
115                            if (log.isDebugEnabled()) {
116                                log.debug(String.format(
117                                        "User %s has no READ access on synchronization root %s, not including it in children.",
118                                        session.getPrincipal().getName(), idRef));
119                            }
120                            continue;
121                        }
122                        DocumentModel doc = session.getDocument(idRef);
123                        // Filter by creator
124                        // TODO: allow filtering by dc:creator in
125                        // NuxeoDriveManager#getSynchronizationRoots(Principal
126                        // principal)
127                        if (session.getPrincipal().getName().equals(doc.getPropertyValue("dc:creator"))) {
128                            // NXP-19442: Avoid useless and costly call to DocumentModel#getLockInfo
129                            FileSystemItem child = getFileSystemItemAdapterService().getFileSystemItem(doc, this,
130                                    false, false, false);
131                            if (child == null) {
132                                if (log.isDebugEnabled()) {
133                                    log.debug(String.format(
134                                            "Synchronization root %s cannot be adapted as a FileSystemItem, maybe because user %s doesn't have the required permission on it (default required permission is ReadWrite). Not including it in children.",
135                                            idRef, session.getPrincipal().getName()));
136                                }
137                                continue;
138                            }
139                            if (log.isDebugEnabled()) {
140                                log.debug(String.format("Including synchronization root %s in children.", idRef));
141                            }
142                            children.add(child);
143                        }
144                    }
145                }
146            }
147            Collections.sort(children);
148            return children;
149        }
150    }
151
152    @Override
153    public ScrollFileSystemItemList scrollDescendants(String scrollId, int batchSize, long keepAlive) {
154        if (getCanScrollDescendants()) {
155            return super.scrollDescendants(scrollId, batchSize, keepAlive);
156        } else {
157            throw new UnsupportedOperationException(
158                    "Cannot scroll through the descendants of the user sync root parent folder item, please call getChildren() instead.");
159        }
160    }
161
162    private boolean isUserWorkspaceSyncRoot(DocumentModel doc) {
163        NuxeoDriveManager nuxeoDriveManager = Framework.getService(NuxeoDriveManager.class);
164        return nuxeoDriveManager.isSynchronizationRoot(principal, doc);
165    }
166
167}