-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathconfig.js
289 lines (272 loc) · 11.5 KB
/
config.js
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
import {readdirSync, readFileSync, writeFileSync, existsSync} from 'fs';
import path from 'path';
import * as drpy from '../libs/drpyS.js';
import {naturalSort, urljoin} from '../utils/utils.js'
import {ENV} from "../utils/env.js";
import {validatePwd} from "../utils/api_validate.js";
import {getSitesMap} from "../utils/sites-map.js";
import batchExecute from '../libs_drpy/batchExecute.js';
const {jsEncoder} = drpy;
// 工具函数:生成 JSON 数据
async function generateSiteJSON(jsDir, configDir, requestHost, sub, subFilePath, pwd) {
const files = readdirSync(jsDir);
let valid_files = files.filter((file) => file.endsWith('.js') && !file.startsWith('_')); // 筛选出不是 "_" 开头的 .js 文件
let sort_list = [];
if (sub) {
if (sub.mode === 0) {
valid_files = valid_files.filter(it => (new RegExp(sub.reg || '.*')).test(it));
} else if (sub.mode === 1) {
valid_files = valid_files.filter(it => !(new RegExp(sub.reg || '.*')).test(it));
}
let sort_file = path.join(path.dirname(subFilePath), `./order_common.html`);
if (!existsSync(sort_file)) {
sort_file = path.join(path.dirname(subFilePath), `./order_common.example.html`);
}
if (sub.sort) {
sort_file = path.join(path.dirname(subFilePath), `./${sub.sort}.html`);
if (!existsSync(sort_file)) {
sort_file = path.join(path.dirname(subFilePath), `./${sub.sort}.example.html`);
}
}
if (existsSync(sort_file)) {
console.log('sort_file:', sort_file);
let sort_file_content = readFileSync(sort_file, 'utf-8');
// console.log(sort_file_content)
sort_list = sort_file_content.split('\n').filter(it => it.trim()).map(it => it.trim());
// console.log(sort_list);
}
}
let sites = [];
// console.log('hide_adult:', ENV.get('hide_adult'));
if (ENV.get('hide_adult') === '1') {
valid_files = valid_files.filter(it => !(new RegExp('\\[[密]\\]|密+')).test(it));
}
let SitesMap = getSitesMap(configDir);
// console.log(SitesMap);
const tasks = valid_files.map((file) => {
return {
func: async ({file, jsDir, requestHost, pwd, drpy, SitesMap, jsEncoder}) => {
const baseName = path.basename(file, '.js'); // 去掉文件扩展名
let api = `${requestHost}/api/${baseName}`; // 使用请求的 host 地址,避免硬编码端口
if (pwd) {
api += `?pwd=${pwd}`;
}
let ruleObject = {
searchable: 0, // 固定值
filterable: 0, // 固定值
quickSearch: 0, // 固定值
};
try {
ruleObject = await drpy.getRuleObject(path.join(jsDir, file));
} catch (e) {
throw new Error(`Error parsing rule object for file: ${file}, ${e.message}`);
}
let fileSites = [];
if (baseName === 'push_agent') {
let key = 'push_agent';
let name = `${ruleObject.title}(DS)`;
fileSites.push({key, name});
} else if (SitesMap.hasOwnProperty(baseName) && Array.isArray(SitesMap[baseName])) {
SitesMap[baseName].forEach((it) => {
let key = `drpyS_${it.alias}`;
let name = `${it.alias}(DS)`;
let ext = it.queryObject.type === 'url' ? it.queryObject.params : it.queryStr;
if (ext) {
ext = jsEncoder.gzip(ext);
}
fileSites.push({key, name, ext});
});
} else {
let key = `drpyS_${baseName}`;
let name = `${baseName}(DS)`;
fileSites.push({key, name});
}
fileSites.forEach((fileSite) => {
const site = {
key: fileSite.key,
name: fileSite.name,
type: 4, // 固定值
api,
searchable: ruleObject.searchable,
filterable: ruleObject.filterable,
quickSearch: ruleObject.quickSearch,
more: ruleObject.more,
ext: fileSite.ext || "", // 固定为空字符串
};
sites.push(site);
});
},
param: {file, jsDir, requestHost, pwd, drpy, SitesMap, jsEncoder},
id: file,
};
});
const listener = {
func: (param, id, error, result) => {
if (error) {
console.error(`Error processing file ${id}:`, error.message);
} else {
// console.log(`Successfully processed file ${id}:`, result);
}
},
param: {}, // 外部参数可以在这里传入
};
await batchExecute(tasks, listener);
// 订阅再次处理别名的情况
if (sub) {
if (sub.mode === 0) {
sites = sites.filter(it => (new RegExp(sub.reg || '.*')).test(it.name));
} else if (sub.mode === 1) {
sites = sites.filter(it => !(new RegExp(sub.reg || '.*')).test(it.name));
}
}
// 青少年模式再次处理自定义别名的情况
if (ENV.get('hide_adult') === '1') {
sites = sites.filter(it => !(new RegExp('\\[[密]\\]|密+')).test(it.name));
}
sites = naturalSort(sites, 'name', sort_list);
return {sites};
}
function generateParseJSON(jxDir, requestHost) {
const files = readdirSync(jxDir);
const parses = files
.filter((file) => file.endsWith('.js') && !file.startsWith('_')) // 筛选出不是 "_" 开头的 .js 文件
.map((file) => {
const baseName = path.basename(file, '.js'); // 去掉文件扩展名
const api = `${requestHost}/parse/${baseName}?url=`; // 使用请求的 host 地址,避免硬编码端口
return {
name: baseName,
url: api,
type: 1,
ext: {
flag: [
"qiyi",
"imgo",
"爱奇艺",
"奇艺",
"qq",
"qq 预告及花絮",
"腾讯",
"youku",
"优酷",
"pptv",
"PPTV",
"letv",
"乐视",
"leshi",
"mgtv",
"芒果",
"sohu",
"xigua",
"fun",
"风行"
]
},
header: {
"User-Agent": "Mozilla/5.0"
}
}
});
return {parses};
}
function generateLivesJSON(requestHost) {
let lives = [];
let live_url = process.env.LIVE_URL || '';
let epg_url = process.env.EPG_URL || ''; // 从.env文件读取
let logo_url = process.env.LOGO_URL || ''; // 从.env文件读取
if (live_url && !live_url.startsWith('http')) {
let public_url = urljoin(requestHost, 'public/');
live_url = urljoin(public_url, live_url);
}
// console.log('live_url:', live_url);
if (live_url) {
lives.push(
{
"name": "直播",
"type": 0,
"url": live_url,
"playerType": 1,
"ua": "okhttp/3.12.13",
"epg": epg_url,
"logo": logo_url
}
)
}
return {lives}
}
function generatePlayerJSON(configDir, requestHost) {
let playerConfig = {};
let playerConfigPath = path.join(configDir, './player.json');
if (existsSync(playerConfigPath)) {
try {
playerConfig = JSON.parse(readFileSync(playerConfigPath, 'utf-8'))
} catch (e) {
}
}
return playerConfig
}
function getSubs(subFilePath) {
let subs = [];
try {
const subContent = readFileSync(subFilePath, 'utf-8');
subs = JSON.parse(subContent)
} catch (e) {
console.log(`读取订阅失败:${e.message}`);
}
return subs
}
export default (fastify, options, done) => {
fastify.get('/index', {preHandler: validatePwd}, async (request, reply) => {
if (!existsSync(options.indexFilePath)) {
reply.code(404).send({error: 'index.json not found'});
return;
}
const content = readFileSync(options.indexFilePath, 'utf-8');
reply.send(JSON.parse(content));
});
// 接口:返回配置 JSON,同时写入 index.json
fastify.get('/config*', {preHandler: validatePwd}, async (request, reply) => {
let t1 = (new Date()).getTime();
const query = request.query; // 获取 query 参数
const pwd = query.pwd || '';
const sub_code = query.sub || '';
const cfg_path = request.params['*']; // 捕获整个路径
try {
// 获取主机名,协议及端口
const protocol = request.headers['x-forwarded-proto'] || (request.socket.encrypted ? 'https' : 'http'); // http 或 https
const hostname = request.hostname; // 主机名,不包含端口
const port = request.socket.localPort; // 获取当前服务的端口
console.log(`cfg_path:${cfg_path},port:${port}`);
let requestHost = cfg_path === '/1' ? `${protocol}://${hostname}` : `http://127.0.0.1:${options.PORT}`; // 动态生成根地址
let sub = null;
if (sub_code) {
let subs = getSubs(options.subFilePath);
sub = subs.find(it => it.code === sub_code);
// console.log('sub:', sub);
if (sub && sub.status === 0) {
return reply.status(500).send({error: `此订阅码:【${sub_code}】已禁用`});
}
}
const siteJSON = await generateSiteJSON(options.jsDir, options.configDir, requestHost, sub, options.subFilePath, pwd);
const parseJSON = generateParseJSON(options.jxDir, requestHost);
const livesJSON = generateLivesJSON(requestHost);
const playerJSON = generatePlayerJSON(options.configDir, requestHost);
const configObj = {sites_count: siteJSON.sites.length, ...siteJSON, ...parseJSON, ...livesJSON, ...playerJSON};
// console.log(configObj);
const configStr = JSON.stringify(configObj, null, 2);
if (!process.env.VERCEL) { // Vercel 环境不支持写文件,关闭此功能
writeFileSync(options.indexFilePath, configStr, 'utf8'); // 写入 index.json
if (cfg_path === '/1') {
writeFileSync(options.customFilePath, configStr, 'utf8'); // 写入 index.json
}
}
let t2 = (new Date()).getTime();
let cost = t2 - t1;
// configObj.cost = cost;
// reply.send(configObj);
reply.send(Object.assign({cost}, configObj));
} catch (error) {
reply.status(500).send({error: 'Failed to generate site JSON', details: error.message});
}
});
done();
};