2025-02-03 23:37:20 +00:00
|
|
|
import validators
|
|
|
|
|
|
2024-05-06 04:27:46 +00:00
|
|
|
from typing import Optional
|
2024-06-13 00:14:48 +00:00
|
|
|
from urllib.parse import urlparse
|
2024-08-27 22:10:27 +00:00
|
|
|
|
2024-05-06 04:27:46 +00:00
|
|
|
from pydantic import BaseModel
|
|
|
|
|
|
|
|
|
|
|
2024-06-17 07:36:26 +00:00
|
|
|
def get_filtered_results(results, filter_list):
|
|
|
|
|
if not filter_list:
|
2024-06-13 00:14:48 +00:00
|
|
|
return results
|
2025-11-16 18:52:09 +00:00
|
|
|
|
|
|
|
|
# Domains starting without "!" → allowed
|
|
|
|
|
allow_list = [d for d in filter_list if not d.startswith("!")]
|
|
|
|
|
# Domains starting with "!" → blocked
|
|
|
|
|
block_list = [d[1:] for d in filter_list if d.startswith("!")]
|
|
|
|
|
|
2024-06-13 00:14:48 +00:00
|
|
|
filtered_results = []
|
2025-11-16 18:52:09 +00:00
|
|
|
|
2024-06-13 00:14:48 +00:00
|
|
|
for result in results:
|
2025-08-21 08:51:41 +00:00
|
|
|
url = result.get("url") or result.get("link", "") or result.get("href", "")
|
2025-02-03 23:37:20 +00:00
|
|
|
if not validators.url(url):
|
|
|
|
|
continue
|
2025-11-16 18:52:09 +00:00
|
|
|
|
2024-08-27 07:45:17 +00:00
|
|
|
domain = urlparse(url).netloc
|
2025-11-16 18:52:09 +00:00
|
|
|
|
|
|
|
|
# If allow list is non-empty, require domain to match one of them
|
|
|
|
|
if allow_list:
|
|
|
|
|
if not any(domain.endswith(allowed) for allowed in allow_list):
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
# Block list always removes matches
|
|
|
|
|
if any(domain.endswith(blocked) for blocked in block_list):
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
filtered_results.append(result)
|
|
|
|
|
|
2024-06-13 00:14:48 +00:00
|
|
|
return filtered_results
|
|
|
|
|
|
2024-06-17 21:32:23 +00:00
|
|
|
|
2024-05-06 04:27:46 +00:00
|
|
|
class SearchResult(BaseModel):
|
|
|
|
|
link: str
|
|
|
|
|
title: Optional[str]
|
|
|
|
|
snippet: Optional[str]
|