初始化项目

This commit is contained in:
2026-01-08 20:48:55 +08:00
commit 0cc737a8dd
66 changed files with 7410 additions and 0 deletions

View File

@@ -0,0 +1,181 @@
package controller
import (
"butterfliu/internal/service"
"encoding/json"
"io"
"log"
"net/http"
"strconv"
"sync"
"github.com/go-chi/chi/v5"
)
type LibraryController struct {
service *service.LibraryService
scanMutex sync.Mutex
isScanning bool
}
func NewLibraryController(service *service.LibraryService) *LibraryController {
return &LibraryController{service: service}
}
func (c *LibraryController) GetAll(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
libraries, err := c.service.GetAll()
if err != nil {
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
json.NewEncoder(w).Encode(libraries)
}
func (c *LibraryController) Create(w http.ResponseWriter, r *http.Request) {
var library map[string]interface{}
err := json.NewDecoder(r.Body).Decode(&library)
if err != nil {
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
_, err = c.service.Create(library["name"].(string), library["path"].(string))
if err != nil {
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
json.NewEncoder(w).Encode(map[string]string{"msg": "Add library successfully."})
}
func (c *LibraryController) UpdateName(w http.ResponseWriter, r *http.Request) {
idParam := chi.URLParam(r, "id")
name, _ := io.ReadAll(r.Body)
defer r.Body.Close()
id, err := strconv.Atoi(idParam)
if err != nil {
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
err = c.service.UpdateName(id, string(name))
if err != nil {
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
json.NewEncoder(w).Encode(map[string]string{"msg": "Updated library name."})
}
func (c *LibraryController) UpdatePath(w http.ResponseWriter, r *http.Request) {
idParam := chi.URLParam(r, "id")
path, _ := io.ReadAll(r.Body)
defer r.Body.Close()
id, err := strconv.Atoi(idParam)
if err != nil {
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
err = c.service.UpdatePath(id, string(path))
if err != nil {
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
json.NewEncoder(w).Encode(map[string]string{"msg": "Updated library path."})
}
func (c *LibraryController) Scan(w http.ResponseWriter, r *http.Request) {
c.scanMutex.Lock()
if c.isScanning {
c.scanMutex.Unlock()
json.NewEncoder(w).Encode(map[string]string{"error": "Another scan is already in progress"})
return
}
c.isScanning = true
c.scanMutex.Unlock()
idParam := chi.URLParam(r, "id")
id, err := strconv.Atoi(idParam)
if err != nil {
c.scanMutex.Lock()
c.isScanning = false
c.scanMutex.Unlock()
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
go func() {
defer func() {
c.scanMutex.Lock()
c.isScanning = false
c.scanMutex.Unlock()
}()
err := c.service.Scan(id)
if err != nil {
log.Printf("Scan failed: %v", err)
return
}
log.Printf("Scan completed successfully for library %d", id)
}()
json.NewEncoder(w).Encode(map[string]string{"msg": "Library scan started."})
}
func (c *LibraryController) GetScanStatus(w http.ResponseWriter, r *http.Request) {
c.scanMutex.Lock()
scanning := c.isScanning
c.scanMutex.Unlock()
json.NewEncoder(w).Encode(map[string]bool{"scanning": scanning})
}
func (c *LibraryController) Delete(w http.ResponseWriter, r *http.Request) {
idParam := chi.URLParam(r, "id")
id, _ := strconv.Atoi(idParam)
err := c.service.Delete(id)
if err != nil {
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
json.NewEncoder(w).Encode(map[string]string{"msg": "Deleted library."})
}
func (c *LibraryController) GetSongs(w http.ResponseWriter, r *http.Request) {
idParam := chi.URLParam(r, "id")
id, err := strconv.Atoi(idParam)
if err != nil {
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
songs, err := c.service.GetSongs(id)
if err != nil {
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
json.NewEncoder(w).Encode(songs)
}
func (c *LibraryController) GetAllSongs(w http.ResponseWriter, r *http.Request) {
songs, err := c.service.GetAllSongs()
if err != nil {
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
json.NewEncoder(w).Encode(songs)
}
func (c *LibraryController) GetArtists(w http.ResponseWriter, r *http.Request) {
artists, err := c.service.GetArtists()
if err != nil {
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
json.NewEncoder(w).Encode(artists)
}
func (c *LibraryController) GetAlbums(w http.ResponseWriter, r *http.Request) {
albums, err := c.service.GetAlbums()
if err != nil {
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
json.NewEncoder(w).Encode(albums)
}

View File

@@ -0,0 +1,320 @@
package repository
import (
"database/sql"
)
type Library struct {
ID int `json:"id"`
Name string `json:"name"`
Path string `json:"path"`
}
type MediaFile struct {
ID int `json:"id"`
Path string `json:"path"`
LibraryID int `json:"library_id"`
}
type Artist struct {
ID int `json:"id"`
Name string `json:"name"`
}
type Album struct {
ID int `json:"id"`
Title string `json:"title"`
ArtistID int `json:"artist_id"`
}
type Song struct {
ID int `json:"id"`
Title string `json:"title"`
ArtistID int `json:"artist_id"`
AlbumID int `json:"album_id"`
Duration int `json:"duration"`
MediaFileID int `json:"media_file_id"`
}
type SongDetail struct {
ID int `json:"id"`
Title string `json:"title"`
Artist string `json:"artist"`
Album string `json:"album"`
Duration int `json:"duration"`
Path string `json:"path"`
}
type LibraryRepository struct {
db *sql.DB
}
func NewLibraryRepository(db *sql.DB) *LibraryRepository {
return &LibraryRepository{db: db}
}
func (r *LibraryRepository) GetAll() ([]Library, error) {
rows, err := r.db.Query("SELECT id, name, path FROM libraries")
if err != nil {
return nil, err
}
defer rows.Close()
libraries := []Library{}
for rows.Next() {
var lib Library
if err := rows.Scan(&lib.ID, &lib.Name, &lib.Path); err != nil {
return nil, err
}
libraries = append(libraries, lib)
}
return libraries, nil
}
func (r *LibraryRepository) GetByID(id int) (Library, error) {
row := r.db.QueryRow("SELECT id, name, path FROM libraries WHERE id = ?", id)
var lib Library
if err := row.Scan(&lib.ID, &lib.Name, &lib.Path); err != nil {
return Library{}, err
}
return lib, nil
}
func (r *LibraryRepository) Create(name, path string) (Library, error) {
result, err := r.db.Exec("INSERT INTO libraries (name, path) VALUES (?, ?)", name, path)
if err != nil {
return Library{}, err
}
id, err := result.LastInsertId()
if err != nil {
return Library{}, err
}
return Library{
ID: int(id),
Name: name,
Path: path,
}, nil
}
func (r *LibraryRepository) UpdateName(id int, name string) error {
_, err := r.db.Exec("UPDATE libraries SET name = ? WHERE id = ?", name, id)
return err
}
func (r *LibraryRepository) UpdatePath(id int, path string) error {
_, err := r.db.Exec("UPDATE libraries SET path = ? WHERE id = ?", path, id)
return err
}
func (r *LibraryRepository) Delete(id int) error {
_, err := r.db.Exec("DELETE FROM libraries WHERE id = ?", id)
return err
}
func (r *LibraryRepository) GetSongsByLibraryWithDetails(libraryID int) ([]SongDetail, error) {
rows, err := r.db.Query(`
SELECT s.id, s.title, a.name as artist_name, al.title as album_title, s.duration, mf.path
FROM songs s
INNER JOIN media_files mf ON s.media_file_id = mf.id
INNER JOIN artists a ON s.artist_id = a.id
INNER JOIN albums al ON s.album_id = al.id
WHERE mf.library_id = ?
ORDER BY s.title
`, libraryID)
if err != nil {
return nil, err
}
defer rows.Close()
songs := []SongDetail{}
for rows.Next() {
var song SongDetail
if err := rows.Scan(&song.ID, &song.Title, &song.Artist, &song.Album, &song.Duration, &song.Path); err != nil {
return nil, err
}
songs = append(songs, song)
}
return songs, nil
}
func (r *LibraryRepository) GetAllSongsWithDetails() ([]SongDetail, error) {
rows, err := r.db.Query(`
SELECT s.id, s.title, a.name as artist_name, al.title as album_title, s.duration, mf.path
FROM songs s
INNER JOIN media_files mf ON s.media_file_id = mf.id
INNER JOIN artists a ON s.artist_id = a.id
INNER JOIN albums al ON s.album_id = al.id
ORDER BY s.title
`)
if err != nil {
return nil, err
}
defer rows.Close()
songs := []SongDetail{}
for rows.Next() {
var song SongDetail
if err := rows.Scan(&song.ID, &song.Title, &song.Artist, &song.Album, &song.Duration, &song.Path); err != nil {
return nil, err
}
songs = append(songs, song)
}
return songs, nil
}
func (r *LibraryRepository) GetMediaFileByPath(path string) (MediaFile, error) {
row := r.db.QueryRow("SELECT id, path, library_id FROM media_files WHERE path = ?", path)
var mediaFile MediaFile
if err := row.Scan(&mediaFile.ID, &mediaFile.Path, &mediaFile.LibraryID); err != nil {
return MediaFile{}, err
}
return mediaFile, nil
}
func (r *LibraryRepository) CreateMediaFile(path string, libraryID int) (MediaFile, error) {
result, err := r.db.Exec("INSERT INTO media_files (path, library_id) VALUES (?, ?)", path, libraryID)
if err != nil {
return MediaFile{}, err
}
id, err := result.LastInsertId()
if err != nil {
return MediaFile{}, err
}
return MediaFile{
ID: int(id),
Path: path,
}, nil
}
func (r *LibraryRepository) GetArtistByName(name string) (Artist, error) {
row := r.db.QueryRow("SELECT id, name FROM artists WHERE name = ?", name)
var artist Artist
if err := row.Scan(&artist.ID, &artist.Name); err != nil {
return Artist{}, err
}
return artist, nil
}
func (r *LibraryRepository) CreateArtist(name string) (Artist, error) {
result, err := r.db.Exec("INSERT INTO artists (name) VALUES (?)", name)
if err != nil {
return Artist{}, err
}
id, err := result.LastInsertId()
if err != nil {
return Artist{}, err
}
return Artist{
ID: int(id),
Name: name,
}, nil
}
func (r *LibraryRepository) GetAlbumByTitleAndArtist(title string, artistID int) (Album, error) {
row := r.db.QueryRow("SELECT id, title, artist_id FROM albums WHERE title = ? AND artist_id = ?", title, artistID)
var album Album
if err := row.Scan(&album.ID, &album.Title, &album.ArtistID); err != nil {
return Album{}, err
}
return album, nil
}
func (r *LibraryRepository) CreateAlbum(title string, artistID int) (Album, error) {
result, err := r.db.Exec("INSERT INTO albums (title, artist_id) VALUES (?, ?)", title, artistID)
if err != nil {
return Album{}, err
}
id, err := result.LastInsertId()
if err != nil {
return Album{}, err
}
return Album{
ID: int(id),
Title: title,
ArtistID: artistID,
}, nil
}
func (r *LibraryRepository) CreateSong(title string, artistID, albumID, duration, mediaFileID int) (Song, error) {
result, err := r.db.Exec("INSERT INTO songs (title, artist_id, album_id, duration, media_file_id) VALUES (?, ?, ?, ?, ?)", title, artistID, albumID, duration, mediaFileID)
if err != nil {
return Song{}, err
}
id, err := result.LastInsertId()
if err != nil {
return Song{}, err
}
return Song{
ID: int(id),
Title: title,
ArtistID: artistID,
AlbumID: albumID,
Duration: duration,
MediaFileID: mediaFileID,
}, nil
}
func (r *LibraryRepository) GetArtists() ([]Artist, error) {
rows, err := r.db.Query("SELECT id, name FROM artists")
if err != nil {
return nil, err
}
defer rows.Close()
artists := []Artist{}
for rows.Next() {
var artist Artist
if err := rows.Scan(&artist.ID, &artist.Name); err != nil {
return nil, err
}
artists = append(artists, artist)
}
return artists, nil
}
func (r *LibraryRepository) GetAlbums() ([]Album, error) {
rows, err := r.db.Query("SELECT id, title, artist_id FROM albums")
if err != nil {
return nil, err
}
defer rows.Close()
albums := []Album{}
for rows.Next() {
var album Album
if err := rows.Scan(&album.ID, &album.Title, &album.ArtistID); err != nil {
return nil, err
}
albums = append(albums, album)
}
return albums, nil
}
func (r *LibraryRepository) GetSongs() ([]Song, error) {
rows, err := r.db.Query("SELECT id, title, artist_id, album_id, duration, media_file_id FROM songs")
if err != nil {
return nil, err
}
defer rows.Close()
songs := []Song{}
for rows.Next() {
var song Song
if err := rows.Scan(&song.ID, &song.Title, &song.ArtistID, &song.AlbumID, &song.Duration, &song.MediaFileID); err != nil {
return nil, err
}
songs = append(songs, song)
}
return songs, nil
}

View File

@@ -0,0 +1,93 @@
package scanner
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/dhowden/tag"
)
type ScannedSong struct {
Title string
Artist string
Album string
Duration int
Path string
}
func ScanDirectory(dirPath string) ([]ScannedSong, error) {
songs := []ScannedSong{}
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
return songs, err
}
filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
if !isAudioFile(path) {
return nil
}
if song, err := processAudioFile(path); err != nil {
return err
} else {
songs = append(songs, song)
}
return nil
})
return songs, nil
}
func processAudioFile(filePath string) (ScannedSong, error) {
file, err := os.Open(filePath)
if err != nil {
return ScannedSong{}, fmt.Errorf("failed to open file: %v", err)
}
defer file.Close()
metadata, err := tag.ReadFrom(file)
if err != nil {
return ScannedSong{}, fmt.Errorf("failed to read metadata: %v", err)
}
title := metadata.Title()
if title == "" {
title = filepath.Base(filePath)
}
artist := metadata.Artist()
if artist == "" {
artist = "Unknown Artist"
}
album := metadata.Album()
if album == "" {
album = "Unknown Album"
}
return ScannedSong{
Title: title,
Artist: artist,
Album: album,
Duration: 100,
Path: filePath,
}, nil
}
func isAudioFile(path string) bool {
ext := strings.ToLower(filepath.Ext(path))
audioExtensions := []string{".mp3", ".flac", ".m4a", ".wav", ".ogg"}
for _, audioExt := range audioExtensions {
if ext == audioExt {
return true
}
}
return false
}

106
internal/service/library.go Normal file
View File

@@ -0,0 +1,106 @@
package service
import (
"butterfliu/internal/repository"
"butterfliu/internal/scanner"
"log"
)
type LibraryService struct {
repo *repository.LibraryRepository
}
func NewLibraryService(repo *repository.LibraryRepository) *LibraryService {
return &LibraryService{repo: repo}
}
func (s *LibraryService) GetAll() ([]repository.Library, error) {
return s.repo.GetAll()
}
func (s *LibraryService) GetByID(id int) (repository.Library, error) {
return s.repo.GetByID(id)
}
func (s *LibraryService) Create(name, path string) (repository.Library, error) {
return s.repo.Create(name, path)
}
func (s *LibraryService) UpdateName(id int, name string) error {
return s.repo.UpdateName(id, name)
}
func (s *LibraryService) UpdatePath(id int, path string) error {
return s.repo.UpdatePath(id, path)
}
func (s *LibraryService) Delete(id int) error {
return s.repo.Delete(id)
}
func (s *LibraryService) GetSongs(id int) ([]repository.SongDetail, error) {
return s.repo.GetSongsByLibraryWithDetails(id)
}
func (s *LibraryService) GetAllSongs() ([]repository.SongDetail, error) {
return s.repo.GetAllSongsWithDetails()
}
func (s *LibraryService) GetArtists() ([]repository.Artist, error) {
return s.repo.GetArtists()
}
func (s *LibraryService) GetAlbums() ([]repository.Album, error) {
return s.repo.GetAlbums()
}
func (s *LibraryService) Scan(id int) error {
lib, err := s.repo.GetByID(id)
if err != nil {
return err
}
scannedSongs, err := scanner.ScanDirectory(lib.Path)
if err != nil {
return err
}
log.Println("Scanned songs:", len(scannedSongs))
for _, song := range scannedSongs {
mediaFile, err := s.repo.GetMediaFileByPath(song.Path)
if err != nil {
mediaFile, err = s.repo.CreateMediaFile(song.Path, id)
if err != nil {
log.Println("Error adding media file:", song.Path, err)
continue
}
}
artist, err := s.repo.GetArtistByName(song.Artist)
if err != nil {
artist, err = s.repo.CreateArtist(song.Artist)
if err != nil {
log.Println("Error adding artist:", song.Artist, err)
continue
}
}
album, err := s.repo.GetAlbumByTitleAndArtist(song.Album, artist.ID)
if err != nil {
album, err = s.repo.CreateAlbum(song.Album, artist.ID)
if err != nil {
log.Println("Error adding album:", err)
continue
}
}
_, err = s.repo.CreateSong(song.Title, artist.ID, album.ID, song.Duration, mediaFile.ID)
if err != nil {
log.Printf("Song already exists or error adding: %s - %v", song.Title, err)
continue
}
}
return nil
}