Merge branch 'master' into remove-file-from-collection

This commit is contained in:
Abhinav 2021-10-28 14:08:01 +05:30
commit 86f1891d77
17 changed files with 480 additions and 300 deletions

View file

@ -18,7 +18,6 @@ import { VariableSizeList as List } from 'react-window';
import PhotoSwipe from 'components/PhotoSwipe/PhotoSwipe';
import { isInsideBox, isSameDay as isSameDayAnyYear } from 'utils/search';
import { SetDialogMessage } from './MessageDialog';
import { CustomError } from 'utils/common/errorUtil';
import {
GAP_BTW_TILES,
DATE_CONTAINER_HEIGHT,
@ -30,10 +29,10 @@ import {
import { fileIsArchived } from 'utils/file';
import { ALL_SECTION, ARCHIVE_SECTION } from './pages/gallery/Collections';
import { isSharedFile } from 'utils/file';
import { isPlaybackPossible } from 'utils/photoFrame';
const NO_OF_PAGES = 2;
const A_DAY = 24 * 60 * 60 * 1000;
const WAIT_FOR_VIDEO_PLAYBACK = 1 * 1000;
interface TimeStampListItem {
itemType: ITEM_TYPE;
@ -146,7 +145,7 @@ interface Props {
isFirstLoad;
openFileUploader;
loadingBar;
searchMode: boolean;
isInSearchMode: boolean;
search: Search;
setSearchStats: setSearchStats;
deleted?: number[];
@ -165,11 +164,10 @@ const PhotoFrame = ({
isFirstLoad,
openFileUploader,
loadingBar,
searchMode,
isInSearchMode,
search,
setSearchStats,
deleted,
setDialogMessage,
activeCollection,
isSharedCollection,
}: Props) => {
@ -181,12 +179,20 @@ const PhotoFrame = ({
const listRef = useRef(null);
useEffect(() => {
if (searchMode) {
if (isInSearchMode) {
setSearchStats({
resultCount: filteredData.length,
timeTaken: (Date.now() - startTime) / 1000,
});
}
if (search.fileIndex || search.fileIndex === 0) {
const filteredDataIdx = filteredData.findIndex(
(data) => data.dataIndex === search.fileIndex
);
if (filteredDataIdx || filteredDataIdx === 0) {
onThumbnailClick(filteredDataIdx)();
}
}
}, [search]);
useEffect(() => {
@ -225,21 +231,33 @@ const PhotoFrame = ({
setFiles(files);
};
const updateSrcUrl = (index: number, url: string) => {
const updateSrcUrl = async (index: number, url: string) => {
files[index] = {
...files[index],
src: url,
w: window.innerWidth,
h: window.innerHeight,
};
if (files[index].metadata.fileType === FILE_TYPE.VIDEO) {
files[index].html = `
if (await isPlaybackPossible(url)) {
files[index].html = `
<video controls>
<source src="${url}" />
Your browser does not support the video tag.
</video>
`;
delete files[index].src;
} else {
files[index].html = `
<div class="video-loading">
<img src="${files[index].msrc}" />
<div class="download-message" >
${constants.VIDEO_PLAYBACK_FAILED_DOWNLOAD_INSTEAD}
<a class="btn btn-outline-success" href=${url} download="${files[index].metadata.title}"">Download</button>
</div>
</div>
`;
}
} else {
files[index].src = url;
}
setFiles(files);
};
@ -283,101 +301,56 @@ const PhotoFrame = ({
const getSlideData = async (instance: any, index: number, item: File) => {
if (!item.msrc) {
let url: string;
if (galleryContext.thumbs.has(item.id)) {
url = galleryContext.thumbs.get(item.id);
} else {
url = await DownloadManager.getPreview(item);
galleryContext.thumbs.set(item.id, url);
}
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);
let url: string;
if (galleryContext.thumbs.has(item.id)) {
url = galleryContext.thumbs.get(item.id);
} else {
url = await DownloadManager.getPreview(item);
galleryContext.thumbs.set(item.id, url);
}
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
}
} catch (e) {
// ignore
// no-op
}
}
if (!fetching[item.dataIndex]) {
fetching[item.dataIndex] = true;
let url: string;
if (galleryContext.files.has(item.id)) {
url = galleryContext.files.get(item.id);
} else {
url = await DownloadManager.getFile(item, true);
galleryContext.files.set(item.id, url);
}
updateSrcUrl(item.dataIndex, url);
if (item.metadata.fileType === FILE_TYPE.VIDEO) {
try {
await new Promise((resolve, reject) => {
const video = document.createElement('video');
video.addEventListener('timeupdate', function () {
clearTimeout(t);
resolve(null);
});
video.preload = 'metadata';
video.src = url;
video.currentTime = 3;
const t = setTimeout(() => {
reject(
Error(
`${CustomError.VIDEO_PLAYBACK_FAILED} err: wait time exceeded`
)
);
}, WAIT_FOR_VIDEO_PLAYBACK);
});
item.html = `
<video width="320" height="240" controls>
<source src="${url}" />
Your browser does not support the video tag.
</video>
`;
delete item.src;
} catch (e) {
const downloadFile = async () => {
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = item.metadata.title;
document.body.appendChild(a);
a.click();
a.remove();
setOpen(false);
};
setDialogMessage({
title: constants.VIDEO_PLAYBACK_FAILED,
content:
constants.VIDEO_PLAYBACK_FAILED_DOWNLOAD_INSTEAD,
staticBackdrop: true,
proceed: {
text: constants.DOWNLOAD,
action: downloadFile,
variant: 'success',
},
close: {
text: constants.CLOSE,
action: () => setOpen(false),
},
});
return;
}
} else {
item.src = url;
}
item.w = window.innerWidth;
item.h = window.innerHeight;
try {
instance.invalidateCurrItems();
instance.updateSize(true);
fetching[item.dataIndex] = true;
let url: string;
if (galleryContext.files.has(item.id)) {
url = galleryContext.files.get(item.id);
} else {
url = await DownloadManager.getFile(item, true);
galleryContext.files.set(item.id, url);
}
await updateSrcUrl(item.dataIndex, url);
item.html = files[item.dataIndex].html;
item.src = files[item.dataIndex].src;
item.w = files[item.dataIndex].w;
item.h = files[item.dataIndex].h;
try {
instance.invalidateCurrItems();
instance.updateSize(true);
} catch (e) {
// ignore
}
} catch (e) {
// ignore
// no-op
} finally {
fetching[item.dataIndex] = false;
}
}
};
@ -515,7 +488,7 @@ const PhotoFrame = ({
return (
<>
{!isFirstLoad && files.length === 0 && !searchMode ? (
{!isFirstLoad && files.length === 0 && !isInSearchMode ? (
<EmptyScreen>
<img height={150} src="/images/gallery.png" />
<div style={{ color: '#a6a6a6', marginTop: '16px' }}>
@ -635,7 +608,7 @@ const PhotoFrame = ({
return sum;
})();
files.length < 30 &&
!searchMode &&
!isInSearchMode &&
timeStampList.push({
itemType: ITEM_TYPE.BANNER,
banner: (

View file

@ -7,16 +7,15 @@ import {
addToFavorites,
removeFromFavorites,
} from 'services/collectionService';
import { File, FILE_TYPE } from 'services/fileService';
import { File } from 'services/fileService';
import constants from 'utils/strings/constants';
import DownloadManger from 'services/downloadManager';
import exifr from 'exifr';
import Modal from 'react-bootstrap/Modal';
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';
import styled from 'styled-components';
import events from './events';
import { fileNameWithoutExtension, formatDateTime } from 'utils/file';
import { downloadFile, formatDateTime } from 'utils/file';
import { FormCheck } from 'react-bootstrap';
import { prettyPrintExif } from 'utils/exif';
@ -296,21 +295,11 @@ function PhotoSwipe(props: Iprops) {
setShowInfo(true);
};
const downloadFile = async (file) => {
const downloadFileHelper = async (file) => {
const { loadingBar } = props;
const a = document.createElement('a');
a.style.display = 'none';
loadingBar.current.continuousStart();
a.href = await DownloadManger.getFile(file);
await downloadFile(file);
loadingBar.current.complete();
if (file.metadata.fileType === FILE_TYPE.LIVE_PHOTO) {
a.download = fileNameWithoutExtension(file.metadata.title) + '.zip';
} else {
a.download = file.metadata.title;
}
document.body.appendChild(a);
a.click();
a.remove();
};
const { id } = props;
let { className } = props;
@ -344,7 +333,7 @@ function PhotoSwipe(props: Iprops) {
className="pswp-custom download-btn"
title={constants.DOWNLOAD}
onClick={() =>
downloadFile(photoSwipe.currItem)
downloadFileHelper(photoSwipe.currItem)
}
/>

View file

@ -10,6 +10,7 @@ import {
getYearSuggestion,
parseHumanDate,
searchCollection,
searchFiles,
searchLocation,
} from 'services/searchService';
import { getFormattedDate } from 'utils/search';
@ -20,6 +21,9 @@ import SearchIcon from './icons/SearchIcon';
import CrossIcon from './icons/CrossIcon';
import { Collection } from 'services/collectionService';
import CollectionIcon from './icons/CollectionIcon';
import { File, FILE_TYPE } from 'services/fileService';
import ImageIcon from './icons/ImageIcon';
import VideoIcon from './icons/VideoIcon';
const Wrapper = styled.div<{ isDisabled: boolean; isOpen: boolean }>`
position: fixed;
@ -74,6 +78,8 @@ export enum SuggestionType {
DATE,
LOCATION,
COLLECTION,
IMAGE,
VIDEO,
}
export interface DateValue {
date?: number;
@ -94,6 +100,7 @@ interface Props {
searchStats: SearchStats;
collections: Collection[];
setActiveCollection: (id: number) => void;
files: File[];
}
export default function SearchBar(props: Props) {
const [value, setValue] = useState<Suggestion>(null);
@ -112,14 +119,14 @@ export default function SearchBar(props: Props) {
if (!searchPhrase?.length) {
return [];
}
const option = [
const options = [
...getHolidaySuggestion(searchPhrase),
...getYearSuggestion(searchPhrase),
];
const searchedDates = parseHumanDate(searchPhrase);
option.push(
options.push(
...searchedDates.map((searchedDate) => ({
type: SuggestionType.DATE,
value: searchedDate,
@ -131,7 +138,7 @@ export default function SearchBar(props: Props) {
searchPhrase,
props.collections
);
option.push(
options.push(
...collectionResults.map(
(searchResult) =>
({
@ -141,8 +148,20 @@ export default function SearchBar(props: Props) {
} as Suggestion)
)
);
const fileResults = searchFiles(searchPhrase, props.files);
options.push(
...fileResults.map((file) => ({
type:
file.type === FILE_TYPE.IMAGE
? SuggestionType.IMAGE
: SuggestionType.VIDEO,
value: file.index,
label: file.title,
}))
);
const locationResults = await searchLocation(searchPhrase);
option.push(
options.push(
...locationResults.map(
(searchResult) =>
({
@ -152,7 +171,7 @@ export default function SearchBar(props: Props) {
} as Suggestion)
)
);
return option;
return options;
};
const getOptions = debounce(getAutoCompleteSuggestions, 250);
@ -161,7 +180,6 @@ export default function SearchBar(props: Props) {
if (!selectedOption) {
return;
}
switch (selectedOption.type) {
case SuggestionType.DATE:
props.setSearch({
@ -177,12 +195,17 @@ export default function SearchBar(props: Props) {
break;
case SuggestionType.COLLECTION:
props.setActiveCollection(selectedOption.value as number);
resetSearch(true);
setValue(null);
break;
case SuggestionType.IMAGE:
case SuggestionType.VIDEO:
props.setSearch({ fileIndex: selectedOption.value as number });
setValue(null);
break;
}
};
const resetSearch = async (force?: boolean) => {
if (props.isOpen || force) {
const resetSearch = () => {
if (props.isOpen) {
props.loadingBar.current?.continuousStart();
props.setSearch({});
setTimeout(() => {
@ -205,6 +228,10 @@ export default function SearchBar(props: Props) {
return <LocationIcon />;
case SuggestionType.COLLECTION:
return <CollectionIcon />;
case SuggestionType.IMAGE:
return <ImageIcon />;
case SuggestionType.VIDEO:
return <VideoIcon />;
default:
return <SearchIcon />;
}

View file

@ -0,0 +1,21 @@
import React from 'react';
export default function ImageIcon(props) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
height={props.height}
viewBox={props.viewBox}
width={props.width}
fill="currentColor">
<path d="M0 0h24v24H0V0z" fill="none" />
<path d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4.86 8.86l-3 3.87L9 13.14 6 17h12l-3.86-5.14z" />
</svg>
);
}
ImageIcon.defaultProps = {
height: 24,
width: 24,
viewBox: '0 0 24 24',
};

View file

@ -0,0 +1,20 @@
import React from 'react';
export default function VideoIcon(props) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
height={props.height}
viewBox={props.viewBox}
width={props.width}
fill="currentColor">
<path d="M4 6.47L5.76 10H20v8H4V6.47M22 4h-4l2 4h-3l-2-4h-2l2 4h-3l-2-4H8l2 4H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4z" />
</svg>
);
}
VideoIcon.defaultProps = {
height: 24,
width: 24,
viewBox: '0 0 24 24',
};

View file

@ -35,7 +35,7 @@ interface CollectionProps {
syncWithRemote: () => Promise<void>;
setCollectionNamerAttributes: SetCollectionNamerAttributes;
startLoadingBar: () => void;
searchMode: boolean;
isInSearchMode: boolean;
collectionFilesCount: Map<number, number>;
}
@ -87,6 +87,11 @@ const Chip = styled.button<{ active: boolean }>`
}
`;
const Hider = styled.div<{ hide: boolean }>`
opacity: ${(props) => (props.hide ? '0' : '100')};
height: ${(props) => (props.hide ? '0' : 'auto')};
`;
export default function Collections(props: CollectionProps) {
const { activeCollection, collections, setActiveCollection } = props;
const [selectedCollectionID, setSelectedCollectionID] =
@ -119,7 +124,7 @@ export default function Collections(props: CollectionProps) {
useEffect(() => {
updateScrollObj();
}, [collectionWrapperRef.current]);
}, [collectionWrapperRef.current, props.isInSearchMode]);
useEffect(() => {
if (!collectionWrapperRef?.current) {
@ -184,111 +189,104 @@ export default function Collections(props: CollectionProps) {
};
return (
!props.searchMode && (
<>
<CollectionShare
show={collectionShareModalView}
onHide={() => setCollectionShareModalView(false)}
collection={getSelectedCollection(
selectedCollectionID,
props.collections
<Hider hide={props.isInSearchMode}>
<CollectionShare
show={collectionShareModalView}
onHide={() => setCollectionShareModalView(false)}
collection={getSelectedCollection(
selectedCollectionID,
props.collections
)}
syncWithRemote={props.syncWithRemote}
/>
<CollectionBar>
<CollectionContainer>
{scrollObj.scrollLeft > 0 && (
<NavigationButton
scrollDirection={SCROLL_DIRECTION.LEFT}
onClick={scrollCollection(SCROLL_DIRECTION.LEFT)}
/>
)}
syncWithRemote={props.syncWithRemote}
/>
<CollectionBar>
<CollectionContainer>
{scrollObj.scrollLeft > 0 && (
<NavigationButton
scrollDirection={SCROLL_DIRECTION.LEFT}
onClick={scrollCollection(
SCROLL_DIRECTION.LEFT
)}
<Wrapper
ref={collectionWrapperRef}
onScroll={updateScrollObj}>
<Chip
active={activeCollection === ALL_SECTION}
onClick={clickHandler(ALL_SECTION)}>
{constants.ALL}
<div
style={{
display: 'inline-block',
width: '24px',
}}
/>
)}
<Wrapper
ref={collectionWrapperRef}
onScroll={updateScrollObj}>
<Chip
active={activeCollection === ALL_SECTION}
onClick={clickHandler(ALL_SECTION)}>
{constants.ALL}
<div
style={{
display: 'inline-block',
width: '24px',
}}
/>
</Chip>
{sortCollections(
collections,
props.collectionAndTheirLatestFile,
collectionSortBy
).map((item) => (
<OverlayTrigger
key={item.id}
placement="top"
delay={{ show: 250, hide: 400 }}
overlay={renderTooltip(item.id)}>
<Chip
ref={collectionChipsRef[item.id]}
active={activeCollection === item.id}
onClick={clickHandler(item.id)}>
{item.name}
{item.type !==
CollectionType.favorites &&
item.owner.id === user?.id ? (
<OverlayTrigger
rootClose
trigger="click"
placement="bottom"
overlay={collectionOptions}>
<OptionIcon
onClick={() =>
setSelectedCollectionID(
item.id
)
}
/>
</OverlayTrigger>
) : (
<div
style={{
display: 'inline-block',
width: '24px',
}}
</Chip>
{sortCollections(
collections,
props.collectionAndTheirLatestFile,
collectionSortBy
).map((item) => (
<OverlayTrigger
key={item.id}
placement="top"
delay={{ show: 250, hide: 400 }}
overlay={renderTooltip(item.id)}>
<Chip
ref={collectionChipsRef[item.id]}
active={activeCollection === item.id}
onClick={clickHandler(item.id)}>
{item.name}
{item.type !== CollectionType.favorites &&
item.owner.id === user?.id ? (
<OverlayTrigger
rootClose
trigger="click"
placement="bottom"
overlay={collectionOptions}>
<OptionIcon
onClick={() =>
setSelectedCollectionID(
item.id
)
}
/>
)}
</Chip>
</OverlayTrigger>
))}
<Chip
active={activeCollection === ARCHIVE_SECTION}
onClick={clickHandler(ARCHIVE_SECTION)}>
{constants.ARCHIVE}
<div
style={{
display: 'inline-block',
width: '24px',
}}
/>
</Chip>
</Wrapper>
{scrollObj.scrollLeft <
scrollObj.scrollWidth - scrollObj.clientWidth && (
<NavigationButton
scrollDirection={SCROLL_DIRECTION.RIGHT}
onClick={scrollCollection(
SCROLL_DIRECTION.RIGHT
)}
</OverlayTrigger>
) : (
<div
style={{
display: 'inline-block',
width: '24px',
}}
/>
)}
</Chip>
</OverlayTrigger>
))}
<Chip
active={activeCollection === ARCHIVE_SECTION}
onClick={clickHandler(ARCHIVE_SECTION)}>
{constants.ARCHIVE}
<div
style={{
display: 'inline-block',
width: '24px',
}}
/>
)}
</CollectionContainer>
<CollectionSort
setCollectionSortBy={setCollectionSortBy}
activeSortBy={collectionSortBy}
/>
</CollectionBar>
</>
)
</Chip>
</Wrapper>
{scrollObj.scrollLeft <
scrollObj.scrollWidth - scrollObj.clientWidth && (
<NavigationButton
scrollDirection={SCROLL_DIRECTION.RIGHT}
onClick={scrollCollection(SCROLL_DIRECTION.RIGHT)}
/>
)}
</CollectionContainer>
<CollectionSort
setCollectionSortBy={setCollectionSortBy}
activeSortBy={collectionSortBy}
/>
</CollectionBar>
</Hider>
);
}

View file

@ -128,15 +128,19 @@ export default function PreviewCard(props: IProps) {
useLayoutEffect(() => {
if (file && !file.msrc) {
const main = async () => {
const url = await DownloadManager.getPreview(file);
if (isMounted.current) {
setImgSrc(url);
thumbs.set(file.id, url);
file.msrc = url;
if (!file.src) {
file.src = url;
try {
const url = await DownloadManager.getPreview(file);
if (isMounted.current) {
setImgSrc(url);
thumbs.set(file.id, url);
file.msrc = url;
if (!file.src) {
file.src = url;
}
updateUrl(url);
}
updateUrl(url);
} catch (e) {
// no-op
}
};

View file

@ -79,12 +79,33 @@ const GlobalStyles = createGlobalStyle`
height: 100%;
}
.video-loading > div {
.video-loading > div.spinner-border {
position: relative;
top: -50vh;
left: 50vw;
}
.video-loading > div.download-message {
position: relative;
top: -60vh;
left: 0;
height: 16vh;
padding:2vh 0;
background-color: #151414;
color:#ddd;
display: flex;
flex-direction:column;
align-items: center;
justify-content: space-around;
opacity: 0.8;
font-size:20px;
}
.download-message > a{
width: 130px;
}
:root {
--primary: #e26f99,
};

View file

@ -109,6 +109,7 @@ export type setSearchStats = React.Dispatch<React.SetStateAction<SearchStats>>;
export type Search = {
date?: DateValue;
location?: Bbox;
fileIndex?: number;
};
export interface SearchStats {
resultCount: number;
@ -162,6 +163,7 @@ export default function Gallery() {
const [search, setSearch] = useState<Search>({
date: null,
location: null,
fileIndex: null,
});
const [uploadInProgress, setUploadInProgress] = useState(false);
const {
@ -177,7 +179,7 @@ export default function Gallery() {
});
const loadingBar = useRef(null);
const [searchMode, setSearchMode] = useState(false);
const [isInSearchMode, setIsInSearchMode] = useState(false);
const [searchStats, setSearchStats] = useState(null);
const syncInProgress = useRef(true);
const resync = useRef(false);
@ -187,11 +189,6 @@ export default function Gallery() {
useState<Map<number, number>>();
const [activeCollection, setActiveCollection] = useState<number>(undefined);
const [isSharedCollectionActive, setIsSharedCollectionActive] =
useState(false);
const [isFavCollectionActive, setIsFavCollectionActive] = useState(false);
useEffect(() => {
const key = getKey(SESSION_KEYS.ENCRYPTION_KEY);
if (!key) {
@ -249,14 +246,6 @@ export default function Gallery() {
}
const href = `/gallery${collectionURL}`;
router.push(href, undefined, { shallow: true });
setIsSharedCollectionActive(
isSharedCollection(activeCollection, collections)
);
setIsFavCollectionActive(
isFavoriteCollection(activeCollection, collections)
);
}, [activeCollection]);
const syncWithRemote = async (force = false, silent = false) => {
@ -456,8 +445,9 @@ export default function Gallery() {
}
};
const updateSearch = (search: Search) => {
setSearch(search);
const updateSearch = (newSearch: Search) => {
setActiveCollection(ALL_SECTION);
setSearch(newSearch);
setSearchStats(null);
};
@ -503,11 +493,12 @@ export default function Gallery() {
attributes={dialogMessage}
/>
<SearchBar
isOpen={searchMode}
setOpen={setSearchMode}
isOpen={isInSearchMode}
setOpen={setIsInSearchMode}
loadingBar={loadingBar}
isFirstFetch={isFirstFetch}
collections={collections}
files={files}
setActiveCollection={setActiveCollection}
setSearch={updateSearch}
searchStats={searchStats}
@ -515,7 +506,7 @@ export default function Gallery() {
<Collections
collections={collections}
collectionAndTheirLatestFile={collectionsAndTheirLatestFile}
searchMode={searchMode}
isInSearchMode={isInSearchMode}
activeCollection={activeCollection}
setActiveCollection={setActiveCollection}
syncWithRemote={syncWithRemote}
@ -582,13 +573,16 @@ export default function Gallery() {
isFirstLoad={isFirstLoad}
openFileUploader={openFileUploader}
loadingBar={loadingBar}
searchMode={searchMode}
isInSearchMode={isInSearchMode}
search={search}
setSearchStats={setSearchStats}
deleted={deleted}
setDialogMessage={setDialogMessage}
activeCollection={activeCollection}
isSharedCollection={isSharedCollectionActive}
isSharedCollection={isSharedCollection(
activeCollection,
collections
)}
/>
{selected.count > 0 &&
selected.collectionID === activeCollection && (
@ -628,7 +622,10 @@ export default function Gallery() {
count={selected.count}
clearSelection={clearSelection}
activeCollection={activeCollection}
isFavoriteCollection={isFavCollectionActive}
isFavoriteCollection={isFavoriteCollection(
activeCollection,
collections
)}
/>
)}
</FullScreenDropZone>

View file

@ -23,7 +23,6 @@ export enum CollectionType {
}
const COLLECTION_UPDATION_TIME = 'collection-updation-time';
const FAV_COLLECTION = 'fav-collection';
const COLLECTIONS = 'collections';
export interface Collection {
@ -345,7 +344,11 @@ export const addToFavorites = async (file: File) => {
'Favorites',
CollectionType.favorites
);
await localForage.setItem(FAV_COLLECTION, favCollection);
const localCollections = await getLocalCollections();
await localForage.setItem(COLLECTIONS, [
...localCollections,
favCollection,
]);
}
await addToCollection(favCollection, [file]);
} catch (e) {

View file

@ -24,7 +24,7 @@ class DownloadManager {
return URL.createObjectURL(await cacheResp.blob());
}
if (!this.thumbnailObjectUrlPromise.get(file.id)) {
const downloadPromise = this._downloadThumb(
const downloadPromise = this.downloadThumb(
token,
thumbnailCache,
file
@ -35,10 +35,11 @@ class DownloadManager {
} catch (e) {
this.thumbnailObjectUrlPromise.delete(file.id);
logError(e, 'get preview Failed');
throw e;
}
}
_downloadThumb = async (
private downloadThumb = async (
token: string,
thumbnailCache: Cache,
file: File
@ -67,26 +68,29 @@ class DownloadManager {
};
getFile = async (file: File, forPreview = false) => {
let fileUID: string;
if (file.metadata.fileType === FILE_TYPE.VIDEO) {
fileUID = file.id.toString();
} else {
fileUID = `${file.id}_forPreview=${forPreview}`;
}
try {
const getFilePromise = (async () => {
const getFilePromise = async () => {
const fileStream = await this.downloadFile(file);
let fileBlob = await new Response(fileStream).blob();
if (forPreview) {
fileBlob = await convertForPreview(file, fileBlob);
}
return URL.createObjectURL(fileBlob);
})();
if (!this.fileObjectUrlPromise.get(`${file.id}_${forPreview}`)) {
this.fileObjectUrlPromise.set(
`${file.id}_${forPreview}`,
getFilePromise
);
};
if (!this.fileObjectUrlPromise.get(fileUID)) {
this.fileObjectUrlPromise.set(fileUID, getFilePromise());
}
return await this.fileObjectUrlPromise.get(
`${file.id}_${forPreview}`
);
return await this.fileObjectUrlPromise.get(fileUID);
} catch (e) {
this.fileObjectUrlPromise.delete(fileUID);
logError(e, 'Failed to get File');
throw e;
}
};

View file

@ -44,8 +44,8 @@ class FFmpegService {
async function generateThumbnailHelper(ffmpeg: FFmpeg, file: File) {
try {
const inputFileName = `${Date.now().toString}-${file.name}`;
const thumbFileName = `${Date.now().toString}-thumb.png`;
const inputFileName = `${Date.now().toString()}-${file.name}`;
const thumbFileName = `${Date.now().toString()}-thumb.jpeg`;
ffmpeg.FS(
'writeFile',
inputFileName,
@ -62,6 +62,8 @@ async function generateThumbnailHelper(ffmpeg: FFmpeg, file: File) {
`00:00:0${seekTime.toFixed(3)}`,
'-vframes',
'1',
'-vf',
'scale=-1:720',
thumbFileName
);
thumb = ffmpeg.FS('readFile', thumbFileName);

View file

@ -4,6 +4,9 @@ import { getToken } from 'utils/common/key';
import { DateValue, Suggestion, SuggestionType } from 'components/SearchBar';
import HTTPService from './HTTPService';
import { Collection } from './collectionService';
import { File } from './fileService';
import { User } from './userService';
import { getData, LS_KEYS } from 'utils/storage/localStorage';
const ENDPOINT = getEndpoint();
const DIGITS = new Set(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']);
@ -110,3 +113,25 @@ export function searchCollection(
collection.name.toLowerCase().includes(searchPhrase)
);
}
export function searchFiles(searchPhrase: string, files: File[]) {
const user: User = getData(LS_KEYS.USER) ?? {};
const idSet = new Set();
return files
.map((file, idx) => ({
title: file.metadata.title,
index: idx,
type: file.metadata.fileType,
ownerID: file.ownerID,
id: file.id,
}))
.filter((file) => {
if (file.ownerID === user.id && !idSet.has(file.id)) {
idSet.add(file.id);
return true;
}
return false;
})
.filter(({ title }) => title.toLowerCase().includes(searchPhrase))
.slice(0, 4);
}

View file

@ -3,13 +3,21 @@ import { CustomError, errorWithContext } from 'utils/common/errorUtil';
import { logError } from 'utils/sentry';
import { BLACK_THUMBNAIL_BASE64 } from '../../../public/images/black-thumbnail-b64';
import FFmpegService from 'services/ffmpegService';
import { convertToHumanReadable } from 'utils/billingUtil';
const THUMBNAIL_HEIGHT = 720;
const MAX_ATTEMPTS = 3;
const MIN_THUMBNAIL_SIZE = 50000;
const MAX_THUMBNAIL_DIMENSION = 720;
const MIN_COMPRESSION_PERCENTAGE_SIZE_DIFF = 10;
export const MAX_THUMBNAIL_SIZE = 100 * 1024;
const MIN_QUALITY = 0.5;
const MAX_QUALITY = 0.7;
const WAIT_TIME_THUMBNAIL_GENERATION = 10 * 1000;
interface Dimension {
width: number;
height: number;
}
export async function generateThumbnail(
worker,
file: globalThis.File,
@ -26,7 +34,12 @@ export async function generateThumbnail(
} else {
try {
const thumb = await FFmpegService.generateThumbnail(file);
return { thumbnail: thumb, hasStaticThumbnail: false };
const dummyImageFile = new File([thumb], file.name);
canvas = await generateImageThumbnail(
worker,
dummyImageFile,
isHEIC
);
} catch (e) {
canvas = await generateVideoThumbnail(file);
}
@ -74,16 +87,22 @@ export async function generateImageThumbnail(
await new Promise((resolve, reject) => {
image.onload = () => {
try {
const thumbnailWidth =
(image.width * THUMBNAIL_HEIGHT) / image.height;
canvas.width = thumbnailWidth;
canvas.height = THUMBNAIL_HEIGHT;
const imageDimension = {
width: image.width,
height: image.height,
};
const thumbnailDimension = calculateThumbnailDimension(
imageDimension,
MAX_THUMBNAIL_DIMENSION
);
canvas.width = thumbnailDimension.width;
canvas.height = thumbnailDimension.height;
canvasCTX.drawImage(
image,
0,
0,
thumbnailWidth,
THUMBNAIL_HEIGHT
thumbnailDimension.width,
thumbnailDimension.height
);
image = null;
clearTimeout(timeout);
@ -126,16 +145,22 @@ export async function generateVideoThumbnail(file: globalThis.File) {
if (!video) {
throw Error('video load failed');
}
const thumbnailWidth =
(video.videoWidth * THUMBNAIL_HEIGHT) / video.videoHeight;
canvas.width = thumbnailWidth;
canvas.height = THUMBNAIL_HEIGHT;
const videoDimension = {
width: video.videoWidth,
height: video.videoHeight,
};
const thumbnailDimension = calculateThumbnailDimension(
videoDimension,
MAX_THUMBNAIL_DIMENSION
);
canvas.width = thumbnailDimension.width;
canvas.height = thumbnailDimension.height;
canvasCTX.drawImage(
video,
0,
0,
thumbnailWidth,
THUMBNAIL_HEIGHT
thumbnailDimension.width,
thumbnailDimension.height
);
video = null;
clearTimeout(timeout);
@ -166,11 +191,14 @@ export async function generateVideoThumbnail(file: globalThis.File) {
}
async function thumbnailCanvasToBlob(canvas: HTMLCanvasElement) {
let thumbnailBlob = null;
let attempts = 0;
let quality = 1;
let thumbnailBlob: Blob = null;
let prevSize = Number.MAX_SAFE_INTEGER;
let quality = MAX_QUALITY;
do {
if (thumbnailBlob) {
prevSize = thumbnailBlob.size;
}
thumbnailBlob = await new Promise((resolve) => {
canvas.toBlob(
function (blob) {
@ -181,12 +209,49 @@ async function thumbnailCanvasToBlob(canvas: HTMLCanvasElement) {
);
});
thumbnailBlob = thumbnailBlob ?? new Blob([]);
attempts++;
quality /= 2;
quality -= 0.1;
} while (
thumbnailBlob.size > MIN_THUMBNAIL_SIZE &&
attempts <= MAX_ATTEMPTS
quality >= MIN_QUALITY &&
thumbnailBlob.size > MAX_THUMBNAIL_SIZE &&
percentageSizeDiff(thumbnailBlob.size, prevSize) >=
MIN_COMPRESSION_PERCENTAGE_SIZE_DIFF
);
if (thumbnailBlob.size > MAX_THUMBNAIL_SIZE) {
logError(
Error('thumbnail_too_large'),
'thumbnail greater than max limit',
{ thumbnailSize: convertToHumanReadable(thumbnailBlob.size) }
);
}
return thumbnailBlob;
}
function percentageSizeDiff(
newThumbnailSize: number,
oldThumbnailSize: number
) {
return ((oldThumbnailSize - newThumbnailSize) * 100) / oldThumbnailSize;
}
// method to calculate new size of image for limiting it to maximum width and height, maintaining aspect ratio
// returns {0,0} for invalid inputs
function calculateThumbnailDimension(
originalDimension: Dimension,
maxDimension: number
): Dimension {
if (originalDimension.height === 0 || originalDimension.width === 0) {
return { width: 0, height: 0 };
}
const widthScaleFactor = maxDimension / originalDimension.width;
const heightScaleFactor = maxDimension / originalDimension.height;
const scaleFactor = Math.min(widthScaleFactor, heightScaleFactor);
const thumbnailDimension = {
width: Math.round(originalDimension.width * scaleFactor),
height: Math.round(originalDimension.height * scaleFactor),
};
if (thumbnailDimension.width === 0 || thumbnailDimension.height === 0) {
return { width: 0, height: 0 };
}
return thumbnailDimension;
}

View file

@ -11,6 +11,7 @@ import {
import { decodeMotionPhoto } from 'services/motionPhotoService';
import { getMimeTypeFromBlob } from 'services/upload/readFileService';
import { EncryptionResult } from 'services/upload/uploadService';
import DownloadManger from 'services/downloadManager';
import { logError } from 'utils/sentry';
import { User } from 'services/userService';
import CryptoWorker from 'utils/crypto';
@ -36,6 +37,20 @@ export function downloadAsFile(filename: string, content: string) {
a.remove();
}
export async function downloadFile(file) {
const a = document.createElement('a');
a.style.display = 'none';
a.href = await DownloadManger.getFile(file);
if (file.metadata.fileType === FILE_TYPE.LIVE_PHOTO) {
a.download = fileNameWithoutExtension(file.metadata.title) + '.zip';
} else {
a.download = file.metadata.title;
}
document.body.appendChild(a);
a.click();
a.remove();
}
export function fileIsHEIC(mimeType: string) {
return (
mimeType.toLowerCase().endsWith(TYPE_HEIC) ||

View file

@ -0,0 +1,15 @@
const WAIT_FOR_VIDEO_PLAYBACK = 1 * 1000;
export async function isPlaybackPossible(url: string): Promise<boolean> {
return await new Promise((resolve) => {
const t = setTimeout(() => {
resolve(false);
}, WAIT_FOR_VIDEO_PLAYBACK);
const video = document.createElement('video');
video.addEventListener('canplay', function () {
clearTimeout(t);
resolve(true);
});
video.src = url;
});
}

View file

@ -9,7 +9,7 @@ export const logError = (
) => {
const err = errorWithContext(e, msg);
if (!process.env.NEXT_PUBLIC_SENTRY_ENV) {
console.log(err);
console.log(e);
}
Sentry.captureException(err, {
level: Sentry.Severity.Info,
@ -18,6 +18,7 @@ export const logError = (
...(info && {
info: info,
}),
rootCause: { message: e?.message },
},
});
};