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