Skip to content

Commit

Permalink
Merge branch 'sealdice:master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
kenichiLyon authored Sep 18, 2024
2 parents 67640bf + c2dcb78 commit 26ca472
Show file tree
Hide file tree
Showing 19 changed files with 318 additions and 108 deletions.
8 changes: 8 additions & 0 deletions dice/builtin_commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,14 @@ func (d *Dice) registerCoreCommands() {
return CmdExecuteResult{Matched: true, Solved: true}
}

if !cmdArgs.AmIBeMentioned {
// 裸指令,如果当前群内开启,予以提示
if ctx.IsCurGroupBotOn {
ReplyToSender(ctx, msg, "[退群指令] 请@我使用这个命令,以进行确认")
}
return CmdExecuteResult{Matched: true, Solved: true}
}

ReplyToSender(ctx, msg, DiceFormatTmpl(ctx, "核心:骰子退群预告"))

userName := ctx.Dice.Parent.TryGetUserName(msg.Sender.UserID)
Expand Down
9 changes: 8 additions & 1 deletion dice/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -1115,6 +1115,9 @@ func setupBaseTextTemplate(d *Dice) {
"名片_取消设置": {
{`已关闭对{$t玩家}的名片自动修改。`, 1},
},
"记录_导出_成功": {
{`日志文件《{$t文件名字}》已上传至群文件,请自行到群文件查看。`, 1},
},
},
}

Expand Down Expand Up @@ -1850,6 +1853,9 @@ func setupBaseTextTemplate(d *Dice) {
"名片_取消设置": {
SubType: ".sn",
},
"记录_导出_成功": {
SubType: ".log export",
},
},
}
d.TextMapRaw = texts
Expand Down Expand Up @@ -2199,7 +2205,7 @@ func (d *Dice) loads() {
err := json.Unmarshal(data, &groupInfo)
if err == nil {
groupInfo.GroupID = id
groupInfo.UpdatedAtTime = updatedAt
groupInfo.UpdatedAtTime = 0

// 找出其中以群号开头的,这是1.2版本的bug
var toDelete []string
Expand Down Expand Up @@ -2594,6 +2600,7 @@ func (d *Dice) Save(isAuto bool) {
}
}
}

// Pinenutn: Range模板 ServiceAtNew重构代码
d.ImSession.ServiceAtNew.Range(func(key string, groupInfo *GroupInfo) bool {
// Pinenutn: ServiceAtNew重构
Expand Down
57 changes: 18 additions & 39 deletions dice/dice.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"sync"
"time"

"github.com/Masterminds/semver/v3"
"github.com/dop251/goja_nodejs/eventloop"
"github.com/dop251/goja_nodejs/require"
"github.com/go-creed/sat"
Expand All @@ -31,35 +30,6 @@ import (
"sealdice-core/dice/model"
)

var (
APPNAME = "SealDice"

// VERSION 版本号,按固定格式,action 在构建时可能会自动注入部分信息
// 正式:主版本号+yyyyMMdd,如 1.4.5+20240308
// dev:主版本号-dev+yyyyMMdd.7位hash,如 1.4.5-dev+20240308.1a2b3c4
// rc:主版本号-rc.序号+yyyyMMdd.7位hash如 1.4.5-rc.0+20240308.1a2b3c4,1.4.5-rc.1+20240309.2a3b4c4,……
VERSION = semver.MustParse(VERSION_MAIN + VERSION_PRERELEASE + VERSION_BUILD_METADATA)

// VERSION_MAIN 主版本号
VERSION_MAIN = "1.5.0"
// VERSION_PRERELEASE 先行版本号
VERSION_PRERELEASE = "-dev"
// VERSION_BUILD_METADATA 版本编译信息
VERSION_BUILD_METADATA = ""

// APP_CHANNEL 更新频道,stable/dev,在 action 构建时自动注入
APP_CHANNEL = "dev" //nolint:revive

VERSION_CODE = int64(1004006) //nolint:revive

VERSION_JSAPI_COMPATIBLE = []*semver.Version{
VERSION,
semver.MustParse("1.4.5"),
semver.MustParse("1.4.4"),
semver.MustParse("1.4.3"),
}
)

type CmdExecuteResult struct {
Matched bool // 是否是指令
Solved bool `jsbind:"solved"` // 是否响应此指令
Expand Down Expand Up @@ -341,6 +311,10 @@ func (d *Dice) Init() {
_ = os.MkdirAll(filepath.Join(d.BaseConfig.DataDir, "extra"), 0o755)
_ = os.MkdirAll(filepath.Join(d.BaseConfig.DataDir, "scripts"), 0o755)

log := logger.Init(filepath.Join(d.BaseConfig.DataDir, "record.log"), d.BaseConfig.Name, d.BaseConfig.IsLogPrint)
d.Logger = log.Logger
d.LogWriter = log.WX

d.Cron = cron.New()
d.Cron.Start()

Expand All @@ -349,16 +323,13 @@ func (d *Dice) Init() {
var err error
d.DBData, d.DBLogs, err = model.SQLiteDBInit(d.BaseConfig.DataDir)
if err != nil {
// TODO:
fmt.Println(err)
d.Logger.Errorf("Failed to init database: %v", err)
}

d.AttrsManager = &AttrsManager{}
d.AttrsManager.Init(d)

log := logger.Init(filepath.Join(d.BaseConfig.DataDir, "record.log"), d.BaseConfig.Name, d.BaseConfig.IsLogPrint)
d.Logger = log.Logger
d.LogWriter = log.WX
d.BanList = &BanListInfo{Parent: d}
d.BanList.Init()

Expand All @@ -372,7 +343,10 @@ func (d *Dice) Init() {
d.CmdMap = CmdMapCls{}
d.GameSystemMap = new(SyncMap[string, *GameSystemTemplate])
d.ConfigManager = NewConfigManager(filepath.Join(d.BaseConfig.DataDir, "configs", "plugin-configs.json"))
_ = d.ConfigManager.Load()
err = d.ConfigManager.Load()
if err != nil {
d.Logger.Error("Failed to load plugin configs: ", err)
}

d.registerCoreCommands()
d.RegisterBuiltinExt()
Expand Down Expand Up @@ -422,11 +396,16 @@ func (d *Dice) Init() {
count++
d.Save(true)
if count%2 == 0 {
// d.Logger.Info("测试: flush wal")
_ = model.FlushWAL(d.DBData)
_ = model.FlushWAL(d.DBLogs)
if err := model.FlushWAL(d.DBData); err != nil {
d.Logger.Error("Failed to flush WAL: ", err)
}
if err := model.FlushWAL(d.DBLogs); err != nil {
d.Logger.Error("Failed to flush WAL: ", err)
}
if d.CensorManager != nil && d.CensorManager.DB != nil {
_ = model.FlushWAL(d.CensorManager.DB)
if err := model.FlushWAL(d.CensorManager.DB); err != nil {
d.Logger.Error("Failed to flush WAL: ", err)
}
}
}
}
Expand Down
15 changes: 8 additions & 7 deletions dice/dice_attrs_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,11 +150,8 @@ func (am *AttrsManager) Init(d *Dice) {
am.db = d.DBData
am.logger = d.Logger
go func() {
// NOTE(Xiangze Li): 这种不退出的goroutine不利于平稳结束程序
for {
if am.logger == nil {
return
}
// fmt.Println(am.CheckForSave())
am.CheckForSave()
am.CheckAndFreeUnused()
time.Sleep(15 * time.Second)
Expand All @@ -173,8 +170,10 @@ func (am *AttrsManager) CheckForSave() (int, int) {
}

tx, err := db.Begin()
if err != nil && am.logger != nil {
am.logger.Errorf("定期写入用户数据出错(创建事务): %v", err)
if err != nil {
if am.logger != nil {
am.logger.Errorf("定期写入用户数据出错(创建事务): %v", err)
}
return 0, 0
}

Expand All @@ -189,7 +188,9 @@ func (am *AttrsManager) CheckForSave() (int, int) {

err = tx.Commit()
if err != nil {
am.logger.Errorf("定期写入用户数据出错(提交事务): %v", err)
if am.logger != nil {
am.logger.Errorf("定期写入用户数据出错(提交事务): %v", err)
}
_ = tx.Rollback()
return times, 0
}
Expand Down
64 changes: 60 additions & 4 deletions dice/dice_jsvm.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"github.com/dop251/goja_nodejs/console"
"github.com/dop251/goja_nodejs/eventloop"
"github.com/dop251/goja_nodejs/require"
esbuild "github.com/evanw/esbuild/pkg/api"
fetch "github.com/fy0/gojax/fetch"
"github.com/golang-module/carbon"
"github.com/pkg/errors"
Expand Down Expand Up @@ -634,6 +635,11 @@ func (d *Dice) jsClear() {
}
}

func isScriptFile(filename string) bool {
temp := strings.ToLower(filepath.Ext(filename))
return temp == ".js" || temp == ".ts"
}

func (d *Dice) JsLoadScripts() {
d.JsScriptList = []*JsScriptInfo{}

Expand All @@ -644,7 +650,7 @@ func (d *Dice) JsLoadScripts() {
builtinScripts, _ := fs.ReadDir(static.Scripts, "scripts")
_ = os.MkdirAll(builtinPath, 0o755)
for _, script := range builtinScripts {
if !script.IsDir() && filepath.Ext(script.Name()) == ".js" {
if !script.IsDir() && isScriptFile(script.Name()) {
target := filepath.Join(builtinPath, script.Name())
data, _ := static.Scripts.ReadFile("scripts/" + script.Name())
d.JsBuiltinDigestSet[crypto.CalculateSHA512Str(data)] = true
Expand All @@ -666,7 +672,7 @@ func (d *Dice) JsLoadScripts() {
var jsInfos []*JsScriptInfo
// 解析内置脚本
_ = filepath.Walk(builtinPath, func(path string, info fs.FileInfo, err error) error {
if filepath.Ext(path) == ".js" {
if isScriptFile(path) {
d.Logger.Info("正在读取内置脚本: ", path)
data, err := os.ReadFile(path)
if err != nil {
Expand Down Expand Up @@ -694,7 +700,7 @@ func (d *Dice) JsLoadScripts() {
if info.IsDir() && info.Name() == "_builtin" {
return fs.SkipDir
}
if filepath.Ext(path) == ".js" {
if isScriptFile(path) {
d.Logger.Info("正在读取脚本: ", path)
data, err := os.ReadFile(path)
if err != nil {
Expand Down Expand Up @@ -754,6 +760,11 @@ func (d *Dice) JsLoadScripts() {
}
d.Logger.Infof("正在加载脚本「%s:%s:%s」,其依赖:%s", jsInfo.Author, jsInfo.Name, jsInfo.Version, strings.Join(depends, "、"))
}

if strings.ToLower(filepath.Ext(jsInfo.Filename)) == ".ts" {
jsInfo.needCompiled = true
}

d.JsLoadScriptRaw(jsInfo)
}
}
Expand Down Expand Up @@ -861,6 +872,8 @@ type JsScriptInfo struct {
Digest string `json:"-"`
/** 依赖项 */
Depends []JsScriptDepends `json:"depends"`
/** 需要被编译 */
needCompiled bool
}

type JsScriptDepends struct {
Expand Down Expand Up @@ -979,6 +992,8 @@ func (d *Dice) JsParseMeta(s string, installTime time.Time, rawData []byte, buil
if !verOK {
errMsg = append(errMsg, fmt.Sprintf("插件「%s」依赖的海豹版本限制在 %s,与海豹版本(%s)的JSAPI不兼容", jsInfo.Name, v, VERSION.String()))
}
case "needCompiled":
jsInfo.needCompiled = true
}
}
jsInfo.UpdateUrls = updateUrls
Expand All @@ -997,7 +1012,19 @@ func (d *Dice) JsLoadScriptRaw(jsInfo *JsScriptInfo) {
var err error
if jsInfo.Enable {
d.JsLoadingScript = jsInfo
_, err = d.JsRequire.Require(jsInfo.Filename)
var targetPath string
if jsInfo.needCompiled {
d.Logger.Infof("脚本<%s>正在经过编译处理……", jsInfo.Name)
targetPath, err = tsScriptCompile(jsInfo.Filename)
defer func(name string) {
_ = os.Remove(name)
}(targetPath)
} else {
targetPath = jsInfo.Filename
}
if err == nil {
_, err = d.JsRequire.Require(targetPath)
}
d.JsLoadingScript = nil
} else {
d.Logger.Infof("脚本<%s>已被禁用,跳过加载", jsInfo.Name)
Expand All @@ -1011,6 +1038,35 @@ func (d *Dice) JsLoadScriptRaw(jsInfo *JsScriptInfo) {
}
}

func tsScriptCompile(path string) (string, error) {
script, err := os.ReadFile(path)
if err != nil {
return "", err
}
compiled := esbuild.Transform(string(script), esbuild.TransformOptions{
Loader: esbuild.LoaderTS,
})
if len(compiled.Errors) > 0 {
var msg string
for _, e := range compiled.Errors {
msg += e.Text // FIXME 优化错误信息展示
}
return "", errors.New(msg)
}
compiledPath, err := os.CreateTemp("", "compiled-*-"+filepath.Base(path))
if err != nil {
return "", err
}
defer func(compiledPath *os.File) {
_ = compiledPath.Close()
}(compiledPath)
_, err = compiledPath.Write(compiled.Code)
if err != nil {
return "", err
}
return compiledPath.Name(), nil
}

func CheckJsSign(rawData []byte) (bool, SignStatus) {
if OfficialModPublicKey == "" || len(rawData) == 0 {
return false, UnknownSign
Expand Down
4 changes: 2 additions & 2 deletions dice/ext_coc7.go
Original file line number Diff line number Diff line change
Expand Up @@ -1148,7 +1148,7 @@ func RegisterBuiltinExtCoc7(self *Dice) {
cmdTi := &CmdItemInfo{
Name: "ti",
ShortHelp: ".ti // 抽取一个临时性疯狂症状",
Help: "抽取临时性疯狂症状:\n.li // 抽取一个临时性疯狂症状",
Help: "抽取临时性疯狂症状:\n.ti // 抽取一个临时性疯狂症状",
Solve: func(ctx *MsgContext, msg *Message, cmdArgs *CmdArgs) CmdExecuteResult {
if cmdArgs.IsArgEqual(1, "help") {
return CmdExecuteResult{Matched: true, Solved: true, ShowHelp: true}
Expand Down Expand Up @@ -1527,7 +1527,7 @@ func RegisterBuiltinExtCoc7(self *Dice) {

var ss []string
for i = 0; i < val; i++ {
result := ctx.EvalFString(`力量:{$t1=3d6*5} 敏捷:{$t2=3d6*5} 意志:{$t3=3d6*5}\n体质:{$t4=3d6*5} 外貌:{$t5=3d6*5} 教育:{$t6=(2d6+6)*5}\n体型:{$t7=(2d6+6)*5} 智力:{$t8=(2d6+6)*5}\nHP:{($t4+$t7)/10} 幸运:{$t9=3d6*5} [{$t1+$t2+$t3+$t4+$t5+$t6+$t7+$t8}/{$t1+$t2+$t3+$t4+$t5+$t6+$t7+$t8+$t9}]`, nil)
result := ctx.EvalFString(`力量:{力量=3d6*5} 敏捷:{敏捷=3d6*5} 意志:{意志=3d6*5}\n体质:{体质=3d6*5} 外貌:{外貌=3d6*5} 教育:{教育=(2d6+6)*5}\n体型:{体型=(2d6+6)*5} 智力:{智力=(2d6+6)*5} 幸运:{幸运=3d6*5}\nHP:{(体质+体型)/10} <DB:{(力量 + 体型) < 65 ? -2, (力量 + 体型) < 85 ? -1, (力量 + 体型) < 125 ? 0, (力量 + 体型) < 165 ? '1d4', (力量 + 体型) < 205 ? '1d6'}> [{力量+敏捷+意志+体质+外貌+教育+体型+智力}/{力量+敏捷+意志+体质+外貌+教育+体型+智力+幸运}]`, nil)
if result.vm.Error != nil {
break
}
Expand Down
2 changes: 2 additions & 0 deletions dice/ext_log.go
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,8 @@ func RegisterBuiltinExtLog(self *Dice) {
uri = "files://" + logFile.Name()
}
SendFileToSenderRaw(ctx, msg, uri, "skip")
VarSetValueStr(ctx, "$t文件名字", logFileNamePrefix)
ReplyToSenderRaw(ctx, msg, DiceFormatTmpl(ctx, "日志:记录_导出_成功"), "skip")
return CmdExecuteResult{Matched: true, Solved: true}
} else {
return CmdExecuteResult{Matched: true, Solved: true, ShowHelp: true}
Expand Down
Loading

0 comments on commit 26ca472

Please sign in to comment.