1 ## the index structure for redwood. interacts with ferret.
13 def initialize dir=BASE_DIR
16 @sources_dirty = false
18 wsa = Ferret::Analysis::WhiteSpaceAnalyzer.new false
19 sa = Ferret::Analysis::StandardAnalyzer.new Ferret::Analysis::FULL_ENGLISH_STOP_WORDS, true
20 @analyzer = Ferret::Analysis::PerFieldAnalyzer.new wsa
22 @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer
24 self.class.i_am_the_instance self
33 FileUtils.mkdir_p @dir unless File.exists? @dir
39 raise "duplicate source!" if @sources.include? source
41 source.id ||= @sources.size
42 ##TODO: why was this necessary?
43 ##source.id += 1 while @sources.member? source.id
44 @sources[source.id] = source
47 def source_for uri; @sources.values.find { |s| s.is_source_for? uri }; end
48 def usual_sources; @sources.values.find_all { |s| s.usual? }; end
49 def sources; @sources.values; end
51 def load_index dir=File.join(@dir, "ferret")
53 Redwood::log "loading index..."
54 @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
55 Redwood::log "loaded index of #{@index.size} messages"
57 Redwood::log "creating index..."
58 field_infos = Ferret::Index::FieldInfos.new :store => :yes
59 field_infos.add_field :message_id
60 field_infos.add_field :source_id
61 field_infos.add_field :source_info
62 field_infos.add_field :date, :index => :untokenized
63 field_infos.add_field :body, :store => :no
64 field_infos.add_field :label
65 field_infos.add_field :subject
66 field_infos.add_field :from
67 field_infos.add_field :to
68 field_infos.add_field :refs
69 field_infos.add_field :snippet, :index => :no, :term_vector => :no
70 field_infos.create_index dir
71 @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
75 ## Update the message state on disk, by deleting and re-adding it.
76 ## The message must exist in the index. docid and entry are found
78 def update_message m, docid=nil, entry=nil
80 docid, entry = load_entry_for_id m.id
81 raise ArgumentError, "cannot find #{m.id} in the index" unless entry
84 raise "no entry and no source info for message #{m.id}" unless m.source && m.source_info
86 raise "deleting non-corresponding entry #{docid}" unless @index[docid][:message_id] == m.id
92 ## for each new message form the source, yields a bunch of stuff,
93 ## gets the message back from the block, and adds it or updates it.
94 def add_new_messages_from source
96 return if source.done? || source.broken?
98 source.each do |offset, labels|
100 Redwood::log "error loading messages from #{source}: #{source.broken_msg}"
104 labels.each { |l| LabelManager << l }
107 m = Message.new :source => source, :source_info => offset, :labels => labels
109 Redwood::log "skipping duplicate message #{m.id}"
115 if m.source_marked_read?
116 m.remove_label :unread
117 labels.delete :unread
120 docid, entry = load_entry_for_id m.id
121 m = yield m, offset, labels, entry
124 update_message m, docid, entry
127 UpdateManager.relay :add, m
129 rescue MessageFormatError, SourceError => e
130 Redwood::log "ignoring erroneous message at #{source}##{offset}: #{e.message}"
135 def save_index fn=File.join(@dir, "ferret")
136 # don't have to do anything, apparently
140 @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0
142 def contains? m; contains_id? m.id; end
143 def size; @index.size; end
145 ## you should probably not call this on a block that doesn't break
146 ## rather quickly because the results will probably be, as we say
147 ## in scotland, frikkin' huuuge.
148 EACH_BY_DATE_NUM = 100
149 def each_id_by_date opts={}
150 return if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
151 query = build_query opts
154 results = @index.search(query, :sort => "date DESC", :limit => EACH_BY_DATE_NUM, :offset => offset)
155 Redwood::log "got #{results.total_hits} results for query (offset #{offset}) #{query.inspect}"
156 results.hits.each { |hit| yield @index[hit.doc][:message_id], lambda { build_message hit.doc } }
157 break if offset >= results.total_hits - EACH_BY_DATE_NUM
158 offset += EACH_BY_DATE_NUM
162 def num_results_for opts={}
163 return 0 if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
165 index.search(q).total_hits
168 ## yield all messages in the thread containing 'm' by repeatedly
169 ## querying the index. yields pairs of message ids and
170 ## message-building lambdas, so that building an unwanted message
171 ## can be skipped in the block if desired.
172 SAME_SUBJECT_DATE_LIMIT = 7
173 def each_message_in_thread_for m, opts={}
178 ## temporarily disabling subject searching because it's a
179 ## significant slowdown.
181 ## TODO: make this configurable, i guess
183 date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
184 date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
186 q = Ferret::Search::BooleanQuery.new true
187 sq = Ferret::Search::PhraseQuery.new(:subject)
188 wrap_subj(Message.normalize_subj(m.subj)).split(/\s+/).each do |t|
191 q.add_query sq, :must
192 q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
193 q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
195 pending = @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] }
196 Redwood::log "found #{pending.size} results for subject query #{q}"
201 until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
203 next if searched.member? id
205 q = Ferret::Search::BooleanQuery.new true
206 q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
207 q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
210 @index.search_each(q, :limit => :all) do |docid, score|
211 break if opts[:limit] && messages.size >= opts[:limit]
212 mid = @index[docid][:message_id]
213 unless messages.member? mid
214 messages[mid] ||= lambda { build_message docid }
215 refs = @index[docid][:refs].split(" ")
220 Redwood::log "ran #{num_queries} queries to build thread of #{messages.size} messages for #{m.id}" if num_queries > 0
221 messages.each { |mid, builder| yield mid, builder }
224 ## builds a message object from a ferret result
225 def build_message docid
227 source = @sources[doc[:source_id].to_i]
228 #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
229 raise "invalid source #{doc[:source_id]}" unless source
232 "date" => Time.at(doc[:date].to_i),
233 "subject" => unwrap_subj(doc[:subject]),
234 "from" => doc[:from],
236 "message-id" => doc[:message_id],
237 "references" => doc[:refs],
240 Message.new :source => source, :source_info => doc[:source_info].to_i,
241 :labels => doc[:label].split(" ").map { |s| s.intern },
242 :snippet => doc[:snippet], :header => fake_header
245 def fresh_thread_id; @next_thread_id += 1; end
246 def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
247 def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
249 ## Adds a message to the index. The message cannot already exist in
252 raise ArgumentError, "index already contains #{m.id}" if contains? m
255 if m.source.is_a? Integer
258 m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
261 to = (m.to + m.cc + m.bcc).map { |x| x.email }.join(" ")
264 :source_id => source_id,
265 :source_info => m.source_info,
266 :date => m.date.to_indexable_s,
268 :snippet => m.snippet,
269 :label => m.labels.join(" "),
270 :from => m.from ? m.from.email : "",
271 :to => (m.to + m.cc + m.bcc).map { |x| x.email }.join(" "),
272 :subject => wrap_subj(Message.normalize_subj(m.subj)),
273 :refs => (m.refs + m.replytos).uniq.join(" "),
276 @index.add_document d
278 docid, entry = load_entry_for_id m.id
279 ## this hasn't been triggered in a long time. TODO: decide whether it's still a problem.
280 raise "just added message #{m.id} but couldn't find it in a search" unless docid
284 def drop_entry docno; @index.delete docno; end
286 def load_entry_for_id mid
287 results = @index.search(Ferret::Search::TermQuery.new(:message_id, mid))
288 return if results.total_hits == 0
289 docid = results.hits[0].doc
290 [docid, @index[docid]]
293 def load_contacts emails, h={}
294 q = Ferret::Search::BooleanQuery.new true
296 qq = Ferret::Search::BooleanQuery.new true
297 qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
298 qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
301 q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
303 Redwood::log "contact search: #{q}"
306 @index.search_each(q, :sort => "date DESC", :limit => :all) do |docid, score|
307 break if contacts.size >= num
308 #Redwood::log "got message with to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
309 f = @index[docid][:from]
310 t = @index[docid][:to]
312 if AccountManager.is_account_email? f
313 t.split(" ").each { |e| #Redwood::log "adding #{e} because there's a message to him from account email #{f}";
314 contacts[Person.for(e)] = true }
316 #Redwood::log "adding from #{f} because there's a message from him to #{t}"
317 contacts[Person.for(f)] = true
321 contacts.keys.compact
326 def parse_user_query_string str; @qparser.parse str; end
328 query = Ferret::Search::BooleanQuery.new
329 query.add_query opts[:qobj], :must if opts[:qobj]
330 labels = ([opts[:label]] + (opts[:labels] || [])).compact
331 labels.each { |t| query.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
332 if opts[:participants]
333 q2 = Ferret::Search::BooleanQuery.new
334 opts[:participants].each do |p|
335 q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
336 q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
338 query.add_query q2, :must
341 query.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless opts[:load_spam] || labels.include?(:spam)
342 query.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless opts[:load_deleted] || labels.include?(:deleted)
343 query.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not unless opts[:load_killed] || labels.include?(:killed)
347 def load_sources fn=Redwood::SOURCE_FN
348 @sources = Hash[*(Redwood::load_yaml_obj(fn) || []).map { |s| [s.id, s] }.flatten]
349 @sources_dirty = false
352 def save_sources fn=Redwood::SOURCE_FN
353 if @sources_dirty || @sources.any? { |id, s| s.dirty? }
357 FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(bakfn) > File.size(fn)
359 Redwood::save_yaml_obj @sources.values, fn
362 @sources_dirty = false