SocialDragon/folder/main.go
2020-01-15 23:10:20 +01:00

71 lines
1.9 KiB
Go

package folder
import (
"crypto/sha256"
"encoding/hex"
"io/ioutil"
"log"
"os"
"path"
"strings"
"github.com/leonelquinteros/gorand"
"git.1750studios.com/AniNite/SocialDragon/config"
"git.1750studios.com/AniNite/SocialDragon/database"
)
var jobRunning bool
// LoadNewFolders loads the content of configured folder to database
func LoadNewFolders() {
if jobRunning {
return
}
jobRunning = true
log.Printf("Loading new folders...")
files, _ := ioutil.ReadDir(config.C.Folder.Folder)
for _, f := range files {
uuid, err := gorand.UUID()
if err != nil {
log.Printf("Could not generate UUID!")
continue
}
fpath, url := ImageNameGenerator(uuid + f.Name())
err = os.Rename(path.Join(config.C.Folder.Folder, f.Name()), fpath)
if err != nil {
log.Printf("Could not move %s to %s!", path.Join(config.C.Folder.Folder, f.Name()), fpath)
continue
}
var US database.User
database.Db.FirstOrCreate(&US, database.User{Service: database.Folder})
var IT database.Item
IT.UserID = US.ID
IT.IsVideo = false
IT.OriginalID = f.Name()
IT.Path = url
IT.Service = database.Folder
IT.State = database.Inbox
database.Db.Create(&IT)
os.Remove(path.Join(config.C.Folder.Folder, f.Name()))
log.Printf("Found picture %s", f.Name())
}
jobRunning = false
}
// ImageNameGenerator generates media paths
func ImageNameGenerator(seed string) (string, string) {
seedBytes := []byte(seed)
sha256Bytes := sha256.Sum256(seedBytes)
hash := hex.EncodeToString(sha256Bytes[:])
folders := config.C.ContentDirectory + "/" + hash[0:2] + "/" + hash[0:4] + "/"
urls := config.C.ContentWebDirectory + "/" + hash[0:2] + "/" + hash[0:4] + "/"
if err := os.MkdirAll(folders, 0775); err != nil {
log.Fatalf("FAT Could not create ContentDirectory, error: %+v", err)
}
ext := strings.Split(seed, ".")
finalPath := folders + hash + "." + ext[len(ext)-1]
finalURL := urls + hash + "." + ext[len(ext)-1]
return finalPath, finalURL
}