Skip to content

Commit

Permalink
database service
Browse files Browse the repository at this point in the history
  • Loading branch information
Scighost committed Nov 24, 2024
1 parent 844803d commit afbc317
Show file tree
Hide file tree
Showing 4 changed files with 963 additions and 55 deletions.
79 changes: 79 additions & 0 deletions src/Starward/AppService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Starward.Features.Database;
using System;
using System.IO;
using System.Net;
using System.Net.Http;

namespace Starward;

public static class AppService
{



private static IServiceProvider _serviceProvider;


public static string LogFile { get; private set; }



public static void ResetServiceProvider()
{
AppSetting.ClearCache();
_serviceProvider = null!;
}


private static void BuildServiceProvider()
{
if (_serviceProvider == null)
{
var logFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Starward\log");
Directory.CreateDirectory(logFolder);
LogFile = Path.Combine(logFolder, $"Starward_{DateTime.Now:yyMMdd_HHmmss}.log");
Log.Logger = new LoggerConfiguration().WriteTo.File(path: LogFile, outputTemplate: "[{Timestamp:HH:mm:ss.fff}] [{Level:u4}] {SourceContext}{NewLine}{Message}{NewLine}{Exception}{NewLine}")
.Enrich.FromLogContext()
.CreateLogger();
Log.Information($"Welcome to Starward v{AppSetting.AppVersion}\r\nSystem: {Environment.OSVersion}\r\nCommand Line: {Environment.CommandLine}");

var sc = new ServiceCollection();
sc.AddLogging(c => c.AddSerilog(Log.Logger));
sc.AddTransient(_ =>
{
var client = new HttpClient(new SocketsHttpHandler { AutomaticDecompression = DecompressionMethods.All }) { DefaultRequestVersion = HttpVersion.Version20 };
client.DefaultRequestHeaders.Add("User-Agent", $"Starward/{AppSetting.AppVersion}");
return client;
});

_serviceProvider = sc.BuildServiceProvider();
}
}


public static T GetService<T>()
{
BuildServiceProvider();
return _serviceProvider.GetService<T>()!;
}


public static ILogger<T> GetLogger<T>()
{
BuildServiceProvider();
return _serviceProvider.GetService<ILogger<T>>()!;
}


public static SqliteConnection CreateDatabaseConnection()
{
return DatabaseService.CreateConnection();
}



}
120 changes: 65 additions & 55 deletions src/Starward/AppSetting.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
using Starward.Core;
using Dapper;
using Starward.Core;
using Starward.Features.Database;
using Starward.Features.ViewHost;
using Starward.Models;
using Starward.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
Expand Down Expand Up @@ -66,6 +68,7 @@ static AppSetting()
}
if (Directory.Exists(userDataFolder))
{
DatabaseService.SetDatabase(userDataFolder);
UserDataFolder = Path.GetFullPath(userDataFolder);
}
}
Expand Down Expand Up @@ -443,25 +446,23 @@ public static void SetLastRegionOfGame(GameBiz game, GameBiz value)



#region Setting Method

#region Setting Method


private static DatabaseService DatabaseService;

private static Dictionary<string, string?> cache;
private static Dictionary<string, string?> _settingCache;


private static void InitializeSettingProvider()
{
try
{
//DatabaseService ??= GetService<DatabaseService>();
//if (cache is null)
//{
// using var dapper = DatabaseService.CreateConnection();
// cache = dapper.Query<(string Key, string? Value)>("SELECT Key, Value FROM Setting;").ToDictionary(x => x.Key, x => x.Value);
//}
if (_settingCache is null)
{
using var dapper = DatabaseService.CreateConnection();
_settingCache = dapper.Query<(string Key, string? Value)>("SELECT Key, Value FROM Setting;").ToDictionary(x => x.Key, x => x.Value);
}
}
catch { }
}
Expand All @@ -470,27 +471,27 @@ private static void InitializeSettingProvider()

private static T? GetValue<T>(T? defaultValue = default, [CallerMemberName] string? key = null)
{
//if (string.IsNullOrWhiteSpace(key))
//{
// return defaultValue;
//}
//if (string.IsNullOrWhiteSpace(UserDataFolder))
//{
// return defaultValue;
//}
//InitializeSettingProvider();
//try
//{
// if (cache.TryGetValue(key, out string? value))
// {
// return ConvertFromString(value, defaultValue);
// }
// using var dapper = DatabaseService.CreateConnection();
// value = dapper.QueryFirstOrDefault<string>("SELECT Value FROM Setting WHERE Key=@key LIMIT 1;", new { key });
// cache[key] = value;
// return ConvertFromString(value, defaultValue);
//}
//catch
if (string.IsNullOrWhiteSpace(key))
{
return defaultValue;
}
if (string.IsNullOrWhiteSpace(UserDataFolder))
{
return defaultValue;
}
InitializeSettingProvider();
try
{
if (_settingCache.TryGetValue(key, out string? value))
{
return ConvertFromString(value, defaultValue);
}
using var dapper = DatabaseService.CreateConnection();
value = dapper.QueryFirstOrDefault<string>("SELECT Value FROM Setting WHERE Key=@key LIMIT 1;", new { key });
_settingCache[key] = value;
return ConvertFromString(value, defaultValue);
}
catch
{
return defaultValue;
}
Expand All @@ -514,27 +515,27 @@ private static void InitializeSettingProvider()

private static void SetValue<T>(T? value, [CallerMemberName] string? key = null)
{
//if (string.IsNullOrWhiteSpace(key))
//{
// return;
//}
//if (string.IsNullOrWhiteSpace(UserDataFolder))
//{
// return;
//}
//InitializeSettingProvider();
//try
//{
// string? val = value?.ToString();
// if (cache.TryGetValue(key, out string? cacheValue) && cacheValue == val)
// {
// return;
// }
// cache[key] = val;
// using var dapper = DatabaseService.CreateConnection();
// dapper.Execute("INSERT OR REPLACE INTO Setting (Key, Value) VALUES (@key, @val);", new { key, val });
//}
//catch { }
if (string.IsNullOrWhiteSpace(key))
{
return;
}
if (string.IsNullOrWhiteSpace(UserDataFolder))
{
return;
}
InitializeSettingProvider();
try
{
string? val = value?.ToString();
if (_settingCache.TryGetValue(key, out string? cacheValue) && cacheValue == val)
{
return;
}
_settingCache[key] = val;
using var dapper = DatabaseService.CreateConnection();
dapper.Execute("INSERT OR REPLACE INTO Setting (Key, Value) VALUES (@key, @val);", new { key, val });
}
catch { }
}


Expand All @@ -543,15 +544,24 @@ public static void DeleteAllSettings()
{
try
{
//using var dapper = DatabaseService.CreateConnection();
//dapper.Execute("DELETE FROM Setting WHERE TRUE;");
using var dapper = DatabaseService.CreateConnection();
dapper.Execute("DELETE FROM Setting WHERE TRUE;");
}
catch { }
}



public static void ClearCache()
{
_settingCache.Clear();
}



#endregion




}
120 changes: 120 additions & 0 deletions src/Starward/Features/Database/DapperSqlMapper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
using Dapper;
using Starward.Core;
using Starward.Core.GameRecord.Genshin.TravelersDiary;
using Starward.Core.GameRecord.StarRail.TrailblazeCalendar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text.Json;

namespace Starward.Features.Database;


internal class DapperSqlMapper
{

private static JsonSerializerOptions JsonSerializerOptions = new JsonSerializerOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, PropertyNameCaseInsensitive = true };


public class DateTimeOffsetHandler : SqlMapper.TypeHandler<DateTimeOffset>
{
public override DateTimeOffset Parse(object value)
{
if (value is string str)
{
return DateTimeOffset.Parse(str);
}
else
{
return new DateTimeOffset();
}
}

public override void SetValue(IDbDataParameter parameter, DateTimeOffset value)
{
parameter.Value = value.ToString();
}
}



public class TravelersDiaryPrimogemsMonthGroupStatsListHandler : SqlMapper.TypeHandler<List<TravelersDiaryPrimogemsMonthGroupStats>>
{
public override List<TravelersDiaryPrimogemsMonthGroupStats> Parse(object value)
{
if (value is string str)
{
if (!string.IsNullOrWhiteSpace(str))
{
return JsonSerializer.Deserialize<List<TravelersDiaryPrimogemsMonthGroupStats>>(str, JsonSerializerOptions)!;
}
}
return new();
}

public override void SetValue(IDbDataParameter parameter, List<TravelersDiaryPrimogemsMonthGroupStats>? value)
{
parameter.Value = JsonSerializer.Serialize(value, JsonSerializerOptions);
}
}


public class TrailblazeCalendarMonthDataGroupByListHandler : SqlMapper.TypeHandler<List<TrailblazeCalendarMonthDataGroupBy>>
{
public override List<TrailblazeCalendarMonthDataGroupBy> Parse(object value)
{
if (value is string str)
{
if (!string.IsNullOrWhiteSpace(str))
{
return JsonSerializer.Deserialize<List<TrailblazeCalendarMonthDataGroupBy>>(str, JsonSerializerOptions)!;
}
}
return new();
}

public override void SetValue(IDbDataParameter parameter, List<TrailblazeCalendarMonthDataGroupBy>? value)
{
parameter.Value = JsonSerializer.Serialize(value, JsonSerializerOptions);
}
}


public class StringListHandler : SqlMapper.TypeHandler<List<string>>
{
public override List<string> Parse(object value)
{
if (value is string str)
{
if (!string.IsNullOrWhiteSpace(str))
{
return JsonSerializer.Deserialize<List<string>>(str)!;
}
}
return new();
}

public override void SetValue(IDbDataParameter parameter, List<string>? value)
{
parameter.Value = JsonSerializer.Serialize(value, JsonSerializerOptions);
}
}


public class GameBizHandler : SqlMapper.TypeHandler<GameBiz>
{
public override GameBiz? Parse(object value)
{
return new GameBiz(value as string);
}

public override void SetValue(IDbDataParameter parameter, GameBiz? value)
{
parameter.Value = value?.ToString() ?? "";
}
}


}


Loading

0 comments on commit afbc317

Please sign in to comment.