001/**
002 *
003 * Copyright 2016-2021 Fernando Ramirez, Florian Schmaus
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.bob;
018
019import java.util.Collections;
020import java.util.Map;
021import java.util.Set;
022import java.util.WeakHashMap;
023import java.util.concurrent.ConcurrentHashMap;
024
025import org.jivesoftware.smack.ConnectionCreationListener;
026import org.jivesoftware.smack.Manager;
027import org.jivesoftware.smack.SmackException.NoResponseException;
028import org.jivesoftware.smack.SmackException.NotConnectedException;
029import org.jivesoftware.smack.SmackException.NotLoggedInException;
030import org.jivesoftware.smack.XMPPConnection;
031import org.jivesoftware.smack.XMPPConnectionRegistry;
032import org.jivesoftware.smack.XMPPException.XMPPErrorException;
033import org.jivesoftware.smack.iqrequest.AbstractIqRequestHandler;
034import org.jivesoftware.smack.iqrequest.IQRequestHandler.Mode;
035import org.jivesoftware.smack.packet.IQ;
036import org.jivesoftware.smack.util.SHA1;
037
038import org.jivesoftware.smackx.bob.element.BoBIQ;
039import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
040
041import org.jxmpp.jid.Jid;
042import org.jxmpp.util.cache.LruCache;
043
044/**
045 * Bits of Binary manager class.
046 *
047 * @author Fernando Ramirez
048 * @author Florian Schmaus
049 * @see <a href="http://xmpp.org/extensions/xep-0231.html">XEP-0231: Bits of
050 *      Binary</a>
051 */
052public final class BoBManager extends Manager {
053
054    public static final String NAMESPACE = "urn:xmpp:bob";
055
056    static {
057        XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
058            @Override
059            public void connectionCreated(XMPPConnection connection) {
060                getInstanceFor(connection);
061            }
062        });
063    }
064
065    private static final Map<XMPPConnection, BoBManager> INSTANCES = new WeakHashMap<>();
066
067    /**
068     * Get the singleton instance of BoBManager.
069     *
070     * @param connection TODO javadoc me please
071     * @return the instance of BoBManager
072     */
073    public static synchronized BoBManager getInstanceFor(XMPPConnection connection) {
074        BoBManager bobManager = INSTANCES.get(connection);
075        if (bobManager == null) {
076            bobManager = new BoBManager(connection);
077            INSTANCES.put(connection, bobManager);
078        }
079
080        return bobManager;
081    }
082
083    private static final LruCache<ContentId, BoBData> BOB_CACHE = new LruCache<>(128);
084
085    private final Map<ContentId, BoBInfo> bobs = new ConcurrentHashMap<>();
086
087    private BoBManager(XMPPConnection connection) {
088        super(connection);
089        ServiceDiscoveryManager serviceDiscoveryManager = ServiceDiscoveryManager.getInstanceFor(connection);
090        serviceDiscoveryManager.addFeature(NAMESPACE);
091
092        connection.registerIQRequestHandler(
093                new AbstractIqRequestHandler(BoBIQ.ELEMENT, BoBIQ.NAMESPACE, IQ.Type.get, Mode.async) {
094                    @Override
095                    public IQ handleIQRequest(IQ iqRequest) {
096                        BoBIQ bobIQRequest = (BoBIQ) iqRequest;
097                        ContentId contentId = bobIQRequest.getContentId();
098
099                        BoBInfo bobInfo = bobs.get(contentId);
100                        if (bobInfo == null) {
101                            // TODO return item-not-found
102                            return null;
103                        }
104
105                        BoBData bobData = bobInfo.getData();
106                        BoBIQ responseBoBIQ = new BoBIQ(contentId, bobData);
107                        responseBoBIQ.setType(IQ.Type.result);
108                        responseBoBIQ.setTo(bobIQRequest.getFrom());
109                        return responseBoBIQ;
110                    }
111                });
112    }
113
114    /**
115     * Returns true if Bits of Binary is supported by the server.
116     *
117     * @return true if Bits of Binary is supported by the server.
118     * @throws NoResponseException if there was no response from the remote entity.
119     * @throws XMPPErrorException if there was an XMPP error returned.
120     * @throws NotConnectedException if the XMPP connection is not connected.
121     * @throws InterruptedException if the calling thread was interrupted.
122     */
123    public boolean isSupportedByServer()
124            throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
125        return ServiceDiscoveryManager.getInstanceFor(connection()).serverSupportsFeature(NAMESPACE);
126    }
127
128    /**
129     * Request BoB data.
130     *
131     * @param to TODO javadoc me please
132     * @param bobHash TODO javadoc me please
133     * @return the BoB data
134     * @throws NotLoggedInException if the XMPP connection is not authenticated.
135     * @throws NoResponseException if there was no response from the remote entity.
136     * @throws XMPPErrorException if there was an XMPP error returned.
137     * @throws NotConnectedException if the XMPP connection is not connected.
138     * @throws InterruptedException if the calling thread was interrupted.
139     */
140    public BoBData requestBoB(Jid to, ContentId bobHash) throws NotLoggedInException, NoResponseException,
141            XMPPErrorException, NotConnectedException, InterruptedException {
142        BoBData bobData = BOB_CACHE.lookup(bobHash);
143        if (bobData != null) {
144            return bobData;
145        }
146
147        BoBIQ requestBoBIQ = new BoBIQ(bobHash);
148        requestBoBIQ.setType(IQ.Type.get);
149        requestBoBIQ.setTo(to);
150
151        XMPPConnection connection = getAuthenticatedConnectionOrThrow();
152        BoBIQ responseBoBIQ = connection.sendIqRequestAndWaitForResponse(requestBoBIQ);
153
154        bobData = responseBoBIQ.getBoBData();
155        BOB_CACHE.put(bobHash, bobData);
156
157        return bobData;
158    }
159
160    public BoBInfo addBoB(BoBData bobData) {
161        // We only support SHA-1 for now.
162        ContentId bobHash = new ContentId(SHA1.hex(bobData.getContent()), "sha1");
163
164        Set<ContentId> bobHashes = Collections.singleton(bobHash);
165        bobHashes = Collections.unmodifiableSet(bobHashes);
166
167        BoBInfo bobInfo = new BoBInfo(bobHashes, bobData);
168
169        bobs.put(bobHash, bobInfo);
170
171        return bobInfo;
172    }
173
174    public BoBInfo removeBoB(ContentId bobHash) {
175        BoBInfo bobInfo = bobs.remove(bobHash);
176        if (bobInfo == null) {
177            return null;
178        }
179        for (ContentId otherBobHash : bobInfo.getHashes()) {
180            bobs.remove(otherBobHash);
181        }
182        return bobInfo;
183    }
184}