├── requirements.txt ├── reddit_fetch ├── __init__.py ├── config.py ├── generate_tokens.py ├── main.py ├── auth.py └── api.py ├── .sample-env ├── .gitignore ├── sample-docker-compose.yml ├── setup.py ├── Dockerfile ├── .dockerignore ├── docker-entrypoint.sh ├── validate_credentials.py ├── README.md └── LICENSE /requirements.txt: -------------------------------------------------------------------------------- 1 | requests 2 | python-dotenv 3 | rich -------------------------------------------------------------------------------- /reddit_fetch/__init__.py: -------------------------------------------------------------------------------- 1 | from .main import fetch_saved_posts -------------------------------------------------------------------------------- /.sample-env: -------------------------------------------------------------------------------- 1 | CLIENT_ID= 2 | CLIENT_SECRET= 3 | USER_AGENT= 4 | REDIRECT_URI=http://localhost:8080 5 | REDDIT_USERNAME= -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.json 2 | __pycache__/ 3 | *.html 4 | *.txt 5 | Reddit_Fetch.egg-info/ 6 | venv/ 7 | *.bk 8 | test.py 9 | docker-compose.yml 10 | .env 11 | -------------------------------------------------------------------------------- /sample-docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.9" 2 | 3 | services: 4 | reddit-fetcher: 5 | build: . 6 | container_name: reddit-fetcher 7 | env_file: .env 8 | volumes: 9 | - ./data:/data 10 | environment: 11 | - DOCKER=1 12 | - FETCH_INTERVAL=86400 #In seconds, configurable 13 | - OUTPUT_FORMAT=json #Choose between html or json 14 | - FORCE_FETCH=true #Force fetch all the posts or fetch delta from the last fetch 15 | restart: unless-stopped 16 | -------------------------------------------------------------------------------- /reddit_fetch/config.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | from dotenv import load_dotenv 4 | 5 | # Load environment variables 6 | load_dotenv() 7 | 8 | # Reddit API credentials - strip whitespace to avoid common issues 9 | CLIENT_ID = os.getenv("CLIENT_ID", "").strip() 10 | CLIENT_SECRET = os.getenv("CLIENT_SECRET", "").strip() 11 | REDIRECT_URI = os.getenv("REDIRECT_URI", "").strip() # Must match the Reddit App settings 12 | USER_AGENT = os.getenv("USER_AGENT", "").strip() # Fetch dynamically 13 | REDDIT_USERNAME = os.getenv("REDDIT_USERNAME", "").strip() # Fetch dynamically 14 | TOKEN_FILE = "/data/tokens.json" if os.getenv("DOCKER", "0") == "1" else "tokens.json" 15 | 16 | def exponential_backoff(attempt, base_delay=1.0, max_delay=16.0): 17 | """Implements exponential backoff to avoid rate limiting.""" 18 | delay = min(base_delay * (2 ** attempt), max_delay) 19 | time.sleep(delay) 20 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup( 4 | name="Reddit-Fetch", 5 | version="0.1", 6 | packages=find_packages(), 7 | install_requires=[ 8 | "requests", 9 | "python-dotenv", 10 | "rich", 11 | "argparse" 12 | ], 13 | entry_points={ 14 | "console_scripts": [ 15 | "reddit-fetcher=reddit_fetch.main:cli_entry" 16 | ] 17 | }, 18 | include_package_data=True, # ✅ Ensure all necessary files are included 19 | author="Akash Pandey", 20 | author_email="pandeyak12@outlook.com", 21 | description="A tool to fetch and process Reddit saved posts.", 22 | long_description="Reddit-Fetch allows users to retrieve their saved posts from Reddit, format them into JSON or HTML, and store them locally.", 23 | long_description_content_type="text/markdown", 24 | url="https://github.com/akashpandey/Reddit-Fetch", 25 | classifiers=[ 26 | "Programming Language :: Python :: 3", 27 | "License :: OSI Approved :: MIT License", 28 | "Operating System :: OS Independent", 29 | ], 30 | python_requires=">=3.6", 31 | ) 32 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Use the latest Python Alpine image with recent security patches 2 | FROM python:3.11-alpine3.19 3 | 4 | # Update package lists and upgrade all packages to patch vulnerabilities 5 | RUN apk update && apk upgrade --no-cache 6 | 7 | # Upgrade pip to latest version for security fixes 8 | RUN pip install --upgrade pip 9 | 10 | WORKDIR /app 11 | 12 | # Copy requirements first for better Docker layer caching 13 | COPY requirements.txt ./ 14 | 15 | # Install Python dependencies (no build tools needed for these packages) 16 | RUN pip install --no-cache-dir -r requirements.txt 17 | 18 | # Copy the rest of the application code 19 | COPY . . 20 | 21 | # Install the application 22 | RUN pip install --no-cache-dir -e . 23 | 24 | # Set environment variables 25 | ENV DOCKER=1 26 | ENV OUTPUT_FORMAT="json" 27 | ENV FETCH_INTERVAL="86400" 28 | ENV FORCE_FETCH="false" 29 | 30 | # Create data directory 31 | RUN mkdir -p /data && chmod 755 /data 32 | 33 | # Define a persistent volume for data storage 34 | VOLUME ["/data"] 35 | 36 | # Ensure clean line endings and permissions 37 | COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh 38 | RUN chmod +x /usr/local/bin/docker-entrypoint.sh && \ 39 | sed -i 's/\r$//' /usr/local/bin/docker-entrypoint.sh 40 | 41 | 42 | # Use the startup script as entrypoint 43 | ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"] -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | *.json 2 | __pycache__/ 3 | *.html 4 | Reddit_Fetch.egg-info/ 5 | venv/ 6 | *.bk 7 | test.py 8 | *.yml 9 | .env 10 | data/ 11 | .gitignore 12 | .git 13 | *.md 14 | LICENSE 15 | *.egg-info 16 | 17 | # Git and version control 18 | .git 19 | .gitignore 20 | .gitattributes 21 | .github/ 22 | 23 | # IDE and editor files 24 | .vscode/ 25 | .idea/ 26 | *.swp 27 | *.swo 28 | .DS_Store 29 | Thumbs.db 30 | 31 | # Python development files 32 | __pycache__/ 33 | *.pyc 34 | *.pyo 35 | *.pyd 36 | .Python 37 | build/ 38 | develop-eggs/ 39 | dist/ 40 | downloads/ 41 | eggs/ 42 | .eggs/ 43 | lib/ 44 | lib64/ 45 | parts/ 46 | sdist/ 47 | var/ 48 | wheels/ 49 | *.egg-info/ 50 | .installed.cfg 51 | *.egg 52 | 53 | # Testing and coverage 54 | .pytest_cache/ 55 | .tox/ 56 | .coverage 57 | .coverage.* 58 | .cache 59 | nosetests.xml 60 | coverage.xml 61 | *.cover 62 | .hypothesis/ 63 | htmlcov/ 64 | 65 | # Virtual environments 66 | .env 67 | .venv 68 | env/ 69 | venv/ 70 | ENV/ 71 | env.bak/ 72 | venv.bak/ 73 | 74 | # Secrets and credentials 75 | .env* 76 | tokens.json 77 | *.key 78 | *.pem 79 | credentials.json 80 | secrets.json 81 | config.json 82 | 83 | # Runtime and data files 84 | data/ 85 | logs/ 86 | *.log 87 | tmp/ 88 | temp/ 89 | 90 | # Docker files (local overrides) 91 | docker-compose.yml 92 | docker-compose.override.yml 93 | docker-compose.local.yml 94 | 95 | # Documentation and examples (optional - you might want these) 96 | README.md 97 | docs/ 98 | examples/ 99 | 100 | # OS generated files 101 | .DS_Store 102 | .DS_Store? 103 | ._* 104 | .Spotlight-V100 105 | .Trashes 106 | ehthumbs.db 107 | Thumbs.db -------------------------------------------------------------------------------- /reddit_fetch/generate_tokens.py: -------------------------------------------------------------------------------- 1 | import time 2 | import requests 3 | import base64 4 | import os 5 | import webbrowser 6 | import threading 7 | import json 8 | from http.server import BaseHTTPRequestHandler, HTTPServer 9 | from urllib.parse import urlparse, parse_qs 10 | from dotenv import load_dotenv 11 | 12 | # Load environment variables 13 | load_dotenv() 14 | 15 | # Reddit API Credentials - strip whitespace to avoid common issues 16 | CLIENT_ID = os.getenv("CLIENT_ID", "").strip() 17 | CLIENT_SECRET = os.getenv("CLIENT_SECRET", "").strip() 18 | REDIRECT_URI = os.getenv("REDIRECT_URI", "").strip() # Must match the one registered in Reddit App 19 | USER_AGENT = os.getenv("USER_AGENT", "").strip() # Fetch dynamically 20 | TOKEN_FILE = "tokens.json" 21 | 22 | # Global variable to store auth code 23 | auth_code = None 24 | 25 | # Step 1: Create a Local Server to Capture Authorization Code 26 | class AuthHandler(BaseHTTPRequestHandler): 27 | def do_GET(self): 28 | global auth_code 29 | query_components = parse_qs(urlparse(self.path).query) 30 | if "code" in query_components: 31 | auth_code = query_components["code"][0].strip() 32 | self.send_response(200) 33 | self.end_headers() 34 | self.wfile.write(b"Authorization successful! You can close this tab.") 35 | print(f"✅ Authorization Code Captured: {auth_code}") 36 | else: 37 | self.send_response(400) 38 | self.end_headers() 39 | self.wfile.write(b"Error: Authorization code not found.") 40 | 41 | def start_auth_server(): 42 | """Starts a local HTTP server to capture the Reddit authorization code.""" 43 | server = HTTPServer(("localhost", 8080), AuthHandler) 44 | print("🌍 Waiting for authorization...") 45 | server.handle_request() 46 | 47 | def load_existing_tokens(): 48 | """Checks if a refresh token is already stored in tokens.json.""" 49 | if os.path.exists(TOKEN_FILE): 50 | try: 51 | with open(TOKEN_FILE, "r", encoding="utf-8") as file: 52 | tokens = json.load(file) 53 | if "refresh_token" in tokens: 54 | print("✅ Refresh token already exists. No need to re-authenticate.") 55 | return True # A refresh token is already stored 56 | except (json.JSONDecodeError, ValueError): 57 | print("❌ Token file is corrupted. Re-authenticating...") 58 | return False # No valid refresh token found, proceed with OAuth 59 | 60 | def get_tokens(): 61 | """Fetch new OAuth tokens from Reddit and store only the refresh token.""" 62 | # Check if refresh token already exists 63 | if load_existing_tokens(): 64 | return # Skip authentication 65 | 66 | global auth_code 67 | threading.Thread(target=start_auth_server, daemon=True).start() 68 | 69 | authorization_url = ( 70 | f"https://www.reddit.com/api/v1/authorize?client_id={CLIENT_ID}&response_type=code" 71 | f"&state=RANDOM_STRING&redirect_uri={REDIRECT_URI}&duration=permanent&scope=identity history read save" 72 | ) 73 | 74 | print("🌍 Opening Reddit authorization page in your browser...") 75 | webbrowser.open(authorization_url) 76 | 77 | while auth_code is None: 78 | time.sleep(0.1) 79 | 80 | auth_string = f"{CLIENT_ID}:{CLIENT_SECRET}" 81 | b64_auth = base64.b64encode(auth_string.encode()).decode() 82 | 83 | url = "https://www.reddit.com/api/v1/access_token" 84 | headers = { 85 | "Authorization": f"Basic {b64_auth}", 86 | "User-Agent": USER_AGENT, 87 | "Content-Type": "application/x-www-form-urlencoded" 88 | } 89 | data = { 90 | "grant_type": "authorization_code", 91 | "code": auth_code, 92 | "redirect_uri": REDIRECT_URI 93 | } 94 | 95 | response = requests.post(url, headers=headers, data=data) 96 | 97 | if response.status_code == 200: 98 | tokens = response.json() 99 | 100 | # Save only the refresh token (no timestamp needed) 101 | token_data = {"refresh_token": tokens["refresh_token"]} 102 | 103 | with open(TOKEN_FILE, "w", encoding="utf-8") as file: 104 | json.dump(token_data, file) 105 | 106 | print("✅ Refresh token saved in tokens.json") 107 | else: 108 | error_detail = "" 109 | try: 110 | error_json = response.json() 111 | error_detail = f"\nError: {error_json.get('error', 'Unknown')}" 112 | if 'message' in error_json: 113 | error_detail += f"\nMessage: {error_json['message']}" 114 | except: 115 | error_detail = f"\nResponse: {response.text}" 116 | 117 | print(f"❌ Authentication failed: {response.status_code}{error_detail}") 118 | 119 | if response.status_code == 401: 120 | print("\n⚠️ Common causes of 401 Unauthorized:") 121 | print("1. CLIENT_ID is incorrect (should be the ID under your app name)") 122 | print("2. CLIENT_SECRET is incorrect") 123 | print("3. Credentials have leading/trailing whitespace") 124 | print("4. REDIRECT_URI doesn't match your Reddit app settings exactly") 125 | print("\n💡 Run 'python validate_credentials.py' to test your credentials") 126 | 127 | if __name__ == "__main__": 128 | get_tokens() -------------------------------------------------------------------------------- /docker-entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # Docker entrypoint script for Reddit Fetcher 4 | 5 | set -e # Exit on any error 6 | 7 | echo "?? Starting Reddit Saved Posts Fetcher" 8 | echo "?? Configuration:" 9 | echo " - Output Format: ${OUTPUT_FORMAT:-json}" 10 | echo " - Fetch Interval: ${FETCH_INTERVAL:-86400} seconds" 11 | echo " - Force Fetch: ${FORCE_FETCH:-false}" 12 | echo " - Data Directory: /data" 13 | echo " - Reddit Username: ${REDDIT_USERNAME:-not set}" 14 | 15 | # Function to check if required files exist 16 | check_requirements() { 17 | echo "?? Checking requirements..." 18 | 19 | # Check if tokens.json exists 20 | if [ ! -f "/data/tokens.json" ]; then 21 | echo "? ERROR: /data/tokens.json not found!" 22 | echo "" 23 | echo "?? To fix this:" 24 | echo "1. Generate tokens on a computer with a browser:" 25 | echo " git clone " 26 | echo " cd " 27 | echo " pip install -e ." 28 | echo " python generate_tokens.py" 29 | echo "2. Copy tokens.json to your Docker data directory:" 30 | echo " cp tokens.json /path/to/your/docker/data/" 31 | echo "3. Restart this container:" 32 | echo " docker-compose restart" 33 | echo "" 34 | exit 1 35 | fi 36 | 37 | # Check basic environment variables 38 | if [ -z "$CLIENT_ID" ]; then 39 | echo "? ERROR: CLIENT_ID environment variable not set!" 40 | exit 1 41 | fi 42 | 43 | if [ -z "$CLIENT_SECRET" ]; then 44 | echo "? ERROR: CLIENT_SECRET environment variable not set!" 45 | exit 1 46 | fi 47 | 48 | if [ -z "$REDDIT_USERNAME" ]; then 49 | echo "? ERROR: REDDIT_USERNAME environment variable not set!" 50 | exit 1 51 | fi 52 | 53 | # Check if tokens.json is readable and has content 54 | if [ ! -s "/data/tokens.json" ]; then 55 | echo "? ERROR: /data/tokens.json is empty!" 56 | echo "Please regenerate tokens.json" 57 | exit 1 58 | fi 59 | 60 | # Validate tokens.json format 61 | if ! python3 -c "import json; json.load(open('/data/tokens.json'))" 2>/dev/null; then 62 | echo "? ERROR: /data/tokens.json is not valid JSON!" 63 | echo "Please regenerate tokens.json" 64 | exit 1 65 | fi 66 | 67 | echo "? Requirements check passed" 68 | } 69 | 70 | # Function to run the fetcher 71 | run_fetcher() { 72 | echo "? Fetching Reddit saved posts..." 73 | 74 | # Set environment variables for the reddit-fetcher command 75 | export OUTPUT_FORMAT="${OUTPUT_FORMAT:-json}" 76 | export FORCE_FETCH="${FORCE_FETCH:-false}" 77 | 78 | # Run the fetcher and capture exit code 79 | if reddit-fetcher; then 80 | echo "? Fetch completed successfully" 81 | return 0 82 | else 83 | exit_code=$? 84 | echo "? Fetch failed with exit code: $exit_code" 85 | 86 | # Provide helpful error messages based on common issues 87 | case $exit_code in 88 | 1) 89 | echo "?? This might be an authentication or configuration error." 90 | echo " - Check your .env file and tokens.json" 91 | echo " - Verify your Reddit app credentials" 92 | echo " - Try regenerating tokens.json" 93 | ;; 94 | 130) 95 | echo "?? Process was interrupted (Ctrl+C)" 96 | ;; 97 | *) 98 | echo "?? Unexpected error occurred. Check the logs above." 99 | echo " - Check your internet connection" 100 | echo " - Verify Reddit API is accessible" 101 | echo " - Check file permissions in /data directory" 102 | ;; 103 | esac 104 | 105 | return $exit_code 106 | fi 107 | } 108 | 109 | # Function to handle shutdown gracefully 110 | cleanup() { 111 | echo "" 112 | echo "?? Received shutdown signal" 113 | echo "?? Shutting down Reddit Fetcher..." 114 | exit 0 115 | } 116 | 117 | # Set up signal handlers for graceful shutdown 118 | trap cleanup SIGTERM SIGINT 119 | 120 | # Check requirements before starting 121 | check_requirements 122 | 123 | # If FETCH_INTERVAL is 0 or "once", run once and exit 124 | if [ "$FETCH_INTERVAL" = "0" ] || [ "$FETCH_INTERVAL" = "once" ]; then 125 | echo "?? Single run mode" 126 | run_fetcher 127 | exit $? 128 | fi 129 | 130 | # Validate FETCH_INTERVAL is a number 131 | if ! echo "$FETCH_INTERVAL" | grep -E '^[0-9]+$' > /dev/null; then 132 | echo "? ERROR: FETCH_INTERVAL must be a number (seconds) or 'once'" 133 | echo " Current value: $FETCH_INTERVAL" 134 | exit 1 135 | fi 136 | 137 | # Main loop for continuous operation 138 | echo "?? Starting continuous fetch mode" 139 | echo " Interval: ${FETCH_INTERVAL} seconds ($(echo "scale=2; $FETCH_INTERVAL/3600" | bc 2>/dev/null || echo "?") hours)" 140 | 141 | run_count=0 142 | 143 | while true; do 144 | run_count=$((run_count + 1)) 145 | echo "" 146 | echo "?? Run #${run_count} - $(date)" 147 | 148 | if run_fetcher; then 149 | echo "?? Sleeping for ${FETCH_INTERVAL} seconds..." 150 | 151 | # Calculate next run time (if date command supports it) 152 | if next_time=$(date -d "+${FETCH_INTERVAL} seconds" 2>/dev/null); then 153 | echo " Next run at: $next_time" 154 | else 155 | echo " Next run in: ${FETCH_INTERVAL} seconds" 156 | fi 157 | 158 | # Sleep with ability to interrupt 159 | sleep "${FETCH_INTERVAL}" & 160 | wait $! 161 | else 162 | echo "?? Fetch failed on run #${run_count}" 163 | echo "?? Retrying in 60 seconds..." 164 | sleep 60 & 165 | wait $! 166 | fi 167 | done -------------------------------------------------------------------------------- /validate_credentials.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Reddit Credentials Validator 4 | This script helps diagnose authentication issues with Reddit API credentials. 5 | """ 6 | 7 | import os 8 | import sys 9 | import base64 10 | import requests 11 | from dotenv import load_dotenv 12 | from rich.console import Console 13 | from rich.panel import Panel 14 | from rich.table import Table 15 | 16 | console = Console() 17 | 18 | def main(): 19 | # Load environment variables 20 | load_dotenv() 21 | 22 | # Get credentials with whitespace stripped 23 | client_id = os.getenv("CLIENT_ID", "").strip() 24 | client_secret = os.getenv("CLIENT_SECRET", "").strip() 25 | redirect_uri = os.getenv("REDIRECT_URI", "").strip() 26 | user_agent = os.getenv("USER_AGENT", "").strip() 27 | reddit_username = os.getenv("REDDIT_USERNAME", "").strip() 28 | 29 | console.print("\n[bold cyan]Reddit Credentials Validator[/bold cyan]\n") 30 | 31 | # Create validation table 32 | table = Table(title="Credential Check") 33 | table.add_column("Field", style="cyan", no_wrap=True) 34 | table.add_column("Status", style="magenta") 35 | table.add_column("Value (first/last 4 chars)", style="green") 36 | table.add_column("Length", style="yellow") 37 | table.add_column("Issues", style="red") 38 | 39 | # Validate CLIENT_ID 40 | client_id_issues = [] 41 | if not client_id: 42 | client_id_issues.append("MISSING") 43 | else: 44 | if len(client_id) < 10: 45 | client_id_issues.append("Too short") 46 | if " " in client_id: 47 | client_id_issues.append("Contains spaces") 48 | if client_id != client_id.strip(): 49 | client_id_issues.append("Has leading/trailing whitespace") 50 | 51 | table.add_row( 52 | "CLIENT_ID", 53 | "✅" if not client_id_issues else "❌", 54 | f"{client_id[:4]}...{client_id[-4:]}" if len(client_id) > 8 else client_id if client_id else "N/A", 55 | str(len(client_id)) if client_id else "0", 56 | ", ".join(client_id_issues) if client_id_issues else "OK" 57 | ) 58 | 59 | # Validate CLIENT_SECRET 60 | client_secret_issues = [] 61 | if not client_secret: 62 | client_secret_issues.append("MISSING") 63 | else: 64 | if len(client_secret) < 10: 65 | client_secret_issues.append("Too short") 66 | if " " in client_secret: 67 | client_secret_issues.append("Contains spaces") 68 | if client_secret != client_secret.strip(): 69 | client_secret_issues.append("Has leading/trailing whitespace") 70 | 71 | table.add_row( 72 | "CLIENT_SECRET", 73 | "✅" if not client_secret_issues else "❌", 74 | f"{client_secret[:4]}...{client_secret[-4:]}" if len(client_secret) > 8 else "***" if client_secret else "N/A", 75 | str(len(client_secret)) if client_secret else "0", 76 | ", ".join(client_secret_issues) if client_secret_issues else "OK" 77 | ) 78 | 79 | # Validate REDIRECT_URI 80 | redirect_uri_issues = [] 81 | if not redirect_uri: 82 | redirect_uri_issues.append("MISSING") 83 | else: 84 | if not redirect_uri.startswith(("http://", "https://")): 85 | redirect_uri_issues.append("Invalid format") 86 | if " " in redirect_uri: 87 | redirect_uri_issues.append("Contains spaces") 88 | 89 | table.add_row( 90 | "REDIRECT_URI", 91 | "✅" if not redirect_uri_issues else "❌", 92 | redirect_uri if redirect_uri else "N/A", 93 | str(len(redirect_uri)) if redirect_uri else "0", 94 | ", ".join(redirect_uri_issues) if redirect_uri_issues else "OK" 95 | ) 96 | 97 | # Validate USER_AGENT 98 | user_agent_issues = [] 99 | if not user_agent: 100 | user_agent_issues.append("MISSING") 101 | else: 102 | if len(user_agent) < 5: 103 | user_agent_issues.append("Too short") 104 | if not any(char in user_agent for char in ['/', ' ']): 105 | user_agent_issues.append("Should follow format: AppName/Version by /u/username") 106 | 107 | table.add_row( 108 | "USER_AGENT", 109 | "✅" if not user_agent_issues else "❌", 110 | user_agent if user_agent else "N/A", 111 | str(len(user_agent)) if user_agent else "0", 112 | ", ".join(user_agent_issues) if user_agent_issues else "OK" 113 | ) 114 | 115 | # Validate REDDIT_USERNAME 116 | username_issues = [] 117 | if not reddit_username: 118 | username_issues.append("MISSING") 119 | 120 | table.add_row( 121 | "REDDIT_USERNAME", 122 | "✅" if not username_issues else "❌", 123 | reddit_username if reddit_username else "N/A", 124 | str(len(reddit_username)) if reddit_username else "0", 125 | ", ".join(username_issues) if username_issues else "OK" 126 | ) 127 | 128 | console.print(table) 129 | 130 | # Test credentials with Reddit API 131 | if client_id and client_secret and not (client_id_issues or client_secret_issues): 132 | console.print("\n[bold yellow]Testing credentials with Reddit API...[/bold yellow]") 133 | 134 | try: 135 | # Try to get an app-only access token (doesn't require user authorization) 136 | auth_string = f"{client_id}:{client_secret}" 137 | b64_auth = base64.b64encode(auth_string.encode()).decode() 138 | 139 | headers = { 140 | "Authorization": f"Basic {b64_auth}", 141 | "User-Agent": user_agent if user_agent else "CredentialValidator/1.0", 142 | "Content-Type": "application/x-www-form-urlencoded" 143 | } 144 | 145 | data = { 146 | "grant_type": "client_credentials" 147 | } 148 | 149 | console.print("Sending request to Reddit API...") 150 | response = requests.post( 151 | "https://www.reddit.com/api/v1/access_token", 152 | headers=headers, 153 | data=data, 154 | timeout=10 155 | ) 156 | 157 | console.print(f"\n[bold]Response Status Code:[/bold] {response.status_code}") 158 | console.print(f"[bold]Response Headers:[/bold] {dict(response.headers)}\n") 159 | 160 | if response.status_code == 200: 161 | console.print(Panel.fit( 162 | "[bold green]✅ SUCCESS![/bold green]\n\n" 163 | "Your CLIENT_ID and CLIENT_SECRET are valid!\n" 164 | "Reddit API accepted your credentials.", 165 | title="Authentication Test Result", 166 | border_style="green" 167 | )) 168 | result = response.json() 169 | console.print(f"\n[dim]Access token received: {result.get('access_token', '')[:20]}...[/dim]") 170 | elif response.status_code == 401: 171 | error_data = response.json() if response.headers.get('content-type', '').startswith('application/json') else {} 172 | console.print(Panel.fit( 173 | f"[bold red]❌ AUTHENTICATION FAILED[/bold red]\n\n" 174 | f"Status: {response.status_code}\n" 175 | f"Error: {error_data.get('error', 'Unknown')}\n" 176 | f"Message: {error_data.get('message', response.text)}\n\n" 177 | f"[yellow]Common causes:[/yellow]\n" 178 | f"1. CLIENT_ID is incorrect (should be the ID under your app name, NOT the secret)\n" 179 | f"2. CLIENT_SECRET is incorrect\n" 180 | f"3. Credentials have extra whitespace\n" 181 | f"4. App type mismatch (must be 'web app', NOT 'script')\n\n" 182 | f"[cyan]Full Response:[/cyan]\n{response.text}", 183 | title="Authentication Test Result", 184 | border_style="red" 185 | )) 186 | else: 187 | console.print(Panel.fit( 188 | f"[bold yellow]⚠️ UNEXPECTED RESPONSE[/bold yellow]\n\n" 189 | f"Status: {response.status_code}\n" 190 | f"Response: {response.text}", 191 | title="Authentication Test Result", 192 | border_style="yellow" 193 | )) 194 | 195 | except requests.exceptions.RequestException as e: 196 | console.print(Panel.fit( 197 | f"[bold red]❌ NETWORK ERROR[/bold red]\n\n" 198 | f"Could not connect to Reddit API:\n{str(e)}", 199 | title="Connection Test Result", 200 | border_style="red" 201 | )) 202 | except Exception as e: 203 | console.print(Panel.fit( 204 | f"[bold red]❌ ERROR[/bold red]\n\n{str(e)}", 205 | title="Test Result", 206 | border_style="red" 207 | )) 208 | else: 209 | console.print("\n[bold red]⚠️ Cannot test credentials - please fix the issues above first.[/bold red]") 210 | 211 | # Print helpful instructions 212 | console.print("\n[bold cyan]How to find your credentials:[/bold cyan]") 213 | console.print("1. Go to: https://www.reddit.com/prefs/apps") 214 | console.print("2. Find your app or create a new one (type MUST be: 'web app')") 215 | console.print("3. CLIENT_ID: The string under your app name (14-22 characters)") 216 | console.print("4. CLIENT_SECRET: Click 'edit' to see the secret") 217 | console.print("5. REDIRECT_URI: Must EXACTLY match what you entered in Reddit app settings") 218 | console.print("\n[dim]Tip: The CLIENT_ID is NOT the same as the CLIENT_SECRET![/dim]\n") 219 | 220 | if __name__ == "__main__": 221 | main() 222 | -------------------------------------------------------------------------------- /reddit_fetch/main.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import sys 4 | 5 | import requests 6 | from reddit_fetch.api import fetch_saved_posts 7 | from reddit_fetch.auth import is_headless, is_docker, show_headless_instructions, load_tokens_safe 8 | from reddit_fetch.config import TOKEN_FILE 9 | from rich.console import Console 10 | from rich.prompt import Confirm, Prompt 11 | from rich.panel import Panel 12 | from rich.text import Text 13 | 14 | console = Console() 15 | 16 | DATA_DIR = "/data/" if os.getenv("DOCKER", "0") == "1" else "./" 17 | LAST_FETCH_FILE = f"{DATA_DIR}last_fetch.json" 18 | 19 | def is_interactive(): 20 | """Returns True if the script is running in an interactive terminal (TTY)""" 21 | try: 22 | return os.isatty(sys.stdin.fileno()) and os.isatty(sys.stdout.fileno()) 23 | except: 24 | return False 25 | 26 | def check_authentication(): 27 | """Check if authentication is available and show appropriate messages.""" 28 | tokens = load_tokens_safe() 29 | 30 | if not tokens: 31 | if is_headless(): 32 | console.print("\n❌ [bold red]Authentication tokens not found![/bold red]") 33 | show_headless_instructions() 34 | 35 | if is_docker(): 36 | console.print(Panel.fit( 37 | Text.from_markup( 38 | "[bold yellow]💡 QUICK DOCKER SETUP REMINDER:[/bold yellow]\n\n" 39 | "1. Generate tokens on a browser system:\n" 40 | " [bold]python generate_tokens.py[/bold]\n\n" 41 | "2. Copy tokens.json to your Docker data directory:\n" 42 | " [bold]cp tokens.json /path/to/data/[/bold]\n\n" 43 | "3. Restart the container:\n" 44 | " [bold]docker restart reddit-fetcher[/bold]" 45 | ), 46 | title="🚀 Docker Setup", 47 | border_style="blue" 48 | )) 49 | 50 | sys.exit(1) 51 | else: 52 | console.print("❌ [bold red]No authentication tokens found.[/bold red]") 53 | console.print("🔄 [yellow]Starting authentication process...[/yellow]") 54 | # On browser systems, the auth flow will handle token generation 55 | return False 56 | 57 | # Check if tokens are valid 58 | if "refresh_token" not in tokens: 59 | console.print("❌ [bold red]Invalid token file: missing refresh_token[/bold red]") 60 | if is_headless(): 61 | show_headless_instructions() 62 | sys.exit(1) 63 | return False 64 | 65 | console.print("✅ [bold green]Authentication tokens found and loaded.[/bold green]") 66 | return True 67 | 68 | def cli_entry(): 69 | console.print("\n🚀 [bold cyan]Welcome to Reddit Saved Posts Fetcher![/bold cyan]", style="bold yellow") 70 | console.print("Fetch and save your Reddit saved posts easily.\n", style="italic green") 71 | 72 | # Show environment information 73 | is_docker_env = is_docker() 74 | is_headless_env = is_headless() 75 | is_non_interactive = not is_interactive() 76 | 77 | console.print(f"🐳 Docker Environment: {'Yes' if is_docker_env else 'No'}", style="bold blue") 78 | console.print(f"🖥️ Headless System: {'Yes' if is_headless_env else 'No'}", style="bold blue") 79 | console.print(f"💬 Interactive Session: {'Yes' if not is_non_interactive else 'No'}", style="bold magenta") 80 | 81 | # Check authentication before proceeding 82 | if not check_authentication(): 83 | # If we're here, we're on a browser system but tokens are missing/invalid 84 | # The authentication will be handled by the API calls 85 | pass 86 | 87 | # Configure execution based on environment 88 | if is_docker_env or is_non_interactive: 89 | # Non-interactive mode - use environment variables 90 | format_choice = os.getenv("OUTPUT_FORMAT", "json") 91 | force_fetch = os.getenv("FORCE_FETCH", "false").lower() == "true" 92 | 93 | console.print(f"🔧 [bold blue]Non-interactive mode detected[/bold blue]") 94 | console.print(f"📄 Output format: [bold]{format_choice}[/bold]") 95 | console.print(f"🔄 Force fetch: [bold]{force_fetch}[/bold]") 96 | else: 97 | # Interactive mode - ask user for preferences 98 | try: 99 | format_choice = Prompt.ask("Select output format", choices=["json", "html"], default="json") 100 | force_fetch = Confirm.ask("Do you want to force fetch all saved posts?", default=False) 101 | except KeyboardInterrupt: 102 | console.print("\n👋 [yellow]Operation cancelled by user.[/yellow]") 103 | sys.exit(0) 104 | except Exception as e: 105 | console.print(f"\n❌ [bold red]Error getting user input: {e}[/bold red]") 106 | console.print("🔧 [yellow]Falling back to default settings...[/yellow]") 107 | format_choice = "json" 108 | force_fetch = False 109 | 110 | # Handle force fetch 111 | if force_fetch and os.path.exists(LAST_FETCH_FILE): 112 | try: 113 | os.remove(LAST_FETCH_FILE) 114 | console.print("🔄 [yellow]Force fetch enabled. Deleting last fetch record...[/yellow]") 115 | except Exception as e: 116 | console.print(f"⚠️ [yellow]Could not delete last fetch file: {e}[/yellow]") 117 | 118 | # Attempt to fetch posts 119 | try: 120 | console.print(f"\n📡 [bold blue]Starting to fetch saved posts...[/bold blue]") 121 | result = fetch_saved_posts(format=format_choice, force_fetch=force_fetch) 122 | 123 | if not result or result["count"] == 0: 124 | console.print("ℹ️ [bold blue]No posts were fetched. This could mean:[/bold blue]") 125 | console.print(" • No new posts since last fetch") 126 | console.print(" • No saved posts in your Reddit account") 127 | console.print(" • Authentication or API issues") 128 | return 129 | 130 | # Extract data from result 131 | posts_content = result["content"] 132 | posts_count = result["count"] 133 | result_format = result["format"] 134 | 135 | # Save the output 136 | output_file = f"{DATA_DIR}saved_posts.{result_format}" 137 | 138 | with open(output_file, "w", encoding="utf-8") as file: 139 | if result_format == "json": 140 | json.dump(posts_content, file, indent=4) 141 | else: 142 | file.write(posts_content) 143 | 144 | console.print(f"\n✅ [bold green]Successfully fetched {posts_count} posts![/bold green]") 145 | console.print(f"💾 Output saved to [bold green]{output_file}[/bold green]") 146 | 147 | if is_docker_env: 148 | console.print(f"🐳 [bold blue]File available in your mounted data directory[/bold blue]") 149 | 150 | except KeyboardInterrupt: 151 | console.print("\n👋 [yellow]Operation cancelled by user.[/yellow]") 152 | sys.exit(0) 153 | except PermissionError as e: 154 | console.print(f"\n❌ [bold red]Permission error: {e}[/bold red]") 155 | console.print("🔧 [yellow]Check file permissions for the output directory.[/yellow]") 156 | sys.exit(1) 157 | except FileNotFoundError as e: 158 | console.print(f"\n❌ [bold red]File not found: {e}[/bold red]") 159 | console.print("🔧 [yellow]Check that all required files exist.[/yellow]") 160 | sys.exit(1) 161 | except json.JSONDecodeError as e: 162 | console.print(f"\n❌ [bold red]JSON parsing error: {e}[/bold red]") 163 | console.print("🔧 [yellow]There may be corrupted data files. Try using --force-fetch.[/yellow]") 164 | sys.exit(1) 165 | except requests.exceptions.RequestException as e: 166 | console.print(f"\n❌ [bold red]Network error: {e}[/bold red]") 167 | console.print("🔧 [yellow]Check your internet connection and try again.[/yellow]") 168 | sys.exit(1) 169 | except (AttributeError, KeyError, TypeError) as e: 170 | if "access_token" in str(e) or "refresh_token" in str(e) or "401" in str(e) or "403" in str(e): 171 | # This looks like an authentication error 172 | console.print(f"\n❌ [bold red]Authentication error: {e}[/bold red]") 173 | if is_headless_env: 174 | console.print("🔧 [yellow]Authentication failed in headless environment.[/yellow]") 175 | show_headless_instructions() 176 | else: 177 | console.print("🔧 [yellow]Try running the authentication process again.[/yellow]") 178 | else: 179 | # This is likely a code/data structure error 180 | console.print(f"\n❌ [bold red]Data processing error: {e}[/bold red]") 181 | console.print("🔧 [yellow]This may be a bug. Please check the error details above.[/yellow]") 182 | console.print("💡 [blue]You can try using --force-fetch to start fresh.[/blue]") 183 | sys.exit(1) 184 | except Exception as e: 185 | # Generic error handling with better context 186 | error_str = str(e).lower() 187 | console.print(f"\n❌ [bold red]Unexpected error: {e}[/bold red]") 188 | 189 | if any(auth_keyword in error_str for auth_keyword in ['token', 'auth', '401', '403', 'unauthorized', 'forbidden']): 190 | # Likely authentication related 191 | console.print("🔧 [yellow]This appears to be an authentication issue.[/yellow]") 192 | if is_headless_env: 193 | show_headless_instructions() 194 | else: 195 | console.print("🔧 [yellow]Try regenerating your authentication tokens.[/yellow]") 196 | elif any(network_keyword in error_str for network_keyword in ['connection', 'timeout', 'network', 'dns']): 197 | # Likely network related 198 | console.print("🔧 [yellow]This appears to be a network connectivity issue.[/yellow]") 199 | console.print("💡 [blue]Check your internet connection and try again.[/blue]") 200 | else: 201 | # Unknown error 202 | console.print("🔧 [yellow]This may be a bug or unexpected condition.[/yellow]") 203 | console.print("💡 [blue]Please report this issue with the error details above.[/blue]") 204 | 205 | sys.exit(1) 206 | 207 | def main(): 208 | """Main entry point for the CLI.""" 209 | try: 210 | cli_entry() 211 | except Exception as e: 212 | console.print(f"\n💥 [bold red]Unexpected error: {e}[/bold red]") 213 | console.print("🐛 [yellow]Please report this issue if it persists.[/yellow]") 214 | sys.exit(1) 215 | 216 | if __name__ == "__main__": 217 | console.print("🟢 Script reached __main__, calling cli_entry()", style="bold magenta") 218 | cli_entry() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Reddit Saved Posts Fetcher 3 | 4 | Automatically fetch and export your saved Reddit posts and comments to JSON or HTML format. 5 | 6 | ## Features 7 | 8 | * **Incremental Sync** - Only fetches new posts since last run 9 | * **Force Fetch** - Option to re-download all saved posts 10 | * **Multiple Formats** - Export to JSON or HTML bookmarks 11 | * **Docker Support** - Easy containerized deployment 12 | * **Smart Authentication** - Handles token refresh automatically 13 | * **Credential Validator** - Built-in tool to diagnose authentication issues 14 | 15 | ## File Location Summary 16 | 17 | Understanding where to place `.env` and `tokens.json` for each method: 18 | 19 | ### Method 1: CLI Script 20 | ``` 21 | your-project/ # Git clone directory 22 | ├── .env # Create here 23 | ├── tokens.json # Generated here 24 | ├── saved_posts.json # Output here 25 | └── reddit_fetch/ # Source code 26 | ``` 27 | 28 | ### Method 2: Build Your Own Image 29 | ``` 30 | # Source directory (for building) 31 | Reddit-Fetch/ 32 | ├── .env # Create here for auth generation 33 | ├── tokens.json # Generated here 34 | └── Dockerfile # Build from here 35 | 36 | # Deployment directory (for running) 37 | reddit-fetcher-deploy/ 38 | ├── docker-compose.yml 39 | ├── .env # Copy from source directory 40 | └── data/ 41 | └── tokens.json # Copy from source directory 42 | ``` 43 | 44 | ### Method 3: Pre-built Image 45 | ``` 46 | # Source directory (any computer with browser) 47 | temp-auth-setup/ 48 | ├── .env # Create here for auth generation 49 | └── tokens.json # Generated here 50 | 51 | # Deployment directory (VPS/server) 52 | reddit-fetcher-docker/ 53 | ├── docker-compose.yml 54 | ├── .env # Copy from source directory 55 | └── data/ 56 | └── tokens.json # Copy from source directory 57 | ``` 58 | 59 | --- 60 | 61 | ## Prerequisites 62 | 63 | ### Get Reddit API Credentials 64 | 65 | 1. Go to [Reddit Apps](https://www.reddit.com/prefs/apps) 66 | 2. Click **"Create App"** or **"Create Another App"** 67 | 3. Fill out the form: 68 | * **Name** : `My Reddit Fetcher` (or any name) 69 | * **App type** : Select **"web app"** (NOT "script") 70 | * **Redirect URI** : `http://localhost:8080` 71 | 4. Click **"Create app"** 72 | 5. Copy your credentials: 73 | * **Client ID**: The short string UNDER your app name (14-22 characters, e.g., `DyPeM38zXGcvax`) 74 | * **Client Secret**: Click "edit" to reveal the longer secret string 75 | 76 | **Common mistakes**: 77 | - The CLIENT_ID is the small text under your app name, NOT the secret! 78 | - App type must be "web app" for OAuth to work properly 79 | 80 | --- 81 | 82 | ## Usage Methods 83 | 84 | Choose one of these three methods: 85 | 86 | ## Method 1: CLI Script (Local Development) 87 | 88 | **Best for** : Testing, development, one-time use 89 | 90 | ### Setup 91 | 92 | ```bash 93 | git clone https://github.com/your-username/Reddit-Fetch.git 94 | cd Reddit-Fetch 95 | 96 | # Create virtual environment (recommended) 97 | python3 -m venv venv 98 | source venv/bin/activate # On Windows: venv\Scripts\activate 99 | 100 | # Install package and dependencies 101 | pip install -e . 102 | ``` 103 | 104 | ### Configure 105 | 106 | Create a `.env` file: 107 | 108 | ```ini 109 | CLIENT_ID=your_client_id_here 110 | CLIENT_SECRET=your_client_secret_here 111 | REDIRECT_URI=http://localhost:8080 112 | USER_AGENT=RedditFetcher/1.0 (by /u/your_reddit_username) 113 | REDDIT_USERNAME=your_reddit_username 114 | ``` 115 | 116 | **Important**: Make sure there are no extra spaces or quotes around your credentials! 117 | 118 | ### Validate Credentials (Recommended) 119 | 120 | Before authenticating, test your credentials to avoid common issues: 121 | 122 | ```bash 123 | python validate_credentials.py 124 | ``` 125 | 126 | This script will: 127 | - Check if all required credentials are present 128 | - Validate credential format 129 | - Test your CLIENT_ID and CLIENT_SECRET with Reddit API 130 | - Show detailed error messages if something is wrong 131 | 132 | ### Authenticate 133 | 134 | ```bash 135 | python generate_tokens.py 136 | ``` 137 | 138 | This opens your browser to authorize the app and creates `tokens.json`. 139 | 140 | ### Run 141 | 142 | ```bash 143 | # Interactive mode 144 | reddit-fetcher 145 | 146 | # Non-interactive mode 147 | OUTPUT_FORMAT=json FORCE_FETCH=false reddit-fetcher 148 | ``` 149 | 150 | --- 151 | 152 | ## Method 2: Build Your Own Docker Image 153 | 154 | **Best for** : Custom modifications, self-hosted environments 155 | 156 | ### Step 1: Prepare Authentication (on a computer with browser) 157 | 158 | ```bash 159 | git clone https://github.com/your-username/Reddit-Fetch.git 160 | cd Reddit-Fetch 161 | 162 | # Create virtual environment 163 | python3 -m venv venv 164 | source venv/bin/activate 165 | 166 | # Install package and dependencies 167 | pip install -e . 168 | ``` 169 | 170 | Create `.env` file: 171 | 172 | ```ini 173 | CLIENT_ID=your_client_id_here 174 | CLIENT_SECRET=your_client_secret_here 175 | REDIRECT_URI=http://localhost:8080 176 | USER_AGENT=RedditFetcher/1.0 (by /u/your_reddit_username) 177 | REDDIT_USERNAME=your_reddit_username 178 | ``` 179 | 180 | **Important**: No extra spaces or quotes around credentials! 181 | 182 | Validate credentials (recommended): 183 | 184 | ```bash 185 | python validate_credentials.py 186 | ``` 187 | 188 | Generate tokens: 189 | 190 | ```bash 191 | python generate_tokens.py 192 | ``` 193 | 194 | ### Step 2: Build Docker Image 195 | 196 | ```bash 197 | docker build -t reddit-fetcher . 198 | ``` 199 | 200 | ### Step 3: Prepare Files for Container 201 | 202 | ```bash 203 | # Create data directory 204 | mkdir -p ./data 205 | 206 | # Copy authentication tokens 207 | cp tokens.json ./data/ 208 | ``` 209 | 210 | ### Step 4: Run Container 211 | 212 | ```bash 213 | # One-time run 214 | docker run --rm \ 215 | --env-file .env \ 216 | -e OUTPUT_FORMAT=json \ 217 | -e FORCE_FETCH=false \ 218 | -v $(pwd)/data:/data \ 219 | reddit-fetcher 220 | 221 | # Or use docker-compose.yml 222 | docker-compose up -d 223 | ``` 224 | 225 | **docker-compose.yml:** 226 | 227 | ```yaml 228 | version: '3.8' 229 | services: 230 | reddit-fetcher: 231 | build: . # Builds from local Dockerfile 232 | container_name: reddit-fetcher 233 | env_file: .env 234 | environment: 235 | - DOCKER=1 236 | - FETCH_INTERVAL=86400 # Run every 24 hours 237 | - OUTPUT_FORMAT=json 238 | - FORCE_FETCH=false 239 | volumes: 240 | - ./data:/data 241 | restart: unless-stopped 242 | ``` 243 | 244 | --- 245 | 246 | ## Method 3: Use Pre-built Docker Image (Recommended) 247 | 248 | **Best for** : Production use, quick deployment, automated scheduling 249 | 250 | ### Step 1: Prepare Authentication (on a computer with browser) 251 | 252 | **⚠️ Important** : You must do this step on a computer with a web browser first. 253 | 254 | ```bash 255 | git clone https://github.com/your-username/Reddit-Fetch.git 256 | cd Reddit-Fetch 257 | 258 | # Create virtual environment 259 | python3 -m venv venv 260 | source venv/bin/activate 261 | 262 | # Install package and dependencies 263 | pip install -e . 264 | ``` 265 | 266 | Create `.env` file: 267 | 268 | ```ini 269 | CLIENT_ID=your_client_id_here 270 | CLIENT_SECRET=your_client_secret_here 271 | REDIRECT_URI=http://localhost:8080 272 | USER_AGENT=RedditFetcher/1.0 (by /u/your_reddit_username) 273 | REDDIT_USERNAME=your_reddit_username 274 | ``` 275 | 276 | **⚠️ Important**: No extra spaces or quotes around credentials! 277 | 278 | Validate credentials (recommended): 279 | 280 | ```bash 281 | python validate_credentials.py 282 | ``` 283 | 284 | Generate authentication tokens: 285 | 286 | ```bash 287 | python generate_tokens.py 288 | ``` 289 | 290 | ### Step 2: Prepare Docker Environment 291 | 292 | **Copy files to your Docker server:** 293 | 294 | ```bash 295 | # Create project directory 296 | mkdir reddit-fetcher-docker 297 | cd reddit-fetcher-docker 298 | 299 | # Copy .env file to project directory 300 | cp /path/to/Reddit-Fetch/.env . 301 | 302 | # Create data directory and copy tokens 303 | mkdir data 304 | cp /path/to/Reddit-Fetch/tokens.json ./data/ 305 | ``` 306 | 307 | ### Step 3: Create docker-compose.yml 308 | 309 | ```yaml 310 | version: '3.8' 311 | services: 312 | reddit-fetcher: 313 | image: pandeyak/reddit-fetcher:latest # Pre-built image from Docker Hub 314 | container_name: reddit-fetcher 315 | env_file: .env # Loads Reddit API credentials 316 | environment: 317 | - DOCKER=1 318 | - FETCH_INTERVAL=86400 # Run every 24 hours (in seconds) 319 | - OUTPUT_FORMAT=json # Choose: json or html 320 | - FORCE_FETCH=false # Set to true to fetch all posts 321 | volumes: 322 | - ./data:/data # Maps local data directory to container 323 | restart: unless-stopped 324 | ``` 325 | 326 | ### Step 4: Run 327 | 328 | ```bash 329 | # Start the container 330 | docker-compose up -d 331 | 332 | # View logs 333 | docker-compose logs -f 334 | 335 | # Stop the container 336 | docker-compose down 337 | ``` 338 | 339 | ### File Structure for Method 3: 340 | 341 | ``` 342 | reddit-fetcher-docker/ 343 | ├── docker-compose.yml 344 | ├── .env # Reddit API credentials 345 | └── data/ 346 | ├── tokens.json # Authentication tokens (copied from Step 1) 347 | ├── saved_posts.json # Output file (generated) 348 | └── last_fetch.json # Tracking file (generated) 349 | ``` 350 | 351 | --- 352 | 353 | ## Configuration Options 354 | 355 | ### Environment Variables 356 | 357 | | Variable | Description | Default | Required | 358 | | ------------------- | ------------------------------------ | ------------------------- | -------- | 359 | | `CLIENT_ID` | Reddit app client ID | - | ✅ | 360 | | `CLIENT_SECRET` | Reddit app client secret | - | ✅ | 361 | | `REDIRECT_URI` | OAuth redirect URI | `http://localhost:8080` | ✅ | 362 | | `USER_AGENT` | Reddit API user agent | - | ✅ | 363 | | `REDDIT_USERNAME` | Your Reddit username | - | ✅ | 364 | | `OUTPUT_FORMAT` | Export format:`json`or `html` | `json` | ❌ | 365 | | `FORCE_FETCH` | Fetch all posts:`true`or `false` | `false` | ❌ | 366 | | `FETCH_INTERVAL` | Seconds between runs (Docker only) | `86400` | ❌ | 367 | 368 | ### Docker-specific Commands 369 | 370 | ```bash 371 | # One-time run with pre-built image 372 | docker run --rm \ 373 | --env-file .env \ 374 | -e OUTPUT_FORMAT=json \ 375 | -e FORCE_FETCH=false \ 376 | -v $(pwd)/data:/data \ 377 | pandeyak/reddit-fetcher:latest 378 | 379 | # Force fetch all posts 380 | docker run --rm \ 381 | --env-file .env \ 382 | -e FORCE_FETCH=true \ 383 | -v $(pwd)/data:/data \ 384 | pandeyak/reddit-fetcher:latest 385 | ``` 386 | 387 | --- 388 | 389 | ## Using as Python Library 390 | 391 | ```python 392 | from reddit_fetch.api import fetch_saved_posts 393 | 394 | # Fetch new posts in JSON format 395 | result = fetch_saved_posts(format="json", force_fetch=False) 396 | print(f"Found {result['count']} new posts") 397 | 398 | # Access the posts 399 | posts = result['content'] 400 | for post in posts: 401 | print(f"- {post['title']} (r/{post['subreddit']})") 402 | ``` 403 | 404 | --- 405 | 406 | ## Output Files 407 | 408 | ### JSON Format (`saved_posts.json`) 409 | 410 | ```json 411 | [ 412 | { 413 | "title": "Amazing post title", 414 | "url": "https://reddit.com/r/example/...", 415 | "subreddit": "example", 416 | "created_utc": 1649123456, 417 | "fullname": "t3_abc123", 418 | "type": "post", 419 | "author": "username", 420 | "score": 42 421 | } 422 | ] 423 | ``` 424 | 425 | ### HTML Format (`saved_posts.html`) 426 | 427 | Beautiful HTML file with styled bookmarks, perfect for importing into bookmark managers. 428 | 429 | --- 430 | 431 | ## Troubleshooting 432 | 433 | ### Authentication Issues 434 | 435 | **Error: "Invalid client id" or "401 Unauthorized"** 436 | 437 | This is the most common issue! Run the credential validator first: 438 | 439 | ```bash 440 | python validate_credentials.py 441 | ``` 442 | 443 | **Common causes:** 444 | 445 | 1. **CLIENT_ID is incorrect** 446 | - The CLIENT_ID is the string UNDER your app name (14-22 characters) 447 | - It's NOT the same as CLIENT_SECRET 448 | - Find it at: https://www.reddit.com/prefs/apps 449 | 450 | 2. **Extra whitespace in credentials** 451 | - Remove any quotes, spaces, or line breaks from your .env file 452 | - Example: `CLIENT_ID=abc123` (NOT `CLIENT_ID= abc123 `) 453 | 454 | 3. **CLIENT_SECRET is incorrect** 455 | - Click "edit" on your Reddit app to see the secret 456 | - Make sure you copied the entire secret 457 | 458 | 4. **REDIRECT_URI doesn't match** 459 | - Must EXACTLY match what's in your Reddit app settings 460 | - Common: `http://localhost:8080` (note: http, not https) 461 | 462 | 5. **App type mismatch** 463 | - Your Reddit app MUST be type "web app" 464 | - If you created a "script" type app, delete it and create a new "web app" 465 | 466 | **Error: "No authentication tokens found"** 467 | 468 | * **CLI** : Make sure `tokens.json` exists in project directory 469 | * **Docker** : Ensure `tokens.json` is in the `data/` directory 470 | * **Solution** : Regenerate tokens with `python generate_tokens.py` 471 | 472 | **Error: "Failed to refresh access token"** 473 | 474 | * Delete `tokens.json` and regenerate tokens 475 | * Check that your Reddit app credentials are correct 476 | * Run `python validate_credentials.py` to diagnose 477 | 478 | ### Docker Issues 479 | 480 | **Error: "Cannot open web browser" in Docker** 481 | 482 | * This is expected! Docker containers can't open browsers 483 | * You must generate tokens on a computer with a browser first (Step 1) 484 | 485 | **Error: "Permission denied" in Docker** 486 | 487 | * Fix file permissions: `chmod 644 tokens.json .env` 488 | * Fix directory permissions: `chmod 755 data/` 489 | 490 | **Error: "File not found" in Docker** 491 | 492 | * Verify file structure matches the example above 493 | * Ensure `.env` and `tokens.json` are in correct locations 494 | 495 | ### General Issues 496 | 497 | **"No new posts found"** 498 | 499 | * Check if you have new saved posts on Reddit 500 | * Try force fetch: Set `FORCE_FETCH=true` 501 | * Verify `REDDIT_USERNAME` in `.env` is correct 502 | 503 | **"Headless system detected" on desktop** 504 | 505 | * Override detection: `REDDIT_FETCHER_HEADLESS=false reddit-fetcher` 506 | 507 | --- 508 | 509 | ## Method Comparison 510 | 511 | | Feature | CLI Script | Build Docker | Pre-built Docker | 512 | | ------------------------- | --------------- | ------------- | ---------------- | 513 | | **Setup Time** | Fast | Medium | Fast | 514 | | **Customization** | Full | Full | Limited | 515 | | **Dependencies** | Python required | Docker only | Docker only | 516 | | **Auto-scheduling** | Manual/cron | Built-in | Built-in | 517 | | **Updates** | Git pull | Rebuild image | Pull new image | 518 | | **Best for** | Development | Custom needs | Production | 519 | 520 | --- 521 | 522 | ## Contributing 523 | 524 | Contributions welcome! Please feel free to submit issues and pull requests. 525 | 526 | ## License 527 | 528 | MIT License - see LICENSE file for details. 529 | -------------------------------------------------------------------------------- /reddit_fetch/auth.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import json 4 | import time 5 | import requests 6 | import base64 7 | import threading 8 | import webbrowser 9 | from http.server import BaseHTTPRequestHandler, HTTPServer 10 | from urllib.parse import urlparse, parse_qs 11 | from reddit_fetch.config import CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, USER_AGENT, TOKEN_FILE 12 | from rich.console import Console 13 | from rich.panel import Panel 14 | from rich.text import Text 15 | 16 | console = Console() 17 | 18 | # Global variable to store the authorization code 19 | auth_code = None 20 | 21 | def is_headless(): 22 | """Detects if the system is running in headless mode.""" 23 | # Manual override via environment variable 24 | headless_override = os.environ.get("REDDIT_FETCHER_HEADLESS") 25 | if headless_override is not None: 26 | return headless_override.lower() in ['1', 'true', 'yes'] 27 | 28 | # Explicit Docker indicators (high confidence) 29 | if (os.environ.get("DOCKER") == "1" or 30 | os.path.exists("/.dockerenv")): 31 | return True 32 | 33 | # SSH connections (high confidence) 34 | if (os.environ.get("SSH_CONNECTION") or 35 | os.environ.get("SSH_CLIENT")): 36 | return True 37 | 38 | # Check if we can actually open a browser 39 | try: 40 | import webbrowser 41 | browser = webbrowser.get() 42 | if not browser: 43 | return True 44 | except Exception: 45 | return True 46 | 47 | # Platform-specific GUI checks 48 | if sys.platform.startswith('linux'): 49 | # On Linux, check for GUI environment more carefully 50 | display = os.environ.get("DISPLAY") 51 | xdg_session = os.environ.get("XDG_SESSION_TYPE") 52 | wayland_display = os.environ.get("WAYLAND_DISPLAY") 53 | 54 | # If we have either X11 or Wayland, probably not headless 55 | if display or wayland_display: 56 | # But check if it's just a TTY session 57 | if xdg_session in ['tty', 'console']: 58 | return True 59 | return False 60 | else: 61 | # No display variables - likely headless 62 | return True 63 | 64 | elif sys.platform == 'darwin': # macOS 65 | # macOS usually has GUI unless explicitly headless 66 | return False 67 | 68 | elif sys.platform == 'win32': # Windows 69 | # Windows usually has GUI 70 | return False 71 | 72 | # Default: if we can't determine, assume GUI is available 73 | return False 74 | 75 | def is_docker(): 76 | """Detects if running inside Docker container.""" 77 | return ( 78 | os.environ.get("DOCKER") == "1" 79 | or os.path.exists("/.dockerenv") 80 | or os.path.exists("/proc/1/cgroup") and "docker" in open("/proc/1/cgroup").read() 81 | ) 82 | 83 | def show_headless_instructions(): 84 | """Shows instructions for headless authentication.""" 85 | authorization_url = ( 86 | f"https://www.reddit.com/api/v1/authorize?client_id={CLIENT_ID}&response_type=code" 87 | f"&state=RANDOM_STRING&redirect_uri={REDIRECT_URI}&duration=permanent&scope=identity history read save" 88 | ) 89 | 90 | if is_docker(): 91 | # Docker-specific instructions 92 | console.print(Panel.fit( 93 | Text.from_markup( 94 | "[bold red]🐳 DOCKER CONTAINER DETECTED[/bold red]\n\n" 95 | "[bold yellow]Authentication tokens are required but missing![/bold yellow]\n\n" 96 | "[white]This Docker container cannot open a web browser for authentication.\n" 97 | "You need to generate tokens on a system with a web browser.\n\n" 98 | "[bold cyan]SOLUTION:[/bold cyan]\n" 99 | "1. On a computer with a web browser, clone this repo\n" 100 | "2. Install dependencies: [bold]pip install -e .[/bold]\n" 101 | "3. Create a .env file with your Reddit API credentials\n" 102 | "4. Run: [bold]python generate_tokens.py[/bold]\n" 103 | "5. Copy the generated [bold]tokens.json[/bold] to your Docker data directory\n" 104 | "6. Restart this container\n\n" 105 | "[dim]For detailed instructions, see the README.md file.[/dim]" 106 | ), 107 | title="🔑 Authentication Required", 108 | border_style="red" 109 | )) 110 | else: 111 | # General headless instructions 112 | console.print(Panel.fit( 113 | Text.from_markup( 114 | "[bold red]🖥️ HEADLESS SYSTEM DETECTED[/bold red]\n\n" 115 | "[bold yellow]Cannot open web browser for authentication![/bold yellow]\n\n" 116 | "[white]This system doesn't have a GUI or web browser available.\n" 117 | "You need to authenticate on a system with a web browser.\n\n" 118 | "[bold cyan]SOLUTION:[/bold cyan]\n" 119 | "1. On a computer with a web browser:\n" 120 | " • Open this URL in your browser:\n" 121 | f" [link]{authorization_url}[/link]\n\n" 122 | " • Complete the Reddit authorization\n" 123 | " • Copy the authorization code from the redirect URL\n\n" 124 | "2. Or generate tokens using the browser system:\n" 125 | " • Run [bold]python generate_tokens.py[/bold] on browser system\n" 126 | " • Copy [bold]tokens.json[/bold] to this headless system\n\n" 127 | "[bold red]MANUAL AUTHENTICATION URL:[/bold red]\n" 128 | f"[link]{authorization_url}[/link]\n\n" 129 | "[dim]For detailed instructions, see the README.md file.[/dim]" 130 | ), 131 | title="🔑 Authentication Required", 132 | border_style="red" 133 | )) 134 | 135 | return None 136 | 137 | def load_tokens_safe(): 138 | """Handles token loading safely, ensuring better error handling in headless mode.""" 139 | if not os.path.exists(TOKEN_FILE): 140 | console.print("❌ [bold red]No authentication tokens found.[/bold red]") 141 | return None 142 | 143 | try: 144 | with open(TOKEN_FILE, "r", encoding="utf-8") as file: 145 | tokens = json.load(file) 146 | console.print("✅ [bold green]Authentication tokens loaded successfully.[/bold green]") 147 | return tokens 148 | except json.JSONDecodeError: 149 | console.print("❌ [bold red]Token file is corrupted. Please re-authenticate.[/bold red]") 150 | return None 151 | except Exception as e: 152 | console.print(f"❌ [bold red]Error loading tokens: {e}[/bold red]") 153 | return None 154 | 155 | def save_tokens(tokens): 156 | """Safely saves tokens to `tokens.json`.""" 157 | try: 158 | with open(TOKEN_FILE, "w", encoding="utf-8") as file: 159 | json.dump(tokens, file, indent=2) 160 | console.print(f"💾 [bold green]Tokens saved to {TOKEN_FILE}[/bold green]") 161 | except Exception as e: 162 | console.print(f"❌ [bold red]Error saving tokens: {e}[/bold red]") 163 | 164 | def refresh_access_token_safe(): 165 | """Refreshes the access token and handles headless system failures.""" 166 | tokens = load_tokens_safe() 167 | if not tokens or "refresh_token" not in tokens: 168 | console.print("❌ [bold red]No refresh token found. Re-authentication required.[/bold red]") 169 | 170 | # Check if we're in a headless environment 171 | if is_headless(): 172 | show_headless_instructions() 173 | return None 174 | else: 175 | # Try to get new tokens on systems with browsers 176 | return get_new_tokens() 177 | 178 | refresh_token = tokens["refresh_token"] 179 | auth_string = f"{CLIENT_ID}:{CLIENT_SECRET}" 180 | b64_auth = base64.b64encode(auth_string.encode()).decode() 181 | 182 | headers = { 183 | "Authorization": f"Basic {b64_auth}", 184 | "User-Agent": USER_AGENT, 185 | "Content-Type": "application/x-www-form-urlencoded" 186 | } 187 | data = { 188 | "grant_type": "refresh_token", 189 | "refresh_token": refresh_token 190 | } 191 | 192 | try: 193 | response = requests.post("https://www.reddit.com/api/v1/access_token", 194 | headers=headers, data=data, timeout=30) 195 | 196 | if response.status_code == 200: 197 | new_token_data = response.json() 198 | access_token = new_token_data.get("access_token") 199 | 200 | if access_token: 201 | tokens["access_token"] = access_token 202 | tokens["timestamp"] = time.time() 203 | 204 | # Update refresh token if provided 205 | if "refresh_token" in new_token_data: 206 | tokens["refresh_token"] = new_token_data["refresh_token"] 207 | 208 | save_tokens(tokens) 209 | console.print("🔄 [bold green]Access token refreshed successfully.[/bold green]") 210 | return access_token 211 | else: 212 | console.print("❌ [bold red]Invalid access token received from Reddit.[/bold red]") 213 | else: 214 | error_detail = "" 215 | try: 216 | error_json = response.json() 217 | error_detail = f"\nError: {error_json.get('error', 'Unknown')}" 218 | if 'message' in error_json: 219 | error_detail += f"\nMessage: {error_json['message']}" 220 | except: 221 | error_detail = f"\nResponse: {response.text}" 222 | 223 | console.print(f"❌ [bold red]Failed to refresh access token: {response.status_code}{error_detail}[/bold red]") 224 | 225 | if response.status_code == 401: 226 | console.print("[yellow]Possible causes:[/yellow]") 227 | console.print("1. CLIENT_ID or CLIENT_SECRET changed or incorrect") 228 | console.print("2. Refresh token expired or revoked") 229 | console.print("3. Credentials have whitespace issues") 230 | 231 | except requests.exceptions.RequestException as e: 232 | console.print(f"❌ [bold red]Network error while refreshing token: {e}[/bold red]") 233 | except Exception as e: 234 | console.print(f"❌ [bold red]Unexpected error while refreshing token: {e}[/bold red]") 235 | 236 | # Refresh failed - handle based on environment 237 | if is_headless(): 238 | console.print("❌ [bold red]Token refresh failed in headless environment.[/bold red]") 239 | show_headless_instructions() 240 | return None 241 | else: 242 | console.print("🔄 [yellow]Token refresh failed, attempting to get new tokens...[/yellow]") 243 | return get_new_tokens() 244 | 245 | def validate_credentials(): 246 | """Validates Reddit API credentials format.""" 247 | issues = [] 248 | 249 | if not CLIENT_ID: 250 | issues.append("CLIENT_ID is missing") 251 | elif len(CLIENT_ID) < 10: 252 | issues.append(f"CLIENT_ID seems too short ({len(CLIENT_ID)} chars, expected 14-22)") 253 | elif " " in CLIENT_ID: 254 | issues.append("CLIENT_ID contains spaces (this will cause authentication to fail)") 255 | 256 | if not CLIENT_SECRET: 257 | issues.append("CLIENT_SECRET is missing") 258 | elif len(CLIENT_SECRET) < 10: 259 | issues.append(f"CLIENT_SECRET seems too short ({len(CLIENT_SECRET)} chars)") 260 | elif " " in CLIENT_SECRET: 261 | issues.append("CLIENT_SECRET contains spaces (this will cause authentication to fail)") 262 | 263 | if not REDIRECT_URI: 264 | issues.append("REDIRECT_URI is missing") 265 | elif not REDIRECT_URI.startswith(("http://", "https://")): 266 | issues.append(f"REDIRECT_URI must start with http:// or https:// (got: {REDIRECT_URI})") 267 | 268 | if not USER_AGENT: 269 | issues.append("USER_AGENT is missing") 270 | elif len(USER_AGENT) < 5: 271 | issues.append("USER_AGENT seems too short") 272 | 273 | if issues: 274 | console.print("❌ [bold red]Credential validation failed:[/bold red]") 275 | for issue in issues: 276 | console.print(f" • {issue}") 277 | console.print("\n[cyan]Run 'python validate_credentials.py' for detailed diagnostics[/cyan]") 278 | return False 279 | 280 | return True 281 | 282 | def get_new_tokens(): 283 | """Requests new authentication tokens via OAuth.""" 284 | # Check if we're in a headless environment first 285 | if is_headless(): 286 | console.print("❌ [bold red]Cannot authenticate in headless environment.[/bold red]") 287 | show_headless_instructions() 288 | return None 289 | 290 | global auth_code 291 | 292 | # Validate credentials format 293 | if not validate_credentials(): 294 | return None 295 | 296 | try: 297 | threading.Thread(target=start_auth_server, daemon=True).start() 298 | 299 | authorization_url = ( 300 | f"https://www.reddit.com/api/v1/authorize?client_id={CLIENT_ID}&response_type=code" 301 | f"&state=RANDOM_STRING&redirect_uri={REDIRECT_URI}&duration=permanent&scope=identity history read save" 302 | ) 303 | 304 | console.print("🌍 [bold yellow]Opening Reddit authorization page in your browser...[/bold yellow]") 305 | 306 | if webbrowser.open(authorization_url): 307 | console.print("✅ Browser opened successfully") 308 | else: 309 | console.print("⚠️ [yellow]Could not open browser automatically.[/yellow]") 310 | console.print(f"Please manually visit: [link]{authorization_url}[/link]") 311 | 312 | # Wait for authorization code with timeout 313 | timeout = 300 # 5 minutes 314 | start_time = time.time() 315 | 316 | while auth_code is None: 317 | if time.time() - start_time > timeout: 318 | console.print("❌ [bold red]Authentication timeout. Please try again.[/bold red]") 319 | return None 320 | time.sleep(0.1) 321 | 322 | # Exchange code for tokens 323 | auth_string = f"{CLIENT_ID}:{CLIENT_SECRET}" 324 | b64_auth = base64.b64encode(auth_string.encode()).decode() 325 | 326 | url = "https://www.reddit.com/api/v1/access_token" 327 | headers = { 328 | "Authorization": f"Basic {b64_auth}", 329 | "User-Agent": USER_AGENT, 330 | "Content-Type": "application/x-www-form-urlencoded" 331 | } 332 | data = { 333 | "grant_type": "authorization_code", 334 | "code": auth_code, 335 | "redirect_uri": REDIRECT_URI 336 | } 337 | 338 | response = requests.post(url, headers=headers, data=data, timeout=30) 339 | 340 | if response.status_code == 200: 341 | tokens = response.json() 342 | tokens["timestamp"] = time.time() 343 | save_tokens(tokens) 344 | console.print("✅ [bold green]Authentication successful! Tokens saved.[/bold green]") 345 | return tokens["access_token"] 346 | else: 347 | error_detail = "" 348 | try: 349 | error_json = response.json() 350 | error_detail = f"\nError: {error_json.get('error', 'Unknown')}" 351 | if 'message' in error_json: 352 | error_detail += f"\nMessage: {error_json['message']}" 353 | except: 354 | error_detail = f"\nResponse: {response.text}" 355 | 356 | console.print(f"❌ [bold red]Authentication failed: {response.status_code}{error_detail}[/bold red]") 357 | 358 | if response.status_code == 401: 359 | console.print("\n[yellow]Common causes of 401 Unauthorized:[/yellow]") 360 | console.print("1. CLIENT_ID is incorrect (check it matches your Reddit app)") 361 | console.print("2. CLIENT_SECRET is incorrect") 362 | console.print("3. Credentials have leading/trailing whitespace") 363 | console.print("4. REDIRECT_URI doesn't match your Reddit app settings exactly") 364 | console.print("\n[cyan]Run 'python validate_credentials.py' to test your credentials[/cyan]") 365 | 366 | return None 367 | 368 | except Exception as e: 369 | console.print(f"❌ [bold red]Authentication error: {e}[/bold red]") 370 | return None 371 | 372 | class AuthHandler(BaseHTTPRequestHandler): 373 | def do_GET(self): 374 | global auth_code 375 | query_components = parse_qs(urlparse(self.path).query) 376 | if "code" in query_components: 377 | auth_code = query_components["code"][0].strip() 378 | self.send_response(200) 379 | self.end_headers() 380 | self.wfile.write(b"Authorization successful! You can close this tab.") 381 | console.print(f"✅ [bold green]Authorization code received![/bold green]") 382 | else: 383 | self.send_response(400) 384 | self.end_headers() 385 | self.wfile.write(b"Error: Authorization code not found.") 386 | 387 | def log_message(self, format, *args): 388 | # Suppress HTTP server logs 389 | pass 390 | 391 | def start_auth_server(): 392 | """Start a temporary local web server to receive the OAuth callback.""" 393 | try: 394 | port = int(REDIRECT_URI.split(":")[-1]) 395 | server = HTTPServer(("localhost", port), AuthHandler) 396 | console.print(f"🌍 [bold blue]Waiting for authorization on {REDIRECT_URI}...[/bold blue]") 397 | server.handle_request() 398 | except OSError as e: 399 | if "Address already in use" in str(e): 400 | console.print(f"❌ [bold red]Port {REDIRECT_URI.split(':')[-1]} is already in use.[/bold red]") 401 | console.print("Please close other applications using this port or change REDIRECT_URI.") 402 | else: 403 | console.print(f"❌ [bold red]Server error: {e}[/bold red]") 404 | sys.exit(1) 405 | except Exception as e: 406 | console.print(f"❌ [bold red]Unexpected server error: {e}[/bold red]") 407 | sys.exit(1) -------------------------------------------------------------------------------- /reddit_fetch/api.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import requests 4 | import time 5 | from reddit_fetch.auth import load_tokens_safe, refresh_access_token_safe 6 | from reddit_fetch.config import USER_AGENT, REDDIT_USERNAME, exponential_backoff 7 | from rich.console import Console 8 | 9 | console = Console() 10 | 11 | DATA_DIR = "/data/" if os.getenv("DOCKER", "0") == "1" else "./" 12 | LAST_FETCH_FILE = f"{DATA_DIR}last_fetch.json" 13 | OUTPUT_JSON = f"{DATA_DIR}saved_posts.json" 14 | OUTPUT_HTML = f"{DATA_DIR}saved_posts.html" 15 | 16 | def get_valid_access_token(): 17 | """Gets a valid access token, refreshing if necessary.""" 18 | tokens = load_tokens_safe() 19 | if not tokens: 20 | console.print("❌ [bold red]No stored tokens found. Re-authenticating...[/bold red]") 21 | access_token = refresh_access_token_safe() 22 | if not access_token: 23 | console.print("❌ [bold red]Re-authentication failed. Exiting...[/bold red]") 24 | return None 25 | return access_token 26 | 27 | # Check if access token exists 28 | access_token = tokens.get("access_token") 29 | if not access_token: 30 | console.print("🔄 [yellow]No access token found, attempting to refresh...[/yellow]") 31 | access_token = refresh_access_token_safe() 32 | if not access_token: 33 | console.print("❌ [bold red]Failed to get access token. Manual re-authentication needed.[/bold red]") 34 | return None 35 | return access_token 36 | 37 | # Check if access token is expired (if timestamp exists) 38 | if "timestamp" in tokens: 39 | time_elapsed = time.time() - tokens["timestamp"] 40 | # Reddit access tokens typically expire after 3600 seconds (1 hour) 41 | if time_elapsed > 3300: # 55 minutes buffer 42 | console.print("⏰ [yellow]Access token appears expired, refreshing...[/yellow]") 43 | access_token = refresh_access_token_safe() 44 | if not access_token: 45 | console.print("❌ [bold red]Failed to refresh expired token.[/bold red]") 46 | return None 47 | return access_token 48 | 49 | return access_token 50 | 51 | def make_request(endpoint): 52 | """Makes an API request to Reddit, handling authentication and errors.""" 53 | 54 | access_token = get_valid_access_token() 55 | if not access_token: 56 | return None 57 | 58 | headers = {"Authorization": f"Bearer {access_token}", "User-Agent": USER_AGENT} 59 | url = f"https://oauth.reddit.com{endpoint}" 60 | 61 | attempt = 0 62 | while attempt < 5: 63 | try: 64 | response = requests.get(url, headers=headers, timeout=30) 65 | except requests.exceptions.RequestException as e: 66 | console.print(f"❌ [bold red]Network error: {e}[/bold red]") 67 | attempt += 1 68 | if attempt < 5: 69 | exponential_backoff(attempt) 70 | continue 71 | return None 72 | 73 | if response.status_code == 401: 74 | console.print("🔄 [yellow]Access token expired, refreshing...[/yellow]") 75 | new_access_token = refresh_access_token_safe() 76 | if not new_access_token: 77 | console.print("❌ [bold red]Refresh token failed, manual re-authentication needed.[/bold red]") 78 | return None 79 | headers["Authorization"] = f"Bearer {new_access_token}" 80 | 81 | # Retry the request with new token 82 | try: 83 | response = requests.get(url, headers=headers, timeout=30) 84 | except requests.exceptions.RequestException as e: 85 | console.print(f"❌ [bold red]Network error on retry: {e}[/bold red]") 86 | return None 87 | 88 | if response.status_code == 200: 89 | try: 90 | return response.json() 91 | except json.JSONDecodeError: 92 | console.print(f"❌ [bold red]Invalid JSON response from Reddit API[/bold red]") 93 | return None 94 | 95 | elif response.status_code == 429: 96 | console.print("⚠️ [bold yellow]Rate limited. Retrying with backoff...[/bold yellow]") 97 | attempt += 1 98 | exponential_backoff(attempt) 99 | 100 | elif response.status_code == 403: 101 | console.print("❌ [bold red]Access forbidden. Check your Reddit app permissions and scopes.[/bold red]") 102 | return None 103 | 104 | elif response.status_code == 404: 105 | console.print("❌ [bold red]Reddit API endpoint not found. Check username and endpoint.[/bold red]") 106 | return None 107 | 108 | else: 109 | console.print(f"❌ [bold red]Error {response.status_code}: {response.reason}[/bold red]") 110 | console.print(f"❌ [bold red]Response: {response.text}[/bold red]") 111 | attempt += 1 112 | if attempt < 5: 113 | exponential_backoff(attempt) 114 | 115 | console.print("❌ [bold red]Max retry attempts reached.[/bold red]") 116 | return None 117 | 118 | def fetch_saved_posts(format="json", force_fetch=False): 119 | """Fetch saved Reddit posts, using `after` for full fetch and `before` for incremental fetch. 120 | 121 | Args: 122 | format (str): Output format - "json" or "html" 123 | force_fetch (bool): If True, fetch all posts from scratch 124 | 125 | Returns: 126 | dict: A dictionary containing: 127 | - content: The actual posts (list for JSON, string for HTML) 128 | - count: Number of posts fetched 129 | - format: The format used ("json" or "html") 130 | """ 131 | 132 | last_fetch_timestamp = None 133 | last_fetch_before = None 134 | fetch_mode = "before" # Default fetch mode for incremental updates 135 | cursor_param = None # Holds `after` or `before` value 136 | 137 | # Read last_fetch.json if it exists 138 | if os.path.exists(LAST_FETCH_FILE) and not force_fetch: 139 | try: 140 | with open(LAST_FETCH_FILE, "r", encoding="utf-8") as file: 141 | last_fetch_data = json.load(file) 142 | last_fetch_timestamp = last_fetch_data.get("last_fetch") 143 | last_fetch_before = last_fetch_data.get("before") 144 | cursor_param = last_fetch_before # Start from the last known post 145 | console.print(f"📋 [bold blue]Incremental fetch from timestamp: {last_fetch_timestamp}[/bold blue]") 146 | console.print(f"📋 [bold blue]Starting from post ID: {last_fetch_before}[/bold blue]") 147 | except (json.JSONDecodeError, FileNotFoundError) as e: 148 | console.print(f"⚠️ [bold yellow]Could not read last_fetch.json: {e}. Starting fresh fetch.[/bold yellow]") 149 | 150 | # Use `after` for force fetch (fetch ALL saved posts) 151 | if force_fetch or not os.path.exists(LAST_FETCH_FILE): 152 | fetch_mode = "after" 153 | cursor_param = None # Reset to fetch all data from the start 154 | console.print("🚀 [bold cyan]Force Fetch Activated: Fetching ALL saved posts using pagination.[/bold cyan]") 155 | 156 | new_posts = [] 157 | page_count = 0 158 | total_processed = 0 159 | 160 | # Load existing posts to check for duplicates in incremental mode 161 | existing_post_ids = set() 162 | if not force_fetch and os.path.exists(OUTPUT_JSON): 163 | try: 164 | with open(OUTPUT_JSON, "r", encoding="utf-8") as file: 165 | existing_posts = json.load(file) 166 | existing_post_ids = {post["fullname"] for post in existing_posts} 167 | console.print(f"📋 [blue]Loaded {len(existing_post_ids)} existing post IDs for duplicate checking[/blue]") 168 | except (json.JSONDecodeError, FileNotFoundError) as e: 169 | console.print(f"⚠️ [yellow]Could not load existing posts for duplicate checking: {e}[/yellow]") 170 | 171 | while True: 172 | endpoint = f"/user/{REDDIT_USERNAME}/saved?limit=100" 173 | if cursor_param: 174 | endpoint += f"&{fetch_mode}={cursor_param}" # Dynamically switch between `after` and `before` 175 | 176 | page_count += 1 177 | console.print(f"📡 [dim]Fetching page {page_count}...[/dim]") 178 | saved_posts = make_request(endpoint) 179 | 180 | if not saved_posts or "data" not in saved_posts: 181 | console.print(f"⚠️ [yellow]No data received from Reddit API on page {page_count}[/yellow]") 182 | break 183 | 184 | posts = saved_posts["data"].get("children", []) 185 | if not posts: 186 | console.print(f"✅ [green]No more posts available. Fetched {page_count - 1} pages total.[/green]") 187 | break # No more posts available 188 | 189 | total_processed += len(posts) 190 | console.print(f"📄 [blue]Processing {len(posts)} posts from page {page_count}[/blue]") 191 | 192 | posts_found_this_page = 0 193 | duplicate_count = 0 194 | 195 | for post in posts: 196 | data = post["data"] 197 | post_id = data["name"] 198 | 199 | # For incremental fetch, stop if we've seen this post before 200 | if not force_fetch and post_id in existing_post_ids: 201 | duplicate_count += 1 202 | console.print(f"🔄 [dim]Found existing post: {post_id} - stopping incremental fetch[/dim]") 203 | # Don't break immediately, process any new posts in this batch first 204 | continue 205 | 206 | # Handle both posts and comments 207 | post_type = "post" if data.get("title") else "comment" 208 | 209 | if post_type == "post": 210 | new_posts.append({ 211 | "title": data.get("title", "No Title"), 212 | "url": data.get("url", f"https://reddit.com{data.get('permalink', '#')}"), 213 | "subreddit": data.get("subreddit"), 214 | "created_utc": data.get("created_utc"), 215 | "fullname": data["name"], # Store Reddit's unique identifier 216 | "type": "post", 217 | "author": data.get("author", "[deleted]"), 218 | "score": data.get("score", 0) 219 | }) 220 | else: 221 | # Handle saved comments 222 | new_posts.append({ 223 | "title": f"Comment in: {data.get('link_title', 'Unknown Post')}", 224 | "url": f"https://reddit.com{data.get('permalink', '#')}", 225 | "subreddit": data.get("subreddit"), 226 | "created_utc": data.get("created_utc"), 227 | "fullname": data["name"], 228 | "type": "comment", 229 | "author": data.get("author", "[deleted]"), 230 | "score": data.get("score", 0), 231 | "body": data.get("body", "")[:200] + "..." if len(data.get("body", "")) > 200 else data.get("body", "") 232 | }) 233 | 234 | posts_found_this_page += 1 235 | 236 | console.print(f"🆕 [green]Found {posts_found_this_page} new posts on this page[/green]") 237 | if duplicate_count > 0: 238 | console.print(f"🔄 [yellow]Found {duplicate_count} duplicate posts - stopping incremental fetch[/yellow]") 239 | 240 | # For incremental fetch, stop if we found duplicates (we've caught up) 241 | if not force_fetch and duplicate_count > 0: 242 | console.print(f"✅ [green]Incremental fetch complete. Processed {page_count} pages, found {len(new_posts)} new posts.[/green]") 243 | break 244 | 245 | # Move pagination cursor 246 | if fetch_mode == "after": 247 | cursor_param = posts[-1]["data"]["name"] # Take LAST post for force fetch 248 | else: 249 | cursor_param = posts[0]["data"]["name"] # Take FIRST post for incremental 250 | 251 | # Add a small delay to be nice to Reddit's servers 252 | time.sleep(0.5) 253 | 254 | console.print(f"📊 [bold blue]Total: Processed {total_processed} posts across {page_count} pages, found {len(new_posts)} new posts[/bold blue]") 255 | 256 | # **Store last fetched post details** 257 | if new_posts: 258 | last_fetched_value = new_posts[-1]["created_utc"] if fetch_mode == "after" else new_posts[0]["created_utc"] 259 | last_fetched_after = new_posts[-1]["fullname"] if fetch_mode == "after" else None 260 | last_fetched_before = new_posts[0]["fullname"] if fetch_mode == "before" else None 261 | 262 | try: 263 | with open(LAST_FETCH_FILE, "w", encoding="utf-8") as file: 264 | json.dump({ 265 | "last_fetch": last_fetched_value, 266 | "after": last_fetched_after, 267 | "before": last_fetched_before, 268 | "timestamp": time.time(), 269 | "total_fetched": len(new_posts) 270 | }, file, indent=2) 271 | 272 | console.print(f"📌 Last fetch timestamp updated: {last_fetched_value}", style="bold cyan") 273 | console.print(f"📌 Last fetch `after` updated: {last_fetched_after if last_fetched_after else 'N/A'}", style="bold cyan") 274 | console.print(f"📌 Last fetch `before` updated: {last_fetched_before if last_fetched_before else 'N/A'}", style="bold cyan") 275 | except Exception as e: 276 | console.print(f"⚠️ [yellow]Could not save last fetch data: {e}[/yellow]") 277 | 278 | # Load existing posts and merge 279 | existing_posts = [] 280 | if os.path.exists(OUTPUT_JSON) and not force_fetch: 281 | try: 282 | with open(OUTPUT_JSON, "r", encoding="utf-8") as file: 283 | existing_posts = json.load(file) 284 | console.print(f"📋 [blue]Loaded {len(existing_posts)} existing posts from storage[/blue]") 285 | except (json.JSONDecodeError, FileNotFoundError) as e: 286 | console.print(f"⚠️ [yellow]Could not load existing posts: {e}. Starting fresh.[/yellow]") 287 | 288 | # Combine and deduplicate posts 289 | combined_posts = new_posts + existing_posts # Prepend new posts instead of appending 290 | unique_posts = {post["fullname"]: post for post in combined_posts}.values() # Remove duplicates 291 | unique_posts_list = list(unique_posts) 292 | 293 | console.print(f"🔄 [green]Combined {len(new_posts)} new + {len(existing_posts)} existing = {len(unique_posts_list)} unique posts[/green]") 294 | 295 | # Always save JSON version for data integrity 296 | try: 297 | with open(OUTPUT_JSON, "w", encoding="utf-8") as file: 298 | json.dump(unique_posts_list, file, indent=2, ensure_ascii=False) 299 | console.print(f"💾 [green]Saved {len(unique_posts_list)} posts to {OUTPUT_JSON}[/green]") 300 | except Exception as e: 301 | console.print(f"❌ [red]Could not save JSON file: {e}[/red]") 302 | 303 | # Return based on requested format 304 | if format == "html": 305 | html_output = generate_html_output(unique_posts_list) 306 | return { 307 | "content": html_output, 308 | "count": len(new_posts), # Return count of NEW posts, not total 309 | "format": "html" 310 | } 311 | else: # JSON format 312 | return { 313 | "content": unique_posts_list, 314 | "count": len(new_posts), # Return count of NEW posts, not total 315 | "format": "json" 316 | } 317 | 318 | console.print("ℹ️ [bold blue]No new posts found.[/bold blue]") 319 | 320 | # Return consistent structure even when no posts found 321 | if format == "html": 322 | return { 323 | "content": "Saved Reddit Posts

No posts found.

", 324 | "count": 0, 325 | "format": "html" 326 | } 327 | else: 328 | return { 329 | "content": [], 330 | "count": 0, 331 | "format": "json" 332 | } 333 | 334 | def generate_html_output(posts_list): 335 | """Generate HTML output from posts list.""" 336 | html_parts = [] 337 | 338 | # HTML header 339 | html_parts.append(''' 340 | 341 | 342 | 343 | 344 | Saved Reddit Posts 345 | 412 | 413 | 414 |
415 |

Saved Reddit Posts

416 |
417 | Total Saved Items: ''' + str(len(posts_list)) + ''' 418 |
''') 419 | 420 | for index, post in enumerate(posts_list, start=1): 421 | post_type = post.get("type", "post") 422 | author = post.get("author", "[deleted]") 423 | score = post.get("score", 0) 424 | subreddit = post.get("subreddit", "unknown") 425 | 426 | # Convert timestamp to readable date 427 | created_utc = post.get("created_utc", 0) 428 | if created_utc: 429 | try: 430 | from datetime import datetime 431 | date_str = datetime.fromtimestamp(created_utc).strftime("%Y-%m-%d %H:%M") 432 | except (ValueError, OSError): 433 | date_str = "Unknown date" 434 | else: 435 | date_str = "Unknown date" 436 | 437 | # Escape HTML characters in title and other content 438 | title = post.get('title', 'No Title').replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"') 439 | url = post.get('url', '#').replace('"', '"') 440 | 441 | html_parts.append(f''' 442 |
443 |
444 | {index}. 445 | {title} 446 |
447 | ''') 450 | 451 | # Add comment body if it's a comment 452 | if post_type == "comment" and post.get("body"): 453 | comment_body = post.get("body", "").replace('&', '&').replace('<', '<').replace('>', '>') 454 | html_parts.append(f'
{comment_body}
') 455 | 456 | html_parts.append('
') 457 | 458 | # Add footer 459 | current_time = time.strftime("%Y-%m-%d %H:%M:%S") 460 | html_parts.append(f''' 461 |
462 | Generated on: {current_time} 463 |
464 |
465 | 466 | ''') 467 | 468 | return '\n'.join(html_parts) 469 | 470 | def fetch_saved_posts_legacy(format="json", force_fetch=False): 471 | """Legacy function that returns just the content for backward compatibility. 472 | 473 | Returns: 474 | list or str: Posts data (list for JSON, HTML string for HTML) 475 | """ 476 | result = fetch_saved_posts(format, force_fetch) 477 | return result["content"] if result else ([] if format == "json" else "") -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright © 2007 Free Software Foundation, Inc. 5 | 6 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for software and other kinds of works. 11 | 12 | The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. 13 | 14 | When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. 15 | 16 | To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. 17 | 18 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. 19 | 20 | Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. 21 | 22 | For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. 23 | 24 | Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. 25 | 26 | Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. 27 | 28 | The precise terms and conditions for copying, distribution and modification follow. 29 | 30 | TERMS AND CONDITIONS 31 | 32 | 0. Definitions. 33 | 34 | “This License” refers to version 3 of the GNU General Public License. 35 | 36 | “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. 37 | 38 | “The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. 39 | 40 | To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. 41 | 42 | A “covered work” means either the unmodified Program or a work based on the Program. 43 | 44 | To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. 45 | 46 | To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. 47 | 48 | An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 49 | 50 | 1. Source Code. 51 | The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. 52 | 53 | A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. 54 | 55 | The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. 56 | 57 | The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. 58 | 59 | The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. 60 | 61 | The Corresponding Source for a work in source code form is that same work. 62 | 63 | 2. Basic Permissions. 64 | All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. 65 | 66 | You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. 67 | 68 | Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 69 | 70 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 71 | No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. 72 | 73 | When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 74 | 75 | 4. Conveying Verbatim Copies. 76 | You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. 77 | 78 | You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 79 | 80 | 5. Conveying Modified Source Versions. 81 | You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: 82 | 83 | a) The work must carry prominent notices stating that you modified it, and giving a relevant date. 84 | 85 | b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. 86 | 87 | c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. 88 | 89 | d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. 90 | 91 | A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 92 | 93 | 6. Conveying Non-Source Forms. 94 | You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: 95 | 96 | a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. 97 | 98 | b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. 99 | 100 | c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. 101 | 102 | d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. 103 | 104 | e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. 105 | 106 | A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. 107 | 108 | A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. 109 | 110 | “Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. 111 | 112 | If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). 113 | 114 | The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. 115 | 116 | Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 117 | 118 | 7. Additional Terms. 119 | “Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. 120 | 121 | When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. 122 | 123 | Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: 124 | 125 | a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or 126 | 127 | b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or 128 | 129 | c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or 130 | 131 | d) Limiting the use for publicity purposes of names of licensors or authors of the material; or 132 | 133 | e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or 134 | 135 | f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. 136 | 137 | All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. 138 | 139 | If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. 140 | 141 | Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 142 | 143 | 8. Termination. 144 | You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). 145 | 146 | However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. 147 | 148 | Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. 149 | 150 | Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 151 | 152 | 9. Acceptance Not Required for Having Copies. 153 | You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 154 | 155 | 10. Automatic Licensing of Downstream Recipients. 156 | Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. 157 | 158 | An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. 159 | 160 | You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 161 | 162 | 11. Patents. 163 | A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. 164 | 165 | A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. 166 | 167 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. 168 | 169 | In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. 170 | 171 | If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. 172 | 173 | If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. 174 | 175 | A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. 176 | 177 | Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 178 | 179 | 12. No Surrender of Others' Freedom. 180 | If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 181 | 182 | 13. Use with the GNU Affero General Public License. 183 | Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 184 | 185 | 14. Revised Versions of this License. 186 | The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 187 | 188 | Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. 189 | 190 | If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. 191 | 192 | Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 193 | 194 | 15. Disclaimer of Warranty. 195 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 196 | 197 | 16. Limitation of Liability. 198 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 199 | 200 | 17. Interpretation of Sections 15 and 16. 201 | If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 202 | 203 | END OF TERMS AND CONDITIONS 204 | 205 | How to Apply These Terms to Your New Programs 206 | 207 | If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. 208 | 209 | To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. 210 | 211 | Reddit-Fetch 212 | Copyright (C) 2025 giteaadmin 213 | 214 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 215 | 216 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 217 | 218 | You should have received a copy of the GNU General Public License along with this program. If not, see . 219 | 220 | Also add information on how to contact you by electronic and paper mail. 221 | 222 | If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: 223 | 224 | Reddit-Fetch Copyright (C) 2025 giteaadmin 225 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 226 | This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. 227 | 228 | The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. 229 | 230 | You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . 231 | 232 | The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . 233 | --------------------------------------------------------------------------------