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.CoreInstance;
037import org.nuxeo.ecm.core.api.CoreSession;
038import org.nuxeo.ecm.core.api.DocumentModel;
039import org.nuxeo.ecm.core.api.IdRef;
040import org.nuxeo.ecm.core.api.security.SecurityConstants;
041import org.nuxeo.runtime.api.Framework;
042
043/**
044 * User workspace based implementation of the parent {@link FolderItem} of the user's synchronization roots.
045 *
046 * @author Antoine Taillefer
047 */
048public class UserSyncRootParentFolderItem extends DocumentBackedFolderItem {
049
050    private static final long serialVersionUID = 1L;
051
052    private static final Log log = LogFactory.getLog(UserSyncRootParentFolderItem.class);
053
054    protected boolean isUserWorkspaceSyncRoot = false;
055
056    public UserSyncRootParentFolderItem(String factoryName, DocumentModel doc, FolderItem parentItem, String folderName) {
057        this(factoryName, doc, parentItem, folderName, false);
058    }
059
060    public UserSyncRootParentFolderItem(String factoryName, DocumentModel doc, FolderItem parentItem,
061            String folderName, boolean relaxSyncRootConstraint) {
062        this(factoryName, doc, parentItem, folderName, relaxSyncRootConstraint, true);
063    }
064
065    public UserSyncRootParentFolderItem(String factoryName, DocumentModel doc, FolderItem parentItem,
066            String folderName, boolean relaxSyncRootConstraint, boolean getLockInfo) {
067        super(factoryName, parentItem, doc, relaxSyncRootConstraint, getLockInfo);
068        name = folderName;
069        canRename = false;
070        canDelete = false;
071        isUserWorkspaceSyncRoot = isUserWorkspaceSyncRoot(doc);
072        canCreateChild = isUserWorkspaceSyncRoot;
073        canScrollDescendants = isUserWorkspaceSyncRoot;
074    }
075
076    protected UserSyncRootParentFolderItem() {
077        // Needed for JSON deserialization
078    }
079
080    @Override
081    public void rename(String name) {
082        throw new UnsupportedOperationException("Cannot rename a virtual folder item.");
083    }
084
085    @Override
086    public void delete() {
087        throw new UnsupportedOperationException("Cannot delete a virtual folder item.");
088    }
089
090    @Override
091    public FileSystemItem move(FolderItem dest) {
092        throw new UnsupportedOperationException("Cannot move a virtual folder item.");
093    }
094
095    @Override
096    public List<FileSystemItem> getChildren() {
097
098        if (isUserWorkspaceSyncRoot) {
099            return super.getChildren();
100        } else {
101            List<FileSystemItem> children = new ArrayList<FileSystemItem>();
102            Map<String, SynchronizationRoots> syncRootsByRepo = Framework.getService(NuxeoDriveManager.class)
103                                                                         .getSynchronizationRoots(principal);
104            for (String repositoryName : syncRootsByRepo.keySet()) {
105                try (CoreSession session = CoreInstance.openCoreSession(repositoryName, principal)) {
106                    Set<IdRef> syncRootRefs = syncRootsByRepo.get(repositoryName).getRefs();
107                    Iterator<IdRef> syncRootRefsIt = syncRootRefs.iterator();
108                    while (syncRootRefsIt.hasNext()) {
109                        IdRef idRef = syncRootRefsIt.next();
110                        // TODO: ensure sync roots cache is up-to-date if ACL
111                        // change, for now need to check permission
112                        // See https://jira.nuxeo.com/browse/NXP-11146
113                        if (!session.hasPermission(idRef, SecurityConstants.READ)) {
114                            if (log.isDebugEnabled()) {
115                                log.debug(String.format(
116                                        "User %s has no READ access on synchronization root %s, not including it in children.",
117                                        session.getPrincipal().getName(), idRef));
118                            }
119                            continue;
120                        }
121                        DocumentModel doc = session.getDocument(idRef);
122                        // Filter by creator
123                        // TODO: allow filtering by dc:creator in
124                        // NuxeoDriveManager#getSynchronizationRoots(Principal
125                        // principal)
126                        if (session.getPrincipal().getName().equals(doc.getPropertyValue("dc:creator"))) {
127                            // NXP-19442: Avoid useless and costly call to DocumentModel#getLockInfo
128                            FileSystemItem child = getFileSystemItemAdapterService().getFileSystemItem(doc, this,
129                                    false, false, false);
130                            if (child == null) {
131                                if (log.isDebugEnabled()) {
132                                    log.debug(String.format(
133                                            "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.",
134                                            idRef, session.getPrincipal().getName()));
135                                }
136                                continue;
137                            }
138                            if (log.isDebugEnabled()) {
139                                log.debug(String.format("Including synchronization root %s in children.", idRef));
140                            }
141                            children.add(child);
142                        }
143                    }
144                }
145            }
146            Collections.sort(children);
147            return children;
148        }
149    }
150
151    @Override
152    public ScrollFileSystemItemList scrollDescendants(String scrollId, int batchSize, long keepAlive) {
153        if (getCanScrollDescendants()) {
154            return super.scrollDescendants(scrollId, batchSize, keepAlive);
155        } else {
156            throw new UnsupportedOperationException(
157                    "Cannot scroll through the descendants of the user sync root parent folder item, please call getChildren() instead.");
158        }
159    }
160
161    private boolean isUserWorkspaceSyncRoot(DocumentModel doc) {
162        NuxeoDriveManager nuxeoDriveManager = Framework.getService(NuxeoDriveManager.class);
163        return nuxeoDriveManager.isSynchronizationRoot(principal, doc);
164    }
165
166}