Skip to content

Commit

Permalink
Add in-memory settings to enable/disable imouto pics upload
Browse files Browse the repository at this point in the history
  • Loading branch information
ImoutoChan committed Mar 31, 2024
1 parent 689a3fb commit 202b4cf
Show file tree
Hide file tree
Showing 20 changed files with 683 additions and 22 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,15 @@

### Navigator
* Fix webp previews in the list view
* Add button to enable/disable imouto pics upload in Room

### Viewer
* Add jfif to the list of supported image formats

### Room
* Add in-memory settings to enable/disable imouto pics upload and api for it
* Add tests for the imouto pics upload settings

# 4.24.0

### Navigator
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace ImoutoRebirth.Navigator.Services.Collections;

public interface IImoutoPicsUploaderStateService
{
Task EnableAsync();

Task DisableAsync();

Task<bool> IsEnabledAsync();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using ImoutoRebirth.Room.WebApi.Client;

namespace ImoutoRebirth.Navigator.Services.Collections;

internal class ImoutoPicsUploaderStateService : IImoutoPicsUploaderStateService
{
private readonly ImoutoPicsUploaderEnabledClient _imoutoPicsUploaderEnabledClient;

public ImoutoPicsUploaderStateService(ImoutoPicsUploaderEnabledClient imoutoPicsUploaderEnabledClient)
=> _imoutoPicsUploaderEnabledClient = imoutoPicsUploaderEnabledClient;

public async Task EnableAsync()
=> await _imoutoPicsUploaderEnabledClient.EnableImoutoPicsUploaderAsync();

public async Task DisableAsync()
=> await _imoutoPicsUploaderEnabledClient.DisableImoutoPicsUploaderAsync();

public async Task<bool> IsEnabledAsync()
=> await _imoutoPicsUploaderEnabledClient.IsImoutoPicsUploaderEnabledAsync();
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ static ServiceLocator()
sc.AddTransient<ICollectionService, CollectionService>();
sc.AddTransient<IDestinationFolderService, DestinationFolderService>();
sc.AddTransient<ISourceFolderService, SourceFolderService>();

sc.AddTransient<IImoutoPicsUploaderStateService, ImoutoPicsUploaderStateService>();

sc.AddTransient<IFileService, FileService>();
sc.AddTransient<IFileTagService, FileTagService>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,15 @@
Header="Auto shuffle on every load"
IsOn="{Binding AutoShuffle}" />

<controls:ToggleSwitch Margin="0,25,0,0"
Header="Is ImoutoPics integration active"
IsOn="{Binding IsImoutoPicsUploaderEnabled}"
IsEnabled="False" />

<Button Content="Toggle ImoutoPics"
Command="{Binding ToggleImoutoPicsCommand}"
Margin="0,25,0,0" />

<TextBlock Margin="0,25,0,0"
Text="Path Overrides" />

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ private async Task InitializeAsync()
{
var topTagsUpdateTask = TagsEdit.UpdateUsersTopTags();
await CollectionManager.ReloadCollectionsAsync();
await Settings.InitializeAsync();
TagSearchVM.AddCollections(CollectionManager.Collections);
await topTagsUpdateTask;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
using ImoutoRebirth.Common;
using ImoutoRebirth.Common.WPF;
using ImoutoRebirth.Common.WPF.Commands;
using ImoutoRebirth.Navigator.Services;
using ImoutoRebirth.Navigator.Services.Collections;
using MahApps.Metro.Theming;

namespace ImoutoRebirth.Navigator.ViewModel;
Expand All @@ -15,7 +17,10 @@ internal class SettingsVM : VMBase
private AccentColorMenuData _selectedAccentColor;
private int _selectedTheme;
private ICommand? _saveCommand;
private ICommand? _toggleImoutoPicsCommand;
private string _pathOverrides;
private readonly IImoutoPicsUploaderStateService _imoutoPicsUploaderStateService;
private bool _isImoutoPicsUploaderEnabled;

public SettingsVM()
{
Expand All @@ -32,6 +37,8 @@ public SettingsVM()

ShowPreviewOnSelect = Settings.Default.ActivatePreviewOnSelect;
PathOverrides = Settings.Default.PathOverrides;

_imoutoPicsUploaderStateService = ServiceLocator.GetService<IImoutoPicsUploaderStateService>();
}

public bool ShowPreviewOnSelect
Expand Down Expand Up @@ -138,6 +145,12 @@ public string LilinHost
set => Settings.Default.LilinHost = value;
}

public bool IsImoutoPicsUploaderEnabled
{
get => _isImoutoPicsUploaderEnabled;
set => OnPropertyChanged(ref _isImoutoPicsUploaderEnabled, value, () => IsImoutoPicsUploaderEnabled);
}

public string RoomHost
{
get => Settings.Default.RoomHost;
Expand All @@ -146,6 +159,8 @@ public string RoomHost

public ICommand SaveCommand => _saveCommand ??= new RelayCommand(_ => Save());

public ICommand ToggleImoutoPicsCommand => _toggleImoutoPicsCommand ??= new AsyncCommand(() => ToggleImoutoPics());

private static void Save() => Settings.Default.Save();

public event EventHandler? ShowPreviewOnSelectChanged;
Expand All @@ -155,6 +170,25 @@ private void OnShowPreviewOnSelectChanged()
var handler = ShowPreviewOnSelectChanged;
handler?.Invoke(this, EventArgs.Empty);
}

public async Task InitializeAsync()
{
IsImoutoPicsUploaderEnabled = await _imoutoPicsUploaderStateService.IsEnabledAsync();
}

private async Task ToggleImoutoPics()
{
if (IsImoutoPicsUploaderEnabled)
{
await _imoutoPicsUploaderStateService.DisableAsync();
}
else
{
await _imoutoPicsUploaderStateService.EnableAsync();
}

IsImoutoPicsUploaderEnabled = await _imoutoPicsUploaderStateService.IsEnabledAsync();
}
}

public class AccentColorMenuData
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using ImoutoRebirth.Common.Cqrs.Abstract;
using ImoutoRebirth.Room.Application.Services;

namespace ImoutoRebirth.Room.Application.Cqrs.ImoutoPicsUploadStateSlice;

public record EnableImoutoPicsUploaderCommand : ICommand;

public record DisableImoutoPicsUploaderCommand : ICommand;

internal class EnableImoutoPicsUploaderCommandHandler
: ICommandHandler<EnableImoutoPicsUploaderCommand>
, ICommandHandler<DisableImoutoPicsUploaderCommand>
{
private readonly IImoutoPicsUploaderRepository _imoutoPicsUploaderRepository;

public EnableImoutoPicsUploaderCommandHandler(IImoutoPicsUploaderRepository imoutoPicsUploaderRepository)
=> _imoutoPicsUploaderRepository = imoutoPicsUploaderRepository;

public Task Handle(EnableImoutoPicsUploaderCommand _, CancellationToken ct)
{
var state = _imoutoPicsUploaderRepository.Get();
state.Enable();

return Task.CompletedTask;
}

public Task Handle(DisableImoutoPicsUploaderCommand _, CancellationToken ct)
{
var state = _imoutoPicsUploaderRepository.Get();
state.Disable();

return Task.CompletedTask;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using ImoutoRebirth.Common.Cqrs.Abstract;
using ImoutoRebirth.Room.Application.Services;

namespace ImoutoRebirth.Room.Application.Cqrs.ImoutoPicsUploadStateSlice;

public record IsImoutoPicsUploaderEnabledQuery : IQuery<bool>;

internal class IsImoutoPicsUploaderEnabledQueryHandler
: IQueryHandler<IsImoutoPicsUploaderEnabledQuery, bool>
{
private readonly IImoutoPicsUploaderRepository _imoutoPicsUploaderRepository;

public IsImoutoPicsUploaderEnabledQueryHandler(IImoutoPicsUploaderRepository imoutoPicsUploaderRepository)
=> _imoutoPicsUploaderRepository = imoutoPicsUploaderRepository;

public Task<bool> Handle(IsImoutoPicsUploaderEnabledQuery _, CancellationToken ct)
{
var state = _imoutoPicsUploaderRepository.Get();
return Task.FromResult(state.IsEnabled);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Runtime.CompilerServices;
using ImoutoRebirth.Common.Cqrs.Abstract;
using ImoutoRebirth.Common.Domain;
using ImoutoRebirth.Room.Application.Cqrs.ImoutoPicsUploadStateSlice;
using ImoutoRebirth.Room.Application.Services;
using ImoutoRebirth.Room.Domain;
using ImoutoRebirth.Room.Domain.CollectionAggregate;
Expand Down Expand Up @@ -73,7 +74,11 @@ private async Task SaveAndReport(Guid collectionId, SystemFileMoved moved)

await _remoteCommandService.SaveTags(newId, moved.SourceTags);
await _remoteCommandService.UpdateMetadataRequest(newId, moved.SystemFile.Md5);
await _imoutoPicsUploader.UploadFile(moved.MovedFileInfo.FullName);

var isUploadEnabled = await _mediator.Send(new IsImoutoPicsUploaderEnabledQuery());

if (isUploadEnabled)
await _imoutoPicsUploader.UploadFile(moved.MovedFileInfo.FullName);
}

private SystemFileMoved MoveFile(Collection collection, SystemFilePreparedToMove preparedToMove)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Reflection;
using ImoutoRebirth.Common.Cqrs;
using ImoutoRebirth.Room.Application.Cqrs;
using ImoutoRebirth.Room.Application.Services;
using Microsoft.Extensions.DependencyInjection;

namespace ImoutoRebirth.Room.Application;
Expand All @@ -18,6 +19,8 @@ public static IServiceCollection AddRoomApplication(
});
services.AddLoggingBehavior();
services.AddTransactionBehavior();

services.AddSingleton<IImoutoPicsUploaderRepository, ImoutoPicsUploaderRepository>();

return services;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using ImoutoRebirth.Room.Domain;

namespace ImoutoRebirth.Room.Application.Services;

public interface IImoutoPicsUploaderRepository
{
ImoutoPicsUploaderState Get();
}

/// <summary>
/// Should be registered as a singleton.
/// </summary>
public class ImoutoPicsUploaderRepository : IImoutoPicsUploaderRepository
{
private readonly ImoutoPicsUploaderState _state = new();

public ImoutoPicsUploaderState Get() => _state;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace ImoutoRebirth.Room.Domain;

public class ImoutoPicsUploaderState
{
public bool IsEnabled { get; private set; } = true;

public void Enable() => IsEnabled = true;

public void Disable() => IsEnabled = false;
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Xunit;

namespace ImoutoRebirth.Room.IntegrationTests;
Expand Down Expand Up @@ -807,6 +808,58 @@ public async Task MultipleFileIsMovedToDestinationWithSameName()
.Should().Be(Path.Combine(destFolderPath, "file1-5f30f9953332c230d11e3f26db5ae9a0.jpg"));
}

[Fact]
public async Task ImoutoPicsUploadCalledWhenImoutoPicsUploaderEnabled()
{
// arrange
var (_, sourceFolderPath, destFolderPath) = await CreateDefaultCollection(
sourceShouldCheckFormat: false,
sourceShouldCheckHashFromName: false ,
sourceShouldCreateTagsFromSubfolders: false,
sourceShouldAddTagFromFilename: false,
sourceSupportedExtensions: new []{ "jpg" },
destShouldCreateSubfoldersByHash: false,
destShouldRenameByHash: false);

var testFile = new FileInfo(Path.Combine(_webApp.TestsLocation, "Resources", "file1-5f30f9953332c230d11e3f26db5ae9a0.jpg"));

await _webApp.Client.PostAsync("/imouto-pics-uploader-enabled", null);

// act
testFile.CopyTo(Path.Combine(sourceFolderPath, testFile.Name));
await _mediator.Send(new OverseeCommand());

// assert
var file = Path.Combine(destFolderPath, "file1-5f30f9953332c230d11e3f26db5ae9a0.jpg");
_webApp.ImoutoPicsUploaderMock.Verify(x => x.UploadFile(file), Times.Once);
}

[Fact()]
public async Task ImoutoPicsUploadShouldNotBeCalledWhenImoutoPicsUploaderDisabled()
{
// arrange
var (_, sourceFolderPath, destFolderPath) = await CreateDefaultCollection(
sourceShouldCheckFormat: false,
sourceShouldCheckHashFromName: false ,
sourceShouldCreateTagsFromSubfolders: false,
sourceShouldAddTagFromFilename: false,
sourceSupportedExtensions: new []{ "jpg" },
destShouldCreateSubfoldersByHash: false,
destShouldRenameByHash: false);

var testFile = new FileInfo(Path.Combine(_webApp.TestsLocation, "Resources", "file1-5f30f9953332c230d11e3f26db5ae9a0.jpg"));

await _webApp.Client.DeleteAsync("/imouto-pics-uploader-enabled");

// act
testFile.CopyTo(Path.Combine(sourceFolderPath, testFile.Name));
await _mediator.Send(new OverseeCommand());

// assert
var file = Path.Combine(destFolderPath, "file1-5f30f9953332c230d11e3f26db5ae9a0.jpg");
_webApp.ImoutoPicsUploaderMock.Verify(x => x.UploadFile(file), Times.Never);
}

private async Task<CreatedCollection> CreateDefaultCollection(
bool sourceShouldCheckFormat = false,
bool sourceShouldCheckHashFromName = false,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
using System.Reflection;
using ImoutoRebirth.Common.MassTransit;
using ImoutoRebirth.Room.Application.Services;
using ImoutoRebirth.Room.Database;
using ImoutoRebirth.Room.Infrastructure;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Moq;
using Npgsql;
using Xunit;

Expand Down Expand Up @@ -33,6 +35,8 @@ public string TestsTempLocation
public string TestsLocation
=> new FileInfo(Assembly.GetExecutingAssembly().Location).Directory!.FullName;

public Mock<IImoutoPicsUploader> ImoutoPicsUploaderMock { get; } = new();

protected override IHost CreateHost(IHostBuilder builder)
{
builder.ConfigureServices(services =>
Expand All @@ -47,13 +51,17 @@ protected override IHost CreateHost(IHostBuilder builder)
.Union(services.Where(
d => d.ServiceType == typeof(IHostedService)
&& d.ImplementationType?.Name == "QuartzHostedService"))

// replace IImoutoPicsUploader with mock
.Union(services.Where(x => x.ServiceType == typeof(IImoutoPicsUploader)))
.ToList();

foreach (var descriptor in descriptors)
services.Remove(descriptor);

services.AddDbContext<RoomDbContext>(x => x.UseNpgsql(ConnectionString, y => y.UseNodaTime()));
services.AddMassTransitTestHarness(с => с.AddRoomMassTransitSetup());
services.AddTransient<IImoutoPicsUploader>(x => ImoutoPicsUploaderMock.Object);
});

var host = base.CreateHost(builder);
Expand Down
Loading

0 comments on commit 202b4cf

Please sign in to comment.