-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTelegramClientFactory.cs
More file actions
62 lines (51 loc) · 1.39 KB
/
Copy pathTelegramClientFactory.cs
File metadata and controls
62 lines (51 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using TL;
using WTelegram;
namespace a2g.TelegramStickerViewer;
public sealed class TelegramClientFactory
{
private readonly IConfiguration _config;
private readonly SemaphoreSlim _lock = new(1, 1);
private Client? _client;
private User? _me;
public TelegramClientFactory(IConfiguration config)
{
_config = config;
}
public async Task<Client> GetClientAsync(CancellationToken ct)
{
if (_client is not null)
return _client;
await _lock.WaitAsync(ct);
try
{
if (_client is not null)
return _client;
_client = new Client(Config);
await _client.ConnectAsync();
return _client;
}
finally
{
_lock.Release();
}
}
public async Task<User> LoginIfNeededAsync(CancellationToken ct)
{
if (_me is not null)
return _me;
var client = await GetClientAsync(ct);
_me = await client.LoginUserIfNeeded();
return _me;
}
private string? Config(string what)
{
return what switch
{
"api_id" => _config["Telegram:ApiId"],
"api_hash" => _config["Telegram:ApiHash"],
"phone_number" => _config["Telegram:PhoneNumber"],
"session_pathname" => _config["Telegram:SessionPath"],
_ => null
};
}
}