DigiKam4 Archive

Change to only need the one json file and changed AppSettings to not need a binder file

Editorconfig for no new line before open braces

Nuget package bumps

Database lowest-version-history
This commit is contained in:
2025-07-27 16:03:47 -07:00
parent ab90adee42
commit c4d42d79a0
31 changed files with 644 additions and 458 deletions

View File

@ -21,12 +21,12 @@ csharp_indent_case_contents = true
csharp_indent_case_contents_when_block = true csharp_indent_case_contents_when_block = true
csharp_indent_labels = one_less_than_current csharp_indent_labels = one_less_than_current
csharp_indent_switch_labels = true csharp_indent_switch_labels = true
csharp_new_line_before_catch = true csharp_new_line_before_catch = false
csharp_new_line_before_else = true csharp_new_line_before_else = false
csharp_new_line_before_finally = true csharp_new_line_before_finally = false
csharp_new_line_before_members_in_anonymous_types = true csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_before_members_in_object_initializers = true csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_open_brace = all csharp_new_line_before_open_brace = none
csharp_new_line_between_query_expression_clauses = true csharp_new_line_between_query_expression_clauses = true
csharp_prefer_braces = false csharp_prefer_braces = false
csharp_prefer_qualified_reference = true:error csharp_prefer_qualified_reference = true:error
@ -106,101 +106,37 @@ dotnet_code_quality_unused_parameters = all
dotnet_code_quality_unused_parameters = non_public dotnet_code_quality_unused_parameters = non_public
dotnet_code_quality.CAXXXX.api_surface = private, internal dotnet_code_quality.CAXXXX.api_surface = private, internal
dotnet_diagnostic.CA1001.severity = error # CA1001: Types that own disposable fields should be disposable dotnet_diagnostic.CA1001.severity = error # CA1001: Types that own disposable fields should be disposable
dotnet_diagnostic.CA1001.severity = none # Question - CA1001: Types that own disposable fields should be disposable
dotnet_diagnostic.CA1051.severity = error # CA1051: Do not declare visible instance fields dotnet_diagnostic.CA1051.severity = error # CA1051: Do not declare visible instance fields
dotnet_diagnostic.CA1051.severity = none # Question - CA1051: Do not declare visible instance fields
dotnet_diagnostic.CA1416.severity = none # Question - CA1416: This call site is reachable on all platforms. 'EventLogEntryType.Error' is only supported on: 'windows'.
dotnet_diagnostic.CA1510.severity = none # Question - CA1510: Use 'ArgumentNullException.ThrowIfNull' instead of explicitly throwing a new exception instance
dotnet_diagnostic.CA1511.severity = warning # CA1511: Use 'ArgumentException.ThrowIfNullOrEmpty' instead of explicitly throwing a new exception instance dotnet_diagnostic.CA1511.severity = warning # CA1511: Use 'ArgumentException.ThrowIfNullOrEmpty' instead of explicitly throwing a new exception instance
dotnet_diagnostic.CA1513.severity = warning # Use 'ObjectDisposedException.ThrowIf' instead of explicitly throwing a new exception instance dotnet_diagnostic.CA1513.severity = warning # Use 'ObjectDisposedException.ThrowIf' instead of explicitly throwing a new exception instance
dotnet_diagnostic.CA1825.severity = warning # CA1825: Avoid zero-length array allocations dotnet_diagnostic.CA1825.severity = warning # CA1825: Avoid zero-length array allocations
dotnet_diagnostic.CA1829.severity = error # CA1829: Use Length/Count property instead of Count() when available dotnet_diagnostic.CA1829.severity = warning # CA1829: Use Length/Count property instead of Count() when available
dotnet_diagnostic.CA1829.severity = none # Question - CA1829: Use Length/Count property instead of Enumerable.Count method
dotnet_diagnostic.CA1834.severity = warning # CA1834: Consider using 'StringBuilder.Append(char)' when applicable dotnet_diagnostic.CA1834.severity = warning # CA1834: Consider using 'StringBuilder.Append(char)' when applicable
dotnet_diagnostic.CA1860.severity = error # CA1860: Prefer comparing 'Count' to 0 rather than using 'Any()', both for clarity and for performance dotnet_diagnostic.CA1860.severity = error # CA1860: Prefer comparing 'Count' to 0 rather than using 'Any()', both for clarity and for performance
dotnet_diagnostic.CA1860.severity = none # Question - CA1860: Avoid using 'Enumerable.Any()' extension method
dotnet_diagnostic.CA1862.severity = warning # CA1862: Prefer using 'string.Equals(string, StringComparison)' to perform a case-insensitive comparison, but keep in mind that this might cause subtle changes in behavior, so make sure to conduct thorough testing after applying the suggestion, or if culturally sensitive comparison is not required, consider using 'StringComparison.OrdinalIgnoreCase' dotnet_diagnostic.CA1862.severity = warning # CA1862: Prefer using 'string.Equals(string, StringComparison)' to perform a case-insensitive comparison, but keep in mind that this might cause subtle changes in behavior, so make sure to conduct thorough testing after applying the suggestion, or if culturally sensitive comparison is not required, consider using 'StringComparison.OrdinalIgnoreCase'
dotnet_diagnostic.CA1862.severity = none # Question - CA1862: Prefer using 'string.Equals(string, StringComparison)' to perform a case-insensitive comparison, but keep in mind that this might cause subtle changes in behavior, so make sure to conduct thorough testing after applying the suggestion, or if culturally sensitive comparison is not required, consider using 'StringComparison.OrdinalIgnoreCase'
dotnet_diagnostic.CA1869.severity = none # CA1869: Avoid creating a new 'JsonSerializerOptions' instance for every serialization operation. Cache and reuse instances instead. dotnet_diagnostic.CA1869.severity = none # CA1869: Avoid creating a new 'JsonSerializerOptions' instance for every serialization operation. Cache and reuse instances instead.
dotnet_diagnostic.CA2200.severity = none # Question - CA2200: Re-throwing caught exception changes stack information
dotnet_diagnostic.CA2201.severity = none # CA2201: Exception type System.NullReferenceException is reserved by the runtime dotnet_diagnostic.CA2201.severity = none # CA2201: Exception type System.NullReferenceException is reserved by the runtime
dotnet_diagnostic.CA2208.severity = none # Question - CA2208: Instantiate argument exceptions correctly
dotnet_diagnostic.CA2211.severity = none # Question - CA2211: Non-constant fields should not be visible
dotnet_diagnostic.CA2249.severity = none # Question - CA2249: Use 'string.Contains' instead of 'string.IndexOf' to improve readability
dotnet_diagnostic.CA2253.severity = none # Question - CA2253: Named placeholders should not be numeric values
dotnet_diagnostic.CA2254.severity = none # CA2254: The logging message template should not vary between calls to 'LoggerExtensions.LogInformation(ILogger, string?, params object?[])' dotnet_diagnostic.CA2254.severity = none # CA2254: The logging message template should not vary between calls to 'LoggerExtensions.LogInformation(ILogger, string?, params object?[])'
dotnet_diagnostic.CS0103.severity = none # Question - CS0103: The name 'Functions' does not exist in the current context
dotnet_diagnostic.CS0168.severity = none # Question - CS0168: The variable 'ex' is declared but never used
dotnet_diagnostic.CS0219.severity = none # Question - CS0219: The variable 'result' is assigned but its value is never used
dotnet_diagnostic.CS0618.severity = none # Question - CS0618: Compiler Warning (level 2)
dotnet_diagnostic.CS0659.severity = none # Question - CS0659: Compiler Warning (level 3)
dotnet_diagnostic.CS8600.severity = none # Question - CS8600: Converting null literal or possible null value to non-nullable type
dotnet_diagnostic.CS8602.severity = none # Question - CS8602: Dereference of a possibly null reference.
dotnet_diagnostic.CS8603.severity = none # Question - CS8603: Possible null reference return
dotnet_diagnostic.CS8604.severity = none # Question - CS8604: Possible null reference argument for parameter.
dotnet_diagnostic.CS0612.severity = none # Question - CS0612: is obsolete
dotnet_diagnostic.CS8618.severity = none # Question - CS8618: Non-nullable variable must contain a non-null value when exiting constructor
dotnet_diagnostic.CS8625.severity = none # Question - CS8625: Cannot convert null literal to non-nullable reference type.
dotnet_diagnostic.CS8629.severity = none # Question - CS8629: Nullable value type may be null
dotnet_diagnostic.CS8765.severity = none # Question - CS8765: Nullability of type of parameter doesn't match overridden member (possibly because of nullability attributes)
dotnet_diagnostic.IDE0001.severity = warning # IDE0001: Simplify name dotnet_diagnostic.IDE0001.severity = warning # IDE0001: Simplify name
dotnet_diagnostic.IDE0002.severity = warning # Simplify (member access) - System.Version.Equals("1", "2"); Version.Equals("1", "2"); dotnet_diagnostic.IDE0002.severity = warning # Simplify (member access) - System.Version.Equals("1", "2"); Version.Equals("1", "2");
dotnet_diagnostic.IDE0004.severity = warning # IDE0004: Cast is redundant. dotnet_diagnostic.IDE0004.severity = warning # IDE0004: Cast is redundant.
dotnet_diagnostic.IDE0004.severity = none # Question - IDE0004: Cast is redundant. dotnet_diagnostic.IDE0005.severity = warning # Using directive is unnecessary
dotnet_diagnostic.IDE0003.severity = none # Question - IDE0003: this and Me preferences
dotnet_diagnostic.IDE0005.severity = error # Using directive is unnecessary
dotnet_diagnostic.IDE0005.severity = none # Question - IDE0005: Remove unnecessary using directives
dotnet_diagnostic.IDE0008.severity = none # Question - IDE0008: 'var' preferences
dotnet_diagnostic.IDE0010.severity = none # Add missing cases to switch statement (IDE0010) dotnet_diagnostic.IDE0010.severity = none # Add missing cases to switch statement (IDE0010)
dotnet_diagnostic.IDE0017.severity = none # Question - IDE0017: Use object initializers
dotnet_diagnostic.IDE0019.severity = none # Question - IDE0019: Use pattern matching to avoid 'as' followed by a 'null' check
dotnet_diagnostic.IDE0021.severity = none # Question - IDE0021: Use expression body for constructors
dotnet_diagnostic.IDE0022.severity = none # Question - IDE0022: Use expression body for methods
dotnet_diagnostic.IDE0025.severity = none # Question - IDE0025: Use expression body for properties
dotnet_diagnostic.IDE0027.severity = none # Question - IDE0027: Use expression body for accessor
dotnet_diagnostic.IDE0028.severity = error # IDE0028: Collection initialization can be simplified dotnet_diagnostic.IDE0028.severity = error # IDE0028: Collection initialization can be simplified
dotnet_diagnostic.IDE0028.severity = none # Question - IDE0028: Use collection initializers or expressions
dotnet_diagnostic.IDE0031.severity = warning # Use null propagation (IDE0031) dotnet_diagnostic.IDE0031.severity = warning # Use null propagation (IDE0031)
dotnet_diagnostic.IDE0031.severity = none # Question - IDE0031: Use null propagation (IDE0031)
dotnet_diagnostic.IDE0032.severity = none # Question - IDE0032: Use auto-implemented property
dotnet_diagnostic.IDE0037.severity = none # Question - IDE0037: Member name can be simplified
dotnet_diagnostic.IDE0040.severity = none # Question - IDE0040: Add accessibility modifiers
dotnet_diagnostic.IDE0041.severity = none # Question - IDE0041: Use 'is null' check
dotnet_diagnostic.IDE0044.severity = none # Question - IDE0044: Add readonly modifier
dotnet_diagnostic.IDE0047.severity = warning # IDE0047: Parentheses can be removed dotnet_diagnostic.IDE0047.severity = warning # IDE0047: Parentheses can be removed
dotnet_diagnostic.IDE0047.severity = none # Question - IDE0047: Parentheses preferences
dotnet_diagnostic.IDE0048.severity = none # Parentheses preferences (IDE0047 and IDE0048) dotnet_diagnostic.IDE0048.severity = none # Parentheses preferences (IDE0047 and IDE0048)
dotnet_diagnostic.IDE0049.severity = warning # Use language keywords instead of framework type names for type references (IDE0049) dotnet_diagnostic.IDE0049.severity = warning # Use language keywords instead of framework type names for type references (IDE0049)
dotnet_diagnostic.IDE0051.severity = error # Private member '' is unused [, ] dotnet_diagnostic.IDE0051.severity = error # Private member '' is unused [, ]
dotnet_diagnostic.IDE0051.severity = none # Question - IDE0051: Remove unused private member dotnet_diagnostic.IDE0058.severity = warning # IDE0058: Expression value is never used
dotnet_diagnostic.IDE0053.severity = none # Question - IDE0053: Use expression body for lambdas
dotnet_diagnostic.IDE0054.severity = none # Question - IDE0054: Use compound assignment
dotnet_diagnostic.IDE0055.severity = none # Question - IDE0055: Formatting rule
dotnet_diagnostic.IDE0057.severity = none # Question - IDE0057: Substring can be simplified
dotnet_diagnostic.IDE0058.severity = error # IDE0058: Expression value is never used
dotnet_diagnostic.IDE0058.severity = none # Question - IDE0058: Remove unnecessary expression value
dotnet_diagnostic.IDE0059.severity = none # Question - IDE0059: Remove unnecessary value assignment
dotnet_diagnostic.IDE0060.severity = error # IDE0060: Remove unused parameter dotnet_diagnostic.IDE0060.severity = error # IDE0060: Remove unused parameter
dotnet_diagnostic.IDE0060.severity = none # Question - IDE0060: Remove unused parameter
dotnet_diagnostic.IDE0063.severity = none # Question - IDE0063: Use simple 'using' statement
dotnet_diagnostic.IDE0066.severity = none # Question - IDE0066: Use switch expression
dotnet_diagnostic.IDE0074.severity = warning # IDE0074: Use compound assignment dotnet_diagnostic.IDE0074.severity = warning # IDE0074: Use compound assignment
dotnet_diagnostic.IDE0078.severity = none # Question - IDE0078: Use pattern matching
dotnet_diagnostic.IDE0100.severity = none # Question - IDE0100: Remove redundant equality
dotnet_diagnostic.IDE0090.severity = none # Question - IDE0090: Simplify new expression
dotnet_diagnostic.IDE0130.severity = none # Namespace does not match folder structure (IDE0130) dotnet_diagnostic.IDE0130.severity = none # Namespace does not match folder structure (IDE0130)
dotnet_diagnostic.IDE0161.severity = none # Question - IDE0161: Namespace declaration preferences
dotnet_diagnostic.IDE0270.severity = none # Question - IDE0270: Null check can be simplified
dotnet_diagnostic.IDE0270.severity = warning # IDE0270: Null check can be simplified dotnet_diagnostic.IDE0270.severity = warning # IDE0270: Null check can be simplified
dotnet_diagnostic.IDE0290.severity = none # Use primary constructor [Distance]csharp(IDE0290) dotnet_diagnostic.IDE0290.severity = none # Use primary constructor [Distance]csharp(IDE0290)
dotnet_diagnostic.IDE0300.severity = error # IDE0300: Collection initialization can be simplified dotnet_diagnostic.IDE0300.severity = error # IDE0300: Collection initialization can be simplified
dotnet_diagnostic.IDE0065.severity = none # Question - IDE0065: 'using' directive placement
dotnet_diagnostic.IDE0300.severity = none # Question - IDE0300: Collection initialization can be simplified
dotnet_diagnostic.IDE0301.severity = error #IDE0301: Collection initialization can be simplified dotnet_diagnostic.IDE0301.severity = error #IDE0301: Collection initialization can be simplified
dotnet_diagnostic.IDE0305.severity = none # IDE0305: Collection initialization can be simplified dotnet_diagnostic.IDE0305.severity = none # IDE0305: Collection initialization can be simplified
dotnet_diagnostic.IDE1006.severity = none # Question - IDE1006: Use collection expression for builder dotnet_style_prefer_collection_expression
dotnet_diagnostic.IDE2000.severity = error # IDE2000: Allow multiple blank lines
dotnet_diagnostic.IDE2000.severity = none # Question - IDE2000: Allow multiple blank lines
dotnet_naming_rule.abstract_method_should_be_pascal_case.severity = warning dotnet_naming_rule.abstract_method_should_be_pascal_case.severity = warning
dotnet_naming_rule.abstract_method_should_be_pascal_case.style = pascal_case dotnet_naming_rule.abstract_method_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.abstract_method_should_be_pascal_case.symbols = abstract_method dotnet_naming_rule.abstract_method_should_be_pascal_case.symbols = abstract_method

View File

@ -26,6 +26,7 @@
"dbmdl", "dbmdl",
"dbproj", "dbproj",
"DENITED", "DENITED",
"Digi",
"dlldata", "dlldata",
"docstates", "docstates",
"ebug", "ebug",

View File

@ -1,3 +1,5 @@
@host = http://0.0.0.0:5001
GET {{host}}/api/v1/assets/columns/ GET {{host}}/api/v1/assets/columns/
Accept: application/json Accept: application/json
@ -33,6 +35,11 @@ Accept: application/json
### ###
GET {{host}}/api/v1/assets/{{ownerId}}/set-digi-kam-4-archive-immich/
Accept: application/json
###
GET {{host}}/api/v1/assets/{{ownerId}}/archived-tag/ GET {{host}}/api/v1/assets/{{ownerId}}/archived-tag/
Accept: application/json Accept: application/json

View File

@ -1,27 +1,27 @@
using ImmichToSlideshow.Services; using ImmichToSlideshow.Services;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace ImmichToSlideshow.Controllers; namespace ImmichToSlideshow.Controllers;
[ApiController] [ApiController]
[Route("api/v1/[controller]")] [Route("api/v1/[controller]")]
public class AssetsController(AssetService assetService) : ControllerBase public class AssetsController(AssetService assetService) : ControllerBase {
{
private readonly string _ContentType = "application/json"; private readonly string _ContentType = "application/json";
private readonly AssetService _AssetService = assetService; private readonly AssetService _AssetService = assetService;
[HttpGet("columns")] [HttpGet("columns")]
public IActionResult GetColumns() => public IActionResult GetColumns() =>
Content(_AssetService.GetColumns(), _ContentType); Content(_AssetService.GetColumns() ?? string.Empty, _ContentType);
[HttpGet("owner-ids")] [HttpGet("owner-ids")]
public IActionResult GetOwnerIds() => public IActionResult GetOwnerIds() =>
Content(_AssetService.GetOwnerIds(), _ContentType); Content(_AssetService.GetOwnerIds() ?? string.Empty, _ContentType);
[HttpGet("{ownerId:guid}")] [HttpGet("{ownerId:guid}")]
public IActionResult Get(Guid ownerId) => public IActionResult Get(Guid ownerId) =>
Content(_AssetService.GetAssets(ownerId), _ContentType); Content(_AssetService.GetAssets(ownerId) ?? string.Empty, _ContentType);
[HttpGet("{ownerId:guid}/random-paths")] [HttpGet("{ownerId:guid}/random-paths")]
public IActionResult GetRandomPaths(Guid ownerId) => public IActionResult GetRandomPaths(Guid ownerId) =>
@ -29,11 +29,11 @@ public class AssetsController(AssetService assetService) : ControllerBase
[HttpGet("{ownerId:guid}/archived-tag")] [HttpGet("{ownerId:guid}/archived-tag")]
public IActionResult GetArchivedTag(Guid ownerId) => public IActionResult GetArchivedTag(Guid ownerId) =>
Content(_AssetService.GetArchivedTag(ownerId), _ContentType); Content(_AssetService.GetArchivedTag(ownerId) ?? string.Empty, _ContentType);
[HttpGet("{ownerId:guid}/save-random-paths")] [HttpGet("{ownerId:guid}/save-random-paths")]
public IActionResult SaveRandomPaths(Guid ownerId) => public IActionResult SaveRandomPaths(Guid ownerId) =>
Content(_AssetService.SaveRandomPaths(ownerId), _ContentType); Content(_AssetService.SaveRandomPaths(ownerId) ?? string.Empty, _ContentType);
[HttpGet("{ownerId:guid}/sync-immich")] [HttpGet("{ownerId:guid}/sync-immich")]
public IActionResult SyncImmich(Guid ownerId) => public IActionResult SyncImmich(Guid ownerId) =>
@ -43,4 +43,8 @@ public class AssetsController(AssetService assetService) : ControllerBase
public IActionResult SetArchiveImmich(Guid ownerId) => public IActionResult SetArchiveImmich(Guid ownerId) =>
Ok(_AssetService.SetArchiveImmich(ownerId)); Ok(_AssetService.SetArchiveImmich(ownerId));
[HttpGet("{ownerId:guid}/set-digi-kam-4-archive-immich")]
public IActionResult SetDigiKam4ArchiveImmich(Guid ownerId) =>
Ok(_AssetService.SetDigiKam4ArchiveImmich(ownerId));
} }

View File

@ -3,11 +3,9 @@ using ImmichToSlideshow.Services;
namespace ImmichToSlideshow.DependencyInjection; namespace ImmichToSlideshow.DependencyInjection;
public static class ServiceCollectionExtensions public static class ServiceCollectionExtensions {
{
public static IServiceCollection AddServices(this IServiceCollection services, AppSettings appSettings) public static IServiceCollection AddServices(this IServiceCollection services, AppSettings appSettings) {
{
_ = services.AddScoped<AssetService>(); _ = services.AddScoped<AssetService>();
_ = services.AddSingleton(_ => appSettings); _ = services.AddSingleton(_ => appSettings);
return services; return services;

View File

@ -0,0 +1,74 @@
using ImmichToSlideshow.Models.DigiKam;
using System.Collections.ObjectModel;
namespace ImmichToSlideshow.Domain;
// Business concerns
public record ImageTag(long Id,
string Name,
string Tag) {
internal static ReadOnlyCollection<ImageTag>? Get(string tag, string? tagsPath, string? imageTagsPath, string? imagesPath) {
List<ImageTag>? results;
ReadOnlyCollection<Tags>? tags = Tags.GetTags(tagsPath);
if (tags is null || tags.Count == 0) {
results = null;
} else {
ReadOnlyCollection<int> tagIds = GetTagIds(tag, tags);
if (tagIds.Count == 0) {
results = null;
} else {
ReadOnlyCollection<ImageTags>? imageTags = ImageTags.GetImageTags(imageTagsPath);
if (imageTags is null || imageTags.Count == 0) {
results = null;
} else {
ReadOnlyCollection<int> imageIds = GetImageIds(imageTags, tagIds);
if (imageIds.Count == 0) {
results = null;
} else {
results = [];
long id;
ImageTag imageTag;
ReadOnlyCollection<Images>? images = Images.GetImages(imagesPath);
if (images is null || images.Count == 0) {
results = null;
} else {
foreach (Images i in images) {
if (!imageIds.Contains(i.Id) || !long.TryParse(i.Name.Split('.')[0], out id)) {
continue;
}
imageTag = new(Id: id, Name: i.Name, Tag: tag);
results.Add(imageTag);
}
}
}
}
}
}
return results?.AsReadOnly();
}
private static ReadOnlyCollection<int> GetTagIds(string tag, ReadOnlyCollection<Tags> tags) {
List<int> results = [];
foreach (Tags t in tags) {
if (t.Name != tag) {
continue;
}
results.Add(t.Id);
}
return results.AsReadOnly();
}
private static ReadOnlyCollection<int> GetImageIds(ReadOnlyCollection<ImageTags> imageTags, ReadOnlyCollection<int> tagIds) {
List<int> results = [];
foreach (ImageTags i in imageTags) {
if (!tagIds.Contains(i.TagId)) {
continue;
}
results.Add(i.ImageId);
}
return results.AsReadOnly();
}
}

View File

@ -1,13 +1,8 @@
namespace ImmichToSlideshow.Domain; namespace ImmichToSlideshow.Domain;
public class Product // Business concerns
{
public Guid Id { get; init; } = Guid.NewGuid(); public record Product(Guid Id,
public required string Name { get; init; } string Name,
public required string Category { get; init; } string Category,
public required string SubCategory { get; init; } string SubCategory);
// Business concerns
}

View File

@ -1,14 +1,11 @@
namespace ImmichToSlideshow.Domain; namespace ImmichToSlideshow.Domain;
public class User // Business concerns
{
public Guid Id { get; init; } = Guid.NewGuid(); public record User(Guid Id,
public List<Product> Products { get; init; } = []; List<Product> Products) {
internal void AddProduct(Product product) => internal void AddProduct(Product product) =>
Products.Add(product); Products.Add(product);
// Business concerns
} }

View File

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
@ -7,6 +7,7 @@
<UserSecretsId>cc24ad7a-1d95-4c47-a3ea-0d8475ab06da</UserSecretsId> <UserSecretsId>cc24ad7a-1d95-4c47-a3ea-0d8475ab06da</UserSecretsId>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Npgsql" Version="9.0.0" /> <PackageReference Include="Npgsql" Version="9.0.3" />
<PackageReference Include="System.Text.Json" Version="9.0.7" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -3,31 +3,68 @@ using System.Text.Json.Serialization;
namespace ImmichToSlideshow.Models; namespace ImmichToSlideshow.Models;
public record AppSettings(int AddDays, public record AppSettings(string Company, Settings Settings, string URLs, string[] WithOrigins) {
string ArchivedTag,
string Company,
string ConnectionString,
string CurrentCommit,
string CurrentResultsDirectory,
string[] FilterTags,
string ImmichUploadDirectory,
string RandomResultsDirectory,
string SyncDirectory,
string URLs,
string[] WithOrigins,
string WorkingDirectoryName)
{
public override string ToString() public override string ToString() {
{
string result = JsonSerializer.Serialize(this, AppSettingsSourceGenerationContext.Default.AppSettings); string result = JsonSerializer.Serialize(this, AppSettingsSourceGenerationContext.Default.AppSettings);
return result; return result;
} }
private static void Verify(AppSettings appSettings) {
if (appSettings?.Company is null)
throw new NullReferenceException(nameof(Company));
if (appSettings?.URLs is null)
throw new NullReferenceException(nameof(URLs));
if (appSettings?.WithOrigins is null)
throw new NullReferenceException(nameof(WithOrigins));
if (appSettings?.Settings?.AddDays is null)
throw new NullReferenceException(nameof(Settings.AddDays));
if (appSettings?.Settings?.ArchivedTag is null)
throw new NullReferenceException(nameof(Settings.ArchivedTag));
if (appSettings?.Settings?.ConnectionString is null)
throw new NullReferenceException(nameof(Settings.ConnectionString));
if (appSettings?.Settings?.DigiKam4 is null)
throw new NullReferenceException(nameof(Settings.DigiKam4));
if (appSettings?.Settings?.FilterTags is null)
throw new NullReferenceException(nameof(Settings.FilterTags));
if (appSettings?.Settings?.ImmichUploadDirectory is null)
throw new NullReferenceException(nameof(Settings.ImmichUploadDirectory));
if (appSettings?.Settings?.RandomResultsDirectory is null)
throw new NullReferenceException(nameof(Settings.RandomResultsDirectory));
if (appSettings?.Settings?.SyncDirectory is null)
throw new NullReferenceException(nameof(Settings.SyncDirectory));
}
public static AppSettings Get(IConfigurationRoot configurationRoot) {
AppSettings result;
#pragma warning disable IL3050, IL2026
string? urls = configurationRoot.GetSection(nameof(URLs)).Get<string>();
string? company = configurationRoot.GetSection(nameof(Company)).Get<string>();
Settings? settings = configurationRoot.GetSection(nameof(Settings)).Get<Settings>();
string[]? withOrigins = configurationRoot.GetSection(nameof(WithOrigins)).Get<string[]>();
#pragma warning restore IL3050, IL2026
if (company is null || settings is null || urls is null || withOrigins is null) {
List<string> paths = [];
foreach (IConfigurationProvider configurationProvider in configurationRoot.Providers) {
if (configurationProvider is not Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider jsonConfigurationProvider)
continue;
if (jsonConfigurationProvider.Source.FileProvider is not Microsoft.Extensions.FileProviders.PhysicalFileProvider physicalFileProvider)
continue;
paths.Add(physicalFileProvider.Root);
}
throw new NotSupportedException($"Not found!{Environment.NewLine}{string.Join(Environment.NewLine, paths.Distinct())}");
}
result = new(Company: company,
Settings: settings,
URLs: urls,
WithOrigins: withOrigins);
Verify(result);
return result;
}
} }
[JsonSourceGenerationOptions(WriteIndented = true)] [JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(AppSettings))] [JsonSerializable(typeof(AppSettings))]
internal partial class AppSettingsSourceGenerationContext : JsonSerializerContext internal partial class AppSettingsSourceGenerationContext : JsonSerializerContext {
{
} }

View File

@ -1,2 +0,0 @@
[*.cs]
csharp_preserve_single_line_statements = true

View File

@ -1,95 +0,0 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ImmichToSlideshow.Models.Binder;
public class AppSettings
{
public int? AddDays { get; set; }
public string? ArchivedTag { get; set; }
public string? Company { get; set; }
public string? ConnectionString { get; set; }
public string? CurrentCommit { get; set; }
public string? CurrentResultsDirectory { get; set; }
public string[]? FilterTags { get; set; }
public string? ImmichUploadDirectory { get; set; }
public string? RandomResultsDirectory { get; set; }
public string? SyncDirectory { get; set; }
public string? URLs { get; set; }
public string[]? WithOrigins { get; set; }
public string? WorkingDirectoryName { get; set; }
public override string ToString()
{
string result = JsonSerializer.Serialize(this, BinderAppSettingsSourceGenerationContext.Default.AppSettings);
return result;
}
private static void PreVerify(IConfigurationRoot configurationRoot, AppSettings? appSettings)
{
if (appSettings?.Company is null)
{
List<string> paths = [];
foreach (IConfigurationProvider configurationProvider in configurationRoot.Providers)
{
if (configurationProvider is not Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider jsonConfigurationProvider)
continue;
if (jsonConfigurationProvider.Source.FileProvider is not Microsoft.Extensions.FileProviders.PhysicalFileProvider physicalFileProvider)
continue;
paths.Add(physicalFileProvider.Root);
}
throw new NotSupportedException($"Not found!{Environment.NewLine}{string.Join(Environment.NewLine, paths.Distinct())}");
}
}
private static Models.AppSettings Get(AppSettings? appSettings)
{
Models.AppSettings result;
if (appSettings?.AddDays is null) throw new NullReferenceException(nameof(appSettings.AddDays));
if (appSettings?.ArchivedTag is null) throw new NullReferenceException(nameof(appSettings.ArchivedTag));
if (appSettings?.Company is null) throw new NullReferenceException(nameof(appSettings.Company));
if (appSettings?.ConnectionString is null) throw new NullReferenceException(nameof(appSettings.ConnectionString));
if (appSettings?.CurrentCommit is null) throw new NullReferenceException(nameof(appSettings.CurrentCommit));
if (appSettings?.CurrentResultsDirectory is null) throw new NullReferenceException(nameof(appSettings.CurrentResultsDirectory));
if (appSettings?.FilterTags is null) throw new NullReferenceException(nameof(appSettings.FilterTags));
if (appSettings?.ImmichUploadDirectory is null) throw new NullReferenceException(nameof(appSettings.ImmichUploadDirectory));
if (appSettings?.RandomResultsDirectory is null) throw new NullReferenceException(nameof(appSettings.RandomResultsDirectory));
if (appSettings?.SyncDirectory is null) throw new NullReferenceException(nameof(appSettings.SyncDirectory));
if (appSettings?.URLs is null) throw new NullReferenceException(nameof(appSettings.URLs));
if (appSettings?.WithOrigins is null) throw new NullReferenceException(nameof(appSettings.WithOrigins));
if (appSettings?.WorkingDirectoryName is null) throw new NullReferenceException(nameof(appSettings.WorkingDirectoryName));
result = new(appSettings.AddDays.Value,
appSettings.ArchivedTag,
appSettings.Company,
appSettings.ConnectionString,
appSettings.CurrentCommit,
appSettings.CurrentResultsDirectory,
appSettings.FilterTags,
appSettings.ImmichUploadDirectory,
appSettings.RandomResultsDirectory,
appSettings.SyncDirectory,
appSettings.URLs,
appSettings.WithOrigins,
appSettings.WorkingDirectoryName);
return result;
}
public static Models.AppSettings Get(IConfigurationRoot configurationRoot)
{
Models.AppSettings result;
#pragma warning disable IL3050, IL2026
AppSettings? appSettings = configurationRoot.Get<AppSettings>();
#pragma warning restore IL3050, IL2026
PreVerify(configurationRoot, appSettings);
result = Get(appSettings);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(AppSettings))]
internal partial class BinderAppSettingsSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -0,0 +1,11 @@
using System.Text.Json.Serialization;
namespace ImmichToSlideshow.Models.DigiKam;
public record AlbumRoots([property: JsonPropertyName("caseSensitivity")] int CaseSensitivity,
[property: JsonPropertyName("id")] int Id,
[property: JsonPropertyName("identifier")] string Identifier,
[property: JsonPropertyName("label")] string Label,
[property: JsonPropertyName("specificPath")] string SpecificPath,
[property: JsonPropertyName("status")] int Status,
[property: JsonPropertyName("type")] int Type);

View File

@ -0,0 +1,12 @@
using System.Text.Json.Serialization;
namespace ImmichToSlideshow.Models.DigiKam;
public record Albums([property: JsonPropertyName("albumRoot")] int AlbumRoot,
[property: JsonPropertyName("caption")] object Caption,
[property: JsonPropertyName("collection")] object Collection,
[property: JsonPropertyName("date")] string Date,
[property: JsonPropertyName("icon")] object Icon,
[property: JsonPropertyName("id")] int Id,
[property: JsonPropertyName("modificationDate")] DateTime ModificationDate,
[property: JsonPropertyName("relativePath")] string RelativePath);

View File

@ -0,0 +1,11 @@
using System.Text.Json.Serialization;
namespace ImmichToSlideshow.Models.DigiKam;
public record ImageComments([property: JsonPropertyName("author")] object Author,
[property: JsonPropertyName("comment")] string Comment,
[property: JsonPropertyName("date")] object Date,
[property: JsonPropertyName("id")] int Id,
[property: JsonPropertyName("imageid")] int ImageId,
[property: JsonPropertyName("language")] string Language,
[property: JsonPropertyName("type")] int Type);

View File

@ -0,0 +1,15 @@
using System.Text.Json.Serialization;
namespace ImmichToSlideshow.Models.DigiKam;
public record ImagePositions([property: JsonPropertyName("accuracy")] object Accuracy,
[property: JsonPropertyName("altitude")] double? Altitude,
[property: JsonPropertyName("description")] object Description,
[property: JsonPropertyName("imageid")] int ImageId,
[property: JsonPropertyName("latitude")] string Latitude,
[property: JsonPropertyName("latitudeNumber")] double? LatitudeNumber,
[property: JsonPropertyName("longitude")] string Longitude,
[property: JsonPropertyName("longitudeNumber")] double? LongitudeNumber,
[property: JsonPropertyName("orientation")] object Orientation,
[property: JsonPropertyName("roll")] object Roll,
[property: JsonPropertyName("tilt")] object Tilt);

View File

@ -0,0 +1,8 @@
using System.Text.Json.Serialization;
namespace ImmichToSlideshow.Models.DigiKam;
public record ImageTagProperties([property: JsonPropertyName("imageid")] int ImageId,
[property: JsonPropertyName("property")] string Property,
[property: JsonPropertyName("tagid")] int TagId,
[property: JsonPropertyName("value")] string Value);

View File

@ -0,0 +1,21 @@
using System.Collections.ObjectModel;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ImmichToSlideshow.Models.DigiKam;
public record ImageTags([property: JsonPropertyName("imageid")] int ImageId,
[property: JsonPropertyName("tagid")] int TagId) {
internal static ReadOnlyCollection<ImageTags>? GetImageTags(string? path) {
ImageTags[]? results;
if (string.IsNullOrEmpty(path) || !File.Exists(path)) {
results = null;
} else {
string json = File.ReadAllText(path);
results = JsonSerializer.Deserialize<ImageTags[]>(json);
}
return results?.AsReadOnly();
}
}

View File

@ -0,0 +1,28 @@
using System.Collections.ObjectModel;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ImmichToSlideshow.Models.DigiKam;
public record Images([property: JsonPropertyName("album")] int? Album,
[property: JsonPropertyName("category")] int Category,
[property: JsonPropertyName("fileSize")] object FileSize,
[property: JsonPropertyName("id")] int Id,
[property: JsonPropertyName("manualOrder")] object ManualOrder,
[property: JsonPropertyName("modificationDate")] DateTime ModificationDate,
[property: JsonPropertyName("name")] string Name,
[property: JsonPropertyName("status")] int Status,
[property: JsonPropertyName("uniqueHash")] string UniqueHash) {
internal static ReadOnlyCollection<Images>? GetImages(string? path) {
Images[]? results;
if (string.IsNullOrEmpty(path) || !File.Exists(path)) {
results = null;
} else {
string json = File.ReadAllText(path);
results = JsonSerializer.Deserialize<Images[]>(json);
}
return results?.AsReadOnly();
}
}

View File

@ -0,0 +1,7 @@
using System.Text.Json.Serialization;
namespace ImmichToSlideshow.Models.DigiKam;
public record TagProperties([property: JsonPropertyName("property")] string Property,
[property: JsonPropertyName("tagid")] int TagId,
[property: JsonPropertyName("value")] object Value);

View File

@ -0,0 +1,24 @@
using System.Collections.ObjectModel;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ImmichToSlideshow.Models.DigiKam;
public record Tags([property: JsonPropertyName("icon")] object Icon,
[property: JsonPropertyName("iconkde")] object IconKDE,
[property: JsonPropertyName("id")] int Id,
[property: JsonPropertyName("name")] string Name,
[property: JsonPropertyName("pid")] int PId) {
internal static ReadOnlyCollection<Tags>? GetTags(string? path) {
Tags[]? results;
if (string.IsNullOrEmpty(path) || !File.Exists(path)) {
results = null;
} else {
string json = File.ReadAllText(path);
results = JsonSerializer.Deserialize<Tags[]>(json);
}
return results?.AsReadOnly();
}
}

View File

@ -0,0 +1,22 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ImmichToSlideshow.Models;
public record DigiKam4(string Images,
string ImageTagProperties,
string ImageTags,
string TagProperties,
string Tags) {
public override string ToString() {
string result = JsonSerializer.Serialize(this, DigiKam4SourceGenerationContext.Default.DigiKam4);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(DigiKam4))]
public partial class DigiKam4SourceGenerationContext : JsonSerializerContext {
}

View File

@ -1,3 +1,4 @@
using ImmichToSlideshow.Domain;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
@ -10,11 +11,9 @@ public sealed record Identifier(string[] DirectoryNames,
int Id, int Id,
long Length, long Length,
string PaddedId, string PaddedId,
long Ticks) long Ticks) {
{
public override string ToString() public override string ToString() {
{
string result = JsonSerializer.Serialize(this, IdentifierSourceGenerationContext.Default.Identifier); string result = JsonSerializer.Serialize(this, IdentifierSourceGenerationContext.Default.Identifier);
return result; return result;
} }
@ -22,6 +21,9 @@ public sealed record Identifier(string[] DirectoryNames,
internal static string GetDeviceAssetIds(ReadOnlyCollection<Identifier> identifiers) => internal static string GetDeviceAssetIds(ReadOnlyCollection<Identifier> identifiers) =>
$"'{string.Join($"',{Environment.NewLine}'", (from l in identifiers select GetDeviceAssetId(l)).ToArray())}'"; $"'{string.Join($"',{Environment.NewLine}'", (from l in identifiers select GetDeviceAssetId(l)).ToArray())}'";
internal static string GetDeviceAssetIds(ReadOnlyCollection<ImageTag> imageTags) =>
$"'{string.Join($"',{Environment.NewLine}'", (from l in imageTags select l.Name).ToArray())}'";
internal static string GetDeviceAssetId(Identifier identifier) => internal static string GetDeviceAssetId(Identifier identifier) =>
$"{identifier.PaddedId}{identifier.Extension}"; $"{identifier.PaddedId}{identifier.Extension}";
@ -29,12 +31,10 @@ public sealed record Identifier(string[] DirectoryNames,
[JsonSourceGenerationOptions(WriteIndented = true)] [JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(Identifier))] [JsonSerializable(typeof(Identifier))]
public partial class IdentifierSourceGenerationContext : JsonSerializerContext public partial class IdentifierSourceGenerationContext : JsonSerializerContext {
{
} }
[JsonSourceGenerationOptions(WriteIndented = true)] [JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(Identifier[]))] [JsonSerializable(typeof(Identifier[]))]
public partial class IdentifierCollectionSourceGenerationContext : JsonSerializerContext public partial class IdentifierCollectionSourceGenerationContext : JsonSerializerContext {
{
} }

View File

@ -31,11 +31,9 @@ public record Asset([property: JsonPropertyName("id")] string Id,
// [property: JsonPropertyName("stackId")]? object? StackId, // [property: JsonPropertyName("stackId")]? object? StackId,
[property: JsonPropertyName("duplicateId")] string? DuplicateId, [property: JsonPropertyName("duplicateId")] string? DuplicateId,
// [property: JsonPropertyName("status")] string Status, // [property: JsonPropertyName("status")] string Status,
[property: JsonPropertyName("path")] string Path) [property: JsonPropertyName("path")] string Path) {
{
public override string ToString() public override string ToString() {
{
string result = JsonSerializer.Serialize(this, AssetSourceGenerationContext.Default.Asset); string result = JsonSerializer.Serialize(this, AssetSourceGenerationContext.Default.Asset);
return result; return result;
} }
@ -44,12 +42,10 @@ public record Asset([property: JsonPropertyName("id")] string Id,
[JsonSourceGenerationOptions(WriteIndented = true)] [JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(Asset))] [JsonSerializable(typeof(Asset))]
internal partial class AssetSourceGenerationContext : JsonSerializerContext internal partial class AssetSourceGenerationContext : JsonSerializerContext {
{
} }
[JsonSourceGenerationOptions(WriteIndented = true)] [JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(Asset[]))] [JsonSerializable(typeof(Asset[]))]
internal partial class AssetCollectionSourceGenerationContext : JsonSerializerContext internal partial class AssetCollectionSourceGenerationContext : JsonSerializerContext {
{
} }

View File

@ -10,11 +10,9 @@ public record Tag([property: JsonPropertyName("id")] string Id,
// [property: JsonPropertyName("updatedAt")] DateTime UpdatedAt, // [property: JsonPropertyName("updatedAt")] DateTime UpdatedAt,
// [property: JsonPropertyName("color")] char Color, // [property: JsonPropertyName("color")] char Color,
// [property: JsonPropertyName("parentId")] string ParentId, // [property: JsonPropertyName("parentId")] string ParentId,
[property: JsonPropertyName("updateId")] string UpdateId) [property: JsonPropertyName("updateId")] string UpdateId) {
{
public override string ToString() public override string ToString() {
{
string result = JsonSerializer.Serialize(this, TagSourceGenerationContext.Default.Tag); string result = JsonSerializer.Serialize(this, TagSourceGenerationContext.Default.Tag);
return result; return result;
} }
@ -23,12 +21,10 @@ public record Tag([property: JsonPropertyName("id")] string Id,
[JsonSourceGenerationOptions(WriteIndented = true)] [JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(Tag))] [JsonSerializable(typeof(Tag))]
internal partial class TagSourceGenerationContext : JsonSerializerContext internal partial class TagSourceGenerationContext : JsonSerializerContext {
{
} }
[JsonSourceGenerationOptions(WriteIndented = true)] [JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(Tag[]))] [JsonSerializable(typeof(Tag[]))]
internal partial class TagCollectionSourceGenerationContext : JsonSerializerContext internal partial class TagCollectionSourceGenerationContext : JsonSerializerContext {
{
} }

View File

@ -0,0 +1,27 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ImmichToSlideshow.Models;
public record Settings(int AddDays,
string ArchivedTag,
string ConnectionString,
DigiKam4? DigiKam4,
string[] FilterTags,
string ImmichUploadDirectory,
float LowestVersionHistory,
string NotNinePath,
string RandomResultsDirectory,
string SyncDirectory) {
public override string ToString() {
string result = JsonSerializer.Serialize(this, SettingsSourceGenerationContext.Default.Settings);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(Settings))]
public partial class SettingsSourceGenerationContext : JsonSerializerContext {
}

View File

@ -1,7 +1,6 @@
namespace ImmichToSlideshow.Persistence.Database; namespace ImmichToSlideshow.Persistence.Database;
public static class DbConstants public static class DbConstants {
{
public const string DefaultConnectionStringPath = "Database:ConnectionStrings:DefaultConnection"; public const string DefaultConnectionStringPath = "Database:ConnectionStrings:DefaultConnection";

View File

@ -4,14 +4,12 @@ using ImmichToSlideshow.RequestPipeline;
namespace ImmichToSlideshow; namespace ImmichToSlideshow;
public class Program public class Program {
{
public static void Main(string[] args) public static void Main(string[] args) {
{
WebApplicationBuilder webApplicationBuilder = WebApplication.CreateBuilder(args); WebApplicationBuilder webApplicationBuilder = WebApplication.CreateBuilder(args);
_ = webApplicationBuilder.Configuration.AddUserSecrets<Program>(); _ = webApplicationBuilder.Configuration.AddUserSecrets<Program>();
AppSettings appSettings = Models.Binder.AppSettings.Get(webApplicationBuilder.Configuration); AppSettings appSettings = AppSettings.Get(webApplicationBuilder.Configuration);
_ = webApplicationBuilder.Services.AddControllers(); _ = webApplicationBuilder.Services.AddControllers();
_ = webApplicationBuilder.Services.AddServices(appSettings); _ = webApplicationBuilder.Services.AddServices(appSettings);
WebApplication webApplication = webApplicationBuilder.Build(); WebApplication webApplication = webApplicationBuilder.Build();

View File

@ -2,19 +2,16 @@ using ImmichToSlideshow.Models;
namespace ImmichToSlideshow.RequestPipeline; namespace ImmichToSlideshow.RequestPipeline;
public static class WebApplicationExtensions public static class WebApplicationExtensions {
{
public static WebApplication InitializeDatabase(this WebApplication webApplication) => public static WebApplication InitializeDatabase(this WebApplication webApplication) =>
// DBInitializer.Initialize(application.Configuration[DbConstants.DefaultConnectionStringPath]!); // DBInitializer.Initialize(application.Configuration[DbConstants.DefaultConnectionStringPath]!);
webApplication; webApplication;
public static WebApplication InitializeCorsAndHttps(this WebApplication webApplication, AppSettings appSettings) public static WebApplication InitializeCorsAndHttps(this WebApplication webApplication, AppSettings appSettings) {
{
_ = webApplication.UseCors(corsPolicyBuilder => _ = webApplication.UseCors(corsPolicyBuilder =>
corsPolicyBuilder.WithOrigins(appSettings.WithOrigins).AllowAnyHeader().AllowAnyMethod()); corsPolicyBuilder.WithOrigins(appSettings.WithOrigins).AllowAnyHeader().AllowAnyMethod());
if (appSettings.URLs.Contains("https", StringComparison.InvariantCultureIgnoreCase)) if (appSettings.URLs.Contains("https", StringComparison.InvariantCultureIgnoreCase)) {
{
_ = webApplication.UseHttpsRedirection(); _ = webApplication.UseHttpsRedirection();
_ = webApplication.UseHsts(); _ = webApplication.UseHsts();
} }

View File

@ -1,3 +1,4 @@
using ImmichToSlideshow.Domain;
using ImmichToSlideshow.Models; using ImmichToSlideshow.Models;
using ImmichToSlideshow.Models.Immich; using ImmichToSlideshow.Models.Immich;
using Npgsql; using Npgsql;
@ -8,21 +9,18 @@ using System.Text.Json;
namespace ImmichToSlideshow.Services; namespace ImmichToSlideshow.Services;
public class AssetService(ILogger<Program> logger, AppSettings appSettings) public class AssetService(ILogger<Program> logger, AppSettings appSettings) {
{
#pragma warning disable CS9124 #pragma warning disable CS9124
private readonly ILogger<Program> _Logger = logger; private readonly ILogger<Program> _Logger = logger;
private readonly AppSettings _AppSettings = appSettings; private readonly Settings _Settings = appSettings.Settings;
#pragma warning restore CS9124 #pragma warning restore CS9124
private static int? ExecuteNonQuery(string connectionString, string commandText, ReadOnlyCollection<NpgsqlParameter> npgsqlParameters) private static int? ExecuteNonQuery(string connectionString, string commandText, ReadOnlyCollection<NpgsqlParameter> npgsqlParameters) {
{
int? result; int? result;
if (string.IsNullOrEmpty(connectionString)) if (string.IsNullOrEmpty(connectionString)) {
result = null; result = null;
else } else {
{
using NpgsqlConnection npgsqlConnection = new(connectionString); using NpgsqlConnection npgsqlConnection = new(connectionString);
npgsqlConnection.Open(); npgsqlConnection.Open();
using NpgsqlCommand npgsqlCommand = new(commandText, npgsqlConnection); using NpgsqlCommand npgsqlCommand = new(commandText, npgsqlConnection);
@ -32,61 +30,60 @@ public class AssetService(ILogger<Program> logger, AppSettings appSettings)
return result; return result;
} }
private static StringBuilder GetForJsonPath(string connectionString, string commandText, ReadOnlyCollection<NpgsqlParameter> npgsqlParameters) private static StringBuilder GetForJsonPath(string connectionString, string commandText, ReadOnlyCollection<NpgsqlParameter> npgsqlParameters) {
{
StringBuilder result = new(); StringBuilder result = new();
using NpgsqlConnection npgsqlConnection = new(connectionString); using NpgsqlConnection npgsqlConnection = new(connectionString);
npgsqlConnection.Open(); npgsqlConnection.Open();
using NpgsqlCommand npgsqlCommand = new(commandText, npgsqlConnection); using NpgsqlCommand npgsqlCommand = new(commandText, npgsqlConnection);
npgsqlCommand.Parameters.AddRange(npgsqlParameters.ToArray()); npgsqlCommand.Parameters.AddRange(npgsqlParameters.ToArray());
NpgsqlDataReader npgsqlDataReader = npgsqlCommand.ExecuteReader(CommandBehavior.SequentialAccess); NpgsqlDataReader npgsqlDataReader = npgsqlCommand.ExecuteReader(CommandBehavior.SequentialAccess);
while (npgsqlDataReader.Read()) while (npgsqlDataReader.Read()) {
_ = result.Append(npgsqlDataReader.GetString(0)); _ = result.Append(npgsqlDataReader.GetString(0));
}
return result; return result;
} }
public string? GetColumns() public string? GetColumns() {
{
string result; string result;
NpgsqlParameter[] npgsqlParameters = []; NpgsqlParameter[] npgsqlParameters = [];
string commandText = CommandText.GetColumns(); string commandText = CommandText.GetColumns();
StringBuilder stringBuilder = GetForJsonPath(_AppSettings.ConnectionString, commandText, npgsqlParameters.AsReadOnly()); StringBuilder stringBuilder = GetForJsonPath(_Settings.ConnectionString, commandText, npgsqlParameters.AsReadOnly());
result = stringBuilder.ToString(); result = stringBuilder.ToString();
if (result.Length == 1) if (result.Length == 1) {
File.WriteAllText(".vscode/jsonl/.jsonl", result); File.WriteAllText(".vscode/jsonl/.jsonl", result);
}
return result; return result;
} }
public string? GetOwnerIds() public string? GetOwnerIds() {
{
string result; string result;
NpgsqlParameter[] npgsqlParameters = []; NpgsqlParameter[] npgsqlParameters = [];
string commandText = CommandText.GetOwnerIdActiveImage(); string commandText = CommandText.GetOwnerIdActiveImage(_Settings.LowestVersionHistory);
StringBuilder stringBuilder = GetForJsonPath(_AppSettings.ConnectionString, commandText, npgsqlParameters.AsReadOnly()); StringBuilder stringBuilder = GetForJsonPath(_Settings.ConnectionString, commandText, npgsqlParameters.AsReadOnly());
result = stringBuilder.ToString(); result = stringBuilder.ToString();
if (result.Length == 1) if (result.Length == 1) {
File.WriteAllText(".vscode/jsonl/.jsonl", result); File.WriteAllText(".vscode/jsonl/.jsonl", result);
}
return result; return result;
} }
public string? GetAssets(Guid ownerId) public string? GetAssets(Guid ownerId) {
{
string result; string result;
NpgsqlParameter[] npgsqlParameters = [new NpgsqlParameter(nameof(ownerId), ownerId)]; NpgsqlParameter[] npgsqlParameters = [new NpgsqlParameter(nameof(ownerId), ownerId)];
string commandText = CommandText.GetAssetActiveImagePreviewNotDuplicate(_AppSettings.FilterTags); string commandText = CommandText.GetAssetActiveImagePreviewNotDuplicate(_Settings.LowestVersionHistory, _Settings.FilterTags);
StringBuilder stringBuilder = GetForJsonPath(_AppSettings.ConnectionString, commandText, npgsqlParameters.AsReadOnly()); StringBuilder stringBuilder = GetForJsonPath(_Settings.ConnectionString, commandText, npgsqlParameters.AsReadOnly());
result = stringBuilder.ToString(); result = stringBuilder.ToString();
if (result.Length == 1) if (result.Length == 1) {
File.WriteAllText(".vscode/jsonl/assets.jsonl", result); File.WriteAllText(".vscode/jsonl/assets.jsonl", result);
}
return result; return result;
} }
public ReadOnlyCollection<string>? GetRandomPaths(Guid ownerId) public ReadOnlyCollection<string>? GetRandomPaths(Guid ownerId) {
{
string[]? results; string[]? results;
NpgsqlParameter[] npgsqlParameters = [new NpgsqlParameter(nameof(ownerId), ownerId)]; NpgsqlParameter[] npgsqlParameters = [new NpgsqlParameter(nameof(ownerId), ownerId)];
string commandText = CommandText.GetAssetActiveImagePreviewNotDuplicate(_AppSettings.FilterTags); string commandText = CommandText.GetAssetActiveImagePreviewNotDuplicate(_Settings.LowestVersionHistory, _Settings.FilterTags);
StringBuilder stringBuilder = GetForJsonPath(_AppSettings.ConnectionString, commandText, npgsqlParameters.AsReadOnly()); StringBuilder stringBuilder = GetForJsonPath(_Settings.ConnectionString, commandText, npgsqlParameters.AsReadOnly());
string json = stringBuilder.ToString(); string json = stringBuilder.ToString();
Random random = new(); Random random = new();
string ownerIdValue = ownerId.ToString(); string ownerIdValue = ownerId.ToString();
@ -95,49 +92,44 @@ public class AssetService(ILogger<Program> logger, AppSettings appSettings)
return results?.AsReadOnly(); return results?.AsReadOnly();
} }
public Tag[]? GetArchivedTag(AppSettings appSettings, Guid ownerId) public Tag[]? GetArchivedTag(Settings settings, Guid ownerId) {
{ Tag[]? results;
Tag[] results;
Guid userId = ownerId; Guid userId = ownerId;
string value = appSettings.ArchivedTag; string value = settings.ArchivedTag;
NpgsqlParameter[] npgsqlParameters = NpgsqlParameter[] npgsqlParameters = [
[
new NpgsqlParameter(nameof(value), value), new NpgsqlParameter(nameof(value), value),
new NpgsqlParameter(nameof(userId), userId), new NpgsqlParameter(nameof(userId), userId),
]; ];
string commandText = CommandText.GetArchivedTag(); string commandText = CommandText.GetArchivedTag(_Settings.LowestVersionHistory);
StringBuilder stringBuilder = GetForJsonPath(appSettings.ConnectionString, commandText, npgsqlParameters.AsReadOnly()); StringBuilder stringBuilder = GetForJsonPath(settings.ConnectionString, commandText, npgsqlParameters.AsReadOnly());
string json = stringBuilder.ToString(); string json = stringBuilder.ToString();
results = JsonSerializer.Deserialize(json, TagCollectionSourceGenerationContext.Default.TagArray); results = JsonSerializer.Deserialize(json, TagCollectionSourceGenerationContext.Default.TagArray);
return results; return results;
} }
public string? GetArchivedTag(Guid ownerId) public string? GetArchivedTag(Guid ownerId) {
{ string? result;
string result; Tag[]? tags = GetArchivedTag(_Settings, ownerId);
Tag[]? tags = GetArchivedTag(_AppSettings, ownerId);
result = tags is null || tags.Length != 1 ? null : tags[0].Id; result = tags is null || tags.Length != 1 ? null : tags[0].Id;
return result; return result;
} }
public string? SaveRandomPaths(Guid ownerId) public string? SaveRandomPaths(Guid ownerId) {
{
string? results; string? results;
DateTime dateTime = DateTime.Now; DateTime dateTime = DateTime.Now;
string tomorrow = dateTime.AddDays(1).ToString("MM-dd"); string tomorrow = dateTime.AddDays(1).ToString("MM-dd");
if (Directory.Exists(_AppSettings.RandomResultsDirectory)) if (Directory.Exists(_Settings.RandomResultsDirectory)) {
_ = Directory.CreateDirectory(_AppSettings.RandomResultsDirectory); _ = Directory.CreateDirectory(_Settings.RandomResultsDirectory);
FileInfo fileInfo = new(Path.Combine(_AppSettings.RandomResultsDirectory, $"{tomorrow}.json")); }
if (fileInfo.Exists && fileInfo.CreationTime > dateTime.AddDays(_AppSettings.AddDays)) FileInfo fileInfo = new(Path.Combine(_Settings.RandomResultsDirectory, $"{tomorrow}.json"));
if (fileInfo.Exists && fileInfo.CreationTime > dateTime.AddDays(_Settings.AddDays)) {
results = null; results = null;
else } else {
{
_Logger.LogDebug("Writing <{FullName}>", fileInfo.FullName); _Logger.LogDebug("Writing <{FullName}>", fileInfo.FullName);
ReadOnlyCollection<string>? paths = GetRandomPaths(ownerId); ReadOnlyCollection<string>? paths = GetRandomPaths(ownerId);
if (paths is null) if (paths is null) {
results = null; results = null;
else } else {
{
_Logger.LogInformation("{count} path(s)", paths.Count.ToString()); _Logger.LogInformation("{count} path(s)", paths.Count.ToString());
results = JsonSerializer.Serialize(paths); results = JsonSerializer.Serialize(paths);
File.WriteAllText(fileInfo.FullName, results); File.WriteAllText(fileInfo.FullName, results);
@ -148,32 +140,32 @@ public class AssetService(ILogger<Program> logger, AppSettings appSettings)
private record Record(string Source, string Destination); private record Record(string Source, string Destination);
public ReadOnlyCollection<string> SyncImmich(Guid ownerId) public ReadOnlyCollection<string> SyncImmich(Guid ownerId) {
{
List<string> results = []; List<string> results = [];
Record record; Record record;
List<Record> records = []; List<Record> records = [];
if (Directory.Exists(_AppSettings.SyncDirectory)) if (Directory.Exists(_Settings.SyncDirectory)) {
_ = Directory.CreateDirectory(_AppSettings.SyncDirectory); _ = Directory.CreateDirectory(_Settings.SyncDirectory);
int syncLength = _AppSettings.SyncDirectory.Length; }
string[] syncFiles = Directory.GetFiles(_AppSettings.SyncDirectory, "*", SearchOption.AllDirectories); int syncLength = _Settings.SyncDirectory.Length;
string[] syncFiles = Directory.GetFiles(_Settings.SyncDirectory, "*", SearchOption.AllDirectories);
string[] syncCheck = syncFiles.Select(l => l[syncLength..]).ToArray(); string[] syncCheck = syncFiles.Select(l => l[syncLength..]).ToArray();
if (Directory.Exists(_AppSettings.ImmichUploadDirectory)) if (Directory.Exists(_Settings.ImmichUploadDirectory)) {
_ = Directory.CreateDirectory(_AppSettings.ImmichUploadDirectory); _ = Directory.CreateDirectory(_Settings.ImmichUploadDirectory);
int immichUploadLength = _AppSettings.ImmichUploadDirectory.Length; }
string[] immichUploadFiles = Directory.GetFiles(_AppSettings.ImmichUploadDirectory, "*", SearchOption.AllDirectories); int immichUploadLength = _Settings.ImmichUploadDirectory.Length;
string[] immichUploadFiles = Directory.GetFiles(_Settings.ImmichUploadDirectory, "*", SearchOption.AllDirectories);
string[] immichUploadCheck = immichUploadFiles.Select(l => l[immichUploadLength..]).ToArray(); string[] immichUploadCheck = immichUploadFiles.Select(l => l[immichUploadLength..]).ToArray();
for (int i = 0; i < immichUploadFiles.Length; i++) for (int i = 0; i < immichUploadFiles.Length; i++) {
{ if (syncCheck.Contains(immichUploadCheck[i])) {
if (syncCheck.Contains(immichUploadCheck[i]))
continue; continue;
}
results.Add(immichUploadCheck[i]); results.Add(immichUploadCheck[i]);
record = new(immichUploadFiles[i], string.Concat(_AppSettings.SyncDirectory, immichUploadCheck[i])); record = new(immichUploadFiles[i], string.Concat(_Settings.SyncDirectory, immichUploadCheck[i]));
records.Add(record); records.Add(record);
} }
_Logger.LogInformation("{count} file(s)", results.Count.ToString()); _Logger.LogInformation("{count} file(s)", results.Count.ToString());
for (int i = 0; i < records.Count; i++) for (int i = 0; i < records.Count; i++) {
{
record = records[i]; record = records[i];
_Logger.LogDebug("Copying <{source}>", record.Source); _Logger.LogDebug("Copying <{source}>", record.Source);
File.Copy(record.Source, record.Destination); File.Copy(record.Source, record.Destination);
@ -181,51 +173,73 @@ public class AssetService(ILogger<Program> logger, AppSettings appSettings)
return results.AsReadOnly(); return results.AsReadOnly();
} }
public ReadOnlyCollection<int> SetArchiveImmich(Guid ownerId) public ReadOnlyCollection<int>? SetArchiveImmich(Guid ownerId) {
{
ReadOnlyCollection<int>? results; ReadOnlyCollection<int>? results;
string checkDirectory = Path.Combine(_AppSettings.CurrentResultsDirectory, "B)Metadata", _AppSettings.CurrentCommit, "[]"); if (!File.Exists(_Settings.NotNinePath)) {
if (!Directory.Exists(checkDirectory))
results = null; results = null;
else } else {
{ string json = File.ReadAllText(_Settings.NotNinePath);
string checkFile = Path.Combine(checkDirectory, "!9.json"); Identifier[]? identifiers = JsonSerializer.Deserialize<Identifier[]>(json);
if (!File.Exists(checkFile)) if (identifiers is null || identifiers.Length == 0) {
results = null; results = null;
else } else {
{ Tag[]? tags = GetArchivedTag(_Settings, ownerId);
string json = File.ReadAllText(checkFile); if (tags is null || tags.Length != 1) {
Identifier[]? identifiers = JsonSerializer.Deserialize<Identifier[]>(json);
if (identifiers is null || identifiers.Length == 0)
results = null; results = null;
else } else {
{ results = SetArchiveImmich(logger, _Settings, ownerId, identifiers.AsReadOnly(), tags.AsReadOnly());
Tag[]? tags = GetArchivedTag(_AppSettings, ownerId);
if (tags is null || tags.Length != 1)
results = null;
else
results = SetArchiveImmich(logger, appSettings, ownerId, identifiers.AsReadOnly(), tags.AsReadOnly());
} }
} }
} }
return results?.AsReadOnly(); return results?.AsReadOnly();
} }
private static ReadOnlyCollection<int> SetArchiveImmich(ILogger<Program> logger, AppSettings appSettings, Guid ownerId, ReadOnlyCollection<Identifier> identifiers, ReadOnlyCollection<Tag> tags) private static ReadOnlyCollection<int>? SetArchiveImmich(ILogger<Program> logger, Settings settings, Guid ownerId, string tagsId, string deviceAssetIds) {
{
ReadOnlyCollection<int>? results; ReadOnlyCollection<int>? results;
string tagsId = tags[0].Id; NpgsqlParameter[] npgsqlParameters = [
NpgsqlParameter[] npgsqlParameters =
[
new NpgsqlParameter(nameof(tagsId), tagsId), new NpgsqlParameter(nameof(tagsId), tagsId),
new NpgsqlParameter(nameof(ownerId), ownerId), new NpgsqlParameter(nameof(ownerId), ownerId),
]; ];
string deviceAssetIds = Identifier.GetDeviceAssetIds(identifiers); string commandText = CommandText.SetAssetArchived(settings.LowestVersionHistory, deviceAssetIds);
string commandText = CommandText.SetAssetArchived(deviceAssetIds);
logger.LogDebug(commandText.Replace($"@{nameof(tagsId)}", $"'{tagsId}'").Replace($"@{nameof(ownerId)}", $"'{ownerId}'".ToString())); logger.LogDebug(commandText.Replace($"@{nameof(tagsId)}", $"'{tagsId}'").Replace($"@{nameof(ownerId)}", $"'{ownerId}'".ToString()));
int? result = ExecuteNonQuery(appSettings.ConnectionString, commandText, npgsqlParameters.AsReadOnly()); int? result = ExecuteNonQuery(settings.ConnectionString, commandText, npgsqlParameters.AsReadOnly());
results = result is null ? null : new([result.Value]); results = result is null ? null : new([result.Value]);
return results?.AsReadOnly(); return results?.AsReadOnly();
} }
private static ReadOnlyCollection<int>? SetArchiveImmich(ILogger<Program> logger, Settings settings, Guid ownerId, ReadOnlyCollection<Identifier> identifiers, ReadOnlyCollection<Tag> tags) {
ReadOnlyCollection<int>? results;
string tagsId = tags[0].Id;
string deviceAssetIds = Identifier.GetDeviceAssetIds(identifiers);
results = SetArchiveImmich(logger, settings, ownerId, tagsId, deviceAssetIds);
return results?.AsReadOnly();
}
public ReadOnlyCollection<int>? SetDigiKam4ArchiveImmich(Guid ownerId) {
ReadOnlyCollection<int>? results;
ReadOnlyCollection<ImageTag>? imageTags = ImageTag.Get(tag: _Settings.ArchivedTag,
tagsPath: _Settings.DigiKam4?.Tags,
imageTagsPath: _Settings.DigiKam4?.ImageTags,
imagesPath: _Settings.DigiKam4?.Images);
if (imageTags is null || imageTags.Count == 0) {
results = null;
} else {
Tag[]? tags = GetArchivedTag(_Settings, ownerId);
if (tags is null || tags.Length != 1) {
results = null;
} else {
results = SetArchiveImmich(logger, _Settings, ownerId, imageTags, tags.AsReadOnly());
}
}
return results?.AsReadOnly();
}
private static ReadOnlyCollection<int>? SetArchiveImmich(ILogger<Program> logger, Settings settings, Guid ownerId, ReadOnlyCollection<ImageTag> imageTags, ReadOnlyCollection<Tag> tags) {
ReadOnlyCollection<int>? results;
string tagsId = tags[0].Id;
string deviceAssetIds = Identifier.GetDeviceAssetIds(imageTags);
results = SetArchiveImmich(logger, settings, ownerId, tagsId, deviceAssetIds);
return results?.AsReadOnly();
}
} }

View File

@ -1,129 +1,176 @@
namespace ImmichToSlideshow.Services; namespace ImmichToSlideshow.Services;
internal static class CommandText internal static class CommandText {
{
internal static string GetColumns() internal static string GetColumns() { // cSpell:disable
{ // cSpell:disable List<string> results = [
List<string> results = new(); // " SELECT COALESCE(SUM(checksum_failures), 0) ",
// results.Add(" SELECT COALESCE(SUM(checksum_failures), 0) "); // " FROM pg_stat_database ",
// results.Add(" FROM pg_stat_database "); // " SELECT json_agg(t) ",
// results.Add(" SELECT json_agg(t) "); // " FROM information_schema.tables t ",
// results.Add(" FROM information_schema.tables t "); // " WHERE table_schema= 'public' ",
// results.Add(" WHERE table_schema= 'public' "); // " AND table_type= 'BASE TABLE' ",
// results.Add(" AND table_type= 'BASE TABLE' "); " SELECT json_agg(c) ",
results.Add(" SELECT json_agg(c) "); " FROM information_schema.columns c ",
results.Add(" FROM information_schema.columns c "); // " WHERE table_name = 'assets' ",
// results.Add(" WHERE table_name = 'assets' "); // " WHERE table_name = 'libraries' ",
// results.Add(" WHERE table_name = 'libraries' "); " WHERE table_name = 'asset_files'; "
results.Add(" WHERE table_name = 'asset_files' "); ];
return string.Join(Environment.NewLine, results); return string.Join(Environment.NewLine, results);
} // cSpell:enable } // cSpell:enable
internal static string GetOwnerIdActiveImage() internal static string GetOwnerIdActiveImage(float lowestVersionHistory) { // cSpell:disable
{ // cSpell:disable List<string> results = [
List<string> results = new(); " SELECT json_agg(j) ",
results.Add(" SELECT json_agg(j) "); " FROM ( ",
results.Add(" FROM ( "); " SELECT a.\"ownerId\" "
results.Add(" SELECT a.\"ownerId\" "); ];
results.Add(" FROM assets a "); if (lowestVersionHistory <= 1.129) {
results.Add(" WHERE a.\"status\" = 'active' "); results.Add(" FROM assets a ");
results.Add(" AND a.\"type\" = 'IMAGE' "); } else {
results.Add(" GROUP"); results.Add(" FROM public.asset a ");
results.Add(" BY a.\"ownerId\" "); }
results.Add(" ) j "); results.AddRange([
" WHERE a.\"status\" = 'active' ",
" AND a.\"type\" = 'IMAGE' ",
" GROUP",
" BY a.\"ownerId\" ",
" ) j; "
]);
return string.Join(Environment.NewLine, results); return string.Join(Environment.NewLine, results);
} // cSpell:enable } // cSpell:enable
internal static string GetAssetActiveImagePreviewNotDuplicate(string[] filterTags) internal static string GetAssetActiveImagePreviewNotDuplicate(float lowestVersionHistory, string[] filterTags) { // cSpell:disable
{ // cSpell:disable List<string> results = [
List<string> results = new(); " SELECT json_agg(j) ",
results.Add(" SELECT json_agg(j) "); " FROM ( ",
results.Add(" FROM ( "); " SELECT a.\"id\" ",
results.Add(" SELECT a.\"id\" "); " , a.\"deviceAssetId\" ",
results.Add(" , a.\"deviceAssetId\" "); // " , a.\"ownerId\" ",
// results.Add(" , a.\"ownerId\" "); // " , a.\"deviceId\" ",
// results.Add(" , a.\"deviceId\" "); // " , a.\"type\" ",
// results.Add(" , a.\"type\" "); " , a.\"originalPath\" ",
results.Add(" , a.\"originalPath\" "); // " , a.\"fileCreatedAt\" ",
// results.Add(" , a.\"fileCreatedAt\" "); // " , a.\"fileModifiedAt\" ",
// results.Add(" , a.\"fileModifiedAt\" "); // " , a.\"isFavorite\" ",
// results.Add(" , a.\"isFavorite\" "); // " , a.\"duration\" ",
// results.Add(" , a.\"duration\" "); // " , a.\"encodedVideoPath\" ",
// results.Add(" , a.\"encodedVideoPath\" "); // " , a.\"checksum\" ",
// results.Add(" , a.\"checksum\" "); // " , a.\"isVisible\" ",
// results.Add(" , a.\"isVisible\" "); // " , a.\"livePhotoVideoId\" ",
// results.Add(" , a.\"livePhotoVideoId\" "); // " , a.\"updatedAt\" ",
// results.Add(" , a.\"updatedAt\" "); // " , a.\"createdAt\" ",
// results.Add(" , a.\"createdAt\" "); // " , a.\"isArchived\" ",
// results.Add(" , a.\"isArchived\" "); " , a.\"originalFileName\" ",
results.Add(" , a.\"originalFileName\" "); // " , a.\"sidecarPath\" ",
// results.Add(" , a.\"sidecarPath\" "); // " , a.\"thumbhash\" ",
// results.Add(" , a.\"thumbhash\" "); // " , a.\"isOffline\" ",
// results.Add(" , a.\"isOffline\" "); // " , a.\"libraryId\" ",
// results.Add(" , a.\"libraryId\" "); // " , a.\"isExternal\" ",
// results.Add(" , a.\"isExternal\" "); // " , a.\"deletedAt\" ",
// results.Add(" , a.\"deletedAt\" "); // " , a.\"localDateTime\" ",
// results.Add(" , a.\"localDateTime\" "); // " , a.\"stackId\" ",
// results.Add(" , a.\"stackId\" "); " , a.\"duplicateId\" ",
results.Add(" , a.\"duplicateId\" "); // " , a.\"status\" ",
// results.Add(" , a.\"status\" "); " , f.\"path\" "
results.Add(" , f.\"path\" "); ];
results.Add(" FROM assets a "); if (lowestVersionHistory <= 1.129) {
results.Add(" INNER "); results.Add(" FROM assets a ");
results.Add(" JOIN asset_files f "); } else {
results.Add(" ON a.\"id\" = f.\"assetId\" "); results.Add(" FROM public.asset a ");
results.Add(" WHERE a.\"status\" = 'active' "); }
results.Add(" AND a.\"type\" = 'IMAGE' "); results.AddRange(" INNER ");
results.Add(" AND f.\"type\" = 'preview' "); if (lowestVersionHistory <= 1.129) {
results.Add(" AND a.\"duplicateId\" is null "); results.Add(" JOIN asset_files f ");
results.Add(" AND a.\"id\" not in ( "); } else {
results.Add(" SELECT \"assetsId\" "); results.Add(" JOIN public.asset_file f ");
results.Add(" FROM tag_asset g "); }
results.Add(" JOIN tags t "); results.AddRange([
results.Add(" ON g.\"tagsId\" = t.\"id\" "); " ON a.\"id\" = f.\"assetId\" ",
results.Add($" WHERE t.\"value\" in ('{string.Join("','", filterTags)}') "); " WHERE a.\"status\" = 'active' ",
results.Add(" ) "); " AND a.\"type\" = 'IMAGE' ",
results.Add(" AND a.\"isExternal\" = true "); " AND f.\"type\" = 'preview' ",
results.Add(" AND a.\"isOffline\" = false "); " AND a.\"duplicateId\" is null ",
results.Add(" AND a.\"ownerId\" = @ownerId "); " AND a.\"id\" not in ( ",
results.Add(" ) j "); " SELECT \"assetsId\" "
]);
if (lowestVersionHistory <= 1.129) {
results.Add(" FROM tag_asset g ");
} else {
results.Add(" FROM public.tag_asset g ");
}
if (lowestVersionHistory <= 1.129) {
results.Add(" JOIN tags t ");
} else {
results.Add(" JOIN public.tag t ");
}
results.AddRange([
" ON g.\"tagsId\" = t.\"id\" ",
$" WHERE t.\"value\" in ('{string.Join("','", filterTags)}') ",
" ) ",
" AND a.\"isExternal\" = true ",
" AND a.\"isOffline\" = false ",
" AND a.\"ownerId\" = @ownerId ",
" ) j; "
]);
return string.Join(Environment.NewLine, results); return string.Join(Environment.NewLine, results);
} // cSpell:enable } // cSpell:enable
internal static string SetAssetArchived(string deviceAssetIds) internal static string SetAssetArchived(float lowestVersionHistory, string deviceAssetIds) { // cSpell:disable
{ // cSpell:disable List<string> results = [
List<string> results = new(); " INSERT INTO tag_asset ",
results.Add(" INSERT INTO tag_asset "); " (\"assetsId\", \"tagsId\") ",
results.Add(" (\"assetsId\", \"tagsId\") "); " SELECT a.\"id\", @tagsId::uuid "
results.Add(" SELECT a.\"id\", @tagsId::uuid "); ];
results.Add(" FROM assets a "); if (lowestVersionHistory <= 1.129) {
results.Add(" WHERE a.\"type\" = 'IMAGE' "); results.Add(" FROM assets a ");
results.Add(" AND a.\"ownerId\" = @ownerId "); } else {
results.Add(" AND a.\"deviceAssetId\" in ( "); results.Add(" FROM public.asset a ");
results.Add(deviceAssetIds); }
results.Add(" ) "); results.AddRange([
results.Add(" AND a.\"id\" not in ( "); " WHERE a.\"type\" = 'IMAGE' ",
results.Add(" SELECT \"id\" "); " AND a.\"ownerId\" = @ownerId ",
results.Add(" FROM assets b "); " AND a.\"deviceAssetId\" in ( ",
deviceAssetIds,
" ) ",
" AND a.\"id\" not in ( ",
" SELECT \"id\" "
]);
if (lowestVersionHistory <= 1.129) {
results.Add(" FROM assets b ");
} else {
results.Add(" FROM public.asset b ");
}
results.Add(" INNER "); results.Add(" INNER ");
results.Add(" JOIN tag_asset t "); if (lowestVersionHistory <= 1.129) {
results.Add(" ON b.\"id\" = t.\"assetsId\" "); results.Add(" JOIN tag_asset t ");
results.Add(" WHERE t.\"tagsId\" = @tagsId::uuid "); } else {
results.Add(" AND b.\"deviceAssetId\" in ( "); results.Add(" JOIN public.tag_asset t ");
results.Add(deviceAssetIds); }
results.Add(" ) "); results.AddRange([
results.Add(" ) "); " ON b.\"id\" = t.\"assetsId\" ",
" WHERE t.\"tagsId\" = @tagsId::uuid ",
" AND b.\"deviceAssetId\" in ( ",
deviceAssetIds,
" ) ",
" ); "
]);
return string.Join(Environment.NewLine, results); return string.Join(Environment.NewLine, results);
} // cSpell:enable } // cSpell:enable
internal static string GetArchivedTag() internal static string GetArchivedTag(float lowestVersionHistory) { // cSpell:disable
{ // cSpell:disable List<string> results = [
List<string> results = new(); " SELECT json_agg(t) "
results.Add(" SELECT json_agg(t) "); ];
results.Add(" FROM tags t "); if (lowestVersionHistory <= 1.129) {
results.Add($" WHERE t.\"value\" = @value "); results.Add(" FROM tags t ");
results.Add(" AND t.\"userId\" = @userId "); } else {
results.Add(" FROM public.tag t ");
}
results.AddRange([
" WHERE t.\"value\" = @value ",
" AND t.\"userId\" = @userId; "
]);
return string.Join(Environment.NewLine, results); return string.Join(Environment.NewLine, results);
} // cSpell:enable } // cSpell:enable