Skip to content

Commit 6b002a7

Browse files
committed
feat: add setup configuration
1 parent 33b32ef commit 6b002a7

14 files changed

Lines changed: 1323 additions & 35 deletions
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"api_id": "62071",
3+
"hash_id": "2204b5c6075aeb2e1cdc81e68e2f9256",
4+
"mongo_connection_string": "mongodb://mateo:mateoMongo@192.168.0.22:27017",
5+
"avoid_checking_certificate": true
6+
}

TelegramDownloader/Data/ITelegramService.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ namespace TelegramDownloader.Data
77
{
88
public interface ITelegramService
99
{
10+
bool IsConfigured { get; }
11+
void InitializeClient();
1012
Task<string> checkAuth(string number, bool isPhone = false);
1113
Task<User> GetUser();
1214
bool checkChannelExist(string id);

TelegramDownloader/Data/TelegramService.cs

Lines changed: 71 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,73 @@ public TelegramService(TransactionInfoService tis, IDbService db, ILogger<IFileS
4545
_persistence = persistence;
4646
// createDownloadFolder();
4747
mut.WaitOne();
48-
if (client == null)
48+
try
4949
{
50-
newClient();
50+
if (client == null && HasValidCredentials())
51+
{
52+
newClient();
53+
}
54+
else if (!HasValidCredentials())
55+
{
56+
_logger.LogWarning("TelegramService: Credentials not configured - setup required");
57+
}
58+
}
59+
catch (Exception ex)
60+
{
61+
_logger.LogWarning(ex, "TelegramService: Could not initialize client - setup may be required");
62+
}
63+
finally
64+
{
65+
mut.ReleaseMutex();
66+
}
67+
}
68+
69+
private static bool HasValidCredentials()
70+
{
71+
var apiId = GeneralConfigStatic.tlconfig?.api_id ?? Environment.GetEnvironmentVariable("api_id");
72+
var apiHash = GeneralConfigStatic.tlconfig?.hash_id ?? Environment.GetEnvironmentVariable("hash_id");
73+
return !string.IsNullOrWhiteSpace(apiId) && !string.IsNullOrWhiteSpace(apiHash);
74+
}
75+
76+
public bool IsConfigured => HasValidCredentials() && client != null;
77+
78+
/// <summary>
79+
/// Initializes or reinitializes the Telegram client.
80+
/// Call this after setup is complete to create the client with new credentials.
81+
/// </summary>
82+
public void InitializeClient()
83+
{
84+
if (client != null)
85+
{
86+
_logger.LogInformation("Client already initialized");
87+
return;
88+
}
89+
90+
if (!HasValidCredentials())
91+
{
92+
_logger.LogWarning("Cannot initialize client - credentials not configured");
93+
return;
5194
}
5295

53-
mut.ReleaseMutex();
96+
mut.WaitOne();
97+
try
98+
{
99+
if (client == null) // Double-check after acquiring lock
100+
{
101+
_logger.LogInformation("Initializing Telegram client after setup");
102+
newClient();
103+
_logger.LogInformation("Telegram client initialized successfully");
104+
}
105+
}
106+
catch (Exception ex)
107+
{
108+
_logger.LogError(ex, "Failed to initialize Telegram client: {Message}", ex.Message);
109+
throw;
110+
}
111+
finally
112+
{
113+
mut.ReleaseMutex();
114+
}
54115
}
55116

56117
private void createDownloadFolder()
@@ -156,6 +217,13 @@ public bool checkChannelExist(string id)
156217

157218
public async Task<string> checkAuth(string number, bool isPhone = false)
158219
{
220+
// Return early if client is not initialized (setup required)
221+
if (client == null)
222+
{
223+
_logger.LogWarning("checkAuth called but client is null - setup required");
224+
return "setup_required";
225+
}
226+
159227
_logger.LogInformation("Checking authentication - IsPhone: {IsPhone}", isPhone);
160228
if (client.UserId != null && number == null)
161229
{

TelegramDownloader/Data/db/DbService.cs

Lines changed: 61 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,67 @@ public class DbService : IDbService
2727
public DbService(ILogger<DbService> logger)
2828
{
2929
_logger = logger;
30-
client = new MongoClient(GeneralConfigStatic.tlconfig?.mongo_connection_string ?? Environment.GetEnvironmentVariable("connectionString"));
31-
currentDatabase = getDatabase("default");
32-
this.dbName = "default";
33-
_logger.LogInformation("DbService initialized - Connected to MongoDB");
30+
var connectionString = GeneralConfigStatic.tlconfig?.mongo_connection_string
31+
?? Environment.GetEnvironmentVariable("connectionString");
32+
33+
if (string.IsNullOrWhiteSpace(connectionString))
34+
{
35+
_logger.LogWarning("DbService: MongoDB connection string not configured - setup required");
36+
// Use a default that will fail gracefully when actually used
37+
connectionString = "mongodb://localhost:27017";
38+
}
39+
40+
try
41+
{
42+
var settings = MongoClientSettings.FromConnectionString(connectionString);
43+
settings.ServerSelectionTimeout = TimeSpan.FromSeconds(5);
44+
settings.ConnectTimeout = TimeSpan.FromSeconds(5);
45+
client = new MongoClient(settings);
46+
currentDatabase = getDatabase("default");
47+
this.dbName = "default";
48+
_logger.LogInformation("DbService initialized - Connected to MongoDB");
49+
}
50+
catch (Exception ex)
51+
{
52+
_logger.LogWarning(ex, "DbService: Could not connect to MongoDB - setup may be required");
53+
// Create client anyway for later use after setup
54+
client = new MongoClient(connectionString);
55+
currentDatabase = client.GetDatabase("default");
56+
this.dbName = "default";
57+
}
58+
}
59+
60+
/// <summary>
61+
/// Reinitializes the MongoDB connection with a new connection string.
62+
/// Call this after setup when the connection string has been configured.
63+
/// </summary>
64+
public void ReinitializeConnection(string connectionString)
65+
{
66+
if (string.IsNullOrWhiteSpace(connectionString))
67+
{
68+
_logger.LogWarning("ReinitializeConnection: Connection string is empty");
69+
return;
70+
}
71+
72+
try
73+
{
74+
_logger.LogInformation("Reinitializing MongoDB connection...");
75+
var settings = MongoClientSettings.FromConnectionString(connectionString);
76+
settings.ServerSelectionTimeout = TimeSpan.FromSeconds(5);
77+
settings.ConnectTimeout = TimeSpan.FromSeconds(5);
78+
79+
// Create new client with updated connection string
80+
client = new MongoClient(settings);
81+
currentDatabase = getDatabase("default");
82+
this.dbName = "default";
83+
84+
_logger.LogInformation("DbService reinitialized - Connected to MongoDB with new connection string");
85+
}
86+
catch (Exception ex)
87+
{
88+
_logger.LogError(ex, "Failed to reinitialize MongoDB connection: {Message}", ex.Message);
89+
throw;
90+
}
3491
}
3592

3693
public async Task<IClientSessionHandle> getSession()

TelegramDownloader/Data/db/IDbService.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ namespace TelegramDownloader.Data.db
77
{
88
public interface IDbService
99
{
10+
void ReinitializeConnection(string connectionString);
1011
Task<IClientSessionHandle> getSession();
1112
Task<BsonSharedInfoModel> InsertSharedInfo(BsonSharedInfoModel sim, string dbName = DbService.SHARED_DB_NAME, string collection = "info");
1213
Task<List<BsonSharedInfoModel>> getSharedInfoList(string dbName = DbService.SHARED_DB_NAME, string collection = "info", string? filter = null);

TelegramDownloader/Pages/Index.razor

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
@using QRCoder
77
@using TelegramDownloader.Data
88
@using TelegramDownloader.Models
9+
@using TelegramDownloader.Services
910
@inject ITelegramService ts
11+
@inject ISetupService SetupService
1012
@inject NavigationManager NavManager
1113
@inject IJSRuntime JSRuntime;
1214
@inject PreloadService preloadService
@@ -163,8 +165,40 @@
163165
{
164166
try
165167
{
168+
// Check if setup is complete using async method
169+
var status = await SetupService.GetSetupStatusAsync();
170+
if (status.CurrentStep != SetupStep.Complete)
171+
{
172+
NavManager.NavigateTo("/setup", forceLoad: true);
173+
return;
174+
}
175+
176+
// If Telegram client is not configured, try to initialize it
177+
if (!ts.IsConfigured)
178+
{
179+
try
180+
{
181+
ts.InitializeClient();
182+
}
183+
catch (Exception ex)
184+
{
185+
// If initialization fails, redirect to setup
186+
Console.WriteLine($"Failed to initialize Telegram client: {ex.Message}");
187+
NavManager.NavigateTo("/setup", forceLoad: true);
188+
return;
189+
}
190+
}
191+
166192
Model ??= new();
167193
Model.type = await ts.checkAuth(Model.value);
194+
195+
// Handle setup_required response - only redirect if actually not configured
196+
if (Model.type == "setup_required" && !ts.IsConfigured)
197+
{
198+
NavManager.NavigateTo("/setup", forceLoad: true);
199+
return;
200+
}
201+
168202
StateHasChanged();
169203
await isLogin();
170204
}

0 commit comments

Comments
 (0)