2017-10-06 07:19:02 +00:00
|
|
|
package contented
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2017-10-08 02:53:00 +00:00
|
|
|
"errors"
|
2017-10-06 07:19:02 +00:00
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/boltdb/bolt"
|
2017-10-08 02:53:00 +00:00
|
|
|
"github.com/speps/go-hashids"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
hashIdSalt = "contented"
|
|
|
|
hashIdMinLength = 2
|
2017-10-06 07:19:02 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Metadata struct {
|
2017-10-08 02:53:00 +00:00
|
|
|
FileHash string
|
2017-10-06 07:19:02 +00:00
|
|
|
FileSize int64
|
|
|
|
UploadTime time.Time
|
|
|
|
UploadIP string
|
|
|
|
Filename string
|
|
|
|
MimeType string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (this *Server) Metadata(fileID string) (*Metadata, error) {
|
|
|
|
var m Metadata
|
|
|
|
err := this.db.View(func(tx *bolt.Tx) error {
|
|
|
|
content := tx.Bucket(this.metadataBucket).Get([]byte(fileID))
|
|
|
|
if len(content) == 0 {
|
|
|
|
return os.ErrNotExist
|
|
|
|
}
|
|
|
|
|
|
|
|
return json.Unmarshal(content, &m)
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &m, nil
|
|
|
|
}
|
|
|
|
|
2017-10-08 02:53:00 +00:00
|
|
|
func idToString(v uint64) string {
|
|
|
|
hd := hashids.NewData()
|
|
|
|
hd.Salt = hashIdSalt
|
|
|
|
hd.MinLength = hashIdMinLength
|
|
|
|
h, _ := hashids.NewWithData(hd)
|
|
|
|
s, _ := h.EncodeInt64([]int64{int64(v)})
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
|
|
|
func (this *Server) AddMetadata(m Metadata) (string, error) {
|
2017-10-06 07:19:02 +00:00
|
|
|
jb, err := json.Marshal(m)
|
|
|
|
if err != nil {
|
2017-10-08 02:53:00 +00:00
|
|
|
return "", err
|
2017-10-06 07:19:02 +00:00
|
|
|
}
|
|
|
|
|
2017-10-08 02:53:00 +00:00
|
|
|
var shortRef string = ""
|
|
|
|
|
|
|
|
err = this.db.Update(func(tx *bolt.Tx) error {
|
|
|
|
b := tx.Bucket(this.metadataBucket)
|
|
|
|
seq, _ := b.NextSequence() // cannot fail
|
|
|
|
shortRef = idToString(seq)
|
|
|
|
return tx.Bucket(this.metadataBucket).Put([]byte(shortRef), jb)
|
2017-10-06 07:19:02 +00:00
|
|
|
})
|
2017-10-08 02:53:00 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
if shortRef == "" {
|
|
|
|
return "", errors.New("Invalid URL generated")
|
|
|
|
}
|
|
|
|
|
|
|
|
return shortRef, nil
|
2017-10-06 07:19:02 +00:00
|
|
|
}
|