#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2019 Étienne Loks # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # See the file COPYING for details. import os.path import sys from django.conf import settings from django.core.management.base import BaseCommand from ishtar_common.utils import find_all_symlink, \ rename_and_simplify_media_name, get_used_media class Command(BaseCommand): args = '' help = 'Simplify name of files in media' def add_arguments(self, parser): parser.add_argument( '--exclude', nargs='?', dest='exclude', default=None, help="Field to exclude separated with \",\". Example: " "ishtar_common.Import.imported_file," "ishtar_common.Import.imported_images" ) parser.add_argument( '--limit', nargs='?', dest='limit', default=None, help="Field to limit to separated with \",\"." ) def handle(self, *args, **options): exclude = options['exclude'].split(',') if options['exclude'] else [] limit = options['limit'].split(',') if options['limit'] else [] verbose = options['verbosity'] current_links = dict(list(find_all_symlink(settings.MEDIA_ROOT))) new_names = {} if verbose == 2: sys.stdout.write("* list current media...\n") sys.stdout.flush() media = get_used_media(exclude=exclude, limit=limit, return_object_and_field=True) ln = len(media) for idx, result in enumerate(sorted(media, key=lambda x: x[2])): if verbose == 2: nb_point = 10 sys.stdout.write("* processing {}/{} {}{}\r".format( idx + 1, ln, (idx % nb_point) * ".", " " * nb_point) ) sys.stdout.flush() obj, field_name, media = result if not os.path.isfile(media): # missing file... continue if media not in new_names: new_name, modified = rename_and_simplify_media_name(media) if not modified: continue new_names[media] = new_name setattr(obj, field_name, new_names[media]) obj._no_move = True obj._cached_label_checked = True obj.skip_history_when_saving = True obj.save() if verbose > 2: sys.stdout.write("{} renamed {}\n".format( media, new_names[media].split(os.sep)[-1])) if media in current_links.keys(): os.remove(current_links[media]) os.symlink(new_names[media], current_links[media]) if verbose > 2: sys.stdout.write( "symlink {} changed to point to {}\n".format( current_links[media], new_names[media])) current_links.pop(media) if verbose == 2: sys.stdout.write("\n")