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