Skip to content

Commit

Permalink
feat: done, minimal testing (everything should work, don't have time …
Browse files Browse the repository at this point in the history
…to extensively test everything)
  • Loading branch information
WomB0ComB0 committed Sep 2, 2024
1 parent 8bdd168 commit 92d2989
Show file tree
Hide file tree
Showing 6 changed files with 151 additions and 249 deletions.
120 changes: 29 additions & 91 deletions src/app/(dashboard)/(reupload)/allresources/_components/reinput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export const ReUploadResource = () => {
id: mylearning_id,
clearId: clearMyLearningId,
generateNewId,
setPersistedId,
} = usePersistedId('mylearning_id');
const supabase = createClient();
const router = useRouter();
Expand Down Expand Up @@ -133,7 +134,7 @@ export const ReUploadResource = () => {
}
};

const handleUpload = async (input: any, title: string) => {
const handleUpload = async (input: any, title: string, newLearningId: string) => {
if (!input || input.trim() === '') {
toast.error('Input cannot be empty');
return;
Expand All @@ -157,12 +158,10 @@ export const ReUploadResource = () => {
return;
}

const newLearningId = generateNewId();

const response = await saveOutput(input, newLearningId, userData.user.id, title);
if (response && response.id) {
toast.success('Resource created successfully');
router.push(`/dashboard?mylearning_id=${newLearningId}`);
setPersistedId(newLearningId);
} else {
toast.error('Failed to create resource');
}
Expand All @@ -175,44 +174,46 @@ export const ReUploadResource = () => {
};

const submitChanges = async () => {
if (isLoading) return; // Prevent multiple submissions
if (isLoading) return;

try {
setIsLoading(true);
const supabase = createClient();
const {
data: { user },
error: userError,
} = await supabase.auth.getUser();

if (userError || !user) {
toast.error('User authentication failed. Please log in and try again.');
return;
}

const newLearningId = generateNewId();

let input;
let title;

if (fileType === 'video') {
const keyWordsArray = await handleVideoUpload();
if (!keyWordsArray || keyWordsArray.length === 0) {
toast.error('Failed to extract keywords from video');
return;
}
input = keyWordsArray.join(', ');
title = `Video: ${input.slice(0, 30)}...`;
input = keyWordsArray.toString();
title = `Video: ${selectedFile?.name}`;
} else if (fileType === 'text') {
if (!content.trim()) {
toast.error('Content cannot be empty');
return;
}
input = content;
title = `Text: ${content.slice(0, 30)}...`;
} else if (fileType === 'keywords') {
if (!keywords.trim()) {
toast.error('Keywords cannot be empty');
return;
}
input = keywords;
title = `Keywords: ${keywords.slice(0, 30)}...`;
} else {
toast.error('Please select a file type');
return;
}

await handleUpload(input, title);
await handleUpload(input, title, newLearningId);

window.open(`/dashboard?mylearning_id=${newLearningId}`, '_self');
} catch (err: any) {
console.error('Error when updating resource:', err);
toast.error(`Error when updating resource: ${err.message}`);
console.error('Error in submitChanges:', err);
toast.error(`Error when submitting changes: ${err.message}`);
} finally {
setIsLoading(false);
}
Expand Down Expand Up @@ -260,31 +261,6 @@ export const ReUploadResource = () => {
</DialogHeader>

<div className="grid gap-2">
{/* <Button
variant="outline"
className="w-full"
onClick={() => setFileType("image")}
disabled>
<ImageIcon className="w-4 h-4 mr-1" />
Image
</Button> */}
<Button
variant="outline"
disabled={true}
className="w-full"
onClick={() => setFileType('video')}
>
<VideoIcon className="w-4 h-4 mr-1" />
Video
</Button>
{/* <Button
variant="outline"
className="w-full"
onClick={() => setFileType("audio")}
disabled>
<AudioLinesIcon className="w-4 h-4 mr-1" />
Audio
</Button> */}
<Button
variant="outline"
className="w-full"
Expand All @@ -293,30 +269,10 @@ export const ReUploadResource = () => {
<TextIcon className="w-4 h-4 mr-1" />
Keywords / Topic
</Button>
<Button
variant="outline"
className="w-full"
onClick={() => setFileType('text')}
>
<TextIcon className="w-4 h-4 mr-1" />
Text
</Button>
</div>
</>
)}

{fileType === 'text' && (
<div className="grid gap-2">
<Label htmlFor="content">Content</Label>
<Textarea
id="content"
placeholder="Write your content here"
value={content}
onChange={handleContentChange}
/>
</div>
)}

{fileType === 'keywords' && (
<div className="grid gap-2">
<Label htmlFor="keywords">Keywords / Topic</Label>
Expand All @@ -329,32 +285,14 @@ export const ReUploadResource = () => {
</div>
)}

{/* {fileType === 'video' && (
<>
<DialogTitle>Choose Video File</DialogTitle>
<input
type="file"
name="file"
accept=".mp4"
onChange={handleVideoFileChange}
className="rounded-md"
/>
</>
)} */}

{fileType === 'video' && objectURL && (
<div className="grid gap-2">
<Label htmlFor="name">Preview</Label>
<div>
<video controls src={objectURL}></video>
</div>
</div>
)}

{fileType && (
<div className="flex justify-end">
<DialogFooter>
<Button type="submit" onClick={submitChanges} disabled={isLoading}>
<Button
type="submit"
onClick={submitChanges}
disabled={isLoading}
>
{isLoading ? 'Uploading ...' : 'Upload'}
</Button>
</DialogFooter>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,16 @@ import { createMyLearning } from '@/app/api/v1/outputs/repository';
import { usePersistedId } from '@/hooks';
import { createClient } from '@/utils/supabase/client';
import { useRouter } from 'next/navigation';
import { useQueryState } from 'nuqs';
import { toast } from 'sonner';
import { v4 as uuidv4 } from 'uuid';

export const ReUploadKeyword = () => {
const { id: mylearning_id, clearId: clearMyLearningId } = usePersistedId('mylearning_id');

const {
id: mylearning_id,
clearId: clearMyLearningId,
generateNewId,
setPersistedId,
} = usePersistedId('mylearning_id');
const supabase = createClient();
const router = useRouter();
const [isOpen, setIsOpen] = useState(false);
const [isDrawerOpen, setIsDrawerOpen] = useState(false);
Expand Down Expand Up @@ -90,59 +93,84 @@ export const ReUploadKeyword = () => {

const [fileType, setFileType] = useState<'keywords'>();

const handleVideoFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files && event.target.files.length > 0) {
const file = event.target.files[0];
const pathURL = URL.createObjectURL(file);
setSelectedFile(file);
setObjectURL(pathURL);
// console.log(objectURL);
const handleUpload = async (input: any, title: string, newLearningId: string) => {
if (!input || input.trim() === '') {
toast.error('Input cannot be empty');
return;
}
};

const handleUpload = async (input: any, mylearning_id: string, userId: string) => {
try {
setIsLoading(true);
const response = await createMyLearning(input, mylearning_id, userId);

if (response && response.data) {
toast.success('Keywords uploaded successfully');
router.push(`/dashboard?mylearning_id=${response.data.id}`);
const { data: sessionData, error: sessionError } = await supabase.auth.getSession();

if (sessionError || !sessionData.session) {
toast.error('Your session has expired. Please sign in again.');
router.push('/signin/password_signin');
return;
}

const { data: userData, error: userError } = await supabase.auth.getUser();

if (userError || !userData.user) {
toast.error('Failed to get user information. Please try again.');
return;
}

const response = await saveOutput(input, newLearningId, userData.user.id, title);
if (response && response.id) {
toast.success('Resource created successfully');
setPersistedId(newLearningId); // Update the persisted ID
} else {
console.error('Unexpected response structure:', response);
toast.error('Failed to upload keywords: Invalid response structure');
toast.error('Failed to create resource');
}
} catch (err: any) {
console.error('Error when handling upload:', err);
toast.error(`Failed to upload keywords: ${err.message || 'Unknown error'}`);
console.error('Error in handleUpload:', err);
toast.error(`Error when saving output: ${err.message}`);
} finally {
setIsLoading(false);
}
};

const submitChanges = async () => {
const supabase = createClient();
const {
data: { user },
error: userError,
} = await supabase.auth.getUser();

if (userError || !user) {
toast.error('User authentication failed. Please log in and try again.');
return;
}
if (isLoading) return;

if (!mylearning_id) {
toast.error('Learning ID is missing');
return;
}
try {
setIsLoading(true);
const supabase = createClient();
const {
data: { user },
error: userError,
} = await supabase.auth.getUser();

let input;
if (fileType == 'keywords') {
input = keywords;
}
if (userError || !user) {
toast.error('User authentication failed. Please log in and try again.');
return;
}

const newLearningId = generateNewId(); // Generate a new ID

if (fileType == 'keywords') {
if (!keywords.trim()) {
toast.error('Keywords cannot be empty');
return;
}
const input = keywords;
const title = `Keywords: ${keywords.slice(0, 30)}...`;
await handleUpload(input, title, newLearningId);
} else {
toast.error('Please select a file type');
return;
}

await handleUpload(input, mylearning_id, user.id);
// Redirect to the dashboard with the new ID
router.push(`/dashboard?mylearning_id=${newLearningId}`);
} catch (err: any) {
console.error('Error in submitChanges:', err);
toast.error(`Error when submitting changes: ${err.message}`);
} finally {
setIsLoading(false);
}
};

return (
Expand Down Expand Up @@ -214,7 +242,11 @@ export const ReUploadKeyword = () => {
{fileType && (
<div className="flex justify-end">
<DialogFooter>
<Button type="submit" onClick={submitChanges} disabled={isLoading}>
<Button
type="submit"
onClick={submitChanges}
disabled={isLoading}
>
{isLoading ? 'Uploading ...' : 'Upload'}
</Button>
</DialogFooter>
Expand Down
Loading

0 comments on commit 92d2989

Please sign in to comment.