Загрузка данных


import os
import socket
from flask import Flask, request, send_from_directory, render_template_string
import qrcode

app = Flask(__name__)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Локальный обмен</title>
    <style>
        body { font-family: sans-serif; padding: 20px; max-width: 600px; margin: 0 auto; background: #f4f4f9; }
        .card { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); margin-bottom: 20px; }
        textarea, input[type="file"], input[type="submit"] { width: 100%; margin-top: 10px; box-sizing: border-box; }
        textarea { height: 100px; }
        button, input[type="submit"] { padding: 10px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
        ul { list-style: none; padding: 0; }
        li { margin: 8px 0; }
        a { color: #007bff; text-decoration: none; }
    </style>
</head>
<body>
    <div class="card">
        <h3>Отправить на ПК</h3>
        <form action="/send_text" method="post">
            <textarea name="text" placeholder="Введите текст..."></textarea>
            <input type="submit" value="Отправить текст">
        </form>
        <hr>
        <form action="/upload_file" method="post" enctype="multipart/form-data">
            <input type="file" name="file">
            <input type="submit" value="Отправить файл">
        </form>
    </div>

    <div class="card">
        <h3>Получить с ПК</h3>
        <form action="/set_pc_data" method="post" style="margin-bottom: 15px;">
            <textarea name="pc_text" placeholder="Текст для передачи на телефон..."></textarea>
            <input type="submit" value="Задать текст для телефона">
        </form>

        {% if pc_text %}
        <div>
            <p><b>Буфер с ПК:</b></p>
            <p id="pc-text-content" style="background: #e9ecef; padding: 10px; border-radius: 4px;">{{ pc_text }}</p>
            <script>
                navigator.clipboard.writeText(`{{ pc_text }}`).catch(err => console.error(err));
            </script>
        </div>
        {% endif %}
    </div>

    <div class="card">
        <h3>Файлы в рабочей папке</h3>
        <ul>
        {% for file in files %}
            {% if file != 'share.py' and file != 'gui.py' and file != 'enter.txt' %}
            <li><a href="/download/{{ file }}" download>{{ file }}</a></li>
            {% endif %}
        {% endfor %}
        </ul>
    </div>
</body>
</html>
"""

pc_state = {"text": ""}

def get_local_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(('10.255.255.255', 1))
        ip = s.getsockname()[0]
    except Exception:
        ip = '127.0.0.1'
    finally:
        s.close()
    return ip

@app.route('/')
def index():
    files = [f for f in os.listdir(BASE_DIR) if os.path.isfile(os.path.join(BASE_DIR, f))]
    return render_template_string(HTML_TEMPLATE, pc_text=pc_state["text"], files=files)

@app.route('/send_text', methods=['POST'])
def receive_text():
    text = request.form.get('text', '')
    if text:
        # Убираем все каретки, чистим крайние переносы
        text = text.replace('\r\n', '\n').replace('\r', '\n').strip()
        # Принудительно делаем один чистый перенос CRLF для Блокнота
        text_for_notepad = text.replace('\n', '\r\n')
        
        filepath = os.path.join(BASE_DIR, 'enter.txt')
        # newline='' убирает подмену со стороны Python в \r\r\n
        with open(filepath, 'a', encoding='utf-8', newline='') as f:
            f.write(text_for_notepad + '\r\n---\r\n')
            
    return index()

@app.route('/upload_file', methods=['POST'])
def receive_file():
    if 'file' in request.files:
        file = request.files['file']
        if file.filename != '':
            file.save(os.path.join(BASE_DIR, file.filename))
    return index()

@app.route('/set_pc_data', methods=['POST'])
def set_pc_data():
    pc_state["text"] = request.form.get('pc_text', '')
    return index()

@app.route('/download/<path:filename>')
def download_file(filename):
    return send_from_directory(BASE_DIR, filename, as_attachment=True)

if __name__ == '__main__':
    port = 5000
    ip = get_local_ip()
    url = f"http://{ip}:{port}"
    
    qr = qrcode.QRCode()
    qr.add_data(url)
    qr.make(fit=True)
    
    print(f"\nСервер запущен. Адрес: {url}\n")
    qr.print_ascii(invert=True)
    
    app.run(host='0.0.0.0', port=port)