Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
5.5 kB
1
Indexable
Never
import React, { useState, useEffect } from 'react';
import db from './firebase-config';
import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
import { Button, Container, Grid, Typography, CircularProgress, Snackbar } from '@mui/material';
import MuiAlert from '@mui/material/Alert';
import './App.css';
import ErrorPage from './components/ErrorPage';
import Watermark from './components/Watermark';
import CircularProgressWithLabel from './components/CircularProgressWithLabel';
import FileLoadingIndicator from './components/FileLoadingIndicator';
import Modal from './components/Modal';

const STORAGE_PATH = 'uploads/';
const PREVIEW_PATH = 'previews/';
const FILES_COLLECTION = 'files';

const App = () => {
  const [isUsers, setUsers] = useState([]);
  const [isLoading, setLoading] = useState(false);
  const [isSnackbarOpen, setSnackbarOpen] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");
  const [uploadProgress, setUploadProgress] = useState(0);
  const [currentFileIndex, setCurrentFileIndex] = useState(0);
  const [totalFiles, setTotalFiles] = useState(1);
  const [fileControl, setFileControl] = useState(0);
  const [progressControl, setProgressControl] = useState(0);
  const [finalProgress, setFinalProgress] = useState([]);
  const [sumControl, setSumControl] = useState(0);
  const [isModalOpen, setModalOpen] = useState(false);
  const [modalItem, setModalItem] = useState(null);
  const [sessionId, setSessionId] = useState('');

  // Generate a unique session ID
  useEffect(() => {
    const uniqueSessionId = `session_${Date.now()}_${Math.floor(Math.random() * 1000000)}`;
    setSessionId(uniqueSessionId);
  }, []);

  useEffect(() => {
    // Fetch and display files tied to the current sessionId
    const query = db.collection(FILES_COLLECTION)
                    .where('sessionId', '==', sessionId)
                    .orderBy('datetime', 'desc');

    const unsubscribe = query.onSnapshot(snapshot => {
      setUsers(snapshot.docs.map(doc => ({
        id: doc.id,
        title: doc.data().title,
        image: doc.data().images,
        preview: doc.data().preview,
        datetime: doc.data().datetime,
        type: doc.data().type
      })));
    });

    return () => unsubscribe();
  }, [sessionId]);

  useEffect(() => {
    if (sumControl) {
      const sum = finalProgress.reduce((a, b) => a + b, 0);
      setUploadProgress(sum / totalFiles);
    }
  }, [sumControl, finalProgress, totalFiles]);

  useEffect(() => {
    if (fileControl) {
      setCurrentFileIndex(index => index + 1);
    }
  }, [fileControl]);

  useEffect(() => {
    if (progressControl) {
      setFinalProgress(progress => {
        progress[progressControl.index] = progressControl.value;
        return progress;
      });
      setSumControl(new Date().getUTCMilliseconds());
    }
  }, [progressControl]);

  const handleCloseSnackBar = (event, reason) => {
    if (reason === 'clickaway') {
      return;
    }
    setSnackbarOpen(false);
  };

  const openModal = (item) => {
    setModalItem(item);
    setModalOpen(true);
  };

  const closeModal = () => {
    setModalOpen(false);
    setModalItem(null);
  };

  const addList = async (e) => {
    try {
      const storage = getStorage();
      setLoading(true);
      const filesLocal = Array.from(e.target.files);
      setTotalFiles(filesLocal.length);

      const uploadPromises = filesLocal.map(async (file, index) => {
        const storagePath = STORAGE_PATH + file.name;
        const storageRef = ref(storage, storagePath);
        const uploadTask = uploadBytesResumable(storageRef, file);

        return new Promise((resolve, reject) => {
          uploadTask.on('state_changed', (snapshot) => {
            const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            setProgressControl({ index, "value": progress });
          },
          (error) => {
            console.log(`Error uploading ${file.name}:`, error);
            setProgressControl({ index, "value": 100 });
            setFileControl(new Date().getUTCMilliseconds());
            setErrorMessage(error.message);
            setSnackbarOpen(true);
            resolve();
          },
          async () => {
            const downloadURL = await getDownloadURL(uploadTask.snapshot.ref);
            // Save file information to Firestore with the current sessionId
            db.collection(FILES_COLLECTION).add({
              title: file.name,
              images: downloadURL,
              datetime: firebase.firestore.FieldValue.serverTimestamp(),
              sessionId, // Include the sessionId with each upload
              type: file.type.startsWith('image/') ? 'image' : 'video'
            });
            setFileControl(new Date().getUTCMilliseconds());
            resolve();
          });
        });
      });

      await Promise.all(uploadPromises);
      setLoading(false);
    } catch (error) {
      console.error("Failed to upload files", error);
      setLoading(false);
    }
  };

  return (
    <div className="App" style={{ backgroundColor: "#a090a2", height: "100vh", overflowY: "auto" }}>
      {/* Snackbar, Modal, and other UI elements go here */}
      {/* Make sure to include the sessionId in your Firestore queries to ensure users only see their uploads */}
    </div>
  );
};

export default App;
Leave a Comment