Initial commit

This commit is contained in:
Artem Mamonov
2025-02-06 02:36:10 +01:00
commit acf9b43671
24 changed files with 1946 additions and 0 deletions

96
internal/fs/fs.go Normal file
View File

@@ -0,0 +1,96 @@
package fs
import (
"errors"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"photodisk/internal/config"
)
const AlbumDir = "albums"
func AlbumsPath() string {
return filepath.Join(config.Get().Data, AlbumDir)
}
func AlbumPath(id string) string {
return filepath.Join(AlbumsPath(), id)
}
func AlbumFile(id string, fileName string) string {
return filepath.Join(AlbumPath(id), fileName)
}
func CreateAlbum(id string) error {
return os.MkdirAll(AlbumPath(id), os.ModePerm)
}
func DeleteAlbum(id string) error {
return os.RemoveAll(AlbumPath(id))
}
func FileExists(albumId string, fileName string) (string, bool) {
path := AlbumFile(albumId, fileName)
_, err := os.Stat(path)
return path, err == nil
}
func ListFiles(albumId string) ([]string, error) {
files, err := os.ReadDir(AlbumPath(albumId))
if err != nil {
return nil, err
}
var fileNames []string
for _, file := range files {
fileNames = append(fileNames, file.Name())
}
return fileNames, nil
}
func CreateFile(albumId string, fileName string, file multipart.File) error {
filePath := filepath.Join(AlbumPath(albumId), fileName)
// Check if file already exists
if _, err := os.Stat(filePath); !os.IsNotExist(err) {
return errors.New("file already exists")
}
// Validate the file is a real JPEG image
buffer := make([]byte, 512)
_, err := file.Read(buffer)
if err != nil {
return err
}
contentType := http.DetectContentType(buffer)
if contentType != "image/jpeg" && contentType != "video/mp4" {
return errors.New("file is not a JPEG image or MP4 video")
}
// Reset file pointer to the beginning
file.Seek(0, 0)
// Create destination file
out, err := os.Create(filePath)
if err != nil {
return err
}
defer out.Close()
// Copy the uploaded file to the destination file
_, err = io.Copy(out, file)
if err != nil {
return err
}
return nil
}
func IsImageFile(fileName string) bool {
ext := filepath.Ext(fileName)
return ext == ".jpg" || ext == ".jpeg" || ext == ".png"
}