354 lines
13 KiB
C#
354 lines
13 KiB
C#
using Microsoft.AspNetCore.Hosting;
|
|
using Microsoft.Data.SqlClient;
|
|
using Microsoft.Extensions.Configuration;
|
|
using SkiaSharp;
|
|
using System;
|
|
using System.Drawing;
|
|
using System.IO;
|
|
using System.Threading.Tasks;
|
|
namespace HRM.BO
|
|
{
|
|
|
|
|
|
public class EmployeePhotoService
|
|
{
|
|
private readonly string _thumbnailFolder;
|
|
private readonly string _pendingFolder;
|
|
private const int TargetSize = 100;
|
|
|
|
public EmployeePhotoService(IWebHostEnvironment env)
|
|
{
|
|
// Deliberately the content root, NOT wwwroot. Under wwwroot these files were served
|
|
// by UseStaticFiles to anyone who could guess an employee number, bypassing the photo
|
|
// endpoints entirely. Here the endpoints are the only way in, so access rules applied
|
|
// there actually hold. This sits alongside the other runtime data folders the app
|
|
// already keeps at the content root (Documents, EMPPHOTO, LOGO).
|
|
string photoRoot = Path.Combine(env.ContentRootPath, "EmployeePhotos");
|
|
|
|
// Approved photos. Every read path (GetuploadEmpPhoto, GetuploadEmpFile) serves from here.
|
|
_thumbnailFolder = Path.Combine(photoRoot, "EmpthumbnailsImage");
|
|
|
|
// Photos an employee has submitted but an admin has not approved yet. Only the
|
|
// profile-update approval screen reads from here; on approve the file moves to
|
|
// _thumbnailFolder, on reject it is deleted.
|
|
_pendingFolder = Path.Combine(photoRoot, "EmpPendingImage");
|
|
|
|
EnsureFolder(_thumbnailFolder);
|
|
EnsureFolder(_pendingFolder);
|
|
}
|
|
|
|
private static void EnsureFolder(string folder)
|
|
{
|
|
if (!Directory.Exists(folder))
|
|
{
|
|
Directory.CreateDirectory(folder);
|
|
}
|
|
}
|
|
|
|
public bool ThumbnailExists(string employeeNo) => FindApprovedFile(employeeNo) != null;
|
|
|
|
public async Task<(byte[] Bytes, string ContentType)?> GetThumbnailAsync(string EmployeeNo)
|
|
{
|
|
// Employee numbers arrive from the URL on the photo endpoints, so a rejected one
|
|
// reads as "no photo" rather than blowing up the request.
|
|
var path = FindApprovedFile(EmployeeNo);
|
|
|
|
if (path != null)
|
|
{
|
|
var cached = await File.ReadAllBytesAsync(path);
|
|
return (cached, "image/jpeg");
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
|
|
|
|
private string GetThumbnailPath(string employeeNo) =>
|
|
Path.Combine(_thumbnailFolder, $"{SafeEmployeeNo(employeeNo)}-image.jpg");
|
|
|
|
/// <summary>
|
|
/// Employee numbers reach the photo endpoints straight off the URL, and they end up in a
|
|
/// file path, so anything that could climb out of the photo folders is refused outright.
|
|
/// </summary>
|
|
private static string SafeEmployeeNo(string employeeNo)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(employeeNo))
|
|
throw new ArgumentException("Employee number is required.", nameof(employeeNo));
|
|
|
|
employeeNo = employeeNo.Trim();
|
|
|
|
if (employeeNo.Length > 50
|
|
|| employeeNo.Contains("..")
|
|
|| employeeNo.IndexOf('/') >= 0
|
|
|| employeeNo.IndexOf('\\') >= 0
|
|
|| employeeNo.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
|
|
{
|
|
throw new ArgumentException("Invalid employee number.", nameof(employeeNo));
|
|
}
|
|
|
|
return employeeNo;
|
|
}
|
|
|
|
#region Physical paths (for serving the files over a URL)
|
|
|
|
/// <summary>
|
|
/// Full path of this employee's approved photo, or null when there is none.
|
|
/// </summary>
|
|
public string FindApprovedFile(string employeeNo)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(employeeNo))
|
|
return null;
|
|
|
|
string path;
|
|
try
|
|
{
|
|
path = GetThumbnailPath(employeeNo);
|
|
}
|
|
catch (ArgumentException)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
return File.Exists(path) ? path : null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Full path of this employee's photo awaiting approval, or null when there is none.
|
|
/// </summary>
|
|
public string FindPendingFilePath(string employeeNo) => FindPendingFile(employeeNo);
|
|
|
|
#endregion
|
|
|
|
|
|
#region Pending (awaiting admin approval)
|
|
|
|
/// <summary>
|
|
/// Stores a submitted photo in the pending folder, keyed by employee number, keeping the
|
|
/// original bytes so the approver reviews the real image rather than a 100px thumbnail.
|
|
/// Any photo this employee had pending before is replaced.
|
|
/// </summary>
|
|
public string SavePending(string employeeNo, byte[] imageBytes, string extension)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(employeeNo))
|
|
throw new ArgumentException("Employee number is required to store a pending photo.", nameof(employeeNo));
|
|
|
|
if (imageBytes == null || imageBytes.Length == 0)
|
|
throw new ArgumentException("No image data received.", nameof(imageBytes));
|
|
|
|
extension = NormalizeExtension(extension);
|
|
|
|
// Only one pending photo per employee — drop earlier submissions, whatever their extension.
|
|
DeletePending(employeeNo);
|
|
|
|
var finalPath = Path.Combine(_pendingFolder, $"{SafeEmployeeNo(employeeNo)}-pending{extension}");
|
|
WriteAtomic(finalPath, imageBytes);
|
|
|
|
return Path.GetFileName(finalPath);
|
|
}
|
|
|
|
public bool PendingExists(string employeeNo) => FindPendingFile(employeeNo) != null;
|
|
|
|
/// <summary>
|
|
/// The pending photo as stored, or null when this employee has none awaiting approval.
|
|
/// </summary>
|
|
public (byte[] Bytes, string FileName)? GetPending(string employeeNo)
|
|
{
|
|
var path = FindPendingFile(employeeNo);
|
|
if (path == null)
|
|
return null;
|
|
|
|
return (File.ReadAllBytes(path), Path.GetFileName(path));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Promotes the pending photo to the approved folder and removes it from pending.
|
|
/// Returns false when nothing was pending, so callers can fall back to the older
|
|
/// database-backed approval path for requests raised before this folder existed.
|
|
/// </summary>
|
|
public bool ApprovePending(string employeeNo)
|
|
{
|
|
var path = FindPendingFile(employeeNo);
|
|
if (path == null)
|
|
return false;
|
|
|
|
byte[] bytes = File.ReadAllBytes(path);
|
|
GenerateThumbnail(employeeNo, bytes);
|
|
DeletePending(employeeNo);
|
|
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Drops a pending photo without approving it (rejection, or a withdrawn request).
|
|
/// </summary>
|
|
public void DeletePending(string employeeNo)
|
|
{
|
|
string safeNo;
|
|
try
|
|
{
|
|
safeNo = SafeEmployeeNo(employeeNo);
|
|
}
|
|
catch (ArgumentException)
|
|
{
|
|
return;
|
|
}
|
|
|
|
foreach (var file in Directory.GetFiles(_pendingFolder, $"{safeNo}-pending.*"))
|
|
{
|
|
try
|
|
{
|
|
File.Delete(file);
|
|
}
|
|
catch (IOException)
|
|
{
|
|
// A locked file here only leaves a stale pending image; the next submission
|
|
// overwrites it. Not worth failing the approval the caller is in the middle of.
|
|
}
|
|
}
|
|
}
|
|
|
|
private string FindPendingFile(string employeeNo)
|
|
{
|
|
string safeNo;
|
|
try
|
|
{
|
|
safeNo = SafeEmployeeNo(employeeNo);
|
|
}
|
|
catch (ArgumentException)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var matches = Directory.GetFiles(_pendingFolder, $"{safeNo}-pending.*");
|
|
if (matches.Length == 0)
|
|
return null;
|
|
|
|
// Defensive: if an earlier failed cleanup left more than one, the newest is the request.
|
|
Array.Sort(matches, (a, b) => File.GetLastWriteTimeUtc(b).CompareTo(File.GetLastWriteTimeUtc(a)));
|
|
return matches[0];
|
|
}
|
|
|
|
private static string NormalizeExtension(string extension)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(extension))
|
|
return ".jpg";
|
|
|
|
extension = extension.Trim().ToLowerInvariant();
|
|
if (!extension.StartsWith("."))
|
|
extension = "." + extension;
|
|
|
|
switch (extension)
|
|
{
|
|
case ".jpg":
|
|
case ".jpeg":
|
|
case ".png":
|
|
case ".bmp":
|
|
case ".gif":
|
|
case ".webp":
|
|
return extension;
|
|
default:
|
|
throw new InvalidOperationException($"'{extension}' is not a supported image type.");
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
|
|
|
|
public void GenerateThumbnail(string employeeNo, byte[] imageBytes, int targetSize = TargetSize)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(employeeNo))
|
|
throw new ArgumentException("Employee number is required to store a photo.", nameof(employeeNo));
|
|
|
|
using var codec = SKCodec.Create(new SKMemoryStream(imageBytes));
|
|
if (codec == null)
|
|
throw new InvalidOperationException("Could not decode image — unsupported or corrupt file.");
|
|
|
|
using var original = SKBitmap.Decode(codec);
|
|
if (original == null)
|
|
throw new InvalidOperationException("Decode failed.");
|
|
|
|
// apply EXIF orientation manually — SkiaSharp doesn't auto-orient like ImageSharp
|
|
using var oriented = ApplyExifOrientation(original, codec.EncodedOrigin);
|
|
|
|
int srcWidth = oriented.Width;
|
|
int srcHeight = oriented.Height;
|
|
|
|
float scale = Math.Max((float)targetSize / srcWidth, (float)targetSize / srcHeight);
|
|
int scaledWidth = (int)Math.Ceiling(srcWidth * scale);
|
|
int scaledHeight = (int)Math.Ceiling(srcHeight * scale);
|
|
|
|
using var resized = oriented.Resize(
|
|
new SKImageInfo(scaledWidth, scaledHeight),
|
|
new SKSamplingOptions(SKFilterMode.Linear, SKMipmapMode.Linear));
|
|
|
|
if (resized == null)
|
|
throw new InvalidOperationException("Resize failed.");
|
|
|
|
int offsetX = (scaledWidth - targetSize) / 2;
|
|
int offsetY = (scaledHeight - targetSize) / 2;
|
|
|
|
using var cropped = new SKBitmap(targetSize, targetSize);
|
|
using (var canvas = new SKCanvas(cropped))
|
|
{
|
|
canvas.Clear(SKColors.White);
|
|
canvas.DrawBitmap(resized, new SKRect(-offsetX, -offsetY, scaledWidth - offsetX, scaledHeight - offsetY));
|
|
}
|
|
|
|
using var image = SKImage.FromBitmap(cropped);
|
|
using var data = image.Encode(SKEncodedImageFormat.Jpeg, 80);
|
|
WriteAtomic(GetThumbnailPath(employeeNo), data.ToArray());
|
|
}
|
|
|
|
private static SKBitmap ApplyExifOrientation(SKBitmap bitmap, SKEncodedOrigin origin)
|
|
{
|
|
// most phone photos are TopLeft (no-op) or RightTop/LeftBottom (90/270 rotation)
|
|
switch (origin)
|
|
{
|
|
case SKEncodedOrigin.TopLeft:
|
|
return bitmap; // already correct, no copy needed
|
|
|
|
case SKEncodedOrigin.RightTop: // rotate 90 CW
|
|
return RotateBitmap(bitmap, 90);
|
|
|
|
case SKEncodedOrigin.BottomRight: // rotate 180
|
|
return RotateBitmap(bitmap, 180);
|
|
|
|
case SKEncodedOrigin.LeftBottom: // rotate 270 CW
|
|
return RotateBitmap(bitmap, 270);
|
|
|
|
default:
|
|
return bitmap; // flips (mirrored) are rare for camera photos — skip for simplicity
|
|
}
|
|
}
|
|
|
|
private static SKBitmap RotateBitmap(SKBitmap bitmap, int degrees)
|
|
{
|
|
bool swapDimensions = degrees == 90 || degrees == 270;
|
|
int width = swapDimensions ? bitmap.Height : bitmap.Width;
|
|
int height = swapDimensions ? bitmap.Width : bitmap.Height;
|
|
|
|
var rotated = new SKBitmap(width, height);
|
|
using var canvas = new SKCanvas(rotated);
|
|
canvas.Translate(width / 2f, height / 2f);
|
|
canvas.RotateDegrees(degrees);
|
|
canvas.Translate(-bitmap.Width / 2f, -bitmap.Height / 2f);
|
|
canvas.DrawBitmap(bitmap, 0, 0);
|
|
|
|
return rotated;
|
|
}
|
|
|
|
// ---------- ATOMIC WRITE (avoids race conditions on concurrent cache misses) ----------
|
|
|
|
// Synchronous on purpose: callers (upload, approve) must not return to the browser before
|
|
// the file is on disk, or the very next read renders the previous photo.
|
|
private static void WriteAtomic(string finalPath, byte[] bytes)
|
|
{
|
|
var tempPath = finalPath + $".{Guid.NewGuid():N}.tmp";
|
|
|
|
File.WriteAllBytes(tempPath, bytes);
|
|
File.Move(tempPath, finalPath, overwrite: true);
|
|
}
|
|
}
|
|
}
|