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 *     Olivier Grisel <ogrisel@nuxeo.com>
018 *     Antoine Taillefer <ataillefer@nuxeo.com>
019 */
020package org.nuxeo.drive.service.impl;
021
022import static org.nuxeo.ecm.platform.query.nxql.CoreQueryDocumentPageProvider.CORE_SESSION_PROPERTY;
023
024import java.io.Serializable;
025import java.security.Principal;
026import java.util.ArrayList;
027import java.util.Calendar;
028import java.util.Collections;
029import java.util.HashMap;
030import java.util.HashSet;
031import java.util.LinkedHashSet;
032import java.util.List;
033import java.util.Map;
034import java.util.Set;
035import java.util.TimeZone;
036import java.util.TreeSet;
037
038import org.apache.commons.logging.Log;
039import org.apache.commons.logging.LogFactory;
040import org.nuxeo.common.utils.Path;
041import org.nuxeo.drive.service.FileSystemChangeFinder;
042import org.nuxeo.drive.service.FileSystemChangeSummary;
043import org.nuxeo.drive.service.FileSystemItemChange;
044import org.nuxeo.drive.service.NuxeoDriveEvents;
045import org.nuxeo.drive.service.NuxeoDriveManager;
046import org.nuxeo.drive.service.SynchronizationRoots;
047import org.nuxeo.drive.service.TooManyChangesException;
048import org.nuxeo.ecm.collections.api.CollectionConstants;
049import org.nuxeo.ecm.collections.api.CollectionManager;
050import org.nuxeo.ecm.core.api.CoreInstance;
051import org.nuxeo.ecm.core.api.CoreSession;
052import org.nuxeo.ecm.core.api.DocumentModel;
053import org.nuxeo.ecm.core.api.DocumentNotFoundException;
054import org.nuxeo.ecm.core.api.DocumentRef;
055import org.nuxeo.ecm.core.api.DocumentSecurityException;
056import org.nuxeo.ecm.core.api.IdRef;
057import org.nuxeo.ecm.core.api.IterableQueryResult;
058import org.nuxeo.ecm.core.api.NuxeoException;
059import org.nuxeo.ecm.core.api.PathRef;
060import org.nuxeo.ecm.core.api.UnrestrictedSessionRunner;
061import org.nuxeo.ecm.core.api.event.CoreEventConstants;
062import org.nuxeo.ecm.core.api.repository.RepositoryManager;
063import org.nuxeo.ecm.core.api.security.SecurityConstants;
064import org.nuxeo.ecm.core.cache.Cache;
065import org.nuxeo.ecm.core.cache.CacheService;
066import org.nuxeo.ecm.core.event.Event;
067import org.nuxeo.ecm.core.event.EventService;
068import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
069import org.nuxeo.ecm.core.query.sql.NXQL;
070import org.nuxeo.ecm.platform.audit.service.NXAuditEventsService;
071import org.nuxeo.ecm.platform.ec.notification.NotificationConstants;
072import org.nuxeo.ecm.platform.query.api.PageProvider;
073import org.nuxeo.ecm.platform.query.api.PageProviderService;
074import org.nuxeo.ecm.platform.query.nxql.NXQLQueryBuilder;
075import org.nuxeo.runtime.api.Framework;
076import org.nuxeo.runtime.model.ComponentContext;
077import org.nuxeo.runtime.model.ComponentInstance;
078import org.nuxeo.runtime.model.DefaultComponent;
079
080/**
081 * Manage list of NuxeoDrive synchronization roots and devices for a given nuxeo user.
082 */
083public class NuxeoDriveManagerImpl extends DefaultComponent implements NuxeoDriveManager {
084
085    private static final Log log = LogFactory.getLog(NuxeoDriveManagerImpl.class);
086
087    public static final String CHANGE_FINDER_EP = "changeFinder";
088
089    public static final String NUXEO_DRIVE_FACET = "DriveSynchronized";
090
091    public static final String DRIVE_SUBSCRIPTIONS_PROPERTY = "drv:subscriptions";
092
093    public static final String DOCUMENT_CHANGE_LIMIT_PROPERTY = "org.nuxeo.drive.document.change.limit";
094
095    public static final TimeZone UTC = TimeZone.getTimeZone("UTC");
096
097    public static final String DRIVE_SYNC_ROOT_CACHE = "driveSyncRoot";
098
099    public static final String DRIVE_COLLECTION_SYNC_ROOT__MEMBER_CACHE = "driveCollectionSyncRootMember";
100
101    protected static final long COLLECTION_CONTENT_PAGE_SIZE = 1000L;
102
103    /**
104     * Cache holding the synchronization roots for a given user (first map key) and repository (second map key).
105     */
106    protected Cache syncRootCache;
107
108    /**
109     * Cache holding the collection sync root member ids for a given user (first map key) and repository (second map
110     * key).
111     */
112    protected Cache collectionSyncRootMemberCache;
113
114    protected static ChangeFinderRegistry changeFinderRegistry;
115
116    protected FileSystemChangeFinder changeFinder;
117
118    protected Cache getSyncRootCache() {
119        if (syncRootCache == null) {
120            syncRootCache = Framework.getService(CacheService.class).getCache(DRIVE_SYNC_ROOT_CACHE);
121        }
122        return syncRootCache;
123    }
124
125    protected Cache getCollectionSyncRootMemberCache() {
126        if (collectionSyncRootMemberCache == null) {
127            collectionSyncRootMemberCache = Framework.getService(CacheService.class)
128                                                     .getCache(DRIVE_COLLECTION_SYNC_ROOT__MEMBER_CACHE);
129        }
130        return collectionSyncRootMemberCache;
131    }
132
133    protected void clearCache() {
134        log.debug("Invalidating synchronization root cache and collection sync root member cache for all users");
135        if (getSyncRootCache() != null) {
136            syncRootCache.invalidateAll();
137        }
138        if (getCollectionSyncRootMemberCache() != null) {
139            collectionSyncRootMemberCache.invalidateAll();
140        }
141    }
142
143    @Override
144    public void invalidateSynchronizationRootsCache(String userName) {
145        if (log.isDebugEnabled()) {
146            log.debug("Invalidating synchronization root cache for user: " + userName);
147        }
148        getSyncRootCache().invalidate(userName);
149    }
150
151    @Override
152    public void invalidateCollectionSyncRootMemberCache(String userName) {
153        if (log.isDebugEnabled()) {
154            log.debug("Invalidating collection sync root member cache for user: " + userName);
155        }
156        getCollectionSyncRootMemberCache().invalidate(userName);
157    }
158
159    @Override
160    public void invalidateCollectionSyncRootMemberCache() {
161        log.debug("Invalidating collection sync root member cache for all users");
162        getCollectionSyncRootMemberCache().invalidateAll();
163    }
164
165    @Override
166    public void registerSynchronizationRoot(Principal principal, final DocumentModel newRootContainer,
167            CoreSession session) {
168        final String userName = principal.getName();
169        // If new root is child of a sync root, ignore registration, except for
170        // the 'Locally Edited' collection: it is under the personal workspace
171        // and we want to allow both the personal workspace and the 'Locally
172        // Edited' collection to be registered as sync roots
173        Map<String, SynchronizationRoots> syncRoots = getSynchronizationRoots(principal);
174        SynchronizationRoots synchronizationRoots = syncRoots.get(session.getRepositoryName());
175        if (!NuxeoDriveManager.LOCALLY_EDITED_COLLECTION_NAME.equals(newRootContainer.getName())) {
176            for (String syncRootPath : synchronizationRoots.getPaths()) {
177                String syncRootPrefixedPath = syncRootPath + "/";
178
179                if (newRootContainer.getPathAsString().startsWith(syncRootPrefixedPath)) {
180                    // the only exception is when the right inheritance is
181                    // blocked
182                    // in the hierarchy
183                    boolean rightInheritanceBlockedInTheHierarchy = false;
184                    // should get only parents up to the sync root
185
186                    Path parentPath = newRootContainer.getPath().removeLastSegments(1);
187                    while (!"/".equals(parentPath.toString())) {
188                        String parentPathAsString = parentPath.toString() + "/";
189                        if (!parentPathAsString.startsWith(syncRootPrefixedPath)) {
190                            break;
191                        }
192                        PathRef parentRef = new PathRef(parentPathAsString);
193                        if (!session.hasPermission(principal, parentRef, SecurityConstants.READ)) {
194                            rightInheritanceBlockedInTheHierarchy = true;
195                            break;
196                        }
197                        parentPath = parentPath.removeLastSegments(1);
198                    }
199                    if (!rightInheritanceBlockedInTheHierarchy) {
200                        return;
201                    }
202                }
203            }
204        }
205
206        checkCanUpdateSynchronizationRoot(newRootContainer, session);
207
208        // Unregister any sub-folder of the new root, except for the 'Locally
209        // Edited' collection
210        String newRootPrefixedPath = newRootContainer.getPathAsString() + "/";
211        for (String existingRootPath : synchronizationRoots.getPaths()) {
212            if (!existingRootPath.endsWith(NuxeoDriveManager.LOCALLY_EDITED_COLLECTION_NAME)) {
213                if (existingRootPath.startsWith(newRootPrefixedPath)) {
214                    // Unregister the nested root sub-folder first
215                    PathRef ref = new PathRef(existingRootPath);
216                    if (session.exists(ref)) {
217                        DocumentModel subFolder = session.getDocument(ref);
218                        unregisterSynchronizationRoot(principal, subFolder, session);
219                    }
220                }
221            }
222        }
223
224        UnrestrictedSessionRunner runner = new UnrestrictedSessionRunner(session) {
225            @Override
226            public void run() {
227                if (!newRootContainer.hasFacet(NUXEO_DRIVE_FACET)) {
228                    newRootContainer.addFacet(NUXEO_DRIVE_FACET);
229                }
230
231                fireEvent(newRootContainer, session, NuxeoDriveEvents.ABOUT_TO_REGISTER_ROOT, userName);
232
233                @SuppressWarnings("unchecked")
234                List<Map<String, Object>> subscriptions = (List<Map<String, Object>>) newRootContainer.getPropertyValue(
235                        DRIVE_SUBSCRIPTIONS_PROPERTY);
236                boolean updated = false;
237                for (Map<String, Object> subscription : subscriptions) {
238                    if (userName.equals(subscription.get("username"))) {
239                        subscription.put("enabled", Boolean.TRUE);
240                        subscription.put("lastChangeDate", Calendar.getInstance(UTC));
241                        updated = true;
242                        break;
243                    }
244                }
245                if (!updated) {
246                    Map<String, Object> subscription = new HashMap<String, Object>();
247                    subscription.put("username", userName);
248                    subscription.put("enabled", Boolean.TRUE);
249                    subscription.put("lastChangeDate", Calendar.getInstance(UTC));
250                    subscriptions.add(subscription);
251                }
252                newRootContainer.setPropertyValue(DRIVE_SUBSCRIPTIONS_PROPERTY, (Serializable) subscriptions);
253                newRootContainer.putContextData(NXAuditEventsService.DISABLE_AUDIT_LOGGER, true);
254                newRootContainer.putContextData(NotificationConstants.DISABLE_NOTIFICATION_SERVICE, true);
255                newRootContainer.putContextData(CoreSession.SOURCE, "drive");
256                DocumentModel savedNewRootContainer = session.saveDocument(newRootContainer);
257                newRootContainer.putContextData(NXAuditEventsService.DISABLE_AUDIT_LOGGER, false);
258                newRootContainer.putContextData(NotificationConstants.DISABLE_NOTIFICATION_SERVICE, false);
259                fireEvent(savedNewRootContainer, session, NuxeoDriveEvents.ROOT_REGISTERED, userName);
260                session.save();
261            }
262        };
263        runner.runUnrestricted();
264
265        invalidateSynchronizationRootsCache(userName);
266        invalidateCollectionSyncRootMemberCache(userName);
267    }
268
269    @Override
270    public void unregisterSynchronizationRoot(Principal principal, final DocumentModel rootContainer,
271            CoreSession session) {
272        final String userName = principal.getName();
273        checkCanUpdateSynchronizationRoot(rootContainer, session);
274        UnrestrictedSessionRunner runner = new UnrestrictedSessionRunner(session) {
275            @Override
276            public void run() {
277                if (!rootContainer.hasFacet(NUXEO_DRIVE_FACET)) {
278                    rootContainer.addFacet(NUXEO_DRIVE_FACET);
279                }
280                fireEvent(rootContainer, session, NuxeoDriveEvents.ABOUT_TO_UNREGISTER_ROOT, userName);
281                @SuppressWarnings("unchecked")
282                List<Map<String, Object>> subscriptions = (List<Map<String, Object>>) rootContainer.getPropertyValue(
283                        DRIVE_SUBSCRIPTIONS_PROPERTY);
284                for (Map<String, Object> subscription : subscriptions) {
285                    if (userName.equals(subscription.get("username"))) {
286                        subscription.put("enabled", Boolean.FALSE);
287                        subscription.put("lastChangeDate", Calendar.getInstance(UTC));
288                        break;
289                    }
290                }
291                rootContainer.setPropertyValue(DRIVE_SUBSCRIPTIONS_PROPERTY, (Serializable) subscriptions);
292                rootContainer.putContextData(NXAuditEventsService.DISABLE_AUDIT_LOGGER, true);
293                rootContainer.putContextData(NotificationConstants.DISABLE_NOTIFICATION_SERVICE, true);
294                rootContainer.putContextData(CoreSession.SOURCE, "drive");
295                session.saveDocument(rootContainer);
296                rootContainer.putContextData(NXAuditEventsService.DISABLE_AUDIT_LOGGER, false);
297                rootContainer.putContextData(NotificationConstants.DISABLE_NOTIFICATION_SERVICE, false);
298                fireEvent(rootContainer, session, NuxeoDriveEvents.ROOT_UNREGISTERED, userName);
299                session.save();
300            }
301        };
302        runner.runUnrestricted();
303        invalidateSynchronizationRootsCache(userName);
304        invalidateCollectionSyncRootMemberCache(userName);
305    }
306
307    @Override
308    public Set<IdRef> getSynchronizationRootReferences(CoreSession session) {
309        Map<String, SynchronizationRoots> syncRoots = getSynchronizationRoots(session.getPrincipal());
310        return syncRoots.get(session.getRepositoryName()).getRefs();
311    }
312
313    @Override
314    public void handleFolderDeletion(IdRef deleted) {
315        clearCache();
316    }
317
318    protected void fireEvent(DocumentModel sourceDocument, CoreSession session, String eventName,
319            String impactedUserName) {
320        EventService eventService = Framework.getLocalService(EventService.class);
321        DocumentEventContext ctx = new DocumentEventContext(session, session.getPrincipal(), sourceDocument);
322        ctx.setProperty(CoreEventConstants.REPOSITORY_NAME, session.getRepositoryName());
323        ctx.setProperty(CoreEventConstants.SESSION_ID, session.getSessionId());
324        ctx.setProperty("category", NuxeoDriveEvents.EVENT_CATEGORY);
325        ctx.setProperty(NuxeoDriveEvents.IMPACTED_USERNAME_PROPERTY, impactedUserName);
326        Event event = ctx.newEvent(eventName);
327        eventService.fireEvent(event);
328    }
329
330    /**
331     * Uses the {@link AuditChangeFinder} to get the summary of document changes for the given user and last successful
332     * synchronization date.
333     * <p>
334     * The {@link #DOCUMENT_CHANGE_LIMIT_PROPERTY} Framework property is used as a limit of document changes to fetch
335     * from the audit logs. Default value is 1000. If {@code lastSuccessfulSync} is missing (i.e. set to a negative
336     * value), the filesystem change summary is empty but the returned sync date is set to the actual server timestamp
337     * so that the client can reuse it as a starting timestamp for a future incremental diff request.
338     */
339    @Override
340    public FileSystemChangeSummary getChangeSummary(Principal principal, Map<String, Set<IdRef>> lastSyncRootRefs,
341            long lastSuccessfulSync) {
342        Map<String, SynchronizationRoots> roots = getSynchronizationRoots(principal);
343        return getChangeSummary(principal, lastSyncRootRefs, roots, new HashMap<String, Set<String>>(),
344                lastSuccessfulSync, false);
345    }
346
347    /**
348     * Uses the {@link AuditChangeFinder} to get the summary of document changes for the given user and lower bound.
349     * <p>
350     * The {@link #DOCUMENT_CHANGE_LIMIT_PROPERTY} Framework property is used as a limit of document changes to fetch
351     * from the audit logs. Default value is 1000. If {@code lowerBound} is missing (i.e. set to a negative value), the
352     * filesystem change summary is empty but the returned upper bound is set to the greater event log id so that the
353     * client can reuse it as a starting id for a future incremental diff request.
354     */
355    @Override
356    public FileSystemChangeSummary getChangeSummaryIntegerBounds(Principal principal,
357            Map<String, Set<IdRef>> lastSyncRootRefs, long lowerBound) {
358        Map<String, SynchronizationRoots> roots = getSynchronizationRoots(principal);
359        Map<String, Set<String>> collectionSyncRootMemberIds = getCollectionSyncRootMemberIds(principal);
360        return getChangeSummary(principal, lastSyncRootRefs, roots, collectionSyncRootMemberIds, lowerBound, true);
361    }
362
363    protected FileSystemChangeSummary getChangeSummary(Principal principal, Map<String, Set<IdRef>> lastActiveRootRefs,
364            Map<String, SynchronizationRoots> roots, Map<String, Set<String>> collectionSyncRootMemberIds,
365            long lowerBound, boolean integerBounds) {
366        List<FileSystemItemChange> allChanges = new ArrayList<FileSystemItemChange>();
367        // Compute the list of all repositories to consider for the aggregate summary
368        Set<String> allRepositories = new TreeSet<String>();
369        allRepositories.addAll(roots.keySet());
370        allRepositories.addAll(lastActiveRootRefs.keySet());
371        allRepositories.addAll(collectionSyncRootMemberIds.keySet());
372        long syncDate;
373        long upperBound;
374        if (integerBounds) {
375            upperBound = changeFinder.getUpperBound(allRepositories);
376            // Truncate sync date to 0 milliseconds
377            syncDate = System.currentTimeMillis();
378            syncDate = syncDate - (syncDate % 1000);
379        } else {
380            upperBound = changeFinder.getCurrentDate();
381            syncDate = upperBound;
382        }
383        Boolean hasTooManyChanges = Boolean.FALSE;
384        int limit = Integer.parseInt(Framework.getProperty(DOCUMENT_CHANGE_LIMIT_PROPERTY, "1000"));
385        if (!allRepositories.isEmpty() && lowerBound >= 0 && upperBound > lowerBound) {
386            for (String repositoryName : allRepositories) {
387                try (CoreSession session = CoreInstance.openCoreSession(repositoryName, principal)) {
388                    // Get document changes
389                    Set<IdRef> lastRefs = lastActiveRootRefs.get(repositoryName);
390                    if (lastRefs == null) {
391                        lastRefs = Collections.emptySet();
392                    }
393                    SynchronizationRoots activeRoots = roots.get(repositoryName);
394                    if (activeRoots == null) {
395                        activeRoots = SynchronizationRoots.getEmptyRoots(repositoryName);
396                    }
397                    Set<String> repoCollectionSyncRootMemberIds = collectionSyncRootMemberIds.get(repositoryName);
398                    if (repoCollectionSyncRootMemberIds == null) {
399                        repoCollectionSyncRootMemberIds = Collections.emptySet();
400                    }
401                    List<FileSystemItemChange> changes;
402                    if (integerBounds) {
403                        changes = changeFinder.getFileSystemChangesIntegerBounds(session, lastRefs, activeRoots,
404                                repoCollectionSyncRootMemberIds, lowerBound, upperBound, limit);
405                    } else {
406                        changes = changeFinder.getFileSystemChanges(session, lastRefs, activeRoots, lowerBound,
407                                upperBound, limit);
408                    }
409                    allChanges.addAll(changes);
410                } catch (TooManyChangesException e) {
411                    hasTooManyChanges = Boolean.TRUE;
412                    allChanges.clear();
413                    break;
414                }
415            }
416        }
417
418        // Send back to the client the list of currently active roots to be able
419        // to efficiently detect root unregistration events for the next
420        // incremental change summary
421        Map<String, Set<IdRef>> activeRootRefs = new HashMap<String, Set<IdRef>>();
422        for (Map.Entry<String, SynchronizationRoots> rootsEntry : roots.entrySet()) {
423            activeRootRefs.put(rootsEntry.getKey(), rootsEntry.getValue().getRefs());
424        }
425        return new FileSystemChangeSummaryImpl(allChanges, activeRootRefs, syncDate, upperBound, hasTooManyChanges);
426    }
427
428    @Override
429    @SuppressWarnings("unchecked")
430    public Map<String, SynchronizationRoots> getSynchronizationRoots(Principal principal) {
431        String userName = principal.getName();
432        Map<String, SynchronizationRoots> syncRoots = (Map<String, SynchronizationRoots>) getSyncRootCache().get(
433                userName);
434        if (syncRoots == null) {
435            syncRoots = computeSynchronizationRoots(computeSyncRootsQuery(userName), principal);
436            getSyncRootCache().put(userName, (Serializable) syncRoots);
437        }
438        return syncRoots;
439    }
440
441    @Override
442    @SuppressWarnings("unchecked")
443    public Map<String, Set<String>> getCollectionSyncRootMemberIds(Principal principal) {
444        String userName = principal.getName();
445        Map<String, Set<String>> collSyncRootMemberIds = (Map<String, Set<String>>) getCollectionSyncRootMemberCache().get(
446                userName);
447        if (collSyncRootMemberIds == null) {
448            collSyncRootMemberIds = computeCollectionSyncRootMemberIds(principal);
449            getCollectionSyncRootMemberCache().put(userName, (Serializable) collSyncRootMemberIds);
450        }
451        return collSyncRootMemberIds;
452    }
453
454    @Override
455    public boolean isSynchronizationRoot(Principal principal, DocumentModel doc) {
456        String repoName = doc.getRepositoryName();
457        SynchronizationRoots syncRoots = getSynchronizationRoots(principal).get(repoName);
458        return syncRoots.getRefs().contains(doc.getRef());
459    }
460
461    protected Map<String, SynchronizationRoots> computeSynchronizationRoots(String query, Principal principal) {
462        Map<String, SynchronizationRoots> syncRoots = new HashMap<String, SynchronizationRoots>();
463        RepositoryManager repositoryManager = Framework.getLocalService(RepositoryManager.class);
464        for (String repositoryName : repositoryManager.getRepositoryNames()) {
465            try (CoreSession session = CoreInstance.openCoreSession(repositoryName, principal)) {
466                syncRoots.putAll(queryAndFetchSynchronizationRoots(session, query));
467            }
468        }
469        return syncRoots;
470    }
471
472    protected Map<String, SynchronizationRoots> queryAndFetchSynchronizationRoots(CoreSession session, String query) {
473        Map<String, SynchronizationRoots> syncRoots = new HashMap<String, SynchronizationRoots>();
474        Set<IdRef> references = new LinkedHashSet<IdRef>();
475        Set<String> paths = new LinkedHashSet<String>();
476        IterableQueryResult results = session.queryAndFetch(query, NXQL.NXQL);
477        try {
478            for (Map<String, Serializable> result : results) {
479                IdRef docRef = new IdRef(result.get("ecm:uuid").toString());
480                try {
481                    DocumentModel doc = session.getDocument(docRef);
482                    references.add(docRef);
483                    paths.add(doc.getPathAsString());
484                } catch (DocumentNotFoundException e) {
485                    log.warn(String.format(
486                            "Document %s not found, not adding it to the list of synchronization roots for user %s.",
487                            docRef, session.getPrincipal().getName()));
488                } catch (DocumentSecurityException e) {
489                    log.warn(String.format(
490                            "User %s cannot access document %s, not adding it to the list of synchronization roots.",
491                            session.getPrincipal().getName(), docRef));
492                }
493            }
494        } finally {
495            results.close();
496        }
497        SynchronizationRoots repoSyncRoots = new SynchronizationRoots(session.getRepositoryName(), paths, references);
498        syncRoots.put(session.getRepositoryName(), repoSyncRoots);
499        return syncRoots;
500    }
501
502    @SuppressWarnings("unchecked")
503    protected Map<String, Set<String>> computeCollectionSyncRootMemberIds(Principal principal) {
504        Map<String, Set<String>> collectionSyncRootMemberIds = new HashMap<String, Set<String>>();
505        PageProviderService pageProviderService = Framework.getLocalService(PageProviderService.class);
506        RepositoryManager repositoryManager = Framework.getLocalService(RepositoryManager.class);
507        for (String repositoryName : repositoryManager.getRepositoryNames()) {
508            Set<String> collectionMemberIds = new HashSet<String>();
509            try (CoreSession session = CoreInstance.openCoreSession(repositoryName, principal)) {
510                Map<String, Serializable> props = new HashMap<String, Serializable>();
511                props.put(CORE_SESSION_PROPERTY, (Serializable) session);
512                PageProvider<DocumentModel> collectionPageProvider = (PageProvider<DocumentModel>) pageProviderService.getPageProvider(
513                        CollectionConstants.ALL_COLLECTIONS_PAGE_PROVIDER, null, null, 0L, props);
514                List<DocumentModel> collections = collectionPageProvider.getCurrentPage();
515                for (DocumentModel collection : collections) {
516                    if (isSynchronizationRoot(principal, collection)) {
517                        PageProvider<DocumentModel> collectionMemberPageProvider = (PageProvider<DocumentModel>) pageProviderService.getPageProvider(
518                                CollectionConstants.COLLECTION_CONTENT_PAGE_PROVIDER, null,
519                                COLLECTION_CONTENT_PAGE_SIZE, 0L, props, collection.getId());
520                        List<DocumentModel> collectionMembers = collectionMemberPageProvider.getCurrentPage();
521                        for (DocumentModel collectionMember : collectionMembers) {
522                            collectionMemberIds.add(collectionMember.getId());
523                        }
524                    }
525                }
526                collectionSyncRootMemberIds.put(repositoryName, collectionMemberIds);
527            }
528        }
529        return collectionSyncRootMemberIds;
530    }
531
532    protected void checkCanUpdateSynchronizationRoot(DocumentModel newRootContainer, CoreSession session) {
533        // Cannot update a proxy or a version
534        if (newRootContainer.isProxy() || newRootContainer.isVersion()) {
535            throw new NuxeoException(String.format(
536                    "Document '%s' (%s) is not a suitable synchronization root"
537                            + " as it is either a readonly proxy or an archived version.",
538                    newRootContainer.getTitle(), newRootContainer.getRef()));
539        }
540    }
541
542    @Override
543    public FileSystemChangeFinder getChangeFinder() {
544        return changeFinder;
545    }
546
547    @Override
548    @Deprecated
549    public void setChangeFinder(FileSystemChangeFinder changeFinder) {
550        this.changeFinder = changeFinder;
551    }
552
553    /**
554     * @since 5.9.5
555     */
556    protected String computeSyncRootsQuery(String username) {
557        return String.format(
558                "SELECT ecm:uuid FROM Document WHERE %s/*1/username = %s"
559                        + " AND %s/*1/enabled = 1 AND ecm:currentLifeCycleState <> 'deleted' AND ecm:isVersion = 0 ORDER BY dc:title, dc:created DESC",
560                DRIVE_SUBSCRIPTIONS_PROPERTY, NXQLQueryBuilder.prepareStringLiteral(username, true, true),
561                DRIVE_SUBSCRIPTIONS_PROPERTY);
562    }
563
564    @Override
565    public void addToLocallyEditedCollection(CoreSession session, DocumentModel doc) {
566
567        // Add document to "Locally Edited" collection, creating if if not
568        // exists
569        CollectionManager cm = Framework.getService(CollectionManager.class);
570        DocumentModel userCollections = cm.getUserDefaultCollections(doc, session);
571        DocumentRef locallyEditedCollectionRef = new PathRef(userCollections.getPath().toString(),
572                LOCALLY_EDITED_COLLECTION_NAME);
573        DocumentModel locallyEditedCollection = null;
574        if (session.exists(locallyEditedCollectionRef)) {
575            locallyEditedCollection = session.getDocument(locallyEditedCollectionRef);
576            cm.addToCollection(locallyEditedCollection, doc, session);
577        } else {
578            cm.addToNewCollection(LOCALLY_EDITED_COLLECTION_NAME, "Documents locally edited with Nuxeo Drive", doc,
579                    session);
580            locallyEditedCollection = session.getDocument(locallyEditedCollectionRef);
581        }
582
583        // Register "Locally Edited" collection as a synchronization root if not
584        // already the case
585        Set<IdRef> syncRootRefs = getSynchronizationRootReferences(session);
586        if (!syncRootRefs.contains(new IdRef(locallyEditedCollection.getId()))) {
587            registerSynchronizationRoot(session.getPrincipal(), locallyEditedCollection, session);
588        }
589    }
590
591    /*------------------------ DefaultComponent -----------------------------*/
592    @Override
593    public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) {
594        if (CHANGE_FINDER_EP.equals(extensionPoint)) {
595            changeFinderRegistry.addContribution((ChangeFinderDescriptor) contribution);
596        } else {
597            log.error("Unknown extension point " + extensionPoint);
598        }
599    }
600
601    @Override
602    public void unregisterContribution(Object contribution, String extensionPoint, ComponentInstance contributor) {
603        if (CHANGE_FINDER_EP.equals(extensionPoint)) {
604            changeFinderRegistry.removeContribution((ChangeFinderDescriptor) contribution);
605        } else {
606            log.error("Unknown extension point " + extensionPoint);
607        }
608    }
609
610    @Override
611    public void activate(ComponentContext context) {
612        super.activate(context);
613        if (changeFinderRegistry == null) {
614            changeFinderRegistry = new ChangeFinderRegistry();
615        }
616    }
617
618    @Override
619    public void deactivate(ComponentContext context) {
620        super.deactivate(context);
621        changeFinderRegistry = null;
622    }
623
624    /**
625     * Sorts the contributed factories according to their order.
626     */
627    @Override
628    public void applicationStarted(ComponentContext context) {
629        initChangeFinder();
630    }
631
632    protected void initChangeFinder() {
633        changeFinder = changeFinderRegistry.changeFinder;
634    }
635
636}