forked from cgzirim/seek-tune
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmdHandlers.go
204 lines (170 loc) · 4.82 KB
/
cmdHandlers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package main
import (
"context"
"crypto/tls"
"fmt"
"log"
"log/slog"
"net/http"
"os"
"path/filepath"
"song-recognition/db"
"song-recognition/shazam"
"song-recognition/utils"
"song-recognition/wav"
"strings"
"github.com/fatih/color"
"github.com/zishang520/engine.io/v2/types"
"github.com/zishang520/socket.io/v2/socket"
)
const (
SONGS_DIR = "songs"
)
var yellow = color.New(color.FgYellow)
func find(filePath string) {
wavInfo, err := wav.ReadWavInfo(filePath)
if err != nil {
yellow.Println("Error reading wave info:", err)
return
}
samples, err := wav.WavBytesToSamples(wavInfo.Data)
if err != nil {
yellow.Println("Error converting to samples:", err)
return
}
matches, searchDuration, err := shazam.FindMatches(samples, wavInfo.Duration, wavInfo.SampleRate)
if err != nil {
yellow.Println("Error finding matches:", err)
return
}
if len(matches) == 0 {
fmt.Println("\nNo match found.")
fmt.Printf("\nSearch took: %s\n", searchDuration)
return
}
msg := "Matches:"
topMatches := matches
if len(matches) >= 20 {
msg = "Top 20 matches:"
topMatches = matches[:20]
}
fmt.Println(msg)
for _, match := range topMatches {
fmt.Printf("\t- %s by %s, score: %.2f\n",
match.SongTitle, match.SongArtist, match.Score)
}
fmt.Printf("\nSearch took: %s\n", searchDuration)
topMatch := topMatches[0]
fmt.Printf("\nFinal prediction: %s by %s , score: %.2f\n",
topMatch.SongTitle, topMatch.SongArtist, topMatch.Score)
}
func serve(protocol, port string) {
protocol = strings.ToLower(protocol)
// var allowOriginFunc = func(r *http.Request) bool {
// return true
// }
// &engineio.Options{
// Transports: []transport.Transport{
// &polling.Transport{
// CheckOrigin: allowOriginFunc,
// },
// &websocket.Transport{
// CheckOrigin: allowOriginFunc,
// },
// },
// }
server := socket.NewServer(types.CreateServer(nil), nil)
// server.OnConnect("/", func(socket socketio.Conn) error {
// socket.SetContext("")
// log.Println("CONNECTED: ", socket.ID())
// return nil
// })
server.OnEvent("/", "totalSongs", handleTotalSongs)
server.OnEvent("/", "checkSongExists", handleSongExists)
server.OnEvent("/", "checkSongsUnsaved", handleSongsUnsaved)
server.OnEvent("/", "save", handleSave)
server.OnEvent("/", "find", handleFind)
// server.OnError("/", func(s socketio.Conn, e error) {
// log.Println("meet error:", e)
// })
// server.OnDisconnect("/", func(s socketio.Conn, reason string) {
// log.Println("closed", reason)
// })
go func() {
if err := server.Serve(); err != nil {
log.Fatalf("socketio listen error: %s\n", err)
}
}()
defer server.Close()
serveHTTPS := protocol == "https"
serveHTTP(server, serveHTTPS, port)
}
func serveHTTP(socketServer *socket.Server, serveHTTPS bool, port string) {
http.Handle("/socket.io/", socketServer)
if serveHTTPS {
httpsAddr := ":" + port
httpsServer := &http.Server{
Addr: httpsAddr,
TLSConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
},
Handler: socketServer,
}
cert_key_default := "/etc/letsencrypt/live/localport.online/privkey.pem"
cert_file_default := "/etc/letsencrypt/live/localport.online/fullchain.pem"
cert_key := utils.GetEnv("CERT_KEY", cert_key_default)
cert_file := utils.GetEnv("CERT_FILE", cert_file_default)
if cert_key == "" || cert_file == "" {
log.Fatal("Missing cert")
}
log.Printf("Starting HTTPS server on %s\n", httpsAddr)
if err := httpsServer.ListenAndServeTLS(cert_file, cert_key); err != nil {
log.Fatalf("HTTPS server ListenAndServeTLS: %v", err)
}
}
log.Printf("Starting HTTP server on port %v", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatalf("HTTP server ListenAndServe: %v", err)
}
}
func erase(songsDir string) {
logger := utils.GetLogger()
ctx := context.Background()
// wipe db
dbClient, err := db.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 complete")
}