PlotDirector/PlotLine/Controllers/ManuscriptReaderController.cs

74 lines
3.9 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using PlotLine.Services;
using PlotLine.Services.Manuscript;
namespace PlotLine.Controllers;
[Authorize]
[Route("manuscript/reader")]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public sealed class ManuscriptReaderController(ManuscriptReaderService reader, ICurrentUserService currentUser,
ILogger<ManuscriptReaderController> logger) : Controller
{
[HttpGet]
public async Task<IActionResult> Index(int bookId, int? chapterId = null, bool focus = false)
{
Response.Headers["X-Robots-Tag"] = "noindex, nofollow, noarchive";
if (currentUser.UserId is not int user) return Challenge();
if (bookId <= 0 || chapterId is <= 0) return NotFound();
try
{
if (!await reader.CanRead(user, bookId, chapterId)) return NotFound();
return RedirectToAction("Review","Writer",new{bookId,chapterId,focus,reading=true});
}
catch (UnauthorizedAccessException) { return NotFound(); }
catch (SqlException e) when (e.Number == 51000) { return NotFound(); }
catch (Exception e) when (e is SqlException or TimeoutException or System.Text.Json.JsonException)
{
// Log neither SQL error text nor payloads: manuscripts are private content.
logger.LogWarning("Manuscript Reader unavailable ({FailureKind}).", e.GetType().Name);
Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
return View("Unavailable", new { BookId = bookId, ChapterId = chapterId });
}
}
[HttpGet("changes")]
public Task<IActionResult> Changes(int bookId, int chapterId, long knownRevision, string? knownVersion = null) => Poll(async user =>
{
if (bookId <= 0 || chapterId <= 0 || knownVersion is null || knownVersion.Length != 64) return NotFound();
var change = await reader.Check(user, bookId, chapterId, knownRevision, knownVersion);
return change is null ? NotFound() : Json(new { revision = change.Revision.ToString(System.Globalization.CultureInfo.InvariantCulture), changed = change.Changed, version = change.Version,lastSuccessfulSyncUtc=change.LastSuccessfulSyncUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ"),snapshotCapturedUtc=change.SnapshotCapturedUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ") });
});
[HttpGet("chapter")]
public Task<IActionResult> Chapter(int bookId, int chapterId) => Poll(async user =>
{
if (bookId <= 0 || chapterId <= 0) return NotFound();
var model = await reader.Read(user, bookId, chapterId);
return model is null ? NotFound() : Json(new
{
bookId, chapterId, revision = model.Revision.ToString(System.Globalization.CultureInfo.InvariantCulture),
version = model.ContentVersion, title = model.Chapter!.ChapterTitle,
paragraphs = model.Paragraphs.Select(p => new { id = p.Id, text = p.Text, isHeading = p.IsHeading, sceneId=p.SceneID }),
lastSuccessfulSyncUtc = model.LastSuccessfulSyncUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ"),
snapshotCapturedUtc = model.SnapshotCapturedUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ")
});
});
private async Task<IActionResult> Poll(Func<int, Task<IActionResult>> read)
{
Response.Headers["X-Robots-Tag"] = "noindex, nofollow, noarchive";
if (currentUser.UserId is not int user) return Challenge();
try { return await read(user); }
catch (UnauthorizedAccessException) { return NotFound(); }
catch (SqlException e) when (e.Number == 51000) { return NotFound(); }
catch (Exception e) when (e is SqlException or TimeoutException or System.Text.Json.JsonException)
{
logger.LogWarning("Manuscript Reader check unavailable ({FailureKind}).", e.GetType().Name);
return StatusCode(503, new { message = "Manuscript updates are temporarily unavailable." });
}
}
}