import axios, { AxiosResponse } from "axios"; import nodepath from "path"; import eccrypto from "eccrypto"; import Hash from "ipfs-only-hash"; import WebTorrent, { Torrent } from "webtorrent"; import parseTorrent from "parse-torrent"; import { saveAs } from "file-saver"; import { deletePathFromProjectId, addToLocalStorage } from "./IndexedDB"; import { axiosInstance } from "./service"; import { getRoot, getFileHandle, writeFile } from "./FileSystem"; import { openOrCreateDB, add, getLastId, getList } from "./IndexedDB"; import { ENDPOINT_VERSION } from "./const"; import { endpoint as ENDPOINT, webseedUrl as WEBSEED_URL } from "./service"; import { publicToAddress } from "@ethereumjs/util"; import formatDistance from "date-fns/formatDistance"; import { wallet } from "./wallet"; export const client = new WebTorrent(); export const FILE_TYPE = { TORRENT: "application/x-bittorrent", DEFAULT: "application/octet-stream", }; export const UPLOAD_TYPE = ["UNENCRYPTED", "ENCRYPT"]; export type UploadType = (typeof UPLOAD_TYPE)[number]; export interface BufferTorrent extends Buffer { infoHash?: string; magnetURI?: Uint8Array; name?: string; size?: number; } export interface BufferData extends Buffer { name?: string; } export interface GetUploadUrlConfig { path: string; filename: string; contentLength: number; contentType: string; method: UploadType; cidFile: string; cidTorrentFile: string; action?: string; keepPath?: boolean; } export interface UploadUrl { uploadFileUrl: string; webseed: string[]; uploadTorrentUrl: string; filePath: string; cidTorrentFile: string; cidFile: string; contentType: string; contentLength: number; filename: string; keepPath: boolean; action: string; method: UploadType; } type Omit = Pick>; interface UploadOptions { file: File; path: string[]; // Path file projectId: string; uploadType: UploadType; inFolder: boolean; exportedKey?: string; // Need if encrypt onUploadProgress: () => void; // Progress upload file, account: string; } export interface UploadFileOptions extends UploadOptions { isLargeFile?: boolean; chunkSize?: number; uploadUrl?: UploadUrl; // must be ignored when upload single file callback?: ( bufferData: BufferData, webseed: string[], account: string ) => void; // callback must be ignored when upload single file } interface UploadFileWithSignedUrlOptions { uploadUrl: string; uploadTorrentUrl: string; exportedKey?: string; //Need if encrypt } export interface UploadFolderOptions extends Omit { files: FileList | File[]; } interface FileForShare { fileId: string; encryptKey: string; } interface Keys { masterKey: CryptoKey; iv: any; } export const uploadFolder = async ( token: string, publicKey: string, account: string, options: UploadFolderOptions ) => { const { path, projectId, uploadType, exportedKey, onUploadProgress, inFolder, } = options; let { files } = options; files = Array.from(files).filter((file: File) => file.name !== ".DS_Store"); const resUploadFolder = await Promise.all( files.map(async (file) => { const splitString = file.webkitRelativePath.split("/"); splitString.pop(); const multiPath = splitString.length ? "/" + splitString.join("/") : ""; const PATH = path.length === 1 ? splitString.join("/") : path.slice(1).join("/") + multiPath; const formData = new FormData(); formData.append("file", file); const resUploadFile = await uploadFile(token, publicKey, { file, uploadType, projectId, onUploadProgress, account, path: [PATH], inFolder: inFolder, exportedKey, isLargeFile: file.size >= 20 * 1024 * 1024, //20MB, chunkSize: 5 * 1024 * 1024, //5MB }); if (resUploadFile.data.msg === "success") { return resUploadFile.data.data; } }) ); return resUploadFolder; }; export const uploadFile = async ( token: string, publicKey: string, options: UploadFileOptions ) => { const { exportedKey, file, path, projectId, uploadType, inFolder, account, onUploadProgress, isLargeFile, chunkSize, } = options; const fileType = getFileType(file.name, file.type); let bufferData: BufferData; let key, iv, keyData; // create buffer data and encrypt key if (uploadType === UPLOAD_TYPE[1]) { key = await genKeyFromExportKey(exportedKey); if (!key) { return; } iv = window.crypto.getRandomValues(new Uint8Array(12)); bufferData = await getBufferDataEncrypt(file, iv, key); keyData = await encryptKey(key, iv, publicKey); } else { bufferData = await getBufferData(file); } const cidFile: string = await Hash.of(bufferData); const webseed = [`${WEBSEED_URL}${cidFile}`]; const torrent: Torrent = await seed(bufferData, webseed); if (!torrent) throw "Error: Torrent wrong"; await saveFile(bufferData, webseed, account); const cidTorrentFile: string = await Hash.of(torrent.torrentFile); const pathList = [ { path: inFolder ? path.join("") : path.slice(1).join("/"), filename: file.name, keepPath: false, contentLength: file.size, contentType: fileType, method: uploadType, cidFile: cidFile, cidTorrentFile: cidTorrentFile, }, ]; if (path.length === 1 && !inFolder) delete pathList[0].path; // upload with signature const listUrl = await getUploadUrls(projectId, pathList, token); if (!listUrl[0].uploadFileUrl) throw "Get upload urls error!"; return listUrl[0]; // create formDataTorrent to use in uploadFileTorrent const formDataTorrent = new FormData(); const fileNameTorrent = listUrl[0].filename + ".torrent"; formDataTorrent.append( "data", new Blob([torrent.torrentFile]), fileNameTorrent ); const uploadFileTorrentResponse: AxiosResponse = await upload( formDataTorrent, listUrl[0].uploadTorrentUrl, FILE_TYPE.TORRENT, torrent.torrentFile, onUploadProgress ); if (uploadFileTorrentResponse.status !== 200) { throw "Error, please try later!"; } const storageContent = { name: bufferData.name, length: bufferData.byteLength, webseed: webseed, listUrl, type: fileType, account, key: keyData, }; addToLocalStorage(projectId, listUrl[0].filePath, storageContent); // create formData to use in uploadFile const formData = new FormData(); if (uploadType == UPLOAD_TYPE[1]) { formData.append("data", new Blob([bufferData]), listUrl[0].filename); } else { formData.append("file", file, listUrl[0].filename); } let uploadFileResponse: any; if (isLargeFile) { const size = chunkSize || 5 * 1024 * 1024; //5MB uploadFileResponse = await uploadResumable( file, size, listUrl[0].uploadFileUrl, uploadType, bufferData, onUploadProgress ); } else { uploadFileResponse = await upload( formData, listUrl[0].uploadFileUrl, fileType, bufferData, onUploadProgress ); } if (uploadFileResponse.status !== 200 && uploadFileResponse.status !== 201) { throw "Error, please try later!"; } let finalResponse: any; if (uploadType == UPLOAD_TYPE[0]) { await new Promise((resolve) => setTimeout(resolve, 1000)); finalResponse = await getFileByLongPath( projectId, false, listUrl[0].filePath, token ); deletePathFromProjectId(projectId, listUrl[0].filePath); } else { await new Promise((resolve) => setTimeout(resolve, 1000)); const res = await uploadKeyUpdate( projectId, listUrl[0].filePath, keyData, token ); if (res.status === 200) { finalResponse = await getFileByLongPath( projectId, true, listUrl[0].filePath, token ); deletePathFromProjectId(projectId, listUrl[0].filePath); } } return finalResponse; }; export const uploadFileWithSignedUrl = async ( file: File, options: UploadFileWithSignedUrlOptions ) => { const { uploadUrl, uploadTorrentUrl, exportedKey, //optional } = options; const fileType = getFileType(file.name, file.type); let bufferData: BufferData; let key, iv; // create buffer data and encrypt key if (exportedKey) { key = await genKeyFromExportKey(exportedKey); if (!key) { return; } iv = window.crypto.getRandomValues(new Uint8Array(12)); bufferData = await getBufferDataEncrypt(file, iv, key); } else { bufferData = await getBufferData(file); } const cidFile: string = await Hash.of(bufferData); const webseed = [`${WEBSEED_URL}${cidFile}`]; const torrent: Torrent = await seed(bufferData, webseed); if (!torrent) throw "Error: Torrent wrong"; // create formDataTorrent to use in uploadFileTorrent const formDataTorrent = new FormData(); const fileNameTorrent = file.name + ".torrent"; formDataTorrent.append( "data", new Blob([torrent.torrentFile]), fileNameTorrent ); const uploadFileTorrentResponse: AxiosResponse = await upload( formDataTorrent, uploadTorrentUrl, FILE_TYPE.TORRENT, torrent.torrentFile ); if (uploadFileTorrentResponse.status !== 200) { throw "Error, please try later!"; } // create formData to use in uploadFile const formData = new FormData(); if (exportedKey) { formData.append("data", new Blob([bufferData]), file.name); } else { formData.append("file", file, file.name); } let uploadFileResponse; if (file.size >= 20 * 1024 * 1024) { const chunkSize = 5 * 1024 * 1024; //5MB uploadFileResponse = await uploadResumable( file, chunkSize, uploadUrl, exportedKey ? UPLOAD_TYPE[1] : UPLOAD_TYPE[0], bufferData ); } else { uploadFileResponse = await upload( formData, uploadUrl, fileType, bufferData ); } console.log("uploadFileResponse", uploadFileResponse); if (uploadFileResponse.status !== 200 && uploadFileResponse.status !== 201) { throw "Error, please try later!"; } return uploadFileResponse; }; export const getFileByLongPath = async ( projectId: string, type: boolean, filePath: string, token ) => { const config = { method: "get", url: `${ENDPOINT}project-service/${ENDPOINT_VERSION}/files/uploaded?projectId=${projectId}&isEncrypt=${type}&filePath=${filePath}`, headers: { Authorization: "Bearer " + token, }, }; return axiosInstance(config); }; export const getUploadUrls = async ( projectId: string, config: GetUploadUrlConfig[], token: string ): Promise => { config[0].keepPath = false; config[0].action = "write"; const data = { projectId: projectId, pathLists: config, }; return axiosInstance .post(`sign-service/v1/project-file/auth-upload`, data, { headers: { Authorization: "Bearer " + token, }, }) .then((res) => { if (res.data.status === 200) return res.data.data; throw res.data.msg; }); }; const uploadResumable = async ( file: File, chunkSize: number, uploadFileUrl: string, uploadType: UploadType, bufferData: BufferData, onUploadProgress?: (progressEvent, name) => void ) => { const endpointUploadStatus = uploadFileUrl.replace( "upload?", "upload-resumable-status?" ); const requestStatus = await axios.request({ method: "get", maxBodyLength: Infinity, url: endpointUploadStatus, headers: {}, }); const fileChunkId = requestStatus.data.fileId; const partResumable = Math.floor( requestStatus.data.totalChunkUploaded / chunkSize ); const totalParts = Math.ceil(file.size / chunkSize); let response: any; for (let i = partResumable; i < totalParts; i++) { response = await uploadPart( file, fileChunkId, i, totalParts, uploadFileUrl, chunkSize, uploadType, bufferData, onUploadProgress ); } return response; }; const uploadPart = async ( file, filename, part, totalParts, link, chunkSize, uploadType, bufferData, onUploadProgress ) => { try { const endpointUpload = link.replace("upload?", "upload-resumable?"); const start = part * chunkSize; const end = (part + 1) * chunkSize; const formData = new FormData(); if (uploadType == UPLOAD_TYPE[1]) { formData.append( "file", new Blob([bufferData.slice(start, end)]), filename ); } else { formData.append("file", file.slice(start, end), filename); } const config = { headers: { "file-chunk-id": filename, "file-chunk-size": chunkSize, "Content-Range": `bytes ${start}-${end}/${file.size}`, "Content-Type": "multipart/form-data", }, onUploadProgress: (progressEvent) => { if (bufferData?.name) { const progress = { loaded: progressEvent.total ? part + progressEvent.loaded / progressEvent.total : part, total: totalParts, }; onUploadProgress(progress, bufferData?.name); } }, }; const res = await axios.post(endpointUpload, formData, config); return res; } catch (error) { console.log(error); return error; } }; const genKey = () => { return window.crypto.subtle.generateKey( { name: "AES-GCM", length: 256, }, true, ["encrypt", "decrypt"] ); }; const encryptKey = async ( key: CryptoKey, iv: Uint8Array, publicKey: string ) => { const exported = await window.crypto.subtle.exportKey("raw", key); const data = { iv: typeof iv === "string" ? iv : Buffer.from(iv).toString("hex"), key: Buffer.from(exported).toString("hex"), }; const selfEncrypted = await eccrypto.encrypt( Buffer.from(`${publicKey}`, "hex"), Buffer.from(JSON.stringify(data), "utf-8") ); const encryptedKey = `${selfEncrypted.ciphertext.toString( "hex" )}@@${selfEncrypted.ephemPublicKey.toString( "hex" )}@@${selfEncrypted.iv.toString("hex")}@@${selfEncrypted.mac.toString( "hex" )}`; return encryptedKey; }; const getBufferData = async (file: File) => { const buf = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => { resolve(reader.result); }; reader.onerror = reject; reader.readAsArrayBuffer(file); }); const bufferData: BufferData = Buffer.from( new Uint8Array(buf as ArrayBuffer) ); bufferData.name = file.name; return bufferData; }; const getBufferDataEncrypt = async ( file: File, iv: Uint8Array, key: CryptoKey ) => { const encryptedFile = await encryptFile(file, key, iv); const bufferData: BufferData = Buffer.from(new Uint8Array(encryptedFile)); bufferData.name = file.name; return bufferData; }; const encryptFile = async (file: File, key: CryptoKey, iv: Uint8Array) => { const blob = new Blob([file]); const arrayBuffer = await blob.arrayBuffer(); const encryptedData = await window.crypto.subtle.encrypt( { name: "AES-GCM", iv, }, key, arrayBuffer ); return encryptedData; }; export const upload = async ( formData: FormData, url: string, fileType: string, bufferData: BufferTorrent, onUploadProgress?: (progressEvent, name) => void ) => { const isTorrent = bufferData.name ? false : true; const config = { method: "POST", url, headers: { "Content-Type": "multipart/form-data", }, data: formData, onUploadProgress: (progressEvent) => { if (!bufferData?.name) return; if (!isTorrent) { onUploadProgress(progressEvent, bufferData?.name); } }, }; const res: AxiosResponse = await axios(config); return res; }; const seed = (buffer: BufferData, webseed: string[]): Promise => { return new Promise((resolve, reject) => { const torrent = client.seed( buffer, { private: true, announce: [ "wss://tracker.eueno.io", "https://tracker.eueno.io/announce", ], urlList: webseed, }, resolve ); torrent.on("error", reject); }); }; const saveFile = async (buffer: BufferData, url: string[], address: string) => { const db = await openOrCreateDB(); const lastId = await getLastId(db); const id = lastId !== undefined ? lastId + 1 : 1; const result = await saveFileToFileSystem(buffer, id); if (result) saveFileToDB(db, id, buffer.name, url, address); }; const saveFileToFileSystem = async (buffer: BufferData, id: number) => { try { const root = await getRoot(); const fileHandle = await getFileHandle(root, id.toString(), true); await writeFile(fileHandle, buffer); return true; } catch (error) { console.error(error); } }; const saveFileToDB = async ( db: IDBDatabase, id: number, name: string, url: string[], address: string ) => { try { add(db, name, id, address, url); } catch (error) { console.error(error); } }; // ---------------- Get file detail export const getDetailUnencryptedFile = async ( token: string, torrentUrl: string, onProcess?: (torrent, remaining) => void ) => { const response = await axios.request({ method: "GET", url: torrentUrl, responseType: "arraybuffer", }); const magnetURI = Buffer.from(response.data); const torrentInfo = parseTorrent(magnetURI); // const webseed = torrentInfo.urlList; const torrent = client.get(torrentInfo.infoHash); if (torrent) { return new Promise((resolve, reject) => { torrent.files[0].getBuffer(async (err, buffer) => { if (err) reject(err); const buf: BufferTorrent = Buffer.from(buffer); buf.name = torrent.files[0].name; buf.size = torrent.files[0].length; buf.magnetURI = magnetURI; buf.infoHash = torrent.infoHash; resolve(buf); }); }); } return new Promise((resolve, reject) => { client.add( magnetURI, { getAnnounceOpts: () => ({ jwt: token }), }, async (torrent) => { torrent .on("download", function () { let remaining; if (torrent.done) { remaining = "Preparing file ..."; } else { remaining = torrent.timeRemaining !== Infinity ? formatDistance(torrent.timeRemaining, 0, { includeSeconds: true, }) : "Infinity years"; remaining = remaining[0].toUpperCase() + remaining.substring(1) + " remaining."; } onProcess(torrent, remaining); }) .on("done", async function () { torrent.files[0].getBuffer(async (err, buffer) => { const buf: BufferTorrent = buffer; buf.name = torrent.files[0].name; buf.size = torrent.files[0].length; buf.magnetURI = magnetURI; buf.infoHash = torrent.infoHash; resolve(buf); }); }) .on("error", function (err) { console.log(err); reject(err); }); } ); }); }; export const getDetailEncryptedFile = async ( torrentUrl: any, key: string, //encryptedKey token: string, isShare: boolean, webSeed = undefined, //Array account = undefined, //string onProcess?: (torrent, remaining) => void, //function keys?: Keys ) => { try { // get symmetric key let masterKey, iv; if (keys?.masterKey) { masterKey = keys.masterKey; iv = keys.iv; } else { [masterKey, iv] = await getMasterKey(key); } const response = await axios.request({ method: "GET", url: torrentUrl, responseType: "arraybuffer", }); const magnetURI = Buffer.from(response.data); const torrentInfo = parseTorrent(magnetURI); // Check user already have file const check = client.get(torrentInfo.infoHash); if (check) { return new Promise((rs) => { check.files[0].getBuffer(async (_, buffer: any) => { if (isShare) { buffer.name = check.files[0].name; buffer.size = check.files[0].length; const db = await openOrCreateDB(); const listFiles = await getList(db, account); const arrFilter = listFiles.filter( (file) => file.url.length === webSeed.length && file.url.every( (value, index: number) => value === webSeed[index] ) ); if (!arrFilter.length) { saveFile(buffer, webSeed, account); } } const decryptData = await window.crypto.subtle.decrypt( { name: "AES-GCM", iv: Buffer.from(iv, "hex"), }, masterKey, Buffer.from(buffer) ); const buf: any = Buffer.from(decryptData); buf.name = check.files[0].name; buf.size = check.files[0].length; buf.magnetURI = magnetURI; rs(buf); }); }); } return new Promise((resolve, reject) => { client.add( magnetURI, { getAnnounceOpts: () => ({ jwt: token }), }, async (torrent) => { torrent .on("download", function () { let remaining; if (torrent.done) { remaining = "Preparing file ..."; } else { remaining = torrent.timeRemaining !== Infinity ? formatDistance(torrent.timeRemaining, 0, { includeSeconds: true, }) : "Infinity years"; remaining = remaining[0].toUpperCase() + remaining.substring(1) + " remaining."; } onProcess(torrent, remaining); }) .on("done", async function () { torrent.files[0].getBuffer(async (err, buffer: any) => { if (isShare) { buffer.name = torrent.files[0].name; buffer.size = torrent.files[0].length; const db = await openOrCreateDB(); const listFiles = await getList(db, account); if ( // CHECK DUPLICATE IN FILE SYSTEM !listFiles.filter( (file) => file.url.length === webSeed.length && file.url.every( (value, index) => value === webSeed[index] ) ).length ) { saveFile(buffer, webSeed, account); } } const decryptData = await window.crypto.subtle.decrypt( { name: "AES-GCM", iv: Buffer.from(iv, "hex"), }, masterKey, Buffer.from(buffer) ); const buf: any = Buffer.from(decryptData); buf.name = torrent.files[0].name; buf.size = torrent.files[0].length; buf.magnetURI = magnetURI; resolve(buf); }); }) .on("error", function (err) { reject(err); }); } ); }); } catch (error) { console.log(error); } }; export const getDetailMultiEncryptedFiles = async ( ids: Array | Array, token: string, isShare: boolean, account: string, onProcess?: (torrent, remaining) => void //function ) => { if (!ids.length) throw "List of id is required!"; let responseGetFiles: any; let fileList: any; if (isShare) { responseGetFiles = await getListShareWithMebyIds(ids); if (!responseGetFiles) throw "Get files detail error!"; fileList = responseGetFiles.data.data.map((item) => { const file = { encryptKey: item.encryptedKey, ownerAddress: item.ownerAddress, ...item.file, }; return file; }); } else { responseGetFiles = await getFileListById(ids); if (!responseGetFiles) throw "Get files detail error!"; fileList = responseGetFiles.data.data; } const listEncryptKey = fileList.map((file) => file.encryptKey); const listMasterKey = await getMultiMasterKey(listEncryptKey); const response = await Promise.all( fileList.map(async (file, id) => { const keys = { masterKey: listMasterKey[id].masterKey, iv: listMasterKey[id].iv, }; const webSeed = isShare ? [file.url, file.backupUrl] : null; const acc = isShare ? account : null; const bufferData = await getDetailEncryptedFile( file.torrentUrl, "", token, isShare, webSeed, acc, onProcess, keys ); return { ...file, bufferData }; }) ); if (!response) { throw "Get file detail error"; } return response; }; export const createFolder = async ( folderName: string, token: string, currentPathArray: string[] ) => { try { const path = currentPathArray.length === 1 ? "/" : "/" + currentPathArray.slice(1).join("/") + "/"; const data = { projectId: currentPathArray[0], path: path + folderName, }; const config = { method: "post", url: `${ENDPOINT}project-service/${ENDPOINT_VERSION}/files/folder`, headers: { Authorization: "Bearer " + token, }, data, }; return axios(config); } catch (error) { return error; } }; export const getDetailFile = async (id: string | number) => { try { const response = await getFileById(id); if (response?.data?.data.share) { const resData = response?.data?.data; const responseData = { ...resData.share, ...resData }; responseData.encryptKey = responseData.encryptedKey; delete responseData.encryptedKey; delete responseData.share; return responseData; } return response?.data?.data; } catch (error) { console.log(error); } }; export const getFileById = async (id: string | number, token?: string) => { // Get info file const config = { method: "get", url: `${ENDPOINT}project-service/${ENDPOINT_VERSION}/files/${id}`, headers: { Authorization: "Bearer " + token, }, }; return axiosInstance(config); }; export const getFileListById = async ( ids: Array | Array, token?: string ) => { const config = { method: "get", url: `${ENDPOINT}project-service/v1/files/list?ids=[${ids}]`, headers: { Authorization: "Bearer " + token, }, }; return axiosInstance(config); }; // ------------------ Delete export const deleteFile = async (file_id: string | number, token?: string) => { const config = { method: "delete", url: `${ENDPOINT}project-service/${ENDPOINT_VERSION}/files/${file_id}`, headers: { Authorization: "Bearer " + token, }, }; const res = await axiosInstance(config); return res; }; export const deleteFolder = async ( projectId: string, folderPath: string, token?: string ) => { const data = { projectId, folderPath, }; const config = { method: "delete", url: `${ENDPOINT}project-service/${ENDPOINT_VERSION}/files/folder`, data, headers: { Authorization: "Bearer " + token, }, }; const res = await axiosInstance(config); return res; }; //Delete --------------------------- export const downloadFile = async ( torrentUrl: string, token = "", onDownload: () => void ) => { try { const buffer: any = await getDetailUnencryptedFile( (token = ""), torrentUrl, onDownload ); const blobData = new Blob([buffer]); if (!blobData) { throw Error("Download: Invalid buffer"); } saveAs(blobData, buffer.name); // const file: any = new File([buffer], buffer.name); // await seed(file, token, webseed); } catch (error) { console.error(error); } }; // ---------------- Share export const shareFile = async ( toPublicKey: string, chosenId: string, fileType: UploadType ) => { try { // Get encrypted key const data = await getDetailFile(chosenId); const body = { fileId: chosenId, sharedUserAddress: convertPublicToAddress(toPublicKey), }; //Encrypted if (fileType.toUpperCase() === UPLOAD_TYPE[1]) { // Get symmetric key from encrypted key by decrypt with private key of account const [masterKey, iv] = await getMasterKey(data.encryptKey); // Create encrypt key with toPublicKey const encryptedKey = await encryptKey(masterKey, iv, toPublicKey); body["encryptedKey"] = encryptedKey; } // Call API await onShare(body); const res = { status: "success", data, }; return res; } catch (error) { console.log(error); return error; } }; export const shareMultiFile = async ( toPublicKey: string, fileList: Array, fileType: UploadType ) => { try { // Get encrypted key const sharedUserAddress = convertPublicToAddress(toPublicKey); //Encrypted let body; if (fileType.toUpperCase() === UPLOAD_TYPE[1]) { // Get symmetric key from encrypted key by decrypt with private key of account const listEncryptKey = fileList.map((file) => file.encryptKey); const listMasterKey = await getMultiMasterKey(listEncryptKey); const listEncryptedKeyForShare = await Promise.all( listMasterKey.map(async (key, id) => { const encryptedKey = await encryptKey( key.masterKey, key.iv, toPublicKey ); return encryptedKey; }) ); body = fileList.map((file, id) => ({ fileId: file.fileId, sharedUserAddress: sharedUserAddress, encryptedKey: listEncryptedKeyForShare[id], })); } else { body = fileList.map((file) => ({ fileId: file.fileId, sharedUserAddress: sharedUserAddress, })); } const shareResponse = await onShareMultiFile(body); const res = { status: "success", data: shareResponse, }; return res; } catch (error) { console.log(error); return error; } }; export const onShare = async (body: object, token?: string) => { try { const config = { method: "post", url: `${ENDPOINT}share-service/${ENDPOINT_VERSION}/shares`, headers: { Authorization: "Bearer " + token, "Content-Type": "application/json", }, data: body, }; return axiosInstance(config); } catch (error) { console.log(error); } }; export const onShareMultiFile = async (body: object, token?: string) => { try { const config = { method: "post", url: `${ENDPOINT}share-service/${ENDPOINT_VERSION}/shares/batch`, headers: { Authorization: "Bearer " + token, "Content-Type": "application/json", }, data: { data: body, }, }; return axiosInstance(config); } catch (error) { console.log(error); } }; const convertPublicToAddress = (publicKey: string) => { try { const postAddress = publicToAddress( Buffer.from(publicKey, "hex"), true ).toString("hex"); return "0x" + postAddress; } catch (error) { console.log(error); } }; export const getShareList = async (id: string | number, token?: string) => { const config = { method: "get", url: `${ENDPOINT}share-service/${ENDPOINT_VERSION}/shares/share-of-file/${id}`, headers: { Authorization: "Bearer " + token, }, }; return axiosInstance(config); }; export const getShareListToMe = async ( page?: number, pageSize?: number, projectId?: string, relFolderPath?: string ) => { const _page = page || 1; const _pageSize = pageSize || 5; const config = { method: "get", url: `${ENDPOINT}share-service/${ENDPOINT_VERSION}/shares/share-with-me?limit=${_pageSize}&page=${_page}`, params: { projectId, relFolderPath }, }; return axiosInstance(config); }; export const getListShareWithMebyIds = async ( ids: Array | Array ) => { const config = { method: "post", url: `${ENDPOINT}share-service/${ENDPOINT_VERSION}/shares/share-of-file/lists`, data: { fileIds: ids, }, }; return axiosInstance(config); }; export const deleteSharePermission = async ( shareId: string | number, token?: string ) => { const config = { method: "delete", url: `${ENDPOINT}share-service/${ENDPOINT_VERSION}/shares/${shareId}`, headers: { Authorization: "Bearer " + token, }, }; return axiosInstance(config); }; // Share ---------------- // todo: library type Owallet export const getMasterKey = async (key: string) => { const [ciphertext, ephemPublicKey, iv, mac] = key.split("@@"); const encryptedData = { ciphertext, ephemPublicKey, iv, mac, }; let result = await wallet.signDecrypt([encryptedData]); if (!result) { throw new Error("Signature required!"); } result = Buffer.from(result.data[0].data).toString(); result = JSON.parse(result); const masterKey = await window.crypto.subtle.importKey( "raw", Buffer.from(result.key, "hex"), "AES-GCM", true, ["encrypt", "decrypt"] ); return [masterKey, result.iv]; }; export const getMultiMasterKey = async (keys: Array) => { const signData = await Promise.all( keys.map(async (key) => { const [ciphertext, ephemPublicKey, iv, mac] = key.split("@@"); const encryptedData = { ciphertext, ephemPublicKey, iv, mac, }; return encryptedData; }) ); const result = await wallet.signDecrypt(signData); if (!result) { throw new Error("Signature required!"); } const listKeyResponse = await Promise.all( result.data.map(async (item: any) => { const dataToString = Buffer.from(item.data).toString(); const dataBuffer = JSON.parse(dataToString); const masterKey = await window.crypto.subtle.importKey( "raw", Buffer.from(dataBuffer.key, "hex"), "AES-GCM", true, ["encrypt", "decrypt"] ); const keyReturn = { masterKey, iv: dataBuffer.iv, }; return keyReturn; }) ); return listKeyResponse; }; export const genKeyFromExportKey = async (exportKey) => { if (exportKey.length != 43) { throw "Key should be 43 character!"; } const kwtKey = { kty: "oct", k: exportKey, alg: "A256GCM", ext: true, }; const keyImported = await window.crypto.subtle.importKey( "jwk", kwtKey, { name: "AES-GCM", }, true, ["encrypt", "decrypt"] ); ////CHECKING THE KEY const readKey = await window.crypto.subtle.exportKey("jwk", keyImported); return keyImported; }; export const uploadKeyUpdate = async ( projectId, filePath, encryptKey, token ) => { try { const data = { projectId, filePath, encryptKey, }; const config = { method: "put", url: `${ENDPOINT}project-service/${ENDPOINT_VERSION}/files/update-encrypt-key`, headers: { Authorization: "Bearer " + token, }, data, }; const res = await axios(config); return res; } catch (error) { console.log(error); } }; const getFileType = (fileName: string, fileType?: string) => { if (!fileType) { switch (nodepath.parse(fileName).ext) { case ".torrent": return FILE_TYPE.TORRENT; default: return FILE_TYPE.DEFAULT; } } return fileType; };