001/*
002 * (C) Copyright 2018 Nuxeo (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 *     Thomas Roger
018 */
019
020package org.nuxeo.wopi;
021
022import java.util.Arrays;
023
024import org.apache.commons.codec.binary.Base64;
025import org.nuxeo.ecm.core.api.DocumentModel;
026
027/**
028 * Given a WOPI file id, this class extracts information about a blob: a repository name, a doc id and the blob xpath.
029 * <p>
030 * A WOPI file id is a base64 encoded string formatted as {@code repositoryName/docId/xpath}.
031 *
032 * @since 10.3
033 */
034public class FileInfo {
035
036    public final String repositoryName;
037
038    public final String docId;
039
040    public final String xpath;
041
042    /**
043     * Returns a WOPI file id given a {@code repositoryName}, {@code docId} and a blob {@code xpath}.
044     */
045    public static String computeFileId(String repositoryName, String docId, String xpath) {
046        return Base64.encodeBase64String(String.join("/", repositoryName, docId, xpath).getBytes());
047    }
048
049    /**
050     * Returns a WOPI file id given a {@code doc}, and a blob {@code xpath}.
051     */
052    public static String computeFileId(DocumentModel doc, String xpath) {
053        return computeFileId(doc.getRepositoryName(), doc.getId(), xpath);
054    }
055
056    public FileInfo(String fileId) {
057        String str = new String(Base64.decodeBase64(fileId));
058        String[] parts = str.split("/");
059        repositoryName = parts[0];
060        docId = parts[1];
061        xpath = String.join("/", Arrays.asList(parts).subList(2, parts.length));
062    }
063}