Add support for classification of non-fiction books.
[quanlib.git] / walkdir.rb
1 # Walk the directory (and subdirectories), identifying books.
2 #
3 # Expected format:
4 #   .../AuthorName/Title_of_the_Awesome_Book.ext
5 #
6 # Author is given as FirstLast.  For example, 
7 # Robert Anson Heinlein is RoberHeinlein, and 
8 # JKRowling is JoanneRowling.
9 #
10 # Book titles have spaces replaced with underscores,
11 # and punctuation [,!?'] replaced with hyphens.
12 #
13 # If the book forms part of a series, then an all-capitals 
14 # series designator, followed by a numeric volume number, 
15 # followed by an underscore, is prefixed to the name.
16 # For example, Hardy Boys' volume 1, The Tower Treasure, 
17 # is rendered as .../FranklinDixon/HB001_The_Tower_Treasure.epub
18 # and Mrs. Pollifax volume 6, On the China Station, is
19 # .../DorothyGilman/P06_On_the_China_Station.epub.
20
21 require 'book'
22 require 'store'
23
24 class WalkDir
25   def initialize(store, root)
26     @root = root
27     @store = store
28     @files = walk(@root)
29   end
30
31   def books
32     result = []
33     for file in @files.sort
34       if Book.can_handle?(file) && (!is_duplicate?(file))
35         book = Book.new(@store)
36         book.load_from_file!(file)
37         id = @store.store_book(book)
38         result.push(id)
39       end
40     end
41     return result
42   end
43
44   # Duplicate versions of a text are named 
45   #   xxx_suffix.ext
46   # Where suffix is one of bis, ter, quater, quinquies
47   # for the 2nd, 3rd, 4th or 5th variant respectively.
48   def is_duplicate?(file)
49     s = file.to_s
50     suffix = ['_bis.', '_ter.', '_quater.', '_quinquies.']
51     suffix.each do |pat|
52       if s.include?(pat)
53         return true
54       end
55     end
56     
57     return false
58   end
59
60   def walk(path)
61     result = []
62     children = Dir.entries(path)
63     for child in children
64       fullName = (path.chomp("/")) + "/" + child
65       if (File.directory?(fullName)) and (child != ".") and (child != "..") and (!File.symlink?(fullName))
66         sub = walk(fullName)
67         if (sub != nil) and (sub.length > 0)
68           result.concat(sub)
69         end
70       elsif (! File.directory?(fullName))
71         result.push(fullName)
72       end
73     end
74     #puts result
75     return result
76   end
77 end