-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_force_check.js
More file actions
177 lines (149 loc) · 7.24 KB
/
Copy pathrun_force_check.js
File metadata and controls
177 lines (149 loc) · 7.24 KB
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
import dotenv from 'dotenv';
import Logger from './src/utils/logger.js';
import { forceCheckAllMonitors } from './src/utils/force_check.js';
import crud from './src/crud.js';
import mongoose from 'mongoose';
import { Telegraf } from 'telegraf';
import MonitoringService from './src/services/monitoring_service.js';
import { fetchCookie } from './src/api/fetchCookie.js';
// Load environment variables
dotenv.config();
// Get MongoDB URI from environment variables
const mongoUri = process.env.MONGODB_URI;
if (!mongoUri) {
console.error('MongoDB URI not found in environment variables. Please set MONGODB_URI in .env file.');
process.exit(1);
}
// Initialize the bot
const bot = new Telegraf(process.env.TELEGRAM_BOT_TOKEN);
// Connect to MongoDB
console.log('Connecting to MongoDB...');
mongoose.connect(mongoUri)
.then(() => {
console.log('Connected to MongoDB');
runForceCheck();
})
.catch(err => {
console.error('Failed to connect to MongoDB:', err);
process.exit(1);
});
// Function to run the force check
async function runForceCheck() {
try {
Logger.info('[MANUAL] Starting manual force check...');
console.log('[MANUAL] Starting manual force check...');
// Get admin user ID from environment variable or use the first admin from the database
let adminUserId = process.env.ADMIN_USER_IDS ? process.env.ADMIN_USER_IDS.split(',')[0].trim() : null;
if (!adminUserId) {
try {
// Get all users from the database
const users = await crud.getAllUsers();
if (users && users.length > 0) {
adminUserId = users[0].userId;
Logger.info(`[MANUAL] Using user ID from database: ${adminUserId}`);
console.log(`[MANUAL] Using user ID from database: ${adminUserId}`);
} else {
Logger.error('[MANUAL] No users found in database');
console.error('[MANUAL] No users found in database');
process.exit(1);
}
} catch (dbError) {
Logger.error(`[MANUAL] Error getting users from database: ${dbError.message}`);
console.error('[MANUAL] Error getting users from database:', dbError);
process.exit(1);
}
} else {
Logger.info(`[MANUAL] Using admin user ID from environment: ${adminUserId}`);
console.log(`[MANUAL] Using admin user ID from environment: ${adminUserId}`);
}
// Get a cookie for API requests
console.log('[MANUAL] Fetching cookie...');
let cookie = null;
try {
const cookieResult = await fetchCookie();
if (cookieResult && cookieResult.cookie) {
cookie = cookieResult.cookie;
console.log('[MANUAL] Cookie fetched successfully');
} else {
console.log('[MANUAL] Failed to fetch cookie, checking for cookie file...');
// Try to read cookie from file
const fs = await import('fs');
if (fs.existsSync('./cookies.txt')) {
cookie = fs.readFileSync('./cookies.txt', 'utf8').trim();
console.log('[MANUAL] Using cookie from cookies.txt file');
} else {
console.error('[MANUAL] No cookie available, cannot proceed');
process.exit(1);
}
}
} catch (cookieError) {
console.error('[MANUAL] Error fetching cookie:', cookieError);
process.exit(1);
}
// Create a temporary monitoring service for the force check
console.log('[MANUAL] Creating temporary monitoring service...');
const monitoringService = new MonitoringService(bot);
monitoringService.setCookie(cookie);
// Find the highest item ID
console.log('[MANUAL] Finding highest item ID...');
await monitoringService.findHighestItemID();
console.log(`[MANUAL] Found highest item ID: ${monitoringService.currentID}`);
// Run a check for all active monitors
console.log('[MANUAL] Checking all active monitors...');
const monitors = await crud.getAllActiveMonitors();
console.log(`[MANUAL] Found ${monitors.length} active monitors`);
// Process each monitor
let processedCount = 0;
let itemsFound = 0;
for (const monitor of monitors) {
try {
console.log(`[MANUAL] Processing monitor ${monitor._id} (${monitor.name || 'Unnamed'})...`);
// Get the user for this monitor
const user = await crud.getUserById(monitor.user);
if (!user) {
console.log(`[MANUAL] User not found for monitor ${monitor._id}, skipping`);
continue;
}
// Fetch the latest items for this monitor
console.log(`[MANUAL] Fetching latest items for monitor ${monitor._id}...`);
const result = await monitoringService.fetchLatestItemsForMonitor(monitor);
if (result && result.items && result.items.length > 0) {
console.log(`[MANUAL] Found ${result.items.length} items for monitor ${monitor._id}`);
// Process the first item as a test notification
const firstItem = result.items[0];
await monitoringService.processItem(firstItem, monitor, user);
// Update the monitor's last item
await crud.updateMonitor(monitor._id, {
lastItem: firstItem.id.toString(),
lastChecked: new Date()
});
itemsFound++;
} else {
console.log(`[MANUAL] No items found for monitor ${monitor._id}`);
}
processedCount++;
} catch (monitorError) {
console.error(`[MANUAL] Error processing monitor ${monitor._id}:`, monitorError);
}
}
console.log(`[MANUAL] Force check completed. Processed ${processedCount} monitors, found ${itemsFound} items.`);
Logger.info(`[MANUAL] Force check completed. Processed ${processedCount} monitors, found ${itemsFound} items.`);
// Close the MongoDB connection
await mongoose.connection.close();
console.log('Closed MongoDB connection');
// Exit the process
process.exit(0);
} catch (error) {
Logger.error(`[MANUAL] Error in manual force check: ${error.message}`);
console.error('[MANUAL] Error in manual force check:', error);
// Close the MongoDB connection
try {
await mongoose.connection.close();
console.log('Closed MongoDB connection');
} catch (err) {
console.error('Error closing MongoDB connection:', err);
}
// Exit the process with an error code
process.exit(1);
}
}