[Substrate Files] New files module (#6106)

* Upgrade crust-pin to Crust Mainnet

* Update yarn lock

* Files Module (#6)

* Describe file's README

* Change Endpoint name and location

* Update file's README

* Add locales for files

* Files Module (#6)

* Describe file's README

* Change Endpoint name and location

* Update file's README

* Add locales for files

* Update yarn locks file

* Update Crust Pinner to bearer authorization (#7)

* Fix yarn lock

* Add folder support (#8)

* Add folder support

* Fix

* Fix files download

* Fix translation

* Upgrade react component

* Fix ipfs gateway (#9)

* Fix yarnlock

* Upgrade metadata

* Resolve polkadot-js version

* Change copyright

* Fix lint(copyright)

Co-authored-by: Eericxu <2681350846@qq.com>
Co-authored-by: Gavin Fu <gavfu@outlook.com>
Co-authored-by: Yashiro <51014425+yuhui1208@users.noreply.github.com>
This commit is contained in:
badkk 2022-02-17 15:25:00 +08:00 committed by GitHub
parent 7be8f22fc7
commit 0d0bb48a0c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 1326 additions and 2 deletions

View File

@ -7,3 +7,4 @@ export * from './extensions';
export * from './links';
export * from './settings';
export * from './ui';
export * from './ipfs-gateway-endpoints';

View File

@ -0,0 +1,32 @@
// Copyright 2017-2022 @polkadot/apps-config authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { TFunction } from 'i18next';
import type { AuthIpfsEndpoint } from './types';
// Definitions here are with the following values -
// info: the name of a logo as defined in ../ui/logos, specifically in namedLogos
// text: the IPFS endpoint name
// value: the IPFS endpoint domain
// location: IPFS gateway location
export function createAuthIpfsEndpoints (t: TFunction): AuthIpfsEndpoint[] {
return [
{
location: t('Singapore'),
text: t('DCF'),
value: 'https://crustipfs.xyz'
},
{
location: t('Seattle'),
text: t('Crust Network'),
value: 'https://crustwebsites.net'
},
{
location: t('Berlin'),
text: t('⚡️ Thunder Gateway'),
value: 'https://gw.crustapps.net'
}
];
}
export type { AuthIpfsEndpoint };

View File

@ -0,0 +1,8 @@
// Copyright 2017-2022 @polkadot/apps-config authors & contributors
// SPDX-License-Identifier: Apache-2.0
export interface AuthIpfsEndpoint {
text?: string;
value: string;
location?: string;
}

View File

@ -0,0 +1,20 @@
// Copyright 2017-2022 @polkadot/apps-routing authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { TFunction } from 'i18next';
import type { Route } from './types';
import Component from '@polkadot/app-files';
export default function create (t: TFunction): Route {
return {
Component,
display: {
needsApi: []
},
group: 'files',
icon: 'file',
name: 'files',
text: t('nav.files', 'Files', { ns: 'apps-routing' })
};
}

View File

@ -15,6 +15,7 @@ import council from './council';
import democracy from './democracy';
import explorer from './explorer';
import extrinsics from './extrinsics';
import files from './files';
import gilt from './gilt';
import js from './js';
import membership from './membership';
@ -60,6 +61,7 @@ export default function create (t: TFunction): Routes {
signing(t),
sudo(t),
js(t),
files(t),
settings(t)
];
}

View File

@ -4,7 +4,7 @@
import type { IconName } from '@fortawesome/fontawesome-svg-core';
import type { AppProps, BareProps } from '@polkadot/react-components/types';
export type RouteGroup = 'accounts' | 'developer' | 'governance' | 'network' | 'settings';
export type RouteGroup = 'accounts' | 'developer' | 'governance' | 'network' | 'files' | 'settings';
export interface RouteProps extends AppProps, BareProps {
location: any;

View File

@ -0,0 +1,40 @@
{
"Copy file cid": "Copy file cid",
"Copy link": "Copy link",
"Crust Pinner": "Crust Pinner",
"Do not upload files larger than 100MB!": "Do not upload files larger than 100MB!",
"Download": "Download",
"Export": "Export",
"File": "File",
"File streaming and wallet authentication will be processed by the chosen gateway.": "File streaming and wallet authentication will be processed by the chosen gateway.",
"Folder": "Folder",
"Import": "Import",
"Import Success": "Import Success",
"Import files": "Import files",
"Importing": "Importing",
"Loading": "Loading",
"Need to connect a plug-in wallet or import an account first": "Need to connect a plug-in wallet or import an account first",
"No files": "No files",
"Note: The file list is cached locally, switching browsers or devices will not keep displaying the original browser information.": "Note: The file list is cached locally, switching browsers or devices will not keep displaying the original browser information.",
"Please choose account": "Please choose account",
"Please do not upload more than 2000 files": "Please do not upload more than 2000 files",
"Please select non-empty folder": "Please select non-empty folder",
"Select a Web3 IPFS Gateway": "Select a Web3 IPFS Gateway",
"Select a Web3 IPFS Pinner": "Select a Web3 IPFS Pinner",
"Sign and Upload": "Sign and Upload",
"The account's password specified at the creation of this account.": "The account's password specified at the creation of this account.",
"Upload": "Upload",
"Upload File": "Upload File",
"View status in Crust": "View status in Crust",
"Your Files": "Your Files",
"Your file will be pinned to IPFS for long-term storage.": "Your file will be pinned to IPFS for long-term storage.",
"action": "action",
"file cid": "file cid",
"file content error": "file content error",
"file error": "file error",
"file size": "file size",
"files": "files",
"password": "password",
"status": "status",
"transferrable": "transferrable"
}

View File

@ -10,6 +10,7 @@
"nav.democracy": "Democracy",
"nav.explorer": "Explorer",
"nav.extrinsics": "Extrinsics",
"nav.files": "Files",
"nav.gilt": "Gilt",
"nav.js": "JavaScript",
"nav.membership": "Membership",

View File

@ -1,6 +1,7 @@
{
"Accounts": "Accounts",
"Developer": "Developer",
"Files": "Files",
"Governance": "Governance",
"Initializing connection": "Initializing connection",
"Network": "Network",

View File

@ -10,6 +10,7 @@
"app-democracy.json",
"app-explorer.json",
"app-extrinsics.json",
"app-files.json",
"app-gilt.json",
"app-js.json",
"app-parachains.json",

View File

@ -19,6 +19,7 @@
"Aye": "",
"Aye: {{count}}": "",
"Backup": "",
"Berlin": "",
"Blocks nominations": "",
"Bond": "",
"Bounty approval under voting": "",
@ -35,12 +36,14 @@
"Contracts": "",
"Controller account": "",
"Create a backup file for this account": "",
"Crust Network": "",
"Curator has been proposed by council. The bounty is waiting for curator to accept the role.": "",
"Curator proposal under voting": "",
"Curator slash under voting": "",
"Curator's deposit": "",
"Curator's deposit will be slashed and curator will be unassigned. Bounty will return to the Funded state.": "",
"Curator's fee": "",
"DCF": "",
"Dark theme (experimental, work-in-progress)": "",
"Defender": "",
"Delegate": "",
@ -53,7 +56,11 @@
"Distinct stash and controller accounts are recommended to ensure fund security. You will be allowed to make the transaction, but take care to not tie up all funds, only use a portion of the available funds during this period.": "",
"Evaluated {{count}} keys in {{elapsed}}s ({{avg}} keys/s)": "",
"Execute": "",
"Export": "",
"Extensions": "",
"File": "",
"Files": "",
"Folder": "",
"For approvals outstanding approvers will be shown, for hashes that should be cancelled the first approver is required.": "",
"For final approvals, the actual full call data is required to execute the transaction": "",
"Forget this account": "",
@ -63,6 +70,10 @@
"If the motion is approved, Curator's deposit will be slashed and Curator will be unassigned. Bounty will return to the Funded state.": "",
"If the motion is approved, the current Curator will be unassigned and the Bounty will return to the Funded state.": "",
"If you have not claimed rewards straight after the end of the era, the validator is in the active set and you are seeing no rewards, this would mean that the reward payout transaction was made by another account on your behalf. Always check your favorite explorer to see any historic payouts made to your accounts.": "",
"Import": "",
"Import Success": "",
"Import files": "",
"Importing": "",
"Inactive": "",
"Initiate recovery for another": "",
"Ledger app type (originated from)": "",
@ -86,6 +97,7 @@
"Nominating": "",
"Nominators": "",
"None": "",
"Note: The file list is cached locally, switching browsers or devices will not keep displaying the original browser information.": "",
"Online message": "",
"Override any applicable values for the specific signed output. These will be used to construct and display the signed transaction.": "",
"Oversubscribed": "",
@ -93,7 +105,9 @@
"Own validators": "",
"Para validator": "",
"Payouts of rewards for a validator can be initiated by any account. This means that as soon as a validator or nominator requests a payout for an era, all the nominators for that validator will be rewarded. Each user does not need to claim individually and the suggestion is that validators should claim rewards for everybody as soon as an era ends.": "",
"Please do not upload more than 2000 files": "",
"Please read these terms and conditions carefully. By submitting this statement, you are deemed to have accepted these Terms and Conditions. If you do not agree to these terms, please refrain from accessing or proceeding. You can also find them at:": "",
"Please select non-empty folder": "",
"Prior locked voting": "",
"Produced blocks": "",
"Proposer": "",
@ -102,10 +116,12 @@
"Retrieving nominators": "",
"Retrieving validators": "",
"Save": "",
"Seattle": "",
"Set on-chain identity": "",
"Set on-chain sub-identities": "",
"Settings": "",
"Show address on hardware device": "",
"Singapore": "",
"Slash curator": "",
"Slash curator (Council)": "",
"Slashed": "",
@ -169,13 +185,17 @@
"Unassign curator": "",
"Unassign curator under voting": "",
"Undelegate": "",
"United States": "",
"Unknown": "",
"Unless you are a developer with insight into what the specific script does to your environment (based on reading the code being executed) generally the advice would be to not use this environment.": "",
"Unlock the sending account to allow signing of this transaction.": "",
"Unlock vested amount": "",
"Upload": "",
"Upload & deploy code": "",
"Upload & deploy code {{info}}": "",
"Upload File": "",
"Validators": "",
"View status in Crust": "",
"Vote": "",
"Voting": "",
"Voting costs nothing other than the transaction fee and can be done from all accounts with a non-zero spendable balance.": "",
@ -187,6 +207,7 @@
"You need to sign an attestation for the following accounts:": "",
"account type": "",
"accounts": "",
"action": "",
"activate": "",
"address copied": "",
"address index": "",
@ -239,6 +260,11 @@
"events": "",
"external": "",
"extrinsics": "",
"file cid": "",
"file content error": "",
"file error": "",
"file size": "",
"files": "",
"finder": "",
"freezer": "",
"frozen": "",
@ -334,5 +360,6 @@
"{{balance}} voted": "",
"{{count}} key/value pairs encoded for submission": "",
"{{days}} days": "",
"{{percentage}}% turnout": ""
"{{percentage}}% turnout": "",
"⚡️ Thunder Gateway": ""
}

View File

@ -507,6 +507,7 @@
"Show address on hardware device": "在硬件设备上显示地址",
"Sign (no submission)": "签名(不提交)",
"Sign and Submit": "签名并提交",
"Sign and Upload": "签名并上传",
"Sign for multisig": "多重签名",
"Sign message": "签名消息",
"Sign via Qr": "通过 Qr 签名",

View File

@ -99,6 +99,7 @@ function Menu ({ className = '' }: Props): React.ReactElement<Props> {
const groupRef = useRef({
accounts: t('Accounts'),
developer: t('Developer'),
files: t('Files'),
governance: t('Governance'),
network: t('Network'),
settings: t('Settings')

View File

View File

201
packages/page-files/LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,26 @@
# @polkadot/app-files
## Description
***Substrate Files*** is a decentralized storage module which allows substrate-based chains(including `Polkadot/Kusama/Crust/Acala/Clover/Moonbeam/Astar/Phala/...`) users upload their files to [IPFS W3Auth Gateway](https://wiki.crust.network/docs/en/buildIPFSWeb3AuthGW) and decentralized pin their files on [Crust Network](https://crust.network) by using the standard [IPFS W3Auth Pinning Service](https://wiki.crust.network/docs/en/buildIPFSW3AuthPin). This module is a 100% IPFS compatible file storage module, users can pin **NFT files**, host **DApps** or store **on-chain data** in totally DECENTRALIZED way(`guaranteed by Crust protocol`).
Also, the Pinning Service is compatible with several Platforms like `Ethereum`, `Polygon`, `Solana` and `Near`, and funded by [Decentralized Cloud Foundation](https://decloudf.com/). So currently, `Substrate Files` is FREE for all the substrate-based chains!
## Features
Basically, the function is simple, it consist with 2 major parts: `Upload File` and `Manage File Directory`.
### Upload File
Upload files with substrate-based chains account, you can also copy the cid to [Crust Apps](https://apps.crust.network/?rpc=wss%3A%2F%2Frpc.crust.network#/storage) to see how many IPFS replicas of your file.
### Manage files directory
Because the whole files module is decentralized, so your file directory is cached in browser, but you can export and import your file directory info.
## References
- [Crust Network](https://crust.network)
- [IPFS Web3 Authentication Gateway](https://wiki.crust.network/docs/en/buildIPFSWeb3AuthGW)
- [IPFS Web3 Authentication Pinning Service](https://wiki.crust.network/docs/en/buildIPFSW3AuthPin)
- [IPFS Public Gateway](https://docs.ipfs.io/concepts/ipfs-gateway/)
- [IPFS Pinning Service](https://docs.ipfs.io/how-to/work-with-pinning-services/#use-an-existing-pinning-service)

View File

@ -0,0 +1,19 @@
{
"bugs": "https://github.com/polkadot-js/apps/issues",
"homepage": "https://github.com/polkadot-js/apps/tree/master/packages/page-files#readme",
"license": "Apache-2.0",
"name": "@polkadot/app-files",
"private": true,
"repository": {
"directory": "packages/page-files",
"type": "git",
"url": "https://github.com/polkadot-js/apps.git"
},
"sideEffects": false,
"type": "module",
"version": "0.105.2-24",
"dependencies": {
"@babel/runtime": "^7.17.0",
"@polkadot/react-components": "^0.105.2-24"
}
}

View File

@ -0,0 +1,385 @@
// Copyright 2017-2022 @polkadot/app-files authors & contributors
// SPDX-License-Identifier: Apache-2.0
import FileSaver from 'file-saver';
import React, { useCallback, useContext, useRef, useState } from 'react';
import styled from 'styled-components';
import { useFiles } from '@polkadot/app-files/hooks';
import UploadModal from '@polkadot/app-files/UploadModal';
import { Badge, Button, CopyButton, Icon, StatusContext, Table } from '@polkadot/react-components';
import { ActionStatusBase, QueueProps } from '@polkadot/react-components/Status/types';
import { useTranslation } from './translate';
import { DirFile, FileInfo, SaveFile } from './types';
const MCopyButton = styled(CopyButton)`
.copySpan {
display: none;
}
`;
const ItemFile = styled.tr`
height: 3.5rem;
.end {
text-align: end;
}
.actions {
display: flex;
justify-content: flex-end;
align-items: center;
}
`;
const shortStr = (name: string, count = 6): string => {
if (name.length > (count * 2)) {
return `${name.substr(0, count)}...${name.substr(name.length - count)}`;
}
return name;
};
function createUrl (f: SaveFile) {
const endpoint = f.UpEndpoint || 'https://ipfs.io';
return `${endpoint}/ipfs/${f.Hash}?filename=${f.Name}`;
}
const createOnDown = (f: SaveFile) => () => {
window.open(createUrl(f), '_blank');
// FileSaver.saveAs(createUrl(f), f.Name);
};
type FunInputFile = (e: React.ChangeEvent<HTMLInputElement>) => void
const Noop = (): void => undefined;
export interface Props {
className?: string,
}
function CrustFiles ({ className }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { queueAction } = useContext<QueueProps>(StatusContext);
const [showUpMode, setShowUpMode] = useState(false);
const wFiles = useFiles();
const [file, setFile] = useState<FileInfo | undefined>(undefined);
const inputRef = useRef<HTMLInputElement>(null);
const _clickUploadFile = useCallback((dir = false) => {
if (!inputRef.current) return;
// eslint-disable-next-line
// @ts-ignore
// eslint-disable-next-line
inputRef.current.webkitdirectory = dir;
// eslint-disable-next-line
inputRef.current.multiple = dir;
inputRef.current.click();
}, [inputRef]);
const onClickUpFile = useCallback(() => _clickUploadFile(false), [_clickUploadFile]);
const onClickUpFolder = useCallback(() => _clickUploadFile(true), [_clickUploadFile]);
const _onInputFile = useCallback<FunInputFile>((e) => {
const files = e.target.files;
if (!files) return;
if (files.length > 2000) {
queueAction({
action: 'Upload Folder',
message: t('Please do not upload more than 2000 files'),
status: 'error'
});
return;
}
if (files.length === 0) {
queueAction({
action: 'Upload Folder',
message: t('Please select non-empty folder'),
status: 'error'
});
return;
}
// eslint-disable-next-line
// @ts-ignore
// eslint-disable-next-line
const isDirectory = e.target.webkitdirectory;
if (!isDirectory) {
setFile({ file: files[0] });
setShowUpMode(true);
} else if (files.length >= 1) {
// eslint-disable-next-line
// @ts-ignore eslint-disable-next-line
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
const dirFiles: DirFile[] = [];
for (let index = 0; index < files.length; index++) {
// console.info('f:', files[index]);
dirFiles.push(files[index] as DirFile);
}
console.info(dirFiles);
const [dir] = dirFiles[0].webkitRelativePath.split('/');
setFile({ dir, files: dirFiles });
setShowUpMode(true);
}
e.target.value = '';
}, [setFile, setShowUpMode, queueAction, t]);
const _onImportResult = useCallback<(m: string, s?: ActionStatusBase['status']) => void>(
(message, status = 'queued') => {
queueAction && queueAction({
action: t('Import files'),
message,
status
});
},
[queueAction, t]
);
const importInputRef = useRef<HTMLInputElement>(null);
const _clickImport = useCallback(() => {
if (!importInputRef.current) return;
importInputRef.current.click();
}, [importInputRef]);
const _onInputImportFile = useCallback<FunInputFile>((e) => {
try {
_onImportResult(t('Importing'));
const fileReader = new FileReader();
const files = e.target.files;
if (!files) return;
fileReader.readAsText(files[0], 'UTF-8');
if (!(/(.json)$/i.test(e.target.value))) {
return _onImportResult(t('file error'), 'error');
}
fileReader.onload = (e) => {
const _list = JSON.parse(e.target?.result as string) as SaveFile[];
if (!Array.isArray(_list)) {
return _onImportResult(t('file content error'), 'error');
}
const fitter: SaveFile[] = [];
const mapImport: { [key: string]: boolean } = {};
for (const item of _list) {
if (item.Hash && item.Name && item.UpEndpoint && item.PinEndpoint) {
fitter.push(item);
mapImport[item.Hash] = true;
}
}
const filterOld = wFiles.files.filter((item) => !mapImport[item.Hash]);
wFiles.setFiles([...fitter, ...filterOld]);
_onImportResult(t('Import Success'), 'success');
};
} catch (e) {
_onImportResult(t('file content error'), 'error');
}
}, [wFiles, _onImportResult, t]);
const _onClose = useCallback(() => {
setShowUpMode(false);
}, []);
const _onSuccess = useCallback((res: SaveFile) => {
setShowUpMode(false);
const filterFiles = wFiles.files.filter((f) => f.Hash !== res.Hash);
wFiles.setFiles([res, ...filterFiles]);
}, [wFiles]);
const _export = useCallback(() => {
const blob = new Blob([JSON.stringify(wFiles.files)], { type: 'application/json; charset=utf-8' });
FileSaver.saveAs(blob, 'files.json');
}, [wFiles]);
return <main className={className}>
<header>
</header>
<input
onChange={_onInputFile}
ref={inputRef}
style={{ display: 'none' }}
type={'file'}
/>
<input
onChange={_onInputImportFile}
ref={importInputRef}
style={{ display: 'none' }}
type={'file'}
/>
{
file && showUpMode &&
<UploadModal
file={file}
onClose={_onClose}
onSuccess={_onSuccess}
/>
}
<div style={{ display: 'flex', paddingBottom: '1.5rem' }}>
<div className='uploadBtn'>
<Button
icon={'upload'}
label={t('Upload')}
onClick={Noop}
/>
<div className='uploadMenu'>
<div
className='menuItem'
onClick={onClickUpFile}
>{t('File')}</div>
<div
className='menuItem'
onClick={onClickUpFolder}
>{t('Folder')}</div>
</div>
</div>
<div style={{ flex: 1 }} />
<Button
icon={'file-import'}
label={t('Import')}
onClick={_clickImport}
/>
<Button
icon={'file-export'}
label={t('Export')}
onClick={_export}
/>
</div>
<Table
empty={t<string>('No files')}
emptySpinner={t<string>('Loading')}
header={[
[t('files'), 'start', 2],
[t('file cid'), 'expand', 2],
[undefined, 'start'],
[t('file size'), 'expand', 2],
[t('status'), 'expand'],
[t('action'), 'expand'],
[]
]}
>
{wFiles.files.map((f, index) =>
<ItemFile key={`files_item-${index}`}>
<td
className=''
colSpan={2}
>{f.items && <Icon
className='highlight--color'
icon='folder'
/>}
{shortStr(f.Name)}</td>
<td
className='end'
colSpan={2}
>{f.Hash}</td>
<td
className=''
colSpan={1}
>
<MCopyButton value={f.Hash}>
<Badge
color='highlight'
hover={t<string>('Copy file cid')}
icon='copy'
/>
</MCopyButton>
</td>
<td
className='end'
colSpan={2}
>{`${f.Size} bytes`}</td>
<td
className='end'
colSpan={1}
>
<a
href={'https://apps.crust.network/?rpc=wss%3A%2F%2Frpc.crust.network#/storage_files'}
rel='noreferrer'
target='_blank'
>{t('View status in Crust')}</a>
</td>
<td
className='end'
colSpan={1}
>
<div className='actions'>
{!f.items && <Badge
color='highlight'
hover={t<string>('Download')}
icon='download'
onClick={createOnDown(f)}
/>}
<MCopyButton value={createUrl(f)}>
<Badge
color='highlight'
hover={t<string>('Copy link')}
icon='copy'
/>
</MCopyButton>
</div>
</td>
<td colSpan={1} />
</ItemFile>
)}
</Table>
<div>
{t('Note: The file list is cached locally, switching browsers or devices will not keep displaying the original browser information.')}
</div>
</main>;
}
export default React.memo<Props>(styled(CrustFiles)`
h1 {
text-transform: unset !important;
}
.uploadBtn {
position: relative;
padding: 5px 0;
&:hover {
.uploadMenu {
display: block;
}
}
}
.uploadMenu {
z-index: 200;
display: none;
background-color: white;
position: absolute;
top: 43px;
left: 0;
box-shadow: 0 0 8px rgba(0, 0, 0, 0.4);
border-radius: 4px;
overflow: hidden;
line-height: 40px;
.menuItem {
cursor: pointer;
padding: 0 2rem;
display: flex;
align-items: center;
white-space: nowrap;
&:hover {
background-color: var(--bg-page);
}
}
}
`);

View File

@ -0,0 +1,41 @@
// Copyright 2017-2022 @polkadot/app-files authors & contributors
// SPDX-License-Identifier: Apache-2.0
import React, { CSSProperties } from 'react';
import styled from 'styled-components';
export interface Props {
className?: string,
style?: CSSProperties,
progress: number
}
function Progress ({ className = '', progress, style }: Props) {
return (
<div
className={`highlight--border ${className}`}
style={style}
>
<div
className='file-progress-bar highlight--bg'
style={{ width: `${progress}%` }}
/>
</div>
);
}
export default React.memo<Props>(styled(Progress)`
width: 100%;
background: unset;
overflow: hidden;
height: 1.4rem;
border-radius: 0.7rem;
border-style: solid;
border-width: 1px;
.file-progress-bar {
transition: width 100ms ease-in-out;
width: 0;
height: 100%;
}
`);

View File

@ -0,0 +1,384 @@
// Copyright 2017-2022 @polkadot/app-files authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Signer } from '@polkadot/api/types';
import axios, { CancelTokenSource } from 'axios';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { createAuthIpfsEndpoints } from '@polkadot/apps-config';
import { web3FromSource } from '@polkadot/extension-dapp';
import { Available, Button, Dropdown, InputAddress, Label, Modal, Password } from '@polkadot/react-components';
import { useAccounts } from '@polkadot/react-hooks';
import { keyring } from '@polkadot/ui-keyring';
import { isFunction, stringToHex, stringToU8a, u8aToHex } from '@polkadot/util';
import Progress from './Progress';
import { useTranslation } from './translate';
import { DirFile, FileInfo, SaveFile, UploadRes } from './types';
export interface Props {
file: FileInfo,
onClose?: () => void,
onSuccess?: (res: SaveFile) => void,
}
function ShowFile (p: { file: DirFile | File }) {
const f = p.file as DirFile;
return (
<div
style={{
backgroundColor: 'white',
borderBottom: '1px solid rgba(0, 0, 0, 0.15)',
borderRadius: '4px',
padding: '5px 2rem'
}}
>
<Label label={f.webkitRelativePath || p.file.name} />
<span>{`${f.size} bytes`}</span>
</div>
);
}
interface AccountState {
isExternal: boolean;
isHardware: boolean;
isInjected: boolean;
}
interface SignerState {
isUsable: boolean;
signer: Signer | null;
}
const NOOP = (): void => undefined;
function UploadModal (p: Props): React.ReactElement<Props> {
const { file, onClose = NOOP, onSuccess = NOOP } = p;
const { t } = useTranslation();
const endpoints = useMemo(
() => createAuthIpfsEndpoints(t)
.sort(() => Math.random() > 0.5 ? -1 : 1)
.map((item) => ({ ...item, text: `${item.text ?? ''}(${item.location ?? ''})` })),
[t]
);
const [currentEndpoint, setCurrentEndpoint] = useState(endpoints[0]);
const pinEndpoints = useMemo(() => [
{
text: t<string>('Crust Pinner'),
value: 'https://pin.crustcode.com'
}
], [t]);
const [currentPinEndpoint, setCurrentPinEndpoint] = useState(pinEndpoints[0]);
const { hasAccounts } = useAccounts();
const [currentPair, setCurrentPair] = useState(() => keyring.getPairs()[0] || null);
const [account, setAccount] = useState('');
const [{ isInjected }, setAccountState] = useState<AccountState>({
isExternal: false,
isHardware: false,
isInjected: false
});
const [isLocked, setIsLocked] = useState(false);
const [{ isUsable, signer }, setSigner] = useState<SignerState>({ isUsable: true, signer: null });
const [password, setPassword] = useState('');
const [isBusy, setBusy] = useState(false);
const fileSizeError = useMemo(() => {
const MAX = 100 * 1024 * 1024;
if (file.file) {
return file.file.size > MAX;
} else if (file.files) {
let sum = 0;
for (const f of file.files) {
sum += f.size;
}
return sum > MAX;
}
return false;
}, [file]);
const [error, setError] = useState('');
const errorText = fileSizeError ? t<string>('Do not upload files larger than 100MB!') : error;
const [upState, setUpState] = useState({ progress: 0, up: false });
const [cancelUp, setCancelUp] = useState<CancelTokenSource | null>(null);
const onAccountChange = useCallback((nAccount: string | null) => {
if (nAccount) {
setAccount(nAccount);
setCurrentPair(keyring.getPair(nAccount));
}
}, [setAccount, setCurrentPair]);
useEffect(() => {
const meta = (currentPair && currentPair.meta) || {};
const isExternal = (meta.isExternal as boolean) || false;
const isHardware = (meta.isHardware as boolean) || false;
const isInjected = (meta.isInjected as boolean) || false;
const isUsable = !(isExternal || isHardware || isInjected);
setAccountState({ isExternal, isHardware, isInjected });
setIsLocked(
isInjected
? false
: (currentPair && currentPair.isLocked) || false
);
setSigner({ isUsable, signer: null });
// for injected, retrieve the signer
if (meta.source && isInjected) {
web3FromSource(meta.source as string)
.catch(() => null)
.then((injected) => setSigner({
isUsable: isFunction(injected?.signer?.signRaw),
signer: injected?.signer || null
}))
.catch(console.error);
}
}, [currentPair]);
const unLock = useCallback(() => {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
currentPair.decodePkcs8(password);
resolve(1);
} catch (error) {
reject(error);
}
}, 0);
});
}, [currentPair, password]);
const _onClose = useCallback(() => {
if (cancelUp) cancelUp.cancel();
onClose();
}, [cancelUp, onClose]);
const _onClickUp = useCallback(async () => {
setError('');
if (!isUsable || !currentPair) {
return;
}
try {
// 1: sign
setBusy(true);
if (isLocked) {
await unLock();
}
let signature = '';
if (signer && isFunction(signer.signRaw)) {
const res = await signer.signRaw({
address: currentPair.address,
data: stringToHex(currentPair.address),
type: 'bytes'
});
signature = res.signature;
} else {
signature = u8aToHex(currentPair.sign(stringToU8a(currentPair.address)));
}
const perSignData = `${currentPair.address}:${signature}`;
const base64Signature = Buffer.from(perSignData).toString('base64');
const AuthBasic = `Basic ${base64Signature}`;
const AuthBearer = `Bearer ${base64Signature}`;
// 2: up file
const cancel = axios.CancelToken.source();
setCancelUp(cancel);
setUpState({ progress: 0, up: true });
const form = new FormData();
if (file.file) {
form.append('file', file.file, file.file.name);
} else if (file.files) {
for (const f of file.files) {
form.append('file', f, f.webkitRelativePath);
}
}
const UpEndpoint = currentEndpoint.value;
const upResult = await axios.request<UploadRes | string>({
cancelToken: cancel.token,
data: form,
headers: { Authorization: AuthBasic },
maxContentLength: 100 * 1024 * 1024,
method: 'POST',
onUploadProgress: (p: { loaded: number, total: number }) => {
const percent = p.loaded / p.total;
setUpState({ progress: Math.round(percent * 99), up: true });
},
params: { pin: true },
url: `${UpEndpoint}/api/v0/add`
});
let upRes: UploadRes;
if (typeof upResult.data === 'string') {
const jsonStr = upResult.data.replaceAll('}\n{', '},{');
const items = JSON.parse(`[${jsonStr}]`) as UploadRes[];
const folder = items.length - 1;
upRes = items[folder];
delete items[folder];
upRes.items = items;
} else {
upRes = upResult.data;
}
console.info('upResult:', upResult);
setCancelUp(null);
setUpState({ progress: 100, up: false });
// remote pin order
const PinEndpoint = currentPinEndpoint.value;
await axios.request({
data: {
cid: upRes.Hash,
name: upRes.Name
},
headers: { Authorization: AuthBearer },
method: 'POST',
url: `${PinEndpoint}/psa/pins`
});
onSuccess({
...upRes,
PinEndpoint,
UpEndpoint
});
} catch (e) {
setUpState({ progress: 0, up: false });
setBusy(false);
console.error(e);
setError((e as Error).message);
}
}, [file, unLock, signer, isLocked, isUsable, currentPair, currentPinEndpoint, currentEndpoint, onSuccess]);
const _onChangeGateway = useCallback((value: string) => {
const find = endpoints.find((item) => item.value === value);
if (find) setCurrentEndpoint(find);
}, [endpoints, setCurrentEndpoint]);
const _onChangePinner = useCallback((value: string) => {
const find = pinEndpoints.find((item) => item.value === value);
if (find) setCurrentPinEndpoint(find);
}, [pinEndpoints, setCurrentPinEndpoint]);
return (
<Modal
header={t<string>('Upload File')}
onClose={_onClose}
open={true}
size={'medium'}
>
<Modal.Content>
<Modal.Columns>
<div style={{ maxHeight: 300, overflow: 'auto', paddingLeft: '2rem', width: '100%' }}>
{
file.file && <ShowFile file={file.file} />
}
{file.files && file.files.map((f, i) =>
<ShowFile
file={f}
key={`file_item:${i}`}
/>
)}
</div>
</Modal.Columns>
<Modal.Columns>
<Dropdown
help={t<string>('File streaming and wallet authentication will be processed by the chosen gateway.')}
isDisabled={isBusy}
label={t<string>('Select a Web3 IPFS Gateway')}
onChange={_onChangeGateway}
options={endpoints}
value={currentEndpoint.value}
/>
</Modal.Columns>
<Modal.Columns>
<Dropdown
help={t<string>('Your file will be pinned to IPFS for long-term storage.')}
isDisabled={true}
label={t<string>('Select a Web3 IPFS Pinner')}
onChange={_onChangePinner}
options={pinEndpoints}
value={currentPinEndpoint.value}
/>
</Modal.Columns>
<Modal.Columns
hint={
!hasAccounts &&
<p
className='file-info'
style={{ padding: 0 }}
>{t<string>('Need to connect a plug-in wallet or import an account first')}
</p>
}
>
<InputAddress
defaultValue={account}
isDisabled={!hasAccounts || isBusy}
label={t<string>('Please choose account')}
labelExtra={
<Available
label={t<string>('transferrable')}
params={account}
/>
}
onChange={onAccountChange}
type='account'
/>
{
!upState.up && isLocked && !isInjected &&
<Password
help={t<string>('The account\'s password specified at the creation of this account.')}
isError={false}
label={t<string>('password')}
onChange={setPassword}
value={password}
/>
}
<Progress
progress={upState.progress}
style={{ marginLeft: '2rem', marginTop: '2rem', width: 'calc(100% - 2rem)' }}
/>
{
errorText &&
<div
style={{
color: 'orangered',
padding: '1rem',
whiteSpace: 'pre-wrap',
wordBreak: 'break-all'
}}
>
{errorText}
</div>
}
</Modal.Columns>
</Modal.Content>
<Modal.Actions>
<Button
icon={'arrow-circle-up'}
isBusy={isBusy}
isDisabled={!hasAccounts || fileSizeError}
label={t<string>('Sign and Upload')}
onClick={_onClickUp}
/>
</Modal.Actions>
</Modal>
);
}
export default React.memo(UploadModal);

View File

@ -0,0 +1,46 @@
// Copyright 2017-2022 @polkadot/app-files authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { useCallback, useEffect, useMemo, useState } from 'react';
import store from 'store';
import { SaveFile } from './types';
export interface Files {
files: SaveFile[],
}
export interface WrapFiles extends Files {
isLoad: boolean,
setFiles: (files: SaveFile[]) => void
}
const defFilesObj = { files: [], isLoad: true };
export function useFiles (): WrapFiles {
const [filesObj, setFilesObj] = useState<Files>(defFilesObj);
const [isLoad, setIsLoad] = useState(true);
useEffect(() => {
try {
const f = store.get('files', defFilesObj) as Files;
if (f !== defFilesObj) {
setFilesObj(f);
}
setIsLoad(false);
} catch (e) {
setIsLoad(false);
console.error(e);
}
}, []);
const setFiles = useCallback((nFiles: SaveFile[]) => {
const nFilesObj = { ...filesObj, files: nFiles };
setFilesObj(nFilesObj);
store.set('files', nFilesObj);
}, [filesObj]);
return useMemo(() => ({ ...filesObj, isLoad, setFiles }), [filesObj, setFiles, isLoad]);
}

View File

@ -0,0 +1,42 @@
// Copyright 2017-2022 @polkadot/app-files authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { KeyedEvent } from '@polkadot/react-query/types';
import React, { useRef } from 'react';
import CrustFiles from '@polkadot/app-files/CrustFiles';
import { HelpOverlay, Tabs } from '@polkadot/react-components';
import basicMd from '../README.md';
import { useTranslation } from './translate';
interface Props {
basePath: string;
className?: string;
newEvents?: KeyedEvent[];
}
function FilesApp ({ basePath, className }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const itemsRef = useRef([
{
isRoot: true,
name: 'crust',
text: t<string>('Your Files')
}
]);
return (
<main className={className}>
<HelpOverlay md={basicMd as string} />
<Tabs
basePath={basePath}
items={itemsRef.current}
/>
<CrustFiles />
</main>
);
}
export default React.memo(FilesApp);

View File

@ -0,0 +1,10 @@
// Copyright 2017-2022 @polkadot/app-files authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { UseTranslationResponse } from 'react-i18next';
import { useTranslation as useTranslationBase } from 'react-i18next';
export function useTranslation (): UseTranslationResponse<'app-files'> {
return useTranslationBase('app-files');
}

View File

@ -0,0 +1,24 @@
// Copyright 2017-2022 @polkadot/app-files authors & contributors
// SPDX-License-Identifier: Apache-2.0
export interface UploadRes {
Hash: string,
Size: string,
Name: string,
items?: UploadRes[],
}
export interface DirFile extends File {
webkitRelativePath: string,
}
export interface SaveFile extends UploadRes {
UpEndpoint: string,
PinEndpoint: string,
}
export interface FileInfo {
file?: File,
files?: DirFile[],
dir?: string,
}

View File

@ -32,6 +32,8 @@
"@polkadot/app-extrinsics/*": ["page-extrinsics/src/*"],
"@polkadot/app-explorer": ["page-explorer/src"],
"@polkadot/app-explorer/*": ["page-explorer/src/*"],
"@polkadot/app-files": ["page-files/src"],
"@polkadot/app-files/*": ["page-files/src/*"],
"@polkadot/app-gilt": ["page-gilt/src"],
"@polkadot/app-gilt/*": ["page-gilt/src/*"],
"@polkadot/app-i18n": ["page-i18n/src"],

View File

@ -2776,6 +2776,15 @@ __metadata:
languageName: unknown
linkType: soft
"@polkadot/app-files@workspace:packages/page-files":
version: 0.0.0-use.local
resolution: "@polkadot/app-files@workspace:packages/page-files"
dependencies:
"@babel/runtime": ^7.17.0
"@polkadot/react-components": ^0.105.2-24
languageName: unknown
linkType: soft
"@polkadot/app-gilt@workspace:packages/page-gilt":
version: 0.0.0-use.local
resolution: "@polkadot/app-gilt@workspace:packages/page-gilt"