| 1 | /* |
| 2 | * @Author: nevin |
| 3 | * @Date: 2025-01-21 21:12:52 |
| 4 | * @LastEditTime: 2025-03-19 15:10:28 |
| 5 | * @LastEditors: nevin |
| 6 | * @Description: |
| 7 | */ |
| 8 | import { AutoRunType } from '../../db/models/autoRun'; |
| 9 | |
| 10 | export const autoRunTypeEtTag = new Map<AutoRunType, string>([ |
| 11 | [AutoRunType.ReplyComment, 'ET_AUTO_RUN_REPLY_COMMENT'], |
| 12 | ]); |
| 13 | |
| 14 | export enum CycleType { |
| 15 | day = 'day', // 每天HH点触发 |
| 16 | week = 'week', // 每周D日触发(周日=0,周一=1,..., 周六=6) |
| 17 | month = 'month', // 每月DD日触发 |
| 18 | } |
| 19 | |
| 20 | // 工具函数:解析周期类型 |
| 21 | export function parseCycleType(cycleType: string): { |
| 22 | type: CycleType | ''; |
| 23 | param: number; |
| 24 | } { |
| 25 | const [_, type, paramStr] = cycleType.match(/(\w+)-(\d+)/) || []; |
| 26 | return { |
| 27 | type: type as CycleType, |
| 28 | param: parseInt(paramStr || '0'), |
| 29 | }; |
| 30 | } |
| 31 | |
| 32 | // 核心判断函数 |
| 33 | export function hasTriggered( |
| 34 | cycleType: string, |
| 35 | now: Date = new Date(), |
| 36 | ): boolean { |
| 37 | const { type, param } = parseCycleType(cycleType); |
| 38 | const date = new Date(now); |
| 39 | |
| 40 | switch (type) { |
| 41 | case 'day': // 每天HH点触发 |
| 42 | const hour = param; |
| 43 | const todayTrigger = new Date(date); |
| 44 | todayTrigger.setHours(hour, 0, 0, 0); |
| 45 | if (todayTrigger <= date) { |
| 46 | // 当前时间已过当日触发时间 → 已触发 |
| 47 | return true; |
| 48 | } else { |
| 49 | // 未到当日触发时间 → 未触发 |
| 50 | return false; |
| 51 | } |
| 52 | |
| 53 | case 'week': // 每周D日触发(周日=0,周一=1,..., 周六=6) |
| 54 | const targetDay = param; |
| 55 | const daysAgo = (date.getDay() - targetDay + 7) % 7; |
| 56 | const lastTrigger = new Date(date); |
| 57 | lastTrigger.setDate(date.getDate() - daysAgo); |
| 58 | lastTrigger.setHours(0, 0, 0, 0); // 设置为当天0点 |
| 59 | if (lastTrigger <= date) { |
| 60 | // 当前时间已过最近触发日 → 已触发 |
| 61 | return true; |
| 62 | } else { |
| 63 | // 未到最近触发日 → 未触发 |
| 64 | return false; |
| 65 | } |
| 66 | |
| 67 | case 'month': // 每月DD日触发 |
| 68 | const targetDayOfMonth = param; |
| 69 | const currentMonth = date.getMonth(); |
| 70 | const currentYear = date.getFullYear(); |
| 71 | |
| 72 | const lastMonthTrigger = new Date( |
| 73 | currentYear, |
| 74 | currentMonth, |
| 75 | targetDayOfMonth, |
| 76 | ); |
| 77 | if (lastMonthTrigger <= date) { |
| 78 | // 当月触发日已过 → 已触发 |
| 79 | return true; |
| 80 | } else { |
| 81 | // 当月触发日未到 → 未触发 |
| 82 | return false; |
| 83 | } |
| 84 | |
| 85 | default: |
| 86 | return false; |
| 87 | } |
| 88 | } |
| 89 |