using System; using System.IO; using AccountManagement.Domain.TaskAgg; using Company.Domain.AndroidApkVersionAgg; using CompanyManagment.App.Contracts.AndroidApkVersion; using CompanyManagment.Application.Helpers; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using System.Threading.Tasks; using _0_Framework.Application; namespace CompanyManagment.Application; public class AndroidApkVersionApplication : IAndroidApkVersionApplication { private readonly IAndroidApkVersionRepository _androidApkVersionRepository; private readonly ITaskRepository _taskRepository; public AndroidApkVersionApplication(IAndroidApkVersionRepository androidApkVersionRepository, ITaskRepository taskRepository) { _androidApkVersionRepository = androidApkVersionRepository; _taskRepository = taskRepository; } public async Task CreateAndActive(IFormFile file, ApkType apkType, bool isForce = false) { OperationResult op = new OperationResult(); #region Validation if (file == null || file.Length == 0) return op.Failed("لطفا فایل خود را وارد کنید"); // Check if the uploaded file is an APK if (Path.GetExtension(file.FileName).ToLower() != ".apk") return op.Failed("لطفا فایلی با پسوند .apk وارد کنید"); #endregion var activeApks = _androidApkVersionRepository.GetActives(apkType); await activeApks.ExecuteUpdateAsync(setter => setter.SetProperty(e => e.IsActive, IsActive.False)); _androidApkVersionRepository.SaveChanges(); var folderName = apkType == ApkType.WebView ? "GozreshgirWebView" : "GozreshgirFaceDetection"; var path = Path.Combine($"{_taskRepository.GetWebEnvironmentPath()}", "Storage", "Apk", "Android", folderName); Directory.CreateDirectory(path); // Read APK metadata with error handling ApkInfo apk; try { apk = ApkHelper.ReadApkInfo(file.OpenReadStream()); // Validate APK info if (string.IsNullOrEmpty(apk.VersionName) || string.IsNullOrEmpty(apk.VersionCode)) { return op.Failed("فایل APK معتبر نیست - اطلاعات نسخه یافت نشد"); } // Validate version code is numeric if (!int.TryParse(apk.VersionCode, out _)) { return op.Failed("فایل APK معتبر نیست - کد نسخه باید عددی باشد"); } } catch (Exception ex) { return op.Failed("خطا در خواندن فایل APK: " + ex.Message); } string uniqueFileName = $"{Path.GetFileNameWithoutExtension(file.FileName)}.v{apk.VersionName}{Path.GetExtension(file.FileName)}"; string filepath = Path.Combine(path, uniqueFileName); await using (var stream = new FileStream(filepath, FileMode.Create)) { await file.CopyToAsync(stream); } var entity = new AndroidApkVersion(apk.VersionName, apk.VersionCode, IsActive.True, filepath, apkType, isForce); _androidApkVersionRepository.Create(entity); _androidApkVersionRepository.SaveChanges(); return op.Succcedded(); } public async Task CreateAndDeActive(IFormFile file, ApkType apkType, bool isForce = false) { OperationResult op = new OperationResult(); #region Validation if (file == null || file.Length == 0) return op.Failed("لطفا فایل خود را وارد کنید"); // Check if the uploaded file is an APK if (Path.GetExtension(file.FileName).ToLower() != ".apk") return op.Failed("لطفا فایلی با پسوند .apk وارد کنید"); #endregion var folderName = apkType == ApkType.WebView ? "GozreshgirWebView" : "GozreshgirFaceDetection"; var path = Path.Combine($"{_taskRepository.GetWebEnvironmentPath()}", "Storage", "Apk", "Android", folderName); Directory.CreateDirectory(path); // Read APK metadata with error handling ApkInfo apk; try { apk = ApkHelper.ReadApkInfo(file.OpenReadStream()); // Validate APK info if (string.IsNullOrEmpty(apk.VersionName) || string.IsNullOrEmpty(apk.VersionCode)) { return op.Failed("فایل APK معتبر نیست - اطلاعات نسخه یافت نشد"); } // Validate version code is numeric if (!int.TryParse(apk.VersionCode, out _)) { return op.Failed("فایل APK معتبر نیست - کد نسخه باید عددی باشد"); } } catch (Exception ex) { return op.Failed("خطا در خواندن فایل APK: " + ex.Message); } string uniqueFileName = $"{Path.GetFileNameWithoutExtension(file.FileName)}.v{apk.VersionName}{Path.GetExtension(file.FileName)}"; string filepath = Path.Combine(path, uniqueFileName); await using (var stream = new FileStream(filepath, FileMode.Create)) { await file.CopyToAsync(stream); } var entity = new AndroidApkVersion(apk.VersionName, apk.VersionCode, IsActive.False, filepath, apkType, isForce); _androidApkVersionRepository.Create(entity); _androidApkVersionRepository.SaveChanges(); return op.Succcedded(); } public async Task GetLatestActiveVersionPath(ApkType apkType) { return await _androidApkVersionRepository.GetLatestActiveVersionPath(apkType); } public OperationResult Remove(long id) { OperationResult op = new OperationResult(); var entity = _androidApkVersionRepository.Get(id); if (entity == null) return op.Failed("چنین آیتمی وجود ندارد"); var path = entity.Path; _androidApkVersionRepository.Remove(entity); _androidApkVersionRepository.SaveChanges(); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } return op.Succcedded(); } public bool HasAndroidApkToDownload(ApkType apkType) { return _androidApkVersionRepository.Exists(x => x.IsActive == IsActive.True && x.ApkType == apkType); } public Task GetLatestActiveInfo(ApkType apkType, int currentVersionCode) { var latest = _androidApkVersionRepository.GetLatestActive(apkType); if (latest == null) return Task.FromResult(new AndroidApkVersionInfo(0, "0", false, false, string.Empty, string.Empty)); // Return API endpoint for downloading APK file var fileUrl = $"/api/android-apk/download?type={apkType}"; int latestCode = 0; int.TryParse(latest.VersionCode, out latestCode); var shouldUpdate = latestCode > currentVersionCode; return Task.FromResult(new AndroidApkVersionInfo(latestCode, latest.VersionName, shouldUpdate, latest.IsForce, fileUrl, "Bug fixes and improvements")); } }