Skip to content

🛡️ 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/Dockerfile
index 780b6a8..0b04b29 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -18,31 +18,42 @@ RUN pip install --no-cache-dir -r requirements.txt
# Copy backend code
COPY 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 files
COPY 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 nginx
RUN rm /etc/nginx/sites-enabled/default
COPY nginx.conf /etc/nginx/conf.d/default.conf
-# Create startup script
+# Create startup script with directory permission check
RUN 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 used
RUN 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/stderr
stderr_logfile_maxbytes=0
[program:gunicorn]
-command=gunicorn --bind 0.0.0.0:5000 --workers 4 app:app
+command=/app/start.sh
directory=/app
autostart=true
autorestart=true
@@ -112,5 +124,8 @@ stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
EOF
+# Make sure the uploads directory is writable
+RUN chmod -R 777 /data/uploads
+
# Start supervisor
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
\ No newline at end of file
diff --git a/backend/app.py b/backend/app.py
index 5608086..c17c2a0 100644
--- a/backend/app.py
+++ b/backend/app.py
@@ -6,6 +6,7 @@ from datetime import datetime, timedelta, date
from werkzeug.utils import secure_filename
from flask_cors import CORS
import logging
+import time
app = 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 = None
def 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 serving
return 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.yml
index 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_healthy
restart: unless-stopped
warrackerdb:
diff --git a/nginx.conf b/nginx.conf
index 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 compression
gzip 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 root
location /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 uploads
location ~* \.(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 file
diff --git a/ping.html b/ping.html
new file mode 100644
index 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 file
diff --git a/test.html b/test.html
new file mode 100644
index 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 file
diff --git a/uploads/20250303033711_dummy-invoice-1018x1440.png b/uploads/20250303033711_dummy-invoice-1018x1440.png
new file mode 100644
index 0000000..43cba0d
Binary files /dev/null and b/uploads/20250303033711_dummy-invoice-1018x1440.png differ
diff --git a/uploads/debug-test.txt b/uploads/debug-test.txt
new file mode 100644
index 0000000..28820b6
--- /dev/null
+++ b/uploads/debug-test.txt
@@ -0,0 +1 @@
+Test content for debugging
diff --git a/uploads/test.txt b/uploads/test.txt
new file mode 100644
index 0000000..d670460
--- /dev/null
+++ b/uploads/test.txt
@@ -0,0 +1 @@
+test content