|
| 1 | +""" |
| 2 | +DynamoDB Link Validator Helper |
| 3 | +
|
| 4 | +This module provides utilities to check and store scraped links in AWS DynamoDB |
| 5 | +with TTL-based expiration to avoid reprocessing the same content. |
| 6 | +""" |
| 7 | + |
| 8 | +import boto3 |
| 9 | +from datetime import datetime, timedelta |
| 10 | +from typing import Optional |
| 11 | +from botocore.exceptions import ClientError |
| 12 | + |
| 13 | + |
| 14 | +class LinkValidator: |
| 15 | + """ |
| 16 | + Helper class to validate and store links in DynamoDB with TTL support. |
| 17 | + |
| 18 | + Table schema: |
| 19 | + - Partition key: link (String) |
| 20 | + - Sort key: timestamp (Number) - used as TTL attribute |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__( |
| 24 | + self, |
| 25 | + table_name: str = "lunchdeal", |
| 26 | + region_name: str = "eu-central-1", |
| 27 | + aws_account_id: str = "840940990295" |
| 28 | + ): |
| 29 | + """ |
| 30 | + Initialize the LinkValidator with DynamoDB connection. |
| 31 | + |
| 32 | + Args: |
| 33 | + table_name: Name of the DynamoDB table |
| 34 | + region_name: AWS region |
| 35 | + aws_account_id: AWS account ID (for reference) |
| 36 | + """ |
| 37 | + self.table_name = table_name |
| 38 | + self.region_name = region_name |
| 39 | + self.aws_account_id = aws_account_id |
| 40 | + |
| 41 | + # Initialize DynamoDB resource |
| 42 | + self.dynamodb = boto3.resource('dynamodb', region_name=region_name) |
| 43 | + self.table = self.dynamodb.Table(table_name) |
| 44 | + |
| 45 | + def link_exists(self, link: str) -> bool: |
| 46 | + """ |
| 47 | + Check if a link already exists in DynamoDB and has not expired. |
| 48 | + |
| 49 | + Args: |
| 50 | + link: The URL to check |
| 51 | + |
| 52 | + Returns: |
| 53 | + True if the link exists and has not expired, False otherwise |
| 54 | + """ |
| 55 | + try: |
| 56 | + current_timestamp = int(datetime.now().timestamp()) |
| 57 | + |
| 58 | + # Query for the link with timestamp >= current time |
| 59 | + response = self.table.query( |
| 60 | + KeyConditionExpression=boto3.dynamodb.conditions.Key('link').eq(link) & |
| 61 | + boto3.dynamodb.conditions.Key('timestamp').gte(current_timestamp), |
| 62 | + Limit=1 |
| 63 | + ) |
| 64 | + |
| 65 | + # If we found any items, the link exists and is not expired |
| 66 | + return len(response.get('Items', [])) > 0 |
| 67 | + |
| 68 | + except ClientError as e: |
| 69 | + print(f"Error checking link existence: {e}") |
| 70 | + # On error, assume link doesn't exist to avoid skipping content |
| 71 | + return False |
| 72 | + |
| 73 | + def add_link(self, link: str, ttl_weeks: int = 8) -> bool: |
| 74 | + """ |
| 75 | + Add a link to DynamoDB with a TTL timestamp. |
| 76 | + |
| 77 | + Args: |
| 78 | + link: The URL to store |
| 79 | + ttl_weeks: Number of weeks until the link expires (default: 8) |
| 80 | + |
| 81 | + Returns: |
| 82 | + True if successfully added, False otherwise |
| 83 | + """ |
| 84 | + try: |
| 85 | + current_time = datetime.now() |
| 86 | + expiry_time = current_time + timedelta(weeks=ttl_weeks) |
| 87 | + timestamp = int(expiry_time.timestamp()) |
| 88 | + |
| 89 | + # Put item in DynamoDB |
| 90 | + self.table.put_item( |
| 91 | + Item={ |
| 92 | + 'link': link, |
| 93 | + 'timestamp': timestamp, |
| 94 | + 'created_at': current_time.isoformat(), |
| 95 | + 'expires_at': expiry_time.isoformat() |
| 96 | + } |
| 97 | + ) |
| 98 | + |
| 99 | + print(f"Successfully added link: {link} (expires: {expiry_time.isoformat()})") |
| 100 | + return True |
| 101 | + |
| 102 | + except ClientError as e: |
| 103 | + print(f"Error adding link: {e}") |
| 104 | + return False |
| 105 | + |
| 106 | + def mark_link_processed(self, link: str, ttl_weeks: int = 8) -> bool: |
| 107 | + """ |
| 108 | + Convenience method to mark a link as processed (alias for add_link). |
| 109 | + |
| 110 | + Args: |
| 111 | + link: The URL to mark as processed |
| 112 | + ttl_weeks: Number of weeks until the link expires (default: 8) |
| 113 | + |
| 114 | + Returns: |
| 115 | + True if successfully marked, False otherwise |
| 116 | + """ |
| 117 | + return self.add_link(link, ttl_weeks) |
| 118 | + |
| 119 | + |
| 120 | +def get_validator() -> LinkValidator: |
| 121 | + """ |
| 122 | + Factory function to create a LinkValidator instance with default settings. |
| 123 | + |
| 124 | + Returns: |
| 125 | + LinkValidator instance configured for the lunchdeal table |
| 126 | + """ |
| 127 | + return LinkValidator() |
| 128 | + |
| 129 | + |
| 130 | +# Standalone functions for easier imports |
| 131 | +def check_link(link: str) -> bool: |
| 132 | + """ |
| 133 | + Check if a link exists in DynamoDB (standalone function). |
| 134 | + |
| 135 | + Args: |
| 136 | + link: The URL to check |
| 137 | + |
| 138 | + Returns: |
| 139 | + True if link exists and has not expired, False otherwise |
| 140 | + """ |
| 141 | + validator = get_validator() |
| 142 | + return validator.link_exists(link) |
| 143 | + |
| 144 | + |
| 145 | +def mark_processed(link: str, ttl_weeks: int = 8) -> bool: |
| 146 | + """ |
| 147 | + Mark a link as processed in DynamoDB (standalone function). |
| 148 | + |
| 149 | + Args: |
| 150 | + link: The URL to mark as processed |
| 151 | + ttl_weeks: Number of weeks until expiration (default: 8) |
| 152 | + |
| 153 | + Returns: |
| 154 | + True if successfully marked, False otherwise |
| 155 | + """ |
| 156 | + validator = get_validator() |
| 157 | + return validator.add_link(link, ttl_weeks) |
0 commit comments