Innovenergy_trunk/csharp/App/Backend/Database/Db.cs

189 lines
6.2 KiB
C#

using System.Reactive.Concurrency;
using System.Reactive.Linq;
using InnovEnergy.App.Backend.DataTypes;
using InnovEnergy.App.Backend.DataTypes.Methods;
using InnovEnergy.App.Backend.Relations;
using InnovEnergy.Lib.S3Utils;
using InnovEnergy.Lib.S3Utils.DataTypes;
using InnovEnergy.Lib.Utils;
using SQLite;
using SQLiteConnection = SQLite.SQLiteConnection;
namespace InnovEnergy.App.Backend.Database;
public static partial class Db
{
// internal const String DbPath = "./db.sqlite";
private static SQLiteConnection Connection { get; } = ((Func<SQLiteConnection>)(() =>
{
var latestDb = new DirectoryInfo(@"DbBackups").GetFiles()
.OrderBy(f => f.LastWriteTime)
.Last().Name;
var fileConnection = new SQLiteConnection("DbBackups/"+latestDb);
Console.Out.Write(latestDb);
var memoryConnection = new SQLiteConnection(":memory:");
// fileConnection.Backup(memoryConnection.DatabasePath);
memoryConnection.CreateTable<User>();
memoryConnection.CreateTable<Installation>();
memoryConnection.CreateTable<Folder>();
memoryConnection.CreateTable<FolderAccess>();
memoryConnection.CreateTable<InstallationAccess>();
memoryConnection.CreateTable<Session>();
memoryConnection.CreateTable<OrderNumber2Installation>();
fileConnection.Table<Session> ().ForEach(memoryConnection.Insert);
fileConnection.Table<Folder> ().ForEach(memoryConnection.Insert);
fileConnection.Table<Installation> ().ForEach(memoryConnection.Insert);
fileConnection.Table<User> ().ForEach(memoryConnection.Insert);
fileConnection.Table<FolderAccess> ().ForEach(memoryConnection.Insert);
fileConnection.Table<InstallationAccess> ().ForEach(memoryConnection.Insert);
fileConnection.Table<OrderNumber2Installation>().ForEach(memoryConnection.Insert);
return memoryConnection;
}))();
public static void BackupDatabase()
{
var filename = "db-" + DateTimeOffset.UtcNow.ToUnixTimeSeconds() + ".sqlite";
Connection.Backup("DbBackups/" + filename);
}
public static TableQuery<Session> Sessions => Connection.Table<Session>();
public static TableQuery<Folder> Folders => Connection.Table<Folder>();
public static TableQuery<Installation> Installations => Connection.Table<Installation>();
public static TableQuery<User> Users => Connection.Table<User>();
public static TableQuery<FolderAccess> FolderAccess => Connection.Table<FolderAccess>();
public static TableQuery<InstallationAccess> InstallationAccess => Connection.Table<InstallationAccess>();
public static TableQuery<OrderNumber2Installation> OrderNumber2Installation => Connection.Table<OrderNumber2Installation>();
public static void Init()
{
// used to force static constructor
}
static Db()
{
// on startup create/migrate tables
Connection.RunInTransaction(() =>
{
Connection.CreateTable<User>();
Connection.CreateTable<Installation>();
Connection.CreateTable<Folder>();
Connection.CreateTable<FolderAccess>();
Connection.CreateTable<InstallationAccess>();
Connection.CreateTable<Session>();
Connection.CreateTable<OrderNumber2Installation>();
});
Observable.Interval(TimeSpan.FromHours(0.5))
.StartWith(0) // Do it right away (on startup)
.ObserveOn(TaskPoolScheduler.Default)
.SubscribeOn(TaskPoolScheduler.Default)
.SelectMany(Cleanup)
.Subscribe();
}
private static Boolean RunTransaction(Func<Boolean> func)
{
var savepoint = Connection.SaveTransactionPoint();
var success = false;
try
{
success = func();
}
finally
{
if (success)
Connection.Release(savepoint);
else
Connection.RollbackTo(savepoint);
}
return success;
}
private static async Task<Boolean> Cleanup(Int64 _)
{
await UpdateS3Urls();
DeleteStaleSessions();
return true;
}
private static void DeleteStaleSessions()
{
var deadline = DateTime.Now.AddDays((-1)*Session.MaxAge.Days);
Sessions.Delete(s => s.LastSeen < deadline);
}
private static async Task UpdateS3Urls()
{
var regions = Installations
.Select(i => i.S3Region)
.Distinct()
.ToList();
const String provider = "exo.io";
foreach (var region in regions)
{
var s3Region = new S3Region($"https://{region}.{provider}", ExoCmd.S3Creds!);
var bucketList = await s3Region.ListAllBuckets();
var installations = from bucket in bucketList.Buckets
from installation in Installations
where installation.BucketName() == bucket.BucketName
select installation;
foreach (var installation in installations)
{
await installation.RenewS3Credentials();
}
}
}
public static async Task<Boolean> SendPasswordResetEmail(User user, String sessionToken)
{
try
{
await user.SendPasswordResetEmail(sessionToken);
return true;
}
catch
{
return false;
}
}
public static async Task<Boolean> SendNewUserEmail(User user)
{
try
{
await user.SendNewUserWelcomeMessage();
return true;
}
catch
{
return false;
}
}
public static Boolean DeleteUserPassword(User user)
{
user.Password = "";
user.MustResetPassword = true;
return Update(user);
}
}