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