-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
339 lines (320 loc) · 9.39 KB
/
Copy pathdb.js
File metadata and controls
339 lines (320 loc) · 9.39 KB
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const fetch = require('node-fetch');
const PROVIDER = (process.env.DB_PROVIDER || '').toUpperCase();
// Initialize the active database provider
let dbAdapter = null;
class MemoryAdapter {
constructor() {
this.cache = new Map();
}
async get(key) {
return this.cache.get(key) || null;
}
async set(key, value) {
this.cache.set(key, value);
}
async getByShortId(id) {
for (const row of this.cache.values()) {
if (row && row.id === id) return row;
}
return null;
}
}
class JsonFileAdapter {
constructor(filePath) {
this.filePath = filePath || path.join(__dirname, 'db.json');
this.data = {};
this.load();
}
load() {
try {
if (fs.existsSync(this.filePath)) {
this.data = JSON.parse(fs.readFileSync(this.filePath, 'utf8'));
}
} catch (e) {
console.error('[db] Failed to load JSON database:', e.message);
}
}
save() {
try {
const dir = path.dirname(this.filePath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(this.filePath, JSON.stringify(this.data, null, 2), 'utf8');
} catch (e) {
console.error('[db] Failed to save JSON database:', e.message);
}
}
async get(key) {
return this.data[key] || null;
}
async set(key, value) {
this.data[key] = value;
this.save();
}
async getByShortId(id) {
return Object.values(this.data).find(row => row && row.id === id) || null;
}
}
class SqliteAdapter {
constructor(filePath) {
let DatabaseSync;
try {
const sqliteModule = require('node:sqlite');
DatabaseSync = sqliteModule.DatabaseSync;
} catch (e) {
throw new Error('SQLite database provider requires Node.js v22.5.0+ (built-in node:sqlite module missing).');
}
this.db = new DatabaseSync(filePath || path.join(__dirname, 'db.sqlite'));
this.db.exec(`
CREATE TABLE IF NOT EXISTS songs (
query_hash TEXT PRIMARY KEY,
id TEXT UNIQUE NOT NULL,
query TEXT NOT NULL,
title TEXT,
artist TEXT,
album TEXT,
art_url TEXT,
preview_url TEXT,
links TEXT NOT NULL,
country TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
this.db.exec(`
CREATE INDEX IF NOT EXISTS idx_songs_id ON songs(id)
`);
}
async get(key) {
try {
const stmt = this.db.prepare('SELECT * FROM songs WHERE query_hash = ?');
const row = stmt.get(key);
if (!row) return null;
return { ...row, links: JSON.parse(row.links) };
} catch (e) {
console.error('[db] SQLite read failed:', e.message);
return null;
}
}
async getByShortId(id) {
try {
const stmt = this.db.prepare('SELECT * FROM songs WHERE id = ?');
const row = stmt.get(id);
if (!row) return null;
return { ...row, links: JSON.parse(row.links) };
} catch (e) {
console.error('[db] SQLite query by short ID failed:', e.message);
return null;
}
}
async set(key, value) {
try {
const stmt = this.db.prepare(`
INSERT OR REPLACE INTO songs (query_hash, id, query, title, artist, album, art_url, preview_url, links, country)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
stmt.run(
key,
value.id,
value.query,
value.title,
value.artist,
value.album,
value.art_url,
value.preview_url,
JSON.stringify(value.links),
value.country
);
return true;
} catch (e) {
console.error('[db] SQLite write failed:', e.message);
return false;
}
}
}
class SupabaseAdapter {
constructor(url, key) {
this.url = url.replace(/\/$/, '');
this.key = key;
}
async get(key) {
try {
const response = await fetch(`${this.url}/rest/v1/songs?query_hash=eq.${encodeURIComponent(key)}`, {
headers: {
'apikey': this.key,
'Authorization': `Bearer ${this.key}`
}
});
if (response.ok) {
const rows = await response.json();
return rows[0] || null;
}
} catch (e) {
console.error('[db] Supabase read failed:', e.message);
}
return null;
}
async getByShortId(id) {
try {
const response = await fetch(`${this.url}/rest/v1/songs?id=eq.${encodeURIComponent(id)}`, {
headers: {
'apikey': this.key,
'Authorization': `Bearer ${this.key}`
}
});
if (response.ok) {
const rows = await response.json();
return rows[0] || null;
}
} catch (e) {
console.error('[db] Supabase query by short ID failed:', e.message);
}
return null;
}
async set(key, value) {
try {
const response = await fetch(`${this.url}/rest/v1/songs`, {
method: 'POST',
headers: {
'apikey': this.key,
'Authorization': `Bearer ${this.key}`,
'Content-Type': 'application/json',
'Prefer': 'resolution=merge-duplicates'
},
body: JSON.stringify({
query_hash: key,
id: value.id,
query: value.query,
title: value.title,
artist: value.artist,
album: value.album,
art_url: value.art_url,
preview_url: value.preview_url,
links: value.links,
country: value.country
})
});
return response.ok;
} catch (e) {
console.error('[db] Supabase write failed:', e.message);
}
return false;
}
}
// Instantiate DB Adapter based on configuration
if (PROVIDER === 'SUPABASE' && process.env.SUPABASE_URL && process.env.SUPABASE_KEY) {
dbAdapter = new SupabaseAdapter(process.env.SUPABASE_URL, process.env.SUPABASE_KEY);
console.log('Database Provider: SUPABASE (REST API)');
} else if (PROVIDER === 'SQLITE') {
const filePath = process.env.DB_FILE_PATH || path.join(__dirname, 'db.sqlite');
dbAdapter = new SqliteAdapter(filePath);
console.log(`Database Provider: SQLITE (${filePath})`);
} else if (PROVIDER === 'JSON') {
const filePath = process.env.DB_FILE_PATH || path.join(__dirname, 'db.json');
dbAdapter = new JsonFileAdapter(filePath);
console.log(`Database Provider: LOCAL JSON (${filePath})`);
} else {
dbAdapter = new MemoryAdapter();
console.log('Database Provider: MEMORY (Transient Cache)');
}
function generateShortId() {
return crypto.randomBytes(4).toString('hex'); // 8 character alphanumeric string
}
function normalizeMusicUrl(urlStr) {
if (!urlStr || typeof urlStr !== 'string') return urlStr;
let val = urlStr.trim();
if (!val.startsWith('http://') && !val.startsWith('https://') && !val.startsWith('spotify:')) {
return val;
}
try {
val = val.replace('music.youtube.com', 'youtube.com');
if (val.includes('youtube.com/shorts/')) {
val = val.replace('youtube.com/shorts/', 'youtube.com/watch?v=');
}
const u = new URL(val);
const host = u.hostname.toLowerCase();
if (host.includes('apple.com')) {
u.hostname = 'music.apple.com';
const parts = u.pathname.split('/');
if (parts.length > 1) {
const segment = parts[1];
if (/^[a-z]{2}(-[a-z]{2,4})?$/i.test(segment)) {
parts.splice(1, 1);
u.pathname = parts.join('/');
}
}
const trackId = u.searchParams.get('i');
u.search = '';
if (trackId) {
u.searchParams.set('i', trackId);
}
} else if (host.includes('spotify.com')) {
u.searchParams.delete('si');
u.searchParams.delete('context');
} else if (host.includes('youtube.com')) {
const videoId = u.searchParams.get('v');
u.search = '';
if (videoId) {
u.searchParams.set('v', videoId);
}
} else if (host.includes('youtu.be')) {
u.search = '';
}
return u.toString();
} catch (e) {
return val;
}
}
function getQueryHash(query) {
const normalized = normalizeMusicUrl(query);
const norm = normalized.trim().toLowerCase();
return crypto.createHash('sha256').update(norm).digest('hex');
}
module.exports = {
isDbActive: () => PROVIDER === 'SUPABASE' || PROVIDER === 'SQLITE' || PROVIDER === 'JSON',
normalizeMusicUrl,
getCachedSong: async (query) => {
const hash = getQueryHash(query);
const row = await dbAdapter.get(hash);
if (!row) return null;
return {
links: row.links,
title: row.title,
artist: row.artist,
album: row.album,
art: row.art_url,
preview: row.preview_url,
shortId: row.id
};
},
saveCachedSong: async (query, country, songData) => {
const normalized = normalizeMusicUrl(query);
const hash = getQueryHash(normalized);
const shortId = songData.shortId || generateShortId();
const dbRow = {
id: shortId,
query: normalized,
title: songData.title || songData.t || null,
artist: songData.artist || songData.a || null,
album: songData.album || null,
art_url: songData.art || null,
preview_url: songData.preview || null,
links: songData.links || songData.l || {},
country: country || 'US'
};
await dbAdapter.set(hash, dbRow);
return shortId;
},
getSongByShortId: async (id) => {
const row = await dbAdapter.getByShortId(id);
if (!row) return null;
return {
t: row.title,
a: row.artist,
art: row.art_url,
preview: row.preview_url,
l: row.links
};
}
};