Subversion Repositories programming

Rev

Rev 366 | Rev 371 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 366 Rev 368
Line 1... Line 1...
1
#!/usr/bin/env python
1
#!/usr/bin/env python
2
 
2
 
3
###
-
 
4
# Copyright: Ira W. Snyder (devel@irasnyder.com)
3
# 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)
4
# License: GNU General Public License v2 (or at your option, any later version)
8
###
-
 
9
 
5
 
10
import os, re, shutil, sys, threading, time
6
import os, re, shutil, sys
11
from optparse import OptionParser
7
from optparse import OptionParser
12
 
8
 
13
### Default Configuration Variables ###
9
### Default Configuration Variables ###
14
DICT_FILE = '~/.config/animesorter2/animesorter.dict'
10
DICT_FILE = '~/.config/animesorter2/animesorter.dict'
15
WORK_DIR =  '~/downloads/usenet'
11
WORK_DIR =  '~/downloads/usenet'
16
SORT_DIR =  '/data/Anime'
12
SORT_DIR =  '/data/Anime'
17
TYPES_REGEX = '.*(avi|ogm|mkv|mp4|\d\d\d)$'
13
TYPES_REGEX = '.*(avi|ogm|mkv|mp4|\d\d\d)$'
18
 
14
 
19
### Enum for the print_queue
15
### Functions for the printing system
-
 
16
def print_prog_header():
-
 
17
    print 'Regular Expression File Sorter (aka animesorter)'
-
 
18
    print '================================================================================'
-
 
19
    print 'Copyright (c) 2005,2006, Ira W. Snyder (devel@irasnyder.com)'
-
 
20
    print 'All rights reserved.'
-
 
21
    print 'This program is licensed under the GNU GPL v2'
-
 
22
    print
-
 
23
 
-
 
24
def print_move_file_suc(f, t):
-
 
25
    print 'Moved %s to %s' % (f, t)
-
 
26
 
-
 
27
def print_move_file_fail(f, t):
20
(PROG_HDR, DIR_HDR, MOV_FILE_SUC, MOV_FILE_FAIL,
28
    print 'FAILED to move %s to %s' % (f, t)
-
 
29
 
-
 
30
def print_dir_create_suc(d):
-
 
31
    print 'Created directory %s' % (d, )
-
 
32
 
-
 
33
def print_dir_create_fail(d):
-
 
34
    print 'Failed to create directory %s' % (d, )
-
 
35
 
-
 
36
def print_dict_suc(dic, num):
-
 
37
    print 'Successfully loaded %d records from %s\n' % (num, dic)
-
 
38
 
-
 
39
def print_dict_fail(dic):
21
DIR_CREATE_SUC, DIR_CREATE_FAIL, DICT_SUC, DICT_FAIL,
40
    print 'Opening dictionary: %s FAILED' % (dic, )
-
 
41
 
22
DICT_BAD_LINE) = range(9)
42
def print_dict_bad_line(dic):
-
 
43
    print 'Bad line in dictionary: %s' % (dic, )
23
 
44
 
24
class AnimeSorter2:
45
class AnimeSorter2:
25
 
46
 
26
    def __init__(self, options):
47
    def __init__(self, options):
27
        self.options = options
48
        self.options = options
28
        self.__print_queue = []
-
 
29
 
49
 
30
    def parse_dict(self):
50
    def parse_dict(self):
31
        """Parses a dictionary file containing the sort definitions in the form:
51
        """Parses a dictionary file containing the sort definitions in the form:
32
        DIRECTORY = PATTERN
52
        DIRECTORY = PATTERN
33
 
53
 
Line 38... Line 58...
38
            try:
58
            try:
39
                data = f.read()
59
                data = f.read()
40
            finally:
60
            finally:
41
                f.close()
61
                f.close()
42
        except IOError:
62
        except IOError:
43
            self.add_to_print_queue(DICT_FAIL, self.options.dict_file)
63
            print_dict_fail (self.options.dict_file)
44
            sys.exit()
64
            sys.exit()
45
 
65
 
46
        ### Get a LIST containing each line in the file
66
        ### Get a LIST containing each line in the file
47
        lines = [l for l in data.split('\n') if len(l) > 0]
67
        lines = [l for l in data.split('\n') if len(l) > 0]
48
 
68
 
Line 55... Line 75...
55
        ### Split each line into a tuple, and strip each element of spaces
75
        ### Split each line into a tuple, and strip each element of spaces
56
        result = self.split_lines(lines)
76
        result = self.split_lines(lines)
57
        result = [(re.compile(r), d) for r, d in result]
77
        result = [(re.compile(r), d) for r, d in result]
58
 
78
 
59
        ### Give some information about the dictionary we are using
79
        ### Give some information about the dictionary we are using
60
        self.add_to_print_queue(DICT_SUC, self.options.dict_file, len(result))
80
        print_dict_suc (self.options.dict_file, len(result))
61
 
81
 
62
        return tuple(result)
82
        return tuple(result)
63
 
83
 
64
    def split_lines(self, lines):
84
    def split_lines(self, lines):
65
 
85
 
Line 70... Line 90...
70
            try:
90
            try:
71
                r, d = l.split('=')
91
                r, d = l.split('=')
72
                r = r.strip()
92
                r = r.strip()
73
                d = d.strip()
93
                d = d.strip()
74
            except ValueError:
94
            except ValueError:
75
                self.add_to_print_queue(DICT_BAD_LINE, l)
95
                print_dict_bad_line (l)
76
                continue
96
                continue
77
 
97
 
78
            result.append((r, d))
98
            result.append((r, d))
79
 
99
 
80
        return result
100
        return result
Line 100... Line 120...
100
        ## Create the directory if it doesn't exist
120
        ## Create the directory if it doesn't exist
101
        if not os.path.isdir(todir):
121
        if not os.path.isdir(todir):
102
            try:
122
            try:
103
                if self.get_user_choice('Make directory?: %s' % (todir, )):
123
                if self.get_user_choice('Make directory?: %s' % (todir, )):
104
                    os.makedirs(todir)
124
                    os.makedirs(todir)
105
                    self.add_to_print_queue(DIR_CREATE_SUC, todir)
125
                    print_dir_create_suc (todir)
106
            except:
126
            except:
107
                self.add_to_print_queue(DIR_CREATE_FAIL, todir)
127
                print_dir_create_fail (todir)
108
 
128
 
109
        ## Try to move every file, one at a time
129
        ## Try to move every file, one at a time
110
        for f in files:
130
        for f in files:
111
            srcname = os.path.join(fromdir, f)
131
            srcname = os.path.join(fromdir, f)
112
            dstname = os.path.join(todir, f)
132
            dstname = os.path.join(todir, f)
113
 
133
 
114
            try:
134
            try:
115
                if self.get_user_choice('Move file?: %s --> %s' % (srcname, dstname)):
135
                if self.get_user_choice('Move file?: %s --> %s' % (srcname, dstname)):
116
                    shutil.move(srcname, dstname)
136
                    shutil.move(srcname, dstname)
117
                    self.add_to_print_queue(MOV_FILE_SUC, f, todir)
137
                    print_move_file_suc (f, todir)
118
            except:
138
            except:
119
                self.add_to_print_queue(MOV_FILE_FAIL, f, todir)
139
                print_move_file_fail (f, todir)
120
 
140
 
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
 
141
 
197
    def __dir_walker(self, dict, root, dirs, files):
142
    def __dir_walker(self, dict, root, dirs, files):
198
 
143
 
199
        ## Get all of the files in the directory that are of the correct types
144
        ## Get all of the files in the directory that are of the correct types
200
        types_re = re.compile(TYPES_REGEX, re.IGNORECASE)
145
        types_re = re.compile(TYPES_REGEX, re.IGNORECASE)
Line 227... Line 172...
227
 
172
 
228
            print 'Response not understood, try again.'
173
            print 'Response not understood, try again.'
229
 
174
 
230
    def main(self):
175
    def main(self):
231
 
176
 
232
        ## Start the print queue
-
 
233
        self.start_print_queue()
-
 
234
 
-
 
235
        ## Print the program's header
177
        ## Print the program's header
236
        self.add_to_print_queue(PROG_HDR)
178
        print_prog_header ()
237
 
179
 
238
        ## Parse the dictionary
180
        ## Parse the dictionary
239
        dict = self.parse_dict()
181
        dict = self.parse_dict()
240
 
182
 
241
        if self.options.recursive:
183
        if self.options.recursive:
Line 245... Line 187...
245
        else:
187
        else:
246
            self.__dir_walker(dict, self.options.start_dir,
188
            self.__dir_walker(dict, self.options.start_dir,
247
                    [d for d in os.listdir(self.options.start_dir) if os.path.isdir(d)],
189
                    [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)])
190
                    [f for f in os.listdir(self.options.start_dir) if os.path.isfile(f)])
249
 
191
 
250
        ## Stop the print queue
-
 
251
        self.stop_print_queue()
-
 
252
 
-
 
253
### MAIN IS HERE ###
192
### MAIN IS HERE ###
254
if __name__ == '__main__':
193
def main():
255
 
194
 
256
    ### Get the program options
195
    ### Get the program options
257
    parser = OptionParser()
196
    parser = OptionParser()
258
    parser.add_option('-q', '--quiet', action='store_false', dest='verbose',
197
    parser.add_option('-q', '--quiet', action='store_false', dest='verbose',
259
            default=True, help='Don\'t print status messages to stdout')
198
            default=True, help='Don\'t print status messages to stdout')
Line 277... Line 216...
277
    options.output_dir = os.path.abspath(os.path.expanduser(options.output_dir))
216
    options.output_dir = os.path.abspath(os.path.expanduser(options.output_dir))
278
 
217
 
279
    as = AnimeSorter2(options)
218
    as = AnimeSorter2(options)
280
    as.main()
219
    as.main()
281
 
220
 
-
 
221
if __name__ == '__main__':
-
 
222
    main ()
-
 
223
 
-
 
224
# vim: set ts=4 sw=4 sts=4 expandtab: