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 @@ ...@@ -18,6 +18,8 @@
<PackageReference Include="prometheus-net" Version="5.0.2" /> <PackageReference Include="prometheus-net" Version="5.0.2" />
<PackageReference Include="prometheus-net.AspNetCore" Version="5.0.2" /> <PackageReference Include="prometheus-net.AspNetCore" Version="5.0.2" />
<PackageReference Include="prometheus-net.SystemMetrics" Version="2.0.0" /> <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="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.0" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.15.0" /> <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.15.0" />
......
...@@ -6,6 +6,7 @@ namespace FTP_Services.Core.Models ...@@ -6,6 +6,7 @@ namespace FTP_Services.Core.Models
public string AdminConnectionString { get; set; } public string AdminConnectionString { get; set; }
public string ConnectionString_MRD { get; set; } public string ConnectionString_MRD { get; set; }
public string Secret { get; set; } public string Secret { get; set; }
public string listeningPort {get; set;}
public AppSettings() public AppSettings()
{ {
...@@ -13,6 +14,7 @@ namespace FTP_Services.Core.Models ...@@ -13,6 +14,7 @@ namespace FTP_Services.Core.Models
ConnectionString = ""; ConnectionString = "";
AdminConnectionString = ""; AdminConnectionString = "";
ConnectionString_MRD = ""; ConnectionString_MRD = "";
listeningPort="";
} }
public FTPConfiguration FTPConfiguration { get; set; } public FTPConfiguration FTPConfiguration { get; set; }
......
...@@ -366,5 +366,7 @@ namespace FTP_Services.Core.Models ...@@ -366,5 +366,7 @@ namespace FTP_Services.Core.Models
public string? RemotePassword { get; set; } public string? RemotePassword { get; set; }
public int RemotePort { get; set; } public int RemotePort { get; set; }
public string? WebRemotePath { get; set; } public string? WebRemotePath { get; set; }
public int? Type { get; set; }
public bool? IsSFTP { get; set; }
} }
} }
// Services/FtpService.cs // Services/FtpService.cs
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Diagnostics; using System.Diagnostics;
using System.Drawing; // using System.Drawing;
using System.Drawing.Drawing2D; // using System.Drawing.Drawing2D;
using System.Drawing.Imaging; // using System.Drawing.Imaging;
using System.Net; using System.Net;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using FluentFTP; using FluentFTP;
using FTP_Services.Core.Models; using FTP_Services.Core.Models;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using Renci.SshNet;
public class FluentFtpService public class FluentFtpService
{ {
...@@ -36,11 +40,12 @@ public class FluentFtpService ...@@ -36,11 +40,12 @@ public class FluentFtpService
$"/{payload.WebRemotePath.TrimEnd('/')}/{payload.FolderPath.TrimStart('/')}"; $"/{payload.WebRemotePath.TrimEnd('/')}/{payload.FolderPath.TrimStart('/')}";
string fullLocalPath = Path.Combine(localTempDir, Guid.NewGuid().ToString()); string fullLocalPath = Path.Combine(localTempDir, Guid.NewGuid().ToString());
_log($"fullLocalPath : {fullLocalPath}");
try try
{ {
if (Directory.Exists(localTempDir)) if (Directory.Exists(localTempDir))
{ {
_log($"localTempDir is Exist : {localTempDir}");
Directory.Delete(localTempDir, recursive: true); Directory.Delete(localTempDir, recursive: true);
Directory.CreateDirectory(localTempDir); Directory.CreateDirectory(localTempDir);
} }
...@@ -74,6 +79,7 @@ public class FluentFtpService ...@@ -74,6 +79,7 @@ public class FluentFtpService
try try
{ {
await ftpClient.Connect(); await ftpClient.Connect();
_log($"Connected to FTP: {payload.RemoteHost}"); _log($"Connected to FTP: {payload.RemoteHost}");
...@@ -92,6 +98,7 @@ public class FluentFtpService ...@@ -92,6 +98,7 @@ public class FluentFtpService
processStart = DateTime.Now; processStart = DateTime.Now;
_log($"Processing started at {processStart:HH:mm:ss}"); _log($"Processing started at {processStart:HH:mm:ss}");
string encryptionKey = "12345678909876543210123456789098"; string encryptionKey = "12345678909876543210123456789098";
foreach (var fileName in payload.FilePaths) foreach (var fileName in payload.FilePaths)
{ {
string localFilePath = Path.Combine(fullLocalPath, fileName); string localFilePath = Path.Combine(fullLocalPath, fileName);
...@@ -105,13 +112,20 @@ public class FluentFtpService ...@@ -105,13 +112,20 @@ public class FluentFtpService
{ {
byte[] encryptedData = await System.IO.File.ReadAllBytesAsync(localFilePath); byte[] encryptedData = await System.IO.File.ReadAllBytesAsync(localFilePath);
byte[] decryptedBytes = DecryptFTPFile(encryptedData, encryptionKey); byte[] decryptedBytes = DecryptFTPFile(encryptedData, encryptionKey);
using var msDecrypted = new MemoryStream(decryptedBytes); //using var msDecrypted = new MemoryStream(decryptedBytes);
using var originalImage = Image.FromStream(msDecrypted); // using var originalImage = Image.FromStream(msDecrypted);
using var resizedImage = ResizeFTPImage(originalImage, Width, Height); // 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(); using var ms = new MemoryStream();
resizedImage.Save(msResized, ImageFormat.Jpeg); image.SaveAsJpeg(ms);
string base64 = Convert.ToBase64String(msResized.ToArray());
string base64 = Convert.ToBase64String(ms.ToArray());
// byte[] fileBytes = await File.ReadAllBytesAsync(localFilePath); // byte[] fileBytes = await File.ReadAllBytesAsync(localFilePath);
// string base64 = Convert.ToBase64String(fileBytes); // string base64 = Convert.ToBase64String(fileBytes);
...@@ -152,156 +166,252 @@ public class FluentFtpService ...@@ -152,156 +166,252 @@ public class FluentFtpService
return results; 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, FTPDocumentResponseModel payload,
string localTempDir, string localTempDir,
int height, int height,
int width int width)
)
{ {
var results = new List<(string FileName, string? Base64, string? Error)>(); var results = new List<(string FileName, string? Base64, string? Error)>();
string remoteFolderPath = 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 try
{ {
// Recreate temp directory
if (Directory.Exists(localTempDir)) if (Directory.Exists(localTempDir))
{ {
Directory.Delete(localTempDir, recursive: true); Directory.Delete(localTempDir, true);
Directory.CreateDirectory(localTempDir);
} }
}
catch (Exception ex)
{
_log($"Failed to delete temp folder: {ex.Message}");
}
const string encryptionKey = "12345678909876543210123456789098"; Directory.CreateDirectory(localTempDir);
using var ftpClient = new AsyncFtpClient( var overallStart = DateTime.Now;
host: payload.RemoteHost, _log($"===== FileService START [{overallStart:yyyy-MM-dd HH:mm:ss}] =====");
port: payload.RemotePort,
credentials: new NetworkCredential(payload.RemoteUser, payload.RemotePassword)
)
{
Config = { DataConnectionType = FtpDataConnectionType.AutoPassive }
};
var overallStart = DateTime.Now; #region Connect
_log($"===== FtpService START [{overallStart:yyyy-MM-dd HH:mm:ss}] =====");
try if (payload.IsSFTP != true)
{ {
await ftpClient.Connect(); ftpClient = new AsyncFtpClient(
_log($"Connected to FTP server: {payload.RemoteHost}:{payload.RemotePort}"); 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; var downloadStart = DateTime.Now;
_log($"Download started at {downloadStart:HH:mm:ss}");
foreach (var fileName in payload.FilePaths) foreach (var fileName in payload.FilePaths)
{ {
string remoteFilePath = $"{remoteFolderPath}/{fileName}"; string remoteFilePath =
string localFilePath = Path.Combine(localTempDir, fileName); $"{remoteFolderPath.TrimEnd('/')}/{fileName}";
string localFilePath =
Path.Combine(localTempDir, fileName);
try try
{ {
var status = await ftpClient.DownloadFile( _log($"Downloading: {remoteFilePath}");
localFilePath,
remoteFilePath, if (payload.IsSFTP != true)
FtpLocalExists.Overwrite, {
FtpVerify.Retry var status = await ftpClient!.DownloadFile(
); localFilePath,
remoteFilePath,
if (status == FtpStatus.Failed) FtpLocalExists.Overwrite,
results.Add((fileName, null, "FTP download failed")); 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) 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 downloadEnd = DateTime.Now;
var downloadDuration = downloadEnd - downloadStart;
_log( _log(
$"Download ended at {downloadEnd:HH:mm:ss} " $"Download completed in {(downloadEnd - downloadStart).TotalSeconds:N0} seconds");
+ $"(Duration: {downloadDuration.Hours}h {downloadDuration.Minutes}m {downloadDuration.Seconds}s)"
);
var processStart = DateTime.Now; #endregion
_log($"Processing started at {processStart:HH:mm:ss}");
#region Convert To Base64
foreach (var fileName in payload.FilePaths) foreach (var fileName in payload.FilePaths)
{ {
string localFilePath = Path.Combine(localTempDir, fileName); string localFilePath =
Path.Combine(localTempDir, fileName);
if (!File.Exists(localFilePath)) if (!File.Exists(localFilePath))
{ {
results.Add((fileName, null, "File not found after download"));
continue; continue;
} }
try try
{ {
byte[] encryptedData = await File.ReadAllBytesAsync(localFilePath); byte[] fileBytes =
byte[] decryptedBytes = DecryptFTPFile(encryptedData, encryptionKey); await File.ReadAllBytesAsync(localFilePath);
using var msDecrypted = new MemoryStream(decryptedBytes); string extension =
using var originalImage = Image.FromStream(msDecrypted); Path.GetExtension(localFilePath)
using var resizedImage = ResizeFTPImage(originalImage, width, height); .ToLowerInvariant();
using var msResized = new MemoryStream(); // PDF
resizedImage.Save(msResized, ImageFormat.Jpeg); if (extension == ".pdf")
string base64 = Convert.ToBase64String(msResized.ToArray()); {
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) 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; #endregion
var processDuration = processEnd - processStart;
var overallEnd = DateTime.Now;
_log( _log(
$"Processing ended at {processEnd:HH:mm:ss} " $"===== FileService END [{overallEnd:yyyy-MM-dd HH:mm:ss}] =====");
+ $"(Duration: {processDuration.Hours}h {processDuration.Minutes}m {processDuration.Seconds}s)"
);
// await ftpClient.Disconnect(); return results;
} }
catch (Exception ex) catch (Exception ex)
{ {
results.Add(("Connection", null, $"FTP Connection failed: {ex.Message}")); _log($"Connection failed: {ex.Message}");
_log($"FTP Connection failed: {ex.Message}");
results.Add(
("Connection", null,
$"Connection failed: {ex.Message}"));
return results;
} }
finally finally
{ {
try try
{ {
await ftpClient.Disconnect(); if (ftpClient?.IsConnected == true)
_log("FTP client disconnected successfully."); {
await ftpClient.Disconnect();
_log("FTP disconnected.");
}
if (sftpClient?.IsConnected == true)
{
sftpClient.Disconnect();
_log("SFTP disconnected.");
}
} }
catch (Exception ex) 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) private byte[] DecryptFTPFile(byte[] encryptedData, string encryptionKey)
...@@ -334,19 +444,19 @@ public class FluentFtpService ...@@ -334,19 +444,19 @@ public class FluentFtpService
return decryptedBytes; return decryptedBytes;
} }
private Image ResizeFTPImage(Image img, int width, int height) // private Image ResizeFTPImage(Image img, int width, int height)
{ // {
var bmp = new Bitmap(width, height); // var bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp)) // using (Graphics g = Graphics.FromImage(bmp))
{ // {
g.CompositingQuality = CompositingQuality.HighQuality; // g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic; // g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.HighQuality; // g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(img, 0, 0, width, height); // g.DrawImage(img, 0, 0, width, height);
} // }
img.Dispose(); // img.Dispose();
return bmp; // return bmp;
} // }
// public async Task< // public async Task<
// List<(string FileName, string? Base64, string? Error)> // List<(string FileName, string? Base64, string? Error)>
......
...@@ -131,17 +131,30 @@ app.UseEndpoints(endpoints => ...@@ -131,17 +131,30 @@ app.UseEndpoints(endpoints =>
// }); // });
// }); // });
var appSettings = builder.Configuration
.GetSection("AppSettings")
.Get<AppSettings>();
if (app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment())
{ {
app.Run("http://localhost:5604"); app.Run("http://localhost:5604");
//app.Run(appSettings.listeningPort);
} }
else 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 ...@@ -503,11 +503,11 @@ namespace FTP_Services.Services
public List<object>? ConfigValues(int CompanyId) public List<object>? ConfigValues(int CompanyId)
{ {
string FFDatabaseName = GetDatabaseNameFromConnectionString(_appSettings.ConnectionString); string DatabaseName = GetDatabaseNameFromConnectionString(_appSettings.ConnectionString);
string AdminDatabaseName = GetDatabaseNameFromConnectionString(_appSettings.AdminConnectionString); string AdminDatabaseName = GetDatabaseNameFromConnectionString(_appSettings.AdminConnectionString);
string MRDDatabaseName = GetDatabaseNameFromConnectionString(_appSettings.ConnectionString_MRD); 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; List<object>? ConfigValuesData = null;
try try
......
{ {
"AppSettings": { "AppSettings": {
"Secret": "A78E-F7FA-B0FD-DAA45BB866CD-AA73D560-DACC-978C-4A9B-9924-5DE7E33F0040-GCD00", "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", "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", "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": { "FTPConfiguration": {
"Username": "admin", "Username": "admin",
"Password": "Fmh@xp@rt01", "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