-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdBlocker.cs
77 lines (64 loc) · 2.38 KB
/
AdBlocker.cs
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
75
76
77
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms; // Required for MessageBox
public class AdBlocker : IDisposable
{
private HashSet<string> blockedDomains;
public AdBlocker()
{
string blockListFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "siteblockerlist.txt");
if (string.IsNullOrWhiteSpace(blockListFilePath) || !File.Exists(blockListFilePath))
{
throw new FileNotFoundException("Ad blocker list file not found or invalid path.");
}
blockedDomains = ReadBlockedDomainsFromFile(blockListFilePath);
}
private HashSet<string> ReadBlockedDomainsFromFile(string filePath)
{
HashSet<string> domains = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
try
{
string[] lines = File.ReadAllLines(filePath);
foreach (string line in lines)
{
string domain = line.Trim();
if (!string.IsNullOrWhiteSpace(domain))
{
domains.Add(domain);
}
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"Error reading blocked domains file: {ex.Message}");
throw; // Rethrow to indicate a critical error
}
catch (Exception ex)
{
Console.WriteLine($"Error reading blocked domains file: {ex.Message}");
}
return domains;
}
public bool ShouldBlockRequest(string url)
{
if (!string.IsNullOrEmpty(url) && Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
{
string domain = uri.Host;
if (blockedDomains.Contains(domain))
{
DisplayBlockedMessage(domain);
return true;
}
}
return false;
}
private void DisplayBlockedMessage(string blockedDomain)
{
MessageBox.Show($"Access to the site '{blockedDomain}' has been blocked because it has been identified as potentially harmful or malicious. Please ensure your safety by not attempting to bypass this restriction.", "Blocked Site", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
public void Dispose()
{
// You may add cleanup logic here if needed
}
}