- my $tid;
- if (@refs) {
- @refs = map { mid_compressed($_) } @refs;
- my %uniq;
- @refs = grep { !$uniq{$_}++ } @refs; # uniq
-
- $doc->add_term(xpfx('inreplyto') . $refs[-1]);
-
- my $ref_pfx = xpfx('references');
-
- # first ref *should* be the thread root,
- # but we can never trust clients to do the right thing
- my $ref = shift @refs;
- $doc->add_term($ref_pfx . $ref);
- $tid = $self->_resolve_mid_to_tid($ref);
-
- # the rest of the refs should point to this tid:
- foreach $ref (@refs) {
- $doc->add_term($ref_pfx . $ref);
- my $ptid = $self->_resolve_mid_to_tid($ref);
- if ($tid ne $ptid) {
- $self->merge_threads($tid, $ptid);
- }
- }
- } else {
- $tid = $self->next_thread_id;
- }
- $doc->add_term(xpfx('thread') . $tid);
-}
-
-sub lookup_message {
- my ($self, $mid) = @_;
- $mid = mid_clean($mid);
- $mid = mid_compressed($mid);
-
- my $doc_id = $self->find_unique_doc_id('mid', $mid);
- my $smsg;
- if (defined $doc_id) {
- # raises on error:
- my $doc = $self->{xdb}->get_document($doc_id);
- $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
- $smsg->doc_id($doc_id);
- }
- $smsg;
-}
-
-sub find_unique_doc_id {
- my ($self, $term, $value) = @_;
-
- my ($begin, $end) = $self->find_doc_ids($term, $value);
-
- return undef if $begin->equal($end); # not found
-
- my $rv = $begin->get_docid;
-
- # sanity check
- $begin->inc;
- $begin->equal($end) or die "Term '$term:$value' is not unique\n";
- $rv;
-}
-
-# returns begin and end PostingIterator
-sub find_doc_ids {
- my ($self, $term, $value) = @_;
-
- $self->find_doc_ids_for_term(xpfx($term) . $value);
-}
-
-# returns begin and end PostingIterator
-sub find_doc_ids_for_term {
- my ($self, $term) = @_;
- my $db = $self->{xdb};
-
- ($db->postlist_begin($term), $db->postlist_end($term));
-}
-
-# this will create a ghost as necessary
-sub _resolve_mid_to_tid {
- my ($self, $mid) = @_;
-
- my $smsg = $self->lookup_message($mid) || $self->create_ghost($mid);
- $smsg->thread_id;
-}
-
-sub create_ghost {
- my ($self, $mid, $tid) = @_;
-
- $mid = mid_compressed($mid);
- $tid = $self->next_thread_id unless defined $tid;
-
- my $doc = Search::Xapian::Document->new;
- $doc->add_term(xpfx('mid') . $mid);
- $doc->add_term(xpfx('thread') . $tid);
- $doc->add_term(xpfx('type') . 'ghost');
-
- my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
- $self->link_message($smsg, 1);
- $self->{xdb}->add_document($doc);
-
- $smsg;
-}
-
-sub merge_threads {
- my ($self, $winner_tid, $loser_tid) = @_;
- my ($head, $tail) = $self->find_doc_ids('thread', $loser_tid);
- my $thread_pfx = xpfx('thread');
- my $db = $self->{xdb};
-
- for (; $head != $tail; $head->inc) {
- my $docid = $head->get_docid;
- my $doc = $db->get_document($docid);
- $doc->remove_term($thread_pfx . $loser_tid);
- $doc->add_term($thread_pfx . $winner_tid);
- $db->replace_document($docid, $doc);