all repos — myprecious @ main

A lightweight web service to backup precious game saves.

myprecious/files.py (view raw)

 1import os
 2from contextlib import suppress
 3from werkzeug.utils import secure_filename
 4import myprecious.constants as c
 5from myprecious.db import add_save
 6
 7def get_save_folder(platform_id, game_id, user_id):
 8    return os.path.join(c.BASE_DIRECTORY, c.CONTENT_DIRECTORY, str(platform_id), str(game_id), str(user_id))
 9
10def get_title_platform(game_id, platform_id):
11    # TODO: use IGDB api to validate game_id, platform_id and return title and platform name
12    res = { "title": "title", "platform": "platform"}
13    if res is None:
14        raise Exception
15    return res["title"], res["platform"]
16
17def handle_upload(request, user_id):
18    f = request.files['file']
19    if f.filename is None:
20        return "Bad file upload."
21    filename = secure_filename(f.filename)
22    if filename == "":
23        return "Bad filename."
24    try:
25        game_id = int(request.form['game_id'])
26        platform_id = int(request.form['platform_id'])
27    except ValueError:
28        return "Wrong parameter type."
29    
30    try:
31        title, platform = get_title_platform(game_id, platform_id)
32    except Exception:
33        return "Bad or manipulated game data."
34    
35    old_filename = add_save(game_id, title, platform_id, platform, user_id, filename)
36    save_folder = get_save_folder(platform_id, game_id, user_id)
37    with suppress(FileExistsError):
38        os.makedirs(save_folder)
39    if old_filename is not None:
40        os.remove(os.path.join(save_folder, old_filename))
41    save_file = os.path.join(save_folder, filename)
42    f.save(save_file)
43    return None