AIx_Smarttalk/src/main/file.js

302 lines
9.1 KiB
JavaScript
Raw Normal View History

2024-07-18 16:28:00 +08:00
import CryptoJS from 'crypto-js'
const fs = require('fs')
const path = require('path')
2024-07-15 20:05:15 +08:00
import { ElectronDownloadManager } from 'electron-dl-manager'
import { dialog } from 'electron'
2024-07-18 15:17:15 +08:00
import axios from 'axios'
2024-07-18 16:28:00 +08:00
const uploadUrl = import.meta.env.VITE_APP_UPLOAD_API + '/smarttalk/file/upload'
2024-07-15 20:05:15 +08:00
const manager = new ElectronDownloadManager()
export default async function ({ app, shell, BrowserWindow, ipcMain }) {
const userDataPath = app.getPath('userData')
2024-07-16 17:50:01 +08:00
const appRootFilePath = userDataPath + '\\selfFile\\'
2024-07-18 15:17:15 +08:00
const appTempFilePath = userDataPath + '\\tempFile\\'
2024-07-16 17:50:01 +08:00
ipcMain.on('is-have-local-file', (e, fileNewName) => {
let filePath = appRootFilePath + fileNewName
fs.access(filePath, fs.constants.F_OK, (err) => {
if (err) {
2024-07-18 15:17:15 +08:00
e.reply('is-have-local-file-reply' + fileNewName, false)
2024-07-16 17:50:01 +08:00
return
}
2024-07-18 15:17:15 +08:00
e.reply('is-have-local-file-reply' + fileNewName, true)
2024-07-16 17:50:01 +08:00
})
})
//默认浏览器打开url
ipcMain.on('open-url-browser', (e, url) => {
shell.openPath(url)
})
//使用默认应用打开本地文件
2024-07-16 17:50:01 +08:00
ipcMain.on('open-path-app', (e, destination) => {
let path = appRootFilePath + destination
shell.openExternal(path).catch((error) => {
console.log(error)
})
})
//复制文件
ipcMain.on('copy-file-default', (e, { source, destination }) => {
copyFile(source, destination, (error, filePath) => {
e.reply('copy-file-default-reply', { error, filePath })
})
})
2024-07-18 15:17:15 +08:00
//复制文件
ipcMain.on('export-file-default', (e, list) => {
exportFile(list, (res) => {
e.reply('export-file-default-reply', res)
})
})
2024-07-18 16:28:00 +08:00
function getFileMD5(file) {
return new Promise((resolve, reject) => {
const fileReader = new FileReader()
fileReader.onload = (e) => {
const buffer = e.target.result
let md5 = CryptoJS.MD5(buffer).toString()
resolve(md5)
}
fileReader.readAsArrayBuffer(file)
})
}
2024-07-18 15:17:15 +08:00
ipcMain.on('creat-file-default', (e, { name, uploadData, cookie }) => {
createFolder('tempFile').then(() => {
let path = appTempFilePath + name
fs.writeFileSync(path, '', 'utf-8')
// 读取文件
fs.readFile(path, (err, data) => {
if (err) {
return console.error(err)
}
// 配置上传的请求
const config = {
headers: {
2024-07-18 16:28:00 +08:00
'Content-Type': 'multipart/form-data', // 或者其他适合上传文件的Content-Type
2024-07-18 15:17:15 +08:00
Authorization: 'Bearer ' + cookie
}
}
2024-07-18 16:28:00 +08:00
let md5 = CryptoJS.MD5(data).toString()
let formData = new FormData()
2024-07-18 15:17:15 +08:00
// 使用axios上传文件
2024-07-18 16:28:00 +08:00
let file = new File([data], name, {
type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
})
formData.append('file', file)
formData.append('md5',md5)
for (let key in uploadData) {
if (uploadData.hasOwnProperty(key)) { // 检查是否是对象自身的属性
formData.append(key,uploadData[key])
}
}
formData.append("fileFlag","教案")
2024-07-18 15:17:15 +08:00
axios
2024-07-18 16:28:00 +08:00
.post(uploadUrl, formData, config)
2024-07-18 15:17:15 +08:00
.then((response) => {
2024-07-18 16:28:00 +08:00
e.reply('creat-file-default-reply', response.data)
2024-07-18 15:17:15 +08:00
console.log('File uploaded successfully:', response.data)
})
.catch((error) => {
console.error('Error uploading file:', error)
})
})
})
})
2024-07-16 17:50:01 +08:00
//获取应用文件目录
ipcMain.on('get-root-file-path', (e) => {
e.reply('get-root-file-path-reply', appRootFilePath)
})
//下载文件
2024-07-16 17:50:01 +08:00
ipcMain.on('download-file-default', (e, { url, fileName }) => {
2024-07-15 20:05:15 +08:00
createFolder('selfFile').then(async () => {
const browserWindow = BrowserWindow.fromId(e.sender.id)
const id = await manager.download({
window: browserWindow,
url: url,
2024-07-16 17:50:01 +08:00
saveAsFilename: fileName,
directory: appRootFilePath,
callbacks: {
onDownloadStarted: async ({ id, item, webContents }) => {
// Do something with the download id
},
2024-07-18 15:17:15 +08:00
onDownloadProgress: async ({ id, item, percentCompleted }) => {},
onDownloadCompleted: async ({ id, item }) => {
2024-07-16 17:50:01 +08:00
console.log('完成')
2024-07-18 15:17:15 +08:00
e.reply('download-file-default' + fileName, true)
2024-07-16 17:50:01 +08:00
},
onDownloadCancelled: async () => {
console.log('取消')
2024-07-18 15:17:15 +08:00
e.reply('download-file-default' + fileName, false)
2024-07-16 17:50:01 +08:00
},
onDownloadInterrupted: async () => {
console.log('中断')
2024-07-18 15:17:15 +08:00
e.reply('download-file-default' + fileName, false)
},
2024-07-16 17:50:01 +08:00
onError: (err, data) => {
console.log(err.toString())
2024-07-18 15:17:15 +08:00
e.reply('download-file-default' + fileName, false)
2024-07-16 17:50:01 +08:00
}
}
2024-07-15 20:05:15 +08:00
})
})
})
/**...
* 接收渲染进程 保存文件的 的通知
* @param {Object} event
* @param {String} url 下载链接
* @param {String} fileName 文件名称包括后缀名例如图1.png
*/
ipcMain.on('save-as', function (event, url, fileName) {
2024-07-16 17:50:01 +08:00
let win = BrowserWindow.getFocusedWindow()
2024-07-15 20:05:15 +08:00
//通过扩展名识别文件类型
let filters = [{ name: '全部文件', extensions: ['*'] }]
let ext = path.extname(fileName) //获取扩展名
if (ext && ext !== '.') {
const name = ext.slice(1, ext.length)
if (name) {
filters.unshift({
name: '',
extensions: [name]
})
}
}
let filePath = null //用户选择存放文件的路径
//1- 弹出另存为弹框,用于获取保存路径
dialog
.showSaveDialog(win, {
title: '另存为',
filters,
defaultPath: fileName
})
.then((result) => {
//点击保存后开始下载
filePath = result.filePath
if (filePath) {
win.webContents.downloadURL(url) // 触发will-download事件
}
})
.catch(() => {
console.log('另存为--catch')
})
//2- 准备下载的时候触发
win.webContents.session.once('will-download', (event, item, webContents) => {
if (!filePath) return
//设置下载项的保存文件路径
item.setSavePath(filePath)
})
})
2024-07-18 15:17:15 +08:00
function exportFile(list, callback) {
let win = BrowserWindow.getFocusedWindow()
//通过扩展名识别文件类型
let filePath = null //用户选择存放文件的路径
//1- 弹出另存为弹框,用于获取保存路径
dialog
.showOpenDialog(win, {
properties: ['openDirectory']
})
.then(async (result) => {
if (result.filePaths[0]) {
filePath = result.filePaths[0]
let res = []
for (let i = 0; i < list.length; i++) {
let item = list[i]
let source = appRootFilePath + item.id
let destination = filePath + '/' + item.name
await copyRelFile(source, filterCopyFile(destination), (error, path) => {
res.push({ error, path })
})
}
callback(res)
}
})
.catch(() => {
console.log('另存为--catch')
})
}
function isHaveFile(path) {
return fs.existsSync(path)
}
function filterCopyFile(path, index = 0) {
if (isHaveFile(path) === true) {
index++
path = path.replaceAll('.', `(${index}).`)
return filterCopyFile(path, index)
} else {
return path
}
}
function copyRelFile(source, destination, callback) {
return new Promise((resolve, reject) => {
const readStream = fs.createReadStream(source)
const writeStream = fs.createWriteStream(destination)
readStream.on('error', (error) => {
reject()
callback(error, null)
})
writeStream.on('error', (error) => {
reject()
callback(error, null)
})
writeStream.on('close', () => {
console.log('关闭写入流')
callback(null, destination)
resolve()
})
readStream.pipe(writeStream)
})
}
function copyFile(source, destination, callback) {
2024-07-16 17:50:01 +08:00
let path = appRootFilePath + destination
createFolder('selfFile').then(() => {
const readStream = fs.createReadStream(source)
const writeStream = fs.createWriteStream(path)
readStream.on('error', (error) => {
callback(error, null)
})
writeStream.on('error', (error) => {
callback(error, null)
})
writeStream.on('close', () => {
callback(null, path)
})
readStream.pipe(writeStream)
})
}
function createFolder(folderName) {
return new Promise((resolve, reject) => {
const folderPath = path.join(userDataPath, folderName)
// 异步检查文件夹是否存在,不存在则创建
fs.access(folderPath, fs.constants.F_OK, (err) => {
if (err) {
fs.mkdir(folderPath, { recursive: true }, (mkdirErr) => {
if (mkdirErr) {
console.error(mkdirErr)
reject()
} else {
console.log(`Folder ${folderName} created successfully.`)
resolve()
}
})
} else {
console.log(`Folder ${folderName} already exists.`)
resolve()
}
})
})
}
}