osint-dashboard/news/scraper/newsScraper/pipelines.py

148 lines
4.8 KiB
Python
Raw Normal View History

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import datetime
import logging
import psycopg2
import os
from scrapy.exceptions import DropItem
from newsScraper.feed_util import unwrap_cdata_title
log = logging.getLogger(__name__)
# Feed items dated further ahead than this are event listings (or clock skew
# from the source), not news. Dropping them keeps `ORDER BY timestamp DESC`
# from pinning the top of /api/news for days. See docs/news.md.
FUTURE_TOLERANCE = datetime.timedelta(hours=2)
def _parsed_timestamp(value):
"""Return an aware UTC datetime for an item timestamp, or None.
None means "could not parse" — callers must keep such items, exactly as
before this guard existed (undated items currently get now() upstream).
"""
if isinstance(value, datetime.datetime):
ts = value
elif isinstance(value, str) and value.strip():
try:
ts = datetime.datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
except ValueError:
return None
else:
return None
if ts.tzinfo is None:
ts = ts.replace(tzinfo=datetime.timezone.utc)
return ts.astimezone(datetime.timezone.utc)
def is_future_dated(value, now=None, tolerance=FUTURE_TOLERANCE):
"""True when a parsed publish timestamp is more than `tolerance` ahead."""
ts = _parsed_timestamp(value)
if ts is None:
return False
now = now or datetime.datetime.now(datetime.timezone.utc)
return ts > now + tolerance
class PostgresPipeline:
def __init__(self, db_config):
# 1. Store the config
self.db_config = db_config
# 2. Initialize the set here so it exists when process_item is called
self.seen_urls = set()
# 3. Future-dated drops, reported once per run in close_spider()
self.future_dated_dropped = 0
@classmethod
def from_crawler(cls, crawler):
db_config = {
'host': crawler.settings.get('DB_HOST'),
'database': crawler.settings.get('DB_NAME'),
'user': crawler.settings.get('DB_USER'),
'password': crawler.settings.get('DB_PASSWORD'),
}
return cls(db_config=db_config)
def open_spider(self, spider):
# Connect using environment variables
self.connection = psycopg2.connect(
host=os.getenv('DB_HOST'),
database=os.getenv('DB_NAME'),
user=os.getenv('DB_USER'),
password=os.getenv('DB_PASSWORD'),
port=os.getenv('DB_PORT', '5432')
)
self.cur = self.connection.cursor()
# Create table if it doesn't exist
self.cur.execute("""
CREATE TABLE IF NOT EXISTS articles (
id SERIAL PRIMARY KEY,
title TEXT,
url TEXT UNIQUE,
content TEXT,
domain TEXT,
timestamp TIMESTAMPTZ
)
""")
self.connection.commit()
def process_item(self, item, spider):
url = item['url']
if is_future_dated(item.get('timestamp')):
self.future_dated_dropped += 1
stats = getattr(getattr(spider, 'crawler', None), 'stats', None)
if stats is not None:
stats.inc_value('future_dated_dropped')
raise DropItem(f"Future-dated item: {url}")
if url in self.seen_urls:
raise DropItem(f"Duplicate URL (in-memory): {url}")
self.seen_urls.add(url)
item['title'] = unwrap_cdata_title(item['title'])
try:
self.cur.execute("""
INSERT INTO articles (title, url, content, domain, timestamp)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (url) DO NOTHING
""", (
item['title'],
item['url'],
item['text'],
item['domain'],
item['timestamp']
))
if self.cur.rowcount == 0:
raise DropItem(f"Duplicate URL (database): {url}")
self.connection.commit()
return item
except DropItem:
self.connection.rollback()
raise
except Exception as e:
spider.logger.error(f"Error saving to Postgres: {e}")
self.connection.rollback()
raise
def close_spider(self, spider):
if self.future_dated_dropped:
spider.logger.info(
"Dropped %d future-dated item(s) (>%s ahead)",
self.future_dated_dropped, FUTURE_TOLERANCE,
)
self.cur.close()
self.connection.close()
from itemadapter import ItemAdapter
class NewsscraperPipeline:
def process_item(self, item, spider):
return item