Fix: file-manager and swarm-desktop bugs (#714)
- drive capacity display with stamp polling - download/upload progress handling - overlay and tooltip issues - FileMaganger readme - ultra-light mode handling - account feed view page - download media files - remove not found syncing link - fix ultra light node wallet page - tooltip issues --------- Co-authored-by: Andrei Mitrea <andrei.mitrea.hq@gmail.com> Co-authored-by: nidishk <nidishkrishnan45@gmail.com> Co-authored-by: Ferenc Sárai <sarai.ferenc@gmail.com> Co-authored-by: Nándor Komlódi <nandor.komlodi@gmail.com> Co-authored-by: rolandlor <33499567+rolandlor@users.noreply.github.com>
This commit is contained in:
+3
-1
@@ -25,4 +25,6 @@ yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
|
||||
settings.json
|
||||
settings.json
|
||||
|
||||
**.tgz
|
||||
@@ -18,9 +18,9 @@ Stay up to date by joining the [official Discord](https://discord.gg/GU22h2utj6)
|
||||
|
||||

|
||||
|
||||
| Node Setup | Upload Files | Download Content | Accounting | Settings |
|
||||
| ------------------------------------ | -------------------------------------- | ------------------------------------------ | ----------------------------------------- | ------------------------------------- |
|
||||
|  |  |  |  |  |
|
||||
| Node Setup | Upload Files | Download Content | Accounting | Settings | File Manager |
|
||||
| ------------------------------------ | -------------------------------------- | ------------------------------------------ | ----------------------------------------- | ------------------------------------- | ---------------------------------- |
|
||||
|  |  |  |  |  |  |
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -30,6 +30,7 @@ Stay up to date by joining the [official Discord](https://discord.gg/GU22h2utj6)
|
||||
- [Docker](#docker)
|
||||
- [Contribute](#contribute)
|
||||
- [Development](#development)
|
||||
- [File Manager](#file-manager)
|
||||
- [Maintainers](#maintainers)
|
||||
- [License](#license)
|
||||
|
||||
@@ -107,6 +108,9 @@ files. We support following variables:
|
||||
- `REACT_APP_DEFAULT_RPC_URL` (`string`) defines the default RPC provider URL. Be aware, that his only configures the
|
||||
default value. The user can override this in Settings, which is then persisted in local store and has priority over
|
||||
the value set in this env. variable. By default `https://xdai.fairdatasociety.org` is used.
|
||||
- `REACT_APP_FORMBRICKS_ENV_ID` and `REACT_APP_FORMBRICKS_APP_URL` (`string`) configures the
|
||||
[Formbricks](https://formbricks.com/) integration for user feedback collection. If these variables are not set, the
|
||||
feedback form is not available in the app.
|
||||
|
||||
#### Swarm Desktop development
|
||||
|
||||
@@ -121,6 +125,19 @@ npm start
|
||||
npm run desktop # This will inject the API key to the Dashboard
|
||||
```
|
||||
|
||||
## File Manager
|
||||
|
||||
The File Manager module provides intuitive decentralized file storage and management.
|
||||
|
||||
For comprehensive documentation, see the [File Manager Documentation](./docs/FILE_MANAGER.md).
|
||||
|
||||
### Features
|
||||
|
||||
- Create and manage multiple drives with configurable capacity and lifetime
|
||||
- Upload, download, and organize files with version control
|
||||
- Manage postage stamps required for file uploads
|
||||
- Configure erasure coding levels for data redundancy
|
||||
|
||||
## Contribute
|
||||
|
||||
There are some ways you can make this module better:
|
||||
|
||||
@@ -0,0 +1,605 @@
|
||||
# File Manager Module Documentation
|
||||
|
||||
## Introduction
|
||||
|
||||
The File Manager module is a decentralized file storage interface built on top of Ethereum Swarm. It provides a complete file management system that leverages Swarm's postage stamp mechanism for incentivized storage and retrieval.
|
||||
|
||||
### Table of Contents
|
||||
|
||||
- [Introduction](#introduction)
|
||||
- [Key Concepts](#key-concepts)
|
||||
- [Architecture Overview](#architecture-overview)
|
||||
- [Module Structure](#module-structure)
|
||||
- [Getting Started](#getting-started)
|
||||
- [State Management](#state-management)
|
||||
- [Core Features](#core-features)
|
||||
- [Operation Flows](#operation-flows)
|
||||
- [Component Architecture](#component-architecture)
|
||||
- [Design Patterns](#design-patterns)
|
||||
- [Troubleshooting](#troubleshooting)
|
||||
- [Testing Approach](#testing-approach)
|
||||
- [Performance Considerations](#performance-considerations)
|
||||
- [Known Limitations](#known-limitations)
|
||||
- [Future Enhancements](#future-enhancements)
|
||||
|
||||
### What is File Manager?
|
||||
|
||||
File Manager allows users to:
|
||||
- Create and manage multiple isolated storage containers (drives)
|
||||
- Upload, download, and organize files with folder support
|
||||
- Configure security levels (redundancy levels) using erasure coding
|
||||
- Purchase and manage postage stamp batches to pay for storage
|
||||
- Track file versions and restore previous states
|
||||
- Handle file conflicts and perform bulk operations
|
||||
|
||||
### Core Philosophy
|
||||
|
||||
File Manager is built around several key principles:
|
||||
|
||||
1. **Decentralization**: All file metadata and content are stored on Swarm, not centralized servers
|
||||
2. **User Control**: Users own their private keys and control their data
|
||||
3. **Stamp-Based Storage**: All operations require valid postage stamps (blockchain-backed storage payment)
|
||||
4. **Complexity Management**: Components follow strict complexity limits (max 20) with extraction patterns
|
||||
5. **State Consistency**: Real-time synchronization between UI and Swarm storage
|
||||
|
||||
---
|
||||
|
||||
## Key Concepts
|
||||
|
||||
### Drives
|
||||
|
||||
**Drives** are isolated storage containers that hold files and folders. Each drive:
|
||||
- Has a unique ID derived from its creation topic on Swarm
|
||||
- Is associated with a specific postage batch
|
||||
- Has configurable initial capacity and desired lifetime (inherited from batch)
|
||||
- Can be either an **admin drive** (manages system state) or **user drive** (stores user files)
|
||||
- Maintains its own file list and metadata
|
||||
|
||||
**Admin Drive** is a special drive that:
|
||||
- Is created once per File Manager instance
|
||||
- Stores the list of all user drives
|
||||
- Must be initialized before any other operations
|
||||
- Uses a stamp labeled `ADMIN_STAMP_LABEL`
|
||||
- Cannot be deleted (only reset)
|
||||
|
||||
**User Drives** are regular drives that:
|
||||
- Store user files and folders
|
||||
- Can be created, upgraded, or destroyed
|
||||
- Appear in the sidebar for navigation
|
||||
- Move to "Expired Drives" when their postage batch expires
|
||||
|
||||
### Postage Stamps
|
||||
|
||||
**Postage Stamps** (or batches) are blockchain-based payment mechanisms for Swarm storage:
|
||||
- Purchased with BZZ tokens (Swarm's native token)
|
||||
- Have a **batchID** (unique identifier)
|
||||
- Define **initial capacity** (storage space) and **desired lifetime** (time-to-live)
|
||||
- Must be **usable** (not expired, not diluted beyond capacity)
|
||||
- Can have optional labels for identification
|
||||
|
||||
**Postage Batch Validation** is critical:
|
||||
- Before creating drives
|
||||
- Before uploading files
|
||||
- During admin drive initialization
|
||||
- Invalid or unusable batches cause operations to fail
|
||||
|
||||
### File Info
|
||||
|
||||
**FileInfo** objects represent files in File Manager:
|
||||
- Stored as metadata on Swarm (not in local storage)
|
||||
- Contains: name, size, mime type, timestamps, drive association
|
||||
- Has a **topic** (unique identifier derived from path and parent)
|
||||
- Can be **trashed** (soft delete) or **forgotten** (hard delete)
|
||||
- Supports versioning via **history** (Swarm feed entries)
|
||||
|
||||
### Erasure Coding
|
||||
|
||||
**Erasure coding** provides data redundancy:
|
||||
- **OFF**: No redundancy (1x storage)
|
||||
- **MEDIUM**: Moderate redundancy (~2x storage)
|
||||
- **STRONG**: High redundancy (~3x storage)
|
||||
- **INSANE**: Very high redundancy (~4x storage)
|
||||
- **PARANOID**: Maximum redundancy (~5x storage)
|
||||
|
||||
Higher levels cost more but protect against data loss if Swarm nodes go offline.
|
||||
|
||||
---
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
### High-Level Flow
|
||||
|
||||
The File Manager follows a layered architecture:
|
||||
|
||||
1. **User Action** - User interacts with UI components
|
||||
2. **Component Layer** - FileBrowser, DriveItem, Modals handle UI logic
|
||||
3. **Context Layer** - FileManagerProvider, ViewProvider, SearchProvider manage state
|
||||
4. **Library Layer** - FileManagerBase from @solarpunkltd/file-manager-lib handles business logic
|
||||
5. **API Layer** - Bee API from @ethersphere/bee-js communicates with Swarm
|
||||
6. **Network Layer** - Swarm network stores data
|
||||
|
||||
### State Management
|
||||
|
||||
File Manager uses **React Context** for state management with three separate contexts:
|
||||
|
||||
1. **FileManagerProvider** - Core FM state: drives, files, admin drive, current drive. Manages FM instance lifecycle and event listeners.
|
||||
|
||||
2. **ViewProvider** - UI view preferences (grid/list) and current item being viewed (drive name or search results).
|
||||
|
||||
3. **SearchProvider** - Search query and scope (all drives, selected drive), filter options (include active, include trashed).
|
||||
|
||||
This separation ensures that updates in one context don't unnecessarily trigger re-renders in components that only depend on other contexts.
|
||||
|
||||
### Component Hierarchy
|
||||
|
||||
The component structure follows a strict hierarchy:
|
||||
- **FileManagerPage** - Orchestrates initialization flow
|
||||
- **Providers** - Wrap entire tree (FileManager → View → Search)
|
||||
- **Header** - Top navigation
|
||||
- **AdminStatusBar** - Admin stamp status display
|
||||
- **Sidebar** - Drive list with create/destroy actions
|
||||
- **FileBrowser** - Main file browser with operations
|
||||
- **Modals** - Various modals for different operations
|
||||
|
||||
---
|
||||
|
||||
## Module Structure
|
||||
|
||||
### Directory Organization
|
||||
|
||||
The File Manager module is organized into logical sections:
|
||||
|
||||
**Components Directory** - All React UI components, each in its own folder with associated styles and tests. Major components include FileBrowser (main interface), Sidebar (drive navigation), various modals for operations, and reusable elements like buttons and dropdowns.
|
||||
|
||||
**Hooks Directory** - Custom React hooks for specific functionality. Key hooks include useTransfers (upload/download management), useFileFiltering (search and filtering), useBulkActions (bulk operations), and useSorting (column sorting).
|
||||
|
||||
**Utils Directory** - Pure utility functions. Includes Bee API wrappers for stamp validation and drive operations, common helpers for formatting, download logic, and UI utilities.
|
||||
|
||||
**Constants Directory** - Configuration constants for erasure code levels, postage batch desired lifetimes, tooltips, and transfer statuses.
|
||||
|
||||
---
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Prerequisites
|
||||
|
||||
1. **Bee Node**: Running Bee node (dev mode or mainnet). Can be local or remote connection via Settings.
|
||||
|
||||
2. **Wallet Balance**: BZZ tokens to purchase postage batches, and xDAI for gas fees on blockchain transactions.
|
||||
|
||||
3. **CORS Configuration**: Bee node must allow CORS from the dashboard origin.
|
||||
|
||||
### Initial Setup Flow
|
||||
|
||||
**First Launch - Private Key Generation**
|
||||
|
||||
When a user first visits File Manager, they must provide or generate a private key. This key is stored in browser local storage and is critical - loss of the key means permanent data loss with no recovery option.
|
||||
|
||||
**One-Time Admin Drive Creation**
|
||||
|
||||
After the private key is set, the system checks for an admin drive. If none exists, the InitialModal appears automatically. The user selects initial capacity and desired lifetime, then purchases a postage batch with BZZ tokens. The system creates the admin drive which stores all user drive metadata.
|
||||
|
||||
**Creating User Drives**
|
||||
|
||||
Once the admin drive exists, users can create user drives from the sidebar. They enter a drive name (max 40 characters), select initial capacity, desired lifetime, and security level (erasure coding). The system displays the BZZ cost and creates the drive upon confirmation.
|
||||
|
||||
**Uploading Files**
|
||||
|
||||
Users select a drive from the sidebar, then drag-and-drop files or click "Upload File(s)". They choose an active postage batch, and the system monitors progress with ETA calculations. Files are uploaded with automatic conflict resolution if names already exist.
|
||||
|
||||
---
|
||||
|
||||
## State Management
|
||||
|
||||
### FileManager Provider
|
||||
|
||||
The FileManager Provider is the core state management solution. It manages:
|
||||
|
||||
**Core State**: The FileManagerBase instance, all files across drives, user drives with valid postage batches, expired drives, admin drive, currently selected drive, and currently selected postage batch.
|
||||
|
||||
**Error States**: Initialization errors, error modal visibility, and reset requirements when admin postage batch is invalid.
|
||||
|
||||
**Synchronization**: Real-time updates through event listeners that respond to drive and file changes from the FileManagerBase library.
|
||||
|
||||
### Initialization Sequence
|
||||
|
||||
The provider handles a complex initialization:
|
||||
|
||||
1. **Private Key Check** - Retrieves key from local storage. If missing, initialization halts until user provides one.
|
||||
|
||||
2. **Bee Instance Creation** - Creates Bee client with the private key as signer, then creates FileManagerBase instance.
|
||||
|
||||
3. **Event Listener Registration** - Registers handlers for all file manager events (drive created, file uploaded, file trashed, etc.).
|
||||
|
||||
4. **Admin Postage Batch Validation** - If admin postage batch exists, validates it's still usable. Invalid batches trigger reset flow.
|
||||
|
||||
5. **State Synchronization** - Categorizes drives into admin, user, and expired based on postage batch validity. Populates file list.
|
||||
|
||||
### Drive Categorization
|
||||
|
||||
The system continuously categorizes drives based on postage batch validity:
|
||||
|
||||
**Admin Drive** - Must have valid postage batch. If invalid, entire FM enters reset state.
|
||||
|
||||
**User Drives** - Drives with valid, usable postage batches appear in main drive list for normal operations.
|
||||
|
||||
**Expired Drives** - Drives whose postage batches expired but data still exists on Swarm. Appear in collapsed section, cannot be modified but can be viewed.
|
||||
|
||||
### State Synchronization Methods
|
||||
|
||||
**Sync Files** - Updates the files array when files are uploaded, trashed, restored, or forgotten. Can update entire list or individual files incrementally.
|
||||
|
||||
**Sync Drives** - Updates drive arrays (user, expired, admin) when drives are created, upgraded, or destroyed. Fetches current postage batch validity and recategorizes.
|
||||
|
||||
**Resync** - Full state refresh that re-initializes FM instance and restores previous selections if still valid. Used after major operations or manual refresh.
|
||||
|
||||
**Refresh Postage Batch** - Updates a specific postage batch's information without full resync. Used after uploads to update capacity.
|
||||
|
||||
### Event Flow
|
||||
|
||||
When a user performs an operation like uploading a file:
|
||||
|
||||
1. Component calls FM method
|
||||
2. FileManagerBase library executes operation
|
||||
3. Library emits event when complete
|
||||
4. Provider's event listener catches it
|
||||
5. Provider updates React state
|
||||
6. UI automatically re-renders with new data
|
||||
|
||||
This event-driven architecture keeps UI and Swarm state perfectly synchronized.
|
||||
|
||||
---
|
||||
|
||||
## Core Features
|
||||
|
||||
### Upload Management
|
||||
|
||||
The upload system handles complex scenarios:
|
||||
|
||||
**Conflict Detection** - Before upload, checks if file name already exists in target drive. Offers three resolution options: Cancel (skip file), Keep Both (rename with suffix like "file (1).txt"), or Replace (overwrite with new version).
|
||||
|
||||
**Queue Processing** - Uploads are queued and processed with maximum 10 concurrent uploads. This prevents overwhelming the network while maintaining good throughput.
|
||||
|
||||
**Progress Tracking** - Each upload shows percentage complete, data transferred, elapsed time, and ETA. ETA uses smoothing algorithm to prevent wild fluctuations from network speed variations.
|
||||
|
||||
**Postage Batch Validation** - Before each upload, validates the selected postage batch is still usable. Verifies sufficient capacity remains for the file size considering erasure coding overhead.
|
||||
|
||||
**Cancellation** - Users can cancel in-progress uploads. The system uses abort controllers to cleanly terminate HTTP requests and update transfer status.
|
||||
|
||||
### Download Management
|
||||
|
||||
Downloads execute in the background using browser's native download API:
|
||||
|
||||
**Progress Tracking** - Similar to uploads, shows percentage, speed, and ETA for each download.
|
||||
|
||||
**Bulk Downloads** - Users can select multiple files and download all at once. Each download tracks independently.
|
||||
|
||||
**Background Execution** - Downloads continue even if user navigates away from File Manager (within same browser tab).
|
||||
|
||||
### File Filtering
|
||||
|
||||
The filtering system supports multiple criteria:
|
||||
|
||||
**Search Query** - Case-insensitive substring matching on file names.
|
||||
|
||||
**Drive Scope** - Filter to selected drive only, or search across all drives.
|
||||
|
||||
**Trash Status** - Include active files only, trashed files only, or both.
|
||||
|
||||
**State Preservation** - When entering search mode, current filter settings are saved. Clearing search restores previous settings automatically.
|
||||
|
||||
### Sorting
|
||||
|
||||
Users can sort file lists by multiple columns:
|
||||
|
||||
**Sort Keys** - Name (alphabetical), Size (bytes), Timestamp (upload date), Drive (name, when searching all drives).
|
||||
|
||||
**Sort Direction** - Ascending or descending. Clicking same column header toggles direction.
|
||||
|
||||
**Sort Reset** - Clear sorting returns to natural order (order from Swarm).
|
||||
|
||||
### Bulk Operations
|
||||
|
||||
Select multiple files and perform batch actions:
|
||||
|
||||
**Bulk Trash** - Move multiple files to trash (soft delete). Can be restored later.
|
||||
|
||||
**Bulk Restore** - Restore multiple trashed files to active status.
|
||||
|
||||
**Bulk Forget** - Permanently delete files (irreversible). Requires confirmation.
|
||||
|
||||
**Bulk Download** - Download multiple files simultaneously with individual progress tracking.
|
||||
|
||||
### Version History
|
||||
|
||||
Files support full version history:
|
||||
|
||||
**Version Tracking** - Each file upload creates new version, previous versions retained.
|
||||
|
||||
**View History** - Modal shows all versions with timestamps and sizes.
|
||||
|
||||
**Restore Version** - Roll back to any previous version, which becomes the new current version.
|
||||
|
||||
**Storage Impact** - Each version consumes postage batch capacity, old versions can be forgotten but space continues to be occupied.
|
||||
|
||||
### Drag and Drop
|
||||
|
||||
Full drag-and-drop support for file uploads:
|
||||
|
||||
**Visual Feedback** - Overlay appears when dragging files over browser area.
|
||||
|
||||
**Drag Counter** - Tracks nested drag events to prevent flickering on complex layouts.
|
||||
|
||||
**Drop Handling** - Processes dropped files through same upload pipeline as manual selection.
|
||||
|
||||
---
|
||||
|
||||
## Operation Flows
|
||||
|
||||
### Initial Setup
|
||||
|
||||
**User Opens /file-manager**
|
||||
- System checks for private key in local storage
|
||||
- If no key: Shows PrivateKeyModal for user to enter or generate key
|
||||
- If has key: Initializes FileManager
|
||||
|
||||
**FileManager Initialization**
|
||||
- Creates Bee instance with user's private key
|
||||
- Creates FileManagerBase instance
|
||||
- Registers event listeners for all FM events
|
||||
- Reads admin state from Swarm
|
||||
|
||||
**Admin Drive Validation**
|
||||
- If admin postage batch exists and valid: Loads drives and files, shows FileBrowser
|
||||
- If admin postage batch exists but invalid: Sets reset flag, shows InitialModal in reset mode
|
||||
- If no admin postage batch (first time): Shows InitialModal for first-time setup
|
||||
|
||||
**Creating Admin Drive**
|
||||
- User selects desired lifetime and security level (erasure coding)
|
||||
- System calculates cost in BZZ tokens
|
||||
- User confirms and purchases postage batch (blockchain transaction)
|
||||
- System creates admin drive with purchased postage batch
|
||||
- Success: Shows Sidebar and FileBrowser
|
||||
|
||||
### Creating User Drive
|
||||
|
||||
**User Initiates Creation**
|
||||
- Clicks "Create New Drive" button in Sidebar
|
||||
- CreateDriveModal appears
|
||||
|
||||
**Drive Configuration**
|
||||
- User enters drive name (validated: max 40 chars)
|
||||
- Selects initial capacity from dropdown
|
||||
- Selects desired lifetime from dropdown
|
||||
- Chooses security level (erasure coding: OFF, MEDIUM, STRONG, INSANE, PARANOID)
|
||||
|
||||
**Cost Calculation**
|
||||
- System fetches current BZZ cost based on capacity, desired lifetime, and redundancy level
|
||||
- Displays total cost to user
|
||||
- Validates user has sufficient BZZ balance
|
||||
- If insufficient: Shows error, disables Create button
|
||||
- If sufficient: Enables Create button
|
||||
|
||||
**Drive Creation**
|
||||
- User clicks Create
|
||||
- System shows creation progress indicator
|
||||
- Purchases new postage batch (blockchain transaction, waits for confirmation)
|
||||
- Creates drive metadata on Swarm
|
||||
- FM emits DRIVE_CREATED event
|
||||
- Provider categorizes drive (has usable postage batch)
|
||||
- Drive appears in Sidebar
|
||||
- Success: User can now select and use the drive
|
||||
|
||||
### Uploading Files
|
||||
|
||||
**File Selection**
|
||||
- User drags files onto browser OR clicks "Upload file(s)" button
|
||||
- System receives file list
|
||||
|
||||
**Conflict Resolution (per file)**
|
||||
- Checks if file.name already exists in current drive
|
||||
- If no conflict: Proceeds with original name
|
||||
- If conflict: Shows UploadConflictModal with options:
|
||||
- Cancel: Skip this file
|
||||
- Keep Both: Rename to unique name (e.g., "file (1).txt")
|
||||
- Replace: Overwrite existing file, creating new version
|
||||
|
||||
**Queue Processing**
|
||||
- All files added to upload queue with resolved names
|
||||
- Queue processes maximum 10 files concurrently
|
||||
- For each file in batch:
|
||||
- Validates postage batch still exists and is usable
|
||||
- Verifies sufficient drive space remains
|
||||
- Creates transfer tracking item (shows in UI)
|
||||
- Executes upload with progress callbacks to Swarm
|
||||
- Updates progress (percentage, ETA, elapsed time)
|
||||
- On completion: Marks transfer Done, refreshes postage batch capacity
|
||||
- On error: Marks transfer Error, shows error message
|
||||
- Next batch starts when previous completes
|
||||
|
||||
**Event Synchronization**
|
||||
- FM library emits FILE_UPLOADED event
|
||||
- Provider's sync method adds/updates file in state
|
||||
- UI automatically updates to show new file
|
||||
|
||||
### Destroying Drive
|
||||
|
||||
**User Initiates Destruction**
|
||||
- Clicks menu button on Drive Item in Sidebar
|
||||
- Selects "Destroy Drive" from context menu
|
||||
- DestroyDriveModal appears with confirmation prompt
|
||||
|
||||
**Confirmation**
|
||||
- User reads warning about permanent deletion
|
||||
- User clicks "Destroy" button
|
||||
|
||||
**Destruction Process**
|
||||
- Modal closes
|
||||
- Progress overlay appears (spinner with "Destroying drive..." text)
|
||||
- Overlay is clickable to expand to full progress modal
|
||||
- System executes drive destruction:
|
||||
- Deletes drive metadata from Swarm
|
||||
- FM emits DRIVE_DESTROYED event
|
||||
- Provider removes drive from drives array
|
||||
- Provider removes all files belonging to destroyed drive
|
||||
- Progress overlay disappears
|
||||
- Drive no longer appears in Sidebar
|
||||
- If drive was selected: View switches to another drive or empty state
|
||||
|
||||
### Downloading Files
|
||||
|
||||
**User Initiates Download**
|
||||
- User right-clicks file
|
||||
- Selects "Download" from menu
|
||||
|
||||
**Download Tracking**
|
||||
- System creates download transfer item in UI
|
||||
- Transfer item shows: file name, size, progress percentage
|
||||
- Download panel appears at bottom of screen
|
||||
|
||||
**Download Execution**
|
||||
- System retrieves file from Swarm using file's topic
|
||||
- Uses browser's native download API to save file
|
||||
- Progress callbacks update UI in real-time:
|
||||
- Bytes downloaded / total bytes (from Swarm chunks)
|
||||
- Download speed
|
||||
- Estimated time remaining (ETA with smoothing)
|
||||
- Elapsed time
|
||||
|
||||
**Background Processing**
|
||||
- Downloads execute in background
|
||||
- User can continue browsing File Manager
|
||||
- Multiple downloads can run simultaneously
|
||||
- Each download tracks independently
|
||||
|
||||
**Completion**
|
||||
- On success: Browser saves file to user's downloads folder
|
||||
- Transfer item marked as "Done"
|
||||
- User can dismiss completed downloads
|
||||
- On error: Shows error message, allows retry
|
||||
|
||||
**Cancellation**
|
||||
- User clicks cancel button on transfer item
|
||||
- System aborts HTTP request using AbortController
|
||||
- Transfer item marked as "Cancelled"
|
||||
- Partial download discarded
|
||||
|
||||
### Search Operation
|
||||
|
||||
**Entering Search**
|
||||
- User types in search box
|
||||
- SearchContext captures query
|
||||
- System saves current scope and filter settings
|
||||
- Sets inSearch flag to true
|
||||
|
||||
**Filtering Execution**
|
||||
- useFileFiltering hook processes files array:
|
||||
- Filters by trash status (active/trashed based on checkboxes)
|
||||
- Filters by drive scope (selected drive vs all drives)
|
||||
- Filters by search query (case-insensitive substring match on name)
|
||||
- Returns filtered array
|
||||
|
||||
**Sorting Application**
|
||||
- useSorting hook processes filtered array
|
||||
- Applies current sort key and direction
|
||||
- Returns sorted array
|
||||
|
||||
**Display**
|
||||
- FileBrowserContent renders sorted list
|
||||
- If searching all drives: Shows drive name column
|
||||
- If no results: Shows "No files found" message
|
||||
|
||||
**Exiting Search**
|
||||
- User clears search box (empty query)
|
||||
- System restores saved scope and filter settings
|
||||
- Sets inSearch flag to false
|
||||
- View returns to previous state
|
||||
|
||||
---
|
||||
|
||||
## Component Architecture
|
||||
|
||||
### Hierarchical Structure
|
||||
|
||||
File Manager follows strict component hierarchy to manage complexity:
|
||||
|
||||
**Page Level** - FileManagerPage orchestrates the entire module, handling initialization states and conditional rendering.
|
||||
|
||||
**Provider Level** - Three nested contexts (FileManager → View → Search) wrap the component tree, each managing separate concerns.
|
||||
|
||||
**Layout Level** - Header, AdminStatusBar, Sidebar, and FileBrowser form the main layout structure.
|
||||
|
||||
**Feature Level** - Major features like FileBrowser contain sub-components for specific areas (TopBar, Header, Content, Modals, Overlays).
|
||||
|
||||
**Primitive Level** - Reusable elements like buttons, dropdowns, tooltips, progress bars used throughout.
|
||||
|
||||
### Component Responsibilities
|
||||
|
||||
Each component has a single, clear responsibility:
|
||||
|
||||
**FileManagerPage** - Orchestrates initialization flow and conditional rendering based on FM state.
|
||||
|
||||
**Sidebar** - Displays drive list, handles navigation, shows drive creation button.
|
||||
|
||||
**DriveItem** - Renders individual drive with capacity info, context menu, progress indicators.
|
||||
|
||||
**FileBrowser** - Main file browser interface, coordinates all file operations.
|
||||
|
||||
**FileBrowserModals** - Renders all modals (extracted for complexity management).
|
||||
|
||||
**FileBrowserOverlays** - Renders progress overlays (extracted for complexity management).
|
||||
|
||||
---
|
||||
|
||||
## Known Limitations
|
||||
|
||||
### Admin Drive Expiration
|
||||
|
||||
**Status**: Not fully handled (TODO in code).
|
||||
|
||||
**Current Behavior**: When admin drive postage batch expires, entire FM enters invalid state. User must reset and create new admin drive. Previous user drives remain accessible if their postage batches are valid.
|
||||
|
||||
**Desired Behavior**: System detects admin postage batch expiration before it happens, shows warning with "Extend Batch" button, seamlessly extends admin postage batch without requiring reset.
|
||||
|
||||
### Drive Name Length
|
||||
|
||||
**Limitation**: Drive names limited to 40 characters maximum.
|
||||
|
||||
**Reason**: Swarm feed entry size constraints limit metadata size.
|
||||
|
||||
**Workaround**: Use shorter, descriptive names. Consider abbreviations or codes for long project names.
|
||||
|
||||
### Postage Batch Selection in CreateDriveModal
|
||||
|
||||
**Status**: TODO comment in code.
|
||||
|
||||
**Current Behavior**: CreateDriveModal always purchases new postage batch for each drive.
|
||||
|
||||
**Desired Behavior**: Dropdown to select from existing usable postage batches (like InitialModal has), allowing users to reuse batches with remaining capacity.
|
||||
|
||||
**Impact**: Users must purchase separate postage batch for each drive, even if existing batches have sufficient capacity for multiple drives.
|
||||
|
||||
### Postage Batch Capacity Calculation
|
||||
|
||||
**Issue**: Capacity calculation depends on erasure coding level.
|
||||
|
||||
**Problem**: Frontend calculates approximate capacity based on redundancy multiplier. Actual capacity depends on how Bee node distributes chunks across Swarm network.
|
||||
|
||||
**Current**: Approximate calculation usually close enough for practical use.
|
||||
|
||||
**Ideal**: Bee node provides exact remaining capacity calculation accounting for actual chunk distribution and erasure coding overhead.
|
||||
|
||||
### Ultra-Light Nodes
|
||||
|
||||
**Limitation**: Ultra-light Bee nodes cannot create drives or purchase postage batches.
|
||||
|
||||
**Requirement**: Users must upgrade to light node to use File Manager.
|
||||
|
||||
**Error Message**: Displayed in InitialModal and CreateDriveModal when ultra-light node detected.
|
||||
|
||||
**Documentation**: https://docs.ethswarm.org/docs/desktop/configuration/#upgrading-from-an-ultra-light-to-a-light-node
|
||||
|
||||
---
|
||||
|
||||
|
||||
*This documentation provides a comprehensive functional overview of the File Manager module. For implementation details, refer to the source code in `src/modules/filemanager/` and `src/providers/FileManager.tsx`.*
|
||||
Generated
+20
-62
@@ -9,7 +9,7 @@
|
||||
"version": "0.33.3",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"@ethersphere/bee-js": "^10.1.1",
|
||||
"@ethersphere/bee-js": "^10.3.0",
|
||||
"@ethersproject/keccak256": "^5.7.0",
|
||||
"@ethersproject/strings": "^5.7.0",
|
||||
"@fairdatasociety/fdp-storage": "^0.19.0",
|
||||
@@ -17,7 +17,7 @@
|
||||
"@material-ui/core": "4.12.3",
|
||||
"@material-ui/icons": "4.11.2",
|
||||
"@material-ui/lab": "4.0.0-alpha.57",
|
||||
"@solarpunkltd/file-manager-lib": "^1.0.0",
|
||||
"@solarpunkltd/file-manager-lib": "^1.0.4",
|
||||
"axios": "^0.28.1",
|
||||
"bignumber.js": "^9.1.2",
|
||||
"buffer": "^6.0.3",
|
||||
@@ -49,12 +49,12 @@
|
||||
"bee-dashboard": "serve.js"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.22.0",
|
||||
"@babel/core": "^7.24.0",
|
||||
"@babel/plugin-proposal-class-properties": "^7.18.6",
|
||||
"@babel/plugin-transform-runtime": "^7.22.0",
|
||||
"@babel/preset-env": "^7.22.0",
|
||||
"@babel/preset-react": "^7.22.0",
|
||||
"@babel/preset-typescript": "^7.22.0",
|
||||
"@babel/plugin-transform-runtime": "^7.24.0",
|
||||
"@babel/preset-env": "^7.24.0",
|
||||
"@babel/preset-react": "^7.23.3",
|
||||
"@babel/preset-typescript": "^7.23.3",
|
||||
"@commitlint/config-conventional": "14.1.0",
|
||||
"@testing-library/jest-dom": "5.16.4",
|
||||
"@testing-library/react": "12.1.2",
|
||||
@@ -159,7 +159,6 @@
|
||||
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.27.1",
|
||||
"@babel/generator": "^7.28.5",
|
||||
@@ -819,7 +818,6 @@
|
||||
"integrity": "sha512-p9OkPbZ5G7UT1MofwYFigGebnrzGJacoBSQM0/6bi/PUMVE+qlWDD/OalvQKbwgQzU6dl0xAv6r4X7Jme0RYxA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/helper-plugin-utils": "^7.27.1"
|
||||
},
|
||||
@@ -1761,7 +1759,6 @@
|
||||
"integrity": "sha512-2KH4LWGSrJIkVf5tSiBFYuXDAoWRq2MMwgivCf+93dd0GQi8RXLjKA/0EvRnVV5G0hrHczsquXuD01L8s6dmBw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/helper-annotate-as-pure": "^7.27.1",
|
||||
"@babel/helper-module-imports": "^7.27.1",
|
||||
@@ -2721,12 +2718,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@ethersphere/bee-js": {
|
||||
"version": "10.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@ethersphere/bee-js/-/bee-js-10.1.1.tgz",
|
||||
"integrity": "sha512-4EdlFSrfeZr9v7BNTDXDPqXN2gVXssGAXWy5dKZ2/3TJySBjm9NxnFlmOb1pieCBu6WIumffHYtd3J+pym3JVg==",
|
||||
"version": "10.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@ethersphere/bee-js/-/bee-js-10.3.0.tgz",
|
||||
"integrity": "sha512-jMv7+PS2q/oB8Tgmw9Mtx7ztIuO822ll5Qsy+O7So9HdZ9Wc+1o5jh1Aoi5HFY22P4fMzjLJDHDqNNk60a/jIw==",
|
||||
"dependencies": {
|
||||
"axios": "^0.30.0",
|
||||
"cafe-utility": "^32.2.0",
|
||||
"cafe-utility": "^33.3.4",
|
||||
"debug": "^4.4.1",
|
||||
"isomorphic-ws": "^4.0.1",
|
||||
"semver": "^7.3.5",
|
||||
@@ -4156,7 +4153,6 @@
|
||||
"integrity": "sha512-sdpgI/PL56QVsEJldwEe4FFaFTLUqN+rd7sSZiRCdx2E/C7z5yK0y/khAWVBH24tXwto7I1hCzNWfJGZIYJKnw==",
|
||||
"deprecated": "Material UI v4 doesn't receive active development since September 2021. See the guide https://mui.com/material-ui/migration/migration-v4/ to upgrade to v5.",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.4.4",
|
||||
"@material-ui/styles": "^4.11.4",
|
||||
@@ -4195,7 +4191,6 @@
|
||||
"integrity": "sha512-fQNsKX2TxBmqIGJCSi3tGTO/gZ+eJgWmMJkgDiOfyNaunNaxcklJQFaFogYcFl0qFuaEz1qaXYXboa/bUXVSOQ==",
|
||||
"deprecated": "You can now upgrade to @mui/icons. See the guide: https://mui.com/guides/migration-v4/",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.4.4"
|
||||
},
|
||||
@@ -4769,7 +4764,6 @@
|
||||
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -4977,13 +4971,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@solarpunkltd/file-manager-lib": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@solarpunkltd/file-manager-lib/-/file-manager-lib-1.0.0.tgz",
|
||||
"integrity": "sha512-LHLQN/cXzezMLOBA+9jnv4T4Vf+LaNd8WCRsSFUfrZ5+dCEVvXfJqnAdplbwC2hdz1eMMxe4r4bFt0mCnIiBGg==",
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@solarpunkltd/file-manager-lib/-/file-manager-lib-1.0.4.tgz",
|
||||
"integrity": "sha512-EMNWNgXHyEHuQWcMgtlU5LBN/XkvwXR9kl/DMK82yFG3txeaCcCWuakErirc1UQ1RFELuEE5RuOcgQD1rtvUDA==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@ethersphere/bee-js": "^10.1.1",
|
||||
"cafe-utility": "^32.2.0"
|
||||
"@ethersphere/bee-js": "^10.2.0",
|
||||
"cafe-utility": "^33.3.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
@@ -5746,7 +5740,6 @@
|
||||
"integrity": "sha512-ljvjjs3DNXummeIaooB4cLBKg2U6SPI6Hjra/9rRIy7CpM0HpLtG9HptkMKAb4HYWy5S7HUvJEuWgr/y0U8SHw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"undici-types": "~7.13.0"
|
||||
}
|
||||
@@ -5817,7 +5810,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-17.0.34.tgz",
|
||||
"integrity": "sha512-46FEGrMjc2+8XhHXILr+3+/sTe3OfzSPU9YGKILLrUYbQ1CLQC9Daqo1KzENGXAWwrFwiY0l4ZbF20gRvgpWTg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/prop-types": "*",
|
||||
"@types/scheduler": "*",
|
||||
@@ -6039,7 +6031,6 @@
|
||||
"integrity": "sha512-DXVU6Cg29H2M6EybqSg2A+x8DgO9TCUBRp4QEXQHJceLS7ogVDP0g3Lkg/SZCqcvkAP/RruuQqK0gdlkgmhSUA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "5.28.0",
|
||||
"@typescript-eslint/type-utils": "5.28.0",
|
||||
@@ -6225,7 +6216,6 @@
|
||||
"integrity": "sha512-ekqoNRNK1lAcKhZESN/PdpVsWbP9jtiNqzFWkp/yAUdZvJalw2heCYuqRmM5eUJSIYEkgq5sGOjq+ZqsLMjtRA==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "5.28.0",
|
||||
"@typescript-eslint/types": "5.28.0",
|
||||
@@ -6694,7 +6684,6 @@
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -6808,7 +6797,6 @@
|
||||
"integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.1",
|
||||
"fast-json-stable-stringify": "^2.0.0",
|
||||
@@ -7987,7 +7975,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.8.25",
|
||||
"caniuse-lite": "^1.0.30001754",
|
||||
@@ -8083,9 +8070,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/cafe-utility": {
|
||||
"version": "32.2.0",
|
||||
"resolved": "https://registry.npmjs.org/cafe-utility/-/cafe-utility-32.2.0.tgz",
|
||||
"integrity": "sha512-Pz1XZ9HCG0oVEfM/iAmefkaKoSJxPfJh1d7a7sFM/WqXf2Yg4bqoRioFdy+awEtFCJjC7XJzKtG0w0y57x2K0Q=="
|
||||
"version": "33.3.4",
|
||||
"resolved": "https://registry.npmjs.org/cafe-utility/-/cafe-utility-33.3.4.tgz",
|
||||
"integrity": "sha512-7ptqOyxSKI3h7E5Qq2DTHu7kudOVE9vTgkRapBB7d9PUr3V1vgK5OdY2XTs7oOL8Gzr6ReE8hEG+QWC+EZGjnw=="
|
||||
},
|
||||
"node_modules/call-bind": {
|
||||
"version": "1.0.8",
|
||||
@@ -9184,7 +9171,6 @@
|
||||
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -10719,7 +10705,6 @@
|
||||
"deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@eslint/eslintrc": "^1.3.0",
|
||||
"@humanwhocodes/config-array": "^0.9.2",
|
||||
@@ -11308,7 +11293,6 @@
|
||||
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -11579,7 +11563,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@ethersproject/abi": "5.8.0",
|
||||
"@ethersproject/abstract-provider": "5.8.0",
|
||||
@@ -12455,7 +12438,6 @@
|
||||
}
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"deepmerge": "^2.1.1",
|
||||
"hoist-non-react-statics": "^3.3.0",
|
||||
@@ -14454,7 +14436,6 @@
|
||||
"integrity": "sha512-Yn0mADZB89zTtjkPJEXwrac3LHudkQMR+Paqa8uxJHCBr9agxztUifWCyiYrjhMPBoUVBjyny0I7XH6ozDr7QQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@jest/core": "^27.5.1",
|
||||
"import-local": "^3.0.2",
|
||||
@@ -16633,7 +16614,6 @@
|
||||
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -17811,7 +17791,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.11",
|
||||
"picocolors": "^1.1.1",
|
||||
@@ -19089,7 +19068,6 @@
|
||||
"integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"cssesc": "^3.0.0",
|
||||
"util-deprecate": "^1.0.2"
|
||||
@@ -19217,7 +19195,6 @@
|
||||
"integrity": "sha512-9fbDAXSBcc6Bs1mZrDYb3XKzDLm4EXXL9sC1LqKP5rZkT6KRr/rf9amVUcODVXgguK/isJz0d0hP72WeaKWsvA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"prettier": "bin-prettier.js"
|
||||
},
|
||||
@@ -19357,7 +19334,6 @@
|
||||
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
|
||||
"integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.4.0",
|
||||
"object-assign": "^4.1.1",
|
||||
@@ -19672,7 +19648,6 @@
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-17.0.2.tgz",
|
||||
"integrity": "sha512-gnhPt75i/dq/z3/6q/0asP78D0u592D5L1pd7M8P+dck6Fu/jJeL6iVVK23fptSUZj8Vjf++7wXA8UNclGQcbA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0",
|
||||
"object-assign": "^4.1.1"
|
||||
@@ -19845,7 +19820,6 @@
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-17.0.2.tgz",
|
||||
"integrity": "sha512-s4h96KtLDUQlsENhMn1ar8t2bEa+q/YAtj8pPPdIjPDGBDIVNsrD9aXNWqspUe6AzKCIG0C1HZZLqLV7qpOBGA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0",
|
||||
"object-assign": "^4.1.1",
|
||||
@@ -19924,7 +19898,6 @@
|
||||
"integrity": "sha512-F27qZr8uUqwhWZboondsPx8tnC3Ct3SxZA3V5WyEvujRyyNv0VYPhoBg1gZ8/MV5tubQp76Trw8lTv9hzRBa+A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
@@ -20651,7 +20624,6 @@
|
||||
"integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"rollup": "dist/bin/rollup"
|
||||
},
|
||||
@@ -20837,7 +20809,6 @@
|
||||
"integrity": "sha512-t+YPtOQHpGW1QWsh1CHQ5cPIr9lbbGZLZnbihP/D/qZj/yuV68m8qarcV17nvkOX81BCrvzAlq2klCQFZghyTg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"chokidar": "^4.0.0",
|
||||
"immutable": "^5.0.2",
|
||||
@@ -22734,7 +22705,6 @@
|
||||
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -22887,8 +22857,7 @@
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/tiny-warning/-/tiny-warning-1.0.3.tgz",
|
||||
"integrity": "sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA==",
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tmpl": {
|
||||
"version": "1.0.5",
|
||||
@@ -23009,7 +22978,6 @@
|
||||
"integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@cspotcode/source-map-support": "^0.8.0",
|
||||
"@tsconfig/node10": "^1.0.7",
|
||||
@@ -23155,7 +23123,6 @@
|
||||
"integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==",
|
||||
"dev": true,
|
||||
"license": "(MIT OR CC0-1.0)",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
@@ -23270,7 +23237,6 @@
|
||||
"integrity": "sha512-goMHfm00nWPa8UvR/CPSvykqf6dVV8x/dp0c5mFTMTIu0u0FlGWRioyy7Nn0PGAdHxpJZnuO/ut+PpQ8UiHAig==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -23684,7 +23650,6 @@
|
||||
"integrity": "sha512-hUtqAR3ZLVEYDEABdBioQCIqSoguHbFn1K7WlPPWSuXmx0031BD73PSE35jKyftdSh4YLDoQNgK4pqBt5Q82MA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/eslint-scope": "^3.7.7",
|
||||
"@types/estree": "^1.0.8",
|
||||
@@ -23734,7 +23699,6 @@
|
||||
"integrity": "sha512-NLhDfH/h4O6UOy+0LSso42xvYypClINuMNBVVzX4vX98TmTaTUxwRbXdhucbFMd2qLaCTcLq/PdYrvi8onw90w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@discoveryjs/json-ext": "^0.5.0",
|
||||
"@webpack-cli/configtest": "^1.2.0",
|
||||
@@ -23817,7 +23781,6 @@
|
||||
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -23875,7 +23838,6 @@
|
||||
"integrity": "sha512-0XavAZbNJ5sDrCbkpWL8mia0o5WPOd2YGtxrEiZkBK9FjLppIUK2TgxK6qGD2P3hUXTJNNPVibrerKcx5WkR1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/bonjour": "^3.5.9",
|
||||
"@types/connect-history-api-fallback": "^1.3.5",
|
||||
@@ -23936,7 +23898,6 @@
|
||||
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -24070,7 +24031,6 @@
|
||||
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -24417,7 +24377,6 @@
|
||||
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -24747,7 +24706,6 @@
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
|
||||
"integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
},
|
||||
|
||||
+8
-8
@@ -27,11 +27,11 @@
|
||||
},
|
||||
"overrides": {
|
||||
"@fairdatasociety/fdp-storage": {
|
||||
"@ethersphere/bee-js": "^10.1.1"
|
||||
"@ethersphere/bee-js": "^10.2.0"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@ethersphere/bee-js": "^10.1.1",
|
||||
"@ethersphere/bee-js": "^10.3.0",
|
||||
"@ethersproject/keccak256": "^5.7.0",
|
||||
"@ethersproject/strings": "^5.7.0",
|
||||
"@fairdatasociety/fdp-storage": "^0.19.0",
|
||||
@@ -39,7 +39,7 @@
|
||||
"@material-ui/core": "4.12.3",
|
||||
"@material-ui/icons": "4.11.2",
|
||||
"@material-ui/lab": "4.0.0-alpha.57",
|
||||
"@solarpunkltd/file-manager-lib": "^1.0.0",
|
||||
"@solarpunkltd/file-manager-lib": "^1.0.4",
|
||||
"axios": "^0.28.1",
|
||||
"bignumber.js": "^9.1.2",
|
||||
"buffer": "^6.0.3",
|
||||
@@ -68,12 +68,12 @@
|
||||
"stream-browserify": "^3.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.22.0",
|
||||
"@babel/core": "^7.24.0",
|
||||
"@babel/plugin-proposal-class-properties": "^7.18.6",
|
||||
"@babel/plugin-transform-runtime": "^7.22.0",
|
||||
"@babel/preset-env": "^7.22.0",
|
||||
"@babel/preset-react": "^7.22.0",
|
||||
"@babel/preset-typescript": "^7.22.0",
|
||||
"@babel/plugin-transform-runtime": "^7.24.0",
|
||||
"@babel/preset-env": "^7.24.0",
|
||||
"@babel/preset-react": "^7.23.3",
|
||||
"@babel/preset-typescript": "^7.23.3",
|
||||
"@commitlint/config-conventional": "14.1.0",
|
||||
"@testing-library/jest-dom": "5.16.4",
|
||||
"@testing-library/react": "12.1.2",
|
||||
|
||||
@@ -28,6 +28,7 @@ const useStyles = (backgroundColor: string) =>
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
textAlign: 'center',
|
||||
height: '130px',
|
||||
},
|
||||
iconWrapper: {
|
||||
display: 'flex',
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { createStyles, makeStyles } from '@material-ui/core'
|
||||
import { ReactElement } from 'react'
|
||||
|
||||
const useStyles = makeStyles(() =>
|
||||
createStyles({
|
||||
audio: {
|
||||
width: '100%',
|
||||
maxWidth: '250px',
|
||||
},
|
||||
}),
|
||||
)
|
||||
|
||||
interface AudioProps {
|
||||
src: string | undefined
|
||||
maxHeight?: string
|
||||
maxWidth?: string
|
||||
}
|
||||
|
||||
export function FitAudio(props: AudioProps): ReactElement {
|
||||
const classes = useStyles()
|
||||
|
||||
const inlineStyles: Record<string, string> = {}
|
||||
|
||||
props.maxHeight && (inlineStyles.maxHeight = props.maxHeight)
|
||||
props.maxWidth && (inlineStyles.maxWidth = props.maxWidth)
|
||||
|
||||
return <audio className={classes.audio} src={props.src} style={inlineStyles} controls />
|
||||
}
|
||||
+1
-1
@@ -4,7 +4,7 @@ import App from './App'
|
||||
import './index.css'
|
||||
import reportWebVitals from './reportWebVitals'
|
||||
|
||||
const desktopEnabled = Boolean(process.env.REACT_APP_BEE_DESKTOP_ENABLED)
|
||||
const desktopEnabled = process.env.REACT_APP_BEE_DESKTOP_ENABLED === 'true'
|
||||
const desktopUrl = process.env.REACT_APP_BEE_DESKTOP_URL
|
||||
const beeApiUrl = process.env.REACT_APP_BEE_HOST
|
||||
const defaultRpcUrl = process.env.REACT_APP_DEFAULT_RPC_URL
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import { ReactElement, useState, useMemo, useEffect, useRef, useContext } from 'react'
|
||||
import { ReactElement, useState, useMemo, useEffect, useContext, useCallback } from 'react'
|
||||
import './AdminStatusBar.scss'
|
||||
import { ProgressBar } from '../ProgressBar/ProgressBar'
|
||||
import { Tooltip } from '../Tooltip/Tooltip'
|
||||
import { PostageBatch } from '@ethersphere/bee-js'
|
||||
import { DriveInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import { UpgradeDriveModal } from '../UpgradeDriveModal/UpgradeDriveModal'
|
||||
import { calculateStampCapacityMetrics } from '../../utils/bee'
|
||||
import { DriveInfo, estimateDriveListMetadataSize } from '@solarpunkltd/file-manager-lib'
|
||||
import { Context as FMContext } from '../../../../providers/FileManager'
|
||||
import { ConfirmModal } from '../ConfirmModal/ConfirmModal'
|
||||
import { calculateStampCapacityMetrics } from '../../utils/bee'
|
||||
import { getHumanReadableFileSize } from '../../../../utils/file'
|
||||
import { UpgradeDriveModal } from '../UpgradeDriveModal/UpgradeDriveModal'
|
||||
import { UpgradeTimeoutModal } from '../UpgradeTimeoutModal/UpgradeTimeoutModal'
|
||||
import { FILE_MANAGER_EVENTS, POLLING_TIMEOUT_MS } from '../../constants/common'
|
||||
import { useStampPolling } from '../../hooks/useStampPolling'
|
||||
|
||||
interface AdminStatusBarProps {
|
||||
adminStamp: PostageBatch | null
|
||||
@@ -24,34 +28,61 @@ export function AdminStatusBar({
|
||||
isCreationInProgress,
|
||||
setErrorMessage,
|
||||
}: AdminStatusBarProps): ReactElement {
|
||||
const { setShowError, refreshStamp } = useContext(FMContext)
|
||||
const { drives, setShowError, refreshStamp } = useContext(FMContext)
|
||||
|
||||
const [isUpgradeDriveModalOpen, setIsUpgradeDriveModalOpen] = useState(false)
|
||||
const [isUpgradeTimeoutModalOpen, setIsUpgradeTimeoutModalOpen] = useState(false)
|
||||
const [isUpgrading, setIsUpgrading] = useState(false)
|
||||
const [actualStamp, setActualStamp] = useState<PostageBatch | null>(adminStamp)
|
||||
const [showProgressModal, setShowProgressModal] = useState(true)
|
||||
|
||||
const isMountedRef = useRef(true)
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
isMountedRef.current = false
|
||||
}
|
||||
const handleStampUpdated = useCallback((updatedStamp: PostageBatch) => {
|
||||
setActualStamp(updatedStamp)
|
||||
}, [])
|
||||
|
||||
const handlePollingStateChange = useCallback((_isPolling: boolean) => {
|
||||
// no-op
|
||||
}, [])
|
||||
|
||||
const { startPolling } = useStampPolling({
|
||||
onStampUpdated: handleStampUpdated,
|
||||
onPollingStateChange: handlePollingStateChange,
|
||||
refreshStamp,
|
||||
timeout: POLLING_TIMEOUT_MS,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
setShowProgressModal(isCreationInProgress || loading)
|
||||
}, [isCreationInProgress, loading, setShowProgressModal])
|
||||
|
||||
useEffect(() => {
|
||||
setActualStamp(adminStamp)
|
||||
}, [adminStamp, setActualStamp])
|
||||
if (!adminStamp || !actualStamp) {
|
||||
setActualStamp(adminStamp)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (actualStamp.batchID.toString() !== adminStamp.batchID.toString()) {
|
||||
setActualStamp(adminStamp)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const incomingSize = adminStamp.size.toBytes()
|
||||
const currentSize = actualStamp.size.toBytes()
|
||||
const incomingExpiry = adminStamp.duration.toEndDate().getTime()
|
||||
const currentExpiry = actualStamp.duration.toEndDate().getTime()
|
||||
|
||||
if (incomingSize > currentSize || incomingExpiry > currentExpiry) {
|
||||
setActualStamp(adminStamp)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [adminStamp])
|
||||
|
||||
useEffect(() => {
|
||||
if (!adminDrive) return
|
||||
|
||||
const id = adminDrive.id.toString()
|
||||
const batchId = adminStamp?.batchID.toString() || ''
|
||||
|
||||
const onStart = (e: Event) => {
|
||||
const { driveId } = (e as CustomEvent).detail || {}
|
||||
@@ -61,43 +92,79 @@ export function AdminStatusBar({
|
||||
}
|
||||
}
|
||||
|
||||
const onEnd = async (e: Event) => {
|
||||
const { driveId, success, error } = (e as CustomEvent).detail || {}
|
||||
const onEnd = (e: Event) => {
|
||||
const { driveId, success, error, updatedStamp } = (e as CustomEvent).detail || {}
|
||||
|
||||
if (!success) {
|
||||
if (error) {
|
||||
setErrorMessage?.(error)
|
||||
}
|
||||
if (driveId !== id) return
|
||||
|
||||
if (!success && error) {
|
||||
setIsUpgrading(false)
|
||||
setErrorMessage?.(error)
|
||||
setShowError(true)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (driveId === id && batchId) {
|
||||
setIsUpgrading(false)
|
||||
if (updatedStamp) {
|
||||
setActualStamp(updatedStamp)
|
||||
}
|
||||
|
||||
const upgradedStamp = await refreshStamp(batchId)
|
||||
setIsUpgrading(false)
|
||||
}
|
||||
|
||||
if (!isMountedRef.current) return
|
||||
const onTimeout = (e: Event) => {
|
||||
const { driveId } = (e as CustomEvent).detail || {}
|
||||
|
||||
if (upgradedStamp) {
|
||||
setActualStamp(upgradedStamp)
|
||||
}
|
||||
if (driveId === id) {
|
||||
setIsUpgradeTimeoutModalOpen(true)
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('fm:drive-upgrade-start', onStart as EventListener)
|
||||
window.addEventListener('fm:drive-upgrade-end', onEnd as EventListener)
|
||||
window.addEventListener(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_START, onStart as EventListener)
|
||||
window.addEventListener(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_END, onEnd as EventListener)
|
||||
window.addEventListener(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_TIMEOUT, onTimeout as EventListener)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('fm:drive-upgrade-start', onStart as EventListener)
|
||||
window.removeEventListener('fm:drive-upgrade-end', onEnd as EventListener)
|
||||
window.removeEventListener(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_START, onStart as EventListener)
|
||||
window.removeEventListener(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_END, onEnd as EventListener)
|
||||
window.removeEventListener(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_TIMEOUT, onTimeout as EventListener)
|
||||
}
|
||||
}, [adminDrive, adminStamp?.batchID, setErrorMessage, setShowError, refreshStamp, setIsUpgrading])
|
||||
}, [adminDrive, setErrorMessage, setShowError])
|
||||
|
||||
const { capacityPct, usedSize, totalSize } = useMemo(
|
||||
() => calculateStampCapacityMetrics(actualStamp, adminDrive),
|
||||
[actualStamp, adminDrive],
|
||||
)
|
||||
const handleTimeoutCancel = useCallback(() => {
|
||||
setIsUpgrading(false)
|
||||
setIsUpgradeTimeoutModalOpen(false)
|
||||
|
||||
// Restart polling to continue checking for capacity updates
|
||||
if (actualStamp) {
|
||||
startPolling(actualStamp)
|
||||
}
|
||||
}, [actualStamp, startPolling])
|
||||
|
||||
const { capacityPct, usedSize, totalSize } = useMemo(() => {
|
||||
if (!actualStamp) {
|
||||
return {
|
||||
capacityPct: 0,
|
||||
usedSize: '—',
|
||||
totalSize: '—',
|
||||
}
|
||||
}
|
||||
|
||||
const estimatedDlSizeBytes = estimateDriveListMetadataSize(drives) * drives.length
|
||||
const {
|
||||
capacityPct: reportedPct,
|
||||
usedBytes: reportedUsedBytes,
|
||||
stampSizeBytes,
|
||||
} = calculateStampCapacityMetrics(actualStamp, [], adminDrive?.redundancyLevel)
|
||||
const actualUsedSizeBytes = Math.max(reportedUsedBytes, estimatedDlSizeBytes)
|
||||
const actualPct = Math.max(reportedPct, (actualUsedSizeBytes / stampSizeBytes) * 100)
|
||||
|
||||
return {
|
||||
capacityPct: actualPct,
|
||||
usedSize: getHumanReadableFileSize(actualUsedSizeBytes),
|
||||
totalSize: getHumanReadableFileSize(stampSizeBytes),
|
||||
}
|
||||
}, [actualStamp, adminDrive, drives])
|
||||
|
||||
const expiresAt = useMemo(
|
||||
() => (actualStamp ? actualStamp.duration.toEndDate().toLocaleDateString() : '—'),
|
||||
@@ -109,22 +176,9 @@ export function AdminStatusBar({
|
||||
const statusVerb = isCreationInProgress ? 'Creating' : 'Loading'
|
||||
const statusText = statusVerb + ' admin drive, please do not reload'
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={`fm-admin-status-bar-container${blurCls}`} aria-busy={isBusy ? 'true' : 'false'}>
|
||||
<div className="fm-admin-status-bar-left">
|
||||
<div className="fm-drive-item-capacity">
|
||||
Capacity <ProgressBar value={capacityPct} width="150px" /> {usedSize} / {totalSize}
|
||||
</div>
|
||||
|
||||
<div>File Manager Available: Until: {expiresAt}</div>
|
||||
|
||||
<Tooltip
|
||||
label="The File Manager works only while your storage remains valid. If it expires, all catalogue metadata is
|
||||
permanently lost."
|
||||
/>
|
||||
</div>
|
||||
|
||||
const renderModalsAndOverlays = () => {
|
||||
return (
|
||||
<>
|
||||
{isUpgradeDriveModalOpen && actualStamp && adminDrive && (
|
||||
<UpgradeDriveModal
|
||||
stamp={actualStamp}
|
||||
@@ -134,13 +188,9 @@ export function AdminStatusBar({
|
||||
/>
|
||||
)}
|
||||
|
||||
<div
|
||||
className="fm-admin-status-bar-upgrade-button"
|
||||
onClick={() => !isBusy && actualStamp && adminDrive && setIsUpgradeDriveModalOpen(true)}
|
||||
aria-disabled={isBusy ? 'true' : 'false'}
|
||||
>
|
||||
{isBusy ? 'Working…' : 'Manage'}
|
||||
</div>
|
||||
{isUpgradeTimeoutModalOpen && adminDrive && actualStamp && (
|
||||
<UpgradeTimeoutModal driveName={adminDrive.name} onOk={handleTimeoutCancel} />
|
||||
)}
|
||||
|
||||
{isUpgrading && (
|
||||
<div className="fm-drive-item-creating-overlay" aria-live="polite">
|
||||
@@ -159,6 +209,38 @@ export function AdminStatusBar({
|
||||
onMinimize={() => setShowProgressModal(false)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={`fm-admin-status-bar-container${blurCls}`} aria-busy={isBusy ? 'true' : 'false'}>
|
||||
<div className="fm-admin-status-bar-left">
|
||||
<div
|
||||
className={`fm-drive-item-capacity ${isUpgrading ? 'fm-drive-item-capacity-updating' : ''}`}
|
||||
title={isUpgrading ? 'Capacity is updating... This may take a few moments.' : ''}
|
||||
>
|
||||
Capacity <ProgressBar value={capacityPct} width="150px" /> {usedSize} / {totalSize}
|
||||
</div>
|
||||
|
||||
<div>File Manager Available: Until: {expiresAt}</div>
|
||||
|
||||
<Tooltip
|
||||
label="The File Manager works only while your storage remains valid. If it expires, all catalogue metadata is
|
||||
permanently lost."
|
||||
/>
|
||||
</div>
|
||||
|
||||
{renderModalsAndOverlays()}
|
||||
|
||||
<div
|
||||
className="fm-admin-status-bar-upgrade-button"
|
||||
onClick={() => !isBusy && actualStamp && adminDrive && setIsUpgradeDriveModalOpen(true)}
|
||||
aria-disabled={isBusy ? 'true' : 'false'}
|
||||
>
|
||||
{isBusy ? 'Working…' : 'Manage'}
|
||||
</div>
|
||||
</div>
|
||||
{!showProgressModal && (loading || isCreationInProgress) && (
|
||||
<div className="fm-admin-status-bar-progress-pill-container">
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Button } from '../Button/Button'
|
||||
import { createPortal } from 'react-dom'
|
||||
|
||||
interface ConfirmModalProps {
|
||||
title?: string
|
||||
title?: React.ReactNode
|
||||
message?: React.ReactNode
|
||||
confirmLabel?: string
|
||||
cancelLabel?: string
|
||||
|
||||
@@ -83,3 +83,9 @@
|
||||
margin-top: 4px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.fm-error-text {
|
||||
color: var(--fm-error, #dc2626);
|
||||
font-size: 12px;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ReactElement, useContext, useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { BZZ, Duration, RedundancyLevel, Size, Utils } from '@ethersphere/bee-js'
|
||||
import { BeeModes, BZZ, DAI, Duration, RedundancyLevel, Size, Utils } from '@ethersphere/bee-js'
|
||||
import './CreateDriveModal.scss'
|
||||
import { CustomDropdown } from '../CustomDropdown/CustomDropdown'
|
||||
import { Button } from '../Button/Button'
|
||||
@@ -18,11 +18,12 @@ import { TOOLTIPS } from '../../constants/tooltips'
|
||||
|
||||
const minMarkValue = Math.min(...erasureCodeMarks.map(mark => mark.value))
|
||||
const maxMarkValue = Math.max(...erasureCodeMarks.map(mark => mark.value))
|
||||
const maxDriveNameLength = 40
|
||||
|
||||
interface CreateDriveModalProps {
|
||||
onCancelClick: () => void
|
||||
onDriveCreated: () => void
|
||||
onCreationStarted: () => void
|
||||
onCreationStarted: (driveName: string) => void
|
||||
onCreationError: (name: string) => void
|
||||
}
|
||||
// TODO: select existing batch id or create a new one - just like in InitialModal
|
||||
@@ -34,6 +35,7 @@ export function CreateDriveModal({
|
||||
}: CreateDriveModalProps): ReactElement {
|
||||
const [isCreateEnabled, setIsCreateEnabled] = useState(false)
|
||||
const [isBalanceSufficient, setIsBalanceSufficient] = useState(true)
|
||||
const [isxDaiBalanceSufficient, setIsxDaiBalanceSufficient] = useState(true)
|
||||
const [capacity, setCapacity] = useState(0)
|
||||
const [lifetimeIndex, setLifetimeIndex] = useState(-1)
|
||||
const [validityEndDate, setValidityEndDate] = useState(new Date())
|
||||
@@ -44,11 +46,19 @@ export function CreateDriveModal({
|
||||
const [cost, setCost] = useState('0')
|
||||
|
||||
const [sizeMarks, setSizeMarks] = useState<{ value: number; label: string }[]>([])
|
||||
const { walletBalance } = useContext(BeeContext)
|
||||
const { walletBalance, nodeInfo } = useContext(BeeContext)
|
||||
const { beeApi } = useContext(SettingsContext)
|
||||
const { fm } = useContext(FMContext)
|
||||
const { fm, drives, expiredDrives, adminDrive } = useContext(FMContext)
|
||||
const currentFetch = useRef<Promise<void> | null>(null)
|
||||
const isMountedRef = useRef(true)
|
||||
const [duplicate, setDuplicate] = useState(false)
|
||||
|
||||
const trimmedName = driveName.trim()
|
||||
const allExistingDriveNames = new Set(
|
||||
[...(drives || []), ...(expiredDrives || []), ...(adminDrive ? [adminDrive] : [])].map(d => d.name.trim()),
|
||||
)
|
||||
const nameExists = trimmedName.length > 0 && allExistingDriveNames.has(trimmedName)
|
||||
const validationError = duplicate && nameExists ? 'Drive already exists. Please choose another name.' : ''
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
@@ -56,6 +66,12 @@ export function CreateDriveModal({
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (duplicate && !nameExists) {
|
||||
setDuplicate(false)
|
||||
}
|
||||
}, [duplicate, nameExists])
|
||||
|
||||
const handleCapacityChange = (value: number, index: number) => {
|
||||
setCapacityIndex(index)
|
||||
}
|
||||
@@ -85,31 +101,37 @@ export function CreateDriveModal({
|
||||
if (!isMountedRef.current) return
|
||||
|
||||
setIsBalanceSufficient(true)
|
||||
setIsxDaiBalanceSufficient(true)
|
||||
|
||||
if ((walletBalance && cost.gte(walletBalance.bzzBalance)) || !walletBalance) {
|
||||
setIsBalanceSufficient(false)
|
||||
}
|
||||
setCost(cost.toSignificantDigits(2))
|
||||
|
||||
const zeroDAI = DAI.fromDecimalString('0')
|
||||
|
||||
if ((walletBalance && zeroDAI.eq(walletBalance.nativeTokenBalance)) || !walletBalance) {
|
||||
setIsxDaiBalanceSufficient(false)
|
||||
}
|
||||
},
|
||||
currentFetch,
|
||||
)
|
||||
|
||||
if (driveName && driveName.trim().length > 0) {
|
||||
setIsCreateEnabled(true)
|
||||
} else {
|
||||
setIsCreateEnabled(false)
|
||||
}
|
||||
const canCreate = Boolean(trimmedName) && !nameExists
|
||||
setIsCreateEnabled(canCreate)
|
||||
} else {
|
||||
setCost('0')
|
||||
setIsCreateEnabled(false)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [capacity, validityEndDate, beeApi, driveName, walletBalance])
|
||||
}, [capacity, validityEndDate, beeApi, walletBalance, nameExists, erasureCodeLevel, trimmedName])
|
||||
|
||||
useEffect(() => {
|
||||
setValidityEndDate(getExpiryDateByLifetime(lifetimeIndex))
|
||||
}, [lifetimeIndex])
|
||||
|
||||
const isUltraLightNode = nodeInfo?.beeMode === BeeModes.ULTRA_LIGHT
|
||||
const isCreateDriveDisabled = isUltraLightNode || !isCreateEnabled || !isBalanceSufficient || !isxDaiBalanceSufficient
|
||||
|
||||
return (
|
||||
<div className="fm-modal-container">
|
||||
<div className="fm-modal-window">
|
||||
@@ -125,7 +147,10 @@ export function CreateDriveModal({
|
||||
placeholder="My important files"
|
||||
value={driveName}
|
||||
onChange={e => setDriveName(e.target.value)}
|
||||
onBlur={() => setDuplicate(true)}
|
||||
maxLength={maxDriveNameLength}
|
||||
/>
|
||||
{validationError && <div className="fm-error-text">{validationError}</div>}
|
||||
</div>
|
||||
<div className="fm-modal-window-input-container">
|
||||
<label htmlFor="drive-initial-capacity" className="fm-input-label">
|
||||
@@ -140,7 +165,7 @@ export function CreateDriveModal({
|
||||
/>
|
||||
</div>
|
||||
<div className="fm-modal-info-warning">
|
||||
Drive sizes shown above are system-calculated based on your current stamp configuration
|
||||
Drive sizes are calculated automatically from your current stamp configuration.
|
||||
</div>
|
||||
<div className="fm-modal-window-input-container">
|
||||
<label htmlFor="drive-desired-lifetime" className="fm-input-label">
|
||||
@@ -174,37 +199,57 @@ export function CreateDriveModal({
|
||||
<div className="fm-emphasized-text">Estimated Cost:</div>
|
||||
<div>
|
||||
{cost} BZZ {isBalanceSufficient ? '' : '(Insufficient balance)'}
|
||||
{isxDaiBalanceSufficient ? '' : ' (Insufficient xDAI balance)'}
|
||||
</div>
|
||||
|
||||
<Tooltip label={TOOLTIPS.DRIVE_ESTIMATED_COST} bottomTooltip={true} />
|
||||
</div>
|
||||
<div>(Based on current network conditions)</div>
|
||||
{isUltraLightNode && (
|
||||
<div>
|
||||
Creating a drive requires running a light node. Please{' '}
|
||||
<a
|
||||
href="https://docs.ethswarm.org/docs/desktop/configuration/#upgrading-from-an-ultra-light-to-a-light-node"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
upgrade
|
||||
</a>{' '}
|
||||
to continue.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="fm-modal-window-footer">
|
||||
<Button
|
||||
label="Create drive"
|
||||
variant="primary"
|
||||
disabled={!isCreateEnabled || !isBalanceSufficient}
|
||||
disabled={isCreateDriveDisabled}
|
||||
onClick={async () => {
|
||||
if (isCreateEnabled && fm && beeApi && walletBalance) {
|
||||
onCreationStarted()
|
||||
if (!trimmedName || nameExists) {
|
||||
setDuplicate(true)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (isCreateEnabled && walletBalance && adminDrive) {
|
||||
onCreationStarted(driveName)
|
||||
onCancelClick()
|
||||
|
||||
await handleCreateDrive(
|
||||
await handleCreateDrive({
|
||||
beeApi,
|
||||
fm,
|
||||
Size.fromBytes(capacity),
|
||||
Duration.fromEndDate(validityEndDate),
|
||||
driveName,
|
||||
encryptionEnabled,
|
||||
erasureCodeLevel,
|
||||
false,
|
||||
false,
|
||||
null,
|
||||
() => onDriveCreated(), // onSuccess
|
||||
() => onCreationError(driveName), // onError
|
||||
)
|
||||
size: Size.fromBytes(capacity),
|
||||
duration: Duration.fromEndDate(validityEndDate),
|
||||
label: trimmedName,
|
||||
encryption: encryptionEnabled,
|
||||
redundancyLevel: erasureCodeLevel,
|
||||
adminRedundancy: adminDrive?.redundancyLevel,
|
||||
isAdmin: false,
|
||||
resetState: false,
|
||||
existingBatch: null,
|
||||
onSuccess: () => onDriveCreated(),
|
||||
onError: () => onCreationError(trimmedName),
|
||||
})
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -58,9 +58,28 @@
|
||||
padding: 4px 0;
|
||||
list-style: none;
|
||||
max-height: 220px;
|
||||
overflow-y: auto;
|
||||
overflow-y: scroll;
|
||||
animation: fadeIn 0.15s;
|
||||
|
||||
scrollbar-gutter: stable;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: #f1f1f1;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: #888;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb:hover {
|
||||
background: #555;
|
||||
}
|
||||
|
||||
li {
|
||||
padding: 10px 16px;
|
||||
cursor: pointer;
|
||||
|
||||
@@ -8,8 +8,10 @@ import AlertIcon from 'remixicon-react/AlertLineIcon'
|
||||
import Radio from '@material-ui/core/Radio'
|
||||
import FormControlLabel from '@material-ui/core/FormControlLabel'
|
||||
import FormControl from '@material-ui/core/FormControl'
|
||||
import { Tooltip } from '../Tooltip/Tooltip'
|
||||
|
||||
import { FileAction } from '../../constants/transfers'
|
||||
import { TOOLTIPS } from '../../constants/tooltips'
|
||||
|
||||
interface DeleteFileModalProps {
|
||||
name?: string
|
||||
@@ -59,7 +61,10 @@ export function DeleteFileModal({
|
||||
control={<Radio checked={value === FileAction.Trash} onChange={() => setValue(FileAction.Trash)} />}
|
||||
label={
|
||||
<div className="fm-radio-label">
|
||||
<div className="fm-radio-label-header fm-main-font-color fm-line-height-fit">Move to Trash</div>
|
||||
<div className="fm-radio-label-header fm-main-font-color fm-line-height-fit">
|
||||
Move to Trash
|
||||
<Tooltip label={TOOLTIPS.FILE_OPERATION_TRASH} iconSize="14px" />
|
||||
</div>
|
||||
<div onClick={e => e.preventDefault()}>
|
||||
Moves {subjectNoun} to the trash. It will still take up space on{' '}
|
||||
{currentDriveName ?? 'this drive'} and expire along with it. You can restore it later.
|
||||
@@ -75,7 +80,10 @@ export function DeleteFileModal({
|
||||
control={<Radio checked={value === FileAction.Forget} onChange={() => setValue(FileAction.Forget)} />}
|
||||
label={
|
||||
<div className="fm-radio-label">
|
||||
<div className="fm-radio-label-header fm-main-font-color fm-line-height-fit">Forget</div>
|
||||
<div className="fm-radio-label-header fm-main-font-color fm-line-height-fit">
|
||||
Forget
|
||||
<Tooltip label={TOOLTIPS.FILE_OPERATION_FORGET} iconSize="14px" />
|
||||
</div>
|
||||
<div onClick={e => e.preventDefault()}>
|
||||
Removes {subjectNoun} from your view. The data will remain on Swarm until{' '}
|
||||
{currentDriveName ?? 'the drive'} expires. This action cannot be easily undone.
|
||||
|
||||
@@ -11,11 +11,46 @@ interface DestroyDriveModalProps {
|
||||
doDestroy: () => void | Promise<void>
|
||||
}
|
||||
|
||||
interface ProgressDestroyModalProps {
|
||||
drive: DriveInfo
|
||||
onMinimize: () => void
|
||||
}
|
||||
|
||||
export function ProgressDestroyModal({ drive, onMinimize }: ProgressDestroyModalProps): ReactElement {
|
||||
const modalRoot = document.querySelector('.fm-main') || document.body
|
||||
|
||||
return createPortal(
|
||||
<div className="fm-modal-container">
|
||||
<div className="fm-modal-window">
|
||||
<div className="fm-modal-window-header fm-red-font">Destroying Drive</div>
|
||||
<div className="fm-modal-window-body">
|
||||
<div className="fm-modal-body-destroy">
|
||||
<div className="fm-emphasized-text">Drive "{drive.name}" is being destroyed</div>
|
||||
<div>Please wait while the operation completes...</div>
|
||||
<div style={{ marginTop: '20px', textAlign: 'center' }}>
|
||||
<div className="fm-mini-spinner" style={{ display: 'inline-block', marginRight: '10px' }} />
|
||||
<span>Destroying drive...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="fm-modal-window-footer">
|
||||
<Button label="Minimize" variant="secondary" onClick={onMinimize} />
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
modalRoot,
|
||||
)
|
||||
}
|
||||
|
||||
export function DestroyDriveModal({ drive, onCancelClick, doDestroy }: DestroyDriveModalProps): ReactElement {
|
||||
const [driveNameInput, setDriveNameInput] = useState('')
|
||||
const destroyDriveText = `DESTROY DRIVE ${drive.name}`
|
||||
const modalRoot = document.querySelector('.fm-main') || document.body
|
||||
|
||||
const handleDestroy = () => {
|
||||
doDestroy()
|
||||
}
|
||||
|
||||
return createPortal(
|
||||
<div className="fm-modal-container">
|
||||
<div className="fm-modal-window">
|
||||
@@ -50,7 +85,7 @@ export function DestroyDriveModal({ drive, onCancelClick, doDestroy }: DestroyDr
|
||||
label="Destroy entire drive"
|
||||
variant="danger"
|
||||
disabled={destroyDriveText !== driveNameInput}
|
||||
onClick={() => doDestroy()}
|
||||
onClick={handleDestroy}
|
||||
/>
|
||||
<Button label="Cancel" variant="secondary" onClick={onCancelClick} />
|
||||
</div>
|
||||
|
||||
+10
-4
@@ -11,14 +11,16 @@ import AlertIcon from 'remixicon-react/AlertLineIcon'
|
||||
import { UpgradeDriveModal } from '../UpgradeDriveModal/UpgradeDriveModal'
|
||||
import { getDaysLeft } from '../../utils/common'
|
||||
|
||||
import { PostageBatch, Size } from '@ethersphere/bee-js'
|
||||
import { DriveInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import { PostageBatch } from '@ethersphere/bee-js'
|
||||
import { DriveInfo, FileInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import { calculateStampCapacityMetrics } from '../../utils/bee'
|
||||
|
||||
const EXPIRING_ITEMS_PAGE_SIZE = 3
|
||||
|
||||
interface ExpiringNotificationModalProps {
|
||||
stamps: PostageBatch[]
|
||||
drives: DriveInfo[]
|
||||
files: FileInfo[]
|
||||
onCancelClick: () => void
|
||||
setErrorMessage?: (error: string) => void
|
||||
}
|
||||
@@ -26,6 +28,7 @@ interface ExpiringNotificationModalProps {
|
||||
export function ExpiringNotificationModal({
|
||||
stamps,
|
||||
drives,
|
||||
files,
|
||||
onCancelClick,
|
||||
setErrorMessage,
|
||||
}: ExpiringNotificationModalProps): ReactElement {
|
||||
@@ -71,6 +74,10 @@ export function ExpiringNotificationModal({
|
||||
|
||||
if (!drive) return null
|
||||
|
||||
const filesPerDrive = files.filter(fi => fi.driveId === drive.id.toString())
|
||||
|
||||
const { usedSize, stampSize } = calculateStampCapacityMetrics(stamp, filesPerDrive, drive.redundancyLevel)
|
||||
|
||||
if (daysLeft < 10) {
|
||||
daysClass = 'fm-red-font'
|
||||
} else if (daysLeft < 30) {
|
||||
@@ -89,8 +96,7 @@ export function ExpiringNotificationModal({
|
||||
{stamp.label} {drive.isAdmin && <Warning style={{ fontSize: '16px' }} />}
|
||||
</div>
|
||||
<div className="fm-expiring-notification-modal-section-left-value">
|
||||
{Size.fromBytes(stamp.size.toBytes() * stamp.usage).toFormattedString()} /{' '}
|
||||
{stamp.size.toFormattedString()}
|
||||
{usedSize} / {stampSize}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ReactElement, useEffect, useLayoutEffect, useRef, useState, useContext } from 'react'
|
||||
import { ReactElement, useEffect, useLayoutEffect, useRef, useState, useContext, useMemo, useCallback } from 'react'
|
||||
import './FileBrowser.scss'
|
||||
import { FileBrowserHeader } from './FileBrowserHeader/FileBrowserHeader'
|
||||
import { FileBrowserContent } from './FileBrowserContent/FileBrowserContent'
|
||||
@@ -15,15 +15,47 @@ import { useDragAndDrop } from '../../hooks/useDragAndDrop'
|
||||
import { useBulkActions } from '../../hooks/useBulkActions'
|
||||
import { SortKey, SortDir, useSorting } from '../../hooks/useSorting'
|
||||
|
||||
import { Point, Dir, safeSetState } from '../../utils/common'
|
||||
import { Point, Dir, safeSetState, getFileId } from '../../utils/common'
|
||||
import { computeContextMenuPosition } from '../../utils/ui'
|
||||
import { FileBrowserTopBar } from './FileBrowserTopBar/FileBrowserTopBar'
|
||||
import { handleDestroyDrive } from '../../utils/bee'
|
||||
import { handleDestroyAndForgetDrive } from '../../utils/bee'
|
||||
import { Context as SettingsContext } from '../../../../providers/Settings'
|
||||
import { ErrorModal } from '../ErrorModal/ErrorModal'
|
||||
import { FileBrowserModals } from './FileBrowserModals'
|
||||
import { FileBrowserContextMenu } from './FileBrowserMenu/FileBrowserContextMenu'
|
||||
import { FileInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import { DriveInfo, FileInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import { ProgressDestroyModal } from '../DestroyDriveModal/DestroyDriveModal'
|
||||
|
||||
const renderDestroySpinner = (
|
||||
isDestroying: boolean,
|
||||
isProgressModalOpen: boolean,
|
||||
currentDrive: DriveInfo | undefined,
|
||||
setter: () => void,
|
||||
) => {
|
||||
if (isProgressModalOpen && isDestroying && currentDrive) {
|
||||
return <ProgressDestroyModal drive={currentDrive} onMinimize={setter} />
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
const showDestroyModal = (isDestroying: boolean, setter: () => void) => {
|
||||
if (!isDestroying) return null
|
||||
|
||||
return (
|
||||
<div className="fm-refresh-overlay" aria-busy="true" aria-live="polite">
|
||||
<div
|
||||
className="fm-refresh-content"
|
||||
onClick={setter}
|
||||
style={{ cursor: 'pointer' }}
|
||||
title="Click to show progress modal"
|
||||
>
|
||||
<div className="fm-mini-spinner" role="status" aria-label="Destroying drive…" />
|
||||
<span className="fm-refresh-text">Destroying drive…</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const extractFilesFromClipboardEvent = (e: React.ClipboardEvent): File[] => {
|
||||
const out: File[] = []
|
||||
@@ -50,7 +82,7 @@ export function FileBrowser({ errorMessage, setErrorMessage }: FileBrowserProps)
|
||||
const { showContext, pos, contextRef, handleContextMenu, handleCloseContext } = useContextMenu<HTMLDivElement>()
|
||||
const { view, setActualItemView } = useView()
|
||||
const { beeApi } = useContext(SettingsContext)
|
||||
const { files, currentDrive, resync, drives, fm, showError, setShowError } = useContext(FMContext)
|
||||
const { files, adminDrive, currentDrive, resync, drives, fm, showError, setShowError } = useContext(FMContext)
|
||||
const {
|
||||
uploadFiles,
|
||||
isUploading,
|
||||
@@ -78,7 +110,10 @@ export function FileBrowser({ errorMessage, setErrorMessage }: FileBrowserProps)
|
||||
|
||||
const [showBulkDeleteModal, setShowBulkDeleteModal] = useState(false)
|
||||
const [showDestroyDriveModal, setShowDestroyDriveModal] = useState(false)
|
||||
const [isDestroying, setIsDestroying] = useState(false)
|
||||
const [isProgressModalOpen, setIsProgressModalOpen] = useState(false)
|
||||
const [confirmBulkForget, setConfirmBulkForget] = useState(false)
|
||||
const [confirmBulkRestore, setConfirmBulkRestore] = useState(false)
|
||||
const [isRefreshing, setIsRefreshing] = useState(false)
|
||||
const [pendingCancelUpload, setPendingCancelUpload] = useState<string | null>(null)
|
||||
|
||||
@@ -125,6 +160,10 @@ export function FileBrowser({ errorMessage, setErrorMessage }: FileBrowserProps)
|
||||
getDriveName,
|
||||
})
|
||||
|
||||
const sortedKey = sorted.map(f => getFileId(f)).join('|')
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
const stableSorted = useMemo(() => sorted, [sortedKey])
|
||||
|
||||
const bulk = useBulkActions({
|
||||
listToRender,
|
||||
trackDownload,
|
||||
@@ -200,32 +239,50 @@ export function FileBrowser({ errorMessage, setErrorMessage }: FileBrowserProps)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDestroyDriveConfirm = async () => {
|
||||
const handleDestroyDriveConfirm = useCallback(async () => {
|
||||
if (!currentDrive) return
|
||||
|
||||
setShowDestroyDriveModal(false)
|
||||
setIsProgressModalOpen(true)
|
||||
setIsDestroying(true)
|
||||
|
||||
await handleDestroyDrive(
|
||||
await handleDestroyAndForgetDrive({
|
||||
beeApi,
|
||||
fm,
|
||||
currentDrive,
|
||||
() => {
|
||||
drive: currentDrive,
|
||||
isDestroy: true,
|
||||
adminDrive,
|
||||
onSuccess: () => {
|
||||
setIsDestroying(false)
|
||||
setIsProgressModalOpen(false)
|
||||
setShowDestroyDriveModal(false)
|
||||
},
|
||||
e => {
|
||||
onError: e => {
|
||||
setIsDestroying(false)
|
||||
setIsProgressModalOpen(false)
|
||||
setShowDestroyDriveModal(false)
|
||||
setErrorMessage?.(`Error destroying drive: ${currentDrive.name}: ${e}`)
|
||||
setShowError(true)
|
||||
},
|
||||
)
|
||||
}
|
||||
})
|
||||
}, [
|
||||
beeApi,
|
||||
fm,
|
||||
currentDrive,
|
||||
adminDrive,
|
||||
setErrorMessage,
|
||||
setIsProgressModalOpen,
|
||||
setShowDestroyDriveModal,
|
||||
setShowError,
|
||||
])
|
||||
|
||||
const handleUploadClose = (name: string) => {
|
||||
const row = uploadItems.find(i => i.name === name)
|
||||
const handleUploadClose = (uuid: string) => {
|
||||
const row = uploadItems.find(i => i.uuid === uuid)
|
||||
|
||||
if (row?.status === TransferStatus.Uploading) {
|
||||
setPendingCancelUpload(name)
|
||||
setPendingCancelUpload(uuid)
|
||||
} else {
|
||||
cancelOrDismissUpload(name)
|
||||
cancelOrDismissUpload(uuid)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -322,6 +379,18 @@ export function FileBrowser({ errorMessage, setErrorMessage }: FileBrowserProps)
|
||||
const showDragOverlay = isDragging && Boolean(currentDrive)
|
||||
const fileCountText = bulk.selectedFiles.length === 1 ? 'file' : 'files'
|
||||
|
||||
// Memoize onBulk object to prevent FileBrowserContent rerenders
|
||||
const onBulk = useMemo(
|
||||
() => ({
|
||||
download: () => bulk.bulkDownload(bulk.selectedFiles),
|
||||
restore: () => setConfirmBulkRestore(true),
|
||||
forget: () => bulk.bulkForget(bulk.selectedFiles),
|
||||
destroy: () => setShowDestroyDriveModal(true),
|
||||
delete: () => setShowBulkDeleteModal(true),
|
||||
}),
|
||||
[bulk],
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
{conflictPortal}
|
||||
@@ -364,7 +433,7 @@ export function FileBrowser({ errorMessage, setErrorMessage }: FileBrowserProps)
|
||||
>
|
||||
<FileBrowserContent
|
||||
key={isSearchMode ? `content-search` : `content-${currentDrive?.id.toString() ?? 'none'}`}
|
||||
listToRender={sorted}
|
||||
listToRender={stableSorted}
|
||||
drives={drives}
|
||||
currentDrive={currentDrive || null}
|
||||
view={view}
|
||||
@@ -373,13 +442,7 @@ export function FileBrowser({ errorMessage, setErrorMessage }: FileBrowserProps)
|
||||
selectedIds={bulk.selectedIds}
|
||||
onToggleSelected={bulk.toggleOne}
|
||||
bulkSelectedCount={bulk.selectedCount}
|
||||
onBulk={{
|
||||
download: () => bulk.bulkDownload(bulk.selectedFiles),
|
||||
restore: () => bulk.bulkRestore(bulk.selectedFiles),
|
||||
forget: () => bulk.bulkForget(bulk.selectedFiles),
|
||||
destroy: () => setShowDestroyDriveModal(true),
|
||||
delete: () => setShowBulkDeleteModal(true),
|
||||
}}
|
||||
onBulk={onBulk}
|
||||
setErrorMessage={setErrorMessage}
|
||||
/>
|
||||
{showError && (
|
||||
@@ -411,7 +474,7 @@ export function FileBrowser({ errorMessage, setErrorMessage }: FileBrowserProps)
|
||||
enableRefresh={Boolean(fm?.adminStamp)}
|
||||
onUploadFile={onContextUploadFile}
|
||||
onBulkDownload={() => bulk.bulkDownload(bulk.selectedFiles)}
|
||||
onBulkRestore={() => bulk.bulkRestore(bulk.selectedFiles)}
|
||||
onBulkRestore={() => setConfirmBulkRestore(true)}
|
||||
onBulkDelete={() => setShowBulkDeleteModal(true)}
|
||||
onBulkDestroy={() => setShowDestroyDriveModal(true)}
|
||||
onBulkForget={() => bulk.bulkForget(bulk.selectedFiles)}
|
||||
@@ -439,6 +502,7 @@ export function FileBrowser({ errorMessage, setErrorMessage }: FileBrowserProps)
|
||||
fileCountText={fileCountText}
|
||||
currentDrive={currentDrive || null}
|
||||
confirmBulkForget={confirmBulkForget}
|
||||
confirmBulkRestore={confirmBulkRestore}
|
||||
showDestroyDriveModal={showDestroyDriveModal}
|
||||
pendingCancelUpload={pendingCancelUpload}
|
||||
onDeleteCancel={() => setShowBulkDeleteModal(false)}
|
||||
@@ -448,6 +512,11 @@ export function FileBrowser({ errorMessage, setErrorMessage }: FileBrowserProps)
|
||||
setConfirmBulkForget(false)
|
||||
}}
|
||||
onForgetCancel={() => setConfirmBulkForget(false)}
|
||||
onRestoreConfirm={async () => {
|
||||
await bulk.bulkRestore(bulk.selectedFiles)
|
||||
setConfirmBulkRestore(false)
|
||||
}}
|
||||
onRestoreCancel={() => setConfirmBulkRestore(false)}
|
||||
onDestroyCancel={() => setShowDestroyDriveModal(false)}
|
||||
onDestroyConfirm={handleDestroyDriveConfirm}
|
||||
onCancelUploadConfirm={() => {
|
||||
@@ -467,6 +536,10 @@ export function FileBrowser({ errorMessage, setErrorMessage }: FileBrowserProps)
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showDestroyModal(isDestroying, () => setIsProgressModalOpen(true))}
|
||||
|
||||
{renderDestroySpinner(isDestroying, isProgressModalOpen, currentDrive, () => setIsProgressModalOpen(false))}
|
||||
</div>
|
||||
|
||||
<div className="fm-file-browser-footer">
|
||||
@@ -474,7 +547,6 @@ export function FileBrowser({ errorMessage, setErrorMessage }: FileBrowserProps)
|
||||
label="Uploading files"
|
||||
type={FileTransferType.Upload}
|
||||
open={isUploading}
|
||||
count={uploadItems.length}
|
||||
items={uploadItems}
|
||||
onRowClose={handleUploadClose}
|
||||
onCloseAll={() => dismissAllUploads()}
|
||||
@@ -483,7 +555,6 @@ export function FileBrowser({ errorMessage, setErrorMessage }: FileBrowserProps)
|
||||
label="Downloading files"
|
||||
type={FileTransferType.Download}
|
||||
open={isDownloading}
|
||||
count={downloadItems.length}
|
||||
items={downloadItems}
|
||||
onRowClose={name => cancelOrDismissDownload(name)}
|
||||
onCloseAll={() => dismissAllDownloads()}
|
||||
|
||||
+4
-3
@@ -1,4 +1,4 @@
|
||||
import { ReactElement, useCallback } from 'react'
|
||||
import { ReactElement, useCallback, memo } from 'react'
|
||||
import { FileItem } from '../FileItem/FileItem'
|
||||
import { FileInfo, DriveInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import { DownloadProgress, TrackDownloadProps, ViewType } from '../../../constants/transfers'
|
||||
@@ -24,7 +24,7 @@ interface FileBrowserContentProps {
|
||||
setErrorMessage?: (error: string) => void
|
||||
}
|
||||
|
||||
export function FileBrowserContent({
|
||||
function FileBrowserContentInner({
|
||||
listToRender,
|
||||
drives,
|
||||
currentDrive,
|
||||
@@ -127,4 +127,5 @@ export function FileBrowserContent({
|
||||
return <>{renderFileList(listToRender, true)}</>
|
||||
}
|
||||
|
||||
export default FileBrowserContent
|
||||
// Memoize to prevent rerenders when parent FileBrowser rerenders due to upload/download progress
|
||||
export const FileBrowserContent = memo(FileBrowserContentInner)
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { ReactElement } from 'react'
|
||||
import type { FileInfo, DriveInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import { ConfirmModal } from '../ConfirmModal/ConfirmModal'
|
||||
import { Tooltip } from '../Tooltip/Tooltip'
|
||||
import { DeleteFileModal } from '../DeleteFileModal/DeleteFileModal'
|
||||
import { DestroyDriveModal } from '../DestroyDriveModal/DestroyDriveModal'
|
||||
import { FileAction } from '../../constants/transfers'
|
||||
import { TOOLTIPS } from '../../constants/tooltips'
|
||||
|
||||
interface FileBrowserModalsProps {
|
||||
showDeleteModal: boolean
|
||||
@@ -11,12 +13,15 @@ interface FileBrowserModalsProps {
|
||||
fileCountText: string
|
||||
currentDrive: DriveInfo | null
|
||||
confirmBulkForget: boolean
|
||||
confirmBulkRestore: boolean
|
||||
showDestroyDriveModal: boolean
|
||||
pendingCancelUpload: string | null
|
||||
onDeleteCancel: () => void
|
||||
onDeleteProceed: (action: FileAction) => void
|
||||
onForgetConfirm: () => Promise<void>
|
||||
onForgetCancel: () => void
|
||||
onRestoreConfirm: () => Promise<void>
|
||||
onRestoreCancel: () => void
|
||||
onDestroyCancel: () => void
|
||||
onDestroyConfirm: () => Promise<void>
|
||||
onCancelUploadConfirm: () => void
|
||||
@@ -29,12 +34,15 @@ export function FileBrowserModals({
|
||||
fileCountText,
|
||||
currentDrive,
|
||||
confirmBulkForget,
|
||||
confirmBulkRestore,
|
||||
showDestroyDriveModal,
|
||||
pendingCancelUpload,
|
||||
onDeleteCancel,
|
||||
onDeleteProceed,
|
||||
onForgetConfirm,
|
||||
onForgetCancel,
|
||||
onRestoreConfirm,
|
||||
onRestoreCancel,
|
||||
onDestroyCancel,
|
||||
onDestroyConfirm,
|
||||
onCancelUploadConfirm,
|
||||
@@ -53,7 +61,12 @@ export function FileBrowserModals({
|
||||
|
||||
{confirmBulkForget && (
|
||||
<ConfirmModal
|
||||
title="Forget permanently?"
|
||||
title={
|
||||
<>
|
||||
Forget permanently?
|
||||
<Tooltip label={TOOLTIPS.FILE_OPERATION_FORGET} />
|
||||
</>
|
||||
}
|
||||
message={
|
||||
<>
|
||||
This removes <b>{selectedFiles.length}</b> {fileCountText} from your view.
|
||||
@@ -68,6 +81,26 @@ export function FileBrowserModals({
|
||||
/>
|
||||
)}
|
||||
|
||||
{confirmBulkRestore && (
|
||||
<ConfirmModal
|
||||
title={
|
||||
<>
|
||||
Restore from trash?
|
||||
<Tooltip label={TOOLTIPS.FILE_OPERATION_RESTORE_FROM_TRASH} />
|
||||
</>
|
||||
}
|
||||
message={
|
||||
<>
|
||||
This will restore <b>{selectedFiles.length}</b> {fileCountText} from trash.
|
||||
</>
|
||||
}
|
||||
confirmLabel="Restore"
|
||||
cancelLabel="Cancel"
|
||||
onConfirm={onRestoreConfirm}
|
||||
onCancel={onRestoreCancel}
|
||||
/>
|
||||
)}
|
||||
|
||||
{showDestroyDriveModal && currentDrive && (
|
||||
<DestroyDriveModal drive={currentDrive} onCancelClick={onDestroyCancel} doDestroy={onDestroyConfirm} />
|
||||
)}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { ReactElement, useContext, useLayoutEffect, useMemo, useState, useRef, useEffect, useCallback } from 'react'
|
||||
import { PostageBatch } from '@ethersphere/bee-js'
|
||||
import { DriveInfo, FileInfo } from '@solarpunkltd/file-manager-lib'
|
||||
|
||||
import './FileItem.scss'
|
||||
import { GetIconElement } from '../../../utils/GetIconElement'
|
||||
import { ContextMenu } from '../../ContextMenu/ContextMenu'
|
||||
import { useContextMenu } from '../../../hooks/useContextMenu'
|
||||
import { Context as SettingsContext } from '../../../../../providers/Settings'
|
||||
import { ActionTag, DownloadProgress, TrackDownloadProps, ViewType } from '../../../constants/transfers'
|
||||
import { DownloadProgress, TrackDownloadProps, ViewType } from '../../../constants/transfers'
|
||||
import { GetInfoModal } from '../../GetInfoModal/GetInfoModal'
|
||||
import { VersionHistoryModal } from '../../VersionHistoryModal/VersionHistoryModal'
|
||||
import { DeleteFileModal } from '../../DeleteFileModal/DeleteFileModal'
|
||||
@@ -12,17 +15,19 @@ import { RenameFileModal } from '../../RenameFileModal/RenameFileModal'
|
||||
import { buildGetInfoGroups } from '../../../utils/infoGroups'
|
||||
import type { FilePropertyGroup } from '../../../utils/infoGroups'
|
||||
import { useView } from '../../../../../pages/filemanager/ViewContext'
|
||||
import type { DriveInfo, FileInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import { Context as FMContext } from '../../../../../providers/FileManager'
|
||||
import { DestroyDriveModal } from '../../DestroyDriveModal/DestroyDriveModal'
|
||||
import { ConfirmModal } from '../../ConfirmModal/ConfirmModal'
|
||||
|
||||
import { capitalizeFirstLetter, Dir, formatBytes, isTrashed, safeSetState } from '../../../utils/common'
|
||||
import { Tooltip } from '../../Tooltip/Tooltip'
|
||||
import { Dir, formatBytes, isTrashed, safeSetState, truncateNameMiddle } from '../../../utils/common'
|
||||
import { FileAction } from '../../../constants/transfers'
|
||||
import { TOOLTIPS } from '../../../constants/tooltips'
|
||||
import { startDownloadingQueue, createDownloadAbort } from '../../../utils/download'
|
||||
import { computeContextMenuPosition } from '../../../utils/ui'
|
||||
import { getUsableStamps, handleDestroyDrive } from '../../../utils/bee'
|
||||
import { PostageBatch } from '@ethersphere/bee-js'
|
||||
import { getUsableStamps, handleDestroyAndForgetDrive, verifyDriveSpace } from '../../../utils/bee'
|
||||
import { guessMime } from '../../../utils/view'
|
||||
import { performFileOperation, FileOperation } from '../../../utils/fileOperations'
|
||||
import { uuidV4 } from '../../../../../utils'
|
||||
|
||||
interface FileItemProps {
|
||||
fileInfo: FileInfo
|
||||
@@ -54,7 +59,7 @@ export function FileItem({
|
||||
setErrorMessage,
|
||||
}: FileItemProps): ReactElement {
|
||||
const { showContext, pos, contextRef, handleContextMenu, handleCloseContext } = useContextMenu<HTMLDivElement>()
|
||||
const { fm, currentDrive, files, drives, setShowError } = useContext(FMContext)
|
||||
const { fm, adminDrive, currentDrive, files, drives, setShowError, refreshStamp } = useContext(FMContext)
|
||||
const { beeApi } = useContext(SettingsContext)
|
||||
const { view } = useView()
|
||||
|
||||
@@ -69,6 +74,7 @@ export function FileItem({
|
||||
const [showDestroyDriveModal, setShowDestroyDriveModal] = useState(false)
|
||||
const [destroyDrive, setDestroyDrive] = useState<DriveInfo | null>(null)
|
||||
const [confirmForget, setConfirmForget] = useState(false)
|
||||
const [confirmRestore, setConfirmRestore] = useState(false)
|
||||
|
||||
const isMountedRef = useRef(true)
|
||||
const rafIdRef = useRef<number | null>(null)
|
||||
@@ -78,6 +84,10 @@ export function FileItem({
|
||||
const isTrashedFile = isTrashed(fileInfo)
|
||||
const statusLabel = isTrashedFile ? 'Trash' : 'Active'
|
||||
|
||||
const latestFileInfo = useMemo(() => {
|
||||
return files.find(f => f.topic.toString() === fileInfo.topic.toString()) ?? fileInfo
|
||||
}, [files, fileInfo])
|
||||
|
||||
useEffect(() => {
|
||||
isMountedRef.current = true
|
||||
|
||||
@@ -133,55 +143,57 @@ export function FileItem({
|
||||
|
||||
handleCloseContext()
|
||||
|
||||
const rawSize = fileInfo.customMetadata?.size
|
||||
const rawSize = latestFileInfo.customMetadata?.size
|
||||
const expectedSize = rawSize ? Number(rawSize) : undefined
|
||||
|
||||
createDownloadAbort(fileInfo.name)
|
||||
createDownloadAbort(latestFileInfo.name)
|
||||
|
||||
await startDownloadingQueue(
|
||||
fm,
|
||||
[fileInfo],
|
||||
[onDownload({ name: fileInfo.name, size: formatBytes(rawSize), expectedSize })],
|
||||
[latestFileInfo],
|
||||
[
|
||||
onDownload({
|
||||
uuid: uuidV4(),
|
||||
name: latestFileInfo.name,
|
||||
size: formatBytes(rawSize),
|
||||
expectedSize,
|
||||
driveName,
|
||||
}),
|
||||
],
|
||||
isNewWindow,
|
||||
)
|
||||
},
|
||||
[handleCloseContext, fm, beeApi, fileInfo, onDownload],
|
||||
[handleCloseContext, fm, beeApi, latestFileInfo, onDownload, driveName],
|
||||
)
|
||||
// TODO: refactor doTrash, doRecover, doForget to a single function with action param and remove switch case mybe
|
||||
const doTrash = useCallback(async () => {
|
||||
if (!fm) return
|
||||
|
||||
const withMeta: FileInfo = {
|
||||
...fileInfo,
|
||||
customMetadata: {
|
||||
...(fileInfo.customMetadata ?? {}),
|
||||
lifecycle: capitalizeFirstLetter(ActionTag.Trashed),
|
||||
lifecycleAt: new Date().toISOString(),
|
||||
},
|
||||
}
|
||||
const handleFileAction = useCallback(
|
||||
async (operation: FileOperation) => {
|
||||
if (!fm || !driveStamp || !currentDrive) return
|
||||
|
||||
await fm.trashFile(withMeta)
|
||||
}, [fm, fileInfo])
|
||||
await performFileOperation({
|
||||
fm,
|
||||
file: latestFileInfo,
|
||||
redundancyLevel: currentDrive.redundancyLevel,
|
||||
driveId: currentDrive.id.toString(),
|
||||
stamp: driveStamp,
|
||||
adminStamp: fm.adminStamp,
|
||||
adminRedundancy: adminDrive?.redundancyLevel,
|
||||
operation,
|
||||
onError: err => {
|
||||
setErrorMessage?.(err)
|
||||
setShowError(true)
|
||||
},
|
||||
onSuccess: () => {
|
||||
const stampToRefresh = operation === FileOperation.Forget ? fm.adminStamp : driveStamp
|
||||
|
||||
const doRecover = useCallback(async () => {
|
||||
if (!fm) return
|
||||
|
||||
const withMeta: FileInfo = {
|
||||
...fileInfo,
|
||||
customMetadata: {
|
||||
...(fileInfo.customMetadata ?? {}),
|
||||
lifecycle: capitalizeFirstLetter(ActionTag.Recovered),
|
||||
lifecycleAt: new Date().toISOString(),
|
||||
},
|
||||
}
|
||||
await fm.recoverFile(withMeta)
|
||||
}, [fm, fileInfo])
|
||||
|
||||
const doForget = useCallback(async () => {
|
||||
if (!fm) return
|
||||
|
||||
await fm.forgetFile(fileInfo)
|
||||
}, [fm, fileInfo])
|
||||
if (stampToRefresh) {
|
||||
refreshStamp(stampToRefresh.batchID.toString())
|
||||
}
|
||||
},
|
||||
})
|
||||
},
|
||||
[fm, driveStamp, adminDrive, currentDrive, latestFileInfo, refreshStamp, setErrorMessage, setShowError],
|
||||
)
|
||||
|
||||
const showDestroyDrive = useCallback(() => {
|
||||
setDestroyDrive(currentDrive || null)
|
||||
@@ -190,34 +202,52 @@ export function FileItem({
|
||||
|
||||
const doRename = useCallback(
|
||||
async (newName: string) => {
|
||||
if (!fm || !currentDrive) return
|
||||
if (!fm || !driveStamp || !currentDrive) {
|
||||
setErrorMessage?.('Invalid FM or Current Drive')
|
||||
setShowError(true)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (takenNames.has(newName)) throw new Error('name-taken')
|
||||
|
||||
try {
|
||||
verifyDriveSpace({
|
||||
fm,
|
||||
redundancyLevel: currentDrive.redundancyLevel,
|
||||
stamp: driveStamp,
|
||||
useInfoSize: true,
|
||||
driveId: currentDrive.id.toString(),
|
||||
cb: err => {
|
||||
throw new Error(err)
|
||||
},
|
||||
})
|
||||
|
||||
await fm.upload(
|
||||
currentDrive,
|
||||
{
|
||||
name: newName,
|
||||
topic: fileInfo.topic,
|
||||
topic: latestFileInfo.topic,
|
||||
file: {
|
||||
reference: fileInfo.file.reference,
|
||||
historyRef: fileInfo.file.historyRef,
|
||||
reference: latestFileInfo.file.reference,
|
||||
historyRef: latestFileInfo.file.historyRef,
|
||||
},
|
||||
customMetadata: fileInfo.customMetadata,
|
||||
customMetadata: latestFileInfo.customMetadata,
|
||||
files: [],
|
||||
},
|
||||
{
|
||||
actHistoryAddress: fileInfo.file.historyRef,
|
||||
actHistoryAddress: latestFileInfo.file.historyRef,
|
||||
},
|
||||
)
|
||||
|
||||
refreshStamp(driveStamp.batchID.toString())
|
||||
} catch (e: unknown) {
|
||||
setErrorMessage?.(`Error renaming file ${fileInfo.name}`)
|
||||
setErrorMessage?.(`Error renaming file ${latestFileInfo.name}`)
|
||||
setShowError(true)
|
||||
}
|
||||
},
|
||||
|
||||
[fm, currentDrive, fileInfo, takenNames, setErrorMessage, setShowError],
|
||||
[fm, driveStamp, currentDrive, latestFileInfo, takenNames, refreshStamp, setErrorMessage, setShowError],
|
||||
)
|
||||
|
||||
const MenuItem = ({
|
||||
@@ -332,7 +362,7 @@ export function FileItem({
|
||||
danger
|
||||
onClick={() => {
|
||||
handleCloseContext()
|
||||
doRecover()
|
||||
setConfirmRestore(true)
|
||||
}}
|
||||
>
|
||||
Restore
|
||||
@@ -341,7 +371,7 @@ export function FileItem({
|
||||
danger
|
||||
onClick={() => {
|
||||
handleCloseContext()
|
||||
|
||||
// TODO: isn't parentDrive === currentDrive?
|
||||
const parentDrive = drives.find(d => d.id.toString() === fileInfo.driveId.toString())
|
||||
|
||||
if (parentDrive) {
|
||||
@@ -380,7 +410,6 @@ export function FileItem({
|
||||
handleDownload,
|
||||
handleCloseContext,
|
||||
openGetInfo,
|
||||
doRecover,
|
||||
onBulk,
|
||||
currentDrive,
|
||||
drives,
|
||||
@@ -434,6 +463,9 @@ export function FileItem({
|
||||
return <div className="fm-file-item-content">Error</div>
|
||||
}
|
||||
|
||||
const { mime } = guessMime(fileInfo.name, fileInfo.customMetadata)
|
||||
const mimeType = mime.split('/')[0]?.toLowerCase() || 'file'
|
||||
|
||||
return (
|
||||
<div className="fm-file-item-content" onContextMenu={handleItemContextMenu} onClick={handleCloseContext}>
|
||||
<div className="fm-file-item-content-item fm-checkbox">
|
||||
@@ -446,8 +478,8 @@ export function FileItem({
|
||||
</div>
|
||||
|
||||
<div className="fm-file-item-content-item fm-name" onDoubleClick={() => handleDownload(true)}>
|
||||
<GetIconElement icon={fileInfo.name} />
|
||||
{fileInfo.name}
|
||||
<GetIconElement icon={mimeType} />
|
||||
{truncateNameMiddle(fileInfo.name)}
|
||||
</div>
|
||||
|
||||
{showDriveColumn && (
|
||||
@@ -487,7 +519,7 @@ export function FileItem({
|
||||
|
||||
{showVersionHistory && (
|
||||
<VersionHistoryModal
|
||||
fileInfo={fileInfo}
|
||||
fileInfo={latestFileInfo}
|
||||
onCancelClick={() => {
|
||||
setShowVersionHistory(false)
|
||||
}}
|
||||
@@ -504,9 +536,10 @@ export function FileItem({
|
||||
}}
|
||||
onProceed={action => {
|
||||
setShowDeleteModal(false)
|
||||
|
||||
switch (action) {
|
||||
case FileAction.Trash:
|
||||
doTrash()
|
||||
handleFileAction(FileOperation.Trash)
|
||||
break
|
||||
case FileAction.Forget:
|
||||
setConfirmForget(true)
|
||||
@@ -546,7 +579,12 @@ export function FileItem({
|
||||
|
||||
{confirmForget && (
|
||||
<ConfirmModal
|
||||
title="Forget permanently?"
|
||||
title={
|
||||
<>
|
||||
Forget permanently?
|
||||
<Tooltip label={TOOLTIPS.FILE_OPERATION_FORGET} />
|
||||
</>
|
||||
}
|
||||
message={
|
||||
<>
|
||||
This removes <b title={fileInfo.name}>{fileInfo.name}</b> from your view.
|
||||
@@ -557,7 +595,7 @@ export function FileItem({
|
||||
confirmLabel="Forget"
|
||||
cancelLabel="Cancel"
|
||||
onConfirm={async () => {
|
||||
await doForget()
|
||||
await handleFileAction(FileOperation.Forget)
|
||||
|
||||
safeSetState(isMountedRef, setConfirmForget)(false)
|
||||
}}
|
||||
@@ -567,6 +605,32 @@ export function FileItem({
|
||||
/>
|
||||
)}
|
||||
|
||||
{confirmRestore && (
|
||||
<ConfirmModal
|
||||
title={
|
||||
<>
|
||||
Restore from trash?
|
||||
<Tooltip label={TOOLTIPS.FILE_OPERATION_RESTORE_FROM_TRASH} />
|
||||
</>
|
||||
}
|
||||
message={
|
||||
<>
|
||||
This will restore <b title={fileInfo.name}>{fileInfo.name}</b> from trash.
|
||||
</>
|
||||
}
|
||||
confirmLabel="Restore"
|
||||
cancelLabel="Cancel"
|
||||
onConfirm={async () => {
|
||||
await handleFileAction(FileOperation.Recover)
|
||||
|
||||
safeSetState(isMountedRef, setConfirmRestore)(false)
|
||||
}}
|
||||
onCancel={() => {
|
||||
setConfirmRestore(false)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{showDestroyDriveModal && destroyDrive && (
|
||||
<DestroyDriveModal
|
||||
drive={destroyDrive}
|
||||
@@ -577,20 +641,22 @@ export function FileItem({
|
||||
doDestroy={async () => {
|
||||
setShowDestroyDriveModal(false)
|
||||
|
||||
await handleDestroyDrive(
|
||||
await handleDestroyAndForgetDrive({
|
||||
beeApi,
|
||||
fm,
|
||||
destroyDrive,
|
||||
() => {
|
||||
drive: destroyDrive,
|
||||
adminDrive,
|
||||
isDestroy: true,
|
||||
onSuccess: () => {
|
||||
setShowDestroyDriveModal(false)
|
||||
setDestroyDrive(null)
|
||||
},
|
||||
e => {
|
||||
onError: e => {
|
||||
setShowDestroyDriveModal(false)
|
||||
setErrorMessage?.(`Error destroying drive: ${destroyDrive.name}: ${e}`)
|
||||
setShowError(true)
|
||||
},
|
||||
)
|
||||
})
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
+2
-16
@@ -3,26 +3,14 @@ import './FileProgressNotification.scss'
|
||||
import UpIcon from 'remixicon-react/ArrowUpSLineIcon'
|
||||
import DownIcon from 'remixicon-react/ArrowDownSLineIcon'
|
||||
import { FileProgressWindow } from '../FileProgressWindow/FileProgressWindow'
|
||||
import { FileTransferType, TransferStatus } from '../../constants/transfers'
|
||||
|
||||
type ProgressItem = {
|
||||
name: string
|
||||
size?: string
|
||||
percent?: number
|
||||
kind?: FileTransferType
|
||||
status?: TransferStatus
|
||||
driveName?: string
|
||||
etaSec?: number
|
||||
elapsedSec?: number
|
||||
}
|
||||
import { FileTransferType, TransferStatus, ProgressItem } from '../../constants/transfers'
|
||||
|
||||
interface FileProgressNotificationProps {
|
||||
label?: string
|
||||
type: FileTransferType
|
||||
open?: boolean
|
||||
count?: number
|
||||
items?: ProgressItem[]
|
||||
onRowClose?: (name: string) => void
|
||||
onRowClose?: (uuid: string) => void
|
||||
onCloseAll?: () => void
|
||||
}
|
||||
|
||||
@@ -30,7 +18,6 @@ export function FileProgressNotification({
|
||||
label,
|
||||
type,
|
||||
open,
|
||||
count,
|
||||
items,
|
||||
onRowClose,
|
||||
onCloseAll,
|
||||
@@ -88,7 +75,6 @@ export function FileProgressNotification({
|
||||
|
||||
{showFileProgressWindow && (
|
||||
<FileProgressWindow
|
||||
numberOfFiles={items && items.length ? undefined : count}
|
||||
items={items}
|
||||
type={type}
|
||||
onCancelClick={() => setShowFileProgressWindow(false)}
|
||||
|
||||
@@ -4,26 +4,15 @@ import ArrowDownIcon from 'remixicon-react/ArrowDownSLineIcon'
|
||||
import './FileProgressWindow.scss'
|
||||
import { GetIconElement } from '../../utils/GetIconElement'
|
||||
import { ProgressBar } from '../ProgressBar/ProgressBar'
|
||||
import { FileTransferType, TransferBarColor, TransferStatus } from '../../constants/transfers'
|
||||
import { capitalizeFirstLetter } from '../../utils/common'
|
||||
|
||||
type ProgressItem = {
|
||||
name: string
|
||||
percent?: number
|
||||
size?: string
|
||||
kind?: FileTransferType
|
||||
status?: TransferStatus
|
||||
driveName?: string
|
||||
etaSec?: number
|
||||
elapsedSec?: number
|
||||
}
|
||||
import { FileTransferType, TransferBarColor, TransferStatus, ProgressItem } from '../../constants/transfers'
|
||||
import { capitalizeFirstLetter, truncateNameMiddle } from '../../utils/common'
|
||||
import { guessMime } from '../../utils/view'
|
||||
|
||||
interface FileProgressWindowProps {
|
||||
numberOfFiles?: number
|
||||
items?: ProgressItem[]
|
||||
type: FileTransferType
|
||||
onCancelClick: () => void
|
||||
onRowClose?: (name: string) => void
|
||||
onRowClose?: (uuid: string) => void
|
||||
onCloseAll?: () => void
|
||||
}
|
||||
|
||||
@@ -48,7 +37,6 @@ const formatDuration = (sec?: number) => {
|
||||
}
|
||||
|
||||
export function FileProgressWindow({
|
||||
numberOfFiles,
|
||||
items,
|
||||
type,
|
||||
onCancelClick,
|
||||
@@ -57,11 +45,8 @@ export function FileProgressWindow({
|
||||
}: FileProgressWindowProps): ReactElement | null {
|
||||
const listRef = useRef<HTMLDivElement | null>(null)
|
||||
const firstRowRef = useRef<HTMLDivElement | null>(null)
|
||||
const count = items?.length ?? numberOfFiles ?? 0
|
||||
const rows: ProgressItem[] =
|
||||
items && items.length > 0
|
||||
? items
|
||||
: Array.from({ length: count }, (_, i) => ({ name: `Pending file ${i + 1}`, percent: 0, size: '' }))
|
||||
const count = items?.length ?? 0
|
||||
const rows: ProgressItem[] = items ?? []
|
||||
|
||||
const getTransferInfo = (item: ProgressItem, pct?: number) => {
|
||||
const transferType = capitalizeFirstLetter(item?.kind ?? type)
|
||||
@@ -92,6 +77,7 @@ export function FileProgressWindow({
|
||||
const listEl = listRef.current
|
||||
|
||||
if (!rowEl || !listEl) return
|
||||
|
||||
const rowH = rowEl.getBoundingClientRect().height
|
||||
const safeRowH = rowH > 0 ? rowH : 72
|
||||
listEl.style.maxHeight = `${safeRowH * 5}px`
|
||||
@@ -152,24 +138,27 @@ export function FileProgressWindow({
|
||||
|
||||
const centerDisplay = getCenterText() || '\u00A0'
|
||||
|
||||
const { mime } = guessMime(item.name)
|
||||
const mimeType = mime.split('/')[0].toLowerCase() || 'file'
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fm-file-progress-window-file-item"
|
||||
key={`${item.name}`}
|
||||
key={item.uuid || `${item.name}-${idx}`}
|
||||
ref={idx === 0 ? firstRowRef : undefined}
|
||||
>
|
||||
<div className="fm-file-progress-window-file-type-icon">
|
||||
<GetIconElement size="14" icon={item.name} color="black" />
|
||||
<GetIconElement size="14" icon={mimeType} color="black" />
|
||||
</div>
|
||||
|
||||
<div className="fm-file-progress-window-file-datas">
|
||||
<div className="fm-file-progress-window-file-item-header">
|
||||
<div className="fm-file-progress-window-name" title={item.name}>
|
||||
<div className="fm-file-progress-window-name-text">{item.name}</div>
|
||||
<div className="fm-file-progress-window-name-text">{truncateNameMiddle(item.name, 25, 8, 8)}</div>
|
||||
{item.driveName && (
|
||||
<div className="fm-drive-line">
|
||||
<span className="fm-drive-chip" title={`Drive: ${item.driveName}`}>
|
||||
{item.driveName}
|
||||
{truncateNameMiddle(item.driveName, 25, 8, 8)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
@@ -182,7 +171,7 @@ export function FileProgressWindow({
|
||||
<button
|
||||
className="fm-file-progress-window-row-close"
|
||||
aria-label={rowActionLabel}
|
||||
onClick={() => onRowClose?.(item.name)}
|
||||
onClick={() => onRowClose?.(item.uuid)}
|
||||
type="button"
|
||||
>
|
||||
<CloseIcon size="14" />
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
overflow: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
overscroll-behavior: contain;
|
||||
padding-right: 2px;
|
||||
padding-right: 14px;
|
||||
padding-left: 14px;
|
||||
}
|
||||
.fm-modal-window.fm-get-info-modal .fm-modal-window-body::-webkit-scrollbar,
|
||||
.fm-get-info-body::-webkit-scrollbar {
|
||||
@@ -66,23 +67,60 @@
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
max-width: 60%;
|
||||
overflow-wrap: anywhere;
|
||||
word-break: break-word;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||
color: #111827;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.fm-copy-btn {
|
||||
margin-left: 6px;
|
||||
.fm-copyable-value {
|
||||
border: none;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
padding: 2px;
|
||||
line-height: 0;
|
||||
padding: 4px 8px;
|
||||
transition: background-color 0.2s;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.fm-copy-btn:hover {
|
||||
background: #f5f5f5;
|
||||
.fm-copyable-value:hover {
|
||||
background: rgba(237, 129, 49, 0.1);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.fm-copyable-value svg {
|
||||
flex-shrink: 0;
|
||||
color: rgb(237, 129, 49);
|
||||
}
|
||||
|
||||
.fm-copied-indicator {
|
||||
position: absolute;
|
||||
left: -70px;
|
||||
background: rgb(237, 129, 49);
|
||||
color: white;
|
||||
padding: 4px 8px;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
animation: fadeInOut 2s ease-in-out;
|
||||
}
|
||||
|
||||
@keyframes fadeInOut {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateX(-10px);
|
||||
}
|
||||
10% {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
90% {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
100% {
|
||||
opacity: 0;
|
||||
transform: translateX(-10px);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ReactElement, useState } from 'react'
|
||||
import { ReactElement, useState, useEffect } from 'react'
|
||||
import './GetInfoModal.scss'
|
||||
import { Button } from '../Button/Button'
|
||||
import { createPortal } from 'react-dom'
|
||||
@@ -16,11 +16,28 @@ interface GetInfoModalProps {
|
||||
export function GetInfoModal({ name, onCancelClick, properties }: GetInfoModalProps): ReactElement {
|
||||
const modalRoot = document.querySelector('.fm-main') || document.body
|
||||
const [copiedKey, setCopiedKey] = useState<string | null>(null)
|
||||
const timeoutRef = useState<{ [key: string]: NodeJS.Timeout }>({})[0]
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
Object.values(timeoutRef).forEach(timeout => clearTimeout(timeout))
|
||||
}
|
||||
}, [timeoutRef])
|
||||
|
||||
const handleCopy = async (prop: FileProperty) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(prop.raw ?? prop.value)
|
||||
|
||||
if (timeoutRef[prop.key]) {
|
||||
clearTimeout(timeoutRef[prop.key])
|
||||
}
|
||||
|
||||
setCopiedKey(prop.key)
|
||||
window.setTimeout(() => setCopiedKey(null), 1200)
|
||||
|
||||
timeoutRef[prop.key] = setTimeout(() => {
|
||||
setCopiedKey(prev => (prev === prop.key ? null : prev))
|
||||
delete timeoutRef[prop.key]
|
||||
}, 2000)
|
||||
} catch {
|
||||
/* noop */
|
||||
}
|
||||
@@ -45,20 +62,20 @@ export function GetInfoModal({ name, onCancelClick, properties }: GetInfoModalPr
|
||||
{group.properties.map(prop => (
|
||||
<div key={prop.key} className="fm-get-info-modal-property-row">
|
||||
<span className="fm-get-info-modal-property-label">{prop.label}</span>
|
||||
<span className="fm-get-info-modal-property-value">
|
||||
{prop.value}
|
||||
{(prop.raw || prop.value.includes('...')) && (
|
||||
<button
|
||||
className="fm-copy-btn"
|
||||
onClick={() => handleCopy(prop)}
|
||||
aria-label={`Copy ${prop.label}`}
|
||||
type="button"
|
||||
title={copiedKey === prop.key ? 'Copied!' : 'Copy'}
|
||||
>
|
||||
<ClipboardIcon size="14px" />
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
{prop.raw || prop.value.includes('...') ? (
|
||||
<button
|
||||
className="fm-get-info-modal-property-value fm-copyable-value"
|
||||
onClick={() => handleCopy(prop)}
|
||||
aria-label={`Copy ${prop.label}`}
|
||||
type="button"
|
||||
>
|
||||
<ClipboardIcon size="12px" />
|
||||
<span className="fm-copyable-value-text">{prop.value}</span>
|
||||
{copiedKey === prop.key && <span className="fm-copied-indicator">Copied!</span>}
|
||||
</button>
|
||||
) : (
|
||||
<span className="fm-get-info-modal-property-value">{prop.value}</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
.fm-initialization-modal-container {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
background: rgba(237, 237, 237);
|
||||
backdrop-filter: blur(5px);
|
||||
background: transparent;
|
||||
backdrop-filter: none;
|
||||
z-index: 1300;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.fm-initialization-modal-container .fm-modal-window {
|
||||
pointer-events: auto;
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
.fm-initilization-progress-content {
|
||||
@@ -16,3 +23,7 @@
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.fm-main:has(.fm-initialization-modal-container) {
|
||||
border-left: none;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ReactElement, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
|
||||
|
||||
import { BZZ, DAI, Duration, PostageBatch, RedundancyLevel, Size, Utils } from '@ethersphere/bee-js'
|
||||
import { BeeModes, BZZ, DAI, Duration, PostageBatch, RedundancyLevel, Size, Utils } from '@ethersphere/bee-js'
|
||||
import './InitialModal.scss'
|
||||
import { CustomDropdown } from '../CustomDropdown/CustomDropdown'
|
||||
import { Button } from '../Button/Button'
|
||||
@@ -21,7 +21,7 @@ import { TOOLTIPS } from '../../constants/tooltips'
|
||||
interface InitialModalProps {
|
||||
resetState: boolean
|
||||
handleVisibility: (isVisible: boolean) => void
|
||||
handleShowError: (flag: boolean) => void
|
||||
handleShowError: (flag: boolean, errorMessage?: string) => void
|
||||
setIsCreationInProgress: (isCreating: boolean) => void
|
||||
}
|
||||
|
||||
@@ -43,6 +43,25 @@ const createBatchIdOptions = (stamps: PostageBatch[]) => [
|
||||
}),
|
||||
]
|
||||
|
||||
const setSecurityLevel = (setter: (value: RedundancyLevel) => void) => {
|
||||
return (
|
||||
<div className="fm-modal-window-input-container">
|
||||
<label htmlFor="admin-security-level" className="fm-input-label">
|
||||
Security Level <Tooltip label={TOOLTIPS.ADMIN_SECURITY_LEVEL} />
|
||||
</label>
|
||||
<FMSlider
|
||||
id="admin-security-level"
|
||||
defaultValue={0}
|
||||
marks={erasureCodeMarks}
|
||||
onChange={v => setter(v)}
|
||||
minValue={minMarkValue}
|
||||
maxValue={maxMarkValue}
|
||||
step={1}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function InitialModal({
|
||||
resetState,
|
||||
setIsCreationInProgress,
|
||||
@@ -60,8 +79,9 @@ export function InitialModal({
|
||||
const [usableStamps, setUsableStamps] = useState<PostageBatch[]>([])
|
||||
const [selectedBatch, setSelectedBatch] = useState<PostageBatch | null>(null)
|
||||
const [selectedBatchIndex, setSelectedBatchIndex] = useState<number>(-1)
|
||||
const [isNodeSyncing, setIsNodeSyncing] = useState(true)
|
||||
|
||||
const { walletBalance } = useContext(BeeContext)
|
||||
const { walletBalance, nodeInfo } = useContext(BeeContext)
|
||||
const { beeApi } = useContext(SettingsContext)
|
||||
const { fm } = useContext(FMContext)
|
||||
|
||||
@@ -74,30 +94,64 @@ export function InitialModal({
|
||||
}
|
||||
}, [])
|
||||
|
||||
const checkBalances = useCallback(
|
||||
(cost: BZZ) => {
|
||||
setIsBalanceSufficient(true)
|
||||
setIsxDaiBalanceSufficient(true)
|
||||
|
||||
if ((walletBalance && cost.gte(walletBalance.bzzBalance)) || !walletBalance) {
|
||||
safeSetState(isMountedRef, setIsBalanceSufficient)(false)
|
||||
}
|
||||
|
||||
const zeroDAI = DAI.fromDecimalString('0')
|
||||
|
||||
if ((walletBalance && zeroDAI.eq(walletBalance.nativeTokenBalance)) || !walletBalance) {
|
||||
safeSetState(isMountedRef, setIsxDaiBalanceSufficient)(false)
|
||||
}
|
||||
},
|
||||
[walletBalance],
|
||||
)
|
||||
|
||||
const handleCostFetch = useCallback(
|
||||
(cost: BZZ) => {
|
||||
safeSetState(isMountedRef, setIsNodeSyncing)(false)
|
||||
checkBalances(cost)
|
||||
safeSetState(isMountedRef, setCost)(cost.toSignificantDigits(2))
|
||||
},
|
||||
[checkBalances],
|
||||
)
|
||||
|
||||
const handleCostFetchError = useCallback(() => {
|
||||
safeSetState(isMountedRef, setIsNodeSyncing)(true)
|
||||
safeSetState(isMountedRef, setCost)('0')
|
||||
}, [])
|
||||
|
||||
const createAdminDrive = useCallback(async () => {
|
||||
setIsCreationInProgress?.(true)
|
||||
handleVisibility(false)
|
||||
|
||||
await handleCreateDrive(
|
||||
await handleCreateDrive({
|
||||
beeApi,
|
||||
fm,
|
||||
Size.fromBytes(capacity),
|
||||
Duration.fromEndDate(validityEndDate),
|
||||
ADMIN_STAMP_LABEL,
|
||||
false,
|
||||
erasureCodeLevel,
|
||||
true,
|
||||
size: Size.fromBytes(capacity),
|
||||
duration: Duration.fromEndDate(validityEndDate),
|
||||
label: ADMIN_STAMP_LABEL,
|
||||
encryption: false,
|
||||
redundancyLevel: erasureCodeLevel,
|
||||
adminRedundancy: erasureCodeLevel,
|
||||
isAdmin: true,
|
||||
resetState,
|
||||
selectedBatch,
|
||||
() => {
|
||||
existingBatch: selectedBatch,
|
||||
onSuccess: () => {
|
||||
handleVisibility(false)
|
||||
setIsCreationInProgress(false)
|
||||
}, // onSuccess
|
||||
() => {
|
||||
handleShowError(true)
|
||||
},
|
||||
onError: err => {
|
||||
const errorMessage = err instanceof Error ? err.message : String(err)
|
||||
handleShowError(true, errorMessage)
|
||||
setIsCreationInProgress(false)
|
||||
}, // onError
|
||||
)
|
||||
},
|
||||
})
|
||||
}, [
|
||||
beeApi,
|
||||
fm,
|
||||
@@ -113,11 +167,7 @@ export function InitialModal({
|
||||
|
||||
useEffect(() => {
|
||||
const getStamps = async () => {
|
||||
const stamps = (await getUsableStamps(beeApi)).filter(s => {
|
||||
const { capacityPct } = calculateStampCapacityMetrics(s)
|
||||
|
||||
return capacityPct < 100
|
||||
})
|
||||
const stamps = await getUsableStamps(beeApi)
|
||||
|
||||
safeSetState(isMountedRef, setUsableStamps)([...stamps])
|
||||
}
|
||||
@@ -141,70 +191,117 @@ export function InitialModal({
|
||||
false,
|
||||
erasureCodeLevel,
|
||||
beeApi,
|
||||
(cost: BZZ) => {
|
||||
setIsBalanceSufficient(true)
|
||||
setIsxDaiBalanceSufficient(true)
|
||||
|
||||
if ((walletBalance && cost.gte(walletBalance.bzzBalance)) || !walletBalance) {
|
||||
safeSetState(isMountedRef, setIsBalanceSufficient)(false)
|
||||
}
|
||||
|
||||
const zeroDAI = DAI.fromDecimalString('0')
|
||||
|
||||
if ((walletBalance && zeroDAI.eq(walletBalance.nativeTokenBalance)) || !walletBalance) {
|
||||
safeSetState(isMountedRef, setIsxDaiBalanceSufficient)(false)
|
||||
}
|
||||
|
||||
safeSetState(isMountedRef, setCost)(cost.toSignificantDigits(2))
|
||||
},
|
||||
handleCostFetch,
|
||||
currentFetch,
|
||||
handleCostFetchError,
|
||||
)
|
||||
|
||||
if (lifetimeIndex >= 0) {
|
||||
if (lifetimeIndex >= 0 && !isNodeSyncing) {
|
||||
setIsCreateEnabled(true)
|
||||
} else {
|
||||
setIsCreateEnabled(false)
|
||||
}
|
||||
} else {
|
||||
setCost('0')
|
||||
setIsCreateEnabled(false)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [validityEndDate, beeApi, capacity, lifetimeIndex, walletBalance])
|
||||
}, [
|
||||
validityEndDate,
|
||||
erasureCodeLevel,
|
||||
beeApi,
|
||||
capacity,
|
||||
lifetimeIndex,
|
||||
isNodeSyncing,
|
||||
handleCostFetch,
|
||||
handleCostFetchError,
|
||||
])
|
||||
|
||||
useEffect(() => {
|
||||
setValidityEndDate(getExpiryDateByLifetime(lifetimeIndex))
|
||||
}, [lifetimeIndex])
|
||||
|
||||
const nonFullStamps = useMemo(() => {
|
||||
return usableStamps.filter(s => {
|
||||
const { capacityPct } = calculateStampCapacityMetrics(s, [], erasureCodeLevel)
|
||||
|
||||
return capacityPct < 100
|
||||
})
|
||||
}, [usableStamps, erasureCodeLevel])
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedBatchIndex >= 0 && selectedBatchIndex < usableStamps.length) {
|
||||
setSelectedBatch(usableStamps[selectedBatchIndex])
|
||||
if (selectedBatchIndex >= 0 && selectedBatchIndex < nonFullStamps.length) {
|
||||
setSelectedBatch(nonFullStamps[selectedBatchIndex])
|
||||
} else {
|
||||
setSelectedBatch(null)
|
||||
}
|
||||
}, [usableStamps, selectedBatchIndex])
|
||||
}, [nonFullStamps, selectedBatchIndex])
|
||||
|
||||
const { capacityPct, usedSize, totalSize } = useMemo(
|
||||
() => calculateStampCapacityMetrics(selectedBatch),
|
||||
[selectedBatch],
|
||||
)
|
||||
const { capacityPct, usedSize, stampSize } = useMemo(() => {
|
||||
if (!selectedBatch) {
|
||||
return {
|
||||
capacityPct: 0,
|
||||
usedSize: '—',
|
||||
stampSize: '—',
|
||||
usedBytes: 0,
|
||||
stampSizeBytes: 0,
|
||||
remainingBytes: 0,
|
||||
}
|
||||
}
|
||||
|
||||
return calculateStampCapacityMetrics(selectedBatch, [], erasureCodeLevel)
|
||||
}, [selectedBatch, erasureCodeLevel])
|
||||
|
||||
const initText = resetState ? 'Resetting' : 'Initializing'
|
||||
const createText = resetState ? 'Reset' : 'Create'
|
||||
|
||||
const isUltraLightNode = nodeInfo?.beeMode === BeeModes.ULTRA_LIGHT
|
||||
|
||||
const isCreateDriveDisabled =
|
||||
isUltraLightNode ||
|
||||
isNodeSyncing ||
|
||||
(selectedBatch ? false : !isCreateEnabled || !isBalanceSufficient || !isxDaiBalanceSufficient)
|
||||
|
||||
const renderUltraLightNodeWarning = () => {
|
||||
if (!isUltraLightNode) return null
|
||||
|
||||
const upgradeLink = (
|
||||
<a
|
||||
href="https://docs.ethswarm.org/docs/desktop/configuration/#upgrading-from-an-ultra-light-to-a-light-node"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
upgrade
|
||||
</a>
|
||||
)
|
||||
|
||||
if (selectedBatch) {
|
||||
return (
|
||||
<div>
|
||||
{resetState ? 'Resetting' : 'Creating'} a drive requires running a light node. Please {upgradeLink} to
|
||||
continue.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
Purchasing a stamp and {resetState ? 'resetting' : 'creating'} a drive requires running a light node. Please{' '}
|
||||
{upgradeLink} to continue.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fm-initialization-modal-container">
|
||||
<div className="fm-modal-window">
|
||||
<div className="fm-modal-window-header">Welcome to your Swarm File Manager</div>
|
||||
<div>{initText} the File Manager</div>
|
||||
{usableStamps.length > 0 && (
|
||||
{nonFullStamps.length > 0 && (
|
||||
<div className="fm-modal-window-body">
|
||||
<div className="fm-modal-window-input-container">
|
||||
{/* <label htmlFor="admin-desired-lifetime" className="fm-input-label">
|
||||
Link an existing Admin Drive (optional)
|
||||
</label>
|
||||
<br /> */}
|
||||
<CustomDropdown
|
||||
id="batch-id-selector"
|
||||
options={createBatchIdOptions(usableStamps)}
|
||||
options={createBatchIdOptions(nonFullStamps)}
|
||||
value={selectedBatchIndex}
|
||||
label="Link an existing Admin Drive (optional)"
|
||||
onChange={(index: number) => {
|
||||
@@ -219,13 +316,14 @@ export function InitialModal({
|
||||
{selectedBatch && (
|
||||
<div className="fm-drive-item-content">
|
||||
<div className="fm-drive-item-capacity">
|
||||
Capacity <ProgressBar value={capacityPct} width="64px" /> {usedSize} / {totalSize}
|
||||
Capacity <ProgressBar value={capacityPct} width="64px" /> {usedSize} / {stampSize}
|
||||
</div>
|
||||
<div className="fm-drive-item-capacity">
|
||||
Expiry date: {selectedBatch.duration.toEndDate().toLocaleDateString()}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{selectedBatch && setSecurityLevel(setErasureCodeLevel)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -243,20 +341,7 @@ export function InitialModal({
|
||||
placeholder="Select a value"
|
||||
/>
|
||||
</div>
|
||||
<div className="fm-modal-window-input-container">
|
||||
<label htmlFor="admin-security-level" className="fm-input-label">
|
||||
Security Level <Tooltip label={TOOLTIPS.ADMIN_SECURITY_LEVEL} />
|
||||
</label>
|
||||
<FMSlider
|
||||
id="admin-security-level"
|
||||
defaultValue={0}
|
||||
marks={erasureCodeMarks}
|
||||
onChange={value => setErasureCodeLevel(value)}
|
||||
minValue={minMarkValue}
|
||||
maxValue={maxMarkValue}
|
||||
step={1}
|
||||
/>
|
||||
</div>
|
||||
{setSecurityLevel(setErasureCodeLevel)}
|
||||
<div className="fm-modal-window-input-container">
|
||||
<div className="fm-modal-estimated-cost-container">
|
||||
<div className="fm-emphasized-text">Estimated Cost:</div>
|
||||
@@ -267,6 +352,12 @@ export function InitialModal({
|
||||
<Tooltip label={TOOLTIPS.ADMIN_ESTIMATED_COST} />
|
||||
</div>
|
||||
<div>(Based on current network conditions)</div>
|
||||
{renderUltraLightNodeWarning()}
|
||||
{isNodeSyncing && !selectedBatch && (
|
||||
<div className="fm-modal-info-warning" style={{ marginBottom: '16px' }}>
|
||||
Node is syncing. Please wait until sync completes before purchasing a stamp.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -274,7 +365,7 @@ export function InitialModal({
|
||||
<Button
|
||||
label={selectedBatch ? `${createText} Drive` : `Purchase Stamp & ${createText} Drive`}
|
||||
variant="primary"
|
||||
disabled={selectedBatch ? false : !isCreateEnabled || !isBalanceSufficient || !isxDaiBalanceSufficient}
|
||||
disabled={isCreateDriveDisabled}
|
||||
onClick={createAdminDrive}
|
||||
/>
|
||||
<Tooltip
|
||||
|
||||
@@ -7,10 +7,18 @@ import { Context as SettingsContext } from '../../../../providers/Settings'
|
||||
import { PostageBatch } from '@ethersphere/bee-js'
|
||||
import { Context as FMContext } from '../../../../providers/FileManager'
|
||||
import { DriveInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import { FILE_MANAGER_EVENTS } from '../../constants/common'
|
||||
|
||||
const NUMBER_OF_DAYS_WARNING = 7
|
||||
const DAYS_TO_MILLISECONDS_MULTIPLIER = 24 * 60 * 60 * 1000
|
||||
|
||||
const isExpiring = (s: PostageBatch): boolean => {
|
||||
return (
|
||||
s.duration &&
|
||||
s.duration.toEndDate().getTime() <= Date.now() + NUMBER_OF_DAYS_WARNING * DAYS_TO_MILLISECONDS_MULTIPLIER
|
||||
)
|
||||
}
|
||||
|
||||
interface NotificationBarProps {
|
||||
setErrorMessage?: (error: string) => void
|
||||
}
|
||||
@@ -20,7 +28,7 @@ export function NotificationBar({ setErrorMessage }: NotificationBarProps): Reac
|
||||
const [stampsToExpire, setStampsToExpire] = useState<PostageBatch[]>([])
|
||||
const [drivesToExpire, setDrivesToExpire] = useState<DriveInfo[]>([])
|
||||
const { beeApi } = useContext(SettingsContext)
|
||||
const { drives, adminDrive } = useContext(FMContext)
|
||||
const { drives, files, adminDrive } = useContext(FMContext)
|
||||
|
||||
const showExpiration = stampsToExpire.length > 0
|
||||
|
||||
@@ -38,12 +46,7 @@ export function NotificationBar({ setErrorMessage }: NotificationBarProps): Reac
|
||||
(adminDrive?.batchId.toString() === stamp.batchID.toString() ? adminDrive : null)
|
||||
|
||||
if (matchingDrive) {
|
||||
const isExpiring =
|
||||
stamp.duration &&
|
||||
stamp.duration.toEndDate().getTime() <=
|
||||
Date.now() + NUMBER_OF_DAYS_WARNING * DAYS_TO_MILLISECONDS_MULTIPLIER
|
||||
|
||||
if (isExpiring) {
|
||||
if (isExpiring(stamp)) {
|
||||
expiringStamps.push(stamp)
|
||||
expiringDrives.push(matchingDrive)
|
||||
}
|
||||
@@ -61,7 +64,37 @@ export function NotificationBar({ setErrorMessage }: NotificationBarProps): Reac
|
||||
return () => {
|
||||
isMounted = false
|
||||
}
|
||||
}, [beeApi, drives, adminDrive])
|
||||
}, [beeApi, drives, adminDrive, setErrorMessage])
|
||||
|
||||
useEffect(() => {
|
||||
const onDriveUpgradeEnd = (e: Event) => {
|
||||
const { driveId, success, updatedStamp } = (e as CustomEvent).detail || {}
|
||||
|
||||
if (success && updatedStamp && driveId) {
|
||||
if (!isExpiring(updatedStamp)) {
|
||||
setTimeout(() => {
|
||||
setStampsToExpire(prev => {
|
||||
const stampIx = prev.findIndex(s => s.batchID.toString() === updatedStamp.batchID.toString())
|
||||
|
||||
return stampIx !== -1 ? prev.filter((_, i) => i !== stampIx) : prev
|
||||
})
|
||||
|
||||
setDrivesToExpire(prev => {
|
||||
const driveIx = prev.findIndex(d => d.id.toString() === driveId)
|
||||
|
||||
return driveIx !== -1 ? prev.filter((_, i) => i !== driveIx) : prev
|
||||
})
|
||||
}, 150)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_END, onDriveUpgradeEnd as EventListener)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_END, onDriveUpgradeEnd as EventListener)
|
||||
}
|
||||
}, [])
|
||||
|
||||
if (!showExpiration) return null
|
||||
|
||||
@@ -74,6 +107,7 @@ export function NotificationBar({ setErrorMessage }: NotificationBarProps): Reac
|
||||
<ExpiringNotificationModal
|
||||
stamps={stampsToExpire}
|
||||
drives={drivesToExpire}
|
||||
files={files}
|
||||
onCancelClick={() => {
|
||||
setShowExpiringModal(false)
|
||||
}}
|
||||
|
||||
@@ -80,11 +80,52 @@
|
||||
}
|
||||
|
||||
.fm-initialization-modal-container {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
background: transparent;
|
||||
backdrop-filter: none;
|
||||
z-index: 1300;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 24px;
|
||||
box-sizing: border-box;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.fm-initialization-modal-container .fm-modal-window {
|
||||
width: 600px;
|
||||
max-height: calc(100vh - 48px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: visible;
|
||||
pointer-events: auto;
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
.fm-initialization-modal-container .fm-modal-window-header {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.fm-initialization-modal-container .fm-modal-window-footer {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.fm-initialization-modal-container .fm-modal-window-scrollable {
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.fm-main:has(.fm-initialization-modal-container) {
|
||||
border-left: none;
|
||||
}
|
||||
|
||||
@@ -70,99 +70,102 @@ export function PrivateKeyModal({ onSaved }: Props): ReactElement {
|
||||
<div className="fm-modal-window">
|
||||
<div className="fm-modal-window-header">
|
||||
<div>Create Private Key</div>
|
||||
<Tooltip label={TOOLTIPS.PRIVATE_KEY_MODAL_HEADER} />
|
||||
</div>
|
||||
<div>
|
||||
Using a private key ensures that only you can access this File Manager instance. Save it securely before
|
||||
continuing.
|
||||
</div>
|
||||
<div className="fm-modal-info-warning flex-column">
|
||||
<span className="fm-modal-info-warning-text-header">IMPORTANT: Lost keys cannot be recovered</span>
|
||||
<span>
|
||||
Swarm never stores private keys. If you lose this key, access to this File Manager instance will be
|
||||
permanently lost.
|
||||
</span>
|
||||
</div>
|
||||
<div className="fm-modal-window-body">
|
||||
<div className="fm-modal-window-input-container">
|
||||
<label htmlFor="fm-private-key" className="fm-emphasized-text fm-private-key-label">
|
||||
<span>New Private key</span>
|
||||
<button
|
||||
onClick={handleGenerateNew}
|
||||
type="button"
|
||||
className="fm-generate-btn"
|
||||
onMouseEnter={e => (e.currentTarget.style.background = '#e5e7eb')}
|
||||
onMouseLeave={e => (e.currentTarget.style.background = '#f3f4f6')}
|
||||
>
|
||||
Generate New
|
||||
</button>
|
||||
</label>
|
||||
|
||||
<div className="fm-private-key-input-row">
|
||||
<input
|
||||
id="fm-private-key"
|
||||
type="text"
|
||||
className={`fm-input${showError ? ' has-error' : ''} fm-private-key-input`}
|
||||
autoComplete="off"
|
||||
value={value}
|
||||
onChange={e => {
|
||||
setValue(e.target.value)
|
||||
setCopied(false)
|
||||
setShowError(false)
|
||||
}}
|
||||
onBlur={handleBlur}
|
||||
spellCheck={false}
|
||||
/>
|
||||
{
|
||||
<div className="fm-modal-window-scrollable">
|
||||
<div>This key grants access to this File Manager instance. Save it before continuing..</div>
|
||||
<div className="fm-modal-info-warning flex-column">
|
||||
<span className="fm-modal-info-warning-text-header">CRITICAL: Key Cannot Be Recovered</span>
|
||||
<span>
|
||||
Swarm does not store this key and <strong>cannot</strong> retrieve it. Loss of the key will result in
|
||||
permanent loss of access to this File Manager instance.
|
||||
</span>
|
||||
</div>
|
||||
<div className="fm-modal-window-body">
|
||||
<div className="fm-modal-window-input-container">
|
||||
<label htmlFor="fm-private-key" className="fm-emphasized-text fm-private-key-label">
|
||||
<span>1. New Private key</span>
|
||||
<button
|
||||
className="fm-copy-btn"
|
||||
onClick={handleCopyPrivateKey}
|
||||
aria-label="Copy private key"
|
||||
onClick={handleGenerateNew}
|
||||
type="button"
|
||||
title={copied ? 'Copied!' : 'Copy'}
|
||||
className="fm-generate-btn"
|
||||
onMouseEnter={e => (e.currentTarget.style.background = '#e5e7eb')}
|
||||
onMouseLeave={e => (e.currentTarget.style.background = '#f3f4f6')}
|
||||
>
|
||||
{copied ? <CheckDoubleLineIcon size="16px" /> : <ClipboardIcon size="16px" />}
|
||||
Generate New
|
||||
</button>
|
||||
}
|
||||
<Tooltip label={TOOLTIPS.PRIVATE_KEY_MODAL_GENERATED_KEY} />
|
||||
</label>
|
||||
|
||||
<div className="fm-private-key-input-row">
|
||||
<input
|
||||
id="fm-private-key"
|
||||
type="text"
|
||||
className={`fm-input${showError ? ' has-error' : ''} fm-private-key-input`}
|
||||
autoComplete="off"
|
||||
value={value}
|
||||
onChange={e => {
|
||||
setValue(e.target.value)
|
||||
setCopied(false)
|
||||
setShowError(false)
|
||||
}}
|
||||
onBlur={handleBlur}
|
||||
spellCheck={false}
|
||||
/>
|
||||
{
|
||||
<button
|
||||
className="fm-copy-btn"
|
||||
onClick={handleCopyPrivateKey}
|
||||
aria-label="Copy private key"
|
||||
type="button"
|
||||
title={copied ? 'Copied!' : 'Copy'}
|
||||
>
|
||||
{copied ? <CheckDoubleLineIcon size="16px" /> : <ClipboardIcon size="16px" />}
|
||||
</button>
|
||||
}
|
||||
<Tooltip label={TOOLTIPS.PRIVATE_KEY_MODAL_GENERATED_KEY} />
|
||||
</div>
|
||||
<div className="fm-input-hint-error">{showError ? 'Invalid private key.' : ''}</div>
|
||||
</div>
|
||||
|
||||
<div className="fm-modal-window-input-container">
|
||||
<label htmlFor="fm-private-key-confirm" className="fm-emphasized-text fm-confirm-key-label">
|
||||
Confirm Private Key
|
||||
</label>
|
||||
<div className="fm-private-key-input-row">
|
||||
<input
|
||||
id="fm-private-key-confirm"
|
||||
type="text"
|
||||
className="fm-input fm-confirm-key-input"
|
||||
placeholder="Paste or type your private key again"
|
||||
autoComplete="off"
|
||||
value={confirmValue}
|
||||
onChange={e => setConfirmValue(e.target.value)}
|
||||
spellCheck={false}
|
||||
/>
|
||||
<Tooltip label={TOOLTIPS.PRIVATE_KEY_MODAL_CONFIRM_KEY} />
|
||||
</div>
|
||||
<div className="fm-input-hint fm-confirm-key-hint">
|
||||
{confirmValue && value === confirmValue
|
||||
? '✓ Private keys match!'
|
||||
: 'Save the private key securely, then paste or type it again to confirm.'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="fm-input-hint-error">{showError ? 'Invalid private key.' : ''}</div>
|
||||
</div>
|
||||
|
||||
<div className="fm-modal-window-input-container">
|
||||
<label htmlFor="fm-private-key-confirm" className="fm-emphasized-text fm-confirm-key-label">
|
||||
Confirm Private Key
|
||||
</label>
|
||||
<div className="fm-private-key-input-row">
|
||||
<input
|
||||
id="fm-private-key-confirm"
|
||||
type="text"
|
||||
className="fm-input fm-confirm-key-input"
|
||||
placeholder="Paste or type your private key again"
|
||||
autoComplete="off"
|
||||
value={confirmValue}
|
||||
onChange={e => setConfirmValue(e.target.value)}
|
||||
spellCheck={false}
|
||||
/>
|
||||
</div>
|
||||
<div className="fm-input-hint fm-confirm-key-hint">
|
||||
{confirmValue && value === confirmValue ? '✓ Private keys match!' : ''}
|
||||
<div className="fm-modal-window-body">
|
||||
<div className="flex-row">
|
||||
<div>
|
||||
<b>Key Storage:</b>
|
||||
</div>
|
||||
<Tooltip label={TOOLTIPS.PRIVATE_KEY_MODAL_KEY_INFO} />
|
||||
</div>
|
||||
The key is saved only in this browser's local storage. If browser data is cleared, a different browser
|
||||
is used, or the OS is updated, this local copy might be deleted. The key will be required to access this
|
||||
File Manager instance after that.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="fm-modal-window-body">
|
||||
<div className="flex-row">
|
||||
<div>
|
||||
<b>Safety Reminder:</b>
|
||||
</div>
|
||||
</div>
|
||||
<span>
|
||||
A copy of your private key is stored in this browser for convenience, but it’s not a backup - clearing
|
||||
browser data or switching devices will remove it.{' '}
|
||||
<b>Make sure you’ve saved your private key before continuing.</b>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="fm-modal-window-footer">
|
||||
<Button
|
||||
label="Save"
|
||||
|
||||
@@ -7,6 +7,8 @@ import EditIcon from 'remixicon-react/EditLineIcon'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { safeSetState } from '../../utils/common'
|
||||
|
||||
const maxFileNameLength = 60
|
||||
|
||||
interface RenameFileModalProps {
|
||||
currentName: string
|
||||
takenNames?: Set<string> | string[]
|
||||
@@ -115,6 +117,7 @@ export function RenameFileModal({
|
||||
onBlur={() => setTouched(true)}
|
||||
onKeyDown={onKeyDown}
|
||||
placeholder="Enter a new file name"
|
||||
maxLength={maxFileNameLength}
|
||||
/>
|
||||
{error && (
|
||||
<div className="fm-error-text" style={{ marginTop: 8 }}>
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
color: rgb(31, 41, 55);
|
||||
font-weight: 500;
|
||||
transition: background-color 0.3s;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
.fm-drive-item-icon {
|
||||
display: flex;
|
||||
@@ -26,6 +28,7 @@
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: 11px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.fm-drive-item-container {
|
||||
@@ -48,7 +51,41 @@
|
||||
.fm-drive-item-capacity {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
gap: 4px;
|
||||
position: relative;
|
||||
|
||||
& > span {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.fm-tooltip-wrapper {
|
||||
flex-shrink: 0;
|
||||
margin-left: 0;
|
||||
position: relative;
|
||||
z-index: 10;
|
||||
filter: none !important;
|
||||
opacity: 1 !important;
|
||||
pointer-events: auto !important;
|
||||
}
|
||||
|
||||
&.fm-drive-item-capacity-updating {
|
||||
& > span {
|
||||
filter: blur(2px);
|
||||
opacity: 0.6;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
// Keep tooltip interactive even when capacity is updating
|
||||
.fm-tooltip-wrapper {
|
||||
filter: none;
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
}
|
||||
|
||||
.fm-drive-item-actions {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ReactElement, useState, useContext, useEffect, useRef, useMemo } from 'react'
|
||||
import { ReactElement, useState, useContext, useEffect, useMemo, useCallback, useRef, memo } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import Drive from 'remixicon-react/HardDrive2LineIcon'
|
||||
import DriveFill from 'remixicon-react/HardDrive2FillIcon'
|
||||
@@ -8,15 +8,150 @@ import { ProgressBar } from '../../ProgressBar/ProgressBar'
|
||||
import { ContextMenu } from '../../ContextMenu/ContextMenu'
|
||||
import { useContextMenu } from '../../../hooks/useContextMenu'
|
||||
import { Button } from '../../Button/Button'
|
||||
import { DestroyDriveModal } from '../../DestroyDriveModal/DestroyDriveModal'
|
||||
import { DestroyDriveModal, ProgressDestroyModal } from '../../DestroyDriveModal/DestroyDriveModal'
|
||||
import { UpgradeDriveModal } from '../../UpgradeDriveModal/UpgradeDriveModal'
|
||||
import { UpgradeTimeoutModal } from '../../UpgradeTimeoutModal/UpgradeTimeoutModal'
|
||||
import { ViewType } from '../../../constants/transfers'
|
||||
import { useView } from '../../../../../pages/filemanager/ViewContext'
|
||||
import { Context as FMContext } from '../../../../../providers/FileManager'
|
||||
import { PostageBatch } from '@ethersphere/bee-js'
|
||||
import { DriveInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import { calculateStampCapacityMetrics, handleDestroyDrive } from '../../../utils/bee'
|
||||
import { calculateStampCapacityMetrics, handleDestroyAndForgetDrive } from '../../../utils/bee'
|
||||
import { Context as SettingsContext } from '../../../../../providers/Settings'
|
||||
import { truncateNameMiddle } from '../../../utils/common'
|
||||
import { Tooltip } from '../../Tooltip/Tooltip'
|
||||
import { TOOLTIPS } from '../../../constants/tooltips'
|
||||
import { FILE_MANAGER_EVENTS, UPLOAD_POLLING_TIMEOUT_MS } from '../../../constants/common'
|
||||
import { useStampPolling } from '../../../hooks/useStampPolling'
|
||||
|
||||
function useDriveEventListeners(
|
||||
driveId: string,
|
||||
handleUpgradeStart: (eventDriveId: string, id: string) => void,
|
||||
handleUpgradeEnd: (
|
||||
eventDriveId: string,
|
||||
id: string,
|
||||
success: boolean,
|
||||
error: string | undefined,
|
||||
updatedStamp?: PostageBatch,
|
||||
) => void,
|
||||
handleUpgradeTimeout: (eventDriveId: string, id: string) => void,
|
||||
handleFileUploaded: (e: Event) => void,
|
||||
) {
|
||||
useEffect(() => {
|
||||
const onStart = (e: Event) => {
|
||||
const { driveId: eventDriveId } = (e as CustomEvent).detail || {}
|
||||
handleUpgradeStart(eventDriveId, driveId)
|
||||
}
|
||||
|
||||
const onEnd = (e: Event) => {
|
||||
const { driveId: eventDriveId, success, error, updatedStamp } = (e as CustomEvent).detail || {}
|
||||
handleUpgradeEnd(eventDriveId, driveId, success, error, updatedStamp)
|
||||
}
|
||||
|
||||
const onTimeout = (e: Event) => {
|
||||
const { driveId: eventDriveId } = (e as CustomEvent).detail || {}
|
||||
handleUpgradeTimeout(eventDriveId, driveId)
|
||||
}
|
||||
|
||||
window.addEventListener(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_START, onStart as EventListener)
|
||||
window.addEventListener(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_END, onEnd as EventListener)
|
||||
window.addEventListener(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_TIMEOUT, onTimeout as EventListener)
|
||||
window.addEventListener(FILE_MANAGER_EVENTS.FILE_UPLOADED, handleFileUploaded as EventListener)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_START, onStart as EventListener)
|
||||
window.removeEventListener(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_END, onEnd as EventListener)
|
||||
window.removeEventListener(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_TIMEOUT, onTimeout as EventListener)
|
||||
window.removeEventListener(FILE_MANAGER_EVENTS.FILE_UPLOADED, handleFileUploaded as EventListener)
|
||||
}
|
||||
}, [driveId, handleUpgradeStart, handleUpgradeEnd, handleUpgradeTimeout, handleFileUploaded])
|
||||
}
|
||||
|
||||
interface DriveModalsProps {
|
||||
isUpgradeDriveModalOpen: boolean
|
||||
setIsUpgradeDriveModalOpen: (open: boolean) => void
|
||||
isUpgradeTimeoutModalOpen: boolean
|
||||
actualStamp: PostageBatch
|
||||
drive: DriveInfo
|
||||
setErrorMessage?: (error: string) => void
|
||||
isUpgrading: boolean
|
||||
isCapacityUpdating: boolean
|
||||
isDestroying: boolean
|
||||
setIsProgressModalOpen: (open: boolean) => void
|
||||
isProgressModalOpen: boolean
|
||||
isDestroyDriveModalOpen: boolean
|
||||
setIsDestroyDriveModalOpen: (open: boolean) => void
|
||||
doDestroy: () => Promise<void>
|
||||
onCancelTimeout: () => void
|
||||
}
|
||||
|
||||
function DriveModals({
|
||||
isUpgradeDriveModalOpen,
|
||||
setIsUpgradeDriveModalOpen,
|
||||
isUpgradeTimeoutModalOpen,
|
||||
actualStamp,
|
||||
drive,
|
||||
setErrorMessage,
|
||||
isUpgrading,
|
||||
isCapacityUpdating,
|
||||
isDestroying,
|
||||
setIsProgressModalOpen,
|
||||
isProgressModalOpen,
|
||||
isDestroyDriveModalOpen,
|
||||
setIsDestroyDriveModalOpen,
|
||||
doDestroy,
|
||||
onCancelTimeout,
|
||||
}: DriveModalsProps): ReactElement | null {
|
||||
return (
|
||||
<>
|
||||
{isUpgradeDriveModalOpen && (
|
||||
<UpgradeDriveModal
|
||||
stamp={actualStamp}
|
||||
drive={drive}
|
||||
onCancelClick={() => setIsUpgradeDriveModalOpen(false)}
|
||||
setErrorMessage={setErrorMessage}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isUpgradeTimeoutModalOpen && <UpgradeTimeoutModal driveName={drive.name} onOk={onCancelTimeout} />}
|
||||
|
||||
{isUpgrading && (
|
||||
<div className="fm-drive-item-creating-overlay" aria-live="polite">
|
||||
<div className="fm-mini-spinner" />
|
||||
<span>Upgrading drive…</span>
|
||||
</div>
|
||||
)}
|
||||
{isCapacityUpdating && !isUpgrading && (
|
||||
<div className="fm-drive-item-creating-overlay" aria-live="polite">
|
||||
<div className="fm-mini-spinner" />
|
||||
<span>Updating capacity…</span>
|
||||
</div>
|
||||
)}
|
||||
{isDestroying && (
|
||||
<div
|
||||
className="fm-drive-item-creating-overlay"
|
||||
aria-live="polite"
|
||||
onClick={() => setIsProgressModalOpen(true)}
|
||||
style={{ cursor: 'pointer' }}
|
||||
title="Click to show progress modal"
|
||||
>
|
||||
<div className="fm-mini-spinner" />
|
||||
<span>Destroying drive…</span>
|
||||
</div>
|
||||
)}
|
||||
{isProgressModalOpen && isDestroying && (
|
||||
<ProgressDestroyModal drive={drive} onMinimize={() => setIsProgressModalOpen(false)} />
|
||||
)}
|
||||
{isDestroyDriveModalOpen && (
|
||||
<DestroyDriveModal
|
||||
drive={drive}
|
||||
onCancelClick={() => setIsDestroyDriveModalOpen(false)}
|
||||
doDestroy={doDestroy}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
interface DriveItemProps {
|
||||
drive: DriveInfo
|
||||
@@ -25,122 +160,247 @@ interface DriveItemProps {
|
||||
setErrorMessage?: (error: string) => void
|
||||
}
|
||||
|
||||
export function DriveItem({ drive, stamp, isSelected, setErrorMessage }: DriveItemProps): ReactElement {
|
||||
const { fm, setShowError, refreshStamp } = useContext(FMContext)
|
||||
function DriveItemComponent({ drive, stamp, isSelected, setErrorMessage }: DriveItemProps): ReactElement {
|
||||
const { fm, adminDrive, files, setShowError, refreshStamp } = useContext(FMContext)
|
||||
const { beeApi } = useContext(SettingsContext)
|
||||
|
||||
const driveId = drive.id.toString()
|
||||
|
||||
const [isHovered, setIsHovered] = useState(false)
|
||||
const [isDestroyDriveModalOpen, setIsDestroyDriveModalOpen] = useState(false)
|
||||
const [isProgressModalOpen, setIsProgressModalOpen] = useState(false)
|
||||
const [isUpgradeDriveModalOpen, setIsUpgradeDriveModalOpen] = useState(false)
|
||||
const isMountedRef = useRef(true)
|
||||
const [isUpgradeTimeoutModalOpen, setIsUpgradeTimeoutModalOpen] = useState(false)
|
||||
const [isUpgrading, setIsUpgrading] = useState(false)
|
||||
const [isCapacityUpdating, setIsCapacityUpdating] = useState(false)
|
||||
const [isDestroying, setIsDestroying] = useState(false)
|
||||
const [actualStamp, setActualStamp] = useState<PostageBatch>(stamp)
|
||||
const batchIDRef = useRef(stamp.batchID)
|
||||
const isUpgradingRef = useRef(false)
|
||||
const actualStampRef = useRef(actualStamp)
|
||||
const startPollingRef = useRef<((stamp: PostageBatch) => void) | null>(null)
|
||||
const stopPollingRef = useRef<(() => void) | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
actualStampRef.current = actualStamp
|
||||
}, [actualStamp])
|
||||
|
||||
const handleStampUpdated = useCallback((updatedStamp: PostageBatch) => {
|
||||
setActualStamp(updatedStamp)
|
||||
batchIDRef.current = updatedStamp.batchID
|
||||
}, [])
|
||||
|
||||
const handlePollingStateChange = useCallback((isPolling: boolean) => {
|
||||
setIsCapacityUpdating(isPolling)
|
||||
}, [])
|
||||
|
||||
const { startPolling, stopPolling } = useStampPolling({
|
||||
onStampUpdated: handleStampUpdated,
|
||||
onPollingStateChange: handlePollingStateChange,
|
||||
refreshStamp,
|
||||
timeout: UPLOAD_POLLING_TIMEOUT_MS,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
startPollingRef.current = startPolling
|
||||
}, [startPolling])
|
||||
|
||||
useEffect(() => {
|
||||
stopPollingRef.current = stopPolling
|
||||
}, [stopPolling])
|
||||
|
||||
const { showContext, pos, contextRef, setPos, setShowContext } = useContextMenu<HTMLDivElement>()
|
||||
|
||||
const { setView, setActualItemView } = useView()
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
isMountedRef.current = false
|
||||
if (isUpgradingRef.current) {
|
||||
return
|
||||
}
|
||||
}, [])
|
||||
|
||||
if (actualStamp.batchID.toString() !== stamp.batchID.toString()) {
|
||||
setActualStamp(stamp)
|
||||
batchIDRef.current = stamp.batchID
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const incomingSize = stamp.size.toBytes()
|
||||
const currentSize = actualStamp.size.toBytes()
|
||||
const incomingExpiry = stamp.duration.toEndDate().getTime()
|
||||
const currentExpiry = actualStamp.duration.toEndDate().getTime()
|
||||
|
||||
if (incomingSize > currentSize || incomingExpiry > currentExpiry) {
|
||||
setActualStamp(stamp)
|
||||
batchIDRef.current = stamp.batchID
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [stamp])
|
||||
|
||||
useEffect(() => {
|
||||
setActualStamp(stamp)
|
||||
}, [stamp])
|
||||
return () => {
|
||||
if (stopPollingRef.current) {
|
||||
stopPollingRef.current()
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
function handleMenuClick(e: React.MouseEvent) {
|
||||
setShowContext(true)
|
||||
setPos({ x: e.clientX, y: e.clientY })
|
||||
}
|
||||
|
||||
function handleDestroyDriveClick() {
|
||||
setShowContext(false)
|
||||
}
|
||||
const handleUpgradeStart = useCallback((driveId: string, id: string) => {
|
||||
if (driveId !== id) return
|
||||
|
||||
useEffect(() => {
|
||||
const id = drive.id.toString()
|
||||
const batchId = stamp.batchID.toString()
|
||||
isUpgradingRef.current = true
|
||||
setIsUpgrading(true)
|
||||
}, [])
|
||||
|
||||
const onStart = (e: Event) => {
|
||||
const { driveId } = (e as CustomEvent).detail || {}
|
||||
const handleUpgradeEnd = useCallback(
|
||||
(driveId: string, id: string, success: boolean, error: string | undefined, updatedStamp?: PostageBatch) => {
|
||||
if (driveId !== id) return
|
||||
|
||||
if (driveId === id) {
|
||||
setIsUpgrading(true)
|
||||
}
|
||||
}
|
||||
|
||||
const onEnd = async (e: Event) => {
|
||||
const { driveId, success, error } = (e as CustomEvent).detail || {}
|
||||
|
||||
if (!success) {
|
||||
if (error) {
|
||||
setErrorMessage?.(error)
|
||||
}
|
||||
|
||||
setShowError(true)
|
||||
}
|
||||
|
||||
if (driveId === id) {
|
||||
const resetUpgrading = () => {
|
||||
setIsUpgrading(false)
|
||||
|
||||
const upgradedStamp = await refreshStamp(batchId)
|
||||
|
||||
if (!isMountedRef.current) return
|
||||
|
||||
if (upgradedStamp) {
|
||||
setActualStamp(upgradedStamp)
|
||||
}
|
||||
isUpgradingRef.current = false
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('fm:drive-upgrade-start', onStart as EventListener)
|
||||
window.addEventListener('fm:drive-upgrade-end', onEnd as EventListener)
|
||||
if (!success && error) {
|
||||
resetUpgrading()
|
||||
setErrorMessage?.(error)
|
||||
setShowError(true)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('fm:drive-upgrade-start', onStart as EventListener)
|
||||
window.removeEventListener('fm:drive-upgrade-end', onEnd as EventListener)
|
||||
}
|
||||
}, [drive.id, setShowError, setErrorMessage, stamp.batchID, refreshStamp])
|
||||
return
|
||||
}
|
||||
|
||||
const { capacityPct, usedSize, totalSize } = useMemo(
|
||||
() => calculateStampCapacityMetrics(actualStamp, drive),
|
||||
[actualStamp, drive],
|
||||
if (updatedStamp) {
|
||||
setActualStamp(updatedStamp)
|
||||
batchIDRef.current = updatedStamp.batchID
|
||||
setTimeout(resetUpgrading, 300)
|
||||
} else {
|
||||
resetUpgrading()
|
||||
}
|
||||
},
|
||||
[setErrorMessage, setShowError],
|
||||
)
|
||||
|
||||
const doDestroy = useCallback(async () => {
|
||||
const closeModals = () => {
|
||||
setIsDestroyDriveModalOpen(false)
|
||||
setIsDestroying(false)
|
||||
setIsProgressModalOpen(false)
|
||||
}
|
||||
|
||||
setIsDestroyDriveModalOpen(false)
|
||||
setIsProgressModalOpen(true)
|
||||
setIsDestroying(true)
|
||||
|
||||
await handleDestroyAndForgetDrive({
|
||||
beeApi,
|
||||
fm,
|
||||
drive,
|
||||
isDestroy: true,
|
||||
adminDrive,
|
||||
onSuccess: closeModals,
|
||||
onError: e => {
|
||||
closeModals()
|
||||
setErrorMessage?.(`Error destroying drive: ${drive.name}: ${e}`)
|
||||
setShowError(true)
|
||||
},
|
||||
})
|
||||
}, [beeApi, fm, drive, adminDrive, setErrorMessage, setShowError])
|
||||
|
||||
const handleUpgradeTimeout = useCallback(
|
||||
(eventDriveId: string, id: string) => {
|
||||
if (eventDriveId !== id) return
|
||||
setIsUpgradeTimeoutModalOpen(true)
|
||||
},
|
||||
[setIsUpgradeTimeoutModalOpen],
|
||||
)
|
||||
|
||||
const handleCancelTimeout = useCallback(() => {
|
||||
setIsUpgrading(false)
|
||||
isUpgradingRef.current = false
|
||||
setIsUpgradeTimeoutModalOpen(false)
|
||||
|
||||
if (startPollingRef.current && actualStampRef.current) {
|
||||
startPollingRef.current(actualStampRef.current)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleFileUploaded = useCallback(
|
||||
(e: Event) => {
|
||||
const { fileInfo } = (e as CustomEvent).detail || {}
|
||||
|
||||
if (!fileInfo || fileInfo.driveId !== driveId || !startPollingRef.current) return
|
||||
|
||||
startPollingRef.current(actualStampRef.current)
|
||||
},
|
||||
[driveId],
|
||||
)
|
||||
|
||||
useDriveEventListeners(driveId, handleUpgradeStart, handleUpgradeEnd, handleUpgradeTimeout, handleFileUploaded)
|
||||
|
||||
const { capacityPct, usedSize, stampSize } = useMemo(() => {
|
||||
const filesPerDrive = files.filter(fi => fi.driveId === drive.id.toString())
|
||||
|
||||
return calculateStampCapacityMetrics(actualStamp, filesPerDrive, drive.redundancyLevel, isCapacityUpdating)
|
||||
}, [actualStamp, drive, files, isCapacityUpdating])
|
||||
|
||||
const handleDriveClick = useCallback(() => {
|
||||
setView(ViewType.File)
|
||||
setActualItemView?.(drive.name)
|
||||
}, [setView, setActualItemView, drive.name])
|
||||
|
||||
const handleDestroyClick = useCallback(() => {
|
||||
setShowContext(false)
|
||||
setIsDestroyDriveModalOpen(true)
|
||||
}, [setShowContext, setIsDestroyDriveModalOpen])
|
||||
|
||||
const selectedClass = isSelected ? ' fm-drive-item-container-selected' : ''
|
||||
const containerClassName = `fm-drive-item-container${selectedClass}`
|
||||
|
||||
const updatingClass = isUpgrading || isCapacityUpdating ? ' fm-drive-item-capacity-updating' : ''
|
||||
const capacityClassName = `fm-drive-item-capacity${updatingClass}`
|
||||
|
||||
const driveIcon = isHovered ? <DriveFill size="16px" /> : <Drive size="16px" />
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`fm-drive-item-container${isSelected ? ' fm-drive-item-container-selected' : ''}`}
|
||||
onClick={() => {
|
||||
setView(ViewType.File)
|
||||
setActualItemView?.(drive.name)
|
||||
}}
|
||||
>
|
||||
<div className={containerClassName} onClick={handleDriveClick}>
|
||||
<div
|
||||
className="fm-drive-item-info"
|
||||
onMouseEnter={() => setIsHovered(true)}
|
||||
onMouseLeave={() => setIsHovered(false)}
|
||||
>
|
||||
<div className="fm-drive-item-header">
|
||||
<div className="fm-drive-item-icon">{isHovered ? <DriveFill size="16px" /> : <Drive size="16px" />}</div>
|
||||
<div>{drive.name}</div>
|
||||
<div className="fm-drive-item-icon">{driveIcon}</div>
|
||||
<div>{truncateNameMiddle(drive.name, 35, 8, 8)}</div>
|
||||
</div>
|
||||
<div className="fm-drive-item-content">
|
||||
<div className="fm-drive-item-capacity">
|
||||
Capacity <ProgressBar value={capacityPct} width="64px" /> {usedSize} / {totalSize}
|
||||
<div className={capacityClassName}>
|
||||
<span>
|
||||
Capacity <ProgressBar value={capacityPct} width="64px" /> {usedSize} / {stampSize}
|
||||
</span>
|
||||
<Tooltip
|
||||
label={
|
||||
isUpgrading || isCapacityUpdating ? TOOLTIPS.DRIVE_CAPACITY_UPDATING : TOOLTIPS.DRIVE_CAPACITY_INFO
|
||||
}
|
||||
iconSize="12px"
|
||||
disableMargin={true}
|
||||
/>
|
||||
</div>
|
||||
<div className="fm-drive-item-capacity">
|
||||
Expiry date: {actualStamp.duration.toEndDate().toLocaleDateString()}
|
||||
<div className={capacityClassName}>
|
||||
<span>Expiry date: {actualStamp.duration.toEndDate().toLocaleDateString()}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="fm-drive-item-actions">
|
||||
<MoreFill
|
||||
size="13"
|
||||
className={`fm-pointer${isUpgrading ? ' fm-disabled' : ''}`}
|
||||
onClick={!isUpgrading ? handleMenuClick : undefined}
|
||||
aria-disabled={isUpgrading ? 'true' : 'false'}
|
||||
className={`fm-pointer${isUpgrading || isDestroying ? ' fm-disabled' : ''}`}
|
||||
onClick={!isUpgrading && !isDestroying ? handleMenuClick : undefined}
|
||||
aria-disabled={isUpgrading || isDestroying ? 'true' : 'false'}
|
||||
/>
|
||||
{showContext &&
|
||||
createPortal(
|
||||
@@ -153,13 +413,7 @@ export function DriveItem({ drive, stamp, isSelected, setErrorMessage }: DriveIt
|
||||
}}
|
||||
>
|
||||
<ContextMenu>
|
||||
<div
|
||||
className="fm-context-item red"
|
||||
onClick={() => {
|
||||
handleDestroyDriveClick()
|
||||
setIsDestroyDriveModalOpen(true)
|
||||
}}
|
||||
>
|
||||
<div className="fm-context-item red" onClick={handleDestroyClick}>
|
||||
Destroy entire drive
|
||||
</div>
|
||||
</ContextMenu>
|
||||
@@ -171,48 +425,38 @@ export function DriveItem({ drive, stamp, isSelected, setErrorMessage }: DriveIt
|
||||
label="Upgrade"
|
||||
variant="primary"
|
||||
size="small"
|
||||
disabled={isUpgrading}
|
||||
disabled={isUpgrading || isDestroying}
|
||||
onClick={() => setIsUpgradeDriveModalOpen(true)}
|
||||
/>
|
||||
</div>
|
||||
{isUpgradeDriveModalOpen && (
|
||||
<UpgradeDriveModal
|
||||
stamp={actualStamp}
|
||||
drive={drive}
|
||||
onCancelClick={() => setIsUpgradeDriveModalOpen(false)}
|
||||
setErrorMessage={setErrorMessage}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isUpgrading && (
|
||||
<div className="fm-drive-item-creating-overlay" aria-live="polite">
|
||||
<div className="fm-mini-spinner" />
|
||||
<span>Upgrading drive…</span>
|
||||
</div>
|
||||
)}
|
||||
{isDestroyDriveModalOpen && (
|
||||
<DestroyDriveModal
|
||||
drive={drive}
|
||||
onCancelClick={() => setIsDestroyDriveModalOpen(false)}
|
||||
doDestroy={async () => {
|
||||
setIsDestroyDriveModalOpen(false)
|
||||
|
||||
await handleDestroyDrive(
|
||||
beeApi,
|
||||
fm,
|
||||
drive,
|
||||
() => {
|
||||
setIsDestroyDriveModalOpen(false)
|
||||
},
|
||||
e => {
|
||||
setIsDestroyDriveModalOpen(false)
|
||||
setErrorMessage?.(`Error destroying drive: ${drive.name}: ${e}`)
|
||||
setShowError(true)
|
||||
},
|
||||
)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<DriveModals
|
||||
isUpgradeDriveModalOpen={isUpgradeDriveModalOpen}
|
||||
setIsUpgradeDriveModalOpen={setIsUpgradeDriveModalOpen}
|
||||
isUpgradeTimeoutModalOpen={isUpgradeTimeoutModalOpen}
|
||||
actualStamp={actualStamp}
|
||||
drive={drive}
|
||||
setErrorMessage={setErrorMessage}
|
||||
isUpgrading={isUpgrading}
|
||||
isCapacityUpdating={isCapacityUpdating}
|
||||
isDestroying={isDestroying}
|
||||
setIsProgressModalOpen={setIsProgressModalOpen}
|
||||
isProgressModalOpen={isProgressModalOpen}
|
||||
isDestroyDriveModalOpen={isDestroyDriveModalOpen}
|
||||
setIsDestroyDriveModalOpen={setIsDestroyDriveModalOpen}
|
||||
doDestroy={doDestroy}
|
||||
onCancelTimeout={handleCancelTimeout}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function arePropsEqual(prevProps: DriveItemProps, nextProps: DriveItemProps) {
|
||||
const driveIdEqual = prevProps.drive.id.toString() === nextProps.drive.id.toString()
|
||||
const stampIdEqual = prevProps.stamp.batchID.toString() === nextProps.stamp.batchID.toString()
|
||||
const isSelectedEqual = prevProps.isSelected === nextProps.isSelected
|
||||
|
||||
return driveIdEqual && stampIdEqual && isSelectedEqual
|
||||
}
|
||||
|
||||
export const MemoizedDriveItem = memo(DriveItemComponent, arePropsEqual)
|
||||
export const DriveItem = MemoizedDriveItem
|
||||
|
||||
@@ -7,9 +7,10 @@ import { ContextMenu } from '../../ContextMenu/ContextMenu'
|
||||
import { useContextMenu } from '../../../hooks/useContextMenu'
|
||||
import { DriveInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import { Context as FMContext } from '../../../../../providers/FileManager'
|
||||
import { handleForgetDrive } from '../../../utils/bee'
|
||||
import { handleDestroyAndForgetDrive } from '../../../utils/bee'
|
||||
import { ConfirmModal } from '../../ConfirmModal/ConfirmModal'
|
||||
import './DriveItem.scss'
|
||||
import { truncateNameMiddle } from '../../../utils/common'
|
||||
|
||||
interface Props {
|
||||
drive: DriveInfo
|
||||
@@ -18,7 +19,7 @@ interface Props {
|
||||
}
|
||||
|
||||
export function ExpiredDriveItem({ drive, onForgot, setErrorMessage }: Props): ReactElement {
|
||||
const { fm, setShowError } = useContext(FMContext)
|
||||
const { fm, adminDrive, setShowError } = useContext(FMContext)
|
||||
const [isHovered, setIsHovered] = useState(false)
|
||||
const [showForgetConfirm, setShowForgetConfirm] = useState(false)
|
||||
const { showContext, pos, contextRef, setPos, setShowContext } = useContextMenu<HTMLDivElement>()
|
||||
@@ -37,7 +38,7 @@ export function ExpiredDriveItem({ drive, onForgot, setErrorMessage }: Props): R
|
||||
<div className="fm-drive-item-info">
|
||||
<div className="fm-drive-item-header">
|
||||
<div className="fm-drive-item-icon">{isHovered ? <DriveFill size="16px" /> : <Drive size="16px" />}</div>
|
||||
<div>{drive.name}</div>
|
||||
<div>{truncateNameMiddle(drive.name, 35, 8, 8)}</div>
|
||||
</div>
|
||||
<div className="fm-drive-item-content">
|
||||
<div className="fm-drive-item-capacity">Stamp expired — files unavailable</div>
|
||||
@@ -89,21 +90,21 @@ export function ExpiredDriveItem({ drive, onForgot, setErrorMessage }: Props): R
|
||||
cancelLabel="Keep"
|
||||
onCancel={() => setShowForgetConfirm(false)}
|
||||
onConfirm={async () => {
|
||||
if (!fm) return
|
||||
|
||||
await handleForgetDrive(
|
||||
await handleDestroyAndForgetDrive({
|
||||
fm,
|
||||
drive,
|
||||
async () => {
|
||||
isDestroy: false,
|
||||
adminDrive,
|
||||
onSuccess: async () => {
|
||||
setShowForgetConfirm(false)
|
||||
await onForgot?.()
|
||||
},
|
||||
() => {
|
||||
onError: () => {
|
||||
setShowForgetConfirm(false)
|
||||
setErrorMessage?.(`Failed to forget drive ${drive.name}`)
|
||||
setShowError(true)
|
||||
},
|
||||
)
|
||||
})
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -40,6 +40,14 @@
|
||||
}
|
||||
}
|
||||
|
||||
.fm-sidebar-item-description {
|
||||
padding: 8px 12px;
|
||||
text-align: center;
|
||||
color: rgb(75, 85, 99);
|
||||
font-size: 14px;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.fm-sidebar-drive-creation {
|
||||
padding: 12px;
|
||||
border-top: 1px solid rgb(146, 146, 146);
|
||||
|
||||
@@ -20,6 +20,8 @@ import { useView } from '../../../../pages/filemanager/ViewContext'
|
||||
import { Context as FMContext } from '../../../../providers/FileManager'
|
||||
import { getUsableStamps } from '../../utils/bee'
|
||||
import { DriveInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import { truncateNameMiddle } from '../../utils/common'
|
||||
import { FILE_MANAGER_EVENTS } from '../../constants/common'
|
||||
|
||||
interface SidebarProps {
|
||||
loading: boolean
|
||||
@@ -34,6 +36,7 @@ export function Sidebar({ setErrorMessage, loading }: SidebarProps): ReactElemen
|
||||
const [isCreateDriveOpen, setIsCreateDriveOpen] = useState(false)
|
||||
const [usableStamps, setUsableStamps] = useState<PostageBatch[]>([])
|
||||
const [isDriveCreationInProgress, setIsDriveCreationInProgress] = useState(false)
|
||||
const [creatingDriveName, setCreatingDriveName] = useState<string | null>(null)
|
||||
const [isExpiredOpen, setIsExpiredOpen] = useState(false)
|
||||
|
||||
const { beeApi } = useContext(SettingsContext)
|
||||
@@ -65,8 +68,17 @@ export function Sidebar({ setErrorMessage, loading }: SidebarProps): ReactElemen
|
||||
getStamps()
|
||||
}
|
||||
|
||||
const handleUpgradeEnd = async () => {
|
||||
if (isMounted && beeApi) {
|
||||
await getStamps()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_END, handleUpgradeEnd as EventListener)
|
||||
|
||||
return () => {
|
||||
isMounted = false
|
||||
window.removeEventListener(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_END, handleUpgradeEnd as EventListener)
|
||||
}
|
||||
}, [beeApi, drives])
|
||||
|
||||
@@ -81,14 +93,22 @@ export function Sidebar({ setErrorMessage, loading }: SidebarProps): ReactElemen
|
||||
setView(ViewType.File)
|
||||
}
|
||||
|
||||
if (currentDrive && !currentStamp && usableStamps.length > 0) {
|
||||
if (currentDrive && usableStamps.length > 0) {
|
||||
const correspondingStamp = usableStamps.find(s => s.batchID.toString() === currentDrive.batchId.toString())
|
||||
|
||||
if (correspondingStamp) {
|
||||
setCurrentStamp(correspondingStamp)
|
||||
}
|
||||
}
|
||||
}, [fm, drives, currentDrive, currentStamp, usableStamps, setCurrentDrive, setCurrentStamp, setView])
|
||||
}, [fm, drives, currentDrive, usableStamps, setCurrentDrive, setCurrentStamp, setView, beeApi])
|
||||
|
||||
const handleCreateNewDrive = () => {
|
||||
if (isDriveCreationInProgress) {
|
||||
return
|
||||
}
|
||||
|
||||
setIsCreateDriveOpen(true)
|
||||
}
|
||||
|
||||
const isCurrent = (di: DriveInfo) => currentDrive?.id.toString() === di.id.toString()
|
||||
|
||||
@@ -96,12 +116,22 @@ export function Sidebar({ setErrorMessage, loading }: SidebarProps): ReactElemen
|
||||
<div className="fm-sidebar">
|
||||
<div className="fm-sidebar-content">
|
||||
{!loading && (
|
||||
<div className="fm-sidebar-item" onClick={() => setIsCreateDriveOpen(true)}>
|
||||
<div className="fm-sidebar-item-icon">
|
||||
<Add size="16px" />
|
||||
<>
|
||||
<div
|
||||
className={`fm-sidebar-item ${isDriveCreationInProgress ? 'disabled' : ''}`}
|
||||
onClick={() => handleCreateNewDrive()}
|
||||
>
|
||||
<div className="fm-sidebar-item-icon">
|
||||
<Add size="16px" />
|
||||
</div>
|
||||
<div>Create new drive</div>
|
||||
</div>
|
||||
<div>Create new drive</div>
|
||||
</div>
|
||||
{isDriveCreationInProgress && (
|
||||
<div className="fm-sidebar-item-description">
|
||||
{truncateNameMiddle(creatingDriveName || 'Your Drive', 35, 8, 8)} is currently being created.
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{isCreateDriveOpen && (
|
||||
@@ -110,12 +140,19 @@ export function Sidebar({ setErrorMessage, loading }: SidebarProps): ReactElemen
|
||||
onDriveCreated={() => {
|
||||
setIsCreateDriveOpen(false)
|
||||
setIsDriveCreationInProgress(false)
|
||||
setCreatingDriveName(null)
|
||||
}}
|
||||
onCreationStarted={(driveName: string) => {
|
||||
setIsDriveCreationInProgress(true)
|
||||
setCreatingDriveName(driveName)
|
||||
}}
|
||||
onCreationStarted={() => setIsDriveCreationInProgress(true)}
|
||||
onCreationError={(name: string) => {
|
||||
setIsDriveCreationInProgress(false)
|
||||
setErrorMessage?.(`Error creating drive: ${name}`)
|
||||
setErrorMessage?.(
|
||||
`Error creating drive ${name}. Please try again. Possible causes include insufficient xDAI balance or a lost connection to the RPC.`,
|
||||
)
|
||||
setShowError(true)
|
||||
setCreatingDriveName(null)
|
||||
|
||||
return
|
||||
}}
|
||||
@@ -253,7 +290,7 @@ export function Sidebar({ setErrorMessage, loading }: SidebarProps): ReactElemen
|
||||
}}
|
||||
title={`${d.name} Trash`}
|
||||
>
|
||||
{d.name} Trash
|
||||
{truncateNameMiddle(d.name, 35, 8, 8)} Trash
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
margin-left: 4px;
|
||||
overflow: visible !important;
|
||||
}
|
||||
|
||||
.fm-tooltip-wrapper.no-margin {
|
||||
@@ -39,18 +40,15 @@
|
||||
text-align: left;
|
||||
border-radius: 6px;
|
||||
padding: 8px 12px;
|
||||
position: absolute;
|
||||
z-index: 30;
|
||||
top: 50%;
|
||||
left: calc(100% + 6px);
|
||||
position: fixed;
|
||||
z-index: 9999;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
font-weight: 400; /* ensure no bold styling */
|
||||
font-weight: 400;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.16s ease-in-out, visibility 0.16s ease-in-out, transform 0.16s ease-in-out;
|
||||
transition: opacity 0.16s ease-in-out, visibility 0.16s ease-in-out;
|
||||
border: 1px solid rgb(209, 213, 219);
|
||||
transform: translateY(-50%) translateX(4px);
|
||||
}
|
||||
|
||||
.fm-tooltip-container.bottom {
|
||||
@@ -61,18 +59,6 @@
|
||||
visibility: visible;
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
transform: translateY(-50%) translateX(0);
|
||||
}
|
||||
|
||||
/* Left alignment (flip) when wrapper has .left class */
|
||||
.fm-tooltip-wrapper.left .fm-tooltip-container {
|
||||
left: auto;
|
||||
right: calc(100% + 6px);
|
||||
transform: translateY(-50%) translateX(-4px);
|
||||
}
|
||||
|
||||
.fm-tooltip-wrapper.left:hover .fm-tooltip-container {
|
||||
transform: translateY(-50%) translateX(0);
|
||||
}
|
||||
|
||||
.fm-inline-label-with-tooltip {
|
||||
|
||||
@@ -22,6 +22,7 @@ export function Tooltip({
|
||||
bottomTooltip = false,
|
||||
}: TooltipProps): ReactElement {
|
||||
const [alignLeft, setAlignLeft] = useState(false)
|
||||
const [position, setPosition] = useState<{ top: number; left?: number; right?: number } | null>(null)
|
||||
const wrapperRef = useRef<HTMLSpanElement>(null)
|
||||
|
||||
const evaluateAlignment = useCallback(() => {
|
||||
@@ -33,14 +34,27 @@ export function Tooltip({
|
||||
if (!container) return
|
||||
|
||||
const wrapperRect = wrapper.getBoundingClientRect()
|
||||
|
||||
const modalContainer = wrapper.closest('.fm-modal-container') as HTMLElement | null
|
||||
let containerOffset = 0
|
||||
|
||||
if (modalContainer) {
|
||||
const containerRect = modalContainer.getBoundingClientRect()
|
||||
containerOffset = containerRect.left
|
||||
}
|
||||
|
||||
const tooltipWidth = container.offsetWidth || 0
|
||||
const projectedRight = wrapperRect.right + gapPx + tooltipWidth + edgeOffsetPx
|
||||
const viewportWidth = window.innerWidth
|
||||
|
||||
const top = wrapperRect.top + wrapperRect.height / 2
|
||||
|
||||
if (projectedRight > viewportWidth) {
|
||||
setAlignLeft(true)
|
||||
setPosition({ top, right: viewportWidth - wrapperRect.left + gapPx - containerOffset })
|
||||
} else {
|
||||
setAlignLeft(false)
|
||||
setPosition({ top, left: wrapperRect.right + gapPx - containerOffset })
|
||||
}
|
||||
}, [edgeOffsetPx, gapPx])
|
||||
|
||||
@@ -58,6 +72,16 @@ export function Tooltip({
|
||||
</span>
|
||||
<div
|
||||
className={`fm-tooltip-container${bottomTooltip ? ' bottom' : ''}`}
|
||||
style={
|
||||
position
|
||||
? {
|
||||
top: `${position.top}px`,
|
||||
left: position.left !== undefined ? `${position.left}px` : undefined,
|
||||
right: position.right !== undefined ? `${position.right}px` : undefined,
|
||||
transform: 'translateY(-50%)',
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
// eslint-disable-next-line react/no-danger
|
||||
dangerouslySetInnerHTML={{ __html: label }}
|
||||
/>
|
||||
|
||||
@@ -1,5 +1,22 @@
|
||||
.fm-upgrade-drive-modal-container {
|
||||
overflow-y: hidden;
|
||||
}
|
||||
|
||||
.fm-upgrade-drive-modal {
|
||||
width: 600px;
|
||||
max-height: calc(100vh - 48px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.fm-modal-window-scrollable {
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
padding-right: 4px;
|
||||
}
|
||||
|
||||
.fm-upgrade-drive-modal-wallet {
|
||||
@@ -57,4 +74,4 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,13 @@
|
||||
import { ReactElement, useCallback, useContext, useEffect, useRef, useState } from 'react'
|
||||
import './UpgradeDriveModal.scss'
|
||||
import '../../styles/global.scss'
|
||||
import { CustomDropdown } from '../CustomDropdown/CustomDropdown'
|
||||
import { Button } from '../Button/Button'
|
||||
import { Warning } from '@material-ui/icons'
|
||||
import { createPortal } from 'react-dom'
|
||||
import DriveIcon from 'remixicon-react/HardDrive2LineIcon'
|
||||
import DatabaseIcon from 'remixicon-react/Database2LineIcon'
|
||||
import WalletIcon from 'remixicon-react/Wallet3LineIcon'
|
||||
import ExternalLinkIcon from 'remixicon-react/ExternalLinkLineIcon'
|
||||
import CalendarIcon from 'remixicon-react/CalendarLineIcon'
|
||||
import { desiredLifetimeOptions } from '../../constants/stamps'
|
||||
import { Context as BeeContext } from '../../../../providers/Bee'
|
||||
import { fromBytesConversion, getExpiryDateByLifetime } from '../../utils/common'
|
||||
import { Context as SettingsContext } from '../../../../providers/Settings'
|
||||
import { Context as FMContext } from '../../../../providers/FileManager'
|
||||
|
||||
import {
|
||||
BatchId,
|
||||
BeeRequestOptions,
|
||||
@@ -27,8 +20,17 @@ import {
|
||||
Utils,
|
||||
} from '@ethersphere/bee-js'
|
||||
import { DriveInfo } from '@solarpunkltd/file-manager-lib'
|
||||
|
||||
import { CustomDropdown } from '../CustomDropdown/CustomDropdown'
|
||||
import { Button } from '../Button/Button'
|
||||
import { desiredLifetimeOptions } from '../../constants/stamps'
|
||||
import { Context as BeeContext } from '../../../../providers/Bee'
|
||||
import { fromBytesConversion, getExpiryDateByLifetime, truncateNameMiddle } from '../../utils/common'
|
||||
import { Context as SettingsContext } from '../../../../providers/Settings'
|
||||
import { Context as FMContext } from '../../../../providers/FileManager'
|
||||
import { getHumanReadableFileSize } from '../../../../utils/file'
|
||||
import { Warning } from '@material-ui/icons'
|
||||
import { useStampPolling } from '../../hooks/useStampPolling'
|
||||
import { FILE_MANAGER_EVENTS, POLLING_TIMEOUT_MS } from '../../constants/common'
|
||||
|
||||
interface UpgradeDriveModalProps {
|
||||
stamp: PostageBatch
|
||||
@@ -50,10 +52,10 @@ export function UpgradeDriveModal({
|
||||
}: UpgradeDriveModalProps): ReactElement {
|
||||
const { nodeAddresses, walletBalance } = useContext(BeeContext)
|
||||
const { beeApi } = useContext(SettingsContext)
|
||||
const { setShowError } = useContext(FMContext)
|
||||
const { refreshStamp, setShowError } = useContext(FMContext)
|
||||
|
||||
const [isBalanceSufficient, setIsBalanceSufficient] = useState(true)
|
||||
const [capacity, setCapacity] = useState(Size.fromBytes(0))
|
||||
const [capacity, setCapacity] = useState(stamp.size)
|
||||
const [capacityExtensionCost, setCapacityExtensionCost] = useState('')
|
||||
const [capacityIndex, setCapacityIndex] = useState(0)
|
||||
const [durationExtensionCost, setDurationExtensionCost] = useState('')
|
||||
@@ -66,14 +68,37 @@ export function UpgradeDriveModal({
|
||||
const modalRoot = document.querySelector('.fm-main') || document.body
|
||||
const isMountedRef = useRef(true)
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
isMountedRef.current = false
|
||||
}
|
||||
}, [])
|
||||
const { startPolling } = useStampPolling({
|
||||
refreshStamp,
|
||||
onStampUpdated: (updatedStamp: PostageBatch) => {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_END, {
|
||||
detail: {
|
||||
driveId: drive.id.toString(),
|
||||
success: true,
|
||||
updatedStamp,
|
||||
},
|
||||
}),
|
||||
)
|
||||
},
|
||||
onTimeout: (finalStamp: PostageBatch | null) => {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_TIMEOUT, {
|
||||
detail: {
|
||||
driveId: drive.id.toString(),
|
||||
finalStamp: finalStamp || null,
|
||||
},
|
||||
}),
|
||||
)
|
||||
},
|
||||
onPollingStateChange: () => {
|
||||
// no-op
|
||||
},
|
||||
timeout: POLLING_TIMEOUT_MS,
|
||||
})
|
||||
|
||||
const handleCapacityChange = (value: number, index: number) => {
|
||||
setCapacity(Size.fromBytes(value === -1 ? 0 : value))
|
||||
setCapacity(value === -1 ? stamp.size : Size.fromBytes(value))
|
||||
setCapacityIndex(index)
|
||||
}
|
||||
|
||||
@@ -88,8 +113,6 @@ export function UpgradeDriveModal({
|
||||
isCapacityExtensionSet: boolean,
|
||||
isDurationExtensionSet: boolean,
|
||||
) => {
|
||||
setIsBalanceSufficient(true)
|
||||
|
||||
let cost: BZZ | undefined
|
||||
|
||||
try {
|
||||
@@ -107,6 +130,8 @@ export function UpgradeDriveModal({
|
||||
|
||||
if ((walletBalance && cost && cost.gte(walletBalance.bzzBalance)) || !walletBalance) {
|
||||
setIsBalanceSufficient(false)
|
||||
} else {
|
||||
setIsBalanceSufficient(true)
|
||||
}
|
||||
|
||||
const bothExtensions = isCapacityExtensionSet && isDurationExtensionSet
|
||||
@@ -130,7 +155,7 @@ export function UpgradeDriveModal({
|
||||
|
||||
setExtensionCost(noExtensions ? '0' : costText)
|
||||
},
|
||||
[beeApi, walletBalance, setErrorMessage, setShowError],
|
||||
[beeApi, walletBalance, isMountedRef, setErrorMessage, setShowError],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -158,13 +183,14 @@ export function UpgradeDriveModal({
|
||||
useEffect(() => {
|
||||
const fetchExtensionCost = () => {
|
||||
const isCapacitySet = capacityIndex > 0
|
||||
const isDurationSet = true
|
||||
const duration = Duration.fromEndDate(validityEndDate)
|
||||
const isDurationSet = lifetimeIndex >= 0
|
||||
const extendDuration =
|
||||
lifetimeIndex >= 0 ? Duration.fromEndDate(validityEndDate, stamp.duration.toEndDate()) : Duration.ZERO
|
||||
|
||||
handleCostCalculation(
|
||||
stamp.batchID,
|
||||
capacity,
|
||||
duration,
|
||||
extendDuration,
|
||||
undefined,
|
||||
false,
|
||||
defaultErasureCodeLevel,
|
||||
@@ -174,114 +200,126 @@ export function UpgradeDriveModal({
|
||||
}
|
||||
|
||||
fetchExtensionCost()
|
||||
}, [capacity, validityEndDate, capacityIndex, handleCostCalculation, lifetimeIndex, stamp.batchID])
|
||||
}, [capacity, validityEndDate, capacityIndex, handleCostCalculation, lifetimeIndex, stamp.batchID, stamp.duration])
|
||||
|
||||
useEffect(() => {
|
||||
setValidityEndDate(getExpiryDateByLifetime(lifetimeIndex, stamp.duration.toEndDate()))
|
||||
}, [lifetimeIndex, stamp.duration])
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
isMountedRef.current = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
const batchIdStr = stamp.batchID.toString()
|
||||
const shortBatchId = batchIdStr.length > 12 ? `${batchIdStr.slice(0, 4)}...${batchIdStr.slice(-4)}` : batchIdStr
|
||||
|
||||
return createPortal(
|
||||
<div className={`fm-modal-container${containerColor === 'none' ? ' fm-modal-container-no-bg' : ''}`}>
|
||||
<div
|
||||
className={`fm-modal-container fm-upgrade-drive-modal-container${
|
||||
containerColor === 'none' ? ' fm-modal-container-no-bg' : ''
|
||||
}`}
|
||||
>
|
||||
<div className="fm-modal-window fm-upgrade-drive-modal">
|
||||
<div className="fm-modal-window-header">
|
||||
<DriveIcon size="18px" /> Upgrade {drive.name || stamp.label || shortBatchId}
|
||||
<DriveIcon size="18px" /> Upgrade {truncateNameMiddle(drive.name || stamp.label || shortBatchId, 35)}
|
||||
</div>
|
||||
<div>Choose extension period and additional storage for your drive.</div>
|
||||
<div className="fm-modal-window-body">
|
||||
<div className="fm-upgrade-drive-modal-wallet">
|
||||
<div className="fm-upgrade-drive-modal-wallet-header fm-emphasized-text">
|
||||
<WalletIcon size="14px" color="rgb(237, 129, 49)" /> Wallet information
|
||||
</div>
|
||||
{walletBalance && nodeAddresses ? (
|
||||
<div className="fm-upgrade-drive-modal-wallet-info-container">
|
||||
<div className="fm-upgrade-drive-modal-wallet-info">
|
||||
<div>Balance</div>
|
||||
<div>{`${walletBalance.bzzBalance.toSignificantDigits(4)} xBZZ`}</div>
|
||||
</div>
|
||||
<div className="fm-upgrade-drive-modal-wallet-info">
|
||||
<div>Wallet address:</div>
|
||||
<div className="fm-value-snippet">{`${walletBalance.walletAddress.slice(
|
||||
0,
|
||||
4,
|
||||
)}...${walletBalance.walletAddress.slice(-4)}`}</div>
|
||||
</div>
|
||||
<div className="fm-modal-window-scrollable">
|
||||
<div>Choose extension period and additional storage for your drive.</div>
|
||||
<div className="fm-modal-window-body">
|
||||
<div className="fm-upgrade-drive-modal-wallet">
|
||||
<div className="fm-upgrade-drive-modal-wallet-header fm-emphasized-text">
|
||||
<WalletIcon size="14px" color="rgb(237, 129, 49)" /> Wallet information
|
||||
</div>
|
||||
{walletBalance && nodeAddresses ? (
|
||||
<div className="fm-upgrade-drive-modal-wallet-info-container">
|
||||
<div className="fm-upgrade-drive-modal-wallet-info">
|
||||
<div>Balance</div>
|
||||
<div>{`${walletBalance.bzzBalance.toSignificantDigits(4)} xBZZ`}</div>
|
||||
</div>
|
||||
<div className="fm-upgrade-drive-modal-wallet-info">
|
||||
<div>Wallet address:</div>
|
||||
<div className="fm-value-snippet">{`${walletBalance.walletAddress.slice(
|
||||
0,
|
||||
4,
|
||||
)}...${walletBalance.walletAddress.slice(-4)}`}</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div>Wallet information is not available</div>
|
||||
)}
|
||||
<div className="fm-upgrade-drive-modal-info fm-swarm-orange-font">
|
||||
<a
|
||||
className="fm-upgrade-drive-modal-info-link fm-pointer"
|
||||
href="https://www.ethswarm.org/get-bzz#how-to-get-bzz"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<ExternalLinkIcon size="14px" />
|
||||
Need help topping up?
|
||||
</a>
|
||||
</div>
|
||||
) : (
|
||||
<div>Wallet information is not available</div>
|
||||
)}
|
||||
<div className="fm-upgrade-drive-modal-info fm-swarm-orange-font">
|
||||
<a
|
||||
className="fm-upgrade-drive-modal-info-link fm-pointer"
|
||||
href="https://www.ethswarm.org/get-bzz#how-to-get-bzz"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<ExternalLinkIcon size="14px" />
|
||||
Need help topping up?
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="fm-modal-window-body">
|
||||
<div className="fm-upgrade-drive-modal-input-row">
|
||||
<div className="fm-modal-window-input-container">
|
||||
<CustomDropdown
|
||||
id="drive-type"
|
||||
label="Additional storage"
|
||||
icon={<DatabaseIcon size="14px" color="rgb(237, 129, 49)" />}
|
||||
options={sizeMarks}
|
||||
value={capacityIndex === 0 ? -1 : capacity.toBytes()}
|
||||
onChange={handleCapacityChange}
|
||||
/>
|
||||
</div>
|
||||
<div className="fm-modal-window-input-container">
|
||||
<CustomDropdown
|
||||
id="drive-type"
|
||||
label="Duration"
|
||||
icon={<CalendarIcon size="14px" color="rgb(237, 129, 49)" />}
|
||||
options={desiredLifetimeOptions}
|
||||
value={lifetimeIndex}
|
||||
onChange={(value, index) => {
|
||||
setLifetimeIndex(value)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="fm-modal-white-section">
|
||||
<div className="fm-emphasized-text">Summary</div>
|
||||
<div>
|
||||
Drive: {drive.name} {drive.isAdmin && <Warning style={{ fontSize: '16px' }} />}
|
||||
</div>
|
||||
<div>
|
||||
BatchId: {stamp.label} ({shortBatchId})
|
||||
</div>
|
||||
<div>Expiry: {stamp.duration.toEndDate().toLocaleDateString()}</div>
|
||||
<div>
|
||||
Additional storage:{' '}
|
||||
{(() => {
|
||||
if (capacityIndex === 0) return '0 GB'
|
||||
|
||||
return `${
|
||||
fromBytesConversion(Math.max(capacity.toBytes() - stamp.size.toBytes(), 0), 'GB').toFixed(3) + ' GB'
|
||||
} ${durationExtensionCost === '' ? '' : '(' + extensionCost + ' xBZZ)'}`
|
||||
})()}
|
||||
</div>
|
||||
<div>
|
||||
Extension period:{' '}
|
||||
{`${desiredLifetimeOptions[lifetimeIndex]?.label} ${
|
||||
capacityExtensionCost === '' ? '' : '(' + extensionCost + ' xBZZ)'
|
||||
}`}
|
||||
<div className="fm-modal-window-body">
|
||||
<div className="fm-upgrade-drive-modal-input-row">
|
||||
<div className="fm-modal-window-input-container">
|
||||
<CustomDropdown
|
||||
id="drive-type"
|
||||
label="Additional storage"
|
||||
icon={<DatabaseIcon size="14px" color="rgb(237, 129, 49)" />}
|
||||
options={sizeMarks}
|
||||
value={capacityIndex === 0 ? -1 : capacity.toBytes()}
|
||||
onChange={handleCapacityChange}
|
||||
/>
|
||||
</div>
|
||||
<div className="fm-modal-window-input-container">
|
||||
<CustomDropdown
|
||||
id="drive-type"
|
||||
label="Duration"
|
||||
icon={<CalendarIcon size="14px" color="rgb(237, 129, 49)" />}
|
||||
options={desiredLifetimeOptions}
|
||||
value={lifetimeIndex}
|
||||
onChange={(value, index) => {
|
||||
setLifetimeIndex(value)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="fm-upgrade-drive-modal-info fm-emphasized-text">
|
||||
Total:{' '}
|
||||
<span className="fm-swarm-orange-font">
|
||||
{extensionCost} xBZZ {isBalanceSufficient ? '' : '(Insufficient balance)'}
|
||||
</span>
|
||||
<div className="fm-modal-white-section">
|
||||
<div className="fm-emphasized-text">Summary</div>
|
||||
<div>
|
||||
Drive: {truncateNameMiddle(drive.name)} {drive.isAdmin && <Warning style={{ fontSize: '16px' }} />}
|
||||
</div>
|
||||
<div>
|
||||
BatchId: {truncateNameMiddle(stamp.label, 25)} ({shortBatchId})
|
||||
</div>
|
||||
<div>Expiry: {stamp.duration.toEndDate().toLocaleDateString()}</div>
|
||||
<div>
|
||||
Additional storage:{' '}
|
||||
{(() => {
|
||||
if (capacityIndex === 0) return '0 GB'
|
||||
|
||||
return `${
|
||||
fromBytesConversion(Math.max(capacity.toBytes() - stamp.size.toBytes(), 0), 'GB').toFixed(3) + ' GB'
|
||||
} ${durationExtensionCost === '' ? '' : '(' + extensionCost + ' xBZZ)'}`
|
||||
})()}
|
||||
</div>
|
||||
<div>
|
||||
Extension period:{' '}
|
||||
{`${desiredLifetimeOptions[lifetimeIndex]?.label} ${
|
||||
capacityExtensionCost === '' ? '' : '(' + extensionCost + ' xBZZ)'
|
||||
}`}
|
||||
</div>
|
||||
|
||||
<div className="fm-upgrade-drive-modal-info fm-emphasized-text">
|
||||
Total:{' '}
|
||||
<span className="fm-swarm-orange-font">
|
||||
{extensionCost} xBZZ {isBalanceSufficient ? '' : '(Insufficient balance)'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -296,7 +334,7 @@ export function UpgradeDriveModal({
|
||||
try {
|
||||
setIsSubmitting(true)
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('fm:drive-upgrade-start', {
|
||||
new CustomEvent(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_START, {
|
||||
detail: { driveId: drive.id.toString() },
|
||||
}),
|
||||
)
|
||||
@@ -306,24 +344,19 @@ export function UpgradeDriveModal({
|
||||
await beeApi.extendStorage(
|
||||
stamp.batchID,
|
||||
capacity,
|
||||
durationExtensionCost === '0'
|
||||
? Duration.ZERO
|
||||
: Duration.fromEndDate(validityEndDate, stamp.duration.toEndDate()),
|
||||
lifetimeIndex >= 0
|
||||
? Duration.fromEndDate(validityEndDate, stamp.duration.toEndDate())
|
||||
: Duration.ZERO,
|
||||
undefined,
|
||||
false,
|
||||
defaultErasureCodeLevel,
|
||||
)
|
||||
|
||||
// TODO: replace eventlisteners with a better maintainable solution
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('fm:drive-upgrade-end', {
|
||||
detail: { driveId: drive.id.toString(), success: true },
|
||||
}),
|
||||
)
|
||||
startPolling(stamp, capacityIndex > 0)
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : 'Upgrade failed'
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('fm:drive-upgrade-end', {
|
||||
new CustomEvent(FILE_MANAGER_EVENTS.DRIVE_UPGRADE_END, {
|
||||
detail: {
|
||||
driveId: drive.id.toString(),
|
||||
success: false,
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
.fm-upgrade-timeout-modal {
|
||||
.fm-modal-white-section {
|
||||
p {
|
||||
margin-bottom: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
ul {
|
||||
margin-left: 20px;
|
||||
margin-top: 8px;
|
||||
|
||||
li {
|
||||
margin-bottom: 8px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { ReactElement } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { Button } from '../Button/Button'
|
||||
import '../../styles/global.scss'
|
||||
import './UpgradeTimeoutModal.scss'
|
||||
|
||||
interface UpgradeTimeoutModalProps {
|
||||
driveName: string
|
||||
onOk: () => void
|
||||
}
|
||||
|
||||
export function UpgradeTimeoutModal({ driveName, onOk }: UpgradeTimeoutModalProps): ReactElement {
|
||||
const modalRoot = document.querySelector('.fm-main') || document.body
|
||||
|
||||
return createPortal(
|
||||
<div className="fm-modal-container fm-upgrade-timeout-modal">
|
||||
<div className="fm-modal-window">
|
||||
<div className="fm-modal-window-header">Drive upgrade taking longer than expected</div>
|
||||
|
||||
<div className="fm-modal-window-body">
|
||||
<div className="fm-modal-white-section">
|
||||
<p>
|
||||
The upgrade for <strong>{driveName}</strong> is taking longer than expected.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="fm-modal-window-footer">
|
||||
<Button label="OK" variant="primary" onClick={onOk} />
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
modalRoot,
|
||||
)
|
||||
}
|
||||
@@ -7,13 +7,16 @@ import { createPortal } from 'react-dom'
|
||||
import HistoryIcon from 'remixicon-react/HistoryLineIcon'
|
||||
|
||||
import { Context as FMContext } from '../../../../providers/FileManager'
|
||||
import type { FileInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import { FileInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import { FeedIndex } from '@ethersphere/bee-js'
|
||||
import { ConflictAction, useUploadConflictDialog } from '../../hooks/useUploadConflictDialog'
|
||||
import { ConfirmModal } from '../ConfirmModal/ConfirmModal'
|
||||
import { Tooltip } from '../Tooltip/Tooltip'
|
||||
import { TOOLTIPS } from '../../constants/tooltips'
|
||||
|
||||
import { indexStrToBigint } from '../../utils/common'
|
||||
import { VersionsList, truncateNameMiddle } from './VersionList/VersionList'
|
||||
import { verifyDriveSpace } from '../../utils/bee'
|
||||
import { indexStrToBigint, truncateNameMiddle } from '../../utils/common'
|
||||
import { VersionsList } from './VersionList/VersionList'
|
||||
import { ActionTag, DownloadProgress, TrackDownloadProps } from '../../constants/transfers'
|
||||
import { useTransfers } from '../../hooks/useTransfers'
|
||||
|
||||
@@ -32,7 +35,7 @@ interface VersionHistoryModalProps {
|
||||
}
|
||||
|
||||
export function VersionHistoryModal({ fileInfo, onCancelClick, onDownload }: VersionHistoryModalProps): ReactElement {
|
||||
const { fm, files, currentDrive } = useContext(FMContext)
|
||||
const { fm, files, currentDrive, currentStamp, refreshStamp } = useContext(FMContext)
|
||||
|
||||
const localTransfers = useTransfers({})
|
||||
const trackDownload = onDownload ?? localTransfers.trackDownload
|
||||
@@ -180,7 +183,7 @@ export function VersionHistoryModal({ fileInfo, onCancelClick, onDownload }: Ver
|
||||
|
||||
const doRestore = useCallback(
|
||||
async (versionFi: FileInfo): Promise<void> => {
|
||||
if (!fm || !currentDrive) return
|
||||
if (!fm || !currentDrive || !currentStamp) return
|
||||
|
||||
try {
|
||||
const restoredFrom = indexStrToBigint(versionFi.version)
|
||||
@@ -207,14 +210,27 @@ export function VersionHistoryModal({ fileInfo, onCancelClick, onDownload }: Ver
|
||||
},
|
||||
}
|
||||
|
||||
verifyDriveSpace({
|
||||
fm,
|
||||
redundancyLevel: currentDrive.redundancyLevel,
|
||||
stamp: currentStamp,
|
||||
useInfoSize: true,
|
||||
driveId: versionFi.driveId,
|
||||
cb: err => {
|
||||
throw new Error(err)
|
||||
},
|
||||
})
|
||||
|
||||
await fm.restoreVersion(withMeta)
|
||||
|
||||
refreshStamp(versionFi.batchId.toString())
|
||||
onCancelClick()
|
||||
} catch (e) {
|
||||
const msg = (e as Error)?.message || JSON.stringify(e)
|
||||
setError(msg)
|
||||
}
|
||||
},
|
||||
[fm, onCancelClick, currentDrive],
|
||||
[fm, currentStamp, currentDrive, refreshStamp, onCancelClick],
|
||||
)
|
||||
|
||||
const restoreVersion = useCallback(
|
||||
@@ -263,7 +279,7 @@ export function VersionHistoryModal({ fileInfo, onCancelClick, onDownload }: Ver
|
||||
<>
|
||||
Version history –{' '}
|
||||
<span className="vh-title" title={fileInfo.name}>
|
||||
{truncateNameMiddle(fileInfo.name, 56)}
|
||||
{truncateNameMiddle(fileInfo.name)}
|
||||
</span>
|
||||
{fileInfo && (
|
||||
<span
|
||||
@@ -296,16 +312,21 @@ export function VersionHistoryModal({ fileInfo, onCancelClick, onDownload }: Ver
|
||||
|
||||
{renameConfirm && (
|
||||
<ConfirmModal
|
||||
title="Restore this version?"
|
||||
title={
|
||||
<>
|
||||
Restore this version?
|
||||
<Tooltip label={TOOLTIPS.FILE_OPERATION_RESTORE_VERSION} />
|
||||
</>
|
||||
}
|
||||
message={
|
||||
<>
|
||||
Restoring will rename:
|
||||
<b className="vh-name" title={renameConfirm.headName}>
|
||||
{truncateNameMiddle(renameConfirm.headName, 44)}
|
||||
{truncateNameMiddle(renameConfirm.headName)}
|
||||
</b>{' '}
|
||||
→{' '}
|
||||
<b className="vh-name" title={renameConfirm.targetName}>
|
||||
{truncateNameMiddle(renameConfirm.targetName, 44)}
|
||||
{truncateNameMiddle(renameConfirm.targetName)}
|
||||
</b>
|
||||
.
|
||||
</>
|
||||
|
||||
+43
-16
@@ -10,20 +10,15 @@ import DownloadIcon from 'remixicon-react/Download2LineIcon'
|
||||
import { FileInfo } from '@solarpunkltd/file-manager-lib'
|
||||
|
||||
import { Context as FMContext } from '../../../../../providers/FileManager'
|
||||
import { capitalizeFirstLetter, formatBytes, indexStrToBigint } from '../../../utils/common'
|
||||
import { capitalizeFirstLetter, formatBytes, indexStrToBigint, truncateNameMiddle } from '../../../utils/common'
|
||||
import { startDownloadingQueue } from '../../../utils/download'
|
||||
import { ActionTag, DownloadProgress, TrackDownloadProps } from '../../../constants/transfers'
|
||||
import { Context as SettingsContext } from '../../../../../providers/Settings'
|
||||
import { useContextMenu } from '../../../hooks/useContextMenu'
|
||||
|
||||
export const truncateNameMiddle = (s: string, max = 42): string => {
|
||||
const str = String(s)
|
||||
|
||||
if (str.length <= max) return str
|
||||
const half = Math.floor((max - 1) / 2)
|
||||
|
||||
return `${str.slice(0, half)}…${str.slice(-half)}`
|
||||
}
|
||||
import { uuidV4 } from '../../../../../utils'
|
||||
import { ConfirmModal } from '../../ConfirmModal/ConfirmModal'
|
||||
import { Tooltip } from '../../Tooltip/Tooltip'
|
||||
import { TOOLTIPS } from '../../../constants/tooltips'
|
||||
|
||||
interface VersionListProps {
|
||||
versions: FileInfo[]
|
||||
@@ -322,11 +317,11 @@ const RowFull = memo(
|
||||
<div className="vh-rename" title={`Restoring will rename: “${headFi.name}” → “${item.name}”`}>
|
||||
Restoring will rename{' '}
|
||||
<b className="vh-name" title={headFi.name}>
|
||||
{truncateNameMiddle(headFi.name, 44)}
|
||||
{truncateNameMiddle(headFi.name)}
|
||||
</b>{' '}
|
||||
→{' '}
|
||||
<b className="vh-name" title={item.name}>
|
||||
{truncateNameMiddle(item.name, 44)}
|
||||
{truncateNameMiddle(item.name)}
|
||||
</b>
|
||||
</div>
|
||||
)}
|
||||
@@ -401,9 +396,10 @@ VersionRow.displayName = 'VersionRow'
|
||||
export function VersionsList({ versions, headFi, restoreVersion, onDownload }: VersionListProps) {
|
||||
const { handleCloseContext } = useContextMenu<HTMLDivElement>()
|
||||
|
||||
const { fm } = useContext(FMContext)
|
||||
const { fm, drives, currentDrive } = useContext(FMContext)
|
||||
const { beeApi } = useContext(SettingsContext)
|
||||
const [expanded, setExpanded] = useState<Record<string, boolean>>({})
|
||||
const [confirmRestore, setConfirmRestore] = useState<FileInfo | null>(null)
|
||||
|
||||
const toggle = useCallback(
|
||||
(key: string, fi: FileInfo) => {
|
||||
@@ -433,15 +429,20 @@ export function VersionsList({ versions, headFi, restoreVersion, onDownload }: V
|
||||
if (!fm || !beeApi) return
|
||||
const rawSize = fileInfo.customMetadata?.size
|
||||
const expectedSize = rawSize ? Number(rawSize) : undefined
|
||||
const driveName = drives.find(d => d.id.toString() === fileInfo.driveId.toString())?.name ?? currentDrive?.name
|
||||
await startDownloadingQueue(
|
||||
fm,
|
||||
[fileInfo],
|
||||
[onDownload({ name: fileInfo.name, size: formatBytes(rawSize), expectedSize })],
|
||||
[onDownload({ uuid: uuidV4(), name: fileInfo.name, size: formatBytes(rawSize), expectedSize, driveName })],
|
||||
)
|
||||
},
|
||||
[handleCloseContext, fm, beeApi, onDownload],
|
||||
[handleCloseContext, fm, beeApi, onDownload, drives, currentDrive],
|
||||
)
|
||||
|
||||
const handleRestoreClick = useCallback((fileInfo: FileInfo) => {
|
||||
setConfirmRestore(fileInfo)
|
||||
}, [])
|
||||
|
||||
if (!versions.length || !fm) return null
|
||||
|
||||
return (
|
||||
@@ -466,12 +467,38 @@ export function VersionsList({ versions, headFi, restoreVersion, onDownload }: V
|
||||
headFi={headFi}
|
||||
isCurrent={Boolean(isCurrent)}
|
||||
fmDownload={() => handleDownload(item)}
|
||||
onRestore={restoreVersion}
|
||||
onRestore={handleRestoreClick}
|
||||
collapsed={collapsed}
|
||||
onToggle={() => toggle(key, item)}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
|
||||
{confirmRestore && (
|
||||
<ConfirmModal
|
||||
title={
|
||||
<>
|
||||
Restore this version?
|
||||
<Tooltip label={TOOLTIPS.FILE_OPERATION_RESTORE_VERSION} />
|
||||
</>
|
||||
}
|
||||
message={
|
||||
<>
|
||||
This will restore <b title={confirmRestore.name}>{truncateNameMiddle(confirmRestore.name)}</b> to version{' '}
|
||||
{indexStrToBigint(confirmRestore.version)?.toString()}.
|
||||
</>
|
||||
}
|
||||
confirmLabel="Restore"
|
||||
cancelLabel="Cancel"
|
||||
onConfirm={async () => {
|
||||
await restoreVersion(confirmRestore)
|
||||
setConfirmRestore(null)
|
||||
}}
|
||||
onCancel={() => {
|
||||
setConfirmRestore(null)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -9,3 +9,16 @@ export const erasureCodeMarks = Object.entries(RedundancyLevel)
|
||||
value: value as number,
|
||||
label: capitalizeFirstLetter(key),
|
||||
}))
|
||||
|
||||
export const FILE_MANAGER_EVENTS = {
|
||||
FILE_UPLOADED: 'fm:file-uploaded',
|
||||
DRIVE_UPGRADE_START: 'fm:drive-upgrade-start',
|
||||
DRIVE_UPGRADE_END: 'fm:drive-upgrade-end',
|
||||
DRIVE_UPGRADE_TIMEOUT: 'fm:drive-upgrade-timeout',
|
||||
} as const
|
||||
|
||||
export type FileManagerEventName = typeof FILE_MANAGER_EVENTS[keyof typeof FILE_MANAGER_EVENTS]
|
||||
|
||||
export const POLLING_TIMEOUT_MS = 90000
|
||||
export const UPLOAD_POLLING_TIMEOUT_MS = 10000
|
||||
export const POLLING_INTERVAL_MS = 2000
|
||||
|
||||
@@ -1,7 +1,19 @@
|
||||
const plusOne = 1
|
||||
const plusThree = 3
|
||||
const plusSix = 6
|
||||
|
||||
export const desiredLifetimeOptions = [
|
||||
{ value: 0, label: '1 week' },
|
||||
{ value: 1, label: '1 month' },
|
||||
{ value: 2, label: '3 months' },
|
||||
{ value: 3, label: '6 months' },
|
||||
{ value: 4, label: '1 year' },
|
||||
{ value: 0, label: `${plusOne} week` },
|
||||
{ value: 1, label: `${plusOne} month` },
|
||||
{ value: 2, label: `${plusThree} months` },
|
||||
{ value: 3, label: `${plusSix} months` },
|
||||
{ value: 4, label: `${plusOne} year` },
|
||||
]
|
||||
|
||||
export const lifetimeAdjustments = new Map<number, (date: Date) => void>([
|
||||
[0, date => date.setDate(date.getDate() + plusOne * 7)],
|
||||
[1, date => date.setMonth(date.getMonth() + plusOne)],
|
||||
[2, date => date.setMonth(date.getMonth() + plusThree)],
|
||||
[3, date => date.setMonth(date.getMonth() + plusSix)],
|
||||
[4, date => date.setFullYear(date.getFullYear() + plusOne)],
|
||||
])
|
||||
|
||||
@@ -1,33 +1,64 @@
|
||||
// Tooltip content for File Manager
|
||||
const getTitleWithStyle = (title: string): string => {
|
||||
return `<div style="font-weight: bold; margin-bottom: 12px; font-size: 14px;">${title}</div>`
|
||||
}
|
||||
|
||||
export const TOOLTIPS = {
|
||||
// Admin Stamp Creation
|
||||
ADMIN_PREVIOUSLY_CREATED: `<div style="font-weight: bold; margin-bottom: 12px; font-size: 14px;">Use Existing Admin Drive</div>
|
||||
ADMIN_PREVIOUSLY_CREATED: `${getTitleWithStyle('Use Existing Admin Drive')}
|
||||
An existing Admin Drive from a previous session can be selected here. This will link the File Manager to that Admin Drive.
|
||||
<br/>
|
||||
<br/>
|
||||
Otherwise, leave this blank and configure a new Admin Drive below.`,
|
||||
ADMIN_DESIRED_LIFETIME: `Defines how long your deposit will cover storage on the network. It’s an estimate, not a fixed expiry - you can top up anytime to extend it.`,
|
||||
ADMIN_DESIRED_LIFETIME: `${getTitleWithStyle('What is Desired Lifetime?')}
|
||||
To create the Admin Drive, a one-time deposit is required to pay for its storage on the network.
|
||||
<br/>
|
||||
<br/>
|
||||
This sets the initial period the Admin Drive's information will be paid for on the network. This is not a fixed expiry date. It's the estimated time it will take for the drive's balance to be depleted. You can top up any time to extend the lifetime.
|
||||
<br/>
|
||||
<br/>
|
||||
<b>Warning:</b> The Admin Drive is critical for managing files. If its deposit runs out and it is not renewed, the network will no longer store its data, and access to the File Manager instance will be permanently lost.`,
|
||||
|
||||
ADMIN_SECURITY_LEVEL: `This sets how many encrypted copies of your Admin Drive’s information are stored across the network. Higher levels increase resilience but reduce the available storage capacity.`,
|
||||
ADMIN_SECURITY_LEVEL: `${getTitleWithStyle('What is Security Level?')}
|
||||
This controls how many redundant copies of the Admin Drive's core information are created and spread across the network.
|
||||
<br/>
|
||||
<br/>
|
||||
A higher level provides extra protection against data loss in the improbable event of large-scale network disruptions.
|
||||
<br/>
|
||||
<br/>
|
||||
<b>Trade-off:</b> Higher redundancy levels decrease your initial storage, while keeping the initial deposit cost the same for the same Desired Lifetime.`,
|
||||
|
||||
ADMIN_ESTIMATED_COST: `This is a one-time deposit required to create your drive, calculated from the <b>desired lifetime, storage size</b>, and the current <b>storage price.</b>`,
|
||||
ADMIN_ESTIMATED_COST: `${getTitleWithStyle('How is this cost calculated?')}
|
||||
This is the one-time deposit of xBZZ tokens required to create the Admin Drive.
|
||||
<br/>
|
||||
<br/>
|
||||
It is calculated based on two factors:<br/>
|
||||
1. <b>Desired Lifetime:</b> The desired storage duration.<br/>
|
||||
2. <b>Current Network Price:</b> The cost of storage at this moment.
|
||||
<br/>
|
||||
<br/>
|
||||
This deposit is used to pay storage fees on the network over time. The cost is not a one-time purchase but a deposit that will be gradually consumed over time based on the network's storage fees.
|
||||
<br/>
|
||||
<br/>
|
||||
As the deposit depletes, the Admin Drive's lifetime decreases. You can top up the deposit at any time to extend its lifetime.
|
||||
<br/>
|
||||
<br/>
|
||||
<b>Note:</b> This estimate is based on current network conditions and the deposit's depletion rate is subject to change and is contingent upon prevailing market conditions.`,
|
||||
|
||||
ADMIN_PURCHASE_BUTTON: `<div style="font-weight: bold; margin-bottom: 12px; font-size: 14px;">Create Admin Drive</div>
|
||||
ADMIN_PURCHASE_BUTTON: `${getTitleWithStyle('Create Admin Drive')}
|
||||
This action will do two things:
|
||||
<br/>
|
||||
<br/>
|
||||
1. It will make a one-time transaction to deposit the Estimated Cost.<br/>
|
||||
2. It will create the Admin Drive.`,
|
||||
|
||||
ADMIN_PURCHASE_BUTTON_ALREADY_EXISTED_ADMIN_DRIVE: `<div style="font-weight: bold; margin-bottom: 12px; font-size: 14px;">Create Admin Drive</div>
|
||||
ADMIN_PURCHASE_BUTTON_ALREADY_EXISTED_ADMIN_DRIVE: `${getTitleWithStyle('Create Admin Drive')}
|
||||
|
||||
It will create the Admin Drive.`,
|
||||
|
||||
// Drive Creation
|
||||
DRIVE_NAME: `<div style="font-weight: bold; margin-bottom: 12px; font-size: 14px;">About Drive Name</div>
|
||||
DRIVE_NAME: `${getTitleWithStyle('About Drive Name')}
|
||||
Set a human-readable label for this drive (e.g. Personal files). This name is stored as metadata.`,
|
||||
|
||||
DRIVE_INITIAL_CAPACITY: `<div style="font-weight: bold; margin-bottom: 12px; font-size: 14px;">What is Initial Storage?</div>
|
||||
DRIVE_INITIAL_CAPACITY: `${getTitleWithStyle('What is Initial Storage?')}
|
||||
This sets the initial storage capacity. This value is used in combination with lifetime and redundancy, to calculate the initial deposit.
|
||||
<br/>
|
||||
<br/>
|
||||
@@ -36,13 +67,13 @@ This sets the initial storage capacity. This value is used in combination with l
|
||||
<br/>
|
||||
<b>Tip:</b> Selecting a size with a little extra room provides the best flexibility.`,
|
||||
|
||||
DRIVE_DESIRED_LIFETIME: `<div style="font-weight: bold; margin-bottom: 12px; font-size: 14px;">What is Desired Lifetime?</div>
|
||||
DRIVE_DESIRED_LIFETIME: `${getTitleWithStyle('What is Desired Lifetime?')}
|
||||
This sets the initial period the drive's information will be paid for on the network. This is not a fixed expiry date. It's the estimated time it will take for the drive's balance to be depleted. You can top up any time to extend the lifetime.
|
||||
<br/>
|
||||
<br/>
|
||||
<b>Warning:</b> If the deposit balance runs out, the drive's data is no longer paid for and will be scheduled for permanent deletion by the network. The rate of depletion is depends upon actual market conditions.`,
|
||||
|
||||
DRIVE_SECURITY_LEVEL: `<div style="font-weight: bold; margin-bottom: 12px; font-size: 14px;">What is Security Level?</div>
|
||||
DRIVE_SECURITY_LEVEL: `${getTitleWithStyle('What is Security Level?')}
|
||||
This controls the level of data redundancy for your drive's data.
|
||||
<br/>
|
||||
<br/>
|
||||
@@ -51,7 +82,7 @@ Higher levels provide maximum protection against data loss, even in the unlikely
|
||||
<br/>
|
||||
<b>Trade-off:</b> Higher redundancy levels decreases your initial storage, while keeping the initial deposit cost the same for the same Desired Lifetime.`,
|
||||
|
||||
DRIVE_ESTIMATED_COST: `<div style="font-weight: bold; margin-bottom: 12px; font-size: 14px;">How is this cost calculated?</div>
|
||||
DRIVE_ESTIMATED_COST: `${getTitleWithStyle('How is this cost calculated?')}
|
||||
This is the one-time deposit of xBZZ tokens required to fund the drive's storage.
|
||||
<br/>
|
||||
<br/>
|
||||
@@ -72,9 +103,33 @@ As the deposit depletes, the drive's lifetime decreases. You can top up the depo
|
||||
<b>Note:</b> This estimate is based on current network conditions and the deposit's depletion rate is subject to change and is contingent upon prevailing market conditions.`,
|
||||
|
||||
PRIVATE_KEY_MODAL_HEADER: `The Private Key ensures exclusive access to this File Manager instance. It is the user's responsibity to store in a secure and tamper-proof way.`,
|
||||
PRIVATE_KEY_MODAL_GENERATED_KEY: `Advanced users may input a custom key.`,
|
||||
PRIVATE_KEY_MODAL_CONFIRM_KEY: `<div style="font-weight: bold; margin-bottom: 12px; font-size: 14px;">Confirmation Step</div>
|
||||
PRIVATE_KEY_MODAL_GENERATED_KEY: `${getTitleWithStyle('Generated Key')}
|
||||
A unique, 64-character secure key has been generated.
|
||||
<br/>
|
||||
<br/>
|
||||
Advanced users can delete this and input a custom key.`,
|
||||
PRIVATE_KEY_MODAL_CONFIRM_KEY: `${getTitleWithStyle('Confirmation Step')}
|
||||
This is a final safety check to ensure a copy of the key has been saved before proceeding.`,
|
||||
PRIVATE_KEY_MODAL_KEY_INFO: `<div style="font-weight: bold; margin-bottom: 12px; font-size: 14px;">On This Device Only</div>
|
||||
PRIVATE_KEY_MODAL_KEY_INFO: `${getTitleWithStyle('On This Device Only')}
|
||||
For convenience, an encrypted copy of this key is saved in this browser's local storage. This avoids needing to enter it on every visit.`,
|
||||
|
||||
FILE_OPERATION_TRASH: `Note: Moving items to Trash can modify file metadata and history which may cause the node to report a different (sometimes higher) used capacity. This does not upload new data but the displayed usage may change post operation.`,
|
||||
|
||||
FILE_OPERATION_FORGET: `Note: Forgetting hides files from your view but does not delete underlying data on Swarm. Metadata/history changes can affect the reported used capacity. In some cases the UI may show freed visible drive space.`,
|
||||
|
||||
FILE_OPERATION_RESTORE_VERSION: `Note: Restoring versions can alter file metadata and history which may affect the node-reported used capacity. The operation does not upload new data but displayed usage may change post operation.`,
|
||||
|
||||
FILE_OPERATION_RESTORE_FROM_TRASH: `Note: Restoring from Trash can modify file metadata and history which may cause the node to report a different (sometimes higher) used capacity. This does not upload new data but the displayed usage may change post operation.`,
|
||||
|
||||
DRIVE_CAPACITY_UPDATING: `${getTitleWithStyle('Capacity Update in Progress')}
|
||||
The drive's capacity is being refreshed after an upgrade or file operation.
|
||||
<br/>
|
||||
<br/>
|
||||
The system is checking the network for the updated stamp information. This process may take a moment depending on network conditions.
|
||||
<br/>
|
||||
<br/>
|
||||
If no update is detected after the polling period, the display will revert to showing the last known values.`,
|
||||
|
||||
DRIVE_CAPACITY_INFO: `${getTitleWithStyle('Drive Capacity')}
|
||||
Shows how much storage is used on this drive. Actual usage might be a bit higher than file sizes due to storage overhead.`,
|
||||
}
|
||||
|
||||
@@ -45,9 +45,11 @@ export enum DownloadState {
|
||||
}
|
||||
|
||||
export type TrackDownloadProps = {
|
||||
uuid: string
|
||||
name: string
|
||||
size?: string
|
||||
expectedSize?: number
|
||||
driveName?: string
|
||||
}
|
||||
|
||||
export interface DownloadProgress {
|
||||
@@ -55,3 +57,15 @@ export interface DownloadProgress {
|
||||
isDownloading: boolean
|
||||
state?: DownloadState
|
||||
}
|
||||
|
||||
export type ProgressItem = {
|
||||
uuid: string
|
||||
name: string
|
||||
size?: string
|
||||
percent?: number
|
||||
kind?: FileTransferType
|
||||
status?: TransferStatus
|
||||
driveName?: string
|
||||
etaSec?: number
|
||||
elapsedSec?: number
|
||||
}
|
||||
|
||||
@@ -1,29 +1,54 @@
|
||||
import { useCallback, useMemo, useRef, useState, useContext } from 'react'
|
||||
import { useCallback, useMemo, useRef, useState, useContext, useEffect } from 'react'
|
||||
import type { FileInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import { PostageBatch } from '@ethersphere/bee-js'
|
||||
import { Context as FMContext } from '../../../providers/FileManager'
|
||||
import { Context as SettingsContext } from '../../../providers/Settings'
|
||||
import { startDownloadingQueue } from '../utils/download'
|
||||
import { formatBytes, getFileId } from '../utils/common'
|
||||
import { formatBytes, getFileId, safeSetState } from '../utils/common'
|
||||
import { DownloadProgress, TrackDownloadProps } from '../constants/transfers'
|
||||
import { getUsableStamps } from '../utils/bee'
|
||||
import { performBulkFileOperation, FileOperation } from '../utils/fileOperations'
|
||||
import { uuidV4 } from '../../../utils'
|
||||
|
||||
export function useBulkActions(opts: {
|
||||
interface BulkOptions {
|
||||
listToRender: FileInfo[]
|
||||
trackDownload: (props: TrackDownloadProps) => (dp: DownloadProgress) => void
|
||||
}) {
|
||||
const { listToRender, trackDownload } = opts
|
||||
setErrorMessage?: (error: string) => void
|
||||
}
|
||||
|
||||
const { fm } = useContext(FMContext)
|
||||
export function useBulkActions({ listToRender, setErrorMessage, trackDownload }: BulkOptions) {
|
||||
const { fm, adminDrive, drives, refreshStamp, setShowError } = useContext(FMContext)
|
||||
const { beeApi } = useContext(SettingsContext)
|
||||
|
||||
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
|
||||
const [driveStamps, setDriveStamps] = useState<PostageBatch[] | undefined>(undefined)
|
||||
const allIds = useMemo(() => listToRender.map(getFileId), [listToRender])
|
||||
const selectedCount = useMemo(() => allIds.filter(id => selectedIds.has(id)).length, [allIds, selectedIds])
|
||||
const allChecked = useMemo(() => allIds.length > 0 && selectedCount === allIds.length, [allIds.length, selectedCount])
|
||||
const someChecked = useMemo(() => selectedCount > 0 && !allChecked, [selectedCount, allChecked])
|
||||
const isMountedRef = useRef(true)
|
||||
const fileInputRef = useRef<HTMLInputElement | null>(null)
|
||||
|
||||
const selectedFiles = useMemo(
|
||||
() => listToRender.filter(fi => selectedIds.has(getFileId(fi))),
|
||||
[listToRender, selectedIds],
|
||||
)
|
||||
useEffect(() => {
|
||||
isMountedRef.current = true
|
||||
|
||||
const getStamps = async () => {
|
||||
const stamps = await getUsableStamps(beeApi)
|
||||
const stampList = stamps.filter(s => drives.some(d => d.batchId.toString() === s.batchID.toString()))
|
||||
|
||||
safeSetState(isMountedRef, setDriveStamps)(stampList)
|
||||
}
|
||||
|
||||
getStamps()
|
||||
|
||||
return () => {
|
||||
isMountedRef.current = false
|
||||
}
|
||||
}, [beeApi, drives])
|
||||
|
||||
const toggleOne = useCallback((fi: FileInfo, checked: boolean) => {
|
||||
const id = getFileId(fi)
|
||||
@@ -56,45 +81,93 @@ export function useBulkActions(opts: {
|
||||
const rawSize = fi.customMetadata?.size as string | number | undefined
|
||||
const prettySize = formatBytes(rawSize)
|
||||
const expected = rawSize ? Number(rawSize) : undefined
|
||||
const tracker = trackDownload({ name: fi.name, size: prettySize, expectedSize: expected })
|
||||
const driveName = drives.find(d => d.id.toString() === fi.driveId.toString())?.name
|
||||
const tracker = trackDownload({
|
||||
uuid: uuidV4(),
|
||||
name: fi.name,
|
||||
size: prettySize,
|
||||
expectedSize: expected,
|
||||
driveName,
|
||||
})
|
||||
trackers.push(tracker)
|
||||
}
|
||||
|
||||
await startDownloadingQueue(fm, list, trackers)
|
||||
},
|
||||
[fm, trackDownload],
|
||||
[fm, trackDownload, drives],
|
||||
)
|
||||
|
||||
const bulkTrash = useCallback(
|
||||
async (list: FileInfo[]) => {
|
||||
if (!fm || !list?.length) return
|
||||
|
||||
await Promise.allSettled(list.map(f => fm.trashFile(f)))
|
||||
await performBulkFileOperation({
|
||||
fm,
|
||||
files: list,
|
||||
operation: FileOperation.Trash,
|
||||
stamps: driveStamps || [],
|
||||
onError: error => {
|
||||
setErrorMessage?.(error)
|
||||
setShowError(true)
|
||||
},
|
||||
onFileComplete: file => {
|
||||
refreshStamp(file.batchId.toString())
|
||||
},
|
||||
})
|
||||
|
||||
clearAll()
|
||||
},
|
||||
[fm, clearAll],
|
||||
[fm, driveStamps, clearAll, refreshStamp, setErrorMessage, setShowError],
|
||||
)
|
||||
|
||||
const bulkRestore = useCallback(
|
||||
async (list: FileInfo[]) => {
|
||||
if (!fm || !list?.length) return
|
||||
|
||||
await Promise.allSettled(list.map(f => fm.recoverFile(f)))
|
||||
await performBulkFileOperation({
|
||||
fm,
|
||||
files: list,
|
||||
operation: FileOperation.Recover,
|
||||
stamps: driveStamps || [],
|
||||
onError: error => {
|
||||
setErrorMessage?.(error)
|
||||
setShowError(true)
|
||||
},
|
||||
onFileComplete: file => {
|
||||
refreshStamp(file.batchId.toString())
|
||||
},
|
||||
})
|
||||
|
||||
clearAll()
|
||||
},
|
||||
[fm, clearAll],
|
||||
[fm, driveStamps, refreshStamp, clearAll, setErrorMessage, setShowError],
|
||||
)
|
||||
|
||||
const bulkForget = useCallback(
|
||||
async (list: FileInfo[]) => {
|
||||
if (!fm || !list?.length) return
|
||||
if (!fm || !fm.adminStamp || !adminDrive || !list?.length) return
|
||||
|
||||
await Promise.allSettled(list.map(f => fm.forgetFile(f)))
|
||||
await performBulkFileOperation({
|
||||
fm,
|
||||
files: list,
|
||||
operation: FileOperation.Forget,
|
||||
stamps: driveStamps || [],
|
||||
adminStamp: fm.adminStamp,
|
||||
adminDrive: adminDrive || undefined,
|
||||
onError: error => {
|
||||
setErrorMessage?.(error)
|
||||
setShowError(true)
|
||||
},
|
||||
onFileComplete: () => {
|
||||
if (fm.adminStamp) {
|
||||
refreshStamp(fm.adminStamp.batchID.toString())
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
clearAll()
|
||||
},
|
||||
[fm, clearAll],
|
||||
[fm, adminDrive, driveStamps, clearAll, refreshStamp, setErrorMessage, setShowError],
|
||||
)
|
||||
|
||||
return useMemo(
|
||||
|
||||
@@ -15,7 +15,7 @@ interface UseDragAndDropReturn {
|
||||
handleOverlayDrop: (e: React.DragEvent<HTMLDivElement>) => void
|
||||
}
|
||||
|
||||
export function useDragAndDrop({ onFilesDropped, currentDrive }: UseDragAndDropProps): UseDragAndDropReturn {
|
||||
export function useDragAndDrop({ onFilesDropped }: UseDragAndDropProps): UseDragAndDropReturn {
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const dragCounter = useRef(0)
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { useRef, useCallback } from 'react'
|
||||
import { PostageBatch } from '@ethersphere/bee-js'
|
||||
import { POLLING_INTERVAL_MS } from '../constants/common'
|
||||
|
||||
interface UseStampPollingOptions {
|
||||
onStampUpdated: (stamp: PostageBatch) => void
|
||||
onPollingStateChange: (isPolling: boolean) => void
|
||||
onTimeout?: (finalStamp: PostageBatch | null) => void
|
||||
refreshStamp: (batchId: string) => Promise<PostageBatch | null | undefined>
|
||||
timeout: number
|
||||
}
|
||||
|
||||
export function useStampPolling({
|
||||
onStampUpdated,
|
||||
onPollingStateChange,
|
||||
onTimeout,
|
||||
refreshStamp,
|
||||
timeout,
|
||||
}: UseStampPollingOptions) {
|
||||
const pollingIntervalRef = useRef<NodeJS.Timeout | null>(null)
|
||||
const timeoutRef = useRef<NodeJS.Timeout | null>(null)
|
||||
|
||||
const stopPolling = useCallback(() => {
|
||||
if (pollingIntervalRef.current) {
|
||||
clearInterval(pollingIntervalRef.current)
|
||||
pollingIntervalRef.current = null
|
||||
}
|
||||
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current)
|
||||
timeoutRef.current = null
|
||||
}
|
||||
|
||||
onPollingStateChange(false)
|
||||
}, [onPollingStateChange])
|
||||
|
||||
const checkStampUpdate = useCallback(
|
||||
async (
|
||||
batchId: string,
|
||||
oldStampSize: number,
|
||||
oldRemainingSize: number,
|
||||
oldExpiry: number,
|
||||
isCapacityUpgrade?: boolean,
|
||||
): Promise<{ updated: boolean; stamp: PostageBatch | null }> => {
|
||||
try {
|
||||
const updatedStamp = await refreshStamp(batchId)
|
||||
|
||||
if (!updatedStamp) {
|
||||
return { updated: false, stamp: null }
|
||||
}
|
||||
|
||||
const newStampSize = updatedStamp.size.toBytes()
|
||||
const newRemainingSize = updatedStamp.remainingSize.toBytes()
|
||||
const newExpiry = updatedStamp.duration.toEndDate().getTime()
|
||||
const capacityIncreased = newStampSize > oldStampSize
|
||||
const usageIncreased = newRemainingSize < oldRemainingSize
|
||||
const durationUpdated = newExpiry > oldExpiry
|
||||
|
||||
const isCapacityIncreased = capacityIncreased && durationUpdated
|
||||
const isStampDataChanged = capacityIncreased || durationUpdated || usageIncreased
|
||||
|
||||
return {
|
||||
updated: isCapacityUpgrade ? isCapacityIncreased : isStampDataChanged,
|
||||
stamp: updatedStamp,
|
||||
}
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('[useStampPolling] Error refreshing stamp:', error)
|
||||
|
||||
return { updated: false, stamp: null }
|
||||
}
|
||||
},
|
||||
[refreshStamp],
|
||||
)
|
||||
|
||||
const startPolling = useCallback(
|
||||
(originalStamp: PostageBatch, isCapacityUpgrade?: boolean) => {
|
||||
if (pollingIntervalRef.current) {
|
||||
clearInterval(pollingIntervalRef.current)
|
||||
pollingIntervalRef.current = null
|
||||
}
|
||||
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current)
|
||||
timeoutRef.current = null
|
||||
}
|
||||
|
||||
onPollingStateChange(true)
|
||||
|
||||
const batchId = originalStamp.batchID.toString()
|
||||
const oldStampSize = originalStamp.size.toBytes()
|
||||
const oldRemainingSize = originalStamp.remainingSize.toBytes()
|
||||
const oldExpiry = originalStamp.duration.toEndDate().getTime()
|
||||
|
||||
timeoutRef.current = setTimeout(async () => {
|
||||
stopPolling()
|
||||
|
||||
if (!onTimeout) return
|
||||
|
||||
const result = await checkStampUpdate(batchId, oldStampSize, oldRemainingSize, oldExpiry, isCapacityUpgrade)
|
||||
|
||||
if (result.updated && result.stamp) {
|
||||
onStampUpdated(result.stamp)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
onTimeout(result.stamp)
|
||||
}, timeout)
|
||||
|
||||
pollingIntervalRef.current = setInterval(async () => {
|
||||
const result = await checkStampUpdate(batchId, oldStampSize, oldRemainingSize, oldExpiry, isCapacityUpgrade)
|
||||
|
||||
if (result.updated && result.stamp) {
|
||||
onStampUpdated(result.stamp)
|
||||
stopPolling()
|
||||
}
|
||||
}, POLLING_INTERVAL_MS)
|
||||
},
|
||||
[onStampUpdated, onPollingStateChange, onTimeout, stopPolling, timeout, checkStampUpdate],
|
||||
)
|
||||
|
||||
return {
|
||||
startPolling,
|
||||
stopPolling,
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useCallback, useState, useContext, useRef, useEffect } from 'react'
|
||||
import { Context as FMContext } from '../../../providers/FileManager'
|
||||
import { Context as SettingsContext } from '../../../providers/Settings'
|
||||
import type { FileInfo, FileInfoOptions, UploadProgress } from '@solarpunkltd/file-manager-lib'
|
||||
import { ConflictAction, useUploadConflictDialog } from './useUploadConflictDialog'
|
||||
import { formatBytes, safeSetState } from '../utils/common'
|
||||
import { formatBytes, safeSetState, truncateNameMiddle } from '../utils/common'
|
||||
import {
|
||||
DownloadProgress,
|
||||
DownloadState,
|
||||
@@ -10,13 +11,17 @@ import {
|
||||
TrackDownloadProps,
|
||||
TransferStatus,
|
||||
} from '../constants/transfers'
|
||||
import { calculateStampCapacityMetrics } from '../utils/bee'
|
||||
import { validateStampStillExists, verifyDriveSpace } from '../utils/bee'
|
||||
import { isTrashed } from '../utils/common'
|
||||
import { abortDownload } from '../utils/download'
|
||||
import { AbortManager } from '../utils/abortManager'
|
||||
import { uuidV4 } from '../../../utils'
|
||||
import { FILE_MANAGER_EVENTS } from '../constants/common'
|
||||
|
||||
const SAMPLE_WINDOW_MS = 500
|
||||
const ETA_SMOOTHING = 0.3
|
||||
const MAX_UPLOAD_FILES = 10
|
||||
const ABORT_EVENT = 'abort'
|
||||
|
||||
type ResolveResult = {
|
||||
cancelled: boolean
|
||||
@@ -27,6 +32,7 @@ type ResolveResult = {
|
||||
}
|
||||
|
||||
type TransferItem = {
|
||||
uuid: string
|
||||
name: string
|
||||
size?: string
|
||||
percent: number
|
||||
@@ -47,12 +53,15 @@ type ETAState = {
|
||||
type UploadMeta = Record<string, string | number>
|
||||
|
||||
type UploadTask = {
|
||||
uuid: string
|
||||
file: File
|
||||
finalName: string
|
||||
prettySize?: string
|
||||
isReplace: boolean
|
||||
replaceTopic?: string
|
||||
replaceHistory?: string
|
||||
driveId: string
|
||||
driveName: string
|
||||
}
|
||||
|
||||
const normalizeCustomMetadata = (meta: UploadMeta): Record<string, string> => {
|
||||
@@ -62,15 +71,21 @@ const normalizeCustomMetadata = (meta: UploadMeta): Record<string, string> => {
|
||||
return out
|
||||
}
|
||||
|
||||
const buildUploadMeta = (files: File[] | FileList, path?: string): UploadMeta => {
|
||||
const buildUploadMeta = (files: File[] | FileList, path?: string, existingFile?: FileInfo): UploadMeta => {
|
||||
const arr = Array.from(files as File[])
|
||||
const totalSize = arr.reduce((acc, f) => acc + (f.size || 0), 0)
|
||||
const primary = arr[0]
|
||||
|
||||
const previousAccumulated = existingFile
|
||||
? Number(existingFile.customMetadata?.accumulatedSize || existingFile.customMetadata?.size || 0)
|
||||
: 0
|
||||
const accumulatedSize = previousAccumulated + totalSize
|
||||
|
||||
const meta: UploadMeta = {
|
||||
size: String(totalSize),
|
||||
fileCount: String(arr.length),
|
||||
mime: primary?.type || 'application/octet-stream',
|
||||
accumulatedSize: String(accumulatedSize),
|
||||
}
|
||||
|
||||
if (path) meta.path = path
|
||||
@@ -120,17 +135,23 @@ const calculateETA = (
|
||||
}
|
||||
}
|
||||
|
||||
const updateTransferItems = <T extends TransferItem>(items: T[], name: string, update: Partial<T>): T[] => {
|
||||
return items.map(item => (item.name === name ? { ...item, ...update } : item))
|
||||
const updateTransferItems = <T extends TransferItem>(items: T[], uuid: string, update: Partial<T>): T[] => {
|
||||
return items.map(item => {
|
||||
const matches = item.uuid === uuid
|
||||
|
||||
return matches ? { ...item, ...update } : item
|
||||
})
|
||||
}
|
||||
|
||||
const createTransferItem = (
|
||||
uuid: string,
|
||||
name: string,
|
||||
size: string | undefined,
|
||||
kind: FileTransferType,
|
||||
driveName?: string,
|
||||
status: TransferStatus = TransferStatus.Uploading,
|
||||
): TransferItem => ({
|
||||
uuid,
|
||||
name,
|
||||
size,
|
||||
percent: 0,
|
||||
@@ -147,13 +168,14 @@ interface TransferProps {
|
||||
}
|
||||
|
||||
export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
const { fm, currentDrive, currentStamp, files, setShowError, refreshStamp } = useContext(FMContext)
|
||||
const { fm, adminDrive, currentDrive, currentStamp, files, setShowError, refreshStamp } = useContext(FMContext)
|
||||
const { beeApi } = useContext(SettingsContext)
|
||||
const [openConflict, conflictPortal] = useUploadConflictDialog()
|
||||
const isMountedRef = useRef(true)
|
||||
const uploadAbortsRef = useRef<AbortManager>(new AbortManager())
|
||||
const queueRef = useRef<UploadTask[]>([])
|
||||
const runningRef = useRef(false)
|
||||
const cancelledNamesRef = useRef<Set<string>>(new Set())
|
||||
const cancelledQueuedRef = useRef<Set<string>>(new Set())
|
||||
const cancelledUploadingRef = useRef<Set<string>>(new Set())
|
||||
const cancelledDownloadingRef = useRef<Set<string>>(new Set())
|
||||
|
||||
@@ -167,23 +189,27 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
i => i.status !== TransferStatus.Done && i.status !== TransferStatus.Error && i.status !== TransferStatus.Cancelled,
|
||||
)
|
||||
|
||||
const clearAllFlagsFor = useCallback((name: string) => {
|
||||
cancelledNamesRef.current.delete(name)
|
||||
cancelledUploadingRef.current.delete(name)
|
||||
uploadAbortsRef.current.abort(name)
|
||||
queueRef.current = queueRef.current.filter(t => t.finalName !== name)
|
||||
const clearAllFlagsFor = useCallback((uuid: string) => {
|
||||
cancelledQueuedRef.current.delete(uuid)
|
||||
cancelledUploadingRef.current.delete(uuid)
|
||||
uploadAbortsRef.current.abort(uuid)
|
||||
queueRef.current = queueRef.current.filter(t => {
|
||||
return t.uuid !== uuid
|
||||
})
|
||||
}, [])
|
||||
|
||||
const ensureQueuedRow = useCallback(
|
||||
(name: string, kind: FileTransferType, size?: string, driveName?: string) => {
|
||||
clearAllFlagsFor(name)
|
||||
|
||||
(uuid: string, name: string, kind: FileTransferType, size?: string, driveName?: string) => {
|
||||
safeSetState(
|
||||
isMountedRef,
|
||||
setUploadItems,
|
||||
)(prev => {
|
||||
const idx = prev.findIndex(p => p.name === name)
|
||||
const base = createTransferItem(name, size, kind, driveName, TransferStatus.Queued)
|
||||
const idx = prev.findIndex(p => p.uuid === uuid && p.status !== TransferStatus.Done)
|
||||
const base = createTransferItem(uuid, name, size, kind, driveName, TransferStatus.Queued)
|
||||
|
||||
if (idx !== -1) {
|
||||
clearAllFlagsFor(uuid)
|
||||
}
|
||||
|
||||
if (idx === -1) return [...prev, base]
|
||||
const copy = [...prev]
|
||||
@@ -211,6 +237,10 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
const existing = taken[0]
|
||||
const isTrashedExisting = existing ? isTrashed(existing) : false
|
||||
|
||||
if (!existing && allTakenNames.has(originalName)) {
|
||||
return { cancelled: false, finalName: originalName, isReplace: false }
|
||||
}
|
||||
|
||||
const choice = await openConflict({
|
||||
originalName,
|
||||
existingNames: allTakenNames,
|
||||
@@ -237,14 +267,19 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
)
|
||||
|
||||
const trackUpload = useCallback(
|
||||
(name: string, size?: string, kind: FileTransferType = FileTransferType.Upload) => {
|
||||
(
|
||||
uuid: string,
|
||||
name: string,
|
||||
size?: string,
|
||||
kind: FileTransferType = FileTransferType.Upload,
|
||||
driveName?: string,
|
||||
) => {
|
||||
if (!isMountedRef.current) {
|
||||
return () => {
|
||||
// no-op
|
||||
}
|
||||
}
|
||||
|
||||
const driveName = currentDrive?.name
|
||||
const startedAt = Date.now()
|
||||
|
||||
let etaState: ETAState = {
|
||||
@@ -254,8 +289,11 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
}
|
||||
|
||||
setUploadItems(prev => {
|
||||
const idx = prev.findIndex(p => p.name === name)
|
||||
const base = createTransferItem(name, size, kind, driveName, TransferStatus.Uploading)
|
||||
const existing = prev.find(p => p.uuid === uuid)
|
||||
const actualDriveName = existing?.driveName || driveName
|
||||
|
||||
const idx = prev.findIndex(p => p.uuid === uuid)
|
||||
const base = createTransferItem(uuid, name, size, kind, actualDriveName, TransferStatus.Uploading)
|
||||
|
||||
if (idx === -1) return [...prev, base]
|
||||
const copy = [...prev]
|
||||
@@ -265,7 +303,9 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
})
|
||||
|
||||
const onProgress = (progress: UploadProgress) => {
|
||||
if (cancelledUploadingRef.current.has(name) || !isMountedRef.current) return
|
||||
const signal = uploadAbortsRef.current.getSignal(uuid)
|
||||
|
||||
if (cancelledUploadingRef.current.has(uuid) || !isMountedRef.current || signal?.aborted) return
|
||||
|
||||
if (progress.total > 0) {
|
||||
const now = Date.now()
|
||||
@@ -274,91 +314,134 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
const { etaSec, updatedState } = calculateETA(etaState, progress, startedAt, now)
|
||||
etaState = updatedState
|
||||
|
||||
setUploadItems(prev =>
|
||||
updateTransferItems(prev, name, {
|
||||
percent: Math.max(prev.find(it => it.name === name)?.percent || 0, chunkPercentage),
|
||||
kind,
|
||||
etaSec,
|
||||
}),
|
||||
)
|
||||
const isComplete = progress.processed >= progress.total
|
||||
|
||||
if (progress.processed >= progress.total) {
|
||||
const finishedAt = Date.now()
|
||||
setUploadItems(prev =>
|
||||
updateTransferItems(prev, name, {
|
||||
setUploadItems(prev => {
|
||||
const existing = prev.find(it => it.uuid === uuid && it.status === TransferStatus.Uploading)
|
||||
|
||||
if (!existing || existing.status === TransferStatus.Done) return prev
|
||||
|
||||
if (isComplete) {
|
||||
return updateTransferItems(prev, uuid, {
|
||||
percent: 100,
|
||||
status: TransferStatus.Done,
|
||||
kind,
|
||||
etaSec: 0,
|
||||
elapsedSec: Math.round((finishedAt - startedAt) / 1000),
|
||||
}),
|
||||
)
|
||||
}
|
||||
elapsedSec: Math.round((now - startedAt) / 1000),
|
||||
})
|
||||
}
|
||||
|
||||
return updateTransferItems(prev, uuid, {
|
||||
percent: Math.max(existing.percent, chunkPercentage),
|
||||
kind,
|
||||
etaSec,
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return onProgress
|
||||
},
|
||||
[currentDrive?.name],
|
||||
[],
|
||||
)
|
||||
|
||||
const processUploadTask = useCallback(
|
||||
async (task: UploadTask) => {
|
||||
if (!fm || !currentDrive) return
|
||||
if (!fm) return
|
||||
|
||||
const taskDrive = fm.driveList.find(d => d.id.toString() === task.driveId)
|
||||
|
||||
if (!taskDrive) {
|
||||
return
|
||||
}
|
||||
|
||||
const existingFile = task.isReplace ? files.find(f => f.topic.toString() === task.replaceTopic) : undefined
|
||||
|
||||
const info: FileInfoOptions = {
|
||||
name: task.finalName,
|
||||
files: [task.file],
|
||||
customMetadata: normalizeCustomMetadata(buildUploadMeta([task.file])),
|
||||
customMetadata: normalizeCustomMetadata(buildUploadMeta([task.file], undefined, existingFile)),
|
||||
topic: task.isReplace ? task.replaceTopic : undefined,
|
||||
}
|
||||
|
||||
const progressCb = trackUpload(
|
||||
task.uuid,
|
||||
task.finalName,
|
||||
task.prettySize,
|
||||
task.isReplace ? FileTransferType.Update : FileTransferType.Upload,
|
||||
taskDrive.name,
|
||||
)
|
||||
|
||||
safeSetState(
|
||||
isMountedRef,
|
||||
setUploadItems,
|
||||
)(prev =>
|
||||
updateTransferItems(prev, task.finalName, {
|
||||
updateTransferItems(prev, task.uuid, {
|
||||
status: TransferStatus.Uploading,
|
||||
kind: task.isReplace ? FileTransferType.Update : FileTransferType.Upload,
|
||||
startedAt: Date.now(),
|
||||
}),
|
||||
)
|
||||
|
||||
uploadAbortsRef.current.create(task.finalName)
|
||||
uploadAbortsRef.current.create(task.uuid)
|
||||
const signal = uploadAbortsRef.current.getSignal(task.uuid)
|
||||
|
||||
let reject: (reason?: Error) => void
|
||||
const abortHandler = () => {
|
||||
reject(new Error('Upload cancelled'))
|
||||
}
|
||||
|
||||
const checkCancellation = new Promise<never>((_, rej) => {
|
||||
reject = rej
|
||||
signal?.addEventListener(ABORT_EVENT, abortHandler)
|
||||
})
|
||||
|
||||
try {
|
||||
await fm.upload(
|
||||
currentDrive,
|
||||
if (signal?.aborted) {
|
||||
throw new Error('Upload cancelled')
|
||||
}
|
||||
|
||||
const uploadPromise = fm.upload(
|
||||
taskDrive,
|
||||
{ ...info, onUploadProgress: progressCb },
|
||||
{ actHistoryAddress: task.isReplace ? task.replaceHistory : undefined },
|
||||
)
|
||||
|
||||
await Promise.race([uploadPromise, checkCancellation])
|
||||
|
||||
if (currentStamp) {
|
||||
await refreshStamp(currentStamp.batchID.toString())
|
||||
}
|
||||
} catch {
|
||||
const wasCancelled = cancelledUploadingRef.current.has(task.finalName)
|
||||
} catch (error) {
|
||||
const wasCancelled = cancelledUploadingRef.current.has(task.uuid) || signal?.aborted
|
||||
|
||||
if (!wasCancelled) {
|
||||
const errorMsg = error instanceof Error ? error.message : String(error)
|
||||
setErrorMessage?.(`Upload failed: ${errorMsg}`)
|
||||
setShowError(true)
|
||||
}
|
||||
|
||||
safeSetState(
|
||||
isMountedRef,
|
||||
setUploadItems,
|
||||
)(prev =>
|
||||
updateTransferItems(prev, task.finalName, {
|
||||
updateTransferItems(prev, task.uuid, {
|
||||
status: wasCancelled ? TransferStatus.Cancelled : TransferStatus.Error,
|
||||
}),
|
||||
)
|
||||
} finally {
|
||||
uploadAbortsRef.current.abort(task.finalName)
|
||||
cancelledUploadingRef.current.delete(task.finalName)
|
||||
cancelledNamesRef.current.delete(task.finalName)
|
||||
signal?.removeEventListener(ABORT_EVENT, abortHandler)
|
||||
|
||||
const wasCancelled = cancelledUploadingRef.current.has(task.uuid) || signal?.aborted
|
||||
|
||||
if (!wasCancelled) {
|
||||
uploadAbortsRef.current.abort(task.uuid)
|
||||
cancelledUploadingRef.current.delete(task.uuid)
|
||||
cancelledQueuedRef.current.delete(task.uuid)
|
||||
}
|
||||
}
|
||||
},
|
||||
[fm, currentDrive, currentStamp, trackUpload, refreshStamp],
|
||||
[fm, files, currentStamp, trackUpload, refreshStamp, setShowError, setErrorMessage],
|
||||
)
|
||||
|
||||
const trackDownload = useCallback(
|
||||
@@ -369,7 +452,7 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
}
|
||||
}
|
||||
|
||||
const driveName = currentDrive?.name
|
||||
const driveName = props.driveName ?? currentDrive?.name
|
||||
|
||||
let startedAt: number | undefined
|
||||
let etaState: ETAState = {
|
||||
@@ -380,14 +463,15 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
|
||||
setDownloadItems(prev => {
|
||||
const row = createTransferItem(
|
||||
props.uuid,
|
||||
props.name,
|
||||
props.size,
|
||||
FileTransferType.Download,
|
||||
driveName,
|
||||
TransferStatus.Downloading,
|
||||
)
|
||||
row.startedAt = undefined // Downloads start timing when first progress is received
|
||||
const idx = prev.findIndex(p => p.name === props.name)
|
||||
row.startedAt = undefined
|
||||
const idx = prev.findIndex(p => p.uuid === props.uuid)
|
||||
|
||||
if (idx === -1) return [...prev, row]
|
||||
const out = [...prev]
|
||||
@@ -417,10 +501,10 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
}
|
||||
|
||||
setDownloadItems(prev =>
|
||||
updateTransferItems(prev, props.name, {
|
||||
percent: Math.max(prev.find(it => it.name === props.name)?.percent || 0, percent),
|
||||
updateTransferItems(prev, props.uuid, {
|
||||
percent: Math.max(prev.find(it => it.uuid === props.uuid)?.percent || 0, percent),
|
||||
etaSec,
|
||||
startedAt: prev.find(it => it.name === props.name)?.startedAt ?? startedAt,
|
||||
startedAt: prev.find(it => it.uuid === props.uuid)?.startedAt ?? startedAt,
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -428,16 +512,16 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
const finishedAt = Date.now()
|
||||
|
||||
setDownloadItems(prev => {
|
||||
const currentItem = prev.find(it => it.name === props.name)
|
||||
const currentItem = prev.find(it => it.uuid === props.uuid)
|
||||
const elapsedSec = currentItem?.startedAt ? Math.round((finishedAt - currentItem.startedAt) / 1000) : 0
|
||||
|
||||
if (dp.state === DownloadState.Cancelled || dp.state === DownloadState.Error) {
|
||||
const wasCancelled =
|
||||
dp.state === DownloadState.Cancelled || cancelledDownloadingRef.current.has(props.name)
|
||||
dp.state === DownloadState.Cancelled || cancelledDownloadingRef.current.has(props.uuid)
|
||||
|
||||
cancelledDownloadingRef.current.delete(props.name)
|
||||
cancelledDownloadingRef.current.delete(props.uuid)
|
||||
|
||||
return updateTransferItems(prev, props.name, {
|
||||
return updateTransferItems(prev, props.uuid, {
|
||||
status: wasCancelled ? TransferStatus.Cancelled : TransferStatus.Error,
|
||||
etaSec: undefined,
|
||||
elapsedSec: 0,
|
||||
@@ -445,7 +529,7 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
})
|
||||
}
|
||||
|
||||
return updateTransferItems(prev, props.name, {
|
||||
return updateTransferItems(prev, props.uuid, {
|
||||
percent: 100,
|
||||
status: TransferStatus.Done,
|
||||
etaSec: 0,
|
||||
@@ -457,23 +541,48 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
|
||||
return onProgress
|
||||
},
|
||||
[currentDrive?.name],
|
||||
// currentDrive casues rerenders and flickering during the progress tracking
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[],
|
||||
)
|
||||
|
||||
const uploadFiles = useCallback(
|
||||
(picked: FileList | File[]): void => {
|
||||
const filesArr = Array.from(picked)
|
||||
|
||||
if (filesArr.length === 0 || !fm || !currentDrive) return
|
||||
if (filesArr.length === 0 || !fm || !currentDrive || !currentStamp) return
|
||||
|
||||
const currentlyQueued = queueRef.current.length
|
||||
const newFilesCount = filesArr.length
|
||||
const totalAfterAdd = currentlyQueued + newFilesCount
|
||||
|
||||
if (totalAfterAdd > MAX_UPLOAD_FILES) {
|
||||
setErrorMessage?.(
|
||||
`You’re trying to upload ${totalAfterAdd} files, but the limit is ${MAX_UPLOAD_FILES}. Please upload fewer files.`,
|
||||
)
|
||||
setShowError(true)
|
||||
|
||||
return
|
||||
}
|
||||
// TODO: move out this function from the cb and use as a util for better readaility
|
||||
const preflight = async (): Promise<UploadTask[]> => {
|
||||
const progressNames = new Set<string>(uploadItems.map(u => u.name))
|
||||
const progressNames = new Set<string>(
|
||||
uploadItems.filter(u => u.driveName === currentDrive.name).map(u => u.name),
|
||||
)
|
||||
const sameDrive = collectSameDrive(currentDrive.id.toString())
|
||||
const onDiskNames = new Set<string>(sameDrive.map((fi: FileInfo) => fi.name))
|
||||
const reserved = new Set<string>()
|
||||
const tasks: UploadTask[] = []
|
||||
|
||||
let remainingBytes = calculateStampCapacityMetrics(currentStamp || null, currentDrive).remainingBytes
|
||||
const allTaken = new Set<string>([
|
||||
...Array.from(onDiskNames),
|
||||
...Array.from(reserved),
|
||||
...Array.from(progressNames),
|
||||
])
|
||||
|
||||
// Track cumulative file sizes for capacity verification
|
||||
let fileSizeSum = 0
|
||||
let fileCount = 0
|
||||
|
||||
const processFile = async (file: File): Promise<UploadTask | null> => {
|
||||
if (!currentStamp || !currentStamp.usable) {
|
||||
@@ -483,28 +592,30 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
return null
|
||||
}
|
||||
|
||||
const uuid = uuidV4()
|
||||
|
||||
const meta = buildUploadMeta([file])
|
||||
const prettySize = formatBytes(meta.size)
|
||||
|
||||
const allTaken = new Set<string>([
|
||||
...Array.from(onDiskNames),
|
||||
...Array.from(reserved),
|
||||
...Array.from(progressNames),
|
||||
])
|
||||
fileSizeSum += file.size
|
||||
fileCount += 1
|
||||
|
||||
if (file.size > remainingBytes) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(
|
||||
'Skipping upload - insufficient space:',
|
||||
file.name,
|
||||
'size:',
|
||||
file.size,
|
||||
'remaining:',
|
||||
remainingBytes,
|
||||
)
|
||||
setErrorMessage?.('There is not enough space to upload: ' + file.name)
|
||||
setShowError(true)
|
||||
const { ok } = verifyDriveSpace({
|
||||
fm,
|
||||
redundancyLevel: currentDrive.redundancyLevel,
|
||||
stamp: currentStamp,
|
||||
useInfoSize: true,
|
||||
driveId: currentDrive.id.toString(),
|
||||
adminRedundancy: adminDrive?.redundancyLevel,
|
||||
fileSize: fileSizeSum,
|
||||
fileCount,
|
||||
cb: err => {
|
||||
setErrorMessage?.(err + ' (' + truncateNameMiddle(file.name) + ')')
|
||||
setShowError(true)
|
||||
},
|
||||
})
|
||||
|
||||
if (!ok) {
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -533,9 +644,9 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
|
||||
if (!retryInvalidCombo && !retryInvalidName) {
|
||||
reserved.add(finalName)
|
||||
remainingBytes -= file.size
|
||||
|
||||
ensureQueuedRow(
|
||||
uuid,
|
||||
finalName,
|
||||
isReplace ? FileTransferType.Update : FileTransferType.Upload,
|
||||
prettySize,
|
||||
@@ -543,12 +654,15 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
)
|
||||
|
||||
return {
|
||||
uuid,
|
||||
file,
|
||||
finalName,
|
||||
prettySize,
|
||||
isReplace: Boolean(isReplace),
|
||||
replaceTopic,
|
||||
replaceHistory,
|
||||
driveId: currentDrive.id.toString(),
|
||||
driveName: currentDrive.name,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -561,7 +675,8 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
|
||||
if (task) {
|
||||
tasks.push(task)
|
||||
} else if (file.size > remainingBytes) {
|
||||
} else {
|
||||
// Stop processing remaining files if capacity check failed
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -579,14 +694,14 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
|
||||
if (!task) break
|
||||
|
||||
const isCancelled = cancelledNamesRef.current.has(task.finalName)
|
||||
const isCancelled = cancelledQueuedRef.current.has(task.uuid)
|
||||
|
||||
if (isCancelled) {
|
||||
safeSetState(
|
||||
isMountedRef,
|
||||
setUploadItems,
|
||||
)(prev => updateTransferItems(prev, task.finalName, { status: TransferStatus.Cancelled }))
|
||||
cancelledNamesRef.current.delete(task.finalName)
|
||||
)(prev => updateTransferItems(prev, task.uuid, { status: TransferStatus.Cancelled }))
|
||||
cancelledQueuedRef.current.delete(task.uuid)
|
||||
queueRef.current.shift()
|
||||
} else {
|
||||
await processUploadTask(task)
|
||||
@@ -595,10 +710,34 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
}
|
||||
} finally {
|
||||
runningRef.current = false
|
||||
|
||||
if (queueRef.current.length > 0) {
|
||||
runQueue()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
if (!currentStamp || !currentStamp.usable) {
|
||||
setErrorMessage?.('Stamp is not usable.')
|
||||
setShowError(true)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (beeApi) {
|
||||
const stampValid = await validateStampStillExists(beeApi, currentStamp.batchID)
|
||||
|
||||
if (!stampValid) {
|
||||
setErrorMessage?.(
|
||||
'The selected stamp is no longer valid or has been deleted. Please select a different stamp.',
|
||||
)
|
||||
setShowError(true)
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const tasks = await preflight()
|
||||
queueRef.current = queueRef.current.concat(tasks)
|
||||
runQueue()
|
||||
@@ -613,69 +752,73 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
ensureQueuedRow,
|
||||
processUploadTask,
|
||||
uploadItems,
|
||||
adminDrive,
|
||||
setShowError,
|
||||
setErrorMessage,
|
||||
beeApi,
|
||||
],
|
||||
)
|
||||
|
||||
const cancelOrDismissUpload = useCallback(
|
||||
(name: string) => {
|
||||
(uuid: string) => {
|
||||
safeSetState(
|
||||
isMountedRef,
|
||||
setUploadItems,
|
||||
)(prev => {
|
||||
const row = prev.find(r => r.name === name)
|
||||
const row = prev.find(r => r.uuid === uuid)
|
||||
|
||||
if (!row) return prev
|
||||
|
||||
if (row.status === TransferStatus.Queued) {
|
||||
cancelledNamesRef.current.add(name)
|
||||
queueRef.current = queueRef.current.filter(t => t.finalName !== name)
|
||||
cancelledQueuedRef.current.add(row.uuid)
|
||||
queueRef.current = queueRef.current.filter(t => t.uuid !== row.uuid)
|
||||
|
||||
return prev.map(r => (r.name === name ? { ...r, status: TransferStatus.Cancelled } : r))
|
||||
return prev.map(r => (r.uuid === row.uuid ? { ...r, status: TransferStatus.Cancelled } : r))
|
||||
}
|
||||
|
||||
if (row.status === TransferStatus.Uploading) {
|
||||
cancelledUploadingRef.current.add(name)
|
||||
uploadAbortsRef.current.abort(name)
|
||||
cancelledUploadingRef.current.add(row.uuid)
|
||||
uploadAbortsRef.current.abort(row.uuid)
|
||||
|
||||
return prev.map(r => (r.name === name ? { ...r, status: TransferStatus.Cancelled } : r))
|
||||
return prev.map(r => (r.uuid === uuid ? { ...r, status: TransferStatus.Cancelled } : r))
|
||||
}
|
||||
|
||||
clearAllFlagsFor(name)
|
||||
clearAllFlagsFor(row.uuid)
|
||||
|
||||
return prev.filter(r => r.name !== name)
|
||||
return prev.filter(r => r.uuid !== uuid)
|
||||
})
|
||||
},
|
||||
[clearAllFlagsFor],
|
||||
)
|
||||
|
||||
const cancelOrDismissDownload = useCallback((name: string) => {
|
||||
const cancelOrDismissDownload = useCallback((uuid: string) => {
|
||||
safeSetState(
|
||||
isMountedRef,
|
||||
setDownloadItems,
|
||||
)(prev => {
|
||||
const row = prev.find(r => r.name === name)
|
||||
const row = prev.find(r => r.uuid === uuid)
|
||||
|
||||
if (!row) return prev
|
||||
|
||||
if (row.status === TransferStatus.Downloading) {
|
||||
cancelledDownloadingRef.current.add(name)
|
||||
abortDownload(name)
|
||||
cancelledDownloadingRef.current.add(uuid)
|
||||
abortDownload(uuid)
|
||||
|
||||
return prev.map(r => (r.name === name ? { ...r, status: TransferStatus.Cancelled } : r))
|
||||
return prev.map(r => (r.uuid === uuid ? { ...r, status: TransferStatus.Cancelled } : r))
|
||||
}
|
||||
|
||||
cancelledDownloadingRef.current.delete(name)
|
||||
cancelledDownloadingRef.current.delete(uuid)
|
||||
|
||||
return prev.filter(r => r.name !== name)
|
||||
return prev.filter(r => r.uuid !== uuid)
|
||||
})
|
||||
}, [])
|
||||
|
||||
const dismissAllUploads = useCallback(() => {
|
||||
setUploadItems([])
|
||||
cancelledNamesRef.current.clear()
|
||||
uploadAbortsRef.current.clear()
|
||||
queueRef.current = []
|
||||
cancelledQueuedRef.current.clear()
|
||||
cancelledUploadingRef.current.clear()
|
||||
setUploadItems([])
|
||||
}, [])
|
||||
|
||||
const dismissAllDownloads = useCallback(() => {
|
||||
@@ -684,7 +827,31 @@ export function useTransfers({ setErrorMessage }: TransferProps) {
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const handleFileUploaded = (e: Event) => {
|
||||
const { fileInfo } = (e as CustomEvent).detail || {}
|
||||
|
||||
if (!fileInfo) return
|
||||
|
||||
setUploadItems(prev => {
|
||||
const item = prev.find(it => it.name === fileInfo.name && it.status === TransferStatus.Uploading)
|
||||
|
||||
if (!item) return prev
|
||||
|
||||
const elapsedSec = item.startedAt ? Math.round((Date.now() - item.startedAt) / 1000) : 0
|
||||
|
||||
return updateTransferItems(prev, item.uuid, {
|
||||
percent: 100,
|
||||
status: TransferStatus.Done,
|
||||
etaSec: 0,
|
||||
elapsedSec,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
window.addEventListener(FILE_MANAGER_EVENTS.FILE_UPLOADED, handleFileUploaded as EventListener)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener(FILE_MANAGER_EVENTS.FILE_UPLOADED, handleFileUploaded as EventListener)
|
||||
isMountedRef.current = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import { BatchId, Bee, BZZ, Duration, PostageBatch, RedundancyLevel, Size } from '@ethersphere/bee-js'
|
||||
import { FileManagerBase, DriveInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import {
|
||||
FileManagerBase,
|
||||
DriveInfo,
|
||||
estimateDriveListMetadataSize,
|
||||
estimateFileInfoMetadataSize,
|
||||
FileInfo,
|
||||
} from '@solarpunkltd/file-manager-lib'
|
||||
import { getHumanReadableFileSize } from '../../../utils/file'
|
||||
import { ActionTag } from '../constants/transfers'
|
||||
|
||||
export const getUsableStamps = async (bee: Bee | null): Promise<PostageBatch[]> => {
|
||||
if (!bee) {
|
||||
@@ -16,6 +23,19 @@ export const getUsableStamps = async (bee: Bee | null): Promise<PostageBatch[]>
|
||||
}
|
||||
}
|
||||
|
||||
export const validateStampStillExists = async (bee: Bee, batchId: BatchId): Promise<boolean> => {
|
||||
try {
|
||||
const stamp = await bee.getPostageBatch(batchId.toString())
|
||||
|
||||
return stamp.usable
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn(`Failed to validate stamp ${batchId.toString().slice(0, 8)}...:`, error)
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export const fmGetStorageCost = async (
|
||||
capacity: number,
|
||||
validityEndDate: Date,
|
||||
@@ -50,6 +70,7 @@ export const fmFetchCost = async (
|
||||
beeApi: Bee | null,
|
||||
setCost: (cost: BZZ) => void,
|
||||
currentFetch: React.MutableRefObject<Promise<void> | null>,
|
||||
onError?: (error: unknown) => void,
|
||||
) => {
|
||||
if (currentFetch.current) {
|
||||
await currentFetch.current
|
||||
@@ -58,10 +79,22 @@ export const fmFetchCost = async (
|
||||
let isCurrentFetch = true
|
||||
|
||||
const fetchPromise = (async () => {
|
||||
const cost = await fmGetStorageCost(capacity, validityEndDate, encryption, erasureCodeLevel, beeApi)
|
||||
try {
|
||||
const cost = await fmGetStorageCost(capacity, validityEndDate, encryption, erasureCodeLevel, beeApi)
|
||||
|
||||
if (isCurrentFetch) {
|
||||
setCost(cost ?? BZZ.fromDecimalString('0'))
|
||||
if (isCurrentFetch) {
|
||||
if (cost) {
|
||||
setCost(cost)
|
||||
} else {
|
||||
setCost(BZZ.fromDecimalString('0'))
|
||||
onError?.(new Error('Storage cost unavailable - node may be syncing'))
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (isCurrentFetch) {
|
||||
setCost(BZZ.fromDecimalString('0'))
|
||||
onError?.(error)
|
||||
}
|
||||
}
|
||||
})()
|
||||
|
||||
@@ -72,32 +105,95 @@ export const fmFetchCost = async (
|
||||
currentFetch.current = null
|
||||
}
|
||||
|
||||
export const handleCreateDrive = async (
|
||||
beeApi: Bee | null,
|
||||
fm: FileManagerBase | null,
|
||||
size: Size,
|
||||
duration: Duration,
|
||||
label: string,
|
||||
encryption: boolean,
|
||||
erasureCodeLevel: RedundancyLevel,
|
||||
isAdmin: boolean,
|
||||
resetState: boolean,
|
||||
existingBatch: PostageBatch | null,
|
||||
onSuccess?: () => void,
|
||||
onError?: (error: unknown) => void,
|
||||
): Promise<void> => {
|
||||
if (!beeApi || !fm) return
|
||||
export interface CreateDriveOptions {
|
||||
beeApi: Bee | null
|
||||
fm: FileManagerBase | null
|
||||
size: Size
|
||||
duration: Duration
|
||||
label: string
|
||||
encryption: boolean
|
||||
redundancyLevel: RedundancyLevel
|
||||
adminRedundancy: RedundancyLevel
|
||||
isAdmin: boolean
|
||||
resetState: boolean
|
||||
existingBatch: PostageBatch | null
|
||||
onSuccess?: () => void
|
||||
onError?: (error: unknown) => void
|
||||
}
|
||||
|
||||
export const handleCreateDrive = async (options: CreateDriveOptions): Promise<void> => {
|
||||
const {
|
||||
beeApi,
|
||||
fm,
|
||||
size,
|
||||
duration,
|
||||
label,
|
||||
encryption,
|
||||
redundancyLevel,
|
||||
adminRedundancy,
|
||||
isAdmin,
|
||||
resetState,
|
||||
existingBatch,
|
||||
onSuccess,
|
||||
onError,
|
||||
} = { ...options }
|
||||
|
||||
if (!beeApi || !fm) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('Error creating drive: Bee API or FM is invalid!')
|
||||
|
||||
onError?.('Error creating drive: Bee API or FM is invalid!')
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
let batchId: BatchId
|
||||
|
||||
if (!existingBatch) {
|
||||
batchId = await beeApi.buyStorage(size, duration, { label }, undefined, encryption, erasureCodeLevel)
|
||||
if (!isAdmin) {
|
||||
if (!fm.adminStamp) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('Error creating drive: admin stamp is not available')
|
||||
|
||||
throw new Error('Error creating drive: admin stamp is not available')
|
||||
}
|
||||
|
||||
verifyDriveSpace({
|
||||
fm,
|
||||
redundancyLevel,
|
||||
stamp: fm.adminStamp,
|
||||
adminRedundancy,
|
||||
cb: err => {
|
||||
throw new Error(err)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
batchId = await beeApi.buyStorage(size, duration, { label }, undefined, encryption, redundancyLevel)
|
||||
} else {
|
||||
const isValid = await validateStampStillExists(beeApi, existingBatch.batchID)
|
||||
|
||||
if (!isValid) {
|
||||
throw new Error(
|
||||
'The stamp is no longer valid or has been deleted. Please select a different stamp from the list.',
|
||||
)
|
||||
}
|
||||
|
||||
verifyDriveSpace({
|
||||
fm,
|
||||
redundancyLevel,
|
||||
stamp: existingBatch,
|
||||
adminRedundancy,
|
||||
cb: err => {
|
||||
throw new Error(err)
|
||||
},
|
||||
})
|
||||
|
||||
batchId = existingBatch.batchID
|
||||
}
|
||||
|
||||
await fm.createDrive(batchId, label, isAdmin, erasureCodeLevel, resetState)
|
||||
await fm.createDrive(batchId, label, isAdmin, redundancyLevel, resetState)
|
||||
|
||||
onSuccess?.()
|
||||
} catch (e) {
|
||||
@@ -107,68 +203,22 @@ export const handleCreateDrive = async (
|
||||
}
|
||||
}
|
||||
|
||||
interface StampCapacityMetrics {
|
||||
capacityPct: number
|
||||
usedSize: string
|
||||
totalSize: string
|
||||
usedBytes: number
|
||||
totalBytes: number
|
||||
remainingBytes: number
|
||||
export interface DestroyDriveOptions {
|
||||
beeApi?: Bee | null
|
||||
fm: FileManagerBase | null
|
||||
drive: DriveInfo
|
||||
adminDrive: DriveInfo | null
|
||||
isDestroy: boolean
|
||||
onSuccess?: () => void
|
||||
onError?: (error: unknown) => void
|
||||
}
|
||||
|
||||
export const calculateStampCapacityMetrics = (
|
||||
stamp: PostageBatch | null,
|
||||
drive?: DriveInfo | null,
|
||||
): StampCapacityMetrics => {
|
||||
if (!stamp) {
|
||||
return {
|
||||
capacityPct: 0,
|
||||
usedSize: '—',
|
||||
totalSize: '—',
|
||||
usedBytes: 0,
|
||||
totalBytes: 0,
|
||||
remainingBytes: 0,
|
||||
}
|
||||
}
|
||||
export const handleDestroyAndForgetDrive = async (options: DestroyDriveOptions): Promise<void> => {
|
||||
const { beeApi, fm, adminDrive, drive, isDestroy, onSuccess, onError } = { ...options }
|
||||
|
||||
let usedBytes = 0
|
||||
let totalBytes = 0
|
||||
let capacityPct = 0
|
||||
let remainingBytes = 0
|
||||
if (!beeApi || !fm || !fm.adminStamp || !adminDrive) {
|
||||
onError?.('Error destroying drive: Admin Drive, Bee API or FM is invalid!')
|
||||
|
||||
if (drive) {
|
||||
totalBytes = stamp.calculateSize(false, drive.redundancyLevel).toBytes()
|
||||
remainingBytes = stamp.calculateRemainingSize(false, drive.redundancyLevel).toBytes()
|
||||
usedBytes = totalBytes - remainingBytes
|
||||
capacityPct = ((totalBytes - remainingBytes) / totalBytes) * 100
|
||||
} else {
|
||||
capacityPct = stamp.usage * 100
|
||||
usedBytes = stamp.size.toBytes() - stamp.remainingSize.toBytes()
|
||||
totalBytes = stamp.size.toBytes()
|
||||
remainingBytes = totalBytes - usedBytes
|
||||
}
|
||||
|
||||
const usedSize = getHumanReadableFileSize(usedBytes)
|
||||
const totalSize = getHumanReadableFileSize(totalBytes)
|
||||
|
||||
return {
|
||||
capacityPct,
|
||||
usedSize,
|
||||
totalSize,
|
||||
usedBytes,
|
||||
totalBytes,
|
||||
remainingBytes,
|
||||
}
|
||||
}
|
||||
|
||||
export const handleDestroyDrive = async (
|
||||
beeApi: Bee | null,
|
||||
fm: FileManagerBase | null,
|
||||
drive: DriveInfo,
|
||||
onSuccess?: () => void,
|
||||
onError?: (error: unknown) => void,
|
||||
): Promise<void> => {
|
||||
if (!beeApi || !fm) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -179,11 +229,26 @@ export const handleDestroyDrive = async (
|
||||
throw new Error(`Postage stamp (${drive.batchId}) for the current drive (${drive.name}) not found`)
|
||||
}
|
||||
|
||||
verifyDriveSpace({
|
||||
fm,
|
||||
driveId: drive.id.toString(),
|
||||
redundancyLevel: drive.redundancyLevel,
|
||||
stamp: fm.adminStamp,
|
||||
isRemove: true,
|
||||
adminRedundancy: adminDrive.redundancyLevel,
|
||||
cb: err => {
|
||||
throw new Error(err)
|
||||
},
|
||||
})
|
||||
|
||||
const ttlDays = stamp.duration.toDays()
|
||||
|
||||
if (ttlDays <= 2) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn(`Stamp TTL ${ttlDays} <= 2 days, skipping drive destruction: forgetting the drive.`)
|
||||
if (ttlDays <= 2 || !isDestroy) {
|
||||
if (isDestroy) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn(`Stamp TTL ${ttlDays} <= 2 days, skipping drive destruction: forgetting the drive.`)
|
||||
}
|
||||
|
||||
await fm.forgetDrive(drive)
|
||||
|
||||
return
|
||||
@@ -197,18 +262,156 @@ export const handleDestroyDrive = async (
|
||||
}
|
||||
}
|
||||
|
||||
export const handleForgetDrive = async (
|
||||
fm: FileManagerBase | null,
|
||||
drive: DriveInfo,
|
||||
onSuccess?: () => void,
|
||||
onError?: (error: unknown) => void,
|
||||
): Promise<void> => {
|
||||
if (!fm) return
|
||||
export interface StampCapacityMetrics {
|
||||
capacityPct: number
|
||||
usedSize: string
|
||||
stampSize: string
|
||||
usedBytes: number
|
||||
stampSizeBytes: number
|
||||
remainingBytes: number
|
||||
}
|
||||
|
||||
try {
|
||||
await fm.forgetDrive(drive)
|
||||
onSuccess?.()
|
||||
} catch (e) {
|
||||
onError?.(e)
|
||||
export const calculateStampCapacityMetrics = (
|
||||
stamp: PostageBatch,
|
||||
files: FileInfo[],
|
||||
redundancyLevel?: RedundancyLevel,
|
||||
useReportedOnly?: boolean,
|
||||
): StampCapacityMetrics => {
|
||||
let stampSizeBytes = 0
|
||||
let remainingReportedBytes = 0
|
||||
|
||||
if (redundancyLevel !== undefined) {
|
||||
stampSizeBytes = stamp.calculateSize(false, redundancyLevel).toBytes()
|
||||
remainingReportedBytes = stamp.calculateRemainingSize(false, redundancyLevel).toBytes()
|
||||
} else {
|
||||
stampSizeBytes = stamp.size.toBytes()
|
||||
remainingReportedBytes = stamp.remainingSize.toBytes()
|
||||
}
|
||||
|
||||
const usedBytesReported = stampSizeBytes - remainingReportedBytes
|
||||
const pctReportedStampUsage = stamp.usage * 100
|
||||
|
||||
let usedSizeMaxBytes = usedBytesReported
|
||||
let pctFromDriveUsage = pctReportedStampUsage
|
||||
let remainingBytes = remainingReportedBytes
|
||||
|
||||
if (!useReportedOnly) {
|
||||
const usedBytesFromFiles = files
|
||||
.map(f => {
|
||||
let rawSize = 0
|
||||
|
||||
const lifecycle = (f.customMetadata?.lifecycle || '').toString().toLowerCase()
|
||||
const isLifecycleOperation =
|
||||
lifecycle === ActionTag.Trashed || lifecycle === ActionTag.Recovered || lifecycle === ActionTag.Restored
|
||||
|
||||
if (
|
||||
(f.customMetadata?.size && !isLifecycleOperation) ||
|
||||
(f.customMetadata?.size && !f.customMetadata?.accumulatedSize)
|
||||
) {
|
||||
rawSize = Number(f.customMetadata.size)
|
||||
}
|
||||
const accumulatedSize = Number(f.customMetadata?.accumulatedSize || rawSize || 0)
|
||||
|
||||
return accumulatedSize
|
||||
})
|
||||
.reduce((acc, current) => acc + current, 0)
|
||||
|
||||
const remainingBytesFromFiles = stampSizeBytes - usedBytesFromFiles > 0 ? stampSizeBytes - usedBytesFromFiles : 0
|
||||
remainingBytes = Math.min(remainingReportedBytes, remainingBytesFromFiles)
|
||||
|
||||
usedSizeMaxBytes = Math.max(usedBytesFromFiles, usedBytesReported)
|
||||
pctFromDriveUsage = stampSizeBytes > 0 ? (usedSizeMaxBytes / stampSizeBytes) * 100 : 0
|
||||
}
|
||||
|
||||
const usedSizeMax = getHumanReadableFileSize(usedSizeMaxBytes)
|
||||
const capacityPct = Math.max(pctFromDriveUsage, pctReportedStampUsage)
|
||||
const stampSize = getHumanReadableFileSize(stampSizeBytes)
|
||||
|
||||
return {
|
||||
capacityPct,
|
||||
usedSize: usedSizeMax,
|
||||
stampSize,
|
||||
usedBytes: usedSizeMaxBytes,
|
||||
stampSizeBytes,
|
||||
remainingBytes,
|
||||
}
|
||||
}
|
||||
|
||||
export interface DriveSpaceOptions {
|
||||
fm: FileManagerBase
|
||||
driveId?: string
|
||||
redundancyLevel: RedundancyLevel
|
||||
stamp: PostageBatch
|
||||
adminRedundancy?: RedundancyLevel
|
||||
useInfoSize?: boolean
|
||||
isRemove?: boolean
|
||||
fileSize?: number
|
||||
fileCount?: number
|
||||
cb?: (msg: string) => void
|
||||
}
|
||||
|
||||
export const verifyDriveSpace = (
|
||||
options: DriveSpaceOptions,
|
||||
): { remainingBytes: number; totalSizeBytes: number; ok: boolean } => {
|
||||
const { fm, driveId, redundancyLevel, stamp, adminRedundancy, useInfoSize, isRemove, fileSize, fileCount, cb } = {
|
||||
...options,
|
||||
}
|
||||
|
||||
const drives = [...fm.driveList]
|
||||
let filesPerDrives: FileInfo[] = []
|
||||
|
||||
// new drivelist state size calc.
|
||||
if (isRemove) {
|
||||
const driveIx = drives.findIndex(d => d.id.toString() === driveId?.toString())
|
||||
|
||||
if (driveIx === -1) {
|
||||
cb?.(`Admin drive not found during stamp verification`)
|
||||
|
||||
return { remainingBytes: 0, totalSizeBytes: 0, ok: false }
|
||||
}
|
||||
|
||||
drives.splice(driveIx, 1)
|
||||
filesPerDrives = fm.fileInfoList.filter(fi => fi.driveId !== driveId)
|
||||
} else {
|
||||
filesPerDrives = driveId ? fm.fileInfoList.filter(fi => fi.driveId === driveId) : []
|
||||
}
|
||||
|
||||
// admin stamp capacity calcl., needed for forget, destroy, create
|
||||
if (adminRedundancy !== undefined && fm.adminStamp) {
|
||||
// upper limit estimate on the drivelist metadata state size based on the number of drives and files
|
||||
const estimatedDlSizeBytes = estimateDriveListMetadataSize(drives) * drives.length
|
||||
const { remainingBytes: remainingAdminBytes } = calculateStampCapacityMetrics(fm.adminStamp, [], adminRedundancy)
|
||||
|
||||
const ok = remainingAdminBytes >= estimatedDlSizeBytes
|
||||
|
||||
if (!ok) {
|
||||
cb?.(
|
||||
`Insufficient admin drive capacity. Required: ~${getHumanReadableFileSize(
|
||||
estimatedDlSizeBytes,
|
||||
)} bytes, Available: ${getHumanReadableFileSize(
|
||||
remainingAdminBytes,
|
||||
)} bytes. Please top up the admin drive/stamp.`,
|
||||
)
|
||||
|
||||
return { remainingBytes: remainingAdminBytes, totalSizeBytes: estimatedDlSizeBytes, ok }
|
||||
}
|
||||
}
|
||||
|
||||
// other fileinfo metadata size calc.
|
||||
const estimatedFiSize = estimateFileInfoMetadataSize()
|
||||
const count = fileCount ?? 1
|
||||
const estimateReqSizeBytes = Number(Boolean(useInfoSize)) * estimatedFiSize * count + (fileSize ? fileSize : 0)
|
||||
const { remainingBytes } = calculateStampCapacityMetrics(stamp, filesPerDrives, redundancyLevel)
|
||||
|
||||
const ok = remainingBytes >= estimateReqSizeBytes
|
||||
|
||||
if (!ok) {
|
||||
cb?.(
|
||||
`Insufficient capacity. Required: ~${getHumanReadableFileSize(
|
||||
estimateReqSizeBytes,
|
||||
)} bytes, Available: ${getHumanReadableFileSize(remainingBytes)} bytes. Please top up the drive/stamp.`,
|
||||
)
|
||||
}
|
||||
|
||||
return { remainingBytes, totalSizeBytes: estimateReqSizeBytes, ok }
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { PrivateKey } from '@ethersphere/bee-js'
|
||||
import { FileInfo, FileStatus } from '@solarpunkltd/file-manager-lib'
|
||||
import { keccak256 } from '@ethersproject/keccak256'
|
||||
import { toUtf8Bytes } from '@ethersproject/strings'
|
||||
import { lifetimeAdjustments } from '../constants/stamps'
|
||||
|
||||
export function getDaysLeft(expiryDate: Date): number {
|
||||
const now = new Date()
|
||||
@@ -22,14 +23,6 @@ export const fromBytesConversion = (size: number, metric: string) => {
|
||||
}
|
||||
}
|
||||
|
||||
const lifetimeAdjustments = new Map<number, (date: Date) => void>([
|
||||
[0, date => date.setDate(date.getDate() + 7)],
|
||||
[1, date => date.setMonth(date.getMonth() + 1)],
|
||||
[2, date => date.setMonth(date.getMonth() + 3)],
|
||||
[3, date => date.setMonth(date.getMonth() + 6)],
|
||||
[4, date => date.setFullYear(date.getFullYear() + 1)],
|
||||
])
|
||||
|
||||
export function getExpiryDateByLifetime(lifetimeValue: number, actualValidity?: Date): Date {
|
||||
const now = actualValidity || new Date()
|
||||
|
||||
@@ -65,13 +58,13 @@ export const formatBytes = (v?: string | number): string | undefined => {
|
||||
|
||||
if (!Number.isFinite(n) || n < 0) return undefined
|
||||
|
||||
if (n < 1024) return `${n} B`
|
||||
if (n < 1000) return `${n} B`
|
||||
|
||||
const units = ['KB', 'MB', 'GB', 'TB'] as const
|
||||
let val = n / 1024
|
||||
let val = n / 1000
|
||||
let i = 0
|
||||
while (val >= 1024 && i < units.length - 1) {
|
||||
val /= 1024
|
||||
while (val >= 1000 && i < units.length - 1) {
|
||||
val /= 1000
|
||||
i++
|
||||
}
|
||||
|
||||
@@ -135,3 +128,15 @@ export const safeSetState =
|
||||
(value: React.SetStateAction<T>) => {
|
||||
if (ref.current) setter(value)
|
||||
}
|
||||
|
||||
export const truncateNameMiddle = (s: string, max = 40, start?: number, end?: number): string => {
|
||||
if (s.length <= max) return s
|
||||
|
||||
if (start && end && start + end < s.length) {
|
||||
return `${s.slice(0, start)}…${s.slice(-end)}`
|
||||
}
|
||||
|
||||
const half = Math.floor((max - 1) / 2)
|
||||
|
||||
return `${s.slice(0, half)}…${s.slice(-half)}`
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { FileInfo, FileManager } from '@solarpunkltd/file-manager-lib'
|
||||
import { getExtensionFromName, guessMime, VIEWERS } from './view'
|
||||
import { guessMime, VIEWERS } from './view'
|
||||
import { AbortManager } from './abortManager'
|
||||
import { DownloadProgress, DownloadState } from '../constants/transfers'
|
||||
|
||||
@@ -48,15 +48,17 @@ const processStream = async (
|
||||
onDownloadProgress?.({ progress, isDownloading: !done })
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
if ((e as { name?: string }).name === Errors.AbortError) {
|
||||
onDownloadProgress?.({ progress, isDownloading: false, state: DownloadState.Cancelled })
|
||||
const isAbort = (e as { name?: string }).name === Errors.AbortError
|
||||
|
||||
return
|
||||
if (isAbort) {
|
||||
onDownloadProgress?.({ progress, isDownloading: false, state: DownloadState.Cancelled })
|
||||
} else {
|
||||
onDownloadProgress?.({ progress, isDownloading: false, state: DownloadState.Error })
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('Failed to process stream: ', e)
|
||||
}
|
||||
|
||||
onDownloadProgress?.({ progress, isDownloading: false, state: DownloadState.Error })
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('Failed to process stream: ', e)
|
||||
throw e
|
||||
} finally {
|
||||
reader.releaseLock()
|
||||
|
||||
@@ -66,8 +68,10 @@ const processStream = async (
|
||||
} else {
|
||||
await writable?.close()
|
||||
}
|
||||
} catch {
|
||||
} catch (e: unknown) {
|
||||
/* no-op */
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('filehandle close/abort error: ', e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -142,15 +146,24 @@ const getSingleFileHandle = async (
|
||||
info: FileInfo,
|
||||
defaultDownloadFolder: string,
|
||||
): Promise<FileInfoWithHandle[] | undefined> => {
|
||||
const mimeType = guessMime(info.name, info.customMetadata)
|
||||
const { mime, ext } = guessMime(info.name, info.customMetadata)
|
||||
|
||||
const pickerOptions: {
|
||||
suggestedName: string
|
||||
startIn: string
|
||||
types?: Array<{ accept: Record<string, string[]> }>
|
||||
} = {
|
||||
suggestedName: info.name,
|
||||
startIn: defaultDownloadFolder,
|
||||
}
|
||||
|
||||
if (ext) {
|
||||
pickerOptions.types = [{ accept: { [mime]: [`.${ext}`] } }]
|
||||
}
|
||||
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const handle = (await (window as any).showSaveFilePicker({
|
||||
suggestedName: info.name,
|
||||
startIn: defaultDownloadFolder,
|
||||
types: [{ accept: { [mimeType]: [`.${getExtensionFromName(info.name)}`] } }],
|
||||
})) as FileSystemFileHandle
|
||||
const handle = (await (window as any).showSaveFilePicker(pickerOptions)) as FileSystemFileHandle
|
||||
|
||||
return [{ info, handle }]
|
||||
} catch (error: unknown) {
|
||||
@@ -222,16 +235,20 @@ const downloadToDisk = async (
|
||||
handle: FileSystemFileHandle,
|
||||
onDownloadProgress?: (progress: DownloadProgress) => void,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
for (const stream of streams) {
|
||||
await processStream(stream, handle, onDownloadProgress, signal)
|
||||
}
|
||||
|
||||
return true
|
||||
} catch (error: unknown) {
|
||||
if ((error as { name?: string }).name !== Errors.AbortError) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('Error during download to disk: ', error)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,30 +258,36 @@ const downloadToBlob = async (
|
||||
onDownloadProgress?: (progress: DownloadProgress) => void,
|
||||
isOpenWindow?: boolean,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
for (const stream of streams) {
|
||||
const mime = guessMime(info.name, info.customMetadata)
|
||||
const { mime } = guessMime(info.name, info.customMetadata)
|
||||
const blob = await streamToBlob(stream, mime, onDownloadProgress, signal)
|
||||
|
||||
if (blob) {
|
||||
const url = URL.createObjectURL(blob)
|
||||
let opened = false
|
||||
if (!blob) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (isOpenWindow) {
|
||||
opened = openNewWindow(info.name, mime, url)
|
||||
}
|
||||
const url = URL.createObjectURL(blob)
|
||||
let opened = false
|
||||
|
||||
if (!opened) {
|
||||
downloadFromUrl(url, info.name)
|
||||
}
|
||||
if (isOpenWindow) {
|
||||
opened = openNewWindow(info.name, mime, url)
|
||||
}
|
||||
|
||||
if (!opened) {
|
||||
downloadFromUrl(url, info.name)
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
} catch (error: unknown) {
|
||||
if ((error as { name?: string }).name !== Errors.AbortError) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('Error during download and open: ', error)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,29 +342,50 @@ export const startDownloadingQueue = async (
|
||||
try {
|
||||
if (fh.cancelled) {
|
||||
tracker?.({ progress: 0, isDownloading: false, state: DownloadState.Cancelled })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const dataStreams = (await fm.download(fh.info)) as ReadableStream<Uint8Array>[]
|
||||
|
||||
if (!dataStreams || dataStreams.length === 0) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(`No data streams returned for ${name}`)
|
||||
tracker?.({ progress: 0, isDownloading: false, state: DownloadState.Error })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
let success = false
|
||||
|
||||
if (isOpenWindow || !fh.handle) {
|
||||
success = await downloadToBlob(dataStreams, fh.info, tracker, isOpenWindow, signal)
|
||||
} else {
|
||||
const dataStreams = (await fm.download(fh.info)) as ReadableStream<Uint8Array>[]
|
||||
success = await downloadToDisk(dataStreams, fh.handle, tracker, signal)
|
||||
}
|
||||
|
||||
if (isOpenWindow || !fh.handle) {
|
||||
await downloadToBlob(dataStreams, fh.info, tracker, isOpenWindow, signal)
|
||||
} else {
|
||||
await downloadToDisk(dataStreams, fh.handle, tracker, signal)
|
||||
}
|
||||
if (!tracker) {
|
||||
return
|
||||
}
|
||||
|
||||
// Ensure the tracker shows completion
|
||||
if (tracker) {
|
||||
const size = fh.info.customMetadata?.size
|
||||
const finalProgress = size ? Number(size) : 0
|
||||
if (success) {
|
||||
const size = fh.info.customMetadata?.size
|
||||
const finalProgress = size ? Number(size) : 0
|
||||
tracker({ progress: finalProgress, isDownloading: false })
|
||||
|
||||
tracker({ progress: finalProgress, isDownloading: false })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (!signal?.aborted) {
|
||||
tracker({ progress: 0, isDownloading: false, state: DownloadState.Error })
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
const isAbortError = (error as { name?: string }).name === Errors.AbortError
|
||||
|
||||
// Ensure the tracker shows completion
|
||||
if (!isAbortError) {
|
||||
tracker?.({ progress: 0, isDownloading: false, state: DownloadState.Error })
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('download queue error: ', error)
|
||||
} else {
|
||||
tracker?.({ progress: 0, isDownloading: false, state: DownloadState.Cancelled })
|
||||
}
|
||||
@@ -350,7 +394,8 @@ export const startDownloadingQueue = async (
|
||||
}
|
||||
}),
|
||||
)
|
||||
} catch (error: unknown) {
|
||||
// Errors are handled per-file in the map above
|
||||
} catch (e: unknown) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('An error happened in the download queue: ', e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import type { DriveInfo, FileInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import type { FileManagerBase } from '@solarpunkltd/file-manager-lib'
|
||||
import type { PostageBatch, RedundancyLevel } from '@ethersphere/bee-js'
|
||||
import { verifyDriveSpace } from './bee'
|
||||
import { capitalizeFirstLetter } from './common'
|
||||
import { ActionTag } from '../constants/transfers'
|
||||
|
||||
export enum FileOperation {
|
||||
Trash = 'trash',
|
||||
Recover = 'recover',
|
||||
Forget = 'forget',
|
||||
}
|
||||
|
||||
interface FileOperationOptions {
|
||||
fm: FileManagerBase
|
||||
file: FileInfo
|
||||
redundancyLevel: RedundancyLevel
|
||||
driveId: string
|
||||
stamp: PostageBatch
|
||||
adminStamp?: PostageBatch
|
||||
adminRedundancy?: RedundancyLevel
|
||||
operation: FileOperation
|
||||
onError?: (error: string) => void
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
export async function performFileOperation({
|
||||
fm,
|
||||
file,
|
||||
redundancyLevel,
|
||||
driveId,
|
||||
stamp,
|
||||
adminStamp,
|
||||
adminRedundancy,
|
||||
operation,
|
||||
onError,
|
||||
onSuccess,
|
||||
}: FileOperationOptions): Promise<boolean> {
|
||||
try {
|
||||
const isForget = operation === FileOperation.Forget
|
||||
const verifyStamp = isForget ? adminStamp || stamp : stamp
|
||||
|
||||
const { ok } = verifyDriveSpace({
|
||||
fm,
|
||||
redundancyLevel,
|
||||
stamp: verifyStamp,
|
||||
useInfoSize: !isForget,
|
||||
adminRedundancy: isForget ? adminRedundancy : undefined,
|
||||
driveId,
|
||||
fileSize: 0,
|
||||
cb: err => {
|
||||
onError?.(err || `Could not ${operation} file due to insufficient space: ${file.name}`)
|
||||
},
|
||||
})
|
||||
|
||||
if (!ok) return false
|
||||
|
||||
const lifecycleTag = operation === FileOperation.Trash ? ActionTag.Trashed : ActionTag.Recovered
|
||||
const withMeta: FileInfo = {
|
||||
...file,
|
||||
customMetadata: {
|
||||
...(file.customMetadata ?? {}),
|
||||
lifecycle: capitalizeFirstLetter(lifecycleTag),
|
||||
lifecycleAt: new Date().toISOString(),
|
||||
},
|
||||
}
|
||||
|
||||
switch (operation) {
|
||||
case FileOperation.Trash:
|
||||
await fm.trashFile(withMeta)
|
||||
break
|
||||
case FileOperation.Recover:
|
||||
await fm.recoverFile(withMeta)
|
||||
break
|
||||
case FileOperation.Forget:
|
||||
await fm.forgetFile(file)
|
||||
break
|
||||
default:
|
||||
throw new Error(`Unknown operation: ${operation}`)
|
||||
}
|
||||
|
||||
onSuccess?.()
|
||||
|
||||
return true
|
||||
} catch (error) {
|
||||
onError?.(error instanceof Error ? error.message : `Failed to ${operation} file: ${file.name}`)
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export async function performBulkFileOperation({
|
||||
fm,
|
||||
files,
|
||||
operation,
|
||||
stamps,
|
||||
adminStamp,
|
||||
adminDrive,
|
||||
onError,
|
||||
onFileComplete,
|
||||
}: {
|
||||
fm: FileManagerBase
|
||||
files: FileInfo[]
|
||||
operation: FileOperation
|
||||
stamps: PostageBatch[]
|
||||
adminStamp?: PostageBatch
|
||||
adminDrive?: DriveInfo
|
||||
onError?: (error: string) => void
|
||||
onFileComplete?: (file: FileInfo, index: number) => void
|
||||
}): Promise<void> {
|
||||
if (!fm || !files?.length) return
|
||||
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const file = files[i]
|
||||
const defaultErrorMsg = `Could not ${operation} file due to insufficient space: ${file.name}`
|
||||
|
||||
try {
|
||||
const currentStamp = stamps.find(s => s.batchID.toString() === file.batchId.toString())
|
||||
|
||||
if (!currentStamp && operation !== FileOperation.Forget) {
|
||||
onError?.(`Stamp not found for file: ${file.name}`)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (!currentStamp) return
|
||||
|
||||
const success = await performFileOperation({
|
||||
fm,
|
||||
file,
|
||||
redundancyLevel: file.redundancyLevel || 0,
|
||||
driveId: file.driveId,
|
||||
stamp: currentStamp,
|
||||
adminStamp,
|
||||
operation,
|
||||
adminRedundancy: adminDrive?.redundancyLevel,
|
||||
onError,
|
||||
})
|
||||
|
||||
if (!success) {
|
||||
throw new Error(defaultErrorMsg)
|
||||
}
|
||||
|
||||
onFileComplete?.(file, i)
|
||||
} catch (err) {
|
||||
const errorMsg = err instanceof Error ? err.message : String(err)
|
||||
onError?.(errorMsg || defaultErrorMsg)
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import GeneralIcon from 'remixicon-react/FileTextLineIcon'
|
||||
import CalendarIcon from 'remixicon-react/CalendarLineIcon'
|
||||
import AccessIcon from 'remixicon-react/ShieldKeyholeLineIcon'
|
||||
import HardDriveIcon from 'remixicon-react/HardDrive2LineIcon'
|
||||
import { indexStrToBigint } from './common'
|
||||
import { indexStrToBigint, truncateNameMiddle } from './common'
|
||||
import { FEED_INDEX_ZERO, erasureCodeMarks } from '../constants/common'
|
||||
|
||||
export type FileProperty = { key: string; label: string; value: string; raw?: string }
|
||||
@@ -100,7 +100,7 @@ function buildGeneralGroup(
|
||||
{ key: 'type', label: 'Type', value: mime ?? dash },
|
||||
{ key: 'size', label: 'Size', value: size != null ? formatBytes(size) : dash },
|
||||
{ key: 'count', label: 'Items', value: fileCount ?? '1' },
|
||||
{ key: 'path', label: 'Location', value: path || dash },
|
||||
{ key: 'path', label: 'Location', value: truncateNameMiddle(path || dash, 35, 10, 10) },
|
||||
{
|
||||
key: 'hash',
|
||||
label: 'Swarm hash',
|
||||
@@ -162,7 +162,7 @@ function buildAccessGroup(fi: FileInfo, granteeCount?: number): FilePropertyGrou
|
||||
|
||||
function buildStorageGroup(fi: FileInfo, driveName: string, stamp?: PostageBatch): FilePropertyGroup {
|
||||
const stampValue = stamp
|
||||
? stamp.label + ' (' + truncateMiddle(fi.batchId.toString(), 4, 4) + ')'
|
||||
? truncateNameMiddle(stamp.label, 35, 10, 10) + ' (' + truncateMiddle(fi.batchId.toString(), 4, 4) + ')'
|
||||
: truncateMiddle(fi.batchId.toString())
|
||||
|
||||
const redundancyLabel =
|
||||
@@ -180,7 +180,7 @@ function buildStorageGroup(fi: FileInfo, driveName: string, stamp?: PostageBatch
|
||||
value: stampValue,
|
||||
raw: fi.batchId.toString(),
|
||||
},
|
||||
{ key: 'drive', label: 'Drive', value: driveName },
|
||||
{ key: 'drive', label: 'Drive', value: truncateNameMiddle(driveName, 35, 10, 10) },
|
||||
{ key: 'redundancy', label: 'Redundancy', value: redundancyLabel },
|
||||
],
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ export function computeContextMenuPosition(args: {
|
||||
|
||||
const spaceBelow = vh - pos.y
|
||||
|
||||
if (spaceBelow < rect.height * 1.4) {
|
||||
if (spaceBelow < rect.height * 1.8) {
|
||||
top = Math.max(margin, pos.y - rect.height - margin)
|
||||
dir = Dir.Up
|
||||
} else {
|
||||
|
||||
@@ -24,17 +24,21 @@ const EXT_TO_MIME: Record<string, string> = {
|
||||
}
|
||||
|
||||
export function getExtensionFromName(name: string): string {
|
||||
return name.split('.').pop()?.toLowerCase() || ''
|
||||
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): string {
|
||||
export function guessMime(name: string, mtdt?: Record<string, string> | undefined): { mime: string; ext: string } {
|
||||
const md = mtdt?.mimeType || mtdt?.mime || mtdt?.['content-type']
|
||||
|
||||
if (md) return md
|
||||
|
||||
const ext = getExtensionFromName(name)
|
||||
|
||||
return EXT_TO_MIME[ext] || 'application/octet-stream'
|
||||
if (md) return { mime: md, ext }
|
||||
|
||||
const mime = EXT_TO_MIME[ext] || 'application/octet-stream'
|
||||
|
||||
return { mime, ext }
|
||||
}
|
||||
|
||||
export type Viewer = {
|
||||
|
||||
@@ -8,7 +8,6 @@ import Link from 'remixicon-react/LinkIcon'
|
||||
import ExpandableListItem from '../../../components/ExpandableListItem'
|
||||
import ExpandableListItemActions from '../../../components/ExpandableListItemActions'
|
||||
import ExpandableListItemKey from '../../../components/ExpandableListItemKey'
|
||||
import { Loading } from '../../../components/Loading'
|
||||
import { SwarmButton } from '../../../components/SwarmButton'
|
||||
import TroubleshootConnectionCard from '../../../components/TroubleshootConnectionCard'
|
||||
import { Context as BeeContext, CheckState } from '../../../providers/Bee'
|
||||
@@ -16,6 +15,7 @@ import { Context as SettingsContext } from '../../../providers/Settings'
|
||||
import { ROUTES } from '../../../routes'
|
||||
import { AccountNavigation } from '../AccountNavigation'
|
||||
import { Header } from '../Header'
|
||||
import { WalletInfoCard } from '../../../pages/info/WalletInfoCard'
|
||||
|
||||
export function AccountWallet(): ReactElement {
|
||||
const { nodeAddresses, nodeInfo, status, walletBalance } = useContext(BeeContext)
|
||||
@@ -44,7 +44,7 @@ export function AccountWallet(): ReactElement {
|
||||
<Box mb={4}>
|
||||
<Grid container direction="row" justifyContent="space-between" alignItems="center">
|
||||
<Typography variant="h2">Wallet balance</Typography>
|
||||
{isDesktop && (
|
||||
{isDesktop && walletBalance && (
|
||||
<SwarmButton onClick={onDeposit} iconType={Download}>
|
||||
Top up wallet
|
||||
</SwarmButton>
|
||||
@@ -70,8 +70,10 @@ export function AccountWallet(): ReactElement {
|
||||
</Box>
|
||||
</>
|
||||
) : (
|
||||
<Box mb={8}>
|
||||
<Loading />
|
||||
<Box mb={8} alignItems="center" display="flex" justifyContent="center">
|
||||
<Box maxWidth={400}>
|
||||
<WalletInfoCard />
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
<ExpandableListItemActions>
|
||||
|
||||
@@ -48,7 +48,7 @@ export default function CreateNewFeed(): ReactElement {
|
||||
return
|
||||
}
|
||||
const wallet = generateWallet()
|
||||
const stamps = await beeApi.getAllPostageBatch()
|
||||
const stamps = await beeApi.getPostageBatches()
|
||||
|
||||
if (!stamps || !stamps.length) {
|
||||
enqueueSnackbar(<span>No stamp available</span>, { variant: 'error' })
|
||||
|
||||
@@ -27,6 +27,8 @@ export function FeedSubpage(): ReactElement {
|
||||
|
||||
useEffect(() => {
|
||||
if (!identity || !identity.feedHash) {
|
||||
navigate(ROUTES.ACCOUNT_FEEDS, { replace: true })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -35,11 +37,9 @@ export function FeedSubpage(): ReactElement {
|
||||
} catch {
|
||||
setAvailable(false)
|
||||
}
|
||||
}, [beeApi, uuid, identity])
|
||||
}, [beeApi, uuid, identity, navigate])
|
||||
|
||||
if (!identity || !status.all) {
|
||||
navigate(ROUTES.ACCOUNT_FEEDS, { replace: true })
|
||||
|
||||
return <></>
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import { AdminStatusBar } from '../../modules/filemanager/components/AdminStatus
|
||||
import { FileBrowser } from '../../modules/filemanager/components/FileBrowser/FileBrowser'
|
||||
import { InitialModal } from '../../modules/filemanager/components/InitialModal/InitialModal'
|
||||
import { Context as FMContext } from '../../providers/FileManager'
|
||||
import { Context as SettingsContext } from '../../providers/Settings'
|
||||
import { Context as BeeContext, CheckState } from '../../providers/Bee'
|
||||
import { PrivateKeyModal } from '../../modules/filemanager/components/PrivateKeyModal/PrivateKeyModal'
|
||||
import { getSignerPk, removeSignerPk } from '../../../src/modules/filemanager/utils/common'
|
||||
@@ -26,8 +27,10 @@ export function FileManagerPage(): ReactElement {
|
||||
const [errorMessage, setErrorMessage] = useState<string>('')
|
||||
const [showResetModal, setShowResetModal] = useState<boolean>(false)
|
||||
const [isCreationInProgress, setIsCreationInProgress] = useState<boolean>(false)
|
||||
const [showConnectionError, setShowConnectionError] = useState<boolean>(false)
|
||||
|
||||
const { status } = useContext(BeeContext)
|
||||
const { beeApi } = useContext(SettingsContext)
|
||||
const { fm, shallReset, adminDrive, initializationError, init } = useContext(FMContext)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -39,6 +42,18 @@ export function FileManagerPage(): ReactElement {
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (status.all !== CheckState.OK) {
|
||||
setShowConnectionError(true)
|
||||
} else {
|
||||
setShowConnectionError(false)
|
||||
}
|
||||
}, [status.all])
|
||||
|
||||
useEffect(() => {
|
||||
if (!beeApi) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!hasPk) {
|
||||
setIsLoading(false)
|
||||
|
||||
@@ -71,7 +86,7 @@ export function FileManagerPage(): ReactElement {
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
}, [fm, hasPk, initializationError, adminDrive, shallReset])
|
||||
}, [fm, beeApi, hasPk, initializationError, adminDrive, shallReset])
|
||||
|
||||
const handlePrivateKeySaved = useCallback(async () => {
|
||||
if (!isMountedRef.current) return
|
||||
@@ -111,16 +126,6 @@ export function FileManagerPage(): ReactElement {
|
||||
|
||||
const isFormbricksActive = Boolean(fm && fm.adminStamp && adminDrive && !showInitialModal && !loading)
|
||||
|
||||
if (status.all !== CheckState.OK) {
|
||||
return (
|
||||
<div className="fm-main">
|
||||
<div className="fm-loading">
|
||||
<div className="fm-loading-title">Bee node error - cannot load File Manager</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!hasPk) {
|
||||
return (
|
||||
<div className="fm-main">
|
||||
@@ -174,7 +179,13 @@ export function FileManagerPage(): ReactElement {
|
||||
<InitialModal
|
||||
resetState={shallReset}
|
||||
handleVisibility={(isVisible: boolean) => setShowInitialModal(isVisible)}
|
||||
handleShowError={(flag: boolean) => setShowErrorModal(flag)}
|
||||
handleShowError={(flag: boolean, error?: string) => {
|
||||
setShowErrorModal(flag)
|
||||
|
||||
if (error) {
|
||||
setErrorMessage(error)
|
||||
}
|
||||
}}
|
||||
setIsCreationInProgress={(isCreating: boolean) => setIsCreationInProgress(isCreating)}
|
||||
/>
|
||||
</div>
|
||||
@@ -196,10 +207,13 @@ export function FileManagerPage(): ReactElement {
|
||||
if (showErrorModal) {
|
||||
return (
|
||||
<ErrorModal
|
||||
label={'Error during admin state creation, try again'}
|
||||
label={
|
||||
'Error creating Admin Drive. Please try again. Possible causes include insufficient xDAI balance or a lost connection to the RPC.'
|
||||
}
|
||||
onClick={() => {
|
||||
setShowErrorModal(false)
|
||||
setShowInitialModal(true)
|
||||
setErrorMessage('')
|
||||
}}
|
||||
/>
|
||||
)
|
||||
@@ -209,6 +223,12 @@ export function FileManagerPage(): ReactElement {
|
||||
<SearchProvider>
|
||||
<ViewProvider>
|
||||
<div className="fm-main">
|
||||
{showConnectionError && fm && (
|
||||
<ErrorModal
|
||||
label="Bee node connection error. Please check your node status. File Manager will continue when connection is restored."
|
||||
onClick={() => setShowConnectionError(false)}
|
||||
/>
|
||||
)}
|
||||
<FormbricksIntegration isActive={isFormbricksActive} />
|
||||
<Header />
|
||||
<div className="fm-main-content">
|
||||
|
||||
@@ -9,6 +9,7 @@ import { getHumanReadableFileSize } from '../../utils/file'
|
||||
import { shortenHash } from '../../utils/hash'
|
||||
import { AssetIcon } from './AssetIcon'
|
||||
import { FitVideo } from '../../components/FitVideo'
|
||||
import { FitAudio } from '../../components/FitAudio'
|
||||
|
||||
interface Props {
|
||||
previewUri?: string
|
||||
@@ -21,6 +22,10 @@ const getPreviewComponent = (previewUri?: string, metadata?: Metadata) => {
|
||||
return () => <FitVideo src={previewUri} maxWidth="250px" maxHeight="175px" />
|
||||
}
|
||||
|
||||
if (metadata?.isAudio) {
|
||||
return () => <FitAudio src={previewUri} maxWidth="250px" />
|
||||
}
|
||||
|
||||
if (metadata?.isImage) {
|
||||
return () => <FitImage maxWidth="250px" maxHeight="175px" alt="Upload Preview" src={previewUri} />
|
||||
}
|
||||
|
||||
@@ -83,7 +83,8 @@ export function AssetSyncing({ reference }: Props): ReactElement {
|
||||
<DocumentationText>
|
||||
Files are not immediately accessible on the Swarm network. Please wait until your upload is synced to the
|
||||
network.{' '}
|
||||
<a href="https://docs.ethswarm.org/docs/develop/access-the-swarm/syncing">Learn more about syncing</a>.
|
||||
{/* TODO: syncing article was removed, now the only available doc. is at https://docs.ethswarm.org/api/#tag/Tag */}
|
||||
{/* <a href="https://docs.ethswarm.org/docs/develop/access-the-swarm/syncing">Learn more about syncing</a>. */}
|
||||
</DocumentationText>
|
||||
</Box>
|
||||
<Box mb={4}>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Box, Typography } from '@material-ui/core'
|
||||
import { MantarayNode, NULL_ADDRESS } from '@ethersphere/bee-js'
|
||||
import { Bytes, MantarayNode, NULL_ADDRESS } from '@ethersphere/bee-js'
|
||||
import { saveAs } from 'file-saver'
|
||||
import JSZip from 'jszip'
|
||||
import { useSnackbar } from 'notistack'
|
||||
import { ReactElement, useContext, useEffect, useState } from 'react'
|
||||
import { ReactElement, useContext, useEffect, useRef, useState } from 'react'
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
import { HistoryHeader } from '../../components/HistoryHeader'
|
||||
import { Loading } from '../../components/Loading'
|
||||
@@ -36,6 +36,8 @@ export function Share(): ReactElement {
|
||||
const [preview, setPreview] = useState<string | undefined>(undefined)
|
||||
const [metadata, setMetadata] = useState<Metadata | undefined>()
|
||||
|
||||
const isMountedRef = useRef(true)
|
||||
|
||||
async function prepare() {
|
||||
if (!beeApi || !status.all) {
|
||||
return
|
||||
@@ -56,37 +58,53 @@ export function Share(): ReactElement {
|
||||
|
||||
const entries = manifest.collectAndMap()
|
||||
delete entries[META_FILE_NAME]
|
||||
|
||||
if (!isMountedRef.current) return
|
||||
|
||||
setSwarmEntries(entries)
|
||||
|
||||
const docsMetadata = manifest.getDocsMetadata()
|
||||
|
||||
// needed in catch block, shadows the outer variable
|
||||
const indexDocument = docsMetadata.indexDocument
|
||||
|
||||
if (!isMountedRef.current) return
|
||||
|
||||
setIndexDocument(indexDocument)
|
||||
|
||||
try {
|
||||
const remoteMetadata = await beeApi.downloadFile(reference, META_FILE_NAME)
|
||||
const formattedMetadata = remoteMetadata.data.toJSON() as Metadata
|
||||
|
||||
if (formattedMetadata.isVideo || formattedMetadata.isImage) {
|
||||
if (formattedMetadata.isVideo || formattedMetadata.isAudio || formattedMetadata.isImage) {
|
||||
if (!isMountedRef.current) return
|
||||
setPreview(`${apiUrl}/bzz/${reference}`)
|
||||
}
|
||||
|
||||
if (!isMountedRef.current) return
|
||||
|
||||
setMetadata({ ...formattedMetadata, hash })
|
||||
} catch (e) {
|
||||
// if metadata is not available or invalid go with the default one
|
||||
const count = Object.keys(entries).length
|
||||
|
||||
if (!isMountedRef.current) return
|
||||
|
||||
setMetadata({
|
||||
hash,
|
||||
type: count > 1 ? 'folder' : 'unknown',
|
||||
name: reference,
|
||||
count,
|
||||
isWebsite: Boolean(indexDocument && /.*\.html?$/i.test(indexDocument)),
|
||||
isVideo: Boolean(indexDocument && /.*\.(mp4|webm|ogg|mp3|ogg|wav)$/i.test(indexDocument)),
|
||||
isVideo: Boolean(indexDocument && /.*\.(mp4|webm|ogv)$/i.test(indexDocument)),
|
||||
isAudio: Boolean(indexDocument && /.*\.(mp3|ogg|oga|wav|webm|m4a|aac|flac)$/i.test(indexDocument)),
|
||||
isImage: Boolean(indexDocument && /.*\.(jpg|jpeg|png|gif|webp|svg)$/i.test(indexDocument)),
|
||||
// naive assumption based on indexDocument, we don't want to download the whole manifest
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
if (!isMountedRef.current) return
|
||||
|
||||
setNotFound(true)
|
||||
enqueueSnackbar('The specified hash does not contain valid content.', { variant: 'error' })
|
||||
|
||||
@@ -112,9 +130,16 @@ export function Share(): ReactElement {
|
||||
navigate(ROUTES.ACCOUNT_FEEDS_UPDATE.replace(':hash', reference))
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
isMountedRef.current = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true)
|
||||
prepare().finally(() => {
|
||||
if (!isMountedRef.current) return
|
||||
setLoading(false)
|
||||
})
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
@@ -124,19 +149,58 @@ export function Share(): ReactElement {
|
||||
if (!beeApi) {
|
||||
return
|
||||
}
|
||||
|
||||
putHistory(HISTORY_KEYS.DOWNLOAD_HISTORY, reference, determineHistoryName(reference, indexDocument))
|
||||
setDownloading(true)
|
||||
|
||||
if (Object.keys(swarmEntries).length === 1) {
|
||||
window.open(`${apiUrl}/bzz/${reference}/`, '_blank')
|
||||
const singleFileName = Object.keys(swarmEntries)[0]
|
||||
const singleFileHash = Object.values(swarmEntries)[0]
|
||||
|
||||
let fileData: Bytes
|
||||
try {
|
||||
fileData = await beeApi.downloadData(singleFileHash)
|
||||
} catch (err) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('Failed to download file: ', err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const dataArray = fileData.toUint8Array()
|
||||
const arrayBuffer = new ArrayBuffer(dataArray.length)
|
||||
const view = new Uint8Array(arrayBuffer)
|
||||
view.set(dataArray)
|
||||
const blob = new Blob([arrayBuffer], { type: metadata?.type || 'application/octet-stream' })
|
||||
saveAs(blob, metadata?.name || singleFileName || reference)
|
||||
} else {
|
||||
const zip = new JSZip()
|
||||
for (const [path, hash] of Object.entries(swarmEntries)) {
|
||||
zip.file(path, (await beeApi.downloadData(hash)).toUint8Array())
|
||||
try {
|
||||
zip.file(path, (await beeApi.downloadData(hash)).toUint8Array())
|
||||
} catch (err) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('Failed to download files: ', err)
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
const content = await zip.generateAsync({ type: 'blob' })
|
||||
|
||||
let content: Blob
|
||||
try {
|
||||
content = await zip.generateAsync({ type: 'blob' })
|
||||
} catch (err) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('Failed to compress file: ', err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
saveAs(content, reference + '.zip')
|
||||
}
|
||||
|
||||
if (!isMountedRef.current) return
|
||||
|
||||
setDownloading(false)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,8 +9,10 @@ import { useNavigate } from 'react-router-dom'
|
||||
import { DocumentationText } from '../../components/DocumentationText'
|
||||
import { SwarmButton } from '../../components/SwarmButton'
|
||||
import { Context, UploadOrigin } from '../../providers/File'
|
||||
import { Context as BeeContext } from '../../providers/Bee'
|
||||
import { ROUTES } from '../../routes'
|
||||
import { detectIndexHtml } from '../../utils/file'
|
||||
import { BeeModes } from '@ethersphere/bee-js'
|
||||
|
||||
interface Props {
|
||||
uploadOrigin: UploadOrigin
|
||||
@@ -51,6 +53,7 @@ const useStyles = makeStyles((theme: Theme) =>
|
||||
|
||||
export function UploadArea({ uploadOrigin, showHelp }: Props): ReactElement {
|
||||
const { setFiles, setUploadOrigin } = useContext(Context)
|
||||
const { nodeInfo } = useContext(BeeContext)
|
||||
const classes = useStyles()
|
||||
const navigate = useNavigate()
|
||||
const { enqueueSnackbar } = useSnackbar()
|
||||
@@ -121,35 +124,52 @@ export function UploadArea({ uploadOrigin, showHelp }: Props): ReactElement {
|
||||
}
|
||||
}
|
||||
|
||||
const isUploadEnabled = nodeInfo?.beeMode !== BeeModes.ULTRA_LIGHT
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={classes.areaWrapper}>
|
||||
<DropzoneArea
|
||||
key={version}
|
||||
dropzoneClass={classes.dropzone}
|
||||
onChange={handleChange}
|
||||
filesLimit={1e9}
|
||||
maxFileSize={MAX_FILE_SIZE}
|
||||
showPreviews={false}
|
||||
/>
|
||||
<div className={classes.buttonWrapper}>
|
||||
<SwarmButton className={classes.button} onClick={onUploadFileClick} iconType={FilePlus}>
|
||||
Add File
|
||||
</SwarmButton>
|
||||
<SwarmButton className={classes.button} onClick={onUploadFolderClick} iconType={FolderPlus}>
|
||||
Add Folder
|
||||
</SwarmButton>
|
||||
<SwarmButton className={classes.button} onClick={onUploadWebsiteClick} iconType={PlusCircle}>
|
||||
Add Website
|
||||
</SwarmButton>
|
||||
{isUploadEnabled && (
|
||||
<div className={classes.areaWrapper}>
|
||||
<DropzoneArea
|
||||
key={version}
|
||||
dropzoneClass={classes.dropzone}
|
||||
onChange={handleChange}
|
||||
filesLimit={1e9}
|
||||
maxFileSize={MAX_FILE_SIZE}
|
||||
showPreviews={false}
|
||||
/>
|
||||
<div className={classes.buttonWrapper}>
|
||||
<SwarmButton className={classes.button} onClick={onUploadFileClick} iconType={FilePlus}>
|
||||
Add File
|
||||
</SwarmButton>
|
||||
<SwarmButton className={classes.button} onClick={onUploadFolderClick} iconType={FolderPlus}>
|
||||
Add Folder
|
||||
</SwarmButton>
|
||||
<SwarmButton className={classes.button} onClick={onUploadWebsiteClick} iconType={PlusCircle}>
|
||||
Add Website
|
||||
</SwarmButton>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{showHelp && (
|
||||
)}
|
||||
{isUploadEnabled && showHelp && (
|
||||
<DocumentationText>
|
||||
You can click the buttons above or simply drag and drop to add a file or folder. To upload a website to Swarm,
|
||||
make sure that your folder contains an “index.html” file.
|
||||
</DocumentationText>
|
||||
)}
|
||||
{!isUploadEnabled && (
|
||||
<DocumentationText>
|
||||
Uploading files requires running a light node. Please{' '}
|
||||
<a
|
||||
href="https://docs.ethswarm.org/docs/desktop/configuration/#upgrading-from-an-ultra-light-to-a-light-node"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
upgrade
|
||||
</a>{' '}
|
||||
to continue.
|
||||
</DocumentationText>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { ReactElement } from 'react'
|
||||
import { HistoryHeader } from '../../components/HistoryHeader'
|
||||
import { Typography } from '@material-ui/core'
|
||||
|
||||
export default function PageNotFound(): ReactElement {
|
||||
return (
|
||||
<div>
|
||||
<HistoryHeader>Page not found</HistoryHeader>
|
||||
<Typography>
|
||||
The given url is invalid. Please go back or <a href="/">navigate to Home screen.</a>
|
||||
</Typography>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -59,6 +59,13 @@ export function Provider({ children }: Props): ReactElement {
|
||||
setPreviewBlob(videoBlob)
|
||||
}
|
||||
|
||||
if (metadata.isAudio) {
|
||||
const audioFile = files[0]
|
||||
const audioBlob = new Blob([audioFile], { type: audioFile.type })
|
||||
setPreviewUri(URL.createObjectURL(audioBlob))
|
||||
setPreviewBlob(audioBlob)
|
||||
}
|
||||
|
||||
if (metadata.isImage) {
|
||||
resize(files[0], PREVIEW_DIMENSIONS.maxWidth, PREVIEW_DIMENSIONS.maxHeight).then(blob => {
|
||||
setPreviewUri(URL.createObjectURL(blob)) // NOTE: Until it is cleared with URL.revokeObjectURL, the file stays allocated in memory
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Context as SettingsContext } from './Settings'
|
||||
import { DriveInfo } from '@solarpunkltd/file-manager-lib'
|
||||
import { getSignerPk } from '../modules/filemanager/utils/common'
|
||||
import { getUsableStamps } from '../../src/modules/filemanager/utils/bee'
|
||||
import { FILE_MANAGER_EVENTS } from '../modules/filemanager/constants/common'
|
||||
|
||||
interface ContextInterface {
|
||||
fm: FileManagerBase | null
|
||||
@@ -178,7 +179,7 @@ export function Provider({ children }: Props) {
|
||||
return
|
||||
}
|
||||
|
||||
const { adminDrive: tmpAdminDrive, userDrives, expiredDrives } = findDrives(manager.getDrives(), usableStamps)
|
||||
const { adminDrive: tmpAdminDrive, userDrives, expiredDrives } = findDrives(manager.driveList, usableStamps)
|
||||
setAdminDrive(tmpAdminDrive)
|
||||
setDrives(userDrives)
|
||||
setExpiredDrives(expiredDrives)
|
||||
@@ -192,19 +193,17 @@ export function Provider({ children }: Props) {
|
||||
}
|
||||
}, [fm, syncDrives])
|
||||
|
||||
const refreshStamp = useCallback(
|
||||
async (batchId: string): Promise<PostageBatch | undefined> => {
|
||||
const usableStamps = await getUsableStamps(beeApi)
|
||||
const refreshedStamp = usableStamps.find(s => s.batchID.toString() === batchId)
|
||||
// no useCallback is needed because it caches the stamp
|
||||
const refreshStamp = async (batchId: string): Promise<PostageBatch | undefined> => {
|
||||
const usableStamps = await getUsableStamps(beeApi)
|
||||
const refreshedStamp = usableStamps.find(s => s.batchID.toString() === batchId)
|
||||
|
||||
if (currentStamp && currentStamp.batchID.toString() === batchId && refreshedStamp) {
|
||||
setCurrentStamp(refreshedStamp)
|
||||
}
|
||||
if (currentStamp && currentStamp.batchID.toString() === batchId && refreshedStamp) {
|
||||
setCurrentStamp(refreshedStamp)
|
||||
}
|
||||
|
||||
return refreshedStamp
|
||||
},
|
||||
[beeApi, currentStamp],
|
||||
)
|
||||
return refreshedStamp
|
||||
}
|
||||
|
||||
const init = useCallback(async (): Promise<FileManagerBase | null> => {
|
||||
const pk = getSignerPk()
|
||||
@@ -226,6 +225,15 @@ export function Provider({ children }: Props) {
|
||||
setInitializationError(!success)
|
||||
|
||||
if (success) {
|
||||
if (manager.adminStamp && !manager.adminStamp.usable) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn('Admin stamp exists but is not usable')
|
||||
setShallReset(true)
|
||||
setInitializationError(true)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
setFm(manager)
|
||||
syncDrives(manager)
|
||||
syncFiles(manager)
|
||||
@@ -255,9 +263,10 @@ export function Provider({ children }: Props) {
|
||||
manager.emitter.on(FileManagerEvents.DRIVE_CREATED, handleDriveCreated)
|
||||
manager.emitter.on(FileManagerEvents.DRIVE_DESTROYED, handleDriveDestroyed)
|
||||
manager.emitter.on(FileManagerEvents.DRIVE_FORGOTTEN, handleDriveForgotten)
|
||||
manager.emitter.on(FileManagerEvents.FILE_UPLOADED, ({ fileInfo }: { fileInfo: FileInfo }) =>
|
||||
syncFiles(manager, fileInfo),
|
||||
)
|
||||
manager.emitter.on(FileManagerEvents.FILE_UPLOADED, ({ fileInfo }: { fileInfo: FileInfo }) => {
|
||||
syncFiles(manager, fileInfo)
|
||||
window.dispatchEvent(new CustomEvent(FILE_MANAGER_EVENTS.FILE_UPLOADED, { detail: { fileInfo } }))
|
||||
})
|
||||
manager.emitter.on(FileManagerEvents.FILE_VERSION_RESTORED, ({ restored }: { restored: FileInfo }) =>
|
||||
syncFiles(manager, restored),
|
||||
)
|
||||
@@ -287,7 +296,7 @@ export function Provider({ children }: Props) {
|
||||
const manager = await init()
|
||||
|
||||
if (prevDriveId && manager) {
|
||||
const refreshedDrive = manager.getDrives().find(d => d.id.toString() === prevDriveId)
|
||||
const refreshedDrive = manager.driveList.find(d => d.id.toString() === prevDriveId)
|
||||
setCurrentDrive(refreshedDrive)
|
||||
|
||||
const isValidCurrentStamp = (await getUsableStamps(beeApi)).find(
|
||||
|
||||
@@ -66,7 +66,7 @@ export function Provider({ children, ...propsSettings }: Props): ReactElement {
|
||||
localStorage.getItem(LocalStorageKeys.providerUrl) || propsSettings.defaultRpcUrl || DEFAULT_RPC_URL
|
||||
|
||||
const [apiUrl, setApiUrl] = useState<string>(
|
||||
sessionStorage.getItem('api_host') ?? propsSettings.beeApiUrl ?? initialValues.apiUrl,
|
||||
localStorage.getItem('api_host') ?? propsSettings.beeApiUrl ?? initialValues.apiUrl,
|
||||
)
|
||||
const [beeApi, setBeeApi] = useState<Bee | null>(null)
|
||||
const [desktopApiKey, setDesktopApiKey] = useState<string>(initialValues.desktopApiKey)
|
||||
@@ -86,21 +86,32 @@ export function Provider({ children, ...propsSettings }: Props): ReactElement {
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const url = makeHttpUrl(config?.['api-addr'] ?? apiUrl)
|
||||
const url = makeHttpUrl(localStorage.getItem('api_host') ?? config?.['api-addr'] ?? apiUrl)
|
||||
try {
|
||||
setBeeApi(new Bee(url))
|
||||
sessionStorage.setItem('api_host', url)
|
||||
} catch (e) {
|
||||
setBeeApi(null)
|
||||
}
|
||||
}, [config, apiUrl])
|
||||
|
||||
const updateApiUrl = (url: string) => {
|
||||
const userProvidedUrl = makeHttpUrl(url)
|
||||
|
||||
try {
|
||||
setBeeApi(new Bee(userProvidedUrl))
|
||||
localStorage.setItem('api_host', userProvidedUrl)
|
||||
setApiUrl(userProvidedUrl)
|
||||
} catch (e) {
|
||||
setBeeApi(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Context.Provider
|
||||
value={{
|
||||
apiUrl,
|
||||
beeApi,
|
||||
setApiUrl,
|
||||
setApiUrl: updateApiUrl,
|
||||
lockedApiSettings: Boolean(propsSettings.lockedApiSettings),
|
||||
desktopApiKey,
|
||||
isDesktop,
|
||||
|
||||
Vendored
+1
@@ -15,6 +15,7 @@ interface Metadata extends SwarmMetadata {
|
||||
type: string
|
||||
isWebsite?: boolean
|
||||
isVideo?: boolean
|
||||
isAudio?: boolean
|
||||
isImage?: boolean
|
||||
count?: number
|
||||
hash?: string
|
||||
|
||||
+3
-1
@@ -28,6 +28,7 @@ import { GiftCardTopUpIndex } from './pages/top-up/GiftCardTopUpIndex'
|
||||
import { Swap } from './pages/top-up/Swap'
|
||||
import { Context as SettingsContext } from './providers/Settings'
|
||||
import { FileManagerPage } from './pages/filemanager'
|
||||
import PageNotFound from './pages/not-found/PageNotFound'
|
||||
|
||||
export enum ROUTES {
|
||||
INFO = '/',
|
||||
@@ -55,7 +56,7 @@ export enum ROUTES {
|
||||
ACCOUNT_FEEDS = '/account/feeds',
|
||||
ACCOUNT_FEEDS_NEW = '/account/feeds/new',
|
||||
ACCOUNT_FEEDS_UPDATE = '/account/feeds/update/:hash',
|
||||
ACCOUNT_FEEDS_VIEW = '/account/feeds/:uuid',
|
||||
ACCOUNT_FEEDS_VIEW = '/account/feeds/view/:uuid',
|
||||
ACCOUNT_INVITATIONS = '/account/invitations',
|
||||
ACCOUNT_STAKING = '/account/staking',
|
||||
FDP = '/fdp',
|
||||
@@ -102,6 +103,7 @@ const BaseRouter = (): ReactElement => {
|
||||
<Route path={ROUTES.ACCOUNT_STAKING} element={<AccountStaking />} />
|
||||
<Route path={ROUTES.FDP} element={<FDP />} />
|
||||
{isDesktop && <Route path={ROUTES.ACCOUNT_INVITATIONS} element={<GiftCards />} />}
|
||||
<Route path="*" element={<PageNotFound />} />
|
||||
</Routes>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
export function isSupportedAudioType(type: string) {
|
||||
const commonAudioTypes = [
|
||||
'audio/wav',
|
||||
'audio/wave',
|
||||
'audio/x-wav',
|
||||
'audio/mpeg',
|
||||
'audio/mp3',
|
||||
'audio/ogg',
|
||||
'audio/webm',
|
||||
'audio/aac',
|
||||
'audio/flac',
|
||||
'audio/m4a',
|
||||
'audio/x-m4a',
|
||||
]
|
||||
|
||||
if (commonAudioTypes.includes(type.toLowerCase())) {
|
||||
return true
|
||||
}
|
||||
|
||||
const audio = document.createElement('audio')
|
||||
const result = audio.canPlayType(type)
|
||||
|
||||
return Boolean(result)
|
||||
}
|
||||
+23
-11
@@ -1,5 +1,6 @@
|
||||
import { isSupportedImageType } from './image'
|
||||
import { isSupportedVideoType } from './video'
|
||||
import { isSupportedAudioType } from './audio'
|
||||
|
||||
const indexHtmls = ['index.html', 'index.htm']
|
||||
|
||||
@@ -15,6 +16,10 @@ export function detectIndexHtml(files: FilePath[]): DetectedIndex | false {
|
||||
return false
|
||||
}
|
||||
|
||||
if (files.length === 1) {
|
||||
return false
|
||||
}
|
||||
|
||||
const exactMatch = paths.find(x => indexHtmls.includes(x))
|
||||
|
||||
if (exactMatch) {
|
||||
@@ -48,24 +53,30 @@ export function detectIndexHtml(files: FilePath[]): DetectedIndex | false {
|
||||
}
|
||||
|
||||
export function getHumanReadableFileSize(bytes: number): string {
|
||||
if (bytes >= 1e15) {
|
||||
return (bytes / 1e15).toFixed(2) + ' PB'
|
||||
const KB = 1000
|
||||
const MB = KB * 1000
|
||||
const GB = MB * 1000
|
||||
const TB = GB * 1000
|
||||
const PB = TB * 1000
|
||||
|
||||
if (bytes >= PB) {
|
||||
return (bytes / PB).toFixed(2) + ' PB'
|
||||
}
|
||||
|
||||
if (bytes >= 1e12) {
|
||||
return (bytes / 1e12).toFixed(2) + ' TB'
|
||||
if (bytes >= TB) {
|
||||
return (bytes / TB).toFixed(2) + ' TB'
|
||||
}
|
||||
|
||||
if (bytes >= 1e9) {
|
||||
return (bytes / 1e9).toFixed(2) + ' GB'
|
||||
if (bytes >= GB) {
|
||||
return (bytes / GB).toFixed(2) + ' GB'
|
||||
}
|
||||
|
||||
if (bytes >= 1e6) {
|
||||
return (bytes / 1e6).toFixed(2) + ' MB'
|
||||
if (bytes >= MB) {
|
||||
return (bytes / MB).toFixed(2) + ' MB'
|
||||
}
|
||||
|
||||
if (bytes >= 1e3) {
|
||||
return (bytes / 1e3).toFixed(2) + ' kB'
|
||||
if (bytes >= KB) {
|
||||
return (bytes / KB).toFixed(2) + ' KB'
|
||||
}
|
||||
|
||||
return bytes + ' bytes'
|
||||
@@ -91,9 +102,10 @@ export function getMetadata(files: FilePath[]): Metadata {
|
||||
const count = files.length
|
||||
const isWebsite = Boolean(detectIndexHtml(files))
|
||||
const isVideo = isSupportedVideoType(type)
|
||||
const isAudio = isSupportedAudioType(type)
|
||||
const isImage = isSupportedImageType(type)
|
||||
|
||||
return { size, name, type, isWebsite, count, isVideo, isImage }
|
||||
return { size, name, type, isWebsite, count, isVideo, isAudio, isImage }
|
||||
}
|
||||
|
||||
export function getPath(file: FilePath): string {
|
||||
|
||||
+7
-3
@@ -1,8 +1,12 @@
|
||||
export function isSupportedVideoType(type: string) {
|
||||
const commonVideoTypes = ['video/mp4', 'video/webm', 'video/ogg', 'video/quicktime', 'video/x-msvideo', 'video/avi']
|
||||
|
||||
if (commonVideoTypes.includes(type.toLowerCase())) {
|
||||
return true
|
||||
}
|
||||
|
||||
const video = document.createElement('video')
|
||||
|
||||
const result = video.canPlayType(type)
|
||||
const isDefinitelySupported = result && result !== 'maybe'
|
||||
|
||||
return Boolean(isDefinitelySupported)
|
||||
return Boolean(result)
|
||||
}
|
||||
|
||||
+21
-5
@@ -1,22 +1,38 @@
|
||||
import { detectIndexHtml } from './file'
|
||||
|
||||
describe('file utils', () => {
|
||||
it('detectIndexHtml should find index.html', () => {
|
||||
it('detectIndexHtml should find index.html with multiple files', () => {
|
||||
expect(
|
||||
detectIndexHtml([
|
||||
{ name: 'swarm.png', path: 'swarm.png' },
|
||||
{ name: 'index.html', path: 'index.html' },
|
||||
]),
|
||||
).toBe('index.html')
|
||||
).toEqual({ indexPath: 'index.html' })
|
||||
})
|
||||
|
||||
it('detectIndexHtml should find index.htm', () => {
|
||||
it('detectIndexHtml should find index.htm with multiple files', () => {
|
||||
expect(
|
||||
detectIndexHtml([
|
||||
{ name: 'index.htm', path: 'index.htm' },
|
||||
{ name: 'swarm.png', path: 'swarm.png' },
|
||||
]),
|
||||
).toBe('index.htm')
|
||||
).toEqual({ indexPath: 'index.htm' })
|
||||
})
|
||||
|
||||
it('detectIndexHtml should NOT detect single index.html file as website', () => {
|
||||
expect(
|
||||
detectIndexHtml([
|
||||
{ name: 'index.html', path: 'index.html' },
|
||||
]),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('detectIndexHtml should NOT detect single index.htm file as website', () => {
|
||||
expect(
|
||||
detectIndexHtml([
|
||||
{ name: 'index.htm', path: 'index.htm' },
|
||||
]),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('detectIndexHtml should find nested index.html', () => {
|
||||
@@ -25,7 +41,7 @@ describe('file utils', () => {
|
||||
{ name: 'swarm.png', path: 'sample-folder/swarm.png' },
|
||||
{ name: 'index.html', path: 'sample-folder/index.html' },
|
||||
]),
|
||||
).toBe('index.html')
|
||||
).toEqual({ indexPath: 'sample-folder/index.html', commonPrefix: 'sample-folder/' })
|
||||
})
|
||||
|
||||
it('detectIndexHtml should not find nested index.htm when ambigous', () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"target": "es5",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 158 KiB |
Reference in New Issue
Block a user