chore(git): merge branch 'staging' into issue-121
This commit is contained in:
commit
276ad23e2c
@ -6,7 +6,7 @@ module.exports = {
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:react-hooks/recommended'
|
||||
],
|
||||
ignorePatterns: ['dist', '.eslintrc.cjs'],
|
||||
ignorePatterns: ['dist', '.eslintrc.cjs', 'licenseChecker.cjs'],
|
||||
parser: '@typescript-eslint/parser',
|
||||
plugins: ['react-refresh'],
|
||||
rules: {
|
||||
|
19
.git-hooks/commit-msg
Executable file
19
.git-hooks/commit-msg
Executable file
@ -0,0 +1,19 @@
|
||||
#!/bin/sh
|
||||
# Get the commit message (the parameter we're given is just the path to the
|
||||
# temporary file which holds the message).
|
||||
commit_message=$(cat "$1")
|
||||
|
||||
if (echo "$commit_message" | grep -Eq "^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\([a-z0-9 \-]+\))?!?: .+$") then
|
||||
tput setaf 2;
|
||||
echo -e "${GREEN} ✔ Commit message meets Conventional Commit standards"
|
||||
tput sgr0;
|
||||
exit 0
|
||||
fi
|
||||
|
||||
tput setaf 1;
|
||||
echo -e "${RED}❌ Commit message does not meet the Conventional Commit standard!"
|
||||
tput sgr0;
|
||||
echo "An example of a valid message is:"
|
||||
echo " feat(login): add the 'remember me' button"
|
||||
echo "ℹ More details at: https://www.conventionalcommits.org/en/v1.0.0/#summary"
|
||||
exit 1
|
13
.git-hooks/pre-commit
Executable file
13
.git-hooks/pre-commit
Executable file
@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
|
||||
# Avoid commits to the master branch
|
||||
BRANCH=`git rev-parse --abbrev-ref HEAD`
|
||||
REGEX="^(master|main|staging|development)$"
|
||||
|
||||
if [[ "$BRANCH" =~ $REGEX ]]; then
|
||||
echo "You are on branch $BRANCH. Are you sure you want to commit to this branch?"
|
||||
echo "If so, commit with -n to bypass the pre-commit hook."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
npm run lint-staged
|
@ -17,9 +17,21 @@ jobs:
|
||||
with:
|
||||
node-version: 18
|
||||
|
||||
- name: Audit
|
||||
run: npm audit
|
||||
|
||||
- name: Install Dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: License check
|
||||
run: npm run license-checker
|
||||
|
||||
- name: Lint check
|
||||
run: npm run lint
|
||||
|
||||
- name: Formatter check
|
||||
run: npm run formatter:check
|
||||
|
||||
- name: Create .env File
|
||||
run: echo "VITE_MOST_POPULAR_RELAYS=${{ vars.VITE_MOST_POPULAR_RELAYS }}" > .env
|
||||
|
||||
|
34
.gitea/workflows/staging-pull-request.yaml
Normal file
34
.gitea/workflows/staging-pull-request.yaml
Normal file
@ -0,0 +1,34 @@
|
||||
name: Open PR on Staging
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, edited, synchronize]
|
||||
branches:
|
||||
- staging
|
||||
|
||||
jobs:
|
||||
audit_and_check:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: 18
|
||||
|
||||
- name: Audit
|
||||
run: npm audit
|
||||
|
||||
- name: Install Dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: License check
|
||||
run: npm run license-checker
|
||||
|
||||
- name: Lint check
|
||||
run: npm run lint
|
||||
|
||||
- name: Formatter check
|
||||
run: npm run formatter:check
|
28
licenseChecker.cjs
Normal file
28
licenseChecker.cjs
Normal file
@ -0,0 +1,28 @@
|
||||
const process = require('node:process')
|
||||
const licenseChecker = require('license-checker')
|
||||
|
||||
const check = (cwd) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
licenseChecker.init(
|
||||
{
|
||||
production: true,
|
||||
start: cwd,
|
||||
excludePrivatePackages: true,
|
||||
onlyAllow:
|
||||
'AFLv2.1;Apache 2.0;Apache-2.0;Apache*;Artistic-2.0;0BSD;BSD*;BSD-2-Clause;BSD-3-Clause;BSD 3-Clause;CC0-1.0;CC-BY-3.0;CC-BY-4.0;ISC;MIT;MPL-2.0;ODC-By-1.0;Python-2.0;Unlicense;',
|
||||
excludePackages: ''
|
||||
},
|
||||
(error, json) => {
|
||||
if (error) {
|
||||
reject(error)
|
||||
} else {
|
||||
resolve(json)
|
||||
}
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
check(process.cwd(), true)
|
||||
.then(() => console.log('All packages are licensed properly'))
|
||||
.catch((err) => console.log('license checker err', err))
|
1670
package-lock.json
generated
1670
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
20
package.json
20
package.json
@ -7,11 +7,16 @@
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
|
||||
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 32",
|
||||
"lint:fix": "eslint . --fix --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
|
||||
"lint:staged": "eslint --fix --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
|
||||
"formatter:check": "prettier --check \"src/**/*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}\"",
|
||||
"formatter:fix": "prettier --write \"src/**/*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}\"",
|
||||
"preview": "vite preview"
|
||||
"formatter:staged": "prettier --write --ignore-unknown",
|
||||
"preview": "vite preview",
|
||||
"preinstall": "git config core.hooksPath .git-hooks",
|
||||
"license-checker": "node licenseChecker.cjs",
|
||||
"lint-staged": "lint-staged"
|
||||
},
|
||||
"dependencies": {
|
||||
"@emotion/react": "11.11.4",
|
||||
@ -36,6 +41,8 @@
|
||||
"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",
|
||||
"react-dnd-html5-backend": "16.0.1",
|
||||
@ -50,6 +57,7 @@
|
||||
"@types/crypto-js": "^4.2.2",
|
||||
"@types/file-saver": "2.0.7",
|
||||
"@types/lodash": "4.14.202",
|
||||
"@types/pdfjs-dist": "^2.10.378",
|
||||
"@types/react": "^18.2.56",
|
||||
"@types/react-dom": "^18.2.19",
|
||||
"@typescript-eslint/eslint-plugin": "^7.0.2",
|
||||
@ -58,10 +66,18 @@
|
||||
"eslint": "^8.56.0",
|
||||
"eslint-plugin-react-hooks": "^4.6.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.5",
|
||||
"license-checker": "^25.0.1",
|
||||
"lint-staged": "^15.2.8",
|
||||
"prettier": "3.2.5",
|
||||
"ts-css-modules-vite-plugin": "1.0.20",
|
||||
"typescript": "^5.2.2",
|
||||
"vite": "^5.1.4",
|
||||
"vite-tsconfig-paths": "4.3.2"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.{js,jsx,ts,tsx}": [
|
||||
"npm run lint:staged"
|
||||
],
|
||||
"*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}": "npm run formatter:staged"
|
||||
}
|
||||
}
|
||||
|
589
src/components/DrawPDFFields/index.tsx
Normal file
589
src/components/DrawPDFFields/index.tsx
Normal file
@ -0,0 +1,589 @@
|
||||
import {
|
||||
AccessTime,
|
||||
CalendarMonth,
|
||||
ExpandMore,
|
||||
Gesture,
|
||||
PictureAsPdf,
|
||||
Badge,
|
||||
Work,
|
||||
Close
|
||||
} from '@mui/icons-material'
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
Accordion,
|
||||
AccordionDetails,
|
||||
AccordionSummary,
|
||||
CircularProgress,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
MenuItem,
|
||||
Select
|
||||
} from '@mui/material'
|
||||
import styles from './style.module.scss'
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
import * as PDFJS from 'pdfjs-dist'
|
||||
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 = new URL(
|
||||
'pdfjs-dist/build/pdf.worker.min.mjs',
|
||||
import.meta.url
|
||||
).toString()
|
||||
|
||||
interface Props {
|
||||
selectedFiles: File[]
|
||||
users: User[]
|
||||
metadata: { [key: string]: ProfileMetadata }
|
||||
onDrawFieldsChange: (pdfFiles: PdfFile[]) => void
|
||||
}
|
||||
|
||||
export const DrawPDFFields = (props: Props) => {
|
||||
const { selectedFiles } = props
|
||||
|
||||
const [pdfFiles, setPdfFiles] = useState<PdfFile[]>([])
|
||||
const [parsingPdf, setParsingPdf] = useState<boolean>(false)
|
||||
const [showDrawToolBox, setShowDrawToolBox] = useState<boolean>(false)
|
||||
|
||||
const [selectedTool, setSelectedTool] = useState<DrawTool | null>()
|
||||
const [toolbox] = useState<DrawTool[]>([
|
||||
{
|
||||
identifier: MarkType.SIGNATURE,
|
||||
icon: <Gesture />,
|
||||
label: 'Signature',
|
||||
active: false
|
||||
},
|
||||
{
|
||||
identifier: MarkType.FULLNAME,
|
||||
icon: <Badge />,
|
||||
label: 'Full Name',
|
||||
active: true
|
||||
},
|
||||
{
|
||||
identifier: MarkType.JOBTITLE,
|
||||
icon: <Work />,
|
||||
label: 'Job Title',
|
||||
active: false
|
||||
},
|
||||
{
|
||||
identifier: MarkType.DATE,
|
||||
icon: <CalendarMonth />,
|
||||
label: 'Date',
|
||||
active: false
|
||||
},
|
||||
{
|
||||
identifier: MarkType.DATETIME,
|
||||
icon: <AccessTime />,
|
||||
label: 'Datetime',
|
||||
active: false
|
||||
}
|
||||
])
|
||||
|
||||
const [mouseState, setMouseState] = useState<MouseState>({
|
||||
clicked: false
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedFiles) {
|
||||
setParsingPdf(true)
|
||||
|
||||
parsePdfPages().finally(() => {
|
||||
setParsingPdf(false)
|
||||
})
|
||||
}
|
||||
}, [selectedFiles])
|
||||
|
||||
useEffect(() => {
|
||||
if (pdfFiles) props.onDrawFieldsChange(pdfFiles)
|
||||
}, [pdfFiles])
|
||||
|
||||
/**
|
||||
* Drawing events
|
||||
*/
|
||||
useEffect(() => {
|
||||
// window.addEventListener('mousedown', onMouseDown);
|
||||
window.addEventListener('mouseup', onMouseUp)
|
||||
|
||||
return () => {
|
||||
// window.removeEventListener('mousedown', onMouseDown);
|
||||
window.removeEventListener('mouseup', onMouseUp)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const refreshPdfFiles = () => {
|
||||
setPdfFiles([...pdfFiles])
|
||||
}
|
||||
|
||||
/**
|
||||
* Fired only when left click and mouse over pdf page
|
||||
* Creates new drawnElement and pushes in the array
|
||||
* It is re rendered and visible right away
|
||||
*
|
||||
* @param event Mouse event
|
||||
* @param page PdfPage where press happened
|
||||
*/
|
||||
const onMouseDown = (event: any, page: PdfPage) => {
|
||||
// Proceed only if left click
|
||||
if (event.button !== 0) return
|
||||
|
||||
// Only allow drawing if mouse is not over other drawn element
|
||||
const isOverPdfImageWrapper = event.target.tagName === 'IMG'
|
||||
|
||||
if (!selectedTool || !isOverPdfImageWrapper) {
|
||||
return
|
||||
}
|
||||
|
||||
const { mouseX, mouseY } = getMouseCoordinates(event)
|
||||
|
||||
const newField: DrawnField = {
|
||||
left: mouseX,
|
||||
top: mouseY,
|
||||
width: 0,
|
||||
height: 0,
|
||||
counterpart: '',
|
||||
type: selectedTool.identifier
|
||||
}
|
||||
|
||||
page.drawnFields.push(newField)
|
||||
|
||||
setMouseState((prev) => {
|
||||
return {
|
||||
...prev,
|
||||
clicked: true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Drawing is finished, resets all the variables used to draw
|
||||
* @param event Mouse event
|
||||
*/
|
||||
const onMouseUp = () => {
|
||||
setMouseState((prev) => {
|
||||
return {
|
||||
...prev,
|
||||
clicked: false,
|
||||
dragging: false,
|
||||
resizing: false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* After {@link onMouseDown} create an drawing element, this function gets called on every pixel moved
|
||||
* which alters the newly created drawing element, resizing it while mouse move
|
||||
* @param event Mouse event
|
||||
* @param page PdfPage where moving is happening
|
||||
*/
|
||||
const onMouseMove = (event: any, page: PdfPage) => {
|
||||
if (mouseState.clicked && selectedTool) {
|
||||
const lastElementIndex = page.drawnFields.length - 1
|
||||
const lastDrawnField = page.drawnFields[lastElementIndex]
|
||||
|
||||
const { mouseX, mouseY } = getMouseCoordinates(event)
|
||||
|
||||
const width = mouseX - lastDrawnField.left
|
||||
const height = mouseY - lastDrawnField.top
|
||||
|
||||
lastDrawnField.width = width
|
||||
lastDrawnField.height = height
|
||||
|
||||
const currentDrawnFields = page.drawnFields
|
||||
|
||||
currentDrawnFields[lastElementIndex] = lastDrawnField
|
||||
|
||||
refreshPdfFiles()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fired when event happens on the drawn element which will be moved
|
||||
* mouse coordinates relative to drawn element will be stored
|
||||
* so when we start moving, offset can be calculated
|
||||
* mouseX - offsetX
|
||||
* mouseY - offsetY
|
||||
*
|
||||
* @param event Mouse event
|
||||
* @param drawnField Which we are moving
|
||||
*/
|
||||
const onDrawnFieldMouseDown = (event: any) => {
|
||||
event.stopPropagation()
|
||||
|
||||
// Proceed only if left click
|
||||
if (event.button !== 0) return
|
||||
|
||||
const drawingRectangleCoords = getMouseCoordinates(event)
|
||||
|
||||
setMouseState({
|
||||
dragging: true,
|
||||
clicked: false,
|
||||
coordsInWrapper: {
|
||||
mouseX: drawingRectangleCoords.mouseX,
|
||||
mouseY: drawingRectangleCoords.mouseY
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the drawnElement by the mouse position (mouse can grab anywhere on the drawn element)
|
||||
* @param event Mouse event
|
||||
* @param drawnField which we are moving
|
||||
*/
|
||||
const onDranwFieldMouseMove = (event: any, drawnField: DrawnField) => {
|
||||
if (mouseState.dragging) {
|
||||
const { mouseX, mouseY, rect } = getMouseCoordinates(
|
||||
event,
|
||||
event.target.parentNode
|
||||
)
|
||||
const coordsOffset = mouseState.coordsInWrapper
|
||||
|
||||
if (coordsOffset) {
|
||||
let left = mouseX - coordsOffset.mouseX
|
||||
let top = mouseY - coordsOffset.mouseY
|
||||
|
||||
const rightLimit = rect.width - drawnField.width - 3
|
||||
const bottomLimit = rect.height - drawnField.height - 3
|
||||
|
||||
if (left < 0) left = 0
|
||||
if (top < 0) top = 0
|
||||
if (left > rightLimit) left = rightLimit
|
||||
if (top > bottomLimit) top = bottomLimit
|
||||
|
||||
drawnField.left = left
|
||||
drawnField.top = top
|
||||
|
||||
refreshPdfFiles()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fired when clicked on the resize handle, sets the state for a resize action
|
||||
* @param event Mouse event
|
||||
* @param drawnField which we are resizing
|
||||
*/
|
||||
const onResizeHandleMouseDown = (event: any) => {
|
||||
// Proceed only if left click
|
||||
if (event.button !== 0) return
|
||||
|
||||
event.stopPropagation()
|
||||
|
||||
setMouseState({
|
||||
resizing: true
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Resizes the drawn element by the mouse position
|
||||
* @param event Mouse event
|
||||
* @param drawnField which we are resizing
|
||||
*/
|
||||
const onResizeHandleMouseMove = (event: any, drawnField: DrawnField) => {
|
||||
if (mouseState.resizing) {
|
||||
const { mouseX, mouseY } = getMouseCoordinates(
|
||||
event,
|
||||
event.target.parentNode.parentNode
|
||||
)
|
||||
|
||||
const width = mouseX - drawnField.left
|
||||
const height = mouseY - drawnField.top
|
||||
|
||||
drawnField.width = width
|
||||
drawnField.height = height
|
||||
|
||||
refreshPdfFiles()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the drawn element using the indexes in the params
|
||||
* @param event Mouse event
|
||||
* @param pdfFileIndex pdf file index
|
||||
* @param pdfPageIndex pdf page index
|
||||
* @param drawnFileIndex drawn file index
|
||||
*/
|
||||
const onRemoveHandleMouseDown = (
|
||||
event: any,
|
||||
pdfFileIndex: number,
|
||||
pdfPageIndex: number,
|
||||
drawnFileIndex: number
|
||||
) => {
|
||||
event.stopPropagation()
|
||||
|
||||
pdfFiles[pdfFileIndex].pages[pdfPageIndex].drawnFields.splice(
|
||||
drawnFileIndex,
|
||||
1
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Used to stop mouse click propagating to the parent elements
|
||||
* so select can work properly
|
||||
* @param event Mouse event
|
||||
*/
|
||||
const onUserSelectHandleMouseDown = (event: any) => {
|
||||
event.stopPropagation()
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the mouse coordinates relative to a element in the `event` param
|
||||
* @param event MouseEvent
|
||||
* @param customTarget mouse coordinates relative to this element, if not provided
|
||||
* event.target will be used
|
||||
*/
|
||||
const getMouseCoordinates = (event: any, customTarget?: any) => {
|
||||
const target = customTarget ? customTarget : event.target
|
||||
const rect = target.getBoundingClientRect()
|
||||
const mouseX = event.clientX - rect.left //x position within the element.
|
||||
const mouseY = event.clientY - rect.top //y position within the element.
|
||||
|
||||
return {
|
||||
mouseX,
|
||||
mouseY,
|
||||
rect
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the pdf binary files and converts it's pages to images
|
||||
* creates the pdfFiles object and sets to a state
|
||||
*/
|
||||
const parsePdfPages = async () => {
|
||||
const pdfFiles: PdfFile[] = await toPdfFiles(selectedFiles)
|
||||
|
||||
setPdfFiles(pdfFiles)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns if expanded pdf accordion is present
|
||||
*/
|
||||
const hasExpandedPdf = () => {
|
||||
return !!pdfFiles.filter((pdfFile) => !!pdfFile.expanded).length
|
||||
}
|
||||
|
||||
const handleAccordionExpandChange = (expanded: boolean, pdfFile: PdfFile) => {
|
||||
pdfFile.expanded = expanded
|
||||
|
||||
refreshPdfFiles()
|
||||
setShowDrawToolBox(hasExpandedPdf())
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the drawing tool
|
||||
* @param drawTool to draw with
|
||||
*/
|
||||
const handleToolSelect = (drawTool: DrawTool) => {
|
||||
// If clicked on the same tool, unselect
|
||||
if (drawTool.identifier === selectedTool?.identifier) {
|
||||
setSelectedTool(null)
|
||||
return
|
||||
}
|
||||
|
||||
setSelectedTool(drawTool)
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the pdf pages and drawing elements
|
||||
*/
|
||||
const getPdfPages = (pdfFile: PdfFile, pdfFileIndex: number) => {
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
width: '100%'
|
||||
}}
|
||||
>
|
||||
{pdfFile.pages.map((page, pdfPageIndex: number) => {
|
||||
return (
|
||||
<div
|
||||
key={pdfPageIndex}
|
||||
style={{
|
||||
border: '1px solid #c4c4c4',
|
||||
marginBottom: '10px'
|
||||
}}
|
||||
className={`${styles.pdfImageWrapper} ${selectedTool ? styles.drawing : ''}`}
|
||||
onMouseMove={(event) => {
|
||||
onMouseMove(event, page)
|
||||
}}
|
||||
onMouseDown={(event) => {
|
||||
onMouseDown(event, page)
|
||||
}}
|
||||
>
|
||||
<img
|
||||
draggable="false"
|
||||
style={{ width: '100%' }}
|
||||
src={page.image}
|
||||
/>
|
||||
|
||||
{page.drawnFields.map((drawnField, drawnFieldIndex: number) => {
|
||||
return (
|
||||
<div
|
||||
key={drawnFieldIndex}
|
||||
onMouseDown={onDrawnFieldMouseDown}
|
||||
onMouseMove={(event) => {
|
||||
onDranwFieldMouseMove(event, drawnField)
|
||||
}}
|
||||
className={styles.drawingRectangle}
|
||||
style={{
|
||||
left: `${drawnField.left}px`,
|
||||
top: `${drawnField.top}px`,
|
||||
width: `${drawnField.width}px`,
|
||||
height: `${drawnField.height}px`,
|
||||
pointerEvents: mouseState.clicked ? 'none' : 'all'
|
||||
}}
|
||||
>
|
||||
<span
|
||||
onMouseDown={onResizeHandleMouseDown}
|
||||
onMouseMove={(event) => {
|
||||
onResizeHandleMouseMove(event, drawnField)
|
||||
}}
|
||||
className={styles.resizeHandle}
|
||||
></span>
|
||||
<span
|
||||
onMouseDown={(event) => {
|
||||
onRemoveHandleMouseDown(
|
||||
event,
|
||||
pdfFileIndex,
|
||||
pdfPageIndex,
|
||||
drawnFieldIndex
|
||||
)
|
||||
}}
|
||||
className={styles.removeHandle}
|
||||
>
|
||||
<Close fontSize="small" />
|
||||
</span>
|
||||
<div
|
||||
onMouseDown={onUserSelectHandleMouseDown}
|
||||
className={styles.userSelect}
|
||||
>
|
||||
<FormControl fullWidth size="small">
|
||||
<InputLabel id="counterparts">Counterpart</InputLabel>
|
||||
<Select
|
||||
value={drawnField.counterpart}
|
||||
onChange={(event) => {
|
||||
drawnField.counterpart = event.target.value
|
||||
refreshPdfFiles()
|
||||
}}
|
||||
labelId="counterparts"
|
||||
label="Counterparts"
|
||||
>
|
||||
{props.users.map((user, index) => {
|
||||
let displayValue = truncate(
|
||||
hexToNpub(user.pubkey),
|
||||
{
|
||||
length: 16
|
||||
}
|
||||
)
|
||||
|
||||
const metadata = props.metadata[user.pubkey]
|
||||
|
||||
if (metadata) {
|
||||
displayValue = truncate(
|
||||
metadata.name ||
|
||||
metadata.display_name ||
|
||||
metadata.username,
|
||||
{
|
||||
length: 16
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<MenuItem
|
||||
key={index}
|
||||
value={hexToNpub(user.pubkey)}
|
||||
>
|
||||
{displayValue}
|
||||
</MenuItem>
|
||||
)
|
||||
})}
|
||||
</Select>
|
||||
</FormControl>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
if (parsingPdf) {
|
||||
return (
|
||||
<Box sx={{ width: '100%', textAlign: 'center' }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
if (!pdfFiles.length) {
|
||||
return ''
|
||||
}
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Box sx={{ mt: 1 }}>
|
||||
<Typography sx={{ mb: 1 }}>Draw fields on the PDFs:</Typography>
|
||||
|
||||
{pdfFiles.map((pdfFile, pdfFileIndex: number) => {
|
||||
return (
|
||||
<Accordion
|
||||
key={pdfFileIndex}
|
||||
expanded={pdfFile.expanded}
|
||||
onChange={(_event, expanded) => {
|
||||
handleAccordionExpandChange(expanded, pdfFile)
|
||||
}}
|
||||
>
|
||||
<AccordionSummary
|
||||
expandIcon={<ExpandMore />}
|
||||
aria-controls={`panel${pdfFileIndex}-content`}
|
||||
id={`panel${pdfFileIndex}header`}
|
||||
>
|
||||
<PictureAsPdf sx={{ mr: 1 }} />
|
||||
{pdfFile.file.name}
|
||||
</AccordionSummary>
|
||||
<AccordionDetails>
|
||||
{getPdfPages(pdfFile, pdfFileIndex)}
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
)
|
||||
})}
|
||||
</Box>
|
||||
|
||||
{showDrawToolBox && (
|
||||
<Box className={styles.drawToolBoxContainer}>
|
||||
<Box className={styles.drawToolBox}>
|
||||
{toolbox
|
||||
.filter((drawTool) => drawTool.active)
|
||||
.map((drawTool: DrawTool, index: number) => {
|
||||
return (
|
||||
<Box
|
||||
key={index}
|
||||
onClick={() => {
|
||||
handleToolSelect(drawTool)
|
||||
}}
|
||||
className={`${styles.toolItem} ${selectedTool?.identifier === drawTool.identifier ? styles.selected : ''}`}
|
||||
>
|
||||
{drawTool.icon}
|
||||
{drawTool.label}
|
||||
</Box>
|
||||
)
|
||||
})}
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
)
|
||||
}
|
113
src/components/DrawPDFFields/style.module.scss
Normal file
113
src/components/DrawPDFFields/style.module.scss
Normal file
@ -0,0 +1,113 @@
|
||||
.pdfFieldItem {
|
||||
background: white;
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.drawToolBoxContainer {
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
z-index: 50;
|
||||
|
||||
.drawToolBox {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
min-width: 100px;
|
||||
background-color: white;
|
||||
padding: 15px;
|
||||
box-shadow: 0 0 10px 1px #0000003b;
|
||||
border-radius: 4px;
|
||||
|
||||
.toolItem {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
border: 1px solid rgba(0, 0, 0, 0.137);
|
||||
padding: 5px;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
|
||||
&.selected {
|
||||
border-color: #01aaad;
|
||||
color: #01aaad;
|
||||
}
|
||||
|
||||
&:not(.selected) {
|
||||
&:hover {
|
||||
border-color: #01aaad79;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.pdfImageWrapper {
|
||||
position: relative;
|
||||
user-select: none;
|
||||
|
||||
&.drawing {
|
||||
cursor: crosshair;
|
||||
}
|
||||
}
|
||||
|
||||
.drawingRectangle {
|
||||
position: absolute;
|
||||
border: 1px solid #01aaad;
|
||||
z-index: 50;
|
||||
background-color: #01aaad4b;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
|
||||
&.nonEditable {
|
||||
cursor: default;
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
.resizeHandle {
|
||||
position: absolute;
|
||||
right: -5px;
|
||||
bottom: -5px;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
background-color: #fff;
|
||||
border: 1px solid rgb(160, 160, 160);
|
||||
border-radius: 50%;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.removeHandle {
|
||||
position: absolute;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
top: -30px;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
background-color: #fff;
|
||||
border: 1px solid rgb(160, 160, 160);
|
||||
border-radius: 50%;
|
||||
color: #E74C3C;
|
||||
font-size: 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.userSelect {
|
||||
position: absolute;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
bottom: -60px;
|
||||
min-width: 170px;
|
||||
min-height: 30px;
|
||||
background: #fff;
|
||||
padding: 5px 0;
|
||||
}
|
||||
}
|
43
src/components/PDFView/PdfItem.tsx
Normal file
43
src/components/PDFView/PdfItem.tsx
Normal file
@ -0,0 +1,43 @@
|
||||
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
|
43
src/components/PDFView/PdfMarkItem.tsx
Normal file
43
src/components/PDFView/PdfMarkItem.tsx
Normal file
@ -0,0 +1,43 @@
|
||||
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
|
103
src/components/PDFView/PdfMarking.tsx
Normal file
103
src/components/PDFView/PdfMarking.tsx
Normal file
@ -0,0 +1,103 @@
|
||||
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'
|
||||
import { EMPTY } from '../../utils/const.ts'
|
||||
import { Container } from '../Container'
|
||||
import styles from '../../pages/sign/style.module.scss'
|
||||
|
||||
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 (
|
||||
<>
|
||||
<Container 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}
|
||||
/>
|
||||
)}
|
||||
</Container>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default PdfMarking
|
46
src/components/PDFView/PdfPageItem.tsx
Normal file
46
src/components/PDFView/PdfPageItem.tsx
Normal file
@ -0,0 +1,46 @@
|
||||
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
|
51
src/components/PDFView/index.tsx
Normal file
51
src/components/PDFView/index.tsx
Normal file
@ -0,0 +1,51 @@
|
||||
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
|
16
src/components/PDFView/style.module.scss
Normal file
16
src/components/PDFView/style.module.scss
Normal file
@ -0,0 +1,16 @@
|
||||
.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 */
|
||||
}
|
@ -16,6 +16,13 @@ import { queryNip05 } from '../utils'
|
||||
import NDK, { NDKEvent, NDKSubscription } from '@nostr-dev-kit/ndk'
|
||||
import { EventEmitter } from 'tseep'
|
||||
import { localCache } from '../services'
|
||||
import {
|
||||
findRelayListAndUpdateCache,
|
||||
findRelayListInCache,
|
||||
getDefaultRelaySet,
|
||||
getUserRelaySet,
|
||||
isOlderThanOneWeek
|
||||
} from '../utils/relays.ts'
|
||||
|
||||
export class MetadataController extends EventEmitter {
|
||||
private nostrController: NostrController
|
||||
@ -127,10 +134,8 @@ export class MetadataController extends EventEmitter {
|
||||
|
||||
// If cached metadata is found, check its validity
|
||||
if (cachedMetadataEvent) {
|
||||
const oneWeekInMS = 7 * 24 * 60 * 60 * 1000 // Number of milliseconds in one week
|
||||
|
||||
// Check if the cached metadata is older than one week
|
||||
if (Date.now() - cachedMetadataEvent.cachedAt > oneWeekInMS) {
|
||||
if (isOlderThanOneWeek(cachedMetadataEvent.cachedAt)) {
|
||||
// If older than one week, find the metadata from relays in background
|
||||
|
||||
this.checkForMoreRecentMetadata(hexKey, cachedMetadataEvent.event)
|
||||
@ -144,100 +149,32 @@ export class MetadataController extends EventEmitter {
|
||||
return this.checkForMoreRecentMetadata(hexKey, null)
|
||||
}
|
||||
|
||||
public findRelayListMetadata = async (hexKey: string) => {
|
||||
let relayEvent: Event | null = null
|
||||
/**
|
||||
* Based on the hexKey of the current user, this method attempts to retrieve a relay set.
|
||||
* @func findRelayListInCache first checks if there is already an up-to-date
|
||||
* relay list available in cache; if not -
|
||||
* @func findRelayListAndUpdateCache checks if the relevant relay event is available from
|
||||
* the purple pages relay;
|
||||
* @func findRelayListAndUpdateCache will run again if the previous two calls return null and
|
||||
* check if the relevant relay event can be obtained from 'most popular relays'
|
||||
* If relay event is found, it will be saved in cache for future use
|
||||
* @param hexKey of the current user
|
||||
* @return RelaySet which will contain either relays extracted from the user Relay Event
|
||||
* or a fallback RelaySet with Sigit's Relay
|
||||
*/
|
||||
public findRelayListMetadata = async (hexKey: string): Promise<RelaySet> => {
|
||||
const relayEvent =
|
||||
(await findRelayListInCache(hexKey)) ||
|
||||
(await findRelayListAndUpdateCache(
|
||||
[this.specialMetadataRelay],
|
||||
hexKey
|
||||
)) ||
|
||||
(await findRelayListAndUpdateCache(
|
||||
await this.nostrController.getMostPopularRelays(),
|
||||
hexKey
|
||||
))
|
||||
|
||||
// Attempt to retrieve the metadata event from the local cache
|
||||
const cachedRelayListMetadataEvent =
|
||||
await localCache.getUserRelayListMetadata(hexKey)
|
||||
|
||||
if (cachedRelayListMetadataEvent) {
|
||||
const oneWeekInMS = 7 * 24 * 60 * 60 * 1000 // Number of milliseconds in one week
|
||||
|
||||
// Check if the cached event is not older than one week
|
||||
if (Date.now() - cachedRelayListMetadataEvent.cachedAt < oneWeekInMS) {
|
||||
relayEvent = cachedRelayListMetadataEvent.event
|
||||
}
|
||||
}
|
||||
|
||||
// define filter for relay list
|
||||
const eventFilter: Filter = {
|
||||
kinds: [kinds.RelayList],
|
||||
authors: [hexKey]
|
||||
}
|
||||
|
||||
const pool = new SimplePool()
|
||||
|
||||
// Try to get the relayList event from a special relay (wss://purplepag.es)
|
||||
if (!relayEvent) {
|
||||
relayEvent = await pool
|
||||
.get([this.specialMetadataRelay], eventFilter)
|
||||
.then((event) => {
|
||||
if (event) {
|
||||
// update the event in local cache
|
||||
localCache.addUserRelayListMetadata(event)
|
||||
}
|
||||
return event
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(err)
|
||||
return null
|
||||
})
|
||||
}
|
||||
|
||||
if (!relayEvent) {
|
||||
// If no valid relayList event is found from the special relay, get the most popular relays
|
||||
const mostPopularRelays =
|
||||
await this.nostrController.getMostPopularRelays()
|
||||
|
||||
// Query the most popular relays for relayList event
|
||||
relayEvent = await pool
|
||||
.get(mostPopularRelays, eventFilter)
|
||||
.then((event) => {
|
||||
if (event) {
|
||||
// update the event in local cache
|
||||
localCache.addUserRelayListMetadata(event)
|
||||
}
|
||||
return event
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(err)
|
||||
return null
|
||||
})
|
||||
}
|
||||
|
||||
if (relayEvent) {
|
||||
const relaySet: RelaySet = {
|
||||
read: [],
|
||||
write: []
|
||||
}
|
||||
|
||||
// a list of r tags with relay URIs and a read or write marker.
|
||||
const relayTags = relayEvent.tags.filter((tag) => tag[0] === 'r')
|
||||
|
||||
// Relays marked as read / write are called READ / WRITE relays, respectively
|
||||
relayTags.forEach((tag) => {
|
||||
if (tag.length >= 3) {
|
||||
const marker = tag[2]
|
||||
|
||||
if (marker === 'read') {
|
||||
relaySet.read.push(tag[1])
|
||||
} else if (marker === 'write') {
|
||||
relaySet.write.push(tag[1])
|
||||
}
|
||||
}
|
||||
|
||||
// If the marker is omitted, the relay is used for both purposes
|
||||
if (tag.length === 2) {
|
||||
relaySet.read.push(tag[1])
|
||||
relaySet.write.push(tag[1])
|
||||
}
|
||||
})
|
||||
|
||||
return relaySet
|
||||
}
|
||||
|
||||
throw new Error('No relay list metadata found.')
|
||||
return relayEvent ? getUserRelaySet(relayEvent.tags) : getDefaultRelaySet()
|
||||
}
|
||||
|
||||
public extractProfileMetadataContent = (event: Event) => {
|
||||
|
@ -44,6 +44,7 @@ import {
|
||||
getNsecBunkerDelegatedKey,
|
||||
verifySignedEvent
|
||||
} from '../utils'
|
||||
import { getDefaultRelayMap } from '../utils/relays.ts'
|
||||
|
||||
export class NostrController extends EventEmitter {
|
||||
private static instance: NostrController
|
||||
@ -650,7 +651,7 @@ export class NostrController extends EventEmitter {
|
||||
*/
|
||||
getRelayMap = async (
|
||||
npub: string
|
||||
): Promise<{ map: RelayMap; mapUpdated: number }> => {
|
||||
): Promise<{ map: RelayMap; mapUpdated?: number }> => {
|
||||
const mostPopularRelays = await this.getMostPopularRelays()
|
||||
|
||||
const pool = new SimplePool()
|
||||
@ -691,7 +692,7 @@ export class NostrController extends EventEmitter {
|
||||
|
||||
return Promise.resolve({ map: relaysMap, mapUpdated: event.created_at })
|
||||
} else {
|
||||
return Promise.reject('User relays were not found.')
|
||||
return Promise.resolve({ map: getDefaultRelayMap() })
|
||||
}
|
||||
}
|
||||
|
||||
|
76
src/data/metaSamples.json
Normal file
76
src/data/metaSamples.json
Normal file
@ -0,0 +1,76 @@
|
||||
{
|
||||
"creatorMetaExample": {
|
||||
"fileHashes": {
|
||||
"firstPdfFile.pdf": "da5f857e77d3aa59c461efad804116931c059b36e6b4da0b5d9452753ec70c05",
|
||||
"da5f857e77d3aa59c461efad804116931c059b36e6b4da0b5d9452753ec70c05/1.png": "hash123png1",
|
||||
"da5f857e77d3aa59c461efad804116931c059b36e6b4da0b5d9452753ec70c05/2.png": "hash321png2"
|
||||
},
|
||||
"markConfig": {
|
||||
"npub1x77qywdllzetv9ncnhlfpv62kshlgtt0uqlsq3v22uzzkk2xvvrsn6uyfy": {
|
||||
"da5f857e77d3aa59c461efad804116931c059b36e6b4da0b5d9452753ec70c05/1.png": [
|
||||
{
|
||||
"id": 1,
|
||||
"type": "FULLNAME",
|
||||
"markLocation": {
|
||||
"top": 56,
|
||||
"left": 306,
|
||||
"height": 200,
|
||||
"width": 100,
|
||||
"page": 1
|
||||
},
|
||||
"npub": "npub1x77qywdllzetv9ncnhlfpv62kshlgtt0uqlsq3v22uzzkk2xvvrsn6uyfy",
|
||||
"pdfFileHash": "da5f857e77d3aa59c461efad804116931c059b36e6b4da0b5d9452753ec70c05"
|
||||
}
|
||||
],
|
||||
"da5f857e77d3aa59c461efad804116931c059b36e6b4da0b5d9452753ec70c05/2.png": [
|
||||
{
|
||||
"id": 2,
|
||||
"markType": "FULLNAME",
|
||||
"location": {
|
||||
"top": 76,
|
||||
"left": 283,
|
||||
"height": 150,
|
||||
"width": 123,
|
||||
"page": 2
|
||||
},
|
||||
"npub": "npub1x77qywdllzetv9ncnhlfpv62kshlgtt0uqlsq3v22uzzkk2xvvrsn6uyfy",
|
||||
"pdfFileHash": "da5f857e77d3aa59c461efad804116931c059b36e6b4da0b5d9452753ec70c05"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"docSignatureExample": {
|
||||
"prevSig": "10de030dd2bfafbbd34969645bd0b3f5e8ab71b3b32091fb29bbea5e272f8a3b7284ef667b6a02e9becc1036450d9fbe5c1c6d146fa91d70e0d8f3cd54d64f17",
|
||||
"marks": [
|
||||
{
|
||||
"id": 1,
|
||||
"type": "FULLNAME",
|
||||
"markLocation": {
|
||||
"top": 56,
|
||||
"left": 306,
|
||||
"height": 200,
|
||||
"width": 100,
|
||||
"page": 1
|
||||
},
|
||||
"npub": "npub1x77qywdllzetv9ncnhlfpv62kshlgtt0uqlsq3v22uzzkk2xvvrsn6uyfy",
|
||||
"pdfFileHash": "da5f857e77d3aa59c461efad804116931c059b36e6b4da0b5d9452753ec70c05",
|
||||
"value": "Pera Peric"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"markType": "FULLNAME",
|
||||
"location": {
|
||||
"top": 76,
|
||||
"left": 283,
|
||||
"height": 150,
|
||||
"width": 123,
|
||||
"page": 2
|
||||
},
|
||||
"npub": "npub1x77qywdllzetv9ncnhlfpv62kshlgtt0uqlsq3v22uzzkk2xvvrsn6uyfy",
|
||||
"pdfFileHash": "da5f857e77d3aa59c461efad804116931c059b36e6b4da0b5d9452753ec70c05",
|
||||
"value": "Pera Peric"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
@ -136,7 +136,7 @@ export const MainLayout = () => {
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
setLoadingSpinnerDesc(`Loading SIGit History`)
|
||||
setLoadingSpinnerDesc(`Loading SIGit history...`)
|
||||
getUsersAppData()
|
||||
.then((appData) => {
|
||||
if (appData) {
|
||||
|
@ -24,7 +24,7 @@ import JSZip from 'jszip'
|
||||
import { MuiFileInput } from 'mui-file-input'
|
||||
import { Event, kinds } from 'nostr-tools'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { DndProvider, useDrag, useDrop } from 'react-dnd'
|
||||
import { DndProvider, DragSourceMonitor, useDrag, useDrop } from 'react-dnd'
|
||||
import { HTML5Backend } from 'react-dnd-html5-backend'
|
||||
import { useSelector } from 'react-redux'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
@ -59,7 +59,11 @@ import {
|
||||
updateUsersAppData,
|
||||
uploadToFileStorage
|
||||
} from '../../utils'
|
||||
import { Container } from '../../components/Container'
|
||||
import styles from './style.module.scss'
|
||||
import { PdfFile } from '../../types/drawing'
|
||||
import { DrawPDFFields } from '../../components/DrawPDFFields'
|
||||
import { Mark } from '../../types/mark.ts'
|
||||
|
||||
export const CreatePage = () => {
|
||||
const navigate = useNavigate()
|
||||
@ -84,6 +88,46 @@ export const CreatePage = () => {
|
||||
|
||||
const nostrController = NostrController.getInstance()
|
||||
|
||||
const [metadata, setMetadata] = useState<{ [key: string]: ProfileMetadata }>(
|
||||
{}
|
||||
)
|
||||
const [drawnPdfs, setDrawnPdfs] = useState<PdfFile[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
users.forEach((user) => {
|
||||
if (!(user.pubkey in metadata)) {
|
||||
const metadataController = new MetadataController()
|
||||
|
||||
const handleMetadataEvent = (event: Event) => {
|
||||
const metadataContent =
|
||||
metadataController.extractProfileMetadataContent(event)
|
||||
if (metadataContent)
|
||||
setMetadata((prev) => ({
|
||||
...prev,
|
||||
[user.pubkey]: metadataContent
|
||||
}))
|
||||
}
|
||||
|
||||
metadataController.on(user.pubkey, (kind: number, event: Event) => {
|
||||
if (kind === kinds.Metadata) {
|
||||
handleMetadataEvent(event)
|
||||
}
|
||||
})
|
||||
|
||||
metadataController
|
||||
.findMetadata(user.pubkey)
|
||||
.then((metadataEvent) => {
|
||||
if (metadataEvent) handleMetadataEvent(metadataEvent)
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(
|
||||
`error occurred in finding metadata for: ${user.pubkey}`,
|
||||
err
|
||||
)
|
||||
})
|
||||
}
|
||||
})
|
||||
}, [metadata, users])
|
||||
// Set up event listener for authentication event
|
||||
nostrController.on('nsecbunker-auth', (url) => {
|
||||
setAuthUrl(url)
|
||||
@ -265,14 +309,16 @@ export const CreatePage = () => {
|
||||
}
|
||||
|
||||
// Handle errors during file arrayBuffer conversion
|
||||
const handleFileError = (file: File) => (err: any) => {
|
||||
const handleFileError = (file: File) => (err: unknown) => {
|
||||
console.log(
|
||||
`Error while getting arrayBuffer of file ${file.name} :>> `,
|
||||
err
|
||||
)
|
||||
if (err instanceof Error) {
|
||||
toast.error(
|
||||
err.message || `Error while getting arrayBuffer of file ${file.name}`
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@ -297,11 +343,39 @@ 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
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
.map((mark, index) => {
|
||||
return { ...mark, id: index }
|
||||
})
|
||||
}
|
||||
|
||||
// Handle errors during zip file generation
|
||||
const handleZipError = (err: any) => {
|
||||
const handleZipError = (err: unknown) => {
|
||||
console.log('Error in zip:>> ', err)
|
||||
setIsLoading(false)
|
||||
if (err instanceof Error) {
|
||||
toast.error(err.message || 'Error occurred in generating zip file')
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@ -309,15 +383,13 @@ export const CreatePage = () => {
|
||||
const generateZipFile = async (zip: JSZip): Promise<ArrayBuffer | null> => {
|
||||
setLoadingSpinnerDesc('Generating zip file')
|
||||
|
||||
const arraybuffer = await zip
|
||||
return await zip
|
||||
.generateAsync({
|
||||
type: 'arraybuffer',
|
||||
compression: 'DEFLATE',
|
||||
compressionOptions: { level: 6 }
|
||||
})
|
||||
.catch(handleZipError)
|
||||
|
||||
return arraybuffer
|
||||
}
|
||||
|
||||
// Encrypt the zip file with the generated encryption key
|
||||
@ -364,22 +436,18 @@ export const CreatePage = () => {
|
||||
|
||||
if (!arraybuffer) return null
|
||||
|
||||
const finalZipFile = new File(
|
||||
[new Blob([arraybuffer])],
|
||||
`${unixNow}.sigit.zip`,
|
||||
{
|
||||
return new File([new Blob([arraybuffer])], `${unixNow}.sigit.zip`, {
|
||||
type: 'application/zip'
|
||||
}
|
||||
)
|
||||
|
||||
return finalZipFile
|
||||
})
|
||||
}
|
||||
|
||||
// Handle errors during file upload
|
||||
const handleUploadError = (err: any) => {
|
||||
const handleUploadError = (err: unknown) => {
|
||||
console.log('Error in upload:>> ', err)
|
||||
setIsLoading(false)
|
||||
if (err instanceof Error) {
|
||||
toast.error(err.message || 'Error occurred in uploading file')
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@ -394,14 +462,12 @@ export const CreatePage = () => {
|
||||
type: 'application/sigit'
|
||||
})
|
||||
|
||||
const fileUrl = await uploadToFileStorage(file)
|
||||
return 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
|
||||
@ -414,9 +480,13 @@ export const CreatePage = () => {
|
||||
encryptionKey
|
||||
)
|
||||
|
||||
if (!finalZipFile) return
|
||||
if (!finalZipFile) {
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
saveAs(finalZipFile, 'request.sigit.zip')
|
||||
saveAs(finalZipFile, `request-${now()}.sigit.zip`)
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
const generateFilesZip = async (): Promise<ArrayBuffer | null> => {
|
||||
@ -425,15 +495,13 @@ export const CreatePage = () => {
|
||||
zip.file(file.name, file)
|
||||
})
|
||||
|
||||
const arraybuffer = await zip
|
||||
return await zip
|
||||
.generateAsync({
|
||||
type: 'arraybuffer',
|
||||
compression: 'DEFLATE',
|
||||
compressionOptions: { level: 6 }
|
||||
})
|
||||
.catch(handleZipError)
|
||||
|
||||
return arraybuffer
|
||||
}
|
||||
|
||||
const generateCreateSignature = async (
|
||||
@ -444,11 +512,13 @@ 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 content: CreateSignatureEventContent = {
|
||||
signers: signers.map((signer) => hexToNpub(signer.pubkey)),
|
||||
viewers: viewers.map((viewer) => hexToNpub(viewer.pubkey)),
|
||||
fileHashes,
|
||||
markConfig,
|
||||
zipUrl,
|
||||
title
|
||||
}
|
||||
@ -482,11 +552,7 @@ export const CreatePage = () => {
|
||||
: viewers.map((viewer) => viewer.pubkey)
|
||||
).filter((receiver) => receiver !== usersPubkey)
|
||||
|
||||
const promises = receivers.map((receiver) =>
|
||||
sendNotification(receiver, meta)
|
||||
)
|
||||
|
||||
return promises
|
||||
return receivers.map((receiver) => sendNotification(receiver, meta))
|
||||
}
|
||||
|
||||
const handleCreate = async () => {
|
||||
@ -603,9 +669,11 @@ export const CreatePage = () => {
|
||||
}
|
||||
|
||||
const arrayBuffer = await generateZipFile(zip)
|
||||
if (!arrayBuffer) return
|
||||
if (!arrayBuffer) {
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
setLoadingSpinnerDesc('Encrypting zip file')
|
||||
const encryptedArrayBuffer = await encryptZipFile(
|
||||
arrayBuffer,
|
||||
encryptionKey
|
||||
@ -615,6 +683,10 @@ export const CreatePage = () => {
|
||||
}
|
||||
}
|
||||
|
||||
const onDrawFieldsChange = (pdfFiles: PdfFile[]) => {
|
||||
setDrawnPdfs(pdfFiles)
|
||||
}
|
||||
|
||||
if (authUrl) {
|
||||
return (
|
||||
<iframe
|
||||
@ -629,7 +701,7 @@ export const CreatePage = () => {
|
||||
return (
|
||||
<>
|
||||
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
|
||||
<Box className={styles.container}>
|
||||
<Container className={styles.container}>
|
||||
<TextField
|
||||
label="Title"
|
||||
value={title}
|
||||
@ -697,23 +769,34 @@ export const CreatePage = () => {
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<DisplayUser
|
||||
metadata={metadata}
|
||||
users={users}
|
||||
handleUserRoleChange={handleUserRoleChange}
|
||||
handleRemoveUser={handleRemoveUser}
|
||||
moveSigner={moveSigner}
|
||||
/>
|
||||
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
|
||||
|
||||
<DrawPDFFields
|
||||
metadata={metadata}
|
||||
users={users}
|
||||
selectedFiles={selectedFiles}
|
||||
onDrawFieldsChange={onDrawFieldsChange}
|
||||
/>
|
||||
|
||||
<Box sx={{ mt: 1, mb: 5, display: 'flex', justifyContent: 'center' }}>
|
||||
<Button onClick={handleCreate} variant="contained">
|
||||
Create
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
</Container>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
type DisplayUsersProps = {
|
||||
metadata: { [key: string]: ProfileMetadata }
|
||||
users: User[]
|
||||
handleUserRoleChange: (role: UserRole, pubkey: string) => void
|
||||
handleRemoveUser: (pubkey: string) => void
|
||||
@ -721,51 +804,12 @@ type DisplayUsersProps = {
|
||||
}
|
||||
|
||||
const DisplayUser = ({
|
||||
metadata,
|
||||
users,
|
||||
handleUserRoleChange,
|
||||
handleRemoveUser,
|
||||
moveSigner
|
||||
}: DisplayUsersProps) => {
|
||||
const [metadata, setMetadata] = useState<{ [key: string]: ProfileMetadata }>(
|
||||
{}
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
users.forEach((user) => {
|
||||
if (!(user.pubkey in metadata)) {
|
||||
const metadataController = new MetadataController()
|
||||
|
||||
const handleMetadataEvent = (event: Event) => {
|
||||
const metadataContent =
|
||||
metadataController.extractProfileMetadataContent(event)
|
||||
if (metadataContent)
|
||||
setMetadata((prev) => ({
|
||||
...prev,
|
||||
[user.pubkey]: metadataContent
|
||||
}))
|
||||
}
|
||||
|
||||
metadataController.on(user.pubkey, (kind: number, event: Event) => {
|
||||
if (kind === kinds.Metadata) {
|
||||
handleMetadataEvent(event)
|
||||
}
|
||||
})
|
||||
|
||||
metadataController
|
||||
.findMetadata(user.pubkey)
|
||||
.then((metadataEvent) => {
|
||||
if (metadataEvent) handleMetadataEvent(metadataEvent)
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(
|
||||
`error occurred in finding metadata for: ${user.pubkey}`,
|
||||
err
|
||||
)
|
||||
})
|
||||
}
|
||||
})
|
||||
}, [users])
|
||||
|
||||
return (
|
||||
<TableContainer component={Paper} elevation={3} sx={{ marginTop: '20px' }}>
|
||||
<Table>
|
||||
@ -935,7 +979,7 @@ const SignerRow = ({
|
||||
item: () => {
|
||||
return { id: user.pubkey, index }
|
||||
},
|
||||
collect: (monitor: any) => ({
|
||||
collect: (monitor: DragSourceMonitor) => ({
|
||||
isDragging: monitor.isDragging()
|
||||
})
|
||||
})
|
||||
|
@ -6,6 +6,8 @@
|
||||
color: $text-color;
|
||||
margin-top: 10px;
|
||||
gap: 10px;
|
||||
width: 550px;
|
||||
max-width: 550px;
|
||||
|
||||
.inputBlock {
|
||||
display: flex;
|
||||
|
@ -91,7 +91,8 @@ export const RelaysPage = () => {
|
||||
if (isMounted) {
|
||||
if (
|
||||
!relaysState?.mapUpdated ||
|
||||
newRelayMap.mapUpdated > relaysState?.mapUpdated
|
||||
(newRelayMap?.mapUpdated !== undefined &&
|
||||
newRelayMap?.mapUpdated > relaysState?.mapUpdated)
|
||||
) {
|
||||
if (
|
||||
!relaysState?.map ||
|
||||
|
37
src/pages/sign/MarkFormField.tsx
Normal file
37
src/pages/sign/MarkFormField.tsx
Normal file
@ -0,0 +1,37 @@
|
||||
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
|
@ -5,7 +5,7 @@ import JSZip from 'jszip'
|
||||
import _ from 'lodash'
|
||||
import { MuiFileInput } from 'mui-file-input'
|
||||
import { Event, verifyEvent } from 'nostr-tools'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useSelector } from 'react-redux'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { toast } from 'react-toastify'
|
||||
@ -17,12 +17,15 @@ import { CreateSignatureEventContent, Meta, SignedEvent } from '../../types'
|
||||
import {
|
||||
decryptArrayBuffer,
|
||||
encryptArrayBuffer,
|
||||
extractMarksFromSignedMeta,
|
||||
extractZipUrlAndEncryptionKey,
|
||||
generateEncryptionKey,
|
||||
generateKeysFile,
|
||||
getFilesWithHashes,
|
||||
getHash,
|
||||
hexToNpub,
|
||||
isOnline,
|
||||
loadZip,
|
||||
now,
|
||||
npubToHex,
|
||||
parseJson,
|
||||
@ -31,9 +34,20 @@ import {
|
||||
signEventForMetaFile,
|
||||
updateUsersAppData
|
||||
} from '../../utils'
|
||||
import { Container } from '../../components/Container'
|
||||
import { DisplayMeta } from './internal/displayMeta'
|
||||
import styles from './style.module.scss'
|
||||
import { Container } from '../../components/Container'
|
||||
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'
|
||||
enum SignedStatus {
|
||||
Fully_Signed,
|
||||
User_Is_Next_Signer,
|
||||
@ -59,7 +73,7 @@ export const SignPage = () => {
|
||||
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
|
||||
const [files, setFiles] = useState<{ [filename: string]: ArrayBuffer }>({})
|
||||
const [files, setFiles] = useState<{ [filename: string]: PdfFile }>({})
|
||||
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
|
||||
@ -71,6 +85,7 @@ 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
|
||||
}>({})
|
||||
@ -89,6 +104,10 @@ 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) {
|
||||
@ -179,6 +198,18 @@ 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)
|
||||
setIsReadyToSign(isCurrentUserMarksComplete(currentUserMarks))
|
||||
}
|
||||
|
||||
setSignedBy(Object.keys(meta.docSignatures) as `npub1${string}`[])
|
||||
}
|
||||
@ -186,149 +217,13 @@ export const SignPage = () => {
|
||||
if (meta) {
|
||||
handleUpdatedMeta(meta)
|
||||
}
|
||||
}, [meta])
|
||||
}, [meta, usersPubkey])
|
||||
|
||||
useEffect(() => {
|
||||
if (metaInNavState) {
|
||||
const processSigit = async () => {
|
||||
setIsLoading(true)
|
||||
setLoadingSpinnerDesc('Extracting zipUrl and encryption key from meta')
|
||||
|
||||
const res = await extractZipUrlAndEncryptionKey(metaInNavState)
|
||||
if (!res) {
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
const { zipUrl, encryptionKey } = res
|
||||
|
||||
setLoadingSpinnerDesc('Fetching file from file server')
|
||||
axios
|
||||
.get(zipUrl, {
|
||||
responseType: 'arraybuffer'
|
||||
})
|
||||
.then((res) => {
|
||||
handleArrayBufferFromBlossom(res.data, encryptionKey)
|
||||
setMeta(metaInNavState)
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(`error occurred in getting file from ${zipUrl}`, err)
|
||||
toast.error(
|
||||
err.message || `error occurred in getting file from ${zipUrl}`
|
||||
)
|
||||
})
|
||||
.finally(() => {
|
||||
setIsLoading(false)
|
||||
})
|
||||
}
|
||||
|
||||
processSigit()
|
||||
} else if (decryptedArrayBuffer) {
|
||||
handleDecryptedArrayBuffer(decryptedArrayBuffer).finally(() =>
|
||||
setIsLoading(false)
|
||||
)
|
||||
} else if (uploadedZip) {
|
||||
decrypt(uploadedZip)
|
||||
.then((arrayBuffer) => {
|
||||
if (arrayBuffer) handleDecryptedArrayBuffer(arrayBuffer)
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(`error occurred in decryption`, err)
|
||||
toast.error(err.message || `error occurred in decryption`)
|
||||
})
|
||||
.finally(() => {
|
||||
setIsLoading(false)
|
||||
})
|
||||
} else {
|
||||
setIsLoading(false)
|
||||
setDisplayInput(true)
|
||||
}
|
||||
}, [decryptedArrayBuffer, uploadedZip, metaInNavState])
|
||||
|
||||
const handleArrayBufferFromBlossom = async (
|
||||
arrayBuffer: ArrayBuffer,
|
||||
encryptionKey: string
|
||||
) => {
|
||||
// array buffer returned from blossom is encrypted.
|
||||
// So, first decrypt it
|
||||
const decrypted = await decryptArrayBuffer(
|
||||
arrayBuffer,
|
||||
encryptionKey
|
||||
).catch((err) => {
|
||||
console.log('err in decryption:>> ', err)
|
||||
toast.error(err.message || 'An error occurred in decrypting file.')
|
||||
setIsLoading(false)
|
||||
return null
|
||||
})
|
||||
|
||||
if (!decrypted) return
|
||||
|
||||
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 null
|
||||
})
|
||||
|
||||
if (!zip) return
|
||||
|
||||
const files: { [filename: string]: ArrayBuffer } = {}
|
||||
const fileHashes: { [key: string]: string | null } = {}
|
||||
const fileNames = Object.values(zip.files).map((entry) => entry.name)
|
||||
|
||||
// generate hashes for all files in zipArchive
|
||||
// these hashes can be used to verify the originality of files
|
||||
for (const fileName of fileNames) {
|
||||
const arrayBuffer = await readContentOfZipEntry(
|
||||
zip,
|
||||
fileName,
|
||||
'arraybuffer'
|
||||
)
|
||||
|
||||
if (arrayBuffer) {
|
||||
files[fileName] = arrayBuffer
|
||||
|
||||
const hash = await getHash(arrayBuffer)
|
||||
if (hash) {
|
||||
fileHashes[fileName] = hash
|
||||
}
|
||||
} else {
|
||||
fileHashes[fileName] = null
|
||||
}
|
||||
}
|
||||
|
||||
setFiles(files)
|
||||
setCurrentFileHashes(fileHashes)
|
||||
}
|
||||
|
||||
const parseKeysJson = async (zip: JSZip) => {
|
||||
const keysFileContent = await readContentOfZipEntry(
|
||||
zip,
|
||||
'keys.json',
|
||||
'string'
|
||||
)
|
||||
|
||||
if (!keysFileContent) return null
|
||||
|
||||
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) => {
|
||||
const decrypt = useCallback(
|
||||
async (file: File) => {
|
||||
setLoadingSpinnerDesc('Decrypting 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
|
||||
})
|
||||
const zip = await loadZip(file)
|
||||
if (!zip) return
|
||||
|
||||
const parsedKeysJson = await parseKeysJson(zip)
|
||||
@ -392,6 +287,142 @@ export const SignPage = () => {
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
[nostrController]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
// online mode - from create and home page views
|
||||
if (metaInNavState) {
|
||||
const processSigit = async () => {
|
||||
setIsLoading(true)
|
||||
setLoadingSpinnerDesc('Extracting zipUrl and encryption key from meta')
|
||||
|
||||
const res = await extractZipUrlAndEncryptionKey(metaInNavState)
|
||||
if (!res) {
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
const { zipUrl, encryptionKey } = res
|
||||
|
||||
setLoadingSpinnerDesc('Fetching file from file server')
|
||||
axios
|
||||
.get(zipUrl, {
|
||||
responseType: 'arraybuffer'
|
||||
})
|
||||
.then((res) => {
|
||||
handleArrayBufferFromBlossom(res.data, encryptionKey)
|
||||
setMeta(metaInNavState)
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(`error occurred in getting file from ${zipUrl}`, err)
|
||||
toast.error(
|
||||
err.message || `error occurred in getting file from ${zipUrl}`
|
||||
)
|
||||
})
|
||||
.finally(() => {
|
||||
setIsLoading(false)
|
||||
})
|
||||
}
|
||||
|
||||
processSigit()
|
||||
} else if (decryptedArrayBuffer) {
|
||||
handleDecryptedArrayBuffer(decryptedArrayBuffer).finally(() =>
|
||||
setIsLoading(false)
|
||||
)
|
||||
} else if (uploadedZip) {
|
||||
decrypt(uploadedZip)
|
||||
.then((arrayBuffer) => {
|
||||
if (arrayBuffer) handleDecryptedArrayBuffer(arrayBuffer)
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(`error occurred in decryption`, err)
|
||||
toast.error(err.message || `error occurred in decryption`)
|
||||
})
|
||||
.finally(() => {
|
||||
setIsLoading(false)
|
||||
})
|
||||
} else {
|
||||
setIsLoading(false)
|
||||
setDisplayInput(true)
|
||||
}
|
||||
}, [decryptedArrayBuffer, uploadedZip, metaInNavState, decrypt])
|
||||
|
||||
const handleArrayBufferFromBlossom = async (
|
||||
arrayBuffer: ArrayBuffer,
|
||||
encryptionKey: string
|
||||
) => {
|
||||
// array buffer returned from blossom is encrypted.
|
||||
// So, first decrypt it
|
||||
const decrypted = await decryptArrayBuffer(
|
||||
arrayBuffer,
|
||||
encryptionKey
|
||||
).catch((err) => {
|
||||
console.log('err in decryption:>> ', err)
|
||||
toast.error(err.message || 'An error occurred in decrypting file.')
|
||||
setIsLoading(false)
|
||||
return null
|
||||
})
|
||||
|
||||
if (!decrypted) return
|
||||
|
||||
const zip = await loadZip(decrypted)
|
||||
if (!zip) {
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
const files: { [filename: string]: PdfFile } = {}
|
||||
const fileHashes: { [key: string]: string | null } = {}
|
||||
const fileNames = Object.values(zip.files).map((entry) => entry.name)
|
||||
|
||||
// generate hashes for all files in zipArchive
|
||||
// these hashes can be used to verify the originality of files
|
||||
for (const fileName of fileNames) {
|
||||
const arrayBuffer = await readContentOfZipEntry(
|
||||
zip,
|
||||
fileName,
|
||||
'arraybuffer'
|
||||
)
|
||||
|
||||
if (arrayBuffer) {
|
||||
files[fileName] = await convertToPdfFile(arrayBuffer, fileName)
|
||||
|
||||
const hash = await getHash(arrayBuffer)
|
||||
if (hash) {
|
||||
fileHashes[fileName] = hash
|
||||
}
|
||||
} else {
|
||||
fileHashes[fileName] = null
|
||||
}
|
||||
}
|
||||
|
||||
setFiles(files)
|
||||
setCurrentFileHashes(fileHashes)
|
||||
}
|
||||
|
||||
const setUpdatedMarks = (markToUpdate: Mark) => {
|
||||
const updatedMarks = updateMarks(marks, markToUpdate)
|
||||
setMarks(updatedMarks)
|
||||
}
|
||||
|
||||
const parseKeysJson = async (zip: JSZip) => {
|
||||
const keysFileContent = await readContentOfZipEntry(
|
||||
zip,
|
||||
'keys.json',
|
||||
'string'
|
||||
)
|
||||
|
||||
if (!keysFileContent) return null
|
||||
|
||||
return 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
|
||||
})
|
||||
}
|
||||
|
||||
const handleDecryptedArrayBuffer = async (arrayBuffer: ArrayBuffer) => {
|
||||
@ -399,32 +430,27 @@ export const SignPage = () => {
|
||||
|
||||
setLoadingSpinnerDesc('Parsing zip file')
|
||||
|
||||
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
|
||||
})
|
||||
|
||||
const zip = await loadZip(decryptedZipFile)
|
||||
if (!zip) return
|
||||
|
||||
const files: { [filename: string]: ArrayBuffer } = {}
|
||||
const files: { [filename: string]: PdfFile } = {}
|
||||
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 (let fileName of fileNames) {
|
||||
for (const fileName of fileNames) {
|
||||
const arrayBuffer = await readContentOfZipEntry(
|
||||
zip,
|
||||
fileName,
|
||||
'arraybuffer'
|
||||
)
|
||||
|
||||
fileName = fileName.replace(/^files\//, '')
|
||||
if (arrayBuffer) {
|
||||
files[fileName] = arrayBuffer
|
||||
files[fileName] = await convertToPdfFile(arrayBuffer, fileName)
|
||||
|
||||
const hash = await getHash(arrayBuffer)
|
||||
if (hash) {
|
||||
@ -488,7 +514,10 @@ export const SignPage = () => {
|
||||
const prevSig = getPrevSignersSig(hexToNpub(usersPubkey!))
|
||||
if (!prevSig) return
|
||||
|
||||
const signedEvent = await signEventForMeta(prevSig)
|
||||
const marks = getSignerMarksForMeta()
|
||||
if (!marks) return
|
||||
|
||||
const signedEvent = await signEventForMeta({ prevSig, marks })
|
||||
if (!signedEvent) return
|
||||
|
||||
const updatedMeta = updateMetaSignatures(meta, signedEvent)
|
||||
@ -502,14 +531,22 @@ export const SignPage = () => {
|
||||
}
|
||||
|
||||
// Sign the event for the meta file
|
||||
const signEventForMeta = async (prevSig: string) => {
|
||||
const signEventForMeta = async (signerContent: {
|
||||
prevSig: string
|
||||
marks: Mark[]
|
||||
}) => {
|
||||
return await signEventForMetaFile(
|
||||
JSON.stringify({ prevSig }),
|
||||
JSON.stringify(signerContent),
|
||||
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)
|
||||
@ -527,7 +564,7 @@ export const SignPage = () => {
|
||||
encryptionKey: string
|
||||
): Promise<File | null> => {
|
||||
// Get the current timestamp in seconds
|
||||
const unixNow = Math.floor(Date.now() / 1000)
|
||||
const unixNow = now()
|
||||
const blob = new Blob([encryptedArrayBuffer])
|
||||
// Create a File object with the Blob data
|
||||
const file = new File([blob], `compressed.sigit`, {
|
||||
@ -577,22 +614,18 @@ export const SignPage = () => {
|
||||
|
||||
if (!arraybuffer) return null
|
||||
|
||||
const finalZipFile = new File(
|
||||
[new Blob([arraybuffer])],
|
||||
`${unixNow}.sigit.zip`,
|
||||
{
|
||||
return new File([new Blob([arraybuffer])], `${unixNow}.sigit.zip`, {
|
||||
type: 'application/zip'
|
||||
}
|
||||
)
|
||||
|
||||
return finalZipFile
|
||||
})
|
||||
}
|
||||
|
||||
// Handle errors during zip file generation
|
||||
const handleZipError = (err: any) => {
|
||||
const handleZipError = (err: unknown) => {
|
||||
console.log('Error in zip:>> ', err)
|
||||
setIsLoading(false)
|
||||
if (err instanceof Error) {
|
||||
toast.error(err.message || 'Error occurred in generating zip file')
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@ -673,7 +706,9 @@ export const SignPage = () => {
|
||||
setIsLoading(true)
|
||||
setLoadingSpinnerDesc('Signing nostr event')
|
||||
|
||||
const prevSig = getLastSignersSig()
|
||||
if (!meta) return
|
||||
|
||||
const prevSig = getLastSignersSig(meta, signers)
|
||||
if (!prevSig) return
|
||||
|
||||
const signedEvent = await signEventForMetaFile(
|
||||
@ -701,9 +736,9 @@ export const SignPage = () => {
|
||||
|
||||
zip.file('meta.json', stringifiedMeta)
|
||||
|
||||
Object.entries(files).forEach(([fileName, arrayBuffer]) => {
|
||||
zip.file(`files/${fileName}`, arrayBuffer)
|
||||
})
|
||||
for (const [fileName, pdf] of Object.entries(files)) {
|
||||
zip.file(`files/${fileName}`, await pdf.file.arrayBuffer())
|
||||
}
|
||||
|
||||
const arrayBuffer = await zip
|
||||
.generateAsync({
|
||||
@ -723,7 +758,7 @@ export const SignPage = () => {
|
||||
if (!arrayBuffer) return
|
||||
|
||||
const blob = new Blob([arrayBuffer])
|
||||
const unixNow = Math.floor(Date.now() / 1000)
|
||||
const unixNow = now()
|
||||
saveAs(blob, `exported-${unixNow}.sigit.zip`)
|
||||
|
||||
setIsLoading(false)
|
||||
@ -740,9 +775,9 @@ export const SignPage = () => {
|
||||
|
||||
zip.file('meta.json', stringifiedMeta)
|
||||
|
||||
Object.entries(files).forEach(([fileName, arrayBuffer]) => {
|
||||
zip.file(`files/${fileName}`, arrayBuffer)
|
||||
})
|
||||
for (const [fileName, pdf] of Object.entries(files)) {
|
||||
zip.file(`files/${fileName}`, await pdf.file.arrayBuffer())
|
||||
}
|
||||
|
||||
const arrayBuffer = await zip
|
||||
.generateAsync({
|
||||
@ -769,7 +804,7 @@ export const SignPage = () => {
|
||||
const finalZipFile = await createFinalZipFile(encryptedArrayBuffer, key)
|
||||
|
||||
if (!finalZipFile) return
|
||||
const unixNow = Math.floor(Date.now() / 1000)
|
||||
const unixNow = now()
|
||||
saveAs(finalZipFile, `exported-${unixNow}.sigit.zip`)
|
||||
}
|
||||
|
||||
@ -806,37 +841,6 @@ 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
|
||||
@ -848,9 +852,13 @@ export const SignPage = () => {
|
||||
)
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return <LoadingSpinner desc={loadingSpinnerDesc} />
|
||||
}
|
||||
|
||||
if (isReadyToSign) {
|
||||
return (
|
||||
<>
|
||||
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
|
||||
<Container className={styles.container}>
|
||||
{displayInput && (
|
||||
<>
|
||||
@ -920,4 +928,15 @@ export const SignPage = () => {
|
||||
</Container>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<PdfMarking
|
||||
files={getFilesWithHashes(files, currentFileHashes)}
|
||||
currentUserMarks={currentUserMarks}
|
||||
setIsReadyToSign={setIsReadyToSign}
|
||||
setCurrentUserMarks={setCurrentUserMarks}
|
||||
setUpdatedMarks={setUpdatedMarks}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
@ -34,10 +34,11 @@ 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]: ArrayBuffer }
|
||||
files: { [filename: string]: PdfFile }
|
||||
submittedBy: string
|
||||
signers: `npub1${string}`[]
|
||||
viewers: `npub1${string}`[]
|
||||
@ -143,7 +144,7 @@ export const DisplayMeta = ({
|
||||
}, [users, submittedBy])
|
||||
|
||||
const downloadFile = async (filename: string) => {
|
||||
const arrayBuffer = files[filename]
|
||||
const arrayBuffer = await files[filename].file.arrayBuffer()
|
||||
if (!arrayBuffer) return
|
||||
|
||||
const blob = new Blob([arrayBuffer])
|
||||
|
@ -2,6 +2,8 @@
|
||||
|
||||
.container {
|
||||
color: $text-color;
|
||||
width: 550px;
|
||||
max-width: 550px;
|
||||
|
||||
.inputBlock {
|
||||
position: relative;
|
||||
@ -47,4 +49,40 @@
|
||||
@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 } from '../../controllers'
|
||||
import { MetadataController, NostrController } from '../../controllers'
|
||||
import {
|
||||
CreateSignatureEventContent,
|
||||
Meta,
|
||||
@ -24,18 +24,32 @@ import {
|
||||
} from '../../types'
|
||||
import {
|
||||
decryptArrayBuffer,
|
||||
extractMarksFromSignedMeta,
|
||||
extractZipUrlAndEncryptionKey,
|
||||
getHash,
|
||||
hexToNpub,
|
||||
now,
|
||||
npubToHex,
|
||||
parseJson,
|
||||
readContentOfZipEntry,
|
||||
shorten
|
||||
shorten,
|
||||
signEventForMetaFile
|
||||
} 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 = () => {
|
||||
@ -67,10 +81,13 @@ 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) {
|
||||
@ -125,6 +142,7 @@ 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
|
||||
@ -140,6 +158,10 @@ export const VerifyPage = () => {
|
||||
)
|
||||
|
||||
if (arrayBuffer) {
|
||||
files[fileName] = await convertToPdfFile(
|
||||
arrayBuffer,
|
||||
fileName!
|
||||
)
|
||||
const hash = await getHash(arrayBuffer)
|
||||
|
||||
if (hash) {
|
||||
@ -151,6 +173,7 @@ export const VerifyPage = () => {
|
||||
}
|
||||
|
||||
setCurrentFileHashes(fileHashes)
|
||||
setFiles(files)
|
||||
|
||||
setSigners(createSignatureContent.signers)
|
||||
setViewers(createSignatureContent.viewers)
|
||||
@ -360,6 +383,73 @@ 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]
|
||||
|
||||
@ -522,6 +612,11 @@ 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,3 +1,4 @@
|
||||
import { Mark } from './mark'
|
||||
import { Keys } from '../store/auth/types'
|
||||
|
||||
export enum UserRole {
|
||||
@ -22,12 +23,14 @@ export interface CreateSignatureEventContent {
|
||||
signers: `npub1${string}`[]
|
||||
viewers: `npub1${string}`[]
|
||||
fileHashes: { [key: string]: string }
|
||||
markConfig: Mark[]
|
||||
title: string
|
||||
zipUrl: string
|
||||
}
|
||||
|
||||
export interface SignedEventContent {
|
||||
prevSig: string
|
||||
marks: Mark[]
|
||||
}
|
||||
|
||||
export interface Sigit {
|
||||
|
49
src/types/drawing.ts
Normal file
49
src/types/drawing.ts
Normal file
@ -0,0 +1,49 @@
|
||||
export interface MouseState {
|
||||
clicked?: boolean
|
||||
dragging?: boolean
|
||||
resizing?: boolean
|
||||
coordsInWrapper?: {
|
||||
mouseX: number
|
||||
mouseY: number
|
||||
}
|
||||
}
|
||||
|
||||
export interface PdfFile {
|
||||
file: File
|
||||
pages: PdfPage[]
|
||||
expanded?: boolean
|
||||
}
|
||||
|
||||
export interface PdfPage {
|
||||
image: string
|
||||
drawnFields: DrawnField[]
|
||||
}
|
||||
|
||||
export interface DrawnField {
|
||||
left: number
|
||||
top: number
|
||||
width: number
|
||||
height: number
|
||||
type: MarkType
|
||||
/**
|
||||
* npub of a counter part
|
||||
*/
|
||||
counterpart: string
|
||||
}
|
||||
|
||||
export interface DrawTool {
|
||||
identifier: MarkType
|
||||
label: string
|
||||
icon: JSX.Element
|
||||
defaultValue?: string
|
||||
selected?: boolean
|
||||
active?: boolean
|
||||
}
|
||||
|
||||
export enum MarkType {
|
||||
SIGNATURE = 'SIGNATURE',
|
||||
JOBTITLE = 'JOBTITLE',
|
||||
FULLNAME = 'FULLNAME',
|
||||
DATE = 'DATE',
|
||||
DATETIME = 'DATETIME'
|
||||
}
|
24
src/types/mark.ts
Normal file
24
src/types/mark.ts
Normal file
@ -0,0 +1,24 @@
|
||||
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
|
||||
}
|
||||
|
||||
export interface MarkLocation {
|
||||
top: number
|
||||
left: number
|
||||
height: number
|
||||
width: number
|
||||
page: number
|
||||
}
|
@ -1,6 +1,7 @@
|
||||
export interface ProfileMetadata {
|
||||
name?: string
|
||||
display_name?: string
|
||||
username?: string
|
||||
picture?: string
|
||||
banner?: string
|
||||
about?: string
|
||||
|
@ -10,4 +10,19 @@ export interface OutputByType {
|
||||
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]>
|
||||
|
12
src/utils/const.ts
Normal file
12
src/utils/const.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { MarkType } from '../types/drawing.ts'
|
||||
|
||||
export const EMPTY: string = ''
|
||||
export const MARK_TYPE_TRANSLATION: { [key: string]: string } = {
|
||||
[MarkType.FULLNAME.valueOf()]: 'Full Name'
|
||||
}
|
||||
/**
|
||||
* Number of milliseconds in one week.
|
||||
* Calc based on: 7 * 24 * 60 * 60 * 1000
|
||||
*/
|
||||
export const ONE_WEEK_IN_MS: number = 604800000
|
||||
export const SIGIT_RELAY: string = 'wss://relay.sigit.io'
|
@ -6,3 +6,4 @@ export * from './nostr'
|
||||
export * from './string'
|
||||
export * from './zip'
|
||||
export * from './utils'
|
||||
export * from './mark'
|
||||
|
110
src/utils/mark.ts
Normal file
110
src/utils/mark.ts
Normal file
@ -0,0 +1,110 @@
|
||||
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,14 +83,12 @@ export const signEventForMetaFile = async (
|
||||
}
|
||||
|
||||
// Sign the event
|
||||
const signedEvent = await nostrController.signEvent(event).catch((err) => {
|
||||
return 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
|
||||
}
|
||||
|
||||
/**
|
||||
|
263
src/utils/pdf.ts
Normal file
263
src/utils/pdf.ts
Normal file
@ -0,0 +1,263 @@
|
||||
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 = new URL(
|
||||
'pdfjs-dist/build/pdf.worker.min.mjs',
|
||||
import.meta.url
|
||||
).toString()
|
||||
|
||||
/**
|
||||
* 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
|
||||
}
|
116
src/utils/relays.ts
Normal file
116
src/utils/relays.ts
Normal file
@ -0,0 +1,116 @@
|
||||
import { Filter, SimplePool } from 'nostr-tools'
|
||||
import { RelayList } from 'nostr-tools/kinds'
|
||||
import { Event } from 'nostr-tools'
|
||||
import { localCache } from '../services'
|
||||
import { ONE_WEEK_IN_MS, SIGIT_RELAY } from './const.ts'
|
||||
import { RelayMap, RelaySet } from '../types'
|
||||
|
||||
const READ_MARKER = 'read'
|
||||
const WRITE_MARKER = 'write'
|
||||
|
||||
/**
|
||||
* Attempts to find a relay list from the provided lookUpRelays.
|
||||
* If the relay list is found, it will be added to the user relay list metadata.
|
||||
* @param lookUpRelays
|
||||
* @param hexKey
|
||||
* @return found relay list or null
|
||||
*/
|
||||
const findRelayListAndUpdateCache = async (
|
||||
lookUpRelays: string[],
|
||||
hexKey: string
|
||||
): Promise<Event | null> => {
|
||||
try {
|
||||
const eventFilter: Filter = {
|
||||
kinds: [RelayList],
|
||||
authors: [hexKey]
|
||||
}
|
||||
const pool = new SimplePool()
|
||||
const event = await pool.get(lookUpRelays, eventFilter)
|
||||
if (event) {
|
||||
await localCache.addUserRelayListMetadata(event)
|
||||
}
|
||||
return event
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to find a relay list in cache. If it is present, it will check that the cached event is not
|
||||
* older than one week.
|
||||
* @param hexKey
|
||||
* @return RelayList event if it's not older than a week; otherwise null
|
||||
*/
|
||||
const findRelayListInCache = async (hexKey: string): Promise<Event | null> => {
|
||||
try {
|
||||
// Attempt to retrieve the metadata event from the local cache
|
||||
const cachedRelayListMetadataEvent =
|
||||
await localCache.getUserRelayListMetadata(hexKey)
|
||||
|
||||
// Check if the cached event is not older than one week
|
||||
if (
|
||||
cachedRelayListMetadataEvent &&
|
||||
isOlderThanOneWeek(cachedRelayListMetadataEvent.cachedAt)
|
||||
) {
|
||||
return cachedRelayListMetadataEvent.event
|
||||
}
|
||||
|
||||
return null
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms a list of relay tags from a Nostr Event to a RelaySet.
|
||||
* @param tags
|
||||
*/
|
||||
const getUserRelaySet = (tags: string[][]): RelaySet => {
|
||||
return tags
|
||||
.filter(isRelayTag)
|
||||
.reduce<RelaySet>(toRelaySet, getDefaultRelaySet())
|
||||
}
|
||||
|
||||
const getDefaultRelaySet = (): RelaySet => ({
|
||||
read: [SIGIT_RELAY],
|
||||
write: [SIGIT_RELAY]
|
||||
})
|
||||
|
||||
const getDefaultRelayMap = (): RelayMap => ({
|
||||
[SIGIT_RELAY]: { write: true, read: true }
|
||||
})
|
||||
|
||||
const isOlderThanOneWeek = (cachedAt: number) => {
|
||||
return Date.now() - cachedAt < ONE_WEEK_IN_MS
|
||||
}
|
||||
|
||||
const isRelayTag = (tag: string[]): boolean => tag[0] === 'r'
|
||||
|
||||
const toRelaySet = (obj: RelaySet, tag: string[]): RelaySet => {
|
||||
if (tag.length >= 3) {
|
||||
const marker = tag[2]
|
||||
|
||||
if (marker === READ_MARKER) {
|
||||
obj.read.push(tag[1])
|
||||
} else if (marker === WRITE_MARKER) {
|
||||
obj.write.push(tag[1])
|
||||
}
|
||||
}
|
||||
if (tag.length === 2) {
|
||||
obj.read.push(tag[1])
|
||||
obj.write.push(tag[1])
|
||||
}
|
||||
|
||||
return obj
|
||||
}
|
||||
|
||||
export {
|
||||
findRelayListAndUpdateCache,
|
||||
findRelayListInCache,
|
||||
getUserRelaySet,
|
||||
getDefaultRelaySet,
|
||||
getDefaultRelayMap,
|
||||
isOlderThanOneWeek
|
||||
}
|
34
src/utils/sign.ts
Normal file
34
src/utils/sign.ts
Normal file
@ -0,0 +1,34 @@
|
||||
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,3 +1,5 @@
|
||||
import { PdfFile } from '../types/drawing.ts'
|
||||
|
||||
export const compareObjects = (
|
||||
obj1: object | null | undefined,
|
||||
obj2: object | null | undefined
|
||||
@ -64,3 +66,17 @@ 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 { OutputByType, OutputType } from '../types'
|
||||
import { InputFileFormat, OutputByType, OutputType } from '../types'
|
||||
|
||||
/**
|
||||
* Read the content of a file within a zip archive.
|
||||
@ -9,7 +9,7 @@ import { 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.
|
||||
*/
|
||||
export const readContentOfZipEntry = async <T extends OutputType>(
|
||||
const readContentOfZipEntry = async <T extends OutputType>(
|
||||
zip: JSZip,
|
||||
filePath: string,
|
||||
outputType: T
|
||||
@ -22,8 +22,9 @@ export const readContentOfZipEntry = async <T extends OutputType>(
|
||||
return null
|
||||
}
|
||||
|
||||
// Read the content of the zip entry asynchronously
|
||||
const fileContent = await zipEntry.async(outputType).catch((err) => {
|
||||
// Read and return the content of the zip entry asynchronously
|
||||
// or null if an error has occurred
|
||||
return 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(
|
||||
@ -31,7 +32,16 @@ export 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