File size: 1,195 Bytes
7a4b92f
 
 
 
 
 
a2bc65a
7a4b92f
 
a2bc65a
 
 
 
 
 
7a4b92f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2bc65a
7a4b92f
 
a2bc65a
 
7a4b92f
 
 
 
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
import os;
from datetime import datetime;

USER_DATA_DIR = "user_data/"


def save_data(bytes, filename, identifier=None):
    """Take a file and saved it to a new user_data folder"""
    
    dirname = create_data_dir(identifier)
    
    return save_data_to_dir(bytes, filename, dirname)

def save_data_to_dir(bytes, filename, dirname):

    filepath = os.path.join(dirname, filename) 
    
    assert bytes[0:3] == b'DDF'

    with open(filepath, 'wb') as out:
        out.write(bytes)
        
    # check this is actually a valid ARIS file to catch any malicious fish scientists
    try:
        with open(filepath, 'rb') as file:
            assert file.read(3) == b'DDF'
    except:
        print("Bad file!", filepath)
        return False, None, None
    
    return True, filepath, dirname

def create_data_dir(identifier = None):
    """Create a (probably) unique directory for a task."""
    dirname = os.path.join(USER_DATA_DIR, str(int(datetime.now().timestamp())))
    if identifier:
        dirname = os.path.join(dirname, identifier)
    if os.path.exists(dirname):
        print("Warning,", dirname, "already exists.")
    os.makedirs(dirname, exist_ok=True)
    return dirname