001/*
002 * (C) Copyright 2015 Nuxeo SA (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 *      Nelson Silva
018 */
019
020package org.nuxeo.ecm.media.publishing;
021
022import com.google.api.client.auth.oauth2.Credential;
023import org.nuxeo.ecm.media.publishing.adapter.PublishableMedia;
024import org.nuxeo.ecm.platform.oauth2.providers.NuxeoOAuth2ServiceProvider;
025import org.nuxeo.ecm.platform.oauth2.providers.OAuth2ServiceProvider;
026import org.nuxeo.ecm.platform.oauth2.providers.OAuth2ServiceProviderRegistry;
027import org.nuxeo.runtime.api.Framework;
028
029/**
030 * Abstract Media Publishing Provider using OAuth2
031 *
032 * @since 7.3
033 */
034public abstract class OAuth2MediaPublishingProvider implements MediaPublishingProvider {
035
036    private final String providerName;
037
038    public OAuth2MediaPublishingProvider(String providerName) {
039        this.providerName = providerName;
040    }
041
042    protected OAuth2ServiceProvider getOAuth2ServiceProvider() {
043        OAuth2ServiceProviderRegistry oAuth2ProviderRegistry = Framework.getService(OAuth2ServiceProviderRegistry.class);
044        return oAuth2ProviderRegistry.getProvider(providerName);
045    }
046
047    protected Credential getCredential(String account) {
048        return getOAuth2ServiceProvider() != null ? getOAuth2ServiceProvider().loadCredential(account) : null;
049    }
050
051    @Override
052    public boolean isAvailable() {
053        NuxeoOAuth2ServiceProvider serviceProvider = (NuxeoOAuth2ServiceProvider) getOAuth2ServiceProvider();
054        return serviceProvider != null && serviceProvider.isEnabled() &&
055            serviceProvider.getClientSecret() != null && serviceProvider.getClientId() != null;
056    }
057
058    @Override
059    public boolean isMediaAvailable(PublishableMedia media) {
060        NuxeoOAuth2ServiceProvider serviceProvider = (NuxeoOAuth2ServiceProvider) getOAuth2ServiceProvider();
061        String account = media.getAccount(providerName);
062        return isAvailable() && serviceProvider != null && getCredential(account) != null;
063    }
064}