302 lines
9.1 KiB
JavaScript
302 lines
9.1 KiB
JavaScript
import CryptoJS from 'crypto-js'
|
||
|
||
const fs = require('fs')
|
||
const path = require('path')
|
||
import { ElectronDownloadManager } from 'electron-dl-manager'
|
||
import { dialog } from 'electron'
|
||
import axios from 'axios'
|
||
const uploadUrl = import.meta.env.VITE_APP_UPLOAD_API + '/smarttalk/file/upload'
|
||
const manager = new ElectronDownloadManager()
|
||
export default async function ({ app, shell, BrowserWindow, ipcMain }) {
|
||
const userDataPath = app.getPath('userData')
|
||
const appRootFilePath = userDataPath + '\\selfFile\\'
|
||
const appTempFilePath = userDataPath + '\\tempFile\\'
|
||
ipcMain.on('is-have-local-file', (e, fileNewName) => {
|
||
let filePath = appRootFilePath + fileNewName
|
||
fs.access(filePath, fs.constants.F_OK, (err) => {
|
||
if (err) {
|
||
e.reply('is-have-local-file-reply' + fileNewName, false)
|
||
return
|
||
}
|
||
e.reply('is-have-local-file-reply' + fileNewName, true)
|
||
})
|
||
})
|
||
//默认浏览器打开url
|
||
ipcMain.on('open-url-browser', (e, url) => {
|
||
shell.openPath(url)
|
||
})
|
||
//使用默认应用打开本地文件
|
||
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 })
|
||
})
|
||
})
|
||
|
||
//复制文件
|
||
ipcMain.on('export-file-default', (e, list) => {
|
||
exportFile(list, (res) => {
|
||
e.reply('export-file-default-reply', res)
|
||
})
|
||
})
|
||
|
||
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)
|
||
})
|
||
}
|
||
|
||
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: {
|
||
'Content-Type': 'multipart/form-data', // 或者其他适合上传文件的Content-Type
|
||
Authorization: 'Bearer ' + cookie
|
||
}
|
||
}
|
||
let md5 = CryptoJS.MD5(data).toString()
|
||
let formData = new FormData()
|
||
// 使用axios上传文件
|
||
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","教案")
|
||
axios
|
||
.post(uploadUrl, formData, config)
|
||
.then((response) => {
|
||
e.reply('creat-file-default-reply', response.data)
|
||
console.log('File uploaded successfully:', response.data)
|
||
})
|
||
.catch((error) => {
|
||
console.error('Error uploading file:', error)
|
||
})
|
||
})
|
||
})
|
||
})
|
||
|
||
//获取应用文件目录
|
||
ipcMain.on('get-root-file-path', (e) => {
|
||
e.reply('get-root-file-path-reply', appRootFilePath)
|
||
})
|
||
|
||
//下载文件
|
||
ipcMain.on('download-file-default', (e, { url, fileName }) => {
|
||
createFolder('selfFile').then(async () => {
|
||
const browserWindow = BrowserWindow.fromId(e.sender.id)
|
||
const id = await manager.download({
|
||
window: browserWindow,
|
||
url: url,
|
||
saveAsFilename: fileName,
|
||
directory: appRootFilePath,
|
||
callbacks: {
|
||
onDownloadStarted: async ({ id, item, webContents }) => {
|
||
// Do something with the download id
|
||
},
|
||
onDownloadProgress: async ({ id, item, percentCompleted }) => {},
|
||
onDownloadCompleted: async ({ id, item }) => {
|
||
console.log('完成')
|
||
e.reply('download-file-default' + fileName, true)
|
||
},
|
||
onDownloadCancelled: async () => {
|
||
console.log('取消')
|
||
e.reply('download-file-default' + fileName, false)
|
||
},
|
||
onDownloadInterrupted: async () => {
|
||
console.log('中断')
|
||
e.reply('download-file-default' + fileName, false)
|
||
},
|
||
onError: (err, data) => {
|
||
console.log(err.toString())
|
||
e.reply('download-file-default' + fileName, false)
|
||
}
|
||
}
|
||
})
|
||
})
|
||
})
|
||
|
||
/**另存为...
|
||
* 接收渲染进程 保存文件的 的通知
|
||
* @param {Object} event
|
||
* @param {String} url 下载链接
|
||
* @param {String} fileName 文件名称包括后缀名,例如图1.png
|
||
*/
|
||
ipcMain.on('save-as', function (event, url, fileName) {
|
||
let win = BrowserWindow.getFocusedWindow()
|
||
//通过扩展名识别文件类型
|
||
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)
|
||
})
|
||
})
|
||
|
||
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) {
|
||
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()
|
||
}
|
||
})
|
||
})
|
||
}
|
||
}
|