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" }