File size: 2,543 Bytes
a0fda44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import { useState, useEffect } from "react";
import { useDispatch } from "react-redux";
import { chatActions } from "../store/chatSlice";
import { notificationActions } from "../store/notificationSlice";
import useFetch from "./useFetch";

const useUpload = (fn, formatsAllowed) => {
  const [base64Format, setBase64Format] = useState();
  const [fileType, setFileType] = useState();
  const [extraFileData, setExtraFileData] = useState();
  const dispatch = useDispatch();

  //   Convert file to base64
  const fileToBase64 = (file) => {
    const reader = new FileReader();

    reader.readAsDataURL(file);

    reader.onloadend = () => {
      setBase64Format(reader.result);
    };
  };

  //   Handle file being added to form
  const handleFileUpload = (event) => {
    // Get file
    const file = event.target.files[0];

    setExtraFileData(event.target.extraFileData);

    // Restrict to only files less than 50mb
    const limit = 51200000;

    if (file.size > limit) {
      dispatch(
        notificationActions.addNotification({
          message: "File too large",
          type: "error",
        })
      );
      return;
    }

    // Restrict to only allowed formats
    if (
      !formatsAllowed.some((format) =>
        file.type.toLowerCase().startsWith(format.toLowerCase())
      )
    ) {
      const errorMessage = formatsAllowed.reduce((finalStr, currStr, index) => {
        if (!index) return finalStr;
        else {
          return finalStr + ` or ${currStr}`;
        }
      }, `${formatsAllowed[0]}`);

      dispatch(
        notificationActions.addNotification({
          message: `Only ${errorMessage} allowed`,
          type: "error",
        })
      );

      return;
    }

    const fileTypeStr = file.type.split("/")[0].toLowerCase();
    setFileType(fileTypeStr);
    dispatch(chatActions.setMode({ mode: `${fileTypeStr}Upload` }));

    // Convert file
    fileToBase64(file);
  };

  // Upload file to cloud
  const { reqFn: uploadToCloud, reqState: fileUploadState } = useFetch(
    { method: "POST", url: "/upload" },
    (data) => {
      fn({ ...data.data.uploadData, extraFileData });
      setBase64Format("");
    },
    () => {
      dispatch(chatActions.resetMode());
    }
  );

  useEffect(() => {
    if (base64Format) {
      uploadToCloud({
        data: base64Format,
        fileType: fileType === "audio" ? "video" : fileType,
      });
    }
  }, [base64Format]);

  return {
    handleFileUpload,
    fileUploadState,
    uploadToCloud,
  };
};

export default useUpload;