|
| 1 | +/* |
| 2 | +Copyright 2024 The Matrix.org Foundation C.I.C. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +import React, {useEffect} from "react"; |
| 18 | + |
| 19 | +import {canAddAuthToMediaUrl, getMediaByUrl} from "../../../utils/media"; |
| 20 | + |
| 21 | +interface IProps extends React.HTMLProps<HTMLImageElement> { |
| 22 | +} |
| 23 | + |
| 24 | +const AuthedImage: React.FC<IProps> = (props) => { |
| 25 | + const [src, setSrc] = React.useState<string | undefined>(""); |
| 26 | + |
| 27 | + useEffect(() => { |
| 28 | + let blobUrl: string | undefined; |
| 29 | + async function getImage(): Promise<void> { |
| 30 | + if (props.src) { |
| 31 | + if (await canAddAuthToMediaUrl(props.src)) { |
| 32 | + const response = await getMediaByUrl(props.src); |
| 33 | + blobUrl = URL.createObjectURL(await response.blob()); |
| 34 | + setSrc(blobUrl); |
| 35 | + } else { |
| 36 | + // Skip blob caching if we're just doing a plain http(s) request. |
| 37 | + setSrc(props.src); |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + // noinspection JSIgnoredPromiseFromCall |
| 43 | + getImage(); |
| 44 | + |
| 45 | + return () => { |
| 46 | + // Cleanup |
| 47 | + if (blobUrl) { |
| 48 | + URL.revokeObjectURL(blobUrl); |
| 49 | + } |
| 50 | + }; |
| 51 | + }, [props.src]); |
| 52 | + |
| 53 | + const props2 = {...props}; |
| 54 | + props2.src = src; |
| 55 | + |
| 56 | + return ( |
| 57 | + // eslint-disable-next-line jsx-a11y/alt-text |
| 58 | + <img {...props2} /> |
| 59 | + ); |
| 60 | +}; |
| 61 | + |
| 62 | +export default AuthedImage; |
0 commit comments