2025-02-03 17:37:20 -06:00
|
|
|
import validators
|
|
|
|
|
|
2024-05-06 12:27:46 +08:00
|
|
|
from typing import Optional
|
2024-06-13 07:14:48 +07:00
|
|
|
from urllib.parse import urlparse
|
2024-08-28 00:10:27 +02:00
|
|
|
|
2024-05-06 12:27:46 +08:00
|
|
|
from pydantic import BaseModel
|
|
|
|
|
|
|
|
|
|
|
2024-06-17 14:36:26 +07:00
|
|
|
def get_filtered_results(results, filter_list):
|
|
|
|
|
if not filter_list:
|
2024-06-13 07:14:48 +07:00
|
|
|
return results
|
2025-11-16 13:52:09 -05: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 07:14:48 +07:00
|
|
|
filtered_results = []
|
2025-11-16 13:52:09 -05:00
|
|
|
|
2024-06-13 07:14:48 +07:00
|
|
|
for result in results:
|
2025-08-21 12:51:41 +04:00
|
|
|
url = result.get("url") or result.get("link", "") or result.get("href", "")
|
2025-02-03 17:37:20 -06:00
|
|
|
if not validators.url(url):
|
|
|
|
|
continue
|
2025-11-16 13:52:09 -05:00
|
|
|
|
2024-08-27 13:15:17 +05:30
|
|
|
domain = urlparse(url).netloc
|
2025-11-16 13:52:09 -05: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 07:14:48 +07:00
|
|
|
return filtered_results
|
|
|
|
|
|
2024-06-17 14:32:23 -07:00
|
|
|
|
2024-05-06 12:27:46 +08:00
|
|
|
class SearchResult(BaseModel):
|
|
|
|
|
link: str
|
|
|
|
|
title: Optional[str]
|
|
|
|
|
snippet: Optional[str]
|