-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathlive.js
More file actions
486 lines (426 loc) · 13.6 KB
/
live.js
File metadata and controls
486 lines (426 loc) · 13.6 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
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
/**
* 直播数据解析服务
* 负责解析M3U和TXT格式的直播文件
*/
import axios from 'axios'
import configService from './config.js'
/**
* 直播服务类
*/
class LiveService {
constructor() {
this.liveData = null
this.lastFetchTime = null
this.cacheExpiry = 10 * 60 * 1000 // 10分钟缓存
}
/**
* 获取直播配置信息
* @returns {Promise<object|null>} 直播配置信息
*/
async getLiveConfig() {
try {
// 优先使用独立的直播配置地址
const liveConfigUrl = configService.getLiveConfigUrl()
if (liveConfigUrl) {
return {
name: '直播配置',
url: liveConfigUrl,
type: 'live'
}
}
// 如果没有独立的直播配置地址,尝试从点播配置中获取(向后兼容)
const configData = await configService.getConfigData()
if (configData && configData.lives && Array.isArray(configData.lives) && configData.lives.length > 0) {
return configData.lives[0] // 通常只有一个直播配置
}
return null
} catch (error) {
console.error('获取直播配置失败:', error)
return null
}
}
/**
* 获取直播数据
* @param {boolean} forceRefresh - 是否强制刷新
* @returns {Promise<object>} 解析后的直播数据
*/
async getLiveData(forceRefresh = false) {
try {
// 检查缓存是否有效
const now = Date.now()
const isCacheValid = this.liveData &&
this.lastFetchTime &&
(now - this.lastFetchTime) < this.cacheExpiry
if (!forceRefresh && isCacheValid) {
console.log('使用缓存的直播数据')
return this.liveData
}
// 获取直播配置
const liveConfig = await this.getLiveConfig()
if (!liveConfig || !liveConfig.url) {
throw new Error('未找到直播配置或直播地址')
}
console.log('从直播地址获取数据:', liveConfig.url)
// 获取直播文件内容
const response = await axios.get(liveConfig.url, {
timeout: 15000
// 注意:浏览器环境下不能设置 User-Agent 头,浏览器会自动处理
})
if (!response.data) {
throw new Error('直播数据为空')
}
// 根据URL判断文件类型并解析
const fileContent = response.data
let parsedData
if (liveConfig.url.toLowerCase().includes('.m3u')) {
parsedData = this.parseM3U(fileContent, liveConfig)
} else if (liveConfig.url.toLowerCase().includes('.txt')) {
parsedData = this.parseTXT(fileContent, liveConfig)
} else {
// 尝试根据内容判断格式
if (fileContent.includes('#EXTM3U') || fileContent.includes('#EXTINF')) {
parsedData = this.parseM3U(fileContent, liveConfig)
} else if (fileContent.includes('#genre#')) {
parsedData = this.parseTXT(fileContent, liveConfig)
} else {
throw new Error('不支持的直播文件格式')
}
}
this.liveData = parsedData
this.lastFetchTime = now
console.log('直播数据解析成功,分组数量:', parsedData.groups.length)
return this.liveData
} catch (error) {
console.error('获取直播数据失败:', error)
throw error
}
}
/**
* 解析M3U格式的直播文件
* @param {string} content - 文件内容
* @param {object} config - 直播配置
* @returns {object} 解析后的数据
*/
parseM3U(content, config) {
const lines = content.split('\n').map(line => line.trim()).filter(line => line)
const groups = new Map()
const channels = []
let currentChannel = null
for (let i = 0; i < lines.length; i++) {
const line = lines[i]
if (line.startsWith('#EXTINF:')) {
// 解析频道信息 - 修复正则表达式来正确处理属性和频道名称
const match = line.match(/#EXTINF:(-?\d+),(.*)$/)
if (match) {
const duration = match[1]
const fullStr = match[2].trim()
// 查找最后一个逗号,分离属性和频道名称
const lastCommaIndex = fullStr.lastIndexOf(',')
let attributesStr = ''
let displayName = fullStr
if (lastCommaIndex > 0) {
// 检查逗号前是否有属性(包含=号)
const beforeComma = fullStr.substring(0, lastCommaIndex)
if (beforeComma.includes('=')) {
attributesStr = beforeComma
displayName = fullStr.substring(lastCommaIndex + 1).trim()
}
}
// 解析属性
const attributes = {}
if (attributesStr) {
// 匹配所有属性,包括 tvg-id、tvg-name、tvg-logo、group-title 等
const attrMatches = attributesStr.matchAll(/(\w+(?:-\w+)*)="([^"]*)"/g)
for (const attrMatch of attrMatches) {
attributes[attrMatch[1]] = attrMatch[2]
}
}
// 频道名称优先使用 tvg-name,其次使用显示名称
const channelName = attributes['tvg-name'] || displayName
const groupName = attributes['group-title'] || '未分组'
const logoUrl = attributes['tvg-logo'] || this.generateLogoUrl(channelName, config)
// 解析清晰度信息(从显示名称中提取)
const qualityInfo = this.extractQualityInfo(displayName)
currentChannel = {
name: channelName,
displayName: displayName, // 保留原始显示名称
group: groupName,
logo: logoUrl,
tvgId: attributes['tvg-id'] || '',
tvgName: attributes['tvg-name'] || channelName,
quality: qualityInfo.quality,
resolution: qualityInfo.resolution,
codec: qualityInfo.codec,
url: null
}
}
} else if (line.startsWith('http') && currentChannel) {
// 设置频道URL
currentChannel.url = line
channels.push(currentChannel)
// 添加到分组,并处理同名频道的线路归类
const groupName = currentChannel.group
if (!groups.has(groupName)) {
groups.set(groupName, {
name: groupName,
channels: []
})
}
const group = groups.get(groupName)
// 查找是否已存在同名频道
const existingChannel = group.channels.find(ch => ch.name === currentChannel.name)
if (existingChannel) {
// 如果已存在同名频道,添加为新线路
if (!existingChannel.routes) {
// 将原有频道转换为线路1
existingChannel.routes = [
{
id: 1,
name: '线路1',
url: existingChannel.url,
quality: existingChannel.quality,
resolution: existingChannel.resolution,
codec: existingChannel.codec
}
]
}
// 添加新线路
existingChannel.routes.push({
id: existingChannel.routes.length + 1,
name: `线路${existingChannel.routes.length + 1}`,
url: currentChannel.url,
quality: currentChannel.quality,
resolution: currentChannel.resolution,
codec: currentChannel.codec
})
// 更新频道的当前线路为第一个线路
existingChannel.currentRoute = existingChannel.routes[0]
} else {
// 新频道,直接添加
group.channels.push(currentChannel)
}
currentChannel = null
}
}
return {
config: config,
groups: Array.from(groups.values()),
channels: channels,
totalChannels: channels.length
}
}
/**
* 从显示名称中提取清晰度信息
* @param {string} displayName - 显示名称
* @returns {object} 清晰度信息
*/
extractQualityInfo(displayName) {
const result = {
quality: '',
resolution: '',
codec: ''
}
// 提取清晰度标识
const qualityPatterns = [
/高码/,
/超清/,
/高清/,
/标清/,
/流畅/
]
// 提取分辨率信息
const resolutionPatterns = [
/4K/i,
/1080[pP]/,
/720[pP]/,
/576[pP]/,
/480[pP]/,
/(\d+)[pP]/
]
// 提取编码格式
const codecPatterns = [
/HEVC/i,
/H\.?264/i,
/H\.?265/i,
/AVC/i
]
// 提取帧率信息
const fpsPatterns = [
/(\d+)[-\s]?FPS/i,
/(\d+)帧/
]
// 匹配清晰度
for (const pattern of qualityPatterns) {
const match = displayName.match(pattern)
if (match) {
result.quality = match[0]
break
}
}
// 匹配分辨率
for (const pattern of resolutionPatterns) {
const match = displayName.match(pattern)
if (match) {
result.resolution = match[0]
break
}
}
// 匹配编码格式
for (const pattern of codecPatterns) {
const match = displayName.match(pattern)
if (match) {
result.codec = match[0]
break
}
}
// 匹配帧率
for (const pattern of fpsPatterns) {
const match = displayName.match(pattern)
if (match) {
result.fps = match[1] || match[0]
break
}
}
return result
}
/**
* 解析TXT格式的直播文件
* @param {string} content - 文件内容
* @param {object} config - 直播配置
* @returns {object} 解析后的数据
*/
parseTXT(content, config) {
const lines = content.split('\n').map(line => line.trim()).filter(line => line)
const groups = new Map()
const channels = []
let currentGroupName = '未分组'
for (const line of lines) {
if (line.includes('#genre#')) {
// 分组标记 - 格式为 "分组名称,#genre#"
const genreIndex = line.indexOf('#genre#')
if (genreIndex > 0) {
// 提取逗号前的分组名称
currentGroupName = line.substring(0, genreIndex).replace(/,$/, '').trim()
} else {
// 兼容其他可能的格式
currentGroupName = line.replace('#genre#', '').trim()
}
if (!groups.has(currentGroupName)) {
groups.set(currentGroupName, {
name: currentGroupName,
channels: []
})
}
} else if (line.includes(',http')) {
// 频道信息
const parts = line.split(',')
if (parts.length >= 2) {
const name = parts[0].trim()
const url = parts.slice(1).join(',').trim()
const channel = {
name: name,
group: currentGroupName,
logo: this.generateLogoUrl(name, config),
tvgName: name,
url: url
}
channels.push(channel)
// 添加到分组
if (!groups.has(currentGroupName)) {
groups.set(currentGroupName, {
name: currentGroupName,
channels: []
})
}
groups.get(currentGroupName).channels.push(channel)
}
}
}
return {
config: config,
groups: Array.from(groups.values()),
channels: channels,
totalChannels: channels.length
}
}
/**
* 生成频道Logo URL
* @param {string} channelName - 频道名称
* @param {object} config - 直播配置
* @returns {string} Logo URL
*/
generateLogoUrl(channelName, config) {
if (config.logo && config.logo.includes('{name}')) {
return config.logo.replace('{name}', encodeURIComponent(channelName))
}
return ''
}
/**
* 获取EPG信息
* @param {string} channelName - 频道名称
* @param {string} date - 日期 (YYYY-MM-DD)
* @param {object} config - 直播配置
* @returns {string} EPG URL
*/
getEPGUrl(channelName, date, config) {
if (config.epg && config.epg.includes('{name}') && config.epg.includes('{date}')) {
return config.epg
.replace('{name}', encodeURIComponent(channelName))
.replace('{date}', date)
}
return ''
}
/**
* 搜索频道
* @param {string} keyword - 搜索关键词
* @returns {Array} 匹配的频道列表
*/
searchChannels(keyword) {
if (!this.liveData || !keyword) {
return []
}
const lowerKeyword = keyword.toLowerCase()
return this.liveData.channels.filter(channel =>
channel.name.toLowerCase().includes(lowerKeyword) ||
channel.group.toLowerCase().includes(lowerKeyword)
)
}
/**
* 根据分组获取频道
* @param {string} groupName - 分组名称
* @returns {Array} 频道列表
*/
getChannelsByGroup(groupName) {
if (!this.liveData) {
return []
}
const group = this.liveData.groups.find(g => g.name === groupName)
return group ? group.channels : []
}
/**
* 清除缓存
*/
clearCache() {
this.liveData = null
this.lastFetchTime = null
console.log('直播数据缓存已清除')
}
/**
* 获取直播数据状态
* @returns {object} 状态信息
*/
getStatus() {
return {
hasData: !!this.liveData,
lastFetchTime: this.lastFetchTime,
cacheAge: this.lastFetchTime ? Date.now() - this.lastFetchTime : null,
isCacheValid: this.liveData && this.lastFetchTime &&
(Date.now() - this.lastFetchTime) < this.cacheExpiry,
groupsCount: this.liveData ? this.liveData.groups.length : 0,
channelsCount: this.liveData ? this.liveData.totalChannels : 0
}
}
}
// 创建单例实例
const liveService = new LiveService()
export default liveService