001/*
002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *      Nelson Silva
016 */
017
018package org.nuxeo.ecm.media.publishing;
019
020import com.google.api.client.auth.oauth2.Credential;
021import org.nuxeo.ecm.media.publishing.adapter.PublishableMedia;
022import org.nuxeo.ecm.platform.oauth2.providers.NuxeoOAuth2ServiceProvider;
023import org.nuxeo.ecm.platform.oauth2.providers.OAuth2ServiceProvider;
024import org.nuxeo.ecm.platform.oauth2.providers.OAuth2ServiceProviderRegistry;
025import org.nuxeo.runtime.api.Framework;
026
027/**
028 * Abstract Media Publishing Provider using OAuth2
029 *
030 * @since 7.3
031 */
032public abstract class OAuth2MediaPublishingProvider implements MediaPublishingProvider {
033
034    private final String providerName;
035
036    public OAuth2MediaPublishingProvider(String providerName) {
037        this.providerName = providerName;
038    }
039
040    protected OAuth2ServiceProvider getOAuth2ServiceProvider() {
041        OAuth2ServiceProviderRegistry oAuth2ProviderRegistry = Framework.getLocalService(OAuth2ServiceProviderRegistry.class);
042        return oAuth2ProviderRegistry.getProvider(providerName);
043    }
044
045    protected Credential getCredential(String account) {
046        return getOAuth2ServiceProvider() != null ? getOAuth2ServiceProvider().loadCredential(account) : null;
047    }
048
049    @Override
050    public boolean isAvailable() {
051        NuxeoOAuth2ServiceProvider serviceProvider = (NuxeoOAuth2ServiceProvider) getOAuth2ServiceProvider();
052        return serviceProvider != null && serviceProvider.isEnabled() &&
053            serviceProvider.getClientSecret() != null && serviceProvider.getClientId() != null;
054    }
055
056    @Override
057    public boolean isMediaAvailable(PublishableMedia media) {
058        NuxeoOAuth2ServiceProvider serviceProvider = (NuxeoOAuth2ServiceProvider) getOAuth2ServiceProvider();
059        String account = media.getAccount(providerName);
060        return isAvailable() && serviceProvider != null && getCredential(account) != null;
061    }
062}