|
|
|
package domain
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"time"
|
|
|
|
"strconv"
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
type BogFileService struct {
|
|
|
|
user_agent_repo UserAgentRepository
|
|
|
|
file_data_repo FileDataRepository
|
|
|
|
default_allowance_bytes int64
|
|
|
|
default_allowance_duration time.Duration
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewBogFileService(
|
|
|
|
user_agent_repo UserAgentRepository,
|
|
|
|
file_data_repo FileDataRepository,
|
|
|
|
da_bytes int64,
|
|
|
|
da_duration time.Duration,
|
|
|
|
) BogFileService {
|
|
|
|
return BogFileService {user_agent_repo, file_data_repo, da_bytes, da_duration}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (b BogFileService) getOrCreateUA(useragent_in string) *UserAgent{
|
|
|
|
ua, err := b.user_agent_repo.GetByName(useragent_in)
|
|
|
|
|
|
|
|
if err == ErrNotExists {
|
|
|
|
new_ua := UserAgent {
|
|
|
|
0, useragent_in, time.Now(), b.default_allowance_duration, FileSizeQuota { b.default_allowance_bytes, 0 },
|
|
|
|
}
|
|
|
|
created_ua, err := b.user_agent_repo.Create(new_ua)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return created_ua
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return ua
|
|
|
|
}
|
|
|
|
|
|
|
|
func (b BogFileService) SaveFile(ref FileReference, src io.Reader, size int64) error {
|
|
|
|
user_agent := b.getOrCreateUA(ref.UserAgent)
|
|
|
|
|
|
|
|
if !user_agent.FileQuota.Allows(size) {
|
|
|
|
return ErrExceedQuota
|
|
|
|
}
|
|
|
|
|
|
|
|
f, err := b.file_data_repo.Create(ref.Path, strconv.FormatInt(user_agent.ID, 10))
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
io.Copy(f, src)
|
|
|
|
f.Close()
|
|
|
|
user_agent.FileQuota.Add(size)
|
|
|
|
b.user_agent_repo.Update(user_agent.ID, *user_agent)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (b BogFileService) OpenOutFile(ref FileReference) (BogOutFile, error) {
|
|
|
|
user_agent, err := b.user_agent_repo.GetByName(ref.UserAgent)
|
|
|
|
if err == ErrNotExists {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
f, err := b.file_data_repo.Open(ref.Path, strconv.FormatInt(user_agent.ID, 10))
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return f, nil
|
|
|
|
}
|