-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
278 lines (228 loc) · 10.1 KB
/
app.py
File metadata and controls
278 lines (228 loc) · 10.1 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
from flask import Flask, request, render_template, redirect, url_for, session, flash, jsonify
import requests, mysql.connector, json
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
app.secret_key = 'your_secret_key' # Change this to a random secret key
import re
def extract_termination(pgn):
match = re.search(r'\[Termination "(.*?)"\]', pgn)
return match.group(1) if match else "Unknown"
# Add this function to your existing imports
app.jinja_env.filters['extract_termination'] = extract_termination
def create_db_connection():
connection = mysql.connector.connect(host='localhost', user='root', password='priyanshu', database='chess_analyzer')
return connection
@app.route('/')
def index():
if 'user_id' in session:
return render_template('home.html')
return redirect(url_for('login'))
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
connection = create_db_connection()
cursor = connection.cursor(dictionary=True)
cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
user = cursor.fetchone()
if user and check_password_hash(user['password'], password):
session['user_id'] = user['player_id']
session['username'] = user['username']
flash('Logged in successfully!', 'success')
return redirect(url_for('index'))
else:
flash('Invalid username or password', 'error')
cursor.close()
connection.close()
return render_template('login.html')
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
connection = create_db_connection()
cursor = connection.cursor()
hashed_password = generate_password_hash(password)
try:
cursor.execute("INSERT INTO users (username, password) VALUES (%s, %s)", (username, hashed_password))
connection.commit()
player_id = cursor.lastrowid
cursor.execute("INSERT INTO win_log (player_id, white_win, black_win, no_of_draws) VALUES (%s, %s, %s, %s)",
(player_id, 0, 0, 0))
connection.commit()
flash('Registration successful! Please log in.', 'success')
return redirect(url_for('login'))
except mysql.connector.IntegrityError:
flash('Username already exists', 'error')
finally:
cursor.close()
connection.close()
return render_template('register.html')
@app.route('/logout')
def logout():
session.pop('user_id', None)
session.pop('username', None)
flash('Logged out successfully', 'success')
return redirect(url_for('login'))
@app.route('/view_games')
def view_games():
if 'user_id' not in session:
return redirect(url_for('login'))
return render_template('view_games.html')
@app.route('/fetch', methods=['POST'])
def fetch():
if 'user_id' not in session:
return redirect(url_for('login'))
username = request.form['username']
req_url = f"https://api.chess.com/pub/player/{username}/games/archives"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36'
}
req_response = requests.get(req_url, headers=headers)
if req_response.status_code == 200:
game_archives = req_response.json()
if game_archives:
game_archive_latest_month = game_archives["archives"][-1]
latest_month_game_data = requests.get(game_archive_latest_month, headers=headers)
if latest_month_game_data.status_code == 200:
return render_template('view_games.html', games=latest_month_game_data.json()["games"], username=username)
else:
return render_template('view_games.html', error=f"Couldn't fetch latest month game data. Status code:{latest_month_game_data.status_code}", username=username)
else:
return render_template('view_games.html', error=f"Archives are empty for the user {username}", username=username)
else:
return render_template('view_games.html', error=f"Couldn't fetch data for user {username}. Status code:{req_response.status_code}", username=username)
@app.route('/save_game', methods=['POST'])
def save_game():
if 'user_id' not in session:
return redirect(url_for('login'))
game_data = request.form.get('game_data')
if not game_data:
return render_template('view_games.html', error="No game data received.")
try:
game = json.loads(game_data)
except json.JSONDecodeError as err:
return render_template('view_games.html', error=f"Error parsing game data: {err}")
game_pgn = game.get('pgn', '')
game_white = game.get('white', {}).get('username', '')
game_black = game.get('black', {}).get('username', '')
game_id = game.get('url', '')
game_white_result=game.get('white',{}).get('result',{})
game_black_result=game.get('black',{}).get('result',{})
connection = create_db_connection()
cursor = connection.cursor()
try:
insert_game_data_query = """
INSERT INTO game_data (game_id, white_player, black_player, white_result, black_result, moves)
VALUES (%s, %s, %s, %s, %s, %s)
"""
values_game_data = (
game_id,
game_white,
game_black,
game.get('white', {}).get('result', ''),
game.get('black', {}).get('result', ''),
game_pgn
)
cursor.execute(insert_game_data_query, values_game_data)
insert_saved_game_query = """
INSERT INTO saved_games (player_id, chess_com_game_id)
VALUES (%s, %s)
"""
values_saved_game = (session['user_id'], game_id)
cursor.execute(insert_saved_game_query, values_saved_game)
if(game_white_result=="win"):
insert_winlog_query="""
update win_log
set white_win=white_win+1
where player_id=(select player_id from users where username=%s)
"""
cursor.execute(insert_winlog_query,(session['username'],))
elif(game_black_result=="win"):
insert_winlog_query="""
update win_log
set black_win=black_win+1
where player_id=(select player_id from users where username=%s)
"""
cursor.execute(insert_winlog_query,(session['username'],))
elif(game_black_result=="agreed" or game_black_result=="repetition" or game_black_result=="timevsinsufficient" or game_black_result=="stalemate"):
insert_winlog_query="""
update win_log
set no_of_draws=no_of_draws+1
where player_id=(select player_id from users where username=%s)
"""
cursor.execute(insert_winlog_query,(session['username'],))
connection.commit()
return render_template('view_games.html', success="Game saved successfully")
except mysql.connector.IntegrityError:
return render_template('view_games.html', error="Game already exists")
except mysql.connector.Error as err:
return render_template('view_games.html', error=f"Error saving game: {err}")
finally:
cursor.close()
connection.close()
@app.route('/saved_games')
def saved_games():
if 'user_id' not in session:
return redirect(url_for('login'))
connection = create_db_connection()
cursor = connection.cursor(dictionary=True)
try:
query = """
SELECT gd.id, gd.white_player, gd.black_player, gd.white_result, gd.black_result
FROM game_data gd
JOIN saved_games sg ON gd.game_id = sg.chess_com_game_id
WHERE sg.player_id = %s
"""
cursor.execute(query, (session['user_id'],))
saved_games = cursor.fetchall()
return render_template('saved_games.html', saved_games=saved_games)
except mysql.connector.Error as err:
return render_template('saved_games.html', error=f"Error fetching saved games: {err}")
finally:
cursor.close()
connection.close()
@app.route('/delete_game', methods=['GET', 'POST'])
def delete_game():
if 'user_id' not in session:
return redirect(url_for('login'))
if request.method == 'POST':
game_id = request.form.get('game_id')
connection = create_db_connection()
cursor = connection.cursor()
try:
cursor.execute("DELETE FROM game_data WHERE id = %s", (game_id,))
connection.commit()
flash('Game deleted successfully', 'success')
except mysql.connector.Error as err:
flash(f'Error deleting game: {err}', 'error')
finally:
cursor.close()
connection.close()
return redirect(url_for('saved_games'))
return render_template('delete_game.html')
@app.route('/view_stats')
def view_stats():
if 'user_id' not in session:
return redirect(url_for('login'))
connection = create_db_connection()
cursor = connection.cursor(dictionary=True)
try:
# Fetch all users and their current stats from win_log
query = """
SELECT u.username, u.player_id, w.white_win, w.black_win, w.no_of_draws
FROM users u
JOIN win_log w ON u.player_id = w.player_id
"""
cursor.execute(query)
user_stats = cursor.fetchall()
return render_template('view_stats.html', user_stats=user_stats)
except mysql.connector.Error as err:
flash(f'Error fetching statistics: {err}', 'error')
return redirect(url_for('index'))
finally:
cursor.close()
connection.close()
if __name__ == '__main__':
app.run(debug=True)