66 Commits
1.1 ... 1.6.50

Author SHA1 Message Date
HolographicHat
4417feab53 encode uri to avoid charset problem 2022-04-17 23:46:11 +08:00
HolographicHat
28080dbafd fix 2022-04-17 22:54:35 +08:00
HolographicHat
a8b6419157 Update README.md 2022-04-16 21:52:50 +08:00
HolographicHat
7f8296c3dc fix bug and bump version to 1.6 2022-04-16 21:07:00 +08:00
HolographicHat
37382b28e0 auto package script 2022-04-16 20:59:32 +08:00
HolographicHat
a46e49722f auto package script 2022-04-16 00:35:41 +08:00
HolographicHat
700cbbb86d update 2022-04-13 20:54:00 +08:00
HolographicHat
6a23153f70 add oversea(NA-SiliconValley) api 2022-04-13 19:34:14 +08:00
HolographicHat
75e3cd848f update 2022-04-12 20:00:12 +08:00
HolographicHat
96912d3da7 support gbk encoding 2022-04-10 14:18:01 +08:00
HolographicHat
02b034cc48 Merge remote-tracking branch 'origin/master' 2022-04-10 13:03:08 +08:00
HolographicHat
00898d11cb fix 2022-04-10 13:02:36 +08:00
HolographicHat
7cf03ad905 Update README.md 2022-04-10 02:03:08 +08:00
HolographicHat
7d9e5bc218 Update README.md 2022-04-09 20:37:27 +08:00
HolographicHat
60f0d8d23b fix appcenter log upload error 2022-04-09 19:33:52 +08:00
HolographicHat
1e15a49667 new format 2022-04-09 16:35:46 +08:00
HolographicHat
4528af7235 rollback 2022-04-09 00:30:16 +08:00
HolographicHat
9850d1dbe4 bump version to 1.5 2022-04-09 00:19:15 +08:00
HolographicHat
b1f307de83 snapgenshin format update 2022-04-08 23:56:43 +08:00
HolographicHat
bea596b906 fetch achievement data from self api server 2022-04-08 23:56:20 +08:00
HolographicHat
dd582437bc use fastest cdn to fetch data 2022-04-07 22:50:36 +08:00
HolographicHat
ea168ce96b support snapgenshin 2022-04-07 21:56:27 +08:00
HolographicHat
90ab4dafe9 speed test file 2022-04-07 21:26:09 +08:00
HolographicHat
55f1ce3d55 auto export to cocogoat 2022-04-07 21:04:49 +08:00
HolographicHat
0e51e080d4 no hard code loc 2022-04-07 20:13:42 +08:00
HolographicHat
01ab053d7d Update README.md 2022-04-06 22:18:26 +08:00
HolographicHat
41af9c7cdb better pause impl 2022-04-06 13:05:20 +08:00
HolographicHat
8a0c82f89f catch wmi error 2022-04-06 11:26:05 +08:00
HolographicHat
d64bf8149e Update README.md 2022-04-06 08:53:10 +08:00
HolographicHat
82e85f5ea0 v1.4 2022-04-06 00:15:42 +08:00
HolographicHat
891a19c3f7 select game by open file dialog, optimize code and message 2022-04-06 00:14:48 +08:00
HolographicHat
7b94964342 more message and check, better privilege test 2022-04-06 00:13:03 +08:00
HolographicHat
d5e290e866 modify and add some message, optimize 2022-04-06 00:11:21 +08:00
HolographicHat
f7c48472f1 native: enablePrivilege and copyToClipboard 2022-04-06 00:03:12 +08:00
HolographicHat
a6b80d3588 more error check 2022-04-05 20:13:52 +08:00
HolographicHat
18e3d3ffe3 fix #5 2022-04-05 19:11:12 +08:00
HolographicHat
a22ad8e87d Merge remote-tracking branch 'origin/master' 2022-04-05 18:53:42 +08:00
HolographicHat
35ec8b5859 native: import wmi as submodule 2022-04-05 18:53:09 +08:00
HolographicHat
35899e74f6 Update README.md 2022-04-05 02:23:54 +08:00
HolographicHat
bb4d5215f1 native: getDeviceID and getDeviceInfo 2022-04-05 02:22:01 +08:00
HolographicHat
e4e76286c9 native addon 2022-04-04 22:50:59 +08:00
HolographicHat
be5a457639 native addon 2022-04-04 17:08:47 +08:00
HolographicHat
945a94222a Update README.md 2022-04-03 23:40:26 +08:00
HolographicHat
3d03496074 Update messages 2022-04-02 22:48:51 +08:00
HolographicHat
1e6ebc76dd Update README.md 2022-04-02 22:37:15 +08:00
HolographicHat
ab47ff2b06 fix crash when hosts not exist 2022-04-01 20:31:49 +08:00
HolographicHat
5fe6e80cc8 Merge remote-tracking branch 'origin/master' 2022-03-30 14:10:23 +08:00
HolographicHat
a23d7f3cc9 more handler 2022-03-30 14:09:50 +08:00
HolographicHat
0ab6444b6f more message 2022-03-29 22:33:24 +08:00
HolographicHat
00f0aaa4a6 2.6 Achievement data 2022-03-28 18:30:08 +08:00
HolographicHat
2377dbd492 Update achievement-data.json 2022-03-28 18:26:00 +08:00
HolographicHat
0b015886ea Update README.md 2022-03-28 16:32:28 +08:00
HolographicHat
4adfc9a312 Update README.md 2022-03-27 13:04:14 +08:00
HolographicHat
b4cd69f303 v1.3 2022-03-27 12:51:41 +08:00
HolographicHat
c76ddd9e3f fix wrong field name 2022-03-27 12:47:25 +08:00
HolographicHat
d40c456494 add default arg for read registry method 2022-03-26 20:51:54 +08:00
HolographicHat
408169da4e Merge remote-tracking branch 'origin/master' 2022-03-26 17:55:57 +08:00
HolographicHat
9de8e957fd add server disconnect handler 2022-03-26 16:59:21 +08:00
HolographicHat
a287e5db43 Update README.md 2022-03-26 16:39:43 +08:00
HolographicHat
589048b912 Update README.md 2022-03-26 16:39:14 +08:00
HolographicHat
79517a37d2 try to fix copy error 2022-03-25 21:53:14 +08:00
HolographicHat
e022f04661 fix achievement data error 2022-03-25 21:33:46 +08:00
HolographicHat
d1a635be7c fix exit hook 2022-03-25 21:32:43 +08:00
HolographicHat
aa853262b7 Merge remote-tracking branch 'origin/master' 2022-03-25 19:23:18 +08:00
HolographicHat
bdf9561dfa fix crash when appcenter error 2022-03-25 19:22:34 +08:00
HolographicHat
a663fddeb0 Update README.md 2022-03-23 20:58:21 +08:00
30 changed files with 3934 additions and 3198 deletions

5
.gitignore vendored
View File

@@ -1,7 +1,12 @@
cache
cert
config.json
out.*
node_modules
.idea
YaeAchievement-*.7z
YaeAchievement-*.exe
export*.json
secret.js
package-lock.json
native.node

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "native/src/wmi"]
path = native/src/wmi
url = https://github.com/HolographicHat/wmi

View File

@@ -1,28 +1,19 @@
# 原神成就导出工具
![GitHub](https://img.shields.io/github/license/HolographicHat/genshin-achievement-export?label=License&style=flat-square) ![GitHub issues](https://img.shields.io/github/issues/HolographicHat/genshin-achievement-export?label=Issues&style=flat-square) ![Downloads](https://img.shields.io/github/downloads/HolographicHat/genshin-achievement-export/total?color=brightgreen&label=Downloads&style=flat-square) ![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)
![GitHub](https://img.shields.io/badge/License-GPL--3.0-brightgreen?style=flat-square) ![GitHub release (latest by date)](https://img.shields.io/github/v/release/HolographicHat/genshin-achievement-export?color=brightgreen&label=Release&style=flat-square) ![GitHub issues](https://img.shields.io/github/issues/HolographicHat/genshin-achievement-export?label=Issues&style=flat-square) ![Downloads](https://img.shields.io/github/downloads/HolographicHat/genshin-achievement-export/total?color=brightgreen&label=Downloads&style=flat-square) ![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)
- 支持导出所有成就
- 没有窗口大小游戏或语言等要求
- 更快、更准
- 支持官服B服与国际服
- 支持导出至[椰羊](https://cocogoat.work/achievement)、[SnapGenshin](https://github.com/DGP-Studio/Snap.Genshin)、[Paimon.moe](https://paimon.moe/achievement/)、[Seelie.me](https://seelie.me/achievements)和表格文件(csv)
- 没有窗口大小、游戏语言等要求
## 使用说明
**打开程序前需要关闭正在运行的原神主程序**
第一次打开需要先设置原神主程序所在路径,支持多个路径, 使用符号'*'分隔
![alt](https://upload-bbs.mihoyo.com/upload/2022/03/22/165631158/a1bbf8d0604a29830c09822add53f749_8463600217231045373.png)
- 自定义代理: 配置文件内添加proxy字段详细请参看[Axios-请求配置](https://axios-http.com/zh/docs/req_config)
```json
{
"path": [],
"offlineResource": false,
"customCDN": "",
"proxy": {
"protocol": "http",
"host": "127.0.0.1",
"port": 7890
}
}
```
第一次打开需要先设置原神主程序(YuanShen.exe/GenshinImpact.exe)所在路径
![alt](https://upload-bbs.mihoyo.com/upload/2022/04/06/165631158/e540a5a6d50cd5fdee19665435548e00_514247033566841954.jpg)
### Windows7
系统变量添加名为```NODE_SKIP_PLATFORM_CHECK```的变量并将值设为```1```
[[?]如何添加环境变量](https://www.bing.com/search?q=windows+7+环境变量)
## 下载地址
[releases/latest](https://github.com/HolographicHat/genshin-achievement-export/releases/latest)
@@ -30,11 +21,21 @@
## 问题反馈
[issues](https://github.com/HolographicHat/genshin-achievement-export/issues)或[QQ群: 913777414](https://qm.qq.com/cgi-bin/qm/qr?k=9UGz-chQVTjZa4b82RA_A41vIcBVNpms&jump_from=webapi)
## FAQ
1. Q: 为什么需要管理员权限
## 常见问题
0. Q: 程序异常退出或被强行终止后,程序报错:网络错误(22-1) 或 原神启动时报错: 无法连接网络(4201)
A: 用文本编辑器打开```C:\Windows\System32\drivers\etc\hosts```,删除```127.0.0.1 dispatch**global.yuanshen.com```后保存,重启原神
1. Q: 原神启动时报错: 数据异常(31-4302)
A: 不要把软件和原神主程序放一起
2. Q: 为什么需要管理员权限
A: 临时修改Hosts和启动原神
2. Q: 报毒?
A: 执行命令或修改hosts引发相关代码可在./utils.js,./appcenter.js下找到
3. Q: 报毒?
A: 执行命令或修改hosts引发相关代码可在./utils.js,./appcenter.js下找到
## TODO
- [ ] GUI
4. Q: 原神进门后没有自动退出,程序输出停留在“加载完成”
A: 关闭代理后重试
5. Q: 网络错误,请检查网络后重试 (21-x)
A: 如果你是校园网用户使用流量上网并重试如果你是海外用户打开config.json将oversea_api的值设置为true并重试

File diff suppressed because it is too large Load Diff

77
app.js
View File

@@ -1,41 +1,63 @@
const zlib = require("zlib")
const proxy = require("udp-proxy")
const cp = require("child_process")
const rs = require("./regionServer")
const cloud = require("./secret")
const appcenter = require("./appcenter")
const { initConfig, splitPacket, upload, decodeProto, log, setupHost, KPacket, debug, checkCDN, checkUpdate } = require("./utils")
const regionServer = require("./regionServer")
const {
initConfig, splitPacket, upload, decodeProto, log, setupHost, KPacket, debug, checkUpdate,
brotliCompressSync, brotliDecompressSync, checkGameIsRunning, checkPortIsUsing
} = require("./utils")
const { exportData } = require("./export")
const { exitHook } = require("./exitHook.js");
const { enablePrivilege, pause } = require("./native")
const onExit = () => {
setupHost(true)
console.log("按任意键退出")
pause()
};
// TODO: use kotlin rewrite it
(async () => {
try {
exitHook(() => {
setupHost(true)
console.log("按任意键退出")
cp.execSync("pause > nul", { stdio: "inherit" })
process.on("SIGHUP", () => setupHost(true))
process.on("unhandledRejection", (reason, promise) => {
console.log("Unhandled Rejection at: ", promise, "\n0Reason:", reason)
})
appcenter.init()
let conf = await initConfig()
process.on("uncaughtException", (err, origin) => {
appcenter.uploadError(err, true)
console.log(err)
console.log(`Origin: ${origin}`)
process.exit(1)
})
process.on("exit", onExit)
process.on("SIGINT", onExit)
try {
cp.execSync("net session", { stdio: "ignore" })
enablePrivilege()
} catch (e) {
console.log("\x1b[91m请使用管理员身份运行此程序\x1b[0m")
return
console.log("请使用管理员身份运行此程序")
process.exit(-1)
}
appcenter.startup()
let conf = await initConfig()
cloud.init(conf)
checkPortIsUsing()
checkGameIsRunning()
log("检查更新")
await checkUpdate()
checkCDN().then(_ => debug("CDN check success."))
let gameProcess
let unexpectedExit = true
rs.create(conf,() => {
regionServer.create(conf,() => {
setupHost()
gameProcess = cp.execFile(conf.executable, { cwd: conf.path },err => {
if (err !== null && !err.killed) {
throw err
}
})
log("启动原神")
gameProcess.on("exit", () => {
if (unexpectedExit) process.exit(0)
if (unexpectedExit) {
console.log("游戏进程异常退出")
process.exit(0)
}
})
},(ip, port, hServer) => {
let login = false
@@ -60,16 +82,18 @@ const { exitHook } = require("./exitHook.js");
}
}
let monitor;
let stopped = false
const createMonitor = () => {
monitor = setInterval(async () => {
if (login && lastRecvTimestamp + 2 < parseInt(Date.now() / 1000)) {
if (login && lastRecvTimestamp + 2 < parseInt(Date.now() / 1000) && !stopped) {
stopped = true
unexpectedExit = false
server.close()
server.close(() => {})
hServer.close()
gameProcess.kill()
clearInterval(monitor)
setupHost(true)
console.log("正在处理数据,请稍后...")
log("正在处理数据,请稍后...")
let packets = Array.from(cache.values())
cache.clear()
packets.sort((a, b) => a.frg - b.frg)
@@ -91,14 +115,14 @@ const { exitHook } = require("./exitHook.js");
return Buffer.concat([len, data])
})
const merged = Buffer.concat(packets)
const compressed = zlib.brotliCompressSync(merged)
const compressed = brotliCompressSync(merged)
const response = await upload(compressed)
const data = brotliDecompressSync(response.data)
if (response.status !== 200) {
log(`发生错误: ${response.data.toString()}`)
log(`发生错误: ${data}`)
log(`请求ID: ${response.headers["x-api-requestid"]}`)
log("请联系开发者以获取帮助")
} else {
const data = zlib.brotliDecompressSync(response.data)
const proto = await decodeProto(data,"AllAchievement")
await exportData(proto)
}
@@ -112,6 +136,8 @@ const { exitHook } = require("./exitHook.js");
login = true
}
})
server.on("error", err => console.log(`Proxy error: ${err.message}` + err.message))
server.on("proxyError", err => console.log(`Proxy error: ${err.message}` + err.message))
server.on("proxyMsg", (msg, _) => {
lastRecvTimestamp = parseInt(Date.now() / 1000)
let buf = Buffer.from(msg)
@@ -121,6 +147,9 @@ const { exitHook } = require("./exitHook.js");
createMonitor()
debug("服务端握手应答")
break
case 404:
lastRecvTimestamp = parseInt(Date.now() / 1000) - 2333
break
default:
console.log(`Unhandled: ${buf.toString("hex")}`)
process.exit(2)
@@ -136,7 +165,7 @@ const { exitHook } = require("./exitHook.js");
})
})
return server
}).then(() => console.log("加载完毕"))
}).then(() => log("加载完毕"))
} catch (e) {
console.log(e)
if (e instanceof Error) {

View File

@@ -1,73 +1,46 @@
const cp = require("child_process")
const axios = require("axios")
const crypto = require("crypto")
const { version } = require("./version")
const { getDeviceID, getDeviceInfo } = require("./native")
const getTimestamp = (d = new Date()) => {
const p = i => i.toString().padStart(2, "0")
return `${d.getUTCFullYear()}-${p(d.getUTCMonth() + 1)}-${p(d.getUTCDate())}T${p(d.getUTCHours())}:${p(d.getUTCMinutes())}:${p(d.getUTCSeconds())}.${p(d.getUTCMilliseconds())}Z`
}
const readRegistry = (path, key) => {
const i = cp.execSync(`reg query "${path}" /v ${key}`, {
encoding: "utf-8"
}).split("\n")[2].split(" ").filter(s => s.length > 0).map(s => s.trim())
switch (i[1]) {
case "REG_SZ":
return i[2]
case "REG_DWORD":
return parseInt(i[2])
default:
throw "Unsupported"
}
}
const queue = []
const session = crypto.randomUUID()
const key = "648b83bf-d439-49bd-97f4-e1e506bdfe39"
const install = (() => {
const s = readRegistry("HKCU\\SOFTWARE\\miHoYoSDK", "MIHOYOSDK_DEVICE_ID")
return `${s.substring(0, 8)}-${s.substring(8, 12)}-${s.substring(12, 16)}-${s.substring(16, 20)}-${s.substring(20, 32)}`
const id = getDeviceID()
return id === undefined ? crypto.randomUUID() : id
})()
const device = (() => {
const csi = cp.execSync("wmic computersystem get manufacturer,model /format:csv", {
encoding: "utf-8"
}).split("\n")[2].split(",").map(s => s.trim())
const osi = cp.execSync("wmic os get currentTimeZone, version /format:csv", {
encoding: "utf-8"
}).split("\n")[2].split(",").map(s => s.trim())
return {
model: csi[2],
oemName: csi[1],
timeZoneOffset: parseInt(osi[1]),
osBuild: `${osi[2]}.${readRegistry("HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "UBR")}`,
osVersion: osi[2],
locale: readRegistry("HKCU\\Control Panel\\International", "LocaleName"),
carrierCountry: readRegistry("HKCU\\Control Panel\\International\\Geo", "Name"),
sdkName: "appcenter.wpf.netcore",
sdkVersion: "4.5.0",
osName: "WINDOWS",
appVersion: version.name,
appBuild: version.code,
appNamespace: "default"
}
const info = getDeviceInfo()
info.appBuild = version.code
info.appVersion = version.name
info.sdkName = "appcenter.wpf.netcore"
info.sdkVersion = "4.5.0"
info.osName = "WINDOWS"
info.appNamespace = "default"
return info
})()
const upload = () => {
if (queue.length > 0) {
try {
const data = JSON.stringify({ "logs": queue })
axios.post("https://in.appcenter.ms/logs?api-version=1.0.0", data,{
headers: {
"App-Secret": key,
"Install-ID": install
}
}).then(_ => {
queue.length = 0
})
} catch (e) {}
const logs = []
for (let i = 0; i <= queue.length; i++) {
logs.push(queue.pop())
}
const data = JSON.stringify({"logs": logs})
axios.post("https://in.appcenter.ms/logs?api-version=1.0.0", data,{
headers: {
"App-Secret": key,
"Install-ID": install
}
}).catch(_ => {}).then()
}
}
@@ -108,7 +81,20 @@ const uploadError = (err, fatal) => {
upload()
}
const init = () => {
const uploadEvent = (name, prop) => {
const content = {
type: "event",
id: crypto.randomUUID(),
sid: session,
name: name,
properties: prop,
timestamp: getTimestamp(),
device: device
}
queue.push(content)
}
const startup = () => {
queue.push({
type: "startService",
services: [ "Analytics","Crashes" ],
@@ -122,9 +108,9 @@ const init = () => {
device: device
})
upload()
setInterval(() => upload(), 10000)
setInterval(() => upload(), 5000)
}
module.exports = {
init, upload, uploadError
startup, upload, uploadError, uploadEvent
}

Binary file not shown.

View File

@@ -1,50 +0,0 @@
// https://github.com/sindresorhus/exit-hook
const callbacks = new Set();
let isCalled = false;
let isRegistered = false;
function exit(shouldManuallyExit, signal) {
if (isCalled) {
return;
}
isCalled = true;
for (const callback of callbacks) {
callback();
}
if (shouldManuallyExit === true) {
process.exit(128 + signal);
}
}
function exitHook(onExit) {
callbacks.add(onExit);
if (!isRegistered) {
isRegistered = true;
process.once('exit', exit);
process.once('SIGINT', exit.bind(undefined, true, 2));
process.once('SIGTERM', exit.bind(undefined, true, 15));
// PM2 Cluster shutdown message. Caught to support async handlers with pm2, needed because
// explicitly calling process.exit() doesn't trigger the beforeExit event, and the exit
// event cannot support async handlers, since the event loop is never called after it.
process.on('message', message => {
if (message === 'shutdown') {
exit(true, -128);
}
});
}
return () => {
callbacks.delete(onExit);
};
}
module.exports = {
exitHook
}

132
export.js
View File

@@ -1,75 +1,93 @@
const fs = require("fs")
const axios = require("axios")
const readline = require("readline")
const { exec } = require("child_process")
const { loadCache } = require("./utils")
const { randomUUID } = require("crypto")
const { loadCache, log, openUrl } = require("./utils")
const { checkSnapFastcall, copyToClipboard } = require("./native")
const exportToSeelie = proto => {
const out = { achievements: {} }
proto.list.filter(achievement => achievement.status === 3).forEach(({id}) => {
proto.list.filter(a => a.status === 3 || a.status === 2).forEach(({id}) => {
out.achievements[id] = { done: true }
})
const fp = `./export-${Date.now()}-seelie.json`
fs.writeFileSync(fp, JSON.stringify(out))
console.log(`导出为文件: ${fp}`)
log(`导出为文件: ${fp}`)
}
const exportToPaimon = async proto => {
const out = { achievements: {} }
const achTable = new Map()
const excel = await loadCache("ExcelBinOutput/AchievementExcelConfigData.json")
excel.forEach(({GoalId, Id}) => {
achTable.set(Id, GoalId === undefined ? 0 : GoalId)
})
proto.list.filter(achievement => achievement.status === 3).forEach(({id}) => {
const gid = achTable.get(id)
if (out.achievements[gid] === undefined) {
out.achievements[gid] = {}
const out = { achievement: {} }
const data = await loadCache()
proto.list.filter(a => a.status === 3 || a.status === 2).forEach(({id}) => {
const gid = data["a"][id]
if (out.achievement[gid] === undefined) {
out.achievement[gid] = {}
}
out.achievements[gid][id] = true
out.achievement[gid][id] = true
})
const fp = `./export-${Date.now()}-paimon.json`
fs.writeFileSync(fp, JSON.stringify(out))
console.log(`导出为文件: ${fp}`)
log(`导出为文件: ${fp}`)
}
const exportToSnapGenshin = async proto => {
const out = []
proto.list.filter(a => a.status === 3 || a.status === 2).forEach(({id, finishTimestamp}) => {
out.push({
id: id,
timestamp: finishTimestamp
})
})
if (checkSnapFastcall()) {
const json = JSON.stringify(out)
const path = `${process.env.TMP}/YaeAchievement-export-${randomUUID()}`
fs.writeFileSync(path, json)
openUrl(`snapgenshin://achievement/import/file?path=\"${path}\"`)
log("在 SnapGenshin 进行下一步操作")
} else {
const json = JSON.stringify(out, null, 2)
copyToClipboard(json)
log("导出内容已复制到剪贴板")
}
}
const exportToCocogoat = async proto => {
const out = {
value: {
achievements: []
}
achievements: []
}
const achTable = new Map()
const preStageAchievementIdList = []
const excel = await loadCache("ExcelBinOutput/AchievementExcelConfigData.json")
excel.forEach(({GoalId, Id, PreStageAchievementId}) => {
if (PreStageAchievementId !== undefined) {
preStageAchievementIdList.push(PreStageAchievementId)
}
achTable.set(Id, GoalId === undefined ? 0 : GoalId)
})
const data = await loadCache()
const p = i => i.toString().padStart(2, "0")
const getDate = ts => {
const d = new Date(parseInt(`${ts}000`))
return `${d.getFullYear()}/${p(d.getMonth()+1)}/${p(d.getDate())}`
}
proto.list.filter(achievement => achievement.status === 3).forEach(({current, finishTimestamp, id, require}) => {
out.value.achievements.push({
proto.list.filter(a => a.status === 3 || a.status === 2).forEach(({current, finishTimestamp, id, require}) => {
const curAch = data["a"][id]
out.achievements.push({
id: id,
status: current === undefined || current === 0 || preStageAchievementIdList.includes(id) ? `${require}/${require}` : `${current}/${require}`,
categoryId: achTable.get(id),
status: current === undefined || current === 0 || curAch["p"] === undefined ? `${require}/${require}` : `${current}/${require}`,
categoryId: curAch["g"],
date: getDate(finishTimestamp)
})
})
exec("clip").stdin.end(JSON.stringify(out,null,2))
console.log("导出内容已复制到剪贴板")
const response = await axios.post(`https://77.cocogoat.work/v1/memo?source=${encodeURI("全部成就")}`, out).catch(_ => {
console.log("网络错误,请检查网络后重试 (26-1)")
process.exit(261)
})
if (response.status !== 201) {
console.log(`API StatusCode 错误,请联系开发者以获取帮助 (26-2-${response.status})`)
process.exit(262)
}
const retcode = openUrl(`https://cocogoat.work/achievement?memo=${response.data.key}`)
if (retcode > 32) {
log("在浏览器内进行下一步操作")
} else {
log(`导出失败,请联系开发者以获取帮助 (26-3-${retcode})`)
}
}
const exportToCsv = async proto => {
const excel = await loadCache("achievement-data.json", "HolographicHat/genshin-achievement-export")
const achievementMap = new Map()
excel["achievement"].forEach(obj => {
achievementMap.set(parseInt(obj.id), obj)
})
const data = await loadCache()
const outputLines = ["ID,状态,特辑,名称,描述,当前进度,目标进度,完成时间"]
const getStatusText = i => {
switch (i) {
@@ -84,20 +102,23 @@ const exportToCsv = async proto => {
const p = i => i.toString().padStart(2, "0")
return `${d.getFullYear()}/${p(d.getMonth() + 1)}/${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`
}
const bl = [84517]
proto.list.forEach(({current, finishTimestamp, id, status, require}) => {
const desc = achievementMap.get(id) === undefined ? (() => {
console.log(`Error get id ${id} in excel`)
return {
goal: "未知",
name: "未知",
desc: "未知"
}
})() : achievementMap.get(id)
outputLines.push(`${id},${getStatusText(status)},${excel.goal[desc.goal]},${desc.name},${desc.desc},${status !== 1 ? current === 0 ? require : current : current},${require},${status === 1 ? "" : getTime(finishTimestamp)}`)
if (!bl.includes(id)) {
const curAch = data["a"][id] === undefined ? (() => {
console.log(`Error get id ${id} in excel`)
return {
g: "未知",
n: "未知",
d: "未知"
}
})() : data["a"][id]
outputLines.push(`${id},${getStatusText(status)},${data["g"][curAch.g]},${curAch.n},${curAch.d},${status !== 1 ? current === 0 ? require : current : current},${require},${status === 1 ? "" : getTime(finishTimestamp)}`)
}
})
const fp = `./export-${Date.now()}.csv`
fs.writeFileSync(fp, `\uFEFF${outputLines.join("\n")}`)
console.log(`导出为文件: ${fp}`)
log(`导出为文件: ${fp}`)
}
const exportData = async proto => {
@@ -108,18 +129,25 @@ const exportData = async proto => {
const question = (query) => new Promise(resolve => {
rl.question(query, resolve)
})
const chosen = await question("导出至: \n[0] 椰羊 (https://cocogoat.work/achievement)\n[1] Paimon.moe\n[2] Seelie.me\n[3] 表格文件 (默认)\n> ")
const chosen = await question("导出至: \n[0] 椰羊 (https://cocogoat.work/achievement)\n[1] SnapGenshin\n[2] Paimon.moe\n[3] Seelie.me\n[4] 表格文件 (默认)\n输入一个数字(0-4): ")
rl.close()
switch (chosen) {
switch (chosen.trim()) {
case "0":
await exportToCocogoat(proto)
break
case "1":
await exportToPaimon(proto)
await exportToSnapGenshin(proto)
break
case "2":
await exportToPaimon(proto)
break
case "3":
await exportToSeelie(proto)
break
case "raw":
fs.writeFileSync(`./export-${Date.now()}-raw.json`, JSON.stringify(proto,null,2))
log("OK")
break
default:
await exportToCsv(proto)
}

10
native.d.ts vendored Normal file
View File

@@ -0,0 +1,10 @@
export function selectGameExecutable(): string
export function checkGameIsRunning(processName: string): boolean
export function whoUseThePort(port: number): object
export function copyToClipboard(value: string): any
export function checkSnapFastcall(): boolean
export function enablePrivilege(): any
export function getDeviceInfo(): any
export function getDeviceID(): string
export function openUrl(url: string): number
export function pause(): any

5
native/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
CMakeLists.txt
.idea
cmake-build-debug
node_modules
build

42
native/binding.gyp Normal file
View File

@@ -0,0 +1,42 @@
{
"targets": [
{
"target_name": "native",
"sources": [
"src/main.cc",
"src/utils.h",
"src/utils.cc",
"src/define.h",
"src/wmi/wmi.cpp",
"src/wmi/wmi.hpp",
"src/wmi/unistd.h",
"src/wmi/wmiresult.cpp",
"src/wmi/wmiresult.hpp",
"src/wmi/wmiclasses.hpp",
"src/wmi/wmiexception.hpp",
"src/registry/registry.hpp"
],
"cflags!": [
"-fno-exceptions"
],
"cflags_cc!": [
"-fno-exceptions"
],
"defines": [
"NAPI_DISABLE_CPP_EXCEPTIONS"
],
"include_dirs": [
"<!(node -p \"require('node-addon-api').include_dir\")"
],
"msvs_settings": {
"VCCLCompilerTool": {
"AdditionalOptions": [
"-std:c++latest",
"-DUNICODE",
"-sdl"
]
}
}
}
]
}

16
native/package.json Normal file
View File

@@ -0,0 +1,16 @@
{
"name": "genshin-export-native",
"version": "1.0.0",
"description": "",
"scripts": {
"build": "node-gyp rebuild && copy .\\build\\Release\\native.node ..\\genshin-export\\",
"build-for-win7": "node-gyp rebuild --target=v14.17.0 && copy .\\build\\Release\\native.node ..\\genshin-export\\"
},
"gypfile": true,
"devDependencies": {
"node-gyp": "^9.0.0"
},
"dependencies": {
"node-addon-api": "^4.3.0"
}
}

14
native/src/define.h Normal file
View File

@@ -0,0 +1,14 @@
#pragma once
#include <string>
#include <iostream>
#include <napi.h>
#include <Windows.h>
#include <TlHelp32.h>
using std::string, std::wstring, std::cout, std::to_string;
using Napi::Object, Napi::Env, Napi::Function, Napi::Value, Napi::CallbackInfo, Napi::TypeError, Napi::Error;
typedef unsigned char byte;
typedef unsigned long ul;
typedef unsigned long long ull;

202
native/src/main.cc Normal file
View File

@@ -0,0 +1,202 @@
#include "utils.h"
#include "define.h"
#include "wmi/wmi.hpp"
#include "wmi/wmiclasses.hpp"
#include "registry/registry.hpp"
#include <conio.h>
#include <iphlpapi.h>
#pragma comment(lib,"ws2_32.lib")
#pragma comment(lib,"iphlpapi.lib")
using Wmi::Win32_ComputerSystem, Wmi::Win32_OperatingSystem, Wmi::retrieveWmi;
namespace native {
Value checkGameIsRunning(const CallbackInfo &info) {
Env env = info.Env();
if (info.Length() != 1 || !info[0].IsString()) {
TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException();
return env.Undefined();
}
wstring name = StringToWString(info[0].As<Napi::String>().Utf8Value());
bool isRunning = false;
PROCESSENTRY32 entry;
entry.dwSize = sizeof(entry);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry) == TRUE) {
while (Process32Next(snapshot, &entry) == TRUE) {
if (wstring(entry.szExeFile) == name) {
isRunning = true;
}
}
}
CloseHandle(snapshot);
return Napi::Boolean::New(env, isRunning);
}
Value selectGameExecutable(const CallbackInfo &info) {
Env env = info.Env();
Napi::String path;
if (OpenFile(env, path) != ERROR_SUCCESS) {
Error::New(env, "Failed to open file: " + to_string(CommDlgExtendedError())).ThrowAsJavaScriptException();
return env.Undefined();
}
return path;
}
Value whoUseThePort(const CallbackInfo &info) {
Env env = info.Env();
if (info.Length() != 1 || !info[0].IsNumber()) {
TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException();
return env.Undefined();
}
DWORD dwSize = 0;
PMIB_TCPTABLE_OWNER_PID pTcpTable = nullptr;
GetExtendedTcpTable(pTcpTable, &dwSize, TRUE,AF_INET,TCP_TABLE_OWNER_PID_ALL,0);
pTcpTable = (PMIB_TCPTABLE_OWNER_PID)new byte[dwSize];
if(GetExtendedTcpTable(pTcpTable,&dwSize,TRUE,AF_INET,TCP_TABLE_OWNER_PID_ALL,0) != NO_ERROR) {
Error::New(env, "GetExtendedTcpTable failed").ThrowAsJavaScriptException();
return env.Undefined();
}
int port = info[0].As<Napi::Number>().Int32Value();
auto nNum = (int)pTcpTable->dwNumEntries;
DWORD pid = 0;
for(int i = 0; i < nNum; i++) {
if (htons(pTcpTable->table[i].dwLocalPort) == port) {
pid = pTcpTable->table[i].dwOwningPid;
break;
}
}
delete pTcpTable;
Value ret = env.Undefined();
if (pid != 0) {
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
if (hProcess == nullptr) {
Error::New(env, "OpenProcess error: " + to_string(GetLastError())).ThrowAsJavaScriptException();
return env.Undefined();
}
TCHAR fnBuf[MAX_PATH];
DWORD length = MAX_PATH;
if (QueryFullProcessImageName(hProcess, 0, fnBuf, &length) == 0) {
Error::New(env, "QueryFullProcessImageName error: " + to_string(GetLastError())).ThrowAsJavaScriptException();
return env.Undefined();
}
Object obj = Object::New(env);
obj.Set("pid", Napi::Number::New(env, pid));
obj.Set("path", Napi::String::New(env, WStringToString(fnBuf)));
ret = obj;
}
return ret;
}
Value getDeviceID(const CallbackInfo &info) {
Env env = info.Env();
wstring wd;
if (RegUtils::GetString(HKEY_CURRENT_USER, L"SOFTWARE\\miHoYoSDK", L"MIHOYOSDK_DEVICE_ID", wd) != ERROR_SUCCESS) {
return env.Undefined();
}
string id = WStringToString(wd);
return Napi::String::New(env, id.substr(0, 8) + "-" + id.substr(8, 4) + "-" + id.substr(12, 4) + "-" + id.substr(16, 4) + "-" + id.substr(20, 12));
}
Value getDeviceInfo(const CallbackInfo &info) {
Env env = info.Env();
HDC desktop = GetDC(nullptr);
int sw = GetDeviceCaps(desktop, DESKTOPHORZRES);
int sh = GetDeviceCaps(desktop, DESKTOPVERTRES);
ReleaseDC(nullptr, desktop);
DWORD buildNum = RegUtils::GetInt(env, HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", L"UBR", 0);
wstring locale;
if (RegUtils::GetString(HKEY_CURRENT_USER, L"Control Panel\\International", L"LocaleName", locale) != ERROR_SUCCESS) {
locale = L"zh-CN";
}
wstring country;
if (RegUtils::GetString(HKEY_CURRENT_USER, L"Control Panel\\International\\Geo", L"Name", country) != ERROR_SUCCESS) {
country = L"CN";
}
Object obj = Object::New(env);
obj.Set("locale", Napi::String::New(env, WStringToString(locale)));
obj.Set("screenSize", Napi::String::New(env, to_string(sw) + "x" + to_string(sh)));
obj.Set("carrierCountry", Napi::String::New(env, WStringToString(country)));
try {
auto computer = retrieveWmi<Win32_ComputerSystem>();
obj.Set("model", Napi::String::New(env, computer.Model));
obj.Set("oemName", Napi::String::New(env, computer.Manufacturer));
} catch (Wmi::WmiException &e) {
obj.Set("model", Napi::String::New(env, "Unknown"));
obj.Set("oemName", Napi::String::New(env, "Unknown"));
}
try {
auto os = retrieveWmi<Win32_OperatingSystem>();
string osv = os.Version;
obj.Set("osBuild", Napi::String::New(env, osv + "." + to_string(buildNum)));
obj.Set("osVersion", Napi::String::New(env, osv));
obj.Set("timeZoneOffset", Napi::Number::New(env, os.CurrentTimeZone));
} catch (Wmi::WmiException &e) {
obj.Set("osBuild", Napi::String::New(env, "Unknown"));
obj.Set("osVersion", Napi::String::New(env, "Unknown"));
obj.Set("timeZoneOffset", Napi::Number::New(env, 480));
}
return obj;
}
Value enablePrivilege(const CallbackInfo &info) {
Env env = info.Env();
EnablePrivilege(env, L"SeDebugPrivilege");
return env.Undefined();
}
Value copyToClipboard(const CallbackInfo &info) {
Env env = info.Env();
string text = info[0].As<Napi::String>().Utf8Value();
if (OpenClipboard(nullptr)) {
EmptyClipboard();
HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, text.length() + 1);
if (hg != nullptr) {
memcpy(GlobalLock(hg), text.c_str(), text.length() + 1);
GlobalUnlock(hg);
SetClipboardData(CF_TEXT, hg);
}
CloseClipboard();
}
return env.Undefined();
}
Value pause(const CallbackInfo &info) {
while(!_kbhit()) {
Sleep(10);
}
return info.Env().Undefined();
}
Value openUrl(const CallbackInfo &info) {
Env env = info.Env();
wstring url = StringToWString(info[0].As<Napi::String>().Utf8Value());
HINSTANCE retcode = ShellExecute(GetConsoleWindow(), L"open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
return Napi::Number::New(env, (INT_PTR)retcode); // NOLINT(cppcoreguidelines-narrowing-conversions)
}
Value checkSnapFastcall(const CallbackInfo &info) {
Env env = info.Env();
wstring queryResult;
RegUtils::GetString(HKEY_CLASSES_ROOT, L"snapgenshin", L"", queryResult);
return Napi::Boolean::New(env, wcscmp(queryResult.c_str(), L"URL:snapgenshin") == 0);
}
Object init(Env env, Object exports) {
exports.Set("pause", Function::New(env, pause));
exports.Set("openUrl", Function::New(env, openUrl));
exports.Set("getDeviceID", Function::New(env, getDeviceID));
exports.Set("getDeviceInfo", Function::New(env, getDeviceInfo));
exports.Set("whoUseThePort", Function::New(env, whoUseThePort));
exports.Set("copyToClipboard", Function::New(env, copyToClipboard));
exports.Set("enablePrivilege", Function::New(env, enablePrivilege));
exports.Set("checkSnapFastcall", Function::New(env, checkSnapFastcall));
exports.Set("checkGameIsRunning", Function::New(env, checkGameIsRunning));
exports.Set("selectGameExecutable", Function::New(env, selectGameExecutable));
return exports;
}
NODE_API_MODULE(addon, init)
}

View File

@@ -0,0 +1,39 @@
#pragma once
#ifndef REGISTRY_HPP
#define REGISTRY_HPP
#include "../define.h"
namespace RegUtils {
DWORD GetInt(Env env, HKEY hKey, const wstring &path, const wstring &value, DWORD defaultValue) {
DWORD data = 0;
DWORD size = sizeof(DWORD);
LSTATUS retcode = RegGetValue(hKey, path.c_str(), value.c_str(), RRF_RT_REG_DWORD, nullptr, &data, &size);
if (retcode != ERROR_SUCCESS) {
return defaultValue;
}
return data;
}
LSTATUS GetString(HKEY hKey, const wstring &path, const wstring &value, wstring &result) {
DWORD size = 0;
LSTATUS retcode = RegGetValue(hKey, path.c_str(), value.c_str(), RRF_RT_REG_SZ, nullptr, nullptr, &size);
if (retcode != ERROR_SUCCESS) {
return retcode;
}
wstring data;
DWORD len = size / sizeof(WCHAR);
data.resize(len);
retcode = RegGetValue(hKey, path.c_str(), value.c_str(), RRF_RT_REG_SZ, nullptr, &data[0], &size);
if (retcode != ERROR_SUCCESS) {
return retcode;
}
data.resize((len-1));
result = data;
return ERROR_SUCCESS;
}
}
#endif //REGISTRY_HPP

76
native/src/utils.cc Normal file
View File

@@ -0,0 +1,76 @@
#include "utils.h"
#include "define.h"
wstring StringToWString(const string &src, UINT codePage) {
int len = MultiByteToWideChar(codePage, 0, src.c_str(), -1, nullptr, 0);
auto *buffer = new WCHAR[len];
MultiByteToWideChar(codePage, 0, src.c_str(), -1, buffer, len);
wstring strTemp(buffer);
delete[] buffer;
return strTemp;
}
string WStringToString(const wstring &src, UINT codePage) {
int len = WideCharToMultiByte(codePage, 0, src.c_str(), -1, nullptr, 0, nullptr, nullptr);
auto *buffer = new CHAR[len];
WideCharToMultiByte(codePage, 0, src.c_str(), -1, buffer, len, nullptr, nullptr);
string strTemp(buffer);
delete[] buffer;
return strTemp;
}
void Log(Env env, const string &msg) {
auto logFunc = env.Global().Get("console").As<Object>().Get("log").As<Function>();
logFunc.Call({ Napi::String::New(env, msg) });
}
void Log(Env env, const wstring &msg) {
auto logFunc = env.Global().Get("console").As<Object>().Get("log").As<Function>();
logFunc.Call({ Napi::String::New(env, WStringToString(msg)) });
}
LSTATUS OpenFile(Env env, Napi::String &result, HWND parent) {
OPENFILENAME open;
ZeroMemory(&open, sizeof(open));
WCHAR file[32768];
file[0]=L'\0';
open.Flags = OFN_FILEMUSTEXIST | OFN_NONETWORKBUTTON | OFN_PATHMUSTEXIST | OFN_EXPLORER;
open.hwndOwner = parent;
open.nMaxFile = 32768;
open.lpstrFile = file;
open.lpstrTitle = L"选择原神主程序";
open.lpstrFilter = L"国服/国际服主程序 (YuanShen/GenshinImpact.exe)\0YuanShen.exe;GenshinImpact.exe\0";
open.lStructSize = sizeof(open);
if(GetOpenFileName(&open)) {
result = GetACP() == 936 ? Napi::String::New(env, WStringToString(file, CP_UTF8)) : Napi::String::New(env, WStringToString(file));
return ERROR_SUCCESS;
} else {
return ERROR_ERRORS_ENCOUNTERED;
}
}
BOOL EnablePrivilege(Env env, const wstring &name) {
HANDLE hToken;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken)) {
Error::New(env, "OpenProcessToken error: " + to_string(GetLastError())).ThrowAsJavaScriptException();
return FALSE;
}
TOKEN_PRIVILEGES tp;
ZeroMemory(&tp, sizeof(tp));
tp.PrivilegeCount = 1;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!LookupPrivilegeValue(nullptr, name.c_str(), &tp.Privileges[0].Luid)) {
Error::New(env, "LookupPrivilegeValue error: " + to_string(GetLastError())).ThrowAsJavaScriptException();
return FALSE;
}
if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), nullptr, nullptr)) {
Error::New(env, "AdjustTokenPrivileges error: " + to_string(GetLastError())).ThrowAsJavaScriptException();
return FALSE;
}
if (GetLastError() == ERROR_NOT_ALL_ASSIGNED) {
Error::New(env, "The token does not have the specified privilege.").ThrowAsJavaScriptException();
return FALSE;
}
CloseHandle(hToken);
return TRUE;
}

15
native/src/utils.h Normal file
View File

@@ -0,0 +1,15 @@
#pragma once
#include "define.h"
string WStringToString(const wstring &src, UINT codePage = CP_ACP);
wstring StringToWString(const string &src, UINT codePage = CP_ACP);
LSTATUS OpenFile(Env env, Napi::String &result, HWND parent = GetConsoleWindow());
BOOL EnablePrivilege(Env env, const wstring &name);
void Log(Env env, const string &msg);
void Log(Env env, const wstring &msg);
#ifndef GENSHIN_EXPORT_NATIVE_UTILS_H
#define GENSHIN_EXPORT_NATIVE_UTILS_H
#endif //GENSHIN_EXPORT_NATIVE_UTILS_H

1
native/src/wmi Submodule

Submodule native/src/wmi added at aab36ea1e1

View File

@@ -3,18 +3,17 @@
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"pkg": "pkg -t node16-win-x64 -C Brotli app.js --build -o app.exe",
"pkg-for-windows7": "pkg -t node14-win-x64 -C Brotli app.js --build -o app-win7.exe"
},
"keywords": [],
"author": "",
"license": "ISC",
"private": true,
"dependencies": {
"ini": "^2.0.0",
"axios": "^0.26.1",
"udp-proxy": "^1.2.0",
"protobufjs": "^6.11.2"
"ini": "^2.0.0",
"protobufjs": "^6.11.2",
"udp-proxy": "^1.2.0"
},
"devDependencies": {
"pkg": "file:C:/Users/holog/Desktop/pkg-main"
}
}

2
package/app.manifest Normal file
View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"><trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"><security><requestedPrivileges><requestedExecutionLevel level="requireAdministrator" uiAccess="false"/></requestedPrivileges></security></trustInfo><application xmlns="urn:schemas-microsoft-com:asm.v3"><windowsSettings><dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware><longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware></windowsSettings></application><compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"><application><supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/><supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/><supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/><supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/></application></compatibility></assembly>

BIN
package/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 353 KiB

57
package/package.js Normal file
View File

@@ -0,0 +1,57 @@
const fs = require("fs")
const pkg = require("pkg")
const { log } = require("../utils")
const { version } = require("../version")
const { execSync } = require("child_process")
const name = `YaeAchievement-${ version.isDev ? "DevBuild" : "Release" }-${((t = new Date()) => {
const p = i => i.toString().padStart(2, "0")
return `${p(t.getMonth()+1)}${p(t.getDate())}${p(t.getHours())}${p(t.getMinutes())}`
})()}`
const generateAndCompileVersionInfo = () => {
const vci = version.name.split(".")
let content = fs.readFileSync("./version.rc", "utf-8")
content = content.replaceAll("${BID}" , vci[2] === undefined ? "0" : vci[2])
content = content.replaceAll("${YEAR}" , (new Date()).getFullYear())
content = content.replaceAll("${MAJOR_VERSION}", vci[0])
content = content.replaceAll("${MINOR_VERSION}", vci[1])
content = content.replaceAll("${ORIGINAL_NAME}", `${name}.exe`)
fs.writeFileSync("./tmp.rc", content, "utf-8")
execSync(`rh.exe -open tmp.rc -save tmp.res -action compile -log NUL`)
fs.rm("./tmp.rc", () => {})
}
const generateScript = (path) => {
let content = fs.readFileSync("./rh.script", "utf-8")
content = content.replaceAll("${PATH}", path)
fs.writeFileSync("./tmp.script", content, "utf-8")
}
const cleanUp = () => {
fs.rm("./rh.ini", () => {})
fs.rm("./tmp.res", () => {})
fs.rm("./tmp.script", () => {})
}
const c = {
forWin7: false,
sevenZipPath: "\"C:/Program Files/7-Zip/7z.exe\""
};
(async () => {
const fn = c.forWin7 ? `${name}-Win7` : name
const nv = c.forWin7 ? "14.19.1" : "16.14.2"
log("Generate and compile version info")
generateAndCompileVersionInfo()
log("Modify executable file resources")
const path = `C:/Users/holog/.pkg-cache/v3.3/built-v${nv}-win-x64`
generateScript(path)
execSync(`rh.exe -script tmp.script`)
cleanUp()
log("Build and compress package")
await pkg.exec(`../app.js -t node${nv.split(".")[0]}-win-x64 -C Brotli --build -o ${fn}.exe`.split(" "))
execSync(`${c.sevenZipPath} a ${fn}.7z ${fn}.exe -mx=9 -myx=9 -mmt=4 -sdel -stl`)
log("Done")
})()

BIN
package/rh.exe Normal file

Binary file not shown.

10
package/rh.script Normal file
View File

@@ -0,0 +1,10 @@
[FILENAMES]
Exe=${PATH}
SaveAs=${PATH}
Log=NUL
[COMMANDS]
-delete MANIFEST,,
-delete ICONGROUP,,
-addoverwrite icon.ico, ICONGROUP,1,0
-addoverwrite tmp.res, VERSIONINFO,1,0
-addoverwrite app.manifest MANIFEST,1,0

23
package/version.rc Normal file
View File

@@ -0,0 +1,23 @@
1 VERSIONINFO
FILEVERSION ${MAJOR_VERSION},${MINOR_VERSION},${BID},0
PRODUCTVERSION ${MAJOR_VERSION},${MINOR_VERSION},${BID},0
FILEOS 0x4
FILETYPE 0x1
{
BLOCK "StringFileInfo"
{
BLOCK "000004B0"
{
VALUE "ProductName", "YaeAchievement"
VALUE "ProductVersion", "${MAJOR_VERSION}.${MINOR_VERSION}.${BID}"
VALUE "FileDescription", "YaeAchievement"
VALUE "FileVersion", "${MAJOR_VERSION}.${MINOR_VERSION}.${BID}"
VALUE "OriginalFilename", "${ORIGINAL_NAME}"
VALUE "LegalCopyright", "Copyright (c) ${YEAR} HolographicHat"
}
}
BLOCK "VarFileInfo"
{
VALUE "Translation", 0x0000 0x04B0
}
}

View File

@@ -22,10 +22,24 @@ message Achievement {
}
message QueryCurRegion {
bytes field0 = 11;
bytes field1 = 12;
bytes field2 = 13;
msg0 info = 3;
int32 retcode = 1;
string message = 2;
msg0 info = 3;
oneof group {
msg3 field2 = 4;
msg4 field3 = 5;
}
bytes field4 = 11;
bytes field5 = 12;
bytes field6 = 13;
}
message QueryRegionList {
int32 retcode = 1;
bytes field0 = 5;
bytes field1 = 6;
bool field2 = 7;
repeated msg2 list = 2;
}
message msg0 {
@@ -37,35 +51,36 @@ message msg0 {
string field3 = 9;
string field4 = 10;
string field5 = 11;
uint32 field6 = 14;
string field7 = 16;
uint32 field8 = 18;
string field9 = 19;
string fieldA = 20;
bytes fieldB = 23;
string fieldC = 24;
string fieldD = 26;
string fieldE = 27;
string fieldF = 30;
string fieldG = 31;
string fieldH = 32;
string fieldI = 33;
msg1 fieldJ = 22;
string field6 = 12;
string field7 = 13;
uint32 field8 = 14;
string field9 = 16;
uint32 fieldA = 18;
string fieldB = 19;
string fieldC = 20;
msg1 fieldD = 22;
bytes fieldE = 23;
string fieldF = 24;
string fieldG = 26;
string fieldH = 27;
bool fieldI = 28;
string fieldJ = 29;
string fieldK = 30;
string fieldL = 31;
string fieldM = 32;
string fieldN = 33;
string fieldO = 34;
msg1 fieldP = 35;
}
message msg1 {
uint32 field0 = 1;
string field1 = 3;
string field2 = 4;
string field3 = 5;
string field4 = 6;
}
message QueryRegionList {
bytes field0 = 5;
bytes field1 = 6;
bool field2 = 7;
repeated msg2 list = 2;
bool field1 = 2;
string field2 = 3;
string field3 = 4;
string field4 = 5;
string field5 = 6;
string field6 = 7;
}
message msg2 {
@@ -74,3 +89,14 @@ message msg2 {
string field2 = 3;
string url = 4;
}
message msg3 {
string field0 = 1;
}
message msg4 {
uint32 field0 = 1;
uint32 field1 = 2;
string field2 = 3;
string field3 = 4;
}

View File

@@ -16,8 +16,15 @@ const getModifiedRegionList = async (conf) => {
channel_id: conf.channel,
sub_channel_id: conf.subChannel
}
}).catch(_ => {
console.log("网络错误,请检查网络后重试 (22-1)")
process.exit(221)
})
const regions = await decodeProto(Buffer.from(d.data,"base64"),"QueryRegionList")
if (regions["retcode"] !== 0) {
console.log(`系统错误,请稍后重试 (${regions["retcode"]}-23)`)
process.exit(23)
}
regions.list = regions.list.map(item => {
const host = new URL(item.url).host
if (regions.list.length === 1) {
@@ -36,12 +43,19 @@ const getModifiedRegionInfo = async (url, uc, hs) => {
const query = noQueryRequest ? "" : `?${splitUrl[1]}`
const d = await axios.get(`https://${host}/query_cur_region${query}`, {
responseType: "text"
}).catch(_ => {
console.log("网络错误,请检查网络后重试 (22-2)")
process.exit(222)
})
if (noQueryRequest) {
preparedRegions[host] = true
return d.data
} else {
const region = await decodeProto(Buffer.from(d.data,"base64"),"QueryCurRegion")
if (region["retcode"] !== 0) {
console.log(`${region["message"]} (${region["retcode"]}-24)`)
process.exit(24)
}
const info = region.info
if (preparedRegions[host]) {
if (currentProxy !== undefined) {
@@ -69,7 +83,7 @@ const create = async (conf, regionListLoadedCallback, regionSelectCallback) => {
passphrase: ""
}, async (request, response) => {
const url = request.url
debug("HTTP请求: %s", url)
debug("HTTP: %s", url)
response.writeHead(200, { "Content-Type": "text/html" })
if (url.startsWith("/query_region_list")) {
response.end(regions)
@@ -80,17 +94,14 @@ const create = async (conf, regionListLoadedCallback, regionSelectCallback) => {
const frontResponse = await axios.get(`https://${conf.dispatchIP}${url}`, {
responseType: "arraybuffer",
httpsAgent: agent
}).catch(err => {
console.log("网络错误,请检查网络后重试 (22-3)")
console.log(err.message)
process.exit(223)
})
response.end(frontResponse.data)
}
})
hServer.on("error", err => {
if (err["code"] === "EADDRINUSE") {
console.log("本机 443 端口被其它程序占用,请关闭后重试")
}
throw err
})
hServer.listen(443, "127.0.0.1", () => {
}).listen(443, "127.0.0.1", () => {
regionListLoadedCallback()
})
}

235
utils.js
View File

@@ -1,20 +1,17 @@
const fs = require("fs")
const dns = require("dns")
const ini = require("ini")
const util = require("util")
const zlib = require("zlib")
const cloud = require("./secret")
const native = require("./native")
const readline = require("readline")
const protobuf = require("protobufjs")
const { version } = require("./version")
const { promisify } = require("util")
const { createHash } = require("crypto")
const path = require("path")
const { uploadEvent } = require("./appcenter")
const messages = path.join(__dirname, "./proto/Messages.proto")
let axios = require("axios")
const sleep = ms => new Promise(resolve => {
setTimeout(resolve, ms)
})
const encodeProto = (object, name) => protobuf.load(messages).then(r => {
const msgType = r.lookupType(name)
@@ -26,79 +23,107 @@ const decodeProto = (buf, name) => protobuf.load(messages).then(r => {
return r.lookupType(name).decode(buf)
})
const checkPath = (path, cb) => {
if (!fs.existsSync(`${path}/UnityPlayer.dll`) && !fs.existsSync(`${path}/pkg_version`)) {
throw Error(`路径有误: ${path}`)
const checkPath = path => new Promise((resolve, reject) => {
if (!fs.existsSync(`${path}/UnityPlayer.dll`) || !fs.existsSync(`${path}/pkg_version`)) {
reject(`路径有误 ${path}`)
} else {
cb(path)
resolve(path)
}
}
})
let conf
const initConfig = async () => {
const configFileName = "./config.json"
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
const question = (query) => new Promise(resolve => {
rl.question(query, resolve)
})
const lookup = util.promisify(dns.lookup).bind(dns)
if (fs.existsSync(configFileName)) {
conf = JSON.parse(fs.readFileSync(configFileName, "utf-8"))
if (conf.offlineResource !== undefined || conf.customCDN !== undefined || conf.proxy !== undefined) {
conf.proxy = undefined
conf.customCDN = undefined
conf.offlineResource = undefined
fs.writeFileSync(configFileName, JSON.stringify(conf, null, 2))
}
} else {
const p = await question("原神主程序(YuanShen.exe或GenshinImpact.exe)所在路径: (支持多个路径, 使用符号'*'分隔)\n")
conf = {
path: [],
offlineResource: false,
customCDN: ""
oversea_api: false
}
p.split("*").forEach(s => {
checkPath(s, () => {
if (!conf.path.includes(s)) {
conf.path.push(s)
}
})
let p = ""
try {
p = path.dirname(native.selectGameExecutable())
} catch (e) {
process.exit(1)
}
await checkPath(p).catch(reason => {
console.log(reason)
process.exit(1)
})
conf.path.push(p)
fs.writeFileSync(configFileName, JSON.stringify(conf, null, 2))
rl.close()
}
if (conf.proxy !== undefined) {
axios = axios.create({
proxy: conf.proxy
})
if (conf.oversea_api === undefined) {
conf.oversea_api = false
fs.writeFileSync(configFileName, JSON.stringify(conf, null, 2))
}
if (conf.path.length === 1) {
checkPath(conf.path[0], p => {
await checkPath(conf.path[0]).catch(reason => {
console.log(reason)
process.exit(1)
}).then(p => {
conf.path = p
})
} else {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
const question = (query) => new Promise(resolve => {
rl.question(query, resolve)
})
const idx = await question(`选择客户端: \n${conf.path.map((s, i) => {
const fp = fs.existsSync(`${s}/GenshinImpact.exe`) ? `${s}\\GenshinImpact.exe` : `${s}\\YuanShen.exe`
return `[${i}] ${fp}`
}).join("\n")}\n> `)
checkPath(conf.path[parseInt(idx)], p => {
await checkPath(conf.path[parseInt(idx)]).catch(reason => {
console.log(reason)
process.exit(1)
}).then(p => {
conf.path = p
})
rl.close()
}
rl.close()
conf.isOversea = fs.existsSync(conf.path + "/GenshinImpact.exe")
conf.dataDir = conf.isOversea ? conf.path + "/GenshinImpact_Data" : conf.path + "/YuanShen_Data"
const readGameRes = (path) => fs.readFileSync(conf.dataDir + path)
// noinspection JSUnresolvedVariable
const genshinConf = ini.parse(fs.readFileSync(conf.path + "/config.ini", "utf-8")).General
conf.channel = genshinConf.channel
// noinspection JSUnresolvedVariable
conf.subChannel = genshinConf.sub_channel
conf.version = readGameRes("/Persistent/ChannelName").toString() + readGameRes("/Persistent/ScriptVersion").toString()
conf.executable = conf.isOversea ? conf.path + "/GenshinImpact.exe" : conf.path + "/YuanShen.exe"
const readGameRes = (path) => fs.readFileSync(conf.dataDir + path, "utf-8")
const genshinConf = ini.parse(fs.readFileSync(`${conf.path}/config.ini`, "utf-8"))["General"]
conf.channel = genshinConf["channel"]
conf.subChannel = genshinConf["sub_channel"]
conf.version = readGameRes("/Persistent/ChannelName") + readGameRes("/Persistent/ScriptVersion")
conf.executable = conf.isOversea ? `${conf.path}/GenshinImpact.exe` : `${conf.path}/YuanShen.exe`
conf.dispatchUrl = `dispatch${conf.isOversea ? "os" : "cn"}global.yuanshen.com`
conf.dispatchIP = (await lookup(conf.dispatchUrl, 4)).address
conf.dispatchIP = (await promisify(dns.lookup).bind(dns)(conf.dispatchUrl, 4)).address
uploadEvent("AppInitialize", { ClientVersion: version.name, GameVersion: conf.version })
return conf
}
const checkGameIsRunning = () => {
const name = path.basename(conf.executable)
if (native.checkGameIsRunning(name)) {
console.log("原神正在运行,请关闭后重试")
process.exit(301)
}
}
const checkPortIsUsing = () => {
const portUsage = native.whoUseThePort(443)
if (portUsage !== undefined) {
console.log(`443端口被 ${path.basename(portUsage["path"])}(${portUsage["pid"]}) 占用,结束该进程后重试`)
process.exit(14)
}
}
const openUrl = url => native.openUrl(encodeURI(url))
const splitPacket = buf => {
let offset = 0
let arr = []
@@ -116,77 +141,51 @@ const md5 = str => {
return h.digest("hex")
}
let cdnUrlFormat = null
/*
* Structure:
* UInt16 = 0x4321: magic num
* UInt8 = 0x2 : version
* Char[32] : data md5
* ... : compressed data
*/
String.prototype.format = function() {
const args = arguments;
return this.replace(/{(\d+)}/g, (match, number) => typeof args[number] != "undefined" ? args[number] : match)
}
const checkCDN = async () => {
try {
cdnUrlFormat = "https://cdn.jsdelivr.net/gh/{0}@master/{1}"
await axios.head(cdnUrlFormat.format("github/fetch", ".gitignore"))
return
} catch (e) {}
try {
cdnUrlFormat = "https://raw.githubusercontent.com/{0}/master/{1}"
await axios.head(cdnUrlFormat.format("github/fetch", ".gitignore"))
return
} catch (e) {}
try {
const s = conf === undefined ? "" : conf.customCDN.trim()
if (s.length > 0) {
cdnUrlFormat = s
await axios.head(cdnUrlFormat.format("github/fetch", ".gitignore"))
return
}
} catch (e) {}
try {
cdnUrlFormat = "https://raw.fastgit.org/{0}/master/{1}"
await axios.head(cdnUrlFormat.format("github/fetch", ".gitignore"))
return
} catch (e) {}
try {
cdnUrlFormat = "https://ghproxy.net/https://raw.githubusercontent.com/{0}/master/{1}"
await axios.head(cdnUrlFormat.format("github/fetch", ".gitignore"))
return
} catch (e) {}
throw "没有可用的CDN"
}
const loadCache = async (fp, repo = "Dimbreath/GenshinData") => {
console.log(cdnUrlFormat.format(repo, fp))
const loadCache = async (fp = "latest-data") => {
log(`正在加载资源: ${fp}`)
const startAt = Date.now()
fs.mkdirSync("./cache", { recursive: true })
const localPath = `./cache/${md5(fp)}`
if (conf.offlineResource) {
const fd = brotliDecompressSync(fs.readFileSync(localPath))
return JSON.parse(fd.subarray(1 + fd.readUInt8()).toString())
// remove old cache file
fs.readdir("./cache/", (err, files) => {
if (err === null) files.forEach(s => {
const fn = `./cache/${s}`
if (!fn.endsWith(".ch")) fs.rm(fn,_ => {})
})
})
const localPath = `./cache/${md5(fp)}.ch`
const headers = {
"x-content-hash": "0".repeat(32)
}
const header = {}
let fd = Buffer.alloc(0)
if (fs.existsSync(localPath)) {
fd = brotliDecompressSync(fs.readFileSync(localPath))
const etagLength = fd.readUInt8()
header["If-None-Match"] = fd.subarray(1, 1 + etagLength).toString()
fd = fs.readFileSync(localPath)
if (fd.readUInt16BE(0) === 0x4321 && fd.readUInt8(2) === 2) {
headers["x-content-hash"] = fd.subarray(3, 35).toString("utf-8")
}
}
const headResponse = await axios.head(cdnUrlFormat.format(repo, fp), {
headers: header,
validateStatus: _ => true
})
if (headResponse.status === 304) {
console.log("文件 %s 命中缓存", fp)
const etagLength = fd.readUInt8()
return JSON.parse(fd.subarray(1 + etagLength).toString())
const resp = await cloud.get(`/${fp}`, "application/json", headers, "arraybuffer")
if (resp.status === 304) {
log(`完成 (Cache, ${Date.now() - startAt}ms)`)
return JSON.parse(brotliDecompressSync(fd.subarray(35)).toString())
} else {
console.log("正在下载资源, 请稍后...")
const response = await axios.get(cdnUrlFormat.format(repo, fp))
const etag = response.headers.etag
const str = JSON.stringify(response.data)
const comp = brotliCompressSync(Buffer.concat([Buffer.of(etag.length), Buffer.from(etag), Buffer.from(str)]))
fs.writeFileSync(localPath, comp)
console.log("完成.")
return response.data
const compressedData = resp.data
const decompressedData = brotliDecompressSync(compressedData)
const buf = Buffer.allocUnsafe(compressedData.length + 35)
buf.writeUInt16BE(0x4321, 0)
buf.writeUInt8(0x2, 2)
buf.fill(md5(decompressedData), 3)
buf.fill(compressedData, 35)
fs.writeFileSync(localPath, buf)
log(`完成 (Network, ${Date.now() - startAt}ms)`)
return JSON.parse(decompressedData)
}
}
@@ -209,9 +208,9 @@ const upload = async data => {
const checkUpdate = async () => {
const data = (await cloud.get("/latest-version")).data
if (data["vc"] !== version.code) {
console.log(`有可用更新: ${version.name} => ${data["vn"]}`)
console.log(`更新内容: \n${data["ds"]}`)
console.log("下载地址: https://github.com/HolographicHat/genshin-achievement-export/releases\n")
log(`有可用更新: ${version.name} => ${data["vn"]}`)
log(`更新内容: \n${data["ds"]}`)
log("下载地址: https://github.com/HolographicHat/genshin-achievement-export/releases\n")
}
}
@@ -224,10 +223,14 @@ const brotliCompressSync = data => zlib.brotliCompressSync(data,{
const brotliDecompressSync = data => zlib.brotliDecompressSync(data)
let hostsContent = ""
let hostsContent = undefined
const setupHost = (restore = false) => {
const path = "C:\\Windows\\System32\\drivers\\etc\\hosts"
if (restore && hostsContent === undefined) return
const path = `${process.env.windir}\\System32\\drivers\\etc\\hosts`
if (!fs.existsSync(path)) {
fs.writeFileSync(path, "")
}
fs.chmodSync(path, 0o777)
if (restore) {
fs.writeFileSync(path, hostsContent)
@@ -288,6 +291,6 @@ class KPacket {
}
module.exports = {
log, sleep, encodeProto, decodeProto, initConfig, splitPacket, upload, brotliCompressSync, brotliDecompressSync,
setupHost, loadCache, debug, checkCDN, checkUpdate, KPacket, cdnUrlFormat
log, encodeProto, decodeProto, initConfig, splitPacket, upload, brotliCompressSync, brotliDecompressSync,
setupHost, loadCache, debug, checkUpdate, KPacket, checkGameIsRunning, checkPortIsUsing, openUrl
}

View File

@@ -1,6 +1,7 @@
const version = {
code: 2,
name: "1.0.1"
code: 7,
name: "1.6.50",
isDev: true
}
module.exports = { version }