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