refactor: wordlist shouldn't use bot singleton #35
[rbot] / lib / rbot / core / utils / wordlist.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: rbot wordlist provider
5 #
6 # Author:: Raine Virta <rane@kapsi.fi>
7
8 require "find"
9
10 module ::Irc
11 class Bot
12 class Wordlist
13   def self.get(bot, where, options={})
14     wordlist_base = bot.path('wordlists')
15     opts = { :spaces => false }.merge(options)
16
17     wordlist_path = File.join(wordlist_base, where)
18     raise "wordlist not found: #{wordlist_path}" unless File.exist?(wordlist_path)
19
20     # Location is a directory -> combine all lists beneath it
21     wordlist = if File.directory?(wordlist_path)
22       wordlists = []
23       Find.find(wordlist_path) do |path|
24         next if path == wordlist_path
25         wordlists << path unless File.directory?(path)
26       end
27
28       wordlists.map { |list| File.readlines(list) }.flatten
29     else
30       File.readlines(wordlist_path)
31     end
32
33     # wordlists are assumed to be UTF-8, but we need to strip the BOM, if present
34     wordlist.map! { |l| l.sub("\xef\xbb\xbf",'').strip }
35     wordlist.reject do |word|
36       word =~ /\s/ && !opts[:spaces] ||
37       word.empty?
38     end
39   end
40
41   # Return an array with the list of available wordlists.
42   # Available options:
43   # pattern:: pattern that should be matched by the wordlist filename
44   def self.list(bot, options={})
45     wordlist_base = bot.path('wordlists')
46     pattern = options[:pattern] || "**"
47     # refuse patterns that contain ../
48     return [] if pattern =~ /\.\.\//
49     striplen = wordlist_base.length+1
50     Dir.glob(File.join(wordlist_base, pattern)).map { |name|
51       name[striplen..-1]
52     }
53   end
54
55   def self.exist?(bot, path)
56     wordlist_base = bot.path('wordlists')
57     fn = path.to_s
58     # refuse to check outside of the wordlist base directory
59     return false if fn =~ /\.\.\//
60     File.exist?(File.join(wordlist_base, fn))
61   end
62
63 end
64 end
65 end