aboutsummaryrefslogtreecommitdiff
path: root/api
diff options
context:
space:
mode:
Diffstat (limited to 'api')
-rw-r--r--api/auth/login.py14
-rw-r--r--api/auth/login_token.py4
-rw-r--r--api/auth/signup.py26
-rw-r--r--api/auth/token.py28
-rw-r--r--api/dynamic_import.py6
-rw-r--r--api/game/accept.py2
-rw-r--r--api/game/cleanup.py6
-rw-r--r--api/game/info.py68
-rw-r--r--api/game/new.py20
-rw-r--r--api/game/random.py8
-rw-r--r--api/game/socket.py46
-rw-r--r--api/game/voerbak_connector.py8
-rw-r--r--api/hierarchy.py2
-rw-r--r--api/randid.py4
-rw-r--r--api/rating.py16
-rw-r--r--api/ruleset.py20
-rw-r--r--api/social/create_relation.py14
-rw-r--r--api/social/friend_accept.py4
-rw-r--r--api/social/request_list.py4
-rw-r--r--api/social/search.py4
-rw-r--r--api/status.py14
-rw-r--r--api/user/avatar.py4
-rw-r--r--api/user/games.py56
-rw-r--r--api/user/info.py46
-rw-r--r--api/user/password.py2
-rw-r--r--api/user/preferences.py24
-rw-r--r--api/user/status.py4
27 files changed, 227 insertions, 227 deletions
diff --git a/api/auth/login.py b/api/auth/login.py
index 4ae1650..94752d9 100644
--- a/api/auth/login.py
+++ b/api/auth/login.py
@@ -16,22 +16,22 @@ def index():
# return malformed request if email or password is missing
if not email or \
- not password:
+ not password:
return "", 400
# resolve user_id from username or email
user_id = None
user_id = user_id or cursor.execute(
- "select user_id from users where email = ?", [email]
+ "select user_id from users where email = ?", [email]
).fetchone()
user_id = user_id or cursor.execute(
- "select user_id from users where lower(username) = lower(?)", [email]
+ "select user_id from users where lower(username) = lower(?)", [email]
).fetchone()
if user_id == None: return "", 401
# check the password
passwd = cursor.execute(
- "select password_hash from users where user_id = ?", [user_id[0]]
+ "select password_hash from users where user_id = ?", [user_id[0]]
).fetchone()
check = passwords.check_password(password, passwd[0])
if not check: return "", 401
@@ -43,9 +43,9 @@ def index():
# make response with the set_cookie header
res = make_response("", 200)
res.set_cookie(
- "token",
- new_token["token"],
- expires=int(new_token["expirationDate"] / 1000)
+ "token",
+ new_token["token"],
+ expires=int(new_token["expirationDate"] / 1000)
)
return res
diff --git a/api/auth/login_token.py b/api/auth/login_token.py
index bb67c4f..b5b1579 100644
--- a/api/auth/login_token.py
+++ b/api/auth/login_token.py
@@ -7,8 +7,8 @@ from auth.token import validate_token, hash_token
def token_login(token):
hashed = hash_token({"token": token, "expirationDate": 0})
user_id = cursor.execute(
- "select user_id from users where valid_tokens like ?",
- [f"%{hashed['token']}%"]
+ "select user_id from users where valid_tokens like ?",
+ [f"%{hashed['token']}%"]
).fetchone()
return None if not user_id else user_id[0]
diff --git a/api/auth/signup.py b/api/auth/signup.py
index f9a1af5..5e74076 100644
--- a/api/auth/signup.py
+++ b/api/auth/signup.py
@@ -16,7 +16,7 @@ def validate_username(username):
def validate_email(email):
#TODO: use node_modules/email-validator/index.js
return len(email) > 1 and \
- "@" in email
+ "@" in email
# checks if the password is safe (regex explanation in pages/register.tsx)
@@ -40,26 +40,26 @@ def index():
# return 400 (malformed request) if any of the required data is missing
if not username or \
- not email or \
- not password:
+ not email or \
+ not password:
return "", 400
# return 403 (forbidden) if any of the required data is invalid
if not validate_username(username) or \
- not validate_email(email) or \
- not validate_password(password):
+ not validate_email(email) or \
+ not validate_password(password):
return {"error": "form_data_invalid"}, 403
# check if username is taken
if cursor.execute(
- "select username from users where lower(username) = lower(?)",
- [username]
+ "select username from users where lower(username) = lower(?)",
+ [username]
).fetchone():
return {"error": "username_taken"}, 403
# check if email is taken
if cursor.execute("select email from users where email = ?",
- [email]).fetchone():
+ [email]).fetchone():
return {"error": "email_taken"}, 403
# create new user_id, hash password and note timestamp
@@ -69,8 +69,8 @@ def index():
# write new user to database and commit
cursor.execute(
- "insert into users values (?, ?, ?, NULL, NULL, ?, ?, \"[]\", FALSE, \"user\", \"{}\", \"online\") ",
- (user_id, username, email, password_hash, registered)
+ "insert into users values (?, ?, ?, NULL, NULL, ?, ?, \"[]\", FALSE, \"user\", \"{}\", \"online\") ",
+ (user_id, username, email, password_hash, registered)
)
connection.commit()
@@ -81,9 +81,9 @@ def index():
# create a flask response object to add the set-cookie header to
res = make_response("", 200)
res.set_cookie(
- "token",
- new_token["token"],
- expires=int(new_token["expirationDate"] / 1000)
+ "token",
+ new_token["token"],
+ expires=int(new_token["expirationDate"] / 1000)
)
return res
diff --git a/api/auth/token.py b/api/auth/token.py
index d75c91b..e94b014 100644
--- a/api/auth/token.py
+++ b/api/auth/token.py
@@ -8,32 +8,32 @@ import time
# get valid token hashes for a given user_id
def valid_tokens(user_id):
tokens = json.loads(
- cursor.execute(
- "select valid_tokens from users where user_id = ?", [user_id]
- ).fetchone()[0]
+ cursor.execute(
+ "select valid_tokens from users where user_id = ?", [user_id]
+ ).fetchone()[0]
)
# return only tokens that aren't expired
return [
- token for token in tokens
- if token["expirationDate"] > int(time.time() * 1000)
+ token for token in tokens
+ if token["expirationDate"] > int(time.time() * 1000)
]
def validate_token(user_id, token):
tokens = valid_tokens(user_id)
return hashlib.sha256(str(token).encode()).hexdigest() in [
- t["token"] for t in tokens
- if t["expirationDate"] > int(time.time() * 1000)
+ t["token"] for t in tokens
+ if t["expirationDate"] > int(time.time() * 1000)
]
def modify_tokens(user_id, formatted_token, remove):
temp_tokens = valid_tokens(user_id)
temp_tokens.remove(formatted_token
- ) if remove else temp_tokens.append(formatted_token)
+ ) if remove else temp_tokens.append(formatted_token)
cursor.execute(
- "update users set valid_tokens = ? where user_id = ?",
- [json.dumps(temp_tokens), user_id]
+ "update users set valid_tokens = ? where user_id = ?",
+ [json.dumps(temp_tokens), user_id]
)
connection.commit()
@@ -48,13 +48,13 @@ def revoke_token(user_id, formatted_token):
def hash_token(token):
return {
- "token": hashlib.sha256(str(token["token"]).encode()).hexdigest(),
- "expirationDate": token["expirationDate"]
+ "token": hashlib.sha256(str(token["token"]).encode()).hexdigest(),
+ "expirationDate": token["expirationDate"]
}
def generate_token():
return {
- "token": secrets.token_hex(128),
- "expirationDate": int(time.time() * 1000) + (24 * 60 * 60 * 1000)
+ "token": secrets.token_hex(128),
+ "expirationDate": int(time.time() * 1000) + (24 * 60 * 60 * 1000)
}
diff --git a/api/dynamic_import.py b/api/dynamic_import.py
index 5ce9b6b..ecf9ea1 100644
--- a/api/dynamic_import.py
+++ b/api/dynamic_import.py
@@ -9,9 +9,9 @@ import glob
files = glob.glob(os.path.dirname(__file__) + "/**/*.py", recursive=True)
files.remove(__file__)
files = [
- str(filename).replace(os.path.dirname(__file__) + "/",
- '').replace("/", ".").replace(".py", '')
- for filename in files
+ str(filename).replace(os.path.dirname(__file__) + "/",
+ '').replace("/", ".").replace(".py", '')
+ for filename in files
]
diff --git a/api/game/accept.py b/api/game/accept.py
index a231d3a..5a09df2 100644
--- a/api/game/accept.py
+++ b/api/game/accept.py
@@ -18,7 +18,7 @@ join_game = Blueprint('game_accept', __name__)
@auth_required("user")
def index(game_id):
if cursor.execute("select status from games where game_id = ?",
- [game_id]).fetchone()[0] != "wait_for_opponent":
+ [game_id]).fetchone()[0] != "wait_for_opponent":
return "", 403
start_game(game_id, user_id)
diff --git a/api/game/cleanup.py b/api/game/cleanup.py
index 5b705d2..cc0aab8 100644
--- a/api/game/cleanup.py
+++ b/api/game/cleanup.py
@@ -7,8 +7,8 @@ import time
def cleanup():
now = int(time.time() * 1000)
old_games = cursor.execute(
- "select game_id from games where (status = \"wait_for_opponent\" or status = \"in_progress\") and last_activity < ?",
- [now - 5 * 60 * 1e3]
+ "select game_id from games where (status = \"wait_for_opponent\" or status = \"in_progress\") and last_activity < ?",
+ [now - 5 * 60 * 1e3]
).fetchall()
for game_id in old_games:
cursor.execute("delete from games where game_id = ?", [game_id[0]])
@@ -16,7 +16,7 @@ def cleanup():
def set_interval(
- func, sec
+ func, sec
): # https://stackoverflow.com/questions/2697039/python-equivalent-of-setinterval
def func_wrapper():
set_interval(func, sec)
diff --git a/api/game/info.py b/api/game/info.py
index 869a19c..71fed2e 100644
--- a/api/game/info.py
+++ b/api/game/info.py
@@ -8,25 +8,25 @@ from ruleset import resolve_ruleset
def format_game(game_id, user_id=None):
game = cursor.execute(
- "select " + ", ".join(
- [
- "game_id", # 0
- "parent_game", # 1
- "moves", # 2
- "player_1_id", # 3
- "player_2_id", # 4
- "outcome", # 5
- "created", # 6
- "started", # 7
- "duration", # 8
- "rating_delta_player_1", # 9
- "rating_delta_player_2", # 10
- "ruleset", # 11
- "status", # 12
- "private", # 13
- ]
- ) + " from games where game_id = ?",
- [game_id]
+ "select " + ", ".join(
+ [
+ "game_id", # 0
+ "parent_game", # 1
+ "moves", # 2
+ "player_1_id", # 3
+ "player_2_id", # 4
+ "outcome", # 5
+ "created", # 6
+ "started", # 7
+ "duration", # 8
+ "rating_delta_player_1", # 9
+ "rating_delta_player_2", # 10
+ "ruleset", # 11
+ "status", # 12
+ "private", # 13
+ ]
+ ) + " from games where game_id = ?",
+ [game_id]
).fetchone()
is_player_1 = game[4] != user_id
@@ -36,30 +36,30 @@ def format_game(game_id, user_id=None):
# parse moves into list and return empty list if moves string is empty
moves = [] if len(game[2]) == 0 else [
- int(move) for move in str(game[2] + "0").split(",")
+ int(move) for move in str(game[2] + "0").split(",")
]
return {
- "id": game[0],
- "parent": game[1],
- "moves": moves,
- "opponent": None if not opponent else format_user(opponent),
- "outcome": None if not game[5] else outcome(game[5], is_player_1),
- "created": game[6],
- "started": game[7],
- "duration": game[8],
- "rating": game[9] if is_player_1 else game[10],
- "rating_opponent": game[10] if is_player_1 else game[9],
- "ruleset": resolve_ruleset(game[11]),
- "status": game[12],
- "private": bool(game[13]),
+ "id": game[0],
+ "parent": game[1],
+ "moves": moves,
+ "opponent": None if not opponent else format_user(opponent),
+ "outcome": None if not game[5] else outcome(game[5], is_player_1),
+ "created": game[6],
+ "started": game[7],
+ "duration": game[8],
+ "rating": game[9] if is_player_1 else game[10],
+ "rating_opponent": game[10] if is_player_1 else game[9],
+ "ruleset": resolve_ruleset(game[11]),
+ "status": game[12],
+ "private": bool(game[13]),
}
# check if game_id exists in database
def valid_game_id(game_id):
query = cursor.execute(
- "select game_id from games where game_id = ?", [game_id]
+ "select game_id from games where game_id = ?", [game_id]
).fetchone()
return bool(query)
diff --git a/api/game/new.py b/api/game/new.py
index 7f0862b..8c936de 100644
--- a/api/game/new.py
+++ b/api/game/new.py
@@ -13,8 +13,8 @@ def create_game(user_1_id, private=False, user_2_id=None):
game_id = new_uuid("games")
cursor.execute(
- "insert into games values (?, NULL, \"\", ?, ?, NULL, ?, NULL, ?, NULL, NULL, NULL, \"wait_for_opponent\", \"default\", ?, FALSE) ",
- (game_id, user_1_id, user_2_id, timestamp, timestamp, private)
+ "insert into games values (?, NULL, \"\", ?, ?, NULL, ?, NULL, ?, NULL, NULL, NULL, \"wait_for_opponent\", \"default\", ?, FALSE) ",
+ (game_id, user_1_id, user_2_id, timestamp, timestamp, private)
)
connection.commit()
@@ -25,25 +25,25 @@ def start_game(game_id, user_2_id):
timestamp = int(time.time() * 1000)
db_game = cursor.execute(
- "select player_2_id, status, private from games where game_id = ?",
- [game_id]
+ "select player_2_id, status, private from games where game_id = ?",
+ [game_id]
).fetchone()
if db_game[1] != "wait_for_opponent": return False
if db_game[0] == None:
cursor.execute(
- "update games set player_2_id = ? where game_id = ?",
- (user_2_id, game_id)
+ "update games set player_2_id = ? where game_id = ?",
+ (user_2_id, game_id)
)
cursor.execute(
- "update games set status = \"in_progress\", started = ?, last_activity = ? where game_id = ?",
- (timestamp, timestamp, game_id)
+ "update games set status = \"in_progress\", started = ?, last_activity = ? where game_id = ?",
+ (timestamp, timestamp, game_id)
)
connection.commit()
players = cursor.execute(
- "select player_1_id, player_2_id from games where game_id = ?",
- [game_id]
+ "select player_1_id, player_2_id from games where game_id = ?",
+ [game_id]
).fetchone()
games[game_id] = game(game_id, io, players[0], players[1])
diff --git a/api/game/random.py b/api/game/random.py
index 2dfbe0b..559c9e5 100644
--- a/api/game/random.py
+++ b/api/game/random.py
@@ -17,7 +17,7 @@ random_game = Blueprint('random', __name__)
def index(user_id):
# get public_games (random opponent queue)
public_games = cursor.execute(
- "select game_id from games where private = FALSE and status = \"wait_for_opponent\""
+ "select game_id from games where private = FALSE and status = \"wait_for_opponent\""
).fetchall()
game_started = False
@@ -36,9 +36,9 @@ def index(user_id):
game_started = True
return {
- "id": game_id,
- "player_1": player_1,
- "game_started": game_started
+ "id": game_id,
+ "player_1": player_1,
+ "game_started": game_started
}, 200
diff --git a/api/game/socket.py b/api/game/socket.py
index 63f680c..8bbc951 100644
--- a/api/game/socket.py
+++ b/api/game/socket.py
@@ -31,8 +31,8 @@ class game:
now = int(time.time() * 1000)
cursor.execute(
- "update games set last_activity = ?, moves = moves || ? || ',' where game_id = ?",
- [now, column, self.game_id]
+ "update games set last_activity = ?, moves = moves || ? || ',' where game_id = ?",
+ [now, column, self.game_id]
)
connection.commit()
@@ -42,11 +42,11 @@ class game:
winner = self.board.board[int(self.board.win_positions[0][0])]
outcome = "w" if winner == "2" else "l"
io.emit(
- "finish", {
- "winPositions": self.board.win_positions,
- "boardFull": self.board.board_full
- },
- room=self.room
+ "finish", {
+ "winPositions": self.board.win_positions,
+ "boardFull": self.board.board_full
+ },
+ room=self.room
)
self.close("finished", outcome)
return
@@ -60,18 +60,18 @@ class game:
def close(self, new_status, outcome):
cursor.execute(
- " ".join(
- [
- "update games set", "moves = moves || '0',",
- "duration = ?,", "status = ?,", "outcome = ?",
- "where game_id = ?"
- ]
- ), [
- int(time.time() * 1000) - cursor.execute(
- "select started from games where game_id = ?",
- [self.game_id]
- ).fetchone()[0], new_status, outcome, self.game_id
- ]
+ " ".join(
+ [
+ "update games set", "moves = moves || '0',",
+ "duration = ?,", "status = ?,", "outcome = ?",
+ "where game_id = ?"
+ ]
+ ), [
+ int(time.time() * 1000) - cursor.execute(
+ "select started from games where game_id = ?",
+ [self.game_id]
+ ).fetchone()[0], new_status, outcome, self.game_id
+ ]
)
connection.commit()
@@ -81,8 +81,8 @@ class game:
@io.on("newMove")
def new_move(data):
if not data["game_id"] or \
- not data["move"] or \
- not data["token"]:
+ not data["move"] or \
+ not data["token"]:
return
if not data["game_id"] in games: return
@@ -95,7 +95,7 @@ def new_move(data):
@io.on("resign")
def resign(data):
if not data["game_id"] or \
- not request.cookies.get("token"):
+ not request.cookies.get("token"):
return
if not data["game_id"] in games: return
@@ -103,7 +103,7 @@ def resign(data):
if not user_id: return
if games[data["game_id"]].player_1_id != user_id and \
- games[data["game_id"]].player_2_id != user_id:
+ games[data["game_id"]].player_2_id != user_id:
return
games[data["game_id"]].resign()
diff --git a/api/game/voerbak_connector.py b/api/game/voerbak_connector.py
index 412a512..0b51bd5 100644
--- a/api/game/voerbak_connector.py
+++ b/api/game/voerbak_connector.py
@@ -21,10 +21,10 @@ class bord:
self.board_full = False
self.win_positions = []
self.process = subprocess.Popen(
- [VOERBAK_LOCATION, f"-w {w}", f"-h {h}"],
- stdin=subprocess.PIPE,
- stdout=subprocess.PIPE,
- stderr=None
+ [VOERBAK_LOCATION, f"-w {w}", f"-h {h}"],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=None
)
self.process.stdin.flush()
diff --git a/api/hierarchy.py b/api/hierarchy.py
index f080c45..f75613c 100644
--- a/api/hierarchy.py
+++ b/api/hierarchy.py
@@ -16,7 +16,7 @@ def auth_required(level):
if not user_id: return "", 403
user_rank_text = cursor.execute(
- "select type from users where user_id = ?", [user_id]
+ "select type from users where user_id = ?", [user_id]
).fetchone()[0]
required_rank = ranks.index(level)
diff --git a/api/randid.py b/api/randid.py
index c837c2f..6c1ca9d 100644
--- a/api/randid.py
+++ b/api/randid.py
@@ -10,8 +10,8 @@ def new_uuid(table_name):
column_name = tables[table_name]
# check if id is already taken
if cursor.execute(
- f"select {column_name} from {table_name} where {column_name} = ?",
- [temp_uuid]
+ f"select {column_name} from {table_name} where {column_name} = ?",
+ [temp_uuid]
).fetchone():
return new_uuid(table_name)
else:
diff --git a/api/rating.py b/api/rating.py
index d2beaa3..5295f0d 100644
--- a/api/rating.py
+++ b/api/rating.py
@@ -13,9 +13,9 @@ def rating_v1(won_games): # python is a garbage language
def get_all_games(user_id):
return cursor.execute("select player_1_id, player_2_id, outcome " + \
- "from games " + \
- "where (player_1_id = ? or player_2_id = ?) " + \
- "and status = \"finished\" or status = \"resign\"", [user_id, user_id]).fetchall()
+ "from games " + \
+ "where (player_1_id = ? or player_2_id = ?) " + \
+ "and status = \"finished\" or status = \"resign\"", [user_id, user_id]).fetchall()
# simple rating function that doesn't use game analysis
@@ -24,16 +24,16 @@ def get_rating(user_id):
games = get_all_games(user_id)
# get all games for user_id and switch perspective in which user_id is player_2_id
mapped_games = [
- game if game[0] == user_id else
- (game[1], game[0], outcome(game[2], False)) for game in games
+ game if game[0] == user_id else
+ (game[1], game[0], outcome(game[2], False)) for game in games
]
counted_opponents = {}
for game in mapped_games:
# calculate sum score against user (+1 for win, -1 for lose, 0 for draw game)
counted_opponents[game[1]] = (counted_opponents.get(game[1]) or 0) + {
- "w": 1,
- "l": -1,
- "d": 0
+ "w": 1,
+ "l": -1,
+ "d": 0
}[game[2]]
for opponent in counted_opponents:
# apply the cool curve to the sum score and add to the base score of 400
diff --git a/api/ruleset.py b/api/ruleset.py
index 92c7077..5f33e09 100644
--- a/api/ruleset.py
+++ b/api/ruleset.py
@@ -3,16 +3,16 @@ import json
# predefined rulesets
rulesets = {
- "default": {
- "timelimit": {
- "enabled": False,
- "minutes": 0,
- "seconds": 0,
- "addmove": 0,
- "shared": False,
- },
- "ranked": True,
- }
+ "default": {
+ "timelimit": {
+ "enabled": False,
+ "minutes": 0,
+ "seconds": 0,
+ "addmove": 0,
+ "shared": False,
+ },
+ "ranked": True,
+ }
}
diff --git a/api/social/create_relation.py b/api/social/create_relation.py
index f58e105..af81b69 100644
--- a/api/social/create_relation.py
+++ b/api/social/create_relation.py
@@ -14,7 +14,7 @@ def two_person_endpoint(func):
user_2_id = data.get("id") or ""
if not user_1_id or \
- not user_2_id:
+ not user_2_id:
return "", 403
return func(user_1_id, user_2_id)
@@ -28,8 +28,8 @@ def create_relation(user_1_id, user_2_id, relation_type):
remove_relation(user_2_id, user_1_id)
timestamp = int(time.time() * 1000)
cursor.execute(
- "insert into social values (?, ?, ?, ?)",
- [user_1_id, user_2_id, relation_type, timestamp]
+ "insert into social values (?, ?, ?, ?)",
+ [user_1_id, user_2_id, relation_type, timestamp]
)
connection.commit()
@@ -37,8 +37,8 @@ def create_relation(user_1_id, user_2_id, relation_type):
# remove relation between user_1_id and user_2_id (one-way)
def remove_relation(user_1_id, user_2_id):
cursor.execute(
- "delete from social where user_1_id = ? and user_2_id = ?",
- [user_1_id, user_2_id]
+ "delete from social where user_1_id = ? and user_2_id = ?",
+ [user_1_id, user_2_id]
)
connection.commit()
@@ -58,12 +58,12 @@ def create_relation_route(relation_type):
friend_request = Blueprint('friend_request', __name__)
friend_request.add_url_rule(
- '/request', 'route', create_relation_route("outgoing"), methods=["POST"]
+ '/request', 'route', create_relation_route("outgoing"), methods=["POST"]
)
block = Blueprint('block', __name__)
block.add_url_rule(
- '/block', 'route', create_relation_route("block"), methods=["POST"]
+ '/block', 'route', create_relation_route("block"), methods=["POST"]
)
dynamic_routes = [["/social", friend_request], ["/social", block]]
diff --git a/api/social/friend_accept.py b/api/social/friend_accept.py
index 75dd3b9..4eb4837 100644
--- a/api/social/friend_accept.py
+++ b/api/social/friend_accept.py
@@ -11,8 +11,8 @@ accept = Blueprint('accept', __name__)
@two_person_endpoint
def route(user_1_id, user_2_id):
cursor.execute(
- "update social set type = \"friendship\" where user_1_id = ? and user_2_id = ?",
- [user_2_id, user_1_id]
+ "update social set type = \"friendship\" where user_1_id = ? and user_2_id = ?",
+ [user_2_id, user_1_id]
)
connection.commit()
diff --git a/api/social/request_list.py b/api/social/request_list.py
index 8d1acd6..9b79203 100644
--- a/api/social/request_list.py
+++ b/api/social/request_list.py
@@ -12,8 +12,8 @@ requests = Blueprint('requests', __name__)
def route(user_2_id):
# get a list of friend requests
request_list = cursor.execute(
- "select user_1_id from social where user_2_id = ? and type = \"outgoing\"",
- [user_2_id]
+ "select user_1_id from social where user_2_id = ? and type = \"outgoing\"",
+ [user_2_id]
).fetchall()
# get user_id for each result to prevent repeat user/info requests
diff --git a/api/social/search.py b/api/social/search.py
index a22ea73..f0ce8a2 100644
--- a/api/social/search.py
+++ b/api/social/search.py
@@ -17,8 +17,8 @@ def index():
# use levenshtein with max distance 3 to search for users
#TODO: use mysql and sort by best match
results = cursor.execute(
- "select user_id from users where levenshtein(lower(username), lower(?), 3)",
- [query]
+ "select user_id from users where levenshtein(lower(username), lower(?), 3)",
+ [query]
).fetchmany(20)
formatted = {"results": []}
diff --git a/api/status.py b/api/status.py
index 45410a4..a47c6c4 100644
--- a/api/status.py
+++ b/api/status.py
@@ -7,13 +7,13 @@ status = Blueprint('server_status', __name__)
@status.route('/status')
def index():
return {
- # "users": int,
- "games":
- len(
- cursor.execute(
- "select game_id from games where status = \"in_progress\""
- ).fetchall()
- )
+ # "users": int,
+ "games":
+ len(
+ cursor.execute(
+ "select game_id from games where status = \"in_progress\""
+ ).fetchall()
+ )
}
diff --git a/api/user/avatar.py b/api/user/avatar.py
index 1b5500a..b034c3e 100644
--- a/api/user/avatar.py
+++ b/api/user/avatar.py
@@ -28,14 +28,14 @@ def get_avatar():
@avatar.route(
- '/avatar', methods=["POST"]
+ '/avatar', methods=["POST"]
) #TODO: pillow image size validation (client side resize)
@auth_required("user")
def update_avatar(login):
if not request.data: return "", 400
open(f"database/avatars/{login}.png",
- "wb").write(decode(request.data, "base64"))
+ "wb").write(decode(request.data, "base64"))
return "", 200
diff --git a/api/user/games.py b/api/user/games.py
index 83d721a..92799bd 100644
--- a/api/user/games.py
+++ b/api/user/games.py
@@ -12,26 +12,26 @@ import json
# get total game outcome amount for user
def sum_games(user_id): #! SANITIZE USER_ID FIRST
wld_querys = [
- ' '.join(
- [
- "select count(game_id)",
- "from games",
- "where",
- f"player_{x[0]}_id = \"{user_id}\" and",
- f"outcome = \"{x[1]}\"",
- ]
- ) for x in [(1, "w"), (1, "l"), (2, "w"), (2, "l")]
+ ' '.join(
+ [
+ "select count(game_id)",
+ "from games",
+ "where",
+ f"player_{x[0]}_id = \"{user_id}\" and",
+ f"outcome = \"{x[1]}\"",
+ ]
+ ) for x in [(1, "w"), (1, "l"), (2, "w"), (2, "l")]
]
wld_querys.insert(
- 0, ' '.join(
- [
- "select count(game_id)",
- "from games",
- "where",
- f"(player_1_id = \"{user_id}\" or player_2_id = \"{user_id}\") and",
- "outcome = \"d\"",
- ]
- )
+ 0, ' '.join(
+ [
+ "select count(game_id)",
+ "from games",
+ "where",
+ f"(player_1_id = \"{user_id}\" or player_2_id = \"{user_id}\") and",
+ "outcome = \"d\"",
+ ]
+ )
)
big_query = "select " + ", ".join([f"({query})" for query in wld_querys])
@@ -40,18 +40,18 @@ def sum_games(user_id): #! SANITIZE USER_ID FIRST
# win and lose are calculated from user_id's perspective (player_1_id, player_2_id in db)
return {
- "draw": results[0],
- "win": results[1] + results[4],
- "lose": results[2] + results[3],
- "games": reduce(lambda a, b: a + b, results)
+ "draw": results[0],
+ "win": results[1] + results[4],
+ "lose": results[2] + results[3],
+ "games": reduce(lambda a, b: a + b, results)
}
# get `count` games that `user_id` participated in, sorted by newest game
def fetch_games(user_id, count):
game_ids = cursor.execute(
- "select game_id from games where player_1_id = ? or player_2_id = ? order by created desc",
- [user_id, user_id]
+ "select game_id from games where player_1_id = ? or player_2_id = ? order by created desc",
+ [user_id, user_id]
).fetchmany(count)
export = []
@@ -73,21 +73,21 @@ def index():
token = request.cookies.get("token") or ""
if not user_id and \
- not token:
+ not token:
return "", 400
if token and not user_id:
user_id = token_login(token)
if not cursor.execute(
- "select user_id from users where user_id = ?", [user_id]
+ "select user_id from users where user_id = ?", [user_id]
).fetchone():
return "", 403
export = {}
merge(
- export, {"totals": sum_games(user_id)},
- {"games": fetch_games(user_id, 20)}
+ export, {"totals": sum_games(user_id)},
+ {"games": fetch_games(user_id, 20)}
)
return export, 200
diff --git a/api/user/info.py b/api/user/info.py
index de0d2e8..ee20814 100644
--- a/api/user/info.py
+++ b/api/user/info.py
@@ -8,7 +8,7 @@ import json
# check if user_id exists in database
def valid_user_id(user_id):
query = cursor.execute(
- "select user_id from users where user_id = ?", [user_id]
+ "select user_id from users where user_id = ?", [user_id]
).fetchone()
return bool(query)
@@ -16,8 +16,8 @@ def valid_user_id(user_id):
# get relation to user_2_id from user_1_id's perspective
def get_relation_to(user_1_id, user_2_id):
relation = cursor.execute("select * from social where " + \
- "(user_1_id = ? and user_2_id = ?) or " + \
- "(user_1_id = ? and user_2_id = ?)", [user_1_id, user_2_id, user_2_id, user_1_id]).fetchone()
+ "(user_1_id = ? and user_2_id = ?) or " + \
+ "(user_1_id = ? and user_2_id = ?)", [user_1_id, user_2_id, user_2_id, user_1_id]).fetchone()
if not relation: return "none"
if relation[2] == "friendship": return "friends"
if relation[2] == "outgoing" and relation[0] == user_1_id:
@@ -31,8 +31,8 @@ def get_relation_to(user_1_id, user_2_id):
# get users friend count
def count_friends(user_id):
query = cursor.execute(
- "select type from social where (user_1_id = ? or user_2_id = ?) and type = \"friendship\"",
- [user_id, user_id]
+ "select type from social where (user_1_id = ? or user_2_id = ?) and type = \"friendship\"",
+ [user_id, user_id]
).fetchall()
return len(query) #FIXME: use SQL count() instead of python's len()
@@ -40,25 +40,25 @@ def count_friends(user_id):
# get user/info of `user_id` as `viewer` (id)
def format_user(user_id, viewer=''):
user = cursor.execute(
- "select " + ", ".join(
- [
- "username",
- "user_id",
- "country",
- "registered",
- "status",
- ]
- ) + " from users where user_id = ?", [user_id]
+ "select " + ", ".join(
+ [
+ "username",
+ "user_id",
+ "country",
+ "registered",
+ "status",
+ ]
+ ) + " from users where user_id = ?", [user_id]
).fetchone()
formatted_user = {
- "username": user[0],
- "id": user[1],
- "country": user[2],
- "registered": user[3],
- "status": user[4],
- "friends": count_friends(user_id),
- "rating":
- get_rating(user_id), #TODO: calculate rating based on game analysis
+ "username": user[0],
+ "id": user[1],
+ "country": user[2],
+ "registered": user[3],
+ "status": user[4],
+ "friends": count_friends(user_id),
+ "rating":
+ get_rating(user_id), #TODO: calculate rating based on game analysis
}
if viewer:
#FIXME: validate viewer id?
@@ -86,7 +86,7 @@ def index():
if username:
temp_user_id = cursor.execute(
- "select user_id from users where username = ?", [username]
+ "select user_id from users where username = ?", [username]
).fetchone()
if len(temp_user_id) > 0: user_id = temp_user_id
diff --git a/api/user/password.py b/api/user/password.py
index ff52ba4..b77067f 100644
--- a/api/user/password.py
+++ b/api/user/password.py
@@ -10,7 +10,7 @@ def index():
data = request.get_json()
if not data["password"] or \
- not data["newPassword"]:
+ not data["newPassword"]:
return "", 400
return {}, 200
diff --git a/api/user/preferences.py b/api/user/preferences.py
index 2feaade..2ca4a05 100644
--- a/api/user/preferences.py
+++ b/api/user/preferences.py
@@ -8,15 +8,15 @@ import json
# fill missing dict keys in preferences object
def format_preferences(prefs):
return {
- "darkMode":
- prefs.get("darkMode") or False,
- "ruleset":
- resolve_ruleset(json.dumps(prefs.get("ruleset") or {}) or "default"),
- "userColors": {
- "diskA": prefs.get("userColors", {}).get("diskA") or "",
- "diskB": prefs.get("userColors", {}).get("diskB") or "",
- "background": prefs.get("userColors", {}).get("background") or ""
- }
+ "darkMode":
+ prefs.get("darkMode") or False,
+ "ruleset":
+ resolve_ruleset(json.dumps(prefs.get("ruleset") or {}) or "default"),
+ "userColors": {
+ "diskA": prefs.get("userColors", {}).get("diskA") or "",
+ "diskB": prefs.get("userColors", {}).get("diskB") or "",
+ "background": prefs.get("userColors", {}).get("background") or ""
+ }
}
@@ -27,7 +27,7 @@ preferences = Blueprint('preferences', __name__)
@auth_required("user")
def get_preferences(login):
user_prefs = cursor.execute(
- "select preferences from users where user_id = ?", [login]
+ "select preferences from users where user_id = ?", [login]
).fetchone()
return {"preferences": format_preferences(json.loads(user_prefs[0]))}, 200
@@ -41,8 +41,8 @@ def index(login):
formatted_json = format_preferences(new_preferences)
cursor.execute(
- "update users set preferences = ? where user_id = ?",
- [json.dumps(formatted_json), login]
+ "update users set preferences = ? where user_id = ?",
+ [json.dumps(formatted_json), login]
)
connection.commit()
diff --git a/api/user/status.py b/api/user/status.py
index e762d12..219481a 100644
--- a/api/user/status.py
+++ b/api/user/status.py
@@ -14,8 +14,8 @@ def index(user_id):
if not status: return "", 400
cursor.execute(
- "update users set status = ? where user_id = ?",
- [status[0:200], user_id]
+ "update users set status = ? where user_id = ?",
+ [status[0:200], user_id]
)
connection.commit()