-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbacklogmain.py
More file actions
314 lines (256 loc) · 11.3 KB
/
backlogmain.py
File metadata and controls
314 lines (256 loc) · 11.3 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
"""Main module for database management and routes to frontend."""
import hashlib
import uuid
import json
import requests
from flask import Flask, request, jsonify, Response
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from rankingservice import create_ranking
# pip install flask flask_sqlalchemy psycopg2 flask_cors if first time running
rankings = {}
app = Flask(__name__)
CORS(app)
# Connection: MAKE SURE TO REPLACE USERNAME:PASSWORD WITH THE ONE SET UP ON YOUR OWN DEVICE
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://username:password@localhost/backlog_manager'
db = SQLAlchemy(app)
RAWG_QUERY_URL = "https://api.rawg.io/api/games"
RAWG_GAME_STAT = "https://api.rawg.io/api/games/{}"
API_KEY = "1af69e1cf8664df59d23e49cd5aca2ea"
# Creates tables in the database (one-time setup for now)
with app.app_context():
db.create_all()
# Allow requests from frontend
# First time users set orgins to the frontend url
CORS(app, resources={r"/*": {"origins": "http://128.113.126.87:3000"}})
class Users(db.Model):
"""Users table with columns: email, name, hashed passwords, and session token."""
email = db.Column(db.String(100), unique=True, nullable=False, primary_key=True)
name = db.Column(db.String(100), unique=True, nullable=False)
password_hash = db.Column(db.String(200), nullable=False)
session_token = db.Column(db.String(200), unique=True, nullable=True)
def __repr__(self):
return f'<User {self.email}>'
def set_password(self, password: str):
"""Hashes and stores the password."""
self.password_hash = hashlib.sha256(password.encode()).hexdigest()
def verify_password(self, input_password: str) -> bool:
"""Checks if the given password matches the stored hash."""
return self.password_hash == hashlib.sha256(input_password.encode()).hexdigest()
def generate_token(self):
"""Generates a new session token."""
self.session_token = str(uuid.uuid4())
class Preferences(db.Model):
"""Preferences table with solumns: email and preferences(json).
Example preferences: genres[], completionTime, esrbRating, platforms[], use_reviews
"""
email = db.Column(db.String(100), unique=True, nullable=False, primary_key=True)
preferences = db.Column(db.JSON, nullable=False)
def __repr__(self):
return f'<User {self.email}>'
class Library(db.Model):
"""Game Library table with columns: email and gameid."""
email = db.Column(db.String(100), nullable=False, primary_key=True)
gameid = db.Column(db.Integer(), nullable=False, primary_key=True)
def __repr__(self):
return f'<Library {self.email}>'
@classmethod
def find_a_users_game(cls, email, gameid):
"""finds a users specific game based on given gameid"""
return cls.query.filter_by(email=email, gameid=gameid).first()
@classmethod
def find_a_users_gamelist(cls, email):
"""finds all games owned by the user"""
return cls.query.filter_by(email=email).all()
class Game(db.Model):
"""Game table with columns:
id, name, platform, genre, release date, description, and a image.
"""
id = db.Column(db.Integer(), unique=True, nullable=False, primary_key=True)
name = db.Column(db.String(200), nullable=False)
platform = db.Column(db.String(200), nullable=False)
genre = db.Column(db.String(200), nullable=False)
release_date = db.Column(db.String(200), nullable=False)
description = db.Column(db.String(200), nullable=False)
image = db.Column(db.String(200), nullable=False)
def __repr__(self):
return f'<Game {self.name}>'
@app.route('/register', methods=['POST'])
def register():
"""API route to register a new user: http://127.0.0.1:5000/register."""
data = request.json
existing_user = Users.query.filter((Users.email == data['email'])).first()
if existing_user:
return jsonify({"error": "User already exists!"}), 400
new_user = Users(email=data['email'], name=data['name'])
new_user.set_password(data['password'])
db.session.add(new_user)
new_user.generate_token()
db.session.commit()
return jsonify({'token': new_user.session_token}), 201
@app.route('/login', methods=['POST'])
def login():
"""API route to login a user: http://127.0.0.1:5000/login."""
data = request.json
user = Users.query.filter_by(email=data['email']).first()
if user and user.verify_password(data['password']):
user.generate_token()
db.session.commit()
return jsonify({'token': user.session_token}), 200
return jsonify({'error': 'Invalid email or password'}), 401
@app.route('/add-game', methods=['POST'])
def add_game():
"""WPI API route to add game for a user: http://127.0.0.1:5000/add-game."""
data = request.json
token = data['token']
rawg_id = data['game_id']
user = Users.query.filter_by(session_token=token).first()
if not user:
return jsonify({'error': 'Invalid token'}), 401
existing = Library.find_a_users_game(user.email, rawg_id)
if existing:
return jsonify({'message': 'Game already added'})
new_entry = Library(email=user.email, gameid=rawg_id)
db.session.add(new_entry)
db.session.commit()
return jsonify({'message': 'Game added successfully'})
@app.route('/delete-game', methods=['POST'])
def delete_game():
"""API route to delete game for a user: http://127.0.0.1:5000/delete-game."""
data = request.json
token = data['token']
rawg_id = data['game_id']
user = Users.query.filter_by(session_token=token).first()
if not user:
return jsonify({'error': 'Invalid token'}), 401
game = Library.find_a_users_game(user.email, rawg_id)
if not game:
return jsonify({'message': 'Game not found in library'})
db.session.delete(game)
db.session.commit()
return jsonify({'message': 'Game deleted successfully'})
@app.route('/get-games-library', methods=['POST', 'OPTIONS'])
def get_game_library():
"""API route to get a user's game library: http://127.0.0.1:5000/get-games-library."""
if request.method == 'OPTIONS':
return '', 200
data = request.json
token = data['token']
user = Users.query.filter_by(session_token=token).first()
if not user:
return jsonify({'error': 'Invalid token'}), 401
user_games = Library.find_a_users_gamelist(user.email)
game_ids = [entry.gameid for entry in user_games]
results = []
for game_id in game_ids:
response = requests.get(RAWG_GAME_STAT.format(game_id), params={'key': API_KEY}, timeout=15)
if response.status_code == 200:
game_data = response.json()
results.append({'id': game_data['id'], 'name': game_data['name']})
json_data = json.dumps(results)
return Response(json_data, content_type='application/json')
@app.route('/search-games', methods=['POST'])
def search_games():
"""API route to search for games using RAWG API:
http://127.0.0.1:5000/search-games."""
data = request.json
search_query = data['query']
params = {
'key': API_KEY,
'search': search_query
}
response = requests.get(RAWG_QUERY_URL, params=params, timeout=15)
results = response.json().get('results', [])
games = [{'id': game['id'], 'name': game['name']} for game in results]
return jsonify({'results': games})
@app.route('/get-default-preferences', methods=['POST'])
def get_default_preferences():
"""API route to get a user's default preferences from the database:
http://127.0.0.1:5000/save-default-preferences.
"""
data = request.json
token = data['token']
user = Users.query.filter_by(session_token=token).first()
#check if user exists
if not user:
return jsonify({'error': 'Invalid token'}), 401
preferences = Preferences.query.filter_by(email=user.email).first()
if preferences:
return jsonify({'preferences': preferences.preferences})
else:
return jsonify({'error': 'No preferences found'}), 404
@app.route('/save-default-preferences', methods=['POST'])
def save_default_preferences():
"""API route to save user preferences to the database:
http://127.0.0.1:5000/save-default-preferences.
"""
data = request.json
token = data['token']
preferences = data['preferences']
user = Users.query.filter_by(session_token=token).first()
if not user:
return jsonify({'error': 'Invalid token'}), 401
existing_preferences = Preferences.query.filter_by(email=user.email).first()
if existing_preferences:
existing_preferences.preferences = preferences
else:
new_preferences = Preferences(email=user.email, preferences=preferences)
db.session.add(new_preferences)
db.session.commit()
return jsonify({'message': 'Preferences saved successfully'})
@app.route('/parse-preferences', methods=['POST'])
def parse_preferences():
"""API route to ranks games based on the user's owned games and preferences:
http://127.0.0.1:5000/parse-preferences.
"""
if request.method == 'OPTIONS':
return '', 200
data = request.json
token = data['token']
preferences = data['preferences']
user = Users.query.filter_by(session_token=token).first()
if not user:
return jsonify({'error': 'Invalid token'}), 401
user_games = Library.find_a_users_gamelist(user.email)
if not user_games:
print("nope")
return jsonify({'error': 'No owned games found'}), 404
game_ids = [game.gameid for game in user_games]
ranked_games = create_ranking(preferences, game_ids)
rankings[user.email] = ranked_games
return jsonify({"message": "Ranking sent to frontend"})
@app.route('/receive-ranking', methods=['POST'])
def receive_ranking():
"""API route to send users ranking of games: http://127.0.0.1:5000/receive-ranking."""
if request.method == 'OPTIONS':
return '', 200
data = request.json
token = data['token']
user = Users.query.filter_by(session_token=token).first()
if not user:
return jsonify({'error': 'Invalid token'}), 401
if user.email not in rankings:
return jsonify({'error': 'No ranking found'}), 404
return jsonify({"ranked_games": rankings[user.email]})
@app.route('/get-game-stats', methods=['POST'])
def get_game_stats():
"""API route to gather a game's detail: http://127.0.0.1:5000/get-game-stats."""
data = request.json
game_id = data['game_id']
response = requests.get(RAWG_GAME_STAT.format(game_id), params={'key': API_KEY}, timeout=15)
if response.status_code == 200:
game_data = response.json()
game_stats = {'title': game_data['name'],
'cover': game_data['background_image'],
'releaseDate': game_data['released'],
'developer': [dev['name'] for dev in game_data['developers']],
'genres': [genre['name'] for genre in game_data['genres']],
'platforms': [plat['platform']['name'] for plat in game_data['platforms']],
'reviews': game_data['ratings']}
if game_data.get('esrb_rating'):
game_stats['rating'] = game_data['esrb_rating']['name']
else:
game_stats['rating'] = "None"
return jsonify({'game_stats': game_stats})
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000, debug=False)