Kavita/API/Program.cs
Joseph Milazzo 78ffb8a8a2
Release Shakeout (#1186)
* Cleaned up some styles on the progress bar in book reader

* Fixed up some phone-hidden classes and added titles around the codebase. Stat reporting on first run now takes into account that admin user wont exist.

* Fixed manage library page not updating last scan time when a notification event comes in.

* Integrated SeriesSort ComicInfo tag (somehow it got missed)

* Some minor style changes and no results found for bookmarks on chapter detail modal

* Fixed the labels in action bar on book reader so Prev/Next are in same place

* Cleaned up some responsive styles around images and reduced custom classes in light of new display classes on collection detail and series detail pages

* Fixed an issue with webkit browsers and book reader where the scroll to would fail as the document wasn't fully rendered. A 10ms delay seems to fix the issue.

* Cleaned up some code and filtering for collections. Collection detail is missing filtering functionality somehow, disabled the button and will add in future release

* Correctly validate and show a message when a user is not an admin or has change password role when going through forget password flow.

* Fixed a bug on manage libraries where library last scan didn't work on first scan of a library, due to there being no updated series.

* Fixed a rendering issue with text being focused on confirm email page textboxes. Fixed a bug where when deleting a theme that was default, Kavita didn't reset Dark as the default theme.

* Cleaned up the naming and styles for side nav active item hover

* Fixed event widget to have correct styling on eink and light

* Tried to fix a rendering issue on side nav for light themes, but can't figure it out

* On light more, ensure switches are green

* Fixed a bug where opening a page with a preselected filter, the filter toggle button would require 2 clicks to collapse

* Reverted the revert of On Deck.

* Improved the upload by url experience by sending a custom fail error to UI when a url returns 401.

* When deleting a library, emit a series removed event for each series removed so user's dashboards/screens update.

* Fixed an api throwing an error due to text being sent back instead of json.

* Fixed a refresh bug with refreshing pending invites after deleting an invite. Ensure we always refresh pending invites even if user cancel's from invite, as they might invite, then hit cancel, where invite is still active.

* Fixed a bug where invited users with + in the email would fail due to validation, but UI wouldn't properly inform user.
2022-04-02 07:38:14 -07:00

154 lines
6.0 KiB
C#

using System;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Security.Cryptography;
using System.Threading.Tasks;
using API.Data;
using API.Entities;
using API.Entities.Enums;
using API.Services;
using Kavita.Common;
using Kavita.Common.EnvironmentInfo;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace API
{
public class Program
{
private static readonly int HttpPort = Configuration.Port;
protected Program()
{
}
public static async Task Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
var isDocker = new OsInfo(Array.Empty<IOsVersionAdapter>()).IsDocker;
var directoryService = new DirectoryService(null, new FileSystem());
// Before anything, check if JWT has been generated properly or if user still has default
if (!Configuration.CheckIfJwtTokenSet() &&
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != Environments.Development)
{
Console.WriteLine("Generating JWT TokenKey for encrypting user sessions...");
var rBytes = new byte[128];
RandomNumberGenerator.Create().GetBytes(rBytes);
Configuration.JwtToken = Convert.ToBase64String(rBytes).Replace("/", string.Empty);
}
var host = CreateHostBuilder(args).Build();
using var scope = host.Services.CreateScope();
var services = scope.ServiceProvider;
try
{
var logger = services.GetRequiredService<ILogger<Program>>();
var context = services.GetRequiredService<DataContext>();
var pendingMigrations = await context.Database.GetPendingMigrationsAsync();
if (pendingMigrations.Any())
{
logger.LogInformation("Performing backup as migrations are needed. Backup will be kavita.db in temp folder");
var migrationDirectory = await GetMigrationDirectory(context, directoryService);
directoryService.ExistOrCreate(migrationDirectory);
if (!directoryService.FileSystem.File.Exists(
directoryService.FileSystem.Path.Join(migrationDirectory, "kavita.db")))
{
directoryService.CopyFileToDirectory(directoryService.FileSystem.Path.Join(directoryService.ConfigDirectory, "kavita.db"), migrationDirectory);
logger.LogInformation("Database backed up to {MigrationDirectory}", migrationDirectory);
}
}
await context.Database.MigrateAsync();
await Seed.SeedRoles(services.GetRequiredService<RoleManager<AppRole>>());
await Seed.SeedSettings(context, directoryService);
await Seed.SeedThemes(context);
await Seed.SeedUserApiKeys(context);
if (isDocker && new FileInfo("data/appsettings.json").Exists)
{
logger.LogCritical("WARNING! Mount point is incorrect, nothing here will persist. Please change your container mount from /kavita/data to /kavita/config");
return;
}
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
var context = services.GetRequiredService<DataContext>();
var migrationDirectory = await GetMigrationDirectory(context, directoryService);
logger.LogCritical(ex, "A migration failed during startup. Restoring backup from {MigrationDirectory} and exiting", migrationDirectory);
directoryService.CopyFileToDirectory(directoryService.FileSystem.Path.Join(migrationDirectory, "kavita.db"), directoryService.ConfigDirectory);
return;
}
await host.RunAsync();
}
private static async Task<string> GetMigrationDirectory(DataContext context, IDirectoryService directoryService)
{
string currentVersion = null;
try
{
currentVersion =
(await context.ServerSetting.SingleOrDefaultAsync(s =>
s.Key == ServerSettingKey.InstallVersion))?.Value;
}
catch (Exception)
{
// ignored
}
if (string.IsNullOrEmpty(currentVersion))
{
currentVersion = "vUnknown";
}
var migrationDirectory = directoryService.FileSystem.Path.Join(directoryService.TempDirectory,
"migration", currentVersion);
return migrationDirectory;
}
private static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.Sources.Clear();
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("config/appsettings.json", optional: true, reloadOnChange: false)
.AddJsonFile($"config/appsettings.{env.EnvironmentName}.json",
optional: true, reloadOnChange: false);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseKestrel((opts) =>
{
opts.ListenAnyIP(HttpPort, options => { options.Protocols = HttpProtocols.Http1AndHttp2; });
});
webBuilder.UseStartup<Startup>();
});
}
}