roulette/roulette.py

368 lines
10 KiB
Python
Raw Normal View History

2017-01-26 22:32:27 +00:00
# -*- coding: utf8 -*
2017-01-28 14:57:39 +00:00
# TODO : renommer 'etat' dela sqlite en 'fin_ban'
2017-01-27 09:49:01 +00:00
from flask import Flask, request, g, redirect, url_for, \
2017-01-26 22:32:27 +00:00
abort, render_template, flash
from functools import wraps
from contextlib import closing
import sqlite3
import MySQLdb as mdb
from time import time, localtime, strftime
import locale
import random
2017-01-28 14:57:39 +00:00
from getpass import getpass
2017-01-26 22:32:27 +00:00
# configuration
DEBUG = True
SECRET_KEY = "\xf3'\xd2\xf7\xa4[.h\x8e\x11|\xda\x00\x9fyS\xfe\xb3(!\x91'6\x16"
2017-01-28 14:57:39 +00:00
USERnom = 'admin'
2017-01-26 22:32:27 +00:00
PASSWORD = 'pipo'
2017-01-28 14:57:39 +00:00
SQLITE_FILEnom = '/var/roulette/players.db'
2017-01-26 22:32:27 +00:00
SQLITE_SCHEMA = 'schema.sql'
MYSQL_HOST = 'mysql.rez'
2017-01-28 14:57:39 +00:00
MYSQL_USER = 're2o'
MYSQL_DB = 're2o'
2017-01-26 22:32:27 +00:00
BAN_DURATION = 30. * 60.
IMMUNITY_FILE = '/var/www/roulette/immunity'
2017-01-26 22:32:27 +00:00
ASSHOLES_FILE = '/var/www/roulette/assholes'
2017-01-28 14:57:39 +00:00
IMMUNITY = []
2017-01-26 22:32:27 +00:00
ASSHOLES = []
2017-01-28 15:03:00 +00:00
app = Flask(__name__)
app.config.from_object(__name__)
2017-01-26 22:32:27 +00:00
app.secret_key = SECRET_KEY
random.seed(time())
locale.setlocale(locale.LC_ALL, 'fr_FR.utf8')
# Utilisation de la base SQLite
def connect_sqlite():
2017-01-28 14:57:39 +00:00
return sqlite3.connect(SQLITE_FILEnom)
2017-01-26 22:32:27 +00:00
def init_db():
2017-01-28 14:57:39 +00:00
2017-01-26 22:32:27 +00:00
# Initialisation de la base SQLite
with closing(connect_sqlite()) as con_sqlite:
2017-01-26 23:58:05 +00:00
with app.open_resource('schema.sql') as f:
con_sqlite.cursor().executescript(f.read().decode("utf-8"))
2017-01-26 23:58:32 +00:00
con_sqlite.commit()
2017-01-26 22:32:27 +00:00
2017-01-28 14:57:39 +00:00
cur_sqlite.execute('''create table players (uid,prenom,nom, etat)''')
cur_sqlite.execute('''create table machines (id,uid_user,ip)''')
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))
con_sqlite.commit()
con_sqlite.close()
2017-01-26 22:32:27 +00:00
def duration_format(seconds):
hours = seconds // 3600
2017-01-26 22:32:27 +00:00
seconds -= 3600*hours
minutes = seconds // 60
2017-01-26 22:32:27 +00:00
seconds -= 60*minutes
s_str = seconds <= 1 and 'seconde' or 'secondes'
m_str = minutes <= 1 and 'minute' or 'minutes'
h_str = hours <= 1 and 'heure' or 'heures'
if hours == 0:
if minutes == 0:
return '%01d %s' % (seconds, s_str)
return '%01d %s et %01d %s' % (minutes, m_str, seconds, s_str)
return '%01d %s, %01d %s et %01d %s' % (hours, h_str, minutes, m_str, seconds, s_str)
def get_ip():
return request.remote_addr
def get_player(player_id):
con = connect_sqlite()
cur = con.cursor()
2017-01-28 14:57:39 +00:00
cur.execute("""select uid,prenom,nom,etat
2017-01-26 22:32:27 +00:00
where id=(?)""", [player_id])
row = cur.fetchone()
con.close()
2017-01-28 14:57:39 +00:00
return {'uid': row[0], 'prenom': row[1], 'nom': row[2], 'etat': row[3]}
2017-01-26 22:32:27 +00:00
def get_player_from_ip(ip):
con = connect_sqlite()
cur = con.cursor()
2017-01-28 14:57:39 +00:00
cur.execute("""select players.id,players.prenom,players.nom,
machines.id,machines.ip,players.etat
2017-01-26 22:32:27 +00:00
from players
inner join machines on players.id=machines.player_id
where machines.ip=(?)""", [ip])
row = cur.fetchone()
con.close()
user = None
if row is not None:
2017-01-28 14:57:39 +00:00
user = {'uid': row[0], 'prenom': row[1], 'nom': row[2], \
'id': row[3], 'ip': row[4], 'etat': row[5]}
2017-01-26 22:32:27 +00:00
return user
2017-01-28 14:57:39 +00:00
def get_player_from_full_nom(prenom, nom):
2017-01-26 22:32:27 +00:00
con = connect_sqlite()
cur = con.cursor()
2017-01-28 14:57:39 +00:00
cur.execute("""select players.id,players.prenom,players.nom,
machines.id,machines.ip,players.etat
2017-01-26 22:32:27 +00:00
from players
inner join machines on players.id=machines.player_id
2017-01-28 14:57:39 +00:00
where players.prenom=(?) and players.nom=(?)""", [prenom, nom])
2017-01-26 22:32:27 +00:00
row = cur.fetchone()
con.close()
user = None
if row is not None:
2017-01-28 14:57:39 +00:00
user = {'id': row[0], 'prenom': row[1], 'nom': row[2], \
'id': row[3], 'ip': row[4], 'etat': row[5]}
2017-01-26 22:32:27 +00:00
return user
def is_banned(user_id):
con = connect_sqlite()
cur = con.cursor()
2017-01-28 14:57:39 +00:00
cur.execute("""select etat from players where id=(?)""", [user_id])
2017-01-26 22:32:27 +00:00
2017-01-28 14:57:39 +00:00
etat = cur.fetchone()[0]
2017-01-26 22:32:27 +00:00
con.close()
2017-01-28 14:57:39 +00:00
return time() < etat
2017-01-26 22:32:27 +00:00
def playable_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
2017-01-27 08:35:18 +00:00
ip=get_ip()
2017-01-28 15:07:34 +00:00
# if DEBUG and ip == '172.21.3.124':
user = get_player_from_ip(ip)
2017-01-27 08:35:18 +00:00
2017-01-27 09:49:01 +00:00
if not user:
2017-01-26 22:32:27 +00:00
return render_template('not_subscribed.html')
# Un utilisateur banni ne peut pas jouer
2017-01-27 09:49:01 +00:00
elif is_banned(user['id']):
2017-01-26 22:32:27 +00:00
return banned()
return f(*args, **kwargs)
return decorated_function
def get_players_not_banned():
con = connect_sqlite()
cur = con.cursor()
2017-01-28 14:57:39 +00:00
cur.execute("""select id,prenom,nom from players
where (?) > etat """, [time()])
2017-01-26 22:32:27 +00:00
rows = cur.fetchall()
con.close()
2017-01-28 14:57:39 +00:00
return [{'id': row[0], 'prenom': row[1], 'nom': row[2]} for row in rows]
2017-01-26 22:32:27 +00:00
def cheat(player_id, target_id):
success = random.choice([True, False])
try:
2017-01-26 22:32:27 +00:00
ok = [line.strip().partition(' ') for line in IMMUNITY]
2017-01-28 14:57:39 +00:00
ok = [get_player_from_full_nom(noms[0], noms[2])['id'] for noms in ok]
2017-01-26 22:32:27 +00:00
ko = [line.strip().partition(' ') for line in ASSHOLES]
2017-01-28 14:57:39 +00:00
ko = [get_player_from_full_nom(noms[0], noms[2])['id'] for noms in ko]
2017-01-26 22:32:27 +00:00
if target_id in ko:
success = True
elif player_id in ko:
success = False
elif target_id in ok:
2017-01-26 22:44:28 +00:00
success = False
2017-01-26 22:32:27 +00:00
except TypeError:
2017-01-26 22:44:28 +00:00
pass
2017-01-26 22:32:27 +00:00
return success
2017-01-26 22:32:27 +00:00
def ban(player_id, target_id, success):
player = get_player(player_id)
target = get_player(target_id)
2017-01-26 22:32:27 +00:00
banned_player = success and target or player
con = connect_sqlite()
cur = con.cursor()
2017-01-28 14:57:39 +00:00
cur.execute("""select id,etat from players
2017-01-26 22:32:27 +00:00
where id=(?)""", [banned_player['id']])
2017-01-28 14:57:39 +00:00
etat = cur.fetchone()[0]
etat = time() + BAN_DURATION
2017-01-26 22:32:27 +00:00
2017-01-28 14:57:39 +00:00
cur.execute("""update players set etat=(?)
where id=(?)""", [etat, banned_player['id']])
2017-01-26 22:32:27 +00:00
cur.execute("""insert into bans (player_id,target_id,success,time)
values (?,?,?,?)""", [player['id'], target['id'], \
success and 1 or 0, time()])
con.commit()
con.close()
def unban(player_id):
con = connect_sqlite()
cur = con.cursor()
2017-01-28 14:57:39 +00:00
cur.execute("""update players set etat=(?)
2017-01-26 22:32:27 +00:00
where id=(?)""", [time() - BAN_DURATION, player_id])
2017-01-26 22:32:27 +00:00
con.commit()
con.close()
def get_bans(player_id):
con = connect_sqlite()
cur = con.cursor()
# Bannissements concernant le joueur :
cur.execute("""select player_id,target_id,success,time from bans
where target_id=(?)
or player_id=(?)""", [player_id, player_id])
rows = cur.fetchall()
con.close()
return [{'player_id': row[0], 'target_id': row[1], \
'success': row[2], 'time': row[3]} for row in rows]
def banned():
player = get_player_from_ip(get_ip())
2017-01-27 00:10:29 +00:00
if DEBUG:
print(player,'is banned and tries to play')
2017-01-26 22:32:27 +00:00
last_ban = sorted(get_bans(player['id']), key=lambda p: p['time'], \
reverse=False)[-1]
if last_ban['target_id'] == player['id'] and last_ban['success'] == 1:
source = get_player(last_ban['player_id'])
explanation = u'Tu t\'es fait bannir par %s %s.' \
2017-01-28 14:57:39 +00:00
% (source['prenom'], source['nom'])
2017-01-26 22:32:27 +00:00
else:
explanation = u'Tu t\'es banni toi-même, pas de chance...'
2017-01-28 14:57:39 +00:00
timeleft = duration_format(int(player['etat'] - time()))
2017-01-26 22:32:27 +00:00
return render_template('banned.html', \
explanation=explanation, timeleft=timeleft)
2017-01-26 22:32:27 +00:00
@app.route('/banned_ip')
def banned_ip():
# Liste des ip pour récupération par babel et plop
2017-01-27 00:06:04 +00:00
if not DEBUG:
2017-01-27 08:35:18 +00:00
if get_ip() not in ['10.7.0.254']:
2017-01-27 00:06:04 +00:00
abort(403)
2017-01-26 22:32:27 +00:00
con = connect_sqlite()
cur = con.cursor()
cur.execute("""select machines.ip from players
inner join machines on players.id=machines.player_id
2017-01-28 14:57:39 +00:00
where players.etat>(?)""", [time()])
2017-01-26 22:32:27 +00:00
rows = cur.fetchall()
con.close()
return '\n'.join([row[0] for row in rows])
@app.route('/')
@playable_required
def home():
2017-01-27 09:49:01 +00:00
player = get_player_from_ip(get_ip())
2017-01-26 22:32:27 +00:00
#if ip not in ['10.69.8.5', '10.69.8.202']:
# abort(403)
2017-01-27 07:42:34 +00:00
if DEBUG:
print(player, 'arrived')
2017-01-26 22:32:27 +00:00
bans = sorted(get_bans(player['id']), \
key=lambda ban: ban['time'], \
reverse=True)
bans_hist = []
for ban in bans:
date = strftime('%Hh%M (%A)', localtime(ban['time']))
source = get_player(ban['player_id'])
target = get_player(ban['target_id'])
if target['id'] == player['id']:
if ban['success']:
entry = ('ban', u'%s : %s %s a réussi à t\'avoir.' \
2017-01-28 14:57:39 +00:00
% (date, source['prenom'], source['nom']))
2017-01-26 22:32:27 +00:00
else:
entry = ('warn', u'%s : %s %s a essayé de te bannir, en vain.' \
2017-01-28 14:57:39 +00:00
% (date, source['prenom'], source['nom']))
2017-01-26 22:32:27 +00:00
else:
if ban['success']:
entry = ('ok', u'%s : Tu as banni %s %s avec succès.' \
2017-01-28 14:57:39 +00:00
% (date, target['prenom'], target['nom']))
2017-01-26 22:32:27 +00:00
else:
entry = ('ban', u'%s : Tu as échoué en voulant bannir %s %s.' \
2017-01-28 14:57:39 +00:00
% (date, target['prenom'], target['nom']))
2017-01-26 22:32:27 +00:00
bans_hist.append(entry)
return render_template('home.html', bans_hist=bans_hist)
@app.route('/jouer', methods=['GET', 'POST'])
@playable_required
def play():
ip = get_ip()
player = get_player_from_ip(ip)
# Traitement de la requête de bannissement
if request.method == 'POST':
target_id = request.form['target_id']
if target_id != 'none':
if is_banned(target_id):
flash(u'Utilisateur déjà banni, il faut en choisir un autre.')
else:
success = cheat(player['id'], target_id)
2017-01-26 22:32:27 +00:00
if success:
target = get_player(target_id)
ban(player['id'], target_id, True)
flash(u'Trop cool, %s a été tranché pour un bon moment.' \
2017-01-28 14:57:39 +00:00
% target['prenom'])
2017-01-26 22:32:27 +00:00
else:
ban(player['id'], target_id, False)
return banned()
# Liste des joueurs non bannis, triée dans l'ordre croissant ou décroissant
players = sorted(get_players_not_banned(), \
2017-01-28 14:57:39 +00:00
key=lambda player: player['prenom'], \
2017-01-26 22:32:27 +00:00
reverse = random.choice([True, False]))
# sans le joueur actuel
players = filter(lambda p: p['id'] != player['id'], players)
return render_template('play.html', players=players)
2017-01-28 15:03:00 +00:00
if __name__ == '__main__':
2017-01-26 22:32:27 +00:00
app.run()