Files
Backend-Api/ServiceHost/Areas/Camera/Controllers/CameraController.cs

483 lines
17 KiB
C#

using ServiceHost.BaseControllers;
using System;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using _0_Framework.Application;
using _0_Framework.Exceptions;
using AccountManagement.Application.Contracts.Account;
using AccountManagement.Application.Contracts.CameraAccount;
using AccountManagement.Domain.TaskAgg;
using CompanyManagment.App.Contracts.AndroidApkVersion;
using CompanyManagment.App.Contracts.PersonnleCode;
using CompanyManagment.App.Contracts.RollCall;
using CompanyManagment.App.Contracts.RollCallEmployee;
using CompanyManagment.App.Contracts.RollCallService;
using CompanyManagment.App.Contracts.Employee;
using CompanyManagment.App.Contracts.EmployeeFaceEmbedding;
using CompanyManagment.App.Contracts.CameraBugReport;
using Microsoft.AspNetCore.Authorization;
namespace ServiceHost.Areas.Camera.Controllers;
public class CameraController : CameraBaseController
{
private readonly IWebHostEnvironment _webHostEnvironment;
private readonly IConfiguration _configuration;
private readonly IEmployeeApplication _employeeApplication;
private readonly IRollCallApplication _rollCallApplication;
private readonly IRollCallServiceApplication _rollCallServiceApplication;
private readonly IRollCallEmployeeApplication _rollCallEmployeeApplication;
private readonly IAuthHelper _authHelper;
private readonly IPersonnelCodeApplication _personnelCodeApplication;
private readonly IAccountApplication _accountApplication;
private readonly IPasswordHasher _passwordHasher;
private readonly ICameraAccountApplication _cameraAccountApplication;
private readonly IEmployeeFaceEmbeddingApplication _employeeFaceEmbeddingApplication;
private long _workshopId;
private readonly IHttpClientFactory _httpClientFactory;
private readonly HttpClient _faceEmbeddingHttpClient;
private readonly IAndroidApkVersionApplication _androidApkVersionApplication;
private readonly ICameraBugReportApplication _cameraBugReportApplication;
public CameraController(IWebHostEnvironment webHostEnvironment,
IConfiguration configuration,
IEmployeeApplication employeeApplication,
IRollCallApplication rollCallApplication,
IAuthHelper authHelper,
IRollCallServiceApplication rollCallServiceApplication,
IRollCallEmployeeApplication rollCallEmployeeApplication,
IPersonnelCodeApplication personnelCodeApplication,
IAccountApplication accountApplication,
IPasswordHasher passwordHasher,
ICameraAccountApplication cameraAccountApplication,
IEmployeeFaceEmbeddingApplication employeeFaceEmbeddingApplication,
IHttpClientFactory httpClientFactory,
IAndroidApkVersionApplication androidApkVersionApplication,
ICameraBugReportApplication cameraBugReportApplication)
{
_webHostEnvironment = webHostEnvironment;
_configuration = configuration;
_employeeApplication = employeeApplication;
_rollCallApplication = rollCallApplication;
_authHelper = authHelper;
_rollCallServiceApplication = rollCallServiceApplication;
_rollCallEmployeeApplication = rollCallEmployeeApplication;
_personnelCodeApplication = personnelCodeApplication;
_accountApplication = accountApplication;
_passwordHasher = passwordHasher;
_cameraAccountApplication = cameraAccountApplication;
_employeeFaceEmbeddingApplication = employeeFaceEmbeddingApplication;
_httpClientFactory = httpClientFactory;
_androidApkVersionApplication = androidApkVersionApplication;
_cameraBugReportApplication = cameraBugReportApplication;
_faceEmbeddingHttpClient = httpClientFactory.CreateClient();
_faceEmbeddingHttpClient.BaseAddress = new Uri("http://localhost:8000/");
_workshopId= authHelper.GetWorkshopId();
}
[HttpPost("login")]
[AllowAnonymous]
public IActionResult CameraLogin([FromBody] CameraLoginRequest request)
{
_accountApplication.CameraLogin(request);
return Ok(new
{
WorkshopId = _workshopId,
});
}
[HttpPost("embedding")]
[AllowAnonymous]
public async Task<ActionResult<List<EmployeeFaceEmbeddingDto>>> WorkshopEmbedding()
{
if (!User.Identity?.IsAuthenticated ?? false)
{
return Unauthorized();
}
_workshopId = _authHelper.GetWorkshopId();
var data = await _employeeFaceEmbeddingApplication
.GetByWorkshopIdsAsync([_workshopId]);
return data;
}
[HttpPost("flag/{employeeId:long}")]
public async Task<IActionResult> GetFlag(long employeeId)
{
var flagId = _rollCallApplication.Flag(employeeId, _workshopId);
return Ok(new
{
flagId = flagId,
status = flagId == 0 ? "enter": "exit"
});
}
[HttpPost("exit")]
public IActionResult Exit([FromBody]RollCallExitRequest request)
{
var employeeId = request.EmployeeId;
var flagId = request.FlagId;
bool rollCallEmployee = _rollCallEmployeeApplication.IsEmployeeRollCallActive(employeeId,
_workshopId);
if (!rollCallEmployee)
{
throw new BadRequestException("پرسنل مورد نظر غیر فعال است");
}
_faceEmbeddingHttpClient.PostAsync("embeddings/refine",
JsonContent.Create(new {
employeeId,
workshopId = _workshopId,
embedding =request.Embeddings ,
confidence =request.Confidence ,
metadata =new{},
}));
var repeatStatus = _rollCallApplication.CheckRepeat(employeeId, _workshopId);
switch (repeatStatus)
{
case "IncomRegistred-InvalidOut":
throw new BadRequestException("شما به تازگی ثبت ورود نموده اید ,تا 2 دقیقه نمی توانید ثبت خروج نمایید");
case "outRegistred-InvalidIncom":
throw new BadRequestException("شما به تازگی ثبت خروج نموده اید تا 2 دقیقه نمی توانید ثبت ورود نمایید");
}
var res = _rollCallApplication.Edit(flagId);
if (res.IsSuccedded)
{
return new JsonResult(new
{
isSuccess = true,
});
}
throw new BadRequestException(res.Message);
}
[HttpPost("enter")]
public IActionResult Enter([FromBody]RollCallEnterRequest request)
{
var employeeId = request.EmployeeId;
var now = DateTime.Now;
var command = new CreateRollCall()
{
WorkshopId = _workshopId,
EmployeeId = request.EmployeeId,
StartDate = now,
};
bool rollCallEmployee = _rollCallEmployeeApplication.IsEmployeeRollCallActive(employeeId,
_workshopId);
if (!rollCallEmployee)
{
throw new BadRequestException("پرسنل مورد نظر غیر فعال است");
}
_faceEmbeddingHttpClient.PostAsync("embeddings/refine",
JsonContent.Create(new {
employeeId,
workshopId = _workshopId,
embedding =request.Embeddings ,
confidence =request.Confidence ,
metadata =new{},
}));
var repeatStatus = _rollCallApplication.CheckRepeat(employeeId, _workshopId);
switch (repeatStatus)
{
case "IncomRegistred-InvalidOut":
throw new BadRequestException("شما به تازگی ثبت ورود نموده اید ,تا 2 دقیقه نمی توانید ثبت خروج نمایید");
case "outRegistred-InvalidIncom":
throw new BadRequestException("شما به تازگی ثبت خروج نموده اید تا 2 دقیقه نمی توانید ثبت ورود نمایید");
}
var res = _rollCallApplication.Create(command);
if (res.IsSuccedded)
{
return new JsonResult(new
{
isSuccess = true,
});
}
else
{
return new JsonResult(new
{
isSuccess = false,
});
}
}
[AllowAnonymous]
[HttpGet("check-update")]
public async Task<IActionResult> CheckUpdate([FromQuery] ApkType type, [FromQuery] int currentVersionCode = 0)
{
var info = await _androidApkVersionApplication.GetLatestActiveInfo(type, currentVersionCode);
return Ok(new
{
latestVersionCode = info.LatestVersionCode,
latestVersionName = info.LatestVersionName,
shouldUpdate = info.ShouldUpdate,
isForceUpdate = info.IsForceUpdate,
downloadUrl = info.DownloadUrl,
releaseNotes = info.ReleaseNotes
});
}
[AllowAnonymous]
[HttpGet("download")]
public async Task<IActionResult> Download([FromQuery] ApkType type)
{
// Check if APK exists
if (!_androidApkVersionApplication.HasAndroidApkToDownload(type))
{
return NotFound(new { message = $"هیچ فایل APK فعالی برای {type} یافت نشد" });
}
// Get the path to the latest active APK
var path = await _androidApkVersionApplication.GetLatestActiveVersionPath(type);
if (string.IsNullOrEmpty(path) || !System.IO.File.Exists(path))
{
return NotFound(new { message = "فایل APK یافت نشد" });
}
// Set appropriate file name for download
var fileName = type == ApkType.WebView
? "Gozareshgir.apk"
: "Gozareshgir-FaceDetection.apk";
// Return the file for download
return PhysicalFile(path, "application/vnd.android.package-archive", fileName);
}
[HttpGet("SendPersonelCodeToGetEmployeeId")]
public IActionResult SendPersonelCodeToGetEmployeeId(long personelCode, long workshopId)
{
long employeeId = _personnelCodeApplication.GetEmployeeIdByPersonelCode(personelCode, workshopId);
if (employeeId == 0)
{
return new JsonResult(new
{
isSuccess = false,
message = "کد پرسنلی یافت نشد",
});
}
bool rollcallEmployee = _rollCallEmployeeApplication.IsEmployeeRollCallActive(employeeId, workshopId);
if (!rollcallEmployee)
{
return new JsonResult(new
{
isSuccess = false,
message = "پرسنل مورد نظر غیر فعال است",
});
}
var repeatStatus = _rollCallApplication.CheckRepeat(employeeId, workshopId);
switch (repeatStatus)
{
case "IncomRegistred-InvalidOut":
return new JsonResult(new
{
isSuccess = false,
message = "شما به تازگی ثبت ورود نموده اید ,تا 2 دقیقه نمی توانید ثبت خروج نمایید",
});
case "outRegistred-InvalidIncom":
return new JsonResult(new
{
isSuccess = false,
message = "شما به تازگی ثبت خروج نموده اید تا 2 دقیقه نمی توانید ثبت ورود نمایید",
});
}
return new JsonResult(new
{
isSuccess = true,
message = "",
personId = $"{employeeId}",
});
}
[HttpGet("EmployeeFlag")]
public IActionResult EmployeeFlag(long employeeId, long workshopId)
{
var employee = _rollCallEmployeeApplication.GetByEmployeeIdAndWorkshopId(employeeId, workshopId);
var employeeFullName = employee?.EmployeeFullName ?? string.Empty;
var flagId = _rollCallApplication.Flag(employeeId, workshopId);
return new JsonResult(new
{
employeeName = employeeFullName,
flag = flagId
});
}
[HttpGet("Logout")]
public IActionResult Logout()
{
_accountApplication.Logout();
return new JsonResult(new { isSuccess = true });
}
/// <summary>
/// ارسال گزارش خرابی از طرف دوربین
/// </summary>
[HttpPost("bug-report")]
[AllowAnonymous]
public IActionResult SubmitBugReport([FromBody] SubmitBugReportRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(new { success = false, message = "داده‌های ارسالی معتبر نیستند" });
}
try
{
var command = new CreateCameraBugReportCommand
{
Title = request.Title,
Description = request.Description,
UserEmail = request.UserEmail,
AccountId = request.AccountId,
DeviceModel = request.DeviceInfo?.DeviceModel,
OsVersion = request.DeviceInfo?.OsVersion,
Platform = request.DeviceInfo?.Platform,
Manufacturer = request.DeviceInfo?.Manufacturer,
DeviceId = request.DeviceInfo?.DeviceId,
ScreenResolution = request.DeviceInfo?.ScreenResolution,
MemoryInMB = request.DeviceInfo?.MemoryInMB ?? 0,
StorageInMB = request.DeviceInfo?.StorageInMB ?? 0,
BatteryLevel = request.DeviceInfo?.BatteryLevel ?? 0,
IsCharging = request.DeviceInfo?.IsCharging ?? false,
NetworkType = request.DeviceInfo?.NetworkType,
AppVersion = request.AppInfo?.AppVersion,
BuildNumber = request.AppInfo?.BuildNumber,
PackageName = request.AppInfo?.PackageName,
InstallTime = request.AppInfo?.InstallTime ?? DateTime.Now,
LastUpdateTime = request.AppInfo?.LastUpdateTime ?? DateTime.Now,
Flavor = request.AppInfo?.Flavor,
Type = (CameraBugReportType)request.Type,
Priority = (CameraBugPriority)request.Priority,
StackTrace = request.StackTrace,
Logs = request.Logs,
Screenshots = request.Screenshots
};
var result = _cameraBugReportApplication.Create(command);
if (result.IsSuccedded)
{
return Ok(new
{
success = true,
message = result.Message ?? "گزارش خرابی با موفقیت ارسال شد"
});
}
return BadRequest(new
{
success = false,
message = result.Message ?? "خطا در ارسال گزارش خرابی"
});
}
catch (Exception ex)
{
return BadRequest(new
{
success = false,
message = $"خطا در ارسال گزارش خرابی: {ex.Message}"
});
}
}
}
public class RollCallExitRequest:RollCallEnterRequest
{
public long FlagId { get; set; }
}
public class RollCallEnterRequest
{
public long EmployeeId { get; set; }
public List<double> Embeddings { get; set; }
public float Confidence { get; set; }
}
public class CameraFlagRequest
{
public long EmployeeId { get; set; }
public long WorkshopId { get; set; }
}
/// <summary>
/// درخواست ارسال گزارش خرابی از طرف دوربین
/// </summary>
public class SubmitBugReportRequest
{
public string Title { get; set; }
public string Description { get; set; }
public string UserEmail { get; set; }
public long? AccountId { get; set; }
public int Type { get; set; } // BugReportType enum value
public int Priority { get; set; } // BugPriority enum value
public string StackTrace { get; set; }
public List<string> Logs { get; set; }
public List<string> Screenshots { get; set; } // Base64 encoded images
public DeviceInfoRequest DeviceInfo { get; set; }
public AppInfoRequest AppInfo { get; set; }
}
/// <summary>
/// اطلاعات دستگاه
/// </summary>
public class DeviceInfoRequest
{
public string DeviceModel { get; set; }
public string OsVersion { get; set; }
public string Platform { get; set; }
public string Manufacturer { get; set; }
public string DeviceId { get; set; }
public string ScreenResolution { get; set; }
public int MemoryInMB { get; set; }
public int StorageInMB { get; set; }
public int BatteryLevel { get; set; }
public bool IsCharging { get; set; }
public string NetworkType { get; set; }
}
/// <summary>
/// اطلاعات برنامه
/// </summary>
public class AppInfoRequest
{
public string AppVersion { get; set; }
public string BuildNumber { get; set; }
public string PackageName { get; set; }
public DateTime InstallTime { get; set; }
public DateTime LastUpdateTime { get; set; }
public string Flavor { get; set; }
}