-
-
Notifications
You must be signed in to change notification settings - Fork 7.7k
Expand file tree
/
Copy pathupdate.ts
More file actions
288 lines (234 loc) · 7.99 KB
/
Copy pathupdate.ts
File metadata and controls
288 lines (234 loc) · 7.99 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
import { getStreamInfo, loadIssues, createThread } from '../../utils'
import { STREAMS_DIR, LOGS_DIR } from '../../constants'
import { Playlist, Issue, Stream } from '../../models'
import { loadData, data as apiData } from '../../api'
import { Logger, Collection } from '@freearhey/core'
import { Storage } from '@freearhey/storage-js'
import { PlaylistParser } from '../../core'
import * as sdk from '@iptv-org/sdk'
const processedIssues = new Collection<Issue>()
const skippedIssues = new Collection<Issue>()
const logger = new Logger({ level: 5 })
let streams = new Collection<Stream>()
let cache = new Collection<Stream>()
function cacheData() {
cache = streams.clone()
}
function resetData() {
streams = cache
}
async function main() {
logger.info('loading data from api...')
await loadData()
logger.info('loading issues...')
const issues = await loadIssues()
logger.info('loading streams...')
await loadStreams()
logger.info('processing issues...')
await processIssues(issues)
logger.info('saving streams...')
await saveStreams()
logger.info('saving logs...')
await saveLogs()
logger.info(
`skipped ${skippedIssues.count()} issue(s): ${skippedIssues
.map((issue: Issue) => `#${issue.number}`)
.join(', ')}`
)
logger.info(
`processed ${processedIssues.count()} issue(s): ${processedIssues
.map((issue: Issue) => `#${issue.number}`)
.join(', ')}`
)
}
main()
async function saveLogs() {
const logStorage = new Storage(LOGS_DIR)
const output = processedIssues.map((issue: Issue) => `closes #${issue.number}`).join(', ')
await logStorage.save('playlist_update.log', output)
}
async function saveStreams() {
const streamsStorage = new Storage(STREAMS_DIR)
const groupedStreams = streams.groupBy((stream: Stream) => stream.getFilepath())
for (const filepath of groupedStreams.keys()) {
let filteredStreams = new Collection<Stream>(groupedStreams.get(filepath))
filteredStreams = filteredStreams.filter((stream: Stream) => stream.removed === false)
const playlist = new Playlist(filteredStreams, { public: false })
await streamsStorage.save(filepath, playlist.toString())
}
}
async function loadStreams() {
const streamsStorage = new Storage(STREAMS_DIR)
const parser = new PlaylistParser({
storage: streamsStorage
})
const files = await streamsStorage.list('**/*.m3u')
streams = await parser.parse(files)
streams = streams.map((stream: Stream) => {
stream.setGuides(apiData.guidesGroupedByStreamId.get(stream.getId()))
return stream
})
}
async function processIssues(issues: Collection<Issue>) {
const requests = issues.filter((issue: Issue) => issue.labels.includes('approved')).all()
for (const issue of requests) {
switch (true) {
case issue.labels.includes('streams:remove'):
await removeStream(issue)
break
case issue.labels.includes('streams:edit'):
await editStream(issue)
break
case issue.labels.includes('streams:add'):
await addStream(issue)
break
}
}
}
async function removeStream(issue: Issue) {
const log = createThread(issue, 'streams/remove')
log.start()
const data = issue.data
if (data.missing('stream_url')) {
log.error('The request is missing the "Stream URL"')
skippedIssues.add(issue)
return
}
const streamUrls = data.getString('stream_url') || ''
let changed = false
streamUrls
.split(/\r?\n/)
.filter(Boolean)
.forEach((link: string) => {
const found: Stream = streams.first((_stream: Stream) => _stream.url === link.trim())
if (found) {
found.removed = true
changed = true
log.info(`The stream with the URL "${link}" has been removed from the playlists`)
} else {
log.error(`The stream with the URL "${link}" is missing from the playlists`)
}
})
if (changed) {
processedIssues.add(issue)
} else {
log.error('None of the URLs specified in the request were found in the playlists')
skippedIssues.add(issue)
}
}
async function editStream(issue: Issue) {
const log = createThread(issue, 'streams/edit')
log.start()
const data = issue.data
const streamUrl = data.getString('stream_url')
if (!streamUrl) {
log.error('The request is missing the "Stream URL"')
skippedIssues.add(issue)
return
}
const stream: Stream = streams.first((_stream: Stream) => _stream.url === streamUrl)
if (!stream) {
log.error(`The stream with the URL "${streamUrl}" is already in the playlists`)
skippedIssues.add(issue)
return
}
cacheData()
stream.updateWithIssue(data)
stream.setGuides(apiData.guidesGroupedByStreamId.get(stream.getId()))
const errors = new Collection<Error>()
errors.concat(stream.validate())
if (errors.isNotEmpty()) {
errors.forEach((err: Error) => {
log.error(err.message)
})
skippedIssues.add(issue)
resetData()
log.info('All changes have been reverted')
return
}
log.info('The stream description has been updated')
processedIssues.add(issue)
}
async function addStream(issue: Issue) {
const log = createThread(issue, 'streams/add')
log.start()
const data = issue.data
if (data.missing('stream_id')) {
log.error('The request is missing the "Stream ID"')
skippedIssues.add(issue)
return
}
const streamUrl = data.getString('stream_url')
if (!streamUrl) {
log.error('The request is missing the "Stream URL"')
skippedIssues.add(issue)
return
}
if (streams.includes((_stream: Stream) => _stream.url === streamUrl)) {
log.error(`The stream with the URL "${streamUrl}" is already included in the playlists`)
skippedIssues.add(issue)
return
}
const streamId = data.getString('stream_id') || ''
const [channelId, feedId] = streamId.split('@')
const channel: sdk.Models.Channel | undefined = apiData.channelsKeyById.get(channelId)
if (!channel) {
log.error(`There is no channel with the ID "${channelId}" in the database`)
skippedIssues.add(issue)
return
}
const blocklistRecords: sdk.Models.BlocklistRecord[] | undefined =
apiData.blocklistRecordsGroupedByChannel.get(channelId)
if (blocklistRecords) {
blocklistRecords.forEach((record: sdk.Models.BlocklistRecord) => {
if (record.reason === 'dmca') {
log.error(
`The channel has been added to our blocklist due to the claims of the copyright holder: ${record.ref}`
)
} else if (record.reason === 'nsfw') {
log.error(`The channel has been added to our blocklist due to NSFW content: ${record.ref}`)
}
})
skippedIssues.add(issue)
return
}
cacheData()
const httpUserAgent = data.getString('http_user_agent') || null
const httpReferrer = data.getString('http_referrer') || null
let quality = data.getString('quality') || null
if (!quality) {
const streamInfo = await getStreamInfo(streamUrl, { httpUserAgent, httpReferrer })
if (streamInfo) {
const height = streamInfo?.resolution?.height
if (height) {
quality = `${height}p`
}
}
}
const stream = new Stream({
channel: channelId,
feed: feedId,
title: channel.name,
url: streamUrl,
user_agent: httpUserAgent,
referrer: httpReferrer,
quality,
label: data.getString('label') || ''
})
stream.updateTitle().updateFilepath()
stream.setGuides(apiData.guidesGroupedByStreamId.get(stream.getId()))
streams.add(stream)
const errors = new Collection<Error>()
errors.concat(stream.validate())
if (errors.isNotEmpty()) {
errors.forEach((err: Error) => {
log.error(err.message)
})
skippedIssues.add(issue)
resetData()
log.info('All changes have been reverted')
return
}
log.info('The stream has been added to playlists')
processedIssues.add(issue)
}