#!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging import os import shutil import sys import unicodedata # command line # pure-uploadscript -p /home/ftp/.on_ftp_upload.pid -B -g 1001 -r /home/ftp/on_ftp_upload.py -u 1001 BASE_DIR = '/home/ftp/storage/' INCOMING_DIR = BASE_DIR + 'incoming/' WWW_DIR = BASE_DIR + 'www/' ALLOWED_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.' LOG_FILE = '/home/ftp/on_ftp_upload.log' LOG_LEVEL = 'INFO' def clean_name(name): # strip accents and replace non allowed characters return ''.join((c if c in ALLOWED_CHARS else '_') for c in unicodedata.normalize('NFD', name) if unicodedata.category(c) != 'Mn') if __name__ == '__main__': # setup logging logging.basicConfig( filename=LOG_FILE, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', level=getattr(logging, LOG_LEVEL), ) try: logging.debug('Starting script') if len(sys.argv) < 2: logging.info('Not enough arguments') sys.exit(1) src_path = sys.argv[1] if not src_path.startswith(BASE_DIR): logging.info('File %s will not be moved because it is not in base dir', src_path) sys.exit(0) # remove special characters name = os.path.basename(src_path) new_name = clean_name(name) if name != new_name: new_path = os.path.join(os.path.dirname(src_path), new_name) os.rename(src_path, new_path) logging.info('File %s has been renamed to %s', src_path, new_path) src_path = new_path # move file if not src_path.startswith(INCOMING_DIR): logging.info('File %s will not be moved because it is not in the incoming dir', src_path) sys.exit(0) dest_path = src_path.replace(INCOMING_DIR, WWW_DIR) if not os.path.exists(os.path.dirname(dest_path)): os.system('mkdir -p -m 775 "%s"' % os.path.dirname(dest_path)) shutil.move(src_path, dest_path) logging.info('File moved %s', src_path) except Exception as e: logging.error('Failed to move file %s. Error: %s', src_path, e) sys.exit(1) else: sys.exit(0)