protected bool TryGetService(string usn, string svcid, out CpService service) { string deviceUUID; string serviceTypeVersion; service = null; if (!ParserHelper.TryParseUSN(usn, out deviceUUID, out serviceTypeVersion)) { return(false); } string type; int version; if (!ParserHelper.TryParseTypeVersion_URN(serviceTypeVersion, out type, out version)) { return(false); } foreach (CpService matchingService in _connection.Device.FindServicesByServiceTypeAndVersion(type, version, false)) { if (matchingService.ServiceId == svcid) { service = matchingService; return(true); } } return(false); }
public EventSubscription(string sid, ServiceDescriptor serviceDescriptor, CpService service, DateTime expiration) { _sid = sid; _serviceDescriptor = serviceDescriptor; _service = service; _expiration = expiration; }
private Response SaveCouchPotato() { var couchPotatoSettings = this.Bind <CouchPotatoSettings>(); var valid = this.Validate(couchPotatoSettings); if (!valid.IsValid) { return(Response.AsJson(valid.SendJsonError())); } var watcherSettings = WatcherSettings.GetSettings(); if (watcherSettings.Enabled) { return (Response.AsJson(new JsonResponseModel { Result = false, Message = "Cannot have Watcher and CouchPotato both enabled." })); } couchPotatoSettings.ApiKey = couchPotatoSettings.ApiKey.Trim(); var result = CpService.SaveSettings(couchPotatoSettings); return(Response.AsJson(result ? new JsonResponseModel { Result = true, Message = "Successfully Updated the Settings for CouchPotato!" } : new JsonResponseModel { Result = false, Message = "Could not update the settings, take a look at the logs." })); }
private void OnSubscribeOrRenewSubscriptionResponseReceived(IAsyncResult ar) { ChangeEventSubscriptionState state = (ChangeEventSubscriptionState)ar.AsyncState; lock (_cpData.SyncObj) _pendingCalls.Remove(state); CpService service = state.Service; try { HttpWebResponse response = (HttpWebResponse)state.Request.EndGetResponse(ar); try { if (response.StatusCode != HttpStatusCode.OK) { service.InvokeEventSubscriptionFailed(new UPnPError((uint)response.StatusCode, response.StatusDescription)); return; } string dateStr = response.Headers.Get("DATE"); string sid = response.Headers.Get("SID"); string timeoutStr = response.Headers.Get("TIMEOUT"); DateTime date = DateTime.ParseExact(dateStr, "R", CultureInfo.InvariantCulture).ToLocalTime(); int timeout; if (string.IsNullOrEmpty(timeoutStr) || (!timeoutStr.StartsWith("Second-") || !int.TryParse(timeoutStr.Substring("Second-".Length).Trim(), out timeout))) { service.InvokeEventSubscriptionFailed(new UPnPError((int)HttpStatusCode.BadRequest, "Invalid answer from UPnP device")); return; } DateTime expiration = date.AddSeconds(timeout); EventSubscription subscription; lock (_cpData.SyncObj) { if (_subscriptions.TryGetValue(sid, out subscription)) { subscription.Expiration = expiration; } else { _subscriptions.Add(sid, new EventSubscription(sid, state.ServiceDescriptor, service, expiration)); } CheckSubscriptionRenewalTimer(_subscriptions.Values); } } finally { response.Close(); } } catch (WebException e) { HttpWebResponse response = (HttpWebResponse)e.Response; service.InvokeEventSubscriptionFailed(new UPnPError(response == null ? 503 : (uint)response.StatusCode, "Cannot complete event subscription")); if (response != null) { response.Close(); } return; } }
public ClientConnection(UPnPControlPoint controlPoint, DeviceConnection connection, ClientDescriptor clientDescriptor) { _controlPoint = controlPoint; _connection = connection; _clientDescriptor = clientDescriptor; _connection.DeviceDisconnected += OnUPnPDeviceDisconnected; try { CpService ccsStub = connection.Device.FindServiceByServiceId(UPnPTypesAndIds.CLIENT_CONTROLLER_SERVICE_ID); if (ccsStub == null) { throw new InvalidDataException("ClientController service not found in device '{0}' of type '{1}:{2}'", clientDescriptor.MPFrontendServerUUID, UPnPTypesAndIds.FRONTEND_SERVER_DEVICE_TYPE, UPnPTypesAndIds.FRONTEND_SERVER_DEVICE_TYPE_VERSION); } lock (_connection.CPData.SyncObj) _clientController = new UPnPClientControllerServiceProxy(ccsStub); // TODO: other services } catch (Exception) { _connection.DeviceDisconnected -= OnUPnPDeviceDisconnected; throw; } }
private Negotiator CouchPotato() { dynamic model = new ExpandoObject(); var settings = CpService.GetSettings(); model = settings; return(View["CouchPotato", model]); }
private async Task <Response> RequestMovieAndUpdateStatus(RequestedModel request, string qualityId) { var cpSettings = await CpService.GetSettingsAsync(); Log.Info("Adding movie to CouchPotato : {0}", request.Title); if (!cpSettings.Enabled) { // Approve it request.Approved = true; Log.Warn("We approved movie: {0} but could not add it to CouchPotato because it has not been setup", request.Title); // Update the record var inserted = await Service.UpdateRequestAsync(request); return(Response.AsJson(inserted ? new JsonResponseModel { Result = true, Message = "This has been approved, but It has not been sent to CouchPotato because it has not been configured." } : new JsonResponseModel { Result = false, Message = "We could not approve this request. Please try again or check the logs." })); } var result = CpApi.AddMovie(request.ImdbId, cpSettings.ApiKey, request.Title, cpSettings.FullUri, string.IsNullOrEmpty(qualityId) ? cpSettings.ProfileId : qualityId); Log.Trace("Adding movie to CP result {0}", result); if (result) { // Approve it request.Approved = true; // Update the record var inserted = await Service.UpdateRequestAsync(request); return(Response.AsJson(inserted ? new JsonResponseModel { Result = true } : new JsonResponseModel { Result = false, Message = "We could not approve this request. Please try again or check the logs." })); } return (Response.AsJson( new { Result = false, Message = "Something went wrong adding the movie to CouchPotato! Please check your settings." })); }
internal void SubscribeEvents(CpService service, ServiceDescriptor serviceDescriptor) { lock (_cpData.SyncObj) { HttpWebRequest request = CreateEventSubscribeRequest(serviceDescriptor); ChangeEventSubscriptionState state = new ChangeEventSubscriptionState(serviceDescriptor, service, request); _pendingCalls.Add(state); IAsyncResult result = state.Request.BeginGetResponse(OnSubscribeOrRenewSubscriptionResponseReceived, state); NetworkHelper.AddTimeout(request, result, EVENT_SUBSCRIPTION_CALL_TIMEOUT * 1000); } }
protected ServerStateProxy RegisterServerStateProxy(DeviceConnection connection) { CpService stub = connection.Device.FindServiceByServiceId(Consts.SERVICE_ID); if (stub == null) { throw new NotSupportedException("ServerStateProxy not supported by this UPnP device."); } _proxy = new ServerStateProxy(stub); return(_proxy); }
public EventSubscription FindEventSubscriptionByService(CpService service) { lock (_cpData.SyncObj) foreach (EventSubscription subscription in _subscriptions.Values) { if (subscription.Service == service) { return(subscription); } } return(null); }
protected IResourceInformationService TryGetResourceInformationService(RootDescriptor rootDescriptor) { DeviceConnection connection; using (_networkTracker.SharedControlPointData.Lock.EnterRead()) { object service; if (rootDescriptor.SSDPRootEntry.ClientProperties.TryGetValue(KEY_RESOURCE_INFORMATION_SERVICE, out service)) { return(service as IResourceInformationService); } } DeviceDescriptor rootDevice = DeviceDescriptor.CreateRootDeviceDescriptor(rootDescriptor); DeviceDescriptor frontendServerDevice = rootDevice.FindFirstDevice( UPnPTypesAndIds.BACKEND_SERVER_DEVICE_TYPE, UPnPTypesAndIds.BACKEND_SERVER_DEVICE_TYPE_VERSION) ?? rootDevice.FindFirstDevice(UPnPTypesAndIds.FRONTEND_SERVER_DEVICE_TYPE, UPnPTypesAndIds.FRONTEND_SERVER_DEVICE_TYPE_VERSION); if (frontendServerDevice == null) { return(null); } string deviceUuid = frontendServerDevice.DeviceUUID; try { connection = _controlPoint.Connect(rootDescriptor, deviceUuid, UPnPExtendedDataTypes.ResolveDataType); } catch (Exception e) { ServiceRegistration.Get <ILogger>().Warn("Error connecting to UPnP MP2 device '{0}'", e, deviceUuid); return(null); } try { CpService rasStub = connection.Device.FindServiceByServiceId(UPnPTypesAndIds.RESOURCE_INFORMATION_SERVICE_ID); if (rasStub == null) { throw new InvalidDataException("ResourceAccess service not found in device '{0}'", deviceUuid); } IResourceInformationService ris = new UPnPResourceInformationServiceProxy(rasStub); using (_networkTracker.SharedControlPointData.Lock.EnterWrite()) rootDescriptor.SSDPRootEntry.ClientProperties[KEY_RESOURCE_INFORMATION_SERVICE] = ris; return(ris); } catch (Exception e) { ServiceRegistration.Get <ILogger>().Warn("Error connecting to services of UPnP MP2 device '{0}'", e, deviceUuid); _controlPoint.Disconnect(deviceUuid); return(null); } }
public ServerSettingsProxy RegisterServerSettingsProxy(DeviceConnection connection) { CpService serverSettingsStub = connection.Device.FindServiceByServiceId(Consts.SERVERSETTINGS_SERVICE_ID); if (serverSettingsStub == null) { throw new NotSupportedException("ServerSettingsProxy not supported by this UPnP device."); } ServerSettingsProxy settingsProxy = new ServerSettingsProxy(serverSettingsStub); return(settingsProxy); }
public NativeTvProxy RegisterNativeTvProxy(DeviceConnection connection) { CpService tvStub = connection.Device.FindServiceByServiceId(Consts.SLIMTV_SERVICE_ID); if (tvStub == null) { throw new NotSupportedException("NativeTvService not supported by this UPnP device."); } NativeTvProxy tvProxy = new NativeTvProxy(tvStub); return(tvProxy); }
public static FanArtServiceProxy RegisterFanArtServiceProxy(DeviceConnection connection) { CpService fanArtStub = connection.Device.FindServiceByServiceId(Consts.FANART_SERVICE_ID); if (fanArtStub == null) { throw new NotSupportedException("FanArtService not supported by this UPnP device."); } FanArtServiceProxy fanArtProxy = new FanArtServiceProxy(fanArtStub); return(fanArtProxy); }
protected static void HandleVariableChangeNotification(XmlReader reader, CpService service, UPnPVersion upnpVersion) { string variableName = reader.LocalName; CpStateVariable stateVariable; if (!service.StateVariables.TryGetValue(variableName, out stateVariable)) { // We don't know that variable - this is an error case but we won't raise an exception here return; } object value = stateVariable.DataType.SoapDeserializeValue(reader, upnpVersion.VerMin == 0); service.InvokeStateVariableChanged(stateVariable, value); }
public EventSubscription FindEventSubscriptionByService(CpService service) { using (_cpData.Lock.EnterRead()) { foreach (EventSubscription subscription in _subscriptions.Values) { if (subscription.Service == service) { return(subscription); } } } return(null); }
internal void OnSubscribeEvents(CpService service) { if (!service.IsConnected) { throw new IllegalCallException("Service '{0}' is not connected to a UPnP network service", service.FullQualifiedName); } if (IsServiceSubscribedForEvents(service)) { throw new IllegalCallException("Service '{0}' is already subscribed to receive state variable change events", service.FullQualifiedName); } ServiceDescriptor serviceDescriptor = GetServiceDescriptor(service); _genaClientController.SubscribeEvents(service, serviceDescriptor); }
internal void OnUnsubscribeEvents(CpService service) { if (!service.IsConnected) { throw new IllegalCallException("Service '{0}' is not connected to a UPnP network service", service.FullQualifiedName); } EventSubscription subscription = _genaClientController.FindEventSubscriptionByService(service); if (subscription == null) { throw new IllegalCallException("Service '{0}' is not subscribed to receive events", service.FullQualifiedName); } _genaClientController.UnsubscribeEvents(subscription); }
private Response SaveCouchPotato() { var couchPotatoSettings = this.Bind <CouchPotatoSettings>(); var valid = this.Validate(couchPotatoSettings); if (!valid.IsValid) { return(Response.AsJson(valid.SendJsonError())); } var result = CpService.SaveSettings(couchPotatoSettings); return(Response.AsJson(result ? new JsonResponseModel { Result = true, Message = "Successfully Updated the Settings for CouchPotato!" } : new JsonResponseModel { Result = false, Message = "Could not update the settings, take a look at the logs." })); }
internal void OnActionCalled(CpAction action, IList <object> inParams, object clientState) { if (!action.IsConnected) { throw new UPnPDisconnectedException("Action '{0}' is not connected to a UPnP network action", action.FullQualifiedName); } CpService service = action.ParentService; ServiceDescriptor sd = GetServiceDescriptor(service); string message = SOAPHandler.EncodeCall(action, inParams, _rootDescriptor.SSDPRootEntry.UPnPVersion); HttpWebRequest request = CreateActionCallRequest(sd, action); ActionCallState state = new ActionCallState(action, clientState, request); state.SetRequestMessage(message); lock (_cpData.SyncObj) _pendingCalls.Add(state); IAsyncResult result = state.Request.BeginGetResponse(OnCallResponseReceived, state); NetworkHelper.AddTimeout(request, result, PENDING_ACTION_CALL_TIMEOUT * 1000); }
protected ServiceDescriptor GetServiceDescriptor(CpService service) { if (!service.IsConnected) { throw new IllegalCallException("Service '{0}' is not connected to a UPnP network service", service.FullQualifiedName); } IDictionary <string, ServiceDescriptor> serviceDescriptors; string deviceUUID = service.ParentDevice.UUID; if (!_rootDescriptor.ServiceDescriptors.TryGetValue(deviceUUID, out serviceDescriptors)) { throw new IllegalCallException("Device '{0}' is not connected to a UPnP network device", deviceUUID); } ServiceDescriptor sd; if (!serviceDescriptors.TryGetValue(service.ServiceTypeVersion_URN, out sd)) { throw new IllegalCallException("Service '{0}' in device '{1}' is not connected to a UPnP network service", service.ServiceTypeVersion_URN, deviceUUID); } return(sd); }
private async Task <Response> GetCpProfiles() { var settings = this.Bind <CouchPotatoSettings>(); var valid = this.Validate(settings); if (!valid.IsValid) { return(Response.AsJson(valid.SendJsonError())); } var profiles = CpApi.GetProfiles(settings.FullUri, settings.ApiKey); // set the cache if (profiles != null) { Cache.Set(CacheKeys.CouchPotatoQualityProfiles, profiles); } // Save the first profile found (user might not press save...) settings.ProfileId = profiles?.list?.FirstOrDefault()?._id; await CpService.SaveSettingsAsync(settings); return(Response.AsJson(profiles)); }
public UPnPUserProfileDataManagementServiceProxy(CpService serviceStub) : base(serviceStub, "UserProfileDataManagement") { }
public ServerStateProxy(CpService serviceStub) : base(serviceStub, Consts.SERVICE_NAME) { serviceStub.StateVariableChanged += OnStateVariableChanged; serviceStub.SubscribeStateVariables(); }
public ServerSettingsProxy(CpService serviceStub) : base(serviceStub, Consts.SERVERSETTINGS_SERVICE_NAME) { ServiceRegistration.Set <IServerSettingsClient>(this); }
public NativeTvProxy(CpService serviceStub) : base(serviceStub, "NativeTv") { ServiceRegistration.Set <ITvProvider>(this); }
private void SubscribeFailed(CpService service, UPnPError error) { Log.Log.Error("DRI: failed to subscribe to state variable events for service {0}, code = {1}, description = {2}", _unqualifiedServiceName, error.ErrorCode, error.ErrorDescription); }
public UPnPServerControllerServiceProxy(CpService serviceStub) : base(serviceStub, "ServerController") { serviceStub.StateVariableChanged += OnStateVariableChanged; serviceStub.SubscribeStateVariables(); }
public UPnPClientControllerServiceProxy(CpService serviceStub) : base(serviceStub, "ClientController") { }
private Response RequestMovie(int movieId) { var movieApi = new TheMovieDbApi(); var movieInfo = movieApi.GetMovieInformation(movieId).Result; var fullMovieName = $"{movieInfo.Title}{(movieInfo.ReleaseDate.HasValue ? $" ({movieInfo.ReleaseDate.Value.Year})" : string.Empty)}"; Log.Trace("Getting movie info from TheMovieDb"); Log.Trace(movieInfo.DumpJson); //#if !DEBUG var settings = PrService.GetSettings(); // check if the movie has already been requested Log.Info("Requesting movie with id {0}", movieId); var existingRequest = RequestService.CheckRequest(movieId); if (existingRequest != null) { // check if the current user is already marked as a requester for this movie, if not, add them if (!existingRequest.UserHasRequested(Username)) { existingRequest.RequestedUsers.Add(Username); RequestService.UpdateRequest(existingRequest); } return(Response.AsJson(new JsonResponseModel { Result = true, Message = settings.UsersCanViewOnlyOwnRequests ? $"{fullMovieName} was successfully added!" : $"{fullMovieName} has already been requested!" })); } Log.Debug("movie with id {0} doesnt exists", movieId); try { var movies = Checker.GetPlexMovies(); if (Checker.IsMovieAvailable(movies.ToArray(), movieInfo.Title, movieInfo.ReleaseDate?.Year.ToString())) { return(Response.AsJson(new JsonResponseModel { Result = false, Message = $"{fullMovieName} is already in Plex!" })); } } catch (ApplicationSettingsException) { return(Response.AsJson(new JsonResponseModel { Result = false, Message = $"We could not check if {fullMovieName} is in Plex, are you sure it's correctly setup?" })); } //#endif var model = new RequestedModel { ProviderId = movieInfo.Id, Type = RequestType.Movie, Overview = movieInfo.Overview, ImdbId = movieInfo.ImdbId, PosterPath = "http://image.tmdb.org/t/p/w150/" + movieInfo.PosterPath, Title = movieInfo.Title, ReleaseDate = movieInfo.ReleaseDate ?? DateTime.MinValue, Status = movieInfo.Status, RequestedDate = DateTime.UtcNow, Approved = false, RequestedUsers = new List <string> { Username }, Issues = IssueState.None, }; Log.Trace(settings.DumpJson()); if (ShouldAutoApprove(RequestType.Movie, settings)) { var cpSettings = CpService.GetSettings(); Log.Trace("Settings: "); Log.Trace(cpSettings.DumpJson); if (cpSettings.Enabled) { Log.Info("Adding movie to CP (No approval required)"); var result = CouchPotatoApi.AddMovie(model.ImdbId, cpSettings.ApiKey, model.Title, cpSettings.FullUri, cpSettings.ProfileId); Log.Debug("Adding movie to CP result {0}", result); if (result) { model.Approved = true; Log.Info("Adding movie to database (No approval required)"); RequestService.AddRequest(model); if (ShouldSendNotification()) { var notificationModel = new NotificationModel { Title = model.Title, User = Username, DateTime = DateTime.Now, NotificationType = NotificationType.NewRequest }; NotificationService.Publish(notificationModel); } return(Response.AsJson(new JsonResponseModel { Result = true, Message = $"{fullMovieName} was successfully added!" })); } return (Response.AsJson(new JsonResponseModel { Result = false, Message = "Something went wrong adding the movie to CouchPotato! Please check your settings." })); } else { model.Approved = true; Log.Info("Adding movie to database (No approval required)"); RequestService.AddRequest(model); if (ShouldSendNotification()) { var notificationModel = new NotificationModel { Title = model.Title, User = Username, DateTime = DateTime.Now, NotificationType = NotificationType.NewRequest }; NotificationService.Publish(notificationModel); } return(Response.AsJson(new JsonResponseModel { Result = true, Message = $"{fullMovieName} was successfully added!" })); } } try { Log.Info("Adding movie to database"); var id = RequestService.AddRequest(model); var notificationModel = new NotificationModel { Title = model.Title, User = Username, DateTime = DateTime.Now, NotificationType = NotificationType.NewRequest }; NotificationService.Publish(notificationModel); return(Response.AsJson(new JsonResponseModel { Result = true, Message = $"{fullMovieName} was successfully added!" })); } catch (Exception e) { Log.Fatal(e); return(Response.AsJson(new JsonResponseModel { Result = false, Message = "Something went wrong adding the movie to CouchPotato! Please check your settings." })); } }