summaryrefslogtreecommitdiff
path: root/lib/filebrowser/management/commands/fb_version_remove.py
blob: 4e4767a0c1351c79c7bdba2584dbf0c1f0581b4e (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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# coding: utf-8

# Python
import os, re

# Django
from django.core.management.base import BaseCommand, CommandError

# Filebrowser
from filebrowser.settings import EXTENSION_LIST, EXCLUDE, MEDIA_ROOT, DIRECTORY, VERSIONS, EXTENSIONS


class Command(BaseCommand):
    args = '<media_path>'
    help = "Remove version files of a specific version in MEDIA_ROOT or subdirectory of MEDIA_ROOT"

    def handle(self, *args, **options):
        
        media_path = ""
        
        if len(args):
            media_path = args[0]
        
        path = os.path.join(MEDIA_ROOT, media_path)
        
        if not os.path.isdir(path):
            raise CommandError('<media_path> must be a directory in MEDIA_ROOT. "%s" is no directory.' % path);
        
        self.stdout.write("\n%s\n" % self.help)
        self.stdout.write("in this case: %s\n" % path)
        
        # get suffix or prefix
        default_prefix_or_suffix = "s"
        while 1:
            self.stdout.write('\nOlder versions of django-filebrowser used to prefix the filename with the version name.\n')
            self.stdout.write('Current version of django-filebrowser adds the version name as suffix.\n')
            prefix_or_suffix = raw_input('"p" for prefix or "s" for suffix (leave blank for "%s"): ' % default_prefix_or_suffix)
            
            if default_prefix_or_suffix and prefix_or_suffix == '':
                prefix_or_suffix = default_prefix_or_suffix
            if prefix_or_suffix != "s" and prefix_or_suffix != "p":
                sys.stderr.write('Error: "p" and "s" are the only valid inputs.\n')
                prefix_or_suffix = None
                continue
            break
        
        # get version name
        while 1:
            version_name = raw_input('\nversion name ("thumb", "big",...): ')
            
            if version_name == "":
                self.stderr.write('Error: You have to enter a version name like "thumb" or "big".\n')
                version_name = None
                continue
            else:
                break
        
        # get list of all matching files
        files = self.get_files(path, version_name, (prefix_or_suffix == "p"))
        
        # output (short version) of files to be deleted
        if len(files) > 15:
            self.stdout.write('\nFirst/Last 5 files to remove:\n')
            for current_file in files[:5]:
                self.stdout.write('%s\n' % current_file)
            self.stdout.write('...\n')    
            self.stdout.write('...\n')
            for current_file in files[len(files)-5:]:
                self.stdout.write('%s\n' % current_file)
        else:
            self.stdout.write('\nFiles to remove:\n')
            for current_file in files:
                self.stdout.write('%s\n' % current_file)
        
        # no files...done
        if len(files) == 0:
            self.stdout.write('0 files removed.\n\n')
            return
        else:
            self.stdout.write('%d file(s) will be removed.\n\n' % len(files))
        
        # ask to make sure
        do_remove = ""
        self.stdout.write('Sure you want to delete these files?\n')
        do_remove = raw_input('"y" for Yes or "n" for No (leave blank for No): ')
        
        # if "yes" we delete. any different case we finish without removing anything
        if do_remove == "y":
            for current_file in files:
                os.remove(current_file)
            self.stdout.write('%d file(s) removed.\n\n' % len(files))
        else:
            self.stdout.write('No files removed.\n\n')
        return
        
    
    # get files mathing:
    # path: search recoursive in this path (os.walk)
    # version_name: string is pre/suffix of filename
    # search_for_prefix: if true we match against the start of the filename (default is the end)
    def get_files(self, path, version_name, search_for_prefix):
        file_list = []
        # Precompile regular expressions
        filter_re = []
        for exp in EXCLUDE:
           filter_re.append(re.compile(exp))
        
        # walkt throu the filebrowser directory
        # for all/new files (except file versions itself and excludes)
        for dirpath,dirnames,filenames in os.walk(path):
            for filename in filenames:
                filtered = False
                # no "hidden" files (stating with ".")
                if filename.startswith('.'):
                    continue
                # check the exclude list
                for re_prefix in filter_re:
                    if re_prefix.search(filename):
                        filtered = True
                if filtered:
                    continue
                (filename_noext, extension) = os.path.splitext(filename)
                # images only
                if extension in EXTENSIONS["Image"]:
                    # if image matches with version_name we add it to the file_list
                    if search_for_prefix:
                        if filename_noext.startswith(version_name + "_"):
                            file_list.append(os.path.join(dirpath, filename))
                    elif filename_noext.endswith("_" + version_name):
                        file_list.append(os.path.join(dirpath, filename))
        
        return file_list