]> git.cworth.org Git - sup/blob - lib/sup/index.rb
Merge commit 'origin/reply-to-hook'
[sup] / lib / sup / index.rb
1 ## the index structure for redwood. interacts with ferret.
2
3 require 'fileutils'
4 require 'ferret'
5 begin
6   require 'chronic'
7   $have_chronic = true
8 rescue LoadError => e
9   Redwood::log "optional 'chronic' library not found (run 'gem install chronic' to install)"
10   $have_chronic = false
11 end
12
13 module Redwood
14
15 class Index
16   class LockError < StandardError
17     def initialize h
18       @h = h
19     end
20
21     def method_missing m; @h[m.to_s] end
22   end
23
24   include Singleton
25
26   attr_reader :index
27   alias ferret index
28   def initialize dir=BASE_DIR
29     @dir = dir
30     @sources = {}
31     @sources_dirty = false
32
33     wsa = Ferret::Analysis::WhiteSpaceAnalyzer.new false
34     sa = Ferret::Analysis::StandardAnalyzer.new [], true
35     @analyzer = Ferret::Analysis::PerFieldAnalyzer.new wsa
36     @analyzer[:body] = sa
37     @analyzer[:subject] = sa
38     @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer, :or_default => false
39     @lock = Lockfile.new lockfile, :retries => 0, :max_age => nil
40
41     self.class.i_am_the_instance self
42   end
43
44   def lockfile; File.join @dir, "lock" end
45
46   def lock
47     Redwood::log "locking #{lockfile}..."
48     begin
49       @lock.lock
50     rescue Lockfile::MaxTriesLockError
51       raise LockError, @lock.lockinfo_on_disk
52     end
53   end
54
55   def start_lock_update_thread
56     @lock_update_thread = Redwood::reporting_thread("lock update") do
57       while true
58         sleep 30
59         @lock.touch_yourself
60       end
61     end
62   end
63
64   def stop_lock_update_thread
65     @lock_update_thread.kill if @lock_update_thread
66     @lock_update_thread = nil
67   end
68
69   def fancy_lock_error_message_for e
70     secs = Time.now - e.mtime
71     mins = secs.to_i / 60
72     time =
73       if mins == 0
74         "#{secs.to_i} seconds"
75       else
76         "#{mins} minutes"
77       end
78
79     <<EOS
80 Error: the sup index is locked by another process! User '#{e.user}' on
81 host '#{e.host}' is running #{e.pname} with pid #{e.pid}. The process was alive
82 as of #{time} ago.
83 EOS
84   end
85
86   def lock_or_die
87     begin
88       lock
89     rescue LockError => e
90       $stderr.puts fancy_lock_error_message_for(e)
91       $stderr.puts <<EOS
92
93 You can wait for the process to finish, or, if it crashed and left a
94 stale lock file behind, you can manually delete #{@lock.path}.
95 EOS
96       exit
97     end
98   end
99
100   def unlock
101     if @lock && @lock.locked?
102       Redwood::log "unlocking #{lockfile}..."
103       @lock.unlock
104     end
105   end
106
107   def load
108     load_sources
109     load_index
110   end
111
112   def save
113     Redwood::log "saving index and sources..."
114     FileUtils.mkdir_p @dir unless File.exists? @dir
115     save_sources
116     save_index
117   end
118
119   def add_source source
120     raise "duplicate source!" if @sources.include? source
121     @sources_dirty = true
122     max = @sources.max_of { |id, s| s.is_a?(DraftLoader) || s.is_a?(SentLoader) ? 0 : id }
123     source.id ||= (max || 0) + 1
124     ##source.id += 1 while @sources.member? source.id
125     @sources[source.id] = source
126   end
127
128   def sources
129     ## favour the inbox by listing non-archived sources first
130     @sources.values.sort_by { |s| s.id }.partition { |s| !s.archived? }.flatten
131   end
132
133   def source_for uri; sources.find { |s| s.is_source_for? uri }; end
134   def usual_sources; sources.find_all { |s| s.usual? }; end
135
136   def load_index dir=File.join(@dir, "ferret")
137     if File.exists? dir
138       Redwood::log "loading index..."
139       @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
140       Redwood::log "loaded index of #{@index.size} messages"
141     else
142       Redwood::log "creating index..."
143       field_infos = Ferret::Index::FieldInfos.new :store => :yes
144       field_infos.add_field :message_id, :index => :untokenized
145       field_infos.add_field :source_id
146       field_infos.add_field :source_info
147       field_infos.add_field :date, :index => :untokenized
148       field_infos.add_field :body
149       field_infos.add_field :label
150       field_infos.add_field :attachments
151       field_infos.add_field :subject
152       field_infos.add_field :from
153       field_infos.add_field :to
154       field_infos.add_field :refs
155       field_infos.add_field :snippet, :index => :no, :term_vector => :no
156       field_infos.create_index dir
157       @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
158     end
159   end
160
161   ## Syncs the message to the index: deleting if it's already there,
162   ## and adding either way. Index state will be determined by m.labels.
163   ##
164   ## docid and entry can be specified if they're already known.
165   def sync_message m, docid=nil, entry=nil, opts={}
166     docid, entry = load_entry_for_id m.id unless docid && entry
167
168     raise "no source info for message #{m.id}" unless m.source && m.source_info
169     raise "trying to delete non-corresponding entry #{docid} with index message-id #{@index[docid][:message_id].inspect} and parameter message id #{m.id.inspect}" if docid && @index[docid][:message_id] != m.id
170
171     source_id = 
172       if m.source.is_a? Integer
173         m.source
174       else
175         m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
176       end
177
178     snippet = 
179       if m.snippet_contains_encrypted_content? && $config[:discard_snippets_from_encrypted_messages]
180         ""
181       else
182         m.snippet
183       end
184
185     ## write the new document to the index. if the entry already exists in the
186     ## index, reuse it (which avoids having to reload the entry from the source,
187     ## which can be quite expensive for e.g. large threads of IMAP actions.)
188     ##
189     ## exception: if the index entry belongs to an earlier version of the
190     ## message, use everything from the new message instead, but union the
191     ## flags. this allows messages sent to mailing lists to have their header
192     ## updated and to have flags set properly.
193     ##
194     ## minor hack: messages in sources with lower ids have priority over
195     ## messages in sources with higher ids. so messages in the inbox will
196     ## override everyone, and messages in the sent box will be overridden
197     ## by everyone else.
198     ##
199     ## written in this manner to support previous versions of the index which
200     ## did not keep around the entry body. upgrading is thus seamless.
201     entry ||= {}
202     labels = m.labels.uniq # override because this is the new state, unless...
203
204     ## if we are a later version of a message, ignore what's in the index,
205     ## but merge in the labels.
206     if entry[:source_id] && entry[:source_info] && entry[:label] &&
207       ((entry[:source_id].to_i > source_id) || (entry[:source_info].to_i < m.source_info))
208       labels = (entry[:label].split(/\s+/).map { |l| l.intern } + m.labels).uniq
209       #Redwood::log "found updated version of message #{m.id}: #{m.subj}"
210       #Redwood::log "previous version was at #{entry[:source_id].inspect}:#{entry[:source_info].inspect}, this version at #{source_id.inspect}:#{m.source_info.inspect}"
211       #Redwood::log "merged labels are #{labels.inspect} (index #{entry[:label].inspect}, message #{m.labels.inspect})"
212       entry = {}
213     end
214
215     ## if force_overwite is true, ignore what's in the index. this is used
216     ## primarily by sup-sync to force index updates.
217     entry = {} if opts[:force_overwrite]
218
219     d = {
220       :message_id => m.id,
221       :source_id => source_id,
222       :source_info => m.source_info,
223       :date => (entry[:date] || m.date.to_indexable_s),
224       :body => (entry[:body] || m.indexable_content),
225       :snippet => snippet, # always override
226       :label => labels.uniq.join(" "),
227       :attachments => (entry[:attachments] || m.attachments.uniq.join(" ")),
228       :from => (entry[:from] || (m.from ? m.from.indexable_content : "")),
229       :to => (entry[:to] || (m.to + m.cc + m.bcc).map { |x| x.indexable_content }.join(" ")),
230       :subject => (entry[:subject] || wrap_subj(Message.normalize_subj(m.subj))),
231       :refs => (entry[:refs] || (m.refs + m.replytos).uniq.join(" ")),
232     }
233
234     @index.delete docid if docid
235     @index.add_document d
236     
237     docid, entry = load_entry_for_id m.id
238     ## this hasn't been triggered in a long time. TODO: decide whether it's still a problem.
239     raise "just added message #{m.id.inspect} but couldn't find it in a search" unless docid
240     true
241   end
242
243   def save_index fn=File.join(@dir, "ferret")
244     # don't have to do anything, apparently
245   end
246
247   def contains_id? id
248     @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0
249   end
250   def contains? m; contains_id? m.id; end
251   def size; @index.size; end
252
253   ## you should probably not call this on a block that doesn't break
254   ## rather quickly because the results can be very large.
255   EACH_BY_DATE_NUM = 100
256   def each_id_by_date opts={}
257     return if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
258     query = build_query opts
259     offset = 0
260     while true
261       results = @index.search(query, :sort => "date DESC", :limit => EACH_BY_DATE_NUM, :offset => offset)
262       Redwood::log "got #{results.total_hits} results for query (offset #{offset}) #{query.inspect}"
263       results.hits.each { |hit| yield @index[hit.doc][:message_id], lambda { build_message hit.doc } }
264       break if offset >= results.total_hits - EACH_BY_DATE_NUM
265       offset += EACH_BY_DATE_NUM
266     end
267   end
268
269   def num_results_for opts={}
270     return 0 if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
271
272     q = build_query opts
273     index.search(q, :limit => 1).total_hits
274   end
275
276   ## yield all messages in the thread containing 'm' by repeatedly
277   ## querying the index. yields pairs of message ids and
278   ## message-building lambdas, so that building an unwanted message
279   ## can be skipped in the block if desired.
280   ##
281   ## only two options, :limit and :skip_killed. if :skip_killed is
282   ## true, stops loading any thread if a message with a :killed flag
283   ## is found.
284   SAME_SUBJECT_DATE_LIMIT = 7
285   MAX_CLAUSES = 1000
286   def each_message_in_thread_for m, opts={}
287     #Redwood::log "Building thread for #{m.id}: #{m.subj}"
288     messages = {}
289     searched = {}
290     num_queries = 0
291
292     pending = [m.id]
293     if $config[:thread_by_subject] # do subject queries
294       date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
295       date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
296
297       q = Ferret::Search::BooleanQuery.new true
298       sq = Ferret::Search::PhraseQuery.new(:subject)
299       wrap_subj(Message.normalize_subj(m.subj)).split(/\s+/).each do |t|
300         sq.add_term t
301       end
302       q.add_query sq, :must
303       q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
304
305       q = build_query :qobj => q
306
307       p1 = @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] }
308       Redwood::log "found #{p1.size} results for subject query #{q}"
309
310       p2 = @index.search(q.to_s, :limit => :all).hits.map { |hit| @index[hit.doc][:message_id] }
311       Redwood::log "found #{p2.size} results in string form"
312
313       pending = (pending + p1 + p2).uniq
314     end
315
316     until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
317       q = Ferret::Search::BooleanQuery.new true
318       # this disappeared in newer ferrets... wtf.
319       # q.max_clause_count = 2048
320
321       lim = [MAX_CLAUSES / 2, pending.length].min
322       pending[0 ... lim].each do |id|
323         searched[id] = true
324         q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
325         q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
326       end
327       pending = pending[lim .. -1]
328
329       q = build_query :qobj => q
330
331       num_queries += 1
332       killed = false
333       @index.search_each(q, :limit => :all) do |docid, score|
334         break if opts[:limit] && messages.size >= opts[:limit]
335         if @index[docid][:label].split(/\s+/).include?("killed") && opts[:skip_killed]
336           killed = true
337           break
338         end
339         mid = @index[docid][:message_id]
340         unless messages.member?(mid)
341           #Redwood::log "got #{mid} as a child of #{id}"
342           messages[mid] ||= lambda { build_message docid }
343           refs = @index[docid][:refs].split(" ")
344           pending += refs.select { |id| !searched[id] }
345         end
346       end
347     end
348
349     if killed
350       Redwood::log "thread for #{m.id} is killed, ignoring"
351       false
352     else
353       Redwood::log "ran #{num_queries} queries to build thread of #{messages.size + 1} messages for #{m.id}: #{m.subj}" if num_queries > 0
354       messages.each { |mid, builder| yield mid, builder }
355       true
356     end
357   end
358
359   ## builds a message object from a ferret result
360   def build_message docid
361     doc = @index[docid]
362     source = @sources[doc[:source_id].to_i]
363     #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
364     raise "invalid source #{doc[:source_id]}" unless source
365
366     fake_header = {
367       "date" => Time.at(doc[:date].to_i),
368       "subject" => unwrap_subj(doc[:subject]),
369       "from" => doc[:from],
370       "to" => doc[:to].split(/\s+/).join(", "), # reformat
371       "message-id" => doc[:message_id],
372       "references" => doc[:refs].split(/\s+/).map { |x| "<#{x}>" }.join(" "),
373     }
374
375     Message.new :source => source, :source_info => doc[:source_info].to_i, 
376                 :labels => doc[:label].split(" ").map { |s| s.intern },
377                 :snippet => doc[:snippet], :header => fake_header
378   end
379
380   def fresh_thread_id; @next_thread_id += 1; end
381   def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
382   def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
383
384   def drop_entry docno; @index.delete docno; end
385
386   def load_entry_for_id mid
387     results = @index.search(Ferret::Search::TermQuery.new(:message_id, mid))
388     return if results.total_hits == 0
389     docid = results.hits[0].doc
390     [docid, @index[docid]]
391   end
392
393   def load_contacts emails, h={}
394     q = Ferret::Search::BooleanQuery.new true
395     emails.each do |e|
396       qq = Ferret::Search::BooleanQuery.new true
397       qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
398       qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
399       q.add_query qq
400     end
401     q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
402     
403     Redwood::log "contact search: #{q}"
404     contacts = {}
405     num = h[:num] || 20
406     @index.search_each(q, :sort => "date DESC", :limit => :all) do |docid, score|
407       break if contacts.size >= num
408       #Redwood::log "got message #{docid} to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
409       f = @index[docid][:from]
410       t = @index[docid][:to]
411
412       if AccountManager.is_account_email? f
413         t.split(" ").each { |e| contacts[PersonManager.person_for(e)] = true }
414       else
415         contacts[PersonManager.person_for(f)] = true
416       end
417     end
418
419     contacts.keys.compact
420   end
421
422   def load_sources fn=Redwood::SOURCE_FN
423     source_array = (Redwood::load_yaml_obj(fn) || []).map { |o| Recoverable.new o }
424     @sources = Hash[*(source_array).map { |s| [s.id, s] }.flatten]
425     @sources_dirty = false
426   end
427
428   def has_any_from_source_with_label? source, label
429     q = Ferret::Search::BooleanQuery.new
430     q.add_query Ferret::Search::TermQuery.new("source_id", source.id.to_s), :must
431     q.add_query Ferret::Search::TermQuery.new("label", label.to_s), :must
432     index.search(q, :limit => 1).total_hits > 0
433   end
434
435 protected
436
437   ## do any specialized parsing
438   ## returns nil and flashes error message if parsing failed
439   def parse_user_query_string s
440     extraopts = {}
441
442     subs = s.gsub(/\b(to|from):(\S+)\b/) do
443       field, name = $1, $2
444       if(p = ContactManager.contact_for(name))
445         [field, p.email]
446       elsif name == "me"
447         [field, "(" + AccountManager.user_emails.join("||") + ")"]
448       else
449         [field, name]
450       end.join(":")
451     end
452
453     ## if we see a label:deleted or a label:spam term anywhere in the query
454     ## string, we set the extra load_spam or load_deleted options to true.
455     ## bizarre? well, because the query allows arbitrary parenthesized boolean
456     ## expressions, without fully parsing the query, we can't tell whether
457     ## the user is explicitly directing us to search spam messages or not.
458     ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
459     ## search spam messages or not?
460     ##
461     ## so, we rely on the fact that turning these extra options ON turns OFF
462     ## the adding of "-label:deleted" or "-label:spam" terms at the very
463     ## final stage of query processing. if the user wants to search spam
464     ## messages, not adding that is the right thing; if he doesn't want to
465     ## search spam messages, then not adding it won't have any effect.
466     extraopts[:load_spam] = true if subs =~ /\blabel:spam\b/
467     extraopts[:load_deleted] = true if subs =~ /\blabel:deleted\b/
468
469     ## gmail style "is" operator
470     subs = subs.gsub(/\b(is|has):(\S+)\b/) do
471       field, label = $1, $2
472       case label
473       when "read"
474         "-label:unread"
475       when "spam"
476         extraopts[:load_spam] = true
477         "label:spam"
478       when "deleted"
479         extraopts[:load_deleted] = true
480         "label:deleted"
481       else
482         "label:#{$2}"
483       end
484     end
485
486     ## gmail style attachments "filename" and "filetype" searches
487     subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
488       field, name = $1, ($3 || $4)
489       case field
490       when "filename"
491         Redwood::log "filename - translated #{field}:#{name} to attachments:(#{name.downcase})"
492         "attachments:(#{name.downcase})"
493       when "filetype"
494         Redwood::log "filetype - translated #{field}:#{name} to attachments:(*.#{name.downcase})"
495         "attachments:(*.#{name.downcase})"
496       end
497     end
498
499     if $have_chronic
500       chronic_failure = false
501       subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
502         break if chronic_failure
503         field, datestr = $1, ($3 || $4)
504         realdate = Chronic.parse(datestr, :guess => false, :context => :none)
505         if realdate
506           case field
507           when "after"
508             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.end}"
509             "date:(>= #{sprintf "%012d", realdate.end.to_i})"
510           when "before"
511             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
512             "date:(<= #{sprintf "%012d", realdate.begin.to_i})"
513           else
514             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate}"
515             "date:(<= #{sprintf "%012d", realdate.end.to_i}) date:(>= #{sprintf "%012d", realdate.begin.to_i})"
516           end
517         else
518           BufferManager.flash "Can't understand date #{datestr.inspect}!"
519           chronic_failure = true
520         end
521       end
522       subs = nil if chronic_failure
523     end
524     
525     if subs
526       [@qparser.parse(subs), extraopts]
527     else
528       nil
529     end
530   end
531
532   def build_query opts
533     query = Ferret::Search::BooleanQuery.new
534     query.add_query opts[:qobj], :must if opts[:qobj]
535     labels = ([opts[:label]] + (opts[:labels] || [])).compact
536     labels.each { |t| query.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
537     if opts[:participants]
538       q2 = Ferret::Search::BooleanQuery.new
539       opts[:participants].each do |p|
540         q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
541         q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
542       end
543       query.add_query q2, :must
544     end
545         
546     query.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless opts[:load_spam] || labels.include?(:spam)
547     query.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless opts[:load_deleted] || labels.include?(:deleted)
548     query.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not if opts[:skip_killed]
549     query
550   end
551
552   def save_sources fn=Redwood::SOURCE_FN
553     if @sources_dirty || @sources.any? { |id, s| s.dirty? }
554       bakfn = fn + ".bak"
555       if File.exists? fn
556         File.chmod 0600, fn
557         FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(fn) == 0
558       end
559       Redwood::save_yaml_obj sources.sort_by { |s| s.id.to_i }, fn, true
560       File.chmod 0600, fn
561     end
562     @sources_dirty = false
563   end
564 end
565
566 end