-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
265 lines (221 loc) · 9.56 KB
/
main.py
File metadata and controls
265 lines (221 loc) · 9.56 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
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify
from flask_login import LoginManager, login_user, logout_user, login_required, current_user
import os
from dotenv import load_dotenv
from app.services.tmdb import TMDBService
from app.services.recommender import RecommendationService
from app.models import db, bcrypt, User, Content, Interaction
# Load environment variables
load_dotenv()
# --- App Initialization ---
app = Flask(
__name__,
template_folder="app/templates",
static_folder="app/static"
)
app.secret_key = os.getenv('SECRET_KEY', 'dev-secret-key')
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL', 'sqlite:///movies.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# --- Initialize Extensions ---
login_manager = LoginManager()
db.init_app(app)
bcrypt.init_app(app)
login_manager.init_app(app)
# --- User Loader for Flask-Login ---
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
# --- Custom CLI command to create DB tables ---
@app.cli.command("init-db")
def init_db():
"""Clear existing data and create new tables."""
with app.app_context():
db.create_all()
print("Initialized the database.")
# --- Routes ---
@app.route('/')
def index():
selected_genre = request.args.get('genre', '')
sort_by = request.args.get('sort_by', 'popularity.desc')
genres = TMDBService.get_genres().get('genres', [])
discover_results = TMDBService.discover_movies(genre=selected_genre, sort_by=sort_by)
movies = discover_results.get('results', [])
discover_title = "Discover Movies"
if selected_genre:
genre_name = next((g['name'] for g in genres if g['id'] == int(selected_genre)), None)
if genre_name:
discover_title = f"{genre_name} Movies"
recommendations = []
if current_user.is_authenticated:
with app.app_context():
recs_from_db = RecommendationService.get_recommendations(current_user.id)
for rec in recs_from_db:
details = TMDBService.get_details(rec.tmdb_id, rec.content_type)
if details:
details['media_type'] = rec.content_type
recommendations.append(details)
popular_tv = TMDBService.get_popular_tv().get('results', [])[:10]
return render_template('index.html', movies=movies, tv_shows=popular_tv, recommendations=recommendations, genres=genres, selected_genre=selected_genre, sort_by=sort_by, discover_title=discover_title)
# --- MODIFIED: interact() function ---
@app.route('/interact', methods=['POST'])
@login_required
def interact():
data = request.json
tmdb_id = data.get('tmdb_id')
content_type = data.get('content_type')
# Get all possible interaction data
rating = data.get('rating')
is_interested = data.get('is_interested')
is_watched = data.get('is_watched')
if not tmdb_id or not content_type:
return jsonify({'status': 'error', 'message': 'Missing data'}), 400
with app.app_context():
content = Content.query.filter_by(tmdb_id=tmdb_id, content_type=content_type).first()
if not content:
details = TMDBService.get_details(tmdb_id, content_type)
if not details:
return jsonify({'status': 'error', 'message': 'Could not find content details'}), 404
content = Content(tmdb_id=tmdb_id, title=details.get('title') or details.get('name'), content_type=content_type, poster_path=details.get('poster_path'))
db.session.add(content)
db.session.commit()
interaction = Interaction.query.filter_by(user_id=current_user.id, content_id=content.id).first()
if not interaction:
interaction = Interaction(user_id=current_user.id, content_id=content.id)
# Apply the updates from the request
if rating:
interaction.rating = int(rating)
interaction.is_watched = True # Rating implies watching
if is_interested:
interaction.is_interested = True
if is_watched:
interaction.is_watched = True
db.session.add(interaction)
db.session.commit()
if rating:
with app.app_context():
RecommendationService.update_recommendations_for_user(current_user.id)
return jsonify({'status': 'success', 'message': 'Interaction recorded'})
@app.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('index'))
if request.method == 'POST':
username = request.form['username']
email = request.form['email']
password = request.form['password']
with app.app_context():
user_exists = User.query.filter_by(username=username).first()
email_exists = User.query.filter_by(email=email).first()
if user_exists:
flash('Username already exists.', 'error')
elif email_exists:
flash('Email address is already registered.', 'error')
else:
new_user = User(username=username, email=email)
new_user.set_password(password)
db.session.add(new_user)
db.session.commit()
flash('Account created successfully! Please log in.', 'success')
return redirect(url_for('login'))
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
with app.app_context():
user = User.query.filter_by(username=username).first()
if user and user.check_password(password):
login_user(user, remember=True)
flash('Login successful!', 'success')
return redirect(url_for('index'))
else:
flash('Invalid username or password', 'error')
return render_template('login.html')
# --- MODIFIED: profile() function ---
@app.route('/profile')
@login_required
def profile():
# Fetch watched items (this will now include rated and marked as watched)
watched_interactions = Interaction.query.filter(
Interaction.user_id == current_user.id,
Interaction.is_watched == True
).order_by(Interaction.id.desc()).all()
# Fetch watchlist items
watchlist_items = Interaction.query.filter(
Interaction.user_id == current_user.id,
Interaction.is_interested == True
).order_by(Interaction.id.desc()).all()
return render_template('profile.html', watched_interactions=watched_interactions, watchlist_items=watchlist_items)
@app.route('/logout')
@login_required
def logout():
logout_user()
flash('You have been logged out.', 'info')
return redirect(url_for('index'))
@app.route('/movie/<int:movie_id>')
def movie_detail(movie_id):
try:
movie = TMDBService.get_movie_details(movie_id)
videos = TMDBService.get_movie_videos(movie_id).get('results', [])
trailer = next((v for v in videos if v['type'] == 'Trailer'), None)
user_interaction = None
if current_user.is_authenticated:
with app.app_context():
content = Content.query.filter_by(tmdb_id=movie_id, content_type='movie').first()
if content:
user_interaction = Interaction.query.filter_by(
user_id=current_user.id,
content_id=content.id
).first()
return render_template(
'content_detail.html',
content=movie,
trailer=trailer,
content_type='movie',
interaction=user_interaction
)
except Exception as e:
print(f"Error fetching movie details: {e}")
flash('Error loading movie details.', 'error')
return redirect(url_for('index'))
@app.route('/tv/<int:tv_id>')
def tv_detail(tv_id):
try:
tv_show = TMDBService.get_tv_details(tv_id)
videos = TMDBService.get_tv_videos(tv_id).get('results', [])
trailer = next((v for v in videos if v['type'] == 'Trailer'), None)
user_interaction = None
if current_user.is_authenticated:
with app.app_context():
content = Content.query.filter_by(tmdb_id=tv_id, content_type='tv').first()
if content:
user_interaction = Interaction.query.filter_by(
user_id=current_user.id,
content_id=content.id
).first()
return render_template(
'content_detail.html',
content=tv_show,
trailer=trailer,
content_type='tv',
interaction=user_interaction
)
except Exception as e:
print(f"Error fetching TV details: {e}")
flash('Error loading TV show details.', 'error')
return redirect(url_for('index'))
@app.route('/search')
def search():
query = request.args.get('q', '')
if query:
try:
results = TMDBService.search_multi(query)
search_results = [item for item in results.get('results', []) if item.get('media_type') in ['movie', 'tv']]
return render_template('search.html', results=search_results, query=query)
except Exception as e:
print(f"Search error: {e}")
flash('Error performing search', 'error')
return render_template('search.html', results=[], query=query)