Skip to content

Let's use AI to Earn!

feat: 文件下载icp

牛文政333a7a46f46c
diff --git a/electron/main/index.ts b/electron/main/index.ts
index 5cc51686..9fdbc9bd 100644
--- a/electron/main/index.ts
+++ b/electron/main/index.ts
@@ -10,7 +10,6 @@ import { getAssetPath } from '../util/index';
import windowOperate from '../util/windowOperate';
import { logger } from '../global/log';
import { SplashWindow } from './splash';
-import { registerFileHandlers } from './ipc/fileHandler';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -126,9 +125,6 @@ app.whenReady().then(async () => {
update(bWin);
views(bWin);
windowOperate.init(bWin);
-
- // 注册文件处理IPC
- registerFileHandlers();
} catch (error) {
logger.error('Failed to start application:', error);
app.quit();
diff --git a/electron/main/ipc/fileHandler.ts b/electron/main/ipc/fileHandler.ts
deleted file mode 100644
index d147352d..00000000
--- a/electron/main/ipc/fileHandler.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-/**
- * 文件处理IPC
- */
-import { ipcMain } from 'electron';
-import { downloadFileToTemp } from '../utils/fileDownloader';
-
-// 注册IPC处理程序
-export function registerFileHandlers() {
- // 下载文件到临时目录
- ipcMain.handle('download-file-to-temp', async (_, url: string, fileType: 'video' | 'image') => {
- try {
- const filePath = await downloadFileToTemp(url, fileType);
- return { success: true, filePath };
- } catch (error) {
- console.error('下载文件失败:', error);
- return { success: false, error: error.message };
- }
- });
-}
\ No newline at end of file
diff --git a/electron/main/tools/controller.ts b/electron/main/tools/controller.ts
index e8905cba..4e5fa4a3 100644
--- a/electron/main/tools/controller.ts
+++ b/electron/main/tools/controller.ts
@@ -5,6 +5,7 @@
* @LastEditors: nevin
* @Description:
*/
+import { FileUtils } from '../../util/file';
import { FFmpegVideoUtil } from '../../util/ffmpeg/video';
import { Controller, Icp, Inject } from '../core/decorators';
import { ToolsService } from './service';
@@ -25,4 +26,18 @@ export class ToolsController {
): Promise<string> {
return await FFmpegVideoUtil.getVideoCover(path, time);
}
+
+ /**
+ * 视频截取指定时间点的帧
+ */
+ @Icp('ICP_TOOL_DOWN_FILE')
+ async downFile(
+ event: Electron.IpcMainInvokeEvent,
+ url: string,
+ name?: string,
+ ): Promise<string> {
+ const res = await FileUtils.downFile(url, name);
+ console.log('-----', res);
+ return '';
+ }
}
diff --git a/electron/main/utils/fileDownloader.ts b/electron/main/utils/fileDownloader.ts
deleted file mode 100644
index 7847f419..00000000
--- a/electron/main/utils/fileDownloader.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-/**
- * 文件下载工具
- * 在Electron主进程中实现文件下载功能
- */
-import { app } from 'electron';
-import * as fs from 'fs';
-import * as path from 'path';
-import axios from 'axios';
-import { v4 as uuidv4 } from 'uuid';
-
-/**
- * 从网络URL下载文件到本地临时目录
- * @param url 文件URL
- * @param fileType 文件类型 'video' | 'image'
- * @returns 本地文件路径
- */
-export const downloadFileToTemp = async (url: string, fileType: 'video' | 'image'): Promise<string> => {
- try {
- // 获取应用数据目录
- const userDataPath = app.getPath('userData');
- const tempDir = path.join(userDataPath, 'temp');
-
- // 确保临时目录存在
- if (!fs.existsSync(tempDir)) {
- fs.mkdirSync(tempDir, { recursive: true });
- }
-
- // 生成唯一文件名
- const fileExtension = fileType === 'video' ? '.mp4' : '.jpg';
- const fileName = `${uuidv4()}${fileExtension}`;
- const filePath = path.join(tempDir, fileName);
-
- // 下载文件
- const response = await axios({
- method: 'GET',
- url: url,
- responseType: 'stream',
- timeout: 60000, // 60秒超时
- });
-
- // 创建写入流
- const writer = fs.createWriteStream(filePath);
-
- // 将响应数据写入文件
- response.data.pipe(writer);
-
- return new Promise((resolve, reject) => {
- writer.on('finish', () => {
- console.log(`文件已下载到: ${filePath}`);
- resolve(filePath);
- });
-
- writer.on('error', (err) => {
- console.error('文件写入失败:', err);
- reject(err);
- });
- });
- } catch (error) {
- console.error('文件下载失败:', error);
- throw error;
- }
-};
\ No newline at end of file
diff --git a/electron/util/file.ts b/electron/util/file.ts
index 858e8aa2..d828449e 100644
--- a/electron/util/file.ts
+++ b/electron/util/file.ts
@@ -3,6 +3,7 @@ import mimeTypes from 'mime-types';
import ffmpeg from 'fluent-ffmpeg';
import { ffprobePath } from './ffprobe_static';
import path from 'path';
+import { net } from 'electron';
// 文件工具类
// 设置 ffprobe 路径
@@ -245,14 +246,14 @@ export class FileUtils {
process.env.HOME || '',
'Library',
'Application Support',
- 'ktt-app',
+ 'att',
);
}
case 'win32': {
- return path.join(process.env.APPDATA || '', 'ktt-app');
+ return path.join(process.env.APPDATA || '', 'att');
}
case 'linux': {
- return path.join(process.env.HOME || '', 'ktt-app');
+ return path.join(process.env.HOME || '', 'att');
}
default: {
console.log('Unsupported platform!');
@@ -260,4 +261,46 @@ export class FileUtils {
}
}
}
+
+ /**
+ * 下载文件
+ * @param url
+ * @param name
+ * @returns
+ */
+ static async downFile(url: string, name?: string): Promise<string> {
+ const dirPath = this.getAppDataPath();
+ console.log('------- dirPath', dirPath);
+
+ await this.checkDirectories(dirPath);
+
+ return new Promise((resolve, reject) => {
+ const request = net.request(url);
+ let fileStream: NodeJS.WritableStream | null = null;
+ let filePath: string;
+
+ request.on('response', (response) => {
+ if (response.statusCode !== 200) {
+ return reject(new Error(`下载失败: 状态码 ${response.statusCode}`));
+ }
+
+ filePath = path.join(dirPath, name || 'default_filename.mp4');
+ fileStream = fs.createWriteStream(filePath);
+
+ response.on('end', () => {
+ if (fileStream) {
+ fileStream.end();
+ resolve(filePath); // 确保filePath已定义
+ }
+ });
+ });
+
+ request.on('error', (err) => {
+ reject(err);
+ });
+
+ // 必须调用request.end()来发送请求
+ request.end();
+ });
+ }
}
diff --git a/src/icp/file.ts b/src/icp/file.ts
deleted file mode 100644
index c0551008..00000000
--- a/src/icp/file.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * 文件操作IPC接口
- */
-import { message } from 'antd';
-import axios from 'axios';
-
-/**
- * 从网络URL下载文件到本地临时目录
- * @param url 文件URL
- * @param fileType 文件类型 'video' | 'image'
- * @returns 本地文件路径或URL
- */
-export const icpDownloadFileToTemp = async (url: string, fileType: 'video' | 'image'): Promise<string> => {
- try {
- // 检查是否支持IPC
- if (window.electron?.ipcRenderer) {
- // 使用Electron IPC
- const result = await window.electron.ipcRenderer.invoke('download-file-to-temp', url, fileType);
-
- if (!result.success) {
- throw new Error(result.error || '下载失败');
- }
-
- return result.filePath;
- } else {
- // 浏览器环境下,直接返回URL
- // 验证URL是否可访问
- try {
- const response = await axios.head(url);
- if (response.status === 200) {
- console.log('URL可访问,直接使用原始URL');
- return url;
- }
- } catch (error) {
- console.warn('URL访问检查失败,继续使用原始URL', error);
- }
-
- return url;
- }
- } catch (error) {
- console.error('文件下载失败:', error);
- message.error('文件下载失败,使用原始URL继续');
- // 出错时返回原始URL
- return url;
- }
-};
\ No newline at end of file
diff --git a/src/icp/tools.ts b/src/icp/tools.ts
index 4a91a18c..77953047 100644
--- a/src/icp/tools.ts
+++ b/src/icp/tools.ts
@@ -19,3 +19,17 @@ export async function ipcGetVideoCover(path: string, time?: string) {
);
return res;
}
+
+/**
+ * 下载文件到本地
+ * @param url
+ * @param name
+ */
+export async function ipcDownFile(url: string, name?: string) {
+ const res: string = await window.ipcRenderer.invoke(
+ 'ICP_TOOL_DOWN_FILE',
+ url,
+ name,
+ );
+ return res;
+}
diff --git a/src/views/reply/index.tsx b/src/views/reply/index.tsx
index b1cbb54d..ce1f1786 100644
--- a/src/views/reply/index.tsx
+++ b/src/views/reply/index.tsx
@@ -9,6 +9,7 @@ import { ipcCreatorList } from '@/icp/reply';
import { Button } from 'antd';
import { useCallback, useState } from 'react';
import AccountSidebar from '../account/components/AccountSidebar/AccountSidebar';
+import { ipcDownFile } from '@/icp/tools';
export default function Page() {
const [activeTab, setActiveTab] = useState('car');
const [activeAccountId, setActiveAccountId] = useState<number>(-1);
@@ -18,6 +19,14 @@ export default function Page() {
console.log('----- res', res);
}
+ async function downFile() {
+ const res = await ipcDownFile(
+ 'https://ai-to-earn.oss-cn-beijing.aliyuncs.com/development/temp/nopath/202503/f1cffb9c-c42a-4fcc-8516-0e2c276ee2f8.mp4',
+ '111',
+ );
+ console.log('----- res', res);
+ }
+
return (
<div>
<div>
@@ -32,6 +41,10 @@ export default function Page() {
<Button type="primary" onClick={getCreatorList}>
获取列表
</Button>
+
+ <Button type="primary" onClick={downFile}>
+ 下载文件
+ </Button>
</div>
</div>
);