001/*
002 *  Copyright 2024 Anyware Services
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 */
016package org.ametys.plugins.linkdirectory.repository;
017
018import org.apache.avalon.framework.service.ServiceException;
019import org.apache.avalon.framework.service.ServiceManager;
020import org.apache.avalon.framework.service.Serviceable;
021import org.apache.commons.lang3.StringUtils;
022
023import org.ametys.cms.repository.Content;
024import org.ametys.plugins.explorer.resources.Resource;
025import org.ametys.plugins.explorer.resources.actions.ExplorerResourcesDAO;
026import org.ametys.plugins.linkdirectory.DirectoryHelper;
027import org.ametys.plugins.linkdirectory.Link.LinkType;
028import org.ametys.plugins.repository.AmetysObject;
029import org.ametys.plugins.repository.AmetysObjectIterable;
030import org.ametys.plugins.repository.AmetysObjectResolver;
031import org.ametys.plugins.repository.AmetysRepositoryException;
032import org.ametys.runtime.plugin.component.AbstractLogEnabled;
033import org.ametys.web.repository.page.Page;
034import org.ametys.web.repository.site.Site;
035import org.ametys.web.repository.sitemap.Sitemap;
036import org.ametys.web.site.CopyUpdater;
037
038/**
039 * Update {@link DefaultLink} attribute targeting {@link AmetysObject} related to the original site
040 */
041public class LinksCopyUpdater extends AbstractLogEnabled implements CopyUpdater, Serviceable
042{
043    /** the ametys object resolver */
044    protected AmetysObjectResolver _resolver;
045    /** the directory helper */
046    protected DirectoryHelper _directoryHelper;
047    /** the explorer DAO */
048    protected ExplorerResourcesDAO _explorerDAO;
049
050    public void service(ServiceManager manager) throws ServiceException
051    {
052        _directoryHelper = (DirectoryHelper) manager.lookup(DirectoryHelper.ROLE);
053        _explorerDAO = (ExplorerResourcesDAO) manager.lookup(ExplorerResourcesDAO.ROLE);
054        _resolver = (AmetysObjectResolver) manager.lookup(AmetysObjectResolver.ROLE);
055    }
056    
057    public void updateSite(Site initialSite, Site createdSite)
058    {
059        try (AmetysObjectIterable<Sitemap> sitemaps = createdSite.getSitemaps())
060        {
061            for (Sitemap sitemap : sitemaps)
062            {
063                String allLinksQuery = _directoryHelper.getAllLinksQuery(createdSite.getName(), sitemap.getName());
064                try (AmetysObjectIterable<DefaultLink> links = _resolver.query(allLinksQuery))
065                {
066                    for (DefaultLink link : links)
067                    {
068                        if (link.getUrlType() == LinkType.PAGE)
069                        {
070                            link.setUrl(LinkType.PAGE, _getPage(link.getUrl(), initialSite, createdSite));
071                        }
072                        
073                        String pageId = link.getPage();
074                        if (StringUtils.isNotBlank(link.getPage()))
075                        {
076                            link.setPage(_getPage(pageId, initialSite, createdSite));
077                        }
078                        
079                        if ("resource".equals(link.getPictureType()))
080                        {
081                            link.setResourcePicture(_getResource(link.getResourcePictureId(), initialSite, createdSite));
082                        }
083                    }
084                }
085            }
086        }
087        
088        if (createdSite.needsSave())
089        {
090            createdSite.saveChanges();
091        }
092    }
093    
094    /**
095     * Get the updated page id.
096     * @param initialPageId the initial page id
097     * @param initialSite the initial site
098     * @param createdSite the newly created site
099     * @return the updated id.
100     */
101    protected String _getPage(String initialPageId, Site initialSite, Site createdSite)
102    {
103        try
104        {
105            Page initialPage = _resolver.resolveById(initialPageId);
106            // update only if the page was part of the initial site.
107            if (initialPage.getSite().equals(initialSite))
108            {
109                Sitemap createdSitemap = createdSite.getSitemap(initialPage.getSitemapName());
110                Page createdPage = createdSitemap.getChild(initialPage.getPathInSitemap());
111                return createdPage.getId();
112            }
113            else
114            {
115                return initialPageId;
116            }
117        }
118        catch (AmetysRepositoryException e)
119        {
120            getLogger().error("Failed to migrate link to page '{}' from  site '{}' to site '{}'", initialPageId, initialSite.getName(), createdSite.getName(), e);
121            return initialPageId;
122        }
123    }
124    
125    /**
126     * Get the updated resource id.
127     * @param initialResourceId the initial resource id
128     * @param initialSite the initial site
129     * @param createdSite the newly created site
130     * @return the updated id
131     */
132    protected String _getResource(String initialResourceId, Site initialSite, Site createdSite)
133    {
134        try
135        {
136            Resource initialResource = _resolver.resolveById(initialResourceId);
137            // update only if the resource was part of the initial site resources
138            if (initialResource.getPath().startsWith(initialSite.getRootResources().getPath()))
139            {
140                Resource newResource = createdSite.getRootResources().getChild(initialResource.getResourcePath().substring(1));
141                return newResource.getId();
142            }
143            else
144            {
145                return initialResourceId;
146            }
147        }
148        catch (AmetysRepositoryException e)
149        {
150            getLogger().error("Failed to migrate link picture '{}' from  site '{}' to site '{}'", initialResourceId, initialSite.getName(), createdSite.getName(), e);
151            return initialResourceId;
152        }
153    }
154    
155    public void updatePage(Site initialSite, Site createdSite, Page page)
156    {
157        // Nothing to do
158    }
159    
160    public void updateContent(Site initialSite, Site createdSite, Content initialContent, Content createdContent)
161    {
162        // Nothing to do
163    }
164}