util

package
v0.0.0-...-c8dcdd0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 14, 2026 License: AGPL-3.0 Imports: 84 Imported by: 13

Documentation

Index

Constants

View Source
const (
	TLSCACertFilename = "ca.crt"
	TLSCAKeyFilename  = "ca.key"
	TLSCertFilename   = "cert.pem"
	TLSKeyFilename    = "key.pem"
)
View Source
const (
	BazaarStatServer = "https://bazaar.b3logfile.com" // 集市包统计服务地址,七牛云,全球 CDN
	BazaarOSSServer  = "https://oss.b3logfile.com"    // 云端对象存储地址,七牛云,仅用于读取集市包,全球 CDN
)
View Source
const (
	BLOCK_BITS = 22 // Indicate that the blocksize is 4M
	BLOCK_SIZE = 1 << BLOCK_BITS
)
View Source
const (
	EvtConfPandocInitialized = "conf.pandoc.initialized"

	EvtSQLHistoryRebuild      = "sql.history.rebuild"
	EvtSQLAssetContentRebuild = "sql.assetContent.rebuild"
)
View Source
const (
	SortModeNameASC         = iota // 0:文件名字母升序
	SortModeNameDESC               // 1:文件名字母降序
	SortModeUpdatedASC             // 2:文件更新时间升序
	SortModeUpdatedDESC            // 3:文件更新时间降序
	SortModeAlphanumASC            // 4:文件名自然数升序
	SortModeAlphanumDESC           // 5:文件名自然数降序
	SortModeCustom                 // 6:自定义排序
	SortModeRefCountASC            // 7:引用数升序
	SortModeRefCountDESC           // 8:引用数降序
	SortModeCreatedASC             // 9:文件创建时间升序
	SortModeCreatedDESC            // 10:文件创建时间降序
	SortModeSizeASC                // 11:文件大小升序
	SortModeSizeDESC               // 12:文件大小降序
	SortModeSubDocCountASC         // 13:子文档数升序
	SortModeSubDocCountDESC        // 14:子文档数降序
	SortModeFileTree               // 15:使用文档树排序规则

	SortModeUnassigned = 256 // 256:未指定排序规则,按照笔记本优先于文档树获取排序规则
)
View Source
const (
	PushProgressCodeProgressed = 0 // 有进度
	PushProgressCodeEndless    = 1 // 无进度
	PushProgressCodeEnd        = 2 // 关闭进度
)
View Source
const (
	Ver       = "3.7.2"
	IsInsider = false
)
View Source
const (
	ContainerStd     = "std"     // 桌面端
	ContainerDocker  = "docker"  // Docker 容器端
	ContainerAndroid = "android" // Android 端
	ContainerIOS     = "ios"     // iOS 端
	ContainerHarmony = "harmony" // 鸿蒙端

	LocalHost = "127.0.0.1" // 伺服地址
	FixedPort = "6806"      // 固定端口
)
View Source
const DatabaseVer = "202607031200"

DatabaseVer 数据库版本。 格式:yyyyMMddHHmm。修改表结构时需要更新此值,启动时会检测版本变化, 若不一致则自动移除旧数据库文件并重建表结构,同时触发全量重建索引。

View Source
const (
	// EncryptionSpec 表示 AES-GCM 密文信封规范版本。旧版密文没有信封头,读取时保持兼容。
	EncryptionSpec byte = 1
)
View Source
const MaxToolOutputChars = 40000
View Source
const (
	// SQLFlushInterval 为数据库事务队列写入间隔。
	SQLFlushInterval = 3000 * time.Millisecond
)

Variables

View Source
var (
	TesseractBin     = "tesseract"
	TesseractEnabled bool
	TesseractMaxSize = 2 * 1000 * uint64(1000)
	TesseractLangs   []string
)
View Source
var (
	NodeOCRQueue     []string
	NodeOCRQueueLock = sync.Mutex{}
)
View Source
var (
	PandocBinPath         string // Pandoc 可执行文件路径
	PandocTemplatePath    string // Pandoc Docx 模板文件路径
	PandocColorFilterPath string // Pandoc 颜色过滤器路径
)
View Source
var (
	SSL       = false
	UserAgent = "SiYuan/" + Ver
)
View Source
var (
	SiYuanAssetsImage = []string{".apng", ".ico", ".cur", ".jpg", ".jpe", ".jpeg", ".jfif", ".pjp", ".pjpeg", ".png", ".gif", ".webp", ".bmp", ".svg", ".avif"}
	SiYuanAssetsAudio = []string{".mp3", ".wav", ".ogg", ".m4a", ".flac"}
	SiYuanAssetsVideo = []string{".mov", ".weba", ".mkv", ".mp4", ".webm"}
)
View Source
var (
	UseSingleLineSave    = true // UseSingleLineSave 是否使用单行保存 .sy 和数据库 .json 文件。
	LargeFileWarningSize = 8    // LargeFileWarningSize 大文件警告大小,单位:MB
)
View Source
var (
	Langs           = map[string]map[int]string{}
	TimeLangs       = map[string]map[string]any{}
	TaskActionLangs = map[string]map[string]any{}
	TrayMenuLangs   = map[string]map[string]any{}
	AttrViewLangs   = map[string]map[string]any{}
)
View Source
var (
	WebSocketServer *melody.Melody

	// ReloadDocInfoGuard 由 model 层注入,在广播 docInfo 前检查 box 是否仍处于可广播状态。
	// 加密笔记本锁定后返回 false,防止 500ms 延迟任务在锁定后泄漏明文元数据。
	ReloadDocInfoGuard func(boxID string) bool
)
View Source
var (
	RunInContainer             = false // 是否运行在容器中
	SiYuanAccessAuthCodeBypass = false // 是否跳过空锁屏密码检查
	AttachUI                   = false // 是否绑定桌面 UI 进程生命周期(Electron 拉起时为 true,手动 serve 为 false)
)
View Source
var (
	HttpServer  *http.Server // HTTP 伺服器实例
	HttpServing = false      // 是否 HTTP 伺服已经可用

	SafeMode = false // 是否以安全模式启动:禁用代码片段、插件、自定义主题与图标
)
View Source
var (
	HomeDir, _    = gulu.OS.Home()
	WorkingDir, _ = os.Getwd()

	WorkspaceDir       string        // 工作空间目录路径
	WorkspaceName      string        // 工作空间名称
	WorkspaceLock      *flock.Flock  // 工作空间锁
	ConfDir            string        // 配置目录路径
	DataDir            string        // 数据目录路径
	RepoDir            string        // 仓库目录路径
	HistoryDir         string        // 数据历史目录路径
	TempDir            string        // 临时目录路径
	QueueDir           string        // 队列目录路径
	LogPath            string        // 配置目录下的日志文件 siyuan.log 路径
	DBName             = "siyuan.db" // SQLite 数据库文件名
	DBPath             string        // SQLite 数据库文件路径
	HistoryDBPath      string        // SQLite 历史数据库文件路径
	AssetContentDBPath string        // SQLite 资源文件内容数据库文件路径
	BlockTreeDBPath    string        // 区块树数据库文件路径
	AppearancePath     string        // 配置目录下的外观目录 appearance/ 路径
	ThemesPath         string        // 配置目录下的外观目录下的 themes/ 路径
	IconsPath          string        // 配置目录下的外观目录下的 icons/ 路径
	SnippetsPath       string        // 数据目录下的 snippets/ 路径
	ShortcutsPath      string        // 用户家目录下的快捷方式目录路径 home/.config/siyuan/shortcuts/

	UIProcessIDs = sync.Map{} // UI 进程 ID
)
View Source
var (
	ServerURL  *url.URL // 内核服务 URL
	ServerPort = "0"    // HTTP/WebSocket 端口,0 为使用随机端口

	ReadOnly       bool
	AccessAuthCode string
	Lang           = ""

	Container        string // docker, android, ios, harmony, std
	ISMicrosoftStore bool   // 桌面端是否是微软商店版
)
View Source
var CLILogLevel string

CLILogLevel 在 CLI 子命令通过 --log-level 显式指定日志级别时被设置,model.InitConf 末尾据此跳过对 logging.SetLogLevel 的覆盖,使命令行参数优先于 conf.json 的 system.logLevel。

View Source
var CurrentCloudRegion = 0
View Source
var DisabledFeatures []string
View Source
var ErrPandocNotFound = errors.New("not found executable pandoc")
View Source
var IsExiting = atomic.Bool{}

IsExiting 是否正在退出程序。

View Source
var IsUILoaded = false

IsUILoaded 是否已经加载了 UI。

View Source
var LangLegacyToBCP47 = map[string]string{
	"zh_CN":  "zh-CN",
	"zh_CHT": "zh-TW",
	"en_US":  "en",
	"de_DE":  "de",
	"fr_FR":  "fr",
	"es_ES":  "es",
	"pt_BR":  "pt-BR",
	"it_IT":  "it",
	"ja_JP":  "ja",
	"ko_KR":  "ko",
	"ru_RU":  "ru",
	"uk_UA":  "uk",
	"pl_PL":  "pl",
	"nl_NL":  "nl",
	"ar_SA":  "ar",
	"he_IL":  "he",
	"hi_IN":  "hi",
	"id_ID":  "id",
	"th_TH":  "th",
	"tr_TR":  "tr",
	"sk_SK":  "sk",
}

langLegacyToBCP47 从历史下划线标识映射到 BCP 47 标准语言代码。

View Source
var LocalIPs []string
View Source
var MarkdownSettings = &Markdown{
	InlineAsterisk:      true,
	InlineUnderscore:    true,
	InlineSup:           true,
	InlineSub:           true,
	InlineTag:           true,
	InlineMath:          true,
	InlineStrikethrough: true,
	InlineMark:          true,
}

MarkdownSettings 运行时 Markdown 配置。

View Source
var MobileOSVer string

MobileOSVer 移动端操作系统版本。

View Source
var Mode = "prod"

var Mode = "dev"

View Source
var NativeEmojiChars = map[string]bool{}
View Source
var (
	RhyCacheDuration = int64(3600 * 6)
)
View Source
var SK = []byte("696D897C9AA0611B")
View Source
var SearchCaseSensitive bool
View Source
var SearchHanSensitive = true

SearchHanSensitive 是否区分繁简,由 sql.SetHanSensitive 维护;默认 true 与既往行为一致

View Source
var WrongAuthCount int

Functions

func AESDecrypt

func AESDecrypt(cryptStr string) []byte

func AESEncrypt

func AESEncrypt(str string) string

func AddPushChan

func AddPushChan(session *melody.Session)

func AssetName

func AssetName(name, newID string) string

func BatchGetEmbeddings

func BatchGetEmbeddings(texts []string, apiKey, baseURL, model string, dimensions, timeout int) (ret [][]float32, err error)

func BlockCount

func BlockCount(fsize int64) int

func Boot

func Boot()

func BootL10n

func BootL10n(num int, fallback string) string

BootL10n 返回启动进度文案的本地化字符串。

按当前界面语言(util.Lang,来自 conf.json)查 util.Langs 中 _kernel 块的整数键, 依次回退到英文、再回退到调用方传入的 fallback 英文文案。 这样在首启 InitConf() 尚未加载完语言文件时也能显示原文,不会出现空串。

func BootMobile

func BootMobile(container, appDir, workspaceBaseDir, lang string)

func BootWithFlags

func BootWithFlags(workspacePath, wdPath, port, readOnly, accessAuthCode, lang, mode string, ssl, attachUI, safeMode bool)

BootWithFlags 接收已解析好的启动参数,完成环境变量回退、全局变量赋值、工作空间初始化与加锁等启动收尾工作。Boot()(标准库 flag 解析)和 serve 子命令(cobra 解析)都走这个统一入口。

func Broadcast

func Broadcast(msg []byte)

func BroadcastByType

func BroadcastByType(typ, cmd string, code int, msg string, data any)

BroadcastByType 广播所有实例上 typ 类型的会话。

func BroadcastByTypeAndApp

func BroadcastByTypeAndApp(typ, app, cmd string, code int, msg string, data any)

func BroadcastByTypeAndExcludeApp

func BroadcastByTypeAndExcludeApp(excludeApp, typ, cmd string, code int, msg string, data any)

func CalSha1

func CalSha1(b []byte, r io.Reader) ([]byte, error)

func CeilSize

func CeilSize(size int64) int64

func ChatGPT

func ChatGPT(msg string, contextMsgs []string, c *openai.Client, model string, maxTokens int, temperature float64, timeout int) (ret string, stop bool, err error)

func CheckFileSysStatus

func CheckFileSysStatus()

func CheckHostSSRF

func CheckHostSSRF(host string) error

CheckHostSSRF 校验主机名解析出的 IP 不落在内网/回环等不可达地址段, 防止智能体被诱导发起 SSRF 攻击。web_fetch 与 http_request 共用此校验。

func CleanNotExistAssetsTexts

func CleanNotExistAssetsTexts()

func ClearPushProgress

func ClearPushProgress(total int)

func ClosePublishServiceSessions

func ClosePublishServiceSessions()

ClosePublishServiceSessions 关闭所有发布服务的 WebSocket 连接

func ClosePushChan

func ClosePushChan(id string)

func ContainsCJK

func ContainsCJK(text string) bool

func ContainsSubStr

func ContainsSubStr(s string, subStrs []string) bool

func ContextPushMsg

func ContextPushMsg(context map[string]any, msg string)

func Convert2Float

func Convert2Float(s string) (float64, bool)
func ConvertIframeToLink(htmlStr string) string

func ConvertPandoc

func ConvertPandoc(dir string, args ...string) (path string, err error)

func CountIf

func CountIf(list any, op string, threshold any) int

CountIf 统计数字列表中满足指定比较条件的元素个数。 op 为比较操作符:"gt"/"lt"/"eq"/"ge"/"le",threshold 为比较阈值。 例如 CountIf(values, "gt", 0) 统计大于 0 的个数。非数字元素按 0 处理。

func CountSessions

func CountSessions() (ret int)

func CurrentTimeMillis

func CurrentTimeMillis() int64

func CurrentTimeSecondsStr

func CurrentTimeSecondsStr() string

func DataSize

func DataSize() (dataSize, assetsSize int64)

func Decrypt

func Decrypt(key, ciphertext []byte) ([]byte, error)

Decrypt 对应 Encrypt 的解密。兼容旧版 nonce||ciphertext||tag 格式。 密钥错误或密文被篡改时返回错误(GCM 自带完整性校验)。

func DecryptWithAAD

func DecryptWithAAD(key, ciphertext, aad []byte) ([]byte, error)

DecryptWithAAD 对应 EncryptWithAAD 的解密,兼容旧版 nonce||ciphertext||tag 格式。 AAD 不匹配或密文被篡改时返回错误。

func DeduplicateWorkspacePaths

func DeduplicateWorkspacePaths(paths []string) []string

func DeriveKey

func DeriveKey(password string, salt []byte, p Argon2Params) []byte

DeriveKey 用 Argon2id 从密码派生密钥。同一 password+salt+params 多次调用结果一致。

func DeriveSubKey

func DeriveSubKey(dek []byte, purpose string) []byte

DeriveSubKey 用 HKDF-SHA256 从主 DEK 派生用途隔离的子密钥。 同一 (dek, purpose) 多次调用结果一致;不同 purpose 派生出相互独立的子密钥, 实现用途分离——.sy/assets/AV 各用独立子密钥,互不可替代,限制单点密钥泄漏的影响面。

func DisableFeature

func DisableFeature(feature string)

func EmojiPinYinCompare

func EmojiPinYinCompare(str1, str2 string) bool

func Encrypt

func Encrypt(key, plaintext []byte) ([]byte, error)

Encrypt 用 AES-256-GCM 加密。每次调用生成随机 nonce,因此同一明文多次加密结果不同。 返回格式:magic(4B) || spec(1B) || algorithm(1B) || nonceLength(1B) || nonce || ciphertext || GCM tag(16B)。

func EncryptWithAAD

func EncryptWithAAD(key, plaintext, aad []byte) ([]byte, error)

EncryptWithAAD 用 AES-256-GCM 加密并绑定 AAD(附加认证数据)。 AAD 不被加密,但参与 GCM 认证——解密时必须提供相同 AAD,否则认证失败。 把用途/boxID/路径等元数据放入 AAD,可防止同 box 内密文被替换用途或路径(bind 到上下文)。 返回格式与 Encrypt 一致,但 AAD 参与校验。

func EncryptedBlockTreeDBPath

func EncryptedBlockTreeDBPath(boxID string) string

EncryptedBlockTreeDBPath 返回加密笔记本的独立 SQLCipher blocktree db 文件路径。

func EncryptedDBPath

func EncryptedDBPath(boxID string) string

EncryptedDBPath 返回加密笔记本的独立 SQLCipher db 文件路径。 与 siyuan.db 同放 temp 目录,文件名带 boxID 区分多个加密笔记本。db 是可重建的索引,非原始内容。

func EncryptionNonce

func EncryptionNonce(ciphertext []byte) ([]byte, error)

EncryptionNonce 从 AES-GCM 密文中提取 nonce,兼容旧版无信封头格式。

func EscapeHTML

func EscapeHTML(s string) (ret string)

func ExceedLargeFileWarningSize

func ExceedLargeFileWarningSize(fileSize int) bool

func ExistsAssetText

func ExistsAssetText(asset string) (ret bool)

func Ext

func Ext(name string) (ret string)

func ExtraBodyForModel

func ExtraBodyForModel(model string) map[string]any

ExtraBodyForModel 按模型名大小写不敏感匹配内置清单,返回需注入的额外请求参数;无匹配返回 nil。

func FileURLToLocalPath

func FileURLToLocalPath(fileURL string) string

FileURLToLocalPath 将 file:// URL 转为本地文件路径。

func FilterFileName

func FilterFileName(name string) string

func FilterFilePath

func FilterFilePath(p string) (ret string)

func FilterMoveDocFromPaths

func FilterMoveDocFromPaths(fromPaths []string, toPath string) (ret []string)

func FilterSelfChildDocs

func FilterSelfChildDocs(paths []string) (ret []string)

func FilterUploadEmojiFileName

func FilterUploadEmojiFileName(name string) string

func FilterUploadFileName

func FilterUploadFileName(name string) string

func GBK2UTF8

func GBK2UTF8(src []byte) (string, error)

GBK2UTF8 transform GBK byte array into UTF8 string.

func GenerateDEK

func GenerateDEK() ([]byte, error)

GenerateDEK 生成随机数据密钥(32 字节,AES-256)。

func GenerateSalt

func GenerateSalt() ([]byte, error)

GenerateSalt 生成随机 salt(16 字节)。

func GetAbsPathInWorkspace

func GetAbsPathInWorkspace(relPath string) (string, error)

func GetAssetText

func GetAssetText(asset string) (ret string)

func GetBootProgress

func GetBootProgress() int32

func GetBootProgressDetails

func GetBootProgressDetails() (progress int32, details string)

func GetChildDocDepth

func GetChildDocDepth(treeAbsPath string) (ret int)

func GetCloudAccountServer

func GetCloudAccountServer() string

func GetCloudAssetsServer

func GetCloudAssetsServer() string

func GetCloudForumAssetsServer

func GetCloudForumAssetsServer() string

func GetCloudServer

func GetCloudServer() string

func GetCloudSyncServer

func GetCloudSyncServer() string

func GetCloudWebSocketServer

func GetCloudWebSocketServer() string

func GetContainsSubStrs

func GetContainsSubStrs(s string, subStrs []string) (ret []string)

func GetDataAssetsAbsPath

func GetDataAssetsAbsPath() (ret string)

func GetDeviceID

func GetDeviceID() string

func GetDeviceName

func GetDeviceName() string

func GetDiskUsage

func GetDiskUsage(p string) (total, used, free uint64)

func GetDuplicateName

func GetDuplicateName(master string) (ret string)

func GetEtag

func GetEtag(filename string) (etag string, err error)

func GetEtagByHandle

func GetEtagByHandle(f io.Reader, size int64) (etag string, err error)

func GetFilePathsByExts

func GetFilePathsByExts(dirPath string, exts []string) (ret []string)

func GetMimeTypeByExt

func GetMimeTypeByExt(filePath string) (ret string)

func GetMimeTypeByPath

func GetMimeTypeByPath(filePath string) (m *mimetype.MIME, ok bool)

func GetOSPlatform

func GetOSPlatform() (plat string)

func GetOcrJsonText

func GetOcrJsonText(jsonData []map[string]any) (ret string)

GetOcrJsonText 提取并连接所有 text 字段的函数

func GetOrCreateTLSCert

func GetOrCreateTLSCert() (certPath, keyPath string, err error)

GetOrCreateTLSCert returns paths to existing TLS certificates or generates new ones signed by a local CA. Certificates are stored in the conf directory of the workspace.

func GetPrivateIPv4s

func GetPrivateIPv4s() (ret []string)

GetPrivateIPv4s 获取本地所有的私有 IPv4 地址(排除虚拟网卡)

func GetRemoteAddr

func GetRemoteAddr(req *http.Request) string

func GetRequestStringParam

func GetRequestStringParam(c *gin.Context, key string, result *gulu.Result) string

GetRequestStringParam extracts a string parameter from the request (URL or JSON body), with validation and error handling.

func GetRequestUrlStringParam

func GetRequestUrlStringParam(c *gin.Context, key string) string

GetRequestUrlStringParam extracts a string parameter from URL (path or query parameters).

func GetRhyBazaarHash

func GetRhyBazaarHash(ctx context.Context) string

func GetRhyResult

func GetRhyResult(ctx context.Context, force bool) (map[string]any, error)

func GetServerAddrs

func GetServerAddrs() (ret []string)

func GetTodayStart

func GetTodayStart() (ret time.Time)

func GetTreeID

func GetTreeID(treePath string) string

func GetUniqueFilename

func GetUniqueFilename(filePath string) string

func HTTPRequest

func HTTPRequest(method, rawURL string, headers map[string]string, body string) (statusCode int, contentType string, text string, err error)

HTTPRequest 发起一次通用 HTTP 调用,供智能体 http_request 工具使用。 与 WebFetch 不同:本函数不做 HTML→Markdown 转换,文本类响应(含 JSON/XML)原样返回, 便于智能体直接消费 REST API 的 JSON 输出。method 取值:GET/POST/PUT/DELETE/PATCH。 返回的 text 为响应正文(文本类)或落盘后的文件路径(二进制类)。

func HasUnclosedHtmlTag

func HasUnclosedHtmlTag(htmlStr string) bool

func HookUILoaded

func HookUILoaded()

func HumanizeDiffTime

func HumanizeDiffTime(a, b time.Time, lang string) string

func HumanizeRelTime

func HumanizeRelTime(a time.Time, b time.Time, lang string) string

func HumanizeTime

func HumanizeTime(then time.Time, lang string) string

func I18nTerm

func I18nTerm(language, key string) (ret string)

func ISOMonth

func ISOMonth(date time.Time) int

ISOMonth returns the month in which the Thursday of the ISO 8601 week of date occurs.

func ISOWeek

func ISOWeek(date time.Time) int

ISOWeek returns the ISO 8601 week number in which date occurs. Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 of year n+1.

func ISOWeekDate

func ISOWeekDate(day int, date time.Time) time.Time

ISOWeekDate returns the date of the specified day of the week in the ISO 8601 week of date. day: Monday=1, ..., Sunday=7.

func ISOYear

func ISOYear(date time.Time) int

ISOYear returns the ISO 8601 year in which date occurs.

func ImportCABundle

func ImportCABundle(caCertPEM, caKeyPEM string) error

ImportCABundle imports a CA certificate and private key from PEM-encoded strings.

func IncBootProgress

func IncBootProgress(progress int32, details string)

func InitEmojiChars

func InitEmojiChars()

func InitPandoc

func InitPandoc()

func InitTesseract

func InitTesseract()

func InitWorkspace

func InitWorkspace(workspacePath, wdPath string)

func InsertElem

func InsertElem[T any](s []T, index int, value T) []T

InsertElem inserts value at index into s. 0 <= index <= len(s)

func InvalidIDPattern

func InvalidIDPattern(idArg string, result *gulu.Result) bool

func IsAbsPathInWorkspace

func IsAbsPathInWorkspace(absPath string) bool

func IsAssetLinkDest

func IsAssetLinkDest(dest []byte, includeServePath bool) bool

func IsAuthSession

func IsAuthSession(session *melody.Session) bool

func IsBooted

func IsBooted() bool

func IsBrowserRequest

func IsBrowserRequest(c *gin.Context) bool

IsBrowserRequest 判断请求是否来自浏览器(非 SiYuan 原生客户端)。 原生客户端(桌面 Electron、Android/iOS/Harmony)的 User-Agent 均以 "SiYuan/" 开头, 其余视为浏览器。该口径与前端 getFrontend()、electron/main.js 设置的 UA 前缀、 以及 session 鉴权中既有的 HasPrefix(ua, "SiYuan/") 判断保持一致。

func IsChinaCloud

func IsChinaCloud() bool

func IsCiphertext

func IsCiphertext(data []byte) bool

IsCiphertext 判断给定字节是否以加密信封魔数开头(即是否为密文)。 供历史索引等无法取得 boxID/DEK 的路径做防御性检测:读到密文时跳过解析而非按 JSON 报错, 避免加密笔记本的 AV 等对象因路径迁移(同步、导入、历史布局变化)落到全局位置时产生噪声错误。

func IsCloudDrivePath

func IsCloudDrivePath(workspaceAbsPath string) bool

func IsCommonExt

func IsCommonExt(ext string) bool

func IsCompressibleAssetImage

func IsCompressibleAssetImage(p string) bool
func IsDirRegularOrSymlink(dir fs.DirEntry) bool

func IsDisplayableAsset

func IsDisplayableAsset(p string) bool

func IsEmptyDir

func IsEmptyDir(p string) bool

func IsIdle

func IsIdle(idleThreshold time.Duration) bool

IsIdle 自上次用户活动以来是否已超过 idleThreshold。

func IsIndexFixDirty

func IsIndexFixDirty() bool

IsIndexFixDirty 返回是否存在未订正的变更(上次订正后有新用户活动)。

func IsLocalHost

func IsLocalHost(host string) bool

func IsLocalHostname

func IsLocalHostname(hostname string) bool

func IsLocalOrigin

func IsLocalOrigin(origin string) bool

func IsMobileContainer

func IsMobileContainer() bool

IsMobileContainer 表示当前内核运行在 Android、iOS 或鸿蒙客户端上。

func IsNetworkError

func IsNetworkError(err error) bool

func IsOfficeTempFile

func IsOfficeTempFile(assetAbsPath string) bool

IsOfficeTempFile 判断是否为 Office(Word/Excel/PowerPoint/WPS)打开文档时生成的临时文件。 这些文件名以 `~$` 开头,且被宿主程序独占,尝试读取会触发 filelock 的致命错误,需跳过。

func IsOnline

func IsOnline(checkURL string, skipTlsVerify bool, timeout int) bool

func IsPartitionRootPath

func IsPartitionRootPath(path string) bool

IsPartitionRootPath checks if the given path is a partition root path.

func IsPathRegularDirOrSymlinkDir

func IsPathRegularDirOrSymlinkDir(path string) bool

func IsPortOpen

func IsPortOpen(port string) bool

func IsPossiblyImage

func IsPossiblyImage(assetPath string) bool

IsPossiblyImage 模糊判断指定文件链接是否可能是图片。

func IsRelativePath

func IsRelativePath(dest string) bool

func IsReleaseVer

func IsReleaseVer(ver string) bool

IsReleaseVer 判断是否为正式版(不含 alpha、beta、rc 等预发布标识)。

func IsReservedFilename

func IsReservedFilename(baseName string) bool

func IsSensitivePath

func IsSensitivePath(p string) bool

IsSensitivePath 对传入路径做统一的敏感性检测。

为防止通过符号链接绕过黑名单,对工作空间外的路径会额外解析符号链接后再检查一次:这是 globalCopyFiles 等接受工作空间外绝对路径的接口的攻击面。工作空间内的路径不解析符号链接, 一是因为工作空间内文件(如 assets 中指向外部目录的符号链接)可能合法地指向工作空间外, 对其解析后执行系统目录前缀检查会误伤;二是避免在高 QPS 的伺服热路径上引入额外的 stat 开销。 解析失败(如路径不存在)时回退到仅检查原始路径。

func IsSymlink(dir fs.DirEntry) bool

func IsSymlinkPath

func IsSymlinkPath(absPath string) bool

func IsTesseractExtractable

func IsTesseractExtractable(p string) bool

func IsTimeStr

func IsTimeStr(str string) bool

func IsValidPandocBin

func IsValidPandocBin(binPath string) bool

func IsValidUploadFileName

func IsValidUploadFileName(name string) bool

func IsWorkspaceDir

func IsWorkspaceDir(dir string) bool

IsWorkspaceDir 判断指定目录是否是工作空间目录。

func IsWorkspaceLocked

func IsWorkspaceLocked(workspacePath string) bool

func JsonArg

func JsonArg(c *gin.Context, result *gulu.Result) (arg map[string]any, ok bool)

func LangToBCP47

func LangToBCP47(lang string) string

LangToBCP47 把历史下划线标识映射为 BCP 47 标准语言代码(如 zh_CN → zh-CN)。 不是历史下划线标识时原样返回。

func LangToLegacy

func LangToLegacy(lang string) string

LangToLegacy 把 BCP 47 标准语言代码映射为历史下划线标识(如 zh-CN → zh_CN)。 不是 BCP 47 标准语言代码时原样返回。

func LastID

func LastID(p string) (name, id string)

func LinkTarget

func LinkTarget(htmlStr, linkBase string) (ret string)

func ListAvailableModels

func ListAvailableModels(apiKey, apiBaseURL string, timeout int) (models []string, err error)

ListAvailableModels 拉取 Provider 的可用模型清单(GET /v1/models),仅返回模型 ID 列表。 用于填充前端模型名称下拉框。不支持该端点的服务会返回错误,由调用方回退为手动输入。

func LoadAssetsTexts

func LoadAssetsTexts()

func LoadSkillContent

func LoadSkillContent(name string) string

func LogDatabaseSize

func LogDatabaseSize(dbPath string)

func MarkIndexClean

func MarkIndexClean()

MarkIndexClean 标记索引已订正完成,清除脏标志。订正流水线结束后调用。

func Millisecond2Time

func Millisecond2Time(t int64) time.Time

func NaturalCompare

func NaturalCompare(str1, str2 string) bool

func NeedCaptcha

func NeedCaptcha() bool

func NeedWarnDiskUsage

func NeedWarnDiskUsage(dataSize int64) bool

func NewCustomReqClient

func NewCustomReqClient() *req.Client

NewCustomReqClient 创建自定义 req 客户端

func NewLute

func NewLute() (ret *lute.Lute)

func NewOpenAIClient

func NewOpenAIClient(apiKey, apiBaseURL string) *openai.Client

func NewOpenAIClientWithModel

func NewOpenAIClientWithModel(apiKey, apiBaseURL, model string) *openai.Client

NewOpenAIClientWithModel 创建 OpenAI client,并按模型名匹配内置清单注入额外请求参数。 绝大多数模型无匹配,走 NewOpenAIClient 老路径(不包中间件,零开销); 命中清单的模型(如 MiniMax)会注入厂商专属参数(如 reasoning_split)。

func NewStdLute

func NewStdLute() (ret *lute.Lute)

func NodeIDByTime

func NodeIDByTime(t time.Time) string

NodeIDByTime 根据指定时间生成符合块 ID 格式的字符串,算法与 ast.NewNodeID() 一致, 仅时间源不同:用于让历史输入(如移动端速记暂存文件名时间戳)回填为块 ID。

func NormalizeConcurrentReqs

func NormalizeConcurrentReqs(concurrentReqs int, provider int) int

func NormalizeEndpoint

func NormalizeEndpoint(endpoint string) string

func NormalizeLocalPath

func NormalizeLocalPath(endpoint string) string

func NormalizeTimeout

func NormalizeTimeout(timeout int) int

func OcrAsset

func OcrAsset(asset string) (ret []map[string]any, err error)

func Pandoc

func Pandoc(from, to, o, content string) (err error)

func ParseJsonArg

func ParseJsonArg[T any](key string, arg map[string]any, ret *gulu.Result, required, rejectEmpty bool) (value T, ok bool)

ParseJsonArg 使用泛型从 JSON 参数中提取指定键的值。

  • 如果 required 为 true 但参数缺失,则会在 ret.Msg 中说明需要传入的键
  • 如果 rejectEmpty 为 true 但参数值为空,则会在 ret.Msg 中说明该键必须不为空(字符串去空白后、空数组、无任何键的对象)
  • 如果参数存在但类型不匹配,则会在 ret.Msg 中说明该键期望的类型
  • 返回值 ok 为 false 时,表示提取失败、类型不匹配或不满足非空约束

func ParseJsonArgs

func ParseJsonArgs(arg map[string]any, ret *gulu.Result, extractors ...JsonArgParseFunc) bool

ParseJsonArgs 按顺序执行多个提取函数。

  • 任一失败返回 false 并在 ret 中写入错误信息
  • 全部成功返回 true

func ParsePort

func ParsePort(portString string) (uint16, error)

func PinYinCompare

func PinYinCompare(str1, str2 string) bool

func PinYinCompare4FileTree

func PinYinCompare4FileTree(str1, str2 string) bool

func PushBackgroundTask

func PushBackgroundTask(data map[string]any)

func PushClearAllMsg

func PushClearAllMsg()

func PushClearMsg

func PushClearMsg(msgId string)

PushClearMsg 会清空指定消息。

func PushClearProgress

func PushClearProgress()

PushClearProgress 取消进度遮罩。

func PushDownloadProgress

func PushDownloadProgress(id string, percent float32)

func PushEndlessProgress

func PushEndlessProgress(msg string)

func PushErrMsg

func PushErrMsg(msg string, timeout int) (msgId string)

func PushEvent

func PushEvent(event *Result)

func PushKernelPluginState

func PushKernelPluginState(name string, state int)

func PushMsg

func PushMsg(msg string, timeout int) (msgId string)

func PushMsgWithApp

func PushMsgWithApp(app, msg string, timeout int) (msgId string)

func PushNodeOCRQueue

func PushNodeOCRQueue(n *ast.Node)

func PushProgress

func PushProgress(code, current, total int, msg string)

func PushProtyleLoading

func PushProtyleLoading(rootID, msg string)

func PushReloadDoc

func PushReloadDoc(rootID string)

func PushReloadDocInfo

func PushReloadDocInfo(docInfo map[string]any)

func PushReloadEmojiConf

func PushReloadEmojiConf()

func PushReloadFiletree

func PushReloadFiletree()

func PushReloadProtyle

func PushReloadProtyle(rootID string)

func PushReloadTag

func PushReloadTag()

func PushSaveDoc

func PushSaveDoc(rootID, typ string, sources any)

func PushSetDefRefCount

func PushSetDefRefCount(rootID, blockID string, defIDs []string, refCount, rootRefCount int)

func PushSetRefDynamicText

func PushSetRefDynamicText(rootID, blockID, defBlockID, refText, boxID string)

func PushStatusBar

func PushStatusBar(msg string)

func PushTxErr

func PushTxErr(msg string, code int, data any)

func PushUpdateIDs

func PushUpdateIDs(ids map[string]string)

func PushUpdateMsg

func PushUpdateMsg(msgId string, msg string, timeout int)

func RandString

func RandString(length int) string

func RandomSleep

func RandomSleep(minMills, maxMills int)

func ReadSkill

func ReadSkill(name string) (string, error)

func ReadWorkspacePaths

func ReadWorkspacePaths() (ret []string, err error)

func RefreshActivity

func RefreshActivity()

RefreshActivity 刷新用户最近活动时间,并标记索引可能已脏(需要订正)。 在 model.Activity 中间件中,对 /api/transactions* 写操作请求调用。

func RefreshRhyResultJob

func RefreshRhyResultJob()

func ReloadUI

func ReloadUI()

func ReloadUIResetScroll

func ReloadUIResetScroll()

func RemoveAssetText

func RemoveAssetText(asset string)

func RemoveDatabaseFile

func RemoveDatabaseFile(dbPath string)

func RemoveElem

func RemoveElem[T any](s []T, index int) []T

RemoveElem removes the element at index i from s.

func RemoveEmojiInvisible

func RemoveEmojiInvisible(text string) (ret string)

func RemoveID

func RemoveID(name string) string

func RemoveInvalid

func RemoveInvalid(text string) (ret string)

func RemoveInvalidRetainCtrl

func RemoveInvalidRetainCtrl(text string) (ret string)

func RemovePushChan

func RemovePushChan(session *melody.Session)

func RemoveRedundantSpace

func RemoveRedundantSpace(str string) string

func RemoveSkill

func RemoveSkill(name string) error

func RemoveWorkspacePath

func RemoveWorkspacePath(paths []string, target string) []string

func RemoveWorkspaceSession

func RemoveWorkspaceSession(session *SessionData)

func RenameSkill

func RenameSkill(oldName, newName string) error

func ReplaceNewline

func ReplaceNewline(text, replaceWith string) string

func ReportFileSysFatalError

func ReportFileSysFatalError(err error)

func Rerank

func Rerank(query string, documents []string, apiKey, endpoint, model string, topN, timeout int) (indices []int, scores []float64, err error)

Rerank 调用重排服务对 query 与候选文档逐对精排。endpoint 为完整重排端点地址,不同服务商路径无统一标准 (Jina /v1/rerank、阿里云 compatible-api/v1/reranks、Cohere /v1/rerank 等),由用户照文档填写。 返回的 indices 与 scores 均按 relevance_score 降序,indices 指向传入 documents 的下标。 对每条 document 文本按 rerankDocTextMaxLen 截断,防超服务端 token 限制。 topN 语义:topN <= 0 时不传 top_n(服务端默认返回全部文档评分,搜索场景用此避免被服务端 top_n 上限截断); topN > 0 时透传给服务端,仅用于测试连通性等只需少量结果的场景。

func ResolveLongestExistingParent

func ResolveLongestExistingParent(absPath string) string

ResolveLongestExistingParent 解析 absPath 中最长已存在部分的 symlink,拼回剩余路径。 例如 absPath = /workspace/data/link/newdir/file,其中 /workspace/data/link 是指向 /workspace/data/<encBoxID>/ 的 symlink,newdir/file 尚不存在: 返回 /workspace/data/<encBoxID>/newdir/file。

func Reverse

func Reverse(s string) string

func SHA256Hash

func SHA256Hash(data []byte) string

func SSRFSafeDialer

func SSRFSafeDialer(timeout time.Duration) *net.Dialer

SSRFSafeDialer returns a net.Dialer whose Control hook blocks private, loopback, link-local and unspecified IPs.

func SanitizeHTML

func SanitizeHTML(h string) string

func SanitizeName

func SanitizeName(name string) string

SanitizeName replaces all non-alphanumeric characters in the input string with underscores.

func SanitizeSVG

func SanitizeSVG(svgInput string) string

func SaveAssetsTexts

func SaveAssetsTexts()

func SaveSkill

func SaveSkill(name, content string) error

func ServeMultiplexed

func ServeMultiplexed(ln net.Listener, handler http.Handler, certPath, keyPath string, httpServer, httpsServer *http.Server) (*http.Server, *http.Server, error)

ServeMultiplexed 在同一个 listener 上同时承载 HTTP 与 HTTPS(含 HTTP/2)。

httpServer / httpsServer 用于承载两种连接的 *http.Server,传 nil 时内部自行创建。 返回实际使用的两个 server,方便调用方在需要时关闭其上的活跃连接(如发布服务)。

注意:cmux 派生出的 listener 内部嵌入的是底层 root listener,对其调用 Close 实际会关闭 root, 因此 HTTP 与 HTTPS 必须使用各自的 *http.Server,不能共用——否则共用 server 的 Close 会把 root 一并关掉,导致 m.Serve 提前返回非关闭类错误。

func SessionsByType

func SessionsByType(typ string) (ret []*melody.Session)

func SetAssetText

func SetAssetText(asset, text string)

func SetBootDetails

func SetBootDetails(details string)

func SetBooted

func SetBooted()

func SetNetworkProxy

func SetNetworkProxy(proxyURL string)

func ShortPathForBootingDisplay

func ShortPathForBootingDisplay(p string) string

func SizeOfDirectory

func SizeOfDirectory(path string) (size int64, err error)

func SkillsDir

func SkillsDir() string

func Tesseract

func Tesseract(imgAbsPath string) (ret []map[string]any)

func TestEmbeddingModel

func TestEmbeddingModel(apiKey, apiBaseURL, model string, dimensions, timeout int) (matched bool, dims int, err error)

TestEmbeddingModel 测试嵌入模型可用性,发送极简文本并返回首个向量维度。 返回值:matched 表示是否连通成功,dimensions 为返回的向量维度(便于核对配置), err 为请求错误(鉴权失败、网络异常、模型不存在等,原样返回便于调用方展示原因)。

func TestModel

func TestModel(apiKey, apiBaseURL, model string, timeout int) (available []string, matched bool, err error)

TestModel 测试模型可用性。优先调用 ListModels(GET /v1/models)拉取可用模型清单, 校验 model 是否在其中;若该端点不可用(部分 OpenAI 兼容服务未实现),则回退到极简 Chat Completion。 返回值:available 为可用模型清单(仅 ListModels 成功时填充),matched 表示 model 是否可用, err 为请求错误(鉴权失败、网络异常、模型不存在等,原样返回便于调用方展示原因)。

func TestRerankModel

func TestRerankModel(apiKey, apiBaseURL, model string, timeout int) (matched bool, err error)

TestRerankModel 测试重排模型可用性,用极简 query+documents 发一次重排请求验证连通性与鉴权。 返回值:matched 表示是否连通成功,err 为请求错误(鉴权失败、网络异常、模型不存在等,原样返回便于调用方展示原因)。

func TimeFromID

func TimeFromID(id string) (ret string)

func ToFloat64

func ToFloat64(v any) (float64, bool)

ToFloat64 将常用数值/字符串类型转换为 float64。

func TrimSpaceInPath

func TrimSpaceInPath(p string) string

func TruncateLenFileName

func TruncateLenFileName(name string) (ret string)

func TruncateToolOutput

func TruncateToolOutput(text, sessionID string) string

func UTF82GBK

func UTF82GBK(src string) ([]byte, error)

UTF82GBK transform UTF8 rune into GBK byte array.

func UnescapeHTML

func UnescapeHTML(s string) (ret string)

func UnlockWorkspace

func UnlockWorkspace()

func WaitForTesseractInit

func WaitForTesseractInit()

func WaitForUILoaded

func WaitForUILoaded()
func WalkWithSymlinks(root string, fn fs.WalkDirFunc) error

func WebFetch

func WebFetch(rawURL, format string) (string, error)

func WebSearch

func WebSearch(query, exaApiKey string) (string, error)

func Weekday

func Weekday(date time.Time) int

Weekday returns the day of the week specified by date. Sunday=0, Monday=1, ..., Saturday=6.

func WeekdayCN

func WeekdayCN(date time.Time) string

WeekdayCN returns the day of the week specified by date. Sunday=日, Monday=一, ..., Saturday=六.

func WeekdayCN2

func WeekdayCN2(date time.Time) string

WeekdayCN2 returns the day of the week specified by date. Sunday=天, Monday=一, ..., Saturday=六.

func WriteFileByMmap

func WriteFileByMmap(filePath string, data []byte) (err error)

WriteFileByMmap 使用内存映射将 data 原地覆写到 filePath。

流程:OpenFile(O_RDWR|O_CREATE) → Truncate 到精确长度 → mmap.Map(RDWR) → copy 写入 → Flush → Unmap,全程持有 filelock 的进程内互斥锁,避免并发写冲突。

相比 filelock.WriteFile(临时文件 + rename + fsync),此路径在进程级 I/O 计数(IO Write Bytes)上几乎不计——copy 是纯内存写,不经过 I/O 子系统, 只有 Flush 会产生极少量计入。出错时由调用方回退到 filelock.WriteFile。

func WriteFilePaths

func WriteFilePaths(paths []string) error

当前仅在 Windows、macOS 上实现,其他平台返回错误

func WriteWorkspacePaths

func WriteWorkspacePaths(workspacePaths []string) (err error)

Types

type Argon2Params

type Argon2Params struct {
	Memory      uint32 `json:"memory"`      // 单次派生占用的内存,单位 KB
	Iterations  uint32 `json:"iterations"`  // 遍历内存的次数
	Parallelism uint8  `json:"parallelism"` // 并行线程数
	KeyLength   uint32 `json:"keyLength"`   // 输出密钥长度,单位字节
}

Argon2Params 是 Argon2id 密钥派生函数的参数。参数本身不是秘密,会随配置落盘,以便跨平台一致地派生密钥。 默认值遵循 OWASP 2023 推荐(64 MB 内存 / 3 次迭代 / 4 线程 / 32 字节输出)。

func DefaultArgon2Params

func DefaultArgon2Params() Argon2Params

DefaultArgon2Params 返回 OWASP 2023 推荐的 Argon2id 参数。

func ValidateArgon2Params

func ValidateArgon2Params(p Argon2Params) (Argon2Params, error)

ValidateArgon2Params 校验 Argon2id 参数是否在合理范围内。 KeyLength 为 0 时视为旧配置,返回默认值;非零但不合法的参数返回错误。 防止恶意备份设置极大内存导致 OOM,或过弱参数降低安全性。

type BlockStatResult

type BlockStatResult struct {
	RuneCount  int `json:"runeCount"`
	WordCount  int `json:"wordCount"`
	LinkCount  int `json:"linkCount"`
	ImageCount int `json:"imageCount"`
	RefCount   int `json:"refCount"`
	BlockCount int `json:"blockCount"`
}

type Font

type Font struct {
	Family      string `json:"family"`      // 对应 CSS font-family
	Weight      int    `json:"weight"`      // 对应 CSS font-weight
	DisplayName string `json:"displayName"` // 给人看的名称 (Family + Subfamily)
}

func LoadSysFonts

func LoadSysFonts() []*Font

type InstallSkillResult

type InstallSkillResult struct {
	Names        []string `json:"names"`
	Descriptions []string `json:"descriptions"`
}

InstallSkillResult 记录一次安装落地的 skill 列表

func InstallSkill

func InstallSkill(rawURL string) (*InstallSkillResult, error)

InstallSkill 从 GitHub 仓库或直链下载并安装 skill 到 SkillsDir()。 支持的输入:owner/repo 简写、整条 "npx skills add owner/repo -g" 命令、 完整 GitHub 仓库/子目录/commit URL、raw SKILL.md 直链、release zip 直链。

type JsonArgParseFunc

type JsonArgParseFunc func(arg map[string]any, ret *gulu.Result) bool

JsonArgParseFunc 为单次提取函数,用于 ParseJsonArgs 批量提取。

func BindJsonArg

func BindJsonArg[T any](key string, dest *T, required, rejectEmpty bool) JsonArgParseFunc

BindJsonArg 创建一个提取函数:从 arg 取 key 并写入 dest,供 ParseJsonArgs 使用。

type Markdown

type Markdown struct {
	InlineAsterisk      bool `json:"inlineAsterisk"`      // 是否启用行级 * 语法
	InlineUnderscore    bool `json:"inlineUnderscore"`    // 是否启用行级 _ 语法
	InlineSup           bool `json:"inlineSup"`           // 是否启用行级上标
	InlineSub           bool `json:"inlineSub"`           // 是否启用行级下标
	InlineTag           bool `json:"inlineTag"`           // 是否启用行级标签
	InlineMath          bool `json:"inlineMath"`          // 是否启用行级公式
	InlineStrikethrough bool `json:"inlineStrikethrough"` // 是否启用行级删除线
	InlineMark          bool `json:"inlineMark"`          // 是否启用行级标记
}

type Notifications

type Notifications struct {
	DocTreeMaxList       bool `json:"docTreeMaxList"`       // 文档面板展开上限提示,默认启用
	TagMaxList           bool `json:"tagMaxList"`           // 标签面板展开上限提示,默认启用
	WorkspaceNotSSD      bool `json:"workspaceNotSSD"`      // 工作空间未放置在固态硬盘警告,默认启用
	BrowserCompatibility bool `json:"browserCompatibility"` // 浏览器兼容性提示,默认启用
}

Notifications 外观通知开关配置。https://github.com/siyuan-note/siyuan/issues/17797 Appearance.Notifications 为 nil 时表示旧配置尚未迁移,整体按默认启用处理。

var NotificationsCfg *Notifications

func NewNotifications

func NewNotifications() *Notifications

NewNotifications 创建默认全部启用的通知配置。新增内置通知时在此统一调整默认值,避免多处分散。

type Optional

type Optional[T any] struct {
	Value  T
	Exists bool
	IsNull bool
}

Optional is a generic type that represents an optional value, which can be in one of three states:

  • not set (Exists=false)
  • set to a non-null value (Exists=true, IsNull=false)
  • explicitly set to null (Exists=true, IsNull=true).

This allows distinguishing between "not provided" and "explicitly null" when unmarshaling JSON.

func (Optional[T]) HasValue

func (o Optional[T]) HasValue() bool

func (Optional[T]) IsNullValue

func (o Optional[T]) IsNullValue() bool

func (Optional[T]) IsZero

func (o Optional[T]) IsZero() bool

func (Optional[T]) MarshalJSON

func (o Optional[T]) MarshalJSON() ([]byte, error)

func (*Optional[T]) UnmarshalJSON

func (o *Optional[T]) UnmarshalJSON(data []byte) error

type PushMode

type PushMode int
const (
	PushModeBroadcast                   PushMode = 0 // 所有应用所有会话广播
	PushModeSingleSelf                  PushMode = 1 // 自我应用会话单播
	PushModeBroadcastExcludeSelf        PushMode = 2 // 非自我会话广播
	PushModeBroadcastExcludeSelfApp     PushMode = 4 // 非自我应用所有会话广播
	PushModeBroadcastApp                PushMode = 5 // 单个应用内所有会话广播
	PushModeBroadcastMainExcludeSelfApp PushMode = 6 // 非自我应用主会话广播
)

type Result

type Result struct {
	Cmd       string         `json:"cmd"`
	ReqId     float64        `json:"reqId"`
	AppId     string         `json:"app"`
	SessionId string         `json:"sid"`
	PushMode  PushMode       `json:"pushMode"`
	Callback  any            `json:"callback"`
	Code      int            `json:"code"`
	Msg       string         `json:"msg"`
	Data      any            `json:"data"`
	Context   map[string]any `json:"context,omitempty"`
}

func NewCmdResult

func NewCmdResult(cmdName string, cmdId float64, pushMode PushMode) *Result

func NewResult

func NewResult() *Result

func (*Result) Bytes

func (r *Result) Bytes() []byte

type SessionData

type SessionData struct {
	Workspaces map[string]*WorkspaceSession // <WorkspacePath, WorkspaceSession>
}

SessionData represents the session.

func GetSession

func GetSession(c *gin.Context) *SessionData

GetSession returns session of the specified context.

func (*SessionData) Clear

func (sd *SessionData) Clear(c *gin.Context)

func (*SessionData) Save

func (sd *SessionData) Save(c *gin.Context) error

Save saves the current session of the specified context.

type SkillInfo

type SkillInfo struct {
	Name        string `json:"name"`
	Description string `json:"description"`
}

func DiscoverSkills

func DiscoverSkills() []SkillInfo

type StatusBar

type StatusBar struct {
	MsgTaskDatabaseIndexCommitDisabled        bool `json:"msgTaskDatabaseIndexCommitDisabled"`
	MsgTaskHistoryDatabaseIndexCommitDisabled bool `json:"msgTaskHistoryDatabaseIndexCommitDisabled"`
	MsgTaskAssetDatabaseIndexCommitDisabled   bool `json:"msgTaskAssetDatabaseIndexCommitDisabled"`
	MsgTaskHistoryGenerateFileDisabled        bool `json:"msgTaskHistoryGenerateFileDisabled"`
}

StatusBar 底部状态栏配置。https://github.com/siyuan-note/siyuan/issues/16236

var StatusBarCfg *StatusBar

type WorkspaceSession

type WorkspaceSession struct {
	AccessAuthCode string
	Captcha        string
}

func GetWorkspaceSession

func GetWorkspaceSession(session *SessionData) (ret *WorkspaceSession)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL