初始化项目
This commit is contained in:
10
.idea/.gitignore
generated
vendored
Normal file
10
.idea/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
# 默认忽略的文件
|
||||||
|
/shelf/
|
||||||
|
/workspace.xml
|
||||||
|
# 已忽略包含查询文件的默认文件夹
|
||||||
|
/queries/
|
||||||
|
# Datasource local storage ignored files
|
||||||
|
/dataSources/
|
||||||
|
/dataSources.local.xml
|
||||||
|
# 基于编辑器的 HTTP 客户端请求
|
||||||
|
/httpRequests/
|
||||||
9
.idea/butterfliu-2.iml
generated
Normal file
9
.idea/butterfliu-2.iml
generated
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<module type="WEB_MODULE" version="4">
|
||||||
|
<component name="Go" enabled="true" />
|
||||||
|
<component name="NewModuleRootManager">
|
||||||
|
<content url="file://$MODULE_DIR$" />
|
||||||
|
<orderEntry type="inheritedJdk" />
|
||||||
|
<orderEntry type="sourceFolder" forTests="false" />
|
||||||
|
</component>
|
||||||
|
</module>
|
||||||
12
.idea/dataSources.xml
generated
Normal file
12
.idea/dataSources.xml
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
|
||||||
|
<data-source source="LOCAL" name="butterfliu" uuid="14a0c5a9-94a6-4306-817e-8996c1d963b3">
|
||||||
|
<driver-ref>sqlite.xerial</driver-ref>
|
||||||
|
<synchronize>true</synchronize>
|
||||||
|
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
|
||||||
|
<jdbc-url>jdbc:sqlite:$PROJECT_DIR$/butterfliu.db</jdbc-url>
|
||||||
|
<working-dir>$ProjectFileDir$</working-dir>
|
||||||
|
</data-source>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
6
.idea/data_source_mapping.xml
generated
Normal file
6
.idea/data_source_mapping.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="DataSourcePerFileMappings">
|
||||||
|
<file url="file://$PROJECT_DIR$/.idea/queries/Query.sql" value="14a0c5a9-94a6-4306-817e-8996c1d963b3" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
11
.idea/go.imports.xml
generated
Normal file
11
.idea/go.imports.xml
generated
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="GoImports">
|
||||||
|
<option name="excludedPackages">
|
||||||
|
<array>
|
||||||
|
<option value="github.com/pkg/errors" />
|
||||||
|
<option value="golang.org/x/net/context" />
|
||||||
|
</array>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
8
.idea/modules.xml
generated
Normal file
8
.idea/modules.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ProjectModuleManager">
|
||||||
|
<modules>
|
||||||
|
<module fileurl="file://$PROJECT_DIR$/.idea/butterfliu-2.iml" filepath="$PROJECT_DIR$/.idea/butterfliu-2.iml" />
|
||||||
|
</modules>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
6
.idea/sqldialects.xml
generated
Normal file
6
.idea/sqldialects.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="SqlDialectMappings">
|
||||||
|
<file url="file://$PROJECT_DIR$/.idea/queries/Query.sql" dialect="SQLite" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
BIN
butterfliu.db
Normal file
BIN
butterfliu.db
Normal file
Binary file not shown.
BIN
butterfliu.exe
Normal file
BIN
butterfliu.exe
Normal file
Binary file not shown.
143
cmd/migrate/main.go
Normal file
143
cmd/migrate/main.go
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"butterfliu/migrations"
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
_ "github.com/mattn/go-sqlite3"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
if len(os.Args) < 2 {
|
||||||
|
printUsage()
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
command := os.Args[1]
|
||||||
|
|
||||||
|
// Database file path
|
||||||
|
dbPath := "./butterfliu.db"
|
||||||
|
if len(os.Args) > 3 && os.Args[1] == "db" {
|
||||||
|
dbPath = os.Args[3]
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Using database: %s", dbPath)
|
||||||
|
|
||||||
|
// Open database connection
|
||||||
|
db, err := sql.Open("sqlite3", dbPath)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Error opening database %s: %v", dbPath, err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
// Test connection
|
||||||
|
if err = db.Ping(); err != nil {
|
||||||
|
log.Fatalf("Error connecting to database %s: %v", dbPath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize migration table
|
||||||
|
if err = migrations.InitMigrationTable(db); err != nil {
|
||||||
|
log.Fatalf("Error initializing migration table: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch command {
|
||||||
|
case "up":
|
||||||
|
// Run all pending migrations
|
||||||
|
if err := migrations.MigrateUp(db); err != nil {
|
||||||
|
log.Fatalf("Error applying migrations: %v", err)
|
||||||
|
}
|
||||||
|
log.Println("All migrations applied successfully")
|
||||||
|
|
||||||
|
case "down":
|
||||||
|
if len(os.Args) < 3 {
|
||||||
|
log.Println("Error: Missing target version")
|
||||||
|
printUsage()
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
targetVersion, err := parseVersion(os.Args[2])
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Error parsing target version: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Roll back migrations to target version
|
||||||
|
if err := migrations.MigrateDown(db, targetVersion); err != nil {
|
||||||
|
log.Fatalf("Error rolling back migrations: %v", err)
|
||||||
|
}
|
||||||
|
log.Printf("Migrations rolled back to version %d successfully\n", targetVersion)
|
||||||
|
|
||||||
|
case "reset":
|
||||||
|
// Roll back all migrations
|
||||||
|
if err := migrations.MigrateDown(db, 0); err != nil {
|
||||||
|
log.Fatalf("Error rolling back migrations: %v", err)
|
||||||
|
}
|
||||||
|
log.Println("All migrations rolled back successfully")
|
||||||
|
|
||||||
|
case "refresh":
|
||||||
|
// Roll back all migrations and then apply them again
|
||||||
|
if err := migrations.MigrateDown(db, 0); err != nil {
|
||||||
|
log.Fatalf("Error rolling back migrations: %v", err)
|
||||||
|
}
|
||||||
|
if err := migrations.MigrateUp(db); err != nil {
|
||||||
|
log.Fatalf("Error applying migrations: %v", err)
|
||||||
|
}
|
||||||
|
log.Println("All migrations refreshed successfully")
|
||||||
|
|
||||||
|
case "status":
|
||||||
|
// Show migration status
|
||||||
|
migrationList, err := migrations.ListMigrations(db)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Error listing migrations: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("Migration Status:")
|
||||||
|
log.Println("=================")
|
||||||
|
for _, migration := range migrationList {
|
||||||
|
status := "Pending"
|
||||||
|
appliedAt := ""
|
||||||
|
if applied, ok := migration["applied"].(bool); ok && applied {
|
||||||
|
status = "Applied"
|
||||||
|
appliedAt = migration["applied_at"].(string)
|
||||||
|
}
|
||||||
|
log.Printf("%d: %s - %s %s\n", migration["version"], migration["description"], status, appliedAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
case "create":
|
||||||
|
if len(os.Args) < 3 {
|
||||||
|
log.Println("Error: Missing migration name")
|
||||||
|
printUsage()
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
name := os.Args[2]
|
||||||
|
if err := migrations.CreateMigration(name); err != nil {
|
||||||
|
log.Fatalf("Error creating migration: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
log.Printf("Error: Unknown command '%s'\n", command)
|
||||||
|
printUsage()
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func printUsage() {
|
||||||
|
log.Println("Usage: go run cmd/migrate/main.go <command> [args]")
|
||||||
|
log.Println("")
|
||||||
|
log.Println("Commands:")
|
||||||
|
log.Println(" up Apply all pending migrations")
|
||||||
|
log.Println(" down <version> Roll back migrations to specified version")
|
||||||
|
log.Println(" reset Roll back all migrations")
|
||||||
|
log.Println(" refresh Roll back all migrations and apply them again")
|
||||||
|
log.Println(" status Show migration status")
|
||||||
|
log.Println(" create <name> Create a new migration")
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseVersion(s string) (int, error) {
|
||||||
|
var v int
|
||||||
|
_, err := fmt.Sscanf(s, "%d", &v)
|
||||||
|
return v, err
|
||||||
|
}
|
||||||
50
config/config.go
Normal file
50
config/config.go
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
DatabasePath string
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadConfig loads configuration from environment variables
|
||||||
|
func LoadConfig() *Config {
|
||||||
|
cfg := &Config{
|
||||||
|
DatabasePath: getEnv("DATABASE_PATH", "./butterfliu.db"),
|
||||||
|
}
|
||||||
|
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
// getEnv gets an environment variable with a default value
|
||||||
|
func getEnv(key, defaultValue string) string {
|
||||||
|
if value := os.Getenv(key); value != "" {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
// getEnvAsInt gets an environment variable as integer
|
||||||
|
func getEnvAsInt(key string, defaultValue int) int {
|
||||||
|
if value := os.Getenv(key); value != "" {
|
||||||
|
if intValue, err := strconv.Atoi(value); err == nil {
|
||||||
|
return intValue
|
||||||
|
}
|
||||||
|
log.Printf("Warning: Invalid integer value for %s: %s, using default: %d", key, value, defaultValue)
|
||||||
|
}
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
// getEnvAsInt64 gets an environment variable as int64
|
||||||
|
func getEnvAsInt64(key string, defaultValue int64) int64 {
|
||||||
|
if value := os.Getenv(key); value != "" {
|
||||||
|
if intValue, err := strconv.ParseInt(value, 10, 64); err == nil {
|
||||||
|
return intValue
|
||||||
|
}
|
||||||
|
log.Printf("Warning: Invalid int64 value for %s: %s, using default: %d", key, value, defaultValue)
|
||||||
|
}
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
443
db.go
Normal file
443
db.go
Normal file
@@ -0,0 +1,443 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"butterfliu/migrations"
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
var DB *sql.DB
|
||||||
|
|
||||||
|
func GetDB() *sql.DB {
|
||||||
|
return DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func InitDB(dbPath string) error {
|
||||||
|
dir := filepath.Dir(dbPath)
|
||||||
|
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||||
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||||
|
return fmt.Errorf("failed to create database directory %s: %v", dir, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var err error
|
||||||
|
|
||||||
|
DB, _ = sql.Open("sqlite3", dbPath)
|
||||||
|
|
||||||
|
DB.Ping()
|
||||||
|
|
||||||
|
if err = migrations.InitMigrationTable(DB); err != nil {
|
||||||
|
return fmt.Errorf("failed to initialize migration table: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-migrate by default, can be disabled with AUTO_MIGRATE=false
|
||||||
|
if os.Getenv("AUTO_MIGRATE") != "false" {
|
||||||
|
log.Println("Auto-migration enabled, applying pending migrations...")
|
||||||
|
if err = migrations.MigrateUp(DB); err != nil {
|
||||||
|
log.Printf("Warning: Auto migration failed: %v", err)
|
||||||
|
} else {
|
||||||
|
log.Println("Auto-migration completed successfully")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.Println("Auto-migration disabled")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func CloseDB() error {
|
||||||
|
if DB != nil {
|
||||||
|
return DB.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func AddLibrary(name, path string) (Library, error) {
|
||||||
|
absPath, err := filepath.Abs(path)
|
||||||
|
if err != nil {
|
||||||
|
return Library{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := DB.Exec(
|
||||||
|
"INSERT INTO libraries (name, path) VALUES (?, ?)",
|
||||||
|
name, absPath,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return Library{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
id, err := result.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
return Library{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return Library{
|
||||||
|
ID: int(id),
|
||||||
|
Name: name,
|
||||||
|
Path: absPath,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetLibraries() ([]Library, error) {
|
||||||
|
rows, err := 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 GetLibraryByID(id int) (Library, error) {
|
||||||
|
row := 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 UpdateLibraryName(id int, name string) error {
|
||||||
|
_, err := DB.Exec(
|
||||||
|
"UPDATE libraries SET name = ? WHERE id = ?",
|
||||||
|
name, id,
|
||||||
|
)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
func UpdateLibraryPath(id int, path string) error {
|
||||||
|
_, err := DB.Exec(
|
||||||
|
"UPDATE libraries SET path = ? WHERE id = ?",
|
||||||
|
path, id,
|
||||||
|
)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
func DeleteLibrary(id int) error {
|
||||||
|
_, err := DB.Exec("DELETE FROM libraries WHERE id = ?", id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func AddMediaFile(path string, libraryID int) (MediaFile, error) {
|
||||||
|
result, err := 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 GetMediaFileByPath(path string) (MediaFile, error) {
|
||||||
|
row := DB.QueryRow("SELECT id, path FROM media_files WHERE path = ?", path)
|
||||||
|
var mediaFile MediaFile
|
||||||
|
if err := row.Scan(&mediaFile.ID, &mediaFile.Path); err != nil {
|
||||||
|
return MediaFile{}, err
|
||||||
|
}
|
||||||
|
return mediaFile, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func AddArtist(name string) (Artist, error) {
|
||||||
|
result, err := 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 GetArtists() ([]Artist, error) {
|
||||||
|
rows, err := 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 GetArtistByID(id int) (Artist, error) {
|
||||||
|
row := DB.QueryRow("SELECT id, name FROM artists WHERE id = ?", id)
|
||||||
|
var artist Artist
|
||||||
|
if err := row.Scan(&artist.ID, &artist.Name); err != nil {
|
||||||
|
return Artist{}, err
|
||||||
|
}
|
||||||
|
return artist, nil
|
||||||
|
}
|
||||||
|
func GetArtistByName(name string) (Artist, error) {
|
||||||
|
row := 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 UpdateArtistName(id int, name string) error {
|
||||||
|
_, err := DB.Exec("UPDATE artists SET name = ? WHERE id = ?", name, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func DeleteArtist(id int) error {
|
||||||
|
_, err := DB.Exec("DELETE FROM artists WHERE id = ?", id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func AddAlbum(title string, artistID int) (Album, error) {
|
||||||
|
result, err := 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 GetAlbums() ([]Album, error) {
|
||||||
|
rows, err := 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 GetAlbumByID(id int) (Album, error) {
|
||||||
|
row := DB.QueryRow("SELECT id, title, artist_id FROM albums WHERE id = ?", id)
|
||||||
|
var album Album
|
||||||
|
if err := row.Scan(&album.ID, &album.Title, &album.ArtistID); err != nil {
|
||||||
|
return Album{}, err
|
||||||
|
}
|
||||||
|
return album, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetAlbumByTitle(title string) (Album, error) {
|
||||||
|
row := DB.QueryRow("SELECT id, title, artist_id FROM albums WHERE title = ?", title)
|
||||||
|
var album Album
|
||||||
|
if err := row.Scan(&album.ID, &album.Title, &album.ArtistID); err != nil {
|
||||||
|
return Album{}, err
|
||||||
|
}
|
||||||
|
return album, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetAlbumByTitleAndArtist(title string, artistID int) (Album, error) {
|
||||||
|
row := 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 GetAlbumsByArtist(artistID int) ([]Album, error) {
|
||||||
|
rows, err := DB.Query("SELECT id, title, artist_id FROM albums WHERE artist_id = ?", artistID)
|
||||||
|
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 UpdateAlbumTitle(id int, title string) error {
|
||||||
|
_, err := DB.Exec("UPDATE albums SET title = ? WHERE id = ?", title, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
func UpdateAlbumArtistID(id, artistID int) error {
|
||||||
|
_, err := DB.Exec("UPDATE albums SET artist_id = ?", artistID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
func DeleteAlbum(id int) error {
|
||||||
|
_, err := DB.Exec("DELETE FROM albums WHERE id = ?", id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func AddSong(title string, artistID, albumID, duration, mediaFileID int) (Song, error) {
|
||||||
|
result, err := 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 GetSongs() ([]Song, error) {
|
||||||
|
rows, err := DB.Query("SELECT id, 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.ArtistID, &song.AlbumID, &song.Duration, &song.MediaFileID); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
songs = append(songs, song)
|
||||||
|
}
|
||||||
|
return songs, nil
|
||||||
|
}
|
||||||
|
func UpdateSongTitle(id int, title string) error {
|
||||||
|
_, err := DB.Exec("UPDATE songs SET title = ? WHERE id = ?", title, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
func UpdateSongArtistID(id int, artistID int) error {
|
||||||
|
_, err := DB.Exec("UPDATE songs SET artist_id = ?", artistID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
func UpdateSongAlbumID(id, albumID int) error {
|
||||||
|
_, err := DB.Exec("UPDATE songs SET album_id = ?", albumID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
func UpdateSongDuration(id, duration int) error {
|
||||||
|
_, err := DB.Exec("UPDATE songs SET duration = ?", duration)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
func DeleteSong(id int) error {
|
||||||
|
_, err := DB.Exec("DELETE FROM songs WHERE id = ?", id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetSongsByLibrary(libraryID int) ([]Song, error) {
|
||||||
|
rows, err := DB.Query(`
|
||||||
|
SELECT s.id, s.title, s.artist_id, s.album_id, s.duration, s.media_file_id
|
||||||
|
FROM songs s
|
||||||
|
INNER JOIN media_files mf ON s.media_file_id = mf.id
|
||||||
|
WHERE mf.library_id = ?
|
||||||
|
ORDER BY s.title
|
||||||
|
`, libraryID)
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
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"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetSongsByLibraryWithDetails(libraryID int) ([]SongDetail, error) {
|
||||||
|
rows, err := 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 GetAllSongsWithDetails() ([]SongDetail, error) {
|
||||||
|
rows, err := 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
|
||||||
|
}
|
||||||
9
go.mod
Normal file
9
go.mod
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
module butterfliu
|
||||||
|
|
||||||
|
go 1.23.5
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8
|
||||||
|
github.com/go-chi/chi/v5 v5.2.3
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.32
|
||||||
|
)
|
||||||
6
go.sum
Normal file
6
go.sum
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8 h1:OtSeLS5y0Uy01jaKK4mA/WVIYtpzVm63vLVAPzJXigg=
|
||||||
|
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8/go.mod h1:apkPC/CR3s48O2D7Y++n1XWEpgPNNCjXYga3PPbJe2E=
|
||||||
|
github.com/go-chi/chi/v5 v5.2.3 h1:WQIt9uxdsAbgIYgid+BpYc+liqQZGMHRaUwp0JUcvdE=
|
||||||
|
github.com/go-chi/chi/v5 v5.2.3/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.32 h1:JD12Ag3oLy1zQA+BNn74xRgaBbdhbNIDYvQUEuuErjs=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.32/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||||
181
internal/controller/library.go
Normal file
181
internal/controller/library.go
Normal 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)
|
||||||
|
}
|
||||||
320
internal/repository/library.go
Normal file
320
internal/repository/library.go
Normal 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
|
||||||
|
}
|
||||||
93
internal/scanner/scanner.go
Normal file
93
internal/scanner/scanner.go
Normal 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
106
internal/service/library.go
Normal 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
|
||||||
|
}
|
||||||
49
main.go
Normal file
49
main.go
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"butterfliu/internal/controller"
|
||||||
|
"butterfliu/internal/repository"
|
||||||
|
"butterfliu/internal/service"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/go-chi/chi/v5/middleware"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
err := InitDB("./butterfliu.db")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
r := chi.NewRouter()
|
||||||
|
r.Use(middleware.Logger)
|
||||||
|
|
||||||
|
libraryRepo := repository.NewLibraryRepository(GetDB())
|
||||||
|
libraryService := service.NewLibraryService(libraryRepo)
|
||||||
|
libraryController := controller.NewLibraryController(libraryService)
|
||||||
|
|
||||||
|
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Write([]byte("Hello World!"))
|
||||||
|
})
|
||||||
|
|
||||||
|
r.Route("/api/libraries", func(r chi.Router) {
|
||||||
|
r.Get("/", libraryController.GetAll)
|
||||||
|
r.Post("/", libraryController.Create)
|
||||||
|
r.Put("/{id}/name", libraryController.UpdateName)
|
||||||
|
r.Put("/{id}/path", libraryController.UpdatePath)
|
||||||
|
r.Post("/{id}/scan", libraryController.Scan)
|
||||||
|
r.Get("/scan-status", libraryController.GetScanStatus)
|
||||||
|
r.Delete("/{id}", libraryController.Delete)
|
||||||
|
r.Get("/{id}/songs", libraryController.GetSongs)
|
||||||
|
})
|
||||||
|
|
||||||
|
r.Route("/api", func(r chi.Router) {
|
||||||
|
r.Get("/songs", libraryController.GetAllSongs)
|
||||||
|
r.Get("/artists", libraryController.GetArtists)
|
||||||
|
r.Get("/albums", libraryController.GetAlbums)
|
||||||
|
})
|
||||||
|
|
||||||
|
http.ListenAndServe(":8102", r)
|
||||||
|
}
|
||||||
96
migrations/001_initial_schema.go
Normal file
96
migrations/001_initial_schema.go
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
package migrations
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
RegisterMigration(
|
||||||
|
1,
|
||||||
|
"Initial schema",
|
||||||
|
migrateInitialSchemaUp,
|
||||||
|
migrateInitialSchemaDown,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func migrateInitialSchemaUp(tx *sql.Tx) error {
|
||||||
|
_, err := tx.Exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS libraries (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
path TEXT NOT NULL)`)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = tx.Exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS media_files (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
path TEXT NOT NULL,
|
||||||
|
library_id INTEGER NOT NULL)`)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = tx.Exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS artists (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = tx.Exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS albums (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
artist_id INTEGER,
|
||||||
|
FOREIGN KEY (artist_id) REFERENCES artists(id),
|
||||||
|
UNIQUE(title, artist_id)
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = tx.Exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS songs (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
album_id INTEGER,
|
||||||
|
artist_id INTEGER,
|
||||||
|
duration INTEGER,
|
||||||
|
media_file_id INTEGER UNIQUE,
|
||||||
|
FOREIGN KEY (album_id) REFERENCES albums(id),
|
||||||
|
FOREIGN KEY (artist_id) REFERENCES artists(id),
|
||||||
|
FOREIGN KEY (media_file_id) REFERENCES media_files(id)
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func migrateInitialSchemaDown(tx *sql.Tx) error {
|
||||||
|
// Drop tables in reverse order to avoid foreign key constraints
|
||||||
|
tables := []string{
|
||||||
|
"songs",
|
||||||
|
"albums",
|
||||||
|
"artists",
|
||||||
|
"media_files",
|
||||||
|
"libraries",
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, table := range tables {
|
||||||
|
_, err := tx.Exec("DROP TABLE IF EXISTS " + table)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
143
migrations/README.md
Normal file
143
migrations/README.md
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
# Database Migration System
|
||||||
|
|
||||||
|
This package provides a simple database migration system for Butterfliu. It allows you to:
|
||||||
|
|
||||||
|
- Create new migrations
|
||||||
|
- Apply pending migrations
|
||||||
|
- Roll back migrations
|
||||||
|
- Check migration status
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
### Running Migrations
|
||||||
|
|
||||||
|
To run migrations, use the following command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go run cmd/migrate/main.go up
|
||||||
|
```
|
||||||
|
|
||||||
|
This will apply all pending migrations.
|
||||||
|
|
||||||
|
**Important:** Migrations must be run manually before starting the application. The application no longer automatically applies migrations on startup.
|
||||||
|
|
||||||
|
### Rolling Back Migrations
|
||||||
|
|
||||||
|
To roll back migrations to a specific version, use:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go run cmd/migrate/main.go down <version>
|
||||||
|
```
|
||||||
|
|
||||||
|
For example, to roll back to version 1:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go run cmd/migrate/main.go down 1
|
||||||
|
```
|
||||||
|
|
||||||
|
To roll back all migrations:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go run cmd/migrate/main.go reset
|
||||||
|
```
|
||||||
|
|
||||||
|
### Checking Migration Status
|
||||||
|
|
||||||
|
To check the status of all migrations:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go run cmd/migrate/main.go status
|
||||||
|
```
|
||||||
|
|
||||||
|
### Refreshing Migrations
|
||||||
|
|
||||||
|
To roll back all migrations and then apply them again:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go run cmd/migrate/main.go refresh
|
||||||
|
```
|
||||||
|
|
||||||
|
### Creating a New Migration
|
||||||
|
|
||||||
|
To create a new migration:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go run cmd/migrate/main.go create <name>
|
||||||
|
```
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go run cmd/migrate/main.go create add_user_table
|
||||||
|
```
|
||||||
|
|
||||||
|
This will create a new migration file in the `migrations` directory.
|
||||||
|
|
||||||
|
## Auto-Migration
|
||||||
|
|
||||||
|
By default, auto-migration is **enabled**. The application will automatically apply all pending migrations on startup.
|
||||||
|
|
||||||
|
To disable auto-migration, set the `AUTO_MIGRATE` environment variable to `false`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Disable auto-migration
|
||||||
|
export AUTO_MIGRATE=false
|
||||||
|
|
||||||
|
# Then run the application
|
||||||
|
go run main.go
|
||||||
|
```
|
||||||
|
|
||||||
|
**Recommended usage:**
|
||||||
|
- **Development:** Auto-migration is enabled by default for convenience
|
||||||
|
- **Production:** Set `AUTO_MIGRATE=false` and run migrations manually using `go run cmd/migrate/main.go up` before deploying
|
||||||
|
|
||||||
|
## Migration File Structure
|
||||||
|
|
||||||
|
Each migration file should implement two functions:
|
||||||
|
|
||||||
|
- `Up`: Applies the migration
|
||||||
|
- `Down`: Rolls back the migration
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```go
|
||||||
|
package migrations
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
RegisterMigration(
|
||||||
|
3,
|
||||||
|
"Add user table",
|
||||||
|
migrateAddUserTableUp,
|
||||||
|
migrateAddUserTableDown,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func migrateAddUserTableUp(tx *sql.Tx) error {
|
||||||
|
_, err := tx.Exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
username TEXT NOT NULL UNIQUE,
|
||||||
|
password TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func migrateAddUserTableDown(tx *sql.Tx) error {
|
||||||
|
_, err := tx.Exec(`DROP TABLE IF EXISTS users`)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
1. Always provide both `Up` and `Down` functions
|
||||||
|
2. Make migrations idempotent when possible
|
||||||
|
3. Use transactions to ensure atomicity
|
||||||
|
4. Keep migrations small and focused
|
||||||
|
5. Test migrations before applying them to production
|
||||||
205
migrations/cli.go
Normal file
205
migrations/cli.go
Normal file
@@ -0,0 +1,205 @@
|
|||||||
|
package migrations
|
||||||
|
|
||||||
|
import (
|
||||||
|
"butterfliu/config"
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
_ "github.com/mattn/go-sqlite3"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RunMigrationCLI runs the migration command-line interface
|
||||||
|
func RunMigrationCLI() {
|
||||||
|
if len(os.Args) < 2 {
|
||||||
|
printUsage()
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
command := os.Args[1]
|
||||||
|
|
||||||
|
// Load configuration
|
||||||
|
cfg := config.LoadConfig()
|
||||||
|
|
||||||
|
// Database file path - use configuration
|
||||||
|
dbPath := cfg.DatabasePath
|
||||||
|
log.Printf("Using database: %s", dbPath)
|
||||||
|
|
||||||
|
// Open database connection
|
||||||
|
db, err := sql.Open("sqlite3", dbPath)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Error opening database %s: %v", dbPath, err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
// Test connection
|
||||||
|
if err = db.Ping(); err != nil {
|
||||||
|
log.Fatalf("Error connecting to database %s: %v", dbPath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize migration table
|
||||||
|
if err = InitMigrationTable(db); err != nil {
|
||||||
|
log.Fatalf("Error initializing migration table: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch command {
|
||||||
|
case "up":
|
||||||
|
// Run all pending migrations
|
||||||
|
if err := MigrateUp(db); err != nil {
|
||||||
|
log.Fatalf("Error applying migrations: %v", err)
|
||||||
|
}
|
||||||
|
fmt.Println("All migrations applied successfully")
|
||||||
|
|
||||||
|
case "down":
|
||||||
|
if len(os.Args) < 3 {
|
||||||
|
fmt.Println("Error: Missing target version")
|
||||||
|
printUsage()
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
targetVersion, err := strconv.Atoi(os.Args[2])
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Error parsing target version: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Roll back migrations to target version
|
||||||
|
if err := MigrateDown(db, targetVersion); err != nil {
|
||||||
|
log.Fatalf("Error rolling back migrations: %v", err)
|
||||||
|
}
|
||||||
|
fmt.Printf("Migrations rolled back to version %d successfully\n", targetVersion)
|
||||||
|
|
||||||
|
case "reset":
|
||||||
|
// Roll back all migrations
|
||||||
|
if err := MigrateDown(db, 0); err != nil {
|
||||||
|
log.Fatalf("Error rolling back migrations: %v", err)
|
||||||
|
}
|
||||||
|
fmt.Println("All migrations rolled back successfully")
|
||||||
|
|
||||||
|
case "refresh":
|
||||||
|
// Roll back all migrations and then apply them again
|
||||||
|
if err := MigrateDown(db, 0); err != nil {
|
||||||
|
log.Fatalf("Error rolling back migrations: %v", err)
|
||||||
|
}
|
||||||
|
if err := MigrateUp(db); err != nil {
|
||||||
|
log.Fatalf("Error applying migrations: %v", err)
|
||||||
|
}
|
||||||
|
fmt.Println("All migrations refreshed successfully")
|
||||||
|
|
||||||
|
case "status":
|
||||||
|
// Show migration status
|
||||||
|
migrations, err := ListMigrations(db)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Error listing migrations: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("Migration Status:")
|
||||||
|
fmt.Println("=================")
|
||||||
|
for _, migration := range migrations {
|
||||||
|
status := "Pending"
|
||||||
|
appliedAt := ""
|
||||||
|
if applied, ok := migration["applied"].(bool); ok && applied {
|
||||||
|
status = "Applied"
|
||||||
|
appliedAt = migration["applied_at"].(string)
|
||||||
|
}
|
||||||
|
fmt.Printf("%d: %s - %s %s\n", migration["version"], migration["description"], status, appliedAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
case "create":
|
||||||
|
if len(os.Args) < 3 {
|
||||||
|
fmt.Println("Error: Missing migration name")
|
||||||
|
printUsage()
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
name := os.Args[2]
|
||||||
|
if err := CreateMigration(name); err != nil {
|
||||||
|
log.Fatalf("Error creating migration: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
fmt.Printf("Error: Unknown command '%s'\n", command)
|
||||||
|
printUsage()
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func printUsage() {
|
||||||
|
fmt.Println("Usage: go run cmd/migrate/main.go <command> [args]")
|
||||||
|
fmt.Println("")
|
||||||
|
fmt.Println("Commands:")
|
||||||
|
fmt.Println(" up Apply all pending migrations")
|
||||||
|
fmt.Println(" down <version> Roll back migrations to specified version")
|
||||||
|
fmt.Println(" reset Roll back all migrations")
|
||||||
|
fmt.Println(" refresh Roll back all migrations and apply them again")
|
||||||
|
fmt.Println(" status Show migration status")
|
||||||
|
fmt.Println(" create <name> Create a new migration")
|
||||||
|
}
|
||||||
|
|
||||||
|
func CreateMigration(name string) error {
|
||||||
|
// Get next version number
|
||||||
|
allMigrations := getMigrations()
|
||||||
|
nextVersion := 1
|
||||||
|
for _, migration := range allMigrations {
|
||||||
|
if migration.Version >= nextVersion {
|
||||||
|
nextVersion = migration.Version + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create migration file - use absolute path from current working directory
|
||||||
|
filename := fmt.Sprintf("%03d_%s.go", nextVersion, name)
|
||||||
|
// Get the absolute path to the migrations directory
|
||||||
|
migrationDir, err := filepath.Abs("migrations")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to get migrations directory path: %v", err)
|
||||||
|
}
|
||||||
|
migrationPath := filepath.Join(migrationDir, filename)
|
||||||
|
|
||||||
|
// Check if file already exists
|
||||||
|
if _, err := os.Stat(migrationPath); err == nil {
|
||||||
|
return fmt.Errorf("migration file already exists: %s", migrationPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create migration file content
|
||||||
|
content := fmt.Sprintf(`package migrations
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
RegisterMigration(
|
||||||
|
%d,
|
||||||
|
"%s",
|
||||||
|
migrate%sUp,
|
||||||
|
migrate%sDown,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func migrate%sUp(tx *sql.Tx) error {
|
||||||
|
// TODO: Implement migration up
|
||||||
|
_, err := tx.Exec(`+"`"+`
|
||||||
|
-- Add your SQL here
|
||||||
|
`+"`"+`)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func migrate%sDown(tx *sql.Tx) error {
|
||||||
|
// TODO: Implement migration down
|
||||||
|
_, err := tx.Exec(`+"`"+`
|
||||||
|
-- Add your SQL here
|
||||||
|
`+"`"+`)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
`, nextVersion, name, name, name, name, name)
|
||||||
|
|
||||||
|
// Write file
|
||||||
|
if err := os.WriteFile(migrationPath, []byte(content), 0644); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Created migration file: %s\n", migrationPath)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
218
migrations/migrations.go
Normal file
218
migrations/migrations.go
Normal file
@@ -0,0 +1,218 @@
|
|||||||
|
package migrations
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"sort"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Migration represents a database migration
|
||||||
|
type Migration struct {
|
||||||
|
Version int
|
||||||
|
Description string
|
||||||
|
Up func(*sql.Tx) error
|
||||||
|
Down func(*sql.Tx) error
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
migrations = []Migration{}
|
||||||
|
mu sync.RWMutex
|
||||||
|
)
|
||||||
|
|
||||||
|
// RegisterMigration adds a migration to the list of available migrations
|
||||||
|
func RegisterMigration(version int, description string, up, down func(*sql.Tx) error) {
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
|
||||||
|
migrations = append(migrations, Migration{
|
||||||
|
Version: version,
|
||||||
|
Description: description,
|
||||||
|
Up: up,
|
||||||
|
Down: down,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Sort migrations by version
|
||||||
|
sort.Slice(migrations, func(i, j int) bool {
|
||||||
|
return migrations[i].Version < migrations[j].Version
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// getMigrations returns a copy of the migrations list (thread-safe)
|
||||||
|
func getMigrations() []Migration {
|
||||||
|
mu.RLock()
|
||||||
|
defer mu.RUnlock()
|
||||||
|
|
||||||
|
result := make([]Migration, len(migrations))
|
||||||
|
copy(result, migrations)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// InitMigrationTable creates the schema_migrations table if it doesn't exist
|
||||||
|
func InitMigrationTable(db *sql.DB) error {
|
||||||
|
_, err := db.Exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
|
version INTEGER PRIMARY KEY,
|
||||||
|
applied_at TIMESTAMP NOT NULL
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCurrentVersion returns the current database schema version
|
||||||
|
func GetCurrentVersion(db *sql.DB) (int, error) {
|
||||||
|
var version int
|
||||||
|
err := db.QueryRow(`
|
||||||
|
SELECT COALESCE(MAX(version), 0) FROM schema_migrations
|
||||||
|
`).Scan(&version)
|
||||||
|
return version, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// MigrateUp applies all pending migrations
|
||||||
|
func MigrateUp(db *sql.DB) error {
|
||||||
|
// Get current version
|
||||||
|
currentVersion, err := GetCurrentVersion(db)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply pending migrations
|
||||||
|
allMigrations := getMigrations()
|
||||||
|
for _, migration := range allMigrations {
|
||||||
|
if migration.Version > currentVersion {
|
||||||
|
log.Printf("Applying migration %d: %s", migration.Version, migration.Description)
|
||||||
|
|
||||||
|
// Begin transaction
|
||||||
|
tx, err := db.Begin()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply migration
|
||||||
|
if err := migration.Up(tx); err != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
return fmt.Errorf("error applying migration %d: %w", migration.Version, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Record migration
|
||||||
|
_, err = tx.Exec(
|
||||||
|
"INSERT INTO schema_migrations (version, applied_at) VALUES (?, ?)",
|
||||||
|
migration.Version, time.Now(),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
return fmt.Errorf("error recording migration %d: %w", migration.Version, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Commit transaction
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return fmt.Errorf("error committing migration %d: %w", migration.Version, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Successfully applied migration %d", migration.Version)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MigrateDown rolls back migrations to the specified version
|
||||||
|
// If targetVersion is 0, rolls back all migrations
|
||||||
|
func MigrateDown(db *sql.DB, targetVersion int) error {
|
||||||
|
// Get current version
|
||||||
|
currentVersion, err := GetCurrentVersion(db)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get a copy of migrations and sort in reverse order
|
||||||
|
allMigrations := getMigrations()
|
||||||
|
sort.Slice(allMigrations, func(i, j int) bool {
|
||||||
|
return allMigrations[i].Version > allMigrations[j].Version
|
||||||
|
})
|
||||||
|
|
||||||
|
// Roll back migrations
|
||||||
|
for _, migration := range allMigrations {
|
||||||
|
if migration.Version <= currentVersion && migration.Version > targetVersion {
|
||||||
|
log.Printf("Rolling back migration %d: %s", migration.Version, migration.Description)
|
||||||
|
|
||||||
|
// Begin transaction
|
||||||
|
tx, err := db.Begin()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply down migration
|
||||||
|
if err := migration.Down(tx); err != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
return fmt.Errorf("error rolling back migration %d: %w", migration.Version, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove migration record
|
||||||
|
_, err = tx.Exec(
|
||||||
|
"DELETE FROM schema_migrations WHERE version = ?",
|
||||||
|
migration.Version,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
return fmt.Errorf("error removing migration record %d: %w", migration.Version, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Commit transaction
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return fmt.Errorf("error committing rollback of migration %d: %w", migration.Version, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Successfully rolled back migration %d", migration.Version)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListMigrations returns a list of all available migrations and their status
|
||||||
|
func ListMigrations(db *sql.DB) ([]map[string]interface{}, error) {
|
||||||
|
// Get current version (unused but kept for reference)
|
||||||
|
_, err := GetCurrentVersion(db)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get applied migrations with timestamps
|
||||||
|
rows, err := db.Query("SELECT version, applied_at FROM schema_migrations")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
appliedMigrations := make(map[int]time.Time)
|
||||||
|
for rows.Next() {
|
||||||
|
var version int
|
||||||
|
var appliedAt time.Time
|
||||||
|
if err := rows.Scan(&version, &appliedAt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
appliedMigrations[version] = appliedAt
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create result
|
||||||
|
var result []map[string]interface{}
|
||||||
|
allMigrations := getMigrations()
|
||||||
|
for _, migration := range allMigrations {
|
||||||
|
appliedAt, applied := appliedMigrations[migration.Version]
|
||||||
|
appliedAtStr := ""
|
||||||
|
if applied {
|
||||||
|
appliedAtStr = appliedAt.Format("2006-01-02 15:04:05")
|
||||||
|
}
|
||||||
|
result = append(result, map[string]interface{}{
|
||||||
|
"version": migration.Version,
|
||||||
|
"description": migration.Description,
|
||||||
|
"applied": applied,
|
||||||
|
"applied_at": appliedAtStr,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
33
models.go
Normal file
33
models.go
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
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"`
|
||||||
|
}
|
||||||
39
queue.go
Normal file
39
queue.go
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Task func() error
|
||||||
|
|
||||||
|
type Queue struct {
|
||||||
|
ch chan Task
|
||||||
|
done chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewQueue(buf int) *Queue { return &Queue{ch: make(chan Task, buf)} }
|
||||||
|
|
||||||
|
func (q *Queue) Push(t Task) { q.ch <- t }
|
||||||
|
|
||||||
|
func (q *Queue) Run(ctx context.Context) {
|
||||||
|
q.done = make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
defer close(q.done)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case t := <-q.ch:
|
||||||
|
if err := t(); err != nil {
|
||||||
|
log.Printf("task failed: %v", err)
|
||||||
|
}
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queue) Stop() {
|
||||||
|
close(q.ch)
|
||||||
|
<-q.done
|
||||||
|
}
|
||||||
95
scanner.go
Normal file
95
scanner.go
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
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()
|
||||||
|
|
||||||
|
// Read metadata
|
||||||
|
metadata, err := tag.ReadFrom(file)
|
||||||
|
if err != nil {
|
||||||
|
return ScannedSong{}, fmt.Errorf("failed to read metadata: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract metadata
|
||||||
|
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
|
||||||
|
}
|
||||||
40
scanner_test.go
Normal file
40
scanner_test.go
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestIsAudioFile(t *testing.T) {
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
path string
|
||||||
|
expected bool
|
||||||
|
}{
|
||||||
|
{"mp3 file", "song.mp3", true},
|
||||||
|
{"flac file", "song.flac", true},
|
||||||
|
{"m4a file", "song.m4a", true},
|
||||||
|
{"wav file", "song.wav", true},
|
||||||
|
{"ogg file", "song.ogg", true},
|
||||||
|
{"aac file", "song.aac", false},
|
||||||
|
{"wma file", "song.wma", false},
|
||||||
|
{"uppercase extension", "song.MP3", true},
|
||||||
|
{"mixed case", "song.Mp3", true},
|
||||||
|
{"txt file", "song.txt", false},
|
||||||
|
{"jpg file", "song.jpg", false},
|
||||||
|
{"no extension", "song", false},
|
||||||
|
{"dot in name", "my.song.mp3", true},
|
||||||
|
{"multiple dots", "my.song.final.mp3", true},
|
||||||
|
{"path with directory", "/path/to/song.mp3", true},
|
||||||
|
{"Windows path", "C:\\Music\\song.mp3", true},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
result := isAudioFile(tt.path)
|
||||||
|
if result != tt.expected {
|
||||||
|
t.Errorf("isAudioFile(%q) = %v, want %v", tt.path, result, tt.expected)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
8
web/.editorconfig
Normal file
8
web/.editorconfig
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
[*.{js,jsx,mjs,cjs,ts,tsx,mts,cts,vue,css,scss,sass,less,styl}]
|
||||||
|
charset = utf-8
|
||||||
|
indent_size = 2
|
||||||
|
indent_style = space
|
||||||
|
insert_final_newline = true
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
end_of_line = lf
|
||||||
|
max_line_length = 100
|
||||||
1
web/.gitattributes
vendored
Normal file
1
web/.gitattributes
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
* text=auto eol=lf
|
||||||
36
web/.gitignore
vendored
Normal file
36
web/.gitignore
vendored
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
.DS_Store
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
coverage
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
|
|
||||||
|
*.tsbuildinfo
|
||||||
|
|
||||||
|
.eslintcache
|
||||||
|
|
||||||
|
# Cypress
|
||||||
|
/cypress/videos/
|
||||||
|
/cypress/screenshots/
|
||||||
|
|
||||||
|
# Vitest
|
||||||
|
__screenshots__/
|
||||||
6
web/.prettierrc.json
Normal file
6
web/.prettierrc.json
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/prettierrc",
|
||||||
|
"semi": false,
|
||||||
|
"singleQuote": true,
|
||||||
|
"printWidth": 100
|
||||||
|
}
|
||||||
9
web/.vscode/extensions.json
vendored
Normal file
9
web/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"recommendations": [
|
||||||
|
"Vue.volar",
|
||||||
|
"vitest.explorer",
|
||||||
|
"dbaeumer.vscode-eslint",
|
||||||
|
"EditorConfig.EditorConfig",
|
||||||
|
"esbenp.prettier-vscode"
|
||||||
|
]
|
||||||
|
}
|
||||||
50
web/README.md
Normal file
50
web/README.md
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
# web
|
||||||
|
|
||||||
|
This template should help get you started developing with Vue 3 in Vite.
|
||||||
|
|
||||||
|
## Recommended IDE Setup
|
||||||
|
|
||||||
|
[VS Code](https://code.visualstudio.com/) + [Vue (Official)](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur).
|
||||||
|
|
||||||
|
## Recommended Browser Setup
|
||||||
|
|
||||||
|
- Chromium-based browsers (Chrome, Edge, Brave, etc.):
|
||||||
|
- [Vue.js devtools](https://chromewebstore.google.com/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd)
|
||||||
|
- [Turn on Custom Object Formatter in Chrome DevTools](http://bit.ly/object-formatters)
|
||||||
|
- Firefox:
|
||||||
|
- [Vue.js devtools](https://addons.mozilla.org/en-US/firefox/addon/vue-js-devtools/)
|
||||||
|
- [Turn on Custom Object Formatter in Firefox DevTools](https://fxdx.dev/firefox-devtools-custom-object-formatters/)
|
||||||
|
|
||||||
|
## Customize configuration
|
||||||
|
|
||||||
|
See [Vite Configuration Reference](https://vite.dev/config/).
|
||||||
|
|
||||||
|
## Project Setup
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm install
|
||||||
|
```
|
||||||
|
|
||||||
|
### Compile and Hot-Reload for Development
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### Compile and Minify for Production
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm build
|
||||||
|
```
|
||||||
|
|
||||||
|
### Run Unit Tests with [Vitest](https://vitest.dev/)
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm test:unit
|
||||||
|
```
|
||||||
|
|
||||||
|
### Lint with [ESLint](https://eslint.org/)
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm lint
|
||||||
|
```
|
||||||
32
web/eslint.config.js
Normal file
32
web/eslint.config.js
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||||
|
import globals from 'globals'
|
||||||
|
import js from '@eslint/js'
|
||||||
|
import pluginVue from 'eslint-plugin-vue'
|
||||||
|
import pluginVitest from '@vitest/eslint-plugin'
|
||||||
|
import skipFormatting from '@vue/eslint-config-prettier/skip-formatting'
|
||||||
|
|
||||||
|
export default defineConfig([
|
||||||
|
{
|
||||||
|
name: 'app/files-to-lint',
|
||||||
|
files: ['**/*.{js,mjs,jsx,vue}'],
|
||||||
|
},
|
||||||
|
|
||||||
|
globalIgnores(['**/dist/**', '**/dist-ssr/**', '**/coverage/**']),
|
||||||
|
|
||||||
|
{
|
||||||
|
languageOptions: {
|
||||||
|
globals: {
|
||||||
|
...globals.browser,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
js.configs.recommended,
|
||||||
|
...pluginVue.configs['flat/essential'],
|
||||||
|
|
||||||
|
{
|
||||||
|
...pluginVitest.configs.recommended,
|
||||||
|
files: ['src/**/__tests__/*'],
|
||||||
|
},
|
||||||
|
skipFormatting,
|
||||||
|
])
|
||||||
13
web/index.html
Normal file
13
web/index.html
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<link rel="icon" href="/favicon.ico">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Vite App</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<script type="module" src="/src/main.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
8
web/jsconfig.json
Normal file
8
web/jsconfig.json
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["./src/*"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"exclude": ["node_modules", "dist"]
|
||||||
|
}
|
||||||
39
web/package.json
Normal file
39
web/package.json
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
{
|
||||||
|
"name": "web",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"engines": {
|
||||||
|
"node": "^20.19.0 || >=22.12.0"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"preview": "vite preview",
|
||||||
|
"test:unit": "vitest",
|
||||||
|
"lint": "eslint . --fix --cache",
|
||||||
|
"format": "prettier --write --experimental-cli src/"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"lucide-vue-next": "^0.561.0",
|
||||||
|
"open-props": "^1.7.17",
|
||||||
|
"pinia": "^3.0.4",
|
||||||
|
"vue": "^3.5.25",
|
||||||
|
"vue-router": "^4.6.3"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^9.39.1",
|
||||||
|
"@vitejs/plugin-vue": "^6.0.2",
|
||||||
|
"@vitest/eslint-plugin": "^1.5.0",
|
||||||
|
"@vue/eslint-config-prettier": "^10.2.0",
|
||||||
|
"@vue/test-utils": "^2.4.6",
|
||||||
|
"eslint": "^9.39.1",
|
||||||
|
"eslint-plugin-vue": "~10.5.1",
|
||||||
|
"globals": "^16.5.0",
|
||||||
|
"jsdom": "^27.2.0",
|
||||||
|
"prettier": "3.6.2",
|
||||||
|
"vite": "npm:rolldown-vite@latest",
|
||||||
|
"vite-plugin-vue-devtools": "^8.0.5",
|
||||||
|
"vitest": "^4.0.14"
|
||||||
|
}
|
||||||
|
}
|
||||||
3952
web/pnpm-lock.yaml
generated
Normal file
3952
web/pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
BIN
web/public/favicon.ico
Normal file
BIN
web/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
17
web/src/App.vue
Normal file
17
web/src/App.vue
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
<script setup>
|
||||||
|
import { RouterLink, RouterView } from 'vue-router'
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<header>
|
||||||
|
<nav>
|
||||||
|
<RouterLink to="/music">所有歌曲</RouterLink>
|
||||||
|
<RouterLink to="/settings">设置</RouterLink>
|
||||||
|
<RouterLink to="/about">About</RouterLink>
|
||||||
|
</nav>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<RouterView />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped></style>
|
||||||
20
web/src/assets/base.css
Normal file
20
web/src/assets/base.css
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
/* the props */
|
||||||
|
@import 'open-props/style';
|
||||||
|
|
||||||
|
/* optional imports that use the props */
|
||||||
|
@import 'open-props/normalize';
|
||||||
|
@import 'open-props/buttons';
|
||||||
|
|
||||||
|
/* just light or dark themes */
|
||||||
|
@import 'open-props/normalize/dark';
|
||||||
|
@import 'open-props/buttons/dark';
|
||||||
|
@import 'open-props/normalize/light';
|
||||||
|
@import 'open-props/buttons/light';
|
||||||
|
|
||||||
|
/* individual imports */
|
||||||
|
@import 'open-props/indigo';
|
||||||
|
@import 'open-props/easings';
|
||||||
|
@import 'open-props/animations';
|
||||||
|
@import 'open-props/sizes';
|
||||||
|
@import 'open-props/gradients';
|
||||||
|
/* see PropPacks for the full list */
|
||||||
1
web/src/assets/logo.svg
Normal file
1
web/src/assets/logo.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 261.76 226.69"><path d="M161.096.001l-30.225 52.351L100.647.001H-.005l130.877 226.688L261.749.001z" fill="#41b883"/><path d="M161.096.001l-30.225 52.351L100.647.001H52.346l78.526 136.01L209.398.001z" fill="#34495e"/></svg>
|
||||||
|
After Width: | Height: | Size: 276 B |
23
web/src/assets/main.css
Normal file
23
web/src/assets/main.css
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
@import './base.css';
|
||||||
|
|
||||||
|
/* 使用 Open Props 的自定义颜色变量 */
|
||||||
|
:root {
|
||||||
|
--brand: var(--orange-6);
|
||||||
|
--brand-hover: var(--orange-7);
|
||||||
|
--brand-light: var(--orange-3);
|
||||||
|
--text-light: var(--gray-5);
|
||||||
|
}
|
||||||
|
|
||||||
|
h1,
|
||||||
|
h2,
|
||||||
|
h3,
|
||||||
|
h4 {
|
||||||
|
color: var(--gray-8);
|
||||||
|
font-family: var(--font-transitional);
|
||||||
|
}
|
||||||
|
|
||||||
|
p,
|
||||||
|
li {
|
||||||
|
color: var(--gray-7);
|
||||||
|
font-family: var(--font-humanist);
|
||||||
|
}
|
||||||
72
web/src/components/AddLibraryDialog.vue
Normal file
72
web/src/components/AddLibraryDialog.vue
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
<template>
|
||||||
|
<dialog ref="dialogRef" :open="modelValue" @cancel="handleCancel" @close="handleClose">
|
||||||
|
<form method="dialog">
|
||||||
|
<p>添加音乐库</p>
|
||||||
|
<div class="dialog-body">
|
||||||
|
<input v-model="name" type="text" placeholder="名称" />
|
||||||
|
<input v-model="path" type="text" placeholder="路径" />
|
||||||
|
<div class="dialog-buttons">
|
||||||
|
<button :disabled="!validated" @click="confirm" value="confirm">确认</button>
|
||||||
|
<button @click="close" value="cancel">取消</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, computed, watch } from 'vue'
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
modelValue: Boolean,
|
||||||
|
title: String,
|
||||||
|
})
|
||||||
|
|
||||||
|
const name = ref()
|
||||||
|
const path = ref()
|
||||||
|
|
||||||
|
const emit = defineEmits(['update:modelValue', 'confirm'])
|
||||||
|
|
||||||
|
const dialogRef = ref(null)
|
||||||
|
|
||||||
|
// 监听外部值变化,同步到 dialog 元素
|
||||||
|
watch(
|
||||||
|
() => props.modelValue,
|
||||||
|
(val) => {
|
||||||
|
if (val) {
|
||||||
|
dialogRef.value?.showModal()
|
||||||
|
} else {
|
||||||
|
dialogRef.value?.close()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
// 关闭时更新 v-model
|
||||||
|
const close = () => emit('update:modelValue', false)
|
||||||
|
const confirm = () => {
|
||||||
|
emit('confirm', name.value, path.value)
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
|
||||||
|
const validated = computed(() => name.value && path.value)
|
||||||
|
|
||||||
|
// ESC 键触发 cancel 事件
|
||||||
|
const handleCancel = () => close()
|
||||||
|
// 调用 close() 时触发
|
||||||
|
const handleClose = () => emit('update:modelValue', false)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.dialog-body {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--size-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.dialog-buttons {
|
||||||
|
display: flex;
|
||||||
|
gap: var(--size-3);
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
14
web/src/components/DropDown.vue
Normal file
14
web/src/components/DropDown.vue
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
<template>
|
||||||
|
<div @click="visible = !visible">
|
||||||
|
<slot name="trigger"></slot>
|
||||||
|
</div>
|
||||||
|
<div v-if="visible">
|
||||||
|
<slot></slot>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
const visible = ref(false)
|
||||||
|
</script>
|
||||||
44
web/src/components/HelloWorld.vue
Normal file
44
web/src/components/HelloWorld.vue
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
<script setup>
|
||||||
|
defineProps({
|
||||||
|
msg: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="greetings">
|
||||||
|
<h1 class="green">{{ msg }}</h1>
|
||||||
|
<h3>
|
||||||
|
You’ve successfully created a project with
|
||||||
|
<a href="https://vite.dev/" target="_blank" rel="noopener">Vite</a> +
|
||||||
|
<a href="https://vuejs.org/" target="_blank" rel="noopener">Vue 3</a>.
|
||||||
|
</h3>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
h1 {
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: 2.6rem;
|
||||||
|
position: relative;
|
||||||
|
top: -10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
h3 {
|
||||||
|
font-size: 1.2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.greetings h1,
|
||||||
|
.greetings h3 {
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (min-width: 1024px) {
|
||||||
|
.greetings h1,
|
||||||
|
.greetings h3 {
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
50
web/src/components/LibraryCard.vue
Normal file
50
web/src/components/LibraryCard.vue
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
<template>
|
||||||
|
<div class="library-card">
|
||||||
|
<h4>{{ props.name }}</h4>
|
||||||
|
<DropDown>
|
||||||
|
<template v-slot:trigger>
|
||||||
|
<button><EllipsisVertical /></button>
|
||||||
|
</template>
|
||||||
|
<button @click="viewSongs">查看歌曲</button>
|
||||||
|
<button @click="scanCard">扫描</button>
|
||||||
|
<button type="reset" @click="deleteCard">删除</button>
|
||||||
|
</DropDown>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { EllipsisVertical } from 'lucide-vue-next'
|
||||||
|
import PopupMenu from './PopupMenu.vue'
|
||||||
|
import DropDown from './DropDown.vue'
|
||||||
|
const props = defineProps({
|
||||||
|
name: String,
|
||||||
|
id: Number,
|
||||||
|
})
|
||||||
|
const emit = defineEmits(['delete', 'scan', 'viewSongs'])
|
||||||
|
|
||||||
|
const scanCard = () => {
|
||||||
|
emit('scan', props.id)
|
||||||
|
}
|
||||||
|
const deleteCard = () => {
|
||||||
|
emit('delete', props.id)
|
||||||
|
}
|
||||||
|
const viewSongs = () => {
|
||||||
|
emit('viewSongs', props.id)
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.library-card {
|
||||||
|
max-width: var(--size-fluid-8);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
background-color: var(--stone-3);
|
||||||
|
aspect-ratio: var(--ratio-square);
|
||||||
|
border-radius: var(--radius-2);
|
||||||
|
box-shadow: var(--shadow-1);
|
||||||
|
padding: var(--size-6);
|
||||||
|
margin: var(--size-3);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
102
web/src/components/PopupMenu.vue
Normal file
102
web/src/components/PopupMenu.vue
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
<template>
|
||||||
|
<slot name="trigger" @click.prevent="console.log(222)"></slot>
|
||||||
|
<!-- 遮罩:点击外部关闭 -->
|
||||||
|
<div v-if="visible" class="pm-mask" @click="close" @contextmenu.prevent></div>
|
||||||
|
|
||||||
|
<!-- 菜单容器 -->
|
||||||
|
<Transition name="pm-fade">
|
||||||
|
<div
|
||||||
|
v-if="visible"
|
||||||
|
class="pm-wrapper"
|
||||||
|
:style="{ top: y + 'px', left: x + 'px' }"
|
||||||
|
@contextmenu.prevent
|
||||||
|
></div>
|
||||||
|
</Transition>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { nextTick, onBeforeUnmount, ref, watch } from 'vue'
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
items: { type: Array, default: () => [] }, // 菜单项
|
||||||
|
show: Boolean, // 显示开关
|
||||||
|
point: { type: Object, default: () => ({ x: 0, y: 0 }) }, // 坐标
|
||||||
|
})
|
||||||
|
|
||||||
|
const emit = defineEmits(['update:show', 'select'])
|
||||||
|
|
||||||
|
const visible = ref(false)
|
||||||
|
const x = ref(0)
|
||||||
|
const y = ref(0)
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => props.show,
|
||||||
|
async (val) => {
|
||||||
|
if (!val) return (visible.value = false)
|
||||||
|
// 先拿到坐标再渲染,防止超出屏幕
|
||||||
|
x.value = props.point.x
|
||||||
|
y.value = props.point.y
|
||||||
|
visible.value = true
|
||||||
|
await nextTick()
|
||||||
|
fixPosition()
|
||||||
|
// 全局监听
|
||||||
|
document.addEventListener('keydown', onKeyDown)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
function fixPosition() {
|
||||||
|
const el = document.querySelector('.pm-wrapper')
|
||||||
|
if (!el) return
|
||||||
|
const { innerWidth, innerHeight } = window
|
||||||
|
const { offsetWidth: w, offsetHeight: h } = el
|
||||||
|
if (x.value + w > innerWidth) x.value = innerWidth - w - 4
|
||||||
|
if (y.value + h > innerHeight) y.value = innerHeight - h - 4
|
||||||
|
}
|
||||||
|
|
||||||
|
function close() {
|
||||||
|
visible.value = false
|
||||||
|
emit('update:show', false)
|
||||||
|
document.removeEventListener('keydown', onKeyDown)
|
||||||
|
}
|
||||||
|
|
||||||
|
function onKeyDown(e) {
|
||||||
|
if (e.key === 'Escape') close()
|
||||||
|
}
|
||||||
|
|
||||||
|
function onClick(item) {
|
||||||
|
if (item.disabled) return
|
||||||
|
emit('select', item)
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
|
||||||
|
onBeforeUnmount(() => document.removeEventListener('keydown', onKeyDown))
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.pm-mask {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 998;
|
||||||
|
}
|
||||||
|
.pm-wrapper {
|
||||||
|
position: fixed;
|
||||||
|
z-index: 999;
|
||||||
|
background: #fff;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 4px 0;
|
||||||
|
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
.pm-fade-enter-active,
|
||||||
|
.pm-fade-leave-active {
|
||||||
|
transition:
|
||||||
|
opacity 0.15s,
|
||||||
|
transform 0.15s;
|
||||||
|
transform-origin: left top;
|
||||||
|
}
|
||||||
|
.pm-fade-enter-from,
|
||||||
|
.pm-fade-leave-to {
|
||||||
|
opacity: 0;
|
||||||
|
transform: scale(0.95);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
95
web/src/components/TheWelcome.vue
Normal file
95
web/src/components/TheWelcome.vue
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
<script setup>
|
||||||
|
import WelcomeItem from './WelcomeItem.vue'
|
||||||
|
import DocumentationIcon from './icons/IconDocumentation.vue'
|
||||||
|
import ToolingIcon from './icons/IconTooling.vue'
|
||||||
|
import EcosystemIcon from './icons/IconEcosystem.vue'
|
||||||
|
import CommunityIcon from './icons/IconCommunity.vue'
|
||||||
|
import SupportIcon from './icons/IconSupport.vue'
|
||||||
|
|
||||||
|
const openReadmeInEditor = () => fetch('/__open-in-editor?file=README.md')
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<WelcomeItem>
|
||||||
|
<template #icon>
|
||||||
|
<DocumentationIcon />
|
||||||
|
</template>
|
||||||
|
<template #heading>Documentation</template>
|
||||||
|
|
||||||
|
Vue’s
|
||||||
|
<a href="https://vuejs.org/" target="_blank" rel="noopener">official documentation</a>
|
||||||
|
provides you with all information you need to get started.
|
||||||
|
</WelcomeItem>
|
||||||
|
|
||||||
|
<WelcomeItem>
|
||||||
|
<template #icon>
|
||||||
|
<ToolingIcon />
|
||||||
|
</template>
|
||||||
|
<template #heading>Tooling</template>
|
||||||
|
|
||||||
|
This project is served and bundled with
|
||||||
|
<a href="https://vite.dev/guide/features.html" target="_blank" rel="noopener">Vite</a>. The
|
||||||
|
recommended IDE setup is
|
||||||
|
<a href="https://code.visualstudio.com/" target="_blank" rel="noopener">VSCode</a>
|
||||||
|
+
|
||||||
|
<a href="https://github.com/vuejs/language-tools" target="_blank" rel="noopener"
|
||||||
|
>Vue - Official</a
|
||||||
|
>. If you need to test your components and web pages, check out
|
||||||
|
<a href="https://vitest.dev/" target="_blank" rel="noopener">Vitest</a>
|
||||||
|
and
|
||||||
|
<a href="https://www.cypress.io/" target="_blank" rel="noopener">Cypress</a>
|
||||||
|
/
|
||||||
|
<a href="https://playwright.dev/" target="_blank" rel="noopener">Playwright</a>.
|
||||||
|
|
||||||
|
<br />
|
||||||
|
|
||||||
|
More instructions are available in
|
||||||
|
<a href="javascript:void(0)" @click="openReadmeInEditor"><code>README.md</code></a
|
||||||
|
>.
|
||||||
|
</WelcomeItem>
|
||||||
|
|
||||||
|
<WelcomeItem>
|
||||||
|
<template #icon>
|
||||||
|
<EcosystemIcon />
|
||||||
|
</template>
|
||||||
|
<template #heading>Ecosystem</template>
|
||||||
|
|
||||||
|
Get official tools and libraries for your project:
|
||||||
|
<a href="https://pinia.vuejs.org/" target="_blank" rel="noopener">Pinia</a>,
|
||||||
|
<a href="https://router.vuejs.org/" target="_blank" rel="noopener">Vue Router</a>,
|
||||||
|
<a href="https://test-utils.vuejs.org/" target="_blank" rel="noopener">Vue Test Utils</a>, and
|
||||||
|
<a href="https://github.com/vuejs/devtools" target="_blank" rel="noopener">Vue Dev Tools</a>. If
|
||||||
|
you need more resources, we suggest paying
|
||||||
|
<a href="https://github.com/vuejs/awesome-vue" target="_blank" rel="noopener">Awesome Vue</a>
|
||||||
|
a visit.
|
||||||
|
</WelcomeItem>
|
||||||
|
|
||||||
|
<WelcomeItem>
|
||||||
|
<template #icon>
|
||||||
|
<CommunityIcon />
|
||||||
|
</template>
|
||||||
|
<template #heading>Community</template>
|
||||||
|
|
||||||
|
Got stuck? Ask your question on
|
||||||
|
<a href="https://chat.vuejs.org" target="_blank" rel="noopener">Vue Land</a>
|
||||||
|
(our official Discord server), or
|
||||||
|
<a href="https://stackoverflow.com/questions/tagged/vue.js" target="_blank" rel="noopener"
|
||||||
|
>StackOverflow</a
|
||||||
|
>. You should also follow the official
|
||||||
|
<a href="https://bsky.app/profile/vuejs.org" target="_blank" rel="noopener">@vuejs.org</a>
|
||||||
|
Bluesky account or the
|
||||||
|
<a href="https://x.com/vuejs" target="_blank" rel="noopener">@vuejs</a>
|
||||||
|
X account for latest news in the Vue world.
|
||||||
|
</WelcomeItem>
|
||||||
|
|
||||||
|
<WelcomeItem>
|
||||||
|
<template #icon>
|
||||||
|
<SupportIcon />
|
||||||
|
</template>
|
||||||
|
<template #heading>Support Vue</template>
|
||||||
|
|
||||||
|
As an independent project, Vue relies on community backing for its sustainability. You can help
|
||||||
|
us by
|
||||||
|
<a href="https://vuejs.org/sponsor/" target="_blank" rel="noopener">becoming a sponsor</a>.
|
||||||
|
</WelcomeItem>
|
||||||
|
</template>
|
||||||
86
web/src/components/WelcomeItem.vue
Normal file
86
web/src/components/WelcomeItem.vue
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
<template>
|
||||||
|
<div class="item">
|
||||||
|
<i>
|
||||||
|
<slot name="icon"></slot>
|
||||||
|
</i>
|
||||||
|
<div class="details">
|
||||||
|
<h3>
|
||||||
|
<slot name="heading"></slot>
|
||||||
|
</h3>
|
||||||
|
<slot></slot>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.item {
|
||||||
|
margin-top: 2rem;
|
||||||
|
display: flex;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.details {
|
||||||
|
flex: 1;
|
||||||
|
margin-left: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
i {
|
||||||
|
display: flex;
|
||||||
|
place-items: center;
|
||||||
|
place-content: center;
|
||||||
|
width: 32px;
|
||||||
|
height: 32px;
|
||||||
|
color: var(--color-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
h3 {
|
||||||
|
font-size: 1.2rem;
|
||||||
|
font-weight: 500;
|
||||||
|
margin-bottom: 0.4rem;
|
||||||
|
color: var(--color-heading);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (min-width: 1024px) {
|
||||||
|
.item {
|
||||||
|
margin-top: 0;
|
||||||
|
padding: 0.4rem 0 1rem calc(var(--section-gap) / 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
i {
|
||||||
|
top: calc(50% - 25px);
|
||||||
|
left: -26px;
|
||||||
|
position: absolute;
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
background: var(--color-background);
|
||||||
|
border-radius: 8px;
|
||||||
|
width: 50px;
|
||||||
|
height: 50px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.item:before {
|
||||||
|
content: ' ';
|
||||||
|
border-left: 1px solid var(--color-border);
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
bottom: calc(50% + 25px);
|
||||||
|
height: calc(50% - 25px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.item:after {
|
||||||
|
content: ' ';
|
||||||
|
border-left: 1px solid var(--color-border);
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
top: calc(50% + 25px);
|
||||||
|
height: calc(50% - 25px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.item:first-of-type:before {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.item:last-of-type:after {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
11
web/src/components/__tests__/HelloWorld.spec.js
Normal file
11
web/src/components/__tests__/HelloWorld.spec.js
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { describe, it, expect } from 'vitest'
|
||||||
|
|
||||||
|
import { mount } from '@vue/test-utils'
|
||||||
|
import HelloWorld from '../HelloWorld.vue'
|
||||||
|
|
||||||
|
describe('HelloWorld', () => {
|
||||||
|
it('renders properly', () => {
|
||||||
|
const wrapper = mount(HelloWorld, { props: { msg: 'Hello Vitest' } })
|
||||||
|
expect(wrapper.text()).toContain('Hello Vitest')
|
||||||
|
})
|
||||||
|
})
|
||||||
7
web/src/components/icons/IconCommunity.vue
Normal file
7
web/src/components/icons/IconCommunity.vue
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
<template>
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor">
|
||||||
|
<path
|
||||||
|
d="M15 4a1 1 0 1 0 0 2V4zm0 11v-1a1 1 0 0 0-1 1h1zm0 4l-.707.707A1 1 0 0 0 16 19h-1zm-4-4l.707-.707A1 1 0 0 0 11 14v1zm-4.707-1.293a1 1 0 0 0-1.414 1.414l1.414-1.414zm-.707.707l-.707-.707.707.707zM9 11v-1a1 1 0 0 0-.707.293L9 11zm-4 0h1a1 1 0 0 0-1-1v1zm0 4H4a1 1 0 0 0 1.707.707L5 15zm10-9h2V4h-2v2zm2 0a1 1 0 0 1 1 1h2a3 3 0 0 0-3-3v2zm1 1v6h2V7h-2zm0 6a1 1 0 0 1-1 1v2a3 3 0 0 0 3-3h-2zm-1 1h-2v2h2v-2zm-3 1v4h2v-4h-2zm1.707 3.293l-4-4-1.414 1.414 4 4 1.414-1.414zM11 14H7v2h4v-2zm-4 0c-.276 0-.525-.111-.707-.293l-1.414 1.414C5.42 15.663 6.172 16 7 16v-2zm-.707 1.121l3.414-3.414-1.414-1.414-3.414 3.414 1.414 1.414zM9 12h4v-2H9v2zm4 0a3 3 0 0 0 3-3h-2a1 1 0 0 1-1 1v2zm3-3V3h-2v6h2zm0-6a3 3 0 0 0-3-3v2a1 1 0 0 1 1 1h2zm-3-3H3v2h10V0zM3 0a3 3 0 0 0-3 3h2a1 1 0 0 1 1-1V0zM0 3v6h2V3H0zm0 6a3 3 0 0 0 3 3v-2a1 1 0 0 1-1-1H0zm3 3h2v-2H3v2zm1-1v4h2v-4H4zm1.707 4.707l.586-.586-1.414-1.414-.586.586 1.414 1.414z"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</template>
|
||||||
7
web/src/components/icons/IconDocumentation.vue
Normal file
7
web/src/components/icons/IconDocumentation.vue
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
<template>
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" fill="currentColor">
|
||||||
|
<path
|
||||||
|
d="M11 2.253a1 1 0 1 0-2 0h2zm-2 13a1 1 0 1 0 2 0H9zm.447-12.167a1 1 0 1 0 1.107-1.666L9.447 3.086zM1 2.253L.447 1.42A1 1 0 0 0 0 2.253h1zm0 13H0a1 1 0 0 0 1.553.833L1 15.253zm8.447.833a1 1 0 1 0 1.107-1.666l-1.107 1.666zm0-14.666a1 1 0 1 0 1.107 1.666L9.447 1.42zM19 2.253h1a1 1 0 0 0-.447-.833L19 2.253zm0 13l-.553.833A1 1 0 0 0 20 15.253h-1zm-9.553-.833a1 1 0 1 0 1.107 1.666L9.447 14.42zM9 2.253v13h2v-13H9zm1.553-.833C9.203.523 7.42 0 5.5 0v2c1.572 0 2.961.431 3.947 1.086l1.107-1.666zM5.5 0C3.58 0 1.797.523.447 1.42l1.107 1.666C2.539 2.431 3.928 2 5.5 2V0zM0 2.253v13h2v-13H0zm1.553 13.833C2.539 15.431 3.928 15 5.5 15v-2c-1.92 0-3.703.523-5.053 1.42l1.107 1.666zM5.5 15c1.572 0 2.961.431 3.947 1.086l1.107-1.666C9.203 13.523 7.42 13 5.5 13v2zm5.053-11.914C11.539 2.431 12.928 2 14.5 2V0c-1.92 0-3.703.523-5.053 1.42l1.107 1.666zM14.5 2c1.573 0 2.961.431 3.947 1.086l1.107-1.666C18.203.523 16.421 0 14.5 0v2zm3.5.253v13h2v-13h-2zm1.553 12.167C18.203 13.523 16.421 13 14.5 13v2c1.573 0 2.961.431 3.947 1.086l1.107-1.666zM14.5 13c-1.92 0-3.703.523-5.053 1.42l1.107 1.666C11.539 15.431 12.928 15 14.5 15v-2z"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</template>
|
||||||
7
web/src/components/icons/IconEcosystem.vue
Normal file
7
web/src/components/icons/IconEcosystem.vue
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
<template>
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="20" fill="currentColor">
|
||||||
|
<path
|
||||||
|
d="M11.447 8.894a1 1 0 1 0-.894-1.789l.894 1.789zm-2.894-.789a1 1 0 1 0 .894 1.789l-.894-1.789zm0 1.789a1 1 0 1 0 .894-1.789l-.894 1.789zM7.447 7.106a1 1 0 1 0-.894 1.789l.894-1.789zM10 9a1 1 0 1 0-2 0h2zm-2 2.5a1 1 0 1 0 2 0H8zm9.447-5.606a1 1 0 1 0-.894-1.789l.894 1.789zm-2.894-.789a1 1 0 1 0 .894 1.789l-.894-1.789zm2 .789a1 1 0 1 0 .894-1.789l-.894 1.789zm-1.106-2.789a1 1 0 1 0-.894 1.789l.894-1.789zM18 5a1 1 0 1 0-2 0h2zm-2 2.5a1 1 0 1 0 2 0h-2zm-5.447-4.606a1 1 0 1 0 .894-1.789l-.894 1.789zM9 1l.447-.894a1 1 0 0 0-.894 0L9 1zm-2.447.106a1 1 0 1 0 .894 1.789l-.894-1.789zm-6 3a1 1 0 1 0 .894 1.789L.553 4.106zm2.894.789a1 1 0 1 0-.894-1.789l.894 1.789zm-2-.789a1 1 0 1 0-.894 1.789l.894-1.789zm1.106 2.789a1 1 0 1 0 .894-1.789l-.894 1.789zM2 5a1 1 0 1 0-2 0h2zM0 7.5a1 1 0 1 0 2 0H0zm8.553 12.394a1 1 0 1 0 .894-1.789l-.894 1.789zm-1.106-2.789a1 1 0 1 0-.894 1.789l.894-1.789zm1.106 1a1 1 0 1 0 .894 1.789l-.894-1.789zm2.894.789a1 1 0 1 0-.894-1.789l.894 1.789zM8 19a1 1 0 1 0 2 0H8zm2-2.5a1 1 0 1 0-2 0h2zm-7.447.394a1 1 0 1 0 .894-1.789l-.894 1.789zM1 15H0a1 1 0 0 0 .553.894L1 15zm1-2.5a1 1 0 1 0-2 0h2zm12.553 2.606a1 1 0 1 0 .894 1.789l-.894-1.789zM17 15l.447.894A1 1 0 0 0 18 15h-1zm1-2.5a1 1 0 1 0-2 0h2zm-7.447-5.394l-2 1 .894 1.789 2-1-.894-1.789zm-1.106 1l-2-1-.894 1.789 2 1 .894-1.789zM8 9v2.5h2V9H8zm8.553-4.894l-2 1 .894 1.789 2-1-.894-1.789zm.894 0l-2-1-.894 1.789 2 1 .894-1.789zM16 5v2.5h2V5h-2zm-4.553-3.894l-2-1-.894 1.789 2 1 .894-1.789zm-2.894-1l-2 1 .894 1.789 2-1L8.553.106zM1.447 5.894l2-1-.894-1.789-2 1 .894 1.789zm-.894 0l2 1 .894-1.789-2-1-.894 1.789zM0 5v2.5h2V5H0zm9.447 13.106l-2-1-.894 1.789 2 1 .894-1.789zm0 1.789l2-1-.894-1.789-2 1 .894 1.789zM10 19v-2.5H8V19h2zm-6.553-3.894l-2-1-.894 1.789 2 1 .894-1.789zM2 15v-2.5H0V15h2zm13.447 1.894l2-1-.894-1.789-2 1 .894 1.789zM18 15v-2.5h-2V15h2z"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</template>
|
||||||
7
web/src/components/icons/IconSupport.vue
Normal file
7
web/src/components/icons/IconSupport.vue
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
<template>
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor">
|
||||||
|
<path
|
||||||
|
d="M10 3.22l-.61-.6a5.5 5.5 0 0 0-7.666.105 5.5 5.5 0 0 0-.114 7.665L10 18.78l8.39-8.4a5.5 5.5 0 0 0-.114-7.665 5.5 5.5 0 0 0-7.666-.105l-.61.61z"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</template>
|
||||||
19
web/src/components/icons/IconTooling.vue
Normal file
19
web/src/components/icons/IconTooling.vue
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
<!-- This icon is from <https://github.com/Templarian/MaterialDesign>, distributed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0) license-->
|
||||||
|
<template>
|
||||||
|
<svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||||
|
aria-hidden="true"
|
||||||
|
role="img"
|
||||||
|
class="iconify iconify--mdi"
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
preserveAspectRatio="xMidYMid meet"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
d="M20 18v-4h-3v1h-2v-1H9v1H7v-1H4v4h16M6.33 8l-1.74 4H7v-1h2v1h6v-1h2v1h2.41l-1.74-4H6.33M9 5v1h6V5H9m12.84 7.61c.1.22.16.48.16.8V18c0 .53-.21 1-.6 1.41c-.4.4-.85.59-1.4.59H4c-.55 0-1-.19-1.4-.59C2.21 19 2 18.53 2 18v-4.59c0-.32.06-.58.16-.8L4.5 7.22C4.84 6.41 5.45 6 6.33 6H7V5c0-.55.18-1 .57-1.41C7.96 3.2 8.44 3 9 3h6c.56 0 1.04.2 1.43.59c.39.41.57.86.57 1.41v1h.67c.88 0 1.49.41 1.83 1.22l2.34 5.39z"
|
||||||
|
fill="currentColor"
|
||||||
|
></path>
|
||||||
|
</svg>
|
||||||
|
</template>
|
||||||
14
web/src/main.js
Normal file
14
web/src/main.js
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import './assets/main.css'
|
||||||
|
|
||||||
|
import { createApp } from 'vue'
|
||||||
|
import { createPinia } from 'pinia'
|
||||||
|
|
||||||
|
import App from './App.vue'
|
||||||
|
import router from './router'
|
||||||
|
|
||||||
|
const app = createApp(App)
|
||||||
|
|
||||||
|
app.use(createPinia())
|
||||||
|
app.use(router)
|
||||||
|
|
||||||
|
app.mount('#app')
|
||||||
38
web/src/router/index.js
Normal file
38
web/src/router/index.js
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import { createRouter, createWebHistory } from 'vue-router'
|
||||||
|
import HomeView from '../views/HomeView.vue'
|
||||||
|
|
||||||
|
const router = createRouter({
|
||||||
|
history: createWebHistory(import.meta.env.BASE_URL),
|
||||||
|
routes: [
|
||||||
|
{
|
||||||
|
path: '/',
|
||||||
|
name: 'home',
|
||||||
|
component: HomeView,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/music',
|
||||||
|
name: 'music',
|
||||||
|
component: () => import('../views/MusicView.vue'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/music/:id',
|
||||||
|
name: 'music-library',
|
||||||
|
component: () => import('../views/MusicView.vue'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/settings',
|
||||||
|
name: 'settings',
|
||||||
|
component: () => import('../views/SettingsView.vue'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/about',
|
||||||
|
name: 'about',
|
||||||
|
// route level code-splitting
|
||||||
|
// this generates a separate chunk (About.[hash].js) for this route
|
||||||
|
// which is lazy-loaded when the route is visited.
|
||||||
|
component: () => import('../views/AboutView.vue'),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
export default router
|
||||||
65
web/src/stores/butterfliu.js
Normal file
65
web/src/stores/butterfliu.js
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
import { ref } from 'vue'
|
||||||
|
import { defineStore } from 'pinia'
|
||||||
|
|
||||||
|
export const useButterfliuStore = defineStore('butterfliu', () => {
|
||||||
|
const libraries = ref([])
|
||||||
|
async function fetchLibraries() {
|
||||||
|
libraries.value = await (await fetch('/api/libraries')).json()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function scanLibrary(id) {
|
||||||
|
const resp = await fetch('/api/libraries/' + id + '/scan', {
|
||||||
|
method: 'POST',
|
||||||
|
})
|
||||||
|
const result = await resp.json()
|
||||||
|
|
||||||
|
console.log(result)
|
||||||
|
}
|
||||||
|
async function addLibrary(name, path) {
|
||||||
|
const resp = await fetch('/api/libraries', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({
|
||||||
|
name,
|
||||||
|
path,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
const result = await resp.json()
|
||||||
|
|
||||||
|
console.log(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteLibrary(id) {
|
||||||
|
const resp = await fetch('/api/libraries/' + id, {
|
||||||
|
method: 'DELETE',
|
||||||
|
})
|
||||||
|
const result = await resp.json()
|
||||||
|
|
||||||
|
console.log(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchLibrarySongs(id) {
|
||||||
|
const resp = await fetch('/api/libraries/' + id + '/songs')
|
||||||
|
const songs = await resp.json()
|
||||||
|
return songs
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchArtists() {
|
||||||
|
const resp = await fetch('/api/artists')
|
||||||
|
const artists = await resp.json()
|
||||||
|
return artists
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchAlbums() {
|
||||||
|
const resp = await fetch('/api/albums')
|
||||||
|
const albums = await resp.json()
|
||||||
|
return albums
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchAllSongs() {
|
||||||
|
const resp = await fetch('/api/songs')
|
||||||
|
const songs = await resp.json()
|
||||||
|
return songs
|
||||||
|
}
|
||||||
|
|
||||||
|
return { libraries, fetchLibraries, scanLibrary, addLibrary, deleteLibrary, fetchLibrarySongs, fetchArtists, fetchAlbums, fetchAllSongs }
|
||||||
|
})
|
||||||
12
web/src/stores/counter.js
Normal file
12
web/src/stores/counter.js
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { ref, computed } from 'vue'
|
||||||
|
import { defineStore } from 'pinia'
|
||||||
|
|
||||||
|
export const useCounterStore = defineStore('counter', () => {
|
||||||
|
const count = ref(0)
|
||||||
|
const doubleCount = computed(() => count.value * 2)
|
||||||
|
function increment() {
|
||||||
|
count.value++
|
||||||
|
}
|
||||||
|
|
||||||
|
return { count, doubleCount, increment }
|
||||||
|
})
|
||||||
7
web/src/views/AboutView.vue
Normal file
7
web/src/views/AboutView.vue
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
<template>
|
||||||
|
<div class="about">
|
||||||
|
<h1>This is an about page</h1>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style></style>
|
||||||
9
web/src/views/HomeView.vue
Normal file
9
web/src/views/HomeView.vue
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<script setup>
|
||||||
|
import TheWelcome from '../components/TheWelcome.vue'
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<main>
|
||||||
|
<TheWelcome />
|
||||||
|
</main>
|
||||||
|
</template>
|
||||||
97
web/src/views/MusicView.vue
Normal file
97
web/src/views/MusicView.vue
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
<template>
|
||||||
|
<div class="hero">
|
||||||
|
<h1>{{ library?.name || '所有歌曲' }}</h1>
|
||||||
|
<p>{{ songs.length }} 首歌曲</p>
|
||||||
|
</div>
|
||||||
|
<div class="song-list">
|
||||||
|
<div v-for="s in songs" :key="s.id" class="song-item">
|
||||||
|
<span class="song-id">{{ s.id }}</span>
|
||||||
|
<div class="song-textbox">
|
||||||
|
<span class="song-title">{{ s.title }}</span>
|
||||||
|
<span class="song-artist">{{ s.artist }}</span>
|
||||||
|
<span class="song-album">{{ s.album }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, computed, onMounted, watch } from 'vue'
|
||||||
|
import { useRoute } from 'vue-router'
|
||||||
|
import { useButterfliuStore } from '@/stores/butterfliu'
|
||||||
|
|
||||||
|
const route = useRoute()
|
||||||
|
const butterfliu = useButterfliuStore()
|
||||||
|
const songs = ref([])
|
||||||
|
|
||||||
|
const libraries = computed(() => butterfliu.libraries)
|
||||||
|
const library = computed(() => {
|
||||||
|
const libId = parseInt(route.params.id)
|
||||||
|
return libraries.value.find(l => l.id === libId)
|
||||||
|
})
|
||||||
|
|
||||||
|
async function loadSongs() {
|
||||||
|
const libId = route.params.id
|
||||||
|
if (libId) {
|
||||||
|
songs.value = await butterfliu.fetchLibrarySongs(libId)
|
||||||
|
} else {
|
||||||
|
songs.value = await butterfliu.fetchAllSongs()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(() => route.params.id, () => {
|
||||||
|
loadSongs()
|
||||||
|
})
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
butterfliu.fetchLibraries()
|
||||||
|
loadSongs()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.song-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--size-1);
|
||||||
|
}
|
||||||
|
.song-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--size-3);
|
||||||
|
padding: var(--size-1);
|
||||||
|
&:hover {
|
||||||
|
background-color: var(--stone-1);
|
||||||
|
box-shadow: var(--shadow-1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.song-id {
|
||||||
|
text-align: center;
|
||||||
|
inline-size: var(--size-8);
|
||||||
|
line-height: var(--size-8);
|
||||||
|
aspect-ratio: var(--ratio-square);
|
||||||
|
font-family: var(--font-classical-humanist);
|
||||||
|
}
|
||||||
|
|
||||||
|
.song-textbox {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.song-title {
|
||||||
|
font-weight: bold;
|
||||||
|
font-size: var(--font-size-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.song-artist {
|
||||||
|
color: var(--stone-6);
|
||||||
|
font-size: var(--font-size-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.song-album {
|
||||||
|
color: var(--stone-5);
|
||||||
|
font-size: var(--font-size-0);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
67
web/src/views/SettingsView.vue
Normal file
67
web/src/views/SettingsView.vue
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
<template>
|
||||||
|
<div class="setting">
|
||||||
|
<h1>设置</h1>
|
||||||
|
<p>管理您的音乐库和系统配置</p>
|
||||||
|
<p class="controll-buttons">
|
||||||
|
<button type="submit" @click="show = true">添加</button>
|
||||||
|
<button @click="butterfliu.fetchLibraries()">刷新</button>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<AddLibraryDialog v-model="show" @confirm="toAddLibrary" />
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<LibraryCard
|
||||||
|
v-for="l in libraries"
|
||||||
|
:key="l.id"
|
||||||
|
:name="l.name"
|
||||||
|
:id="l.id"
|
||||||
|
@scan="toScanLibrary(l.id)"
|
||||||
|
@delete="toDeleteLibrary(l.id)"
|
||||||
|
@viewSongs="toViewSongs(l.id)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
import AddLibraryDialog from '@/components/AddLibraryDialog.vue'
|
||||||
|
import LibraryCard from '@/components/LibraryCard.vue'
|
||||||
|
import { useButterfliuStore } from '@/stores/butterfliu'
|
||||||
|
import { ref, computed } from 'vue'
|
||||||
|
|
||||||
|
const router = useRouter()
|
||||||
|
const butterfliu = useButterfliuStore()
|
||||||
|
butterfliu.fetchLibraries()
|
||||||
|
const libraries = computed(() => butterfliu.libraries)
|
||||||
|
const show = ref(false)
|
||||||
|
|
||||||
|
function toAddLibrary(name, path) {
|
||||||
|
butterfliu.addLibrary(name, path).then(() => butterfliu.fetchLibraries())
|
||||||
|
}
|
||||||
|
|
||||||
|
function toScanLibrary(id) {
|
||||||
|
butterfliu.scanLibrary(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
function toDeleteLibrary(id) {
|
||||||
|
butterfliu.deleteLibrary(id).then(() => butterfliu.fetchLibraries())
|
||||||
|
}
|
||||||
|
|
||||||
|
function toViewSongs(id) {
|
||||||
|
router.push({ name: 'music-library', params: { id } })
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.setting {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--size-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.controll-buttons {
|
||||||
|
display: flex;
|
||||||
|
gap: var(--size-2);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
20
web/vite.config.js
Normal file
20
web/vite.config.js
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { fileURLToPath, URL } from 'node:url'
|
||||||
|
|
||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import vue from '@vitejs/plugin-vue'
|
||||||
|
import vueDevTools from 'vite-plugin-vue-devtools'
|
||||||
|
|
||||||
|
// https://vite.dev/config/
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [vue(), vueDevTools()],
|
||||||
|
server: {
|
||||||
|
proxy: {
|
||||||
|
'/api': 'http://localhost:8102',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
14
web/vitest.config.js
Normal file
14
web/vitest.config.js
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import { mergeConfig, defineConfig, configDefaults } from 'vitest/config'
|
||||||
|
import viteConfig from './vite.config'
|
||||||
|
|
||||||
|
export default mergeConfig(
|
||||||
|
viteConfig,
|
||||||
|
defineConfig({
|
||||||
|
test: {
|
||||||
|
environment: 'jsdom',
|
||||||
|
exclude: [...configDefaults.exclude, 'e2e/**'],
|
||||||
|
root: fileURLToPath(new URL('./', import.meta.url)),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
)
|
||||||
Reference in New Issue
Block a user