forked from Script-Hub-Org/Script-Hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SurgeModuleTool_macOS.js
201 lines (177 loc) · 6.05 KB
/
SurgeModuleTool_macOS.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
const https = require('https')
const http = require('http')
const os = require('os')
const path = require('path')
const fs = require('fs')
const homedir = os.homedir()
const moduledir = path.join(homedir, '/Library/Mobile Documents/iCloud~com~nssurge~inc/Documents')
console.log(`检测目录: ${moduledir}`)
let report = {
success: 0,
fail: [],
noUrl: 0,
}
const modules = []
function readdir(dirPath) {
const files = fs.readdirSync(dirPath)
files.forEach(file => {
const filePath = path.join(dirPath, file)
const stat = fs.statSync(filePath)
if (stat.isDirectory()) {
readdir(filePath)
} else if (file && !/\.(conf|txt|js|list)$/i.test(file) && !/^\./i.test(file)) {
modules.push({ file, filePath })
}
})
}
!(async () => {
readdir(moduledir)
for await (const { file, filePath } of modules) {
// console.log(`处理: ${file} ${filePath}`)
let originalName
let originalDesc
let noUrl
try {
let content = fs.readFileSync(filePath, 'utf8')
const originalNameMatched = `${content}`.match(/^#\!name\s*?=\s*(.*?)\s*(\n|$)/im)
if (originalNameMatched) {
originalName = originalNameMatched[1]
}
const originalDescMatched = `${content}`.match(/^#\!desc\s*?=\s*(.*?)\s*(\n|$)/im)
if (originalDescMatched) {
originalDesc = originalDescMatched[1]
if (originalDesc) {
originalDesc = originalDesc.replace(/^🔗.*?]\s*/i, '')
}
}
const matched = `${content}`.match(/^#SUBSCRIBED\s+(.*?)\s*(\n|$)/im)
if (!matched) {
noUrl = true
throw new Error('无订阅链接')
}
const subscribed = matched[0]
const url = matched[1]
if (!url) {
noUrl = true
throw new Error('无订阅链接')
}
let res = await fetchContent(url)
if (!res) {
throw new Error(`未获取到模块内容`)
}
const nameMatched = `${res}`.match(/^#\!name\s*?=\s*?\s*(.*?)\s*(\n|$)/im)
if (!nameMatched) {
throw new Error(`不是合法的模块内容`)
}
const name = nameMatched[1]
if (!name) {
throw new Error('模块无名称字段')
}
const descMatched = `${res}`.match(/^#\!desc\s*?=\s*?\s*(.*?)\s*(\n|$)/im)
let desc
if (descMatched) {
desc = descMatched[1]
}
if (!desc) {
res = `#!desc=\n${res}`
}
res = res.replace(/^(#SUBSCRIBED|# 🔗 模块链接)(.*?)(\n|$)/gim, '')
// console.log(res);
res = addLineAfterLastOccurrence(res, `\n\n# 🔗 模块链接\n${subscribed.replace(/\n/g, '')}\n`)
content = `${res}`.replace(/^#\!desc\s*?=\s*/im, `#!desc=🔗 [${new Date().toLocaleString()}] `)
fs.writeFileSync(filePath, content, { encoding: 'utf8' })
let nameInfo = `${name}`
let descInfo = `${desc}`
if (originalName && name !== originalName) {
nameInfo = `${originalName} -> ${name}`
}
if (originalDesc && desc !== originalDesc) {
descInfo = `${originalDesc} -> ${desc}`
}
console.log(`\n✅ ${nameInfo}\n${descInfo}\n${file}`)
report.success += 1
await delay(1 * 1000)
} catch (e) {
// console.error(`❌ ${file}: ${e.message ?? e}`)
if (noUrl) {
report.noUrl += 1
} else {
report.fail.push(originalName || file)
}
if (noUrl) {
console.log(`\n🈚️ ${originalName || ''}\n${file}`)
console.log(e.message ?? e)
} else {
console.log(`\n❌ ${originalName || ''}\n${file}`)
console.error(`${originalName || file}: ${e.message ?? e}`)
}
}
}
})()
.catch(async e => {
console.error(e)
})
.finally(() => {
let upErrk = report.fail.length > 0 ? `❌ 更新失败: ${report.fail.length}` : '',
noUrlErrk = report.noUrl > 0 ? `🈚️ 无链接: ${report.noUrl}` : ''
const title = `📦 模块总数: ${report.success + report.fail.length + report.noUrl}`
const message = `${noUrlErrk}\n✅ 更新成功: ${report.success}\n${upErrk}${
report.fail.length > 0 ? `\n${report.fail.join(', ')}` : ''
}`
console.log(`\n${title}\n${message}`)
})
function fetchContent(url, options = {}, timeout = 5000) {
return new Promise((resolve, reject) => {
const client = url.startsWith('https://') ? https : http
const request = client.get(url, options, response => {
if (response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {
const redirectUrl = new URL(response.headers.location, url)
resolve(fetchContent(redirectUrl.toString(), options, timeout))
} else {
let data = ''
response.setEncoding('utf8')
response.on('data', chunk => {
data += chunk
})
response.on('end', () => {
resolve(data)
})
}
})
request.on('error', error => {
reject(error)
})
request.on('timeout', () => {
request.abort()
reject(new Error('请求超时'))
})
request.setTimeout(timeout)
})
}
function convertToValidFileName(str) {
// 替换非法字符为下划线
const invalidCharsRegex = /[\/:*?"<>|]/g
const validFileName = str.replace(invalidCharsRegex, '_')
// 删除多余的点号
const multipleDotsRegex = /\.{2,}/g
const fileNameWithoutMultipleDots = validFileName.replace(multipleDotsRegex, '.')
// 删除文件名开头和结尾的点号和空格
const leadingTrailingDotsSpacesRegex = /^[\s.]+|[\s.]+$/g
const finalFileName = fileNameWithoutMultipleDots.replace(leadingTrailingDotsSpacesRegex, '')
return finalFileName
}
function addLineAfterLastOccurrence(text, addition) {
const regex = /^#!.+?$/gm
const matchArray = text.match(regex)
const lastIndex = matchArray ? matchArray.length - 1 : -1
if (lastIndex >= 0) {
const lastMatch = matchArray[lastIndex]
const insertIndex = text.indexOf(lastMatch) + lastMatch.length
const newText = text.slice(0, insertIndex) + addition + text.slice(insertIndex)
return newText
}
return text
}
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}