[O] Fixed db names

This commit is contained in:
2025-11-21 22:16:50 +08:00
parent b2eaeb7b8d
commit e7122e28df
4 changed files with 34 additions and 26 deletions
+11 -1
View File
@@ -1,7 +1,17 @@
import { MongoClient } from "mongodb"
import type { UserDocument, ResultDocument } from "../../shared/types"
export const mongo = new MongoClient(process.env.MONGO_URL || "mongodb://cat:meow@localhost:27017/")
mongo.connect()
export const db = mongo.db()
export const dbs = {
songsRaw: db.collection('songs_raw'),
serverProps: db.collection('server_props'),
playlistsRaw: db.collection('playlists_raw'),
lyricsRaw: db.collection('lyrics_raw'),
lyricsProcessed: db.collection('lyrics_processed'),
playlists: db.collection('playlists'),
users: db.collection<UserDocument>('users'),
results: db.collection<ResultDocument>('results')
}
+3 -5
View File
@@ -1,18 +1,16 @@
import type { ResultDocument } from "../../shared/types"
import { db } from "./db"
import { dbs } from "./db"
import { ObjectId } from "mongodb"
const results = db.collection<ResultDocument>("results")
export async function saveResult(data: Omit<ResultDocument, "_id" | "createdAt">): Promise<string> {
const doc = { ...data, createdAt: new Date() }
const res = await results.insertOne(doc)
const res = await dbs.results.insertOne(doc)
return res.insertedId.toString()
}
export async function getResult(id: string): Promise<ResultDocument | null> {
try {
return await results.findOne({ _id: new ObjectId(id) })
return await dbs.results.findOne({ _id: new ObjectId(id) })
} catch {
return null
}
+18 -18
View File
@@ -1,7 +1,7 @@
import * as ne from '@neteasecloudmusicapienhanced/api'
import { aiParseLyrics } from './tools/lyrics'
import type { NeteaseSong, UserDocument } from '../../shared/types'
import { db } from './db'
import { dbs } from './db'
import { franc } from 'franc'
import { error } from '@sveltejs/kit'
import type { ObjectId } from 'mongodb'
@@ -11,7 +11,7 @@ import path from 'path'
const CACHE_DIR = path.resolve('static/audio')
const neCookie = async () => (await db.collection('server_props')
const neCookie = async () => (await dbs.serverProps
.findOne({ name: 'global_settings' }))?.netease_login_cookie
?.let((cookie: string) => ({ cookie }))
const checkNetease = async () => (await ne.login_status({ ...await neCookie() }) as any).body.data.account
@@ -24,15 +24,15 @@ const eToString = (e: any) => e.message ?? e.body.message
* @param keyFn Function to get cache key from argument. Defaults to using the argument directly.
* @returns Function that gets data from cache or calls fn and caches result.
*/
const cached = <T, R>(collectionName: string, fn: (arg: T) => Promise<R>, keyFn: (arg: T) => any = (x) => x): (arg: T, noCache?: boolean) => Promise<R> =>
const cached = <T, R>(collection: any, fn: (arg: T) => Promise<R>, keyFn: (arg: T) => any = (x) => x): (arg: T, noCache?: boolean) => Promise<R> =>
async (arg: T, noCache = false): Promise<R> => {
const key = keyFn(arg)
if (!noCache) {
const doc = await db.collection(collectionName).findOne({ _id: key })
const doc = await collection.findOne({ _id: key })
if (doc) return doc.data
}
const result = await fn(arg)
await db.collection(collectionName).replaceOne({ _id: key }, { _id: key, data: result }, { upsert: true })
await collection.replaceOne({ _id: key }, { _id: key, data: result }, { upsert: true })
return result
}
@@ -46,11 +46,11 @@ function parsePlaylistRef(ref: string): number {
throw error(400, "无法识别歌单 URL... 只支持网易云的 URL 哦")
}
const getPlaylistRaw = cached('playlists_raw',
const getPlaylistRaw = cached(dbs.playlistsRaw,
async (id: number) => {
const pl = ((await ne.playlist_detail({ id })).body as any).playlist
for (const track of pl.tracks)
await db.collection('songs_raw').replaceOne({ _id: track.id }, { _id: track.id, data: track }, { upsert: true })
await dbs.songsRaw.replaceOne({ _id: track.id }, { _id: track.id, data: track }, { upsert: true })
return pl
})
@@ -61,7 +61,7 @@ function normalizeTimestamps(text: string): string {
}
interface NeteaseLyricsResponse { lrc: { lyric: string }, lang: string }
const _getLyricsRaw = cached('lyrics_raw',
const _getLyricsRaw = cached(dbs.lyricsRaw,
async (songId: number) => {
const raw = (await ne.lyric({ id: songId })).body as any as NeteaseLyricsResponse
const lang = franc(raw.lrc.lyric.replace(/\[.*?\]/g, '').replace(/\s+/g, ' ').trim())
@@ -82,13 +82,13 @@ const getLyricsRaw = async (songId: number): Promise<NeteaseLyricsResponse & { l
return raw
}
export const getSongRaw = cached('songs_raw',
export const getSongRaw = cached(dbs.songsRaw,
async (songId: number) => {
const detail = await ne.song_detail({ ids: songId.toString() })
return detail.body.songs[0] as NeteaseSong
})
export const getLyricsProcessed = cached('lyrics_processed',
export const getLyricsProcessed = cached(dbs.lyricsProcessed,
async (songId: number) => {
const raw = await getLyricsRaw(songId)
if (raw.lang !== 'jpn') throw error(400, 'Lyrics are not in Japanese')
@@ -134,7 +134,7 @@ export interface SongProcessState { items: ProgressItem[], status: 'running' | '
const songProcessingStatus = new Map<number, SongProcessState>()
export const getSongStatus = (songId: number) => songProcessingStatus.get(songId) || { items: [], status: 'idle' }
export const checkLyricsProcessed = async (songId: number) => !!await db.collection('lyrics_processed').findOne({ _id: songId as any })
export const checkLyricsProcessed = async (songId: number) => !!await dbs.lyricsProcessed.findOne({ _id: songId as any })
export const prepareSong = async (songId: number) => {
if (songProcessingStatus.has(songId)) return
@@ -160,7 +160,7 @@ export const prepareSong = async (songId: number) => {
if (await checkLyricsProcessed(songId)) taskAI.progress = 1
else {
const lrc = await aiParseLyrics(raw.lrc.lyric, (i, n) => taskAI.progress = i / n)
await db.collection('lyrics_processed').replaceOne({ _id: songId as any }, { _id: songId, data: lrc }, { upsert: true })
await dbs.lyricsProcessed.replaceOne({ _id: songId as any }, { _id: songId, data: lrc }, { upsert: true })
taskAI.progress = 1
}
@@ -250,14 +250,14 @@ async function processImport(session: ImportSession, data: any) {
session.done = true
// Save to database
await db.collection('playlists').replaceOne(
await dbs.playlists.replaceOne(
{ _id: session.playlistId as any },
{ _id: session.playlistId, data, importedAt: new Date() },
{ upsert: true }
)
// Add to user's favorites
session.userId?.let(async (uid: any) => await db.collection('users').updateOne(
session.userId?.let(async (uid: any) => await dbs.users.updateOne(
{ _id: uid },
{ $addToSet: { "data.myPlaylists": session.playlistId } }
))
@@ -270,24 +270,24 @@ async function processImport(session: ImportSession, data: any) {
// TODO: A better recommendation system
const defaultPlaylists = [17463338036, 13555799996, 14348145982, 14392963638]
export const listRecPlaylists = async () => {
const list = await db.collection('playlists').find({
const list = await dbs.playlists.find({
_id: { $in: defaultPlaylists }
} as any).map(it => it.data).toArray()
return list.sort((a: any, b: any) => defaultPlaylists.indexOf(a.id) - defaultPlaylists.indexOf(b.id))
}
export const listMyPlaylists = async (user: UserDocument) => (await user.data.myPlaylists?.let(pl => db.collection('playlists').find({
export const listMyPlaylists = async (user: UserDocument) => (await user.data.myPlaylists?.let(pl => dbs.playlists.find({
_id: { $in: pl as any as ObjectId[] }
}).map(it => it.data).toArray())) ?? []
export const getPlaylist = async (playlistId: number | string) => {
const plData = await db.collection('playlists').findOne({ _id: +playlistId as any })
const plData = await dbs.playlists.findOne({ _id: +playlistId as any })
if (!plData) throw error(404, 'Playlist not found')
return plData.data
}
// Check if there are any playlists, if not, import default ones
(async () => {
const count = await db.collection('playlists').countDocuments()
const count = await dbs.playlists.countDocuments()
if (count === 0) {
console.log("No playlists found. Importing default playlists...")
await Promise.all(defaultPlaylists.map(async (id) => await startImport(id.toString())))
+2 -2
View File
@@ -1,8 +1,8 @@
import { db } from "./db"
import { dbs } from "./db"
import { type UserDocument, type UserData } from "../../shared/types.ts";
import { error } from "@sveltejs/kit";
const users = db.collection<UserDocument>("users")
const users = dbs.users
// Build an index once so session lookups stay fast even as the collection grows.
void users.createIndex({ sessions: 1 }, { name: "users_sessions_idx" })