Skip to content

Commit

Permalink
Increase Synced Lyrics Searching, Populate Search after Indexing & Sc…
Browse files Browse the repository at this point in the history
…roll to Bottom for Logs (#146)
  • Loading branch information
WillKirkmanM authored Oct 10, 2024
2 parents b244f10 + c194153 commit 24e0767
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 50 deletions.
22 changes: 14 additions & 8 deletions apps/web/app/(unprotected)/setup/library/page.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
"use client"
"use client";

import getBaseURL from "@/lib/Server/getBaseURL";;

import React, { useState, useEffect } from "react";
import getBaseURL from "@/lib/Server/getBaseURL";
import React, { useState, useEffect, useRef } from "react";
import useWebSocket from "react-use-websocket";
import { ScrollArea, ScrollBar } from "@music/ui/components/scroll-area";
import FileBrowser from "@/components/FileBrowser/FileBrowser";
import Link from "next/link";

export default function SetupLibrary() {
const [messageHistory, setMessageHistory] = useState<MessageEvent<any>[]>([]);

const scrollAreaRef = useRef<HTMLDivElement>(null);

const baseUrl = getBaseURL()?.replace(/^https?:\/\//, '');
const socketUrl = `ws://${baseUrl ?? window.location.hostname}/ws`;
const { lastMessage } = useWebSocket(socketUrl);

useEffect(() => {
if (lastMessage !== null && typeof lastMessage.data === 'string') {
const newMessage = new MessageEvent("message", { data: lastMessage.data });
Expand All @@ -24,6 +24,12 @@ export default function SetupLibrary() {
}
}, [lastMessage]);

useEffect(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
}, [messageHistory]);

return (
<>
<div className="flex flex-col justify-center items-center min-h-screen text-white py-28">
Expand All @@ -34,7 +40,7 @@ export default function SetupLibrary() {
<div className="w-1/2 bg-gray-800 p-4 rounded-md">
<h2 className="text-2xl flex justify-center pb-4">Logs</h2>
<div className="flex justify-center items-center">
<ScrollArea className="h-72 w-full rounded-md border bg-gray-700 p-4">
<ScrollArea viewportRef={scrollAreaRef} className="h-72 w-full rounded-md border bg-gray-700 p-4">
<ul className="py-2">
{messageHistory.map((message) => (
<p key={message.data} className="text-white">{message.data}</p>
Expand All @@ -51,4 +57,4 @@ export default function SetupLibrary() {
</div>
</>
);
}
}
64 changes: 33 additions & 31 deletions apps/web/components/Layout/Playlists.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"use client"
"use client";

import getSession from "@/lib/Authentication/JWT/getSession";
import { getPlaylist, getPlaylists, getUserInfoById } from "@music/sdk";
Expand All @@ -8,7 +8,7 @@ import { ListMusic, Plus } from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
import CreatePlaylistDialog from "../Music/Playlist/CreatePlaylistDialog";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@music/ui/components/accordion"
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@music/ui/components/accordion";
import { useSession } from "../Providers/AuthProvider";

interface Playlist extends OriginalPlaylist {
Expand All @@ -17,7 +17,7 @@ interface Playlist extends OriginalPlaylist {

export default function Playlists() {
const [playlists, setPlaylists] = useState<Playlist[] | null>(null);
const { session } = useSession()
const { session } = useSession();

useEffect(() => {
async function fetchData() {
Expand Down Expand Up @@ -48,34 +48,36 @@ export default function Playlists() {

return (
<div>
<Accordion type="single" collapsible>
<AccordionItem value="playlists">
<AccordionTrigger className="font-heading text-white font-semibold text-sm">
<ListMusic className="h-6 w-6 ml-4 mr-4" />
Playlists
</AccordionTrigger>
<AccordionContent>
{playlists?.map(playlist => (
<div className="pl-5 text-sm flex flex-row items-center gap-3 py-2" key={playlist.id}>
<ListMusic className="size-4" />
<Link href={"/playlist?id=" + playlist.id} key={playlist.id}>
<p className="text-sm" key={playlist.id}>{playlist.name}</p>
<p className="text-xs font-thin">Playlist • {playlist.users.join(", ")}</p>
</Link>
</div>
))}
</AccordionContent>
</AccordionItem>
</Accordion>

<div className="mt-6 flex justify-center">
<CreatePlaylistDialog>
<Button style={{ backgroundColor: "#353535" }}>
<Plus className="mr-2 h-4 w-4" />
Create Playlist
</Button>
</CreatePlaylistDialog>
</div>
{playlists && playlists.length > 0 ? (
<Accordion type="single" collapsible>
<AccordionItem value="playlists">
<AccordionTrigger className="font-heading text-white font-semibold text-sm">
<ListMusic className="h-6 w-6 ml-4 mr-4" />
Playlists
</AccordionTrigger>
<AccordionContent>
{playlists.map((playlist) => (
<div className="pl-5 text-sm flex flex-row items-center gap-3 py-2" key={playlist.id}>
<ListMusic className="size-4" />
<Link href={"/playlist?id=" + playlist.id} key={playlist.id}>
<p className="text-sm" key={playlist.id}>{playlist.name}</p>
<p className="text-xs font-thin">Playlist • {playlist.users.join(", ")}</p>
</Link>
</div>
))}
</AccordionContent>
</AccordionItem>
</Accordion>
) : (
<div className="mt-6 flex justify-center">
<CreatePlaylistDialog>
<Button style={{ backgroundColor: "#353535" }}>
<Plus className="mr-2 h-4 w-4" />
Create Playlist
</Button>
</CreatePlaylistDialog>
</div>
)}
</div>
);
}
36 changes: 27 additions & 9 deletions apps/web/components/Lyrics/LyricsOverlay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,18 +112,36 @@ export default function LyricsOverlay({ children }: QueuePanelProps) {

const fetchLyrics = async () => {
if (song.id) {
const sanitizedSongName = song.name.replace(/\s*\(.*?\)\s*/g, '');
const capitalizeFirstLetter = (str: string) => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
const capitalizedArtistName = capitalizeFirstLetter(song.artist);

const response = await fetch(
`https://lrclib.net/api/search?q=${encodeURIComponent(`${song.name} ${song.artist}`)}`
`https://lrclib.net/api/search?q=${encodeURIComponent(`${sanitizedSongName} ${capitalizedArtistName}`)}`
);
const data: LyricsObjectResponse[] = await response.json();
setCurrentLyrics(data[0]?.plainLyrics ?? "")
const slowdownFactor = reverb ? 1/0.7 : 1;
if (data[0]?.syncedLyrics) {
setLyrics(parseLyrics(data[0].syncedLyrics, slowdownFactor));
setIsSyncedLyrics(true);
} else if (data[0]?.plainLyrics) {
setLyrics(parseLyrics(data[0].plainLyrics, slowdownFactor));
setIsSyncedLyrics(false);
setCurrentLyrics(data[0]?.plainLyrics ?? "");

const slowdownFactor = reverb ? 1 / 0.7 : 1;
let foundSyncedLyrics = false;

for (let i = 0; i < Math.min(data.length, 5); i++) {
if (data[i]?.syncedLyrics) {
setLyrics(parseLyrics(data[i]?.syncedLyrics ?? "", slowdownFactor));
setIsSyncedLyrics(true);
foundSyncedLyrics = true;
break;
}
}

if (!foundSyncedLyrics) {
for (let i = 0; i < Math.min(data.length, 5); i++) {
if (data[i]?.plainLyrics) {
setLyrics(parseLyrics(data[i]?.plainLyrics ?? "", slowdownFactor));
setIsSyncedLyrics(false);
break;
}
}
}
}
};
Expand Down
12 changes: 10 additions & 2 deletions crates/backend/src/routes/music.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ use serde::Deserialize;
use tokio::io::{AsyncReadExt, AsyncSeekExt};
use tokio::process::Command;
use tokio_util::io::ReaderStream;
use tracing::{info, warn};
use tracing::{error, info, warn};
use walkdir::WalkDir;

use crate::routes::search::populate_search_data;
use crate::structures::structures::Artist;
use crate::utils::compare::compare;
use crate::utils::config::{get_config, save_config};
Expand Down Expand Up @@ -130,7 +131,7 @@ pub async fn process_library(path_to_library: web::Path<String>) -> impl Respond
}
}

//https://musicbrainz.org/ws/2/release/cbaf43b4-0d8f-4b58-9173-9fe7298e04e9?inc=aliases+artist-credits+labels+discids+recordings+release-groups+media+discids+recordings+artist-credits+isrcs+artist-rels+release-rels+url-rels+recording-rels+work-rels+label-rels+place-rels+event-rels+area-rels+instrument-rels+series-rels+work-rels&fmt=json
// https://musicbrainz.org/ws/2/release/cbaf43b4-0d8f-4b58-9173-9fe7298e04e9?inc=aliases+artist-credits+labels+discids+recordings+release-groups+media+discids+recordings+artist-credits+isrcs+artist-rels+release-rels+url-rels+recording-rels+work-rels+label-rels+place-rels+event-rels+area-rels+instrument-rels+series-rels+work-rels&fmt=json

let library_guard = library.lock().unwrap();
let elapsed = now.elapsed().as_secs();
Expand All @@ -148,6 +149,13 @@ pub async fn process_library(path_to_library: web::Path<String>) -> impl Respond
let json = serde_json::to_string(data_to_serialize).unwrap();

save_config(&json).await.unwrap();
match populate_search_data().await {
Ok(_) => {},
Err(e) => {
error!("Failed to populate search data: {:?}", e);
}
}

HttpResponse::Ok()
.content_type("application/json; charset=utf-8")
.body(json)
Expand Down

0 comments on commit 24e0767

Please sign in to comment.