-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathIP2RegionService.cs
More file actions
74 lines (65 loc) · 2.36 KB
/
IP2RegionService.cs
File metadata and controls
74 lines (65 loc) · 2.36 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
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Website: https://www.blazor.zone or https://argozhang.github.io/
using IP2Region.Net.XDB;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace BootstrapBlazor.Components;
/// <summary>
/// 默认 IP2Region 实现
/// </summary>
class IP2RegionService : DefaultIpLocatorProvider
{
/// <summary>
/// <inheritdoc/>
/// </summary>
/// <param name="options"></param>
/// <param name="ipRegionOptions"></param>
/// <param name="logger"></param>
public IP2RegionService(IOptions<BootstrapBlazorOptions> options, IOptions<IP2RegionOptions> ipRegionOptions, ILogger<IP2RegionService> logger) : base(options)
{
_options = options;
_ipOptions = ipRegionOptions;
_logger = logger;
Task.Run(InitSearch, CancellationToken.None).ConfigureAwait(false);
}
private readonly IOptions<BootstrapBlazorOptions> _options;
private readonly IOptions<IP2RegionOptions> _ipOptions;
private readonly ILogger<IP2RegionService> _logger;
private readonly TaskCompletionSource _tcs = new();
private Searcher? _search;
/// <summary>
/// <inheritdoc/>
/// </summary>
/// <param name="ip"></param>
protected override async Task<string?> LocateByIp(string ip)
{
await _tcs.Task;
string? result = null;
if (_search != null && _options.Value.WebClientOptions.EnableIpLocator)
{
result = _search.Search(ip);
}
return result;
}
private void InitSearch()
{
var xdbPath = _ipOptions.Value.XdbPath ?? Path.Combine(AppContext.BaseDirectory, "ip2region", "ip2region.xdb");
if (!File.Exists(xdbPath))
{
_logger.LogWarning("IP2Region xdb file not found, please check the file path: {dbPath}", xdbPath);
return;
}
try
{
_search = new Searcher(CachePolicy.Content, xdbPath);
_logger.LogInformation("IP2Region xdb file {dbPath} loaded", xdbPath);
_tcs.TrySetResult();
}
catch (Exception ex)
{
_tcs.TrySetException(ex);
_logger.LogError(ex, "IP2Region xdb file path: {dbPath}", xdbPath);
}
}
}