Subversion Repositories programming

Rev

Rev 184 | Rev 368 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
181 ira 1
#!/usr/bin/env python
2
 
3
###
4
# Copyright: Ira W. Snyder (devel@irasnyder.com)
5
# Start Date: 2006-01-11
6
# End Date:
7
# License: GNU General Public License v2 (or at your option, any later version)
8
###
9
 
10
import os, re, shutil, sys, threading, time
11
from optparse import OptionParser
12
 
13
### Default Configuration Variables ###
14
DICT_FILE = '~/.config/animesorter2/animesorter.dict'
15
WORK_DIR =  '~/downloads/usenet'
16
SORT_DIR =  '/data/Anime'
17
TYPES_REGEX = '.*(avi|ogm|mkv|mp4|\d\d\d)$'
18
 
19
### Enum for the print_queue
20
(PROG_HDR, DIR_HDR, MOV_FILE_SUC, MOV_FILE_FAIL,
21
DIR_CREATE_SUC, DIR_CREATE_FAIL, DICT_SUC, DICT_FAIL,
22
DICT_BAD_LINE) = range(9)
23
 
24
class AnimeSorter2:
25
 
26
    def __init__(self, options):
27
        self.options = options
28
        self.__print_queue = []
29
 
30
    def parse_dict(self):
31
        """Parses a dictionary file containing the sort definitions in the form:
32
        DIRECTORY = PATTERN
33
 
34
        Returns a list of tuples of the form (compiled_regex, to_directory)"""
35
 
36
        try:
37
            f = open(self.options.dict_file, 'r', 0)
38
            try:
39
                data = f.read()
40
            finally:
41
                f.close()
42
        except IOError:
43
            self.add_to_print_queue(DICT_FAIL, self.options.dict_file)
44
            sys.exit()
45
 
46
        ### Get a LIST containing each line in the file
47
        lines = [l for l in data.split('\n') if len(l) > 0]
48
 
366 ira 49
        ### Remove comments / blank lines (zero length lines already removed above)
50
        regex = re.compile ('^\s*#.*$')
51
        lines = [l for l in lines if not re.match (regex, l)]
52
        regex = re.compile ('^\s*$')
53
        lines = [l for l in lines if not re.match (regex, l)]
54
 
181 ira 55
        ### Split each line into a tuple, and strip each element of spaces
56
        result = self.split_lines(lines)
57
        result = [(re.compile(r), d) for r, d in result]
58
 
59
        ### Give some information about the dictionary we are using
60
        self.add_to_print_queue(DICT_SUC, self.options.dict_file, len(result))
61
 
62
        return tuple(result)
63
 
64
    def split_lines(self, lines):
65
 
66
        result = []
67
 
68
        for l in lines:
184 ira 69
 
366 ira 70
            try:
71
                r, d = l.split('=')
72
                r = r.strip()
73
                d = d.strip()
74
            except ValueError:
75
                self.add_to_print_queue(DICT_BAD_LINE, l)
76
                continue
181 ira 77
 
366 ira 78
            result.append((r, d))
181 ira 79
 
80
        return result
81
 
82
    def get_matches(self, files, pattern):
83
        """get_matches(files, pattern):
84
 
85
        files is type LIST
86
        pattern is type sre.SRE_Pattern
87
 
88
        Returns a list of the files matching the pattern as type sre.SRE_Match."""
89
 
90
        matches = [m for m in files if pattern.search(m)]
91
        return matches
92
 
93
    def move_files(self, files, fromdir, todir):
94
        """move_files(files, fromdir, todir):
95
        Move the files represented by the list FILES from FROMDIR to TODIR"""
96
        ## Check for a non-default directory
97
        if todir[0] != '/':
98
            todir = os.path.join(self.options.output_dir, todir)
99
 
100
        ## Create the directory if it doesn't exist
101
        if not os.path.isdir(todir):
102
            try:
103
                if self.get_user_choice('Make directory?: %s' % (todir, )):
104
                    os.makedirs(todir)
105
                    self.add_to_print_queue(DIR_CREATE_SUC, todir)
106
            except:
107
                self.add_to_print_queue(DIR_CREATE_FAIL, todir)
108
 
109
        ## Try to move every file, one at a time
110
        for f in files:
111
            srcname = os.path.join(fromdir, f)
112
            dstname = os.path.join(todir, f)
113
 
114
            try:
115
                if self.get_user_choice('Move file?: %s --> %s' % (srcname, dstname)):
116
                    shutil.move(srcname, dstname)
117
                    self.add_to_print_queue(MOV_FILE_SUC, f, todir)
118
            except:
119
                self.add_to_print_queue(MOV_FILE_FAIL, f, todir)
120
 
121
    def print_prog_header(self, arg1, arg2):
122
        print 'Regular Expression File Sorter (aka animesorter)'
123
        print '================================================================================'
124
        print 'Copyright (c) 2005,2006, Ira W. Snyder (devel@irasnyder.com)'
125
        print 'All rights reserved.'
126
        print 'This program is licensed under the GNU GPL v2'
127
        print
128
 
129
    def print_dir_header(self, arg1, arg2):
130
        print 'Working in directory: %s' % arg1
131
        print '================================================================================'
132
 
133
    def print_move_file_suc(self, arg1, arg2):
134
        print 'Moved %s to %s' % (arg1, arg2)
135
 
136
    def print_move_file_fail(self, arg1, arg2):
137
        print 'FAILED to move %s to %s' % (arg1, arg2)
138
 
139
    def print_dir_create_suc(self, arg1, arg2):
140
        print 'Created directory %s' % (arg1, )
141
 
142
    def print_dir_create_fail(self, arg1, arg2):
143
        print 'Failed to create directory %s' % (arg1, )
144
 
145
    def print_dict_suc(self, arg1, arg2):
146
        print 'Using dictionary file: %s' % (arg1, )
147
        print 'Successfully loaded %d records' % (arg2, )
148
        print
149
 
150
    def print_dict_fail(self, arg1, arg2):
151
        print 'Opening dictionary: %s FAILED' % (arg1, )
152
        sys.exit()
153
 
154
    def print_dict_bad_line(self, arg1, arg2):
155
        print 'Bad line in dictionary: %s' % (arg1, )
156
 
157
    def print_thread_routine(self):
158
 
159
        # Loop forever
160
        while True:
161
 
162
            # If we are being told to stop, and we have nothing to print, STOP
163
            if self.__stop_print_thread == True and len(self.__print_queue) == 0:
164
                break
165
 
166
            # If we have something to print
167
            if len(self.__print_queue) > 0:
168
                (item_type, item_from, item_to) = self.__print_queue[0]
169
                del self.__print_queue[0]
170
 
171
                # Emulate a switch statement
172
                { PROG_HDR : self.print_prog_header,
173
                  DIR_HDR  : self.print_dir_header,
174
                  MOV_FILE_SUC : self.print_move_file_suc,
175
                  MOV_FILE_FAIL : self.print_move_file_fail,
176
                  DIR_CREATE_SUC : self.print_dir_create_suc,
177
                  DIR_CREATE_FAIL : self.print_dir_create_fail,
178
                  DICT_SUC : self.print_dict_suc,
179
                  DICT_FAIL : self.print_dict_fail,
180
                  DICT_BAD_LINE : self.print_dict_bad_line } [item_type](item_from, item_to)
181
 
182
            else:
183
                time.sleep(1)
184
 
185
    def add_to_print_queue(self, item_type, item_from=None, item_to=None):
186
        self.__print_queue.append( (item_type, item_from, item_to) )
187
 
188
    def start_print_queue(self):
189
        if self.options.verbose:
190
            self.__stop_print_thread = False
191
            self.__print_thread = threading.Thread(target=self.print_thread_routine)
192
            self.__print_thread.start()
193
 
194
    def stop_print_queue(self):
195
        self.__stop_print_thread = True
196
 
197
    def __dir_walker(self, dict, root, dirs, files):
198
 
199
        ## Get all of the files in the directory that are of the correct types
200
        types_re = re.compile(TYPES_REGEX, re.IGNORECASE)
201
        raw_matches = [f for f in files if types_re.match(f)]
202
 
203
        ### Loop through the dictionary and try to move everything that matches
204
        for regex, todir in dict:
205
            matches = self.get_matches(raw_matches, regex)
206
 
207
            ## Move the files if we've found some
208
            if len(matches) > 0:
209
                self.move_files(matches, root, todir)
210
 
211
    def get_user_choice(self, prompt):
212
 
213
        # If we're not in interactive mode, then always return True
214
        if self.options.interactive == False:
215
            return True
216
 
217
        # Get the user's choice since we're not in interactive mode
218
        done = False
219
        while not done:
220
            s = raw_input('%s [y/n]: ' % (prompt, )).lower()
221
 
222
            if s == 'y' or s == 'yes':
223
                return True
224
 
225
            if s == 'n' or s == 'no':
226
                return False
227
 
228
            print 'Response not understood, try again.'
229
 
230
    def main(self):
231
 
232
        ## Start the print queue
233
        self.start_print_queue()
234
 
235
        ## Print the program's header
236
        self.add_to_print_queue(PROG_HDR)
237
 
238
        ## Parse the dictionary
239
        dict = self.parse_dict()
240
 
241
        if self.options.recursive:
242
            ## Start walking through directories
243
            for root, dirs, files in os.walk(self.options.start_dir):
244
                self.__dir_walker(dict, root, dirs, files)
245
        else:
246
            self.__dir_walker(dict, self.options.start_dir,
247
                    [d for d in os.listdir(self.options.start_dir) if os.path.isdir(d)],
248
                    [f for f in os.listdir(self.options.start_dir) if os.path.isfile(f)])
249
 
250
        ## Stop the print queue
251
        self.stop_print_queue()
252
 
253
### MAIN IS HERE ###
254
if __name__ == '__main__':
255
 
256
    ### Get the program options
257
    parser = OptionParser()
258
    parser.add_option('-q', '--quiet', action='store_false', dest='verbose',
259
            default=True, help='Don\'t print status messages to stdout')
260
    parser.add_option('-d', '--dict', dest='dict_file', default=DICT_FILE,
261
            help='Read dictionary from FILE', metavar='FILE')
262
    parser.add_option('-n', '--not-recursive', action='store_false', dest='recursive',
263
            default=True, help='don\'t run recursively')
264
    parser.add_option('-s', '--start-dir', dest='start_dir', default=WORK_DIR,
265
            help='Start running at directory DIR', metavar='DIR')
266
    parser.add_option('-o', '--output-dir', dest='output_dir', default=SORT_DIR,
267
            help='Sort files into DIR', metavar='DIR')
268
    parser.add_option('-i', '--interactive', dest='interactive', default=False,
269
            help='Confirm each move', action='store_true')
270
 
271
    ## Parse the options
272
    (options, args) = parser.parse_args()
273
 
274
    ## Correct directories
275
    options.dict_file = os.path.abspath(os.path.expanduser(options.dict_file))
276
    options.start_dir = os.path.abspath(os.path.expanduser(options.start_dir))
277
    options.output_dir = os.path.abspath(os.path.expanduser(options.output_dir))
278
 
279
    as = AnimeSorter2(options)
280
    as.main()
281