🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Fixed uploads to load the invoices
sassanixc267517de223
diff --git a/Dockerfile b/Dockerfileindex 780b6a8..0b04b29 100644--- a/Dockerfile+++ b/Dockerfile@@ -18,31 +18,42 @@ RUN pip install --no-cache-dir -r requirements.txt# Copy backend codeCOPY backend/app.py .-# Create directory for uploads-RUN mkdir -p /data/uploads+# Create directory for uploads with proper permissions+RUN mkdir -p /data/uploads && chmod 777 /data/uploads# Copy frontend filesCOPY frontend/index.html /var/www/html/COPY frontend/script.js /var/www/html/COPY frontend/style.css /var/www/html/+COPY test.html /var/www/html/# Configure nginxRUN rm /etc/nginx/sites-enabled/defaultCOPY nginx.conf /etc/nginx/conf.d/default.conf-# Create startup script+# Create startup script with directory permission checkRUN echo '#!/bin/bash\n\+echo "Checking /data/uploads directory:"\n\+ls -la /data/uploads\n\+echo "Setting permissions:"\n\+chmod -R 777 /data/uploads\n\+ls -la /data/uploads\n\+echo "Starting services..."\n\nginx\n\gunicorn --bind 0.0.0.0:5000 --workers 4 app:app\n\' > /app/start.sh && chmod +x /app/start.sh-# Create nginx configuration+# This is just a fallback, the copied nginx.conf will be usedRUN echo 'server {\n\listen 80;\n\server_name localhost;\n\root /var/www/html;\n\index index.html;\n\\n\+ # Enable detailed error logging\n\+ error_log /var/log/nginx/error.log debug;\n\+ access_log /var/log/nginx/access.log;\n\+ \n\# Enable gzip compression\n\gzip on;\n\gzip_types text/plain text/css application/javascript application/json;\n\@@ -58,17 +69,18 @@ RUN echo 'server {\n\proxy_set_header X-Real-IP $remote_addr;\n\}\n\\n\- # Proxy uploads to backend\n\+ # Direct access to uploads directory\n\location /uploads/ {\n\- proxy_pass http://localhost:5000;\n\- proxy_set_header Host $host;\n\- proxy_set_header X-Real-IP $remote_addr;\n\- }\n\- \n\- # Cache static assets\n\- location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg)$ {\n\- expires 7d;\n\- add_header Cache-Control "public, max-age=604800";\n\+ alias /data/uploads/;\n\+ autoindex on;\n\+ \n\+ # Set appropriate MIME types\n\+ types {\n\+ image/png png PNG;\n\+ image/jpeg jpg jpeg JPG JPEG;\n\+ application/pdf pdf PDF;\n\+ text/plain txt TXT;\n\+ }\n\}\n\}' > /etc/nginx/conf.d/default.conf@@ -102,7 +114,7 @@ stderr_logfile=/dev/stderrstderr_logfile_maxbytes=0[program:gunicorn]-command=gunicorn --bind 0.0.0.0:5000 --workers 4 app:app+command=/app/start.shdirectory=/appautostart=trueautorestart=true@@ -112,5 +124,8 @@ stderr_logfile=/dev/stderrstderr_logfile_maxbytes=0EOF+# Make sure the uploads directory is writable+RUN chmod -R 777 /data/uploads+# Start supervisorCMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]\ No newline at end of filediff --git a/backend/app.py b/backend/app.pyindex 5608086..c17c2a0 100644--- a/backend/app.py+++ b/backend/app.py@@ -6,6 +6,7 @@ from datetime import datetime, timedelta, datefrom werkzeug.utils import secure_filenamefrom flask_cors import CORSimport logging+import timeapp = Flask(__name__)CORS(app) # Enable CORS@@ -27,17 +28,47 @@ DB_NAME = os.environ.get('DB_NAME', 'warranty_db')DB_USER = os.environ.get('DB_USER', 'warranty_user')DB_PASSWORD = os.environ.get('DB_PASSWORD', 'warranty_password')-# Create a connection pool-connection_pool = pool.SimpleConnectionPool(- 1, 10, # min, max connections- host=DB_HOST,- database=DB_NAME,- user=DB_USER,- password=DB_PASSWORD-)+# Add connection retry logic+def create_db_pool(max_retries=5, retry_delay=5):+ attempt = 0+ last_exception = None++ while attempt < max_retries:+ try:+ logger.info(f"Attempting to connect to database (attempt {attempt+1}/{max_retries})")+ connection_pool = pool.SimpleConnectionPool(+ 1, 10, # min, max connections+ host=DB_HOST,+ database=DB_NAME,+ user=DB_USER,+ password=DB_PASSWORD+ )+ logger.info("Database connection successful")+ return connection_pool+ except Exception as e:+ last_exception = e+ logger.error(f"Database connection error: {e}")+ logger.info(f"Retrying in {retry_delay} seconds...")+ time.sleep(retry_delay)+ attempt += 1++ # If we got here, all connection attempts failed+ logger.error(f"Failed to connect to database after {max_retries} attempts")+ raise last_exception++# Create a connection pool with retry logic+try:+ connection_pool = create_db_pool()+except Exception as e:+ logger.error(f"Fatal database connection error: {e}")+ # Allow the app to start even if DB connection fails+ # This lets us serve static files while DB is unavailable+ connection_pool = Nonedef get_db_connection():try:+ if connection_pool is None:+ raise Exception("Database connection pool not initialized")return connection_pool.getconn()except Exception as e:logger.error(f"Database connection error: {e}")@@ -304,12 +335,13 @@ def update_warranty(warranty_id):@app.route('/uploads/<path:filename>')def uploaded_file(filename):+ """Serve files from the uploads directory."""try:- # Make sure this is pointing to the correct absolute path+ # Simple and direct file servingreturn send_from_directory('/data/uploads', filename)except Exception as e:logger.error(f"Error serving file {filename}: {e}")- return jsonify({"error": "File not found"}), 404+ return jsonify({"error": f"Error serving file: {str(e)}"}), 500@app.errorhandler(413)def request_entity_too_large(error):diff --git a/docker-compose.yml b/docker-compose.ymlindex 56d2a80..50c94f8 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -11,7 +11,8 @@ services:- DB_USER=warranty_user- DB_PASSWORD=${DB_PASSWORD:-warranty_password}depends_on:- - warrackerdb+ warrackerdb:+ condition: service_healthyrestart: unless-stoppedwarrackerdb:diff --git a/nginx.conf b/nginx.confindex 044b0db..19c1eea 100644--- a/nginx.conf+++ b/nginx.conf@@ -4,6 +4,10 @@ server {root /usr/share/nginx/html;index index.html;+ # Enable detailed error logging+ error_log /var/log/nginx/error.log debug;+ access_log /var/log/nginx/access.log;+# Enable gzip compressiongzip on;gzip_types text/plain text/css application/javascript application/json;@@ -13,6 +17,12 @@ server {add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';+ # A test location to debug directory paths+ location = /test-uploads {+ add_header Content-Type text/plain;+ return 200 "Uploads directory exists: $document_root\n";+ }+location / {try_files $uri $uri/ /index.html;}@@ -26,23 +36,43 @@ server {proxy_set_header X-Forwarded-Proto $scheme;}- # Proxy uploads to backend+ # Simpler uploads location - using alias instead of rootlocation /uploads/ {- proxy_pass http://warracker:5000/uploads/; # Note the trailing slash- proxy_set_header Host $host;- proxy_set_header X-Real-IP $remote_addr;+ alias /data/uploads/;+ autoindex on;++ # Set appropriate MIME types+ types {+ image/png png PNG;+ image/jpeg jpg jpeg JPG JPEG;+ application/pdf pdf PDF;+ text/plain txt TXT;+ }++ # Disable caching for testing+ add_header Cache-Control "no-cache, no-store, must-revalidate";+ add_header Pragma "no-cache";+ add_header Expires "0";}- # Cache static assets+ # Cache static assets - skip uploadslocation ~* \.(css|js|jpg|jpeg|png|gif|ico|svg)$ {+ # Skip this location if the request is for /uploads/+ if ($request_uri ~* "^/uploads/") {+ return 404;+ }+expires 7d;add_header Cache-Control "public, max-age=604800";}- # Error handling- error_page 404 /index.html;- error_page 500 502 503 504 /50x.html;- location = /50x.html {- root /usr/share/nginx/html;+ # Don't redirect 404s for uploads to index.html+ location ~ ^/uploads/ {+ try_files $uri =404;+ }++ # Error handling - for everything except uploads+ location / {+ error_page 404 = /index.html;}}\ No newline at end of filediff --git a/ping.html b/ping.htmlnew file mode 100644index 0000000..052fce7--- /dev/null+++ b/ping.html@@ -0,0 +1,10 @@+<!DOCTYPE html>+<html>+<head>+ <title>Nginx Test</title>+</head>+<body>+ <h1>Nginx is working</h1>+ <p>If you can see this, nginx is serving static files correctly.</p>+</body>+</html>\ No newline at end of filediff --git a/test.html b/test.htmlnew file mode 100644index 0000000..4923f70--- /dev/null+++ b/test.html@@ -0,0 +1,76 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Image Test</title>+ <style>+ body {+ font-family: Arial, sans-serif;+ padding: 20px;+ max-width: 800px;+ margin: 0 auto;+ }+ .test-box {+ border: 1px solid #ccc;+ padding: 20px;+ margin: 20px 0;+ }+ h1 {+ color: #333;+ }+ img {+ max-width: 100%;+ border: 1px dashed #999;+ }+ .success {+ color: green;+ font-weight: bold;+ }+ .failure {+ color: red;+ font-weight: bold;+ }+ </style>+</head>+<body>+ <h1>Image Loading Test</h1>++ <div class="test-box">+ <h2>Test 1: Direct IMG Tag</h2>+ <p>Testing image: <span id="image-path">/uploads/20250303033711_dummy-invoice-1018x1440.png</span></p>+ <div>+ <img src="/uploads/20250303033711_dummy-invoice-1018x1440.png" alt="Invoice Image" id="test-image">+ </div>+ <p id="status">Loading...</p>+ </div>++ <div class="test-box">+ <h2>Test 2: Text File Test</h2>+ <p>Testing text file from uploads directory:</p>+ <iframe src="/uploads/debug-test.txt" style="width:100%; height:100px; border:1px solid #ccc;"></iframe>+ </div>++ <div class="test-box">+ <h2>Test 3: Directory Listing</h2>+ <p>Testing directory listing:</p>+ <iframe src="/uploads/" style="width:100%; height:200px; border:1px solid #ccc;"></iframe>+ </div>++ <script>+ // Check if image loads+ const img = document.getElementById('test-image');+ const status = document.getElementById('status');++ img.onload = function() {+ status.textContent = "SUCCESS: Image loaded successfully!";+ status.className = "success";+ };++ img.onerror = function() {+ status.textContent = "FAILURE: Image failed to load.";+ status.className = "failure";+ };+ </script>+</body>+</html>\ No newline at end of filediff --git a/uploads/20250303033711_dummy-invoice-1018x1440.png b/uploads/20250303033711_dummy-invoice-1018x1440.pngnew file mode 100644index 0000000..43cba0dBinary files /dev/null and b/uploads/20250303033711_dummy-invoice-1018x1440.png differdiff --git a/uploads/debug-test.txt b/uploads/debug-test.txtnew file mode 100644index 0000000..28820b6--- /dev/null+++ b/uploads/debug-test.txt@@ -0,0 +1 @@+Test content for debuggingdiff --git a/uploads/test.txt b/uploads/test.txtnew file mode 100644index 0000000..d670460--- /dev/null+++ b/uploads/test.txt@@ -0,0 +1 @@+test content