Skip to content

Commit ede250f

Browse files
committed
Add mechanism to detect browser/window/tab closing
1 parent 55c6773 commit ede250f

File tree

6 files changed

+89
-3
lines changed

6 files changed

+89
-3
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,10 @@ Apart from what was to be gained from implementing the requirements, this projec
3232

3333
* Flask==2.2.5
3434
* Flask-Session==0.4.1
35+
* Flask_SocketIO==5.3.6
3536
* geographiclib==2.0
3637
* haversine==2.8.0
37-
* Werkzeug==3.0.0
38+
* Werkzeug==3.0.1
3839

3940
### Usage
4041

app.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from flask import Flask, flash, redirect, render_template, request, session
44
from flask_session import Session
5+
from flask_socketio import SocketIO
56
from werkzeug.security import check_password_hash, generate_password_hash
67
from datetime import datetime
78

@@ -12,6 +13,9 @@
1213
# Configure application
1314
app = Flask(__name__)
1415

16+
app.config['SECRET_KEY'] = 'secret!'
17+
socketio = SocketIO(app)
18+
1519
# View HTML changes without rerunning server
1620
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
1721
app.config['TEMPLATES_AUTO_RELOAD'] = True
@@ -49,6 +53,23 @@ def after_request(response):
4953
return response
5054

5155

56+
@socketio.on('disconnect')
57+
def disconnect():
58+
59+
# Print to debug
60+
# print("\nDISCONNECTED:")
61+
# print(f"Current Game ID: {session['current_game_id']}")
62+
# print(f"Current Location ID: {session['current_game_loc_id']}")
63+
# print(f"Current Game Start: {session['current_game_start']}")
64+
65+
current_game_id = session["current_game_id"]
66+
current_game_start = session['current_game_start']
67+
68+
result = queries.get_disconnected(db, current_game_id, current_game_start)
69+
70+
print(f"{result}\n")
71+
72+
5273
####################################################################
5374
#
5475
# INDEX

geo.db

0 Bytes
Binary file not shown.

queries.py

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
from cs50 import SQL
21
import sqlite3
32
from random import randint
43
from datetime import datetime
54
from math import floor, ceil, exp
65
from haversine import haversine, Unit
6+
import time
77

88

99
def get_user(db, new_username, new_password):
@@ -217,6 +217,60 @@ def get_current_game_deleted(db, current_game_id):
217217
return 1
218218

219219

220+
def get_disconnected(db, current_game_id, current_game_start):
221+
222+
# Set current timestamp
223+
current_game_end = datetime.now()
224+
225+
# Delay function by 5 seconds to allow other functions to update db
226+
time.sleep(5)
227+
228+
# TODO try-catch db connection
229+
# Create connection and cursor
230+
connection = sqlite3.connect(db)
231+
cursor = connection.cursor()
232+
233+
# Check value of game_duration
234+
query = "SELECT game_duration FROM games WHERE id = ?; "
235+
cursor.execute(query, (current_game_id,))
236+
result = cursor.fetchone()
237+
238+
# Check if game record is deleted or still there
239+
if result == None:
240+
# Game record has been deleted
241+
result = f"Game record has been deleted."
242+
243+
else:
244+
# Game record is still there & game_duration is still None
245+
if result[0] == None:
246+
# Calculate duration
247+
duration_sec, duration_min = game_answer_duration(current_game_start, current_game_end)
248+
249+
if duration_sec >= 10:
250+
# Update game_duration
251+
query = "UPDATE games SET game_duration = ? WHERE id = ?; "
252+
cursor.execute(query, (duration_min, current_game_id))
253+
254+
# Commit update
255+
connection.commit()
256+
257+
result = f"Game record updated."
258+
259+
else:
260+
get_current_game_deleted(db, current_game_id)
261+
result = f"Game record deleted."
262+
263+
# Game record is still there & game_duration is still None
264+
else:
265+
result = f"Game record has game_duration."
266+
267+
# Close cursor and connection
268+
cursor.close()
269+
connection.close()
270+
271+
return result
272+
273+
220274
def game_answer_distance(loc_answer_lat, loc_answer_long, game_answer_lat, game_answer_long):
221275

222276
# https://pypi.org/project/haversine/

requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
Flask==2.2.5
22
Flask-Session==0.4.1
3+
Flask_SocketIO==5.3.6
34
geographiclib==2.0
45
haversine==2.8.0
5-
Werkzeug==3.0.0
6+
Werkzeug==3.0.1

templates/game.html

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,5 +72,14 @@
7272
</div>
7373

7474

75+
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
76+
77+
<script type="text/javascript" charset="utf-8">
78+
var socket = io();
79+
socket.on('connect', function() {
80+
socket.emit('my event', {data: 'Game started!'});
81+
});
82+
</script>
83+
7584

7685
{% endblock %}

0 commit comments

Comments
 (0)