Commit 53176dd4 authored by Krishna Reddy Tamatam's avatar Krishna Reddy Tamatam

- Port Setting dynamically

- Compressed icon Api Changes done
parent 39af2a52
......@@ -18,6 +18,8 @@
<PackageReference Include="prometheus-net" Version="5.0.2" />
<PackageReference Include="prometheus-net.AspNetCore" Version="5.0.2" />
<PackageReference Include="prometheus-net.SystemMetrics" Version="2.0.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.12" />
<PackageReference Include="SSH.NET" Version="2025.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.15.0" />
......
......@@ -6,6 +6,7 @@ namespace FTP_Services.Core.Models
public string AdminConnectionString { get; set; }
public string ConnectionString_MRD { get; set; }
public string Secret { get; set; }
public string listeningPort {get; set;}
public AppSettings()
{
......@@ -13,6 +14,7 @@ namespace FTP_Services.Core.Models
ConnectionString = "";
AdminConnectionString = "";
ConnectionString_MRD = "";
listeningPort="";
}
public FTPConfiguration FTPConfiguration { get; set; }
......
......@@ -366,5 +366,7 @@ namespace FTP_Services.Core.Models
public string? RemotePassword { get; set; }
public int RemotePort { get; set; }
public string? WebRemotePath { get; set; }
public int? Type { get; set; }
public bool? IsSFTP { get; set; }
}
}
// Services/FtpService.cs
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
// using System.Drawing;
// using System.Drawing.Drawing2D;
// using System.Drawing.Imaging;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using FluentFTP;
using FTP_Services.Core.Models;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using Renci.SshNet;
public class FluentFtpService
{
......@@ -36,11 +40,12 @@ public class FluentFtpService
$"/{payload.WebRemotePath.TrimEnd('/')}/{payload.FolderPath.TrimStart('/')}";
string fullLocalPath = Path.Combine(localTempDir, Guid.NewGuid().ToString());
_log($"fullLocalPath : {fullLocalPath}");
try
{
if (Directory.Exists(localTempDir))
{
_log($"localTempDir is Exist : {localTempDir}");
Directory.Delete(localTempDir, recursive: true);
Directory.CreateDirectory(localTempDir);
}
......@@ -74,6 +79,7 @@ public class FluentFtpService
try
{
await ftpClient.Connect();
_log($"Connected to FTP: {payload.RemoteHost}");
......@@ -92,6 +98,7 @@ public class FluentFtpService
processStart = DateTime.Now;
_log($"Processing started at {processStart:HH:mm:ss}");
string encryptionKey = "12345678909876543210123456789098";
foreach (var fileName in payload.FilePaths)
{
string localFilePath = Path.Combine(fullLocalPath, fileName);
......@@ -105,13 +112,20 @@ public class FluentFtpService
{
byte[] encryptedData = await System.IO.File.ReadAllBytesAsync(localFilePath);
byte[] decryptedBytes = DecryptFTPFile(encryptedData, encryptionKey);
using var msDecrypted = new MemoryStream(decryptedBytes);
using var originalImage = Image.FromStream(msDecrypted);
using var resizedImage = ResizeFTPImage(originalImage, Width, Height);
//using var msDecrypted = new MemoryStream(decryptedBytes);
// using var originalImage = Image.FromStream(msDecrypted);
// using var resizedImage = ResizeFTPImage(originalImage, Width, Height);
// using var msResized = new MemoryStream();
// resizedImage.Save(msResized, ImageFormat.Jpeg);
using var image = Image.Load(decryptedBytes);
image.Mutate(x => x.Resize(Width, Height));
using var msResized = new MemoryStream();
resizedImage.Save(msResized, ImageFormat.Jpeg);
string base64 = Convert.ToBase64String(msResized.ToArray());
using var ms = new MemoryStream();
image.SaveAsJpeg(ms);
string base64 = Convert.ToBase64String(ms.ToArray());
// byte[] fileBytes = await File.ReadAllBytesAsync(localFilePath);
// string base64 = Convert.ToBase64String(fileBytes);
......@@ -152,156 +166,252 @@ public class FluentFtpService
return results;
}
public async Task<
List<(string FileName, string? Base64, string? Error)>
> DownloadSelectedFilesAndConvertToBase64Async(
public async Task<List<(string FileName, string? Base64, string? Error)>>
DownloadSelectedFilesAndConvertToBase64Async(
FTPDocumentResponseModel payload,
string localTempDir,
int height,
int width
)
int width)
{
var results = new List<(string FileName, string? Base64, string? Error)>();
string remoteFolderPath =
$"/{payload.WebRemotePath.TrimEnd('/')}/{payload.FolderPath.TrimStart('/')}";
$"{payload.WebRemotePath.TrimEnd('/')}/{payload.FolderPath.TrimStart('/')}";
const string encryptionKey = "12345678909876543210123456789098";
AsyncFtpClient? ftpClient = null;
SftpClient? sftpClient = null;
try
{
// Recreate temp directory
if (Directory.Exists(localTempDir))
{
Directory.Delete(localTempDir, recursive: true);
Directory.CreateDirectory(localTempDir);
Directory.Delete(localTempDir, true);
}
}
catch (Exception ex)
{
_log($"Failed to delete temp folder: {ex.Message}");
}
const string encryptionKey = "12345678909876543210123456789098";
Directory.CreateDirectory(localTempDir);
using var ftpClient = new AsyncFtpClient(
host: payload.RemoteHost,
port: payload.RemotePort,
credentials: new NetworkCredential(payload.RemoteUser, payload.RemotePassword)
)
{
Config = { DataConnectionType = FtpDataConnectionType.AutoPassive }
};
var overallStart = DateTime.Now;
_log($"===== FileService START [{overallStart:yyyy-MM-dd HH:mm:ss}] =====");
var overallStart = DateTime.Now;
_log($"===== FtpService START [{overallStart:yyyy-MM-dd HH:mm:ss}] =====");
#region Connect
try
{
await ftpClient.Connect();
_log($"Connected to FTP server: {payload.RemoteHost}:{payload.RemotePort}");
if (payload.IsSFTP != true)
{
ftpClient = new AsyncFtpClient(
host: payload.RemoteHost,
port: payload.RemotePort,
credentials: new NetworkCredential(
payload.RemoteUser,
payload.RemotePassword))
{
Config =
{
DataConnectionType = FtpDataConnectionType.AutoPassive
}
};
await ftpClient.Connect();
_log(
$"FTP Connected : {payload.RemoteHost}:{payload.RemotePort}");
}
else
{
sftpClient = new SftpClient(
payload.RemoteHost,
payload.RemotePort,
payload.RemoteUser,
payload.RemotePassword);
sftpClient.Connect();
_log(
$"SFTP Connected : {payload.RemoteHost}:{payload.RemotePort}");
}
#endregion
#region Download Files
var downloadStart = DateTime.Now;
_log($"Download started at {downloadStart:HH:mm:ss}");
foreach (var fileName in payload.FilePaths)
{
string remoteFilePath = $"{remoteFolderPath}/{fileName}";
string localFilePath = Path.Combine(localTempDir, fileName);
string remoteFilePath =
$"{remoteFolderPath.TrimEnd('/')}/{fileName}";
string localFilePath =
Path.Combine(localTempDir, fileName);
try
{
var status = await ftpClient.DownloadFile(
localFilePath,
remoteFilePath,
FtpLocalExists.Overwrite,
FtpVerify.Retry
);
if (status == FtpStatus.Failed)
results.Add((fileName, null, "FTP download failed"));
_log($"Downloading: {remoteFilePath}");
if (payload.IsSFTP != true)
{
var status = await ftpClient!.DownloadFile(
localFilePath,
remoteFilePath,
FtpLocalExists.Overwrite,
FtpVerify.Retry);
if (status == FtpStatus.Failed)
{
results.Add(
(fileName, null, "FTP download failed"));
continue;
}
}
else
{
using var fileStream = File.Create(localFilePath);
sftpClient!.DownloadFile(
remoteFilePath,
fileStream);
fileStream.Flush();
}
if (File.Exists(localFilePath))
{
var fileInfo = new FileInfo(localFilePath);
_log(
$"Downloaded {fileName} ({fileInfo.Length} bytes)");
}
else
{
results.Add(
(fileName, null, "Downloaded file not found"));
}
}
catch (Exception ex)
{
results.Add((fileName, null, $"FTP download error: {ex.Message}"));
_log(
$"Download failed for {fileName}: {ex.Message}");
results.Add(
(fileName, null,
$"Download failed: {ex.Message}"));
}
}
var downloadEnd = DateTime.Now;
var downloadDuration = downloadEnd - downloadStart;
_log(
$"Download ended at {downloadEnd:HH:mm:ss} "
+ $"(Duration: {downloadDuration.Hours}h {downloadDuration.Minutes}m {downloadDuration.Seconds}s)"
);
$"Download completed in {(downloadEnd - downloadStart).TotalSeconds:N0} seconds");
var processStart = DateTime.Now;
_log($"Processing started at {processStart:HH:mm:ss}");
#endregion
#region Convert To Base64
foreach (var fileName in payload.FilePaths)
{
string localFilePath = Path.Combine(localTempDir, fileName);
string localFilePath =
Path.Combine(localTempDir, fileName);
if (!File.Exists(localFilePath))
{
results.Add((fileName, null, "File not found after download"));
continue;
}
try
{
byte[] encryptedData = await File.ReadAllBytesAsync(localFilePath);
byte[] decryptedBytes = DecryptFTPFile(encryptedData, encryptionKey);
byte[] fileBytes =
await File.ReadAllBytesAsync(localFilePath);
using var msDecrypted = new MemoryStream(decryptedBytes);
using var originalImage = Image.FromStream(msDecrypted);
using var resizedImage = ResizeFTPImage(originalImage, width, height);
string extension =
Path.GetExtension(localFilePath)
.ToLowerInvariant();
using var msResized = new MemoryStream();
resizedImage.Save(msResized, ImageFormat.Jpeg);
string base64 = Convert.ToBase64String(msResized.ToArray());
// PDF
if (extension == ".pdf")
{
string base64 =
Convert.ToBase64String(fileBytes);
results.Add((fileName, base64, null));
results.Add((fileName, base64, null));
continue;
}
// Images
using Image image =
payload.Type == 1
? Image.Load(
DecryptFTPFile(
fileBytes,
encryptionKey))
: Image.Load(fileBytes);
image.Mutate(x =>
x.Resize(width, height));
using var ms = new MemoryStream();
image.SaveAsJpeg(ms);
string imageBase64 =
Convert.ToBase64String(ms.ToArray());
results.Add(
(fileName, imageBase64, null));
}
catch (Exception ex)
{
results.Add((fileName, null, $"Processing failed: {ex.Message}"));
_log(
$"Processing failed for {fileName}: {ex.Message}");
results.Add(
(fileName, null,
$"Processing failed: {ex.Message}"));
}
}
var processEnd = DateTime.Now;
var processDuration = processEnd - processStart;
#endregion
var overallEnd = DateTime.Now;
_log(
$"Processing ended at {processEnd:HH:mm:ss} "
+ $"(Duration: {processDuration.Hours}h {processDuration.Minutes}m {processDuration.Seconds}s)"
);
$"===== FileService END [{overallEnd:yyyy-MM-dd HH:mm:ss}] =====");
// await ftpClient.Disconnect();
return results;
}
catch (Exception ex)
{
results.Add(("Connection", null, $"FTP Connection failed: {ex.Message}"));
_log($"FTP Connection failed: {ex.Message}");
_log($"Connection failed: {ex.Message}");
results.Add(
("Connection", null,
$"Connection failed: {ex.Message}"));
return results;
}
finally
{
try
{
await ftpClient.Disconnect();
_log("FTP client disconnected successfully.");
if (ftpClient?.IsConnected == true)
{
await ftpClient.Disconnect();
_log("FTP disconnected.");
}
if (sftpClient?.IsConnected == true)
{
sftpClient.Disconnect();
_log("SFTP disconnected.");
}
}
catch (Exception ex)
{
_log($"Failed to disconnect FTP client: {ex.Message}");
_log($"Disconnect error: {ex.Message}");
}
}
var overallEnd = DateTime.Now;
var totalDuration = overallEnd - overallStart;
_log(
$"Total Execution Time: {totalDuration.Hours}h {totalDuration.Minutes}m {totalDuration.Seconds}s"
);
_log($"===== FtpService END [{overallEnd:yyyy-MM-dd HH:mm:ss}] =====");
return results;
}
private byte[] DecryptFTPFile(byte[] encryptedData, string encryptionKey)
......@@ -334,19 +444,19 @@ public class FluentFtpService
return decryptedBytes;
}
private Image ResizeFTPImage(Image img, int width, int height)
{
var bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp))
{
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(img, 0, 0, width, height);
}
img.Dispose();
return bmp;
}
// private Image ResizeFTPImage(Image img, int width, int height)
// {
// var bmp = new Bitmap(width, height);
// using (Graphics g = Graphics.FromImage(bmp))
// {
// g.CompositingQuality = CompositingQuality.HighQuality;
// g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// g.SmoothingMode = SmoothingMode.HighQuality;
// g.DrawImage(img, 0, 0, width, height);
// }
// img.Dispose();
// return bmp;
// }
// public async Task<
// List<(string FileName, string? Base64, string? Error)>
......
......@@ -131,17 +131,30 @@ app.UseEndpoints(endpoints =>
// });
// });
var appSettings = builder.Configuration
.GetSection("AppSettings")
.Get<AppSettings>();
if (app.Environment.IsDevelopment())
{
app.Run("http://localhost:5604");
//app.Run(appSettings.listeningPort);
}
else
{
//app.Run(); //For Test Site
//app.Run("http://*:4708"); // For Production
app.Run("http://*:4709"); // krishna
if (OperatingSystem.IsWindows())
{
//Console.WriteLine("Running on Windows.");
app.Run();
//app.Run("http://*:4708"); // For Production
//app.Run("http://*:4709"); // For Admin
//app.Run(appSettings.listeningPort);
}
else if (OperatingSystem.IsLinux())
{
//app.Run("http://0.0.0.0:4709"); ///for linux
app.Run(appSettings.listeningPort);
}
}
......@@ -503,11 +503,11 @@ namespace FTP_Services.Services
public List<object>? ConfigValues(int CompanyId)
{
string FFDatabaseName = GetDatabaseNameFromConnectionString(_appSettings.ConnectionString);
string DatabaseName = GetDatabaseNameFromConnectionString(_appSettings.ConnectionString);
string AdminDatabaseName = GetDatabaseNameFromConnectionString(_appSettings.AdminConnectionString);
string MRDDatabaseName = GetDatabaseNameFromConnectionString(_appSettings.ConnectionString_MRD);
String StrDatabases = "FFDatabaseName : " + FFDatabaseName + " , AdminDatabaseName: " + AdminDatabaseName + ", MRDDatabaseName :" + MRDDatabaseName + ";";
String StrDatabases = "DatabaseName : " + DatabaseName + " , AdminDatabaseName: " + AdminDatabaseName + ", MRDDatabaseName :" + MRDDatabaseName + ";";
List<object>? ConfigValuesData = null;
try
......
{
"AppSettings": {
"Secret": "A78E-F7FA-B0FD-DAA45BB866CD-AA73D560-DACC-978C-4A9B-9924-5DE7E33F0040-GCD00",
"ConnectionString": "SERVER=10.11.12.158;PORT=5432;UID=himsdbuser;PWD=dbuser@hims123!;Database=FF_Backup_02032026;Timeout=1000",
"ConnectionString": "Server=10.11.12.107;User id=curidbuser;password=curidbuser@0987!;Database=CURI_LIVE;Port=5432;MaxPoolSize=1000;Pooling=true;",
"AdminConnectionString": "SERVER=10.11.12.106;PORT=5432;UID=himsdbuser;PWD=dbuser@hims123!;database=CareaxesAdmin;Timeout=1000",
"ConnectionString_MRD": "SERVER=10.11.12.158;PORT=5432;UID=himsdbuser;PWD=dbuser@hims123!;Database=FF_Backup_MRD;Timeout=1000",
"listeningPort": "http://0.0.0.0:4710",
"FTPConfiguration": {
"Username": "admin",
"Password": "Fmh@xp@rt01",
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment