-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdate.js
More file actions
303 lines (248 loc) · 7.42 KB
/
update.js
File metadata and controls
303 lines (248 loc) · 7.42 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
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
/*
Module: VLESS RU Filter Updater
Description: Downloads parent VLESS list, filters RU servers, validates entries, writes cheburnet.txt, logs actions, auto-inits git repo, checks SSH key, commits and pushes changes. Supports single-run and daemon mode with jitter and watchdog.
Run: node update.js [--daemon]
File: update.js
*/
import fs from "fs";
import path from "path";
import https from "https";
import { execSync } from "child_process";
import { fileURLToPath } from "url";
// Resolve working directory
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Config
const PARENT_URL = "https://raw.githubusercontent.com/zieng2/wl/main/vless_lite.txt";
const OUTPUT_FILE = path.join(__dirname, "cheburnet.txt");
const LOG_FILE = path.join(__dirname, "update.log");
const AUTO_INIT = true;
// Log function
function log(msg) {
const timestamp = new Date().toISOString().replace("T", " ").split(".")[0];
fs.appendFileSync(LOG_FILE, `[${timestamp}] ${msg}\n`);
console.log(msg);
}
// Download function
function download(url) {
return new Promise((resolve, reject) => {
https
.get(url, (res) => {
if (res.statusCode !== 200) {
reject(new Error("HTTP " + res.statusCode));
return;
}
let data = "";
res.on("data", (chunk) => (data += chunk));
res.on("end", () => resolve(data));
})
.on("error", reject);
});
}
// Validate VLESS entry
function isValidVless(line) {
if (!line.startsWith("vless://")) return false;
if (!line.includes("@")) return false;
if (!line.includes("#")) return false;
const [urlPart] = line.split("#");
if (urlPart.includes(" ")) return false;
return true;
}
// Detect RU-tag
function isRussianTagged(line) {
return (
line.includes("🇷🇺") ||
line.includes("%F0%9F%87%B7%F0%9F%87%BA")
);
}
// Filter only Russian servers + validate
function filterRussian(list) {
const lines = list.split("\n");
const filtered = lines
.map((l) => l.trim())
.filter((line) => line.length > 0)
.filter((line) => line.includes("vless://"))
.filter(isRussianTagged)
.filter(isValidVless);
// Remove duplicates
return Array.from(new Set(filtered)).join("\n");
}
// Write output file
function writeOutput(content) {
fs.writeFileSync(OUTPUT_FILE, content, "utf8");
}
// Check if file content changed (set-based comparison)
function hasChanged(newContent) {
if (!fs.existsSync(OUTPUT_FILE)) return true;
const oldLines = fs.readFileSync(OUTPUT_FILE, "utf8")
.split("\n")
.map(l => l.trim())
.filter(l => l.length > 0);
const newLines = newContent
.split("\n")
.map(l => l.trim())
.filter(l => l.length > 0);
if (oldLines.length !== newLines.length) return true;
const oldSet = new Set(oldLines);
const newSet = new Set(newLines);
if (oldSet.size !== newSet.size) return true;
for (const line of newSet) {
if (!oldSet.has(line)) return true;
}
return false;
}
// Check if inside a git repo
function isGitRepo() {
return fs.existsSync(path.join(__dirname, ".git"));
}
// Check if git exists
function gitExists() {
try {
execSync("git --version", { stdio: "ignore" });
return true;
} catch {
return false;
}
}
// Auto-init git repo
function gitInit() {
if (!AUTO_INIT) return;
if (!gitExists()) {
log("Git not found. Cannot auto-init repo.");
return;
}
log("Initializing git repository...");
execSync("git init", { stdio: "ignore" });
execSync("git branch -M main", { stdio: "ignore" });
log("Git repository initialized.");
}
// Check SSH key availability (GitHub returns exit code 1 even on success)
function sshAvailable() {
try {
const out = execSync(
"ssh -T -o BatchMode=yes git@github.com-jebance",
{ encoding: "utf8" }
);
return out.includes("successfully authenticated");
} catch (err) {
const output =
(err.stdout ? err.stdout.toString() : "") +
(err.stderr ? err.stderr.toString() : "");
return output.includes("successfully authenticated");
}
}
// Обновлённая функция gitCommit
function gitCommit() {
if (!gitExists()) {
log("Git not found. Skipping commit.");
return;
}
// --- НАСТРОЙКА ПОЛЬЗОВАТЕЛЯ (ваши данные) ---
try {
execSync('git config user.name "JeBance"');
execSync('git config user.email "oleg.prudkov@gmail.com"');
} catch (e) {
log("Failed to set git user");
}
// -------------------------------------------
// Проверяем, запущены ли мы в GitHub Actions
const isGitHubActions = !!process.env.GITHUB_ACTIONS;
const token = process.env.GITHUB_TOKEN;
if (isGitHubActions && token) {
// Меняем remote URL, чтобы использовать токен для пуша
const repoUrl = `https://x-access-token:${token}@github.com/${process.env.GITHUB_REPOSITORY}.git`;
try {
execSync(`git remote set-url origin ${repoUrl}`);
} catch (e) {
log("Failed to set remote URL with token");
}
} else {
// В обычной среде проверяем SSH
if (!sshAvailable()) {
log("SSH key not available. Skipping push.");
return;
}
}
try {
const fileName = path.basename(OUTPUT_FILE);
execSync(`git add ${fileName}`);
// --- ЯВНО УКАЗЫВАЕМ АВТОРА КОММИТА ---
const author = "JeBance <oleg.prudkov@gmail.com>";
execSync(`git commit --author="${author}" -m "chore: update cheburnet.txt (RU-only VLESS list sync)"`);
// ---------------------------------------
execSync("git push");
log("Git commit pushed.");
} catch {
log("No changes to commit.");
}
}
// Main logic
async function main() {
log("Downloading parent list...");
let raw;
try {
raw = await download(PARENT_URL);
log("Download OK");
} catch (err) {
log("Download failed: " + err.message);
log("Fallback: using previous version");
return;
}
log("Filtering RU servers...");
const filtered = filterRussian(raw);
const linesCount =
filtered.trim().length === 0
? 0
: filtered.split("\n").filter((l) => l.trim().length > 0).length;
log("Filtered entries: " + linesCount);
if (linesCount === 0) {
log("No RU entries found. Exiting.");
return;
}
if (!hasChanged(filtered)) {
log("No changes detected. Exiting.");
return;
}
log("Writing output file...");
writeOutput(filtered);
log("Committing changes...");
gitCommit();
log("Done.");
}
// Watchdog wrapper
async function safeMain() {
return new Promise((resolve) => {
let finished = false;
const timeout = setTimeout(() => {
if (!finished) {
log("Watchdog: main() timeout, restarting...");
resolve();
}
}, 5 * 60 * 1000);
main()
.catch((err) => log("Fatal error: " + err.message))
.finally(() => {
finished = true;
clearTimeout(timeout);
resolve();
});
});
}
// Daemon mode
async function daemon() {
while (true) {
await safeMain();
const jitter = Math.floor(Math.random() * 10 * 60 * 1000) - 5 * 60 * 1000;
const sleepTime = 24 * 60 * 60 * 1000 + jitter;
log("Sleeping for " + Math.round(sleepTime / 60000) + " minutes...");
await new Promise((resolve) => setTimeout(resolve, sleepTime));
}
}
// Entry point
const args = process.argv.slice(2);
if (args.includes("--daemon")) {
log("Starting in daemon mode...");
daemon();
} else {
safeMain();
}