events.py 1.24 KB
Newer Older
charlyjazz's avatar
charlyjazz committed
1
2
3
from flask_socketio import SocketIO
from flask import current_app, request

4
5
import os, uuid, json

charlyjazz's avatar
charlyjazz committed
6
7
8
9
10
11

socketio = SocketIO()


@socketio.on('connected')
def connected():
Carlos Azuaje's avatar
python3    
Carlos Azuaje committed
12
    print("%s connected" % (request.sid))
charlyjazz's avatar
charlyjazz committed
13
14
15
16


@socketio.on('disconnect')
def disconnect():
Carlos Azuaje's avatar
python3    
Carlos Azuaje committed
17
    print("%s disconnected" % (request.sid))
charlyjazz's avatar
charlyjazz committed
18
19
20


@socketio.on('start-transfer')
21
22
23
24
25
26
27
28
29
30
31
32
33
def start_transfer(filename, size):
    """Process an upload request from the client."""
    _, ext = os.path.splitext(filename)
    if ext in ['.exe', '.bin', '.js', '.sh', '.py', '.php']:
        return False  # reject the upload
    id = uuid.uuid4().hex  # server-side filename
    with open(current_app.config['FILEDIR'] + id + '.json', 'wt') as f:
        json.dump({'filename': filename, 'size': size}, f)
    with open(current_app.config['FILEDIR'] + id + ext, 'wb') as f:
        pass
    return id + ext  # allow the upload


charlyjazz's avatar
charlyjazz committed
34
@socketio.on('write-chunk')
35
36
37
38
39
40
41
42
43
44
def write_chunk(filename, offset, data):
    """Write a chunk of data sent by the client."""
    if not os.path.exists(current_app.config['FILEDIR'] + filename):
        return False
    try:
        with open(current_app.config['FILEDIR'] + filename, 'r+b') as f:
            f.seek(offset)
            f.write(data)
    except IOError:
        return False
Carlos Azuaje's avatar
python3    
Carlos Azuaje committed
45
    return True