2020-05-08 20:33:32 +02:00
|
|
|
import React from 'react';
|
2020-05-09 03:40:52 +02:00
|
|
|
import useIsMounted from 'effects/use-is-mounted';
|
2020-05-08 20:33:32 +02:00
|
|
|
|
|
|
|
// Returns a blob from the download path
|
2020-05-09 03:40:52 +02:00
|
|
|
export default function useFileStream(fileStream) {
|
|
|
|
const isMounted = useIsMounted();
|
2020-05-08 20:33:32 +02:00
|
|
|
|
|
|
|
const [state, setState] = React.useState({
|
|
|
|
error: false,
|
|
|
|
loading: true,
|
2020-05-09 03:40:52 +02:00
|
|
|
content: null,
|
2020-05-08 20:33:32 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
React.useEffect(() => {
|
2020-05-09 03:40:52 +02:00
|
|
|
if (fileStream && isMounted.current) {
|
|
|
|
let chunks = [];
|
2020-05-08 20:33:32 +02:00
|
|
|
const stream = fileStream();
|
2020-05-09 03:40:52 +02:00
|
|
|
// Handle steam chunk recived
|
2020-05-08 20:33:32 +02:00
|
|
|
stream.on('data', chunk => {
|
2020-05-09 03:40:52 +02:00
|
|
|
if (isMounted.current) {
|
|
|
|
chunks.push(chunk);
|
|
|
|
} else {
|
|
|
|
// Cancel stream if component is not mounted:
|
|
|
|
// The user has left the viewer page
|
|
|
|
stream.destroy();
|
|
|
|
}
|
2020-05-08 20:33:32 +02:00
|
|
|
});
|
2020-05-09 03:40:52 +02:00
|
|
|
// Handle stream ended
|
2020-05-08 20:33:32 +02:00
|
|
|
stream.on('end', () => {
|
2020-05-09 03:40:52 +02:00
|
|
|
if (isMounted.current) {
|
|
|
|
const buffer = Buffer.concat(chunks);
|
|
|
|
const blob = new Blob([buffer]);
|
|
|
|
setState({ content: blob, loading: false });
|
|
|
|
}
|
2020-05-08 20:33:32 +02:00
|
|
|
});
|
2020-05-09 03:40:52 +02:00
|
|
|
// Handle stream error
|
2020-05-08 20:33:32 +02:00
|
|
|
stream.on('error', () => {
|
2020-05-09 03:40:52 +02:00
|
|
|
if (isMounted.current) {
|
|
|
|
setState({ error: true, loading: false });
|
|
|
|
}
|
2020-05-08 20:33:32 +02:00
|
|
|
});
|
|
|
|
}
|
2020-05-09 03:40:52 +02:00
|
|
|
}, [fileStream, isMounted]);
|
2020-05-08 20:33:32 +02:00
|
|
|
|
|
|
|
return state;
|
|
|
|
}
|