Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Refactor

Daoud Clarke9bd43f8b629f
diff --git a/mwmbl/indexer/blacklist.py b/mwmbl/indexer/blacklist.py
index 13c6d7f..5aa9c36 100644
--- a/mwmbl/indexer/blacklist.py
+++ b/mwmbl/indexer/blacklist.py
@@ -1,58 +1,21 @@
-from datetime import timedelta
+"""
+Blacklist utilities for domain filtering.
-from mwmbl.hn_top_domains_filtered import DOMAINS
-from mwmbl.settings import BLACKLIST_DOMAINS_URL, EXCLUDED_DOMAINS, DOMAIN_BLACKLIST_REGEX
-from mwmbl.indexer.blacklist_providers import BlacklistProvider, URLBlacklistProvider, HaGeZiBlacklistProvider, CombinedBlacklistProvider
+This module provides utility functions for creating default blacklist providers.
+The main logic has been moved to blacklist_providers.py for better modularity.
+"""
-# Global provider instance that can be configured
-_blacklist_provider: BlacklistProvider = None
+from mwmbl.indexer.blacklist_providers import (
+ BuiltInRulesBlacklistProvider,
+ HaGeZiBlacklistProvider,
+ CombinedBlacklistProvider,
+ BlacklistProvider
+)
def get_default_blacklist_provider() -> BlacklistProvider:
"""Get the default blacklist provider configuration."""
- # Use HaGeZi as primary with fallback to old URL for compatibility
return CombinedBlacklistProvider([
- HaGeZiBlacklistProvider('light'),
- URLBlacklistProvider(BLACKLIST_DOMAINS_URL)
+ BuiltInRulesBlacklistProvider(),
+ HaGeZiBlacklistProvider('light')
])
-
-
-def set_blacklist_provider(provider: BlacklistProvider) -> None:
- """Set the global blacklist provider (useful for testing)."""
- global _blacklist_provider
- _blacklist_provider = provider
-
-
-def get_blacklist_provider() -> BlacklistProvider:
- """Get the current blacklist provider."""
- global _blacklist_provider
- if _blacklist_provider is None:
- _blacklist_provider = get_default_blacklist_provider()
- return _blacklist_provider
-
-
-def get_blacklist_domains() -> set[str]:
- """Get blacklisted domains using the configured provider."""
- provider = get_blacklist_provider()
- return provider.get_blacklisted_domains()
-
-
-def is_domain_blacklisted(domain: str, blacklist_domains: set[str]):
- if domain in EXCLUDED_DOMAINS or DOMAIN_BLACKLIST_REGEX.search(domain) is not None \
- or domain in blacklist_domains:
- return True
-
- if domain in DOMAINS:
- return False
-
- # TODO: this is to filter out spammy domains that look like:
- # brofqpxj.uelinc.com
- # gzsmjc.fba01.com
- # 59648.etnomurcia.com
- #
- # Eventually we can figure out a better way to identify SEO spam
- domain_parts = domain.split('.')
- if (len(domain_parts) == 3 and domain_parts[2] == "com" and len(domain_parts[0]) in {6, 8}) or (
- set(domain_parts[0]) <= set("1234567890")
- ):
- return True
diff --git a/mwmbl/indexer/update_urls.py b/mwmbl/indexer/update_urls.py
index 9c0bd34..bdd2125 100644
--- a/mwmbl/indexer/update_urls.py
+++ b/mwmbl/indexer/update_urls.py
@@ -15,7 +15,7 @@ from mwmbl.crawler.domains import DomainLinkDatabase
from mwmbl.crawler.urls import URLDatabase, URLStatus, FoundURL
from mwmbl.indexer import process_batch
from mwmbl.indexer.batch_cache import BatchCache
-from mwmbl.indexer.blacklist import get_blacklist_domains, is_domain_blacklisted
+from mwmbl.indexer.blacklist import get_default_blacklist_provider
from mwmbl.indexer.index_batches import get_url_error_status
from mwmbl.indexer.indexdb import BatchStatus
from mwmbl.redis_url_queue import RedisURLQueue, get_domain_max_urls
@@ -41,10 +41,10 @@ def run(batch_cache: BatchCache, new_item_queue: RedisURLQueue, num_batches: int
def record_urls_in_database(batches: Collection[HashedBatch], new_item_queue: RedisURLQueue):
start = datetime.utcnow()
- blacklist_domains = get_blacklist_domains()
+ blacklist_provider = get_default_blacklist_provider()
blacklist_retrieval_time = datetime.utcnow() - start
- logger.info(f"Recording URLs in database for {len(batches)} batches, with {len(blacklist_domains)} blacklist "
- f"domains, retrieved in {blacklist_retrieval_time.total_seconds()} seconds")
+ logger.info(f"Recording URLs in database for {len(batches)} batches, blacklist provider ready "
+ f"in {blacklist_retrieval_time.total_seconds()} seconds")
url_users = {}
url_timestamps = {}
@@ -66,7 +66,7 @@ def record_urls_in_database(batches: Collection[HashedBatch], new_item_queue: Re
continue
for link in item.content.all_links:
process_link(batch.user_id_hash, crawled_page_domain, link, timestamp, url_timestamps, url_users,
- blacklist_domains, domain_links)
+ blacklist_provider, domain_links)
found_urls = [FoundURL(url, url_users[url], url_statuses[url], url_timestamps[url])
for url in url_statuses.keys() | url_users.keys()]
@@ -107,7 +107,7 @@ def add_hn_links(new_item_queue: RedisURLQueue):
def process_link(user_id_hash: str, crawled_page_domain: str, link: Link, timestamp: datetime,
- url_timestamps: dict[str, datetime], url_users: dict[str, str], blacklist_domains: set[str],
+ url_timestamps: dict[str, datetime], url_users: dict[str, str], blacklist_provider,
domain_links: dict[str, set[str]]):
try:
parsed_link = parse_url(link.url)
@@ -119,7 +119,7 @@ def process_link(user_id_hash: str, crawled_page_domain: str, link: Link, timest
logger.debug(f"Couldn't find netloc: {link.url}")
return
- if is_domain_blacklisted(parsed_link.netloc, blacklist_domains):
+ if blacklist_provider.is_domain_blacklisted(parsed_link.netloc):
logger.debug(f"Excluding link for blacklisted domain: {parsed_link}")
return
diff --git a/mwmbl/redis_url_queue.py b/mwmbl/redis_url_queue.py
index f1ca231..c816875 100644
--- a/mwmbl/redis_url_queue.py
+++ b/mwmbl/redis_url_queue.py
@@ -11,7 +11,7 @@ from redis import Redis
from mwmbl.crawler.domains import DomainLinkDatabase, TOP_DOMAINS
from mwmbl.crawler.urls import FoundURL
from mwmbl.hn_top_domains_filtered import DOMAINS
-from mwmbl.indexer.blacklist import get_blacklist_domains, is_domain_blacklisted
+from mwmbl.indexer.blacklist import get_default_blacklist_provider
from mwmbl.settings import CORE_DOMAINS
from mwmbl.utils import parse_url
@@ -52,10 +52,10 @@ def get_domain_max_urls(domain: str, curated_domains: set[str]):
class RedisURLQueue:
- def __init__(self, redis: Redis, get_curated_domains_function: Callable[[], set[str]]) -> None:
+ def __init__(self, redis: Redis, get_curated_domains_function: Callable[[], set[str]], blacklist_provider=None) -> None:
self.redis = redis
- self._black_listed_domains = None
self.get_curated_domains_function = get_curated_domains_function
+ self.blacklist_provider = blacklist_provider or get_default_blacklist_provider()
def queue_urls(self, found_urls: list[FoundURL]):
curated_domains = self.get_curated_domains_function()
@@ -115,7 +115,7 @@ class RedisURLQueue:
else:
domains += list(top_other_domains)
- domains = [domain for domain in domains if not is_domain_blacklisted(domain, self.black_listed_domains)]
+ domains = [domain for domain in domains if not self.blacklist_provider.is_domain_blacklisted(domain)]
logger.info(f"Getting batch from domains {domains}")
# Add a random url as the root domain of one of DOMAINS
@@ -160,9 +160,3 @@ class RedisURLQueue:
def get_domain_count(self, domain: str):
return self.redis.zcard(DOMAIN_URLS_KEY.format(domain=domain))
-
- @property
- def black_listed_domains(self):
- if self._black_listed_domains is None:
- self._black_listed_domains = get_blacklist_domains()
- return self._black_listed_domains
diff --git a/mwmbl/settings.py b/mwmbl/settings.py
index 4dc6173..018ba57 100644
--- a/mwmbl/settings.py
+++ b/mwmbl/settings.py
@@ -44,5 +44,3 @@ CORE_DOMAINS = {
'www.python.org',
'news.ycombinator.com',
}
-
-BLACKLIST_DOMAINS_URL = "https://get.domainsblacklists.com/blacklist.txt"
diff --git a/test/test_blacklist.py b/test/test_blacklist.py
index b98fd48..5088b57 100644
--- a/test/test_blacklist.py
+++ b/test/test_blacklist.py
@@ -1,21 +1,27 @@
-from mwmbl.indexer.blacklist import is_domain_blacklisted
+from mwmbl.indexer.blacklist_providers import BuiltInRulesBlacklistProvider
def test_blacklist_excludes_bad_pattern():
+ """Test that built-in rules blacklist bad patterns."""
+ provider = BuiltInRulesBlacklistProvider()
bad_domains = [
"brofqpxj.uelinc.com",
- "gzsmjc.fba01.com",
+ "gzsmjc.fba01.com",
"59648.etnomurcia.com",
"something.hzqwyou.cn",
]
for domain in bad_domains:
- assert is_domain_blacklisted(domain, set())
+ assert provider.is_domain_blacklisted(domain)
def test_blacklist_allows_top_domains():
- assert not is_domain_blacklisted("teamblog.supportbee.com", set())
+ """Test that built-in rules allow legitimate domains."""
+ provider = BuiltInRulesBlacklistProvider()
+ assert not provider.is_domain_blacklisted("teamblog.supportbee.com")
def test_blacklist_allows_other_domains():
- assert not is_domain_blacklisted("something.com", set())
+ """Test that built-in rules allow other legitimate domains."""
+ provider = BuiltInRulesBlacklistProvider()
+ assert not provider.is_domain_blacklisted("something.com")
diff --git a/test/test_crawl_functional.py b/test/test_crawl_functional.py
index 56a7ea4..ee35c0a 100644
--- a/test/test_crawl_functional.py
+++ b/test/test_crawl_functional.py
@@ -15,7 +15,6 @@ from mwmbl.crawl import Crawler, crawl_url, process_batch, run_indexing
from mwmbl.crawler.batch import HashedBatch, Result, Item, ItemContent
from mwmbl.crawler.urls import FoundURL, URLStatus
from mwmbl.redis_url_queue import RedisURLQueue
-from mwmbl.indexer.blacklist import set_blacklist_provider
from mwmbl.indexer.blacklist_providers import StaticBlacklistProvider
@@ -102,20 +101,15 @@ def sample_found_urls():
]
[email protected](autouse=True)
-def setup_test_blacklist_provider():
- """Configure a static blacklist provider for tests to avoid network calls."""
- # Use a static blacklist provider with known test domains to avoid network calls
+def test_blacklist_provider():
+ """Create a static blacklist provider for tests to avoid network calls."""
test_blacklist_domains = {
'spam.com',
'malware.example',
'badsite.net'
}
- test_provider = StaticBlacklistProvider(test_blacklist_domains)
- set_blacklist_provider(test_provider)
- yield
- # Reset to None so subsequent tests use default
- set_blacklist_provider(None)
+ return StaticBlacklistProvider(test_blacklist_domains)
@pytest.mark.django_db
@@ -138,9 +132,9 @@ class TestCrawlFunctional:
with pytest.raises(SystemExit):
crawler.check_redis()
- def test_url_queue_operations(self, fake_redis, sample_found_urls):
+ def test_url_queue_operations(self, fake_redis, sample_found_urls, test_blacklist_provider):
"""Test RedisURLQueue operations with fake Redis"""
- url_queue = RedisURLQueue(fake_redis, lambda: set())
+ url_queue = RedisURLQueue(fake_redis, lambda: set(), test_blacklist_provider)
# Test queuing URLs
url_queue.queue_urls(sample_found_urls)
@@ -305,9 +299,9 @@ class TestCrawlFunctional:
retrieved_batch = json.loads(batch_data)
assert retrieved_batch['user_id_hash'] == 'test_user'
- def test_domain_scoring_and_url_management(self, fake_redis, sample_found_urls):
+ def test_domain_scoring_and_url_management(self, fake_redis, sample_found_urls, test_blacklist_provider):
"""Test domain scoring and URL management in Redis"""
- url_queue = RedisURLQueue(fake_redis, lambda: set())
+ url_queue = RedisURLQueue(fake_redis, lambda: set(), test_blacklist_provider)
# Queue URLs
url_queue.queue_urls(sample_found_urls)
@@ -323,9 +317,9 @@ class TestCrawlFunctional:
assert example_count >= 0
assert test_count >= 0
- def test_user_url_assignment(self, fake_redis, sample_found_urls):
+ def test_user_url_assignment(self, fake_redis, sample_found_urls, test_blacklist_provider):
"""Test user URL assignment and tracking"""
- url_queue = RedisURLQueue(fake_redis, lambda: set())
+ url_queue = RedisURLQueue(fake_redis, lambda: set(), test_blacklist_provider)
# Queue URLs and get batch
url_queue.queue_urls(sample_found_urls)
@@ -343,10 +337,10 @@ class TestCrawlFunctional:
assert len(uncrawled) == 0 # All URLs should be assigned to this user
def test_integration_workflow(self, fake_redis, mock_settings, mock_environment,
- sample_found_urls, mock_crawl_response, temp_data_path):
+ sample_found_urls, mock_crawl_response, temp_data_path, test_blacklist_provider):
"""Test the complete integration workflow"""
# Setup URL queue
- url_queue = RedisURLQueue(fake_redis, lambda: set())
+ url_queue = RedisURLQueue(fake_redis, lambda: set(), test_blacklist_provider)
url_queue.queue_urls(sample_found_urls)
# Create crawler instance
diff --git a/test/test_update_urls.py b/test/test_update_urls.py
index f201939..47894c6 100644
--- a/test/test_update_urls.py
+++ b/test/test_update_urls.py
@@ -2,6 +2,7 @@ from collections import defaultdict
from mwmbl.crawler.batch import Link
from mwmbl.indexer.update_urls import process_link
+from mwmbl.indexer.blacklist_providers import StaticBlacklistProvider
def test_process_link_normal():
@@ -9,6 +10,7 @@ def test_process_link_normal():
url_timestamps = {}
url_users = {}
domain_links = defaultdict(set)
+ blacklist_provider = StaticBlacklistProvider(set())
process_link(
user_id_hash="abc123",
@@ -17,7 +19,7 @@ def test_process_link_normal():
timestamp=1234,
url_timestamps=url_timestamps,
url_users=url_users,
- blacklist_domains=[],
+ blacklist_provider=blacklist_provider,
domain_links=domain_links,
)
@@ -29,6 +31,8 @@ def test_process_link_excludes_porn():
url_timestamps = {}
url_users = {}
domain_links = {}
+ # Create a blacklist provider that blocks porn sites
+ blacklist_provider = StaticBlacklistProvider({"somepornsite.com"})
process_link(
user_id_hash="abc123",
@@ -37,7 +41,7 @@ def test_process_link_excludes_porn():
timestamp=1234,
url_timestamps=url_timestamps,
url_users=url_users,
- blacklist_domains=[],
+ blacklist_provider=blacklist_provider,
domain_links=domain_links,
)