1
0
Fork 0
mirror of https://github.com/vbatts/imgsrv.git synced 2024-11-24 00:55:41 +00:00
imgsrv/db_fileutil.go

93 lines
2 KiB
Go
Raw Normal View History

2013-02-09 04:43:39 +00:00
package main
import (
"github.com/vbatts/imgsrv/hash"
2013-05-09 16:13:46 +00:00
"github.com/vbatts/imgsrv/types"
2013-08-06 00:29:16 +00:00
"labix.org/v2/mgo"
2013-03-27 20:30:24 +00:00
"labix.org/v2/mgo/bson"
2013-02-09 04:43:39 +00:00
)
2013-02-11 16:00:57 +00:00
/* gfs is a *mgo.GridFS defined in imgsrv.go */
2013-05-09 16:13:46 +00:00
func GetFileByFilename(filename string) (this_file types.File, err error) {
2013-03-27 20:30:24 +00:00
err = gfs.Find(bson.M{"filename": filename}).One(&this_file)
if err != nil {
return this_file, err
}
return this_file, nil
2013-02-11 16:00:57 +00:00
}
2013-05-09 16:13:46 +00:00
func GetFileRandom() (this_file types.File, err error) {
r := hash.Rand64()
2013-03-27 20:30:24 +00:00
err = gfs.Find(bson.M{"random": bson.M{"$gt": r}}).One(&this_file)
if err != nil {
return this_file, err
}
if len(this_file.Md5) == 0 {
err = gfs.Find(bson.M{"random": bson.M{"$lt": r}}).One(&this_file)
}
if err != nil {
return this_file, err
}
return this_file, nil
2013-02-11 16:00:57 +00:00
}
2013-05-09 16:13:46 +00:00
/* Check whether this types.File filename is on Mongo */
2013-02-09 04:43:39 +00:00
func HasFileByFilename(filename string) (exists bool, err error) {
2013-03-27 20:30:24 +00:00
c, err := gfs.Find(bson.M{"filename": filename}).Count()
if err != nil {
return false, err
}
exists = (c > 0)
return exists, nil
2013-02-09 04:43:39 +00:00
}
func HasFileByMd5(md5 string) (exists bool, err error) {
2013-03-27 20:30:24 +00:00
c, err := gfs.Find(bson.M{"md5": md5}).Count()
if err != nil {
return false, err
}
exists = (c > 0)
return exists, nil
2013-02-09 04:43:39 +00:00
}
func HasFileByKeyword(keyword string) (exists bool, err error) {
2013-03-27 20:30:24 +00:00
c, err := gfs.Find(bson.M{"metadata": bson.M{"keywords": keyword}}).Count()
if err != nil {
return false, err
}
exists = (c > 0)
return exists, nil
2013-02-09 04:43:39 +00:00
}
2013-08-06 00:29:16 +00:00
func GetKeywords() (kp []types.KeywordCount, err error) {
job := &mgo.MapReduce{
Map: `
function() {
if (!this.metadata.keywords) {
return;
}
for (index in this.metadata.keywords) {
emit(this.metadata.keywords[index], 1);
}
}
`,
Reduce: `
function(previous, current) {
var count = 0;
for (index in current) {
count += current[index];
}
return count;
}
`,
}
if _, err := gfs.Find(nil).MapReduce(job, &kp); err != nil {
return kp, err
}
return kp, nil
}