Skip to content

Commit aff0e87

Browse files
authored
Merge pull request #12 from RobsonTrasel/feature/dns-mongo-save
Refatoração - Substituição de Arquivos JSON por Armazenamento no MongoDB
2 parents 297658f + a5f1341 commit aff0e87

File tree

10 files changed

+105
-69
lines changed

10 files changed

+105
-69
lines changed

Infrastructure/Infrastructure.csproj

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,9 @@
1414
<Folder Include="Services\" />
1515
<Folder Include="Services\Interfaces\" />
1616
</ItemGroup>
17+
<ItemGroup>
18+
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
19+
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.2" />
20+
<PackageReference Include="MongoDB.Driver" Version="2.19.0" />
21+
</ItemGroup>
1722
</Project>
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
using MongoDB.Bson;
2+
3+
namespace Infrastructure.Repositories.Interfaces;
4+
5+
public interface IMongoDbRepository
6+
{
7+
Task InsertDocumentAsync(BsonDocument document);
8+
Task<List<BsonDocument>> GetAllDocumentsAsync();
9+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
using Infrastructure.Repositories.Interfaces;
2+
using Microsoft.Extensions.Configuration;
3+
using MongoDB.Bson;
4+
using MongoDB.Driver;
5+
namespace Infrastructure.Repositories;
6+
7+
public class MongoDbRepository : IMongoDbRepository
8+
{
9+
private readonly IMongoCollection<BsonDocument> _collection;
10+
11+
public MongoDbRepository(IConfiguration configuration)
12+
{
13+
var connectionString = configuration.GetSection("MongoDB:ConnectionString").Value;
14+
var databaseName = configuration.GetSection("MongoDB:DatabaseName").Value;
15+
var collectionName = configuration.GetSection("MongoDB:CollectionName").Value;
16+
var client = new MongoClient(connectionString);
17+
var database = client.GetDatabase(databaseName);
18+
_collection = database.GetCollection<BsonDocument>(collectionName);
19+
}
20+
21+
public async Task InsertDocumentAsync(BsonDocument document)
22+
{
23+
await _collection.InsertOneAsync(document);
24+
}
25+
26+
public async Task<List<BsonDocument>> GetAllDocumentsAsync()
27+
{
28+
return await _collection.Find(new BsonDocument()).ToListAsync();
29+
}
30+
}

bet-blocker/.env-exemple

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
MONGO_CONNECTION_STRING=
2+
MONGO_DATABASE_NAME=
3+
MONGO_COLLECTION_NAME=

bet-blocker/Business/BetBusiness.cs

Lines changed: 17 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
using System.Collections.Concurrent;
22
using bet_blocker.Business.Interfaces;
3+
using Infrastructure.Repositories.Interfaces;
4+
using MongoDB.Bson;
5+
using System.Collections.Concurrent;
36
using Infrastructure.Services.Interfaces;
47
using System.Text.Json;
58
using static bet_blocker.DTOs.ResponseHostDto;
@@ -11,58 +14,42 @@ namespace bet_blocker.Business
1114
public class BetBusiness : IBetBusiness
1215
{
1316
private readonly ICaller _caller;
17+
private readonly IMongoDbRepository _mongoDbRepository;
1418
private readonly string _endpoint;
15-
private readonly string _storagePath;
1619
private static readonly object LockObject = new object();
1720

18-
public BetBusiness(ICaller caller, IConfiguration configuration)
21+
public BetBusiness(ICaller caller, IMongoDbRepository mongoDbRepository, IConfiguration configuration)
1922
{
2023
_caller = caller;
24+
_mongoDbRepository = mongoDbRepository;
2125
_endpoint = configuration.GetSection("blockList").Value;
22-
_storagePath = configuration.GetSection("StoragePath").Value;
23-
24-
if (!Directory.Exists(_storagePath))
25-
{
26-
Directory.CreateDirectory(_storagePath);
27-
}
2826
}
2927

3028
public void StartResolutionProcess(CancellationToken cancellationToken)
3129
{
3230
lock (LockObject)
3331
{
3432
var currentDate = DateTime.UtcNow.ToString("dd-MM-yyyy");
35-
var filePath = Path.Combine(_storagePath, $"{currentDate}.json");
36-
37-
if (File.Exists(filePath))
33+
var existingDocuments = _mongoDbRepository.GetAllDocumentsAsync().Result;
34+
if (existingDocuments.Any(doc => doc["Date"] == currentDate))
3835
{
3936
throw new InvalidOperationException("A resolução de DNS já foi gerada para hoje. Tente novamente amanhã.");
4037
}
4138
}
42-
4339
_ = Task.Run(async () =>
4440
{
4541
try
4642
{
4743
var resolvedHosts = await GetList(cancellationToken);
4844
var currentDate = DateTime.UtcNow.ToString("dd-MM-yyyy");
49-
50-
var filePath = Path.Combine(_storagePath, $"{currentDate}.json");
51-
52-
var json = JsonSerializer.Serialize(new
45+
var document = new BsonDocument
5346
{
54-
Date = currentDate,
55-
ResolvedHosts = resolvedHosts
56-
}, new JsonSerializerOptions { WriteIndented = true });
47+
{ "Date", currentDate },
48+
{ "ResolvedHosts", new BsonArray(resolvedHosts.Select(host => host.ToBsonDocument())) }
5749

58-
File.WriteAllText(filePath, json);
59-
60-
if (!Directory.Exists(_storagePath))
61-
{
62-
Directory.CreateDirectory(_storagePath);
63-
}
50+
};
6451

65-
File.WriteAllText(filePath, json);
52+
await _mongoDbRepository.InsertDocumentAsync(document);
6653
}
6754
catch (Exception ex)
6855
{
@@ -152,13 +139,12 @@ private static async Task<ResponseHostsDTO> ResolveDomainInfo(string domain)
152139
public object GetResolutionStatus()
153140
{
154141
var currentDate = DateTime.UtcNow.ToString("dd-MM-yyyy");
155-
var filePath = Path.Combine(_storagePath, $"{currentDate}.json");
142+
var documents = _mongoDbRepository.GetAllDocumentsAsync().Result;
156143

157-
if (File.Exists(filePath))
144+
var currentDocument = documents.FirstOrDefault(doc => doc["Date"] == currentDate);
145+
if (currentDocument != null)
158146
{
159-
var json = File.ReadAllText(filePath);
160-
var result = JsonSerializer.Deserialize<object>(json);
161-
return result;
147+
return currentDocument;
162148
}
163149

164150
return "Nenhum processo iniciado ou resolução não encontrada para hoje.";

bet-blocker/Controllers/APIManagerController.cs

Lines changed: 11 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using bet_blocker.Business.Interfaces;
22
using Microsoft.AspNetCore.Mvc;
3+
using MongoDB.Bson;
34

45
namespace bet_blocker.Controllers
56
{
@@ -51,36 +52,26 @@ public IActionResult GetResolutionStatus()
5152
}
5253

5354
[HttpGet("dns")]
54-
public IActionResult GetDnsResolution([FromQuery]string? date = null)
55+
public async Task<IActionResult> GetDnsResolution([FromQuery] string? date = null)
5556
{
5657
try
5758
{
58-
string filePath;
59+
var currentDate = date ?? DateTime.UtcNow.ToString("dd-MM-yyyy");
60+
var documents = _betBusiness.GetResolutionStatus();
5961

60-
if (!string.IsNullOrEmpty(date))
62+
if (documents is MongoDB.Bson.BsonDocument bsonDocument)
6163
{
62-
filePath = Path.Combine(_storagePath, $"{date}.json");
64+
var jsonResult = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<object>(bsonDocument.ToJson());
65+
return Ok(jsonResult);
6366
}
64-
else
65-
{
66-
filePath = Directory.GetFiles(_storagePath, "*.json")
67-
.OrderByDescending(f => System.IO.File.GetCreationTimeUtc(f))
68-
.FirstOrDefault() ?? string.Empty;
69-
}
70-
71-
if (System.IO.File.Exists(filePath))
72-
{
73-
var jsonContent = System.IO.File.ReadAllText(filePath);
74-
var jsonObject = System.Text.Json.JsonSerializer.Deserialize<object>(jsonContent);
7567

76-
return Ok(jsonObject);
77-
}
78-
79-
return NotFound(new { message = "Arquivo não encontrado." });
80-
} catch (Exception ex)
68+
return NotFound(new { message = "Nenhum dado encontrado para a data solicitada." });
69+
}
70+
catch (Exception ex)
8171
{
8272
return StatusCode(500, new { message = "Erro interno ao processar a solicitação.", details = ex.Message });
8373
}
8474
}
75+
8576
}
8677
}

bet-blocker/DependencyInjection/ServicesDi.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
using bet_blocker.Business;
22
using bet_blocker.Business.Interfaces;
3+
using Infrastructure.Repositories;
4+
using Infrastructure.Repositories.Interfaces;
35
using Infrastructure.Services;
46
using Infrastructure.Services.Interfaces;
57

@@ -11,6 +13,7 @@ public static void ConfigureServices(IServiceCollection services)
1113
{
1214
services.AddHttpClient<ICaller, Caller>();
1315
services.AddTransient<IBetBusiness, BetBusiness>();
16+
services.AddSingleton<IMongoDbRepository, MongoDbRepository>();
1417
}
1518
}
1619
}

bet-blocker/Program.cs

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,23 @@
1-
using bet_blocker.DependencyInjection;
2-
using bet_blocker.Extensions;
3-
using Serilog;
4-
1+
using bet_blocker.DependencyInjection;
2+
using bet_blocker.Extensions;
3+
using Serilog;
4+
using DotNetEnv;
5+
56
var builder = WebApplication.CreateBuilder(args);
67

7-
var logger = new LoggerConfiguration()
8-
.MinimumLevel.Debug()
9-
.WriteTo.Console()
10-
.WriteTo.File("log.txt", rollingInterval: RollingInterval.Day)
11-
.CreateLogger();
12-
13-
builder.Services.AddMemoryCache();
8+
DotNetEnv.Env.Load(".env");
9+
10+
var logger = new LoggerConfiguration()
11+
.MinimumLevel.Debug()
12+
.WriteTo.Console()
13+
.WriteTo.File("log.txt", rollingInterval: RollingInterval.Day)
14+
.CreateLogger();
15+
16+
builder.Services.AddMemoryCache();
1417

1518
builder.Services.AddControllers();
1619
builder.Services.AddEndpointsApiExplorer();
17-
builder.Services.AddSwaggerGen();
20+
builder.Services.AddSwaggerGen();
1821
builder.Logging.AddSerilog(logger);
1922

2023
ServicesDi.ConfigureServices(builder.Services);
@@ -27,12 +30,12 @@
2730
app.UseSwaggerUI();
2831
}
2932

30-
app.UseProblemDetailsExceptionHandler(LoggerFactory.Create(builder => builder.AddSerilog(logger)));
33+
app.UseProblemDetailsExceptionHandler(LoggerFactory.Create(builder => builder.AddSerilog(logger)));
3134

32-
app.UseCors(x => x
33-
.AllowAnyMethod()
34-
.AllowAnyHeader()
35-
.SetIsOriginAllowed(origin => true)
35+
app.UseCors(x => x
36+
.AllowAnyMethod()
37+
.AllowAnyHeader()
38+
.SetIsOriginAllowed(origin => true)
3639
.AllowCredentials());
3740

3841
app.UseHttpsRedirection();

bet-blocker/appsettings.json

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,10 @@
77
},
88
"AllowedHosts": "*",
99
"blockList": "https://raw.githubusercontent.com/bet-blocker/bet-blocker/main/blocklist.txt",
10-
"StoragePath": "json"
10+
"StoragePath": "json",
11+
"MongoDB": {
12+
"ConnectionString": "mongodb+srv://robson:dZRnXM336BENYfjK@bet-blocker-db.itdd5.mongodb.net/?retryWrites=true&w=majority&appName=bet-blocker-db",
13+
"DatabaseName": "bet_blocker",
14+
"CollectionName": "dns_resolutions"
15+
}
1116
}

bet-blocker/bet-blocker.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
<PropertyGroup Condition=" '$(RunConfiguration)' == 'https' " />
1111
<PropertyGroup Condition=" '$(RunConfiguration)' == 'http' " />
1212
<ItemGroup>
13+
<PackageReference Include="DotNetEnv" Version="3.1.1" />
1314
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.15" />
1415
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
1516
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />

0 commit comments

Comments
 (0)