added mongodb storage engine
[p5sagit/Email-Archive.git] / lib / Email / Archive / Storage / MongoDB.pm
1 package Email::Archive::Storage::MongoDB;
2 use Moo;
3 use Carp;
4 use Email::MIME;
5 use Email::Abstract;
6 use MongoDB;
7 use autodie;
8 with q/Email::Archive::Storage/;
9
10 has host => (
11     is => 'rw',
12     default => 'localhost',
13 );
14
15 has port => (
16     is => 'rw',
17     default => 27017,
18 );
19
20 has database => (
21     is => 'rw',
22 );
23
24 has collection => (
25     is => 'rw',
26 );
27
28 sub store {
29   my ($self, $email) = @_;
30   $email = Email::Abstract->new($email);
31   $self->collection->insert({
32     message_id => $email->get_header('Message-ID'),
33     from_addr  => $email->get_header('From'),
34     to_addr    => $email->get_header('To'),
35     date       => $email->get_header('Date'),
36     subject    => $email->get_header('Subject'),
37     body       => $email->get_body,
38   });
39 }
40
41 sub search {
42   my ($self, $attribs) = @_;
43   my $message = $self->collection->find_one($attribs);
44
45   return Email::MIME->create(
46     header => [
47       From    => $message->{from_addr},
48       To      => $message->{to_addr},
49       Subject => $message->{subject},
50     ],
51     body => $message->{body},
52   );
53 }
54
55 sub retrieve {
56   my ($self, $message_id) = @_;
57   $self->search({ message_id => $message_id });
58 }
59
60 sub storage_connect {
61   my ($self, $mongo_con_info) = @_;
62   if (defined $mongo_con_info){
63     # should look like host:port:database
64     my ($host, $port, $database, $collection) = split ':', $mongo_con_info;
65     $self->host($host);
66     $self->port($port);
67     $self->database($database);
68     $self->collection($collection);
69   }
70
71   my $conn = MongoDB::Connection->new(
72     host => $self->host,
73     port => $self->port,
74   );
75
76   my $datab = $self->database;
77   my $collec = $self->collection;
78
79   my $db = $conn->$datab;
80   my $coll = $db->$collec;
81
82   # replace name with actual collection object
83   $self->collection($coll);
84
85   return 1;
86 }