summaryrefslogtreecommitdiff
path: root/ishtar_common/management/commands/media_simplify_filenames.py
blob: 2295431cda223ceb3d8fa6b6aa2bfd0df44b1f73 (plain)
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2019  Étienne Loks  <etienne.loks_AT_peacefrogsDOTnet>

# 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 <http://www.gnu.org/licenses/>.

# 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")