1 ## the index structure for redwood. interacts with ferret.
6 #require_gem 'ferret', ">= 0.10.13"
14 def initialize dir=BASE_DIR
17 @sources_dirty = false
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
23 @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer
25 self.class.i_am_the_instance self
34 FileUtils.mkdir_p @dir unless File.exists? @dir
40 raise "duplicate source!" if @sources.include? source
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
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
52 def load_index dir=File.join(@dir, "ferret")
54 Redwood::log "loading index..."
55 @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
56 Redwood::log "loaded index of #{@index.size} messages"
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)
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
80 source ||= entry[:source_id].to_i
81 source_info ||= entry[:source_info].to_i
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
87 raise "deleting non-corresponding entry #{docid}" unless @index[docid][:message_id] == m.id
92 def save_index fn=File.join(@dir, "ferret")
93 # don't have to do anything apparently
97 @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0
99 def contains? m; contains_id? m.id; end
100 def size; @index.size; end
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
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
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
122 index.search(q).total_hits
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={}
135 ## temporarily disabling subject searching because it's a
136 ## significant slowdown.
138 ## TODO: make this configurable, i guess
140 date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
141 date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
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|
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
151 pending = @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] }
152 Redwood::log "found #{pending.size} results for subject query #{q}"
157 until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
159 next if searched.member? id
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
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(" ")
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 }
180 ## builds a message object from a ferret result
181 def build_message 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
188 "date" => Time.at(doc[:date].to_i),
189 "subject" => unwrap_subj(doc[:subject]),
190 "from" => doc[:from],
192 "message-id" => doc[:message_id],
193 "references" => doc[:refs],
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
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
206 return false if contains? m
209 if m.source.is_a? Integer
212 m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
215 to = (m.to + m.cc + m.bcc).map { |x| x.email }.join(" ")
218 :source_id => source_id,
219 :source_info => m.source_info,
220 :date => m.date.to_indexable_s,
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(" "),
230 @index.add_document d
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
238 def drop_entry docno; @index.delete docno; end
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]]
247 def load_contacts emails, h={}
248 q = Ferret::Search::BooleanQuery.new true
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
255 q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
257 Redwood::log "contact search: #{q}"
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]
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 }
270 #Redwood::log "adding from #{f} because there's a message from him to #{t}"
271 contacts[Person.for(f)] = true
275 contacts.keys.compact
280 def parse_user_query_string str; @qparser.parse str; end
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
292 query.add_query q2, :must
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)
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
305 def save_sources fn=Redwood::SOURCE_FN
306 if @sources_dirty || @sources.any? { |id, s| s.dirty? }
310 FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(bakfn) > File.size(fn)
312 Redwood::save_yaml_obj @sources.values, fn
315 @sources_dirty = false