Files
no-copy-frontend/src/app/components/section-search-file.tsx
T

498 lines
14 KiB
TypeScript
Raw Normal View History

2026-01-26 18:42:12 +07:00
'use client'
import { useRef, useState, useCallback, ChangeEvent, DragEvent, useEffect, useMemo } from 'react';
2026-01-27 19:52:01 +07:00
import { IconSearch } from '@/app/ui/icons/icons';
2026-01-26 18:42:12 +07:00
import { fileUpload, cancelUpload, chunkUpload, checkChunkStatus } from '@/app/actions/fileUpload';
import { useTranslations } from 'next-intl';
import { useNavigationBlocker } from '@/app/hooks/useNavigationBlocker';
import { useQueryClient } from '@tanstack/react-query';
2026-01-27 19:52:01 +07:00
import { searchUserFiles, removeUserFile, searchGlobalFiles } from '@/app/actions/fileEntity';
import { SearchedUserFilesList } from '@/app/ui/search/searched-user-files-list';
import { SearchedGlobalFilesList } from '@/app/ui/search/searched-global-files-list';
import { useRouter } from 'next/navigation';
2026-01-26 18:42:12 +07:00
interface SelectedFile {
file: File;
preview: string | undefined;
name: string;
size: string;
}
interface FileUploadInitResponse {
upload_id: string,
file_name: string,
total_chunks: number,
chunk_size: number,
status: string
}
interface SectionSearchFile {
fileType: string
allowedExtensions: string[]
maxFileSize: number
}
export default function SectionSearchFile({ fileType, allowedExtensions, maxFileSize }: SectionSearchFile) {
const fileInputRef = useRef<HTMLInputElement>(null);
const [isDragging, setIsDragging] = useState<boolean>(false);
const [selectedFile, setSelectedFile] = useState<SelectedFile | null>(null);
const [error, setError] = useState<string | null>(null);
const [uploadId, setUploadId] = useState<string | null>(null);
const [isFileUploaded, setIsFileUploaded] = useState<boolean>(false);
const [uploadProgress, setUploadProgress] = useState<number>(0);
2026-01-27 19:52:01 +07:00
const [fileId, setFileId] = useState<string | null>(null);
const [searchedUserFiles, setSearchedUserFiles] = useState<string[]>([]);
const [searchedGlobalFiles, setSearchedGlobalFiles] = useState<string[]>([]);
2026-01-26 18:42:12 +07:00
const queryClient = useQueryClient();
const isCancelledRef = useRef(false);
const t = useTranslations('Global');
const acceptString = useMemo(() => {
if (!allowedExtensions || !Array.isArray(allowedExtensions)) {
return '';
}
return allowedExtensions.map(e => `.${e}`).join(', ');
}, [allowedExtensions]);
const validateFile = (file: File): { isValid: boolean; errorMessage?: string } => {
if (!allowedExtensions.includes(file.type as string)) {
const extension = file.name.split('.').pop()?.toLowerCase();
if (!extension || !allowedExtensions.includes(extension as string)) {
return {
isValid: false,
errorMessage: t('unsupported-file-format')
};
}
}
const MAX_SIZE = maxFileSize;
if (file.size > MAX_SIZE) {
return {
isValid: false,
errorMessage: t('the-file-is-too-large')
};
}
return { isValid: true };
};
const handleFileSelect = useCallback(async (file: File | null): Promise<void> => {
if (!file) {
setError(null);
return;
}
2026-01-27 19:52:01 +07:00
if (fileId) {
await removeUserFile(fileId, 1);
setFileId(null);
}
2026-01-26 18:42:12 +07:00
setError(null);
setIsFileUploaded(false);
2026-01-27 19:52:01 +07:00
setSearchedUserFiles([]);
setSearchedGlobalFiles([]);
2026-01-26 18:42:12 +07:00
setUploadProgress(0);
const validation = validateFile(file);
if (!validation.isValid) {
setError(validation.errorMessage || t('unknown-validation-error'));
return;
}
setSelectedFile({
file,
name: file.name,
size: `${(file.size / 1024 / 1024).toFixed(2)} MB`,
preview: file.size < 10 * 1024 * 1024 ? URL.createObjectURL(file) : undefined
});
2026-01-27 19:52:01 +07:00
handlerFileUpload({
file,
name: file.name,
size: `${(file.size / 1024 / 1024).toFixed(2)} MB`,
preview: file.size < 10 * 1024 * 1024 ? URL.createObjectURL(file) : undefined
});
2026-01-26 18:42:12 +07:00
}, [fileType, t]);
const handleFileInputChange = (event: ChangeEvent<HTMLInputElement>): void => {
const file = event.target.files?.[0] || null;
handleFileSelect(file);
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
};
const handleButtonClick = (): void => {
if (fileInputRef.current) {
fileInputRef.current.click();
}
};
const handleDragOver = (event: DragEvent<HTMLDivElement>): void => {
event.preventDefault();
setIsDragging(true);
};
const handleDragLeave = (): void => {
setIsDragging(false);
};
const handleDrop = (event: DragEvent<HTMLDivElement>): void => {
event.preventDefault();
setIsDragging(false);
const file = event.dataTransfer.files[0];
handleFileSelect(file);
};
const handleClearFile = async (): Promise<void> => {
if (selectedFile && selectedFile.preview) {
URL.revokeObjectURL(selectedFile.preview);
}
if (uploadId) {
await cancelUpload(uploadId);
}
isCancelledRef.current = true;
setIsFileUploaded(false);
setSelectedFile(null);
setError(null);
setUploadProgress(0);
};
const handlerFileUpload = useCallback(async (fileInfo: SelectedFile): Promise<void> => {
if (uploadId) return;
setError(null);
isCancelledRef.current = false;
const file = fileInfo.file;
try {
const extension = file.name.split('.').pop() || '';
const initMessageBody = {
file_name: file.name,
file_type: fileType,
extension: extension,
file_size: file.size
};
const response = await fileUpload(initMessageBody) as FileUploadInitResponse;
if (!response?.upload_id) {
throw new Error('Failed to get upload_id');
}
const CHUNK_SIZE = response.chunk_size;
const totalChunks = response.total_chunks;
setUploadId(response.upload_id);
for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
if (isCancelledRef.current) {
return;
}
2026-01-27 19:52:01 +07:00
const isLastChunk = chunkIndex === totalChunks - 1;
2026-01-26 18:42:12 +07:00
const start = chunkIndex * CHUNK_SIZE;
const end = Math.min(start + CHUNK_SIZE, file.size);
const chunk = file.slice(start, end);
const formData = new FormData();
formData.append('upload_id', response.upload_id);
formData.append('chunk_number', chunkIndex.toString());
formData.append('chunk', chunk);
2026-01-27 19:52:01 +07:00
formData.append('findSimilar', '1');
2026-01-26 18:42:12 +07:00
const chunkResponse = await chunkUpload(formData);
if (chunkResponse.message_desc !== 'Chunk uploaded successfully') {
throw new Error(`Chunk ${chunkIndex} upload failed`);
}
setUploadProgress(Math.floor((chunkIndex + 1) / totalChunks * 100));
2026-01-27 19:52:01 +07:00
if (isLastChunk) {
setFileId(chunkResponse.message_body.file_id);
document.cookie = `searchedFileId=${chunkResponse.message_body.file_id}`
}
2026-01-26 18:42:12 +07:00
}
const chunkStatus = await checkChunkStatus(response.upload_id);
if (chunkStatus.message_body.missing_chunks === 0) {
setIsFileUploaded(true);
await queryClient.invalidateQueries({ queryKey: ['userFilesData'] });
await queryClient.invalidateQueries({ queryKey: ['userFilesInfo'] });
} else {
throw new Error('Not all chunks were uploaded');
}
} catch (error) {
if (!isCancelledRef.current) {
setError(t('error-uploading-file'));
console.error('Upload error:', error);
}
} finally {
setUploadId(null);
}
2026-01-27 19:52:01 +07:00
}, [uploadId, fileType]);
2026-01-26 18:42:12 +07:00
useEffect(() => {
// Обработка закрытия вкладки
// Тут можно попробовать изучить вопрос с navigator.sendBeacon('', blob)
// он нужен для того что бы послать запрос на бек при закрытии вкладки,
// но у него есть свои особенности и стандартные запросы не работают.
const handleUnload = () => {
if (uploadId) {
//const data = JSON.stringify({ uploadId, reason: 'tab_closed' });
//const blob = new Blob([data], { type: 'application/json' });
//navigator.sendBeacon('/api/v1/data/cancel', blob);
console.log('sendBeacon');
}
};
if (uploadId) {
window.addEventListener('unload', handleUnload);
}
return () => {
window.removeEventListener('unload', handleUnload);
};
}, [uploadId]);
useNavigationBlocker({
shouldBlock: !!uploadId,
message: t('have-unsaved-changes'),
onConfirm: async () => {
console.log('User confirmed navigation');
if (uploadId) {
await cancelUpload(uploadId);
}
},
onCancel: () => {
console.log('User cancelled navigation');
}
});
2026-01-27 19:52:01 +07:00
const handlerSearchUserFile = useCallback(async (fileId: string): Promise<void> => {
try {
let result = await searchUserFiles(fileId);
if (result.content.length) {
setSearchedUserFiles(result.content);
}
} catch (error) {
}
}, [fileId])
const handlerSearchGlobalFile = useCallback(async (fileId: string): Promise<void> => {
try {
let result = await searchGlobalFiles(fileId);
if (result.images.length) {
setSearchedGlobalFiles(result.images);
}
} catch (error) {
}
}, [fileId])
2026-01-26 18:42:12 +07:00
return (
<div className="upload-section">
2026-01-27 19:52:01 +07:00
<div className="search-info">
<div className="search-info-title">Как работает поиск?</div>
<div className="search-info-text">
Наша система анализирует загруженный файл и сравнивает его с вашими защищенными файлами,
используя алгоритмы компьютерного зрения и цифровых отпечатков.
</div>
</div>
2026-01-26 18:42:12 +07:00
<div
className={`drag-drop-zone ${isDragging ? 'dragging' : ''}`}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
2026-01-27 19:52:01 +07:00
<IconSearch />
2026-01-26 18:42:12 +07:00
<h4>
2026-01-27 19:52:01 +07:00
Выберите файл для поиска
2026-01-26 18:42:12 +07:00
</h4>
<input
ref={fileInputRef}
type="file"
accept={acceptString}
style={{ display: 'none' }}
onChange={handleFileInputChange}
aria-label="Выбор файла для защиты"
/>
<button
className="btn btn-primary"
onClick={handleButtonClick}
type="button"
>
2026-01-27 19:52:01 +07:00
Выбрать файл
2026-01-26 18:42:12 +07:00
</button>
{error && (
<div className="mt-4 p-3 bg-red-50 border border-red-200 rounded-lg">
<p className="text-red-600 font-medium">{error}</p>
</div>
)}
{selectedFile && (
<div
2026-01-27 19:52:01 +07:00
className={`selected-file`}
2026-01-26 18:42:12 +07:00
>
2026-01-27 19:52:01 +07:00
<div className="selected-file-file-info relative">
2026-01-26 18:42:12 +07:00
<div>
<p className="text-gray-700">
<span className="font-medium">
{t('file')}:
</span> {selectedFile.name}
</p>
<p className="text-gray-700">
<span className="font-medium">
{t('size')}:
</span> {selectedFile.size}
</p>
</div>
{uploadProgress !== 0 && (
<div
2026-01-27 19:52:01 +07:00
className={`absolute top-0 right-0 font-medium ${isFileUploaded ? "text-green-600" : ""}`}
2026-01-26 18:42:12 +07:00
>
{uploadProgress}%
</div>
)}
</div>
</div>
)}
</div>
2026-01-27 19:52:01 +07:00
{isFileUploaded && (
<>
<div
className="mb-4"
>
<button
className="btn btn-primary btn-search"
/* disabled={fileId ? false : true} */
onClick={() => {
if (fileId) {
handlerSearchUserFile(fileId)
}
}}
>
Начать поиск
</button>
</div>
{(searchedUserFiles.length !== 0) && (
<SearchedUserFilesList list={searchedUserFiles} />
)}
<div
className="global-search-section"
>
<div className="global-search-header">
<div className="global-search-title">
Глобальный поиск изображений
</div>
<div className="">
Найти где ещё используется ваше изображение в интернете
</div>
<div className="global-search-badge">
Интернет поиск
</div>
</div>
<div className="global-search-content">
<div className="global-search-info">
<div className="global-search-info-title">
Поиск по всему интернету
</div>
<div className="global-search-info-text">
Используем продвинутые технологии обратного поиска по изображению для поиска копий вашего контента
на сайтах, в социальных сетях и других источниках. Поможет обнаружить несанкционированное использование.
</div>
</div>
<div className="search-counter" id="search-counter">
<div className="counter-info">
<div className="counter-icon" id="counter-icon"></div>
<div className="counter-text">
<div className="counter-label">Глобальных поисков сегодня</div>
<div className="counter-value" id="counter-value">0 из 10</div>
</div>
</div>
<div className="progress-bar">
<div
className="progress-fill"
id="progress-fill"
style={{ width: '0%' }}
>
</div>
</div>
</div>
<button
type="button"
className="global-search-btn"
id="global-search-btn"
onClick={() => {
if (fileId) {
handlerSearchGlobalFile(fileId)
}
}}
>
Найти в интернете
</button>
<div className="global-loading" id="global-loading">
<div className="global-spinner"></div>
<div className="global-loading-text" id="global-loading-text">
Поиск изображений в интернете...
</div>
</div>
<div className={`global-result ${searchedGlobalFiles.length ? 'show' : ''}`} id="global-result">
<div className="global-result-card">
<div className="global-result-header">
<span>Найдено в интернете</span>
</div>
<div className="global-result-content">
<SearchedGlobalFilesList list={searchedGlobalFiles} />
</div>
</div>
</div>
<div className="global-no-result" id="global-no-result">
<div className="global-no-result-icon">&zwj;</div>
<h4>Похожие изображения в интернете не найдены</h4>
<p>Это может означать, что ваше изображение уникально и не используется на других сайтах.</p>
</div>
<div className="global-error" id="global-error">
<strong>Ошибка глобального поиска:</strong>
<span id="global-error-text"></span>
</div>
</div>
</div>
</>
)}
2026-01-26 18:42:12 +07:00
</div>
);
}