Adaptation à la nouvelle BDD

This commit is contained in:
guimoz 2017-01-28 15:57:39 +01:00
parent 81e2714d00
commit 0b9d05966f

View file

@ -1,5 +1,7 @@
# -*- coding: utf8 -* # -*- coding: utf8 -*
# TODO : renommer 'etat' dela sqlite en 'fin_ban'
from flask import Flask, request, g, redirect, url_for, \ from flask import Flask, request, g, redirect, url_for, \
abort, render_template, flash abort, render_template, flash
@ -10,41 +12,32 @@ import MySQLdb as mdb
from time import time, localtime, strftime from time import time, localtime, strftime
import locale import locale
import random import random
from getpass import getpass
# configuration # configuration
DEBUG = True DEBUG = True
SECRET_KEY = "\xf3'\xd2\xf7\xa4[.h\x8e\x11|\xda\x00\x9fyS\xfe\xb3(!\x91'6\x16" SECRET_KEY = "\xf3'\xd2\xf7\xa4[.h\x8e\x11|\xda\x00\x9fyS\xfe\xb3(!\x91'6\x16"
USERNAME = 'admin' USERnom = 'admin'
PASSWORD = 'pipo' PASSWORD = 'pipo'
SQLITE_FILENAME = '/var/roulette/players.db' SQLITE_FILEnom = '/var/roulette/players.db'
SQLITE_SCHEMA = 'schema.sql' SQLITE_SCHEMA = 'schema.sql'
MYSQL_HOST = 'mysql.rez' MYSQL_HOST = 'mysql.rez'
MYSQL_USER = 'rezo_admin_ro' MYSQL_USER = 're2o'
MYSQL_PASSWORD = 'rezopaspipo' MYSQL_DB = 're2o'
MYSQL_DB = 'rezo_admin'
BAN_DURATION = 30. * 60. BAN_DURATION = 30. * 60.
IMMUNITY_FILE = '/var/www/roulette/immunity' IMMUNITY_FILE = '/var/www/roulette/immunity'
ASSHOLES_FILE = '/var/www/roulette/assholes' ASSHOLES_FILE = '/var/www/roulette/assholes'
IMMUNITY = [ IMMUNITY = []
'Lazare Olivry',
'Brieuc Lacroix',
'Elliot Butty',
'Jean-Christophe Carli',
'Juliette Tibayrenc',
'Elise Laurent',
'Goulven Kermarec',
'Siqi Liu',
]
ASSHOLES = [] ASSHOLES = []
app = Flask(__name__) app = Flask(__nom__)
app.config.from_object(__name__) app.config.from_object(__nom__)
app.secret_key = SECRET_KEY app.secret_key = SECRET_KEY
random.seed(time()) random.seed(time())
@ -53,53 +46,28 @@ locale.setlocale(locale.LC_ALL, 'fr_FR.utf8')
# Utilisation de la base SQLite # Utilisation de la base SQLite
def connect_sqlite(): def connect_sqlite():
return sqlite3.connect(SQLITE_FILENAME) return sqlite3.connect(SQLITE_FILEnom)
def init_db(): def init_db():
# Initialisation de la base SQLite # Initialisation de la base SQLite
with closing(connect_sqlite()) as con_sqlite: with closing(connect_sqlite()) as con_sqlite:
with app.open_resource('schema.sql') as f: with app.open_resource('schema.sql') as f:
con_sqlite.cursor().executescript(f.read().decode("utf-8")) con_sqlite.cursor().executescript(f.read().decode("utf-8"))
con_sqlite.commit() con_sqlite.commit()
# Connexion à la base SQLite locale cur_sqlite.execute('''create table players (uid,prenom,nom, etat)''')
con_sqlite = connect_sqlite() cur_sqlite.execute('''create table machines (id,uid_user,ip)''')
cur_sqlite = con_sqlite.cursor() for user in User.objects.filter(school=1):
if user.has_access() and user.is_adherent():
cur_sqlite.execute("""insert into players values (?,?,?,?)""",(user.uid_number, user.nom, user.surnom, 0))
for m in Machine.objects.filter(user= user):
for i in Interface.objects.filter(machine = m):
cur_sqlite.execute("""insert into machines values (?,?,?) """,(i.id, user.uid_number, i.ipv4.ipv4))
# Connexion à la base MySQL sur babel con_sqlite.commit()
con_mysql = mdb.connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB, \ con_sqlite.close()
charset='utf8', use_unicode=True)
cur_mysql = con_mysql.cursor(mdb.cursors.DictCursor)
# Remplissage de la table players à partir de la table utilisateurs
cur_mysql.execute("""select id,prenom,nom from utilisateurs
where etat='STATE_ACTIVE' and ecole_id=1 and id<>1
and typeUtilisateur='membre'""")
rows = cur_mysql.fetchall()
print('players :')
for row in rows:
if row['prenom'] + ' ' + row['nom'] not in IMMUNITY:
print(row)
cur_sqlite.execute("""insert into players values (?,?,?,?)""", \
((row["id"]), row["prenom"], row["nom"], 0))
# Remplissage de la table ip à partir de la table equipements
cur_mysql.execute("""select equipements.id,utilisateurs.id,equipements.ip
from utilisateurs
inner join equipements on utilisateurs.id=equipements.utilisateur_id
where utilisateurs.ecole_id=1 and utilisateurs.id<>1
and utilisateurs.etat='STATE_ACTIVE' and equipements.etat='STATE_ACTIVE'
and utilisateurs.typeUtilisateur='membre'""")
rows = cur_mysql.fetchall()
print('machines :')
for row in rows:
print(row)
cur_sqlite.execute("""insert into machines values (?,?,?)""", \
(row["id"], row["utilisateurs.id"], row["ip"]))
con_sqlite.commit()
cur_sqlite.close()
cur_mysql.close()
def duration_format(seconds): def duration_format(seconds):
hours = seconds // 3600 hours = seconds // 3600
@ -122,20 +90,20 @@ def get_player(player_id):
con = connect_sqlite() con = connect_sqlite()
cur = con.cursor() cur = con.cursor()
cur.execute("""select id,firstname,name,ban_end from players cur.execute("""select uid,prenom,nom,etat
where id=(?)""", [player_id]) where id=(?)""", [player_id])
row = cur.fetchone() row = cur.fetchone()
con.close() con.close()
return {'id': row[0], 'firstname': row[1], 'name': row[2], 'ban_end': row[3]} return {'uid': row[0], 'prenom': row[1], 'nom': row[2], 'etat': row[3]}
def get_player_from_ip(ip): def get_player_from_ip(ip):
con = connect_sqlite() con = connect_sqlite()
cur = con.cursor() cur = con.cursor()
cur.execute("""select players.id,players.firstname,players.name, cur.execute("""select players.id,players.prenom,players.nom,
machines.id,machines.ip,players.ban_end machines.id,machines.ip,players.etat
from players from players
inner join machines on players.id=machines.player_id inner join machines on players.id=machines.player_id
where machines.ip=(?)""", [ip]) where machines.ip=(?)""", [ip])
@ -145,28 +113,28 @@ def get_player_from_ip(ip):
user = None user = None
if row is not None: if row is not None:
user = {'id': row[0], 'firstname': row[1], 'name': row[2], \ user = {'uid': row[0], 'prenom': row[1], 'nom': row[2], \
'machine_id': row[3], 'ip': row[4], 'ban_end': row[5]} 'id': row[3], 'ip': row[4], 'etat': row[5]}
return user return user
def get_player_from_full_name(firstname, name): def get_player_from_full_nom(prenom, nom):
con = connect_sqlite() con = connect_sqlite()
cur = con.cursor() cur = con.cursor()
cur.execute("""select players.id,players.firstname,players.name, cur.execute("""select players.id,players.prenom,players.nom,
machines.id,machines.ip,players.ban_end machines.id,machines.ip,players.etat
from players from players
inner join machines on players.id=machines.player_id inner join machines on players.id=machines.player_id
where players.firstname=(?) and players.name=(?)""", [firstname, name]) where players.prenom=(?) and players.nom=(?)""", [prenom, nom])
row = cur.fetchone() row = cur.fetchone()
con.close() con.close()
user = None user = None
if row is not None: if row is not None:
user = {'id': row[0], 'firstname': row[1], 'name': row[2], \ user = {'id': row[0], 'prenom': row[1], 'nom': row[2], \
'machine_id': row[3], 'ip': row[4], 'ban_end': row[5]} 'id': row[3], 'ip': row[4], 'etat': row[5]}
return user return user
@ -174,17 +142,18 @@ def is_banned(user_id):
con = connect_sqlite() con = connect_sqlite()
cur = con.cursor() cur = con.cursor()
cur.execute("""select ban_end from players where id=(?)""", [user_id]) cur.execute("""select etat from players where id=(?)""", [user_id])
ban_end = cur.fetchone()[0] etat = cur.fetchone()[0]
con.close() con.close()
return time() < ban_end return time() < etat
def playable_required(f): def playable_required(f):
@wraps(f) @wraps(f)
def decorated_function(*args, **kwargs): def decorated_function(*args, **kwargs):
ip=get_ip() ip=get_ip()
if DEBUG and ip == '172.21.3.124'
user = get_player_from_ip(ip) user = get_player_from_ip(ip)
if not user: if not user:
@ -201,22 +170,22 @@ def get_players_not_banned():
con = connect_sqlite() con = connect_sqlite()
cur = con.cursor() cur = con.cursor()
cur.execute("""select id,firstname,name from players cur.execute("""select id,prenom,nom from players
where (?) > ban_end """, [time()]) where (?) > etat """, [time()])
rows = cur.fetchall() rows = cur.fetchall()
con.close() con.close()
return [{'id': row[0], 'firstname': row[1], 'name': row[2]} for row in rows] return [{'id': row[0], 'prenom': row[1], 'nom': row[2]} for row in rows]
def cheat(player_id, target_id): def cheat(player_id, target_id):
success = random.choice([True, False]) success = random.choice([True, False])
try: try:
ok = [line.strip().partition(' ') for line in IMMUNITY] ok = [line.strip().partition(' ') for line in IMMUNITY]
ok = [get_player_from_full_name(names[0], names[2])['id'] for names in ok] ok = [get_player_from_full_nom(noms[0], noms[2])['id'] for noms in ok]
ko = [line.strip().partition(' ') for line in ASSHOLES] ko = [line.strip().partition(' ') for line in ASSHOLES]
ko = [get_player_from_full_name(names[0], names[2])['id'] for names in ko] ko = [get_player_from_full_nom(noms[0], noms[2])['id'] for noms in ko]
if target_id in ko: if target_id in ko:
success = True success = True
@ -240,14 +209,14 @@ def ban(player_id, target_id, success):
con = connect_sqlite() con = connect_sqlite()
cur = con.cursor() cur = con.cursor()
cur.execute("""select id,ban_end from players cur.execute("""select id,etat from players
where id=(?)""", [banned_player['id']]) where id=(?)""", [banned_player['id']])
ban_end = cur.fetchone()[0] etat = cur.fetchone()[0]
ban_end = time() + BAN_DURATION etat = time() + BAN_DURATION
cur.execute("""update players set ban_end=(?) cur.execute("""update players set etat=(?)
where id=(?)""", [ban_end, banned_player['id']]) where id=(?)""", [etat, banned_player['id']])
cur.execute("""insert into bans (player_id,target_id,success,time) cur.execute("""insert into bans (player_id,target_id,success,time)
values (?,?,?,?)""", [player['id'], target['id'], \ values (?,?,?,?)""", [player['id'], target['id'], \
@ -260,7 +229,7 @@ def unban(player_id):
con = connect_sqlite() con = connect_sqlite()
cur = con.cursor() cur = con.cursor()
cur.execute("""update players set ban_end=(?) cur.execute("""update players set etat=(?)
where id=(?)""", [time() - BAN_DURATION, player_id]) where id=(?)""", [time() - BAN_DURATION, player_id])
con.commit() con.commit()
@ -291,11 +260,11 @@ def banned():
if last_ban['target_id'] == player['id'] and last_ban['success'] == 1: if last_ban['target_id'] == player['id'] and last_ban['success'] == 1:
source = get_player(last_ban['player_id']) source = get_player(last_ban['player_id'])
explanation = u'Tu t\'es fait bannir par %s %s.' \ explanation = u'Tu t\'es fait bannir par %s %s.' \
% (source['firstname'], source['name']) % (source['prenom'], source['nom'])
else: else:
explanation = u'Tu t\'es banni toi-même, pas de chance...' explanation = u'Tu t\'es banni toi-même, pas de chance...'
timeleft = duration_format(int(player['ban_end'] - time())) timeleft = duration_format(int(player['etat'] - time()))
return render_template('banned.html', \ return render_template('banned.html', \
explanation=explanation, timeleft=timeleft) explanation=explanation, timeleft=timeleft)
@ -313,7 +282,7 @@ def banned_ip():
cur.execute("""select machines.ip from players cur.execute("""select machines.ip from players
inner join machines on players.id=machines.player_id inner join machines on players.id=machines.player_id
where players.ban_end>(?)""", [time()]) where players.etat>(?)""", [time()])
rows = cur.fetchall() rows = cur.fetchall()
con.close() con.close()
@ -344,17 +313,17 @@ def home():
if target['id'] == player['id']: if target['id'] == player['id']:
if ban['success']: if ban['success']:
entry = ('ban', u'%s : %s %s a réussi à t\'avoir.' \ entry = ('ban', u'%s : %s %s a réussi à t\'avoir.' \
% (date, source['firstname'], source['name'])) % (date, source['prenom'], source['nom']))
else: else:
entry = ('warn', u'%s : %s %s a essayé de te bannir, en vain.' \ entry = ('warn', u'%s : %s %s a essayé de te bannir, en vain.' \
% (date, source['firstname'], source['name'])) % (date, source['prenom'], source['nom']))
else: else:
if ban['success']: if ban['success']:
entry = ('ok', u'%s : Tu as banni %s %s avec succès.' \ entry = ('ok', u'%s : Tu as banni %s %s avec succès.' \
% (date, target['firstname'], target['name'])) % (date, target['prenom'], target['nom']))
else: else:
entry = ('ban', u'%s : Tu as échoué en voulant bannir %s %s.' \ entry = ('ban', u'%s : Tu as échoué en voulant bannir %s %s.' \
% (date, target['firstname'], target['name'])) % (date, target['prenom'], target['nom']))
bans_hist.append(entry) bans_hist.append(entry)
@ -378,14 +347,14 @@ def play():
target = get_player(target_id) target = get_player(target_id)
ban(player['id'], target_id, True) ban(player['id'], target_id, True)
flash(u'Trop cool, %s a été tranché pour un bon moment.' \ flash(u'Trop cool, %s a été tranché pour un bon moment.' \
% target['firstname']) % target['prenom'])
else: else:
ban(player['id'], target_id, False) ban(player['id'], target_id, False)
return banned() return banned()
# Liste des joueurs non bannis, triée dans l'ordre croissant ou décroissant # Liste des joueurs non bannis, triée dans l'ordre croissant ou décroissant
players = sorted(get_players_not_banned(), \ players = sorted(get_players_not_banned(), \
key=lambda player: player['firstname'], \ key=lambda player: player['prenom'], \
reverse = random.choice([True, False])) reverse = random.choice([True, False]))
# sans le joueur actuel # sans le joueur actuel
@ -393,5 +362,5 @@ def play():
return render_template('play.html', players=players) return render_template('play.html', players=players)
if __name__ == '__main__': if __nom__ == '__main__':
app.run() app.run()