1 ## the index structure for redwood. interacts with ferret.
6 #require_gem 'ferret', ">= 0.10.13"
14 def initialize dir=BASE_DIR
17 @sources_dirty = false
19 wsa = Ferret::Analysis::WhiteSpaceAnalyzer.new false
20 sa = Ferret::Analysis::StandardAnalyzer.new Ferret::Analysis::FULL_ENGLISH_STOP_WORDS, true
21 @analyzer = Ferret::Analysis::PerFieldAnalyzer.new wsa
23 @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer
25 self.class.i_am_the_instance self
34 FileUtils.mkdir_p @dir unless File.exists? @dir
40 raise "duplicate source!" if @sources.include? source
42 source.id ||= @sources.size
43 ##TODO: why was this necessary?
44 ##source.id += 1 while @sources.member? source.id
45 @sources[source.id] = source
48 def source_for uri; @sources.values.find { |s| s.is_source_for? uri }; end
49 def usual_sources; @sources.values.find_all { |s| s.usual? }; end
50 def sources; @sources.values; end
52 def load_index dir=File.join(@dir, "ferret")
54 Redwood::log "loading index..."
55 @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
56 Redwood::log "loaded index of #{@index.size} messages"
58 Redwood::log "creating index..."
59 field_infos = Ferret::Index::FieldInfos.new :store => :yes
60 field_infos.add_field :message_id
61 field_infos.add_field :source_id
62 field_infos.add_field :source_info
63 field_infos.add_field :date, :index => :untokenized
64 field_infos.add_field :body, :store => :no
65 field_infos.add_field :label
66 field_infos.add_field :subject
67 field_infos.add_field :from
68 field_infos.add_field :to
69 field_infos.add_field :refs
70 field_infos.add_field :snippet, :index => :no, :term_vector => :no
71 field_infos.create_index dir
72 @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
76 ## update the message by deleting and re-adding
77 def update_message m, source=nil, source_info=nil
78 docid, entry = load_entry_for_id m.id
80 source ||= entry[:source_id].to_i
81 source_info ||= entry[:source_info].to_i
84 ## this happens sometimes. i'm not sure why. ferret bug?
85 raise "no entry and no source info for message #{m.id}: source #{source.inspect}, info #{source_info.inspect}, entry #{entry.inspect}, query #{Ferret::Search::TermQuery.new(:message_id, m.id)}, results #{@index.search(Ferret::Search::TermQuery.new(:message_id, m.id)).inspect}" unless source && source_info
87 raise "deleting non-corresponding entry #{docid}" unless @index[docid][:message_id] == m.id
92 def save_index fn=File.join(@dir, "ferret")
93 # don't have to do anything apparently
97 @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0
99 def contains? m; contains_id? m.id; end
100 def size; @index.size; end
102 ## you should probably not call this on a block that doesn't break
103 ## rather quickly because the results will probably be, as we say
104 ## in scotland, frikkin' huuuge.
105 EACH_BY_DATE_NUM = 100
106 def each_id_by_date opts={}
107 return if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
108 query = build_query opts
111 results = @index.search(query, :sort => "date DESC", :limit => EACH_BY_DATE_NUM, :offset => offset)
112 Redwood::log "got #{results.total_hits} results for query (offset #{offset}) #{query.inspect}"
113 results.hits.each { |hit| yield @index[hit.doc][:message_id], lambda { build_message hit.doc } }
114 break if offset >= results.total_hits - EACH_BY_DATE_NUM
115 offset += EACH_BY_DATE_NUM
119 def num_results_for opts={}
120 return 0 if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
122 index.search(q).total_hits
125 ## yield all messages in the thread containing 'm' by repeatedly
126 ## querying the index. yields pairs of message ids and
127 ## message-building lambdas, so that building an unwanted message
128 ## can be skipped in the block if desired.
129 SAME_SUBJECT_DATE_LIMIT = 7
130 def each_message_in_thread_for m, opts={}
135 ## temporarily disabling subject searching because it's a
136 ## significant slowdown.
138 ## TODO: make this configurable, i guess
140 date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
141 date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
143 q = Ferret::Search::BooleanQuery.new true
144 sq = Ferret::Search::PhraseQuery.new(:subject)
145 wrap_subj(Message.normalize_subj(m.subj)).split(/\s+/).each do |t|
148 q.add_query sq, :must
149 q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
150 q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
152 pending = @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] }
153 Redwood::log "found #{pending.size} results for subject query #{q}"
158 until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
160 next if searched.member? id
162 q = Ferret::Search::BooleanQuery.new true
163 q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
164 q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
167 @index.search_each(q, :limit => :all) do |docid, score|
168 break if opts[:limit] && messages.size >= opts[:limit]
169 mid = @index[docid][:message_id]
170 unless messages.member? mid
171 messages[mid] ||= lambda { build_message docid }
172 refs = @index[docid][:refs].split(" ")
177 Redwood::log "ran #{num_queries} queries to build thread of #{messages.size} messages for #{m.id}" if num_queries > 0
178 messages.each { |mid, builder| yield mid, builder }
181 ## builds a message object from a ferret result
182 def build_message docid
184 source = @sources[doc[:source_id].to_i]
185 #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
186 raise "invalid source #{doc[:source_id]}" unless source
189 "date" => Time.at(doc[:date].to_i),
190 "subject" => unwrap_subj(doc[:subject]),
191 "from" => doc[:from],
193 "message-id" => doc[:message_id],
194 "references" => doc[:refs],
197 Message.new :source => source, :source_info => doc[:source_info].to_i,
198 :labels => doc[:label].split(" ").map { |s| s.intern },
199 :snippet => doc[:snippet], :header => fake_header
202 def fresh_thread_id; @next_thread_id += 1; end
203 def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
204 def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
207 return false if contains? m
210 if m.source.is_a? Integer
213 m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
216 to = (m.to + m.cc + m.bcc).map { |x| x.email }.join(" ")
219 :source_id => source_id,
220 :source_info => m.source_info,
221 :date => m.date.to_indexable_s,
223 :snippet => m.snippet,
224 :label => m.labels.join(" "),
225 :from => m.from ? m.from.email : "",
226 :to => (m.to + m.cc + m.bcc).map { |x| x.email }.join(" "),
227 :subject => wrap_subj(Message.normalize_subj(m.subj)),
228 :refs => (m.refs + m.replytos).uniq.join(" "),
231 @index.add_document d
233 ## TODO: figure out why this is sometimes triggered
234 docid, entry = load_entry_for_id m.id
235 raise "just added message #{m.id} but couldn't find it in a search" unless docid
239 def drop_entry docno; @index.delete docno; end
241 def load_entry_for_id mid
242 results = @index.search(Ferret::Search::TermQuery.new(:message_id, mid))
243 return if results.total_hits == 0
244 docid = results.hits[0].doc
245 [docid, @index[docid]]
248 def load_contacts emails, h={}
249 q = Ferret::Search::BooleanQuery.new true
251 qq = Ferret::Search::BooleanQuery.new true
252 qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
253 qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
256 q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
258 Redwood::log "contact search: #{q}"
261 @index.search_each(q, :sort => "date DESC", :limit => :all) do |docid, score|
262 break if contacts.size >= num
263 #Redwood::log "got message with to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
264 f = @index[docid][:from]
265 t = @index[docid][:to]
267 if AccountManager.is_account_email? f
268 t.split(" ").each { |e| #Redwood::log "adding #{e} because there's a message to him from account email #{f}";
269 contacts[Person.for(e)] = true }
271 #Redwood::log "adding from #{f} because there's a message from him to #{t}"
272 contacts[Person.for(f)] = true
276 contacts.keys.compact
281 def parse_user_query_string str; @qparser.parse str; end
283 query = Ferret::Search::BooleanQuery.new
284 query.add_query opts[:qobj], :must if opts[:qobj]
285 labels = ([opts[:label]] + (opts[:labels] || [])).compact
286 labels.each { |t| query.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
287 if opts[:participants]
288 q2 = Ferret::Search::BooleanQuery.new
289 opts[:participants].each do |p|
290 q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
291 q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
293 query.add_query q2, :must
296 query.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless opts[:load_spam] || labels.include?(:spam)
297 query.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless opts[:load_deleted] || labels.include?(:deleted)
298 query.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not unless opts[:load_killed] || labels.include?(:killed)
302 def load_sources fn=Redwood::SOURCE_FN
303 @sources = Hash[*(Redwood::load_yaml_obj(fn) || []).map { |s| [s.id, s] }.flatten]
304 @sources_dirty = false
307 def save_sources fn=Redwood::SOURCE_FN
308 if @sources_dirty || @sources.any? { |id, s| s.dirty? }
312 FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(bakfn) > File.size(fn)
314 Redwood::save_yaml_obj @sources.values, fn
317 @sources_dirty = false