예제 #1
0
 private UPnPError OnLoad(DvAction action, IList<object> inParams, out IList<object> outParams, CallContext context)
 {
   string settingsTypeName = (string) inParams[0];
   object result = Load(settingsTypeName);
   string serialized = SettingsSerializer.Serialize(result);
   outParams = new List<object> { serialized };
   return null;
 }
예제 #2
0
 private UPnPError OnSave(DvAction action, IList<object> inParams, out IList<object> outParams, CallContext context)
 {
   string settingsTypeName = (string) inParams[0];
   string settings = (string) inParams[1];
   Save(settingsTypeName, settings);
   outParams = new List<object> { };
   return null;
 }
예제 #3
0
    private UPnPError OnGetFanArt(DvAction action, IList<object> inParams, out IList<object> outParams, CallContext context)
    {
      outParams = new List<object>();
      IFanArtService fanArtService = ServiceRegistration.Get<IFanArtService>();
      if (fanArtService == null)
        return new UPnPError(500, "FanArt service not available");

      FanArtConstants.FanArtMediaType fanArtMediaType = (FanArtConstants.FanArtMediaType) Enum.Parse(typeof(FanArtConstants.FanArtMediaType), inParams[0].ToString());
      FanArtConstants.FanArtType fanArtType = (FanArtConstants.FanArtType) Enum.Parse(typeof(FanArtConstants.FanArtType), inParams[1].ToString());
      string name = inParams[2].ToString();
      int maxWidth = (int) inParams[3];
      int maxHeight = (int) inParams[4];
      bool singleRandom = (bool) inParams[5];

      IList<FanArtImage> fanArtImages = fanArtService.GetFanArt(fanArtMediaType, fanArtType, name, maxWidth, maxHeight, singleRandom) ?? new List<FanArtImage>();
      outParams = new List<object> { fanArtImages };
      return null;
    }
    // Cleanup user data

    static UPnPError OnClearAllUserData(DvAction action, IList<object> inParams, out IList<object> outParams,
        CallContext context)
    {
      Guid profileId = MarshallingHelper.DeserializeGuid((string) inParams[0]);
      bool success = ServiceRegistration.Get<IUserProfileDataManagement>().ClearAllUserData(profileId);
      outParams = new List<object> {success};
      return null;
    }
    // User media item data

    static UPnPError OnGetUserMediaItemData(DvAction action, IList<object> inParams, out IList<object> outParams,
        CallContext context)
    {
      Guid profileId = MarshallingHelper.DeserializeGuid((string) inParams[0]);
      Guid mediaItemId = MarshallingHelper.DeserializeGuid((string) inParams[1]);
      string key = (string) inParams[2];
      string data;
      bool success;
      if (!(success = ServiceRegistration.Get<IUserProfileDataManagement>().GetUserMediaItemData(profileId, mediaItemId, key, out data)))
        data = null;
      outParams = new List<object> {data, success};
      return null;
    }
 static UPnPError OnGetProfileByName(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   string profileName = (string) inParams[0];
   UserProfile profile;
   if (!ServiceRegistration.Get<IUserProfileDataManagement>().GetProfileByName(profileName, out profile))
     profile = null;
   outParams = new List<object> {profile};
   return null;
 }
    // User profiles management

    static UPnPError OnGetProfiles(DvAction action, IList<object> inParams, out IList<object> outParams,
        CallContext context)
    {
      ICollection<UserProfile> profiles = ServiceRegistration.Get<IUserProfileDataManagement>().GetProfiles();
      outParams = new List<object> {profiles};
      return null;
    }
 static UPnPError OnGetHomeServerSystemId(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   outParams = new List<object> {ServiceRegistration.Get<IServerConnectionManager>().HomeServerSystemId};
   return null;
 }
 static UPnPError OnTextSearch(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   string searchText = (string) inParams[0];
   IEnumerable<Guid> necessaryMIATypes = MarshallingHelper.ParseCsvGuidCollection((string) inParams[1]);
   IEnumerable<Guid> optionalMIATypes = MarshallingHelper.ParseCsvGuidCollection((string) inParams[2]);
   IFilter filter = (IFilter) inParams[3];
   string searchModeStr = (string) inParams[4];
   string onlineStateStr = (string) inParams[5];
   string capitalizationMode = (string) inParams[6];
   bool excludeCLOBs;
   bool all = false;
   bool caseSensitive = true;
   UPnPError error = ParseSearchMode("SearchMode", searchModeStr, out excludeCLOBs) ?? 
     ParseOnlineState("OnlineState", onlineStateStr, out all) ??
     ParseCapitalizationMode("CapitalizationMode", capitalizationMode, out caseSensitive);
   if (error != null)
   {
     outParams = null;
     return error;
   }
   IMediaLibrary mediaLibrary = ServiceRegistration.Get<IMediaLibrary>();
   MediaItemQuery query = mediaLibrary.BuildSimpleTextSearchQuery(searchText, necessaryMIATypes, optionalMIATypes,
       filter, !excludeCLOBs, caseSensitive);
   IList<MediaItem> mediaItems = mediaLibrary.Search(query, !all);
   outParams = new List<object> {mediaItems};
   return null;
 }
 static UPnPError OnReImportShare(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   Guid shareId = MarshallingHelper.DeserializeGuid((string) inParams[0]);
   Share share = ServiceRegistration.Get<IMediaLibrary>().GetShare(shareId);
   ServiceRegistration.Get<IImporterWorker>().ScheduleRefresh(share.BaseResourcePath, share.MediaCategories, true);
   outParams = null;
   return null;
 }
 static UPnPError OnGetShare(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   Guid shareId = MarshallingHelper.DeserializeGuid((string) inParams[0]);
   Share result = ServiceRegistration.Get<IMediaLibrary>().GetShare(shareId);
   outParams = new List<object> {result};
   return null;
 }
 static UPnPError OnGetShares(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   string systemId = (string) inParams[0];
   string sharesFilterStr = (string) inParams[1];
   bool all;
   UPnPError error = ParseOnlineState("SharesFilter", sharesFilterStr, out all);
   if (error != null)
   {
     outParams = null;
     return error;
   }
   IDictionary<Guid, Share> shares = ServiceRegistration.Get<IMediaLibrary>().GetShares(systemId);
   ICollection<Share> result;
   if (all)
     result = shares.Values;
   else
   {
     ICollection<string> connectedClientsIds = ServiceRegistration.Get<IClientManager>().ConnectedClients.Select(
         connection => connection.Descriptor.MPFrontendServerUUID).ToList();
     result = new List<Share>();
     foreach (Share share in shares.Values)
       if (connectedClientsIds.Contains(share.SystemId))
         result.Add(share);
   }
   outParams = new List<object> {result};
   return null;
 }
 static UPnPError OnUpdateShare(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   Guid shareId = MarshallingHelper.DeserializeGuid((string) inParams[0]);
   ResourcePath baseResourcePath = ResourcePath.Deserialize((string) inParams[1]);
   string shareName = (string) inParams[2];
   string[] mediaCategories = ((string) inParams[3]).Split(',');
   string relocateMediaItemsStr = (string) inParams[4];
   RelocationMode relocationMode;
   UPnPError error = ParseRelocationMode("RelocateMediaItems", relocateMediaItemsStr, out relocationMode);
   if (error != null)
   {
     outParams = null;
     return error;
   }
   IMediaLibrary mediaLibrary = ServiceRegistration.Get<IMediaLibrary>();
   int numAffected = mediaLibrary.UpdateShare(shareId, baseResourcePath, shareName, mediaCategories, relocationMode);
   outParams = new List<object> {numAffected};
   return null;
 }
 static UPnPError OnRegisterShare(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   Share share = (Share) inParams[0];
   ServiceRegistration.Get<IMediaLibrary>().RegisterShare(share);
   outParams = null;
   return null;
 }
 static UPnPError OnNotifyPlayback(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   IMediaLibrary mediaLibrary = ServiceRegistration.Get<IMediaLibrary>();
   Guid mediaItemId = MarshallingHelper.DeserializeGuid((string) inParams[0]);
   mediaLibrary.NotifyPlayback(mediaItemId);
   outParams = null;
   return null;
 }
    static UPnPError OnBrowse(DvAction action, IList<object> inParams, out IList<object> outParams,
        CallContext context)
    {
      Guid parentDirectoryId = MarshallingHelper.DeserializeGuid((string) inParams[0]);
      IEnumerable<Guid> necessaryMIATypes = MarshallingHelper.ParseCsvGuidCollection((string) inParams[1]);
      IEnumerable<Guid> optionalMIATypes = MarshallingHelper.ParseCsvGuidCollection((string) inParams[2]);
      ICollection<MediaItem> result = ServiceRegistration.Get<IMediaLibrary>().Browse(parentDirectoryId, necessaryMIATypes, optionalMIATypes);

      outParams = new List<object> {result};
      return null;
    }
 static UPnPError OnSearch(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   MediaItemQuery query = (MediaItemQuery) inParams[0];
   string onlineStateStr = (string) inParams[1];
   bool all;
   UPnPError error = ParseOnlineState("OnlineState", onlineStateStr, out all);
   if (error != null)
   {
     outParams = null;
     return error;
   }
   IList<MediaItem> mediaItems = ServiceRegistration.Get<IMediaLibrary>().Search(query, !all);
   outParams = new List<object> {mediaItems};
   return null;
 }
 static UPnPError OnSetupDefaultServerShares(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   ServiceRegistration.Get<IMediaLibrary>().SetupDefaultLocalShares();
   outParams = null;
   return null;
 }
 static UPnPError OnGetValueGroups(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   Guid aspectId = MarshallingHelper.DeserializeGuid((string) inParams[0]);
   string attributeName = (string) inParams[1];
   IFilter selectAttributeFilter = (IFilter) inParams[2];
   string projectionFunctionStr = (string) inParams[3];
   IEnumerable<Guid> necessaryMIATypes = MarshallingHelper.ParseCsvGuidCollection((string) inParams[4]);
   IFilter filter = (IFilter) inParams[5];
   string onlineStateStr = (string) inParams[6];
   IMediaItemAspectTypeRegistration miatr = ServiceRegistration.Get<IMediaItemAspectTypeRegistration>();
   MediaItemAspectMetadata miam;
   outParams = null;
   ProjectionFunction projectionFunction;
   bool all = true;
   UPnPError error = ParseProjectionFunction("ProjectionFunction", projectionFunctionStr, out projectionFunction) ??
       ParseOnlineState("OnlineState", onlineStateStr, out all);
   if (error != null)
     return error;
   if (!miatr.LocallyKnownMediaItemAspectTypes.TryGetValue(aspectId, out miam))
     return new UPnPError(600, string.Format("Media item aspect type '{0}' is unknown", aspectId));
   MediaItemAspectMetadata.AttributeSpecification attributeType;
   if (!miam.AttributeSpecifications.TryGetValue(attributeName, out attributeType))
     return new UPnPError(600, string.Format("Media item aspect type '{0}' doesn't contain an attribute of name '{1}'",
         aspectId, attributeName));
   HomogenousMap values = ServiceRegistration.Get<IMediaLibrary>().GetValueGroups(attributeType, selectAttributeFilter,
       projectionFunction, necessaryMIATypes, filter, !all);
   outParams = new List<object> {values};
   return null;
 }
 static UPnPError OnAddMediaItemAspectStorage(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   MediaItemAspectMetadata miam = (MediaItemAspectMetadata) inParams[0];
   ServiceRegistration.Get<IMediaLibrary>().AddMediaItemAspectStorage(miam);
   outParams = null;
   return null;
 }
 static UPnPError OnImportLocation(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   outParams = null;
   ResourcePath path = ResourcePath.Deserialize((string) inParams[0]);
   string[] mediaCategories = ((string) inParams[1]).Split(',');
   string importJobTypeStr = (string) inParams[2];
   ImportJobType importJobType;
   UPnPError error = ParseImportJobType("ImportJobType", importJobTypeStr, out importJobType);
   if (error != null)
     return error;
   if (importJobType == ImportJobType.Refresh)
     ServiceRegistration.Get<IImporterWorker>().ScheduleRefresh(path, mediaCategories, true);
   else
     ServiceRegistration.Get<IImporterWorker>().ScheduleImport(path, mediaCategories, true);
   return null;
 }
 static UPnPError OnRemoveMediaItemAspectStorage(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   Guid aspectId = MarshallingHelper.DeserializeGuid((string) inParams[0]);
   ServiceRegistration.Get<IMediaLibrary>().RemoveMediaItemAspectStorage(aspectId);
   outParams = null;
   return null;
 }
 static UPnPError OnGetProfile(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   Guid profileId = MarshallingHelper.DeserializeGuid((string) inParams[0]);
   UserProfile profile;
   if (!ServiceRegistration.Get<IUserProfileDataManagement>().GetProfile(profileId, out profile))
     profile = null;
   outParams = new List<object> {profile};
   return null;
 }
 static UPnPError OnGetAllManagedMediaItemAspectTypes(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   ICollection<Guid> result = ServiceRegistration.Get<IMediaLibrary>().GetManagedMediaItemAspectMetadata().Keys;
   outParams = new List<object> {MarshallingHelper.SerializeGuidEnumerationToCsv(result)};
   return null;
 }
 static UPnPError OnCreateProfile(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   string profileName = (string) inParams[0];
   Guid profileId = ServiceRegistration.Get<IUserProfileDataManagement>().CreateProfile(profileName);
   outParams = new List<object> {profileId};
   return null;
 }
 static UPnPError OnGetAllManagedMediaItemAspectCreationDates(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   IDictionary<Guid, DateTime> result = ServiceRegistration.Get<IMediaLibrary>().GetManagedMediaItemAspectCreationDates();
   outParams = new List<object> { result };
   return null;
 }
 static UPnPError OnSetUserAdditionalData(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   Guid profileId = MarshallingHelper.DeserializeGuid((string) inParams[0]);
   string key = (string) inParams[1];
   string data = (string) inParams[2];
   bool success = ServiceRegistration.Get<IUserProfileDataManagement>().SetUserAdditionalData(profileId, key, data);
   outParams = new List<object> {success};
   return null;
 }
 static UPnPError OnGetMediaItemAspectMetadata(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   Guid aspectId = MarshallingHelper.DeserializeGuid((string) inParams[0]);
   MediaItemAspectMetadata miam = ServiceRegistration.Get<IMediaLibrary>().GetManagedMediaItemAspectMetadata(aspectId);
   outParams = new List<object> {miam};
   return null;
 }
예제 #29
0
    /// <summary>
    /// Handles all kinds of HTTP over TCP requests - Description, Control and Event subscriptions.
    /// </summary>
    /// <param name="context">HTTP client context of the current request.</param>
    /// <param name="request">HTTP request to handle.</param>
    protected void HandleHTTPRequest_NoLock(IHttpClientContext context, IHttpRequest request)
    {
      Uri uri = request.Uri;
      string hostName = uri.Host;
      string pathAndQuery = uri.LocalPath; // Unfortunately, Uri.PathAndQuery doesn't decode characters like '{' and '}', so we use the Uri.LocalPath property
      try
      {
        DvService service;
        ICollection<EndpointConfiguration> endpoints;
        lock (_serverData.SyncObj)
          endpoints = _serverData.UPnPEndPoints;
        foreach (EndpointConfiguration config in endpoints)
        {
          if (!NetworkHelper.HostNamesEqual(hostName, NetworkHelper.IPAddrToHostName(config.EndPointIPAddress)))
            continue;

          // Common check for supported encodings
          string acceptEncoding = request.Headers.Get("ACCEPT-ENCODING") ?? string.Empty;

          // Handle different HTTP methods here
          if (request.Method == "GET")
          { // GET of descriptions
            if (pathAndQuery.StartsWith(config.DescriptionPathBase))
            {
              string acceptLanguage = request.Headers.Get("ACCEPT-LANGUAGE");
              CultureInfo culture = GetFirstCultureOrDefault(acceptLanguage, CultureInfo.InvariantCulture);

              string description = null;
              DvDevice rootDevice;
              lock (_serverData.SyncObj)
                if (config.RootDeviceDescriptionPathsToRootDevices.TryGetValue(pathAndQuery, out rootDevice))
                  description = rootDevice.BuildRootDeviceDescription(_serverData, config, culture);
                else if (config.SCPDPathsToServices.TryGetValue(pathAndQuery, out service))
                  description = service.BuildSCPDDocument(config, _serverData);
              if (description != null)
              {
                IHttpResponse response = request.CreateResponse(context);
                response.Status = HttpStatusCode.OK;
                response.ContentType = "text/xml; charset=utf-8";
                if (!string.IsNullOrEmpty(acceptLanguage))
                  response.AddHeader("CONTENT-LANGUAGE", culture.ToString());
                using (MemoryStream responseStream = new MemoryStream(UPnPConsts.UTF8_NO_BOM.GetBytes(description)))
                  CompressionHelper.WriteCompressedStream(acceptEncoding, response, responseStream);
                SafeSendResponse(response);
                return;
              }
            }
          }
          else if (request.Method == "POST")
          { // POST of control messages
            if (config.ControlPathsToServices.TryGetValue(pathAndQuery, out service))
            {
              string contentType = request.Headers.Get("CONTENT-TYPE");
              string userAgentStr = request.Headers.Get("USER-AGENT");
              IHttpResponse response = request.CreateResponse(context);
              int minorVersion;
              if (string.IsNullOrEmpty(userAgentStr))
                minorVersion = 0;
              else if (!ParserHelper.ParseUserAgentUPnP1MinorVersion(userAgentStr, out minorVersion))
              {
                response.Status = HttpStatusCode.BadRequest;
                SafeSendResponse(response);
                return;
              }
              string mediaType;
              Encoding encoding;
              if (!EncodingUtils.TryParseContentTypeEncoding(contentType, Encoding.UTF8, out mediaType, out encoding))
                throw new ArgumentException("Unable to parse content type");
              if (mediaType != "text/xml")
              { // As specified in (DevArch), 3.2.1
                response.Status = HttpStatusCode.UnsupportedMediaType;
                SafeSendResponse(response);
                return;
              }
              response.AddHeader("DATE", DateTime.Now.ToUniversalTime().ToString("R"));
              response.AddHeader("SERVER", UPnPConfiguration.UPnPMachineInfoHeader);
              response.AddHeader("CONTENT-TYPE", "text/xml; charset=\"utf-8\"");
              string result;
              HttpStatusCode status;
              try
              {
                CallContext callContext = new CallContext(request, context, config);
                status = SOAPHandler.HandleRequest(service, request.Body, encoding, minorVersion >= 1, callContext, out result);
              }
              catch (Exception e)
              {
                UPnPConfiguration.LOGGER.Warn("Action invocation failed", e);
                result = SOAPHandler.CreateFaultDocument(501, "Action failed");
                status = HttpStatusCode.InternalServerError;
              }
              response.Status = status;
              using (MemoryStream responseStream = new MemoryStream(encoding.GetBytes(result)))
                CompressionHelper.WriteCompressedStream(acceptEncoding, response, responseStream);
              SafeSendResponse(response);
              return;
            }
          }
          else if (request.Method == "SUBSCRIBE" || request.Method == "UNSUBSCRIBE")
          {
            GENAServerController gsc;
            lock (_serverData.SyncObj)
              gsc = _serverData.GENAController;
            if (gsc.HandleHTTPRequest(request, context, config))
              return;
          }
          else
          {
            context.Respond(HttpHelper.HTTP11, HttpStatusCode.MethodNotAllowed, null);
            return;
          }
        }
        // Url didn't match
        context.Respond(HttpHelper.HTTP11, HttpStatusCode.NotFound, null);
      }
      catch (Exception e)
      {
        UPnPConfiguration.LOGGER.Error("UPnPServer: Error handling HTTP request '{0}'", e, uri);
        IHttpResponse response = request.CreateResponse(context);
        response.Status = HttpStatusCode.InternalServerError;
        SafeSendResponse(response);
      }
    }
 static UPnPError OnLoadItem(DvAction action, IList<object> inParams, out IList<object> outParams,
     CallContext context)
 {
   string systemId = (string) inParams[0];
   ResourcePath path = ResourcePath.Deserialize((string) inParams[1]);
   IEnumerable<Guid> necessaryMIATypes = MarshallingHelper.ParseCsvGuidCollection((string) inParams[2]);
   IEnumerable<Guid> optionalMIATypes = MarshallingHelper.ParseCsvGuidCollection((string) inParams[3]);
   MediaItem mediaItem = ServiceRegistration.Get<IMediaLibrary>().LoadItem(systemId, path,
       necessaryMIATypes, optionalMIATypes);
   outParams = new List<object> {mediaItem};
   return null;
 }