]> git.cworth.org Git - sup/blob - lib/sup/index.rb
yet more fixes to imap, some buffer debugging, and more comment cleanups
[sup] / lib / sup / index.rb
1 ## the index structure for redwood. interacts with ferret.
2
3 require 'thread'
4 require 'fileutils'
5 require 'ferret'
6 #require_gem 'ferret', ">= 0.10.13"
7
8 module Redwood
9
10 class Index
11   include Singleton
12
13   attr_reader :index
14   def initialize dir=BASE_DIR
15     @dir = dir
16     @sources = {}
17     @sources_dirty = false
18
19     wsa = Ferret::Analysis::WhiteSpaceAnalyzer.new false
20     sa = Ferret::Analysis::StandardAnalyzer.new Ferret::Analysis::FULL_ENGLISH_STOP_WORDS, true
21     @analyzer = Ferret::Analysis::PerFieldAnalyzer.new wsa
22     @analyzer[:body] = sa
23     @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer
24
25     self.class.i_am_the_instance self
26   end
27
28   def load
29     load_sources
30     load_index
31   end
32
33   def save
34     FileUtils.mkdir_p @dir unless File.exists? @dir
35     save_sources
36     save_index
37   end
38
39   def add_source source
40     raise "duplicate source!" if @sources.include? source
41     @sources_dirty = true
42     source.id ||= @sources.size
43     ##TODO: why was this necessary?
44     ##source.id += 1 while @sources.member? source.id
45     @sources[source.id] = source
46   end
47
48   def source_for name; @sources.values.find { |s| s.is_source_for? name }; end
49   def usual_sources; @sources.values.find_all { |s| s.usual? }; end
50   def sources; @sources.values; end
51
52   def load_index dir=File.join(@dir, "ferret")
53     if File.exists? dir
54       Redwood::log "loading index..."
55       @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
56       Redwood::log "loaded index of #{@index.size} messages"
57     else
58       Redwood::log "creating index..."
59       field_infos = Ferret::Index::FieldInfos.new :store => :yes
60       field_infos.add_field :message_id
61       field_infos.add_field :source_id
62       field_infos.add_field :source_info
63       field_infos.add_field :date, :index => :untokenized
64       field_infos.add_field :body, :store => :no
65       field_infos.add_field :label
66       field_infos.add_field :subject
67       field_infos.add_field :from
68       field_infos.add_field :to
69       field_infos.add_field :refs
70       field_infos.add_field :snippet, :index => :no, :term_vector => :no
71       field_infos.create_index dir
72       @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
73     end
74   end
75
76   ## update the message by deleting and re-adding
77   def update_message m, source=nil, source_info=nil
78     docid, entry = load_entry_for_id m.id
79     if entry
80       source ||= entry[:source_id].to_i
81       source_info ||= entry[:source_info].to_i
82     end
83
84     ## this happens sometimes. i'm not sure why. ferret bug?
85     raise "no entry and no source info for message #{m.id}: source #{source.inspect}, info #{source_info.inspect}, entry #{entry.inspect}, query #{Ferret::Search::TermQuery.new(:message_id, m.id)}, results #{@index.search(Ferret::Search::TermQuery.new(:message_id, m.id)).inspect}" unless source && source_info
86
87     raise "deleting non-corresponding entry #{docid}" unless @index[docid][:message_id] == m.id
88     @index.delete docid
89     add_message m
90   end
91
92   def save_index fn=File.join(@dir, "ferret")
93     # don't have to do anything apparently
94   end
95
96   def contains_id? id
97     @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0
98   end
99   def contains? m; contains_id? m.id; end
100   def size; @index.size; end
101
102   ## you should probably not call this on a block that doesn't break
103   ## rather quickly because the results will probably be, as we say
104   ## in scotland, frikkin' huuuge.
105   EACH_BY_DATE_NUM = 100
106   def each_id_by_date opts={}
107     return if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
108     query = build_query opts
109     offset = 0
110     while true
111       results = @index.search(query, :sort => "date DESC", :limit => EACH_BY_DATE_NUM, :offset => offset)
112       Redwood::log "got #{results.total_hits} results for query (offset #{offset}) #{query.inspect}"
113       results.hits.each { |hit| yield @index[hit.doc][:message_id], lambda { build_message hit.doc } }
114       break if offset >= results.total_hits - EACH_BY_DATE_NUM
115       offset += EACH_BY_DATE_NUM
116     end
117   end
118
119   def num_results_for opts={}
120     return 0 if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
121     q = build_query opts
122     index.search(q).total_hits
123   end
124
125   ## yield all messages in the thread containing 'm' by repeatedly
126   ## querying the index.  yields pairs of message ids and
127   ## message-building lambdas, so that building an unwanted message
128   ## can be skipped in the block if desired.
129   SAME_SUBJECT_DATE_LIMIT = 7
130   def each_message_in_thread_for m, opts={}
131     messages = {}
132     searched = {}
133     num_queries = 0
134
135     ## temporarily disabling subject searching because it's a
136     ## significant slowdown.
137     ##
138     ## TODO: make this configurable, i guess
139     if false
140       date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
141       date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
142
143       q = Ferret::Search::BooleanQuery.new true
144       sq = Ferret::Search::PhraseQuery.new(:subject)
145       wrap_subj(Message.normalize_subj(m.subj)).split(/\s+/).each do |t|
146         sq.add_term t
147       end
148       q.add_query sq, :must
149       q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
150
151       pending = @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] }
152       Redwood::log "found #{pending.size} results for subject query #{q}"
153     else
154       pending = [m.id]
155     end
156
157     until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
158       id = pending.pop
159       next if searched.member? id
160       searched[id] = true
161       q = Ferret::Search::BooleanQuery.new true
162       q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
163       q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
164
165       num_queries += 1
166       @index.search_each(q, :limit => :all) do |docid, score|
167         break if opts[:limit] && messages.size >= opts[:limit]
168         mid = @index[docid][:message_id]
169         unless messages.member? mid
170           messages[mid] ||= lambda { build_message docid }
171           refs = @index[docid][:refs].split(" ")
172           pending += refs
173         end
174       end
175     end
176     Redwood::log "ran #{num_queries} queries to build thread of #{messages.size} messages for #{m.id}"
177     messages.each { |mid, builder| yield mid, builder }
178   end
179
180   ## builds a message object from a ferret result
181   def build_message docid
182     doc = @index[docid]
183     source = @sources[doc[:source_id].to_i]
184     #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
185     raise "invalid source #{doc[:source_id]}" unless source
186
187     fake_header = {
188       "date" => Time.at(doc[:date].to_i),
189       "subject" => unwrap_subj(doc[:subject]),
190       "from" => doc[:from],
191       "to" => doc[:to],
192       "message-id" => doc[:message_id],
193       "references" => doc[:refs],
194     }
195
196     Message.new :source => source, :source_info => doc[:source_info].to_i, 
197                 :labels => doc[:label].split(" ").map { |s| s.intern },
198                 :snippet => doc[:snippet], :header => fake_header
199   end
200
201   def fresh_thread_id; @next_thread_id += 1; end
202   def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
203   def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
204
205   def add_message m
206     return false if contains? m
207
208     source_id = 
209       if m.source.is_a? Integer
210         m.source
211       else
212         m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
213       end
214
215     to = (m.to + m.cc + m.bcc).map { |x| x.email }.join(" ")
216     d = {
217       :message_id => m.id,
218       :source_id => source_id,
219       :source_info => m.source_info,
220       :date => m.date.to_indexable_s,
221       :body => m.content,
222       :snippet => m.snippet,
223       :label => m.labels.join(" "),
224       :from => m.from ? m.from.email : "",
225       :to => (m.to + m.cc + m.bcc).map { |x| x.email }.join(" "),
226       :subject => wrap_subj(Message.normalize_subj(m.subj)),
227       :refs => (m.refs + m.replytos).uniq.join(" "),
228     }
229
230     @index.add_document d
231     
232     ## TODO: figure out why this is sometimes triggered
233     #docid, entry = load_entry_for_id m.id
234     #raise "just added message #{m.id} but couldn't find it in a search" unless docid
235     true
236   end
237
238   def drop_entry docno; @index.delete docno; end
239
240   def load_entry_for_id mid
241     results = @index.search(Ferret::Search::TermQuery.new(:message_id, mid))
242     return if results.total_hits == 0
243     docid = results.hits[0].doc
244     [docid, @index[docid]]
245   end
246
247   def load_contacts emails, h={}
248     q = Ferret::Search::BooleanQuery.new true
249     emails.each do |e|
250       qq = Ferret::Search::BooleanQuery.new true
251       qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
252       qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
253       q.add_query qq
254     end
255     q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
256     
257     Redwood::log "contact search: #{q}"
258     contacts = {}
259     num = h[:num] || 20
260     @index.search_each(q, :sort => "date DESC", :limit => :all) do |docid, score|
261       break if contacts.size >= num
262       #Redwood::log "got message with to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
263       f = @index[docid][:from]
264       t = @index[docid][:to]
265
266       if AccountManager.is_account_email? f
267         t.split(" ").each { |e| #Redwood::log "adding #{e} because there's a message to him from account email #{f}"; 
268           contacts[Person.for(e)] = true }
269       else
270         #Redwood::log "adding from #{f} because there's a message from him to #{t}"
271         contacts[Person.for(f)] = true
272       end
273     end
274
275     contacts.keys.compact
276   end
277
278 protected
279
280   def parse_user_query_string str; @qparser.parse str; end
281   def build_query opts
282     query = Ferret::Search::BooleanQuery.new
283     query.add_query opts[:qobj], :must if opts[:qobj]
284     labels = ([opts[:label]] + (opts[:labels] || [])).compact
285     labels.each { |t| query.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
286     if opts[:participants]
287       q2 = Ferret::Search::BooleanQuery.new
288       opts[:participants].each do |p|
289         q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
290         q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
291       end
292       query.add_query q2, :must
293     end
294         
295     query.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless opts[:load_spam] || labels.include?(:spam)
296     query.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not unless opts[:load_killed] || labels.include?(:killed)
297     query
298   end
299
300   def load_sources fn=Redwood::SOURCE_FN
301     @sources = Hash[*(Redwood::load_yaml_obj(fn) || []).map { |s| [s.id, s] }.flatten]
302     @sources_dirty = false
303   end
304
305   def save_sources fn=Redwood::SOURCE_FN
306     if @sources_dirty || @sources.any? { |id, s| s.dirty? }
307       bakfn = fn + ".bak"
308       if File.exists? fn
309         File.chmod 0600, fn
310         FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(bakfn) > File.size(fn)
311       end
312       Redwood::save_yaml_obj @sources.values, fn
313       File.chmod 0600, fn
314     end
315     @sources_dirty = false
316   end
317 end
318
319 end