feat: sync and update with all changes from solar-punk-ltd fork (#730)
* fix: swap error caused by invalid id and batchcount * fix: enhance creation messages for admin drive and user drives * fix: identity and wallet creation * fix: asset preview types * fix: fm search unicode text * fix: feed identity and stamp usage * fix: ui display changes * fix: stamp buy and dilute * fix: vite polyfill warning for stream * fix: standard mode postage stamp purchase reserves incorrect size and duration * fix: add syncing message for Bee node and update page state handling * refactor: stamp depth and amount validation --------- Co-authored-by: Balint Ujvari <balint.ujvari@solarpunk.buzz> Co-authored-by: Bálint Ujvári <58116288+bosi95@users.noreply.github.com> Co-authored-by: rolandlor <33499567+rolandlor@users.noreply.github.com>
This commit is contained in:
+4
-1
@@ -1,3 +1,6 @@
|
||||
PORT=3002
|
||||
VITE_BEE_DESKTOP_URL=http://localhost:3054
|
||||
VITE_FORMBRICKS_ENV_ID=
|
||||
VITE_FORMBRICKS_APP_URL=
|
||||
VITE_FORMBRICKS_APP_URL=
|
||||
VITE_DEFAULT_RPC_URL=
|
||||
VITE_BEE_DESKTOP_ENABLED=
|
||||
@@ -23,6 +23,7 @@
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
/**.log
|
||||
|
||||
|
||||
settings.json
|
||||
|
||||
@@ -40,7 +40,7 @@ export default function ExpandableListItem({ label, value, tooltip }: Props): Re
|
||||
)}
|
||||
{value && (
|
||||
<Box flex={1} textAlign="right">
|
||||
<Typography variant="body2">
|
||||
<Typography variant="body2" component="div">
|
||||
{value}
|
||||
{tooltip && (
|
||||
<Tooltip title={tooltip} placement="top" arrow>
|
||||
|
||||
@@ -16,11 +16,17 @@ const useStyles = makeStyles()(theme => ({
|
||||
header: {
|
||||
backgroundColor: theme.palette.background.paper,
|
||||
marginBottom: theme.spacing(0.25),
|
||||
borderLeft: `${theme.spacing(0.25)}px solid rgba(0,0,0,0)`,
|
||||
borderLeft: `${theme.spacing(0.25)} solid rgba(0,0,0,0)`,
|
||||
wordBreak: 'break-word',
|
||||
'&:hover': {
|
||||
backgroundColor: theme.palette.background.paper,
|
||||
},
|
||||
'&:focus-within': {
|
||||
backgroundColor: theme.palette.background.paper,
|
||||
},
|
||||
},
|
||||
headerOpen: {
|
||||
borderLeft: `${theme.spacing(0.25)}px solid ${theme.palette.primary.main}`,
|
||||
borderLeft: `${theme.spacing(0.25)} solid ${theme.palette.primary.main}`,
|
||||
},
|
||||
copyValue: {
|
||||
cursor: 'pointer',
|
||||
@@ -95,35 +101,35 @@ export default function ExpandableListItemInput({
|
||||
}
|
||||
|
||||
return (
|
||||
<ListItemButton className={`${classes.header} ${open ? classes.headerOpen : ''}`}>
|
||||
<Box display="flex" flexDirection="column" width="100%">
|
||||
<Box display="flex" flexDirection="row" alignItems="center" width="100%">
|
||||
{label && (
|
||||
<Box flex={1} minWidth={0}>
|
||||
<Typography variant="body1" className={classes.unselectableLabel} component="span">
|
||||
{label}
|
||||
</Typography>
|
||||
<>
|
||||
<ListItemButton className={`${classes.header} ${open ? classes.headerOpen : ''}`}>
|
||||
<Box display="flex" flexDirection="column" width="100%">
|
||||
<Box display="flex" flexDirection="row" alignItems="center" width="100%">
|
||||
{label && (
|
||||
<Box flex={1} minWidth={0}>
|
||||
<Typography variant="body1" className={classes.unselectableLabel} component="span">
|
||||
{label}
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
<Box flex={3} display="flex" alignItems="center" justifyContent="flex-end" minWidth={0} gap={1}>
|
||||
{!open && value && (
|
||||
<Typography
|
||||
variant="body2"
|
||||
component="span"
|
||||
sx={{ minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
|
||||
>
|
||||
{value}
|
||||
</Typography>
|
||||
)}
|
||||
{!expandedOnly && !locked && (
|
||||
<IconButton size="small" className={classes.copyValue} onClick={toggleOpen}>
|
||||
{open ? <Minus strokeWidth={1} /> : <Edit strokeWidth={1} />}
|
||||
</IconButton>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
<Box flex={3} display="flex" alignItems="center" justifyContent="flex-end" minWidth={0} gap={1}>
|
||||
{!open && value && (
|
||||
<Typography
|
||||
variant="body2"
|
||||
component="span"
|
||||
sx={{ minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
|
||||
>
|
||||
{value}
|
||||
</Typography>
|
||||
)}
|
||||
{!expandedOnly && !locked && (
|
||||
<IconButton size="small" className={classes.copyValue} onClick={toggleOpen}>
|
||||
{open ? <Minus strokeWidth={1} /> : <Edit strokeWidth={1} />}
|
||||
</IconButton>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
<Collapse in={open} timeout="auto" unmountOnExit>
|
||||
<Box display="flex" flexDirection="column" width="100%">
|
||||
<Collapse in={open} timeout="auto" unmountOnExit>
|
||||
<Box display="flex" alignItems="center" width="100%" minWidth={0}>
|
||||
<InputBase
|
||||
value={inputValue}
|
||||
@@ -146,36 +152,38 @@ export default function ExpandableListItemInput({
|
||||
/>
|
||||
</Box>
|
||||
{helperText && <ExpandableListItemNote>{helperText}</ExpandableListItemNote>}
|
||||
<Box mt={2}>
|
||||
<ExpandableListItemActions>
|
||||
<SwarmButton
|
||||
disabled={
|
||||
loading ||
|
||||
inputValue === value ||
|
||||
Boolean(confirmLabelDisabled) ||
|
||||
(inputValue === '' && value === undefined)
|
||||
}
|
||||
loading={loading}
|
||||
iconType={confirmIcon ?? Check}
|
||||
onClick={() => {
|
||||
onConfirm?.(inputValue.trim())
|
||||
}}
|
||||
>
|
||||
{confirmLabel || 'Save'}
|
||||
</SwarmButton>
|
||||
<SwarmButton
|
||||
disabled={loading || inputValue === value || inputValue === ''}
|
||||
iconType={X}
|
||||
onClick={() => setInputValue(value || '')}
|
||||
cancel
|
||||
>
|
||||
Cancel
|
||||
</SwarmButton>
|
||||
</ExpandableListItemActions>
|
||||
</Box>
|
||||
</Box>
|
||||
</Collapse>
|
||||
</Box>
|
||||
</ListItemButton>
|
||||
</Collapse>
|
||||
</Box>
|
||||
</ListItemButton>
|
||||
<Collapse in={open} timeout="auto" unmountOnExit>
|
||||
<Box mt={2}>
|
||||
<ExpandableListItemActions>
|
||||
<SwarmButton
|
||||
disabled={
|
||||
loading ||
|
||||
inputValue === value ||
|
||||
Boolean(confirmLabelDisabled) ||
|
||||
(inputValue === '' && value === undefined)
|
||||
}
|
||||
loading={loading}
|
||||
iconType={confirmIcon ?? Check}
|
||||
onClick={() => {
|
||||
onConfirm?.(inputValue.trim())
|
||||
}}
|
||||
>
|
||||
{confirmLabel || 'Save'}
|
||||
</SwarmButton>
|
||||
<SwarmButton
|
||||
disabled={loading || inputValue === value || inputValue === ''}
|
||||
iconType={X}
|
||||
onClick={() => setInputValue(value || '')}
|
||||
cancel
|
||||
>
|
||||
Cancel
|
||||
</SwarmButton>
|
||||
</ExpandableListItemActions>
|
||||
</Box>
|
||||
</Collapse>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -10,11 +10,17 @@ const useStyles = makeStyles()(theme => ({
|
||||
header: {
|
||||
backgroundColor: theme.palette.background.paper,
|
||||
marginBottom: theme.spacing(0.25),
|
||||
borderLeft: `${theme.spacing(0.25)}px solid rgba(0,0,0,0)`,
|
||||
borderLeft: `${theme.spacing(0.25)} solid rgba(0,0,0,0)`,
|
||||
wordBreak: 'break-word',
|
||||
'&:hover': {
|
||||
backgroundColor: theme.palette.background.paper,
|
||||
},
|
||||
'&:focus-within': {
|
||||
backgroundColor: theme.palette.background.paper,
|
||||
},
|
||||
},
|
||||
headerOpen: {
|
||||
borderLeft: `${theme.spacing(0.25)}px solid ${theme.palette.primary.main}`,
|
||||
borderLeft: `${theme.spacing(0.25)} solid ${theme.palette.primary.main}`,
|
||||
},
|
||||
copyValue: {
|
||||
cursor: 'pointer',
|
||||
@@ -69,7 +75,7 @@ export default function ExpandableListItemKey({ label, value, expanded }: Props)
|
||||
|
||||
return (
|
||||
<ListItemButton className={`${classes.header} ${open ? classes.headerOpen : ''}`}>
|
||||
<Grid container direction="column" justifyContent="space-between" alignItems="stretch">
|
||||
<Grid container direction="column" justifyContent="space-between" alignItems="stretch" style={{ width: '100%' }}>
|
||||
<Grid container direction="row" justifyContent="space-between" alignItems="center">
|
||||
{label && (
|
||||
<Typography variant="body1" component="span">
|
||||
|
||||
@@ -10,11 +10,17 @@ const useStyles = makeStyles()(theme => ({
|
||||
header: {
|
||||
backgroundColor: theme.palette.background.paper,
|
||||
marginBottom: theme.spacing(0.25),
|
||||
borderLeft: `${theme.spacing(0.25)}px solid rgba(0,0,0,0)`,
|
||||
borderLeft: `${theme.spacing(0.25)} solid rgba(0,0,0,0)`,
|
||||
wordBreak: 'break-word',
|
||||
'&:hover': {
|
||||
backgroundColor: theme.palette.background.paper,
|
||||
},
|
||||
'&:focus-within': {
|
||||
backgroundColor: theme.palette.background.paper,
|
||||
},
|
||||
},
|
||||
headerOpen: {
|
||||
borderLeft: `${theme.spacing(0.25)}px solid ${theme.palette.primary.main}`,
|
||||
borderLeft: `${theme.spacing(0.25)} solid ${theme.palette.primary.main}`,
|
||||
},
|
||||
openLinkIcon: {
|
||||
cursor: 'pointer',
|
||||
|
||||
@@ -139,7 +139,7 @@ export default function SideBar(): ReactElement {
|
||||
label: 'File Manager',
|
||||
path: ROUTES.FILEMANAGER,
|
||||
icon: FileManagerIcon,
|
||||
pathMatcherSubstring: '/filemanager/',
|
||||
pathMatcherSubstring: '/filemanager',
|
||||
},
|
||||
{
|
||||
label: 'Account',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { BatchId, Bee } from '@ethersphere/bee-js'
|
||||
import { Bee, PostageBatch } from '@ethersphere/bee-js'
|
||||
import { Box } from '@mui/material'
|
||||
import Button from '@mui/material/Button'
|
||||
import Dialog from '@mui/material/Dialog'
|
||||
@@ -8,19 +8,48 @@ import DialogTitle from '@mui/material/DialogTitle'
|
||||
import Input from '@mui/material/Input'
|
||||
import { useSnackbar } from 'notistack'
|
||||
import React, { ReactElement, ReactNode, useState } from 'react'
|
||||
import { makeStyles } from 'tss-react/mui'
|
||||
|
||||
interface Props {
|
||||
type: 'Topup' | 'Dilute'
|
||||
icon: ReactNode
|
||||
bee: Bee
|
||||
stamp: BatchId
|
||||
import { CheckState } from '../providers/Bee'
|
||||
|
||||
const useStyles = makeStyles()(theme => ({
|
||||
buttonSelected: {
|
||||
color: 'white',
|
||||
backgroundColor: theme.palette.primary.main,
|
||||
'&:hover': {
|
||||
color: theme.palette.secondary.main,
|
||||
backgroundColor: 'white',
|
||||
'@media (hover: none)': {
|
||||
color: 'white',
|
||||
backgroundColor: theme.palette.primary.main,
|
||||
},
|
||||
},
|
||||
},
|
||||
buttonUnselected: {
|
||||
color: '#dd7700',
|
||||
backgroundColor: 'white',
|
||||
},
|
||||
}))
|
||||
|
||||
export enum StampExtensionType {
|
||||
Topup = 'Topup',
|
||||
Dilute = 'Dilute',
|
||||
}
|
||||
|
||||
export default function StampExtensionModal({ type, icon, bee, stamp }: Props): ReactElement {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [amount, setAmount] = useState('')
|
||||
interface Props {
|
||||
type: StampExtensionType
|
||||
icon: ReactNode
|
||||
bee: Bee
|
||||
stamp: PostageBatch
|
||||
status: CheckState
|
||||
}
|
||||
|
||||
export default function StampExtensionModal({ type, icon, bee, stamp, status }: Props): ReactElement {
|
||||
const { classes } = useStyles()
|
||||
const [open, setOpen] = useState<boolean>(false)
|
||||
const [amount, setAmount] = useState<string>('')
|
||||
const { enqueueSnackbar } = useSnackbar()
|
||||
const label = `${type} ${stamp.toHex().substring(0, 8)}`
|
||||
const label = `${type} ${stamp.batchID.toHex().substring(0, 8)}`
|
||||
|
||||
const handleClickOpen = (e: React.MouseEvent<HTMLButtonElement>) => {
|
||||
setOpen(true)
|
||||
@@ -32,23 +61,65 @@ export default function StampExtensionModal({ type, icon, bee, stamp }: Props):
|
||||
}
|
||||
|
||||
const handleAction = async () => {
|
||||
if (type === 'Topup') {
|
||||
if (status !== CheckState.OK) {
|
||||
enqueueSnackbar(`Node connection status is not ${CheckState.OK}: ${status}`, { variant: 'error' })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (type === StampExtensionType.Topup) {
|
||||
const isAmountInvalid = BigInt(amount) <= BigInt(0)
|
||||
|
||||
if (isAmountInvalid) {
|
||||
enqueueSnackbar(`Invalid amount: ${amount}, it must be greate than 0`, { variant: 'error' })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await bee.topUpBatch(stamp, amount)
|
||||
await bee.topUpBatch(stamp.batchID, amount)
|
||||
enqueueSnackbar(`Successfully topped up stamp, your changes will appear soon`, { variant: 'success' })
|
||||
} catch (error) {
|
||||
enqueueSnackbar(`Failed to topup stamp: ${error || 'Unknown reason'}`, { variant: 'error' })
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (type === 'Dilute') {
|
||||
if (type === StampExtensionType.Dilute) {
|
||||
const newDepth = parseInt(amount, 10)
|
||||
const ttlDays = stamp.duration.toDays()
|
||||
const currentDepth = stamp.depth
|
||||
const maxHalvings = Math.floor(Math.log2(ttlDays)) + currentDepth
|
||||
const isDepthInvalid = newDepth > maxHalvings || newDepth <= currentDepth
|
||||
|
||||
if (isDepthInvalid) {
|
||||
enqueueSnackbar(`Invalid depth: ${newDepth} (${currentDepth} < new depth < ${maxHalvings})`, {
|
||||
variant: 'error',
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (ttlDays <= 2) {
|
||||
enqueueSnackbar(`TTL: ${ttlDays} <= 2 days, cannot dilute stamp (min. TTL is 1 day)`, {
|
||||
variant: 'warning',
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await bee.diluteBatch(stamp, parseInt(amount, 10))
|
||||
await bee.diluteBatch(stamp.batchID, newDepth)
|
||||
enqueueSnackbar(`Successfully diluted stamp, your changes will appear soon`, { variant: 'success' })
|
||||
} catch (error) {
|
||||
enqueueSnackbar(`Failed to dilute stamp: ${error || 'Unknown reason'}`, { variant: 'error' })
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
enqueueSnackbar(`Failed to extend stamp, unknown operation: ${type}`, { variant: 'error' })
|
||||
}
|
||||
|
||||
const handleChange = (event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
|
||||
@@ -57,7 +128,7 @@ export default function StampExtensionModal({ type, icon, bee, stamp }: Props):
|
||||
|
||||
return (
|
||||
<Box mb={2}>
|
||||
<Button variant="contained" onClick={handleClickOpen} startIcon={icon}>
|
||||
<Button className={classes.buttonSelected} variant="contained" onClick={handleClickOpen} startIcon={icon}>
|
||||
{type}
|
||||
</Button>
|
||||
<Dialog open={open} onClose={handleClose} aria-labelledby="form-dialog-title">
|
||||
@@ -68,7 +139,7 @@ export default function StampExtensionModal({ type, icon, bee, stamp }: Props):
|
||||
margin="dense"
|
||||
id="name"
|
||||
type="text"
|
||||
placeholder={type === 'Topup' ? 'Amount to add' : 'New depth to dilute'}
|
||||
placeholder={type === StampExtensionType.Topup ? 'Amount to add' : 'New depth to dilute'}
|
||||
fullWidth
|
||||
value={amount}
|
||||
onChange={handleChange}
|
||||
@@ -78,7 +149,14 @@ export default function StampExtensionModal({ type, icon, bee, stamp }: Props):
|
||||
<Button onClick={handleClose} color="primary">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button disabled={amount === ''} onClick={handleAction} color="primary">
|
||||
<Button
|
||||
disabled={amount === ''}
|
||||
onClick={async () => {
|
||||
await handleAction()
|
||||
handleClose()
|
||||
}}
|
||||
color="primary"
|
||||
>
|
||||
{type}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
|
||||
@@ -75,6 +75,7 @@ export function SwarmSelect({
|
||||
value={value}
|
||||
className={classes.select}
|
||||
displayEmpty
|
||||
onChange={onChange}
|
||||
renderValue={(value: unknown) => (value ? renderValue(value) : placeholder)}
|
||||
MenuProps={{ MenuListProps: { disablePadding: true }, PaperProps: { square: true } }}
|
||||
>
|
||||
|
||||
@@ -57,7 +57,7 @@ export function SwarmTextInput({
|
||||
variant="filled"
|
||||
className={classes.field}
|
||||
defaultValue={defaultValue || ''}
|
||||
InputProps={{ disableUnderline: true }}
|
||||
slotProps={{ input: { disableUnderline: true } }}
|
||||
placeholder={placeholder}
|
||||
/>
|
||||
)
|
||||
@@ -73,7 +73,7 @@ export function SwarmTextInput({
|
||||
className={classes.field}
|
||||
defaultValue={defaultValue || ''}
|
||||
onChange={onChange}
|
||||
InputProps={{ disableUnderline: true }}
|
||||
slotProps={{ input: { disableUnderline: true } }}
|
||||
placeholder={placeholder}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -24,14 +24,14 @@ const useStyles = makeStyles()(theme => ({
|
||||
},
|
||||
},
|
||||
buttonSelected: {
|
||||
color: 'white',
|
||||
backgroundColor: theme.palette.primary.main,
|
||||
color: theme.palette.secondary.main,
|
||||
backgroundColor: 'white',
|
||||
'&:hover': {
|
||||
color: theme.palette.secondary.main,
|
||||
backgroundColor: 'white',
|
||||
color: 'white',
|
||||
backgroundColor: theme.palette.primary.main,
|
||||
'@media (hover: none)': {
|
||||
color: 'white',
|
||||
backgroundColor: theme.palette.primary.main,
|
||||
color: theme.palette.secondary.main,
|
||||
backgroundColor: 'white',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -12,3 +12,5 @@ export const BEE_DESKTOP_LATEST_RELEASE_PAGE_API =
|
||||
'https://api.github.com/repos/ethersphere/bee-desktop/releases/latest'
|
||||
export const DEFAULT_BEE_API_HOST = 'http://localhost:1633'
|
||||
export const DEFAULT_RPC_URL = 'https://xdai.fairdatasociety.org'
|
||||
export const MIN_STAMP_DEPTH = 17
|
||||
export const MAX_STAMP_DEPTH = 255
|
||||
|
||||
@@ -179,7 +179,13 @@ export function AdminStatusBar({
|
||||
const isBusy = loading || isUpgrading || isCreationInProgress
|
||||
const blurCls = isBusy ? ' is-loading' : ''
|
||||
const statusVerb = isCreationInProgress ? 'Creating' : 'Loading'
|
||||
const statusText = statusVerb + ' admin drive, please do not reload'
|
||||
const statusText = (
|
||||
<>
|
||||
{statusVerb} admin drive — please do not reload the page.
|
||||
<br />
|
||||
This may take a few minutes.
|
||||
</>
|
||||
)
|
||||
|
||||
const renderModalsAndOverlays = () => {
|
||||
return (
|
||||
|
||||
@@ -15,7 +15,7 @@ interface ConfirmModalProps {
|
||||
onCancel?: () => void
|
||||
showFooter?: boolean
|
||||
isProgress?: boolean
|
||||
spinnerMessage?: string
|
||||
spinnerMessage?: React.ReactNode
|
||||
showMinimize?: boolean
|
||||
onMinimize?: () => void
|
||||
background?: boolean
|
||||
|
||||
+1
-2
@@ -3,8 +3,7 @@ import DownIcon from 'remixicon-react/ArrowDownSLineIcon'
|
||||
|
||||
import { BulkActionsResult } from '../../../hooks/useBulkActions'
|
||||
import { SortDir, SortKey } from '../../../hooks/useSorting'
|
||||
|
||||
import { capitalizeFirstLetter } from '@/modules/filemanager/utils/common'
|
||||
import { capitalizeFirstLetter } from '../../../utils/common'
|
||||
|
||||
interface FileBrowserHeaderProps {
|
||||
isSearchMode: boolean
|
||||
|
||||
@@ -3,6 +3,7 @@ import { ReactElement, useState } from 'react'
|
||||
import CheckDoubleLineIcon from 'remixicon-react/CheckDoubleLineIcon'
|
||||
import ClipboardIcon from 'remixicon-react/FileCopyLineIcon'
|
||||
|
||||
import { uuidV4 } from '../../../../utils'
|
||||
import { TOOLTIPS } from '../../constants/tooltips'
|
||||
import { getSigner, setSignerPk } from '../../utils/common'
|
||||
import { Button } from '../Button/Button'
|
||||
@@ -10,8 +11,6 @@ import { Tooltip } from '../Tooltip/Tooltip'
|
||||
|
||||
import './PrivateKeyModal.scss'
|
||||
|
||||
import { uuidV4 } from '@/utils'
|
||||
|
||||
type Props = { onSaved: () => void }
|
||||
|
||||
const generateNewPrivateKey = (): string => {
|
||||
|
||||
@@ -305,7 +305,11 @@ export function Sidebar({ setErrorMessage, loading }: SidebarProps): ReactElemen
|
||||
</div>
|
||||
|
||||
{isDriveCreationInProgress && (
|
||||
<div className="fm-sidebar-drive-creation">Creating drive, please do not reload</div>
|
||||
<div className="fm-sidebar-drive-creation">
|
||||
Creating drive — please do not reload the page.
|
||||
<br />
|
||||
This may take a few minutes.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -26,7 +26,7 @@ interface UseFileFilteringReturn {
|
||||
export function useFileFiltering(props: UseFileFilteringProps): UseFileFilteringReturn {
|
||||
const { files, currentDrive, view, isSearchMode, query, scope, includeActive, includeTrashed } = props
|
||||
|
||||
const q = query.trim().toLowerCase()
|
||||
const q = query.trim().toLowerCase().normalize('NFC')
|
||||
|
||||
const statusIncluded = useCallback(
|
||||
(fi: FileInfo): boolean => {
|
||||
@@ -44,9 +44,11 @@ export function useFileFiltering(props: UseFileFilteringProps): UseFileFiltering
|
||||
const matchesQuery = useCallback(
|
||||
(fi: FileInfo): boolean => {
|
||||
if (!q) return true
|
||||
const name = fi.name.toLowerCase()
|
||||
const mime = (fi.customMetadata?.mime || '').toLowerCase()
|
||||
const topic = String(fi.topic ?? '').toLowerCase()
|
||||
const name = fi.name.toLowerCase().normalize('NFC')
|
||||
const mime = (fi.customMetadata?.mime || '').toLowerCase().normalize('NFC')
|
||||
const topic = String(fi.topic ?? '')
|
||||
.toLowerCase()
|
||||
.normalize('NFC')
|
||||
|
||||
return name.includes(q) || mime.includes(q) || topic.includes(q)
|
||||
},
|
||||
|
||||
@@ -2,7 +2,7 @@ import { ReactElement } from 'react'
|
||||
import FileIcon from 'remixicon-react/FileTextLineIcon'
|
||||
import ImageIcon from 'remixicon-react/Image2LineIcon'
|
||||
|
||||
import { guessMime } from './view'
|
||||
import { guessMime } from '../../../utils/file'
|
||||
|
||||
interface ContextMenuProps {
|
||||
name: string
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { FileInfo, FileManager } from '@solarpunkltd/file-manager-lib'
|
||||
|
||||
import { guessMime, VIEWERS } from '../../../utils/file'
|
||||
import { DownloadProgress, DownloadState } from '../constants/transfers'
|
||||
|
||||
import { AbortManager } from './abortManager'
|
||||
import { isDirectoryPickerSupported, isPickerSupported } from './fileOperations'
|
||||
import { guessMime, VIEWERS } from './view'
|
||||
|
||||
const DefaultDownloadFolder = 'downloads'
|
||||
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
const EXT_TO_MIME: Record<string, string> = {
|
||||
mp4: 'video/mp4',
|
||||
webm: 'video/webm',
|
||||
ogv: 'video/ogg',
|
||||
mp3: 'audio/mpeg',
|
||||
m4a: 'audio/mp4',
|
||||
aac: 'audio/aac',
|
||||
wav: 'audio/wav',
|
||||
ogg: 'audio/ogg',
|
||||
png: 'image/png',
|
||||
jpg: 'image/jpeg',
|
||||
jpeg: 'image/jpeg',
|
||||
gif: 'image/gif',
|
||||
webp: 'image/webp',
|
||||
avif: 'image/avif',
|
||||
svg: 'image/svg+xml',
|
||||
pdf: 'application/pdf',
|
||||
txt: 'text/plain',
|
||||
md: 'text/markdown',
|
||||
json: 'application/json',
|
||||
csv: 'text/csv',
|
||||
html: 'text/html',
|
||||
htm: 'text/html',
|
||||
}
|
||||
|
||||
export function getExtensionFromName(name: string): string {
|
||||
const ext = name.split('.').pop()?.toLowerCase() || ''
|
||||
const hasExtension = name.includes('.') && ext && ext !== name
|
||||
|
||||
return hasExtension ? ext : ''
|
||||
}
|
||||
|
||||
export function guessMime(name: string, mtdt?: Record<string, string> | undefined): { mime: string; ext: string } {
|
||||
const md = mtdt?.mimeType || mtdt?.mime || mtdt?.['content-type']
|
||||
const ext = getExtensionFromName(name)
|
||||
|
||||
if (md) return { mime: md, ext }
|
||||
|
||||
const mime = EXT_TO_MIME[ext] || 'application/octet-stream'
|
||||
|
||||
return { mime, ext }
|
||||
}
|
||||
|
||||
export type Viewer = {
|
||||
name: string
|
||||
test: (mime: string) => boolean
|
||||
render: (win: Window, url: string, mime: string, name: string) => void
|
||||
}
|
||||
|
||||
const VIDEO_HTML = (u: string, title: string) =>
|
||||
`<html><head><meta charset="utf-8"/><title>${title}</title></head><body style="margin:0;background:#000">
|
||||
<video controls autoplay style="width:100%;height:100%" src="${u}"></video>
|
||||
</body></html>`
|
||||
|
||||
const AUDIO_HTML = (u: string, title: string) =>
|
||||
`<html><head><meta charset="utf-8"/><title>${title}</title></head><body>
|
||||
<audio controls autoplay style="width:100%" src="${u}"></audio>
|
||||
</body></html>`
|
||||
|
||||
const IMAGE_HTML = (u: string, title: string) =>
|
||||
`<html><head><meta charset="utf-8"/><title>${title}</title></head><body style="margin:0;background:#111;display:grid;place-items:center;min-height:100vh">
|
||||
<img style="max-width:100%;max-height:100vh" src="${u}" />
|
||||
</body></html>`
|
||||
|
||||
export const VIEWERS: Viewer[] = [
|
||||
{
|
||||
name: 'video',
|
||||
test: m => m.startsWith('video/'),
|
||||
render: (w, url, mime, name) => {
|
||||
w.document.write(VIDEO_HTML(url, name))
|
||||
w.document.title = name
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'audio',
|
||||
test: m => m.startsWith('audio/'),
|
||||
render: (w, url, mime, name) => {
|
||||
w.document.write(AUDIO_HTML(url, name))
|
||||
w.document.title = name
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'image',
|
||||
test: m => m.startsWith('image/'),
|
||||
render: (w, url, mime, name) => {
|
||||
w.document.write(IMAGE_HTML(url, name))
|
||||
w.document.title = name
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'pdf',
|
||||
test: m => m === 'application/pdf',
|
||||
render: (w, url, mime, name) => {
|
||||
w.document.title = name
|
||||
w.location.href = url
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'html',
|
||||
test: m => m === 'text/html',
|
||||
render: (w, url, mime, name) => {
|
||||
w.document.title = name
|
||||
w.location.href = url
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'text-like',
|
||||
test: m => m.startsWith('text/') || m === 'application/json' || m === 'text/markdown',
|
||||
render: (w, url, mime, name) => {
|
||||
w.document.title = name
|
||||
w.location.href = url
|
||||
},
|
||||
},
|
||||
]
|
||||
@@ -104,7 +104,7 @@ export function AccountFeeds(): ReactElement {
|
||||
{x.feedHash && <ExpandableListItemKey label="Feed hash" value={x.feedHash} />}
|
||||
<Box mt={0.75}>
|
||||
<ExpandableListItemActions>
|
||||
<SwarmButton onClick={() => viewFeed(x.uuid)} iconType={Info}>
|
||||
<SwarmButton onClick={() => viewFeed(x.uuid)} iconType={Info} disabled={Boolean(!x.feedHash)}>
|
||||
View Feed Page
|
||||
</SwarmButton>
|
||||
<SwarmButton onClick={() => onShowExport(x)} iconType={Download}>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { NULL_TOPIC } from '@ethersphere/bee-js'
|
||||
import { NULL_TOPIC, PostageBatch } from '@ethersphere/bee-js'
|
||||
import { Box, Grid, Typography } from '@mui/material'
|
||||
import { Wallet } from 'ethers'
|
||||
import { Form, Formik } from 'formik'
|
||||
import { useSnackbar } from 'notistack'
|
||||
import { ReactElement, useContext, useState } from 'react'
|
||||
@@ -12,7 +13,7 @@ import ExpandableListItemActions from '../../components/ExpandableListItemAction
|
||||
import ExpandableListItemKey from '../../components/ExpandableListItemKey'
|
||||
import { HistoryHeader } from '../../components/HistoryHeader'
|
||||
import { SwarmButton } from '../../components/SwarmButton'
|
||||
import { SwarmSelect } from '../../components/SwarmSelect'
|
||||
import { SelectEvent, SwarmSelect } from '../../components/SwarmSelect'
|
||||
import { SwarmTextInput } from '../../components/SwarmTextInput'
|
||||
import { Context as FeedsContext, IdentityType } from '../../providers/Feeds'
|
||||
import { Context as SettingsContext } from '../../providers/Settings'
|
||||
@@ -34,7 +35,8 @@ const initialValues: FormValues = {
|
||||
export default function CreateNewFeed(): ReactElement {
|
||||
const { beeApi } = useContext(SettingsContext)
|
||||
const { identities, setIdentities } = useContext(FeedsContext)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [identityType, setIdentityType] = useState<IdentityType>(IdentityType.PrivateKey)
|
||||
const [loading, setLoading] = useState<boolean>(false)
|
||||
const { enqueueSnackbar } = useSnackbar()
|
||||
|
||||
const navigate = useNavigate()
|
||||
@@ -48,11 +50,24 @@ export default function CreateNewFeed(): ReactElement {
|
||||
|
||||
return
|
||||
}
|
||||
const wallet = generateWallet()
|
||||
const stamps = await beeApi.getPostageBatches()
|
||||
|
||||
let stamps: PostageBatch[] = []
|
||||
let wallet: Wallet
|
||||
|
||||
try {
|
||||
wallet = generateWallet()
|
||||
stamps = (await beeApi.getPostageBatches()).filter(s => s.usable)
|
||||
} catch (err) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(err)
|
||||
enqueueSnackbar(<span>Error during wallet generation or postage stamp retrieval!</span>, { variant: 'error' })
|
||||
setLoading(false)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (!stamps || !stamps.length) {
|
||||
enqueueSnackbar(<span>No stamp available</span>, { variant: 'error' })
|
||||
enqueueSnackbar(<span>No usable stamp available</span>, { variant: 'error' })
|
||||
setLoading(false)
|
||||
|
||||
return
|
||||
@@ -65,17 +80,29 @@ export default function CreateNewFeed(): ReactElement {
|
||||
return
|
||||
}
|
||||
|
||||
const identity = await convertWalletToIdentity(wallet, values.type, values.identityName, values.password)
|
||||
persistIdentity(identities, identity)
|
||||
setIdentities(identities)
|
||||
navigate(ROUTES.ACCOUNT_FEEDS)
|
||||
setLoading(false)
|
||||
try {
|
||||
const identity = await convertWalletToIdentity(wallet, values.type, values.identityName, values.password)
|
||||
persistIdentity(identities, identity)
|
||||
setIdentities(identities)
|
||||
navigate(ROUTES.ACCOUNT_FEEDS)
|
||||
} catch (err) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(err)
|
||||
enqueueSnackbar(<span>Error identity creation!</span>, { variant: 'error' })
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
function cancel() {
|
||||
navigate(-1)
|
||||
}
|
||||
|
||||
function onIdentityTypeChange(event: SelectEvent) {
|
||||
const type = event.target.value as IdentityType
|
||||
setIdentityType(type)
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<HistoryHeader>Create new feed</HistoryHeader>
|
||||
@@ -102,10 +129,13 @@ export default function CreateNewFeed(): ReactElement {
|
||||
<SwarmSelect
|
||||
formik
|
||||
name="type"
|
||||
label={'type'}
|
||||
value={identityType}
|
||||
options={[
|
||||
{ label: 'Keypair Only', value: IdentityType.PrivateKey },
|
||||
{ label: 'Password Protected', value: IdentityType.V3 },
|
||||
]}
|
||||
onChange={onIdentityTypeChange}
|
||||
/>
|
||||
</Box>
|
||||
{values.type === IdentityType.V3 && <SwarmTextInput name="password" label="Password" password formik />}
|
||||
|
||||
@@ -26,8 +26,8 @@ export default function UpdateFeed(): ReactElement {
|
||||
const { status } = useContext(BeeContext)
|
||||
const { hash } = useParams()
|
||||
|
||||
const [selectedStamp, setSelectedStamp] = useState<string | null>(null)
|
||||
const [selectedIdentity, setSelectedIdentity] = useState<Identity | null>(null)
|
||||
const [selectedStamp, setSelectedStamp] = useState<string | null>(stamps ? stamps[0]?.batchID.toHex() : null)
|
||||
const [selectedIdentity, setSelectedIdentity] = useState<Identity | null>(identities[0] ?? null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const { enqueueSnackbar } = useSnackbar()
|
||||
const [showPasswordPrompt, setShowPasswordPrompt] = useState(false)
|
||||
@@ -119,19 +119,28 @@ export default function UpdateFeed(): ReactElement {
|
||||
<HistoryHeader>Update feed</HistoryHeader>
|
||||
<Box mb={2}>
|
||||
<Grid container>
|
||||
<SwarmSelect
|
||||
options={identities.map(x => ({ value: x.uuid, label: `${x.name} Website` }))}
|
||||
onChange={onFeedChange}
|
||||
label="Feed"
|
||||
/>
|
||||
{identities && identities.length ? (
|
||||
<SwarmSelect
|
||||
value={selectedIdentity?.uuid ?? ''}
|
||||
options={identities.map(x => ({ value: x.uuid, label: `${x.name} Website` }))}
|
||||
onChange={onFeedChange}
|
||||
label="Feed"
|
||||
/>
|
||||
) : (
|
||||
<Typography>You need to create an identiy first to be able to update its feed.</Typography>
|
||||
)}
|
||||
</Grid>
|
||||
</Box>
|
||||
|
||||
<Box mb={4}>
|
||||
<Grid container>
|
||||
{stamps ? (
|
||||
{stamps && stamps.length ? (
|
||||
<SwarmSelect
|
||||
options={stamps.map(x => ({ value: x.batchID.toHex(), label: x.batchID.toHex().slice(0, 8) }))}
|
||||
value={selectedStamp ?? ''}
|
||||
options={stamps.map(x => ({
|
||||
value: x.batchID.toHex(),
|
||||
label: x.label ? x.batchID.toHex().slice(0, 8) + ` (${x.label})` : x.batchID.toHex().slice(0, 8),
|
||||
}))}
|
||||
onChange={onStampChange}
|
||||
label="Stamp"
|
||||
/>
|
||||
|
||||
@@ -104,7 +104,7 @@ export default function Feeds(): ReactElement {
|
||||
{x.feedHash && <ExpandableListItemKey label="Feed hash" value={x.feedHash} />}
|
||||
<Box mt={0.75}>
|
||||
<ExpandableListItemActions>
|
||||
<SwarmButton onClick={() => viewFeed(x.uuid)} iconType={Info}>
|
||||
<SwarmButton onClick={() => viewFeed(x.uuid)} iconType={Info} disabled={Boolean(!x.feedHash)}>
|
||||
View Feed Page
|
||||
</SwarmButton>
|
||||
<SwarmButton onClick={() => onShowExport(x)} iconType={Download}>
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
import { DriveInfo, FileManagerBase } from '@solarpunkltd/file-manager-lib'
|
||||
import { ReactElement, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
|
||||
|
||||
import { AdminStatusBar } from '../../modules/filemanager/components/AdminStatusBar/AdminStatusBar'
|
||||
import { Button } from '../../modules/filemanager/components/Button/Button'
|
||||
import { ConfirmModal } from '../../modules/filemanager/components/ConfirmModal/ConfirmModal'
|
||||
import { ErrorModal } from '../../modules/filemanager/components/ErrorModal/ErrorModal'
|
||||
import { FileBrowser } from '../../modules/filemanager/components/FileBrowser/FileBrowser'
|
||||
import { FormbricksIntegration } from '../../modules/filemanager/components/FormbricksIntegration/FormbricksIntegration'
|
||||
import { Header } from '../../modules/filemanager/components/Header/Header'
|
||||
import { InitialModal } from '../../modules/filemanager/components/InitialModal/InitialModal'
|
||||
import { PrivateKeyModal } from '../../modules/filemanager/components/PrivateKeyModal/PrivateKeyModal'
|
||||
import { Sidebar } from '../../modules/filemanager/components/Sidebar/Sidebar'
|
||||
import { getSignerPk, removeSignerPk } from '../../modules/filemanager/utils/common'
|
||||
import { CheckState, Context as BeeContext } from '../../providers/Bee'
|
||||
import { Context as FMContext } from '../../providers/FileManager'
|
||||
import { BrowserPlatform, cacheClearUrls, detectBrowser } from '../../providers/Platform'
|
||||
|
||||
import { SearchProvider } from './SearchContext'
|
||||
import { ViewProvider } from './ViewContext'
|
||||
|
||||
import './FileManager.scss'
|
||||
|
||||
import { AdminStatusBar } from '@/modules/filemanager/components/AdminStatusBar/AdminStatusBar'
|
||||
import { Button } from '@/modules/filemanager/components/Button/Button'
|
||||
import { ConfirmModal } from '@/modules/filemanager/components/ConfirmModal/ConfirmModal'
|
||||
import { ErrorModal } from '@/modules/filemanager/components/ErrorModal/ErrorModal'
|
||||
import { FileBrowser } from '@/modules/filemanager/components/FileBrowser/FileBrowser'
|
||||
import { FormbricksIntegration } from '@/modules/filemanager/components/FormbricksIntegration/FormbricksIntegration'
|
||||
import { Header } from '@/modules/filemanager/components/Header/Header'
|
||||
import { InitialModal } from '@/modules/filemanager/components/InitialModal/InitialModal'
|
||||
import { PrivateKeyModal } from '@/modules/filemanager/components/PrivateKeyModal/PrivateKeyModal'
|
||||
import { Sidebar } from '@/modules/filemanager/components/Sidebar/Sidebar'
|
||||
import { getSignerPk, removeSignerPk } from '@/modules/filemanager/utils/common'
|
||||
import { CheckState, Context as BeeContext } from '@/providers/Bee'
|
||||
import { Context as FMContext } from '@/providers/FileManager'
|
||||
import { BrowserPlatform, cacheClearUrls, detectBrowser } from '@/providers/Platform'
|
||||
|
||||
function PrivateKeyModalBlock({ onSaved }: { onSaved: () => void }) {
|
||||
return (
|
||||
<div className="fm-main">
|
||||
@@ -95,6 +95,22 @@ function LoadingBlock() {
|
||||
)
|
||||
}
|
||||
|
||||
function ChainSyncingBlock() {
|
||||
return (
|
||||
<div className="fm-main">
|
||||
<div className="fm-loading" aria-live="polite">
|
||||
<div className="fm-spinner" aria-hidden="true" />
|
||||
<div className="fm-loading-title">Bee node is syncing…</div>
|
||||
<div className="fm-loading-subtitle">
|
||||
Your Bee node is still syncing the postage batch state from the chain.
|
||||
<br />
|
||||
File Manager will be available once the sync is complete.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ErrorModalBlock({ onClick, label }: { onClick: () => void; label: string }) {
|
||||
return <ErrorModal label={label} onClick={onClick} />
|
||||
}
|
||||
@@ -157,6 +173,7 @@ enum PageState {
|
||||
Loading = 'loading', // bee ready, pk present, FM init in progress
|
||||
Reset = 'reset', // STATE_INVALID emitted and user has not yet acknowledged
|
||||
InitError = 'init-error', // FM init completed with an error (non-reset case)
|
||||
ChainSyncing = 'chain-syncing', // bee node is still syncing postage batch state from chain
|
||||
Initial = 'initial', // FM ready but no admin stamp/drive → show InitialModal
|
||||
AdminError = 'admin-error', // drive creation failed
|
||||
Ready = 'ready', // fully operational
|
||||
@@ -172,7 +189,7 @@ export function FileManagerPage(): ReactElement {
|
||||
const [connectionErrorDismissed, setConnectionErrorDismissed] = useState<boolean>(false)
|
||||
const [cacheHelpUrl, setCacheHelpUrl] = useState<string>(cacheClearUrls[BrowserPlatform.Chrome])
|
||||
|
||||
const { status } = useContext(BeeContext)
|
||||
const { status, chainState } = useContext(BeeContext)
|
||||
const { fm, initDone, shallReset, adminDrive, initializationError, notifyPkSaved } = useContext(FMContext)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -207,6 +224,8 @@ export function FileManagerPage(): ReactElement {
|
||||
}, [isConnectionError])
|
||||
|
||||
const pageState = useMemo((): PageState => {
|
||||
const isChainSyncing = chainState === null
|
||||
|
||||
if (!isBeeReady && !initDone) return PageState.Connecting
|
||||
|
||||
if (!hasPk) return PageState.NoPrivateKey
|
||||
@@ -217,12 +236,15 @@ export function FileManagerPage(): ReactElement {
|
||||
|
||||
if (initializationError && !shallReset) return PageState.InitError
|
||||
|
||||
if (showAdminErrorModal) return PageState.AdminError
|
||||
|
||||
const hasAdminStamp = Boolean(fm?.adminStamp)
|
||||
const hasAdminDrive = Boolean(adminDrive)
|
||||
const setupIncomplete = !hasAdminStamp && !hasAdminDrive
|
||||
|
||||
if (!hasAdminStamp && !hasAdminDrive && !isCreationInProgress) return PageState.Initial
|
||||
if (setupIncomplete && isChainSyncing) return PageState.ChainSyncing
|
||||
|
||||
if (showAdminErrorModal) return PageState.AdminError
|
||||
|
||||
if (setupIncomplete && !isCreationInProgress) return PageState.Initial
|
||||
|
||||
return PageState.Ready
|
||||
}, [
|
||||
@@ -236,6 +258,7 @@ export function FileManagerPage(): ReactElement {
|
||||
fm,
|
||||
adminDrive,
|
||||
isCreationInProgress,
|
||||
chainState,
|
||||
])
|
||||
|
||||
const handlePrivateKeySaved = useCallback(() => {
|
||||
@@ -255,6 +278,10 @@ export function FileManagerPage(): ReactElement {
|
||||
return <LoadingBlock />
|
||||
}
|
||||
|
||||
if (pageState === PageState.ChainSyncing) {
|
||||
return <ChainSyncingBlock />
|
||||
}
|
||||
|
||||
if (pageState === PageState.NoPrivateKey) {
|
||||
return <PrivateKeyModalBlock onSaved={handlePrivateKeySaved} />
|
||||
}
|
||||
@@ -289,12 +316,15 @@ export function FileManagerPage(): ReactElement {
|
||||
}
|
||||
|
||||
if (pageState === PageState.AdminError) {
|
||||
const adminErrorLabel =
|
||||
chainState === null
|
||||
? 'Your Bee node is still syncing the postage batch state from the chain. Please wait for the sync to complete and try again.'
|
||||
: errorMessage ||
|
||||
'Error creating Admin Drive. Please try again. Possible causes include insufficient xDAI balance or a lost connection to the RPC.'
|
||||
|
||||
return (
|
||||
<ErrorModalBlock
|
||||
label={
|
||||
errorMessage ||
|
||||
'Error creating Admin Drive. Please try again. Possible causes include insufficient xDAI balance or a lost connection to the RPC.'
|
||||
}
|
||||
label={adminErrorLabel}
|
||||
onClick={() => {
|
||||
setAdminShowErrorModal(false)
|
||||
setErrorMessage('')
|
||||
|
||||
@@ -8,7 +8,7 @@ import { FitAudio } from '../../components/FitAudio'
|
||||
import { FitImage } from '../../components/FitImage'
|
||||
import { FitVideo } from '../../components/FitVideo'
|
||||
import { shortenText } from '../../utils'
|
||||
import { getHumanReadableFileSize } from '../../utils/file'
|
||||
import { getHumanReadableFileSize, guessMime } from '../../utils/file'
|
||||
import { shortenHash } from '../../utils/hash'
|
||||
|
||||
import { AssetIcon } from './AssetIcon'
|
||||
@@ -18,16 +18,20 @@ interface Props {
|
||||
metadata?: Metadata
|
||||
}
|
||||
|
||||
const getPreviewElement = (previewUri?: string, metadata?: Metadata) => {
|
||||
if (metadata?.isVideo) {
|
||||
const getPreviewElement = (previewUri?: string, metadata?: Metadata, type?: string) => {
|
||||
const isVideoType = Boolean(type && /.*\.(mp4|webm|ogv)$/i.test(type))
|
||||
const isAudioType = Boolean(type && /.*\.(mp3|ogg|oga|wav|webm|m4a|aac|flac)$/i.test(type))
|
||||
const isImageType = Boolean(type && /.*\.(jpg|jpeg|png|gif|webp|svg|ico)$/i.test(type))
|
||||
|
||||
if (metadata?.isVideo || isVideoType) {
|
||||
return <FitVideo src={previewUri} maxWidth="250px" maxHeight="175px" />
|
||||
}
|
||||
|
||||
if (metadata?.isAudio) {
|
||||
if (metadata?.isAudio || isAudioType) {
|
||||
return <FitAudio src={previewUri} maxWidth="250px" />
|
||||
}
|
||||
|
||||
if (metadata?.isImage) {
|
||||
if (metadata?.isImage || isImageType) {
|
||||
return <FitImage maxWidth="250px" maxHeight="175px" alt="Upload Preview" src={previewUri} />
|
||||
}
|
||||
|
||||
@@ -42,18 +46,26 @@ const getPreviewElement = (previewUri?: string, metadata?: Metadata) => {
|
||||
return <AssetIcon icon={<File />} />
|
||||
}
|
||||
|
||||
const getType = (metadata?: Metadata) => {
|
||||
export const getType = (metadata?: Metadata): string => {
|
||||
if (metadata?.isWebsite) return 'Website'
|
||||
|
||||
if (metadata?.type === 'folder') return 'Folder'
|
||||
|
||||
return metadata?.type
|
||||
let metadataType = metadata?.type || 'unknown'
|
||||
let typeFromExtension: string | undefined
|
||||
|
||||
if (metadataType === 'unknown' && metadata?.name) {
|
||||
const { mime } = guessMime(metadata.name)
|
||||
typeFromExtension = mime === 'application/octet-stream' ? 'file' : mime
|
||||
}
|
||||
|
||||
return typeFromExtension || metadataType
|
||||
}
|
||||
|
||||
// TODO: add optional prop for indexDocument when it is already known (e.g. downloading a manifest)
|
||||
export function AssetPreview({ metadata, previewUri }: Props): ReactElement | null {
|
||||
const previewElement = useMemo(() => getPreviewElement(previewUri, metadata), [metadata, previewUri])
|
||||
const type = useMemo(() => getType(metadata), [metadata])
|
||||
const previewElement = useMemo(() => getPreviewElement(previewUri, metadata, type), [metadata, type, previewUri])
|
||||
|
||||
return (
|
||||
<Box mb={4}>
|
||||
|
||||
@@ -16,7 +16,7 @@ import { ROUTES } from '../../routes'
|
||||
import { determineHistoryName, LocalStorageKeys, putHistory } from '../../utils/localStorage'
|
||||
import { loadManifest } from '../../utils/manifest'
|
||||
|
||||
import { AssetPreview } from './AssetPreview'
|
||||
import { AssetPreview, getType } from './AssetPreview'
|
||||
import { AssetSummary } from './AssetSummary'
|
||||
import { AssetSyncing } from './AssetSyncing'
|
||||
import { DownloadActionBar } from './DownloadActionBar'
|
||||
@@ -46,7 +46,7 @@ export function Share(): ReactElement {
|
||||
const count = Object.keys(entries).length
|
||||
const isVideo = Boolean(indexDocument && /.*\.(mp4|webm|ogv)$/i.test(indexDocument))
|
||||
const isAudio = Boolean(indexDocument && /.*\.(mp3|ogg|oga|wav|webm|m4a|aac|flac)$/i.test(indexDocument))
|
||||
const isImage = Boolean(indexDocument && /.*\.(jpg|jpeg|png|gif|webp|svg)$/i.test(indexDocument))
|
||||
const isImage = Boolean(indexDocument && /.*\.(jpg|jpeg|png|gif|webp|svg|ico)$/i.test(indexDocument))
|
||||
|
||||
if (isImage || isVideo || isAudio) {
|
||||
setPreview(`${apiUrl}/bzz/${hash}`)
|
||||
@@ -54,7 +54,7 @@ export function Share(): ReactElement {
|
||||
|
||||
setMetadata({
|
||||
hash,
|
||||
type: count > 1 ? 'folder' : 'unknown',
|
||||
type: count > 1 ? 'folder' : getType(),
|
||||
name: indexDocument || hash || '',
|
||||
count,
|
||||
isWebsite: Boolean(indexDocument && /.*\.html?$/i.test(indexDocument)),
|
||||
|
||||
@@ -14,10 +14,10 @@ import { Context as FileContext } from '../../providers/File'
|
||||
import { Context as SettingsContext } from '../../providers/Settings'
|
||||
import { Context as StampsContext, EnrichedPostageBatch } from '../../providers/Stamps'
|
||||
import { ROUTES } from '../../routes'
|
||||
import { waitUntilStampUsable } from '../../utils'
|
||||
import { detectIndexHtml, getAssetNameFromFiles, packageFile } from '../../utils/file'
|
||||
import { persistIdentity, updateFeed } from '../../utils/identity'
|
||||
import { LocalStorageKeys, putHistory } from '../../utils/localStorage'
|
||||
import { waitUntilStampUsable } from '../../utils/stamp'
|
||||
import { FeedPasswordDialog } from '../feeds/FeedPasswordDialog'
|
||||
import { PostageStampAdvancedCreation } from '../stamps/PostageStampAdvancedCreation'
|
||||
import { PostageStampSelector } from '../stamps/PostageStampSelector'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { BeeModes } from '@ethersphere/bee-js'
|
||||
import { useContext } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import Upload from 'remixicon-react/UploadLineIcon'
|
||||
@@ -19,7 +20,7 @@ export function WalletInfoCard() {
|
||||
)} xBZZ | ${walletBalance.nativeTokenBalance.toSignificantDigits(4)} xDAI`
|
||||
}
|
||||
|
||||
if (nodeInfo?.beeMode && ['light', 'full', 'dev'].includes(nodeInfo.beeMode)) {
|
||||
if (nodeInfo?.beeMode && [BeeModes.LIGHT, BeeModes.FULL, BeeModes.DEV].includes(nodeInfo.beeMode)) {
|
||||
return (
|
||||
<Card
|
||||
buttonProps={{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { PostageBatchOptions, Utils } from '@ethersphere/bee-js'
|
||||
import { PostageBatchOptions, RedundancyLevel, Utils } from '@ethersphere/bee-js'
|
||||
import { Box, Grid, IconButton, Typography } from '@mui/material'
|
||||
import BigNumber from 'bignumber.js'
|
||||
import { useSnackbar } from 'notistack'
|
||||
@@ -11,12 +11,14 @@ import { makeStyles } from 'tss-react/mui'
|
||||
import { SwarmButton } from '../../components/SwarmButton'
|
||||
import { SwarmSelect } from '../../components/SwarmSelect'
|
||||
import { SwarmTextInput } from '../../components/SwarmTextInput'
|
||||
import { MAX_STAMP_DEPTH, MIN_STAMP_DEPTH } from '../../constants'
|
||||
import { Context as BeeContext } from '../../providers/Bee'
|
||||
import { Context as SettingsContext } from '../../providers/Settings'
|
||||
import { Context as StampsContext } from '../../providers/Stamps'
|
||||
import { ROUTES } from '../../routes'
|
||||
import { secondsToTimeString } from '../../utils'
|
||||
import { getHumanReadableFileSize } from '../../utils/file'
|
||||
import { validateDepthInput } from '../../utils/stamp'
|
||||
|
||||
interface Props {
|
||||
onFinished: () => void
|
||||
@@ -80,7 +82,7 @@ export function PostageStampAdvancedCreation({ onFinished }: Props): ReactElemen
|
||||
}
|
||||
|
||||
function getPrice(depth: number, amount: bigint): string {
|
||||
const hasInvalidInput = amount <= 0 || isNaN(depth) || depth < 17 || depth > 255
|
||||
const hasInvalidInput = amount <= 0 || isNaN(depth) || depth < MIN_STAMP_DEPTH || depth > MAX_STAMP_DEPTH
|
||||
|
||||
if (hasInvalidInput) {
|
||||
return '-'
|
||||
@@ -147,38 +149,15 @@ export function PostageStampAdvancedCreation({ onFinished }: Props): ReactElemen
|
||||
setAmountInput(validAmountInput)
|
||||
}
|
||||
|
||||
function validateDepthInput(depthInput: string) {
|
||||
let validDepthInput = '0'
|
||||
|
||||
if (!depthInput) {
|
||||
setDepthError('Required field')
|
||||
} else {
|
||||
const depth = new BigNumber(depthInput)
|
||||
|
||||
if (!depth.isInteger()) {
|
||||
setDepthError('Depth must be an integer')
|
||||
} else if (depth.isLessThan(17)) {
|
||||
setDepthError('Minimal depth is 17')
|
||||
} else if (depth.isGreaterThan(255)) {
|
||||
setDepthError('Depth has to be at most 255')
|
||||
} else {
|
||||
setDepthError('')
|
||||
validDepthInput = depthInput
|
||||
}
|
||||
}
|
||||
|
||||
setDepthInput(validDepthInput)
|
||||
}
|
||||
|
||||
function renderStampVolumesInfo() {
|
||||
const depth = parseInt(depthInput, 10)
|
||||
|
||||
if (depthError || isNaN(depth) || depth < 17 || depth > 255) {
|
||||
if (depthError || isNaN(depth) || depth < MIN_STAMP_DEPTH || depth > MAX_STAMP_DEPTH) {
|
||||
return '-'
|
||||
}
|
||||
|
||||
const theoreticalMaximumVolume = getHumanReadableFileSize(Utils.getStampTheoreticalBytes(depth))
|
||||
const effectiveVolume = getHumanReadableFileSize(Utils.getStampEffectiveBytes(depth))
|
||||
const effectiveVolume = getHumanReadableFileSize(Utils.getStampEffectiveBytes(depth, false, RedundancyLevel.OFF))
|
||||
|
||||
return (
|
||||
<Grid container alignItems="center" className={classes.stampVolumeWrapper}>
|
||||
@@ -217,7 +196,11 @@ export function PostageStampAdvancedCreation({ onFinished }: Props): ReactElemen
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box mb={2}>
|
||||
<SwarmTextInput name="depth" label="Depth" onChange={event => validateDepthInput(event.target.value)} />
|
||||
<SwarmTextInput
|
||||
name="depth"
|
||||
label="Depth"
|
||||
onChange={event => validateDepthInput(event.target.value, setDepthError, setDepthInput)}
|
||||
/>
|
||||
<Box mt={0.25} sx={{ bgcolor: '#f6f6f6' }} p={2}>
|
||||
<Grid container justifyContent="space-between" alignItems="center">
|
||||
<Typography>Corresponding file size</Typography>
|
||||
@@ -242,7 +225,7 @@ export function PostageStampAdvancedCreation({ onFinished }: Props): ReactElemen
|
||||
<Box mb={2}>
|
||||
<SwarmSelect
|
||||
label="Immutable"
|
||||
value="No"
|
||||
value={immutable ? 'Yes' : 'No'}
|
||||
onChange={event => setImmutable(event.target.value === 'Yes')}
|
||||
options={[
|
||||
{ value: 'Yes', label: 'Yes' },
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Duration, PostageBatchOptions, Size, Utils } from '@ethersphere/bee-js'
|
||||
import { Duration, RedundancyLevel, Size, Utils } from '@ethersphere/bee-js'
|
||||
import { Box, Button, Grid, Slider, Typography } from '@mui/material'
|
||||
import { useSnackbar } from 'notistack'
|
||||
import { ReactElement, useContext, useState } from 'react'
|
||||
@@ -8,10 +8,12 @@ import { makeStyles } from 'tss-react/mui'
|
||||
|
||||
import { SwarmButton } from '../../components/SwarmButton'
|
||||
import { SwarmTextInput } from '../../components/SwarmTextInput'
|
||||
import { Context as BeeContext } from '../../providers/Bee'
|
||||
import { Context as SettingsContext } from '../../providers/Settings'
|
||||
import { Context as StampsContext } from '../../providers/Stamps'
|
||||
import { ROUTES } from '../../routes'
|
||||
import { secondsToTimeString } from '../../utils'
|
||||
import { validateDepthInput } from '../../utils/stamp'
|
||||
|
||||
interface Props {
|
||||
onFinished: () => void
|
||||
@@ -48,12 +50,17 @@ export function PostageStampStandardCreation({ onFinished }: Props): ReactElemen
|
||||
const { classes } = useStyles()
|
||||
const { refresh } = useContext(StampsContext)
|
||||
const { beeApi } = useContext(SettingsContext)
|
||||
|
||||
const { chainState } = useContext(BeeContext)
|
||||
const [depthInput, setDepthInput] = useState<number>(Utils.getDepthForSize(Size.fromGigabytes(4)))
|
||||
const [amountInput, setAmountInput] = useState<bigint>(Utils.getAmountForDuration(Duration.fromDays(30), 26500, 5))
|
||||
const [labelInput, setLabelInput] = useState('')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [buttonValue, setButtonValue] = useState(4)
|
||||
const [depthError, setDepthError] = useState<string>('')
|
||||
const [sliderValue, setSliderValue] = useState(30)
|
||||
|
||||
const pricePerBlockDefault = 24000
|
||||
const currentPrice = chainState?.currentPrice ?? pricePerBlockDefault
|
||||
|
||||
const getBatchValue = (value: number) => {
|
||||
return (
|
||||
@@ -74,18 +81,18 @@ export function PostageStampStandardCreation({ onFinished }: Props): ReactElemen
|
||||
if (typeof newValue !== 'number') {
|
||||
return
|
||||
}
|
||||
const amountValue = Utils.getAmountForDuration(Duration.fromDays(newValue), 26500, 5)
|
||||
const amountValue = Utils.getAmountForDuration(Duration.fromDays(newValue), currentPrice, 5)
|
||||
|
||||
setAmountInput(amountValue)
|
||||
setSliderValue(newValue)
|
||||
}
|
||||
|
||||
const { enqueueSnackbar } = useSnackbar()
|
||||
|
||||
function getTtl(amount: bigint): string {
|
||||
const pricePerBlock = 24000
|
||||
|
||||
return `${secondsToTimeString(
|
||||
Utils.getStampDuration(amount, pricePerBlock, 5).toSeconds(),
|
||||
)} (with price of ${pricePerBlock} PLUR per block)`
|
||||
Utils.getStampDuration(amount, currentPrice, 5).toSeconds(),
|
||||
)} (with price of ${currentPrice} PLUR per block)`
|
||||
}
|
||||
|
||||
function getPrice(depth: number, amount: bigint): string {
|
||||
@@ -106,15 +113,15 @@ export function PostageStampStandardCreation({ onFinished }: Props): ReactElemen
|
||||
}
|
||||
|
||||
setSubmitting(true)
|
||||
const amount = BigInt(amountInput)
|
||||
const depth = depthInput
|
||||
const options: PostageBatchOptions = {
|
||||
waitForUsable: false,
|
||||
label: labelInput || undefined,
|
||||
immutableFlag: true,
|
||||
}
|
||||
|
||||
await beeApi.createPostageBatch(amount.toString(), depth, options)
|
||||
await beeApi.buyStorage(
|
||||
Size.fromGigabytes(buttonValue),
|
||||
Duration.fromDays(sliderValue),
|
||||
{ label: labelInput, immutableFlag: true },
|
||||
undefined,
|
||||
false,
|
||||
RedundancyLevel.OFF,
|
||||
)
|
||||
await refresh()
|
||||
onFinished()
|
||||
} catch (e) {
|
||||
@@ -127,8 +134,8 @@ export function PostageStampStandardCreation({ onFinished }: Props): ReactElemen
|
||||
|
||||
function handleBatchSize(gigabytes: number) {
|
||||
setButtonValue(gigabytes)
|
||||
const capacity = Utils.getDepthForSize(Size.fromGigabytes(gigabytes))
|
||||
setDepthInput(capacity)
|
||||
const capacity = Utils.getDepthForSize(Size.fromGigabytes(gigabytes), false, RedundancyLevel.OFF)
|
||||
validateDepthInput(String(capacity), setDepthError, (v: string) => setDepthInput(Number(v)))
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -162,6 +169,7 @@ export function PostageStampStandardCreation({ onFinished }: Props): ReactElemen
|
||||
{getBatchValue(32)}
|
||||
{getBatchValue(256)}
|
||||
</Box>
|
||||
{depthError && <Typography>{depthError}</Typography>}
|
||||
</Box>
|
||||
<Box mb={1}>
|
||||
<Typography variant="h2">Data persistence</Typography>
|
||||
@@ -183,11 +191,12 @@ export function PostageStampStandardCreation({ onFinished }: Props): ReactElemen
|
||||
<Grid container justifyContent="space-between">
|
||||
<Typography>Corresponding TTL (Time to live)</Typography>
|
||||
<Typography>{amountInput ? getTtl(amountInput) : '-'}</Typography>
|
||||
<Typography>{amountInput ? getTtl(amountInput) : '-'}</Typography>
|
||||
</Grid>
|
||||
</Box>
|
||||
<Box display="flex" justifyContent={'right'} mt={0.5}>
|
||||
<Typography style={{ fontSize: '10px', color: 'rgba(0, 0, 0, 0.26)' }}>
|
||||
Current price of 24000 PLUR per block
|
||||
Current price of {currentPrice} PLUR per block
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
@@ -200,7 +209,7 @@ export function PostageStampStandardCreation({ onFinished }: Props): ReactElemen
|
||||
<Grid container justifyContent="space-between" alignItems="center">
|
||||
<Grid>
|
||||
<SwarmButton
|
||||
disabled={submitting || !depthInput || !amountInput}
|
||||
disabled={submitting || !depthInput || Boolean(depthError) || !amountInput}
|
||||
onClick={submit}
|
||||
iconType={Check}
|
||||
loading={submitting}
|
||||
|
||||
@@ -7,8 +7,9 @@ import ExpandableList from '../../components/ExpandableList'
|
||||
import ExpandableListItem from '../../components/ExpandableListItem'
|
||||
import ExpandableListItemActions from '../../components/ExpandableListItemActions'
|
||||
import ExpandableListItemKey from '../../components/ExpandableListItemKey'
|
||||
import StampExtensionModal from '../../components/StampExtensionModal'
|
||||
import { Context } from '../../providers/Settings'
|
||||
import StampExtensionModal, { StampExtensionType } from '../../components/StampExtensionModal'
|
||||
import { Context as BeeContext } from '../../providers/Bee'
|
||||
import { Context as SettingsContext } from '../../providers/Settings'
|
||||
import { EnrichedPostageBatch } from '../../providers/Stamps'
|
||||
import { secondsToTimeString } from '../../utils'
|
||||
import { getHumanReadableFileSize } from '../../utils/file'
|
||||
@@ -20,7 +21,8 @@ interface Props {
|
||||
}
|
||||
|
||||
function StampsTable({ postageStamps }: Props): ReactElement | null {
|
||||
const { beeApi } = useContext(Context)
|
||||
const { beeApi } = useContext(SettingsContext)
|
||||
const { status } = useContext(BeeContext)
|
||||
|
||||
if (!postageStamps || !beeApi) {
|
||||
return null
|
||||
@@ -37,8 +39,8 @@ function StampsTable({ postageStamps }: Props): ReactElement | null {
|
||||
<ExpandableListItem label="Depth" value={String(stamp.depth)} />
|
||||
<ExpandableListItem
|
||||
label="Capacity"
|
||||
value={`${getHumanReadableFileSize(2 ** stamp.depth * 4096 * stamp.usage)} / ${getHumanReadableFileSize(
|
||||
2 ** stamp.depth * 4096,
|
||||
value={`${getHumanReadableFileSize(stamp.size.toBytes() - stamp.remainingSize.toBytes())} / ${getHumanReadableFileSize(
|
||||
stamp.size.toBytes(),
|
||||
)}`}
|
||||
/>
|
||||
<ExpandableListItem label="Amount" value={parseInt(stamp.amount, 10).toLocaleString()} />
|
||||
@@ -49,16 +51,18 @@ function StampsTable({ postageStamps }: Props): ReactElement | null {
|
||||
<ExpandableListItem label="Purchase Block Number" value={stamp.blockNumber} />
|
||||
<ExpandableListItemActions>
|
||||
<StampExtensionModal
|
||||
type="Topup"
|
||||
type={StampExtensionType.Topup}
|
||||
icon={<TimerFlashFill size="1rem" />}
|
||||
bee={beeApi}
|
||||
stamp={stamp.batchID}
|
||||
stamp={stamp}
|
||||
status={status.all}
|
||||
/>
|
||||
<StampExtensionModal
|
||||
type="Dilute"
|
||||
type={StampExtensionType.Dilute}
|
||||
icon={<TimerFlashLine size="1rem" />}
|
||||
bee={beeApi}
|
||||
stamp={stamp.batchID}
|
||||
stamp={stamp}
|
||||
status={status.all}
|
||||
/>
|
||||
</ExpandableListItemActions>
|
||||
</>
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import { createContext, ReactElement, ReactNode, useEffect, useState } from 'react'
|
||||
|
||||
import { PREVIEW_DIMENSIONS } from '../constants'
|
||||
import { FileOrigin } from '../pages/files/FileNavigation'
|
||||
import { getMetadata } from '../utils/file'
|
||||
import { resize } from '../utils/image'
|
||||
|
||||
import { FileOrigin } from '@/pages/files/FileNavigation'
|
||||
|
||||
export type UploadOrigin = { origin: FileOrigin.Upload | FileOrigin.Feed; uuid?: string }
|
||||
|
||||
export const defaultUploadOrigin: UploadOrigin = { origin: FileOrigin.Upload }
|
||||
|
||||
+25
-3
@@ -1,5 +1,5 @@
|
||||
import { EthAddress } from '@ethersphere/bee-js'
|
||||
import { getAddress, JsonRpcProvider, Networkish } from 'ethers'
|
||||
import { getAddress, JsonRpcPayload, JsonRpcProvider, JsonRpcResult, Networkish } from 'ethers'
|
||||
|
||||
export const GNOIS_NETWORK_ID = 100
|
||||
export const GnosisNetwork: Networkish = { chainId: GNOIS_NETWORK_ID, name: 'gnosis', ensAddress: undefined }
|
||||
@@ -39,6 +39,28 @@ export function ethAddressString(address: EthAddress | string): string {
|
||||
return typeof address === 'string' ? getAddress(address) : getAddress(address.toHex())
|
||||
}
|
||||
|
||||
export function newGnosisProvider(url: string): JsonRpcProvider {
|
||||
return new JsonRpcProvider(url, GnosisNetwork, { staticNetwork: true })
|
||||
/**
|
||||
* Some RPC endpoints always return id:1 in their JSON-RPC responses regardless of the id in the request.
|
||||
* Ethers v6 validates that response ids match request ids, so we patch them.
|
||||
*/
|
||||
class FixedIdJsonRpcProvider extends JsonRpcProvider {
|
||||
async _send(payload: JsonRpcPayload | Array<JsonRpcPayload>): Promise<Array<JsonRpcResult>> {
|
||||
const results = await super._send(payload)
|
||||
const payloads = Array.isArray(payload) ? payload : [payload]
|
||||
|
||||
return results.map((result, i) => ({ ...result, id: payloads[i]?.id ?? result.id }))
|
||||
}
|
||||
}
|
||||
|
||||
export function newGnosisProvider(url: string): JsonRpcProvider {
|
||||
return new FixedIdJsonRpcProvider(url, GnosisNetwork, { staticNetwork: true, batchMaxCount: 1 })
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider for RPC validation only — no staticNetwork so getNetwork() actually
|
||||
* calls eth_chainId, but still uses FixedIdJsonRpcProvider to handle endpoints
|
||||
* that return a fixed/wrong id in their responses.
|
||||
*/
|
||||
export function newGnosisProviderForValidation(url: string): JsonRpcProvider {
|
||||
return new FixedIdJsonRpcProvider(url, undefined, { batchMaxCount: 1 })
|
||||
}
|
||||
|
||||
@@ -137,3 +137,119 @@ export function packageFile(file: FilePath, pathOverwrite?: string): FilePath {
|
||||
bytes: file.bytes,
|
||||
}
|
||||
}
|
||||
|
||||
export function getExtensionFromName(name: string): string {
|
||||
const ext = name.split('.').pop()?.toLowerCase() || ''
|
||||
const hasExtension = name.includes('.') && ext && ext !== name
|
||||
|
||||
return hasExtension ? ext : ''
|
||||
}
|
||||
|
||||
const EXT_TO_MIME: Record<string, string> = {
|
||||
mp4: 'video/mp4',
|
||||
webm: 'video/webm',
|
||||
ogv: 'video/ogg',
|
||||
mp3: 'audio/mpeg',
|
||||
m4a: 'audio/mp4',
|
||||
aac: 'audio/aac',
|
||||
wav: 'audio/wav',
|
||||
ogg: 'audio/ogg',
|
||||
png: 'image/png',
|
||||
jpg: 'image/jpeg',
|
||||
jpeg: 'image/jpeg',
|
||||
gif: 'image/gif',
|
||||
webp: 'image/webp',
|
||||
avif: 'image/avif',
|
||||
svg: 'image/svg+xml',
|
||||
pdf: 'application/pdf',
|
||||
txt: 'text/plain',
|
||||
md: 'text/markdown',
|
||||
json: 'application/json',
|
||||
csv: 'text/csv',
|
||||
html: 'text/html',
|
||||
htm: 'text/html',
|
||||
ico: 'image/vnd.microsoft.icon',
|
||||
}
|
||||
|
||||
export function guessMime(name: string, mtdt?: Record<string, string> | undefined): { mime: string; ext: string } {
|
||||
const md = mtdt?.mimeType || mtdt?.mime || mtdt?.['content-type']
|
||||
const ext = getExtensionFromName(name)
|
||||
|
||||
if (md) return { mime: md, ext }
|
||||
|
||||
const mime = EXT_TO_MIME[ext] || 'application/octet-stream'
|
||||
|
||||
return { mime, ext }
|
||||
}
|
||||
|
||||
export type Viewer = {
|
||||
name: string
|
||||
test: (mime: string) => boolean
|
||||
render: (win: Window, url: string, mime: string, name: string) => void
|
||||
}
|
||||
|
||||
const VIDEO_HTML = (u: string, title: string) =>
|
||||
`<html><head><meta charset="utf-8"/><title>${title}</title></head><body style="margin:0;background:#000">
|
||||
<video controls autoplay style="width:100%;height:100%" src="${u}"></video>
|
||||
</body></html>`
|
||||
|
||||
const AUDIO_HTML = (u: string, title: string) =>
|
||||
`<html><head><meta charset="utf-8"/><title>${title}</title></head><body>
|
||||
<audio controls autoplay style="width:100%" src="${u}"></audio>
|
||||
</body></html>`
|
||||
|
||||
const IMAGE_HTML = (u: string, title: string) =>
|
||||
`<html><head><meta charset="utf-8"/><title>${title}</title></head><body style="margin:0;background:#111;display:grid;place-items:center;min-height:100vh">
|
||||
<img style="max-width:100%;max-height:100vh" src="${u}" />
|
||||
</body></html>`
|
||||
|
||||
export const VIEWERS: Viewer[] = [
|
||||
{
|
||||
name: 'video',
|
||||
test: m => m.startsWith('video/'),
|
||||
render: (w, url, mime, name) => {
|
||||
w.document.write(VIDEO_HTML(url, name))
|
||||
w.document.title = name
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'audio',
|
||||
test: m => m.startsWith('audio/'),
|
||||
render: (w, url, mime, name) => {
|
||||
w.document.write(AUDIO_HTML(url, name))
|
||||
w.document.title = name
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'image',
|
||||
test: m => m.startsWith('image/'),
|
||||
render: (w, url, mime, name) => {
|
||||
w.document.write(IMAGE_HTML(url, name))
|
||||
w.document.title = name
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'pdf',
|
||||
test: m => m === 'application/pdf',
|
||||
render: (w, url, mime, name) => {
|
||||
w.document.title = name
|
||||
w.location.href = url
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'html',
|
||||
test: m => m === 'text/html',
|
||||
render: (w, url, mime, name) => {
|
||||
w.document.title = name
|
||||
w.location.href = url
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'text-like',
|
||||
test: m => m.startsWith('text/') || m === 'application/json' || m === 'text/markdown',
|
||||
render: (w, url, mime, name) => {
|
||||
w.document.title = name
|
||||
w.location.href = url
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { BatchId, Bee, NULL_TOPIC, PrivateKey, Reference } from '@ethersphere/bee-js'
|
||||
import { BatchId, Bee, Bytes, NULL_TOPIC, PrivateKey, Reference } from '@ethersphere/bee-js'
|
||||
import { randomBytes, Wallet } from 'ethers'
|
||||
|
||||
import { Identity, IdentityType } from '../providers/Feeds'
|
||||
|
||||
import { LocalStorageKeys } from './localStorage'
|
||||
import { uuidV4, waitUntilStampUsable } from '.'
|
||||
import { waitUntilStampUsable } from './stamp'
|
||||
import { uuidV4 } from '.'
|
||||
|
||||
export function generateWallet(): Wallet {
|
||||
const privateKey = randomBytes(PrivateKey.LENGTH).toString()
|
||||
const privateKey = new Bytes(randomBytes(PrivateKey.LENGTH)).toString()
|
||||
|
||||
return new Wallet(privateKey)
|
||||
}
|
||||
|
||||
+1
-34
@@ -1,4 +1,4 @@
|
||||
import { BatchId, Bee, PostageBatch, Reference } from '@ethersphere/bee-js'
|
||||
import { Reference } from '@ethersphere/bee-js'
|
||||
import { BigNumber } from 'bignumber.js'
|
||||
|
||||
import { BZZ_LINK_DOMAIN } from '../constants'
|
||||
@@ -207,36 +207,3 @@ export function shortenText(text: string, length = 20, separator = '[…]'): str
|
||||
|
||||
return `${text.slice(0, length)}${separator}${text.slice(-length)}`
|
||||
}
|
||||
|
||||
const DEFAULT_POLLING_FREQUENCY = 1_000
|
||||
const DEFAULT_STAMP_USABLE_TIMEOUT = 5 * 60_000
|
||||
|
||||
interface Options {
|
||||
pollingFrequency?: number
|
||||
timeout?: number
|
||||
}
|
||||
|
||||
export function waitUntilStampUsable(batchId: BatchId | string, bee: Bee, options?: Options): Promise<PostageBatch> {
|
||||
return waitForStamp(batchId, bee, options)
|
||||
}
|
||||
|
||||
async function waitForStamp(batchId: BatchId | string, bee: Bee, options?: Options): Promise<PostageBatch> {
|
||||
const timeout = options?.timeout || DEFAULT_STAMP_USABLE_TIMEOUT
|
||||
const pollingFrequency = options?.pollingFrequency || DEFAULT_POLLING_FREQUENCY
|
||||
|
||||
for (let i = 0; i < timeout; i += pollingFrequency) {
|
||||
try {
|
||||
const stamp = await bee.getPostageBatch(batchId)
|
||||
|
||||
if (stamp.usable) {
|
||||
return stamp
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
await sleepMs(pollingFrequency)
|
||||
}
|
||||
|
||||
throw new Error('Wait until stamp usable timeout has been reached')
|
||||
}
|
||||
|
||||
+2
-2
@@ -3,10 +3,10 @@ import { debounce } from '@mui/material'
|
||||
import { Contract, JsonRpcProvider, TransactionReceipt, TransactionResponse, Wallet } from 'ethers'
|
||||
|
||||
import { BZZ_TOKEN_ADDRESS, bzzABI } from './bzzAbi'
|
||||
import { ethAddressString, newGnosisProvider } from './chain'
|
||||
import { ethAddressString, newGnosisProvider, newGnosisProviderForValidation } from './chain'
|
||||
|
||||
async function getNetworkChainId(url: string): Promise<bigint> {
|
||||
const provider = newGnosisProvider(url)
|
||||
const provider = newGnosisProviderForValidation(url)
|
||||
const network = await provider.getNetwork()
|
||||
|
||||
return network.chainId
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { BatchId, Bee, PostageBatch } from '@ethersphere/bee-js'
|
||||
import BigNumber from 'bignumber.js'
|
||||
|
||||
import { MAX_STAMP_DEPTH, MIN_STAMP_DEPTH } from '../constants'
|
||||
|
||||
import { sleepMs } from '.'
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export function validateDepthInput(depthInput: string, onError: (v: any) => void, onSuccess: (v: any) => void) {
|
||||
let validDepthInput = '0'
|
||||
|
||||
if (!depthInput) {
|
||||
onError('Required field')
|
||||
} else {
|
||||
const depth = new BigNumber(depthInput)
|
||||
|
||||
if (!depth.isInteger()) {
|
||||
onError('Depth must be an integer')
|
||||
} else if (depth.isLessThan(MIN_STAMP_DEPTH)) {
|
||||
onError(`Minimal depth is ${MIN_STAMP_DEPTH}`)
|
||||
} else if (depth.isGreaterThan(MAX_STAMP_DEPTH)) {
|
||||
onError(`Depth has to be at most ${MAX_STAMP_DEPTH}`)
|
||||
} else {
|
||||
onError('')
|
||||
validDepthInput = depthInput
|
||||
}
|
||||
}
|
||||
|
||||
onSuccess(validDepthInput)
|
||||
}
|
||||
|
||||
const DEFAULT_POLLING_FREQUENCY = 1_000
|
||||
const DEFAULT_STAMP_USABLE_TIMEOUT = 5 * 60_000
|
||||
|
||||
interface Options {
|
||||
pollingFrequency?: number
|
||||
timeout?: number
|
||||
}
|
||||
|
||||
export function waitUntilStampUsable(batchId: BatchId | string, bee: Bee, options?: Options): Promise<PostageBatch> {
|
||||
return waitForStamp(batchId, bee, options)
|
||||
}
|
||||
|
||||
async function waitForStamp(batchId: BatchId | string, bee: Bee, options?: Options): Promise<PostageBatch> {
|
||||
const timeout = options?.timeout || DEFAULT_STAMP_USABLE_TIMEOUT
|
||||
const pollingFrequency = options?.pollingFrequency || DEFAULT_POLLING_FREQUENCY
|
||||
|
||||
for (let i = 0; i < timeout; i += pollingFrequency) {
|
||||
try {
|
||||
const stamp = await bee.getPostageBatch(batchId)
|
||||
|
||||
if (stamp.usable) {
|
||||
return stamp
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
await sleepMs(pollingFrequency)
|
||||
}
|
||||
|
||||
throw new Error('Wait until stamp usable timeout has been reached')
|
||||
}
|
||||
+1
-1
@@ -59,7 +59,7 @@ export default defineConfig(({ mode }) => {
|
||||
plugins: [
|
||||
react(),
|
||||
nodePolyfills({
|
||||
include: ['util', 'buffer'],
|
||||
include: ['util', 'buffer', 'stream'],
|
||||
globals: {
|
||||
Buffer: true,
|
||||
global: true,
|
||||
|
||||
Reference in New Issue
Block a user