001/**
002 *
003 * Copyright 2017 Paul Schaub
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.omemo.element;
018
019import org.jivesoftware.smack.packet.ExtensionElement;
020import org.jivesoftware.smack.util.Objects;
021import org.jivesoftware.smack.util.XmlStringBuilder;
022import org.jivesoftware.smack.util.stringencoder.Base64;
023
024/**
025 * Class that represents an OmemoElement.
026 *
027 * @author Paul Schaub
028 */
029public abstract class OmemoElement implements ExtensionElement {
030
031    public static final int TYPE_OMEMO_PREKEY_MESSAGE = 1;
032    public static final int TYPE_OMEMO_MESSAGE = 0;
033
034    public static final String NAME_ENCRYPTED = "encrypted";
035    public static final String ATTR_PAYLOAD = "payload";
036
037    private final OmemoHeaderElement header;
038    private final byte[] payload;
039
040    /**
041     * Create a new OmemoMessageElement from a header and a payload.
042     *
043     * @param header  header of the message
044     * @param payload payload
045     */
046    public OmemoElement(OmemoHeaderElement header, byte[] payload) {
047        this.header = Objects.requireNonNull(header);
048        this.payload = payload;
049    }
050
051    public OmemoHeaderElement getHeader() {
052        return header;
053    }
054
055    /**
056     * Return the payload of the message.
057     *
058     * @return encrypted payload of the message.
059     */
060    public byte[] getPayload() {
061        if (payload == null) {
062            return null;
063        }
064        return payload.clone();
065    }
066
067    public boolean isKeyTransportElement() {
068        return payload == null;
069    }
070
071    public boolean isMessageElement() {
072        return payload != null;
073    }
074
075    @Override
076    public XmlStringBuilder toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) {
077        XmlStringBuilder sb = new XmlStringBuilder(this, enclosingNamespace).rightAngleBracket();
078
079        sb.append(header);
080
081        if (payload != null) {
082            sb.openElement(ATTR_PAYLOAD).append(Base64.encodeToString(payload)).closeElement(ATTR_PAYLOAD);
083        }
084
085        sb.closeElement(this);
086        return sb;
087    }
088
089    @Override
090    public String getElementName() {
091        return NAME_ENCRYPTED;
092    }
093}