ContentDirectoryClingAdapter.java

  1. /*
  2.  * *********************************************************************************************************************
  3.  *
  4.  * blueMarine II: Semantic Media Centre
  5.  * http://tidalwave.it/projects/bluemarine2
  6.  *
  7.  * Copyright (C) 2015 - 2021 by Tidalwave s.a.s. (http://tidalwave.it)
  8.  *
  9.  * *********************************************************************************************************************
  10.  *
  11.  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  12.  * the License. You may obtain a copy of the License at
  13.  *
  14.  *     http://www.apache.org/licenses/LICENSE-2.0
  15.  *
  16.  * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  17.  * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the
  18.  * specific language governing permissions and limitations under the License.
  19.  *
  20.  * *********************************************************************************************************************
  21.  *
  22.  * git clone https://bitbucket.org/tidalwave/bluemarine2-src
  23.  * git clone https://github.com/tidalwave-it/bluemarine2-src
  24.  *
  25.  * *********************************************************************************************************************
  26.  */
  27. package it.tidalwave.bluemarine2.upnp.mediaserver.impl;

  28. import javax.annotation.Nonnull;
  29. import javax.inject.Inject;
  30. import java.util.concurrent.atomic.AtomicInteger;
  31. import java.util.stream.Stream;
  32. import java.nio.file.Path;
  33. import org.fourthline.cling.support.model.BrowseFlag;
  34. import org.fourthline.cling.support.model.BrowseResult;
  35. import org.fourthline.cling.support.model.SortCriterion;
  36. import org.fourthline.cling.support.contentdirectory.AbstractContentDirectoryService;
  37. import org.fourthline.cling.support.contentdirectory.ContentDirectoryException;
  38. import org.fourthline.cling.support.contentdirectory.DIDLParser;
  39. import it.tidalwave.bluemarine2.model.spi.CacheManager;
  40. import it.tidalwave.bluemarine2.model.spi.CacheManager.Cache;
  41. import it.tidalwave.bluemarine2.model.spi.Entity;
  42. import it.tidalwave.bluemarine2.mediaserver.ContentDirectory;
  43. import it.tidalwave.bluemarine2.upnp.mediaserver.impl.didl.DIDLAdapter.ContentHolder;
  44. import lombok.extern.slf4j.Slf4j;
  45. import lombok.EqualsAndHashCode;
  46. import lombok.RequiredArgsConstructor;
  47. import lombok.ToString;
  48. import static org.fourthline.cling.support.contentdirectory.ContentDirectoryErrorCode.*;
  49. import static it.tidalwave.bluemarine2.util.Formatters.*;
  50. import static it.tidalwave.bluemarine2.upnp.mediaserver.impl.UpnpUtilities.*;
  51. import static it.tidalwave.bluemarine2.upnp.mediaserver.impl.didl.DIDLAdapter._DIDLAdapter_;

  52. /***********************************************************************************************************************
  53.  *
  54.  * This class implements a minimal "ContentDirectory" compliant to the UPnP specifications. It acts as an adapter with
  55.  * respect to a {@link ContentDirectory}, which provides contents.
  56.  *
  57.  * @see http://upnp.org/specs/av/UPnP-av-ContentDirectory-v1-Service.pdf
  58.  *
  59.  * @stereotype Adapter
  60.  *
  61.  * @author  Fabrizio Giudici
  62.  *
  63.  **********************************************************************************************************************/
  64. @Slf4j
  65. public class ContentDirectoryClingAdapter extends AbstractContentDirectoryService
  66.   {
  67.     @Inject
  68.     private ContentDirectory contentDirectory;

  69.     @Inject
  70.     private CacheManager cacheManager;

  71.     private final AtomicInteger updateId = new AtomicInteger(1); // FIXME: increment on database update

  72.     @RequiredArgsConstructor @EqualsAndHashCode @ToString
  73.     static class BrowseParams
  74.       {
  75.         @Nonnull
  76.         private final String objectId;
  77.         @Nonnull
  78.         private final BrowseFlag browseFlag;
  79.         private final String filter;
  80.         private final long firstResult;
  81.         private final long maxResults;
  82.         private final SortCriterion[] orderby;
  83.       }

  84.     /*******************************************************************************************************************
  85.      *
  86.      * Returns information about an object.
  87.      *
  88.      * @see http://upnp.org/specs/av/UPnP-av-ContentDirectory-v1-Service.pdf
  89.      *
  90.      * @param   objectId                    the id of the object to browse
  91.      * @param   browseFlag                  whether metadata or children content are requested
  92.      * @param   filter                      a filter for returned data
  93.      * @param   firstResult                 the first index of the items to return
  94.      * @param   maxResults                  the maximum number of items to return
  95.      * @param   orderby                     the sort criteria
  96.      * @return                              the requested object
  97.      * @throws  ContentDirectoryException   in case of error
  98.      *
  99.      ******************************************************************************************************************/
  100.     @Override
  101.     public BrowseResult browse (@Nonnull final String objectId,
  102.                                 @Nonnull final BrowseFlag browseFlag,
  103.                                 final String filter,
  104.                                 final long firstResult,
  105.                                 final long maxResults,
  106.                                 final SortCriterion[] orderby)
  107.       throws ContentDirectoryException
  108.       {
  109.         log.info("browse({}, {}, filter: {}, startingIndex: {}, requestedCount: {}, sortCriteria: {})",
  110.                  objectId, browseFlag, filter, firstResult, maxResults, orderby);
  111.         // this repeated log is for capturing test recordings
  112.         log.trace("browse @@@ {} @@@ {} @@@ {} @@@ {} @@@ {} @@@ {})",
  113.                   objectId, browseFlag, firstResult, maxResults, filter, orderby);

  114.         final long baseTime = System.nanoTime();
  115.         final BrowseParams params = new BrowseParams(objectId, browseFlag, filter, firstResult, maxResults, orderby);
  116.         final Cache cache = cacheManager.getCache(getClass());
  117.         final Object result = cache.getCachedObject(params, () -> findEntity(params));
  118.         log.info(">>>> result computed in {} msec", (System.nanoTime() - baseTime) / 1E6);

  119.         if (result instanceof ContentDirectoryException)
  120.           {
  121.             throw (ContentDirectoryException)result;
  122.           }

  123.         log(">>>> returning", (BrowseResult)result);
  124.         return (BrowseResult)result;
  125.       }

  126.     /*******************************************************************************************************************
  127.      *
  128.      * Searches an entity.
  129.      *
  130.      * @param   params  the search parameters
  131.      * @return          a {@link BrowseResult} if the requested entity has been found; a
  132.      *                  {@link ContentDirectoryException} in case of error
  133.      *
  134.      ******************************************************************************************************************/
  135.     @Nonnull
  136.     private Object findEntity (@Nonnull final BrowseParams params)
  137.       {
  138.         try
  139.           {
  140.             final Path path = didlIdToPath(params.objectId);
  141.             final Entity entity = contentDirectory.findRoot()
  142.                                                   .findChildren()
  143.                                                   .withPath(path)
  144.                                                   .optionalResult()
  145.                                                   .orElseThrow(() ->
  146.                                                           new ContentDirectoryException(NO_SUCH_OBJECT,
  147.                                                                     String.format("%s -> %s", params.objectId, path)));
  148.             log.debug(">>>> found {}", entity);
  149.             final ContentHolder holder = entity.as(_DIDLAdapter_).toContent(params.browseFlag,
  150.                                                                           (int)params.firstResult,
  151.                                                                           maxCount(params.maxResults));
  152.             final DIDLParser parser = new DIDLParser();
  153.             return new BrowseResult(parser.generate(holder.getContent()),
  154.                                     holder.getNumberReturned(),
  155.                                     holder.getTotalMatches(),
  156.                                     updateId.get());
  157.           }
  158.         // this method returns exceptions as a result, so they can be cached
  159.         catch (ContentDirectoryException e)
  160.           {
  161.             log.error("", e);
  162.             return e;
  163.           }
  164.         catch (Exception e)
  165.           {
  166.             log.error("", e);
  167.             return new ContentDirectoryException(CANNOT_PROCESS);
  168.           }
  169.       }

  170.     /*******************************************************************************************************************
  171.      *
  172.      ******************************************************************************************************************/
  173.     private static void log (@Nonnull final String message, @Nonnull final BrowseResult browseResult)
  174.       {
  175.         log.info("{} BrowseResult(..., {}, {}, {})",
  176.                  message,
  177.                  browseResult.getCountLong(),
  178.                  browseResult.getTotalMatchesLong(),
  179.                  browseResult.getContainerUpdateIDLong());

  180.         if (log.isDebugEnabled())
  181.           {
  182.             Stream.of(xmlPrettyPrinted(browseResult.getResult()).split("\n"))
  183.                                                                 .forEach(s -> log.debug("{} {}", message, s));
  184.           }
  185.       }
  186.   }