Ejemplo n.º 1
0
 public LocalizationController(ILocalizationService localizationService)
 {
     _localizationService = localizationService;
     _serializerSettings  = STJson.GetSerializerSettings();
     _serializerSettings.DictionaryKeyPolicy  = null;
     _serializerSettings.PropertyNamingPolicy = null;
 }
Ejemplo n.º 2
0
        public LocalizationModule(ILocalizationService localizationService)
        {
            _localizationService = localizationService;
            _serializerSettings  = STJson.GetSerializerSettings();
            _serializerSettings.DictionaryKeyPolicy  = null;
            _serializerSettings.PropertyNamingPolicy = null;

            Get("/", x => GetLocalizationDictionary());
        }
Ejemplo n.º 3
0
        public static CustomFilter ToModel(this CustomFilterResource resource)
        {
            if (resource == null)
            {
                return(null);
            }

            return(new CustomFilter
            {
                Id = resource.Id,
                Type = resource.Type,
                Label = resource.Label,
                Filters = STJson.ToJson(resource.Filters)
            });
        }
Ejemplo n.º 4
0
        public static CustomFilterResource ToResource(this CustomFilter model)
        {
            if (model == null)
            {
                return(null);
            }

            return(new CustomFilterResource
            {
                Id = model.Id,
                Type = model.Type,
                Label = model.Label,
                Filters = STJson.Deserialize <List <ExpandoObject> >(model.Filters)
            });
        }
Ejemplo n.º 5
0
        public ActionResult <CommandResource> StartCommand(CommandResource commandResource)
        {
            var commandType =
                _knownTypes.GetImplementations(typeof(Command))
                .Single(c => c.Name.Replace("Command", "")
                        .Equals(commandResource.Name, StringComparison.InvariantCultureIgnoreCase));

            Request.Body.Seek(0, SeekOrigin.Begin);
            using var reader = new StreamReader(Request.Body);
            var body = reader.ReadToEnd();

            dynamic command = STJson.Deserialize(body, commandType);

            command.Trigger             = CommandTrigger.Manual;
            command.SuppressMessages    = !command.SendUpdatesToClient;
            command.SendUpdatesToClient = true;

            var trackedCommand = _commandQueueManager.Push(command, CommandPriority.Normal, CommandTrigger.Manual);

            return(Created(trackedCommand.Id));
        }
Ejemplo n.º 6
0
 public static object FromJson(this Stream body, Type type)
 {
     body.Position = 0;
     return(STJson.Deserialize(body, type));
 }
Ejemplo n.º 7
0
 public Task WriteToResponse(HttpResponse response, HttpStatusCode statusCode = HttpStatusCode.InternalServerError)
 {
     response.StatusCode  = (int)statusCode;
     response.ContentType = "application/json";
     return(STJson.SerializeAsync(this, response.Body));
 }
Ejemplo n.º 8
0
        public async Task HandleException(HttpContext context)
        {
            _logger.Trace("Handling Exception");

            var response = context.Response;
            var exceptionHandlerPathFeature = context.Features.Get <IExceptionHandlerPathFeature>();
            var exception = exceptionHandlerPathFeature?.Error;

            _logger.Warn(exception);

            var statusCode = HttpStatusCode.InternalServerError;
            var errorModel = new ErrorModel
            {
                Message     = exception.Message,
                Description = exception.ToString()
            };

            if (exception is ApiException apiException)
            {
                _logger.Warn(apiException, "API Error:\n{0}", apiException.Message);

                /* var body = RequestStream.FromStream(context.Request.Body).AsString();
                 * _logger.Trace("Request body:\n{0}", body);*/

                errorModel = new ErrorModel(apiException);
                statusCode = apiException.StatusCode;
            }
            else if (exception is ValidationException validationException)
            {
                _logger.Warn("Invalid request {0}", validationException.Message);

                response.StatusCode  = (int)HttpStatusCode.BadRequest;
                response.ContentType = "application/json";
                await response.WriteAsync(STJson.ToJson(validationException.Errors));

                return;
            }
            else if (exception is NzbDroneClientException clientException)
            {
                errorModel = new ErrorModel
                {
                    Message     = exception.Message,
                    Description = exception.ToString()
                };
                statusCode = clientException.StatusCode;
            }
            else if (exception is ModelNotFoundException notFoundException)
            {
                errorModel = new ErrorModel
                {
                    Message     = exception.Message,
                    Description = exception.ToString()
                };
                statusCode = HttpStatusCode.NotFound;
            }
            else if (exception is ModelConflictException conflictException)
            {
                _logger.Error(exception, "DB error");
                errorModel = new ErrorModel
                {
                    Message     = exception.Message,
                    Description = exception.ToString()
                };
                statusCode = HttpStatusCode.Conflict;
            }
            else if (exception is SQLiteException sqLiteException)
            {
                if (context.Request.Method == "PUT" || context.Request.Method == "POST")
                {
                    if (sqLiteException.Message.Contains("constraint failed"))
                    {
                        errorModel = new ErrorModel
                        {
                            Message = exception.Message,
                        };
                        statusCode = HttpStatusCode.Conflict;
                    }
                }

                _logger.Error(sqLiteException, "[{0} {1}]", context.Request.Method, context.Request.Path);
            }

            _logger.Fatal(exception, "Request Failed. {0} {1}", context.Request.Method, context.Request.Path);

            await errorModel.WriteToResponse(response, statusCode);
        }
Ejemplo n.º 9
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(b =>
            {
                b.ClearProviders();
                b.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                b.AddFilter("Microsoft.AspNetCore", Microsoft.Extensions.Logging.LogLevel.Warning);
                b.AddFilter("Readarr.Http.Authentication", LogLevel.Information);
                b.AddNLog();
            });

            services.AddRouting(options => options.LowercaseUrls = true);

            services.AddResponseCompression();

            services.AddCors(options =>
            {
                options.AddPolicy(VersionedApiControllerAttribute.API_CORS_POLICY,
                                  builder =>
                                  builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader());

                options.AddPolicy("AllowGet",
                                  builder =>
                                  builder.AllowAnyOrigin()
                                  .WithMethods("GET", "OPTIONS")
                                  .AllowAnyHeader());
            });

            services
            .AddControllers(options =>
            {
                options.ReturnHttpNotAcceptable = true;
            })
            .AddApplicationPart(typeof(SystemController).Assembly)
            .AddApplicationPart(typeof(StaticResourceController).Assembly)
            .AddJsonOptions(options =>
            {
                STJson.ApplySerializerSettings(options.JsonSerializerOptions);
            })
            .AddControllersAsServices();

            services
            .AddSignalR()
            .AddJsonProtocol(options =>
            {
                options.PayloadSerializerOptions = STJson.GetSerializerSettings();
            });

            services.AddSingleton <IAuthorizationPolicyProvider, UiAuthorizationPolicyProvider>();
            services.AddAuthorization(options =>
            {
                options.AddPolicy("SignalR", policy =>
                {
                    policy.AuthenticationSchemes.Add("SignalR");
                    policy.RequireAuthenticatedUser();
                });

                // Require auth on everything except those marked [AllowAnonymous]
                options.FallbackPolicy = new AuthorizationPolicyBuilder("API")
                                         .RequireAuthenticatedUser()
                                         .Build();
            });

            services.AddAppAuthentication();
        }
Ejemplo n.º 10
0
 public void Serialize <TModel>(MediaRange contentType, TModel model, Stream outputStream)
 {
     STJson.Serialize(model, outputStream, _serializerSettings);
 }
Ejemplo n.º 11
0
 public NancyJsonSerializer()
 {
     _serializerSettings = STJson.GetSerializerSettings();
 }
Ejemplo n.º 12
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(b =>
            {
                b.ClearProviders();
                b.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                b.AddFilter("Microsoft.AspNetCore", Microsoft.Extensions.Logging.LogLevel.Warning);
                b.AddFilter("Radarr.Http.Authentication", LogLevel.Information);
                b.AddFilter("Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager", LogLevel.Error);
                b.AddNLog();
            });

            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                options.KnownNetworks.Clear();
                options.KnownProxies.Clear();
            });

            services.AddRouting(options => options.LowercaseUrls = true);

            services.AddResponseCompression(options => options.EnableForHttps = true);

            services.AddCors(options =>
            {
                options.AddPolicy(VersionedApiControllerAttribute.API_CORS_POLICY,
                                  builder =>
                                  builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader());

                options.AddPolicy("AllowGet",
                                  builder =>
                                  builder.AllowAnyOrigin()
                                  .WithMethods("GET", "OPTIONS")
                                  .AllowAnyHeader());
            });

            services
            .AddControllers(options =>
            {
                options.ReturnHttpNotAcceptable = true;
            })
            .AddApplicationPart(typeof(SystemController).Assembly)
            .AddApplicationPart(typeof(StaticResourceController).Assembly)
            .AddJsonOptions(options =>
            {
                STJson.ApplySerializerSettings(options.JsonSerializerOptions);
            })
            .AddControllersAsServices();

            services
            .AddSignalR()
            .AddJsonProtocol(options =>
            {
                options.PayloadSerializerOptions = STJson.GetSerializerSettings();
            });

            services.AddDataProtection()
            .PersistKeysToFileSystem(new DirectoryInfo(Configuration["dataProtectionFolder"]));

            services.AddSingleton <IAuthorizationPolicyProvider, UiAuthorizationPolicyProvider>();
            services.AddAuthorization(options =>
            {
                options.AddPolicy("SignalR", policy =>
                {
                    policy.AuthenticationSchemes.Add("SignalR");
                    policy.RequireAuthenticatedUser();
                });

                // Require auth on everything except those marked [AllowAnonymous]
                options.FallbackPolicy = new AuthorizationPolicyBuilder("API")
                                         .RequireAuthenticatedUser()
                                         .Build();
            });

            services.AddAppAuthentication();

            services.PostConfigure <ApiBehaviorOptions>(options =>
            {
                var builtInFactory = options.InvalidModelStateResponseFactory;

                options.InvalidModelStateResponseFactory = context =>
                {
                    var loggerFactory = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>();
                    var logger        = loggerFactory.CreateLogger(context.ActionDescriptor.DisplayName);

                    logger.LogError(STJson.ToJson(context.ModelState));

                    return(builtInFactory(context));
                };
            });
        }
Ejemplo n.º 13
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(b =>
            {
                b.ClearProviders();
                b.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                b.AddFilter("Microsoft.AspNetCore", Microsoft.Extensions.Logging.LogLevel.Warning);
                b.AddFilter("Radarr.Http.Authentication", LogLevel.Information);
                b.AddFilter("Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager", LogLevel.Error);
                b.AddNLog();
            });

            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                options.KnownNetworks.Clear();
                options.KnownProxies.Clear();
            });

            services.AddRouting(options => options.LowercaseUrls = true);

            services.AddResponseCompression(options => options.EnableForHttps = true);

            services.AddCors(options =>
            {
                options.AddPolicy(VersionedApiControllerAttribute.API_CORS_POLICY,
                                  builder =>
                                  builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader());

                options.AddPolicy("AllowGet",
                                  builder =>
                                  builder.AllowAnyOrigin()
                                  .WithMethods("GET", "OPTIONS")
                                  .AllowAnyHeader());
            });

            services
            .AddControllers(options =>
            {
                options.ReturnHttpNotAcceptable = true;
            })
            .AddApplicationPart(typeof(SystemController).Assembly)
            .AddApplicationPart(typeof(StaticResourceController).Assembly)
            .AddJsonOptions(options =>
            {
                STJson.ApplySerializerSettings(options.JsonSerializerOptions);
            })
            .AddControllersAsServices();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v3", new OpenApiInfo
                {
                    Version     = "3.0.0",
                    Title       = "Radarr",
                    Description = "Radarr API docs",
                    License     = new OpenApiLicense
                    {
                        Name = "GPL-3.0",
                        Url  = new Uri("https://github.com/Radarr/Radarr/blob/develop/LICENSE")
                    }
                });

                var apiKeyHeader = new OpenApiSecurityScheme
                {
                    Name        = "X-Api-Key",
                    Type        = SecuritySchemeType.ApiKey,
                    Scheme      = "apiKey",
                    Description = "Apikey passed as header",
                    In          = ParameterLocation.Header,
                    Reference   = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id   = "X-Api-Key"
                    },
                };

                c.AddSecurityDefinition("X-Api-Key", apiKeyHeader);

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    { apiKeyHeader, new string[] { } }
                });

                var apikeyQuery = new OpenApiSecurityScheme
                {
                    Name        = "apikey",
                    Type        = SecuritySchemeType.ApiKey,
                    Scheme      = "apiKey",
                    Description = "Apikey passed as header",
                    In          = ParameterLocation.Query,
                    Reference   = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id   = "apikey"
                    },
                };

                c.AddServer(new OpenApiServer
                {
                    Url       = "{protocol}://{hostpath}",
                    Variables = new Dictionary <string, OpenApiServerVariable>
                    {
                        { "protocol", new OpenApiServerVariable {
                              Default = "http", Enum = new List <string> {
                                  "http", "https"
                              }
                          } },
                        { "hostpath", new OpenApiServerVariable {
                              Default = "localhost:7878"
                          } }
                    }
                });

                c.AddSecurityDefinition("apikey", apikeyQuery);

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    { apikeyQuery, new string[] { } }
                });
            });

            services
            .AddSignalR()
            .AddJsonProtocol(options =>
            {
                options.PayloadSerializerOptions = STJson.GetSerializerSettings();
            });

            services.AddDataProtection()
            .PersistKeysToFileSystem(new DirectoryInfo(Configuration["dataProtectionFolder"]));

            services.AddSingleton <IAuthorizationPolicyProvider, UiAuthorizationPolicyProvider>();
            services.AddAuthorization(options =>
            {
                options.AddPolicy("SignalR", policy =>
                {
                    policy.AuthenticationSchemes.Add("SignalR");
                    policy.RequireAuthenticatedUser();
                });

                // Require auth on everything except those marked [AllowAnonymous]
                options.FallbackPolicy = new AuthorizationPolicyBuilder("API")
                                         .RequireAuthenticatedUser()
                                         .Build();
            });

            services.AddAppAuthentication();

            services.PostConfigure <ApiBehaviorOptions>(options =>
            {
                var builtInFactory = options.InvalidModelStateResponseFactory;

                options.InvalidModelStateResponseFactory = context =>
                {
                    var loggerFactory = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>();
                    var logger        = loggerFactory.CreateLogger(context.ActionDescriptor.DisplayName);

                    logger.LogError(STJson.ToJson(context.ModelState));

                    return(builtInFactory(context));
                };
            });
        }
Ejemplo n.º 14
0
        public void StartServer()
        {
            if (OsInfo.IsWindows)
            {
                if (_runtimeInfo.IsAdmin)
                {
                    _firewallAdapter.MakeAccessible();
                }
            }

            var bindAddress = _configFileProvider.BindAddress;
            var enableSsl   = _configFileProvider.EnableSsl;
            var sslCertPath = _configFileProvider.SslCertPath;

            var urls = new List <string>();

            urls.Add(BuildUrl("http", bindAddress, _configFileProvider.Port));

            if (enableSsl && sslCertPath.IsNotNullOrWhiteSpace())
            {
                urls.Add(BuildUrl("https", bindAddress, _configFileProvider.SslPort));
            }

            _host = new WebHostBuilder()
                    .UseUrls(urls.ToArray())
                    .UseKestrel(options =>
            {
                if (enableSsl && sslCertPath.IsNotNullOrWhiteSpace())
                {
                    options.ConfigureHttpsDefaults(configureOptions =>
                    {
                        X509Certificate2 certificate;

                        try
                        {
                            certificate = new X509Certificate2(sslCertPath, _configFileProvider.SslCertPassword, X509KeyStorageFlags.DefaultKeySet);
                        }
                        catch (CryptographicException ex)
                        {
                            if (ex.HResult == 0x2 || ex.HResult == 0x2006D080)
                            {
                                throw new RadarrStartupException(ex, $"The SSL certificate file {sslCertPath} does not exist");
                            }

                            throw new RadarrStartupException(ex);
                        }

                        configureOptions.ServerCertificate = certificate;
                    });
                }
            })
                    .ConfigureKestrel(serverOptions =>
            {
                serverOptions.AllowSynchronousIO        = true;
                serverOptions.Limits.MaxRequestBodySize = null;
            })
                    .ConfigureLogging(logging =>
            {
                logging.AddProvider(new NLogLoggerProvider());
                logging.SetMinimumLevel(LogLevel.Warning);
            })
                    .ConfigureServices(services =>
            {
                services
                .AddSignalR()
#if !NETCOREAPP
                .AddJsonProtocol(options =>
                {
                    options.PayloadSerializerSettings = Json.GetSerializerSettings();
                });
#else
                .AddJsonProtocol(options =>
                {
                    options.PayloadSerializerOptions = STJson.GetSerializerSettings();
                });
#endif
            })
Ejemplo n.º 15
0
        public void StartServer()
        {
            if (OsInfo.IsWindows && _runtimeInfo.IsAdmin)
            {
                _firewallAdapter.MakeAccessible();
            }

            var bindAddress = _configFileProvider.BindAddress;
            var enableSsl   = _configFileProvider.EnableSsl;
            var sslCertPath = _configFileProvider.SslCertPath;

            var urls = new List <string>();

            urls.Add(BuildUrl("http", bindAddress, _configFileProvider.Port));

            if (enableSsl && sslCertPath.IsNotNullOrWhiteSpace())
            {
                urls.Add(BuildUrl("https", bindAddress, _configFileProvider.SslPort));
            }

            _host = new WebHostBuilder()
                    .UseUrls(urls.ToArray())
                    .UseKestrel(options =>
            {
                if (enableSsl && sslCertPath.IsNotNullOrWhiteSpace())
                {
                    options.ConfigureHttpsDefaults(configureOptions =>
                    {
                        var certificate = new X509Certificate2();
                        certificate.Import(_configFileProvider.SslCertPath, _configFileProvider.SslCertPassword, X509KeyStorageFlags.DefaultKeySet);

                        configureOptions.ServerCertificate = certificate;
                    });
                }
            })
                    .ConfigureKestrel(serverOptions =>
            {
                serverOptions.AllowSynchronousIO        = true;
                serverOptions.Limits.MaxRequestBodySize = null;
            })
                    .ConfigureLogging(logging =>
            {
                logging.AddProvider(new NLogLoggerProvider());
                logging.SetMinimumLevel(LogLevel.Warning);
            })
                    .ConfigureServices(services =>
            {
                services
                .AddSignalR()
                .AddJsonProtocol(options =>
                {
                    options.PayloadSerializerOptions = STJson.GetSerializerSettings();
                });
            })
                    .Configure(app =>
            {
                app.UseRouting();
                app.Properties["host.AppName"] = BuildInfo.AppName;
                app.UsePathBase(_configFileProvider.UrlBase);

                foreach (var middleWare in _middlewares.OrderBy(c => c.Order))
                {
                    _logger.Debug("Attaching {0} to host", middleWare.GetType().Name);
                    middleWare.Attach(app);
                }
            })
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .Build();

            _logger.Info("Listening on the following URLs:");

            foreach (var url in urls)
            {
                _logger.Info("  {0}", url);
            }

            _host.Start();
        }