From 894a4c5e7601098d5ae3a7ec733830495bd54816 Mon Sep 17 00:00:00 2001 From: ABelliqueux Date: Tue, 8 Nov 2022 15:28:53 +0100 Subject: [PATCH] HTTP upload : skip if file exists --- app.py | 31 ++++++++++++++++++++++++++----- defaults.toml | 2 +- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/app.py b/app.py index 5661668..c03365d 100755 --- a/app.py +++ b/app.py @@ -60,6 +60,7 @@ def allowed_ext(filename): # Split from right at first dot to find ext and allow files with "." in name if filename.rsplit(".",1)[-1] in media_exts: return True + def XMLify(string, child_node_name="child"): ''' ''' @@ -120,7 +121,22 @@ def thread_blink(): ''' th = threading.Thread(target=blink_pi, args=(16,)) th.start() - + +def list_media_files(folder): + ''' + List files in folder which extension is allowed (exists in media_exts). + ''' + if os.path.exists(folder): + files = os.listdir(folder); + medias = [] + for fd in files: + if len(fd.split('.')) > 1: + if fd.split('.')[1] in media_exts: + medias.append(fd) + return medias + else: + return [] + @app.route("/") @auth.login_required def main(): @@ -157,7 +173,6 @@ def shutdown(): @auth.login_required def upload_file(): if request.method == "POST": - # TODO : First check name/size of file to avoid uploading if already exists ? # Check if the post request has the file part if "file" not in request.files: return _("No file part: {}").format(str(request.files)) @@ -167,9 +182,15 @@ def upload_file(): if file.filename == "": return _("No selected file") if file and allowed_ext(file.filename): - filename = secure_filename(file.filename) - file.save(os.path.join(upload_folder, filename)) - return _("File saved in {}").format(upload_folder) + if debug: + print("Uploading file {} in {}.".format(str(file.filename, upload_folder))) + if file.filename not in list_media_files(upload_folder): + if debug: + print("Existing files : {}".format(str(list_media_files(upload_folder)))) + filename = secure_filename(file.filename) + file.save(os.path.join(upload_folder, filename)) + return _("File saved in {}").format(upload_folder) + return "File exists, skipping..." return "OK" if __name__ == '__main__': diff --git a/defaults.toml b/defaults.toml index 8910d76..80fa96a 100644 --- a/defaults.toml +++ b/defaults.toml @@ -1,5 +1,5 @@ [DEFAULT] -debug = 0 +debug = 1 auth = "secret" media_folder_local = "~/Videos" media_exts = ["mp4", "avi", "mkv"]