diff --git a/packages/page-nfts/src/AccountItems/Item.tsx b/packages/page-nfts/src/AccountItems/Item.tsx index 92d33095ad..b2792814e1 100644 --- a/packages/page-nfts/src/AccountItems/Item.tsx +++ b/packages/page-nfts/src/AccountItems/Item.tsx @@ -15,7 +15,11 @@ interface Props { function Item ({ className, collectionName, value: { account, id, ipfsData } }: Props): React.ReactElement { 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 ( diff --git a/packages/page-nfts/src/AccountItems/types.ts b/packages/page-nfts/src/AccountItems/types.ts index 15ca2b6a81..0a2413a2f0 100644 --- a/packages/page-nfts/src/AccountItems/types.ts +++ b/packages/page-nfts/src/AccountItems/types.ts @@ -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; } diff --git a/packages/page-nfts/src/AccountItems/useItemsInfos.ts b/packages/page-nfts/src/AccountItems/useItemsInfos.ts index 6602c973d4..1975df3956 100644 --- a/packages/page-nfts/src/AccountItems/useItemsInfos.ts +++ b/packages/page-nfts/src/AccountItems/useItemsInfos.ts @@ -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; +type FetchedMetadata = Map; 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 (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[]]>(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(ipfsHashes, IPFS_FETCH_OPTIONS); + const fetchedMetadata = useMetadataFetch(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; } diff --git a/packages/page-nfts/src/Overview/Collection.tsx b/packages/page-nfts/src/Overview/Collection.tsx index 1d881b2d51..937a0b0dbe 100644 --- a/packages/page-nfts/src/Overview/Collection.tsx +++ b/packages/page-nfts/src/Overview/Collection.tsx @@ -19,7 +19,11 @@ interface Props { function Collection ({ className, value: { details, id, ipfsData } }: Props): React.ReactElement { 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 ( diff --git a/packages/page-nfts/src/types.ts b/packages/page-nfts/src/types.ts index b38640818e..c0cb41df6a 100644 --- a/packages/page-nfts/src/types.ts +++ b/packages/page-nfts/src/types.ts @@ -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 { diff --git a/packages/page-nfts/src/useCollectionInfos.ts b/packages/page-nfts/src/useCollectionInfos.ts index 1e493bb5eb..eb2a732c13 100644 --- a/packages/page-nfts/src/useCollectionInfos.ts +++ b/packages/page-nfts/src/useCollectionInfos.ts @@ -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; +type FetchedMetadata = Map; 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 (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[]]>(api.query.uniques.class.multi, [ids], QUERY_OPTS); const [state, setState] = useState(); - 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(ipfsHashes, IPFS_FETCH_OPTIONS); + const fetchedMetadata = useMetadataFetch(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; } diff --git a/packages/react-hooks/src/index.ts b/packages/react-hooks/src/index.ts index 54d6c17d9a..c24ec91338 100644 --- a/packages/react-hooks/src/index.ts +++ b/packages/react-hooks/src/index.ts @@ -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'; diff --git a/packages/react-hooks/src/useIpfsFetch.ts b/packages/react-hooks/src/useIpfsFetch.ts deleted file mode 100644 index df2d97eceb..0000000000 --- a/packages/react-hooks/src/useIpfsFetch.ts +++ /dev/null @@ -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 extends CallOptions { - transform?: (value: any) => T -} - -function isCid (cid: string): boolean { - return !!cid && (isIPFS.cid(cid) || isIPFS.base32cid(cid.toLowerCase())); -} - -const cache = new Map(); - -async function fetchIpfsData (ipfsHashes: string[]): Promise> { - 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 (ipfsData: Map, { transform }: Options = {}) { - 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 (hashes: string[] | undefined, options?: Options): Map | undefined { - const mountedRef = useIsMountedRef(); - const [value, setValue] = useState | 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(ipfsHashes) - .then((ipfsData) => setValue(postProcessData(ipfsData, options))) - // eslint-disable-next-line @typescript-eslint/no-empty-function - .catch(() => { }); - } - }, [ipfsHashes, options, mountedRef]); - - return value; -} diff --git a/packages/react-hooks/src/useMetadataFetch.ts b/packages/react-hooks/src/useMetadataFetch.ts new file mode 100644 index 0000000000..78154147ff --- /dev/null +++ b/packages/react-hooks/src/useMetadataFetch.ts @@ -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 extends CallOptions { + 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(); + +async function fetchMetadata (metadataLinks: string[]): Promise> { + 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 (fetchedMetadata: Map, { transform }: Options = {}) { + 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 (rawLinks: string[] | undefined, options?: Options): Map | undefined { + const mountedRef = useIsMountedRef(); + const [value, setValue] = useState | 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(metadataLinks) + .then((fetchedMetadata) => setValue(postProcessData(fetchedMetadata, options))) + // eslint-disable-next-line @typescript-eslint/no-empty-function + .catch(() => { }); + } + }, [metadataLinks, options, mountedRef]); + + return value; +}