Support ipfs://ipfs/ links (#9772)

* Support ipfs://ipfs/ links

* A more universal approach

* use toPrimitive() instead of toString()

* Chore
This commit is contained in:
Jegor Sidorenko 2024-02-28 14:37:42 +02:00 committed by GitHub
parent 13e955daaa
commit 585662dbd4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 151 additions and 120 deletions

View File

@ -15,7 +15,11 @@ interface Props {
function Item ({ className, collectionName, value: { account, id, ipfsData } }: Props): React.ReactElement<Props> {
const name = ipfsData?.name || collectionName;
const imageLink = ipfsData?.image ? `https://ipfs.io/ipfs/${ipfsData.image}` : '';
let imageLink = '';
if (ipfsData?.image) {
imageLink = ipfsData.image.toLowerCase().startsWith('http') ? ipfsData.image : `https://ipfs.io/ipfs/${ipfsData.image}`;
}
return (
<tr className={className}>

View File

@ -5,7 +5,7 @@ import type { AccountId } from '@polkadot/types/interfaces';
import type { PalletUniquesItemMetadata } from '@polkadot/types/lookup';
import type { BN } from '@polkadot/util';
export interface ItemSupportedIpfsData {
export interface ItemSupportedMetadata {
name: string | null;
image: string | null;
}
@ -15,5 +15,5 @@ export interface ItemInfo {
id: BN;
key: string;
metadata: PalletUniquesItemMetadata | null;
ipfsData: ItemSupportedIpfsData | null;
ipfsData: ItemSupportedMetadata | null;
}

View File

@ -5,18 +5,19 @@ import type { Option } from '@polkadot/types';
import type { PalletUniquesItemMetadata } from '@polkadot/types/lookup';
import type { BN } from '@polkadot/util';
import type { AccountItem } from '../types.js';
import type { ItemInfo, ItemSupportedIpfsData } from './types.js';
import type { ItemInfo, ItemSupportedMetadata } from './types.js';
import { useEffect, useMemo, useState } from 'react';
import { createNamedHook, useApi, useCall, useIpfsFetch } from '@polkadot/react-hooks';
import { createNamedHook, useApi, useCall, useMetadataFetch } from '@polkadot/react-hooks';
import { normalizeMetadataLink } from '@polkadot/react-hooks/useMetadataFetch';
type IpfsData = Map<string, ItemSupportedIpfsData | null>;
type FetchedMetadata = Map<string, ItemSupportedMetadata | null>;
const QUERY_OPTS = { withParams: true };
const IPFS_FETCH_OPTIONS = {
transform: (data: string | undefined): ItemSupportedIpfsData | null => {
const METADATA_FETCH_OPTIONS = {
transform: (data: string | undefined): ItemSupportedMetadata | null => {
if (!data) {
return null;
}
@ -26,7 +27,7 @@ const IPFS_FETCH_OPTIONS = {
if (result && typeof result === 'object') {
return {
image: typeof result.image === 'string' ? result.image.replace(/ipfs:\/\/|ipfs\//gi, '') : null,
image: typeof result.image === 'string' ? normalizeMetadataLink(result.image) : null,
name: typeof result.name === 'string' ? result.name : null
};
}
@ -52,12 +53,12 @@ function extractInfo ([, itemId]: [BN, BN], metadata: Option<PalletUniquesItemMe
};
}
const addIpfsData = (ipfsData: IpfsData) => (itemInfo: ItemInfo): ItemInfo => {
const ipfsHash = itemInfo.metadata?.data.toString();
const addFetchedMetadata = (fetchedMetadata: FetchedMetadata) => (itemInfo: ItemInfo): ItemInfo => {
const metadataLink = normalizeMetadataLink(itemInfo.metadata?.data.toPrimitive() as string);
return {
...itemInfo,
ipfsData: (ipfsHash && ipfsData.has(ipfsHash) && ipfsData.get(ipfsHash)) || null
ipfsData: (metadataLink && fetchedMetadata.has(metadataLink) && fetchedMetadata.get(metadataLink)) || null
};
};
@ -72,7 +73,7 @@ function useItemsInfosImpl (accountItems: AccountItem[]): ItemInfo[] | undefined
const metadata = useCall<[[[BN, BN][]], Option<PalletUniquesItemMetadata>[]]>(api.query.uniques.instanceMetadataOf.multi, [ids], QUERY_OPTS);
const ipfsHashes = useMemo((): string[] | undefined => {
const metadataLinks = useMemo((): string[] | undefined => {
if (metadata?.[1].length) {
return metadata[1].map((o) =>
o.isSome
@ -84,10 +85,10 @@ function useItemsInfosImpl (accountItems: AccountItem[]): ItemInfo[] | undefined
return undefined;
}, [metadata]);
const ipfsData = useIpfsFetch<ItemSupportedIpfsData | null>(ipfsHashes, IPFS_FETCH_OPTIONS);
const fetchedMetadata = useMetadataFetch<ItemSupportedMetadata | null>(metadataLinks, METADATA_FETCH_OPTIONS);
useEffect((): void => {
if (ipfsData && accountItems.length && metadata?.[0][0].length) {
if (fetchedMetadata && accountItems.length && metadata?.[0][0].length) {
const [collectionId] = metadata[0][0][0];
if (!collectionId.eq(ids[0][0])) {
@ -96,9 +97,9 @@ function useItemsInfosImpl (accountItems: AccountItem[]): ItemInfo[] | undefined
const itemsInfos = metadata[0][0].map((id, index) => extractInfo(id, metadata[1][index], accountItems));
setState(itemsInfos.map(addIpfsData(ipfsData)));
setState(itemsInfos.map(addFetchedMetadata(fetchedMetadata)));
}
}, [accountItems, ids, ipfsData, metadata]);
}, [accountItems, ids, fetchedMetadata, metadata]);
return state;
}

View File

@ -19,7 +19,11 @@ interface Props {
function Collection ({ className, value: { details, id, ipfsData } }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const name = ipfsData?.name || '';
const imageLink = ipfsData?.image ? `https://ipfs.io/ipfs/${ipfsData.image}` : '';
let imageLink = '';
if (ipfsData?.image) {
imageLink = ipfsData.image.toLowerCase().startsWith('http') ? ipfsData.image : `https://ipfs.io/ipfs/${ipfsData.image}`;
}
return (
<tr className={className}>

View File

@ -5,7 +5,7 @@ import type { AccountId } from '@polkadot/types/interfaces';
import type { PalletUniquesCollectionDetails, PalletUniquesCollectionMetadata } from '@polkadot/types/lookup';
import type { BN } from '@polkadot/util';
export interface CollectionSupportedIpfsData {
export interface CollectionSupportedMetadata {
name: string | null;
image: string | null;
}
@ -19,7 +19,7 @@ export interface CollectionInfo {
isOwnerMe: boolean;
key: string;
metadata: PalletUniquesCollectionMetadata | null;
ipfsData: CollectionSupportedIpfsData | null;
ipfsData: CollectionSupportedMetadata | null;
}
export interface CollectionInfoComplete extends CollectionInfo {

View File

@ -5,13 +5,14 @@ import type { Option } from '@polkadot/types';
import type { AccountId } from '@polkadot/types/interfaces';
import type { PalletUniquesCollectionDetails, PalletUniquesCollectionMetadata } from '@polkadot/types/lookup';
import type { BN } from '@polkadot/util';
import type { CollectionInfo, CollectionSupportedIpfsData } from './types.js';
import type { CollectionInfo, CollectionSupportedMetadata } from './types.js';
import { useEffect, useMemo, useState } from 'react';
import { createNamedHook, useAccounts, useApi, useCall, useIpfsFetch } from '@polkadot/react-hooks';
import { createNamedHook, useAccounts, useApi, useCall, useMetadataFetch } from '@polkadot/react-hooks';
import { normalizeMetadataLink } from '@polkadot/react-hooks/useMetadataFetch';
type IpfsData = Map<string, CollectionSupportedIpfsData | null>;
type FetchedMetadata = Map<string, CollectionSupportedMetadata | null>;
const EMPTY_FLAGS = {
isAdminMe: false,
@ -22,8 +23,8 @@ const EMPTY_FLAGS = {
const QUERY_OPTS = { withParams: true };
const IPFS_FETCH_OPTIONS = {
transform: (data: string | undefined): CollectionSupportedIpfsData | null => {
const METADATA_FETCH_OPTIONS = {
transform: (data: string | undefined): CollectionSupportedMetadata | null => {
if (!data) {
return null;
}
@ -33,7 +34,7 @@ const IPFS_FETCH_OPTIONS = {
if (result && typeof result === 'object') {
return {
image: typeof result.image === 'string' ? result.image.replace(/ipfs:\/\/|ipfs\//gi, '') : null,
image: typeof result.image === 'string' ? normalizeMetadataLink(result.image) : null,
name: typeof result.name === 'string' ? result.name : null
};
}
@ -70,12 +71,12 @@ function extractInfo (allAccounts: string[], id: BN, optDetails: Option<PalletUn
};
}
const addIpfsData = (ipfsData: IpfsData) => (collectionInfo: CollectionInfo): CollectionInfo => {
const ipfsHash = collectionInfo.metadata && collectionInfo.metadata.data?.toPrimitive() as string;
const addFetchedMetadata = (fetchedMetadata: FetchedMetadata) => (collectionInfo: CollectionInfo): CollectionInfo => {
const metadataLink = normalizeMetadataLink(collectionInfo.metadata?.data.toPrimitive() as string);
return {
...collectionInfo,
ipfsData: (ipfsHash && ipfsData.has(ipfsHash) && ipfsData.get(ipfsHash)) || null
ipfsData: (metadataLink && fetchedMetadata.has(metadataLink) && fetchedMetadata.get(metadataLink)) || null
};
};
@ -86,7 +87,7 @@ function useCollectionInfosImpl (ids?: BN[]): CollectionInfo[] | undefined {
const details = useCall<[[BN[]], Option<PalletUniquesCollectionDetails>[]]>(api.query.uniques.class.multi, [ids], QUERY_OPTS);
const [state, setState] = useState<CollectionInfo[] | undefined>();
const ipfsHashes = useMemo(
const metadataLinks = useMemo(
() => metadata?.[1].length
? metadata[1].map((o) =>
o.isSome
@ -97,17 +98,17 @@ function useCollectionInfosImpl (ids?: BN[]): CollectionInfo[] | undefined {
[metadata]
);
const ipfsData = useIpfsFetch<CollectionSupportedIpfsData | null>(ipfsHashes, IPFS_FETCH_OPTIONS);
const fetchedMetadata = useMetadataFetch<CollectionSupportedMetadata | null>(metadataLinks, METADATA_FETCH_OPTIONS);
useEffect((): void => {
if (ipfsData && details && metadata && (details[0][0].length === metadata[0][0].length)) {
if (fetchedMetadata && details && metadata && (details[0][0].length === metadata[0][0].length)) {
const collectionInfos = details[0][0].map((id, index) =>
extractInfo(allAccounts, id, details[1][index], metadata[1][index])
);
setState(collectionInfos.map(addIpfsData(ipfsData)));
setState(collectionInfos.map(addFetchedMetadata(fetchedMetadata)));
}
}, [allAccounts, details, ids, ipfsData, metadata]);
}, [allAccounts, details, ids, fetchedMetadata, metadata]);
return state;
}

View File

@ -41,7 +41,6 @@ export { useFormField } from './useFormField.js';
export { useIncrement } from './useIncrement.js';
export { useInflation } from './useInflation.js';
export { useIpfs } from './useIpfs.js';
export { useIpfsFetch } from './useIpfsFetch.js';
export { useIpfsLink } from './useIpfsLink.js';
export { useIsMountedRef } from './useIsMountedRef.js';
export { useJudgements } from './useJudgements.js';
@ -50,6 +49,7 @@ export { useLedger } from './useLedger.js';
export { useMapEntries } from './useMapEntries.js';
export { useMapKeys } from './useMapKeys.js';
export { useMemoValue } from './useMemoValue.js';
export { useMetadataFetch } from './useMetadataFetch.js';
export { useModal } from './useModal.js';
export { useNextTick } from './useNextTick.js';
export { useNonEmptyString } from './useNonEmptyString.js';

View File

@ -1,85 +0,0 @@
// Copyright 2017-2024 @polkadot/react-hooks authors & contributors
// SPDX-License-Identifier: Apache-2.0
import '@polkadot/x-textencoder/shim';
import '@polkadot/x-textdecoder/shim';
import type { CallOptions } from './types.js';
import * as isIPFS from 'is-ipfs';
import { useEffect, useMemo, useState } from 'react';
import { useIsMountedRef } from './useIsMountedRef.js';
interface Options <T> extends CallOptions<T> {
transform?: (value: any) => T
}
function isCid (cid: string): boolean {
return !!cid && (isIPFS.cid(cid) || isIPFS.base32cid(cid.toLowerCase()));
}
const cache = new Map<string, any>();
async function fetchIpfsData <T> (ipfsHashes: string[]): Promise<Map<string, T>> {
const result = new Map();
const promises = ipfsHashes.map((ipfsHash) => {
if (cache.has(ipfsHash)) {
result.set(ipfsHash, cache.get(ipfsHash));
return Promise.resolve();
}
return fetch(`https://ipfs.io/ipfs/${ipfsHash}`)
.then(async (res) => {
const ipfsResponse = res.status >= 200 && res.status < 300 ? await res.text() : null;
cache.set(ipfsHash, ipfsResponse);
result.set(ipfsHash, ipfsResponse);
});
});
await Promise.allSettled(promises);
return result;
}
function postProcessData <T> (ipfsData: Map<string, T>, { transform }: Options<T> = {}) {
if (!transform) {
return ipfsData;
}
for (const [key, value] of ipfsData.entries()) {
ipfsData.set(key, transform(value));
}
return ipfsData;
}
// FIXME This is generic, we cannot really use createNamedHook
export function useIpfsFetch <T> (hashes: string[] | undefined, options?: Options<T>): Map<string, T> | undefined {
const mountedRef = useIsMountedRef();
const [value, setValue] = useState<Map<string, T> | undefined>();
const ipfsHashes = useMemo(() => {
if (!hashes) {
return undefined;
}
return hashes
.map((hash) => isCid(hash) ? hash : '')
.filter((hash) => !!hash);
}, [hashes]);
useEffect((): void => {
if (mountedRef.current && ipfsHashes) {
fetchIpfsData<T>(ipfsHashes)
.then((ipfsData) => setValue(postProcessData<T>(ipfsData, options)))
// eslint-disable-next-line @typescript-eslint/no-empty-function
.catch(() => { });
}
}, [ipfsHashes, options, mountedRef]);
return value;
}

View File

@ -0,0 +1,106 @@
// Copyright 2017-2024 @polkadot/react-hooks authors & contributors
// SPDX-License-Identifier: Apache-2.0
import '@polkadot/x-textencoder/shim';
import '@polkadot/x-textdecoder/shim';
import type { CallOptions } from './types.js';
import { useEffect, useMemo, useState } from 'react';
import { useIsMountedRef } from './useIsMountedRef.js';
interface Options <T> extends CallOptions<T> {
transform?: (value: any) => T
}
export function normalizeMetadataLink (link?: string): string {
if (!link) {
return '';
} else if (link.toLowerCase().startsWith('http')) {
return link;
}
// handle V0 CID
const matchCidV0 = link.match(/Qm[A-Za-z0-9]{44}(?![A-Za-z0-9])/);
if (matchCidV0 !== null) {
return matchCidV0[0];
}
// handle V1 CID
const matchCidV1 = link.match(/[a-z0-9]{59}(?![A-Za-z0-9])/);
if (matchCidV1 !== null) {
return matchCidV1[0];
}
return '';
}
const cache = new Map<string, any>();
async function fetchMetadata <T> (metadataLinks: string[]): Promise<Map<string, T>> {
const result = new Map();
const promises = metadataLinks.map((metadataLink) => {
if (cache.has(metadataLink)) {
result.set(metadataLink, cache.get(metadataLink));
return Promise.resolve();
}
const fetchLink = metadataLink.startsWith('http') ? metadataLink : `https://ipfs.io/ipfs/${metadataLink}`;
return fetch(fetchLink)
.then(async (res) => {
const response = res.status >= 200 && res.status < 300 ? await res.text() : null;
cache.set(metadataLink, response);
result.set(metadataLink, response);
});
});
await Promise.allSettled(promises);
return result;
}
function postProcessData <T> (fetchedMetadata: Map<string, T>, { transform }: Options<T> = {}) {
if (!transform) {
return fetchedMetadata;
}
for (const [key, value] of fetchedMetadata.entries()) {
fetchedMetadata.set(key, transform(value));
}
return fetchedMetadata;
}
// FIXME This is generic, we cannot really use createNamedHook
export function useMetadataFetch <T> (rawLinks: string[] | undefined, options?: Options<T>): Map<string, T> | undefined {
const mountedRef = useIsMountedRef();
const [value, setValue] = useState<Map<string, T> | undefined>();
const metadataLinks = useMemo(() => {
if (!rawLinks) {
return undefined;
}
return rawLinks
.map((hash) => normalizeMetadataLink(hash))
.filter((hash) => !!hash);
}, [rawLinks]);
useEffect((): void => {
if (mountedRef.current && metadataLinks) {
fetchMetadata<T>(metadataLinks)
.then((fetchedMetadata) => setValue(postProcessData<T>(fetchedMetadata, options)))
// eslint-disable-next-line @typescript-eslint/no-empty-function
.catch(() => { });
}
}, [metadataLinks, options, mountedRef]);
return value;
}