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 puts "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
128 rescue MessageFormatError, SourceError => e
129 Redwood::log "ignoring erroneous message at #{source}##{offset}: #{e.message}"
134 def save_index fn=File.join(@dir, "ferret")
135 # don't have to do anything, apparently
139 @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0
141 def contains? m; contains_id? m.id; end
142 def size; @index.size; end
144 ## you should probably not call this on a block that doesn't break
145 ## rather quickly because the results will probably be, as we say
146 ## in scotland, frikkin' huuuge.
147 EACH_BY_DATE_NUM = 100
148 def each_id_by_date opts={}
149 return if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
150 query = build_query opts
153 results = @index.search(query, :sort => "date DESC", :limit => EACH_BY_DATE_NUM, :offset => offset)
154 Redwood::log "got #{results.total_hits} results for query (offset #{offset}) #{query.inspect}"
155 results.hits.each { |hit| yield @index[hit.doc][:message_id], lambda { build_message hit.doc } }
156 break if offset >= results.total_hits - EACH_BY_DATE_NUM
157 offset += EACH_BY_DATE_NUM
161 def num_results_for opts={}
162 return 0 if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
164 index.search(q).total_hits
167 ## yield all messages in the thread containing 'm' by repeatedly
168 ## querying the index. yields pairs of message ids and
169 ## message-building lambdas, so that building an unwanted message
170 ## can be skipped in the block if desired.
171 SAME_SUBJECT_DATE_LIMIT = 7
172 def each_message_in_thread_for m, opts={}
177 ## temporarily disabling subject searching because it's a
178 ## significant slowdown.
180 ## TODO: make this configurable, i guess
182 date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
183 date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
185 q = Ferret::Search::BooleanQuery.new true
186 sq = Ferret::Search::PhraseQuery.new(:subject)
187 wrap_subj(Message.normalize_subj(m.subj)).split(/\s+/).each do |t|
190 q.add_query sq, :must
191 q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
192 q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
194 pending = @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] }
195 Redwood::log "found #{pending.size} results for subject query #{q}"
200 until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
202 next if searched.member? id
204 q = Ferret::Search::BooleanQuery.new true
205 q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
206 q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
209 @index.search_each(q, :limit => :all) do |docid, score|
210 break if opts[:limit] && messages.size >= opts[:limit]
211 mid = @index[docid][:message_id]
212 unless messages.member? mid
213 messages[mid] ||= lambda { build_message docid }
214 refs = @index[docid][:refs].split(" ")
219 Redwood::log "ran #{num_queries} queries to build thread of #{messages.size} messages for #{m.id}" if num_queries > 0
220 messages.each { |mid, builder| yield mid, builder }
223 ## builds a message object from a ferret result
224 def build_message docid
226 source = @sources[doc[:source_id].to_i]
227 #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
228 raise "invalid source #{doc[:source_id]}" unless source
231 "date" => Time.at(doc[:date].to_i),
232 "subject" => unwrap_subj(doc[:subject]),
233 "from" => doc[:from],
235 "message-id" => doc[:message_id],
236 "references" => doc[:refs],
239 Message.new :source => source, :source_info => doc[:source_info].to_i,
240 :labels => doc[:label].split(" ").map { |s| s.intern },
241 :snippet => doc[:snippet], :header => fake_header
244 def fresh_thread_id; @next_thread_id += 1; end
245 def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
246 def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
248 ## Adds a message to the index. The message cannot already exist in
251 raise ArgumentError, "index already contains #{m.id}" if contains? m
254 if m.source.is_a? Integer
257 m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
260 to = (m.to + m.cc + m.bcc).map { |x| x.email }.join(" ")
263 :source_id => source_id,
264 :source_info => m.source_info,
265 :date => m.date.to_indexable_s,
267 :snippet => m.snippet,
268 :label => m.labels.join(" "),
269 :from => m.from ? m.from.email : "",
270 :to => (m.to + m.cc + m.bcc).map { |x| x.email }.join(" "),
271 :subject => wrap_subj(Message.normalize_subj(m.subj)),
272 :refs => (m.refs + m.replytos).uniq.join(" "),
275 @index.add_document d
277 docid, entry = load_entry_for_id m.id
278 ## this hasn't been triggered in a long time. TODO: decide whether it's still a problem.
279 raise "just added message #{m.id} but couldn't find it in a search" unless docid
283 def drop_entry docno; @index.delete docno; end
285 def load_entry_for_id mid
286 results = @index.search(Ferret::Search::TermQuery.new(:message_id, mid))
287 return if results.total_hits == 0
288 docid = results.hits[0].doc
289 [docid, @index[docid]]
292 def load_contacts emails, h={}
293 q = Ferret::Search::BooleanQuery.new true
295 qq = Ferret::Search::BooleanQuery.new true
296 qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
297 qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
300 q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
302 Redwood::log "contact search: #{q}"
305 @index.search_each(q, :sort => "date DESC", :limit => :all) do |docid, score|
306 break if contacts.size >= num
307 #Redwood::log "got message with to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
308 f = @index[docid][:from]
309 t = @index[docid][:to]
311 if AccountManager.is_account_email? f
312 t.split(" ").each { |e| #Redwood::log "adding #{e} because there's a message to him from account email #{f}";
313 contacts[Person.for(e)] = true }
315 #Redwood::log "adding from #{f} because there's a message from him to #{t}"
316 contacts[Person.for(f)] = true
320 contacts.keys.compact
325 def parse_user_query_string str; @qparser.parse str; end
327 query = Ferret::Search::BooleanQuery.new
328 query.add_query opts[:qobj], :must if opts[:qobj]
329 labels = ([opts[:label]] + (opts[:labels] || [])).compact
330 labels.each { |t| query.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
331 if opts[:participants]
332 q2 = Ferret::Search::BooleanQuery.new
333 opts[:participants].each do |p|
334 q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
335 q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
337 query.add_query q2, :must
340 query.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless opts[:load_spam] || labels.include?(:spam)
341 query.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless opts[:load_deleted] || labels.include?(:deleted)
342 query.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not unless opts[:load_killed] || labels.include?(:killed)
346 def load_sources fn=Redwood::SOURCE_FN
347 @sources = Hash[*(Redwood::load_yaml_obj(fn) || []).map { |s| [s.id, s] }.flatten]
348 @sources_dirty = false
351 def save_sources fn=Redwood::SOURCE_FN
352 if @sources_dirty || @sources.any? { |id, s| s.dirty? }
356 FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(bakfn) > File.size(fn)
358 Redwood::save_yaml_obj @sources.values, fn
361 @sources_dirty = false