You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

376 lines
14 KiB

4 weeks ago
import os
3 weeks ago
import uuid
import logging
from datetime import datetime
from flask import Flask, current_app, session, redirect, url_for, request, flash, render_template, jsonify, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from flask_mysqldb import MySQL
import MySQLdb.cursors
from werkzeug.utils import secure_filename
from flask_login import LoginManager, UserMixin, login_user, login_required, current_user
from wtforms import Form, StringField
from wtforms.validators import Length, EqualTo, ValidationError
import pymysql
4 weeks ago
3 weeks ago
conn = pymysql.connect(host="localhost", port=3306,
user="root", password="lin556688",
database="mydatabase", charset="utf8mb4")
# 初始化 Flask 应用
4 weeks ago
app = Flask(__name__)
3 weeks ago
app.config['SECRET_KEY'] = 'your_secret_key'
app.secret_key = os.urandom(24) # 生成更安全的会话密钥
app.config['UPLOAD_FOLDER'] = 'uploads/' # 设置上传文件存储目录
4 weeks ago
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True) # 确保目录存在
3 weeks ago
# 配置日志
logging.basicConfig(filename='app.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# MySQL 配置
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root' # 替换为你的 MySQL 用户名
app.config['MYSQL_PASSWORD'] = 'lin556688' # 替换为你的 MySQL 密码
app.config['MYSQL_DB'] = 'mydatabase'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
# 配置日志记录器
logging.basicConfig(filename='app.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# 自定义日志处理器类
class DatabaseLogHandler(logging.Handler):
def emit(self, record):
log_entry = self.format(record)
# 去掉时间戳中的毫秒部分
timestamp = datetime.strptime(record.asctime, '%Y-%m-%d %H:%M:%S,%f').strftime('%Y-%m-%d %H:%M:%S')
cursor = mysql.connection.cursor()
cursor.execute(
"INSERT INTO logs (timestamp, level, message) VALUES (%s, %s, %s)",
(timestamp, record.levelname, log_entry)
)
mysql.connection.commit()
cursor.close()
# 添加自定义日志处理器
db_handler = DatabaseLogHandler()
db_handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
db_handler.setFormatter(formatter)
logger.addHandler(db_handler)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# 初始化 Flask-Login
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
class User(UserMixin):
def __init__(self, id, username, role):
self.id = id
self.username = username
self.role = role
@login_manager.user_loader
def load_user(user_id):
cursor = mysql.connection.cursor()
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
user_data = cursor.fetchone()
cursor.close()
if user_data:
return User(user_data['id'], user_data['username'], user_data['role'])
return None
@app.route('/')
def home():
return render_template('login.html')
3 weeks ago
@app.route('/view_logs')
@login_required
def view_logs():
with open('app.log', 'r') as log_file:
logs = log_file.readlines()
return render_template('logs.html', logs=logs)
4 weeks ago
# 处理文件上传
@app.route('/upload', methods=['POST'])
def upload_file():
3 weeks ago
logger.info("Handling file upload request")
4 weeks ago
if 'file' not in request.files:
3 weeks ago
logger.warning("No file part in request")
4 weeks ago
return jsonify({'message': 'No file part'}), 400
file = request.files['file']
if file.filename == '':
3 weeks ago
logger.warning("No selected file")
4 weeks ago
return jsonify({'message': 'No selected file'}), 400
3 weeks ago
if file and allowed_file(file.filename):
filename = secure_filename(f"{uuid.uuid4().hex}_{file.filename}")
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
4 weeks ago
file.save(filepath)
3 weeks ago
logger.info(f"File uploaded successfully: {filename}")
4 weeks ago
return jsonify({'message': 'File uploaded successfully', 'filepath': filepath}), 201
3 weeks ago
else:
logger.warning("File type not allowed")
return jsonify({'message': 'File type not allowed'}), 400
4 weeks ago
3 weeks ago
# 提供上传文件的访问
4 weeks ago
@app.route('/uploads/<filename>')
def uploaded_file(filename):
3 weeks ago
logger.info(f"Accessing uploaded file: {filename}")
4 weeks ago
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
# 登录页面
@app.route('/login', methods=['GET', 'POST'])
def login():
3 weeks ago
logger.info("Handling login request")
4 weeks ago
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
3 weeks ago
cursor = mysql.connection.cursor()
cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s", (username, password))
user_data = cursor.fetchone()
cursor.close()
if user_data:
user = User(user_data['id'], user_data['username'], user_data['role'])
login_user(user)
logger.info(f"User {username} logged in with role {user_data['role']}")
if user_data['role'] == '侦查者':
4 weeks ago
return redirect(url_for('scout'))
3 weeks ago
elif user_data['role'] == '指挥者':
4 weeks ago
return redirect(url_for('commander'))
3 weeks ago
elif user_data['role'] == '攻击者':
4 weeks ago
return redirect(url_for('attacker'))
else:
3 weeks ago
logger.warning("Invalid credentials")
4 weeks ago
return "Invalid credentials. Please try again."
3 weeks ago
4 weeks ago
return render_template('login.html')
3 weeks ago
# 处理数据库语句
def con_my_sql(sql_code):
try:
conn.ping(reconnect=True)
cursor= conn.cursor(pymysql.cursors.DictCursor)
cursor.execute(sql_code)
conn.commit()
conn.close()
return cursor
except pymysql.MySQLError as err_massage:
conn.rollback()
conn.close()
return type(err_massage), err_massage
class RegisterForm(Form):
captcha = StringField(validators=[Length(min=4,max=4,message='校验码格式错误')])
username = StringField(validators=[Length(min=3,max=10,message='用户名长度必须在3到10个字符之间')])
password = StringField(validators=[Length(min=6,max=20,message='密码长度必须在6到20个字符之间')])
password_confirm = StringField(validators=[EqualTo('password',message='两次输入的密码不一致')])
4 weeks ago
3 weeks ago
def validate_captcha(self, filed):
if filed.data not in ['1111', '2222', '3333']:
raise ValidationError('校验码错误')
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'GET':
return render_template('register.html')
else:
form = RegisterForm(request.form)
if form.validate():
username = form.username.data
password = form.password.data
captcha = form.captcha.data
# 静态注册码进行角色注册
if captcha == "1111":
role = "侦查者"
if captcha == "2222":
role = "指挥者"
if captcha == "3333":
role = "攻击者"
code = "select * from users where username = '%s'" % username
cursor_ans = con_my_sql(code)
cursor_select = cursor_ans.fetchall()
if len(cursor_select) > 0:
return '用户已经存在 <a href="/">返回登录</a>'
else:
code = "INSERT INTO users(username, password, role) VALUES('%s', '%s', '%s')" % (username, password, role)
print(con_my_sql(code))
return '注册成功 <a href="/">返回登录</a>'
else:
print(form.errors)
return redirect(url_for('register'))
4 weeks ago
# 侦查者页面
@app.route('/scout')
3 weeks ago
@login_required
4 weeks ago
def scout():
3 weeks ago
logger.info("Accessing scout page")
if current_user.role != '侦查者':
logger.warning("Unauthorized access to scout page")
return '用户无此页面访问权限 <a href="/">返回登录<a/>'
4 weeks ago
return render_template('scout.html')
# 指挥者页面
@app.route('/commander')
3 weeks ago
@login_required
4 weeks ago
def commander():
3 weeks ago
logger.info("Accessing commander page")
if current_user.role != '指挥者':
logger.warning("Unauthorized access to commander page")
return '用户无此页面访问权限 <a href="/">返回登录<a/>'
3 weeks ago
# 获取特定目录下的所有文件和攻击坐标状态
directory = 'E:/_Ufo/0000jiegou/TheBattleCar/uploads'
media_items = []
try:
media_items = [f for f in os.listdir(directory)
if os.path.isfile(os.path.join(directory, f)) and allowed_file(f)]
except Exception as e:
logger.error(f"Error accessing directory: {str(e)}")
flash(f"Error accessing directory: {str(e)}")
# 获取攻击状态
cursor = mysql.connection.cursor()
cursor.execute("SELECT id, coordinate, attacked, created_at FROM attacks ORDER BY created_at DESC")
attacks = cursor.fetchall()
cursor.close()
return render_template('commander.html', media_items=media_items, attacks=attacks)
# 指挥者发送攻击坐标
@app.route('/send_attack', methods=['POST'])
@login_required
def send_attack():
logger.info("Handling send attack request")
if current_user.role != '指挥者':
logger.warning("Unauthorized access to send attack")
4 weeks ago
return redirect(url_for('login'))
3 weeks ago
coordinate = request.form.get('coordinate')
if not coordinate:
logger.warning("No coordinate provided")
return "No coordinate provided", 400
# 插入攻击坐标到数据库
cursor = mysql.connection.cursor()
cursor.execute("INSERT INTO attacks (coordinate) VALUES (%s)", (coordinate,))
mysql.connection.commit()
cursor.close()
logger.info(f"Attack coordinate sent: {coordinate}")
flash('攻击坐标已发送')
return redirect(url_for('commander'))
4 weeks ago
# 攻击者页面
@app.route('/attacker')
3 weeks ago
@login_required
4 weeks ago
def attacker():
3 weeks ago
logger.info("Accessing attacker page")
if current_user.role != '攻击者':
logger.warning("Unauthorized access to attacker page")
return '用户无此页面访问权限 <a href="/">返回登录<a/>'
3 weeks ago
# 获取攻击坐标列表
cursor = mysql.connection.cursor()
cursor.execute("SELECT id, coordinate, created_at FROM attacks ORDER BY created_at DESC")
attacks = cursor.fetchall()
cursor.close()
return render_template('attacker.html', attacks=attacks)
# 攻击者执行攻击
@app.route('/execute_attack/<int:attack_id>', methods=['POST'])
@login_required
def execute_attack(attack_id):
logger.info(f"Handling execute attack request for ID: {attack_id}")
if current_user.role != '攻击者':
logger.warning("Unauthorized access to execute attack")
4 weeks ago
return redirect(url_for('login'))
3 weeks ago
cursor = mysql.connection.cursor()
cursor.execute("UPDATE attacks SET attacked = TRUE WHERE id = %s", (attack_id,))
mysql.connection.commit()
cursor.close()
logger.info(f"Attack executed for ID: {attack_id}")
flash(f'已对坐标ID为 {attack_id} 的目标完成打击')
return redirect(url_for('attacker'))
4 weeks ago
# 退出登录(清除会话)
@app.route('/logout')
3 weeks ago
@login_required
4 weeks ago
def logout():
3 weeks ago
logger.info("Handling logout request")
4 weeks ago
session.pop('username', None)
session.pop('role', None)
return redirect(url_for('login'))
3 weeks ago
# 发送消息
4 weeks ago
@app.route('/send_message', methods=['GET', 'POST'])
3 weeks ago
@login_required
4 weeks ago
def send_message():
3 weeks ago
logger.info("Handling send message request")
4 weeks ago
if request.method == 'POST':
message = request.form.get('message')
if not message:
3 weeks ago
logger.warning("No message provided")
4 weeks ago
return "No message provided", 400
3 weeks ago
photo_url = None
if 'photo' in request.files:
file = request.files['photo']
if file.filename != '':
if file and allowed_file(file.filename):
filename = secure_filename(f"{uuid.uuid4().hex}_{file.filename}")
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
photo_url = url_for('uploaded_file', filename=filename, _external=True)
else:
logger.warning("Allowed file types are png, jpg, jpeg, gif")
return "Allowed file types are png, jpg, jpeg, gif", 400
# 插入数据到 MySQL
cursor = mysql.connection.cursor()
cursor.execute("INSERT INTO messages (message, photo_url) VALUES (%s, %s)", (message, photo_url))
mysql.connection.commit()
cursor.close()
logger.info(f"Message sent: {message}, Photo URL: {photo_url}")
4 weeks ago
return f"Message and photo (if uploaded) have been received. Message: {message}\nPhoto URL: {photo_url if photo_url else 'N/A'}"
return render_template('send_message.html')
3 weeks ago
# 获取所有消息
@app.route('/messages', methods=['GET'])
@login_required
def get_messages():
logger.info("Handling get messages request")
cursor = mysql.connection.cursor()
cursor.execute("SELECT id, message, photo_url, created_at FROM messages")
result = cursor.fetchall()
cursor.close()
messages = []
for row in result:
messages.append({
'id': row['id'],
'message': row['message'],
'photo_url': row['photo_url'],
'created_at': row['created_at']
})
return jsonify(messages)
4 weeks ago
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=8000)