ente/src/pages/gallery/index.tsx

554 lines
20 KiB
TypeScript
Raw Normal View History

2021-02-17 08:35:19 +00:00
import React, { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/router';
import { getKey, SESSION_KEYS } from 'utils/storage/sessionStorage';
2021-02-17 05:02:01 +00:00
import { file, syncData, localFiles } from 'services/fileService';
import PreviewCard from './components/PreviewCard';
import { getActualKey, getToken } from 'utils/common/key';
2020-09-20 15:18:35 +00:00
import styled from 'styled-components';
import PhotoSwipe from 'components/PhotoSwipe/PhotoSwipe';
2020-11-20 17:24:21 +00:00
import AutoSizer from 'react-virtualized-auto-sizer';
2020-11-29 14:48:47 +00:00
import { VariableSizeList as List } from 'react-window';
2021-02-08 17:15:13 +00:00
import LoadingBar from 'react-top-loading-bar';
2020-11-28 18:11:24 +00:00
import Collections from './components/Collections';
import Upload from './components/Upload';
2021-02-17 08:06:20 +00:00
import DownloadManager from 'services/downloadManager';
import {
collection,
2021-02-08 16:15:21 +00:00
syncCollections,
CollectionAndItsLatestFile,
getCollectionAndItsLatestFile,
getFavItemIds,
2021-02-08 17:15:13 +00:00
getLocalCollections,
getCollectionUpdationTime,
} from 'services/collectionService';
2021-01-24 20:59:58 +00:00
import constants from 'utils/strings/constants';
import AlertBanner from './components/AlertBanner';
2021-03-09 07:59:45 +00:00
import { Alert, Button, Jumbotron } from 'react-bootstrap';
2021-03-12 12:30:33 +00:00
import subscriptionService, { Plan } from 'services/subscriptionService';
import PlanSelector from './components/PlanSelector';
2020-09-20 15:18:35 +00:00
2021-02-09 05:33:45 +00:00
const DATE_CONTAINER_HEIGHT = 45;
2021-02-08 17:15:13 +00:00
const IMAGE_CONTAINER_HEIGHT = 200;
2021-02-08 17:29:45 +00:00
const NO_OF_PAGES = 2;
2021-02-08 17:15:13 +00:00
2020-11-29 14:48:47 +00:00
enum ITEM_TYPE {
TIME = 'TIME',
TILE = 'TILE',
2020-11-29 14:48:47 +00:00
}
2021-01-12 07:01:00 +00:00
export enum FILE_TYPE {
IMAGE,
VIDEO,
2021-02-08 17:15:13 +00:00
OTHERS,
2021-01-12 07:01:00 +00:00
}
2020-11-29 14:48:47 +00:00
interface TimeStampListItem {
itemType: ITEM_TYPE;
items?: file[];
itemStartIndex?: number;
date?: string;
2020-11-29 14:48:47 +00:00
}
2020-09-20 15:18:35 +00:00
const Container = styled.div`
display: block;
flex: 1;
width: 100%;
flex-wrap: wrap;
margin: 0 auto;
2020-09-20 15:18:35 +00:00
.pswp-thumbnail {
display: inline-block;
cursor: pointer;
}
2020-09-20 15:18:35 +00:00
`;
2020-11-20 17:24:21 +00:00
const ListItem = styled.div`
display: flex;
justify-content: center;
2020-11-28 18:11:24 +00:00
`;
const DeadCenter = styled.div`
flex: 1;
display: flex;
justify-content: center;
align-items: center;
color: #fff;
text-align: center;
flex-direction: column;
2020-11-28 18:11:24 +00:00
`;
2021-02-08 17:15:13 +00:00
const ListContainer = styled.div<{ columns: number }>`
2020-12-19 16:23:35 +00:00
display: grid;
2021-02-08 17:15:13 +00:00
grid-template-columns: repeat(${(props) => props.columns}, 1fr);
2020-12-19 16:23:35 +00:00
grid-column-gap: 8px;
padding: 0 8px;
max-width: 100%;
color: #fff;
2020-11-28 18:16:56 +00:00
@media (min-width: 1000px) {
width: 1000px;
}
2020-11-28 18:11:24 +00:00
@media (min-width: 450px) and (max-width: 1000px) {
width: 600px;
}
2020-11-28 18:11:24 +00:00
@media (max-width: 450px) {
width: 100%;
}
2020-11-20 17:24:21 +00:00
`;
2021-03-09 10:22:09 +00:00
const Image = styled.img`
width: 200px;
max-width: 100%;
display: block;
text-align: center;
margin-left: auto;
margin-right: auto;
margin-bottom: 20px;
`;
2020-11-29 14:55:07 +00:00
const DateContainer = styled.div`
2020-12-19 16:23:35 +00:00
padding-top: 15px;
2020-11-29 14:55:07 +00:00
`;
2021-01-06 06:31:16 +00:00
export default function Gallery(props) {
const router = useRouter();
const [collections, setCollections] = useState<collection[]>([]);
const [
collectionAndItsLatestFile,
setCollectionAndItsLatestFile,
] = useState<CollectionAndItsLatestFile[]>([]);
const [data, setData] = useState<file[]>();
2021-01-20 12:05:04 +00:00
const [favItemIds, setFavItemIds] = useState<Set<number>>();
const [open, setOpen] = useState(false);
2021-02-17 08:35:19 +00:00
const [currentIndex, setCurrentIndex] = useState<number>(0);
const fetching: { [k: number]: boolean } = {};
const [bannerErrorCode, setBannerErrorCode] = useState<number>(null);
2020-12-19 16:23:35 +00:00
const [sinceTime, setSinceTime] = useState(0);
const [isFirstLoad, setIsFirstLoad] = useState(false);
2021-03-12 12:30:33 +00:00
const [planModalView, setPlanModalView] = useState(false);
const [plans, setPlans] = useState<Plan[]>(null);
2021-02-17 08:35:19 +00:00
const loadingBar = useRef(null);
useEffect(() => {
const key = getKey(SESSION_KEYS.ENCRYPTION_KEY);
if (!key) {
router.push('/');
2021-02-17 09:16:20 +00:00
return;
}
const main = async () => {
2021-03-09 16:23:13 +00:00
subscriptionService.init();
setIsFirstLoad((await getCollectionUpdationTime()) == 0);
const data = await localFiles();
const collections = await getLocalCollections();
const collectionAndItsLatestFile = await getCollectionAndItsLatestFile(
collections,
data
);
2021-03-12 12:30:33 +00:00
const plans = await subscriptionService.getPlans();
console.log(plans);
setData(data);
setCollections(collections);
setCollectionAndItsLatestFile(collectionAndItsLatestFile);
2021-03-12 12:30:33 +00:00
setPlans(plans);
const favItemIds = await getFavItemIds(data);
setFavItemIds(favItemIds);
2021-02-17 08:35:19 +00:00
loadingBar.current.continuousStart();
await syncWithRemote();
2021-02-17 08:35:19 +00:00
loadingBar.current.complete();
setIsFirstLoad(false);
};
main();
props.setUploadButtonView(true);
}, []);
const syncWithRemote = async () => {
const token = getToken();
const encryptionKey = await getActualKey();
2021-02-08 16:15:21 +00:00
const collections = await syncCollections(token, encryptionKey);
const { data, isUpdated } = await syncData(token, collections);
const collectionAndItsLatestFile = await getCollectionAndItsLatestFile(
2021-02-08 17:15:13 +00:00
collections,
data
);
const favItemIds = await getFavItemIds(data);
2021-02-08 16:15:21 +00:00
setCollections(collections);
if (isUpdated) {
setData(data);
}
setCollectionAndItsLatestFile(collectionAndItsLatestFile);
setFavItemIds(favItemIds);
2021-02-08 17:15:13 +00:00
setSinceTime(new Date().getTime());
props.setUploadButtonView(true);
2021-02-08 17:15:13 +00:00
};
const updateUrl = (index: number) => (url: string) => {
data[index] = {
...data[index],
msrc: url,
w: window.innerWidth,
h: window.innerHeight,
};
2021-02-08 17:15:13 +00:00
if (
data[index].metadata.fileType === FILE_TYPE.VIDEO &&
!data[index].html
) {
data[index].html = `
2020-11-26 15:57:20 +00:00
<div class="video-loading">
<img src="${url}" />
<div class="spinner-border text-light" role="status">
<span class="sr-only">Loading...</span>
</div>
</div>
`;
delete data[index].src;
}
2021-02-08 17:15:13 +00:00
if (
data[index].metadata.fileType === FILE_TYPE.IMAGE &&
!data[index].src
) {
data[index].src = url;
}
setData(data);
};
const updateSrcUrl = (index: number, url: string) => {
data[index] = {
...data[index],
src: url,
w: window.innerWidth,
h: window.innerHeight,
};
if (data[index].metadata.fileType === FILE_TYPE.VIDEO) {
data[index].html = `
2020-11-26 15:57:20 +00:00
<video controls>
2020-11-26 17:35:26 +00:00
<source src="${url}" />
2020-11-26 15:57:20 +00:00
Your browser does not support the video tag.
</video>
`;
delete data[index].src;
}
setData(data);
};
const handleClose = () => {
setOpen(false);
// syncWithRemote();
};
const onThumbnailClick = (index: number) => () => {
2021-02-17 08:35:19 +00:00
setCurrentIndex(index);
setOpen(true);
};
const getThumbnail = (file: file[], index: number) => {
return (
<PreviewCard
key={`tile-${file[index].id}`}
data={file[index]}
updateUrl={updateUrl(file[index].dataIndex)}
onClick={onThumbnailClick(index)}
/>
);
};
2020-09-20 15:18:35 +00:00
const getSlideData = async (instance: any, index: number, item: file) => {
if (!item.msrc) {
2021-02-17 05:02:01 +00:00
const url = await DownloadManager.getPreview(item);
updateUrl(item.dataIndex)(url);
item.msrc = url;
if (!item.src) {
item.src = url;
}
item.w = window.innerWidth;
item.h = window.innerHeight;
try {
instance.invalidateCurrItems();
instance.updateSize(true);
} catch (e) {
// ignore
}
}
2021-02-16 06:22:59 +00:00
if (!fetching[item.dataIndex]) {
fetching[item.dataIndex] = true;
2021-02-17 05:02:01 +00:00
const url = await DownloadManager.getFile(item);
updateSrcUrl(item.dataIndex, url);
if (item.metadata.fileType === FILE_TYPE.VIDEO) {
item.html = `
2020-11-26 15:57:20 +00:00
<video width="320" height="240" controls>
2020-11-26 17:35:26 +00:00
<source src="${url}" />
2020-11-26 15:57:20 +00:00
Your browser does not support the video tag.
</video>
`;
delete item.src;
item.w = window.innerWidth;
} else {
item.src = url;
}
item.h = window.innerHeight;
try {
instance.invalidateCurrItems();
instance.updateSize(true);
} catch (e) {
// ignore
}
2020-11-28 18:11:24 +00:00
}
};
2021-02-15 14:30:26 +00:00
if (!data) {
return <div />;
}
2020-12-19 16:23:35 +00:00
2021-02-08 09:20:27 +00:00
const selectCollection = (id?: number) => {
const href = `/gallery?collection=${id || ''}`;
router.push(href, undefined, { shallow: true });
};
let idSet = new Set();
const filteredData = data
.map((item, index) => ({
...item,
dataIndex: index,
}))
.filter((item) => {
if (!idSet.has(item.id)) {
2021-01-06 06:31:16 +00:00
if (
!router.query.collection ||
router.query.collection === item.collectionID.toString()
2021-01-06 06:31:16 +00:00
) {
idSet.add(item.id);
return true;
2021-01-06 06:31:16 +00:00
}
return false;
}
return false;
});
const isSameDay = (first, second) => {
return (
first.getFullYear() === second.getFullYear() &&
first.getMonth() === second.getMonth() &&
first.getDate() === second.getDate()
);
};
2020-11-29 14:48:47 +00:00
2021-03-09 16:23:13 +00:00
const urlParams = new URLSearchParams(window.location.search);
const transactionStatus = urlParams.get('success');
let redirectMessage;
if (typeof transactionStatus != 'undefined') {
if (transactionStatus) {
const sessionId = urlParams.get('session_id');
if (sessionId) {
}
}
}
return (
<>
<LoadingBar color="#2dc262" ref={loadingBar} />
{isFirstLoad && (
2021-02-17 08:35:19 +00:00
<div className="text-center">
2021-03-09 10:36:23 +00:00
<Alert variant="success">
2021-02-17 08:35:19 +00:00
{constants.INITIAL_LOAD_DELAY_WARNING}
</Alert>
</div>
)}
<AlertBanner bannerErrorCode={bannerErrorCode} />
2021-03-09 11:38:21 +00:00
<Button
id="checkout"
variant="primary"
size="lg"
block
2021-03-12 12:30:33 +00:00
onClick={() => setPlanModalView(true)}
2021-03-09 11:38:21 +00:00
>
{constants.SUBSCRIBE}
</Button>
2021-03-12 12:30:33 +00:00
<PlanSelector
plans={plans}
modalView={planModalView}
closeModal={() => setPlanModalView(false)}
/>
<Collections
collections={collections}
2021-02-17 08:06:20 +00:00
selected={Number(router.query.collection)}
selectCollection={selectCollection}
/>
<Upload
uploadModalView={props.uploadModalView}
closeUploadModal={props.closeUploadModal}
collectionAndItsLatestFile={collectionAndItsLatestFile}
refetchData={syncWithRemote}
setBannerErrorCode={setBannerErrorCode}
acceptedFiles={props.acceptedFiles}
/>
2021-03-09 07:59:45 +00:00
{!isFirstLoad && data.length == 0 ? (
<Jumbotron>
2021-03-09 10:22:09 +00:00
<Image alt="vault" src="/vault.png" />
<Button variant="primary" onClick={props.openFileUploader}>
2021-03-09 10:22:09 +00:00
{constants.UPLOAD_FIRST_PHOTO}
</Button>
2021-03-09 07:59:45 +00:00
</Jumbotron>
) : filteredData.length ? (
<Container>
<AutoSizer>
{({ height, width }) => {
let columns;
if (width >= 1000) {
columns = 5;
} else if (width < 1000 && width >= 450) {
columns = 3;
} else if (width < 450 && width >= 300) {
columns = 2;
} else {
columns = 1;
}
const timeStampList: TimeStampListItem[] = [];
let listItemIndex = 0;
let currentDate = -1;
filteredData.forEach((item, index) => {
if (
!isSameDay(
2021-02-08 17:15:13 +00:00
new Date(
item.metadata.creationTime / 1000
),
new Date(currentDate)
)
) {
2021-02-08 17:15:13 +00:00
currentDate =
item.metadata.creationTime / 1000;
const dateTimeFormat = new Intl.DateTimeFormat(
'en-IN',
{
weekday: 'short',
year: 'numeric',
month: 'long',
day: 'numeric',
}
);
timeStampList.push({
itemType: ITEM_TYPE.TIME,
2021-02-08 17:15:13 +00:00
date: dateTimeFormat.format(
currentDate
),
});
timeStampList.push({
itemType: ITEM_TYPE.TILE,
items: [item],
itemStartIndex: index,
});
listItemIndex = 1;
} else {
if (listItemIndex < columns) {
2021-02-08 17:15:13 +00:00
timeStampList[
timeStampList.length - 1
].items.push(item);
listItemIndex++;
} else {
listItemIndex = 1;
timeStampList.push({
itemType: ITEM_TYPE.TILE,
items: [item],
itemStartIndex: index,
});
}
}
});
2021-02-08 17:15:13 +00:00
const extraRowsToRender = Math.ceil(
2021-02-08 17:29:45 +00:00
(NO_OF_PAGES * height) / IMAGE_CONTAINER_HEIGHT
2021-02-08 17:15:13 +00:00
);
return (
<List
itemSize={(index) =>
2021-02-08 17:15:13 +00:00
timeStampList[index].itemType ===
ITEM_TYPE.TIME
2021-02-08 17:15:13 +00:00
? DATE_CONTAINER_HEIGHT
: IMAGE_CONTAINER_HEIGHT
}
height={height}
width={width}
itemCount={timeStampList.length}
2020-12-19 16:23:35 +00:00
key={`${router.query.collection}-${columns}-${sinceTime}`}
overscanCount={extraRowsToRender}
>
{({ index, style }) => {
return (
<ListItem style={style}>
2021-02-08 17:15:13 +00:00
<ListContainer
columns={
timeStampList[index]
.itemType ===
ITEM_TYPE.TIME
2021-02-08 17:15:13 +00:00
? 1
: columns
}
>
{timeStampList[index]
.itemType ===
ITEM_TYPE.TIME ? (
2021-02-08 17:15:13 +00:00
<DateContainer>
{
timeStampList[
index
].date
}
</DateContainer>
) : (
timeStampList[
index
].items.map(
(item, idx) => {
return getThumbnail(
filteredData,
2021-02-08 17:15:13 +00:00
timeStampList[
index
]
.itemStartIndex +
idx
);
2021-02-08 17:15:13 +00:00
}
)
)}
</ListContainer>
</ListItem>
);
}}
</List>
);
}}
</AutoSizer>
<PhotoSwipe
isOpen={open}
items={filteredData}
2021-02-17 08:35:19 +00:00
currentIndex={currentIndex}
onClose={handleClose}
gettingData={getSlideData}
2021-01-20 12:05:04 +00:00
favItemIds={favItemIds}
setFavItemIds={setFavItemIds}
loadingBar={loadingBar}
/>
</Container>
) : (
2021-02-08 17:15:13 +00:00
<DeadCenter>
<div>{constants.NOTHING_HERE}</div>
</DeadCenter>
)}
2021-03-09 08:20:43 +00:00
{data.length < 30 && (
<Alert
2021-03-09 10:36:23 +00:00
variant="success"
style={{
position: 'fixed',
bottom: '1%',
width: '100%',
textAlign: 'center',
marginBottom: '0px',
}}
2021-03-09 08:20:43 +00:00
>
{constants.INSTALL_MOBILE_APP()}
</Alert>
)}
</>
);
}