Subversion Repositories programming

Rev

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