5 class FerretIndex < BaseIndex
7 def initialize dir=BASE_DIR
10 @index_mutex = Monitor.new
11 wsa = Ferret::Analysis::WhiteSpaceAnalyzer.new false
12 sa = Ferret::Analysis::StandardAnalyzer.new [], true
13 @analyzer = Ferret::Analysis::PerFieldAnalyzer.new wsa
15 @analyzer[:subject] = sa
16 @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer, :or_default => false
19 def load_index dir=File.join(@dir, "ferret")
21 debug "loading index..."
22 @index_mutex.synchronize do
23 @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer, :id_field => 'message_id')
24 debug "loaded index of #{@index.size} messages"
27 debug "creating index..."
28 @index_mutex.synchronize do
29 field_infos = Ferret::Index::FieldInfos.new :store => :yes
30 field_infos.add_field :message_id, :index => :untokenized
31 field_infos.add_field :source_id
32 field_infos.add_field :source_info
33 field_infos.add_field :date, :index => :untokenized
34 field_infos.add_field :body
35 field_infos.add_field :label
36 field_infos.add_field :attachments
37 field_infos.add_field :subject
38 field_infos.add_field :from
39 field_infos.add_field :to
40 field_infos.add_field :refs
41 field_infos.add_field :snippet, :index => :no, :term_vector => :no
42 field_infos.create_index dir
43 @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer, :id_field => 'message_id')
48 def add_message m; sync_message m end
49 def update_message m; sync_message m end
50 def update_message_state m; sync_message m end
52 def sync_message m, opts={}
55 raise "no source info for message #{m.id}" unless m.source && m.source_info
57 source_id = if m.source.is_a? Integer
60 m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
63 snippet = if m.snippet_contains_encrypted_content? && $config[:discard_snippets_from_encrypted_messages]
69 ## write the new document to the index. if the entry already exists in the
70 ## index, reuse it (which avoids having to reload the entry from the source,
71 ## which can be quite expensive for e.g. large threads of IMAP actions.)
73 ## exception: if the index entry belongs to an earlier version of the
74 ## message, use everything from the new message instead, but union the
75 ## flags. this allows messages sent to mailing lists to have their header
76 ## updated and to have flags set properly.
78 ## minor hack: messages in sources with lower ids have priority over
79 ## messages in sources with higher ids. so messages in the inbox will
80 ## override everyone, and messages in the sent box will be overridden
83 ## written in this manner to support previous versions of the index which
84 ## did not keep around the entry body. upgrading is thus seamless.
86 labels = m.labels # override because this is the new state, unless...
88 ## if we are a later version of a message, ignore what's in the index,
89 ## but merge in the labels.
90 if entry[:source_id] && entry[:source_info] && entry[:label] &&
91 ((entry[:source_id].to_i > source_id) || (entry[:source_info].to_i < m.source_info))
92 labels += entry[:label].to_set_of_symbols
93 #debug "found updated version of message #{m.id}: #{m.subj}"
94 #debug "previous version was at #{entry[:source_id].inspect}:#{entry[:source_info].inspect}, this version at #{source_id.inspect}:#{m.source_info.inspect}"
95 #debug "merged labels are #{labels.inspect} (index #{entry[:label].inspect}, message #{m.labels.inspect})"
99 ## if force_overwite is true, ignore what's in the index. this is used
100 ## primarily by sup-sync to force index updates.
101 entry = {} if opts[:force_overwrite]
105 :source_id => source_id,
106 :source_info => m.source_info,
107 :date => (entry[:date] || m.date.to_indexable_s),
108 :body => (entry[:body] || m.indexable_content),
109 :snippet => snippet, # always override
110 :label => labels.to_a.join(" "),
111 :attachments => (entry[:attachments] || m.attachments.uniq.join(" ")),
113 ## always override :from and :to.
114 ## older versions of Sup would often store the wrong thing in the index
115 ## (because they were canonicalizing email addresses, resulting in the
116 ## wrong name associated with each.) the correct address is read from
117 ## the original header when these messages are opened in thread-view-mode,
118 ## so this allows people to forcibly update the address in the index by
119 ## marking those threads for saving.
120 :from => (m.from ? m.from.indexable_content : ""),
121 :to => (m.to + m.cc + m.bcc).map { |x| x.indexable_content }.join(" "),
123 :subject => (entry[:subject] || wrap_subj(Message.normalize_subj(m.subj))),
124 :refs => (entry[:refs] || (m.refs + m.replytos).uniq.join(" ")),
127 @index_mutex.synchronize do
129 @index.add_document d
132 private :sync_message
134 def save_index fn=File.join(@dir, "ferret")
135 # don't have to do anything, apparently
139 @index_mutex.synchronize { @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0 }
143 @index_mutex.synchronize { @index.size }
146 EACH_BY_DATE_NUM = 100
147 def each_id_by_date query={}
148 return if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
149 ferret_query = build_ferret_query query
152 limit = (query[:limit])? [EACH_BY_DATE_NUM, query[:limit] - offset].min : EACH_BY_DATE_NUM
153 results = @index_mutex.synchronize { @index.search ferret_query, :sort => "date DESC", :limit => limit, :offset => offset }
154 debug "got #{results.total_hits} results for query (offset #{offset}) #{ferret_query.inspect}"
155 results.hits.each do |hit|
156 yield @index_mutex.synchronize { @index[hit.doc][:message_id] }, lambda { build_message hit.doc }
158 break if query[:limit] and offset >= query[:limit] - limit
159 break if offset >= results.total_hits - limit
164 def num_results_for query={}
165 return 0 if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
166 ferret_query = build_ferret_query query
167 @index_mutex.synchronize { @index.search(ferret_query, :limit => 1).total_hits }
170 SAME_SUBJECT_DATE_LIMIT = 7
172 def each_message_in_thread_for m, opts={}
173 #debug "Building thread for #{m.id}: #{m.subj}"
179 if $config[:thread_by_subject] # do subject queries
180 date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
181 date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
183 q = Ferret::Search::BooleanQuery.new true
184 sq = Ferret::Search::PhraseQuery.new(:subject)
185 wrap_subj(Message.normalize_subj(m.subj)).split.each do |t|
188 q.add_query sq, :must
189 q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
191 q = build_ferret_query :qobj => q
193 p1 = @index_mutex.synchronize { @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] } }
194 debug "found #{p1.size} results for subject query #{q}"
196 p2 = @index_mutex.synchronize { @index.search(q.to_s, :limit => :all).hits.map { |hit| @index[hit.doc][:message_id] } }
197 debug "found #{p2.size} results in string form"
199 pending = (pending + p1 + p2).uniq
202 until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
203 q = Ferret::Search::BooleanQuery.new true
204 # this disappeared in newer ferrets... wtf.
205 # q.max_clause_count = 2048
207 lim = [MAX_CLAUSES / 2, pending.length].min
208 pending[0 ... lim].each do |id|
210 q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
211 q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
213 pending = pending[lim .. -1]
215 q = build_ferret_query :qobj => q
219 @index_mutex.synchronize do
220 @index.search_each(q, :limit => :all) do |docid, score|
221 break if opts[:limit] && messages.size >= opts[:limit]
222 if @index[docid][:label].split(/\s+/).include?("killed") && opts[:skip_killed]
226 mid = @index[docid][:message_id]
227 unless messages.member?(mid)
228 #debug "got #{mid} as a child of #{id}"
229 messages[mid] ||= lambda { build_message docid }
230 refs = @index[docid][:refs].split
231 pending += refs.select { |id| !searched[id] }
238 #debug "thread for #{m.id} is killed, ignoring"
241 #debug "ran #{num_queries} queries to build thread of #{messages.size} messages for #{m.id}: #{m.subj}" if num_queries > 0
242 messages.each { |mid, builder| yield mid, builder }
247 ## builds a message object from a ferret result
248 def build_message docid
249 @index_mutex.synchronize do
250 doc = @index[docid] or return
252 source = SourceManager[doc[:source_id].to_i]
253 raise "invalid source #{doc[:source_id]}" unless source
255 #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
258 "date" => Time.at(doc[:date].to_i),
259 "subject" => unwrap_subj(doc[:subject]),
260 "from" => doc[:from],
261 "to" => doc[:to].split.join(", "), # reformat
262 "message-id" => doc[:message_id],
263 "references" => doc[:refs].split.map { |x| "<#{x}>" }.join(" "),
266 m = Message.new :source => source, :source_info => doc[:source_info].to_i,
267 :labels => doc[:label].to_set_of_symbols,
268 :snippet => doc[:snippet]
269 m.parse_header fake_header
275 @index_mutex.synchronize { @index.delete id }
278 def load_contacts emails, h={}
279 q = Ferret::Search::BooleanQuery.new true
281 qq = Ferret::Search::BooleanQuery.new true
282 qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
283 qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
286 q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
288 debug "contact search: #{q}"
291 @index_mutex.synchronize do
292 @index.search_each q, :sort => "date DESC", :limit => :all do |docid, score|
293 break if contacts.size >= num
294 #debug "got message #{docid} to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
295 f = @index[docid][:from]
296 t = @index[docid][:to]
298 if AccountManager.is_account_email? f
299 t.split(" ").each { |e| contacts[Person.from_address(e)] = true }
301 contacts[Person.from_address(f)] = true
306 contacts.keys.compact
310 ferret_query = build_ferret_query query
311 results = @index_mutex.synchronize { @index.search ferret_query, :limit => (query[:limit] || :all) }
312 results.hits.map { |hit| yield @index[hit.doc][:message_id] }
316 @index_mutex.synchronize { @index.optimize }
322 entry[:source_id].to_i
325 class ParseError < StandardError; end
327 ## parse a query string from the user. returns a query object
328 ## that can be passed to any index method with a 'query'
329 ## argument, as well as build_ferret_query.
331 ## raises a ParseError if something went wrong.
335 subs = s.gsub(/\b(to|from):(\S+)\b/) do
337 if(p = ContactManager.contact_for(name))
340 [field, "(" + AccountManager.user_emails.join("||") + ")"]
346 ## if we see a label:deleted or a label:spam term anywhere in the query
347 ## string, we set the extra load_spam or load_deleted options to true.
348 ## bizarre? well, because the query allows arbitrary parenthesized boolean
349 ## expressions, without fully parsing the query, we can't tell whether
350 ## the user is explicitly directing us to search spam messages or not.
351 ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
352 ## search spam messages or not?
354 ## so, we rely on the fact that turning these extra options ON turns OFF
355 ## the adding of "-label:deleted" or "-label:spam" terms at the very
356 ## final stage of query processing. if the user wants to search spam
357 ## messages, not adding that is the right thing; if he doesn't want to
358 ## search spam messages, then not adding it won't have any effect.
359 query[:load_spam] = true if subs =~ /\blabel:spam\b/
360 query[:load_deleted] = true if subs =~ /\blabel:deleted\b/
362 ## gmail style "is" operator
363 subs = subs.gsub(/\b(is|has):(\S+)\b/) do
364 field, label = $1, $2
369 query[:load_spam] = true
372 query[:load_deleted] = true
379 ## gmail style attachments "filename" and "filetype" searches
380 subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
381 field, name = $1, ($3 || $4)
384 debug "filename: translated #{field}:#{name} to attachments:(#{name.downcase})"
385 "attachments:(#{name.downcase})"
387 debug "filetype: translated #{field}:#{name} to attachments:(*.#{name.downcase})"
388 "attachments:(*.#{name.downcase})"
393 subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
394 field, datestr = $1, ($3 || $4)
395 realdate = Chronic.parse datestr, :guess => false, :context => :past
399 debug "chronic: translated #{field}:#{datestr} to #{realdate.end}"
400 "date:(>= #{sprintf "%012d", realdate.end.to_i})"
402 debug "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
403 "date:(<= #{sprintf "%012d", realdate.begin.to_i})"
405 debug "chronic: translated #{field}:#{datestr} to #{realdate}"
406 "date:(<= #{sprintf "%012d", realdate.end.to_i}) date:(>= #{sprintf "%012d", realdate.begin.to_i})"
409 raise ParseError, "can't understand date #{datestr.inspect}"
414 ## limit:42 restrict the search to 42 results
415 subs = subs.gsub(/\blimit:(\S+)\b/) do
418 query[:limit] = lim.to_i
421 raise ParseError, "non-numeric limit #{lim.inspect}"
426 query[:qobj] = @qparser.parse(subs)
429 rescue Ferret::QueryParser::QueryParseException => e
430 raise ParseError, e.message
436 def build_ferret_query query
437 q = Ferret::Search::BooleanQuery.new
438 q.add_query Ferret::Search::MatchAllQuery.new, :must
439 q.add_query query[:qobj], :must if query[:qobj]
440 labels = ([query[:label]] + (query[:labels] || [])).compact
441 labels.each { |t| q.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
442 if query[:participants]
443 q2 = Ferret::Search::BooleanQuery.new
444 query[:participants].each do |p|
445 q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
446 q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
448 q.add_query q2, :must
451 q.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless query[:load_spam] || labels.include?(:spam)
452 q.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless query[:load_deleted] || labels.include?(:deleted)
453 q.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not if query[:skip_killed]
455 q.add_query Ferret::Search::TermQuery.new("source_id", query[:source_id]), :must if query[:source_id]
459 def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
460 def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end