mirror of
https://github.com/rzmk/learnhouse.git
synced 2025-12-19 04:19:25 +00:00
feat: refactor pdfBlock
This commit is contained in:
parent
3715157722
commit
619688676b
9 changed files with 86 additions and 137 deletions
|
|
@ -11,7 +11,7 @@ export default Node.create({
|
||||||
|
|
||||||
addAttributes() {
|
addAttributes() {
|
||||||
return {
|
return {
|
||||||
fileObject: {
|
blockObject: {
|
||||||
default: null,
|
default: null,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -2,13 +2,13 @@ import { NodeViewWrapper } from "@tiptap/react";
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import styled from "styled-components";
|
import styled from "styled-components";
|
||||||
import { AlertCircle, AlertTriangle, FileText, Image, ImagePlus, Info } from "lucide-react";
|
import { AlertCircle, AlertTriangle, FileText, Image, ImagePlus, Info } from "lucide-react";
|
||||||
import { getPDFFile, uploadNewPDFFile } from "../../../../services/files/documents";
|
import { getPDFFile, uploadNewPDFFile } from "../../../../services/blocks/Pdf/pdf";
|
||||||
import { getBackendUrl } from "../../../../services/config";
|
import { getBackendUrl } from "../../../../services/config";
|
||||||
|
|
||||||
function PDFBlockComponent(props: any) {
|
function PDFBlockComponent(props: any) {
|
||||||
const [pdf, setPDF] = React.useState(null);
|
const [pdf, setPDF] = React.useState(null);
|
||||||
const [isLoading, setIsLoading] = React.useState(false);
|
const [isLoading, setIsLoading] = React.useState(false);
|
||||||
const [fileObject, setfileObject] = React.useState(props.node.attrs.fileObject);
|
const [blockObject, setblockObject] = React.useState(props.node.attrs.blockObject);
|
||||||
|
|
||||||
const handlePDFChange = (event: React.ChangeEvent<any>) => {
|
const handlePDFChange = (event: React.ChangeEvent<any>) => {
|
||||||
setPDF(event.target.files[0]);
|
setPDF(event.target.files[0]);
|
||||||
|
|
@ -19,15 +19,15 @@ function PDFBlockComponent(props: any) {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
let object = await uploadNewPDFFile(pdf, props.extension.options.lecture.lecture_id);
|
let object = await uploadNewPDFFile(pdf, props.extension.options.lecture.lecture_id);
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
setfileObject(object);
|
setblockObject(object);
|
||||||
props.updateAttributes({
|
props.updateAttributes({
|
||||||
fileObject: object,
|
blockObject: object,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<NodeViewWrapper className="block-pdf">
|
<NodeViewWrapper className="block-pdf">
|
||||||
{!fileObject && (
|
{!blockObject && (
|
||||||
<BlockPDFWrapper contentEditable={props.extension.options.editable}>
|
<BlockPDFWrapper contentEditable={props.extension.options.editable}>
|
||||||
<div>
|
<div>
|
||||||
<FileText color="#e1e0e0" size={50} />
|
<FileText color="#e1e0e0" size={50} />
|
||||||
|
|
@ -38,11 +38,11 @@ function PDFBlockComponent(props: any) {
|
||||||
<button onClick={handleSubmit}>Submit</button>
|
<button onClick={handleSubmit}>Submit</button>
|
||||||
</BlockPDFWrapper>
|
</BlockPDFWrapper>
|
||||||
)}
|
)}
|
||||||
{fileObject && (
|
{blockObject && (
|
||||||
<BlockPDF>
|
<BlockPDF>
|
||||||
<iframe
|
<iframe
|
||||||
src={`${getBackendUrl()}content/uploads/files/documents/${props.extension.options.lecture.lecture_id}/${fileObject.file_id}.${
|
src={`${getBackendUrl()}content/uploads/files/lectures/${props.extension.options.lecture.lecture_id}/blocks/pdfBlock/${blockObject.block_id}/${blockObject.block_data.file_id}.${
|
||||||
fileObject.file_format
|
blockObject.block_data.file_format
|
||||||
}`}
|
}`}
|
||||||
/>
|
/>
|
||||||
</BlockPDF>
|
</BlockPDF>
|
||||||
|
|
|
||||||
|
|
@ -3,12 +3,12 @@ import { AlertTriangle, Image, Video } from "lucide-react";
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import styled from "styled-components";
|
import styled from "styled-components";
|
||||||
import { getBackendUrl } from "../../../../services/config";
|
import { getBackendUrl } from "../../../../services/config";
|
||||||
import { uploadNewVideoFile } from "../../../../services/files/video";
|
import { uploadNewVideoFile } from "../../../../services/blocks/Video/video";
|
||||||
|
|
||||||
function VideoBlockComponents(props: any) {
|
function VideoBlockComponents(props: any) {
|
||||||
const [video, setVideo] = React.useState(null);
|
const [video, setVideo] = React.useState(null);
|
||||||
const [isLoading, setIsLoading] = React.useState(false);
|
const [isLoading, setIsLoading] = React.useState(false);
|
||||||
const [blockObject, setblockObject] = React.useState(props.node.attrs.fileObject);
|
const [blockObject, setblockObject] = React.useState(props.node.attrs.blockObject);
|
||||||
|
|
||||||
const handleVideoChange = (event: React.ChangeEvent<any>) => {
|
const handleVideoChange = (event: React.ChangeEvent<any>) => {
|
||||||
setVideo(event.target.files[0]);
|
setVideo(event.target.files[0]);
|
||||||
|
|
|
||||||
|
|
@ -7,14 +7,14 @@ export async function uploadNewPDFFile(file: any, lecture_id: string) {
|
||||||
formData.append("file_object", file);
|
formData.append("file_object", file);
|
||||||
formData.append("lecture_id", lecture_id);
|
formData.append("lecture_id", lecture_id);
|
||||||
|
|
||||||
return fetch(`${getAPIUrl()}blocks/document`, RequestBodyForm("POST", formData))
|
return fetch(`${getAPIUrl()}blocks/pdf`, RequestBodyForm("POST", formData))
|
||||||
.then((result) => result.json())
|
.then((result) => result.json())
|
||||||
.catch((error) => console.log("error", error));
|
.catch((error) => console.log("error", error));
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getPDFFile(file_id: string) {
|
export async function getPDFFile(file_id: string) {
|
||||||
// todo : add course id to url
|
// todo : add course id to url
|
||||||
return fetch(`${getAPIUrl()}blocks/document?file_id=${file_id}`, RequestBody("GET", null))
|
return fetch(`${getAPIUrl()}blocks/pdf?file_id=${file_id}`, RequestBody("GET", null))
|
||||||
.then((result) => result.json())
|
.then((result) => result.json())
|
||||||
.catch((error) => console.log("error", error));
|
.catch((error) => console.log("error", error));
|
||||||
}
|
}
|
||||||
|
|
@ -3,12 +3,15 @@ from src.dependencies.auth import get_current_user
|
||||||
from fastapi import HTTPException, status, UploadFile
|
from fastapi import HTTPException, status, UploadFile
|
||||||
from src.services.blocks.block_types.imageBlock.images import create_image_file, get_image_file
|
from src.services.blocks.block_types.imageBlock.images import create_image_file, get_image_file
|
||||||
from src.services.blocks.block_types.videoBlock.videoBlock import create_video_block, get_video_block
|
from src.services.blocks.block_types.videoBlock.videoBlock import create_video_block, get_video_block
|
||||||
from src.services.blocks.block_types.pdfBlock.documents import create_document_file, get_document_file
|
from src.services.blocks.block_types.pdfBlock.pdfBlock import create_pdf_block, get_pdf_block
|
||||||
from src.services.blocks.block_types.quizBlock.quizBlock import create_quiz_block, get_quiz_block_answers, get_quiz_block_options, quizBlock
|
from src.services.blocks.block_types.quizBlock.quizBlock import create_quiz_block, get_quiz_block_answers, get_quiz_block_options, quizBlock
|
||||||
from src.services.users.users import PublicUser
|
from src.services.users.users import PublicUser
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
####################
|
||||||
|
# Image Block
|
||||||
|
####################
|
||||||
|
|
||||||
@router.post("/image")
|
@router.post("/image")
|
||||||
async def api_create_image_file_block(request: Request, file_object: UploadFile, lecture_id: str = Form(), current_user: PublicUser = Depends(get_current_user)):
|
async def api_create_image_file_block(request: Request, file_object: UploadFile, lecture_id: str = Form(), current_user: PublicUser = Depends(get_current_user)):
|
||||||
|
|
@ -25,6 +28,9 @@ async def api_get_image_file_block(request: Request, file_id: str, current_user:
|
||||||
"""
|
"""
|
||||||
return await get_image_file(request, file_id, current_user)
|
return await get_image_file(request, file_id, current_user)
|
||||||
|
|
||||||
|
####################
|
||||||
|
# Video Block
|
||||||
|
####################
|
||||||
|
|
||||||
@router.post("/video")
|
@router.post("/video")
|
||||||
async def api_create_video_file_block(request: Request, file_object: UploadFile, lecture_id: str = Form(), current_user: PublicUser = Depends(get_current_user)):
|
async def api_create_video_file_block(request: Request, file_object: UploadFile, lecture_id: str = Form(), current_user: PublicUser = Depends(get_current_user)):
|
||||||
|
|
@ -41,23 +47,30 @@ async def api_get_video_file_block(request: Request, file_id: str, current_user:
|
||||||
"""
|
"""
|
||||||
return await get_video_block(request, file_id, current_user)
|
return await get_video_block(request, file_id, current_user)
|
||||||
|
|
||||||
|
####################
|
||||||
|
# PDF Block
|
||||||
|
####################
|
||||||
|
|
||||||
@router.post("/document")
|
@router.post("/pdf")
|
||||||
async def api_create_document_file_block(request: Request, file_object: UploadFile, lecture_id: str = Form(), current_user: PublicUser = Depends(get_current_user)):
|
async def api_create_pdf_file_block(request: Request, file_object: UploadFile, lecture_id: str = Form(), current_user: PublicUser = Depends(get_current_user)):
|
||||||
"""
|
"""
|
||||||
Create new document file
|
Create new pdf file
|
||||||
"""
|
"""
|
||||||
return await create_document_file(request, file_object, lecture_id)
|
return await create_pdf_block(request, file_object, lecture_id)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/document")
|
@router.get("/pdf")
|
||||||
async def api_get_document_file_block(request: Request, file_id: str, current_user: PublicUser = Depends(get_current_user)):
|
async def api_get_pdf_file_block(request: Request, file_id: str, current_user: PublicUser = Depends(get_current_user)):
|
||||||
"""
|
"""
|
||||||
Get document file
|
Get pdf file
|
||||||
"""
|
"""
|
||||||
return await get_document_file(request, file_id, current_user)
|
return await get_pdf_block(request, file_id, current_user)
|
||||||
|
|
||||||
|
|
||||||
|
####################
|
||||||
|
# Quiz Block
|
||||||
|
####################
|
||||||
|
|
||||||
@router.post("/quiz/{lecture_id}")
|
@router.post("/quiz/{lecture_id}")
|
||||||
async def api_create_quiz_block(request: Request, quiz_block: quizBlock, lecture_id: str, current_user: PublicUser = Depends(get_current_user)):
|
async def api_create_quiz_block(request: Request, quiz_block: quizBlock, lecture_id: str, current_user: PublicUser = Depends(get_current_user)):
|
||||||
"""
|
"""
|
||||||
|
|
|
||||||
|
|
@ -1,112 +0,0 @@
|
||||||
from uuid import uuid4
|
|
||||||
from pydantic import BaseModel
|
|
||||||
from fastapi import HTTPException, status, UploadFile, Request
|
|
||||||
from fastapi.responses import StreamingResponse
|
|
||||||
import os
|
|
||||||
|
|
||||||
from src.services.users.users import PublicUser
|
|
||||||
|
|
||||||
|
|
||||||
class DocumentFile(BaseModel):
|
|
||||||
file_id: str
|
|
||||||
file_format: str
|
|
||||||
file_name: str
|
|
||||||
file_size: int
|
|
||||||
file_type: str
|
|
||||||
lecture_id: str
|
|
||||||
|
|
||||||
|
|
||||||
async def create_document_file(request: Request, document_file: UploadFile, lecture_id: str):
|
|
||||||
documents = request.app.db["files"]
|
|
||||||
|
|
||||||
# generate file_id
|
|
||||||
file_id = str(f"file_{uuid4()}")
|
|
||||||
|
|
||||||
# get file format
|
|
||||||
file_format = document_file.filename.split(".")[-1]
|
|
||||||
|
|
||||||
# validate file format
|
|
||||||
if file_format not in ["pdf"]:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_409_CONFLICT, detail="Document file format not supported")
|
|
||||||
|
|
||||||
# create file
|
|
||||||
file = await document_file.read()
|
|
||||||
|
|
||||||
# get file size
|
|
||||||
file_size = len(file)
|
|
||||||
|
|
||||||
# get file type
|
|
||||||
file_type = document_file.content_type
|
|
||||||
|
|
||||||
# get file name
|
|
||||||
file_name = document_file.filename
|
|
||||||
|
|
||||||
# create file object
|
|
||||||
uploadable_file = DocumentFile(
|
|
||||||
file_id=file_id,
|
|
||||||
file_format=file_format,
|
|
||||||
file_name=file_name,
|
|
||||||
file_size=file_size,
|
|
||||||
file_type=file_type,
|
|
||||||
lecture_id=lecture_id
|
|
||||||
)
|
|
||||||
# TODO : this is probably not working as intended
|
|
||||||
# create folder for lecture
|
|
||||||
if not os.path.exists(f"content/uploads/files/documents/{lecture_id}"):
|
|
||||||
os.mkdir(f"content/uploads/files/documents/{lecture_id}")
|
|
||||||
|
|
||||||
# upload file to server
|
|
||||||
with open(f"content/uploads/files/documents/{lecture_id}/{file_id}.{file_format}", 'wb') as f:
|
|
||||||
f.write(file)
|
|
||||||
f.close()
|
|
||||||
|
|
||||||
# insert file object into database
|
|
||||||
document_file_in_db = await documents.insert_one(uploadable_file.dict())
|
|
||||||
|
|
||||||
if not document_file_in_db:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_409_CONFLICT, detail="Document file could not be created")
|
|
||||||
|
|
||||||
return uploadable_file
|
|
||||||
|
|
||||||
|
|
||||||
async def get_document_object(request: Request, file_id: str):
|
|
||||||
documents = request.app.db["files"]
|
|
||||||
|
|
||||||
document_file = await documents.find_one({"file_id": file_id})
|
|
||||||
|
|
||||||
if document_file:
|
|
||||||
document_file = DocumentFile(**document_file)
|
|
||||||
return document_file
|
|
||||||
|
|
||||||
else:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_409_CONFLICT, detail="Document file does not exist")
|
|
||||||
|
|
||||||
|
|
||||||
async def get_document_file(request: Request, file_id: str, current_user: PublicUser):
|
|
||||||
documents = request.app.db["files"]
|
|
||||||
|
|
||||||
document_file = await documents.find_one({"file_id": file_id})
|
|
||||||
|
|
||||||
# TODO : check if user has access to file
|
|
||||||
|
|
||||||
if document_file:
|
|
||||||
|
|
||||||
# check media type
|
|
||||||
if document_file.format not in ["pdf"]:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_409_CONFLICT, detail="Document file format not supported")
|
|
||||||
|
|
||||||
# stream file
|
|
||||||
document_file = DocumentFile(**document_file)
|
|
||||||
file_format = document_file.file_format
|
|
||||||
lecture_id = document_file.lecture_id
|
|
||||||
file = open(
|
|
||||||
f"content/uploads/files/documents/{lecture_id}/{file_id}.{file_format}", 'rb')
|
|
||||||
return StreamingResponse(file, media_type=document_file.file_type)
|
|
||||||
|
|
||||||
else:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_409_CONFLICT, detail="Document file does not exist")
|
|
||||||
47
src/services/blocks/block_types/pdfBlock/pdfBlock.py
Normal file
47
src/services/blocks/block_types/pdfBlock/pdfBlock.py
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
from uuid import uuid4
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from fastapi import HTTPException, status, UploadFile, Request
|
||||||
|
from fastapi.responses import StreamingResponse
|
||||||
|
import os
|
||||||
|
from src.services.blocks.schemas.blocks import Block
|
||||||
|
from src.services.blocks.utils.upload_files import upload_file_and_return_file_object
|
||||||
|
|
||||||
|
from src.services.users.users import PublicUser
|
||||||
|
|
||||||
|
|
||||||
|
async def create_pdf_block(request: Request, pdf_file: UploadFile, lecture_id: str):
|
||||||
|
blocks = request.app.db["blocks"]
|
||||||
|
lecture = request.app.db["lectures"]
|
||||||
|
|
||||||
|
block_type = "pdfBlock"
|
||||||
|
|
||||||
|
# get org_id from lecture
|
||||||
|
lecture = await lecture.find_one({"lecture_id": lecture_id}, {"_id": 0, "org_id": 1})
|
||||||
|
org_id = lecture["org_id"]
|
||||||
|
|
||||||
|
# get block id
|
||||||
|
block_id = str(f"block_{uuid4()}")
|
||||||
|
|
||||||
|
block_data = await upload_file_and_return_file_object(request, pdf_file, lecture_id, block_id, ["pdf"], block_type)
|
||||||
|
|
||||||
|
# create block
|
||||||
|
block = Block(block_id=block_id, lecture_id=lecture_id,
|
||||||
|
block_type=block_type, block_data=block_data, org_id=org_id)
|
||||||
|
|
||||||
|
# insert block
|
||||||
|
await blocks.insert_one(block.dict())
|
||||||
|
|
||||||
|
return block
|
||||||
|
|
||||||
|
|
||||||
|
async def get_pdf_block(request: Request, file_id: str, current_user: PublicUser):
|
||||||
|
blocks = request.app.db["blocks"]
|
||||||
|
|
||||||
|
pdf_block = await blocks.find_one({"block_id": file_id})
|
||||||
|
|
||||||
|
if pdf_block:
|
||||||
|
return Block(**pdf_block)
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT, detail="Video file does not exist")
|
||||||
|
|
@ -14,6 +14,7 @@ async def create_video_block(request: Request, video_file: UploadFile, lecture_i
|
||||||
lecture = request.app.db["lectures"]
|
lecture = request.app.db["lectures"]
|
||||||
|
|
||||||
block_type = "videoBlock"
|
block_type = "videoBlock"
|
||||||
|
|
||||||
# get org_id from lecture
|
# get org_id from lecture
|
||||||
lecture = await lecture.find_one({"lecture_id": lecture_id}, {"_id": 0, "org_id": 1})
|
lecture = await lecture.find_one({"lecture_id": lecture_id}, {"_id": 0, "org_id": 1})
|
||||||
org_id = lecture["org_id"]
|
org_id = lecture["org_id"]
|
||||||
|
|
@ -34,13 +35,13 @@ async def create_video_block(request: Request, video_file: UploadFile, lecture_i
|
||||||
|
|
||||||
|
|
||||||
async def get_video_block(request: Request, file_id: str, current_user: PublicUser):
|
async def get_video_block(request: Request, file_id: str, current_user: PublicUser):
|
||||||
photos = request.app.db["blocks"]
|
blocks = request.app.db["blocks"]
|
||||||
|
|
||||||
video_block = await photos.find_one({"block_id": file_id})
|
video_block = await blocks.find_one({"block_id": file_id})
|
||||||
|
|
||||||
if video_block:
|
if video_block:
|
||||||
return Block(**video_block)
|
return Block(**video_block)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_409_CONFLICT, detail="Photo file does not exist")
|
status_code=status.HTTP_409_CONFLICT, detail="Video file does not exist")
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue