Skip to content

Commit

Permalink
#1-4 生成タスク周りをリファクタリング
Browse files Browse the repository at this point in the history
  • Loading branch information
miyaji255 committed Apr 4, 2024
1 parent 2dd3ea7 commit 2f3069a
Show file tree
Hide file tree
Showing 8 changed files with 79 additions and 63 deletions.
35 changes: 17 additions & 18 deletions Epub/KoeBook.Epub/Services/AnalyzerService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ public partial class AnalyzerService(IScraperSelectorService scrapingService, IE
private readonly ILlmAnalyzerService _llmAnalyzerService = llmAnalyzerService;
private Dictionary<string, string> _rubyReplacements = new Dictionary<string, string>();

public async ValueTask<BookScripts> AnalyzeAsync(BookProperties bookProperties, string tempDirectory, string coverFilePath, CancellationToken cancellationToken)
{
coverFilePath = Path.Combine(tempDirectory, "Cover.png");
public async ValueTask<BookScripts> AnalyzeAsync(BookProperties bookProperties, string tempDirectory, CancellationToken cancellationToken)
{
Directory.CreateDirectory(tempDirectory);
var coverFilePath = Path.Combine(tempDirectory, "Cover.png");
using var fs = File.Create(coverFilePath);
await fs.WriteAsync(CoverFile.ToArray(), cancellationToken);
await fs.FlushAsync(cancellationToken);
Expand All @@ -27,9 +28,13 @@ public async ValueTask<BookScripts> AnalyzeAsync(BookProperties bookProperties,
{
document = await _scrapingService.ScrapingAsync(bookProperties.Source, coverFilePath, tempDirectory, bookProperties.Id, cancellationToken);
}
catch (EbookException)
{
throw;
}
catch (Exception ex)
{
EbookException.Throw(ExceptionType.WebScrapingFailed, "", ex);
EbookException.Throw(ExceptionType.WebScrapingFailed, innerException: ex);
return default;
}
_epubDocumentStoreService.Register(document, cancellationToken);
Expand All @@ -45,7 +50,7 @@ public async ValueTask<BookScripts> AnalyzeAsync(BookProperties bookProperties,
{
var line = paragraph.Text;
// rubyタグがあればルビのdictionaryに登録
var rubyDict = ExtractRuby(line);
var rubyDict = ExtractRuby(line).ToDictionary();

Check warning on line 53 in Epub/KoeBook.Epub/Services/AnalyzerService.cs

View workflow job for this annotation

GitHub Actions / test

Possible null reference argument for parameter 'text' in 'IEnumerable<KeyValuePair<string, string>> AnalyzerService.ExtractRuby(string text)'.

foreach (var ruby in rubyDict)
{
Expand Down Expand Up @@ -85,20 +90,11 @@ public async ValueTask<BookScripts> AnalyzeAsync(BookProperties bookProperties,
return bookScripts;
}

private static Dictionary<string, string> ExtractRuby(string text)
private static IEnumerable<KeyValuePair<string, string>> ExtractRuby(string text)
{
var rubyDict = new Dictionary<string, string>();
var rubyRegex = new Regex("<ruby><rb>(.*?)</rb><rp>(</rp><rt>(.*?)</rt><rp>)</rp></ruby>");

foreach (Match match in rubyRegex.Matches(text))
{
if (!rubyDict.ContainsKey(match.Groups[1].Value))
{
rubyDict.Add(match.Groups[1].Value, match.Groups[2].Value);
}
}

return rubyDict;
return RubyRegex()
.Matches(text)
.Select(m => KeyValuePair.Create(m.Groups[1].Value, m.Groups[2].Value));
}

private static string ReplaceBaseTextWithRuby(string text, Dictionary<string, string> rubyDict)
Expand All @@ -113,4 +109,7 @@ private static string ReplaceBaseTextWithRuby(string text, Dictionary<string, st

return resultText;
}

[GeneratedRegex("<ruby><rb>(.*?)</rb><rp>(</rp><rt>(.*?)</rt><rp>)</rp></ruby>")]
private static partial Regex RubyRegex();
}
4 changes: 1 addition & 3 deletions Epub/KoeBook.Epub/Services/EpubGenerateService.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using KoeBook.Core;
using KoeBook.Core.Contracts.Services;
using KoeBook.Core.Models;
using KoeBook.Epub;
using KoeBook.Epub.Contracts.Services;
using KoeBook.Epub.Models;

Expand All @@ -17,8 +16,7 @@ public async ValueTask<string> GenerateEpubAsync(BookScripts bookScripts, string
{
cancellationToken.ThrowIfCancellationRequested();

var document = _documentStoreService.Documents.Where(doc => doc.Id == bookScripts.BookProperties.Id).FirstOrDefault()
?? throw new InvalidOperationException($"The epub document ({bookScripts.BookProperties.Id}) can't be found.");
var document = _documentStoreService.Documents.Single(d => d.Id == bookScripts.BookProperties.Id);

foreach (var scriptLine in bookScripts.ScriptLines)
{
Expand Down
2 changes: 1 addition & 1 deletion KoeBook.Core/Contracts/Services/IAnalyzerService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ public interface IAnalyzerService
/// 本の情報の取得・解析を行います
/// </summary>
/// <returns>編集前の読み上げテキスト</returns>
ValueTask<BookScripts> AnalyzeAsync(BookProperties bookProperties, string tempDirectory, string coverFilePath, CancellationToken cancellationToken);
ValueTask<BookScripts> AnalyzeAsync(BookProperties bookProperties, string tempDirectory, CancellationToken cancellationToken);
}
2 changes: 2 additions & 0 deletions KoeBook.Core/Contracts/Services/IDisplayStateChangeService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ public interface IDisplayStateChangeService
/// </summary>
void UpdateState(BookProperties bookProperties, GenerationState state);

void UpdateTitle(BookProperties bookProperties, string title);

/// <summary>
/// プログレスバーを更新します
/// </summary>
Expand Down
16 changes: 15 additions & 1 deletion KoeBook.Core/Helpers/IDisplayStateChangeEx.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,23 @@ public class DisplayStateChanging(IDisplayStateChangeService displayStateChangeS

private readonly int _maximum = maximum;

private int _progress;

public void UpdateProgress(int progress)
{
_displayStateChangeService.UpdateProgress(_bookProperties, progress, _maximum);
_displayStateChangeService.UpdateProgress(_bookProperties, _progress = progress, _maximum);
}

public void IncrementProgress()
{
_progress++;
_displayStateChangeService.UpdateProgress(_bookProperties, _progress, _maximum);
}

public void Finish()
{
_progress = _maximum;
_displayStateChangeService.UpdateProgress(_bookProperties, _progress, _maximum);
}
}
}
4 changes: 1 addition & 3 deletions KoeBook/Services/CoreMocks/AnalyzerServiceMock.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using KoeBook.Core.Contracts.Services;
using KoeBook.Core.Helpers;
using KoeBook.Core.Models;
using KoeBook.Epub;
using KoeBook.Epub.Models;
using static KoeBook.Core.Helpers.IDisplayStateChangeEx;

namespace KoeBook.Services.CoreMocks;
Expand All @@ -11,7 +9,7 @@ public class AnalyzerServiceMock(IDisplayStateChangeService stateService) : IAna
{
private readonly IDisplayStateChangeService _stateService = stateService;

public async ValueTask<BookScripts> AnalyzeAsync(BookProperties bookProperties, string tempDirectory, string coverFilePath, CancellationToken cancellationToken)
public async ValueTask<BookScripts> AnalyzeAsync(BookProperties bookProperties, string tempDirectory, CancellationToken cancellationToken)
{
DisplayStateChanging stateChanging;
if (bookProperties.SourceType == SourceType.Url)
Expand Down
9 changes: 9 additions & 0 deletions KoeBook/Services/DisplayStateChangeService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,13 @@ public void UpdateState(BookProperties bookProperties, GenerationState state)
taskService.GetProcessingTask(bookProperties.Id).State = state;
});
}

public void UpdateTitle(BookProperties bookProperties, string title)
{
var taskService = _taskService; // thisをキャプチャしないようにする
_ = App.MainWindow.DispatcherQueue.TryEnqueue(() =>
{
taskService.GetProcessingTask(bookProperties.Id).Title = title;
});
}
}
70 changes: 33 additions & 37 deletions KoeBook/Services/GenerationTaskRunnerService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,50 +48,45 @@ private async void TasksChanged(GenerationTask task, ChangedEvents changedEvents

private async ValueTask RunAsync(GenerationTask task)
{
try
{
var scripts = await _analyzerService.AnalyzeAsync(new(task.Id, task.Source, task.SourceType), _tempFolder, "", task.CancellationToken);
task.BookScripts = scripts;
task.State = GenerationState.Editting;
task.Progress = 0;
task.MaximumProgress = 0;
if (task.SkipEdit)
{
var resultPath = await _epubGenService.GenerateEpubAsync(scripts, _tempFolder, task.CancellationToken);
task.State = GenerationState.Completed;
task.Progress = 1;
task.MaximumProgress = 1;
var fileName = Path.GetFileName(resultPath);
File.Copy(resultPath, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "KoeBook", fileName), true);
}
}
catch (OperationCanceledException)
{
task.State = GenerationState.Failed;
}
catch (EbookException e)
{
task.State = GenerationState.Failed;
await _dialogService.ShowInfoAsync("生成失敗", e.ExceptionType.GetEnumMemberValue()!, "OK", default);
}
catch
{
task.State = GenerationState.Failed;
}
if (task.CancellationToken.IsCancellationRequested || task.State == GenerationState.Failed)
return;

await RunAsyncCore(task, true);
await RunAsyncCore(task, false);
}

public async void RunGenerateEpubAsync(GenerationTask task)
{
if (task.CancellationToken.IsCancellationRequested || task.State == GenerationState.Failed || task.BookScripts is null)
return;

await RunAsyncCore(task, false);
}

private async ValueTask RunAsyncCore(GenerationTask task, bool firstStep)
{
var tempDirectory = Path.Combine(_tempFolder, task.Id.ToString());
try
{
var resultPath = await _epubGenService.GenerateEpubAsync(task.BookScripts, _tempFolder, task.CancellationToken);
task.State = GenerationState.Completed;
task.Progress = 1;
task.MaximumProgress = 1;
var fileName = Path.GetFileName(resultPath);
File.Copy(resultPath, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "KoeBook", fileName), true);
if (firstStep)
{
var scripts = await _analyzerService.AnalyzeAsync(new(task.Id, task.Source, task.SourceType), tempDirectory, task.CancellationToken);
task.BookScripts = scripts;
task.State = GenerationState.Editting;
task.Progress = 0;
task.MaximumProgress = 0;
}
else if (task.BookScripts is not null)
{
var resultPath = await _epubGenService.GenerateEpubAsync(task.BookScripts, tempDirectory, task.CancellationToken);
task.State = GenerationState.Completed;
task.Progress = 1;
task.MaximumProgress = 1;
var fileName = Path.GetFileName(resultPath);
File.Move(resultPath, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "KoeBook", fileName), true);
}
else
throw new InvalidOperationException();
}
catch (OperationCanceledException)
{
Expand All @@ -102,9 +97,10 @@ public async void RunGenerateEpubAsync(GenerationTask task)
task.State = GenerationState.Failed;
await _dialogService.ShowInfoAsync("生成失敗", e.ExceptionType.GetEnumMemberValue()!, "OK", default);
}
catch
catch (Exception e)
{
task.State = GenerationState.Failed;
await _dialogService.ShowInfoAsync("生成失敗", $"不明なエラーが発生しました。\n{e.Message}", "OK", default);
}
}

Expand Down

0 comments on commit 2f3069a

Please sign in to comment.