Skip to content

Commit

Permalink
Maybe start using api instead of actions
Browse files Browse the repository at this point in the history
  • Loading branch information
aamirazad committed Jul 8, 2024
1 parent 6523166 commit b3b3c96
Show file tree
Hide file tree
Showing 7 changed files with 216 additions and 55 deletions.
Binary file modified bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"@t3-oss/env-nextjs": "^0.10.1",
"@tanstack/eslint-plugin-query": "^5.43.1",
"@tanstack/react-query": "^5.45.0",
"@tanstack/react-query-devtools": "^5.50.1",
"@tanstack/react-table": "^8.19.2",
"@vercel/postgres": "^0.8.0",
"class-variance-authority": "^0.7.0",
Expand Down
17 changes: 0 additions & 17 deletions src/app/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ export async function setUserProperty<K extends keyof UsersTableType>(
}

export async function getUserData() {
clerkMiddleware();
const { userId } = auth();

if (!userId) return null;
Expand Down Expand Up @@ -79,19 +78,3 @@ export async function getPaperlessDocuments(query: string) {

return data;
}

export async function getRecording(name: string): Promise<string | null> {
const userData = await getUserData();
if (!userData) {
throw new Error("User data is undefined");
}

const url = `${userData.whishperURL}/api/documents/${name}/download/`;
const response = await fetch(url);
if (!response.ok) {
console.log(response);
throw new Error("Failed to fetch recording");
}
const blob = await response.blob();
return URL.createObjectURL(blob);
}
53 changes: 41 additions & 12 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,45 @@
// Fixed code: Moved the QueryClientProvider and ReactQueryDevtools to wrap the entire component, ensuring React Query's context is available throughout the component.

import OpenExternalLink from "@/components/external-link";
import { getRecording } from "./actions";
export default async function HomePage() {
const url =
"https://audio.typhon-sirius.ts.net/api/video/2024_07_04-230439000_WHSHPR_2024-05-18%20-%20Grandma%20telling%20me%20and%20dathi%20about%20the%20past.m4a/download/";
const response = await fetch(url);
console.log(response);
import { getUserData } from "@/app/actions";
import {
useQuery,
QueryClientProvider,
QueryClient,
} from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";

const queryClient = new QueryClient();

export default function HomePage() {
return (
<QueryClientProvider client={queryClient}>
<Content />
<ReactQueryDevtools initialIsOpen={true} />
</QueryClientProvider>
);
}

function Content() {
const {
data: userData,
isLoading,
isError,
error,
} = useQuery({
queryKey: ["userData"],
queryFn: getUserData,
});

if (isLoading) {
console.log("Loading user data...");
}

if (isError) {
console.error("Error fetching user data:", error);
}

console.log("User data:", userData);
return (
<main>
<div>
Expand All @@ -17,12 +52,6 @@ export default async function HomePage() {
to get started.
</div>
<div>Or sign in to access the dashboard.</div>
<audio controls="controls" autoplay="autoplay">
<source
src="https://audio.typhon-sirius.ts.net/api/video/2024_07_04-230439000_WHSHPR_2024-05-18%20-%20Grandma%20telling%20me%20and%20dathi%20about%20the%20past.m4a"
type="audio/mp4"
/>
</audio>
</div>
</main>
);
Expand Down
47 changes: 21 additions & 26 deletions src/components/audio-preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,44 +6,39 @@ import {
QueryClientProvider,
QueryClient,
} from "@tanstack/react-query";
import LoadingSpinner from "./loading-spinner";
import type { UsersTableType } from "@/server/db/schema";
import { getRecording } from "@/app/actions";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";

const queryClient = new QueryClient();

function Player(props: { name: string }) {
const {
data: userData,
isLoading,
error,
} = useQuery({
queryKey: ["audioURL"],
queryFn: async () => {
return getUserData();
},
});

const { data: url } = useQuery({
queryKey: ["url", props.name],
queryFn: getRecording,
});

if (isLoading ?? !userData) {
return <LoadingSpinner>Loading...</LoadingSpinner>;
async function getthedata() {
const userData = await getUserData();
if (!userData) {
console.error("Error getting user data");
return null;
}
return userData;
}

if (error instanceof Error) {
return <p>Error: {error.message}</p>;
}
function Player(props: { name: string }) {
// Fetch user data using useQuery hook

console.log("User data:", userData);

return <p>{url}</p>;
return (
<audio controls={true}>
<source
src="https://audio.typhon-sirius.ts.net/api/video/2024_07_04-230439000_WHSHPR_2024-05-18%20-%20Grandma%20telling%20me%20and%20dathi%20about%20the%20past.m4a"
type="audio/mp4"
/>
</audio>
);
}

export default function AudioPreview({ name }: { name: string }) {
return (
<QueryClientProvider client={queryClient}>
<Player name={name} />
<ReactQueryDevtools initialIsOpen={true} />
</QueryClientProvider>
);
}
138 changes: 138 additions & 0 deletions src/components/secondary-audio-preview.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
"use client";

import { useState, useEffect, useRef } from "react";
import { Button } from "./ui/button";
import { useRouter } from "next/navigation";
import { getUserData } from "@/app/actions";
import {
useQuery,
QueryClientProvider,
QueryClient,
} from "@tanstack/react-query";
import type { AdviceAPIType } from "@/types";
import OpenInternalLink from "./internal-link";

const queryClient = new QueryClient();

async function getPaperlessDocument(
documentId: number,
): Promise<string | null> {
const userData = await getUserData();
if (!userData) {
console.error("Error getting user data");
return null;
}
try {
const url = `${userData.paperlessURL}/api/documents/${documentId}/download/`;
const response = await fetch(url, {
headers: {
Authorization: `Token ${userData.paperlessToken}`,
},
});
if (response.ok) {
const blob = await response.blob();
const objectUrl = URL.createObjectURL(blob);
return objectUrl;
} else {
console.error("Failed to fetch PDF");
return null;
}
} catch (error) {
console.error("Error fetching PDF:", error);
return null;
}
}

function DocumentViewer(props: { id: number }) {
const router = useRouter();

const [pdfUrl, setPdfUrl] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const fetchDataCalledRef = useRef(false);

useEffect(() => {
if (!fetchDataCalledRef.current) {
const fetchData = async () => {
setLoading(true);

try {
const objectUrl = await getPaperlessDocument(props.id);
if (objectUrl) {
setPdfUrl(objectUrl);
} else {
setPdfUrl(null);
}
} catch (error) {
console.error("An error occurred:", error);
setPdfUrl(null);
} finally {
setLoading(false);
}
};

fetchData().catch((error) => {
console.error("An error occurred:", error);
});

fetchDataCalledRef.current = true; // Mark as fetched
}
}, [props.id]); // Include props.id in the dependency array if refetch is needed on id change

if (loading) {
return <SkeletonLoader />;
}

if (!pdfUrl) {
return (
<div className="flex justify-center">
<div className="mx-auto max-w-sm rounded-lg bg-black p-4 shadow-md">
<h1 className="w-full text-center text-2xl font-bold">
Failed to get document
</h1>
</div>
</div>
);
}

return (
<div className="flex h-full w-full min-w-0 justify-center">
<div className="flex h-4/5 flex-col rounded-xl bg-slate-600/50 md:w-1/2">
<div className="m-4 flex flex-grow flex-col justify-center gap-8 md:m-8 md:flex-row md:gap-16">
<div className="h-full flex-shrink flex-grow">
<object
data={pdfUrl}
type="application/pdf"
width="100%"
height="100%"
>
<p>
Your web browser doesn&apos;t have a PDF plugin. Instead you can
<OpenInternalLink href={pdfUrl}>
click here to download the PDF file.
</OpenInternalLink>
</p>
</object>
</div>
<div className="flex flex-shrink-0 flex-col">
<Button
onClick={(e) => {
e.preventDefault();
router.back();
}}
>
Back
</Button>
</div>
</div>
</div>
</div>
);
}

export default function Page(props: { id: number }) {
return (
<QueryClientProvider client={queryClient}>
<DocumentViewer id={props.id} />
</QueryClientProvider>
);
}
15 changes: 15 additions & 0 deletions src/server/querys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"use server";
import { db } from "@/server/db";
import { auth } from "@clerk/nextjs/server";

export async function getUserData() {
const { userId } = auth();

if (!userId) return null;

const userData = await db.query.users.findFirst({
where: (model, { eq }) => eq(model.userId, userId),
});

return userData;
}

0 comments on commit b3b3c96

Please sign in to comment.