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
 
98bb76b
7ee9dd5
 
 
98bb76b
7ee9dd5
 
 
 
 
 
 
9d865f0
 
8a92781
 
 
 
 
 
9d865f0
7ee9dd5
 
0d98acf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
const cron = require('node-cron');
const { prisma } = require('./db');
const { checkSite } = require('./run');
const { sendAggregatedNotification } = require('./notifier');

const jobs = new Map();
const categoryJobs = new Map();  // 用于存储分类定时任务
const DEFAULT_CRON = '0 9 * * *';
let globalScheduleJob = null;

function stopSiteJob(siteId, fastify) {
  if (!jobs.has(siteId)) {
    return false;
  }

  jobs.get(siteId).stop();
  jobs.delete(siteId);
  fastify?.log?.info({ siteId }, 'Stopped individual site job');
  return true;
}

async function scheduleSite(site, fastify) {
  const key = site.id;
  
  // 停止现有任务
  stopSiteJob(key, fastify);
  
  // 检查全局配置是否启用了覆盖
  const globalConfig = await prisma.scheduleConfig.findFirst();
  if (globalConfig?.enabled && globalConfig.overrideIndividual) {
    fastify?.log?.info({ siteId: site.id, name: site.name }, 'Global override enabled, site will be handled by global task');
    return;
  }
  
  // 只为有单独定时配置的站点创建任务
  if (!site.scheduleCron || !site.scheduleCron.trim()) {
    fastify?.log?.info({ siteId: site.id, name: site.name }, 'Site has no custom schedule, will be handled by global task');
    return;
  }
  
  const cronExp = site.scheduleCron;
  const job = cron.schedule(cronExp, async () => {
    try {
      // 重新从数据库获取最新的站点信息,避免使用过期的配置
      const latestSite = await prisma.site.findUnique({ where: { id: site.id } });
      if (!latestSite) {
        fastify?.log?.warn({ siteId: site.id }, 'Site not found, skipping scheduled check');
        return;
      }
      // 有单独配置的站点,不跳过通知,单独发送邮件
      await checkSite(latestSite, fastify, { skipNotification: false, isManual: false });
      fastify?.log?.info({ siteId: latestSite.id, name: latestSite.name }, 'Individual scheduled check done');
    } catch (e) {
      fastify?.log?.warn({ siteId: site.id, name: site.name, err: e.message }, 'Individual scheduled check failed');
    }
  }, {
    timezone: site.timezone || 'UTC',
    scheduled: true  // 确保任务被启动
  });
  
  // 显式启动任务
  job.start();
  
  jobs.set(key, job);
  fastify?.log?.info({ siteId: site.id, name: site.name, cronExp, timezone: site.timezone }, 'Individual schedule task created and started');
}

async function scheduleAll(fastify) {
  const sites = await prisma.site.findMany();
  for (const s of sites) {
    await scheduleSite(s, fastify);
  }
  
  // 也要为所有分类调度定时任务
  await scheduleAllCategories(fastify);
}

function stopAllIndividualJobs(fastify) {
  const count = jobs.size;
  for (const [key, job] of jobs.entries()) {
    job.stop();
    jobs.delete(key);
  }
  fastify?.log?.info({ count }, 'Stopped all individual site jobs');
  return count;
}

function onSiteUpdated(site, fastify) {
  scheduleSite(site, fastify);
}

function onSiteDeleted(siteId, fastify) {
  stopSiteJob(siteId, fastify);
}

// 为分类调度定时任务
async function scheduleCategory(category, fastify) {
  const key = `cat_${category.id}`;
  
  // 停止现有任务
  if (categoryJobs.has(key)) {
    categoryJobs.get(key).stop();
    categoryJobs.delete(key);
 }
  
  // 只为有定时配置的分类创建任务
  if (!category.scheduleCron || !category.scheduleCron.trim()) {
    fastify?.log?.info({ categoryId: category.id, name: category.name }, 'Category has no custom schedule');
    return;
  }
  
  const cronExp = category.scheduleCron;
  const job = cron.schedule(cronExp, async () => {
    try {
      // 重新从数据库获取最新的分类信息
      const latestCategory = await prisma.category.findUnique({
        where: { id: category.id },
        include: { sites: true }
      });
      
      if (!latestCategory) {
        fastify?.log?.warn({ categoryId: category.id }, 'Category not found, skipping scheduled check');
        return;
      }
      
      // 获取该分类下所有需要检测的站点(非置顶)
      // excludeFromBatch 只影响手动一键检测,不影响定时检测
      const sitesToCheck = latestCategory.sites.filter(site =>
        !site.pinned
      );
      
      if (sitesToCheck.length === 0) {
        fastify?.log?.info({ categoryId: latestCategory.id, name: latestCategory.name }, 'No sites to check in category');
        return;
      }
      
      fastify?.log?.info({
        categoryId: latestCategory.id,
        categoryName: latestCategory.name,
        siteCount: sitesToCheck.length
      }, 'Category scheduled check started');
      
      // 依次检测每个站点(使用5秒间隔)
      for (let i = 0; i < sitesToCheck.length; i++) {
        const site = sitesToCheck[i];
        try {
          await checkSite(site, fastify, { skipNotification: false, isManual: false }); // 分类检测也发送单独通知
          fastify?.log?.info({ siteId: site.id, siteName: site.name }, `Site checked in category task`);
        } catch (e) {
          fastify?.log?.error({
            siteId: site.id,
            siteName: site.name,
            error: e.message
          }, 'Site check failed in category task');
        }
        
        // 如果不是最后一个站点,等待5秒
        if (i < sitesToCheck.length - 1) {
          await new Promise(resolve => setTimeout(resolve, 5000));
        }
      }
      
      fastify?.log?.info({
        categoryId: latestCategory.id,
        categoryName: latestCategory.name
      }, 'Category scheduled check completed');
    } catch (e) {
      fastify?.log?.error({
        categoryId: category.id,
        categoryName: category.name,
        error: e.message
      }, 'Category scheduled check failed');
    }
  }, {
    timezone: category.timezone || 'UTC',
    scheduled: true  // 确保任务被启动
  });
  
  // 显式启动任务
  job.start();
  
  categoryJobs.set(key, job);
  fastify?.log?.info({
    categoryId: category.id,
    categoryName: category.name,
    cronExp,
    timezone: category.timezone
  }, 'Category schedule task created and started');
}

// 为所有分类调度定时任务
async function scheduleAllCategories(fastify) {
  const categories = await prisma.category.findMany({ include: { sites: true } });
  for (const category of categories) {
    await scheduleCategory(category, fastify);
  }
}

// 全局定时任务:按配置的时间检测所有没有单独定时配置的站点
// 有单独配置的站点会由 scheduleSite 函数单独调度,并单独发送邮件通知
async function scheduleGlobalTask(config, fastify) {
  // 停止现有的全局任务
  if (globalScheduleJob) {
    globalScheduleJob.stop();
    globalScheduleJob = null;
  }

  if (!config || !config.enabled) {
    fastify?.log?.info('Global schedule task disabled, rescheduling individual site jobs');
    // 全局任务禁用时,重新为有单独配置的站点创建任务
    const allSites = await prisma.site.findMany();
    for (const site of allSites) {
      await scheduleSite(site, fastify);
    }
    return;
  }
  
  // 处理覆盖模式:停止所有单独任务
  if (config.overrideIndividual) {
    fastify?.log?.info('Override mode enabled, stopping all individual site jobs');
    stopAllIndividualJobs(fastify);
  } else {
    // 非覆盖模式:重新为有单独配置的站点创建任务
    fastify?.log?.info('Non-override mode, rescheduling individual site jobs');
    const allSites = await prisma.site.findMany();
    for (const site of allSites) {
      await scheduleSite(site, fastify);
    }
  }

  const { hour, minute, timezone = 'Asia/Shanghai', interval = 30 } = config;
  const cronExp = `${minute} ${hour} * * *`;
  const configId = config.id;

  fastify?.log?.info({ cronExp, timezone, interval }, 'Starting global schedule task');

  globalScheduleJob = cron.schedule(cronExp, async () => {
    try {
      fastify?.log?.info('Global schedule task triggered');
      
      // 重新从数据库获取最新的全局配置,避免使用过期的配置
      const latestConfig = await prisma.scheduleConfig.findUnique({ where: { id: configId } });
      if (!latestConfig || !latestConfig.enabled) {
        fastify?.log?.info('Global schedule task is disabled, skipping');
        return;
      }
      
      const allSites = await prisma.site.findMany();
      
      // 根据最新的 overrideIndividual 决定是否覆盖单独配置
      // 注意:excludeFromBatch 只影响手动一键检测,不影响定时检测
      const sites = latestConfig.overrideIndividual
        ? allSites  // 覆盖模式:检测所有站点(包括 excludeFromBatch=true 的站点)
        : allSites.filter(s => !s.scheduleCron || !s.scheduleCron.trim()); // 只检测没有单独配置的站点(包括 excludeFromBatch=true 的站点)
      
      fastify?.log?.info({ 
        totalSites: allSites.length, 
        overrideIndividual: latestConfig.overrideIndividual,
        sitesWithCustomSchedule: allSites.length - sites.length,
        sitesToCheck: sites.length 
      }, 'Global task: filtering sites');
      
      if (sites.length === 0) {
        fastify?.log?.info('No sites to check (all have custom schedules)');
        await prisma.scheduleConfig.update({
          where: { id: latestConfig.id },
          data: { lastRun: new Date() }
        });
        return;
      }
      
      // 收集所有站点的变更和失败信息
      const sitesWithChanges = [];
      const failedSites = [];
      
      for (let i = 0; i < sites.length; i++) {
        const site = sites[i];
        try {
          fastify?.log?.info({ siteId: site.id, name: site.name }, `Checking site ${i + 1}/${sites.length}`);
          
          // 使用 skipNotification 参数跳过单站点邮件通知
          const result = await checkSite(site, fastify, { skipNotification: true, isManual: false });
          
          // 收集需要发送邮件通知的站点:
          // 1. 有模型变更(无论是否开启签到)
          // 2. 有签到结果(开启签到后,每次都发送)
          if (result.hasChanges || result.checkInResult) {
            sitesWithChanges.push({
              siteName: result.siteName,
              diff: result.hasChanges ? result.diff : null,
              checkInResult: result.checkInResult
            });
            
            const reasons = [];
            if (result.hasChanges) reasons.push('模型变更');
            if (result.checkInResult) reasons.push('签到结果');
            
            fastify?.log?.info({ 
              siteId: site.id,
              siteName: result.siteName,
              hasModelChanges: result.hasChanges,
              hasCheckInResult: !!result.checkInResult,
              reasons: reasons.join(' + ')
            }, `✅ 站点已添加到通知列表: ${reasons.join(' + ')}`);
          } else {
            fastify?.log?.info({ 
              siteId: site.id,
              siteName: result.siteName
            }, '⭕ 站点无变更且无签到,跳过通知');
          }
          
          fastify?.log?.info({ 
            siteId: site.id, 
            hasChanges: result.hasChanges,
            checkInChanged: result.checkInChanged 
          }, 'Site check completed');
        } catch (e) {
          fastify?.log?.error({ siteId: site.id, err: e.message }, 'Site check failed');
          // 收集失败的站点信息
          failedSites.push({
            siteName: site.name,
            error: e.message || String(e)
          });
        }
        
        // 等待间隔时间(除了最后一个站点),使用最新的interval配置
        if (i < sites.length - 1) {
          await new Promise(resolve => setTimeout(resolve, config.interval * 1000));
        }
      }
      
      // 如果有站点发生变更(模型或签到)或有失败,发送聚合邮件
      console.log(`\n[SCHEDULER] ========== 邮件发送检查 ==========`);
      console.log(`[SCHEDULER] 有变更/签到的站点数: ${sitesWithChanges.length}`);
      console.log(`[SCHEDULER] 失败站点数: ${failedSites.length}`);
      
      if (sitesWithChanges.length > 0) {
        console.log(`[SCHEDULER] 站点列表详情:`);
        sitesWithChanges.forEach((sc, idx) => {
          console.log(`  ${idx + 1}. ${sc.siteName}:`);
          console.log(`     - 模型变更: ${sc.diff ? '是' : '否'}`);
          console.log(`     - 签到结果: ${sc.checkInResult ? '是' : '否'}`);
          if (sc.checkInResult) {
            console.log(`       签到状态: ${sc.checkInResult.checkInSuccess ? '成功' : '失败'}`);
            console.log(`       签到消息: ${sc.checkInResult.checkInMessage}`);
          }
        });
      }
      
      if (sitesWithChanges.length > 0 || failedSites.length > 0) {
        try {
          console.log(`[SCHEDULER] 准备发送聚合邮件通知...`);
          fastify?.log?.info({
            sitesWithChangesCount: sitesWithChanges.length,
            failedCount: failedSites.length
          }, 'Sending aggregated notification');
          await sendAggregatedNotification(sitesWithChanges, fastify, failedSites);
          console.log(`[SCHEDULER] ✅ 邮件发送完成`);
        } catch (emailError) {
          console.error(`[SCHEDULER] ❌ 邮件发送失败:`, emailError);
          fastify?.log?.error({ err: emailError.message }, 'Aggregated notification failed');
        }
      } else {
        console.log(`[SCHEDULER] ⭕ 没有需要通知的站点,跳过邮件发送`);
        fastify?.log?.info('No changes or failures detected, skipping notification');
      }
      console.log(`[SCHEDULER] ==========================================\n`);
      
      // 更新最后运行时间
      await prisma.scheduleConfig.update({
        where: { id: latestConfig.id },
        data: { lastRun: new Date() }
      });
      
      fastify?.log?.info('Global schedule task completed');
    } catch (e) {
      fastify?.log?.error({ err: e.message }, 'Global schedule task error');
    }
  }, {
    timezone: timezone,
    scheduled: true  // 确保任务被启动
  });
  
  // 显式启动全局任务
  globalScheduleJob.start();
  
  fastify?.log?.info({ cronExp: cronExp, timezone: timezone }, 'Global schedule task created and started');
}

module.exports = { scheduleAll, onSiteUpdated, onSiteDeleted, scheduleGlobalTask, scheduleCategory, scheduleAllCategories };