Merge pull request #4072 from Ombi-app/feature/reverse-proxy-chnage

Feature/reverse proxy chnage
pull/4075/head v4.0.1128
Jamie 4 years ago committed by GitHub
commit 7f0d427827
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,10 @@
[*.cs]
# CS1591: Missing XML comment for publicly visible type or member
dotnet_diagnostic.CS1591.severity = none
# RCS1090: Add call to 'ConfigureAwait' (or vice versa).
dotnet_diagnostic.RCS1090.severity = none
# RCS1036: Remove redundant empty line.
dotnet_diagnostic.RCS1036.severity = none

@ -8,6 +8,5 @@ namespace Ombi.Attributes
{
Roles = "Admin";
}
}
}

@ -2,39 +2,7 @@
<html lang="en">
<head>
<script type='text/javascript'>
function configExists(url) {
var req = new XMLHttpRequest();
req.open('GET', url, false);
req.send();
return req.status === 200 && req.responseURL === url;
}
var probePath = 'styles/please-wait.js';
var origin = document.location.origin;
var pathSegments = document.location.pathname.split('/');
var basePath = '/'
var configFound = false;
for (var i = 0; i < pathSegments.length; i++) {
var segment = pathSegments[i];
if (segment.length > 0) {
basePath = basePath + segment + '/';
}
var fullPath = origin + basePath + probePath;
configFound = configExists(fullPath);
if (configFound) {
break;
}
}
var basePathToUse = basePath.substring(0, basePath.length - 1); // trim off the trailing '/'
basePathToUse == '' ? '/' : basePathToUse;
window["baseHref"] = configFound ? basePathToUse : '/';
document.write("<base href='" + (configFound ? basePath : '/') + "' />");
console.log(window["baseHref"]);
</script>
<script type='text/javascript'>window["baseHref"] = '/';</script>
<style>
.sk-folding-cube .sk-cube:before {
background-color: white !important;
@ -81,7 +49,6 @@ var line = lines[Math.floor(Math.random() * lines.length)];
window.loading_screen = window.pleaseWait({
// logo: "assets/images/logo.png",
template: `<div class='pg-loading-inner'>
<div class='pg-loading-center-outer'>
<div class='pg-loading-center-middle'>

@ -15,9 +15,7 @@ import { AppModule } from "./app/app.module";
import { hmrBootstrap } from "./hmr";
declare var module: any;
// declare var __webpack_require__: any;
// __webpack_require__.p = '/ombi';
// __webpack_require__ = '/ombi';
if (environment.production) {
enableProdMode();
}

@ -45,6 +45,10 @@
<None Remove="Styles\**" />
<None Remove="wwwroot\dist\**" />
</ItemGroup>
<ItemGroup>
<None Include="..\.editorconfig" Link=".editorconfig" />
</ItemGroup>
<ItemGroup>
@ -68,7 +72,7 @@
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
<PackageReference Include="System.Security.Cryptography.Csp" Version="4.3.0" />
<PackageReference Include="Microsoft.AspNetCore.SpaServices" Version="3.1.10" />
<PackageReference Include="Microsoft.AspNetCore.SpaServices" Version="5.0.0-preview.8.20414.8" />
<PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="5.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.0" />
</ItemGroup>

@ -13,6 +13,10 @@ using Ombi.Extensions;
using Ombi.Helpers;
using System.Threading.Tasks;
using System.Collections.Generic;
using Newtonsoft.Json;
using Ombi.Settings.Settings.Models;
using System.Diagnostics;
using System.IO;
namespace Ombi
{
@ -45,10 +49,11 @@ namespace Ombi
}
});
Console.WriteLine(HelpOutput(result));
if (baseUrl.HasValue())
{
Console.WriteLine($"Base Url: {baseUrl}");
}
UrlArgs = host;
var urlValue = string.Empty;
@ -57,115 +62,75 @@ namespace Ombi
demoInstance.Demo = demo;
instance.StoragePath = storagePath ?? string.Empty;
var services = new ServiceCollection();
services.ConfigureDatabases(null);
using (var provider = services.BuildServiceProvider())
{
var settingsDb = provider.GetRequiredService<SettingsContext>();
using var provider = services.BuildServiceProvider();
var settingsDb = provider.GetRequiredService<SettingsContext>();
var ombiDb = provider.GetRequiredService<OmbiContext>();
if (migrate)
{
Console.WriteLine("Migrate in progress...");
if (migrate)
{
Console.WriteLine("Migrate in progress...");
var migrationTasks = new List<Task>();
var externalDb = provider.GetRequiredService<ExternalContext>();
var ombiDb = provider.GetRequiredService<OmbiContext>();
migrationTasks.Add(settingsDb.Database.MigrateAsync());
migrationTasks.Add(ombiDb.Database.MigrateAsync());
migrationTasks.Add(externalDb.Database.MigrateAsync());
var migrationTasks = new List<Task>();
var externalDb = provider.GetRequiredService<ExternalContext>();
migrationTasks.Add(settingsDb.Database.MigrateAsync());
migrationTasks.Add(ombiDb.Database.MigrateAsync());
migrationTasks.Add(externalDb.Database.MigrateAsync());
Task.WaitAll(migrationTasks.ToArray());
Task.WaitAll(migrationTasks.ToArray());
Console.WriteLine("Migrate complete.");
Environment.Exit(0);
}
Console.WriteLine("Migrate complete.");
Environment.Exit(0);
}
var config = await settingsDb.ApplicationConfigurations.ToListAsync();
var url = config.FirstOrDefault(x => x.Type == ConfigurationTypes.Url);
var dbBaseUrl = config.FirstOrDefault(x => x.Type == ConfigurationTypes.BaseUrl);
var securityToken = config.FirstOrDefault(x => x.Type == ConfigurationTypes.SecurityToken);
await CheckSecurityToken(securityToken, settingsDb, instance);
if (url == null)
var config = await settingsDb.ApplicationConfigurations.ToListAsync();
var url = config.FirstOrDefault(x => x.Type == ConfigurationTypes.Url);
var ombiSettingsContent = await settingsDb.Settings.FirstOrDefaultAsync(x => x.SettingsName == "OmbiSettings");
var securityToken = config.FirstOrDefault(x => x.Type == ConfigurationTypes.SecurityToken);
await CheckSecurityToken(securityToken, settingsDb, instance);
if (url == null)
{
url = new ApplicationConfiguration
{
url = new ApplicationConfiguration
{
Type = ConfigurationTypes.Url,
Value = "http://*:5000"
};
var strat = settingsDb.Database.CreateExecutionStrategy();
await strat.ExecuteAsync(async () =>
{
using (var tran = await settingsDb.Database.BeginTransactionAsync())
{
settingsDb.ApplicationConfigurations.Add(url);
await settingsDb.SaveChangesAsync();
await tran.CommitAsync();
}
});
Type = ConfigurationTypes.Url,
Value = "http://*:5000"
};
var strat = settingsDb.Database.CreateExecutionStrategy();
await strat.ExecuteAsync(async () =>
{
using var tran = await settingsDb.Database.BeginTransactionAsync();
settingsDb.ApplicationConfigurations.Add(url);
await settingsDb.SaveChangesAsync();
await tran.CommitAsync();
});
urlValue = url.Value;
}
urlValue = url.Value;
}
if (!url.Value.Equals(host))
if (!url.Value.Equals(host))
{
url.Value = UrlArgs;
var strat = settingsDb.Database.CreateExecutionStrategy();
await strat.ExecuteAsync(async () =>
{
url.Value = UrlArgs;
var strat = settingsDb.Database.CreateExecutionStrategy();
await strat.ExecuteAsync(async () =>
{
using (var tran = await settingsDb.Database.BeginTransactionAsync())
{
await settingsDb.SaveChangesAsync();
await tran.CommitAsync();
}
});
using var tran = await settingsDb.Database.BeginTransactionAsync();
await settingsDb.SaveChangesAsync();
await tran.CommitAsync();
});
urlValue = url.Value;
}
else if (string.IsNullOrEmpty(urlValue))
{
urlValue = host;
}
urlValue = url.Value;
}
else if (string.IsNullOrEmpty(urlValue))
{
urlValue = host;
}
if (dbBaseUrl == null)
{
if (baseUrl.HasValue() && baseUrl.StartsWith("/"))
{
dbBaseUrl = new ApplicationConfiguration
{
Type = ConfigurationTypes.BaseUrl,
Value = baseUrl
};
var strat = settingsDb.Database.CreateExecutionStrategy();
await strat.ExecuteAsync(async () =>
{
using (var tran = await settingsDb.Database.BeginTransactionAsync())
{
settingsDb.ApplicationConfigurations.Add(dbBaseUrl);
await settingsDb.SaveChangesAsync();
await tran.CommitAsync();
}
});
}
}
else if (baseUrl.HasValue() && !baseUrl.Equals(dbBaseUrl.Value))
{
dbBaseUrl.Value = baseUrl;
var strat = settingsDb.Database.CreateExecutionStrategy();
await strat.ExecuteAsync(async () =>
{
using (var tran = await settingsDb.Database.BeginTransactionAsync())
{
await settingsDb.SaveChangesAsync();
await tran.CommitAsync();
}
});
}
await SortOutBaseUrl(baseUrl, settingsDb, ombiSettingsContent);
Console.WriteLine($"We are running on {urlValue}");
Console.WriteLine($"We are running on {urlValue}");
CreateHostBuilder(args).Build().Run();
}
CreateHostBuilder(args).Build().Run();
}
private static async Task CheckSecurityToken(ApplicationConfiguration securityToken, SettingsContext ctx, StartupSingleton instance)
@ -180,12 +145,10 @@ namespace Ombi
var strat = ctx.Database.CreateExecutionStrategy();
await strat.ExecuteAsync(async () =>
{
using (var tran = await ctx.Database.BeginTransactionAsync())
{
ctx.ApplicationConfigurations.Add(securityToken);
await ctx.SaveChangesAsync();
await tran.CommitAsync();
}
using var tran = await ctx.Database.BeginTransactionAsync();
ctx.ApplicationConfigurations.Add(securityToken);
await ctx.SaveChangesAsync();
await tran.CommitAsync();
});
}
@ -196,7 +159,7 @@ namespace Ombi
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel(serverOptions =>
webBuilder.ConfigureKestrel(_ =>
{
// Set properties and call methods on options
});
@ -215,6 +178,104 @@ namespace Ombi
return result.ToString();
}
private static async Task SortOutBaseUrl(string baseUrl, SettingsContext settingsDb, GlobalSettings ombiSettingsContent)
{
var setBaseUrl = false;
if (ombiSettingsContent == null)
{
Console.WriteLine("Creating new Settings entity");
ombiSettingsContent = new GlobalSettings
{
SettingsName = "OmbiSettings",
Content = JsonConvert.SerializeObject(new OmbiSettings())
};
var strat = settingsDb.Database.CreateExecutionStrategy();
await strat.ExecuteAsync(async () =>
{
using var tran = await settingsDb.Database.BeginTransactionAsync();
settingsDb.Add(ombiSettingsContent);
await settingsDb.SaveChangesAsync();
await tran.CommitAsync();
});
}
var ombiSettings = JsonConvert.DeserializeObject<OmbiSettings>(ombiSettingsContent.Content);
if (ombiSettings == null)
{
if (baseUrl.HasValue() && baseUrl.StartsWith("/"))
{
setBaseUrl = true;
ombiSettings = new OmbiSettings
{
BaseUrl = baseUrl
};
ombiSettingsContent.Content = JsonConvert.SerializeObject(ombiSettings);
var strat = settingsDb.Database.CreateExecutionStrategy();
await strat.ExecuteAsync(async () =>
{
using (var tran = await settingsDb.Database.BeginTransactionAsync())
{
settingsDb.Update(ombiSettingsContent);
await settingsDb.SaveChangesAsync();
await tran.CommitAsync();
}
});
}
}
else if (baseUrl.HasValue() && !baseUrl.Equals(ombiSettings.BaseUrl))
{
setBaseUrl = true;
ombiSettings.BaseUrl = baseUrl;
ombiSettingsContent.Content = JsonConvert.SerializeObject(ombiSettings);
var strat = settingsDb.Database.CreateExecutionStrategy();
await strat.ExecuteAsync(async () =>
{
using (var tran = await settingsDb.Database.BeginTransactionAsync())
{
settingsDb.Update(ombiSettingsContent);
await settingsDb.SaveChangesAsync();
await tran.CommitAsync();
}
});
}
else
{
// The base url might have changed in the settings, so just rewrite
setBaseUrl = true;
baseUrl = ombiSettings.BaseUrl.HasValue() ? ombiSettings.BaseUrl : string.Empty;
}
if (setBaseUrl)
{
var trimmedBaseUrl = baseUrl.EndsWith('/') ? baseUrl.TrimEnd('/') : baseUrl;
var process = Process.GetCurrentProcess().MainModule.FileName;
var ombiInstalledDir = Path.GetDirectoryName(process);
var indexPath = Path.Combine(ombiInstalledDir, "ClientApp", "dist", "index.html");
if (!File.Exists(indexPath))
{
var error = $"Can't set the base URL because we cannot find the file at {indexPath}, if you are trying to set a base url please report this on Github!";
Console.WriteLine(error);
throw new Exception(error);
}
var indexHtml = await File.ReadAllTextAsync(indexPath);
var sb = new StringBuilder(indexHtml);
var headPosition = indexHtml.IndexOf("<head>");
var firstLinkPosition = indexHtml.IndexOf("<link");
sb.Remove(headPosition + 6, firstLinkPosition - headPosition - 6);
sb.Insert(headPosition + 6,
$"<script type='text/javascript'>window[\"baseHref\"] = '{trimmedBaseUrl}';</script><base href=\"{trimmedBaseUrl}/\">");
await File.WriteAllTextAsync(indexPath, sb.ToString());
Console.WriteLine($"Wrote new baseurl at {indexPath}");
}
}
}
public class Options

@ -14,7 +14,7 @@
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"commandLineArgs": "--host http://*:3577",
"commandLineArgs": "--host http://*:3577" ,
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
@ -22,7 +22,7 @@
},
"Ombi": {
"commandName": "Project",
"commandLineArgs": "--host http://localhost:3577 ",
"commandLineArgs": "--host http://localhost:3577 --baseUrl /ombi/",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},

@ -93,7 +93,7 @@ namespace Ombi
.AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
services.AddOmbiMappingProfile();
services.AddAutoMapper(expression => { expression.AddCollectionMappers(); });
services.AddAutoMapper(expression => expression.AddCollectionMappers());
services.RegisterApplicationDependencies(); // Ioc and EF
services.AddSwagger();
@ -110,10 +110,7 @@ namespace Ombi
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);
services.AddSignalR();
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
services.AddSpaStaticFiles(configuration => configuration.RootPath = "ClientApp/dist");
}
@ -155,18 +152,6 @@ namespace Ombi
ombiService.SaveSettings(settings);
}
// Check if it's in the startup args
var appConfig = serviceProvider.GetService<IApplicationConfigRepository>();
var baseUrl = appConfig.Get(ConfigurationTypes.BaseUrl);
if (baseUrl != null)
{
if (baseUrl.Value.HasValue())
{
settings.BaseUrl = baseUrl.Value;
ombiService.SaveSettings(settings);
}
}
if (settings.BaseUrl.HasValue())
{
app.UsePathBase(settings.BaseUrl);
@ -228,8 +213,8 @@ namespace Ombi
app.UseSpa(spa =>
{
#if DEBUG
spa.Options.SourcePath = "ClientApp";
#if DEBUG
spa.UseProxyToSpaDevelopmentServer("http://localhost:3578");
#endif
});

@ -273,7 +273,7 @@
"AllSeasonsTooltip": "This will request every season for this show",
"FirstSeasonTooltip": "This will only request the First Season for this show",
"LatestSeasonTooltip": "This will only request the Latest Season for this show",
"NoEpisodes": "There unfortunatly is no episode data for this show yet!"
"NoEpisodes": "There Unfortunately is no episode data for this show yet!"
},
"SonarrConfiguration": "Sonarr Configuration",
"RadarrConfiguration": "Radarr Configuration",
@ -313,4 +313,4 @@
"MobileQRCode":"Mobile QR Code",
"LegacyApp":"Launch Legacy App"
}
}
}

Loading…
Cancel
Save