View Javadoc
1   /**
2    * This file Copyright (c) 2019 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.dam.app.action;
35  
36  import info.magnolia.dam.jcr.AssetNodeTypes;
37  import info.magnolia.jcr.util.NodeNameHelper;
38  import info.magnolia.jcr.util.NodeTypes;
39  import info.magnolia.jcr.util.NodeUtil;
40  import info.magnolia.ui.CloseHandler;
41  import info.magnolia.ui.api.action.ActionExecutionException;
42  import info.magnolia.ui.contentapp.action.CloseAction;
43  import info.magnolia.ui.datasource.jcr.JcrDatasource;
44  import info.magnolia.ui.editor.JcrBinaryHelper;
45  import info.magnolia.ui.datasource.optionlist.Option;
46  import info.magnolia.ui.ValueContext;
47  import info.magnolia.ui.editor.EditorView;
48  
49  import java.io.File;
50  import java.io.IOException;
51  import java.io.InputStream;
52  import java.util.Collections;
53  import java.util.List;
54  import java.util.Optional;
55  import java.util.stream.Collectors;
56  
57  import javax.inject.Inject;
58  import javax.jcr.Node;
59  import javax.jcr.RepositoryException;
60  
61  import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
62  import org.apache.commons.compress.archivers.zip.ZipFile;
63  import org.apache.commons.io.FilenameUtils;
64  import org.apache.commons.lang3.StringUtils;
65  import org.devlib.schmidt.imageinfo.ImageInfo;
66  
67  import com.vaadin.data.Binder;
68  import com.vaadin.data.BinderValidationStatus;
69  import com.vaadin.data.HasValue;
70  
71  /**
72   * Action which uploads assets.
73   */
74  public class UploadAssetsAction extends CloseAction<UploadAssetsActionDefinition> implements JcrBinaryHelper {
75  
76      private static final String BACKSLASH_DUMMY = "________backslash________";
77  
78      private final EditorView<Node> form;
79      private final ValueContext<Node> valueContext;
80      private final NodeNameHelper nodeNameHelper;
81      private final JcrDatasource jcrDatasource;
82  
83      @Inject
84      public UploadAssetsAction(UploadAssetsActionDefinition definition, CloseHandler closeHandler,
85                                EditorView<Node> form, ValueContext<Node> valueContext,
86                                NodeNameHelper nodeNameHelper, JcrDatasource jcrDatasource) {
87          super(definition, closeHandler);
88          this.form = form;
89          this.valueContext = valueContext;
90          this.nodeNameHelper = nodeNameHelper;
91          this.jcrDatasource = jcrDatasource;
92      }
93  
94      @Override
95      public void execute() throws ActionExecutionException {
96          Optional<File> file = getFile();
97          if (file.isPresent()) {
98              try {
99                  ZipFile zip = new ZipFile(file.get(), getEncoding());
100                 // We use the ant-1.6.5 zip package to workaround encoding issues of the sun implementation (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4244499)
101                 // For some reason, entries are not in the opposite order as how they appear in most tools - reversing here.
102                 // Note that java.util.zip does not show this behaviour, and ant-1.7.1 seems to enumerate entries in alphabetical or random order.
103                 // Another alternative might be http://truezip.dev.java.net
104                 final List zipEntries = Collections.list(zip.getEntries()).stream()
105                         .sorted((firstEntry, secondEntry) -> {
106                             if (firstEntry.isDirectory() != secondEntry.isDirectory()) {
107                                 return Boolean.compare(secondEntry.isDirectory(), firstEntry.isDirectory()); // order folders first
108                             } else {
109                                 return firstEntry.getName().compareTo(secondEntry.getName()); // order alphabetically
110                             }
111                         })
112                         .collect(Collectors.toList());
113 
114                 for (Object zipEntry : zipEntries) {
115                     ZipArchiveEntry entry = (ZipArchiveEntry) zipEntry;
116                     processEntry(zip, entry);
117                 }
118 
119                 getFolderNode().getSession().save();
120             } catch (IOException | RepositoryException e) {
121                 throw new ActionExecutionException(e);
122             }
123             super.execute();
124         }
125     }
126 
127     private void processEntry(org.apache.commons.compress.archivers.zip.ZipFile zip, ZipArchiveEntry entry) throws IOException, RepositoryException {
128         if (entry.getName().startsWith("__MACOSX")) {
129             return;
130         } else if (entry.getName().endsWith(".DS_Store")) {
131             return;
132         }
133         if (entry.isDirectory()) {
134             ensureFolder(entry);
135         } else {
136             handleFileEntry(zip, entry);
137         }
138     }
139 
140     private void handleFileEntry(ZipFile zip, ZipArchiveEntry entry) throws IOException, RepositoryException {
141         String fileName = entry.getName();
142         if (StringUtils.contains(fileName, "/")) {
143             fileName = StringUtils.substringAfterLast(fileName, "/");
144         }
145         try (InputStream stream = zip.getInputStream(entry);
146              InputStream streamForMetaDataDetection = zip.getInputStream(entry);
147              InputStream streamForMimeTypeDetection = zip.getInputStream(entry)
148         ) {
149             String folderPath = StringUtils.strip(extractEntryPath(entry), "/");
150             Node folder = getFolderNode();
151             if (StringUtils.isNotBlank(folderPath)) {
152                 folder = NodeUtil.createPath(folder, folderPath, NodeTypes.Folder.NAME);
153             }
154             Node asset = folder.addNode(fileName, AssetNodeTypes.Asset.NAME);
155             Node node = asset.addNode(AssetNodeTypes.AssetResource.RESOURCE_NAME, AssetNodeTypes.AssetResource.NAME);
156             node.setProperty(AssetNodeTypes.AssetResource.DATA, node.getSession().getValueFactory().createBinary(stream));
157             node.setProperty(AssetNodeTypes.AssetResource.FILENAME, fileName);
158             node.setProperty(AssetNodeTypes.AssetResource.EXTENSION, FilenameUtils.getExtension(fileName));
159             node.setProperty(AssetNodeTypes.AssetResource.MIMETYPE, TIKA.detect(streamForMimeTypeDetection));
160             ImageInfo imageInfo = new ImageInfo();
161             imageInfo.setInput(streamForMetaDataDetection);
162             imageInfo.check();
163             node.setProperty(AssetNodeTypes.AssetResource.HEIGHT, imageInfo.getHeight());
164             node.setProperty(AssetNodeTypes.AssetResource.WIDTH, imageInfo.getWidth());
165         }
166     }
167 
168     private Node getFolderNode() {
169         return valueContext.getSingle().orElse(this.jcrDatasource.getRoot());
170     }
171 
172     private void ensureFolder(ZipArchiveEntry entry) throws RepositoryException {
173         String path = extractEntryPath(entry);
174         NodeUtil.createPath(getFolderNode(), path, NodeTypes.Folder.NAME);
175     }
176 
177     private String extractEntryPath(ZipArchiveEntry entry) {
178         String entryName = entry.getName();
179         String path = (StringUtils.contains(entryName, "/")) ? StringUtils.substringBeforeLast(entryName, "/") : "/";
180         if (!path.startsWith("/")) {
181             path = "/" + path;
182         }
183         // make proper name, the path was already created
184         path = StringUtils.replace(path, "/", BACKSLASH_DUMMY);
185         path = nodeNameHelper.getValidatedName(path);
186         path = StringUtils.replace(path, BACKSLASH_DUMMY, "/");
187         return path;
188     }
189 
190     private Optional<File> getFile() {
191         return form.validate().stream()
192                 .filter(BinderValidationStatus::isOk)
193                 .map(BinderValidationStatus::getBinder)
194                 .flatMap(Binder::getFields)
195                 .map(HasValue::getValue)
196                 .filter(File.class::isInstance)
197                 .map(File.class::cast)
198                 .findFirst();
199     }
200 
201     private String getEncoding() {
202         return form.validate().stream()
203                 .map(BinderValidationStatus::getBinder)
204                 .flatMap(Binder::getFields)
205                 .map(HasValue::getValue)
206                 .filter(Option.class::isInstance)
207                 .map(Option.class::cast)
208                 .map(Option::getValue)
209                 .findFirst()
210                 .orElse(null);
211     }
212 }