]> git.cworth.org Git - sup/blob - lib/sup/index.rb
24e6cee39a930acee9caddfbacc4210a95fd2697
[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 uri; @sources.values.find { |s| s.is_source_for? uri }; 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 true
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::TermQuery.new(:label, "spam"), :must_not
150       q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
151
152       pending = @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] }
153       Redwood::log "found #{pending.size} results for subject query #{q}"
154     else
155       pending = [m.id]
156     end
157
158     until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
159       id = pending.pop
160       next if searched.member? id
161       searched[id] = true
162       q = Ferret::Search::BooleanQuery.new true
163       q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
164       q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
165
166       num_queries += 1
167       @index.search_each(q, :limit => :all) do |docid, score|
168         break if opts[:limit] && messages.size >= opts[:limit]
169         mid = @index[docid][:message_id]
170         unless messages.member? mid
171           messages[mid] ||= lambda { build_message docid }
172           refs = @index[docid][:refs].split(" ")
173           pending += refs
174         end
175       end
176     end
177     Redwood::log "ran #{num_queries} queries to build thread of #{messages.size} messages for #{m.id}" if num_queries > 0
178     messages.each { |mid, builder| yield mid, builder }
179   end
180
181   ## builds a message object from a ferret result
182   def build_message docid
183     doc = @index[docid]
184     source = @sources[doc[:source_id].to_i]
185     #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
186     raise "invalid source #{doc[:source_id]}" unless source
187
188     fake_header = {
189       "date" => Time.at(doc[:date].to_i),
190       "subject" => unwrap_subj(doc[:subject]),
191       "from" => doc[:from],
192       "to" => doc[:to],
193       "message-id" => doc[:message_id],
194       "references" => doc[:refs],
195     }
196
197     Message.new :source => source, :source_info => doc[:source_info].to_i, 
198                 :labels => doc[:label].split(" ").map { |s| s.intern },
199                 :snippet => doc[:snippet], :header => fake_header
200   end
201
202   def fresh_thread_id; @next_thread_id += 1; end
203   def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
204   def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
205
206   def add_message m
207     return false if contains? m
208
209     source_id = 
210       if m.source.is_a? Integer
211         m.source
212       else
213         m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
214       end
215
216     to = (m.to + m.cc + m.bcc).map { |x| x.email }.join(" ")
217     d = {
218       :message_id => m.id,
219       :source_id => source_id,
220       :source_info => m.source_info,
221       :date => m.date.to_indexable_s,
222       :body => m.content,
223       :snippet => m.snippet,
224       :label => m.labels.join(" "),
225       :from => m.from ? m.from.email : "",
226       :to => (m.to + m.cc + m.bcc).map { |x| x.email }.join(" "),
227       :subject => wrap_subj(Message.normalize_subj(m.subj)),
228       :refs => (m.refs + m.replytos).uniq.join(" "),
229     }
230
231     @index.add_document d
232     
233     ## TODO: figure out why this is sometimes triggered
234     docid, entry = load_entry_for_id m.id
235     raise "just added message #{m.id} but couldn't find it in a search" unless docid
236     true
237   end
238
239   def drop_entry docno; @index.delete docno; end
240
241   def load_entry_for_id mid
242     results = @index.search(Ferret::Search::TermQuery.new(:message_id, mid))
243     return if results.total_hits == 0
244     docid = results.hits[0].doc
245     [docid, @index[docid]]
246   end
247
248   def load_contacts emails, h={}
249     q = Ferret::Search::BooleanQuery.new true
250     emails.each do |e|
251       qq = Ferret::Search::BooleanQuery.new true
252       qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
253       qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
254       q.add_query qq
255     end
256     q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
257     
258     Redwood::log "contact search: #{q}"
259     contacts = {}
260     num = h[:num] || 20
261     @index.search_each(q, :sort => "date DESC", :limit => :all) do |docid, score|
262       break if contacts.size >= num
263       #Redwood::log "got message with to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
264       f = @index[docid][:from]
265       t = @index[docid][:to]
266
267       if AccountManager.is_account_email? f
268         t.split(" ").each { |e| #Redwood::log "adding #{e} because there's a message to him from account email #{f}"; 
269           contacts[Person.for(e)] = true }
270       else
271         #Redwood::log "adding from #{f} because there's a message from him to #{t}"
272         contacts[Person.for(f)] = true
273       end
274     end
275
276     contacts.keys.compact
277   end
278
279 protected
280
281   def parse_user_query_string str; @qparser.parse str; end
282   def build_query opts
283     query = Ferret::Search::BooleanQuery.new
284     query.add_query opts[:qobj], :must if opts[:qobj]
285     labels = ([opts[:label]] + (opts[:labels] || [])).compact
286     labels.each { |t| query.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
287     if opts[:participants]
288       q2 = Ferret::Search::BooleanQuery.new
289       opts[:participants].each do |p|
290         q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
291         q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
292       end
293       query.add_query q2, :must
294     end
295         
296     query.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless opts[:load_spam] || labels.include?(:spam)
297     query.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless opts[:load_deleted] || labels.include?(:deleted)
298     query.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not unless opts[:load_killed] || labels.include?(:killed)
299     query
300   end
301
302   def load_sources fn=Redwood::SOURCE_FN
303     @sources = Hash[*(Redwood::load_yaml_obj(fn) || []).map { |s| [s.id, s] }.flatten]
304     @sources_dirty = false
305   end
306
307   def save_sources fn=Redwood::SOURCE_FN
308     if @sources_dirty || @sources.any? { |id, s| s.dirty? }
309       bakfn = fn + ".bak"
310       if File.exists? fn
311         File.chmod 0600, fn
312         FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(bakfn) > File.size(fn)
313       end
314       Redwood::save_yaml_obj @sources.values, fn
315       File.chmod 0600, fn
316     end
317     @sources_dirty = false
318   end
319 end
320
321 end