Subversion Repositories programming

Rev

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