lib/sup/index.rb (29039B) - raw
1 ENV["XAPIAN_FLUSH_THRESHOLD"] = "1000"
2 ENV["XAPIAN_CJK_NGRAM"] = "1"
3
4 require 'xapian'
5 require 'set'
6 require 'fileutils'
7 require 'monitor'
8 require 'chronic'
9
10 require "sup/util/query"
11 require "sup/interactive_lock"
12 require "sup/hook"
13 require "sup/logger/singleton"
14
15
16 if ([Xapian.major_version, Xapian.minor_version, Xapian.revision] <=> [1,2,15]) < 0
17 fail <<-EOF
18 \n
19 Xapian version 1.2.15 or higher required.
20 If you have xapian-full-alaveteli installed,
21 Please remove it by running `gem uninstall xapian-full-alaveteli`
22 since it's been replaced by the xapian-ruby gem.
23
24 EOF
25 end
26
27 module Redwood
28
29 # This index implementation uses Xapian for searching and storage. It
30 # tends to be slightly faster than Ferret for indexing and significantly faster
31 # for searching due to precomputing thread membership.
32 class Index
33 include InteractiveLock
34
35 INDEX_VERSION = '4'
36
37 ## dates are converted to integers for xapian, and are used for document ids,
38 ## so we must ensure they're reasonably valid. this typically only affect
39 ## spam.
40 MIN_DATE = Time.at 0
41 MAX_DATE = Time.at(2**31-1)
42
43 HookManager.register "custom-search", <<EOS
44 Executes before a string search is applied to the index,
45 returning a new search string.
46 Variables:
47 subs: The string being searched.
48 EOS
49
50 class LockError < StandardError
51 def initialize h
52 @h = h
53 end
54
55 def method_missing m; @h[m.to_s] end
56 end
57
58 include Redwood::Singleton
59
60 def initialize dir=BASE_DIR
61 @dir = dir
62 FileUtils.mkdir_p @dir
63 @lock = Lockfile.new lockfile, :retries => 0, :max_age => nil
64 @sync_worker = nil
65 @sync_queue = Queue.new
66 @index_mutex = Monitor.new
67 end
68
69 def lockfile; File.join @dir, "lock" end
70
71 def lock
72 debug "locking #{lockfile}..."
73 begin
74 @lock.lock
75 rescue Lockfile::MaxTriesLockError
76 raise LockError, @lock.lockinfo_on_disk
77 end
78 end
79
80 def start_lock_update_thread
81 @lock_update_thread = Redwood::reporting_thread("lock update") do
82 while true
83 sleep 30
84 @lock.touch_yourself
85 end
86 end
87 end
88
89 def stop_lock_update_thread
90 @lock_update_thread.kill if @lock_update_thread
91 @lock_update_thread = nil
92 end
93
94 def unlock
95 if @lock && @lock.locked?
96 debug "unlocking #{lockfile}..."
97 @lock.unlock
98 end
99 end
100
101 def load failsafe=false
102 SourceManager.load_sources File.join(@dir, "sources.yaml")
103 load_index failsafe
104 end
105
106 def save
107 debug "saving index and sources..."
108 FileUtils.mkdir_p @dir unless File.exist? @dir
109 SourceManager.save_sources File.join(@dir, "sources.yaml")
110 save_index
111 end
112
113 def get_xapian
114 @xapian
115 end
116
117 def load_index failsafe=false
118 path = File.join(@dir, 'xapian')
119 if File.exist? path
120 @xapian = Xapian::WritableDatabase.new(path, Xapian::DB_OPEN)
121 db_version = @xapian.get_metadata 'version'
122 db_version = '0' if db_version.empty?
123 if false
124 info "Upgrading index format #{db_version} to #{INDEX_VERSION}"
125 @xapian.set_metadata 'version', INDEX_VERSION
126 elsif db_version != INDEX_VERSION
127 fail "This Sup version expects a v#{INDEX_VERSION} index, but you have an existing v#{db_version} index. Please run sup-dump to save your labels, move #{path} out of the way, and run sup-sync --restore."
128 end
129 else
130 @xapian = Xapian::WritableDatabase.new(path, Xapian::DB_CREATE)
131 @xapian.set_metadata 'version', INDEX_VERSION
132 @xapian.set_metadata 'rescue-version', '0'
133 end
134 @enquire = Xapian::Enquire.new @xapian
135 @enquire.weighting_scheme = Xapian::BoolWeight.new
136 @enquire.docid_order = Xapian::Enquire::ASCENDING
137 end
138
139 def add_message m; sync_message m, true end
140 def update_message m; sync_message m, true end
141 def update_message_state m; sync_message m[0], false, m[1] end
142
143 def save_index
144 info "Flushing Xapian updates to disk. This may take a while..."
145 @xapian.commit
146 end
147
148 def contains_id? id
149 synchronize { find_docid(id) && true }
150 end
151
152 def contains? m; contains_id? m.id end
153
154 def size
155 synchronize { @xapian.doccount }
156 end
157
158 def empty?; size == 0 end
159
160 ## Yields a message-id and message-building lambda for each
161 ## message that matches the given query, in descending date order.
162 ## You should probably not call this on a block that doesn't break
163 ## rather quickly because the results can be very large.
164 def each_id_by_date query={}
165 each_id(query) { |id| yield id, lambda { build_message id } }
166 end
167
168 ## Return the number of matches for query in the index
169 def num_results_for query={}
170 xapian_query = build_xapian_query query
171 matchset = run_query xapian_query, 0, 0, 100
172 matchset.matches_estimated
173 end
174
175 ## check if a message is part of a killed thread
176 ## (warning: duplicates code below)
177 ## NOTE: We can be more efficient if we assume every
178 ## killed message that hasn't been initially added
179 ## to the indexi s this way
180 def message_joining_killed? m
181 return false unless doc = find_doc(m.id)
182 queue = doc.value(THREAD_VALUENO).split(',')
183 seen_threads = Set.new
184 seen_messages = Set.new [m.id]
185 while not queue.empty?
186 thread_id = queue.pop
187 next if seen_threads.member? thread_id
188 return true if thread_killed?(thread_id)
189 seen_threads << thread_id
190 docs = term_docids(mkterm(:thread, thread_id)).map { |x| @xapian.document x }
191 docs.each do |doc|
192 msgid = doc.value MSGID_VALUENO
193 next if seen_messages.member? msgid
194 seen_messages << msgid
195 queue.concat doc.value(THREAD_VALUENO).split(',')
196 end
197 end
198 false
199 end
200
201 ## yield all messages in the thread containing 'm' by repeatedly
202 ## querying the index. yields pairs of message ids and
203 ## message-building lambdas, so that building an unwanted message
204 ## can be skipped in the block if desired.
205 ##
206 ## only two options, :limit and :skip_killed. if :skip_killed is
207 ## true, stops loading any thread if a message with a :killed flag
208 ## is found.
209 def each_message_in_thread_for m, opts={}
210 # TODO thread by subject
211 return unless doc = find_doc(m.id)
212 queue = doc.value(THREAD_VALUENO).split(',')
213 msgids = [m.id]
214 seen_threads = Set.new
215 seen_messages = Set.new [m.id]
216 while not queue.empty?
217 thread_id = queue.pop
218 next if seen_threads.member? thread_id
219 return false if opts[:skip_killed] && thread_killed?(thread_id)
220 seen_threads << thread_id
221 docs = term_docids(mkterm(:thread, thread_id)).map { |x| @xapian.document x }
222 docs.each do |doc|
223 msgid = doc.value MSGID_VALUENO
224 next if seen_messages.member? msgid
225 msgids << msgid
226 seen_messages << msgid
227 queue.concat doc.value(THREAD_VALUENO).split(',')
228 end
229 end
230 msgids.each { |id| yield id, lambda { build_message id } }
231 true
232 end
233
234 ## Load message with the given message-id from the index
235 def build_message id
236 entry = synchronize { get_entry id }
237 return unless entry
238
239 locations = entry[:locations].map do |source_id,source_info|
240 source = SourceManager[source_id]
241 raise "invalid source #{source_id}" unless source
242 Location.new source, source_info
243 end
244
245 m = Message.new :locations => locations,
246 :labels => entry[:labels],
247 :snippet => entry[:snippet]
248
249 # Try to find person from contacts before falling back to
250 # generating it from the address.
251 mk_person = lambda { |x| Person.from_name_and_email(*x.reverse!) }
252 entry[:from] = mk_person[entry[:from]]
253 entry[:to].map!(&mk_person)
254 entry[:cc].map!(&mk_person)
255 entry[:bcc].map!(&mk_person)
256
257 m.load_from_index! entry
258 m
259 end
260
261 ## Delete message with the given message-id from the index
262 def delete id
263 synchronize { @xapian.delete_document mkterm(:msgid, id) }
264 end
265
266 ## Given an array of email addresses, return an array of Person objects that
267 ## have sent mail to or received mail from any of the given addresses.
268 def load_contacts email_addresses, opts={}
269 contacts = Set.new
270 num = opts[:num] || 20
271 each_id_by_date :participants => email_addresses do |id,b|
272 break if contacts.size >= num
273 m = b.call
274 ([m.from]+m.to+m.cc+m.bcc).compact.each { |p| contacts << [p.name, p.email] }
275 end
276 contacts.to_a.compact[0...num].map { |n,e| Person.from_name_and_email n, e }
277 end
278
279 ## Yield each message-id matching query
280 EACH_ID_PAGE = 100
281 def each_id query={}, ignore_neg_terms = true
282 offset = 0
283 page = EACH_ID_PAGE
284
285 xapian_query = build_xapian_query query, ignore_neg_terms
286 while true
287 ids = run_query_ids xapian_query, offset, (offset+page)
288 ids.each { |id| yield id }
289 break if ids.size < page
290 offset += page
291 end
292 end
293
294 ## Yield each message matching query
295 ## The ignore_neg_terms parameter is used to display result even if
296 ## it contains "forbidden" labels such as :deleted, it is used in
297 ## Poll#poll_from when we need to get the location of a message that
298 ## may contain these labels
299 def each_message query={}, ignore_neg_terms = true, &b
300 each_id query, ignore_neg_terms do |id|
301 yield build_message(id)
302 end
303 end
304
305 # Search messages. Returns an Enumerator.
306 def find_messages query_expr
307 enum_for :each_message, parse_query(query_expr)
308 end
309
310 # wrap all future changes inside a transaction so they're done atomically
311 def begin_transaction
312 synchronize { @xapian.begin_transaction }
313 end
314
315 # complete the transaction and write all previous changes to disk
316 def commit_transaction
317 synchronize { @xapian.commit_transaction }
318 end
319
320 # abort the transaction and revert all changes made since begin_transaction
321 def cancel_transaction
322 synchronize { @xapian.cancel_transaction }
323 end
324
325 ## xapian-compact takes too long, so this is a no-op
326 ## until we think of something better
327 def optimize
328 end
329
330 ## Return the id source of the source the message with the given message-id
331 ## was synced from
332 def source_for_id id
333 synchronize { get_entry(id)[:source_id] }
334 end
335
336 ## Yields each term in the index that starts with prefix
337 def each_prefixed_term prefix
338 term = @xapian._dangerous_allterms_begin prefix
339 lastTerm = @xapian._dangerous_allterms_end prefix
340 until term.equals lastTerm
341 yield term.term
342 term.next
343 end
344 nil
345 end
346
347 ## Yields (in lexicographical order) the source infos of all locations from
348 ## the given source with the given source_info prefix
349 def each_source_info source_id, prefix='', &b
350 p = mkterm :location, source_id, prefix
351 each_prefixed_term p do |x|
352 yield prefix + x[p.length..-1]
353 end
354 end
355
356 class ParseError < StandardError; end
357
358 # Stemmed
359 NORMAL_PREFIX = {
360 'subject' => {:prefix => 'S', :exclusive => false},
361 'body' => {:prefix => 'B', :exclusive => false},
362 'from_name' => {:prefix => 'FN', :exclusive => false},
363 'to_name' => {:prefix => 'TN', :exclusive => false},
364 'name' => {:prefix => %w(FN TN), :exclusive => false},
365 'attachment' => {:prefix => 'A', :exclusive => false},
366 'email_text' => {:prefix => 'E', :exclusive => false},
367 '' => {:prefix => %w(S B FN TN A E), :exclusive => false},
368 }
369
370 # Unstemmed
371 BOOLEAN_PREFIX = {
372 'type' => {:prefix => 'K', :exclusive => true},
373 'from_email' => {:prefix => 'FE', :exclusive => false},
374 'to_email' => {:prefix => 'TE', :exclusive => false},
375 'email' => {:prefix => %w(FE TE), :exclusive => false},
376 'date' => {:prefix => 'D', :exclusive => true},
377 'label' => {:prefix => 'L', :exclusive => false},
378 'source_id' => {:prefix => 'I', :exclusive => true},
379 'attachment_extension' => {:prefix => 'O', :exclusive => false},
380 'msgid' => {:prefix => 'Q', :exclusive => true},
381 'id' => {:prefix => 'Q', :exclusive => true},
382 'thread' => {:prefix => 'H', :exclusive => false},
383 'ref' => {:prefix => 'R', :exclusive => false},
384 'location' => {:prefix => 'J', :exclusive => false},
385 }
386
387 PREFIX = NORMAL_PREFIX.merge BOOLEAN_PREFIX
388
389 COMPL_OPERATORS = %w[AND OR NOT]
390 COMPL_PREFIXES = (
391 %w[
392 from to
393 is has label
394 filename filetypem
395 before on in during after
396 limit
397 ] + NORMAL_PREFIX.keys + BOOLEAN_PREFIX.keys
398 ).map{|p|"#{p}:"} + COMPL_OPERATORS
399
400 ## parse a query string from the user. returns a query object
401 ## that can be passed to any index method with a 'query'
402 ## argument.
403 ##
404 ## raises a ParseError if something went wrong.
405 def parse_query s
406 query = {}
407
408 subs = HookManager.run("custom-search", :subs => s) || s
409
410 subs = "type:mail #{subs}"
411
412 begin
413 subs = SearchManager.expand subs
414 rescue SearchManager::ExpansionError => e
415 raise ParseError, e.message
416 end
417
418 subs = subs.gsub(/\b(to|from):(\S+)\b/) do
419 field, value = $1, $2
420 email_field, name_field = %w(email name).map { |x| "#{field}_#{x}" }
421 if(p = ContactManager.contact_for(value))
422 "#{email_field}:#{p.email}"
423 elsif value == "me"
424 '(' + AccountManager.user_emails.map { |e| "#{email_field}:#{e}" }.join(' OR ') + ')'
425 else
426 "(#{email_field}:#{value} OR #{name_field}:#{value})"
427 end
428 end
429
430 ## gmail style "is" operator
431 subs = subs.gsub(/\b(is|has):(\S+)\b/) do
432 _field, label = $1, $2
433 case label
434 when "read"
435 "-label:unread"
436 when "spam"
437 query[:load_spam] = true
438 "label:spam"
439 when "deleted"
440 query[:load_deleted] = true
441 "label:deleted"
442 else
443 "label:#{$2}"
444 end
445 end
446
447 ## labels are stored lower-case in the index
448 subs = subs.gsub(/\blabel:(\S+)\b/) do
449 label = $1
450 "label:#{label.downcase}"
451 end
452
453 ## if we see a label:deleted or a label:spam term anywhere in the query
454 ## string, we set the extra load_spam or load_deleted options to true.
455 ## bizarre? well, because the query allows arbitrary parenthesized boolean
456 ## expressions, without fully parsing the query, we can't tell whether
457 ## the user is explicitly directing us to search spam messages or not.
458 ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
459 ## search spam messages or not?
460 ##
461 ## so, we rely on the fact that turning these extra options ON turns OFF
462 ## the adding of "-label:deleted" or "-label:spam" terms at the very
463 ## final stage of query processing. if the user wants to search spam
464 ## messages, not adding that is the right thing; if he doesn't want to
465 ## search spam messages, then not adding it won't have any effect.
466 query[:load_spam] = true if subs =~ /\blabel:spam\b/
467 query[:load_deleted] = true if subs =~ /\blabel:deleted\b/
468 query[:load_killed] = true if subs =~ /\blabel:killed\b/
469
470 ## gmail style attachments "filename" and "filetype" searches
471 subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
472 field, name = $1, ($3 || $4)
473 case field
474 when "filename"
475 debug "filename: translated #{field}:#{name} to attachment:\"#{name.downcase}\""
476 "attachment:\"#{name.downcase}\""
477 when "filetype"
478 debug "filetype: translated #{field}:#{name} to attachment_extension:#{name.downcase}"
479 "attachment_extension:#{name.downcase}"
480 end
481 end
482
483 lastdate = 2<<32 - 1
484 firstdate = 0
485 subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
486 field, datestr = $1, ($3 || $4)
487 realdate = Chronic.parse datestr, :guess => false, :context => :past
488 if realdate
489 case field
490 when "after"
491 debug "chronic: translated #{field}:#{datestr} to #{realdate.end}"
492 "date:#{realdate.end.to_i}..#{lastdate}"
493 when "before"
494 debug "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
495 "date:#{firstdate}..#{realdate.end.to_i}"
496 else
497 debug "chronic: translated #{field}:#{datestr} to #{realdate}"
498 "date:#{realdate.begin.to_i}..#{realdate.end.to_i}"
499 end
500 else
501 raise ParseError, "can't understand date #{datestr.inspect}"
502 end
503 end
504
505 ## limit:42 restrict the search to 42 results
506 subs = subs.gsub(/\blimit:(\S+)\b/) do
507 lim = $1
508 if lim =~ /^\d+$/
509 query[:limit] = lim.to_i
510 ''
511 else
512 raise ParseError, "non-numeric limit #{lim.inspect}"
513 end
514 end
515
516 debug "translated query: #{subs.inspect}"
517
518 qp = Xapian::QueryParser.new
519 qp.database = @xapian
520 qp.stemmer = Xapian::Stem.new($config[:stem_language])
521 qp.stemming_strategy = Xapian::QueryParser::STEM_SOME
522 qp.default_op = Xapian::Query::OP_AND
523 begin
524 rangeprocessor = Xapian::NumberRangeProcessor.new DATE_VALUENO, 'date:'
525 qp.add_rangeprocessor rangeprocessor
526 rescue NameError # xapian < 1.3
527 valuerangeprocessor = Xapian::NumberValueRangeProcessor.new DATE_VALUENO, 'date:', true
528 qp.add_valuerangeprocessor valuerangeprocessor
529 end
530 NORMAL_PREFIX.each { |k,info| info[:prefix].each {
531 |v| qp.add_prefix k, v }
532 }
533 BOOLEAN_PREFIX.each { |k,info| info[:prefix].each {
534 |v| qp.add_boolean_prefix k, v, info[:exclusive] }
535 }
536
537 begin
538 xapian_query = qp.parse_query(subs, Xapian::QueryParser::FLAG_PHRASE |
539 Xapian::QueryParser::FLAG_BOOLEAN |
540 Xapian::QueryParser::FLAG_LOVEHATE |
541 Xapian::QueryParser::FLAG_WILDCARD)
542 rescue RuntimeError => e
543 raise ParseError, "xapian query parser error: #{e}"
544 end
545
546 debug "parsed xapian query: #{Util::Query.describe(xapian_query, subs)}"
547
548 if xapian_query.nil? or xapian_query.empty?
549 raise ParseError, "couldn't parse \"#{s}\" as xapian query " \
550 "(special characters aren't indexed)"
551 end
552
553 query[:qobj] = xapian_query
554 query[:text] = s
555 query
556 end
557
558 def save_message m, sync_back = true
559 if @sync_worker
560 @sync_queue << [m, sync_back]
561 else
562 update_message_state [m, sync_back]
563 end
564 m.clear_dirty
565 end
566
567 def save_thread t, sync_back = true
568 t.each_dirty_message do |m|
569 save_message m, sync_back
570 end
571 end
572
573 def start_sync_worker
574 @sync_worker = Redwood::reporting_thread('index sync') { run_sync_worker }
575 end
576
577 def stop_sync_worker
578 return unless worker = @sync_worker
579 @sync_worker = nil
580 @sync_queue << :die
581 worker.join
582 end
583
584 def run_sync_worker
585 while m = @sync_queue.deq
586 return if m == :die
587 update_message_state m
588 # Necessary to keep Xapian calls from lagging the UI too much.
589 sleep 0.03
590 end
591 end
592
593 private
594
595 MSGID_VALUENO = 0
596 THREAD_VALUENO = 1
597 DATE_VALUENO = 2
598
599 MAX_TERM_LENGTH = 245
600
601 # Xapian can very efficiently sort in ascending docid order. Sup always wants
602 # to sort by descending date, so this method maps between them. In order to
603 # handle multiple messages per second, we use a logistic curve centered
604 # around MIDDLE_DATE so that the slope (docid/s) is greatest in this time
605 # period. A docid collision is not an error - the code will pick the next
606 # smallest unused one.
607 DOCID_SCALE = 2.0**32
608 TIME_SCALE = 2.0**27
609 MIDDLE_DATE = Time.gm(2011)
610 def assign_docid m, truncated_date
611 t = (truncated_date.to_i - MIDDLE_DATE.to_i).to_f
612 docid = (DOCID_SCALE - DOCID_SCALE/(Math::E**(-(t/TIME_SCALE)) + 1)).to_i
613 while docid > 0 and docid_exists? docid
614 docid -= 1
615 end
616 docid > 0 ? docid : nil
617 end
618
619 # XXX is there a better way?
620 def docid_exists? docid
621 begin
622 @xapian.doclength docid
623 true
624 rescue RuntimeError #Xapian::DocNotFoundError
625 raise unless $!.message =~ /DocNotFoundError/
626 false
627 end
628 end
629
630 def term_docids term
631 @xapian.postlist(term).map { |x| x.docid }
632 end
633
634 def find_docid id
635 docids = term_docids(mkterm(:msgid,id))
636 fail unless docids.size <= 1
637 docids.first
638 end
639
640 def find_doc id
641 return unless docid = find_docid(id)
642 @xapian.document docid
643 end
644
645 def get_id docid
646 return unless doc = @xapian.document(docid)
647 doc.value MSGID_VALUENO
648 end
649
650 def get_entry id
651 return unless doc = find_doc(id)
652 doc.entry
653 end
654
655 def thread_killed? thread_id
656 not run_query(Q.new(Q::OP_AND, mkterm(:thread, thread_id), mkterm(:label, :Killed)), 0, 1).empty?
657 end
658
659 def synchronize &b
660 @index_mutex.synchronize(&b)
661 end
662
663 def run_query xapian_query, offset, limit, checkatleast=0
664 synchronize do
665 @enquire.query = xapian_query
666 @enquire.mset(offset, limit-offset, checkatleast)
667 end
668 end
669
670 def run_query_ids xapian_query, offset, limit
671 matchset = run_query xapian_query, offset, limit
672 matchset.matches.map { |r| r.document.value MSGID_VALUENO }
673 end
674
675 Q = Xapian::Query
676 def build_xapian_query opts, ignore_neg_terms = true
677 labels = ([opts[:label]] + (opts[:labels] || [])).compact
678 neglabels = [:spam, :deleted, :killed].reject { |l| (labels.include? l) || opts.member?("load_#{l}".intern) }
679 pos_terms, neg_terms = [], []
680
681 ## workaround for https://trac.xapian.org/ticket/855
682 #pos_terms << mkterm(:type, 'mail')
683 pos_terms << Q::MatchAll
684 pos_terms.concat(labels.map { |l| mkterm(:label,l) })
685 pos_terms << opts[:qobj] if opts[:qobj]
686 pos_terms << mkterm(:source_id, opts[:source_id]) if opts[:source_id]
687 pos_terms << mkterm(:location, *opts[:location]) if opts[:location]
688
689 if opts[:participants]
690 participant_terms = opts[:participants].map { |p| [:from,:to].map { |d| mkterm(:email, d, (Redwood::Person === p) ? p.email : p) } }.flatten
691 pos_terms << Q.new(Q::OP_OR, participant_terms)
692 end
693
694 neg_terms.concat(neglabels.map { |l| mkterm(:label,l) }) if ignore_neg_terms
695
696 pos_query = Q.new(Q::OP_AND, pos_terms)
697 neg_query = Q.new(Q::OP_OR, neg_terms)
698
699 if neg_query.empty?
700 pos_query
701 else
702 Q.new(Q::OP_AND_NOT, [pos_query, neg_query])
703 end
704 end
705
706 def sync_message m, overwrite, sync_back = true
707 ## TODO: we should not save the message if the sync_back failed
708 ## since it would overwrite the location field
709 m.sync_back if sync_back
710
711 doc = synchronize { find_doc(m.id) }
712 existed = doc != nil
713 doc ||= Xapian::Document.new
714 do_index_static = overwrite || !existed
715 old_entry = !do_index_static && doc.entry
716 snippet = do_index_static ? m.snippet : old_entry[:snippet]
717
718 entry = {
719 :message_id => m.id,
720 :locations => m.locations.map { |x| [x.source.id, x.info] },
721 :date => truncate_date(m.date),
722 :snippet => snippet,
723 :labels => m.labels.to_a,
724 :from => [m.from.email, m.from.name],
725 :to => m.to.map { |p| [p.email, p.name] },
726 :cc => m.cc.map { |p| [p.email, p.name] },
727 :bcc => m.bcc.map { |p| [p.email, p.name] },
728 :subject => m.subj,
729 :refs => m.refs.to_a,
730 :replytos => m.replytos.to_a,
731 }
732
733 if do_index_static
734 doc.clear_terms
735 doc.clear_values
736 index_message_static m, doc, entry
737 end
738
739 index_message_locations doc, entry, old_entry
740 index_message_threading doc, entry, old_entry
741 index_message_labels doc, entry[:labels], (do_index_static ? [] : old_entry[:labels])
742 doc.entry = entry
743
744 synchronize do
745 unless docid = existed ? doc.docid : assign_docid(m, truncate_date(m.date))
746 # Could be triggered by spam
747 warn "docid underflow, dropping #{m.id.inspect}"
748 return
749 end
750 @xapian.replace_document docid, doc
751 end
752
753 m.labels.each { |l| LabelManager << l }
754 true
755 end
756
757 ## Index content that can't be changed by the user
758 def index_message_static m, doc, entry
759 # Person names are indexed with several prefixes
760 person_termer = lambda do |d|
761 lambda do |p|
762 doc.index_text p.name, PREFIX["#{d}_name"][:prefix] if p.name
763 doc.index_text p.email, PREFIX['email_text'][:prefix]
764 doc.add_term mkterm(:email, d, p.email)
765 end
766 end
767
768 person_termer[:from][m.from] if m.from
769 (m.to+m.cc+m.bcc).each(&(person_termer[:to]))
770
771 # Full text search content
772 subject_text = m.indexable_subject
773 body_text = m.indexable_body
774 doc.index_text subject_text, PREFIX['subject'][:prefix]
775 doc.index_text body_text, PREFIX['body'][:prefix]
776 m.attachments.each { |a| doc.index_text a, PREFIX['attachment'][:prefix] }
777
778 # Miscellaneous terms
779 doc.add_term mkterm(:date, m.date) if m.date
780 doc.add_term mkterm(:type, 'mail')
781 doc.add_term mkterm(:msgid, m.id)
782 m.attachments.each do |a|
783 a =~ /\.(\w+)$/ or next
784 doc.add_term mkterm(:attachment_extension, $1)
785 end
786
787 # Date value for range queries
788 date_value = begin
789 Xapian.sortable_serialise m.date.to_i
790 rescue TypeError
791 Xapian.sortable_serialise 0
792 end
793
794 doc.add_value MSGID_VALUENO, m.id
795 doc.add_value DATE_VALUENO, date_value
796 end
797
798 def index_message_locations doc, entry, old_entry
799 old_entry[:locations].map { |x| x[0] }.uniq.each { |x| doc.remove_term mkterm(:source_id, x) } if old_entry
800 entry[:locations].map { |x| x[0] }.uniq.each { |x| doc.add_term mkterm(:source_id, x) }
801 old_entry[:locations].each { |x| (doc.remove_term mkterm(:location, *x) rescue nil) } if old_entry
802 entry[:locations].each { |x| doc.add_term mkterm(:location, *x) }
803 end
804
805 def index_message_labels doc, new_labels, old_labels
806 return if new_labels == old_labels
807 added = new_labels.to_a - old_labels.to_a
808 removed = old_labels.to_a - new_labels.to_a
809 added.each { |t| doc.add_term mkterm(:label,t) }
810 removed.each { |t| doc.remove_term mkterm(:label,t) }
811 end
812
813 ## Assign a set of thread ids to the document. This is a hybrid of the runtime
814 ## search done by the Ferret index and the index-time union done by previous
815 ## versions of the Xapian index. We first find the thread ids of all messages
816 ## with a reference to or from us. If that set is empty, we use our own
817 ## message id. Otherwise, we use all the thread ids we previously found. In
818 ## the common case there's only one member in that set, but if we're the
819 ## missing link between multiple previously unrelated threads we can have
820 ## more. XapianIndex#each_message_in_thread_for follows the thread ids when
821 ## searching so the user sees a single unified thread.
822 def index_message_threading doc, entry, old_entry
823 return if old_entry && (entry[:refs] == old_entry[:refs]) && (entry[:replytos] == old_entry[:replytos])
824 children = term_docids(mkterm(:ref, entry[:message_id])).map { |docid| @xapian.document docid }
825 parent_ids = entry[:refs] + entry[:replytos]
826 parents = parent_ids.map { |id| find_doc id }.compact
827 thread_members = SavingHash.new { [] }
828 (children + parents).each do |doc2|
829 thread_ids = doc2.value(THREAD_VALUENO).split ','
830 thread_ids.each { |thread_id| thread_members[thread_id] << doc2 }
831 end
832 thread_ids = thread_members.empty? ? [entry[:message_id]] : thread_members.keys
833 thread_ids.each { |thread_id| doc.add_term mkterm(:thread, thread_id) }
834 parent_ids.each { |ref| doc.add_term mkterm(:ref, ref) }
835 doc.add_value THREAD_VALUENO, (thread_ids * ',')
836 end
837
838 def truncate_date date
839 if date < MIN_DATE
840 debug "warning: adjusting too-low date #{date} for indexing"
841 MIN_DATE
842 elsif date > MAX_DATE
843 debug "warning: adjusting too-high date #{date} for indexing"
844 MAX_DATE
845 else
846 date
847 end
848 end
849
850 # Construct a Xapian term
851 def mkterm type, *args
852 case type
853 when :label
854 PREFIX['label'][:prefix] + args[0].to_s.downcase
855 when :type
856 PREFIX['type'][:prefix] + args[0].to_s.downcase
857 when :date
858 PREFIX['date'][:prefix] + args[0].getutc.strftime("%Y%m%d%H%M%S")
859 when :email
860 case args[0]
861 when :from then PREFIX['from_email'][:prefix]
862 when :to then PREFIX['to_email'][:prefix]
863 else raise "Invalid email term type #{args[0]}"
864 end + args[1].to_s.downcase
865 when :source_id
866 PREFIX['source_id'][:prefix] + args[0].to_s.downcase
867 when :location
868 PREFIX['location'][:prefix] + [args[0]].pack('n') + args[1].to_s
869 when :attachment_extension
870 PREFIX['attachment_extension'][:prefix] + args[0].to_s.downcase
871 when :msgid, :ref, :thread
872 PREFIX[type.to_s][:prefix] + args[0][0...(MAX_TERM_LENGTH-1)]
873 else
874 raise "Invalid term type #{type}"
875 end
876 end
877 end
878
879 end
880
881 class Xapian::Document
882 def entry
883 Marshal.load data
884 end
885
886 def entry=(x)
887 self.data = Marshal.dump x
888 end
889
890 def index_text text, prefix, weight=1
891 term_generator = Xapian::TermGenerator.new
892 term_generator.stemmer = Xapian::Stem.new($config[:stem_language])
893 term_generator.document = self
894 term_generator.index_text text, weight, prefix
895 end
896
897 alias old_add_term add_term
898 def add_term term
899 if term.length <= Redwood::Index::MAX_TERM_LENGTH
900 old_add_term term, 0
901 else
902 warn "dropping excessively long term #{term}"
903 end
904 end
905 end