1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
| import os import base64 import hashlib import json import time import uuid from flask import Flask, request, render_template, send_file, jsonify, redirect, url_for import qrcode from cryptography.fernet import Fernet
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads' QR_CODE_FOLDER = 'qr_codes' RECEIVED_FOLDER = 'received_files' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['QR_CODE_FOLDER'] = QR_CODE_FOLDER app.config['RECEIVED_FOLDER'] = RECEIVED_FOLDER
os.makedirs(UPLOAD_FOLDER, exist_ok=True) os.makedirs(QR_CODE_FOLDER, exist_ok=True) os.makedirs(RECEIVED_FOLDER, exist_ok=True)
transfer_sessions = {}
def calculate_sha256(file_path): """计算文件的 SHA-256 哈希值""" sha256_hash = hashlib.sha256() with open(file_path, "rb") as f: for byte_block in iter(lambda: f.read(4096), b""): sha256_hash.update(byte_block) return sha256_hash.hexdigest()
def split_data(data, chunk_size): """将字节数据分割成指定大小的块""" chunks = [] for i in range(0, len(data), chunk_size): chunks.append(data[i:i + chunk_size]) return chunks
def generate_qr_code(data_str, filename): """生成二维码并保存为文件""" qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr.add_data(data_str) qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white") img.save(os.path.join(app.config['QR_CODE_FOLDER'], filename))
@app.route('/') def index(): """主页 - 文件上传""" return render_template('index.html')
@app.route('/upload', methods=['POST']) def upload_file(): """处理文件上传和二维码生成""" if 'files' not in request.files: return "No file part", 400 files = request.files.getlist('files') if not files or all(f.filename == '' for f in files): return "No selected file", 400
try: chunk_size_kb = int(request.form.get('chunk_size', 100)) display_speed = int(request.form.get('display_speed', 2)) except ValueError: return "Invalid input for chunk size or display speed", 400
chunk_size_bytes = chunk_size_kb * 1024 delay_ms = int(1000 / display_speed) if display_speed > 0 else 500
session_id = str(uuid.uuid4()) key = Fernet.generate_key() cipher_suite = Fernet(key) uploaded_files_info = [] all_chunks_data = []
for file in files: if file: filename = file.filename filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(filepath) file_size = os.path.getsize(filepath) file_hash = calculate_sha256(filepath) file_type = file.content_type or 'unknown'
with open(filepath, 'rb') as f: file_content = f.read() encoded_content = base64.b64encode(file_content).decode('utf-8')
metadata = { 'filename': filename, 'size': file_size, 'type': file_type, 'sha256': file_hash }
data_to_encrypt = json.dumps({ 'metadata': metadata, 'content': encoded_content }).encode('utf-8')
encrypted_data = cipher_suite.encrypt(data_to_encrypt) chunks = split_data(encrypted_data, chunk_size_bytes) all_chunks_data.extend([(chunk, filename) for chunk in chunks])
uploaded_files_info.append({ 'name': filename, 'size': file_size, 'hash': file_hash })
qr_filenames = [] total_chunks = len(all_chunks_data) for i, (chunk_data, filename) in enumerate(all_chunks_data): qr_data_dict = { 'session_id': session_id, 'index': i, 'total': total_chunks, 'filename': filename, 'data': base64.b64encode(chunk_data).decode('utf-8') } if i == 0: qr_data_dict['key'] = key.decode('utf-8')
qr_data_str = json.dumps(qr_data_dict) qr_filename = f"qr_{session_id}_{i}.png" generate_qr_code(qr_data_str, qr_filename) qr_filenames.append(qr_filename)
transfer_sessions[session_id] = { 'key': key.decode('utf-8'), 'total_chunks': total_chunks, 'chunks_received': {}, 'files_info': uploaded_files_info }
return render_template('index.html', qr_files=qr_filenames, delay_ms=delay_ms, session_id=session_id, files_info=uploaded_files_info)
@app.route('/scanner') def scanner(): """扫描页面""" return render_template('scanner.html')
@app.route('/receive_chunk', methods=['POST']) def receive_chunk(): """接收扫描到的二维码数据块 (模拟)""" data = request.json qr_data_str = data.get('qr_data') if not qr_data_str: return jsonify({'status': 'error', 'message': 'No QR data received'}), 400
try: qr_data = json.loads(qr_data_str) except json.JSONDecodeError: return jsonify({'status': 'error', 'message': 'Invalid QR data format'}), 400
session_id = qr_data.get('session_id') index = qr_data.get('index') total = qr_data.get('total') filename = qr_data.get('filename') encrypted_chunk_b64 = qr_data.get('data') key_str = qr_data.get('key')
if not session_id or index is None or total is None or not encrypted_chunk_b64: return jsonify({'status': 'error', 'message': 'Missing data in QR code'}), 400
if session_id not in transfer_sessions: transfer_sessions[session_id] = { 'key': key_str, 'total_chunks': total, 'chunks_received': {}, 'files_info': {} } elif key_str: transfer_sessions[session_id]['key'] = key_str
session = transfer_sessions[session_id] try: cipher_suite = Fernet(session['key'].encode('utf-8')) encrypted_chunk = base64.b64decode(encrypted_chunk_b64) decrypted_chunk = cipher_suite.decrypt(encrypted_chunk) chunk_data = json.loads(decrypted_chunk.decode('utf-8')) session['chunks_received'][index] = { 'data': chunk_data, 'filename': filename } except Exception as e: return jsonify({'status': 'error', 'message': f'Decryption failed: {str(e)}'}), 500
if len(session['chunks_received']) == session['total_chunks']: try: sorted_chunks = sorted(session['chunks_received'].items()) if sorted_chunks: files_content = {} for idx, chunk_info in sorted_chunks: fname = chunk_info['filename'] content = chunk_info['data']['content'] if fname not in files_content: files_content[fname] = [] files_content[fname].append(content) for fname, parts in files_content.items(): full_base64_content = "".join(parts) file_content = base64.b64decode(full_base64_content) output_path = os.path.join(app.config['RECEIVED_FOLDER'], f"received_{fname}") with open(output_path, 'wb') as f: f.write(file_content) del transfer_sessions[session_id] return jsonify({'status': 'success', 'message': 'File(s) received and saved.', 'download_url': url_for('download_file', filename=f"received_{list(files_content.keys())[0]}")}) else: return jsonify({'status': 'error', 'message': 'No chunks to assemble'}), 500 except Exception as e: return jsonify({'status': 'error', 'message': f'File assembly failed: {str(e)}'}), 500
return jsonify({'status': 'success', 'message': f'Chunk {index+1}/{total} received'})
@app.route('/download/<filename>') def download_file(filename): """提供下载重组后的文件""" try: return send_file(os.path.join(app.config['RECEIVED_FOLDER'], filename), as_attachment=True) except FileNotFoundError: return "File not found", 404
if __name__ == '__main__': app.run(debug=True)
|