1 ## the index structure for redwood. interacts with ferret.
13 def initialize dir=BASE_DIR
16 @sources_dirty = false
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
22 @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer
24 self.class.i_am_the_instance self
33 Redwood::log "saving index and sources..."
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 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
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 ## Syncs the message to the index: deleting if it's already there,
77 ## and adding either way. Index state will be determined by m.labels.
79 ## docid and entry can be specified if they're already known.
80 def sync_message m, docid=nil, entry=nil
81 docid, entry = load_entry_for_id m.id unless docid && entry
83 raise "no source info for message #{m.id}" unless m.source && m.source_info
84 raise "trying deleting non-corresponding entry #{docid}" if docid && @index[docid][:message_id] != m.id
87 if m.source.is_a? Integer
88 raise "Debugging: integer source set"
91 m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
94 to = (m.to + m.cc + m.bcc).map { |x| x.email }.join(" ")
97 :source_id => source_id,
98 :source_info => m.source_info,
99 :date => m.date.to_indexable_s,
101 :snippet => m.snippet,
102 :label => m.labels.join(" "),
103 :from => m.from ? m.from.email : "",
104 :to => (m.to + m.cc + m.bcc).map { |x| x.email }.join(" "),
105 :subject => wrap_subj(Message.normalize_subj(m.subj)),
106 :refs => (m.refs + m.replytos).uniq.join(" "),
109 @index.delete docid if docid
110 @index.add_document d
112 docid, entry = load_entry_for_id m.id
113 ## this hasn't been triggered in a long time. TODO: decide whether it's still a problem.
114 raise "just added message #{m.id} but couldn't find it in a search" unless docid
118 def save_index fn=File.join(@dir, "ferret")
119 # don't have to do anything, apparently
123 @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0
125 def contains? m; contains_id? m.id; end
126 def size; @index.size; end
128 ## you should probably not call this on a block that doesn't break
129 ## rather quickly because the results can be very large.
130 EACH_BY_DATE_NUM = 100
131 def each_id_by_date opts={}
132 return if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
133 query = build_query opts
136 results = @index.search(query, :sort => "date DESC", :limit => EACH_BY_DATE_NUM, :offset => offset)
137 Redwood::log "got #{results.total_hits} results for query (offset #{offset}) #{query.inspect}"
138 results.hits.each { |hit| yield @index[hit.doc][:message_id], lambda { build_message hit.doc } }
139 break if offset >= results.total_hits - EACH_BY_DATE_NUM
140 offset += EACH_BY_DATE_NUM
144 def num_results_for opts={}
145 return 0 if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
147 index.search(q).total_hits
150 ## yield all messages in the thread containing 'm' by repeatedly
151 ## querying the index. uields pairs of message ids and
152 ## message-building lambdas, so that building an unwanted message
153 ## can be skipped in the block if desired.
155 ## stops loading any thread if a message with a :killed flag is found.
157 SAME_SUBJECT_DATE_LIMIT = 7
158 def each_message_in_thread_for m, opts={}
163 ## todo: make subject querying configurable
164 if true # do subject queries
165 date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
166 date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
168 q = Ferret::Search::BooleanQuery.new true
169 sq = Ferret::Search::PhraseQuery.new(:subject)
170 wrap_subj(Message.normalize_subj(m.subj)).split(/\s+/).each do |t|
173 q.add_query sq, :must
174 q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
176 q = build_query :qobj => q
178 pending = @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] }
179 Redwood::log "found #{pending.size} results for subject query #{q}"
184 until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
186 next if searched.member? id
188 q = Ferret::Search::BooleanQuery.new true
189 q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
190 q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
192 q = build_query :qobj => q, :load_killed => true
195 @index.search_each(q, :limit => :all) do |docid, score|
196 break if opts[:limit] && messages.size >= opts[:limit]
197 break if @index[docid][:label].split(/\s+/).include? "killed" unless opts[:load_killed]
198 mid = @index[docid][:message_id]
199 unless messages.member? mid
200 messages[mid] ||= lambda { build_message docid }
201 refs = @index[docid][:refs].split(" ")
206 Redwood::log "ran #{num_queries} queries to build thread of #{messages.size} messages for #{m.id}" if num_queries > 0
207 messages.each { |mid, builder| yield mid, builder }
210 ## builds a message object from a ferret result
211 def build_message docid
213 source = @sources[doc[:source_id].to_i]
214 #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
215 raise "invalid source #{doc[:source_id]}" unless source
218 "date" => Time.at(doc[:date].to_i),
219 "subject" => unwrap_subj(doc[:subject]),
220 "from" => doc[:from],
222 "message-id" => doc[:message_id],
223 "references" => doc[:refs],
226 Message.new :source => source, :source_info => doc[:source_info].to_i,
227 :labels => doc[:label].split(" ").map { |s| s.intern },
228 :snippet => doc[:snippet], :header => fake_header
231 def fresh_thread_id; @next_thread_id += 1; end
232 def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
233 def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
235 def drop_entry docno; @index.delete docno; end
237 def load_entry_for_id mid
238 results = @index.search(Ferret::Search::TermQuery.new(:message_id, mid))
239 return if results.total_hits == 0
240 docid = results.hits[0].doc
241 [docid, @index[docid]]
244 def load_contacts emails, h={}
245 q = Ferret::Search::BooleanQuery.new true
247 qq = Ferret::Search::BooleanQuery.new true
248 qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
249 qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
252 q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
254 Redwood::log "contact search: #{q}"
257 @index.search_each(q, :sort => "date DESC", :limit => :all) do |docid, score|
258 break if contacts.size >= num
259 #Redwood::log "got message with to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
260 f = @index[docid][:from]
261 t = @index[docid][:to]
263 if AccountManager.is_account_email? f
264 t.split(" ").each { |e| #Redwood::log "adding #{e} because there's a message to him from account email #{f}";
265 contacts[Person.for(e)] = true }
267 #Redwood::log "adding from #{f} because there's a message from him to #{t}"
268 contacts[Person.for(f)] = true
272 contacts.keys.compact
275 def load_sources fn=Redwood::SOURCE_FN
276 source_array = (Redwood::load_yaml_obj(fn) || []).map { |o| Recoverable.new o }
277 @sources = Hash[*(source_array).map { |s| [s.id, s] }.flatten]
278 @sources_dirty = false
283 def parse_user_query_string str; @qparser.parse str; end
285 query = Ferret::Search::BooleanQuery.new
286 query.add_query opts[:qobj], :must if opts[:qobj]
287 labels = ([opts[:label]] + (opts[:labels] || [])).compact
288 labels.each { |t| query.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
289 if opts[:participants]
290 q2 = Ferret::Search::BooleanQuery.new
291 opts[:participants].each do |p|
292 q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
293 q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
295 query.add_query q2, :must
298 query.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless opts[:load_spam] || labels.include?(:spam)
299 query.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless opts[:load_deleted] || labels.include?(:deleted)
300 query.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not unless opts[:load_killed] || labels.include?(:killed)
304 def save_sources fn=Redwood::SOURCE_FN
305 if @sources_dirty || @sources.any? { |id, s| s.dirty? }
309 FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(bakfn) > File.size(fn)
311 Redwood::save_yaml_obj @sources.values, fn
314 @sources_dirty = false