Implement eraze command to delete song files and db collections

This commit is contained in:
Chigozirim Igweamaka 2024-06-30 15:00:45 +01:00
parent 3ffa381e2d
commit cf82256666
3 changed files with 63 additions and 2 deletions

View file

@ -7,6 +7,8 @@ import (
"log"
"log/slog"
"net/http"
"os"
"path/filepath"
"song-recognition/shazam"
"song-recognition/spotify"
"song-recognition/utils"
@ -188,3 +190,51 @@ func serveHTTP(socketServer *socketio.Server, serveHTTPS bool, port string) {
log.Fatalf("HTTP server ListenAndServe: %v", err)
}
}
func erase(songsDir string) {
logger := utils.GetLogger()
ctx := context.Background()
// wipe db
dbClient, err := utils.NewDbClient()
if err != nil {
msg := fmt.Sprintf("Error creating DB client: %v\n", err)
logger.ErrorContext(ctx, msg, slog.Any("error", err))
}
err = dbClient.DeleteCollection("fingerprints")
if err != nil {
msg := fmt.Sprintf("Error deleting collection: %v\n", err)
logger.ErrorContext(ctx, msg, slog.Any("error", err))
}
err = dbClient.DeleteCollection("songs")
if err != nil {
msg := fmt.Sprintf("Error deleting collection: %v\n", err)
logger.ErrorContext(ctx, msg, slog.Any("error", err))
}
// delete song files
err = filepath.Walk(songsDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
ext := filepath.Ext(path)
if ext == ".wav" || ext == ".m4a" {
err := os.Remove(path)
if err != nil {
return err
}
}
}
return nil
})
if err != nil {
msg := fmt.Sprintf("Error walking through directory %s: %v\n", songsDir, err)
logger.ErrorContext(ctx, msg, slog.Any("error", err))
}
fmt.Println("Erase successful")
}

View file

@ -8,7 +8,7 @@ import (
func main() {
if len(os.Args) < 2 {
fmt.Println("Expected 'find', 'download', or 'serve' subcommands")
fmt.Println("Expected 'find', 'download', 'erase', or 'serve' subcommands")
os.Exit(1)
}
@ -33,8 +33,10 @@ func main() {
port := serveCmd.String("p", "5000", "Port to use")
serveCmd.Parse(os.Args[2:])
serve(*protocol, *port)
case "erase":
erase(SONGS_DIR)
default:
fmt.Println("Expected 'find', 'download', or 'serve' subcommands")
fmt.Println("Expected 'find', 'download', 'erase', or 'serve' subcommands")
os.Exit(1)
}
}

View file

@ -214,3 +214,12 @@ func (db *DbClient) DeleteSongByID(songID uint32) error {
return nil
}
func (db *DbClient) DeleteCollection(collectionName string) error {
collection := db.client.Database("song-recognition").Collection(collectionName)
err := collection.Drop(context.Background())
if err != nil {
return fmt.Errorf("error deleting collection: %v", err)
}
return nil
}