]> git.cworth.org Git - sup/blob - lib/sup/ferret_index.rb
Merge branch 'master' into next
[sup] / lib / sup / ferret_index.rb
1 require 'ferret'
2
3 module Redwood
4
5 class FerretIndex < BaseIndex
6
7   HookManager.register "custom-search", <<EOS
8 Executes before a string search is applied to the index,
9 returning a new search string.
10 Variables:
11   subs: The string being searched. Be careful about shadowing:
12     this variable is actually a method, so use a temporary variable
13     or explicitly call self.subs; the substitutions in index.rb
14     don't actually work.
15 EOS
16
17   def initialize dir=BASE_DIR
18     super
19
20     @index_mutex = Monitor.new
21     wsa = Ferret::Analysis::WhiteSpaceAnalyzer.new false
22     sa = Ferret::Analysis::StandardAnalyzer.new [], true
23     @analyzer = Ferret::Analysis::PerFieldAnalyzer.new wsa
24     @analyzer[:body] = sa
25     @analyzer[:subject] = sa
26     @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer, :or_default => false
27   end
28
29   def load_index dir=File.join(@dir, "ferret")
30     if File.exists? dir
31       debug "loading index..."
32       @index_mutex.synchronize do
33         @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer, :id_field => 'message_id')
34         debug "loaded index of #{@index.size} messages"
35       end
36     else
37       debug "creating index..."
38       @index_mutex.synchronize do
39         field_infos = Ferret::Index::FieldInfos.new :store => :yes
40         field_infos.add_field :message_id, :index => :untokenized
41         field_infos.add_field :source_id
42         field_infos.add_field :source_info
43         field_infos.add_field :date, :index => :untokenized
44         field_infos.add_field :body
45         field_infos.add_field :label
46         field_infos.add_field :attachments
47         field_infos.add_field :subject
48         field_infos.add_field :from
49         field_infos.add_field :to
50         field_infos.add_field :refs
51         field_infos.add_field :snippet, :index => :no, :term_vector => :no
52         field_infos.create_index dir
53         @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer, :id_field => 'message_id')
54       end
55     end
56   end
57
58   def add_message m; sync_message m end
59   def update_message m; sync_message m end
60   def update_message_state m; sync_message m end
61
62   def sync_message m, opts={}
63     entry = @index[m.id]
64
65     raise "no source info for message #{m.id}" unless m.source && m.source_info
66
67     source_id = if m.source.is_a? Integer
68       m.source
69     else
70       m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
71     end
72
73     snippet = if m.snippet_contains_encrypted_content? && $config[:discard_snippets_from_encrypted_messages]
74       ""
75     else
76       m.snippet
77     end
78
79     ## write the new document to the index. if the entry already exists in the
80     ## index, reuse it (which avoids having to reload the entry from the source,
81     ## which can be quite expensive for e.g. large threads of IMAP actions.)
82     ##
83     ## exception: if the index entry belongs to an earlier version of the
84     ## message, use everything from the new message instead, but union the
85     ## flags. this allows messages sent to mailing lists to have their header
86     ## updated and to have flags set properly.
87     ##
88     ## minor hack: messages in sources with lower ids have priority over
89     ## messages in sources with higher ids. so messages in the inbox will
90     ## override everyone, and messages in the sent box will be overridden
91     ## by everyone else.
92     ##
93     ## written in this manner to support previous versions of the index which
94     ## did not keep around the entry body. upgrading is thus seamless.
95     entry ||= {}
96     labels = m.labels # override because this is the new state, unless...
97
98     ## if we are a later version of a message, ignore what's in the index,
99     ## but merge in the labels.
100     if entry[:source_id] && entry[:source_info] && entry[:label] &&
101       ((entry[:source_id].to_i > source_id) || (entry[:source_info].to_i < m.source_info))
102       labels += entry[:label].to_set_of_symbols
103       #debug "found updated version of message #{m.id}: #{m.subj}"
104       #debug "previous version was at #{entry[:source_id].inspect}:#{entry[:source_info].inspect}, this version at #{source_id.inspect}:#{m.source_info.inspect}"
105       #debug "merged labels are #{labels.inspect} (index #{entry[:label].inspect}, message #{m.labels.inspect})"
106       entry = {}
107     end
108
109     ## if force_overwite is true, ignore what's in the index. this is used
110     ## primarily by sup-sync to force index updates.
111     entry = {} if opts[:force_overwrite]
112
113     d = {
114       :message_id => m.id,
115       :source_id => source_id,
116       :source_info => m.source_info,
117       :date => (entry[:date] || m.date.to_indexable_s),
118       :body => (entry[:body] || m.indexable_content),
119       :snippet => snippet, # always override
120       :label => labels.to_a.join(" "),
121       :attachments => (entry[:attachments] || m.attachments.uniq.join(" ")),
122
123       ## always override :from and :to.
124       ## older versions of Sup would often store the wrong thing in the index
125       ## (because they were canonicalizing email addresses, resulting in the
126       ## wrong name associated with each.) the correct address is read from
127       ## the original header when these messages are opened in thread-view-mode,
128       ## so this allows people to forcibly update the address in the index by
129       ## marking those threads for saving.
130       :from => (m.from ? m.from.indexable_content : ""),
131       :to => (m.to + m.cc + m.bcc).map { |x| x.indexable_content }.join(" "),
132
133       :subject => (entry[:subject] || wrap_subj(Message.normalize_subj(m.subj))),
134       :refs => (entry[:refs] || (m.refs + m.replytos).uniq.join(" ")),
135     }
136
137     @index_mutex.synchronize do
138       @index.delete m.id
139       @index.add_document d
140     end
141   end
142   private :sync_message
143
144   def save_index fn=File.join(@dir, "ferret")
145     # don't have to do anything, apparently
146   end
147
148   def contains_id? id
149     @index_mutex.synchronize { @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0 }
150   end
151
152   def size
153     @index_mutex.synchronize { @index.size }
154   end
155
156   EACH_BY_DATE_NUM = 100
157   def each_id_by_date query={}
158     return if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
159     ferret_query = build_ferret_query query
160     offset = 0
161     while true
162       limit = (query[:limit])? [EACH_BY_DATE_NUM, query[:limit] - offset].min : EACH_BY_DATE_NUM
163       results = @index_mutex.synchronize { @index.search ferret_query, :sort => "date DESC", :limit => limit, :offset => offset }
164       debug "got #{results.total_hits} results for query (offset #{offset}) #{ferret_query.inspect}"
165       results.hits.each do |hit|
166         yield @index_mutex.synchronize { @index[hit.doc][:message_id] }, lambda { build_message hit.doc }
167       end
168       break if query[:limit] and offset >= query[:limit] - limit
169       break if offset >= results.total_hits - limit
170       offset += limit
171     end
172   end
173
174   def num_results_for query={}
175     return 0 if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
176     ferret_query = build_ferret_query query
177     @index_mutex.synchronize { @index.search(ferret_query, :limit => 1).total_hits }
178   end
179
180   SAME_SUBJECT_DATE_LIMIT = 7
181   MAX_CLAUSES = 1000
182   def each_message_in_thread_for m, opts={}
183     #debug "Building thread for #{m.id}: #{m.subj}"
184     messages = {}
185     searched = {}
186     num_queries = 0
187
188     pending = [m.id]
189     if $config[:thread_by_subject] # do subject queries
190       date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
191       date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
192
193       q = Ferret::Search::BooleanQuery.new true
194       sq = Ferret::Search::PhraseQuery.new(:subject)
195       wrap_subj(Message.normalize_subj(m.subj)).split.each do |t|
196         sq.add_term t
197       end
198       q.add_query sq, :must
199       q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
200
201       q = build_ferret_query :qobj => q
202
203       p1 = @index_mutex.synchronize { @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] } }
204       debug "found #{p1.size} results for subject query #{q}"
205
206       p2 = @index_mutex.synchronize { @index.search(q.to_s, :limit => :all).hits.map { |hit| @index[hit.doc][:message_id] } }
207       debug "found #{p2.size} results in string form"
208
209       pending = (pending + p1 + p2).uniq
210     end
211
212     until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
213       q = Ferret::Search::BooleanQuery.new true
214       # this disappeared in newer ferrets... wtf.
215       # q.max_clause_count = 2048
216
217       lim = [MAX_CLAUSES / 2, pending.length].min
218       pending[0 ... lim].each do |id|
219         searched[id] = true
220         q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
221         q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
222       end
223       pending = pending[lim .. -1]
224
225       q = build_ferret_query :qobj => q
226
227       num_queries += 1
228       killed = false
229       @index_mutex.synchronize do
230         @index.search_each(q, :limit => :all) do |docid, score|
231           break if opts[:limit] && messages.size >= opts[:limit]
232           if @index[docid][:label].split(/\s+/).include?("killed") && opts[:skip_killed]
233             killed = true
234             break
235           end
236           mid = @index[docid][:message_id]
237           unless messages.member?(mid)
238             #debug "got #{mid} as a child of #{id}"
239             messages[mid] ||= lambda { build_message docid }
240             refs = @index[docid][:refs].split
241             pending += refs.select { |id| !searched[id] }
242           end
243         end
244       end
245     end
246
247     if killed
248       #debug "thread for #{m.id} is killed, ignoring"
249       false
250     else
251       #debug "ran #{num_queries} queries to build thread of #{messages.size} messages for #{m.id}: #{m.subj}" if num_queries > 0
252       messages.each { |mid, builder| yield mid, builder }
253       true
254     end
255   end
256
257   ## builds a message object from a ferret result
258   def build_message docid
259     @index_mutex.synchronize do
260       doc = @index[docid] or return
261
262       source = SourceManager[doc[:source_id].to_i]
263       raise "invalid source #{doc[:source_id]}" unless source
264
265       #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
266
267       fake_header = {
268         "date" => Time.at(doc[:date].to_i),
269         "subject" => unwrap_subj(doc[:subject]),
270         "from" => doc[:from],
271         "to" => doc[:to].split.join(", "), # reformat
272         "message-id" => doc[:message_id],
273         "references" => doc[:refs].split.map { |x| "<#{x}>" }.join(" "),
274       }
275
276       m = Message.new :source => source, :source_info => doc[:source_info].to_i,
277                   :labels => doc[:label].to_set_of_symbols,
278                   :snippet => doc[:snippet]
279       m.parse_header fake_header
280       m
281     end
282   end
283
284   def delete id
285     @index_mutex.synchronize { @index.delete id }
286   end
287
288   def load_contacts emails, h={}
289     q = Ferret::Search::BooleanQuery.new true
290     emails.each do |e|
291       qq = Ferret::Search::BooleanQuery.new true
292       qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
293       qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
294       q.add_query qq
295     end
296     q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
297
298     debug "contact search: #{q}"
299     contacts = {}
300     num = h[:num] || 20
301     @index_mutex.synchronize do
302       @index.search_each q, :sort => "date DESC", :limit => :all do |docid, score|
303         break if contacts.size >= num
304         #debug "got message #{docid} to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
305         f = @index[docid][:from]
306         t = @index[docid][:to]
307
308         if AccountManager.is_account_email? f
309           t.split(" ").each { |e| contacts[Person.from_address(e)] = true }
310         else
311           contacts[Person.from_address(f)] = true
312         end
313       end
314     end
315
316     contacts.keys.compact
317   end
318
319   def each_id query={}
320     ferret_query = build_ferret_query query
321     results = @index_mutex.synchronize { @index.search ferret_query, :limit => (query[:limit] || :all) }
322     results.hits.map { |hit| yield @index[hit.doc][:message_id] }
323   end
324
325   def optimize
326     @index_mutex.synchronize { @index.optimize }
327   end
328
329   def source_for_id id
330     entry = @index[id]
331     return unless entry
332     entry[:source_id].to_i
333   end
334
335   class ParseError < StandardError; end
336
337   ## parse a query string from the user. returns a query object
338   ## that can be passed to any index method with a 'query'
339   ## argument, as well as build_ferret_query.
340   ##
341   ## raises a ParseError if something went wrong.
342   def parse_query s
343     query = {}
344
345     subs = HookManager.run("custom-search", :subs => s) || s
346
347     subs = subs.gsub(/\b(to|from):(\S+)\b/) do
348       field, name = $1, $2
349       if(p = ContactManager.contact_for(name))
350         [field, p.email]
351       elsif name == "me"
352         [field, "(" + AccountManager.user_emails.join("||") + ")"]
353       else
354         [field, name]
355       end.join(":")
356     end
357
358     ## if we see a label:deleted or a label:spam term anywhere in the query
359     ## string, we set the extra load_spam or load_deleted options to true.
360     ## bizarre? well, because the query allows arbitrary parenthesized boolean
361     ## expressions, without fully parsing the query, we can't tell whether
362     ## the user is explicitly directing us to search spam messages or not.
363     ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
364     ## search spam messages or not?
365     ##
366     ## so, we rely on the fact that turning these extra options ON turns OFF
367     ## the adding of "-label:deleted" or "-label:spam" terms at the very
368     ## final stage of query processing. if the user wants to search spam
369     ## messages, not adding that is the right thing; if he doesn't want to
370     ## search spam messages, then not adding it won't have any effect.
371     query[:load_spam] = true if subs =~ /\blabel:spam\b/
372     query[:load_deleted] = true if subs =~ /\blabel:deleted\b/
373
374     ## gmail style "is" operator
375     subs = subs.gsub(/\b(is|has):(\S+)\b/) do
376       field, label = $1, $2
377       case label
378       when "read"
379         "-label:unread"
380       when "spam"
381         query[:load_spam] = true
382         "label:spam"
383       when "deleted"
384         query[:load_deleted] = true
385         "label:deleted"
386       else
387         "label:#{$2}"
388       end
389     end
390
391     ## gmail style attachments "filename" and "filetype" searches
392     subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
393       field, name = $1, ($3 || $4)
394       case field
395       when "filename"
396         debug "filename: translated #{field}:#{name} to attachments:(#{name.downcase})"
397         "attachments:(#{name.downcase})"
398       when "filetype"
399         debug "filetype: translated #{field}:#{name} to attachments:(*.#{name.downcase})"
400         "attachments:(*.#{name.downcase})"
401       end
402     end
403
404     if $have_chronic
405       subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
406         field, datestr = $1, ($3 || $4)
407         realdate = Chronic.parse datestr, :guess => false, :context => :past
408         if realdate
409           case field
410           when "after"
411             debug "chronic: translated #{field}:#{datestr} to #{realdate.end}"
412             "date:(>= #{sprintf "%012d", realdate.end.to_i})"
413           when "before"
414             debug "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
415             "date:(<= #{sprintf "%012d", realdate.begin.to_i})"
416           else
417             debug "chronic: translated #{field}:#{datestr} to #{realdate}"
418             "date:(<= #{sprintf "%012d", realdate.end.to_i}) date:(>= #{sprintf "%012d", realdate.begin.to_i})"
419           end
420         else
421           raise ParseError, "can't understand date #{datestr.inspect}"
422         end
423       end
424     end
425
426     ## limit:42 restrict the search to 42 results
427     subs = subs.gsub(/\blimit:(\S+)\b/) do
428       lim = $1
429       if lim =~ /^\d+$/
430         query[:limit] = lim.to_i
431         ''
432       else
433         raise ParseError, "non-numeric limit #{lim.inspect}"
434       end
435     end
436
437     begin
438       query[:qobj] = @qparser.parse(subs)
439       query[:text] = s
440       query
441     rescue Ferret::QueryParser::QueryParseException => e
442       raise ParseError, e.message
443     end
444   end
445
446 private
447
448   def build_ferret_query query
449     q = Ferret::Search::BooleanQuery.new
450     q.add_query Ferret::Search::MatchAllQuery.new, :must
451     q.add_query query[:qobj], :must if query[:qobj]
452     labels = ([query[:label]] + (query[:labels] || [])).compact
453     labels.each { |t| q.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
454     if query[:participants]
455       q2 = Ferret::Search::BooleanQuery.new
456       query[:participants].each do |p|
457         q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
458         q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
459       end
460       q.add_query q2, :must
461     end
462
463     q.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless query[:load_spam] || labels.include?(:spam)
464     q.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless query[:load_deleted] || labels.include?(:deleted)
465     q.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not if query[:skip_killed]
466
467     q.add_query Ferret::Search::TermQuery.new("source_id", query[:source_id]), :must if query[:source_id]
468     q
469   end
470
471   def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
472   def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
473 end
474
475 end