version up

This commit is contained in:
2023-07-31 17:11:39 +08:00
parent befbc7fc9b
commit 8419c9d389
41 changed files with 1053 additions and 286 deletions

View File

@@ -1,5 +1,4 @@
using Microsoft.Extensions.Logging;
using SQLite;
using SQLite;
namespace Blahblah.FlowerApp.Data;
@@ -12,6 +11,8 @@ internal sealed class Constants
public const string LastTokenName = "last_token";
public const string BaseUrl = "https://app.blahblaho.com";
public const string AppVersion = "0.2.731";
public const string UserAgent = $"FlowerApp/{AppVersion}";
public const SQLiteOpenFlags SQLiteFlags =
SQLiteOpenFlags.ReadWrite |
@@ -32,7 +33,7 @@ internal sealed class Constants
authorization = auth;
}
public static async Task<Definitions?> Initialize(ILogger logger, string? version, CancellationToken cancellation = default)
public static async Task<Definitions?> Initialize(ILoggerContent logger, string? version, CancellationToken cancellation = default)
{
try
{
@@ -47,7 +48,7 @@ internal sealed class Constants
}
catch (Exception ex)
{
logger.LogError("error occurs on fetching version and definitions, {error}", ex);
logger.LogError(ex, $"error occurs on fetching version and definitions, {ex.Message}");
}
return null;

View File

@@ -4,27 +4,17 @@ using SQLite;
namespace Blahblah.FlowerApp.Data;
public class FlowerDatabase
public class FlowerDatabase : ILoggerContent
{
private SQLiteAsyncConnection database = null!;
public ILogger Logger { get; }
private readonly ILogger logger;
public FlowerDatabase Database => this;
private SQLiteAsyncConnection database = null!;
public FlowerDatabase(ILogger<FlowerDatabase> logger)
{
this.logger = logger;
Task.Run(async () =>
{
try
{
await Setup();
}
catch (Exception ex)
{
logger.LogError("error occurs on setup, {error}", ex);
}
});
Logger = logger;
}
private Dictionary<int, NamedItem>? categories;
@@ -49,29 +39,68 @@ public class FlowerDatabase
return Constants.EventUnknown;
}
private async Task Setup()
private async Task Init()
{
if (database is not null)
{
return;
}
#if DEBUG
Logger.LogInformation("database path: {path}", Constants.DatabasePath);
#endif
database = new SQLiteAsyncConnection(Constants.DatabasePath, Constants.SQLiteFlags);
#if DEBUG1
var result =
#endif
await database.CreateTablesAsync(CreateFlags.None,
typeof(FlowerItem),
typeof(RecordItem),
typeof(PhotoItem),
typeof(UserItem),
typeof(DefinitionItem),
typeof(ParamItem),
typeof(LogItem));
#if DEBUG1
foreach (var item in result.Results)
{
this.LogInformation($"create table {item.Key}, result: {item.Value}");
}
#endif
}
public async Task Setup()
{
await Init();
#if DEBUG
Constants.SetAuthorization("RF4mfoUur0vHtWzHwD42ka0FhIfGaPnBxoQgrXOYEDg=");
#if DEBUG1
var token = "RF4mfoUur0vHtWzHwD42ka0FhIfGaPnBxoQgrXOYEDg=";
#else
var token = await database.Table<ParamItem>().FirstOrDefaultAsync(p => p.Code == Constants.LastTokenName);
if (token != null)
{
Constants.SetAuthorization(token.Value);
}
var tk = await database.Table<ParamItem>().FirstOrDefaultAsync(p => p.Code == Constants.LastTokenName);
var token = tk?.Value;
#endif
if (token is string t)
{
Constants.SetAuthorization(t);
var user = await database.Table<UserItem>().FirstOrDefaultAsync(u => u.Token == t);
if (user != null)
{
AppResources.SetUser(user);
}
}
var version = await database.Table<ParamItem>().FirstOrDefaultAsync(p => p.Code == Constants.ApiVersionName);
var definition = await Constants.Initialize(logger, version?.Value);
var definition = await Constants.Initialize(this, version?.Value);
if (definition != null)
{
categories = definition.Categories;
events = definition.Events;
logger.LogInformation("new version founded, from ({from}) to ({to})", version?.Value, definition.ApiVersion);
this.LogInformation($"new version founded, from ({version?.Value}) to ({definition.ApiVersion})");
if (version == null)
{
@@ -113,7 +142,7 @@ public class FlowerDatabase
});
}
var rows = await database.InsertAllAsync(defs);
logger.LogInformation("{count} definitions, {rows} rows inserted", defs.Count, rows);
this.LogInformation($"{defs.Count} definitions, {rows} rows inserted");
}
else
{
@@ -139,32 +168,10 @@ public class FlowerDatabase
}
}
private async Task Init()
public async Task<int> AddLog(LogItem log)
{
if (database is not null)
{
return;
}
database = new SQLiteAsyncConnection(Constants.DatabasePath, Constants.SQLiteFlags);
#if DEBUG
var result =
#endif
await database.CreateTablesAsync(CreateFlags.None,
typeof(FlowerItem),
typeof(RecordItem),
typeof(PhotoItem),
typeof(UserItem),
typeof(DefinitionItem),
typeof(ParamItem));
#if DEBUG
foreach (var item in result.Results)
{
logger.LogInformation("create table {table}, result: {result}", item.Key, item.Value);
}
#endif
await Init();
return await database.InsertAsync(log);
}
public async Task<FlowerItem[]> GetFlowers()
@@ -172,4 +179,47 @@ public class FlowerDatabase
await Init();
return await database.Table<FlowerItem>().ToArrayAsync();
}
public async Task<int> UpdateFlowers(IEnumerable<FlowerItem> flowers)
{
await Init();
var ids = flowers.Select(f => f.Id).ToList();
var count = await database.Table<FlowerItem>().DeleteAsync(f => ids.Contains(f.Id));
await database.Table<PhotoItem>().DeleteAsync(p => p.RecordId == null && ids.Contains(p.FlowerId));
await database.InsertAllAsync(flowers);
foreach (var flower in flowers)
{
if (flower.Photos?.Length > 0)
{
await database.InsertAllAsync(flower.Photos);
}
}
return count;
}
public async Task<int> SetUser(UserItem user)
{
await Init();
var count = user.Id > 0 ?
await database.Table<UserItem>().CountAsync(u => u.Id == user.Id) :
0;
if (count > 0)
{
count = await database.UpdateAsync(user);
}
else
{
count = await database.InsertAsync(user);
}
if (count > 0)
{
var c = await database.Table<ParamItem>().FirstOrDefaultAsync(p => p.Code == Constants.LastTokenName);
c ??= new ParamItem { Code = Constants.LastTokenName };
c.Value = user.Token;
await database.InsertOrReplaceAsync(c);
}
return count;
}
}

View File

@@ -1,4 +1,5 @@
using SQLite;
using System.Text.Json.Serialization;
namespace Blahblah.FlowerApp.Data.Model;
@@ -12,19 +13,19 @@ public class FlowerItem
public int OwnerId { get; set; }
[Column("category"), NotNull]
public int Category { get; set; }
public int CategoryId { get; set; }
[Column("Name"), NotNull]
public string Name { get; set; } = null!;
[Column("datebuy"), NotNull]
[Column("datebuy"), JsonPropertyName("dateBuy"), NotNull]
public long DateBuyUnixTime { get; set; }
[Column("cost")]
public decimal? Cost { get; set; }
[Column("purchase")]
public string? PurchaseFrom { get; set; }
public string? Purchase { get; set; }
[Column("memo")]
public string? Memo { get; set; }

View File

@@ -0,0 +1,34 @@
using SQLite;
namespace Blahblah.FlowerApp.Data.Model;
[Table("logs")]
public class LogItem
{
[Column("lid"), PrimaryKey, AutoIncrement]
public int Id { get; set; }
[Column("logtime"), NotNull]
public long LogUnixTime { get; set; }
[Column("uid"), NotNull]
public int OwnerId { get; set; }
[Column("logtype"), NotNull]
public string LogType { get; set; } = null!;
[Column("category"), NotNull]
public string Category { get; set; } = null!;
[Column("message"), NotNull]
public string Message { get; set; } = null!;
[Column("source")]
public string? Source { get; set; } = null!;
[Column("description")]
public string? Description { get; set; }
[Column("client")]
public string? ClientAgent { get; set; }
}

View File

@@ -5,15 +5,12 @@ namespace Blahblah.FlowerApp.Data.Model;
[Table("params")]
public class ParamItem
{
[Column("pid"), PrimaryKey, AutoIncrement]
public int Id { get; set; }
[Column("uid")]
public int? OwnerId { get; set; }
[Column("code"), NotNull]
[Column("code"), PrimaryKey, NotNull]
public string Code { get; set; } = null!;
[Column("uid"), NotNull]
public int OwnerId { get; set; } = AppResources.EmptyUserId;
[Column("value"), NotNull]
public string Value { get; set; } = null!;

View File

@@ -1,4 +1,5 @@
using SQLite;
using System.Text.Json.Serialization;
namespace Blahblah.FlowerApp.Data.Model;
@@ -14,8 +15,8 @@ public class PhotoItem
[Column("fid"), NotNull]
public int FlowerId { get; set; }
[Column("rid"), NotNull]
public int RecordId { get; set; }
[Column("rid")]
public int? RecordId { get; set; }
[Column("filetype"), NotNull]
public string FileType { get; set; } = null!;
@@ -26,7 +27,7 @@ public class PhotoItem
[Column("path"), NotNull]
public string Path { get; set; } = null!;
[Column("dateupload"), NotNull]
[Column("dateupload"), JsonPropertyName("dateUpload"), NotNull]
public long DateUploadUnixTime { get; set; }
[Column("url")]

View File

@@ -1,7 +1,9 @@
using SQLite;
using System.Text.Json.Serialization;
namespace Blahblah.FlowerApp.Data.Model;
[Table("records")]
public class RecordItem
{
[Column("rid"), PrimaryKey, NotNull]
@@ -14,9 +16,9 @@ public class RecordItem
public int FlowerId { get; set; }
[Column("event"), NotNull]
public int EventType { get; set; }
public int EventId { get; set; }
[Column("date"), NotNull]
[Column("date"), JsonPropertyName("date"), NotNull]
public long DateUnixTime { get; set; }
[Column("byuid")]
@@ -33,4 +35,7 @@ public class RecordItem
[Column("longitude")]
public double? Longitude { get; set; }
[Ignore]
public PhotoItem[]? Photos { get; set; }
}

View File

@@ -1,7 +1,9 @@
using SQLite;
using System.Text.Json.Serialization;
namespace Blahblah.FlowerApp.Data.Model;
[Table("users")]
public class UserItem
{
[Column("uid"), PrimaryKey, NotNull]
@@ -19,14 +21,9 @@ public class UserItem
[Column("level"), NotNull]
public int Level { get; set; }
[Column("regdate"), NotNull]
[Column("regdate"), JsonPropertyName("registerDate"), NotNull]
public long RegisterDateUnixTime { get; set; }
//[Column("activedate")]
//public long? ActiveDateUnixTime { get; set; }
//public DateTimeOffset? ActiveDate => ActiveDateUnixTime == null ? null : DateTimeOffset.FromUnixTimeMilliseconds(ActiveDateUnixTime.Value);
[Column("email")]
public string? Email { get; set; }
@@ -35,4 +32,9 @@ public class UserItem
[Column("avatar")]
public byte[]? Avatar { get; set; }
public override string ToString()
{
return $"{{ Id: {Id}, Token: \"{Token}\", UserId: \"{UserId}\", Name: \"{Name}\", Level: {Level}, RegisterDate: \"{DateTimeOffset.FromUnixTimeMilliseconds(RegisterDateUnixTime)}\" }}";
}
}