From b55af040822ce34f212712d8e09cd0e1abf98c9f Mon Sep 17 00:00:00 2001 From: icechen Date: Wed, 2 Mar 2022 04:52:36 +0800 Subject: [PATCH] update --- package.json | 1 + src/component/homeButton/index.tsx | 103 ++++++++++++++++++++++++++++- src/index.tsx | 29 ++++++++ src/pages/dashboard/index.tsx | 71 +++++++++++++++----- src/storage.ts | 12 +++- src/store.ts | 7 +- src/store/fileList.ts | 14 ++-- src/telegram/telegram.ts | 25 ++++--- yarn.lock | 2 +- 9 files changed, 220 insertions(+), 44 deletions(-) diff --git a/package.json b/package.json index 00bd3aa..5f57864 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "@types/node": "^16.11.25", "@types/react": "^17.0.39", "@types/react-dom": "^17.0.11", + "filesize": "^8.0.7", "mtproton": "6.0.0", "react": "^17.0.2", "react-dom": "^17.0.2", diff --git a/src/component/homeButton/index.tsx b/src/component/homeButton/index.tsx index 9fe6c68..0ca1c30 100644 --- a/src/component/homeButton/index.tsx +++ b/src/component/homeButton/index.tsx @@ -1,7 +1,19 @@ import style from "./style.module.css"; -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { Close } from "@mui/icons-material"; -import { IconButton } from "@mui/material"; +import { + Button, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + IconButton, +} from "@mui/material"; +import fileSize from "filesize"; +import SendIcon from "@mui/icons-material/Send"; +import { inputFile, sendFile, uploadBigFile } from "../../telegram/telegram"; +import { useDispatch } from "react-redux"; +import { addFileOfStorage } from "../../store/fileList"; enum Status { normal, @@ -18,6 +30,11 @@ export function HomeButton(props: Props) { let [status, setStatus] = useState(Status.normal); let [boxStyle, setBoxStyle] = useState([style.box]); let [isReceive, setIsReceive] = useState(false); + let [waitedFileList, setWaitedFileList] = useState([]); + let [uploadRatio, setUploadRatio] = useState(0); + let [isFinish, setIsFinish] = useState(false); + const dispatch = useDispatch(); + let onNormal = () => { setStatus(Status.normal); }; @@ -42,6 +59,43 @@ export function HomeButton(props: Props) { } }, [status]); + let addFileInput = useRef(null); + + let OnChangeFileInput = (e: any) => { + setWaitedFileList(e.target.files); + }; + + let handleFileUpload = () => { + setUploadRatio(1); + const reader = new FileReader(); + reader.onload = function (event) { + if (event.target && event.target.result) { + let bytes = event.target.result; + uploadBigFile(bytes as ArrayBuffer, setUploadRatio) + .then((file) => { + console.log("uploadFile ret:", file); + sendFile( + // @ts-ignore + inputFile(file.file_id, file.total_part, waitedFileList[0].name), + waitedFileList[0].type + ).then((result) => { + console.log("sendFile ret:", result); + result.updates[1].message.media.document.file_name = + waitedFileList[0].name; + dispatch( + addFileOfStorage(result.updates[1].message.media.document) + ); + setIsFinish(true); + }); + }) + .catch((error) => { + console.log("uploadFile error:", error); + alert(error); + }); + } + }; + reader.readAsArrayBuffer(waitedFileList[0]); + }; return (
{!isReceive ? ( @@ -51,8 +105,15 @@ export function HomeButton(props: Props) { className={style.addFile} onMouseEnter={onAddFile} onMouseLeave={onNormal} + onClick={() => addFileInput.current?.click()} > 添加文件 +
+ {uploadRatio === 0 && ( + + )} + + ); } diff --git a/src/index.tsx b/src/index.tsx index cdade08..9adac48 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -1,3 +1,5 @@ +// @ts-nocheck + import React from "react"; import ReactDOM from "react-dom"; import reportWebVitals from "./reportWebVitals"; @@ -6,6 +8,33 @@ import { BrowserRouter, Routes, Route } from "react-router-dom"; import Home from "./pages/home"; import { Provider } from "react-redux"; import store from "./store"; +import { updateOfStorage } from "./store/fileList"; + +store.dispatch(updateOfStorage()); + +Date.prototype.Format = function (fmt) { + var o = { + "M+": this.getMonth() + 1, //月份 + "d+": this.getDate(), //日 + "h+": this.getHours(), //小时 + "m+": this.getMinutes(), //分 + "s+": this.getSeconds(), //秒 + "q+": Math.floor((this.getMonth() + 3) / 3), //季度 + S: this.getMilliseconds(), //毫秒 + }; + if (/(y+)/.test(fmt)) + fmt = fmt.replace( + RegExp.$1, + (this.getFullYear() + "").substr(4 - RegExp.$1.length) + ); + for (var k in o) + if (new RegExp("(" + k + ")").test(fmt)) + fmt = fmt.replace( + RegExp.$1, + RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length) + ); + return fmt; +}; ReactDOM.render( diff --git a/src/pages/dashboard/index.tsx b/src/pages/dashboard/index.tsx index b484ba2..32d1f30 100644 --- a/src/pages/dashboard/index.tsx +++ b/src/pages/dashboard/index.tsx @@ -15,6 +15,9 @@ import { TableRow, } from "@mui/material"; import MoreHorizIcon from "@mui/icons-material/MoreHoriz"; +import { useSelectorFileList } from "../../store/fileList"; +import fileSize from "filesize"; +import { downloadFile } from "../../telegram/telegram"; enum ContentType { File, @@ -56,14 +59,34 @@ function Login() { function File() { let [anchorEl, setAnchorEl] = useState(null); + let [waitDownloadFile, setWaitDownloadFile] = useState(null); + let fileList = useSelectorFileList(); + const open = Boolean(anchorEl); - let handleClick = (event: React.MouseEvent) => { - setAnchorEl(event.currentTarget); + let handleClick = (index: number) => { + return (event: React.MouseEvent) => { + console.log("index", index); + setWaitDownloadFile(fileList[index]); + setAnchorEl(event.currentTarget); + }; }; let handleClose = () => { setAnchorEl(null); }; + + let Download = () => { + // @ts-ignore + console.log("waitDownloadFile", waitDownloadFile?.file_name); + downloadFile(waitDownloadFile) + .then((res) => { + console.log("res", res); + }) + .catch((error) => { + console.log("download error:", error); + alert(error); + }); + }; return (
- + @@ -84,19 +107,33 @@ function File() { - - - xxx - - - - - 2020-01-01 12:12:12 - 128MB - + {fileList.map((item: any, index: number) => { + return ( + + + {item.attributes[0].file_name} + + + + + + { + // @ts-ignore + new Date(item.date * 1000).Format("yyyy-MM-dd hh:mm:ss") + } + + {fileSize(item.size)} + + ); + })}
@@ -107,7 +144,7 @@ function File() { anchorEl={anchorEl} onClose={handleClose} > - 下载 + 下载 分享 重命名 diff --git a/src/storage.ts b/src/storage.ts index fd349c1..aa66707 100644 --- a/src/storage.ts +++ b/src/storage.ts @@ -9,11 +9,19 @@ function getLocalStorage() { }, setObject(key: string, value: any) { + console.log("setObject", key, value); return window.localStorage.setItem(key, JSON.stringify(value)); }, - getObject(key: string) { - return JSON.parse(window.localStorage.getItem(key)?.toString() || "{}"); + getObject(key: string, defaultValue?: any) { + let value = window.localStorage.getItem(key); + if (value) { + return JSON.parse(value); + } + if (defaultValue) { + return defaultValue; + } + return {}; }, }; } diff --git a/src/store.ts b/src/store.ts index b5433ac..1908134 100644 --- a/src/store.ts +++ b/src/store.ts @@ -1,8 +1,13 @@ -import { configureStore } from "@reduxjs/toolkit"; +import { configureStore, getDefaultMiddleware } from "@reduxjs/toolkit"; import userReducer from "./store/user"; +import fileListReducer from "./store/fileList"; export default configureStore({ reducer: { user: userReducer, + fileList: fileListReducer, }, + middleware: getDefaultMiddleware({ + serializableCheck: false, + }), }); diff --git a/src/store/fileList.ts b/src/store/fileList.ts index 32cfcd7..1c283a9 100644 --- a/src/store/fileList.ts +++ b/src/store/fileList.ts @@ -4,18 +4,16 @@ import storage from "../storage"; const FileList = createSlice({ name: "fileList", - initialState: { - fileList: [], - }, + initialState: [] as any[], reducers: { updateOfStorage: (state) => { - state.fileList = storage().getObject("fileList"); + state = storage().getObject("fileList", []); + return state; }, addFileOfStorage: (state, action) => { - // @ts-ignore - state.fileList.push(action.payload); - storage().setObject("fileList", state.fileList); + state.push(action.payload); + storage().setObject("fileList", state); }, }, }); @@ -24,6 +22,6 @@ export function useSelectorFileList() { return useSelector((state: any) => state.fileList); } -export const { updateOfStorage } = FileList.actions; +export const { updateOfStorage, addFileOfStorage } = FileList.actions; export default FileList.reducer; diff --git a/src/telegram/telegram.ts b/src/telegram/telegram.ts index eb70391..25eba17 100644 --- a/src/telegram/telegram.ts +++ b/src/telegram/telegram.ts @@ -16,7 +16,7 @@ class TelegramHelper { this.client = new Client({ api_id: appID, api_hash: appHash, - test: true, + test: false, }); } else { let createTransport = function (dc: any, crypto: any) { @@ -86,7 +86,8 @@ class TelegramHelper { } async function uploadBigFile( - bytes: ArrayBuffer + bytes: ArrayBuffer, + callback?: (ratio: number) => void ): Promise<{ file_id: number; total_part: number }> { let file_id = rand_id(); console.log("file_id", file_id); @@ -109,10 +110,8 @@ async function uploadBigFile( file_total_parts: file_total_parts, bytes: tempBytes, }); - if (finished) { - console.log("finished"); - } else { - console.log("not finished"); + if (callback) { + callback(((i + 1) / file_total_parts) * 100); } } catch (error) { return Promise.reject(error); @@ -157,7 +156,7 @@ function sendFile(inputFile: any, type: string) { async function downloadFile(fileDocument: any) { let partSize = 1024 * 1024; - const file_total_parts = Math.ceil(fileDocument.document.size / partSize); + const file_total_parts = Math.ceil(fileDocument.size / partSize); let results = []; for (let i = 0; i < file_total_parts; i++) { @@ -165,9 +164,9 @@ async function downloadFile(fileDocument: any) { let result = await Telegram.call("upload.getFile", { location: { _: "inputDocumentFileLocation", - id: fileDocument.document.id, - access_hash: fileDocument.document.access_hash, - file_reference: fileDocument.document.file_reference, + id: fileDocument.id, + access_hash: fileDocument.access_hash, + file_reference: fileDocument.file_reference, thumb_size: "", }, limit: partSize, @@ -181,7 +180,7 @@ async function downloadFile(fileDocument: any) { } console.log("messages.getDocument:", results); - let bytes = new Uint8Array(fileDocument.document.size); + let bytes = new Uint8Array(fileDocument.size); for (let i = 0; i < results.length; i++) { for (let j = 0; j < results[i].bytes.length; j++) { bytes[i * partSize + j] = results[i].bytes[j]; @@ -190,12 +189,12 @@ async function downloadFile(fileDocument: any) { let downloadBytes = bytes; console.log("downloadBytes", downloadBytes); let blob = new Blob([downloadBytes], { - type: fileDocument.document.mime_type, + type: fileDocument.mime_type, }); let url = window.URL.createObjectURL(blob); let a = document.createElement("a"); a.href = url; - a.download = fileDocument.document.attributes[0].file_name; + a.download = fileDocument.file_name; a.click(); return Promise.resolve(true); } diff --git a/yarn.lock b/yarn.lock index 80ac4ee..d8cf6ec 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4440,7 +4440,7 @@ filelist@^1.0.1: dependencies: minimatch "^3.0.4" -filesize@^8.0.6: +filesize@^8.0.6, filesize@^8.0.7: version "8.0.7" resolved "https://registry.yarnpkg.com/filesize/-/filesize-8.0.7.tgz#695e70d80f4e47012c132d57a059e80c6b580bd8" integrity sha512-pjmC+bkIF8XI7fWaH8KxHcZL3DPybs1roSKP4rKDvy20tAWwIObE4+JIseG2byfGKhud5ZnM4YSGKBz7Sh0ndQ==