2014-04-19 22:37:11 +00:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"labix.org/v2/mgo"
|
|
|
|
"labix.org/v2/mgo/bson"
|
|
|
|
"github.com/ian-kent/MailHog/mailhog/data"
|
|
|
|
"github.com/ian-kent/MailHog/mailhog"
|
|
|
|
)
|
|
|
|
|
2014-04-20 19:33:42 +00:00
|
|
|
type MongoDB struct {
|
|
|
|
Session *mgo.Session
|
|
|
|
Config *mailhog.Config
|
|
|
|
Collection *mgo.Collection
|
|
|
|
}
|
|
|
|
|
|
|
|
func CreateMongoDB(c *mailhog.Config) *MongoDB {
|
2014-04-20 14:35:59 +00:00
|
|
|
session, err := mgo.Dial(c.MongoUri)
|
2014-04-19 22:37:11 +00:00
|
|
|
if(err != nil) {
|
2014-04-20 19:33:42 +00:00
|
|
|
log.Fatalf("Error connecting to MongoDB: %s", err)
|
|
|
|
return nil
|
2014-04-19 22:37:11 +00:00
|
|
|
}
|
2014-04-20 19:33:42 +00:00
|
|
|
return &MongoDB{
|
|
|
|
Session: session,
|
|
|
|
Config: c,
|
|
|
|
Collection: session.DB(c.MongoDb).C(c.MongoColl),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mongo *MongoDB) Store(m *data.SMTPMessage) (string, error) {
|
|
|
|
msg := data.ParseSMTPMessage(mongo.Config, m)
|
|
|
|
err := mongo.Collection.Insert(msg)
|
2014-04-19 22:37:11 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error inserting message: %s", err)
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return msg.Id, nil
|
|
|
|
}
|
|
|
|
|
2014-04-20 19:33:42 +00:00
|
|
|
func (mongo *MongoDB) List(start int, limit int) (*data.Messages, error) {
|
2014-04-20 15:05:50 +00:00
|
|
|
messages := &data.Messages{}
|
2014-04-20 19:33:42 +00:00
|
|
|
err := mongo.Collection.Find(bson.M{}).Skip(start).Limit(limit).All(messages)
|
2014-04-20 15:05:50 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error loading messages: %s", err)
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return messages, nil;
|
|
|
|
}
|
|
|
|
|
2014-04-20 19:33:42 +00:00
|
|
|
func (mongo *MongoDB) DeleteOne(id string) error {
|
|
|
|
_, err := mongo.Collection.RemoveAll(bson.M{"id": id})
|
2014-04-20 16:09:06 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2014-04-20 19:33:42 +00:00
|
|
|
func (mongo *MongoDB) DeleteAll() error {
|
|
|
|
_, err := mongo.Collection.RemoveAll(bson.M{})
|
2014-04-20 16:09:06 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2014-04-20 19:33:42 +00:00
|
|
|
func (mongo *MongoDB) Load(id string) (*data.Message, error) {
|
2014-04-19 22:37:11 +00:00
|
|
|
result := &data.Message{}
|
2014-04-20 19:33:42 +00:00
|
|
|
err := mongo.Collection.Find(bson.M{"id": id}).One(&result)
|
2014-04-19 22:37:11 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error loading message: %s", err)
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return result, nil;
|
|
|
|
}
|