forked from sunfmin/tenpu
/
tenpu.go
113 lines (96 loc) · 2.55 KB
/
tenpu.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package tenpu
import (
"github.com/sunfmin/mgodb"
"io"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"path"
)
var CollectionName = "attachments"
type Storage interface {
Put(filename string, contentType string, body io.Reader, attachment *Attachment) (err error)
Delete(attachment *Attachment) (err error)
Copy(attachment *Attachment, w io.Writer) (err error)
Find(collectionName string, query interface{}, result interface{}) (err error)
Database() *mgodb.Database
}
type Attachment struct {
Id string `bson:"_id"`
OwnerId string
Category string
Filename string
ContentType string
MD5 string
ContentLength int64
Error string
}
func (att *Attachment) MakeId() interface{} {
return att.Id
}
func (att *Attachment) IsImage() (r bool) {
switch att.ContentType {
default:
r = false
case "image/png", "image/jpeg", "image/gif":
r = true
}
return
}
func (att *Attachment) Extname() (r string) {
r = path.Ext(att.Filename)
if len(r) > 0 {
r = r[1:]
}
return
}
func Attachments(ownerid string) (r []*Attachment) {
mgodb.CollectionDo(CollectionName, func(c *mgo.Collection) {
c.Find(bson.M{"ownerid": ownerid}).All(&r)
})
return
}
func AttachmentsByOwnerIds(ownerids []string) (r []*Attachment) {
mgodb.CollectionDo(CollectionName, func(c *mgo.Collection) {
c.Find(bson.M{"ownerid": bson.M{"$in": ownerids}}).All(&r)
})
return
}
func AttachmentById(id string) (r *Attachment) {
mgodb.CollectionDo(CollectionName, func(c *mgo.Collection) {
c.Find(bson.M{"_id": id}).One(&r)
})
return
}
func RemoveAttachmentById(id string) (err error) {
mgodb.CollectionDo(CollectionName, func(c *mgo.Collection) {
c.Remove(bson.M{"_id": id})
})
return
}
type DatabaseClient struct {
Database *mgodb.Database
}
func (dbc *DatabaseClient) Attachments(ownerid string) (r []*Attachment) {
dbc.Database.CollectionDo(CollectionName, func(c *mgo.Collection) {
c.Find(bson.M{"ownerid": ownerid}).All(&r)
})
return
}
func (dbc *DatabaseClient) AttachmentsByOwnerIds(ownerids []string) (r []*Attachment) {
dbc.Database.CollectionDo(CollectionName, func(c *mgo.Collection) {
c.Find(bson.M{"ownerid": bson.M{"$in": ownerids}}).All(&r)
})
return
}
func (dbc *DatabaseClient) AttachmentById(id string) (r *Attachment) {
dbc.Database.CollectionDo(CollectionName, func(c *mgo.Collection) {
c.Find(bson.M{"_id": id}).One(&r)
})
return
}
func (dbc *DatabaseClient) RemoveAttachmentById(id string) (err error) {
dbc.Database.CollectionDo(CollectionName, func(c *mgo.Collection) {
c.Remove(bson.M{"_id": id})
})
return
}