sigit.io/src/pages/create/index.tsx

727 lines
20 KiB
TypeScript
Raw Normal View History

import { Clear, DragHandle } from '@mui/icons-material'
2024-05-14 09:27:05 +00:00
import {
Box,
Button,
FormControl,
IconButton,
InputLabel,
MenuItem,
Paper,
Select,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
TextField,
Tooltip,
Typography
} from '@mui/material'
2024-05-16 11:22:05 +00:00
import JSZip from 'jszip'
import { MuiFileInput } from 'mui-file-input'
import { useEffect, useRef, useState } from 'react'
2024-05-16 11:22:05 +00:00
import { useSelector } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner'
2024-05-16 11:22:05 +00:00
import { UserComponent } from '../../components/username'
2024-05-14 09:27:05 +00:00
import { MetadataController, NostrController } from '../../controllers'
2024-05-16 11:22:05 +00:00
import { appPrivateRoutes } from '../../routes'
import { State } from '../../store/rootReducer'
import { Meta, ProfileMetadata, User, UserRole } from '../../types'
import {
encryptArrayBuffer,
generateEncryptionKey,
getHash,
2024-05-14 09:27:05 +00:00
hexToNpub,
npubToHex,
2024-05-14 09:27:05 +00:00
queryNip05,
sendDM,
2024-05-14 09:27:05 +00:00
shorten,
signEventForMetaFile,
uploadToFileStorage
} from '../../utils'
2024-05-14 09:27:05 +00:00
import styles from './style.module.scss'
import { DndProvider } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'
import type { Identifier, XYCoord } from 'dnd-core'
import { useDrag, useDrop } from 'react-dnd'
2024-05-15 08:41:55 +00:00
export const CreatePage = () => {
const navigate = useNavigate()
const [isLoading, setIsLoading] = useState(false)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
2024-05-14 09:27:05 +00:00
const [authUrl, setAuthUrl] = useState<string>()
2024-05-14 09:27:05 +00:00
const [selectedFiles, setSelectedFiles] = useState<File[]>([])
const [displayUserInput, setDisplayUserInput] = useState(false)
const [userInput, setUserInput] = useState('')
const [userRole, setUserRole] = useState<UserRole>(UserRole.signer)
const [error, setError] = useState<string>()
const [users, setUsers] = useState<User[]>([])
const usersPubkey = useSelector((state: State) => state.auth.usersPubkey)
const nostrController = NostrController.getInstance()
2024-05-15 08:41:55 +00:00
useEffect(() => {
if (usersPubkey) {
setUsers((prev) => {
const existingUserIndex = prev.findIndex(
(user) => user.pubkey === usersPubkey
)
// make logged in user the first signer by default
if (existingUserIndex === -1)
return [{ pubkey: usersPubkey, role: UserRole.signer }, ...prev]
return prev
})
}
}, [usersPubkey])
2024-05-14 09:27:05 +00:00
const handleAddUser = async () => {
setError(undefined)
2024-05-14 09:27:05 +00:00
const addUser = (pubkey: string) => {
setUsers((prev) => {
const existingUserIndex = prev.findIndex(
(user) => user.pubkey === pubkey
)
2024-05-14 09:27:05 +00:00
// add new
if (existingUserIndex === -1)
return [...prev, { pubkey, role: userRole }]
2024-05-14 09:27:05 +00:00
const existingUser = prev[existingUserIndex]
2024-05-14 09:27:05 +00:00
// return existing
if (existingUser.role === userRole) return prev
2024-05-14 09:27:05 +00:00
// change user role
const updatedUsers = [...prev]
const updatedUser = { ...updatedUsers[existingUserIndex] }
updatedUser.role = userRole
updatedUsers[existingUserIndex] = updatedUser
2024-05-14 09:27:05 +00:00
return updatedUsers
})
}
2024-05-14 09:27:05 +00:00
if (userInput.startsWith('npub')) {
const pubkey = npubToHex(userInput)
2024-05-14 09:27:05 +00:00
if (pubkey) {
addUser(pubkey)
setUserInput('')
} else {
setError('Provided npub is not valid. Please enter correct npub.')
}
return
}
2024-05-14 09:27:05 +00:00
if (userInput.includes('@')) {
setIsLoading(true)
setLoadingSpinnerDesc('Querying for nip05')
const nip05Profile = await queryNip05(userInput)
.catch((err) => {
console.error(`error occurred in querying nip05: ${userInput}`, err)
return null
})
.finally(() => {
setIsLoading(false)
setLoadingSpinnerDesc('')
})
if (nip05Profile && nip05Profile.pubkey) {
2024-05-14 09:27:05 +00:00
const pubkey = nip05Profile.pubkey
addUser(pubkey)
setUserInput('')
} else {
setError('Provided nip05 is not valid. Please enter correct nip05.')
}
return
}
setError('Invalid input! Make sure to provide correct npub or nip05.')
}
const handleUserRoleChange = (role: UserRole, pubkey: string) => {
setUsers((prevUsers) =>
prevUsers.map((user) => {
if (user.pubkey === pubkey) {
return {
...user,
role
}
}
return user
})
)
2024-05-14 09:27:05 +00:00
}
const handleRemoveUser = (pubkey: string) => {
setUsers((prev) => prev.filter((user) => user.pubkey !== pubkey))
}
const moveSinger = (dragIndex: number, hoverIndex: number) => {
setUsers((prevUsers) => {
const updatedUsers = [...prevUsers]
const [draggedUser] = updatedUsers.splice(dragIndex, 1)
updatedUsers.splice(hoverIndex, 0, draggedUser)
return updatedUsers
})
}
2024-05-14 09:27:05 +00:00
const handleSelectFiles = (files: File[]) => {
setDisplayUserInput(true)
setSelectedFiles((prev) => {
const prevFileNames = prev.map((file) => file.name)
const newFiles = files.filter(
(file) => !prevFileNames.includes(file.name)
)
2024-05-14 09:27:05 +00:00
return [...prev, ...newFiles]
})
2024-05-14 09:27:05 +00:00
}
2024-05-14 09:27:05 +00:00
const handleRemoveFile = (fileToRemove: File) => {
setSelectedFiles((prevFiles) =>
prevFiles.filter((file) => file.name !== fileToRemove.name)
2024-04-22 11:24:50 +00:00
)
2024-05-14 09:27:05 +00:00
}
2024-04-22 11:24:50 +00:00
2024-05-15 08:41:55 +00:00
const handleCreate = async () => {
2024-05-14 09:27:05 +00:00
if (users.length === 0) {
2024-04-22 11:24:50 +00:00
toast.error(
2024-05-14 09:27:05 +00:00
'No signer/viewer is provided. At least add one signer or viewer.'
2024-04-22 11:24:50 +00:00
)
2024-05-14 09:27:05 +00:00
return
}
2024-04-22 11:24:50 +00:00
2024-05-14 09:27:05 +00:00
if (selectedFiles.length === 0) {
toast.error('No file is selected. Select at least 1 file')
return
}
2024-05-14 09:27:05 +00:00
setIsLoading(true)
setLoadingSpinnerDesc('Generating hashes for files')
const fileHashes: { [key: string]: string } = {}
2024-05-14 09:27:05 +00:00
// generating file hashes
for (const file of selectedFiles) {
const arraybuffer = await file.arrayBuffer().catch((err) => {
console.log(
`err while getting arrayBuffer of file ${file.name} :>> `,
err
)
toast.error(
err.message || `err while getting arrayBuffer of file ${file.name}`
)
return null
})
if (!arraybuffer) return
const hash = await getHash(arraybuffer)
if (!hash) {
setIsLoading(false)
return
}
2024-05-14 09:27:05 +00:00
fileHashes[file.name] = hash
}
2024-05-14 09:27:05 +00:00
const zip = new JSZip()
2024-05-14 09:27:05 +00:00
// zipping files
selectedFiles.forEach((file) => {
zip.file(`files/${file.name}`, file)
})
2024-05-14 10:37:55 +00:00
const signers = users.filter((user) => user.role === UserRole.signer)
const viewers = users.filter((user) => user.role === UserRole.viewer)
2024-05-14 09:27:05 +00:00
setLoadingSpinnerDesc('Signing nostr event')
const signedEvent = await signEventForMetaFile(
fileHashes,
nostrController,
setIsLoading
)
2024-05-14 09:27:05 +00:00
if (!signedEvent) return
2024-05-14 09:27:05 +00:00
// create content for meta file
const meta: Meta = {
signers: signers.map((signer) => hexToNpub(signer.pubkey)),
viewers: viewers.map((viewer) => hexToNpub(viewer.pubkey)),
2024-05-14 09:27:05 +00:00
fileHashes,
submittedBy: hexToNpub(usersPubkey!),
2024-05-14 09:27:05 +00:00
signedEvents: {
[hexToNpub(signedEvent.pubkey)]: JSON.stringify(signedEvent, null, 2)
2024-05-14 09:27:05 +00:00
}
}
2024-05-14 09:27:05 +00:00
try {
const stringifiedMeta = JSON.stringify(meta, null, 2)
zip.file('meta.json', stringifiedMeta)
2024-05-14 09:27:05 +00:00
const metaHash = await getHash(stringifiedMeta)
if (!metaHash) return
2024-04-22 11:24:50 +00:00
2024-05-14 09:27:05 +00:00
const metaHashJson = {
[usersPubkey!]: metaHash
}
zip.file('hashes.json', JSON.stringify(metaHashJson, null, 2))
} catch (err) {
console.error(err)
toast.error('An error occurred in converting meta json to string')
return
2024-04-22 11:24:50 +00:00
}
2024-05-14 09:27:05 +00:00
setLoadingSpinnerDesc('Generating zip file')
2024-04-22 11:24:50 +00:00
2024-05-14 09:27:05 +00:00
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
})
2024-05-14 09:27:05 +00:00
if (!arraybuffer) return
const encryptionKey = await generateEncryptionKey()
setLoadingSpinnerDesc('Encrypting zip file')
const encryptedArrayBuffer = await encryptArrayBuffer(
2024-05-14 09:27:05 +00:00
arraybuffer,
encryptionKey
)
const blob = new Blob([encryptedArrayBuffer])
setLoadingSpinnerDesc('Uploading zip file to file storage.')
const fileUrl = await uploadToFileStorage(blob, nostrController)
.then((url) => {
toast.success('zip file uploaded to file storage')
return url
})
.catch((err) => {
console.log('err in upload:>> ', err)
2024-05-08 14:01:31 +00:00
setIsLoading(false)
toast.error(err.message || 'Error occurred in uploading zip file')
return null
})
if (!fileUrl) return
2024-05-14 09:27:05 +00:00
setLoadingSpinnerDesc('Sending DM to signers/viewers')
// send DM to first signer if exists
2024-05-15 09:55:19 +00:00
const signer =
signers.length > 0 && signers[0].pubkey === usersPubkey
? signers[1]
: signers[0]
if (signer) {
2024-05-14 09:27:05 +00:00
await sendDM(
fileUrl,
encryptionKey,
2024-05-15 09:55:19 +00:00
signer.pubkey,
2024-05-14 09:27:05 +00:00
nostrController,
true,
setAuthUrl
)
} else {
// send DM to all viewers if no signer
for (const viewer of viewers) {
// todo: execute in parallel
await sendDM(
fileUrl,
encryptionKey,
viewer.pubkey,
nostrController,
false,
setAuthUrl
)
}
}
setIsLoading(false)
2024-05-15 08:41:55 +00:00
navigate(
2024-05-16 06:04:19 +00:00
`${appPrivateRoutes.sign}?file=${encodeURIComponent(
2024-05-15 08:41:55 +00:00
fileUrl
)}&key=${encodeURIComponent(encryptionKey)}`
)
}
if (authUrl) {
return (
<iframe
2024-05-15 08:50:21 +00:00
title="Nsecbunker auth"
src={authUrl}
2024-05-15 08:50:21 +00:00
width="100%"
height="500px"
/>
)
}
return (
<>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
<Box className={styles.container}>
2024-05-15 08:50:21 +00:00
<Typography component="label" variant="h6">
2024-05-14 09:27:05 +00:00
Select files
</Typography>
2024-05-14 09:27:05 +00:00
<MuiFileInput
multiple
2024-05-15 08:50:21 +00:00
placeholder="Choose Files"
2024-05-14 09:27:05 +00:00
value={selectedFiles}
onChange={(value) => handleSelectFiles(value)}
/>
<ul>
{selectedFiles.map((file, index) => (
<li key={index}>
2024-05-15 08:50:21 +00:00
<Typography component="label">{file.name}</Typography>
2024-05-14 09:27:05 +00:00
<IconButton onClick={() => handleRemoveFile(file)}>
<Clear style={{ color: 'red' }} />{' '}
</IconButton>
</li>
))}
</ul>
{displayUserInput && (
<>
2024-05-15 08:50:21 +00:00
<Typography component="label" variant="h6">
2024-05-17 11:27:05 +00:00
Add Counterparties
2024-05-14 09:27:05 +00:00
</Typography>
<Box className={styles.inputBlock}>
<TextField
2024-05-15 08:50:21 +00:00
label="nip05 / npub"
2024-05-14 09:27:05 +00:00
value={userInput}
onChange={(e) => setUserInput(e.target.value)}
helperText={error}
error={!!error}
/>
<FormControl fullWidth>
2024-05-15 08:50:21 +00:00
<InputLabel id="select-role-label">Role</InputLabel>
2024-05-14 09:27:05 +00:00
<Select
2024-05-15 08:50:21 +00:00
labelId="select-role-label"
id="demo-simple-select"
2024-05-14 09:27:05 +00:00
value={userRole}
2024-05-15 08:50:21 +00:00
label="Role"
2024-05-14 09:27:05 +00:00
onChange={(e) => setUserRole(e.target.value as UserRole)}
>
<MenuItem value={UserRole.signer}>{UserRole.signer}</MenuItem>
<MenuItem value={UserRole.viewer}>{UserRole.viewer}</MenuItem>
</Select>
</FormControl>
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button
disabled={!userInput}
onClick={handleAddUser}
2024-05-15 08:50:21 +00:00
variant="contained"
2024-05-14 09:27:05 +00:00
>
Add
</Button>
</Box>
</Box>
2024-05-14 09:27:05 +00:00
<DisplayUser
users={users}
handleUserRoleChange={handleUserRoleChange}
handleRemoveUser={handleRemoveUser}
moveSigner={moveSinger}
2024-05-14 09:27:05 +00:00
/>
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleCreate} variant="contained">
2024-05-15 08:41:55 +00:00
Create
2024-05-14 09:27:05 +00:00
</Button>
</Box>
</>
)}
</Box>
</>
)
}
2024-05-14 09:27:05 +00:00
type DisplayUsersProps = {
users: User[]
handleUserRoleChange: (role: UserRole, pubkey: string) => void
2024-05-14 09:27:05 +00:00
handleRemoveUser: (pubkey: string) => void
moveSigner: (dragIndex: number, hoverIndex: number) => void
2024-05-14 09:27:05 +00:00
}
const DisplayUser = ({
users,
handleUserRoleChange,
handleRemoveUser,
moveSigner
2024-05-14 09:27:05 +00:00
}: DisplayUsersProps) => {
const [metadata, setMetadata] = useState<{ [key: string]: ProfileMetadata }>(
{}
)
useEffect(() => {
users.forEach((user) => {
if (!(user.pubkey in metadata)) {
const metadataController = new MetadataController()
metadataController
.findMetadata(user.pubkey)
.then((metadataEvent) => {
const metadataContent =
metadataController.extractProfileMetadataContent(metadataEvent)
if (metadataContent)
setMetadata((prev) => ({
...prev,
[user.pubkey]: metadataContent
}))
})
.catch((err) => {
console.error(
`error occurred in finding metadata for: ${user.pubkey}`,
err
)
})
}
})
}, [users])
return (
<TableContainer component={Paper} elevation={3} sx={{ marginTop: '20px' }}>
<Table>
<TableHead>
<TableRow>
<TableCell className={styles.tableHeaderCell}>User</TableCell>
<TableCell className={styles.tableHeaderCell}>Role</TableCell>
2024-05-14 09:27:05 +00:00
<TableCell>Action</TableCell>
</TableRow>
</TableHead>
<TableBody>
<DndProvider backend={HTML5Backend}>
{users
.filter((user) => user.role === UserRole.signer)
.map((user, index) => (
<SignerRow
userMeta={metadata[user.pubkey]}
user={user}
index={index}
moveSigner={moveSigner}
handleUserRoleChange={handleUserRoleChange}
handleRemoveUser={handleRemoveUser}
/>
))}
</DndProvider>
{users
.filter((user) => user.role === UserRole.viewer)
.map((user, index) => {
const userMeta = metadata[user.pubkey]
return (
<TableRow key={index}>
<TableCell className={styles.tableCell}>
<UserComponent
pubkey={user.pubkey}
name={
userMeta?.display_name ||
userMeta?.name ||
shorten(hexToNpub(user.pubkey))
}
image={userMeta?.picture}
/>
</TableCell>
<TableCell className={styles.tableCell}>
<Select
fullWidth
value={user.role}
onChange={(e) =>
handleUserRoleChange(
e.target.value as UserRole,
user.pubkey
)
}
>
<MenuItem value={UserRole.signer}>
{UserRole.signer}
</MenuItem>
<MenuItem value={UserRole.viewer}>
{UserRole.viewer}
</MenuItem>
</Select>
</TableCell>
<TableCell>
<Tooltip title="Remove User" arrow>
<IconButton onClick={() => handleRemoveUser(user.pubkey)}>
<Clear style={{ color: 'red' }} />
</IconButton>
</Tooltip>
</TableCell>
</TableRow>
)
})}
2024-05-14 09:27:05 +00:00
</TableBody>
</Table>
</TableContainer>
)
}
interface DragItem {
index: number
id: string
type: string
}
type SignerRowProps = {
userMeta: ProfileMetadata
user: User
index: number
moveSigner: (dragIndex: number, hoverIndex: number) => void
handleUserRoleChange: (role: UserRole, pubkey: string) => void
handleRemoveUser: (pubkey: string) => void
}
const SignerRow = ({
userMeta,
user,
index,
moveSigner,
handleUserRoleChange,
handleRemoveUser
}: SignerRowProps) => {
const ref = useRef<HTMLTableRowElement>(null)
const [{ handlerId }, drop] = useDrop<
DragItem,
void,
{ handlerId: Identifier | null }
>({
accept: 'row',
collect(monitor) {
return {
handlerId: monitor.getHandlerId()
}
},
hover(item: DragItem, monitor) {
if (!ref.current) {
return
}
const dragIndex = item.index
const hoverIndex = index
// Don't replace items with themselves
if (dragIndex === hoverIndex) {
return
}
// Determine rectangle on screen
const hoverBoundingRect = ref.current?.getBoundingClientRect()
// Get vertical middle
const hoverMiddleY =
(hoverBoundingRect.bottom - hoverBoundingRect.top) / 2
// Determine mouse position
const clientOffset = monitor.getClientOffset()
// Get pixels to the top
const hoverClientY = (clientOffset as XYCoord).y - hoverBoundingRect.top
// Only perform the move when the mouse has crossed half of the items height
// When dragging downwards, only move when the cursor is below 50%
// When dragging upwards, only move when the cursor is above 50%
// Dragging downwards
if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
return
}
// Dragging upwards
if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
return
}
// Time to actually perform the action
moveSigner(dragIndex, hoverIndex)
// Note: we're mutating the monitor item here!
// Generally it's better to avoid mutations,
// but it's good here for the sake of performance
// to avoid expensive index searches.
item.index = hoverIndex
}
})
const [{ isDragging }, drag] = useDrag({
type: 'row',
item: () => {
return { id: user.pubkey, index }
},
collect: (monitor: any) => ({
isDragging: monitor.isDragging()
})
})
const opacity = isDragging ? 0 : 1
drag(drop(ref))
return (
<TableRow
sx={{ cursor: 'move', opacity }}
data-handler-id={handlerId}
ref={ref}
>
<TableCell
className={styles.tableCell}
sx={{ display: 'flex', alignItems: 'center', gap: '10px' }}
>
<DragHandle />
<UserComponent
pubkey={user.pubkey}
name={
userMeta?.display_name ||
userMeta?.name ||
shorten(hexToNpub(user.pubkey))
}
image={userMeta?.picture}
/>
</TableCell>
<TableCell className={styles.tableCell}>
<Select
fullWidth
value={user.role}
onChange={(e) =>
handleUserRoleChange(e.target.value as UserRole, user.pubkey)
}
>
<MenuItem value={UserRole.signer}>{UserRole.signer}</MenuItem>
<MenuItem value={UserRole.viewer}>{UserRole.viewer}</MenuItem>
</Select>
</TableCell>
<TableCell>
<Tooltip title="Remove User" arrow>
<IconButton onClick={() => handleRemoveUser(user.pubkey)}>
<Clear style={{ color: 'red' }} />
</IconButton>
</Tooltip>
</TableCell>
</TableRow>
)
}