Let's use AI to Earn!
TypeScript auto-publishdouyindouyin-apielectron-appelectron-reactkuaishoukwaipublishedshipinhaotoolxiaohongshu
feat: 自动化任务
yikaJasonMic9fa38b893c5b
diff --git a/electron/main/autoRun/comment.ts b/electron/main/autoRun/comment.tsindex 6bf376f8..6e3b0132 100644--- a/electron/main/autoRun/comment.ts+++ b/electron/main/autoRun/comment.ts@@ -1,7 +1,79 @@/** @Author: nevin* @Date: 2025-01-21 21:12:52- * @LastEditTime: 2025-03-18 21:16:35+ * @LastEditTime: 2025-03-19 15:10:28* @LastEditors: nevin* @Description:*/+import { AutoRunType } from '../../db/models/autoRun';++export const autoRunTypeEtTag = new Map<AutoRunType, string>([+ [AutoRunType.ReplyComment, 'ET_AUTO_RUN_REPLY_COMMENT'],+]);++// 工具函数:解析周期类型+function parseCycleType(cycleType: string): { type: string; param: number } {+ const [_, type, paramStr] = cycleType.match(/(\w+)-(\d+)/) || [];+ return {+ type: type || '',+ param: parseInt(paramStr || '0'),+ };+}++// 核心判断函数+export function hasTriggered(+ cycleType: string,+ now: Date = new Date(),+): boolean {+ const { type, param } = parseCycleType(cycleType);+ const date = new Date(now);++ switch (type) {+ case 'day': // 每天HH点触发+ const hour = param;+ const todayTrigger = new Date(date);+ todayTrigger.setHours(hour, 0, 0, 0);+ if (todayTrigger <= date) {+ // 当前时间已过当日触发时间 → 已触发+ return true;+ } else {+ // 未到当日触发时间 → 未触发+ return false;+ }++ case 'week': // 每周D日触发(周日=0,周一=1,..., 周六=6)+ const targetDay = param;+ const daysAgo = (date.getDay() - targetDay + 7) % 7;+ const lastTrigger = new Date(date);+ lastTrigger.setDate(date.getDate() - daysAgo);+ lastTrigger.setHours(0, 0, 0, 0); // 设置为当天0点+ if (lastTrigger <= date) {+ // 当前时间已过最近触发日 → 已触发+ return true;+ } else {+ // 未到最近触发日 → 未触发+ return false;+ }++ case 'month': // 每月DD日触发+ const targetDayOfMonth = param;+ const currentMonth = date.getMonth();+ const currentYear = date.getFullYear();++ const lastMonthTrigger = new Date(+ currentYear,+ currentMonth,+ targetDayOfMonth,+ );+ if (lastMonthTrigger <= date) {+ // 当月触发日已过 → 已触发+ return true;+ } else {+ // 当月触发日未到 → 未触发+ return false;+ }++ default:+ return false;+ }+}diff --git a/electron/main/autoRun/controller.ts b/electron/main/autoRun/controller.tsindex 5041de0c..8512d62a 100644--- a/electron/main/autoRun/controller.ts+++ b/electron/main/autoRun/controller.ts@@ -1,7 +1,7 @@/** @Author: nevin* @Date: 2025-01-20 22:02:54- * @LastEditTime: 2025-03-19 14:27:36+ * @LastEditTime: 2025-03-19 15:01:43* @LastEditors: nevin* @Description: autoRun AutoRun*/@@ -10,6 +10,7 @@ import { AutoRunService } from './service';import { AutoRunType } from '../../db/models/autoRun';import { getUserInfo } from '../user/comment';import { EtEvent } from '../../global/event';+import { autoRunTypeEtTag } from './comment';@Controller()export class AutoRunController {@@ -108,8 +109,18 @@ export class AutoRunController {@Scheduled('*/1 * * * *', 'all_auto_run_start')async syncAllAutoRunStart() {try {- console.log('------- 111');- EtEvent.emit('ET_RUN_AUTO_RUN', 1111);+ const userInfo = getUserInfo();++ const autoRunList = await this.autoRunService.findAutoRunListOfNeedRun(+ userInfo.id,+ );++ for (const item of autoRunList) {+ const tag = autoRunTypeEtTag.get(item.type);+ if (!tag) continue;+ // TODO: 根据创建记录,对比是否已经执行+ EtEvent.emit(tag, item);+ }} catch (error) {console.error('Failed to sync accounts:', error);}diff --git a/electron/main/autoRun/service.ts b/electron/main/autoRun/service.tsindex 216a65c8..0f719dd1 100644--- a/electron/main/autoRun/service.ts+++ b/electron/main/autoRun/service.ts@@ -24,15 +24,25 @@ export class AutoRunService {AppDataSource.getRepository(AutoRunRecordModel);}+ // 限制处于启动状态的任务数量+ private async chectAutoRunCount(userId: string): Promise<boolean> {+ const count = await this.autoRunRepository.count({+ where: {+ userId,+ status: AutoRunStatus.DOING,+ },+ });++ if (count >= 100) return false;++ return true;+ }+// 创建进程async createAutoRun(data: Partial<AutoRunModel>) {- console.log('------', data);+ if (!(await this.chectAutoRunCount(data.userId!))) return null;- try {- return await this.autoRunRepository.save(data);- } catch (error) {- console.log('----- error', error);- }+ return await this.autoRunRepository.save(data);}// 根据ID查询进程信息@@ -51,6 +61,16 @@ export class AutoRunService {});}+ // 查询需要运行的进程列表+ async findAutoRunListOfNeedRun(userId: string) {+ return await this.autoRunRepository.find({+ where: {+ userId,+ status: AutoRunStatus.DOING,+ },+ });+ }+// 更新进程状态async updateAutoRunStatus(id: number, status: AutoRunStatus) {return await this.autoRunRepository.update(id, {diff --git a/electron/main/core/decorators.ts b/electron/main/core/decorators.tsindex ce8a657f..52b0bdb9 100644--- a/electron/main/core/decorators.ts+++ b/electron/main/core/decorators.ts@@ -1,7 +1,7 @@/** @Author: nevin* @Date: 2025-01-24 17:55:22- * @LastEditTime: 2025-02-13 21:15:38+ * @LastEditTime: 2025-03-19 14:31:34* @LastEditors: nevin* @Description:*/@@ -9,7 +9,7 @@ import 'reflect-metadata';import { ipcMain } from 'electron';import { container } from './container';import { INJECT_METADATA_KEY } from './metadata';-import { Event } from '../../global/event';+import { EtEvent } from '../../global/event';import { scheduleJob, scheduleJobMap } from '../../global/schedule';// Module 装饰器@@ -88,7 +88,7 @@ export function Et(eventName: string) {) {const originalMethod = descriptor.value;- Event.on(eventName, async (...args) => {+ EtEvent.on(eventName, async (...args) => {const controller = container.getController(target.constructor.name);if (!controller) {throw new Error(`Controller ${target.constructor.name} not found`);diff --git a/electron/main/reply/controller.ts b/electron/main/reply/controller.tsindex 6814eea0..e0bae163 100644--- a/electron/main/reply/controller.ts+++ b/electron/main/reply/controller.ts@@ -1,7 +1,7 @@/** @Author: nevin* @Date: 2025-01-20 22:02:54- * @LastEditTime: 2025-03-19 14:25:31+ * @LastEditTime: 2025-03-19 15:01:54* @LastEditors: nevin* @Description: reply Reply*/@@ -151,7 +151,7 @@ export class ReplyController {}// 运行自动任务- @Et('ET_RUN_AUTO_RUN')+ @Et('ET_AUTO_RUN_REPLY_COMMENT')async runAutoReplyComment(autoRunData: AutoRunModel): Promise<any> {console.log('------ runAutoReplyComment ------', autoRunData.createTime);}