
/*
 * Copyright (C) 2003-2017 eXo Platform SAS.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.exoplatform.outlook.rest;

import org.exoplatform.outlook.BadParameterException;
import org.exoplatform.outlook.OutlookException;
import org.exoplatform.outlook.jcr.ContentLink;
import org.exoplatform.outlook.jcr.NodeContent;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;

import javax.jcr.RepositoryException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;

/**
 * Created by The eXo Platform SAS.
 *
 * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a>
 * @version $Id: ContentService.java 00000 Aug 14, 2016 pnedonosko $
 */
@Path("/outlook/content")
public class ContentService extends RESTServiceBase {

  /** The Constant LOG. */
  protected static final Log  LOG = ExoLogger.getLogger(ContentService.class);

  /** The content link. */
  protected final ContentLink contentLink;

  /**
   * Instantiates a new content service.
   *
   * @param contentLink {@link ContentLink}
   */
  public ContentService(ContentLink contentLink) {
    this.contentLink = contentLink;
  }

  /**
   * Document content download link. <br>
   * WARNING! It is publicly accessible service but access from the Documents Server host can be restricted
   * (by default).
   * 
   * @param uriInfo - request info
   * @param request {@link HttpServletRequest}
   * @param userId {@link String}
   * @param key {@link String} file key generated by {@link ContentLink#create(String, javax.jcr.Node)} method
   * @return {@link Response}
   */
  @GET
  @Path("/{userId}/{key}")
  public Response content(@Context UriInfo uriInfo,
                          @Context HttpServletRequest request,
                          @PathParam("userId") String userId,
                          @PathParam("key") String key) {
    String clientHost = getClientHost(request);
    String clientIp = getClientIpAddr(request);
    if (LOG.isDebugEnabled()) {
      LOG.debug("> Outlook document content: " + userId + "@" + key + " to " + clientHost + "(" + clientIp + ")");
    }
    ResponseBuilder resp;
    // TODO Consider for client host/IP restrictions for downloading the content
    boolean canDownload = true;
    if (canDownload) {
      if (key != null && key.length() > 0) {
        try {
          if (userId != null && userId.length() > 0) {
            NodeContent content = contentLink.consume(userId, key);
            if (content != null) {
              resp = Response.ok().entity(content.getData()).type(content.getType());
            } else {
              resp = Response.status(Status.NOT_FOUND).entity("Content not found for " + key);
            }
          } else {
            LOG.error("Error downloading content. User identity not provided");
            resp = Response.status(Status.BAD_REQUEST).entity("User not provided");
          }
        } catch (BadParameterException e) {
          LOG.error("Bad parameter to downloading content for " + key, e);
          resp = Response.status(Status.BAD_REQUEST).entity(e.getMessage());
        } catch (OutlookException e) {
          LOG.error("Error downloading content for " + key, e);
          resp = Response.status(Status.INTERNAL_SERVER_ERROR).entity("Error downloading content. " + e.getMessage());
        } catch (RepositoryException e) {
          LOG.error("Storage error while downloading content for " + key, e);
          resp = Response.status(Status.INTERNAL_SERVER_ERROR).entity("Storage error.");
        } catch (Throwable e) {
          LOG.error("Runtime error while downloading content for " + key, e);
          resp = Response.status(Status.INTERNAL_SERVER_ERROR).entity("Runtime error.");
        }
      } else {
        resp = Response.status(Status.BAD_REQUEST).entity("Null or empty file key.");
      }
    } else {
      LOG.warn("Attempt to download content by not allowed host: " + clientHost);
      resp = Response.status(Status.UNAUTHORIZED).entity("Not a document server.");
    }
    return resp.build();
  }
}
