Compare commits
No commits in common. "12fe476e97e2d907fcb41baa87bd8e1ca74f1b80" and "97aa87d8b115d1507256ced7ce8b7b217bf52c0a" have entirely different histories.
12fe476e97
...
97aa87d8b1
37
package-lock.json
generated
37
package-lock.json
generated
@ -30,7 +30,6 @@
|
||||
"lodash": "4.17.21",
|
||||
"mui-file-input": "4.0.4",
|
||||
"nostr-tools": "2.7.0",
|
||||
"pdf-lib": "^1.17.1",
|
||||
"pdfjs-dist": "^4.4.168",
|
||||
"react": "^18.2.0",
|
||||
"react-dnd": "16.0.1",
|
||||
@ -1742,24 +1741,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@pdf-lib/standard-fonts": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@pdf-lib/standard-fonts/-/standard-fonts-1.0.0.tgz",
|
||||
"integrity": "sha512-hU30BK9IUN/su0Mn9VdlVKsWBS6GyhVfqjwl1FjZN4TxP6cCw0jP2w7V3Hf5uX7M0AZJ16vey9yE0ny7Sa59ZA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pako": "^1.0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/@pdf-lib/upng": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@pdf-lib/upng/-/upng-1.0.1.tgz",
|
||||
"integrity": "sha512-dQK2FUMQtowVP00mtIksrlZhdFXQZPC+taih1q4CvPZ5vqdxR/LKBaFg0oAfzd1GlHZXXSPdQfzQnt+ViGvEIQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pako": "^1.0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/@popperjs/core": {
|
||||
"version": "2.11.8",
|
||||
"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz",
|
||||
@ -4781,18 +4762,6 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/pdf-lib": {
|
||||
"version": "1.17.1",
|
||||
"resolved": "https://registry.npmjs.org/pdf-lib/-/pdf-lib-1.17.1.tgz",
|
||||
"integrity": "sha512-V/mpyJAoTsN4cnP31vc0wfNA1+p20evqqnap0KLoRUN0Yk/p3wN52DOEsL4oBFcLdb76hlpKPtzJIgo67j/XLw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@pdf-lib/standard-fonts": "^1.0.0",
|
||||
"@pdf-lib/upng": "^1.0.1",
|
||||
"pako": "^1.0.11",
|
||||
"tslib": "^1.11.1"
|
||||
}
|
||||
},
|
||||
"node_modules/pdfjs-dist": {
|
||||
"version": "4.4.168",
|
||||
"resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-4.4.168.tgz",
|
||||
@ -5649,12 +5618,6 @@
|
||||
"resolved": "https://registry.npmjs.org/tseep/-/tseep-1.2.1.tgz",
|
||||
"integrity": "sha512-VFnsNcPGC4qFJ1nxbIPSjTmtRZOhlqLmtwRqtLVos8mbRHki8HO9cy9Z1e89EiWyxFmq6LBviI9TQjijxw/mEw=="
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "1.14.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
|
||||
"integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/tstl": {
|
||||
"version": "2.5.13",
|
||||
"resolved": "https://registry.npmjs.org/tstl/-/tstl-2.5.13.tgz",
|
||||
|
@ -36,7 +36,6 @@
|
||||
"lodash": "4.17.21",
|
||||
"mui-file-input": "4.0.4",
|
||||
"nostr-tools": "2.7.0",
|
||||
"pdf-lib": "^1.17.1",
|
||||
"pdfjs-dist": "^4.4.168",
|
||||
"react": "^18.2.0",
|
||||
"react-dnd": "16.0.1",
|
||||
|
@ -8,11 +8,10 @@ import { ProfileMetadata, User } from '../../types';
|
||||
import { PdfFile, DrawTool, MouseState, PdfPage, DrawnField, MarkType } from '../../types/drawing';
|
||||
import { truncate } from 'lodash';
|
||||
import { hexToNpub } from '../../utils';
|
||||
import { toPdfFiles } from '../../utils/pdf.ts'
|
||||
PDFJS.GlobalWorkerOptions.workerSrc = 'node_modules/pdfjs-dist/build/pdf.worker.mjs';
|
||||
|
||||
interface Props {
|
||||
selectedFiles: File[]
|
||||
selectedFiles: any[]
|
||||
users: User[]
|
||||
metadata: { [key: string]: ProfileMetadata }
|
||||
onDrawFieldsChange: (pdfFiles: PdfFile[]) => void
|
||||
@ -139,7 +138,7 @@ export const DrawPDFFields = (props: Props) => {
|
||||
* Drawing is finished, resets all the variables used to draw
|
||||
* @param event Mouse event
|
||||
*/
|
||||
const onMouseUp = () => {
|
||||
const onMouseUp = (event: MouseEvent) => {
|
||||
setMouseState((prev) => {
|
||||
return {
|
||||
...prev,
|
||||
@ -187,7 +186,7 @@ export const DrawPDFFields = (props: Props) => {
|
||||
* @param event Mouse event
|
||||
* @param drawnField Which we are moving
|
||||
*/
|
||||
const onDrawnFieldMouseDown = (event: any) => {
|
||||
const onDrawnFieldMouseDown = (event: any, drawnField: DrawnField) => {
|
||||
event.stopPropagation()
|
||||
|
||||
// Proceed only if left click
|
||||
@ -240,7 +239,7 @@ export const DrawPDFFields = (props: Props) => {
|
||||
* @param event Mouse event
|
||||
* @param drawnField which we are resizing
|
||||
*/
|
||||
const onResizeHandleMouseDown = (event: any) => {
|
||||
const onResizeHandleMouseDown = (event: any, drawnField: DrawnField) => {
|
||||
// Proceed only if left click
|
||||
if (event.button !== 0) return
|
||||
|
||||
@ -316,11 +315,73 @@ export const DrawPDFFields = (props: Props) => {
|
||||
* creates the pdfFiles object and sets to a state
|
||||
*/
|
||||
const parsePdfPages = async () => {
|
||||
const pdfFiles: PdfFile[] = await toPdfFiles(selectedFiles);
|
||||
const pdfFiles: PdfFile[] = []
|
||||
|
||||
for (const file of selectedFiles) {
|
||||
if (file.type.toLowerCase().includes('pdf')) {
|
||||
const data = await readPdf(file)
|
||||
const pages = await pdfToImages(data)
|
||||
|
||||
pdfFiles.push({
|
||||
file: file,
|
||||
pages: pages,
|
||||
expanded: false
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
setPdfFiles(pdfFiles)
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts pdf to the images
|
||||
* @param data pdf file bytes
|
||||
*/
|
||||
const pdfToImages = async (data: any): Promise<PdfPage[]> => {
|
||||
const images: string[] = [];
|
||||
const pdf = await PDFJS.getDocument(data).promise;
|
||||
const canvas = document.createElement("canvas");
|
||||
|
||||
for (let i = 0; i < pdf.numPages; i++) {
|
||||
const page = await pdf.getPage(i + 1);
|
||||
const viewport = page.getViewport({ scale: 3 });
|
||||
const context = canvas.getContext("2d");
|
||||
canvas.height = viewport.height;
|
||||
canvas.width = viewport.width;
|
||||
await page.render({ canvasContext: context!, viewport: viewport }).promise;
|
||||
images.push(canvas.toDataURL());
|
||||
}
|
||||
|
||||
return Promise.resolve(images.map((image) => {
|
||||
return {
|
||||
image,
|
||||
drawnFields: []
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the pdf file binaries
|
||||
*/
|
||||
const readPdf = (file: File) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = (e: any) => {
|
||||
const data = e.target.result
|
||||
|
||||
resolve(data)
|
||||
};
|
||||
|
||||
reader.onerror = (err) => {
|
||||
console.error('err', err)
|
||||
reject(err)
|
||||
};
|
||||
|
||||
reader.readAsDataURL(file);
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns if expanded pdf accordion is present
|
||||
@ -376,7 +437,7 @@ export const DrawPDFFields = (props: Props) => {
|
||||
return (
|
||||
<div
|
||||
key={drawnFieldIndex}
|
||||
onMouseDown={onDrawnFieldMouseDown}
|
||||
onMouseDown={(event) => { onDrawnFieldMouseDown(event, drawnField) }}
|
||||
onMouseMove={(event) => { onDranwFieldMouseMove(event, drawnField)}}
|
||||
className={styles.drawingRectangle}
|
||||
style={{
|
||||
@ -388,7 +449,7 @@ export const DrawPDFFields = (props: Props) => {
|
||||
}}
|
||||
>
|
||||
<span
|
||||
onMouseDown={onResizeHandleMouseDown}
|
||||
onMouseDown={(event) => {onResizeHandleMouseDown(event, drawnField)}}
|
||||
onMouseMove={(event) => {onResizeHandleMouseMove(event, drawnField)}}
|
||||
className={styles.resizeHandle}
|
||||
></span>
|
||||
@ -399,7 +460,7 @@ export const DrawPDFFields = (props: Props) => {
|
||||
<Close fontSize='small'/>
|
||||
</span>
|
||||
<div
|
||||
onMouseDown={onUserSelectHandleMouseDown}
|
||||
onMouseDown={(event) => {onUserSelectHandleMouseDown(event)}}
|
||||
className={styles.userSelect}
|
||||
>
|
||||
<FormControl fullWidth size='small'>
|
||||
|
@ -59,17 +59,13 @@
|
||||
.drawingRectangle {
|
||||
position: absolute;
|
||||
border: 1px solid #01aaad;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
z-index: 50;
|
||||
background-color: #01aaad4b;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
|
||||
&.nonEditable {
|
||||
cursor: default;
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
.resizeHandle {
|
||||
position: absolute;
|
||||
|
@ -1,35 +0,0 @@
|
||||
import { PdfFile } from '../../types/drawing.ts'
|
||||
import { CurrentUserMark } from '../../types/mark.ts'
|
||||
import PdfPageItem from './PdfPageItem.tsx';
|
||||
|
||||
interface PdfItemProps {
|
||||
pdfFile: PdfFile
|
||||
currentUserMarks: CurrentUserMark[]
|
||||
handleMarkClick: (id: number) => void
|
||||
selectedMarkValue: string
|
||||
selectedMark: CurrentUserMark | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Responsible for displaying pages of a single Pdf File.
|
||||
*/
|
||||
const PdfItem = ({ pdfFile, currentUserMarks, handleMarkClick, selectedMarkValue, selectedMark }: PdfItemProps) => {
|
||||
const filterByPage = (marks: CurrentUserMark[], page: number): CurrentUserMark[] => {
|
||||
return marks.filter((m) => m.mark.location.page === page);
|
||||
}
|
||||
return (
|
||||
pdfFile.pages.map((page, i) => {
|
||||
return (
|
||||
<PdfPageItem
|
||||
page={page}
|
||||
key={i}
|
||||
currentUserMarks={filterByPage(currentUserMarks, i)}
|
||||
handleMarkClick={handleMarkClick}
|
||||
selectedMarkValue={selectedMarkValue}
|
||||
selectedMark={selectedMark}
|
||||
/>
|
||||
)
|
||||
}))
|
||||
}
|
||||
|
||||
export default PdfItem
|
@ -1,37 +0,0 @@
|
||||
import { CurrentUserMark } from '../../types/mark.ts'
|
||||
import styles from '../DrawPDFFields/style.module.scss'
|
||||
import { inPx } from '../../utils/pdf.ts'
|
||||
|
||||
interface PdfMarkItemProps {
|
||||
userMark: CurrentUserMark
|
||||
handleMarkClick: (id: number) => void
|
||||
selectedMarkValue: string
|
||||
selectedMark: CurrentUserMark | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Responsible for display an individual Pdf Mark.
|
||||
*/
|
||||
const PdfMarkItem = ({ selectedMark, handleMarkClick, selectedMarkValue, userMark }: PdfMarkItemProps) => {
|
||||
const { location } = userMark.mark;
|
||||
const handleClick = () => handleMarkClick(userMark.mark.id);
|
||||
const getMarkValue = () => (
|
||||
selectedMark?.mark.id === userMark.mark.id
|
||||
? selectedMarkValue
|
||||
: userMark.mark.value
|
||||
)
|
||||
return (
|
||||
<div
|
||||
onClick={handleClick}
|
||||
className={styles.drawingRectangle}
|
||||
style={{
|
||||
left: inPx(location.left),
|
||||
top: inPx(location.top),
|
||||
width: inPx(location.width),
|
||||
height: inPx(location.height)
|
||||
}}
|
||||
>{getMarkValue()}</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PdfMarkItem
|
@ -1,101 +0,0 @@
|
||||
import { Box } from '@mui/material'
|
||||
import styles from '../../pages/sign/style.module.scss'
|
||||
import PdfView from './index.tsx'
|
||||
import MarkFormField from '../../pages/sign/MarkFormField.tsx'
|
||||
import { PdfFile } from '../../types/drawing.ts'
|
||||
import { CurrentUserMark, Mark } from '../../types/mark.ts'
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import {
|
||||
findNextCurrentUserMark,
|
||||
isCurrentUserMarksComplete,
|
||||
updateCurrentUserMarks,
|
||||
} from '../../utils/mark.ts'
|
||||
|
||||
import { EMPTY } from '../../utils/const.ts'
|
||||
|
||||
interface PdfMarkingProps {
|
||||
files: { pdfFile: PdfFile, filename: string, hash: string | null }[],
|
||||
currentUserMarks: CurrentUserMark[],
|
||||
setIsReadyToSign: (isReadyToSign: boolean) => void,
|
||||
setCurrentUserMarks: (currentUserMarks: CurrentUserMark[]) => void,
|
||||
setUpdatedMarks: (markToUpdate: Mark) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Top-level component responsible for displaying Pdfs, Pages, and Marks,
|
||||
* as well as tracking if the document is ready to be signed.
|
||||
* @param props
|
||||
* @constructor
|
||||
*/
|
||||
const PdfMarking = (props: PdfMarkingProps) => {
|
||||
const {
|
||||
files,
|
||||
currentUserMarks,
|
||||
setIsReadyToSign,
|
||||
setCurrentUserMarks,
|
||||
setUpdatedMarks
|
||||
} = props
|
||||
const [selectedMark, setSelectedMark] = useState<CurrentUserMark | null>(null)
|
||||
const [selectedMarkValue, setSelectedMarkValue] = useState<string>("")
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedMark(findNextCurrentUserMark(currentUserMarks) || null)
|
||||
}, [currentUserMarks])
|
||||
|
||||
const handleMarkClick = (id: number) => {
|
||||
const nextMark = currentUserMarks.find((mark) => mark.mark.id === id);
|
||||
setSelectedMark(nextMark!);
|
||||
setSelectedMarkValue(nextMark?.mark.value ?? EMPTY);
|
||||
}
|
||||
|
||||
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (!selectedMarkValue || !selectedMark) return;
|
||||
|
||||
const updatedMark: CurrentUserMark = {
|
||||
...selectedMark,
|
||||
mark: {
|
||||
...selectedMark.mark,
|
||||
value: selectedMarkValue
|
||||
},
|
||||
isCompleted: true
|
||||
}
|
||||
|
||||
setSelectedMarkValue(EMPTY)
|
||||
const updatedCurrentUserMarks = updateCurrentUserMarks(currentUserMarks, updatedMark);
|
||||
setCurrentUserMarks(updatedCurrentUserMarks)
|
||||
setSelectedMark(findNextCurrentUserMark(updatedCurrentUserMarks) || null)
|
||||
console.log(isCurrentUserMarksComplete(updatedCurrentUserMarks))
|
||||
setIsReadyToSign(isCurrentUserMarksComplete(updatedCurrentUserMarks))
|
||||
setUpdatedMarks(updatedMark.mark)
|
||||
}
|
||||
|
||||
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => setSelectedMarkValue(event.target.value)
|
||||
|
||||
return (
|
||||
<>
|
||||
<Box className={styles.container}>
|
||||
{
|
||||
currentUserMarks?.length > 0 && (
|
||||
<PdfView
|
||||
files={files}
|
||||
handleMarkClick={handleMarkClick}
|
||||
selectedMarkValue={selectedMarkValue}
|
||||
selectedMark={selectedMark}
|
||||
currentUserMarks={currentUserMarks}
|
||||
/>)}
|
||||
{
|
||||
selectedMark !== null && (
|
||||
<MarkFormField
|
||||
handleSubmit={handleSubmit}
|
||||
handleChange={handleChange}
|
||||
selectedMark={selectedMark}
|
||||
selectedMarkValue={selectedMarkValue}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default PdfMarking
|
@ -1,46 +0,0 @@
|
||||
import styles from '../DrawPDFFields/style.module.scss'
|
||||
import { PdfPage } from '../../types/drawing.ts'
|
||||
import { CurrentUserMark } from '../../types/mark.ts'
|
||||
import PdfMarkItem from './PdfMarkItem.tsx'
|
||||
interface PdfPageProps {
|
||||
page: PdfPage
|
||||
currentUserMarks: CurrentUserMark[]
|
||||
handleMarkClick: (id: number) => void
|
||||
selectedMarkValue: string
|
||||
selectedMark: CurrentUserMark | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Responsible for rendering a single Pdf Page and its Marks
|
||||
*/
|
||||
const PdfPageItem = ({ page, currentUserMarks, handleMarkClick, selectedMarkValue, selectedMark }: PdfPageProps) => {
|
||||
return (
|
||||
<div
|
||||
className={styles.pdfImageWrapper}
|
||||
style={{
|
||||
border: '1px solid #c4c4c4',
|
||||
marginBottom: '10px',
|
||||
marginTop: '10px'
|
||||
}}
|
||||
>
|
||||
<img
|
||||
draggable="false"
|
||||
src={page.image}
|
||||
style={{ width: '100%'}}
|
||||
|
||||
/>
|
||||
{
|
||||
currentUserMarks.map((m, i) => (
|
||||
<PdfMarkItem
|
||||
key={i}
|
||||
handleMarkClick={handleMarkClick}
|
||||
selectedMarkValue={selectedMarkValue}
|
||||
userMark={m}
|
||||
selectedMark={selectedMark}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PdfPageItem
|
@ -1,42 +0,0 @@
|
||||
import { PdfFile } from '../../types/drawing.ts'
|
||||
import { Box } from '@mui/material'
|
||||
import PdfItem from './PdfItem.tsx'
|
||||
import { CurrentUserMark } from '../../types/mark.ts'
|
||||
|
||||
interface PdfViewProps {
|
||||
files: { pdfFile: PdfFile, filename: string, hash: string | null }[]
|
||||
currentUserMarks: CurrentUserMark[]
|
||||
handleMarkClick: (id: number) => void
|
||||
selectedMarkValue: string
|
||||
selectedMark: CurrentUserMark | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Responsible for rendering Pdf files.
|
||||
*/
|
||||
const PdfView = ({ files, currentUserMarks, handleMarkClick, selectedMarkValue, selectedMark }: PdfViewProps) => {
|
||||
const filterByFile = (currentUserMarks: CurrentUserMark[], hash: string): CurrentUserMark[] => {
|
||||
return currentUserMarks.filter((currentUserMark) => currentUserMark.mark.pdfFileHash === hash)
|
||||
}
|
||||
return (
|
||||
<Box sx={{ width: '100%' }}>
|
||||
{
|
||||
files.map(({ pdfFile, hash }, i) => {
|
||||
if (!hash) return
|
||||
return (
|
||||
<PdfItem
|
||||
pdfFile={pdfFile}
|
||||
key={i}
|
||||
currentUserMarks={filterByFile(currentUserMarks, hash)}
|
||||
selectedMark={selectedMark}
|
||||
handleMarkClick={handleMarkClick}
|
||||
selectedMarkValue={selectedMarkValue}
|
||||
/>
|
||||
)
|
||||
})
|
||||
}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export default PdfView;
|
@ -1,16 +0,0 @@
|
||||
.imageWrapper {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
width: 100%; /* Adjust as needed */
|
||||
height: 100%; /* Adjust as needed */
|
||||
overflow: hidden; /* Ensure no overflow */
|
||||
border: 1px solid #ccc; /* Optional: for visual debugging */
|
||||
background-color: #e0f7fa; /* Optional: for visual debugging */
|
||||
}
|
||||
|
||||
.image {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
object-fit: contain; /* Ensure the image fits within the container */
|
||||
}
|
@ -62,8 +62,6 @@ import {
|
||||
import styles from './style.module.scss'
|
||||
import { PdfFile } from '../../types/drawing'
|
||||
import { DrawPDFFields } from '../../components/DrawPDFFields'
|
||||
import { Mark } from '../../types/mark.ts'
|
||||
import { Container } from '../../components/Container'
|
||||
|
||||
export const CreatePage = () => {
|
||||
const navigate = useNavigate()
|
||||
@ -341,29 +339,26 @@ export const CreatePage = () => {
|
||||
return fileHashes
|
||||
}
|
||||
|
||||
const createMarks = (fileHashes: { [key: string]: string }) : Mark[] => {
|
||||
return drawnPdfs.flatMap((drawnPdf) => {
|
||||
const fileHash = fileHashes[drawnPdf.file.name];
|
||||
return drawnPdf.pages.flatMap((page, index) => {
|
||||
return page.drawnFields.map((drawnField) => {
|
||||
return {
|
||||
type: drawnField.type,
|
||||
location: {
|
||||
page: index,
|
||||
top: drawnField.top,
|
||||
left: drawnField.left,
|
||||
height: drawnField.height,
|
||||
width: drawnField.width,
|
||||
},
|
||||
npub: drawnField.counterpart,
|
||||
pdfFileHash: fileHash
|
||||
}
|
||||
const createMarkConfig = (fileHashes: { [key: string]: string }) => {
|
||||
let markConfig: any = {}
|
||||
|
||||
drawnPdfs.forEach(drawnPdf => {
|
||||
const fileHash = fileHashes[drawnPdf.file.name]
|
||||
|
||||
drawnPdf.pages.forEach((page, pageIndex) => {
|
||||
page.drawnFields.forEach(drawnField => {
|
||||
if (!markConfig[drawnField.counterpart]) markConfig[drawnField.counterpart] = {}
|
||||
if (!markConfig[drawnField.counterpart][fileHash]) markConfig[drawnField.counterpart][fileHash] = []
|
||||
|
||||
markConfig[drawnField.counterpart][fileHash].push({
|
||||
markType: drawnField.type,
|
||||
markLocation: `P:${pageIndex};X:${drawnField.left};Y:${drawnField.top}`
|
||||
})
|
||||
})
|
||||
})
|
||||
.map((mark, index) => {
|
||||
return {...mark, id: index }
|
||||
});
|
||||
})
|
||||
|
||||
return markConfig
|
||||
}
|
||||
|
||||
// Handle errors during zip file generation
|
||||
@ -378,13 +373,15 @@ export const CreatePage = () => {
|
||||
const generateZipFile = async (zip: JSZip): Promise<ArrayBuffer | null> => {
|
||||
setLoadingSpinnerDesc('Generating zip file')
|
||||
|
||||
return await zip
|
||||
const arraybuffer = await zip
|
||||
.generateAsync({
|
||||
type: 'arraybuffer',
|
||||
compression: 'DEFLATE',
|
||||
compressionOptions: { level: 6 }
|
||||
})
|
||||
.catch(handleZipError)
|
||||
|
||||
return arraybuffer
|
||||
}
|
||||
|
||||
// Encrypt the zip file with the generated encryption key
|
||||
@ -431,13 +428,15 @@ export const CreatePage = () => {
|
||||
|
||||
if (!arraybuffer) return null
|
||||
|
||||
return new File(
|
||||
const finalZipFile = new File(
|
||||
[new Blob([arraybuffer])],
|
||||
`${unixNow}.sigit.zip`,
|
||||
{
|
||||
type: 'application/zip'
|
||||
}
|
||||
)
|
||||
|
||||
return finalZipFile
|
||||
}
|
||||
|
||||
// Handle errors during file upload
|
||||
@ -459,12 +458,14 @@ export const CreatePage = () => {
|
||||
type: 'application/sigit'
|
||||
})
|
||||
|
||||
return await uploadToFileStorage(file)
|
||||
const fileUrl = await uploadToFileStorage(file)
|
||||
.then((url) => {
|
||||
toast.success('files.zip uploaded to file storage')
|
||||
return url
|
||||
})
|
||||
.catch(handleUploadError)
|
||||
|
||||
return fileUrl
|
||||
}
|
||||
|
||||
// Manage offline scenarios for signing or viewing the file
|
||||
@ -488,13 +489,15 @@ export const CreatePage = () => {
|
||||
zip.file(file.name, file)
|
||||
})
|
||||
|
||||
return await zip
|
||||
const arraybuffer = await zip
|
||||
.generateAsync({
|
||||
type: 'arraybuffer',
|
||||
compression: 'DEFLATE',
|
||||
compressionOptions: { level: 6 }
|
||||
})
|
||||
.catch(handleZipError)
|
||||
|
||||
return arraybuffer
|
||||
}
|
||||
|
||||
const generateCreateSignature = async (
|
||||
@ -505,7 +508,7 @@ export const CreatePage = () => {
|
||||
) => {
|
||||
const signers = users.filter((user) => user.role === UserRole.signer)
|
||||
const viewers = users.filter((user) => user.role === UserRole.viewer)
|
||||
const markConfig = createMarks(fileHashes)
|
||||
const markConfig = createMarkConfig(fileHashes)
|
||||
|
||||
const content: CreateSignatureEventContent = {
|
||||
signers: signers.map((signer) => hexToNpub(signer.pubkey)),
|
||||
@ -545,9 +548,11 @@ export const CreatePage = () => {
|
||||
: viewers.map((viewer) => viewer.pubkey)
|
||||
).filter((receiver) => receiver !== usersPubkey)
|
||||
|
||||
return receivers.map((receiver) =>
|
||||
const promises = receivers.map((receiver) =>
|
||||
sendNotification(receiver, meta)
|
||||
)
|
||||
|
||||
return promises
|
||||
}
|
||||
|
||||
const handleCreate = async () => {
|
||||
@ -694,7 +699,7 @@ export const CreatePage = () => {
|
||||
return (
|
||||
<>
|
||||
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
|
||||
<Container className={styles.container}>
|
||||
<Box className={styles.container}>
|
||||
<TextField
|
||||
label="Title"
|
||||
value={title}
|
||||
@ -783,7 +788,7 @@ export const CreatePage = () => {
|
||||
Create
|
||||
</Button>
|
||||
</Box>
|
||||
</Container>
|
||||
</Box>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
@ -6,8 +6,6 @@
|
||||
color: $text-color;
|
||||
margin-top: 10px;
|
||||
gap: 10px;
|
||||
width: 550px;
|
||||
max-width: 550px;
|
||||
|
||||
.inputBlock {
|
||||
display: flex;
|
||||
|
@ -1,37 +0,0 @@
|
||||
import { CurrentUserMark } from '../../types/mark.ts'
|
||||
import styles from './style.module.scss'
|
||||
import { Box, Button, TextField } from '@mui/material'
|
||||
|
||||
import { MARK_TYPE_TRANSLATION } from '../../utils/const.ts'
|
||||
|
||||
interface MarkFormFieldProps {
|
||||
handleSubmit: (event: any) => void
|
||||
handleChange: (event: any) => void
|
||||
selectedMark: CurrentUserMark
|
||||
selectedMarkValue: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Responsible for rendering a form field connected to a mark and keeping track of its value.
|
||||
*/
|
||||
const MarkFormField = (props: MarkFormFieldProps) => {
|
||||
const { handleSubmit, handleChange, selectedMark, selectedMarkValue } = props;
|
||||
const getSubmitButton = () => selectedMark.isLast ? 'Complete' : 'Next';
|
||||
return (
|
||||
<div className={styles.fixedBottomForm}>
|
||||
<Box component="form" onSubmit={handleSubmit}>
|
||||
<TextField
|
||||
id="mark-value"
|
||||
label={MARK_TYPE_TRANSLATION[selectedMark.mark.type.valueOf()]}
|
||||
value={selectedMarkValue}
|
||||
onChange={handleChange}
|
||||
/>
|
||||
<Button type="submit" variant="contained">
|
||||
{getSubmitButton()}
|
||||
</Button>
|
||||
</Box>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default MarkFormField;
|
@ -16,13 +16,13 @@ import { State } from '../../store/rootReducer'
|
||||
import { CreateSignatureEventContent, Meta, SignedEvent } from '../../types'
|
||||
import {
|
||||
decryptArrayBuffer,
|
||||
encryptArrayBuffer, extractMarksFromSignedMeta,
|
||||
encryptArrayBuffer,
|
||||
extractZipUrlAndEncryptionKey,
|
||||
generateEncryptionKey,
|
||||
generateKeysFile, getFilesWithHashes,
|
||||
generateKeysFile,
|
||||
getHash,
|
||||
hexToNpub,
|
||||
isOnline, loadZip,
|
||||
isOnline,
|
||||
now,
|
||||
npubToHex,
|
||||
parseJson,
|
||||
@ -31,19 +31,9 @@ import {
|
||||
signEventForMetaFile,
|
||||
updateUsersAppData
|
||||
} from '../../utils'
|
||||
import { Container } from '../../components/Container'
|
||||
import { DisplayMeta } from './internal/displayMeta'
|
||||
import styles from './style.module.scss'
|
||||
import { PdfFile } from '../../types/drawing.ts'
|
||||
import { convertToPdfFile } from '../../utils/pdf.ts'
|
||||
import { CurrentUserMark, Mark } from '../../types/mark.ts'
|
||||
import { getLastSignersSig } from '../../utils/sign.ts'
|
||||
import {
|
||||
filterMarksByPubkey,
|
||||
getCurrentUserMarks,
|
||||
isCurrentUserMarksComplete, updateMarks
|
||||
} from '../../utils'
|
||||
import PdfMarking from '../../components/PDFView/PdfMarking.tsx'
|
||||
import { Container } from '../../components/Container'
|
||||
enum SignedStatus {
|
||||
Fully_Signed,
|
||||
User_Is_Next_Signer,
|
||||
@ -69,7 +59,7 @@ export const SignPage = () => {
|
||||
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
|
||||
const [files, setFiles] = useState<{ [filename: string]: PdfFile }>({})
|
||||
const [files, setFiles] = useState<{ [filename: string]: ArrayBuffer }>({})
|
||||
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
|
||||
@ -81,7 +71,6 @@ export const SignPage = () => {
|
||||
|
||||
const [signers, setSigners] = useState<`npub1${string}`[]>([])
|
||||
const [viewers, setViewers] = useState<`npub1${string}`[]>([])
|
||||
const [marks, setMarks] = useState<Mark[] >([])
|
||||
const [creatorFileHashes, setCreatorFileHashes] = useState<{
|
||||
[key: string]: string
|
||||
}>({})
|
||||
@ -100,8 +89,6 @@ export const SignPage = () => {
|
||||
|
||||
const [authUrl, setAuthUrl] = useState<string>()
|
||||
const nostrController = NostrController.getInstance()
|
||||
const [currentUserMarks, setCurrentUserMarks] = useState<CurrentUserMark[]>([]);
|
||||
const [isReadyToSign, setIsReadyToSign] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (signers.length > 0) {
|
||||
@ -192,16 +179,6 @@ export const SignPage = () => {
|
||||
setViewers(createSignatureContent.viewers)
|
||||
setCreatorFileHashes(createSignatureContent.fileHashes)
|
||||
setSubmittedBy(createSignatureEvent.pubkey)
|
||||
setMarks(createSignatureContent.markConfig);
|
||||
|
||||
if (usersPubkey) {
|
||||
const metaMarks = filterMarksByPubkey(createSignatureContent.markConfig, usersPubkey!)
|
||||
const signedMarks = extractMarksFromSignedMeta(meta)
|
||||
const currentUserMarks = getCurrentUserMarks(metaMarks, signedMarks);
|
||||
setCurrentUserMarks(currentUserMarks);
|
||||
// setCurrentUserMark(findNextCurrentUserMark(currentUserMarks) || null)
|
||||
setIsReadyToSign(isCurrentUserMarksComplete(currentUserMarks))
|
||||
}
|
||||
|
||||
setSignedBy(Object.keys(meta.docSignatures) as `npub1${string}`[])
|
||||
}
|
||||
@ -212,7 +189,6 @@ export const SignPage = () => {
|
||||
}, [meta])
|
||||
|
||||
useEffect(() => {
|
||||
// online mode - from create and home page views
|
||||
if (metaInNavState) {
|
||||
const processSigit = async () => {
|
||||
setIsLoading(true)
|
||||
@ -287,13 +263,16 @@ export const SignPage = () => {
|
||||
|
||||
if (!decrypted) return
|
||||
|
||||
const zip = await loadZip(decrypted)
|
||||
if (!zip) {
|
||||
const zip = await JSZip.loadAsync(decrypted).catch((err) => {
|
||||
console.log('err in loading zip file :>> ', err)
|
||||
toast.error(err.message || 'An error occurred in loading zip file.')
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
const files: { [filename: string]: PdfFile } = {}
|
||||
if (!zip) return
|
||||
|
||||
const files: { [filename: string]: ArrayBuffer } = {}
|
||||
const fileHashes: { [key: string]: string | null } = {}
|
||||
const fileNames = Object.values(zip.files).map((entry) => entry.name)
|
||||
|
||||
@ -307,7 +286,7 @@ export const SignPage = () => {
|
||||
)
|
||||
|
||||
if (arrayBuffer) {
|
||||
files[fileName] = await convertToPdfFile(arrayBuffer, fileName);
|
||||
files[fileName] = arrayBuffer
|
||||
|
||||
const hash = await getHash(arrayBuffer)
|
||||
if (hash) {
|
||||
@ -322,11 +301,6 @@ export const SignPage = () => {
|
||||
setCurrentFileHashes(fileHashes)
|
||||
}
|
||||
|
||||
const setUpdatedMarks = (markToUpdate: Mark) => {
|
||||
const updatedMarks = updateMarks(marks, markToUpdate)
|
||||
setMarks(updatedMarks)
|
||||
}
|
||||
|
||||
const parseKeysJson = async (zip: JSZip) => {
|
||||
const keysFileContent = await readContentOfZipEntry(
|
||||
zip,
|
||||
@ -336,19 +310,25 @@ export const SignPage = () => {
|
||||
|
||||
if (!keysFileContent) return null
|
||||
|
||||
return await parseJson<{ sender: string; keys: string[] }>(
|
||||
const parsedJSON = await parseJson<{ sender: string; keys: string[] }>(
|
||||
keysFileContent
|
||||
).catch((err) => {
|
||||
console.log(`Error parsing content of keys.json:`, err)
|
||||
toast.error(err.message || `Error parsing content of keys.json`)
|
||||
return null
|
||||
})
|
||||
|
||||
return parsedJSON
|
||||
}
|
||||
|
||||
const decrypt = async (file: File) => {
|
||||
setLoadingSpinnerDesc('Decrypting file')
|
||||
|
||||
const zip = await loadZip(file);
|
||||
const zip = await JSZip.loadAsync(file).catch((err) => {
|
||||
console.log('err in loading zip file :>> ', err)
|
||||
toast.error(err.message || 'An error occurred in loading zip file.')
|
||||
return null
|
||||
})
|
||||
if (!zip) return
|
||||
|
||||
const parsedKeysJson = await parseKeysJson(zip)
|
||||
@ -419,27 +399,32 @@ export const SignPage = () => {
|
||||
|
||||
setLoadingSpinnerDesc('Parsing zip file')
|
||||
|
||||
const zip = await loadZip(decryptedZipFile)
|
||||
const zip = await JSZip.loadAsync(decryptedZipFile).catch((err) => {
|
||||
console.log('err in loading zip file :>> ', err)
|
||||
toast.error(err.message || 'An error occurred in loading zip file.')
|
||||
return null
|
||||
})
|
||||
|
||||
if (!zip) return
|
||||
|
||||
const files: { [filename: string]: PdfFile } = {}
|
||||
const files: { [filename: string]: ArrayBuffer } = {}
|
||||
const fileHashes: { [key: string]: string | null } = {}
|
||||
const fileNames = Object.values(zip.files)
|
||||
.filter((entry) => entry.name.startsWith('files/') && !entry.dir)
|
||||
.map((entry) => entry.name)
|
||||
.map((entry) => entry.replace(/^files\//, ''))
|
||||
|
||||
// generate hashes for all entries in files folder of zipArchive
|
||||
// these hashes can be used to verify the originality of files
|
||||
for (const fileName of fileNames) {
|
||||
for (let fileName of fileNames) {
|
||||
const arrayBuffer = await readContentOfZipEntry(
|
||||
zip,
|
||||
fileName,
|
||||
'arraybuffer'
|
||||
)
|
||||
|
||||
fileName = fileName.replace(/^files\//, '')
|
||||
if (arrayBuffer) {
|
||||
files[fileName] = await convertToPdfFile(arrayBuffer, fileName);
|
||||
files[fileName] = arrayBuffer
|
||||
|
||||
const hash = await getHash(arrayBuffer)
|
||||
if (hash) {
|
||||
@ -503,10 +488,7 @@ export const SignPage = () => {
|
||||
const prevSig = getPrevSignersSig(hexToNpub(usersPubkey!))
|
||||
if (!prevSig) return
|
||||
|
||||
const marks = getSignerMarksForMeta()
|
||||
if (!marks) return
|
||||
|
||||
const signedEvent = await signEventForMeta({ prevSig, marks })
|
||||
const signedEvent = await signEventForMeta(prevSig)
|
||||
if (!signedEvent) return
|
||||
|
||||
const updatedMeta = updateMetaSignatures(meta, signedEvent)
|
||||
@ -520,19 +502,14 @@ export const SignPage = () => {
|
||||
}
|
||||
|
||||
// Sign the event for the meta file
|
||||
const signEventForMeta = async (signerContent: { prevSig: string, marks: Mark[] }) => {
|
||||
const signEventForMeta = async (prevSig: string) => {
|
||||
return await signEventForMetaFile(
|
||||
JSON.stringify(signerContent),
|
||||
JSON.stringify({ prevSig }),
|
||||
nostrController,
|
||||
setIsLoading
|
||||
)
|
||||
}
|
||||
|
||||
const getSignerMarksForMeta = (): Mark[] | undefined => {
|
||||
if (currentUserMarks.length === 0) return;
|
||||
return currentUserMarks.map(( { mark }: CurrentUserMark) => mark);
|
||||
}
|
||||
|
||||
// Update the meta signatures
|
||||
const updateMetaSignatures = (meta: Meta, signedEvent: SignedEvent): Meta => {
|
||||
const metaCopy = _.cloneDeep(meta)
|
||||
@ -550,7 +527,7 @@ export const SignPage = () => {
|
||||
encryptionKey: string
|
||||
): Promise<File | null> => {
|
||||
// Get the current timestamp in seconds
|
||||
const unixNow = now()
|
||||
const unixNow = Math.floor(Date.now() / 1000)
|
||||
const blob = new Blob([encryptedArrayBuffer])
|
||||
// Create a File object with the Blob data
|
||||
const file = new File([blob], `compressed.sigit`, {
|
||||
@ -600,13 +577,15 @@ export const SignPage = () => {
|
||||
|
||||
if (!arraybuffer) return null
|
||||
|
||||
return new File(
|
||||
const finalZipFile = new File(
|
||||
[new Blob([arraybuffer])],
|
||||
`${unixNow}.sigit.zip`,
|
||||
{
|
||||
type: 'application/zip'
|
||||
}
|
||||
)
|
||||
|
||||
return finalZipFile
|
||||
}
|
||||
|
||||
// Handle errors during zip file generation
|
||||
@ -694,9 +673,7 @@ export const SignPage = () => {
|
||||
setIsLoading(true)
|
||||
setLoadingSpinnerDesc('Signing nostr event')
|
||||
|
||||
if (!meta) return;
|
||||
|
||||
const prevSig = getLastSignersSig(meta, signers)
|
||||
const prevSig = getLastSignersSig()
|
||||
if (!prevSig) return
|
||||
|
||||
const signedEvent = await signEventForMetaFile(
|
||||
@ -746,7 +723,7 @@ export const SignPage = () => {
|
||||
if (!arrayBuffer) return
|
||||
|
||||
const blob = new Blob([arrayBuffer])
|
||||
const unixNow = now()
|
||||
const unixNow = Math.floor(Date.now() / 1000)
|
||||
saveAs(blob, `exported-${unixNow}.sigit.zip`)
|
||||
|
||||
setIsLoading(false)
|
||||
@ -792,7 +769,7 @@ export const SignPage = () => {
|
||||
const finalZipFile = await createFinalZipFile(encryptedArrayBuffer, key)
|
||||
|
||||
if (!finalZipFile) return
|
||||
const unixNow = now()
|
||||
const unixNow = Math.floor(Date.now() / 1000)
|
||||
saveAs(finalZipFile, `exported-${unixNow}.sigit.zip`)
|
||||
}
|
||||
|
||||
@ -829,6 +806,37 @@ export const SignPage = () => {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This function returns the signature of last signer
|
||||
* It will be used in the content of export signature's signedEvent
|
||||
*/
|
||||
const getLastSignersSig = () => {
|
||||
if (!meta) return null
|
||||
|
||||
// if there're no signers then use creator's signature
|
||||
if (signers.length === 0) {
|
||||
try {
|
||||
const createSignatureEvent: Event = JSON.parse(meta.createSignature)
|
||||
return createSignatureEvent.sig
|
||||
} catch (error) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// get last signer
|
||||
const lastSigner = signers[signers.length - 1]
|
||||
|
||||
// get the signature of last signer
|
||||
try {
|
||||
const lastSignatureEvent: Event = JSON.parse(
|
||||
meta.docSignatures[lastSigner]
|
||||
)
|
||||
return lastSignatureEvent.sig
|
||||
} catch (error) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
if (authUrl) {
|
||||
return (
|
||||
<iframe
|
||||
@ -840,13 +848,9 @@ export const SignPage = () => {
|
||||
)
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return <LoadingSpinner desc={loadingSpinnerDesc} />
|
||||
}
|
||||
|
||||
if (isReadyToSign) {
|
||||
return (
|
||||
<>
|
||||
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
|
||||
<Container className={styles.container}>
|
||||
{displayInput && (
|
||||
<>
|
||||
@ -916,13 +920,4 @@ export const SignPage = () => {
|
||||
</Container>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return <PdfMarking
|
||||
files={getFilesWithHashes(files, currentFileHashes)}
|
||||
currentUserMarks={currentUserMarks}
|
||||
setIsReadyToSign={setIsReadyToSign}
|
||||
setCurrentUserMarks={setCurrentUserMarks}
|
||||
setUpdatedMarks={setUpdatedMarks}
|
||||
/>
|
||||
}
|
||||
|
@ -34,11 +34,10 @@ import { UserAvatar } from '../../../components/UserAvatar'
|
||||
import { MetadataController } from '../../../controllers'
|
||||
import { npubToHex, shorten, hexToNpub, parseJson } from '../../../utils'
|
||||
import styles from '../style.module.scss'
|
||||
import { PdfFile } from '../../../types/drawing.ts'
|
||||
|
||||
type DisplayMetaProps = {
|
||||
meta: Meta
|
||||
files: { [filename: string]: PdfFile }
|
||||
files: { [filename: string]: ArrayBuffer }
|
||||
submittedBy: string
|
||||
signers: `npub1${string}`[]
|
||||
viewers: `npub1${string}`[]
|
||||
@ -144,7 +143,7 @@ export const DisplayMeta = ({
|
||||
}, [users, submittedBy])
|
||||
|
||||
const downloadFile = async (filename: string) => {
|
||||
const arrayBuffer = await files[filename].file.arrayBuffer()
|
||||
const arrayBuffer = files[filename]
|
||||
if (!arrayBuffer) return
|
||||
|
||||
const blob = new Blob([arrayBuffer])
|
||||
|
@ -2,8 +2,6 @@
|
||||
|
||||
.container {
|
||||
color: $text-color;
|
||||
width: 550px;
|
||||
max-width: 550px;
|
||||
|
||||
.inputBlock {
|
||||
position: relative;
|
||||
@ -49,40 +47,4 @@
|
||||
@extend .user;
|
||||
}
|
||||
}
|
||||
|
||||
.fixedBottomForm {
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
width: 100%;
|
||||
max-width: 500px;
|
||||
height: 100px;
|
||||
border-top: 1px solid #ccc;
|
||||
box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
|
||||
padding: 10px 20px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
//z-index: 200;
|
||||
}
|
||||
|
||||
.fixedBottomForm input[type="text"] {
|
||||
width: 80%;
|
||||
padding: 10px;
|
||||
font-size: 16px;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.fixedBottomForm button {
|
||||
background-color: #3f3d56;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 10px 20px;
|
||||
font-size: 16px;
|
||||
margin-left: 10px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
@ -15,7 +15,7 @@ import { useEffect, useState } from 'react'
|
||||
import { toast } from 'react-toastify'
|
||||
import { LoadingSpinner } from '../../components/LoadingSpinner'
|
||||
import { UserAvatar } from '../../components/UserAvatar'
|
||||
import { MetadataController, NostrController } from '../../controllers'
|
||||
import { MetadataController } from '../../controllers'
|
||||
import {
|
||||
CreateSignatureEventContent,
|
||||
Meta,
|
||||
@ -23,30 +23,19 @@ import {
|
||||
SignedEventContent
|
||||
} from '../../types'
|
||||
import {
|
||||
decryptArrayBuffer, extractMarksFromSignedMeta,
|
||||
decryptArrayBuffer,
|
||||
extractZipUrlAndEncryptionKey,
|
||||
getHash,
|
||||
hexToNpub, now,
|
||||
hexToNpub,
|
||||
npubToHex,
|
||||
parseJson,
|
||||
readContentOfZipEntry,
|
||||
shorten, signEventForMetaFile
|
||||
shorten
|
||||
} from '../../utils'
|
||||
import styles from './style.module.scss'
|
||||
import { Cancel, CheckCircle } from '@mui/icons-material'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import axios from 'axios'
|
||||
import { PdfFile } from '../../types/drawing.ts'
|
||||
import {
|
||||
addMarks,
|
||||
convertToPdfBlob,
|
||||
convertToPdfFile,
|
||||
groupMarksByPage,
|
||||
} from '../../utils/pdf.ts'
|
||||
import { State } from '../../store/rootReducer.ts'
|
||||
import { useSelector } from 'react-redux'
|
||||
import { getLastSignersSig } from '../../utils/sign.ts'
|
||||
import { saveAs } from 'file-saver'
|
||||
import { Container } from '../../components/Container'
|
||||
|
||||
export const VerifyPage = () => {
|
||||
@ -78,13 +67,10 @@ export const VerifyPage = () => {
|
||||
const [currentFileHashes, setCurrentFileHashes] = useState<{
|
||||
[key: string]: string | null
|
||||
}>({})
|
||||
const [files, setFiles] = useState<{ [filename: string]: PdfFile}>({})
|
||||
|
||||
const [metadata, setMetadata] = useState<{ [key: string]: ProfileMetadata }>(
|
||||
{}
|
||||
)
|
||||
const usersPubkey = useSelector((state: State) => state.auth.usersPubkey)
|
||||
const nostrController = NostrController.getInstance()
|
||||
|
||||
useEffect(() => {
|
||||
if (uploadedZip) {
|
||||
@ -139,7 +125,6 @@ export const VerifyPage = () => {
|
||||
|
||||
if (!zip) return
|
||||
|
||||
const files: { [filename: string]: PdfFile } = {}
|
||||
const fileHashes: { [key: string]: string | null } = {}
|
||||
const fileNames = Object.values(zip.files).map(
|
||||
(entry) => entry.name
|
||||
@ -155,7 +140,6 @@ export const VerifyPage = () => {
|
||||
)
|
||||
|
||||
if (arrayBuffer) {
|
||||
files[fileName] = await convertToPdfFile(arrayBuffer, fileName!)
|
||||
const hash = await getHash(arrayBuffer)
|
||||
|
||||
if (hash) {
|
||||
@ -167,8 +151,6 @@ export const VerifyPage = () => {
|
||||
}
|
||||
|
||||
setCurrentFileHashes(fileHashes)
|
||||
setFiles(files)
|
||||
|
||||
|
||||
setSigners(createSignatureContent.signers)
|
||||
setViewers(createSignatureContent.viewers)
|
||||
@ -177,8 +159,6 @@ export const VerifyPage = () => {
|
||||
|
||||
setMeta(metaInNavState)
|
||||
setIsLoading(false)
|
||||
|
||||
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
@ -380,73 +360,6 @@ export const VerifyPage = () => {
|
||||
}
|
||||
}
|
||||
|
||||
const handleExport = async () => {
|
||||
if (Object.entries(files).length === 0 ||!meta ||!usersPubkey) return;
|
||||
|
||||
const usersNpub = hexToNpub(usersPubkey)
|
||||
if (
|
||||
!signers.includes(usersNpub) &&
|
||||
!viewers.includes(usersNpub) &&
|
||||
submittedBy !== usersNpub
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
setLoadingSpinnerDesc('Signing nostr event')
|
||||
|
||||
if (!meta) return;
|
||||
|
||||
const prevSig = getLastSignersSig(meta, signers)
|
||||
if (!prevSig) return;
|
||||
|
||||
const signedEvent = await signEventForMetaFile(
|
||||
JSON.stringify({ prevSig }),
|
||||
nostrController,
|
||||
setIsLoading
|
||||
)
|
||||
|
||||
if (!signedEvent) return;
|
||||
|
||||
const exportSignature = JSON.stringify(signedEvent, null, 2)
|
||||
const updatedMeta = {...meta, exportSignature }
|
||||
const stringifiedMeta = JSON.stringify(updatedMeta, null, 2)
|
||||
|
||||
const zip = new JSZip()
|
||||
zip.file('meta.json', stringifiedMeta)
|
||||
|
||||
const marks = extractMarksFromSignedMeta(updatedMeta)
|
||||
const marksByPage = groupMarksByPage(marks)
|
||||
|
||||
for (const [fileName, pdf] of Object.entries(files)) {
|
||||
const pages = await addMarks(pdf.file, marksByPage)
|
||||
const blob = await convertToPdfBlob(pages)
|
||||
zip.file(`/files/${fileName}`, blob)
|
||||
}
|
||||
|
||||
const arrayBuffer = await zip
|
||||
.generateAsync({
|
||||
type: 'arraybuffer',
|
||||
compression: 'DEFLATE',
|
||||
compressionOptions: {
|
||||
level: 6
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log('err in zip:>> ', err)
|
||||
setIsLoading(false)
|
||||
toast.error(err.message || 'Error occurred in generating zip file')
|
||||
return null
|
||||
})
|
||||
|
||||
if (!arrayBuffer) return
|
||||
|
||||
const blob = new Blob([arrayBuffer])
|
||||
saveAs(blob, `exported-${now()}.sigit.zip`)
|
||||
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
const displayUser = (pubkey: string, verifySignature = false) => {
|
||||
const profile = metadata[pubkey]
|
||||
|
||||
@ -609,11 +522,6 @@ export const VerifyPage = () => {
|
||||
Exported By
|
||||
</Typography>
|
||||
{displayExportedBy()}
|
||||
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
|
||||
<Button onClick={handleExport} variant="contained">
|
||||
Export Sigit
|
||||
</Button>
|
||||
</Box>
|
||||
</ListItem>
|
||||
|
||||
{signers.length > 0 && (
|
||||
|
@ -1,4 +1,4 @@
|
||||
import { Mark } from './mark'
|
||||
import { MarkConfig } from "./mark"
|
||||
import { Keys } from '../store/auth/types'
|
||||
|
||||
export enum UserRole {
|
||||
@ -23,14 +23,13 @@ export interface CreateSignatureEventContent {
|
||||
signers: `npub1${string}`[]
|
||||
viewers: `npub1${string}`[]
|
||||
fileHashes: { [key: string]: string }
|
||||
markConfig: Mark[]
|
||||
markConfig: MarkConfig
|
||||
title: string
|
||||
zipUrl: string
|
||||
}
|
||||
|
||||
export interface SignedEventContent {
|
||||
prevSig: string
|
||||
marks: Mark[]
|
||||
}
|
||||
|
||||
export interface Sigit {
|
||||
|
@ -1,26 +1,43 @@
|
||||
import { MarkType } from "./drawing";
|
||||
|
||||
export interface CurrentUserMark {
|
||||
mark: Mark
|
||||
isLast: boolean
|
||||
isCompleted: boolean
|
||||
}
|
||||
|
||||
export interface Mark {
|
||||
id: number;
|
||||
npub: string;
|
||||
pdfFileHash: string;
|
||||
type: MarkType;
|
||||
location: MarkLocation;
|
||||
value?: string;
|
||||
/**
|
||||
* @key png (pdf page) file hash
|
||||
*/
|
||||
[key: string]: MarkConfigDetails[]
|
||||
}
|
||||
|
||||
export interface MarkLocation {
|
||||
top: number;
|
||||
left: number;
|
||||
height: number;
|
||||
width: number;
|
||||
page: number;
|
||||
export interface MarkConfig {
|
||||
/**
|
||||
* @key user npub
|
||||
*/
|
||||
[key: string]: User
|
||||
}
|
||||
|
||||
export interface User {
|
||||
/**
|
||||
* @key png (pdf page) file hash
|
||||
*/
|
||||
[key: string]: MarkConfigDetails[]
|
||||
}
|
||||
|
||||
export interface MarkDetails {
|
||||
/**
|
||||
* @key coords in format X:10;Y:50
|
||||
*/
|
||||
[key: string]: MarkValue
|
||||
}
|
||||
|
||||
export interface MarkValue {
|
||||
value: string
|
||||
}
|
||||
|
||||
export interface MarkConfigDetails {
|
||||
markType: MarkType;
|
||||
/**
|
||||
* Coordinates in format: X:10;Y:50
|
||||
*/
|
||||
markLocation: string;
|
||||
}
|
||||
|
||||
// Creator Meta Object Example
|
||||
|
@ -1,4 +1,4 @@
|
||||
export interface OutputByType {
|
||||
export interface OutputByType {
|
||||
base64: string
|
||||
string: string
|
||||
text: string
|
||||
@ -10,17 +10,4 @@
|
||||
nodebuffer: Buffer
|
||||
}
|
||||
|
||||
interface InputByType {
|
||||
base64: string;
|
||||
string: string;
|
||||
text: string;
|
||||
binarystring: string;
|
||||
array: number[];
|
||||
uint8array: Uint8Array;
|
||||
arraybuffer: ArrayBuffer;
|
||||
blob: Blob;
|
||||
stream: NodeJS.ReadableStream;
|
||||
}
|
||||
|
||||
export type OutputType = keyof OutputByType
|
||||
export type InputFileFormat = InputByType[keyof InputByType] | Promise<InputByType[keyof InputByType]>;
|
@ -1,6 +0,0 @@
|
||||
import { MarkType } from '../types/drawing.ts'
|
||||
|
||||
export const EMPTY: string = ''
|
||||
export const MARK_TYPE_TRANSLATION: { [key: string]: string } = {
|
||||
[MarkType.FULLNAME.valueOf()]: 'Full Name'
|
||||
}
|
@ -6,4 +6,3 @@ export * from './nostr'
|
||||
export * from './string'
|
||||
export * from './zip'
|
||||
export * from './utils'
|
||||
export * from './mark'
|
||||
|
@ -1,98 +0,0 @@
|
||||
import { CurrentUserMark, Mark } from '../types/mark.ts'
|
||||
import { hexToNpub } from './nostr.ts'
|
||||
import { Meta, SignedEventContent } from '../types'
|
||||
import { Event } from 'nostr-tools'
|
||||
|
||||
/**
|
||||
* Takes in an array of Marks already filtered by User.
|
||||
* Returns an array of CurrentUserMarks with correct values mix-and-matched.
|
||||
* @param marks - default Marks extracted from Meta
|
||||
* @param signedMetaMarks - signed user Marks extracted from DocSignatures
|
||||
*/
|
||||
const getCurrentUserMarks = (marks: Mark[], signedMetaMarks: Mark[]): CurrentUserMark[] => {
|
||||
return marks.map((mark, index, arr) => {
|
||||
const signedMark = signedMetaMarks.find((m) => m.id === mark.id);
|
||||
if (signedMark && !!signedMark.value) {
|
||||
mark.value = signedMark.value
|
||||
}
|
||||
return {
|
||||
mark,
|
||||
isLast: isLast(index, arr),
|
||||
isCompleted: !!mark.value
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns next incomplete CurrentUserMark if there is one
|
||||
* @param usersMarks
|
||||
*/
|
||||
const findNextCurrentUserMark = (usersMarks: CurrentUserMark[]): CurrentUserMark | undefined => {
|
||||
return usersMarks.find((mark) => !mark.isCompleted);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns Marks that are assigned to a specific user
|
||||
* @param marks
|
||||
* @param pubkey
|
||||
*/
|
||||
const filterMarksByPubkey = (marks: Mark[], pubkey: string): Mark[] => {
|
||||
return marks.filter(mark => mark.npub === hexToNpub(pubkey))
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes Signed Doc Signatures part of Meta and extracts
|
||||
* all Marks into one flar array, regardless of the user.
|
||||
* @param meta
|
||||
*/
|
||||
const extractMarksFromSignedMeta = (meta: Meta): Mark[] => {
|
||||
return Object.values(meta.docSignatures)
|
||||
.map((val: string) => JSON.parse(val as string))
|
||||
.map((val: Event) => JSON.parse(val.content))
|
||||
.flatMap((val: SignedEventContent) => val.marks)
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the CurrentUserMarks array that every element in that array has been
|
||||
* marked as complete.
|
||||
* @param currentUserMarks
|
||||
*/
|
||||
const isCurrentUserMarksComplete = (currentUserMarks: CurrentUserMark[]): boolean => {
|
||||
return currentUserMarks.every((mark) => mark.isCompleted)
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts an updated mark into an existing array of marks. Returns a copy of the
|
||||
* existing array with a new value inserted
|
||||
* @param marks
|
||||
* @param markToUpdate
|
||||
*/
|
||||
const updateMarks = (marks: Mark[], markToUpdate: Mark): Mark[] => {
|
||||
const indexToUpdate = marks.findIndex(mark => mark.id === markToUpdate.id);
|
||||
return [
|
||||
...marks.slice(0, indexToUpdate),
|
||||
markToUpdate,
|
||||
...marks.slice(indexToUpdate + 1)
|
||||
]
|
||||
}
|
||||
|
||||
const updateCurrentUserMarks = (currentUserMarks: CurrentUserMark[], markToUpdate: CurrentUserMark): CurrentUserMark[] => {
|
||||
const indexToUpdate = currentUserMarks.findIndex((m) => m.mark.id === markToUpdate.mark.id)
|
||||
return [
|
||||
...currentUserMarks.slice(0, indexToUpdate),
|
||||
markToUpdate,
|
||||
...currentUserMarks.slice(indexToUpdate + 1)
|
||||
]
|
||||
}
|
||||
|
||||
const isLast = <T>(index: number, arr: T[]) => (index === (arr.length -1))
|
||||
|
||||
export {
|
||||
getCurrentUserMarks,
|
||||
filterMarksByPubkey,
|
||||
extractMarksFromSignedMeta,
|
||||
isCurrentUserMarksComplete,
|
||||
findNextCurrentUserMark,
|
||||
updateMarks,
|
||||
updateCurrentUserMarks,
|
||||
}
|
@ -83,12 +83,14 @@ export const signEventForMetaFile = async (
|
||||
}
|
||||
|
||||
// Sign the event
|
||||
return await nostrController.signEvent(event).catch((err) => {
|
||||
const signedEvent = await nostrController.signEvent(event).catch((err) => {
|
||||
console.error(err)
|
||||
toast.error(err.message || 'Error occurred in signing nostr event')
|
||||
setIsLoading(false) // Set loading state to false
|
||||
return null
|
||||
})
|
||||
|
||||
return signedEvent // Return the signed event
|
||||
}
|
||||
|
||||
/**
|
||||
|
256
src/utils/pdf.ts
256
src/utils/pdf.ts
@ -1,256 +0,0 @@
|
||||
import { PdfFile, PdfPage } from '../types/drawing.ts'
|
||||
import * as PDFJS from 'pdfjs-dist'
|
||||
import { PDFDocument } from 'pdf-lib'
|
||||
import { Mark } from '../types/mark.ts'
|
||||
|
||||
PDFJS.GlobalWorkerOptions.workerSrc = 'node_modules/pdfjs-dist/build/pdf.worker.mjs';
|
||||
|
||||
/**
|
||||
* Scale between the PDF page's natural size and rendered size
|
||||
* @constant {number}
|
||||
*/
|
||||
const SCALE: number = 3;
|
||||
/**
|
||||
* Defined font size used when generating a PDF. Currently it is difficult to fully
|
||||
* correlate font size used at the time of filling in / drawing on the PDF
|
||||
* because it is dynamically rendered, and the final size.
|
||||
* This should be fixed going forward.
|
||||
* Switching to PDF-Lib will most likely make this problem redundant.
|
||||
*/
|
||||
const FONT_SIZE: number = 40;
|
||||
/**
|
||||
* Current font type used when generating a PDF.
|
||||
*/
|
||||
const FONT_TYPE: string = 'Arial';
|
||||
|
||||
/**
|
||||
* Converts a PDF ArrayBuffer to a generic PDF File
|
||||
* @param arrayBuffer of a PDF
|
||||
* @param fileName identifier of the pdf file
|
||||
*/
|
||||
const toFile = (arrayBuffer: ArrayBuffer, fileName: string) : File => {
|
||||
const blob = new Blob([arrayBuffer], { type: "application/pdf" });
|
||||
return new File([blob], fileName, { type: "application/pdf" });
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a generic PDF File to Sigit's internal Pdf File type
|
||||
* @param {File} file
|
||||
* @return {PdfFile} Sigit's internal PDF File type
|
||||
*/
|
||||
const toPdfFile = async (file: File): Promise<PdfFile> => {
|
||||
const data = await readPdf(file)
|
||||
const pages = await pdfToImages(data)
|
||||
return { file, pages, expanded: false }
|
||||
}
|
||||
/**
|
||||
* Transforms an array of generic PDF Files into an array of Sigit's
|
||||
* internal representation of Pdf Files
|
||||
* @param selectedFiles - an array of generic PDF Files
|
||||
* @return PdfFile[] - an array of Sigit's internal Pdf File type
|
||||
*/
|
||||
const toPdfFiles = async (selectedFiles: File[]): Promise<PdfFile[]> => {
|
||||
return Promise.all(selectedFiles
|
||||
.filter(isPdf)
|
||||
.map(toPdfFile));
|
||||
}
|
||||
|
||||
/**
|
||||
* A utility that transforms a drawing coordinate number into a CSS-compatible string
|
||||
* @param coordinate
|
||||
*/
|
||||
const inPx = (coordinate: number): string => `${coordinate}px`;
|
||||
|
||||
/**
|
||||
* A utility that checks if a given file is of the pdf type
|
||||
* @param file
|
||||
*/
|
||||
const isPdf = (file: File) => file.type.toLowerCase().includes('pdf');
|
||||
|
||||
/**
|
||||
* Reads the pdf file binaries
|
||||
*/
|
||||
const readPdf = (file: File): Promise<string> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = (e: any) => {
|
||||
const data = e.target.result
|
||||
|
||||
resolve(data)
|
||||
};
|
||||
|
||||
reader.onerror = (err) => {
|
||||
console.error('err', err)
|
||||
reject(err)
|
||||
};
|
||||
|
||||
reader.readAsDataURL(file);
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts pdf to the images
|
||||
* @param data pdf file bytes
|
||||
*/
|
||||
const pdfToImages = async (data: any): Promise<PdfPage[]> => {
|
||||
const images: string[] = [];
|
||||
const pdf = await PDFJS.getDocument(data).promise;
|
||||
const canvas = document.createElement("canvas");
|
||||
|
||||
for (let i = 0; i < pdf.numPages; i++) {
|
||||
const page = await pdf.getPage(i + 1);
|
||||
const viewport = page.getViewport({ scale: SCALE });
|
||||
const context = canvas.getContext("2d");
|
||||
canvas.height = viewport.height;
|
||||
canvas.width = viewport.width;
|
||||
await page.render({ canvasContext: context!, viewport: viewport }).promise;
|
||||
images.push(canvas.toDataURL());
|
||||
}
|
||||
|
||||
return Promise.resolve(images.map((image) => {
|
||||
return {
|
||||
image,
|
||||
drawnFields: []
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes in individual pdf file and an object with Marks grouped by Page number
|
||||
* Returns an array of encoded images where each image is a representation
|
||||
* of a PDF page with completed and signed marks from all users
|
||||
*/
|
||||
const addMarks = async (file: File, marksPerPage: {[key: string]: Mark[]}) => {
|
||||
const p = await readPdf(file);
|
||||
const pdf = await PDFJS.getDocument(p).promise;
|
||||
const canvas = document.createElement("canvas");
|
||||
|
||||
const images: string[] = [];
|
||||
|
||||
for (let i = 0; i< pdf.numPages; i++) {
|
||||
const page = await pdf.getPage(i+1)
|
||||
const viewport = page.getViewport({ scale: SCALE });
|
||||
const context = canvas.getContext("2d");
|
||||
canvas.height = viewport.height;
|
||||
canvas.width = viewport.width;
|
||||
await page.render({ canvasContext: context!, viewport: viewport }).promise;
|
||||
|
||||
marksPerPage[i].forEach(mark => draw(mark, context!))
|
||||
|
||||
images.push(canvas.toDataURL());
|
||||
}
|
||||
|
||||
return Promise.resolve(images);
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility to scale mark in line with the PDF-to-PNG scale
|
||||
*/
|
||||
const scaleMark = (mark: Mark): Mark => {
|
||||
const { location } = mark;
|
||||
return {
|
||||
...mark,
|
||||
location: {
|
||||
...location,
|
||||
width: location.width * SCALE,
|
||||
height: location.height * SCALE,
|
||||
left: location.left * SCALE,
|
||||
top: location.top * SCALE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility to check if a Mark has value
|
||||
* @param mark
|
||||
*/
|
||||
const hasValue = (mark: Mark): boolean => !!mark.value;
|
||||
|
||||
/**
|
||||
* Draws a Mark on a Canvas representation of a PDF Page
|
||||
* @param mark to be drawn
|
||||
* @param ctx a Canvas representation of a specific PDF Page
|
||||
*/
|
||||
const draw = (mark: Mark, ctx: CanvasRenderingContext2D) => {
|
||||
const { location } = mark;
|
||||
|
||||
ctx!.font = FONT_SIZE + 'px ' + FONT_TYPE;
|
||||
ctx!.fillStyle = 'black';
|
||||
const textMetrics = ctx!.measureText(mark.value!);
|
||||
const textX = location.left + (location.width - textMetrics.width) / 2;
|
||||
const textY = location.top + (location.height + parseInt(ctx!.font)) / 2;
|
||||
ctx!.fillText(mark.value!, textX, textY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes an array of encoded PDF pages and returns a blob that is a complete PDF file
|
||||
* @param markedPdfPages
|
||||
*/
|
||||
const convertToPdfBlob = async (markedPdfPages: string[]): Promise<Blob> => {
|
||||
const pdfDoc = await PDFDocument.create();
|
||||
|
||||
for (const page of markedPdfPages) {
|
||||
const pngImage = await pdfDoc.embedPng(page)
|
||||
const p = pdfDoc.addPage([pngImage.width, pngImage.height])
|
||||
p.drawImage(pngImage, {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: pngImage.width,
|
||||
height: pngImage.height
|
||||
})
|
||||
}
|
||||
|
||||
const pdfBytes = await pdfDoc.save()
|
||||
return new Blob([pdfBytes], { type: 'application/pdf' })
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes an ArrayBuffer of a PDF file and converts to Sigit's Internal Pdf File type
|
||||
* @param arrayBuffer
|
||||
* @param fileName
|
||||
*/
|
||||
const convertToPdfFile = async (arrayBuffer: ArrayBuffer, fileName: string): Promise<PdfFile> => {
|
||||
const file = toFile(arrayBuffer, fileName);
|
||||
return toPdfFile(file);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param marks - an array of Marks
|
||||
* @function hasValue removes any Mark without a property
|
||||
* @function scaleMark scales remaining marks in line with SCALE
|
||||
* @function byPage groups remaining Marks by their page marks.location.page
|
||||
*/
|
||||
const groupMarksByPage = (marks: Mark[]) => {
|
||||
return marks
|
||||
.filter(hasValue)
|
||||
.map(scaleMark)
|
||||
.reduce<{[key: number]: Mark[]}>(byPage, {})
|
||||
}
|
||||
|
||||
/**
|
||||
* A reducer callback that transforms an array of marks into an object grouped by the page number
|
||||
* Can be replaced by Object.groupBy https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/groupBy
|
||||
* when it is implemented in TypeScript
|
||||
* Implementation is standard from the Array.prototype.reduce documentation
|
||||
* @param obj - accumulator in the reducer callback
|
||||
* @param mark - current value, i.e. Mark being examined
|
||||
*/
|
||||
const byPage = (obj: { [key: number]: Mark[]}, mark: Mark) => {
|
||||
const key = mark.location.page;
|
||||
const curGroup = obj[key] ?? [];
|
||||
return { ...obj, [key]: [...curGroup, mark]
|
||||
}
|
||||
}
|
||||
|
||||
export {
|
||||
toFile,
|
||||
toPdfFile,
|
||||
toPdfFiles,
|
||||
inPx,
|
||||
convertToPdfFile,
|
||||
addMarks,
|
||||
convertToPdfBlob,
|
||||
groupMarksByPage,
|
||||
}
|
@ -1,33 +0,0 @@
|
||||
import { Event } from 'nostr-tools'
|
||||
import { Meta } from '../types'
|
||||
|
||||
/**
|
||||
* This function returns the signature of last signer
|
||||
* It will be used in the content of export signature's signedEvent
|
||||
*/
|
||||
const getLastSignersSig = (meta: Meta, signers: `npub1${string}`[]): string | null => {
|
||||
// if there're no signers then use creator's signature
|
||||
if (signers.length === 0) {
|
||||
try {
|
||||
const createSignatureEvent: Event = JSON.parse(meta.createSignature)
|
||||
return createSignatureEvent.sig
|
||||
} catch (error) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// get last signer
|
||||
const lastSigner = signers[signers.length - 1]
|
||||
|
||||
// get the signature of last signer
|
||||
try {
|
||||
const lastSignatureEvent: Event = JSON.parse(
|
||||
meta.docSignatures[lastSigner]
|
||||
)
|
||||
return lastSignatureEvent.sig
|
||||
} catch (error) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export { getLastSignersSig }
|
@ -1,5 +1,3 @@
|
||||
import { PdfFile } from '../types/drawing.ts'
|
||||
|
||||
export const compareObjects = (
|
||||
obj1: object | null | undefined,
|
||||
obj2: object | null | undefined
|
||||
@ -66,17 +64,3 @@ export const timeout = (ms: number = 60000) => {
|
||||
}, ms) // Timeout duration in milliseconds
|
||||
})
|
||||
}
|
||||
/**
|
||||
* Creates a flat array where each object contains all required information about a Pdf File,
|
||||
* including its name, hash, and content
|
||||
* @param files
|
||||
* @param fileHashes
|
||||
*/
|
||||
export const getFilesWithHashes = (
|
||||
files: { [filename: string ]: PdfFile },
|
||||
fileHashes: { [key: string]: string | null }
|
||||
) => {
|
||||
return Object.entries(files).map(([filename, pdfFile]) => {
|
||||
return { pdfFile, filename, hash: fileHashes[filename] }
|
||||
})
|
||||
}
|
||||
|
@ -1,6 +1,6 @@
|
||||
import JSZip from 'jszip'
|
||||
import { toast } from 'react-toastify'
|
||||
import { InputFileFormat, OutputByType, OutputType } from '../types'
|
||||
import { OutputByType, OutputType } from '../types'
|
||||
|
||||
/**
|
||||
* Read the content of a file within a zip archive.
|
||||
@ -9,7 +9,7 @@ import { InputFileFormat, OutputByType, OutputType } from '../types'
|
||||
* @param outputType The type of output to return (e.g., 'string', 'arraybuffer', 'uint8array', etc.).
|
||||
* @returns A Promise resolving to the content of the file, or null if an error occurs.
|
||||
*/
|
||||
const readContentOfZipEntry = async <T extends OutputType>(
|
||||
export const readContentOfZipEntry = async <T extends OutputType>(
|
||||
zip: JSZip,
|
||||
filePath: string,
|
||||
outputType: T
|
||||
@ -22,9 +22,8 @@ const readContentOfZipEntry = async <T extends OutputType>(
|
||||
return null
|
||||
}
|
||||
|
||||
// Read and return the content of the zip entry asynchronously
|
||||
// or null if an error has occurred
|
||||
return await zipEntry.async(outputType).catch((err) => {
|
||||
// Read the content of the zip entry asynchronously
|
||||
const fileContent = await zipEntry.async(outputType).catch((err) => {
|
||||
// Handle any errors that occur during the read operation
|
||||
console.log(`Error reading content of ${filePath}:`, err)
|
||||
toast.error(
|
||||
@ -32,21 +31,7 @@ const readContentOfZipEntry = async <T extends OutputType>(
|
||||
)
|
||||
return null
|
||||
})
|
||||
|
||||
// Return the file content or null if an error occurred
|
||||
return fileContent
|
||||
}
|
||||
|
||||
const loadZip = async (data: InputFileFormat): Promise<JSZip | null> => {
|
||||
try {
|
||||
return await JSZip.loadAsync(data);
|
||||
} catch (err: any) {
|
||||
console.log('err in loading zip file :>> ', err)
|
||||
toast.error(err.message || 'An error occurred in loading zip file.')
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export {
|
||||
readContentOfZipEntry,
|
||||
loadZip
|
||||
}
|
||||
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user