MACSyncClientImpl.java 11.8 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.auth.oauth.AccessTokenProvider
 *  com.adobe.granite.crypto.CryptoException
 *  com.adobe.granite.crypto.CryptoSupport
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.http.HttpEntity
 *  org.apache.http.HttpResponse
 *  org.apache.http.StatusLine
 *  org.apache.http.client.HttpClient
 *  org.apache.http.client.entity.UrlEncodedFormEntity
 *  org.apache.http.client.methods.HttpGet
 *  org.apache.http.client.methods.HttpPost
 *  org.apache.http.client.methods.HttpUriRequest
 *  org.apache.http.message.BasicNameValuePair
 *  org.apache.http.osgi.services.HttpClientBuilderFactory
 *  org.apache.http.util.EntityUtils
 *  org.apache.sling.api.resource.LoginException
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.commons.json.JSONArray
 *  org.apache.sling.commons.json.JSONObject
 *  org.apache.sling.commons.osgi.PropertiesUtil
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.dam.mac.sync.helper.impl;

import com.adobe.cq.dam.mac.sync.helper.impl.MACSyncClient;
import com.adobe.cq.dam.mac.sync.helper.impl.MACTenantConfiguration;
import com.adobe.cq.dam.mac.sync.helper.impl.http.HTTPUtil;
import com.adobe.cq.dam.mac.sync.helper.impl.util.OAuthUtil;
import com.adobe.granite.auth.oauth.AccessTokenProvider;
import com.adobe.granite.crypto.CryptoException;
import com.adobe.granite.crypto.CryptoSupport;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.osgi.services.HttpClientBuilderFactory;
import org.apache.http.util.EntityUtils;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONObject;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=1, label="%com.adobe.cq.mac.sync.client.name.label", description="%com.adobe.cq.mac.sync.client.name.description")
@Service
public class MACSyncClientImpl
implements MACSyncClient {
    private static final Logger LOG = LoggerFactory.getLogger(MACSyncClientImpl.class);
    private int soTimeOut = 30000;
    @Reference
    private ResourceResolverFactory rrf = null;
    @Reference
    private CryptoSupport cryptoSupport = null;
    @Reference
    private HttpClientBuilderFactory httpClientBuilderFactory = null;
    @Reference(name="accessTokenProvider", target="(auth.token.provider.keypair.alias=replication)", referenceInterface=AccessTokenProvider.class)
    private AccessTokenProvider accessTokenProvider;
    private Map accessTokenProviderProps;
    private static final int DEFAULT_SO_TIMEOUT = 30000;
    @Property(intValue={30000})
    protected static final String SO_TIMEOUT = "com.adobe.dam.mac.sync.client.so.timeout";
    public static final String ACCESS_TOKEN_PROPERTY = "accessTokenProvider";
    private static final String REQUEST_PARAM_SYNC_TYPE = "type";
    private static final String REQUEST_PARAM_MEMBER = "member";
    private static final String REQUEST_PARAM_OPERATION = ":operation";
    private static final String REQUEST_PARAM_PATH = "path";
    private static final String REQUEST_PARAM_DISABLE = "disable";
    private static final String REQUEST_PARAM_CHARSET = "_charset_";
    private static final String MAC_DAM_SYNC_OPERATION = "mac.dam.sync";
    private static final String CC_SYNC = "cc";
    private static final String MAC_SYNC = "mac";
    private static final String ADD_MEMBER_ACTION = "add";
    private static final String REMOVE_MEMBER_ACTION = "remove";
    private static final String CHARSET_UTF8 = "utf-8";

    @Override
    public boolean setupMACSync(String macFolder, boolean disable, MACTenantConfiguration macConfiguration, Collection<String> newMembers, Collection<String> removedMembers) {
        LOG.debug("Setting up sync on MAC");
        try {
            HttpResponse response;
            int status;
            HttpClient client = HTTPUtil.getClient(this.soTimeOut, macConfiguration, this.rrf, this.accessTokenProvider, this.cryptoSupport, this.httpClientBuilderFactory);
            String urlString = macConfiguration.getTenantURL() + "/content/dam";
            HttpPost method = new HttpPost(urlString);
            ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
            params.add(new BasicNameValuePair(":operation", "mac.dam.sync"));
            params.add(new BasicNameValuePair("path", macFolder));
            params.add(new BasicNameValuePair("_charset_", "utf-8"));
            if (disable) {
                params.add(new BasicNameValuePair("disable", "true"));
            }
            if (newMembers != null) {
                params.add(new BasicNameValuePair("type", "cc"));
                for (String newMember : newMembers) {
                    params.add(new BasicNameValuePair("member", "add:" + newMember));
                }
                for (String member : removedMembers) {
                    params.add(new BasicNameValuePair("member", "remove:" + member));
                }
            }
            method.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            method.setEntity((HttpEntity)new UrlEncodedFormEntity(params));
            if (method.containsHeader("Referer")) {
                method.addHeader("Referer", "about:blank");
            }
            if ((status = (response = client.execute((HttpUriRequest)method)).getStatusLine().getStatusCode()) == 200) {
                return true;
            }
            LOG.error("not able to setup mac sync status {}", (Object)status);
            HttpEntity entity = response.getEntity();
            LOG.debug("not able to setup mac sync response {}", (Object)EntityUtils.toString((HttpEntity)entity));
        }
        catch (Exception e) {
            LOG.error("error while setting up mac sync ", (Throwable)e);
        }
        return false;
    }

    @Override
    public Map<String, String> getCCUsers(MACTenantConfiguration macConfiguration) {
        LOG.debug("getting cc user list");
        try {
            HttpClient client = HTTPUtil.getClient(this.soTimeOut, macConfiguration, this.rrf, this.accessTokenProvider, this.cryptoSupport, this.httpClientBuilderFactory);
            String urlString = macConfiguration.getTenantURL() + "/content/dam" + ".ccusers.json?_charset_=utf-8";
            HttpGet method = new HttpGet(urlString);
            if (method.containsHeader("Referer")) {
                method.addHeader("Referer", "about:blank");
            }
            HttpResponse response = client.execute((HttpUriRequest)method);
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString((HttpEntity)entity);
            int status = response.getStatusLine().getStatusCode();
            if (status == 401) {
                LOG.error("Not authorised to perform operation ");
                LOG.debug("response " + responseString);
            } else {
                if (status == 200) {
                    LOG.debug("response " + responseString);
                    HashMap<String, String> ccUsers = new HashMap<String, String>();
                    String responseBodyAsString = responseString;
                    JSONObject results = new JSONObject(responseBodyAsString);
                    Object users = results.get("users");
                    if (users != null) {
                        JSONArray usersArr = (JSONArray)users;
                        for (int i = 0; i < usersArr.length(); ++i) {
                            JSONObject ccUser = usersArr.getJSONObject(i);
                            ccUsers.put((String)ccUser.get("id"), (String)ccUser.get("name"));
                        }
                    }
                    return ccUsers;
                }
                LOG.debug("response " + responseString);
                LOG.error("Could not fetch the list of users, status code is {}", (Object)status);
            }
        }
        catch (Exception e) {
            LOG.error("error while setting up mac sync ", (Throwable)e);
        }
        return Collections.EMPTY_MAP;
    }

    @Override
    public int validateConnection(String clientId, String tenantUrl, String scopes, String tenant) throws IOException, LoginException, URISyntaxException, CryptoException {
        HttpClient client = HTTPUtil.getClient(this.soTimeOut, tenantUrl + "/bin/receive", OAuthUtil.getReplicationUserId(tenant), false, null, this.rrf, this.accessTokenProvider, this.httpClientBuilderFactory);
        HttpGet method = new HttpGet(tenantUrl + "/bin/receive");
        method.addHeader("Action", "Test");
        if (method.containsHeader("Referer")) {
            method.addHeader("Referer", "about:blank");
        }
        HttpResponse response = client.execute((HttpUriRequest)method);
        int status = response.getStatusLine().getStatusCode();
        return status;
    }

    protected synchronized void bindAccessTokenProvider(AccessTokenProvider tokenProvider, Map properties) {
        this.accessTokenProvider = tokenProvider;
        this.accessTokenProviderProps = properties;
        LOG.debug("binding accessTokenProvider");
    }

    protected synchronized void unbindAccessTokenProvider(AccessTokenProvider tokenProvider) {
        this.accessTokenProvider = null;
        this.accessTokenProviderProps = null;
        LOG.debug("un-binding accessTokenProvider");
    }

    @Override
    public Map getAccessTokenProviderProperties() {
        return this.accessTokenProviderProps;
    }

    @Activate
    protected void activate(Map<String, Object> props) throws Exception {
        this.soTimeOut = Math.abs(PropertiesUtil.toInteger((Object)props.get("com.adobe.dam.mac.sync.client.so.timeout"), (int)30000));
        LOG.debug("Setting up socket timeout {}", (Object)this.soTimeOut);
    }

    protected void bindRrf(ResourceResolverFactory resourceResolverFactory) {
        this.rrf = resourceResolverFactory;
    }

    protected void unbindRrf(ResourceResolverFactory resourceResolverFactory) {
        if (this.rrf == resourceResolverFactory) {
            this.rrf = null;
        }
    }

    protected void bindCryptoSupport(CryptoSupport cryptoSupport) {
        this.cryptoSupport = cryptoSupport;
    }

    protected void unbindCryptoSupport(CryptoSupport cryptoSupport) {
        if (this.cryptoSupport == cryptoSupport) {
            this.cryptoSupport = null;
        }
    }

    protected void bindHttpClientBuilderFactory(HttpClientBuilderFactory httpClientBuilderFactory) {
        this.httpClientBuilderFactory = httpClientBuilderFactory;
    }

    protected void unbindHttpClientBuilderFactory(HttpClientBuilderFactory httpClientBuilderFactory) {
        if (this.httpClientBuilderFactory == httpClientBuilderFactory) {
            this.httpClientBuilderFactory = null;
        }
    }
}