-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
874 lines (689 loc) · 26.5 KB
/
app.py
File metadata and controls
874 lines (689 loc) · 26.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
from flask import Flask, render_template, request, redirect, session, g, url_for, current_app, session, jsonify, flash
from werkzeug.utils import secure_filename
from flask_session import Session
from datetime import datetime, timezone
from werkzeug.security import generate_password_hash, check_password_hash
import sqlite3
import waitress
import os
# --- DATABASE CONFIG ---
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
DB_PATH = os.path.join(BASE_DIR, "users.db") # store DB in project root
# --- FLASK CONFIG ---
app = Flask(__name__)
app.secret_key = os.environ.get("FLASK_SECRET", "replace_this_with_real_secret")
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Configuration
UPLOAD_FOLDER = 'static/uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
MAX_FILE_SIZE = 5 * 1024 * 1024 # 5MB
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = MAX_FILE_SIZE
# Create uploads folder if it doesn't exist
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# --- DATABASE HELPERS ---
def get_db():
if "db" not in g:
print("📁 Connecting to database:", os.path.abspath(DB_PATH)) # <-- debug print
g.db = sqlite3.connect(DB_PATH)
g.db.row_factory = sqlite3.Row
g.db.execute("PRAGMA foreign_keys = ON")
return g.db
def time_ago(dt):
if isinstance(dt, str):
dt = datetime.strptime(dt, "%Y-%m-%d %H:%M:%S")
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
now = datetime.now(timezone.utc)
diff = now - dt
seconds = diff.total_seconds()
if seconds < 60:
return "just now"
elif seconds < 3600:
return f"{int(seconds // 60)} minutes ago"
elif seconds < 86400:
return f"{int(seconds // 3600)} hours ago"
else:
return f"{int(seconds // 86400)} days ago"
@app.teardown_appcontext
def close_db(e=None):
db = g.pop("db", None)
if db is not None:
db.close()
# --- ROUTES ---
@app.route("/")
def index():
return render_template("index.html", username=session.get("username"))
@app.route("/signup", methods=["GET", "POST"])
def signup():
if request.method == "POST":
username = request.form.get("username", "").strip()
password = request.form.get("password", "")
hostel = request.form.get("hostel", "").strip()
phone = request.form.get("phone", "").strip()
if not username or not password:
return render_template("signup.html", error="Missing username or password")
db = get_db()
# check existing user
existing = db.execute("SELECT id FROM users WHERE username = ?", (username,)).fetchone()
if existing:
return render_template("signup.html", error="Username already exists")
try:
password_hash = generate_password_hash(password)
db.execute(
"INSERT INTO users (username, password_hash, hostel, phone) VALUES (?, ?, ?, ?)",
(username, password_hash, hostel, phone)
)
db.commit()
except Exception as e:
print("❌ DB Insert Error:", e)
return render_template("signup.html", error="Database error: " + str(e))
session["username"] = username
session["profile_picture"] = None
return redirect("/signin")
return render_template("signup.html")
@app.route("/signin", methods=["GET", "POST"])
def signin():
if request.method == "POST":
username = request.form.get("username", "").strip()
password = request.form.get("password", "")
if not username or not password:
return render_template("signin.html", error="Missing username or password")
db = get_db()
row = db.execute("SELECT * FROM users WHERE username = ?", (username,)).fetchone()
if row is None or not check_password_hash(row["password_hash"], password):
return render_template("signin.html", error="Invalid credentials")
session["username"] = username
session["user_id"] = row["id"]
session["hostel"] = row["hostel"]
session["profile_picture"] = row["profile_picture"]
return redirect("/dashboard")
return render_template("signin.html")
@app.route('/dashboard')
def dashboard():
if 'user_id' not in session:
return redirect(url_for('signin'))
db = get_db()
user_id = session['user_id']
# Compute stats from existing tables
active_offers = db.execute(
"SELECT COUNT(*) FROM items WHERE owner_id = ? AND is_active = 1",
(user_id,)
).fetchone()[0]
total_views = db.execute(
"SELECT COALESCE(SUM(views), 0) FROM items WHERE owner_id = ?",
(user_id,)
).fetchone()[0]
pending_requests = db.execute(
"SELECT COUNT(*) FROM swap_requests WHERE owner_id = ? AND status = 'pending'",
(user_id,)
).fetchone()[0]
completed_swaps = db.execute(
"SELECT COUNT(*) FROM swap_requests WHERE owner_id = ? AND status = 'accepted'",
(user_id,)
).fetchone()[0]
total_attempts = db.execute(
"SELECT COUNT(*) FROM swap_requests WHERE owner_id = ?",
(user_id,)
).fetchone()[0]
success_rate = round((completed_swaps / total_attempts * 100) if total_attempts else 0)
stats = {
"active_offers": active_offers,
"pending_requests": pending_requests,
"total_views": total_views, #consider emoving this if it doesn't make sense to show
"completed_swaps": completed_swaps,
"matches": 0, # placeholder
"success_rate": success_rate,
"total_attempts": total_attempts
}
return render_template(
"dashboard.html",
username=session["username"],
stats=stats,
swap_requests=[],
recent_activity=[],
matches=[]
)
@app.route('/swapRequests')
def swap_requests():
if 'user_id' not in session:
return redirect(url_for('signin'))
db = get_db()
user_id = session['user_id']
# Incoming
incoming = db.execute("""
SELECT
sr.id,
sr.message,
sr.status,
sr.created_at,
i.name AS item_name,
i.image AS item_image,
u.username AS requester_name,
u.email AS requester_email,
u.phone AS requester_phone
FROM swap_requests sr
JOIN items i ON sr.item_id = i.id
JOIN users u ON sr.requester_id = u.id
WHERE sr.owner_id = :user_id
ORDER BY sr.created_at DESC
""", {"user_id": user_id}).fetchall()
# Outgoing
outgoing = db.execute("""
SELECT
sr.id,
sr.message,
sr.status,
sr.created_at,
i.name AS item_name,
i.image AS item_image,
u.username AS owner_name,
u.email AS owner_email,
u.phone AS owner_phone
FROM swap_requests sr
JOIN items i ON sr.item_id = i.id
JOIN users u ON sr.owner_id = u.id
WHERE sr.requester_id = :user_id
ORDER BY sr.created_at DESC
""", {"user_id": user_id}).fetchall()
# Add time_ago to each request
incoming_requests = []
for r in incoming:
r = dict(r)
r['time_ago'] = time_ago(r['created_at'])
incoming_requests.append(r)
outgoing_requests = []
for r in outgoing:
r = dict(r)
r['time_ago'] = time_ago(r['created_at'])
outgoing_requests.append(r)
incoming_count = sum(1 for r in incoming_requests if r['status'] == 'pending')
return render_template(
'swapRequests.html',
username=session["username"],
incoming_requests=incoming_requests,
outgoing_requests=outgoing_requests,
incoming_count=incoming_count,
success=request.args.get('success'),
error=request.args.get('error')
)
@app.route('/swap/respond/<int:request_id>', methods=['POST'])
def respond_to_swap(request_id):
if 'user_id' not in session:
return {"success": False}, 403
db = get_db()
user_id = session['user_id']
data = request.get_json()
action = data.get("action")
if action not in ["accepted", "rejected"]:
return {"success": False}, 400
# Verify ownership
swap = db.execute("""
SELECT id FROM swap_requests
WHERE id = ? AND owner_id = ?
""", (request_id, user_id)).fetchone()
if not swap:
return {"success": False}, 403
db.execute("""
UPDATE swap_requests
SET status = ?, responded_at = CURRENT_TIMESTAMP
WHERE id = ?
""", (action, request_id))
db.commit()
return jsonify( success=True,
message="Swap accepted successfully." if action == "accepted"
else "Swap declined.",
status=action
)
@app.route("/swap/request/<int:item_id>", methods=["POST"])
def request_swap(item_id):
if "user_id" not in session:
return redirect(url_for("signin"))
user_id = session["user_id"]
db = get_db()
item = db.execute("""
SELECT id, owner_id, is_active
FROM items
WHERE id = ?
""", (item_id,)).fetchone()
if not item:
return "Item not found", 404
if item["owner_id"] == user_id:
return "You cannot request your own item", 403
if item["is_active"] != 1:
return "Item not available", 400
existing = db.execute("""
SELECT id FROM swap_requests
WHERE item_id = ? AND requester_id = ? AND status = 'pending'
""", (item_id, user_id)).fetchone()
if existing:
flash("Request already sent.", "warning")
return redirect(url_for("browse_items", item_id=item_id))
db.execute("""
INSERT INTO swap_requests (item_id, requester_id, owner_id, status)
VALUES (?, ?, ?, 'pending')
""", (item_id, user_id, item["owner_id"]))
db.commit()
flash("Swap request sent successfully.", "success")
return redirect(url_for("browse_items", item_id=item_id,))
@app.route("/profile")
def profile():
if "user_id" not in session:
return redirect(url_for("signin"))
db = get_db()
user_id = session["user_id"]
# Active listings
active_listings = db.execute("""
SELECT *
FROM items
WHERE owner_id = ?
AND is_active = 1
ORDER BY created_at DESC
""", (session["user_id"],)).fetchall()
# TEMPORARY placeholders (tables not implemented yet)
swap_history = []
saved_items = db.execute("""
SELECT
items.id,
items.name,
items.category,
items.image,
users.username AS owner_name
FROM saved_items
JOIN items ON saved_items.item_id = items.id
JOIN users ON items.owner_id = users.id
WHERE saved_items.user_id = ?
AND items.is_active = 1
""", (session['user_id'],)).fetchall()
user = db.execute("SELECT profile_picture FROM users WHERE id = ?", (user_id,)).fetchone()
if user and user["profile_picture"]:
session["profile_picture"] = user["profile_picture"]
return render_template(
"profile.html",
username=session["username"],
active_listings=active_listings,
swap_history=swap_history,
saved_items=saved_items
)
# Change Password Route
@app.route('/change-password', methods=['POST'])
def change_password():
if 'user_id' not in session:
return redirect(url_for('signin'))
current_password = request.form.get('current_password')
new_password = request.form.get('new_password')
confirm_password = request.form.get('confirm_password')
# Validate inputs
if not all([current_password, new_password, confirm_password]):
return redirect(url_for('profile', error='All fields are required'))
if new_password != confirm_password:
return redirect(url_for('profile', error='New passwords do not match'))
if len(new_password) < 6:
return redirect(url_for('profile', error='Password must be at least 6 characters'))
# Verify current password
db = get_db()
user = db.execute('SELECT password_hash FROM users WHERE id = ?', (session['user_id'],)).fetchone()
# Check current password
if not user or not check_password_hash(user['password_hash'], current_password):
return redirect(url_for('profile', error='Current password is incorrect'))
# Hash the new password
hashed_password = generate_password_hash(new_password)
# Update the password in the database
db.execute('UPDATE users SET password_hash = ? WHERE id = ?', (hashed_password, session['user_id']))
db.commit()
return redirect(url_for('profile', success='Password updated successfully'))
# Update Profile Route
@app.route('/update-profile', methods=['POST'])
def update_profile():
if 'user_id' not in session:
return redirect(url_for('signin'))
username = request.form.get('username')
email = request.form.get('email')
phone = request.form.get('phone')
hostel = request.form.get('hostel')
# Validate inputs
if not username or not email:
return redirect(url_for('profile', error='Username and email are required'))
# Check if username or email already exists (for other users)
db = get_db()
existing = db.execute('''
SELECT id FROM users
WHERE (username = ? OR email = ?) AND id != ?
''', (username, email, session['user_id'])).fetchone()
if existing:
return redirect(url_for('profile', error='Username or email already taken'))
# Update profile
db.execute('''
UPDATE users
SET username = ?, email = ?, phone = ?, hostel = ?
WHERE id = ?
''', (username, email, phone, hostel, session['user_id']))
db.commit()
# Update session
session['username'] = username
session['email'] = email
return redirect(url_for('profile', success='Profile updated successfully'))
@app.route("/profile/upload-picture", methods=["POST"])
def upload_profile_picture():
if "user_id" not in session:
return redirect(url_for("signin"))
if "profile_picture" not in request.files:
flash("No file selected.", "error")
return redirect(url_for("profile"))
file = request.files["profile_picture"]
if file.filename == "":
flash("No file selected.", "error")
return redirect(url_for("profile"))
allowed_extensions = {"png", "jpg", "jpeg", "webp"}
ext = file.filename.rsplit(".", 1)[-1].lower()
if ext not in allowed_extensions:
flash("Invalid file type. Use PNG, JPG, or WEBP.", "error")
return redirect(url_for("profile"))
# Create unique filename
filename = f"profile_{session['user_id']}.{ext}"
save_path = os.path.join(app.config["UPLOAD_FOLDER"], filename)
file.save(save_path)
# Update DB
db = get_db()
db.execute("UPDATE users SET profile_picture = ? WHERE id = ?",
(filename, session["user_id"]))
db.commit()
# Update session
session["profile_picture"] = filename
flash("Profile picture updated!", "success")
return redirect(url_for("profile"))
@app.route("/profile/delete-picture", methods=["POST"])
def delete_profile_picture():
if "user_id" not in session:
return redirect(url_for("signin"))
db = get_db()
user = db.execute("SELECT profile_picture FROM users WHERE id = ?",
(session["user_id"],)).fetchone()
if user and user["profile_picture"]:
# Delete file from disk
file_path = os.path.join(app.config["UPLOAD_FOLDER"], user["profile_picture"])
if os.path.exists(file_path):
os.remove(file_path)
# Clear from DB
db.execute("UPDATE users SET profile_picture = NULL WHERE id = ?",
(session["user_id"],))
db.commit()
# Clear from session
session.pop("profile_picture", None)
flash("Profile picture removed.", "success")
return redirect(url_for("profile"))
# Delete Account Route
@app.route('/delete-account')
def delete_account():
if 'user_id' not in session:
return redirect(url_for('signin'))
user_id = session['user_id']
db = get_db()
# Delete user's images
items = db.execute('SELECT image FROM items WHERE owner_id = ?', (user_id,)).fetchall()
for item in items:
if item['image']:
try:
os.remove(os.path.join(app.config['UPLOAD_FOLDER'], item['image']))
except:
pass
# Delete all user data (cascading should handle this if set up properly)
db.execute('DELETE FROM items WHERE owner_id = ?', (user_id,))
db.execute('DELETE FROM users WHERE id = ?', (user_id,))
db.commit()
# Clear session
session.clear()
return redirect(url_for('index'))
# Delete Item Route
@app.route('/delete-item/<int:item_id>', methods=['POST'])
def delete_item(item_id):
if 'user_id' not in session:
return jsonify({'success': False, 'error': 'Not logged in'}), 401
db = get_db()
# Get item and verify ownership
item = db.execute(
"SELECT * FROM items WHERE id = ?",
(item_id,)
).fetchone()
if not item:
flash("Item not found.", "danger")
return redirect(url_for("profile"))
if item["owner_id"] != session['user_id']:
flash("You cannot delete this item.", "danger")
return redirect(url_for("profile"))
# Delete image file if exists
if item['image']:
try:
os.remove(os.path.join(app.config['UPLOAD_FOLDER'], item['image']))
except:
pass
# Delete from database
db.execute('DELETE FROM items WHERE id = ?', (item_id,))
db.commit()
flash("Item deleted successfully.", "success")
return redirect(url_for("profile"))
# Browse Items Route
@app.route('/browseItems')
def browse_items():
if 'user_id' not in session:
return redirect(url_for('signin'))
# Get search parameters
search = request.args.get('search', '')
category = request.args.get('category', '')
sort = request.args.get('sort', 'newest')
db = get_db()
# Build query
query = '''
SELECT items.*, users.username as owner_name, users.hostel
FROM items
JOIN users ON items.owner_id = users.id
WHERE items.is_active = 1
'''
params = []
# Add search filter
if search:
query += " AND (items.name LIKE ? OR items.description LIKE ?)"
params.extend([f'%{search}%', f'%{search}%'])
# Add category filter
if category:
query += " AND items.category = ?"
params.append(category)
# Add sorting
if sort == 'newest':
query += " ORDER BY items.created_at DESC"
elif sort == 'oldest':
query += " ORDER BY items.created_at ASC"
elif sort == 'popular':
query += " ORDER BY items.views DESC"
items = db.execute(query, params).fetchall()
user_id = session.get("user_id")
requested_items = db.execute("""
SELECT item_id FROM swap_requests
WHERE requester_id = ? AND status = 'pending'
""", (user_id,)).fetchall()
requested_item_ids = {row['item_id'] for row in requested_items}
return render_template('browseItems.html',
items=items,
username=session.get("username"),
requested_item_ids=requested_item_ids)
@app.route('/item/<int:item_id>')
def item_detail(item_id):
if 'user_id' not in session:
return redirect(url_for('signin'))
user_id = session.get("user_id")
db = get_db()
# Fetch item and owner info
item = db.execute("""
SELECT
i.id,
i.name,
i.description,
i.category,
i.condition,
i.image,
i.created_at,
i.is_active,
u.id as owner_id,
u.username AS owner_name,
u.phone AS owner_phone,
u.hostel AS owner_hostel
FROM items i
JOIN users u ON i.owner_id = u.id
WHERE i.id = ?
""", (item_id,)).fetchone()
if not item:
return redirect(url_for('browse_items'))
# Check if current user already requested this item
requested = False
if user_id:
existing = db.execute("""
SELECT 1 FROM swap_requests
WHERE item_id = ? AND requester_id = ? AND status = 'pending'
""", (item_id, user_id)).fetchone()
requested = bool(existing)
return render_template(
'items_detail.html',
item=item,
username=session.get("username"),
requested=requested
)
# Upload/Add Item Route
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if 'user_id' not in session:
return redirect(url_for('signin'))
if request.method == 'POST':
# Get form data
name = request.form.get('name')
category = request.form.get('category')
description = request.form.get('description')
condition = request.form.get('condition')
looking_for = request.form.get('looking_for', '')
hostel = request.form.get('hostel')
contact_method = request.form.get('contact_method', 'email')
# Validate required fields
if not all([name, category, description, condition, hostel]):
return render_template('Upload.html',
error="Please fill in all required fields",
username=session.get("username"))
# Handle image upload
image_filename = None
if 'image' in request.files:
file = request.files['image']
# Check if file was selected
if file and file.filename != '':
# Validate file type
if not allowed_file(file.filename):
return render_template('Upload.html',
error="Invalid file type. Only PNG, JPG, and JPEG are allowed",
username=session.get("username"))
# Secure the filename and make it unique
filename = secure_filename(file.filename)
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
image_filename = f"{timestamp}_{filename}"
# Save the file
try:
file_path = os.path.join(app.config['UPLOAD_FOLDER'], image_filename)
file.save(file_path)
except Exception as e:
return render_template('Upload.html',
error=f"Failed to upload image: {str(e)}",
username=session.get("username"))
# Insert into database
try:
db = get_db()
db.execute('''
INSERT INTO items (
owner_id, name, category, description, condition,
looking_for, hostel, contact_method, image,
is_active, views, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0, datetime('now'))
''', (
session['user_id'], name, category, description, condition,
looking_for, hostel, contact_method, image_filename
))
db.commit()
# Redirect to browse page after successful upload
return redirect(url_for('browse_items'))
except Exception as e:
# If database insert fails and image was uploaded, delete the image
if image_filename:
try:
os.remove(os.path.join(app.config['UPLOAD_FOLDER'], image_filename))
except:
pass
return render_template('Upload.html',
error=f"Failed to create listing: {str(e)}",
username=session.get("username"))
# GET request - show the form
return render_template('Upload.html', username=session.get("username"))
# Save item function (for the heart button)
@app.route('/save-item/<int:item_id>', methods=['POST'])
def save_item(item_id):
if 'user_id' not in session:
flash("Please login first.", "danger")
return redirect(url_for("signin"))
user_id = session['user_id']
db = get_db()
item = db.execute("""
SELECT id, owner_id, is_active
FROM items
WHERE id = ?
""", (item_id,)).fetchone()
if not item:
flash("Item not found.", "danger")
return redirect(url_for("browse_items"))
if item['is_active'] != 1:
flash("Item not available.", "warning")
return redirect(url_for("item_detail", item_id=item_id))
if item['owner_id'] == user_id:
flash("Cannot save your own item.", "warning")
return redirect(url_for("browse_items", item_id=item_id))
existing = db.execute("""
SELECT 1 FROM saved_items
WHERE user_id = ? AND item_id = ?
""", (user_id, item_id)).fetchone()
if existing:
flash("Item already saved.", "warning")
return redirect(url_for("browse_items", item_id=item_id))
db.execute("""
INSERT INTO saved_items (user_id, item_id)
VALUES (?, ?)
""", (user_id, item_id))
db.commit()
flash("Item saved successfully.", "success")
return redirect(url_for("browse_items", item_id=item_id))
@app.route('/unsave-item/<int:item_id>', methods=['POST'])
def unsave_item(item_id):
if 'user_id' not in session:
flash("Please login first.", "danger")
return redirect(url_for("signin"))
db = get_db()
db.execute("""
DELETE FROM saved_items
WHERE user_id = ? AND item_id = ?
""", (session['user_id'], item_id))
db.commit()
flash("Item removed from saved items.", "warning")
return redirect(url_for("profile") + "#saved-items")
@app.route('/notifications')
def notifications():
return render_template('notifications.html', username=session["username"])
@app.route("/logout")
def logout():
session.clear()
return redirect("/")
@app.errorhandler(404)
def page_not_found(e):
return render_template("404.html"), 404
if __name__ == "__main__":
from waitress import serve
if os.getenv('FLASK_ENV') == 'production':
serve(app, host="0.0.0.0", port=8080) # Production server
else:
app.run(debug=True, host="0.0.0.0", port=8080) # Development server
# how to rubn... python -m flask run