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