5 class FerretIndex < BaseIndex
7 HookManager.register "custom-search", <<EOS
8 Executes before a string search is applied to the index,
9 returning a new search string.
11 subs: The string being searched.
14 def initialize dir=BASE_DIR
17 @index_mutex = Monitor.new
18 wsa = Ferret::Analysis::WhiteSpaceAnalyzer.new false
19 sa = Ferret::Analysis::StandardAnalyzer.new [], true
20 @analyzer = Ferret::Analysis::PerFieldAnalyzer.new wsa
22 @analyzer[:subject] = sa
23 @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer, :or_default => false
26 def load_index dir=File.join(@dir, "ferret")
28 debug "loading index..."
29 @index_mutex.synchronize do
30 @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer, :id_field => 'message_id')
31 debug "loaded index of #{@index.size} messages"
34 debug "creating index..."
35 @index_mutex.synchronize do
36 field_infos = Ferret::Index::FieldInfos.new :store => :yes
37 field_infos.add_field :message_id, :index => :untokenized
38 field_infos.add_field :source_id
39 field_infos.add_field :source_info
40 field_infos.add_field :date, :index => :untokenized
41 field_infos.add_field :body
42 field_infos.add_field :label
43 field_infos.add_field :attachments
44 field_infos.add_field :subject
45 field_infos.add_field :from
46 field_infos.add_field :to
47 field_infos.add_field :refs
48 field_infos.add_field :snippet, :index => :no, :term_vector => :no
49 field_infos.create_index dir
50 @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer, :id_field => 'message_id')
55 def add_message m; sync_message m end
56 def update_message m; sync_message m end
57 def update_message_state m; sync_message m end
59 def sync_message m, opts={}
62 raise "no source info for message #{m.id}" unless m.source && m.source_info
64 source_id = if m.source.is_a? Integer
67 m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
70 snippet = if m.snippet_contains_encrypted_content? && $config[:discard_snippets_from_encrypted_messages]
76 ## write the new document to the index. if the entry already exists in the
77 ## index, reuse it (which avoids having to reload the entry from the source,
78 ## which can be quite expensive for e.g. large threads of IMAP actions.)
80 ## exception: if the index entry belongs to an earlier version of the
81 ## message, use everything from the new message instead, but union the
82 ## flags. this allows messages sent to mailing lists to have their header
83 ## updated and to have flags set properly.
85 ## minor hack: messages in sources with lower ids have priority over
86 ## messages in sources with higher ids. so messages in the inbox will
87 ## override everyone, and messages in the sent box will be overridden
90 ## written in this manner to support previous versions of the index which
91 ## did not keep around the entry body. upgrading is thus seamless.
93 labels = m.labels # override because this is the new state, unless...
95 ## if we are a later version of a message, ignore what's in the index,
96 ## but merge in the labels.
97 if entry[:source_id] && entry[:source_info] && entry[:label] &&
98 ((entry[:source_id].to_i > source_id) || (entry[:source_info].to_i < m.source_info))
99 labels += entry[:label].to_set_of_symbols
100 #debug "found updated version of message #{m.id}: #{m.subj}"
101 #debug "previous version was at #{entry[:source_id].inspect}:#{entry[:source_info].inspect}, this version at #{source_id.inspect}:#{m.source_info.inspect}"
102 #debug "merged labels are #{labels.inspect} (index #{entry[:label].inspect}, message #{m.labels.inspect})"
106 ## if force_overwite is true, ignore what's in the index. this is used
107 ## primarily by sup-sync to force index updates.
108 entry = {} if opts[:force_overwrite]
112 :source_id => source_id,
113 :source_info => m.source_info,
114 :date => (entry[:date] || m.date.to_indexable_s),
115 :body => (entry[:body] || m.indexable_content),
116 :snippet => snippet, # always override
117 :label => labels.to_a.join(" "),
118 :attachments => (entry[:attachments] || m.attachments.uniq.join(" ")),
120 ## always override :from and :to.
121 ## older versions of Sup would often store the wrong thing in the index
122 ## (because they were canonicalizing email addresses, resulting in the
123 ## wrong name associated with each.) the correct address is read from
124 ## the original header when these messages are opened in thread-view-mode,
125 ## so this allows people to forcibly update the address in the index by
126 ## marking those threads for saving.
127 :from => (m.from ? m.from.indexable_content : ""),
128 :to => (m.to + m.cc + m.bcc).map { |x| x.indexable_content }.join(" "),
130 :subject => (entry[:subject] || wrap_subj(Message.normalize_subj(m.subj))),
131 :refs => (entry[:refs] || (m.refs + m.replytos).uniq.join(" ")),
134 @index_mutex.synchronize do
136 @index.add_document d
139 private :sync_message
141 def save_index fn=File.join(@dir, "ferret")
142 # don't have to do anything, apparently
146 @index_mutex.synchronize { @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0 }
150 @index_mutex.synchronize { @index.size }
153 EACH_BY_DATE_NUM = 100
154 def each_id_by_date query={}
155 return if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
156 ferret_query = build_ferret_query query
159 limit = (query[:limit])? [EACH_BY_DATE_NUM, query[:limit] - offset].min : EACH_BY_DATE_NUM
160 results = @index_mutex.synchronize { @index.search ferret_query, :sort => "date DESC", :limit => limit, :offset => offset }
161 debug "got #{results.total_hits} results for query (offset #{offset}) #{ferret_query.inspect}"
162 results.hits.each do |hit|
163 yield @index_mutex.synchronize { @index[hit.doc][:message_id] }, lambda { build_message hit.doc }
165 break if query[:limit] and offset >= query[:limit] - limit
166 break if offset >= results.total_hits - limit
171 def num_results_for query={}
172 return 0 if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
173 ferret_query = build_ferret_query query
174 @index_mutex.synchronize { @index.search(ferret_query, :limit => 1).total_hits }
177 SAME_SUBJECT_DATE_LIMIT = 7
179 def each_message_in_thread_for m, opts={}
180 #debug "Building thread for #{m.id}: #{m.subj}"
186 if $config[:thread_by_subject] # do subject queries
187 date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
188 date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
190 q = Ferret::Search::BooleanQuery.new true
191 sq = Ferret::Search::PhraseQuery.new(:subject)
192 wrap_subj(Message.normalize_subj(m.subj)).split.each do |t|
195 q.add_query sq, :must
196 q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
198 q = build_ferret_query :qobj => q
200 p1 = @index_mutex.synchronize { @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] } }
201 debug "found #{p1.size} results for subject query #{q}"
203 p2 = @index_mutex.synchronize { @index.search(q.to_s, :limit => :all).hits.map { |hit| @index[hit.doc][:message_id] } }
204 debug "found #{p2.size} results in string form"
206 pending = (pending + p1 + p2).uniq
209 until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
210 q = Ferret::Search::BooleanQuery.new true
211 # this disappeared in newer ferrets... wtf.
212 # q.max_clause_count = 2048
214 lim = [MAX_CLAUSES / 2, pending.length].min
215 pending[0 ... lim].each do |id|
217 q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
218 q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
220 pending = pending[lim .. -1]
222 q = build_ferret_query :qobj => q
226 @index_mutex.synchronize do
227 @index.search_each(q, :limit => :all) do |docid, score|
228 break if opts[:limit] && messages.size >= opts[:limit]
229 if @index[docid][:label].split(/\s+/).include?("killed") && opts[:skip_killed]
233 mid = @index[docid][:message_id]
234 unless messages.member?(mid)
235 #debug "got #{mid} as a child of #{id}"
236 messages[mid] ||= lambda { build_message docid }
237 refs = @index[docid][:refs].split
238 pending += refs.select { |id| !searched[id] }
245 #debug "thread for #{m.id} is killed, ignoring"
248 #debug "ran #{num_queries} queries to build thread of #{messages.size} messages for #{m.id}: #{m.subj}" if num_queries > 0
249 messages.each { |mid, builder| yield mid, builder }
254 ## builds a message object from a ferret result
255 def build_message docid
256 @index_mutex.synchronize do
257 doc = @index[docid] or return
259 source = SourceManager[doc[:source_id].to_i]
260 raise "invalid source #{doc[:source_id]}" unless source
262 #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
265 "date" => Time.at(doc[:date].to_i),
266 "subject" => unwrap_subj(doc[:subject]),
267 "from" => doc[:from],
268 "to" => doc[:to].split.join(", "), # reformat
269 "message-id" => doc[:message_id],
270 "references" => doc[:refs].split.map { |x| "<#{x}>" }.join(" "),
273 m = Message.new :source => source, :source_info => doc[:source_info].to_i,
274 :labels => doc[:label].to_set_of_symbols,
275 :snippet => doc[:snippet]
276 m.parse_header fake_header
282 @index_mutex.synchronize { @index.delete id }
285 def load_contacts emails, h={}
286 q = Ferret::Search::BooleanQuery.new true
288 qq = Ferret::Search::BooleanQuery.new true
289 qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
290 qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
293 q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
295 debug "contact search: #{q}"
298 @index_mutex.synchronize do
299 @index.search_each q, :sort => "date DESC", :limit => :all do |docid, score|
300 break if contacts.size >= num
301 #debug "got message #{docid} to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
302 f = @index[docid][:from]
303 t = @index[docid][:to]
305 if AccountManager.is_account_email? f
306 t.split(" ").each { |e| contacts[Person.from_address(e)] = true }
308 contacts[Person.from_address(f)] = true
313 contacts.keys.compact
317 ferret_query = build_ferret_query query
318 results = @index_mutex.synchronize { @index.search ferret_query, :limit => (query[:limit] || :all) }
319 results.hits.map { |hit| yield @index[hit.doc][:message_id] }
323 @index_mutex.synchronize { @index.optimize }
329 entry[:source_id].to_i
332 class ParseError < StandardError; end
334 ## parse a query string from the user. returns a query object
335 ## that can be passed to any index method with a 'query'
336 ## argument, as well as build_ferret_query.
338 ## raises a ParseError if something went wrong.
342 subs = HookManager.run("custom-search", :subs => s) || s
343 subs = s.gsub(/\b(to|from):(\S+)\b/) do
345 if(p = ContactManager.contact_for(name))
348 [field, "(" + AccountManager.user_emails.join("||") + ")"]
354 ## if we see a label:deleted or a label:spam term anywhere in the query
355 ## string, we set the extra load_spam or load_deleted options to true.
356 ## bizarre? well, because the query allows arbitrary parenthesized boolean
357 ## expressions, without fully parsing the query, we can't tell whether
358 ## the user is explicitly directing us to search spam messages or not.
359 ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
360 ## search spam messages or not?
362 ## so, we rely on the fact that turning these extra options ON turns OFF
363 ## the adding of "-label:deleted" or "-label:spam" terms at the very
364 ## final stage of query processing. if the user wants to search spam
365 ## messages, not adding that is the right thing; if he doesn't want to
366 ## search spam messages, then not adding it won't have any effect.
367 query[:load_spam] = true if subs =~ /\blabel:spam\b/
368 query[:load_deleted] = true if subs =~ /\blabel:deleted\b/
370 ## gmail style "is" operator
371 subs = subs.gsub(/\b(is|has):(\S+)\b/) do
372 field, label = $1, $2
377 query[:load_spam] = true
380 query[:load_deleted] = true
387 ## gmail style attachments "filename" and "filetype" searches
388 subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
389 field, name = $1, ($3 || $4)
392 debug "filename: translated #{field}:#{name} to attachments:(#{name.downcase})"
393 "attachments:(#{name.downcase})"
395 debug "filetype: translated #{field}:#{name} to attachments:(*.#{name.downcase})"
396 "attachments:(*.#{name.downcase})"
401 subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
402 field, datestr = $1, ($3 || $4)
403 realdate = Chronic.parse datestr, :guess => false, :context => :past
407 debug "chronic: translated #{field}:#{datestr} to #{realdate.end}"
408 "date:(>= #{sprintf "%012d", realdate.end.to_i})"
410 debug "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
411 "date:(<= #{sprintf "%012d", realdate.begin.to_i})"
413 debug "chronic: translated #{field}:#{datestr} to #{realdate}"
414 "date:(<= #{sprintf "%012d", realdate.end.to_i}) date:(>= #{sprintf "%012d", realdate.begin.to_i})"
417 raise ParseError, "can't understand date #{datestr.inspect}"
422 ## limit:42 restrict the search to 42 results
423 subs = subs.gsub(/\blimit:(\S+)\b/) do
426 query[:limit] = lim.to_i
429 raise ParseError, "non-numeric limit #{lim.inspect}"
434 query[:qobj] = @qparser.parse(subs)
437 rescue Ferret::QueryParser::QueryParseException => e
438 raise ParseError, e.message
444 def build_ferret_query query
445 q = Ferret::Search::BooleanQuery.new
446 q.add_query Ferret::Search::MatchAllQuery.new, :must
447 q.add_query query[:qobj], :must if query[:qobj]
448 labels = ([query[:label]] + (query[:labels] || [])).compact
449 labels.each { |t| q.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
450 if query[:participants]
451 q2 = Ferret::Search::BooleanQuery.new
452 query[:participants].each do |p|
453 q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
454 q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
456 q.add_query q2, :must
459 q.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless query[:load_spam] || labels.include?(:spam)
460 q.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless query[:load_deleted] || labels.include?(:deleted)
461 q.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not if query[:skip_killed]
463 q.add_query Ferret::Search::TermQuery.new("source_id", query[:source_id]), :must if query[:source_id]
467 def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
468 def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end