commit 057481803f743eda55780fcda3d44719d1df9a98 Author: smoh Date: Thu Dec 11 10:20:10 2025 +0900 Initial commit. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cbfd67b --- /dev/null +++ b/.gitignore @@ -0,0 +1,485 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea/ + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/main/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/main/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp +appsettings.Development.json diff --git a/Consts.cs b/Consts.cs new file mode 100644 index 0000000..c4a3786 --- /dev/null +++ b/Consts.cs @@ -0,0 +1,6 @@ +namespace TriliumMind; + +public static class Consts +{ + public const string ConfigLastFetchTimeKey = "LAST_FETCH_TIME"; +} diff --git a/Data/Entities/Config.cs b/Data/Entities/Config.cs new file mode 100644 index 0000000..bf0a7af --- /dev/null +++ b/Data/Entities/Config.cs @@ -0,0 +1,10 @@ +using System.ComponentModel.DataAnnotations; + +namespace TriliumMind.Data.Entities; + +public class Config +{ + [Key] + public string Key { get; set; } = null!; + public string Value { get; set; } = null!; +} diff --git a/Data/Entities/JiraIssue.cs b/Data/Entities/JiraIssue.cs new file mode 100644 index 0000000..e3d4072 --- /dev/null +++ b/Data/Entities/JiraIssue.cs @@ -0,0 +1,20 @@ +using System.ComponentModel.DataAnnotations; + +namespace TriliumMind.Data.Entities; + +public class JiraIssue +{ + [Key] + public string Key { get; set; } = null!; + public string Summary { get; set; } = null!; + public string? Parent { get; set; } + public string Type { get; set; } = null!; + public string Status { get; set; } = null!; + public string Assignee { get; set; } = null!; + public string Manager { get; set; } = null!; + public DateTimeOffset Due { get; set; } + public DateTimeOffset Updated { get; set; } + public DateTimeOffset Published { get; set; } + public string? ObjectId { get; set; } + public int NeedNotify { get; set; } +} \ No newline at end of file diff --git a/Data/IAppDbContext.cs b/Data/IAppDbContext.cs new file mode 100644 index 0000000..8fa8970 --- /dev/null +++ b/Data/IAppDbContext.cs @@ -0,0 +1,13 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using TriliumMind.Data.Entities; + +namespace TriliumMind.Data; + +public interface IAppDbContext : IDisposable +{ + DbSet Configs { get; set; } + DbSet JiraIssues { get; set; } + DatabaseFacade Database { get; } + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/Data/PostgresDbContext.cs b/Data/PostgresDbContext.cs new file mode 100644 index 0000000..a2e34c0 --- /dev/null +++ b/Data/PostgresDbContext.cs @@ -0,0 +1,87 @@ +using Microsoft.EntityFrameworkCore; +using Serilog; +using TriliumMind.Data.Entities; +using TriliumMind.Models; + +namespace TriliumMind.Data; + +public class PostgresDbContext : DbContext, IAppDbContext +{ + private readonly Serilog.ILogger _log; + private readonly string _connectionString; + + public DbSet Configs { get; set; } + public DbSet JiraIssues { get; set; } + + public PostgresDbContext(AppConfigs configs) + { + _log = Log.ForContext(); + var pgConfig = configs.AppSettings.Database.Postgres; + var connectionStringBuilder = new Npgsql.NpgsqlConnectionStringBuilder + { + Host = pgConfig.Host, + Port = pgConfig.Port, + Database = pgConfig.Database, + Username = pgConfig.Username, + Password = pgConfig.Password + }; + + // Set SSL/TLS + if (!string.IsNullOrEmpty(pgConfig.SslCertificatePath)) + { + var certPath = Path.IsPathRooted(pgConfig.SslCertificatePath) + ? pgConfig.SslCertificatePath + : Path.Combine(AppContext.BaseDirectory, pgConfig.SslCertificatePath); + + if (File.Exists(certPath)) + { + _log.Information("Configuring PostgreSQL with SSL certificate: {CertPath}", certPath); + connectionStringBuilder.SslMode = Npgsql.SslMode.VerifyFull; + connectionStringBuilder.RootCertificate = certPath; + } + else + { + _log.Warning("SSL certificate not found at {CertPath}, connecting without SSL", certPath); + connectionStringBuilder.SslMode = Npgsql.SslMode.Prefer; + } + } + else + { + _log.Information("No SSL certificate configured, connecting without SSL"); + connectionStringBuilder.SslMode = Npgsql.SslMode.Prefer; + } + + _connectionString = connectionStringBuilder.ConnectionString; + _log.Debug("PostgreSQL connection string configured (password hidden)"); + } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder.UseNpgsql(_connectionString); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Key); + entity.Property(e => e.Key).IsRequired(); + entity.Property(e => e.Value).IsRequired(); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Key); + entity.Property(e => e.Key).IsRequired(); + entity.Property(e => e.Summary).IsRequired(); + entity.Property(e => e.Type).IsRequired(); + entity.Property(e => e.Status).IsRequired(); + entity.Property(e => e.Assignee).IsRequired(); + entity.Property(e => e.Manager).IsRequired(); + entity.Property(e => e.Due).IsRequired(); + entity.Property(e => e.Updated).IsRequired(); + entity.Property(e => e.Published).IsRequired(); + entity.Property(e => e.NeedNotify).IsRequired(); + }); + } +} diff --git a/Data/SqliteDbContext.cs b/Data/SqliteDbContext.cs new file mode 100644 index 0000000..2df95cd --- /dev/null +++ b/Data/SqliteDbContext.cs @@ -0,0 +1,62 @@ +using Microsoft.EntityFrameworkCore; +using TriliumMind.Data.Entities; +using TriliumMind.Models; + +namespace TriliumMind.Data; + +public class SqliteDbContext : DbContext, IAppDbContext +{ + private readonly string _dbFilePath; + + public DbSet Configs { get; set; } + public DbSet JiraIssues { get; set; } + + public SqliteDbContext(AppConfigs configs) + { + var dbPath = configs.AppSettings.Database.Sqlite.DatabaseFilePath; + + if (Path.IsPathRooted(dbPath) && File.Exists(dbPath)) + { + _dbFilePath = dbPath; + } + else if (Path.IsPathRooted(dbPath)) + { + _dbFilePath = dbPath; + } + else + { + var basePath = AppContext.BaseDirectory; + _dbFilePath = Path.Combine(basePath, dbPath); + } + } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder.UseSqlite($"Data Source={_dbFilePath}"); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Key); + entity.Property(e => e.Key).IsRequired(); + entity.Property(e => e.Value).IsRequired(); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Key); + entity.Property(e => e.Key).IsRequired(); + entity.Property(e => e.Summary).IsRequired(); + entity.Property(e => e.Type).IsRequired(); + entity.Property(e => e.Status).IsRequired(); + entity.Property(e => e.Assignee).IsRequired(); + entity.Property(e => e.Manager).IsRequired(); + entity.Property(e => e.Due).IsRequired(); + entity.Property(e => e.Updated).IsRequired(); + entity.Property(e => e.Published).IsRequired(); + entity.Property(e => e.NeedNotify).IsRequired(); + }); + } +} diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..cd7ec26 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,6 @@ +FROM mcr.microsoft.com/dotnet/runtime:10.0 AS base +WORKDIR /app + +COPY ./publish . + +ENTRYPOINT ["dotnet", "TriliumMind.dll"] diff --git a/Models/AppConfigs.cs b/Models/AppConfigs.cs new file mode 100644 index 0000000..9de7cec --- /dev/null +++ b/Models/AppConfigs.cs @@ -0,0 +1,14 @@ +using Microsoft.Extensions.Options; + +namespace TriliumMind.Models; + +public class AppConfigs +{ + public Dictionary RuntimeConfigs; + public AppSettings AppSettings { get; set; } + public AppConfigs(IOptions options) + { + RuntimeConfigs = new Dictionary(); + AppSettings = options.Value; + } +} diff --git a/Models/AppSettings.cs b/Models/AppSettings.cs new file mode 100644 index 0000000..fd39bd4 --- /dev/null +++ b/Models/AppSettings.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace TriliumMind.Models; + +public class AppSettings +{ + public Trilium Trilium { get; set; } = new Trilium(); + public Jira Jira { get; set; } = new Jira(); + public Database Database { get; set; } = new Database(); +} + +public class Trilium +{ + public string EtapiToken { get; set; } = string.Empty; + public string EtapiBaseUrl { get; set; } = "https://localhost/etapi"; + public string JiraOpenedIssuePageId = string.Empty; + public string JiraWorkingIssuePageId = string.Empty; + public string JiraResolvedIssuePageId = string.Empty; + public string DividendPageId { get; set; } = String.Empty; +} + +public class Jira +{ + public string BaseUrl { get; set; } = string.Empty; + public string ApiBaseUrl { get; set; } = string.Empty; + public string AccessToken { get; set; } = string.Empty; + public List TargetProjects { get; set; } = []; + public DateTime LastFetchDateTime { get; set; } = DateTime.Parse("2025-12-01T00:00:00Z"); + public int FetchInterval { get; set; } = 60; + public string SearchFields { get; set; } = string.Empty; +} + +public class Database +{ + public string Type { get; set; } = "Sqlite"; // "Sqlite" or "Postgres" + public SqliteConfig Sqlite { get; set; } = new SqliteConfig(); + public PostgresConfig Postgres { get; set; } = new PostgresConfig(); +} + +public class SqliteConfig +{ + public string DatabaseFilePath { get; set; } = "TriliumMind.db"; +} + +public class PostgresConfig +{ + public string Host { get; set; } = "localhost"; + public int Port { get; set; } = 5432; + public string Database { get; set; } = "TriliumMind"; + public string Username { get; set; } = string.Empty; + public string Password { get; set; } = string.Empty; + public string SslCertificatePath { get; set; } = string.Empty; +} \ No newline at end of file diff --git a/Models/JiraResponse.cs b/Models/JiraResponse.cs new file mode 100644 index 0000000..9f62817 --- /dev/null +++ b/Models/JiraResponse.cs @@ -0,0 +1,104 @@ +namespace TriliumMind.Models; + +public class JiraResponse +{ + public string expand { get; set; } + public int startAt { get; set; } + public int maxResults { get; set; } + public int total { get; set; } + public Issue[] issues { get; set; } +} + +public class Issue +{ + public string expand { get; set; } + public string id { get; set; } + public string self { get; set; } + public string key { get; set; } + public Fields fields { get; set; } +} + +public class Fields +{ + public string summary { get; set; } // Title + public Assignee assignee { get; set; } + public Reporter reporter { get; set; } + public string updated { get; set; } + public Status status { get; set; } + public Issuetype issuetype { get; set; } + public DateTimeOffset UpdatedAt + { + get + { + // "2025-09-03T15:31:51.000+0900" → "2025-09-03T15:31:51.000+09:00" + var fixedValue = updated.Insert(updated.Length - 2, ":"); + return DateTimeOffset.Parse(fixedValue); + } + } + public DateTime? duedate { get; set; } + public Issue parent { get; set; } + public string customfield_10808 { get; set; } // Epic key +} + +public class Assignee +{ + public string self { get; set; } + public string name { get; set; } + public string key { get; set; } + public string emailAddress { get; set; } + public Avatarurls avatarUrls { get; set; } + public string displayName { get; set; } // Korean name + public bool active { get; set; } + public string timeZone { get; set; } +} + +public class Reporter +{ + public string self { get; set; } + public string name { get; set; } + public string key { get; set; } + public string emailAddress { get; set; } + public Avatarurls avatarUrls { get; set; } + public string displayName { get; set; } // Korean name + public bool active { get; set; } + public string timeZone { get; set; } +} + +public class Avatarurls +{ + public string _48x48 { get; set; } + public string _24x24 { get; set; } + public string _16x16 { get; set; } + public string _32x32 { get; set; } +} + +public class Status +{ + public string self { get; set; } + public string description { get; set; } + public string iconUrl { get; set; } + public string name { get; set; } // Status: Open InProgress ... + public string id { get; set; } + public Statuscategory statusCategory { get; set; } +} + +public class Statuscategory +{ + public string self { get; set; } + public int id { get; set; } + public string key { get; set; } + public string colorName { get; set; } + public string name { get; set; } +} + +public class Issuetype +{ + public string self { get; set; } + public string id { get; set; } + public string description { get; set; } + public string iconUrl { get; set; } + public string name { get; set; } // Type + public bool subtask { get; set; } + public int avatarId { get; set; } +} + diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..db3929b --- /dev/null +++ b/Program.cs @@ -0,0 +1,91 @@ +using Microsoft.EntityFrameworkCore; +using Serilog; +using System.Threading.Channels; +using TriliumMind.Data; +using TriliumMind.Models; +using TriliumMind.Services; +using TriliumMind.Workers; + +namespace TriliumMind +{ + public class Program + { + + public static async Task Main(string[] args) + { + var builder = Host.CreateApplicationBuilder(args); + + // Configure AppSettings + var env = builder.Environment.EnvironmentName; + builder.Configuration + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) + .AddJsonFile($"appsettings.{env}.json", optional: true, reloadOnChange: true) + .AddEnvironmentVariables() + .AddCommandLine(args); + builder.Services.Configure(builder.Configuration); + + Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(builder.Configuration) + .Enrich.FromLogContext() + .WriteTo.Console() + .CreateLogger(); + + // Register Config class (must be registered before DbContext) + builder.Services.AddSingleton(); + + // Register DbContext based on configuration + builder.Services.AddScoped(sp => + { + var appConfigs = sp.GetRequiredService(); + var dbType = appConfigs.AppSettings.Database.Type; + + Log.Information("Configuring database type: {DbType}", dbType); + + return dbType.ToLower() switch + { + "postgres" => new PostgresDbContext(appConfigs), + "sqlite" => new SqliteDbContext(appConfigs), + _ => throw new InvalidOperationException($"Unsupported database type: {dbType}") + }; + }); + + // Register Services + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddScoped(); + + // Register Workers + builder.Services.AddHostedService(); + builder.Services.AddHostedService(); + + // Register Channels + builder.Services.AddSingleton(Channel.CreateUnbounded()); + + var host = builder.Build(); + + try + { + Log.Information("Starting database migration..."); + + using var scope = host.Services.CreateScope(); + + var db = scope.ServiceProvider.GetRequiredService(); + await db.InitializeDatabaseAsync(); + + var appCoinfigs = host.Services.GetRequiredService(); + appCoinfigs.RuntimeConfigs = await db.LoadConfigAsync(); + + Log.Information("Database initialization completed successfully"); + } + catch (Exception ex) + { + Log.Fatal(ex, "Database migration failed. Application cannot start without a valid database connection."); + Log.CloseAndFlush(); + Environment.Exit(1); + } + + host.Run(); + } + } +} diff --git a/Properties/launchSettings.json b/Properties/launchSettings.json new file mode 100644 index 0000000..9433092 --- /dev/null +++ b/Properties/launchSettings.json @@ -0,0 +1,12 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "TriliumMind": { + "commandName": "Project", + "dotnetRunMessages": true, + "environmentVariables": { + "DOTNET_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Services/AppDbService.cs b/Services/AppDbService.cs new file mode 100644 index 0000000..b6c30c4 --- /dev/null +++ b/Services/AppDbService.cs @@ -0,0 +1,105 @@ +using Microsoft.EntityFrameworkCore; +using Serilog; +using TriliumMind.Data; +using TriliumMind.Data.Entities; + +namespace TriliumMind.Services; + +public class AppDbService +{ + private readonly Serilog.ILogger _log; + private readonly IAppDbContext _db; + public AppDbService(IAppDbContext dbContext) + { + _log = Log.ForContext(); + _db = dbContext; + } + + public async Task InitializeDatabaseAsync() + { + try + { + _log.Information("Checking database..."); + + // Create db if not exists + var created = await _db.Database.EnsureCreatedAsync(); + if (created) + { + _log.Information("Database created successfully"); + } + else + { + _log.Information("Database already exists"); + } + + // Migration + var pendingMigrations = await _db.Database.GetPendingMigrationsAsync(); + if (pendingMigrations.Any()) + { + _log.Information("Applying pending migrations..."); + await _db.Database.MigrateAsync(); + _log.Information("Migrations applied successfully"); + } + } + catch (Exception ex) + { + _log.Error(ex, "Failed to initialize database"); + throw; + } + } + + public async Task> LoadConfigAsync() + { + try + { + _log.Information("Loading configuration from database..."); + var configs = await _db.Configs.ToDictionaryAsync(c => c.Key, c => c.Value); + _log.Information("Loaded {count} configuration entries", configs.Count); + return configs; + } + catch (Exception ex) + { + _log.Error(ex, "Failed to load configuration from database"); + throw; + } + } + public async Task GetConfigAsync(string key) + { + try + { + var config = await _db.Configs.FindAsync(key); + return config?.Value; + } + catch (Exception ex) + { + _log.Error(ex, "Failed to get config value for key: {key}", key); + throw; + } + } + public async Task SetConfigAsync(string key, string value) + { + try + { + var config = await _db.Configs.FindAsync(key); + if (config == null) + { + config = new Config { Key = key, Value = value }; + _db.Configs.Add(config); + } + else + { + config.Value = value; + _db.Configs.Update(config); + } + await _db.SaveChangesAsync(); + _log.Debug("Config saved: {key} = {value}", key, value); + } + catch (Exception ex) + { + _log.Error(ex, "Failed to set config value for key: {key}", key); + throw; + } + } + + +} diff --git a/Services/JiraService.cs b/Services/JiraService.cs new file mode 100644 index 0000000..205c7e5 --- /dev/null +++ b/Services/JiraService.cs @@ -0,0 +1,59 @@ +using Serilog; +using Microsoft.Extensions.Options; +using System.Text.Json; +using TriliumMind.Models; + +namespace TriliumMind.Services; + +public class JiraService +{ + private readonly AppConfigs _configs; + private readonly Serilog.ILogger _log; + + public JiraService(AppConfigs configs) + { + _configs = configs; + _log = Log.ForContext(); + } + + public async Task FetchJiraIssuesAsync( + DateTimeOffset lastFetchTime, string targetProject,int startAt, CancellationToken ct) + { + var uri = $"{_configs.AppSettings.Jira.ApiBaseUrl}/" + + $"search?jql=project={targetProject} " + + $"AND updated >= \"{lastFetchTime.ToString("yyyy-MM-dd HH:mm")}\" " + + $"&fields={_configs.AppSettings.Jira.SearchFields}" + + $"&startAt={startAt}&maxResults=50"; + var request = new HttpRequestMessage(HttpMethod.Get, uri); + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Authorization", $"Bearer {_configs.AppSettings.Jira.AccessToken}"); + Log.Debug("Fetch Jira issues ready. Fetch the issues updated after {last_fetch_time} in Project {target_project}.", + lastFetchTime.ToString("yyyy-MM-dd HH:mm"), targetProject); + + using var client = new HttpClient(); + var response = await client.SendAsync(request, ct).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + + var jsonResponse = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false); + var jiraResponse = JsonSerializer.Deserialize(jsonResponse); + + return jiraResponse; + } + + public async Task FetchJiraIssueAsync(string targetIssueKey, CancellationToken ct) + { + var uri = $"{_configs.AppSettings.Jira.ApiBaseUrl}/issue/{targetIssueKey}"; + var request = new HttpRequestMessage(HttpMethod.Get, uri); + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Authorization", $"Bearer {_configs.AppSettings.Jira.AccessToken}"); + Log.Debug("Fetch a Jira issue({issue_key}) ready.", targetIssueKey); + + using var client = new HttpClient(); + var response = await client.SendAsync(request, ct).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + + var jsonResponse = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false); + var issue = JsonSerializer.Deserialize(jsonResponse); + return issue; + } +} diff --git a/Services/TriliumService.cs b/Services/TriliumService.cs new file mode 100644 index 0000000..6e9e4de --- /dev/null +++ b/Services/TriliumService.cs @@ -0,0 +1,37 @@ +using Microsoft.Extensions.Options; +using Serilog; +using System; +using System.Collections.Generic; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text; +using TriliumMind.Models; + +namespace TriliumMind.Services; + +public class TriliumService +{ + private readonly Serilog.ILogger _log; + private readonly AppConfigs _configs; + public TriliumService(AppConfigs configs) + { + _log = Log.ForContext(); + _configs = configs; + } + public async Task FettchPageContentsAsync(Issue issue) + { + var baseUrl = _configs.AppSettings.Trilium.EtapiBaseUrl; + var pageId = "QxxFqCNAtIOy"; + var requstUrl = $"{baseUrl}/notes/{pageId}/content"; + + var client = new HttpClient(); + var request = new HttpRequestMessage(HttpMethod.Get, requstUrl); + request.Headers.Add("Authorization", ""); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + Console.WriteLine(await response.Content.ReadAsStringAsync()); + + // Return new page ID after creating a new page + return ""; + } +} diff --git a/TriliumMind.csproj b/TriliumMind.csproj new file mode 100644 index 0000000..682aae9 --- /dev/null +++ b/TriliumMind.csproj @@ -0,0 +1,19 @@ + + + + net10.0 + enable + enable + dotnet-TriliumMind-bf69239d-751f-426d-afd4-3f66bcf0dc42 + + + + + + + + + + + + diff --git a/TriliumMind.slnx b/TriliumMind.slnx new file mode 100644 index 0000000..259e2fe --- /dev/null +++ b/TriliumMind.slnx @@ -0,0 +1,3 @@ + + + diff --git a/Workers/JiraWorker.cs b/Workers/JiraWorker.cs new file mode 100644 index 0000000..8cbcec5 --- /dev/null +++ b/Workers/JiraWorker.cs @@ -0,0 +1,55 @@ +using Microsoft.Extensions.Options; +using Serilog; +using System.Numerics; +using System.Threading.Channels; +using TriliumMind.Models; +using TriliumMind.Services; + +namespace TriliumMind.Workers; + +public class JiraWorker : BackgroundService +{ + private readonly Serilog.ILogger _log; + private readonly AppConfigs _configs; + private readonly JiraService _jira; + private readonly Channel _issueChannel; + + public JiraWorker(AppConfigs configs, JiraService jaraService, Channel issueChannel) + { + _log = Log.ForContext(); ; + _configs = configs; + _jira = jaraService; + _issueChannel = issueChannel; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + _log.Debug("Worker running at: {time}", DateTimeOffset.Now); + + var lastFetchTime = DateTimeOffset.Parse(_configs.RuntimeConfigs[Consts.ConfigLastFetchTimeKey]); + + var issueList = new List(); + foreach (var targetProject in _configs.AppSettings.Jira.TargetProjects) + { + int startAt = 0, total = 0; + do + { + var response = await _jira.FetchJiraIssuesAsync(DateTimeOffset.Now.AddDays(-1), targetProject, startAt, stoppingToken); + if (response != null) + { + total = response.total; + startAt += response.maxResults; + issueList.AddRange(response.issues); + } + } while(startAt < total); + } + foreach (var item in issueList) + { + await _issueChannel.Writer.WriteAsync(item, stoppingToken); + } + await Task.Delay(_configs.AppSettings.Jira.FetchInterval * 1000, stoppingToken); + } + } +} diff --git a/Workers/TriliumWorker.cs b/Workers/TriliumWorker.cs new file mode 100644 index 0000000..f3a51bd --- /dev/null +++ b/Workers/TriliumWorker.cs @@ -0,0 +1,33 @@ +using Microsoft.Extensions.Options; +using Serilog; +using System.Threading.Channels; +using TriliumMind.Models; +using TriliumMind.Services; + +namespace TriliumMind.Workers; + +public class TriliumWorker : BackgroundService +{ + private readonly Serilog.ILogger _log; + private readonly AppConfigs _config; + private readonly TriliumService _triliumService; + private readonly Channel _issueChannel; + + public TriliumWorker(AppConfigs configs, TriliumService triliumService, Channel issueChannel) + { + _log = Log.ForContext(); + _config = configs; + _triliumService = triliumService; + _issueChannel = issueChannel; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + await foreach(var item in _issueChannel.Reader.ReadAllAsync(stoppingToken)) + { + _log.Information("Processing issue {issue_key} - {issue_summary}", item.key, item.fields.summary); + // Add your processing logic here + //await _triliumService.FettchPageContentsAsync(item); + } + } +} diff --git a/appsettings.json b/appsettings.json new file mode 100644 index 0000000..7526f4f --- /dev/null +++ b/appsettings.json @@ -0,0 +1,51 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "Serilog": { + "Using": [ "Serilog.Sinks.Console" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "Console", + "Args": { + "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] ({SourceContext}) {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext" ] + }, + "Trilium": { + "EtapiToken": "your-token-here", + "EtapiBaseUrl": "https://localhost/etapi", + "JiraOpenedIssuePageId": "yourpageid", + "JiraWorkingIssuePageId": "yourpageid", + "JiraResolvedIssuePageId": "yourpageid", + "DividendPageId": "yourpageid" + }, + "Jira": { + "BaseUrl": "https://localhost", + "ApiBaseUrl": "https://localhost/rest/api/2", + "AccessToken": "your-token-here", + "TargetProjects": [ "MYPROJ" ], + "FetchInterval": 120, + "SearchFields": "key,title" + }, + "Database": { + "Type": "Postgres", + "Sqlite": { + "DatabaseFilePath": "folder/TriliumMind.db" + }, + "Postgres": { + "Host": "localhost", + "Port": 5432, + "Database": "triliummind", + "Username": "your-username", + "Password": "your-password", + "SslCertificatePath": "/path/to/your/certificate.pem" + } + } +}