]> git.cworth.org Git - sup/blob - lib/sup/ferret_index.rb
coerce Message#add_label (and others) arguments to symbols
[sup] / lib / sup / ferret_index.rb
1 require 'ferret'
2
3 module Redwood
4
5 class FerretIndex < BaseIndex
6
7   def initialize dir=BASE_DIR
8     super
9
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
14     @analyzer[:body] = sa
15     @analyzer[:subject] = sa
16     @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer, :or_default => false
17   end
18
19   def load_index dir=File.join(@dir, "ferret")
20     if File.exists? dir
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"
25       end
26     else
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')
44       end
45     end
46   end
47
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
51
52   def sync_message m, opts={}
53     entry = @index[m.id]
54
55     raise "no source info for message #{m.id}" unless m.source && m.source_info
56
57     source_id = if m.source.is_a? Integer
58       m.source
59     else
60       m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
61     end
62
63     snippet = if m.snippet_contains_encrypted_content? && $config[:discard_snippets_from_encrypted_messages]
64       ""
65     else
66       m.snippet
67     end
68
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.)
72     ##
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.
77     ##
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
81     ## by everyone else.
82     ##
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.
85     entry ||= {}
86     labels = m.labels # override because this is the new state, unless...
87
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})"
96       entry = {}
97     end
98
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]
102
103     d = {
104       :message_id => m.id,
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(" ")),
112
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(" "),
122
123       :subject => (entry[:subject] || wrap_subj(Message.normalize_subj(m.subj))),
124       :refs => (entry[:refs] || (m.refs + m.replytos).uniq.join(" ")),
125     }
126
127     @index_mutex.synchronize do
128       @index.delete m.id
129       @index.add_document d
130     end
131   end
132   private :sync_message
133
134   def save_index fn=File.join(@dir, "ferret")
135     # don't have to do anything, apparently
136   end
137
138   def contains_id? id
139     @index_mutex.synchronize { @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0 }
140   end
141
142   def size
143     @index_mutex.synchronize { @index.size }
144   end
145
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
150     offset = 0
151     while true
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 }
157       end
158       break if query[:limit] and offset >= query[:limit] - limit
159       break if offset >= results.total_hits - limit
160       offset += limit
161     end
162   end
163
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 }
168   end
169
170   SAME_SUBJECT_DATE_LIMIT = 7
171   MAX_CLAUSES = 1000
172   def each_message_in_thread_for m, opts={}
173     #debug "Building thread for #{m.id}: #{m.subj}"
174     messages = {}
175     searched = {}
176     num_queries = 0
177
178     pending = [m.id]
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)
182
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|
186         sq.add_term t
187       end
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
190
191       q = build_ferret_query :qobj => q
192
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}"
195
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"
198
199       pending = (pending + p1 + p2).uniq
200     end
201
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
206
207       lim = [MAX_CLAUSES / 2, pending.length].min
208       pending[0 ... lim].each do |id|
209         searched[id] = true
210         q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
211         q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
212       end
213       pending = pending[lim .. -1]
214
215       q = build_ferret_query :qobj => q
216
217       num_queries += 1
218       killed = false
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]
223             killed = true
224             break
225           end
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] }
232           end
233         end
234       end
235     end
236
237     if killed
238       #debug "thread for #{m.id} is killed, ignoring"
239       false
240     else
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 }
243       true
244     end
245   end
246
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
251
252       source = SourceManager[doc[:source_id].to_i]
253       raise "invalid source #{doc[:source_id]}" unless source
254
255       #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
256
257       fake_header = {
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(" "),
264       }
265
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
270       m
271     end
272   end
273
274   def delete id
275     @index_mutex.synchronize { @index.delete id }
276   end
277
278   def load_contacts emails, h={}
279     q = Ferret::Search::BooleanQuery.new true
280     emails.each do |e|
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
284       q.add_query qq
285     end
286     q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
287
288     debug "contact search: #{q}"
289     contacts = {}
290     num = h[:num] || 20
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]
297
298         if AccountManager.is_account_email? f
299           t.split(" ").each { |e| contacts[Person.from_address(e)] = true }
300         else
301           contacts[Person.from_address(f)] = true
302         end
303       end
304     end
305
306     contacts.keys.compact
307   end
308
309   def each_id query={}
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] }
313   end
314
315   def optimize
316     @index_mutex.synchronize { @index.optimize }
317   end
318
319   def source_for_id id
320     entry = @index[id]
321     return unless entry
322     entry[:source_id].to_i
323   end
324
325   class ParseError < StandardError; end
326
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.
330   ##
331   ## raises a ParseError if something went wrong.
332   def parse_query s
333     query = {}
334
335     subs = s.gsub(/\b(to|from):(\S+)\b/) do
336       field, name = $1, $2
337       if(p = ContactManager.contact_for(name))
338         [field, p.email]
339       elsif name == "me"
340         [field, "(" + AccountManager.user_emails.join("||") + ")"]
341       else
342         [field, name]
343       end.join(":")
344     end
345
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?
353     ##
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/
361
362     ## gmail style "is" operator
363     subs = subs.gsub(/\b(is|has):(\S+)\b/) do
364       field, label = $1, $2
365       case label
366       when "read"
367         "-label:unread"
368       when "spam"
369         query[:load_spam] = true
370         "label:spam"
371       when "deleted"
372         query[:load_deleted] = true
373         "label:deleted"
374       else
375         "label:#{$2}"
376       end
377     end
378
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)
382       case field
383       when "filename"
384         debug "filename: translated #{field}:#{name} to attachments:(#{name.downcase})"
385         "attachments:(#{name.downcase})"
386       when "filetype"
387         debug "filetype: translated #{field}:#{name} to attachments:(*.#{name.downcase})"
388         "attachments:(*.#{name.downcase})"
389       end
390     end
391
392     if $have_chronic
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
396         if realdate
397           case field
398           when "after"
399             debug "chronic: translated #{field}:#{datestr} to #{realdate.end}"
400             "date:(>= #{sprintf "%012d", realdate.end.to_i})"
401           when "before"
402             debug "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
403             "date:(<= #{sprintf "%012d", realdate.begin.to_i})"
404           else
405             debug "chronic: translated #{field}:#{datestr} to #{realdate}"
406             "date:(<= #{sprintf "%012d", realdate.end.to_i}) date:(>= #{sprintf "%012d", realdate.begin.to_i})"
407           end
408         else
409           raise ParseError, "can't understand date #{datestr.inspect}"
410         end
411       end
412     end
413
414     ## limit:42 restrict the search to 42 results
415     subs = subs.gsub(/\blimit:(\S+)\b/) do
416       lim = $1
417       if lim =~ /^\d+$/
418         query[:limit] = lim.to_i
419         ''
420       else
421         raise ParseError, "non-numeric limit #{lim.inspect}"
422       end
423     end
424
425     begin
426       query[:qobj] = @qparser.parse(subs)
427       query[:text] = s
428       query
429     rescue Ferret::QueryParser::QueryParseException => e
430       raise ParseError, e.message
431     end
432   end
433
434 private
435
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
447       end
448       q.add_query q2, :must
449     end
450
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]
454
455     q.add_query Ferret::Search::TermQuery.new("source_id", query[:source_id]), :must if query[:source_id]
456     q
457   end
458
459   def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
460   def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
461 end
462
463 end