model

package
v0.0.0-...-c1ba7d0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: AGPL-3.0 Imports: 160 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TxtAssetContentMaxSize = 1024 * 1024 * 4
	PDFAssetContentMaxPage = 1024
)
View Source
const (
	CreateAttributeViewItemDocsSaveModeSubDoc   = "subDoc"
	CreateAttributeViewItemDocsSaveModeTemplate = "template"
)
View Source
const (
	XAuthTokenKey = "X-Auth-Token"

	SessionIdCookieName = "publish-visitor-session-id"

	ClaimsContextKey = "claims"

	ClaimsKeyRole string = "role"
)
View Source
const (
	BacklinkDailyNoteAll     = "all"
	BacklinkDailyNoteOnly    = "only"
	BacklinkDailyNoteExclude = "exclude"
)
View Source
const (
	// REF: https://developers.google.com/calendar/caldav/v2/guide
	CalDavPrefixPath          = "/caldav"
	CalDavPrincipalsPath      = CalDavPrefixPath + "/principals"       // 0 resourceTypeRoot
	CalDavUserPrincipalPath   = CalDavPrincipalsPath + "/main"         // 1 resourceTypeUserPrincipal
	CalDavHomeSetPath         = CalDavUserPrincipalPath + "/calendars" // 2 resourceTypeCalendarHomeSet
	CalDavDefaultCalendarPath = CalDavHomeSetPath + "/default"         // 3 resourceTypeCalendar

	CalDavDefaultCalendarName = "default"

	CalDavCalendarsMetaDataFilePath   = CalDavHomeSetPath + "/calendars.json"
	CalDavCalendarsPropertiesFilePath = CalDavHomeSetPath + "/properties.json"

	ICalendarFileExt = "." + ical.Extension // .ics
)
View Source
const (
	// REF: https://developers.google.com/people/carddav#resources
	CardDavPrefixPath        = "/carddav"
	CardDavPrincipalsPath    = CardDavPrefixPath + "/principals"      // 0 resourceTypeRoot
	CardDavUserPrincipalPath = CardDavPrincipalsPath + "/main"        // 1 resourceTypeUserPrincipal
	CardDavHomeSetPath       = CardDavUserPrincipalPath + "/contacts" // 2 resourceTypeAddressBookHomeSet

	CardDavDefaultAddressBookPath = CardDavHomeSetPath + "/default" // 3 resourceTypeAddressBook
	CardDavDefaultAddressBookName = "default"

	CardDavAddressBooksMetaDataFilePath   = CardDavHomeSetPath + "/address-books.json"
	CardDavAddressBooksPropertiesFilePath = CardDavHomeSetPath + "/properties.json"

	VCardFileExt = "." + vcard.Extension // .vcf
)
View Source
const (
	MaskedUserData       = ""
	MaskedAccessAuthCode = "*******"
)
View Source
const (
	MergeDocHeadingModeFlat         = "flat"
	MergeDocHeadingModeTree         = "tree"
	MergeContentHeadingModePreserve = "preserve"
	MergeContentHeadingModeDemote   = "demote"
)
View Source
const (
	DailyNoteAttrPrefix = "custom-dailynote-"
	NodeAttrTitleEmpty  = treenode.DocumentTitleEmptyAttr
	DocHiddenAttr       = "custom-hidden"
)
View Source
const (
	HistoryOpClean   = "clean"
	HistoryOpUpdate  = "update"
	HistoryOpDelete  = "delete"
	HistoryOpFormat  = "format"
	HistoryOpSync    = "sync"
	HistoryOpReplace = "replace"
	HistoryOpOutline = "outline"
)
View Source
const (
	HistoryTypeDocName  = 0 // Search docs by doc name
	HistoryTypeDoc      = 1 // Search docs by doc name and content
	HistoryTypeAsset    = 2 // Search assets
	HistoryTypeDocID    = 3 // Search docs by doc id
	HistoryTypeDatabase = 4 // Search databases by database id
)
View Source
const (
	ObsidianTaskStateQueued       = "queued"
	ObsidianTaskStateAnalyzing    = "analyzing"
	ObsidianTaskStateReady        = "ready"
	ObsidianTaskStateRevalidating = "revalidating"
	ObsidianTaskStateStaging      = "staging"
	ObsidianTaskStateCreating     = "creating"
	ObsidianTaskStateWriting      = "writing"
	ObsidianTaskStateIndexing     = "indexing"
	ObsidianTaskStateCompleted    = "completed"
	ObsidianTaskStateFailed       = "failed"
	ObsidianTaskStateCancelled    = "cancelled"
)
View Source
const (
	DataChangeReasonSync      = "sync"
	DataChangeReasonOverwrite = "overwrite"
)
View Source
const (
	// SyncProbeOK 表示写入与列举指向同一个对象键
	SyncProbeOK = "ok"
	// SyncProbeConfig 表示可以确定的配置错误
	SyncProbeConfig = "config"
	// SyncProbeNetwork 表示网络或服务端不可达,无法判定配置
	SyncProbeNetwork = "network"
)
View Source
const (
	TxErrCodeBlockNotFound   = 0
	TxErrCodeDataIsSyncing   = 1
	TxErrCodeWriteTree       = 2
	TxErrHandleAttributeView = 3
	TxErrCodePushMsg         = 4
	TxErrCodeSkipTx          = 5 // 操作被跳过,不弹状态异常
	TxErrCodeReloadUI        = 6 // 事务已回滚,重新加载界面以恢复前后端一致状态
)
View Source
const DocSortModeAttr = "custom-sy-subdoc-sort-mode"
View Source
const GlobalBacklinkPageSize = 50
View Source
const (
	InlineStylesVersion = 2
)
View Source
const (
	NodeAttrRiffDecks = "custom-riff-decks"
)
View Source
const PdfOutlineScheme = "pdf-outline"
View Source
const (
	RoleContextKey = "role"
)

Variables

View Source
var (
	ErrLocalBazaarPackageExists       = errors.New("marketplace package already exists")
	ErrLocalBazaarPackageIncompatible = errors.New("marketplace package is incompatible")
)
View Source
var (
	ErrBootAppearanceNotFound       = errors.New("boot appearance not found")
	ErrBootAppearanceAssetForbidden = errors.New("boot appearance asset forbidden")
)
View Source
var (
	ErrorCalDavCalendarNotFound    = errors.New("CalDAV: calendar not found")
	ErrorCalDavCalendarPathInvalid = errors.New("CalDAV: calendar path is invalid")
	ErrorCalDavCalendarExists      = errors.New("CalDAV: calendar already exists")

	ErrorCalDavCalendarObjectNotFound    = errors.New("CalDAV: calendar object not found")
	ErrorCalDavCalendarObjectPathInvalid = errors.New("CalDAV: calendar object path is invalid")
)
View Source
var (
	ErrorCardDavPathInvalid = errors.New("CardDAV: path is invalid")

	ErrorCardDavBookNotFound    = errors.New("CardDAV: address book not found")
	ErrorCardDavBookPathInvalid = errors.New("CardDAV: address book path is invalid")

	ErrorCardDavAddressNotFound                 = errors.New("CardDAV: address not found")
	ErrorCardDavAddressFileExtensionNameInvalid = errors.New("CardDAV: address file extension name is invalid")
	ErrorCardDavBookExists                      = errors.New("CardDAV: address book already exists")
)
View Source
var (
	// ErrEncryptedBoxNotUnlocked 表示加密笔记本当前未解锁。
	ErrEncryptedBoxNotUnlocked = errors.New("encrypted notebook is not unlocked")
	// ErrEncryptedBoxOperationScopeClosed 表示响应级操作作用域已经关闭。
	ErrEncryptedBoxOperationScopeClosed = errors.New("encrypted notebook operation scope is closed")
)
View Source
var (
	ErrNotebookArchiveInvalid        = errors.New("invalid encrypted notebook archive")
	ErrNotebookArchiveChanged        = errors.New("encrypted notebook archive sources changed")
	ErrNotebookArchiveBusy           = errors.New("encrypted notebook archive operation is busy")
	ErrNotebookArchiveConfigured     = errors.New("encrypted notebook recovery requires an unconfigured workspace")
	ErrNotebookArchiveAuthentication = errors.New("encrypted notebook archive authentication failed")
)
View Source
var (
	OnKernelPluginStart  func(petal *Petal) // Called when a plugin is enabled (after loading and starting the plugin)
	OnKernelPluginStop   func(petal *Petal) // Called when a plugin is disabled (before stopping and unloading the plugin)
	OnKernelPluginsStart func()             // Called to start all valid plugins
	OnKernelPluginsStop  func()             // Called to stopping all valid plugins
)
View Source
var (
	ErrPluginPublishDenied  = errors.New("plugin publish access denied")
	ErrPluginPublishMissing = errors.New("plugin publish data has not been generated")
	ErrPluginPublishInvalid = errors.New("invalid plugin publish declaration or data")
)
View Source
var (
	BasicAuthHeaderKey   = "WWW-Authenticate"
	BasicAuthHeaderValue = "Basic realm=\"SiYuan Authorization Require\", charset=\"UTF-8\""
)
View Source
var (
	ErrBoxNotFound   = errors.New("notebook not found")
	ErrBoxClosed     = errors.New("notebook closed")
	ErrBlockNotFound = errors.New("block not found")
	ErrTreeNotFound  = errors.New("tree not found")
	ErrIndexing      = errors.New("indexing")
	ErrBoxUnindexed  = errors.New("notebook unindexed")
	ErrInvalidID     = errors.New("invalid id")
)
View Source
var AIMemoryConversationReadScope func(context.Context) context.Context

AIMemoryConversationReadScope 由会话模块注册,同轮复核共享只读会话快照。

View Source
var AIMemoryConversationReader func(context.Context, string, string) (string, error)

AIMemoryConversationReader 由会话模块注册,只返回成功提交的用户原话及原始身份。

View Source
var AttributeViewKeyNumberFormats = []string{"", "commas", "percent", "USD", "CNY", "EUR", "GBP", "JPY", "RUB", "INR", "KRW", "TRY", "CAD", "CHF", "THB", "AUD", "HKD", "TWD", "MOP", "SGD", "NZD", "ILS", "SKK"}
View Source
var AttributeViewKeyRollupOperators = []string{"", "Unique values", "Count all", "Count values", "Count unique values", "Count empty", "Count not empty", "Percent empty", "Percent not empty", "Percent unique values", "Sum", "Average", "Median", "Min", "Max", "Range", "Earliest", "Latest", "Checked", "Unchecked", "Percent checked", "Percent unchecked"}
View Source
var BazaarPetalStateRevision atomic.Uint64
View Source
var (
	BootSyncSucc atomic.Int32 // -1:未执行,0:执行成功,1:执行失败
)
View Source
var ConfSettingRevision atomic.Uint64
View Source
var CurrentConfVersion = confMigrations[len(confMigrations)-1].version

CurrentConfVersion 是本内核支持的最高配置版本。

View Source
var (
	Decks = map[string]*riff.Deck{}
)
View Source
var ErrAIMemorySourceMissing = errors.New("memory source no longer exists")

ErrAIMemorySourceMissing 仅表示已确认删除的来源,读取故障必须保留原始错误。

View Source
var ErrAutomaticHTTPObsolete = errors.New("automatic HTTP execution is obsolete")
View Source
var ErrBazaarPackagePending = errors.New("bazaar package information has not synced yet")

ErrBazaarPackagePending 表示云端尚未同步包信息。

View Source
var ErrBazaarRatingRateLimited = errors.New("bazaar rating rate limited")

ErrBazaarRatingRateLimited 表示评分请求受到云端频率限制。

View Source
var ErrDocumentTitleConflict = errors.New("document title revision conflict")
View Source
var ErrFailedToConnectCloudServer = errors.New("failed to connect cloud server")
View Source
var (
	ErrInvalidPublishServiceToken = errors.New("invalid publish service token")
)
View Source
var ErrManualAutomationExpired = errors.New("manual automation progress is unavailable")
View Source
var ErrSYTargetNotebookRequired = errors.New("target notebook required")
View Source
var ErrSnippetConflict = errors.New("snippet revision conflict")
View Source
var GlobalUndoLog = newUndoLog(64)

GlobalUndoLog 全局撤销日志单例。内存态,重启清空。

View Source
var KernelID = gulu.Rand.String(7)
View Source
var LivePhotoPreviews = livephoto.NewManager(func() string {
	return filepath.Join(util.TempDir, "assets-cache", "livephoto")
})
View Source
var (
	PDFAssetContentMaxSize uint64 = 1024 * 1024 * 128
)
View Source
var TemplateHTTPSourceRevoked func(sourceIDs []string)

TemplateHTTPSourceRevoked 在许可锁外通知执行管理器,避免锁顺序反转。

Functions

func AIMemoryCandidatesJob

func AIMemoryCandidatesJob()

AIMemoryCandidatesJob 在统一定时任务中执行,无需额外模型调用,桌面与移动端共用。

func AIOCRAsset

func AIOCRAsset(ctx context.Context, path string) (string, error)

AIOCRAsset 使用所选 OCR AI 模型单次识别,未配置独立模型时兼容智能体模型。

func AcquireEncryptedBoxOperation

func AcquireEncryptedBoxOperation(boxID string) error

AcquireEncryptedBoxOperation 为需要把明文结果保留到响应结束的操作取得准入租约。

func AcquireEncryptedBoxOperations

func AcquireEncryptedBoxOperations(ctx context.Context, boxIDs []string) (release func(), err error)

AcquireEncryptedBoxOperations 按固定顺序取得多个笔记本的响应级租约。

func AcquireMCPToolWrite

func AcquireMCPToolWrite() (release func(), err error)

AcquireMCPToolWrite 在工具实际执行及结果转换期间保护工作空间,不覆盖空闲传输等待。

func AcquirePluginRPCWrite

func AcquirePluginRPCWrite() (release func(), err error)

AcquirePluginRPCWrite 为实际 RPC 方法(含异步通知)取得工作空间写入准入租约。 在插件事件循环上只尝试加锁,不等待导入提交,避免阻塞事件循环中的其他回调。 调用者必须在方法真正结束后释放;HTTP 等待者取消不能提前释放仍在执行的方法。

func Activity

func Activity(c *gin.Context)

Activity 记录用户写操作时间,用于 AutoFixIndex 的空闲判断。 只认会产生数据变更的事务类请求(/api/transactions*),因为只有写操作才会引入索引不一致; 读操作和前端定时轮询(如 /api/ai/embeddingStat)不计入,避免 SiYuan 开着却不操作时被判为活跃。

func AddAttributeViewBlock

func AddAttributeViewBlock(tx *Transaction, srcs []map[string]any, avID, dbBlockID, viewID, groupID, previousItemID string, ignoreDefaultFill bool) (err error)

func AddAttributeViewKey

func AddAttributeViewKey(avID, blockID, keyID, keyName, keyType, keyIcon, previousKeyID string, dateFormat av.DateDisplayFormat) (err error)

func AddAttributeViewView

func AddAttributeViewView(avID, blockID, name string, layout av.LayoutType) (string, error)

AddAttributeViewView 通过现有事务创建视图并同步数据库块的显示状态。

func AddCustomEmoji

func AddCustomEmoji(emojiName, imgSrc string)

func AddLANSyncPeer

func AddLANSyncPeer(instance, address string, port int, txt map[string]string) bool

func AddMicrosoftDefenderExclusion

func AddMicrosoftDefenderExclusion() error

func AddSession

func AddSession(username, credentialVersion string) string

AddSession 为指定账户注册发布服务会话并返回实际生效的会话 ID;账户凭据已变更时返回空字符串。 同一用户已有有效会话时复用其 ID,避免重复认证导致会话无限增长 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-f4vj-ppp2-5hg4; 同时按空闲时长清理过期会话,并在超出全局或单账户上限时淘汰最久未活跃的会话。

func AddVirtualBlockRefExclude

func AddVirtualBlockRefExclude(keyword []string)

func AddVirtualBlockRefInclude

func AddVirtualBlockRefInclude(keyword []string)

func AddressBooksMetaDataFilePath

func AddressBooksMetaDataFilePath() string

AddressBooksMetaDataFilePath returns the absolute path of the address books metadata file

func AddressBooksPropertiesFilePath

func AddressBooksPropertiesFilePath() string

AddressBooksPropertiesFilePath 返回通讯录死属性文件的绝对路径。

func AgentMessageImageAssets

func AgentMessageImageAssets(markdown string) []string

AgentMessageImageAssets 返回智能体用户消息中引用的全局资源图片。

func AppendAttributeViewDetachedBlocksWithValues

func AppendAttributeViewDetachedBlocksWithValues(avID string, blocksValues [][]*av.Value) (err error)

func AppendHeadingChildren

func AppendHeadingChildren(id, childrenDOM string)

func AppendPushCreateEntry

func AppendPushCreateEntry(box, p string)

func AppendPushReloadAttrViewEntry

func AppendPushReloadAttrViewEntry(avID string)

func AppendPushReloadDocInfoEntry

func AppendPushReloadDocInfoEntry(box, p string)

func AppendPushReloadFiletreeEntry

func AppendPushReloadFiletreeEntry()

func AppendPushReloadProtyleEntry

func AppendPushReloadProtyleEntry(id string)

func AppendPushReloadTagEntry

func AppendPushReloadTagEntry()

func AppendPushReloadUIEntry

func AppendPushReloadUIEntry()

func AppendPushRemoveEntry

func AppendPushRemoveEntry(box, p, id string)

func AppendPushRenameEntry

func AppendPushRenameEntry(box, p, title string)

func ApplyConfRuntime

func ApplyConfRuntime()

ApplyConfRuntime 供设置接口在替换配置段后重新投影派生运行时状态。

func ApplyImportedConfMigrations

func ApplyImportedConfMigrations(c *AppConf, raw []byte)

ApplyImportedConfMigrations 对导入的配置执行与启动加载相同的迁移。

func ApplyResetSettings

func ApplyResetSettings(previousSearch *conf.Search)

ApplyResetSettings 更新运行时依赖,索引按现有队列重建,不修改笔记本密钥或历史保留策略。

func ApplySearchRuntime

func ApplySearchRuntime()

ApplySearchRuntime 将搜索配置投影到数据库层。数据库打开前设置的 PRAGMA 不会生效, 因此各入口在打开数据库后需要再调用一次。

func AssetPathFromDataRelativePath

func AssetPathFromDataRelativePath(relPath string) (assetPath, boxID string, ok bool)

AssetPathFromDataRelativePath 从 data 相对路径提取文档中使用的资源路径和笔记本 ID。

func AssetPathWithoutQuery

func AssetPathWithoutQuery(relativePath string) string

AssetPathWithoutQuery 返回去掉查询参数后的资源路径,用于复制到导出目录等磁盘路径场景。

func AttachTemplateDocTreePlans

func AttachTemplateDocTreePlans(transactions []*Transaction) (attached bool, err error)

AttachTemplateDocTreePlans 将一次性计划转换为内核事务操作,父文档内容与全部子文档共用一条撤销记录。

func AttributeViewViewConfigRevision

func AttributeViewViewConfigRevision(view *av.View) string

AttributeViewViewConfigRevision 标识视图配置版本,供智能体在整组更新前检查配置是否变化。

func AttributeViewViewFieldIDs

func AttributeViewViewFieldIDs(view *av.View) (ret []string)

AttributeViewViewFieldIDs 按布局顺序返回字段 ID,包含隐藏字段。

func AutoCheckMicrosoftDefenderJob

func AutoCheckMicrosoftDefenderJob()

func AutoConsumeShorthandsJob

func AutoConsumeShorthandsJob()

func AutoFixIndex

func AutoFixIndex()

AutoFixIndex 在用户空闲且存在未订正变更时,自动订正索引。由 cron 每分钟调用。 触发需同时满足:空闲达 idleFixThreshold、存在未订正变更(dirty)、冷却期已过。

func AutoGenerateFileHistory

func AutoGenerateFileHistory()

func AutoLockIdleEncryptedBoxesJob

func AutoLockIdleEncryptedBoxesJob()

AutoLockIdleEncryptedBoxesJob 检查所有已解锁的加密 notebook,将闲置超时的自动锁定。 由 cron 每分钟调用。阈值由 NotebookCrypto.AutoLockMinutes 控制(0 = 禁用)。

func AutoPurgeRepoJob

func AutoPurgeRepoJob()

AutoPurgeRepoJob 自动清理数据仓库 https://github.com/siyuan-note/siyuan/issues/13091

func AutoSpace

func AutoSpace(rootID string) (err error)

func BatchReplaceAttributeViewBlocks

func BatchReplaceAttributeViewBlocks(avID string, isDetached bool, oldNew []map[string]string) (err error)

func BatchSetBlockAttrs

func BatchSetBlockAttrs(blockAttrs []map[string]any) (err error)

func BatchUpdatePackagesContext

func BatchUpdatePackagesContext(ctx context.Context, frontend string) error

BatchUpdatePackagesContext 取消时保留已提交的包,并停止当前下载和后续更新。

func BatchUpdateRecentDocCloseTime

func BatchUpdateRecentDocCloseTime(rootIDs []string) (err error)

BatchUpdateRecentDocCloseTime 批量更新文档关闭时间

func BindDesktopSession

func BindDesktopSession(c *gin.Context, workspaceSession *util.WorkspaceSession, rememberMe bool)

BindDesktopSession 将未记住的本机桌面登录绑定到本次内核启动;窗口隐藏及退出取消不改变绑定。

func BookmarkLabels

func BookmarkLabels() (ret []string)

func BookmarkLabelsByPublishAccess

func BookmarkLabelsByPublishAccess(c *gin.Context, publishAccess PublishAccess) (ret []string)

func BootSyncData

func BootSyncData()

func BoxDocSubFileCount

func BoxDocSubFileCount(boxID string) int

BoxDocSubFileCount 返回笔记本顶层文档的可见下级文档数。

func BoxDocSubFileCountForPublish

func BoxDocSubFileCountForPublish(boxID string, publishAccess PublishAccess) int

BoxDocSubFileCountForPublish 返回发布访问控制下笔记本顶层文档的可见下级文档数。

func BoxDocSubFileCountForPublishAt

func BoxDocSubFileCountForPublishAt(boxID, docPath string, publishAccess PublishAccess) int

BoxDocSubFileCountForPublishAt 返回发布访问控制下指定文档的可见直接子文档数,docPath 为该文档的 .sy 路径。

func BuildAIEditorPrompt

func BuildAIEditorPrompt(input, action string) string

BuildAIEditorPrompt 将编辑器输入填充到操作模板中。没有占位符时保持现有的操作前缀格式。

func BuildAIMemoryContext

func BuildAIMemoryContext(ctx context.Context, task string, sourceIDs []string, budget int) (string, error)

BuildAIMemoryContext 只返回当前范围内有效数据,不把记忆升级为系统命令或工具授权。

func BuildGraph

func BuildGraph(query string) (boxID string, nodes []*GraphNode, links []*GraphLink)

func BuildTreeGraph

func BuildTreeGraph(id, query string) (boxID string, nodes []*GraphNode, links []*GraphLink)

func CacheVirtualBlockRefJob

func CacheVirtualBlockRefJob()

func CalendarsMetaDataFilePath

func CalendarsMetaDataFilePath() string

CalendarsMetaDataFilePath returns the absolute path of the calendars' meta data file

func CalendarsPropertiesFilePath

func CalendarsPropertiesFilePath() string

CalendarsPropertiesFilePath 返回日历死属性文件的绝对路径。

func CancelAIMemory

func CancelAIMemory(id string) error

func CancelDataImport

func CancelDataImport(id string) error

func CancelSyncCheckout

func CancelSyncCheckout(taskID string) bool

CancelSyncCheckout 只接受当前任务 ID,防止旧窗口取消后续同步;返回值表示已提出取消请求。

func CancelTemplateHTTP

func CancelTemplateHTTP(id, app, sessionID string)

func ChangeAttrViewLayout

func ChangeAttrViewLayout(blockID, avID string, newLayout av.LayoutType) (err error)

func ChangeAttrViewLayoutForView

func ChangeAttrViewLayoutForView(blockID, avID, viewID, revision string, newLayout av.LayoutType) (err error)

ChangeAttrViewLayoutForView 精确修改指定视图的布局,并同步显示该视图的镜像数据库块。

func ChangeBoxSort

func ChangeBoxSort(boxIDs []string)

func ChangeFileTreeSort

func ChangeFileTreeSort(boxID string, paths []string)

func ChangeHistoryTick

func ChangeHistoryTick(minutes int)

func ChangeMasterPassword

func ChangeMasterPassword(oldPassword, newPassword string) error

ChangeMasterPassword 改主密码:用旧密码校验后,用新密码派生新 KEK, 重新加密 verifier,并把所有加密笔记本的 WrappedDEK 用新 KEK 重新包络后写回各自的 BoxConf。

使用两阶段提交确保崩溃后可恢复:

Phase 0: 预计算所有新 WrappedDEK(内存)
Phase 1: 写入 migration manifest
Phase 2: 切换全局 verifier
Phase 3: 写入各 box conf + backup
Phase 4: 持久化全局备份和配置,清除 manifest

注意:必须在所有加密笔记本都已 Unmount 的状态下调用(DEK 不在内存),否则新旧 KEK 切换会让缓存与磁盘不一致。

func ChatGPT

func ChatGPT(msg string) (ret string)

func ChatGPTWithAction

func ChatGPTWithAction(ids []string, action string) (ret string)

func CheckAbsPathAccessableByPublishAccess

func CheckAbsPathAccessableByPublishAccess(c *gin.Context, absPath string, publishAccess PublishAccess) bool

func CheckActivationcode

func CheckActivationcode(code string) (retCode int, msg string)

func CheckAdminRole

func CheckAdminRole(c *gin.Context)

func CheckAttributeViewAccessableByPublishAccess

func CheckAttributeViewAccessableByPublishAccess(c *gin.Context, publishAccess PublishAccess, avID string) bool

func CheckAttributeViewBlockAccessableByPublishAccess

func CheckAttributeViewBlockAccessableByPublishAccess(c *gin.Context, publishAccess PublishAccess, avID, blockID string) bool

func CheckAuth

func CheckAuth(c *gin.Context)

func CheckBlockIdAccessableByPublishAccess

func CheckBlockIdAccessableByPublishAccess(c *gin.Context, publishAccess PublishAccess, blockID string) bool

func CheckBlockIdAccessableByPublishAccessInBox

func CheckBlockIdAccessableByPublishAccessInBox(c *gin.Context, publishAccess PublishAccess, blockID, boxID string) bool

func CheckBlockIdMetadataAccessableByPublishAccess

func CheckBlockIdMetadataAccessableByPublishAccess(c *gin.Context, publishAccess PublishAccess, blockID string) bool

func CheckBlockIdMetadataAccessableByPublishAccessInBox

func CheckBlockIdMetadataAccessableByPublishAccessInBox(c *gin.Context, publishAccess PublishAccess, blockID, boxID string) bool

func CheckBlockRefInBox

func CheckBlockRefInBox(ids, exactIDs, deletedIDs []string, boxID string) (ret bool, err error)

CheckBlockRefInBox 检查受影响块的引用,并检查实际删除块的数据库绑定。

func CheckBlockTreeDiscoverableByPublishAccess

func CheckBlockTreeDiscoverableByPublishAccess(publishAccess PublishAccess, bt *treenode.BlockTree) bool

func CheckBlockTreeMetadataAccessableByPublishAccess

func CheckBlockTreeMetadataAccessableByPublishAccess(c *gin.Context, publishAccess PublishAccess, bt *treenode.BlockTree) bool

func CheckDocsRef

func CheckDocsRef(paths []string) (ret bool, err error)

CheckDocsRef 检查文档删除时会递归移除的全部文档。

func CheckDocumentAddressingFileCopies

func CheckDocumentAddressingFileCopies(sources, destinations []string) error

CheckDocumentAddressingFileCopies 预检全部目标内容,拒绝不兼容批次时不复制任何文件。 sources 与 destinations 一一对应;目录内的文件使用复制后的相对位置检查。

func CheckDocumentAddressingFileRemoval

func CheckDocumentAddressingFileRemoval(absPath string) error

CheckDocumentAddressingFileRemoval 校验整本删除:逐条检查树内文档寻址记录,无记录时校验该路径本身。

func CheckDocumentAddressingFileWrite

func CheckDocumentAddressingFileWrite(absPath string, data []byte, directory bool) error

CheckDocumentAddressingFileWrite 在创建目录、覆盖配置或调整时间之前检查待写内容。

func CheckDocumentAddressingPath

func CheckDocumentAddressingPath(absPath string) error

CheckDocumentAddressingPath 在原始文件访问和修复前检查所属笔记本,也检查父目录覆盖的笔记本。

func CheckEmojiAccessableByPublishAccess

func CheckEmojiAccessableByPublishAccess(c *gin.Context, relativePath string, publishAccess PublishAccess) bool

func CheckMCPAuth

func CheckMCPAuth(c *gin.Context)

CheckMCPAuth 仅在 MCP 入口接受 OAuth 凭证,保留 API Token、会话和角色校验。

func CheckNotebookRef

func CheckNotebookRef(boxID string) (ret bool, err error)

CheckNotebookRef 检查笔记本当前索引中的全部文档。

func CheckPathAccessableByPublishIgnore

func CheckPathAccessableByPublishIgnore(box string, path string, publishIgnore PublishAccess) bool

func CheckPluginAccessableInPublish

func CheckPluginAccessableInPublish(name string) bool

func CheckPublishAuthCookie

func CheckPublishAuthCookie(c *gin.Context, ID string, password string) bool

func CheckReadonly

func CheckReadonly(c *gin.Context)

func CheckRepoSnapshot

func CheckRepoSnapshot() (changed bool, err error)

func CheckSnippetAccessableInPublish

func CheckSnippetAccessableInPublish(name, typ string) (found, accessable bool)

func CheckTemplateHTTPSource

func CheckTemplateHTTPSource(source *TemplateHTTPSource) (bool, error)

func CheckUpdate

func CheckUpdate(showMsg bool)

func CheckWidgetAccessableByPublishAccess

func CheckWidgetAccessableByPublishAccess(c *gin.Context, name string, publishAccess PublishAccess) bool

func CheckWidgetAccessableInPublish

func CheckWidgetAccessableInPublish(name string) bool

func CheckoutRepo

func CheckoutRepo(id string)

func CheckoutRepoDirect

func CheckoutRepoDirect(id string) error

func ClaimAttributeViewHTTPAutomation

func ClaimAttributeViewHTTPAutomation(ctx context.Context, id, avID, blockID, app, session string) (*attributeViewHTTPAutomation, context.Context, func(), error)

func CleanupEmptyPluginStorageDirs

func CleanupEmptyPluginStorageDirs()

CleanupEmptyPluginStorageDirs 在插件加载前清理没有任何文件的插件存储目录。

func CleanupRetiredInstallResources

func CleanupRetiredInstallResources() error

CleanupRetiredInstallResources 删除升级后残留的已撤回安装资源,随启动阶段执行。 这些路径都由安装包管理、不存放用户数据,直接删除目录;目录缺失时忽略。

func CleanupRichClipboardBatch

func CleanupRichClipboardBatch(batch string, groups []string)

func ClearAIMemory

func ClearAIMemory(ctx context.Context) (apicontract.AIMemoryClearData, error)

ClearAIMemory 先关闭功能并使旧写入失效,再撤回正式记录;不调用模型、不改原笔记或对话。

func ClearCustomEmojis

func ClearCustomEmojis()

func ClearDEK

func ClearDEK(boxID string)

ClearDEK 清除指定笔记本的 DEK。Unmount 单个加密笔记本时调用。

func ClearGlobalBacklinkSnapshots

func ClearGlobalBacklinkSnapshots(boxID string)

func ClearOutdatedHistoryDirJob

func ClearOutdatedHistoryDirJob()

func ClearRecentDocs

func ClearRecentDocs() error

ClearRecentDocs 清空当前工作区的浏览、打开和关闭记录,后续访问继续记录。

func ClearRichClipboard

func ClearRichClipboard()

func ClearRichClipboardBox

func ClearRichClipboardBox(boxID string)

func ClearSyncProviderConfig

func ClearSyncProviderConfig(provider int) error

ClearSyncProviderConfig 清除指定第三方配置;当前来源必须完整,清除后关闭同步。

func ClearTempFiles

func ClearTempFiles()

func ClearWorkspaceHistory

func ClearWorkspaceHistory() (err error)

func Close

func Close(force, setCurrentWorkspace bool, execInstallPkg int) (exitCode int, installPkgPath string)

Close 完成退出清理,调用方处理退出结果后通过 ExitKernel 结束服务及进程。

force:是否不执行同步过程而直接退出

setCurrentWorkspace:是否将当前工作空间放到工作空间列表的最后一个

execInstallPkg:是否返回新版本安装包

0:默认按照设置项 System.DownloadInstallPkg 检查并推送提示
1:不返回新版本安装包
2:返回新版本安装包路径并退出,由桌面宿主执行安装

返回值 exitCode:

0:正常退出
1:同步执行失败
2:提示新安装包

当 force 为 true(强制退出)并且 execInstallPkg 为 0(默认检查更新)并且新版本安装包已经准备就绪时,将安装包路径返回给桌面宿主 https://github.com/siyuan-note/siyuan/issues/10288

func CloseWatchAssets

func CloseWatchAssets()

func CloseWatchEmojis

func CloseWatchEmojis()

func CloseWatchThemes

func CloseWatchThemes()

func CloseWithContext

func CloseWithContext(ctx context.Context, force, setCurrentWorkspace bool, execInstallPkg int) (int, string)

CloseWithContext 允许请求取消退出同步,数据清理仍等待仓库操作收尾后完整执行。

func CloudChatGPT

func CloudChatGPT(msg string, contextMsgs []string) (ret string, stop bool, err error)

func CommitDataImport

func CommitDataImport(id, mode, password string) (skipped []string, err error)

CommitDataImport 在预检全部通过后提交按路径覆盖;跳过的目录与密钥材料保持原样。

func CommitNotebookArchive

func CommitNotebookArchive(id string, saved bool) error

CommitNotebookArchive 将源目录移到归档旁的恢复目录,整个过程不调用会创建删除历史的普通删除接口。

func ConfNamespaceRevision

func ConfNamespaceRevision(namespace string) uint64

func ConfSectionPatchJSON

func ConfSectionPatchJSON(namespace string, patch []byte) ([]byte, error)

ConfSectionPatchJSON 返回合并后的配置段,调用方在发布前保留契约校验与专用领域动作。

func ConfirmSyncCheckout

func ConfirmSyncCheckout(taskID, token string, saved bool) bool

func ContextWithAIMemoryScope

func ContextWithAIMemoryScope(ctx context.Context, sourceIDs []string) context.Context

ContextWithAIMemoryScope 由业务入口提供已知任务范围,不由工具参数扩大权限。

func ControlConcurrency

func ControlConcurrency(c *gin.Context)

func CopyFileWithDocumentAddressing

func CopyFileWithDocumentAddressing(source, destination string) error

CopyFileWithDocumentAddressing 保留复制范围、权限和时间;文档使用已验证字节及受保护的目标写入。 调用方先检查整个请求批次,此处还会检查当前操作及实际读取的文档,拒绝检查后出现的不兼容源。

func CountSupportedFlashcards

func CountSupportedFlashcards(deck *riff.Deck) int

func CreateAssetHistory

func CreateAssetHistory(assetPath string) (err error)

CreateAssetHistory 为指定资源文件创建历史快照。

func CreateBox

func CreateBox(name string) (id string, err error)

func CreateCloudSyncDir

func CreateCloudSyncDir(name string) (err error)

func CreateDailyNote

func CreateDailyNote(boxID string) (p string, existed bool, err error)

func CreateDailyNoteAt

func CreateDailyNoteAt(boxID string, date time.Time) (p string, existed bool, err error)

CreateDailyNoteAt 按指定日期创建日记,复用日期属性指向的现有文档。

func CreateDailyNoteWithHTTP

func CreateDailyNoteWithHTTP(boxID string, date *time.Time, execution *templatehttp.Execution) (p string, existed bool, err error)

CreateDailyNoteWithHTTP 先提交日记身份,再在创建锁外执行需要确认的正文模板。

func CreateDailyNoteWithSelection

func CreateDailyNoteWithSelection(boxID string, date *time.Time, execution *templatehttp.Execution, selection *DocumentSelection) (p string, existed bool, err error)

CreateDailyNoteWithSelection 在原日记创建流程中验证选择,保留日期属性、复用与正文模板语义。

func CreateDeck

func CreateDeck(name string) (deck *riff.Deck, err error)

func CreateDocByMd

func CreateDocByMd(boxID, p, title, md string, sorts []string, arg map[string]any) (tree *parse.Tree, err error)

func CreateDocByMdSync

func CreateDocByMdSync(boxID, p, title, md string, sorts []string, arg map[string]any) (tree *parse.Tree, err error)

CreateDocByMdSync 同步创建 Markdown 文档并返回事务落盘错误,供成功后需要清理源数据的调用方使用。

func CreateDocByParent

func CreateDocByParent(request DocumentCreateRequest) (document *treenode.DocumentPath, err error)

CreateDocByParent 先排空已排队编辑,再锁定父身份;源提交前在公共写入范围内复核名称条件。 源一旦提交就不删除或换 ID 重试,排序、正文模板失败返回可恢复的已提交状态。

func CreateDocHistory

func CreateDocHistory(id string) (err error)

func CreateEncryptedBox

func CreateEncryptedBox(name, password string) (id string, err error)

CreateEncryptedBox 创建一个新的加密笔记本。可多次调用创建多个。 前置:加密功能已启用。创建时需要主密码(临时派生 KEK 用于 wrap DEK,用完即弃)。 创建后直接用生成的 DEK 打开加密 db 并缓存(已解锁状态),调用方随后调 openNotebook 即可挂载。

func CreatePluginJWT

func CreatePluginJWT(name string) (string, error)

CreatePluginJWT 为指定名称的内核插件创建一个 JWT,包含管理员权限。插件使用这个 JWT 调用内核 API。

func CreateRepoSnapshot

func CreateRepoSnapshot(memo string) (id string, created bool, err error)

func CreateRepoSnapshotWithFullCheck

func CreateRepoSnapshotWithFullCheck(memo string, fullCheck bool) (id string, created bool, err error)

CreateRepoSnapshotWithFullCheck 允许本次快照核对所有本地已落盘文件的内容。

func CreateTemplate

func CreateTemplate(name, content string, overwrite bool) (code int, err error)

CreateTemplate 在 <data>/templates/ 下创建模板文件。name 不含扩展名,content 为 markdown 文本。 overwrite=false 且文件已存在时返回 code=1(与 DocSaveAsTemplate 一致)。

func CreateWithMarkdown

func CreateWithMarkdown(tags, boxID, hPath, md, parentID, id string, withMath bool, clippingHref string, arg map[string]any) (retID string, err error)

func DAVPreconditionStatus

func DAVPreconditionStatus(exists bool, etag, ifMatch, ifNoneMatch string) int

DAVPreconditionStatus 按 RFC 9110 §13.1.1、§13.1.2 评估 If-Match 与 If-None-Match(不含 GET/HEAD 的 304 语义)。 etag 是资源当前的不透明实体标签(不含引号),集合等没有 ETag 的资源传空串; 条件满足返回 0,条件不满足返回 412,请求头格式错误返回 400。

func DataBlockDOM

func DataBlockDOM(data string, luteEngine *lute.Lute) (ret string, err error)

DataBlockDOM 将 Markdown 转换为块 DOM,并校验输入中显式指定的块 ID。

func DavPath2DirectoryPath

func DavPath2DirectoryPath(davPath string) string

DavPath2DirectoryPath converts CalDAV/CardDAV path to absolute path of the file system

func DeactivateUser

func DeactivateUser() (err error)

func DecryptAsset

func DecryptAsset(boxID, diskName string, dek, ciphertext []byte) ([]byte, error)

DecryptAsset 对应解密。

func DecryptAssetName

func DecryptAssetName(boxID, diskName string, dek, ciphertext []byte) (originalName string, err error)

DecryptAssetName 只解密资源的名称元数据,不处理资源内容。

func DecryptAssetNameFromReader

func DecryptAssetNameFromReader(boxID, diskName string, dek []byte, reader io.Reader) (originalName string, err error)

DecryptAssetNameFromReader 从资源头部解密名称元数据,不读取资源内容。

func DecryptAssetToWriter

func DecryptAssetToWriter(boxID, diskName string, dek []byte, reader io.Reader, writer io.Writer) (originalName string, err error)

DecryptAssetToWriter 分块解密资源到 writer,避免大资源同时驻留密文和明文。

func DecryptAssetWithName

func DecryptAssetWithName(boxID, diskName string, dek, ciphertext []byte) (plaintext []byte, originalName string, err error)

DecryptAssetWithName 解密资源内容并返回原始名称。

func DecryptFile

func DecryptFile(boxID, relativePath string, dek, ciphertext []byte) ([]byte, error)

DecryptFile 对应解密。

func DeepCopyBoxEncryption

func DeepCopyBoxEncryption(src *conf.BoxEncryption) *conf.BoxEncryption

DeepCopyBoxEncryption 深拷贝 BoxEncryption(含 []byte 字段),输入 nil 时返回 nil。 供 api 层在反序列化请求体前保存加密字段的不可变快照。

func DeferredSyncAssets

func DeferredSyncAssets() ([]*entity.File, error)

DeferredSyncAssets 仅读取逻辑清单,不发起下载。

func DisableEncryptedNotebook

func DisableEncryptedNotebook() error

DisableEncryptedNotebook 关闭加密笔记本功能。前置:不能有加密笔记本存在, 且不能有依赖当前密钥备份的已删除笔记本历史(否则禁用并删除备份会让这些历史永久锁死,违反 §19)。 清除全局加密配置(MasterSalt/KEKVerifier),KEK/DEK 不再可用。

func DisabledBuiltinSkills

func DisabledBuiltinSkills() []string

func DismissOnboarding

func DismissOnboarding() *conf.Onboarding

func Doc2Heading

func Doc2Heading(srcID, targetID string, after bool) (srcTreeBox, srcTreePath string, err error)

func DocAssets

func DocAssets(rootID string, retainQueryStr bool) (ret []string, err error)

func DocAssetsForPublishAccess

func DocAssetsForPublishAccess(c *gin.Context, publishAccess PublishAccess, rootID string, retainQueryStr bool) ([]string, error)

DocAssetsForPublishAccess 返回发布读者可见的文档资源,属性视图行按其绑定文档的发布访问过滤。

func DocImageAssets

func DocImageAssets(rootID string) (ret []string, err error)

func DocSaveAsTemplate

func DocSaveAsTemplate(id, name string, overwrite bool) (code int, err error)

func DocSaveAsTemplateInDirectory

func DocSaveAsTemplateInDirectory(id, name, directory string, overwrite bool, databaseMode TemplateDatabaseMode) (code int, err error)

func DocSaveAsTemplateInDirectoryAndRemember

func DocSaveAsTemplateInDirectoryAndRemember(id, name, directory string, overwrite bool,
	databaseMode TemplateDatabaseMode) (code int, err error)

func DocSaveAsTemplateWithDatabaseMode

func DocSaveAsTemplateWithDatabaseMode(id, name string, overwrite bool, databaseMode TemplateDatabaseMode) (code int, err error)

func DocTreePublishAccessRevision

func DocTreePublishAccessRevision(policy PublishAccess) string

func DownloadCloudSnapshot

func DownloadCloudSnapshot(tag, id string) (err error)

func DownloadNetAssets2LocalAssets

func DownloadNetAssets2LocalAssets(tree *parse.Tree, onlyImg bool, originalURL string, assetsDirPath string)

DownloadNetAssets2LocalAssets 将语法树中的网络资源下载到本地并改写链接, 不持久化文档树,由调用方负责后续保存与渲染。

func DownloadUpdate

func DownloadUpdate(version string) error

DownloadUpdate 只下载当前通道中与通知版本一致的安装包,不修改自动下载设置。

func DuplicateAttributeViewRow

func DuplicateAttributeViewRow(tx *Transaction, avID, previousItemID, srcRowID, newRowID string) (err error)

DuplicateAttributeViewRow 创建源行的纯文本副本,复制除主键、Rollup、Created、Updated 外的所有字段值, 双向关联同步更新目标属性视图的反向关联列。新行 ID 由调用方(前端)生成并通过 newRowID 传入, 副本插入到 previousItemID(通常为最后选中的条目)之后。

func DuplicateAttributeViewView

func DuplicateAttributeViewView(avID, blockID, sourceViewID, name string) (string, error)

DuplicateAttributeViewView 通过现有事务复制视图配置并同步数据库块的显示状态。

func DuplicateDatabaseBlock

func DuplicateDatabaseBlock(avID string) (newAvID, newBlockID string, err error)

func DuplicateDoc

func DuplicateDoc(tree *parse.Tree) error

func DuplicateDocTree

func DuplicateDocTree(id string) (*parse.Tree, error)

DuplicateDocTree 在原父目录创建完整副本,正文内部关联指向副本,数据库保留镜像及原行绑定。

func EnableEncryptedNotebook

func EnableEncryptedNotebook(password string) error

EnableEncryptedNotebook 启用加密笔记本功能:生成 MasterSalt、派生 KEK、写入校验值并持久化。 重复调用(已启用)返回错误,避免覆盖现有加密笔记本的密钥参数。 KEK 不缓存——启用后用户需对每个加密笔记本单独调 UnlockBox 解锁。

func EnableEncryptedNotebookWithSync

func EnableEncryptedNotebookWithSync(password string) error

EnableEncryptedNotebookWithSync 在启用前先完成同步;同步恢复了既有配置时只校验原主密码。

func EnabledUserSkills

func EnabledUserSkills() []string

func EncryptAsset

func EncryptAsset(boxID, diskName, originalName string, dek, plaintext []byte) ([]byte, error)

EncryptAsset 生成单文件资源容器,名称元数据和内容分块分别认证加密。

func EncryptFile

func EncryptFile(boxID, relativePath string, dek, plaintext []byte) ([]byte, error)

EncryptFile 用 fileKey(DEK 派生子密钥)加密 .sy 文档字节,AAD 绑定 boxID + 稳定文件基名(不含父目录)。 relativePath 会先经 filesys.SyAAD 提取稳定文件基名(<rootID>.sy)并校验合法性, 与文件系统读写共用同一 AAD 构造入口,保证加解密一致。

func EncryptedRawPathBoxID

func EncryptedRawPathBoxID(absPath string) string

EncryptedRawPathBoxID 返回原始文件路径所属的加密笔记本 ID。 同时检查最长已存在父目录解析后的路径,防止通过符号链接绕过加密边界。

func EnsureAllSyncAssets

func EnsureAllSyncAssets() error

EnsureAllSyncAssets 用于完整导出和退出按需模式,不改变资源的逻辑版本。

func EnsureAssetLocal

func EnsureAssetLocal(absPath string) error

EnsureAssetLocal 在调用方完成访问校验后补齐资源,下载内容仍由原有读取流程认证。

func EnsureAssetPrefixLocal

func EnsureAssetPrefixLocal(absPrefix string) error

EnsureAssetPrefixLocal 补齐逻辑清单中的目录内容,不能仅遍历本地磁盘。

func EnsureBoxDoc

func EnsureBoxDoc(boxID string) (boxDocID string, err error)

func EnsureOnboarding

func EnsureOnboarding() (ret *conf.Onboarding, notebookCreated bool, err error)

func ExitKernel

func ExitKernel()

ExitKernel 在退出清理完成后结束服务,移动端保留确认通道直到原生宿主退出。

func Export2Liandi

func Export2Liandi(id string) (err error)

func ExportAv2CSV

func ExportAv2CSV(avID, blockID string) (zipPath string, err error)

func ExportCodeBlock

func ExportCodeBlock(blockID string) (filePath string, err error)

func ExportData

func ExportData() (zipPath string, err error)

func ExportDataInFolder

func ExportDataInFolder(exportFolder string) (name string, err error)

func ExportDocx

func ExportDocx(id, savePath string, removeAssets, merge bool, mergeHeadingOptions ...MergeHeadingOptions) (fullPath string, err error)

func ExportHTML

func ExportHTML(id, savePath string, pdf, keepFold, merge bool, mergeHeadingOptions ...MergeHeadingOptions) (name, dom string, node *ast.Node)

func ExportHTMLWithTitle

func ExportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle bool, customTitle string,
	mergeHeadingOptions ...MergeHeadingOptions) (name, dom string, node *ast.Node)

func ExportMarkdownContent

func ExportMarkdownContent(id string, opts *ExportOptions) (hPath, exportedMd string)

func ExportMarkdownHTML

func ExportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptions ...MergeHeadingOptions) (name, dom string)

func ExportNotebookCryptoBackup

func ExportNotebookCryptoBackup() (downloadPath string, err error)

ExportNotebookCryptoBackup 把密钥备份文件复制到 export 目录,返回可下载的相对路径。 供用户主动导出保存,作为同步之外的独立恢复途径(详见设计文档 §4.1)。 备份文件本身不含主密码(salt 不保密、verifier 是密文),拿到它也解不开任何数据。

func ExportNotebookMarkdownWithOptions

func ExportNotebookMarkdownWithOptions(boxID string, opts *ExportOptions) (zipPath string)

func ExportNotebookSY

func ExportNotebookSY(id string) (zipPath string)

func ExportNotebooksMarkdown

func ExportNotebooksMarkdown(boxIDs []string) (zipPath string)

func ExportNotebooksMarkdownWithOptions

func ExportNotebooksMarkdownWithOptions(boxIDs []string, opts *ExportOptions) (zipPath string)

func ExportNotebooksSY

func ExportNotebooksSY(ids []string) (zipPath string)

ExportNotebooksSY 将多个笔记本打包到同一个可批量导入的 .sy.zip 中。

func ExportPandocConvertZip

func ExportPandocConvertZip(ids []string, pandocTo, ext string) (name, zipPath string)

func ExportPandocConvertZipWithOptions

func ExportPandocConvertZipWithOptions(ids []string, pandocTo, ext string, opts *ExportOptions) (name, zipPath string)

func ExportPreview

func ExportPreview(id string, fillCSSVar bool, avPublishFilter AVExportPublishFilter,
	accessChecker ...EmbedBlockAccessChecker) (retStdHTML string)

func ExportPreviewHTMLWithTitle

func ExportPreviewHTMLWithTitle(id string, keepFold, merge, addTitle bool, customTitle string, keepJSEmbed, excludeTitleImage bool,
	mergeHeadingOptions ...MergeHeadingOptions) (name, dom string, node *ast.Node)

func ExportRepoFile

func ExportRepoFile(id string) (exportPath string, err error)

func ExportResources

func ExportResources(resourcePaths []string, mainName string) (exportFilePath string, err error)

func ExportSYs

func ExportSYs(ids []string) (zipPath string)

func ExportStdMarkdown

func ExportStdMarkdown(id string, opts *ExportOptions) string

func ExportSystemLog

func ExportSystemLog() (zipPath string)

func ExtractBoxIDFromHistoryPath

func ExtractBoxIDFromHistoryPath(absPath string) string

ExtractBoxIDFromHistoryPath 从历史目录下的绝对路径反推 boxID。 路径形如 <HistoryDir>/<timestamp>-<op>/<boxID>/...,切出紧跟在时间戳目录后的一段。 若路径不在 HistoryDir 下或 boxID 非合法 ID 模式,返回空串。

func FileETag

func FileETag(filePath string) (string, error)

FileETag identifies the persisted representation, including equal-size changes whose timestamps may be identical after synchronization.

func FilterAttributeViewByPublishAccess

func FilterAttributeViewByPublishAccess(c *gin.Context, publishAccess PublishAccess, avID, blockID string, viewable av.Viewable) av.Viewable

func FilterContentByPublishAccess

func FilterContentByPublishAccess(c *gin.Context, publishAccess PublishAccess, box string, docPath string, content string, onlyIcon bool) string

func FilterGraphByPublishAccess

func FilterGraphByPublishAccess(c *gin.Context, publishAccess PublishAccess, nodes []*GraphNode, links []*GraphLink) (retNodes []*GraphNode, retLinks []*GraphLink)

func FilterLocalStorageByPublishAccess

func FilterLocalStorageByPublishAccess(localStorage map[string]any) (ret map[string]any)

func FilterRefIDsByPublishAccess

func FilterRefIDsByPublishAccess(c *gin.Context, publishAccess PublishAccess, refIDs []string) (ret []string)

func FilterSearchDocsByPublishAccess

func FilterSearchDocsByPublishAccess(c *gin.Context, publishAccess PublishAccess, docs []map[string]string) (ret []map[string]string)

func FilterViewByPublishAccess

func FilterViewByPublishAccess(c *gin.Context, publishAccess PublishAccess, viewable av.Viewable) (ret av.Viewable)

func FindAssetReferences

func FindAssetReferences(assetPath string) (apicontract.AssetReferencesData, error)

func FindAssetReferencesBatch

func FindAssetReferencesBatch(ctx context.Context, paths []string) (apicontract.AssetReferencesData, error)

func FindAssetReferencesWithContext

func FindAssetReferencesWithContext(ctx context.Context, path string) (apicontract.AssetReferencesData, error)

func FindReplace

func FindReplace(keyword, replacement string, replaceTypes map[string]bool, ids []string, paths, boxes []string, types, subTypes map[string]bool, method, orderBy, groupBy int) (err error)

func FindReplaceInBox

func FindReplaceInBox(keyword, replacement string, replaceTypes map[string]bool, ids []string, paths, boxes []string, types, subTypes map[string]bool, method int, boxID string) (err error)

FindReplaceInBox 与 FindReplace 一致,但按 boxID 路由到加密 db 或全局 db。

func FlushAssetsTextsJob

func FlushAssetsTextsJob()

func FlushTxQueue

func FlushTxQueue()

func FlushUpdateRefTextRenameDocJob

func FlushUpdateRefTextRenameDocJob()

func FullReindex

func FullReindex(needResetScroll bool)

func FullReindexDirect

func FullReindexDirect()

func FullTextSearchHistory

func FullTextSearchHistory(query, box, op string, typ, page int) (ret []string, pageCount, totalCount int)

func FullTextSearchHistoryGroups

func FullTextSearchHistoryGroups(query, box, op string, typ, page int) (ret []string, itemCounts map[string]int, pageCount, totalCount int)

func GenerateAssetsThumbnail

func GenerateAssetsThumbnail(sourceImgPath, resizedImgPath string) (err error)

func GenerateFileHistory

func GenerateFileHistory()

func GenerateFileHistoryForBox

func GenerateFileHistoryForBox(box *Box)

GenerateFileHistoryForBox 对单个 box 生成文件历史。供加密笔记本关闭(锁定)前调用—— 锁定后定时器(GenerateFileHistory)无法为加密笔记本生成历史(不在 GetOpenedBoxes 里)。

func GetAIMemory

func GetAIMemory(ctx context.Context, id string) (apicontract.AIMemoryGetData, error)

func GetAIMemoryForModel

func GetAIMemoryForModel(ctx context.Context, id string) (apicontract.AIMemoryGetData, error)

模型读取与本地管理分离,撤销来源许可后不能经工具旁路导出缓存正文。

func GetAIMemoryTask

func GetAIMemoryTask(id string) (apicontract.AIMemoryTaskData, error)

func GetAssetAbsPath

func GetAssetAbsPath(relativePath string) (string, error)

func GetAssetAbsPathInBox

func GetAssetAbsPathInBox(relativePath, boxID string) (string, error)

GetAssetAbsPathInBox 在指定 box 内解析资源绝对路径,不进行全局遍历。 relativePath 必须以 assets/ 前缀开头,boxID 为空且路径没有 box 查询参数时只解析普通/全局资源,不遍历加密 box。 加密 box 直接从 <boxID>/assets/ 查找,不依赖后缀匹配。

func GetAssetAbsPathWithOpt

func GetAssetAbsPathWithOpt(relativePath string, includeEncrypted bool) (string, error)

GetAssetAbsPathWithOpt 与 GetAssetAbsPath 一致,但可通过 includeEncrypted 控制是否遍历加密 box。 serveAssets 传 true(下游 serveEncryptedAsset 会按锁定状态 fail-closed),其他调用方传 false(安全跳过)。

func GetAssetImgSizeInBox

func GetAssetImgSizeInBox(assetPath, boxID string) (width, height int)

func GetAssetPathByHash

func GetAssetPathByHash(hash, boxID string) string

GetAssetPathByHash 按 hash 查已存在的 asset 路径用于去重。boxID 非空且为加密笔记本时返回空—— 加密笔记本不参与全局去重(避免复用普通明文 asset);普通 box 走全局 cache/SQL(加密笔记本数据不在全局表)。

func GetAttrViewAddingBlockDefaultValues

func GetAttrViewAddingBlockDefaultValues(avID, blockID, viewID, groupID, previousBlockID, addingBlockID string) (ret map[string]*av.Value, err error)

func GetAttributeView

func GetAttributeView(avID string) (ret *av.AttributeView)

func GetAttributeViewBoundBlockIDs

func GetAttributeViewBoundBlockIDs(avID string, itemIDs []string) (ret map[string]string)

func GetAttributeViewContextFilter

func GetAttributeViewContextFilter(attrView *av.AttributeView,
	blockID string) (ret *av.AttributeViewContextFilter, err error)

GetAttributeViewContextFilter 读取物理数据库块独有的上下文筛选配置。

func GetAttributeViewContextFilterFields

func GetAttributeViewContextFilterFields(attrView *av.AttributeView, blockID string) []*av.AttributeViewContextFilterField

GetAttributeViewContextFilterFields 在承载数据库块的笔记本范围内解析上下文筛选候选。

func GetAttributeViewFilterSort

func GetAttributeViewFilterSort(avID, blockID string) (filters []*av.ViewFilter, sorts []*av.ViewSort)

func GetAttributeViewItemIDs

func GetAttributeViewItemIDs(avID string, blockIDs []string) (ret map[string]string)

func GetAttributeViewItemStatuses

func GetAttributeViewItemStatuses(blockID, avID, viewID, query string, itemIDs []string) (ret map[string]string, err error)

func GetAttributeViewItemStatusesWithNested

func GetAttributeViewItemStatusesWithNested(blockID, avID, viewID, query string, itemIDs []string, nested *av.NestedRequest) (map[string]string, error)

func GetAttributeViewKeysByID

func GetAttributeViewKeysByID(avID string, keyIDs ...string) (ret []*av.Key)

func GetAttributeViewPasteRows

func GetAttributeViewPasteRows(blockID, avID, viewID, groupID, query, startItemID string, count int) (
	table *av.Table, inferableKeyIDs []string, err error,
)

GetAttributeViewPasteRows 返回当前表格视图中从指定条目开始的连续行和可安全推断类型的空字段,供粘贴扩充行列。

func GetAttributeViewPasteRowsWithItems

func GetAttributeViewPasteRowsWithItems(blockID, avID, viewID, groupID, query, startItemID string, count int, itemIDs []string) (*av.Table, []string, error)

显式目标用于树形可见窗口;筛选补齐的祖先同样可编辑,不读取其他分页条目。

func GetAttributeViewPrimaryKeyValues

func GetAttributeViewPrimaryKeyValues(avID, keyword string, blockIDs []string, page, pageSize int) (attributeViewName string, databaseBlockIDs []string, keyValues *av.KeyValues, total int, err error)

func GetAttributeViewRelationCandidates

func GetAttributeViewRelationCandidates(srcAvID, relationKeyID, keyword string, selectedBlockIDs []string, page, pageSize int, candidateSort *av.ViewSort, blockIDs ...string) (
	attributeViewName string, databaseBlockIDs []string, customColors []*av.AttributeViewCustomColor,
	columns []*av.TableColumn, selectedRows, rows []*av.TableRow,
	total int, err error,
)

func GetAttributeViewRelationCandidatesWithExcludes

func GetAttributeViewRelationCandidatesWithExcludes(srcAvID, relationKeyID, keyword string, selectedBlockIDs []string, page, pageSize int, candidateSort *av.ViewSort, excludeItemIDs []string, blockIDs ...string) (
	attributeViewName string, databaseBlockIDs []string, customColors []*av.AttributeViewCustomColor,
	columns []*av.TableColumn, selectedRows, rows []*av.TableRow,
	total int, err error,
)

func GetAttributeViewRelationCellCandidates

func GetAttributeViewRelationCellCandidates(avID, keyID, blockID, keyword string, selectedIDs []string, page, pageSize int,
	candidateSort *av.ViewSort, excludes []string, context *AttributeViewRelationCellContext) (
	name string, carriers []string, colors []*av.AttributeViewCustomColor, columns []*av.TableColumn,
	selected, rows []*av.TableRow, total int, err error)

func GetAttributeViewRelationDependencyPrimaryValues

func GetAttributeViewRelationDependencyPrimaryValues(targetID, blockID string, context *AttributeViewRelationContext, keyIDs []string,
	keyword string, itemIDs []string, page, pageSize int) (name string, carriers []string, values *av.KeyValues, total int, err error)

func GetAttributeViewRelationDetailCandidates

func GetAttributeViewRelationDetailCandidates(srcAvID, relationKeyID, keyword string, selectedBlockIDs []string, page, pageSize int, candidateSort *av.ViewSort, excludeItemIDs []string, context *AttributeViewRelationContext, blockIDs ...string) (
	attributeViewName string, databaseBlockIDs []string, customColors []*av.AttributeViewCustomColor,
	columns []*av.TableColumn, selectedRows, rows []*av.TableRow,
	total int, err error,
)

func GetAttributeViewViewTarget

func GetAttributeViewViewTarget(avID, blockID, viewID string) (*av.AttributeView, *av.View, error)

GetAttributeViewViewTarget 根据数据库块和视图 ID 精确读取视图,避免回退到首个视图。

func GetBazaarPackageDetail

func GetBazaarPackageDetail(pkgType, packageName, frontend string) (installed, available *bazaar.Package)

GetBazaarPackageDetail 获取单个集市包的本地安装信息和在线信息。

在线集市不可用时仍返回本地信息,避免网络问题阻断已下载包详情。

func GetBazaarPackageREADME

func GetBazaarPackageREADME(ctx context.Context, repoURL, repoHash, pkgType string) (ret string)

func GetBazaarPackageRating

func GetBazaarPackageRating(ctx context.Context, pkgType, packageName string) (rating *bazaar.PackageRating,
	ratingAvailable bool, userRating int, err error)

GetBazaarPackageRating 获取已安装官方包的公开评分和当前用户评分。

func GetBazaarPackages

func GetBazaarPackages(pkgType, frontend, keyword string) (bazaarPackages []*bazaar.Package)

GetBazaarPackages 获取在线集市包列表

func GetBazaarPackagesWithError

func GetBazaarPackagesWithError(pkgType, frontend, keyword string) ([]*bazaar.Package, error)

GetBazaarPackagesWithError 获取在线集市包,并保留网络错误供工具调用方区分空列表与请求失败。

func GetBlockDOM

func GetBlockDOM(id string) (ret string)

func GetBlockDOMInBox

func GetBlockDOMInBox(id, boxID string) (ret string)

GetBlockDOMInBox 渲染指定笔记本内的块 DOM。boxID 为空时仅查询普通全局库。

func GetBlockDOMWithEmbedInBoxWithAccessChecker

func GetBlockDOMWithEmbedInBoxWithAccessChecker(id, boxID string, accessChecker EmbedBlockAccessChecker) (ret string)

GetBlockDOMWithEmbedInBoxWithAccessChecker 按访问权限渲染指定笔记本内包含嵌入块的 DOM。

func GetBlockDOMsInBox

func GetBlockDOMsInBox(ids []string, boxID string) (ret map[string]string)

GetBlockDOMsInBox 渲染指定笔记本内的块 DOM。禁止在 boxID 未指定时遍历加密笔记本。

func GetBlockDOMsWithEmbedInBoxWithAccessChecker

func GetBlockDOMsWithEmbedInBoxWithAccessChecker(ids []string, boxID string, accessChecker EmbedBlockAccessChecker) (ret map[string]string)

GetBlockDOMsWithEmbedInBoxWithAccessChecker 按访问权限渲染指定笔记本内包含嵌入块的 DOM。

func GetBlockDefIDsByRefTextInBox

func GetBlockDefIDsByRefTextInBox(refText, boxID string) (ret []string)

func GetBlockIndex

func GetBlockIndex(id string) (ret int)

func GetBlockKramdown

func GetBlockKramdown(id, mode string) (ret string)

func GetBlockKramdownInBox

func GetBlockKramdownInBox(id, mode, boxID string) (ret string)

GetBlockKramdownInBox 与 GetBlockKramdown 一致,但按 boxID 路由 blocktree 查询。

func GetBlockKramdowns

func GetBlockKramdowns(ids []string, mode string) (ret map[string]string)

func GetBlockKramdownsInBox

func GetBlockKramdownsInBox(ids []string, mode, boxID string) (ret map[string]string)

GetBlockKramdownsInBox 与 GetBlockKramdowns 一致,但按 boxID 路由 blocktree 查询。

func GetBlockRefIDsByFileAnnotationIDInBox

func GetBlockRefIDsByFileAnnotationIDInBox(id, boxID string) []string

func GetBlockRefText

func GetBlockRefText(id string) string

func GetBlockRefTextInBox

func GetBlockRefTextInBox(id, boxID string) string

GetBlockRefTextInBox 在指定加密笔记本内解析块引锚文本。

func GetBlockRelevantIDsInBox

func GetBlockRelevantIDsInBox(id, boxID string) (parentID, previousID, nextID string, err error)

GetBlockRelevantIDsInBox 获取指定笔记本内块的父级及相邻块 ID。空 box 不回退搜索加密笔记本。

func GetBlockSiblingIDInBox

func GetBlockSiblingIDInBox(id, boxID string) (parent, previous, next string)

GetBlockSiblingIDInBox 获取指定笔记本内块的相邻关系。空 box 不回退搜索加密笔记本。

func GetBlockTreeInfosInBox

func GetBlockTreeInfosInBox(ids []string, boxID string) (ret map[string]*BlockTreeInfo)

GetBlockTreeInfosInBox 获取指定笔记本内的块树信息。空 box 仅查询普通全局库。

func GetBlocksIndexes

func GetBlocksIndexes(ids []string) (ret map[string]int)

func GetBoxEncryption

func GetBoxEncryption(boxID string) (*conf.BoxEncryption, error)

GetBoxEncryption 获取加密笔记本的 BoxEncryption(含 WrappedDEK)。 优先读 conf.json,若缺失/损坏则 fallback 到 per-notebook backup。 返回 nil 表示该 box 非加密;conf 标记加密但密钥材料缺失时返回明确错误。

func GetCloudRepoSnapshots

func GetCloudRepoSnapshots(page int) (ret []*dejavu.Log, pageCount, totalCount int, err error)

func GetCloudRepoSnapshotsByTime

func GetCloudRepoSnapshotsByTime(page int, startTime, endTime int64) (ret []*dejavu.Log, pageCount, totalCount int, err error)

func GetCloudRepoTagSnapshots

func GetCloudRepoTagSnapshots() (ret []*dejavu.Log, err error)

func GetCloudShorthand

func GetCloudShorthand(id string) (ret map[string]any, err error)

func GetCloudShorthands

func GetCloudShorthands(page int) (result map[string]any, err error)

func GetCloudSpace

func GetCloudSpace() (s *Sync, b *Backup, hSize, hAssetSize, hTotalSize, hExchangeSize, hTrafficUploadSize, hTrafficDownloadSize, hTrafficAPIGet, hTrafficAPIPut string, err error)

func GetCloudUser

func GetCloudUser(token string, cached bool) (*conf.User, error)

GetCloudUser 在启动时读取内存账户;需要刷新时保留资源来源切换保护。

func GetCurrentAttributeViewImages

func GetCurrentAttributeViewImages(c *gin.Context, avID, blockID, viewID, query, groupID string) (ret []string, err error)

func GetDEK

func GetDEK(boxID string) ([]byte, error)

GetDEK 取已缓存的 DEK。返回副本,避免外部零化影响缓存。 filesys/assets/db 加解密时调用。

func GetDEKIfUnlocked

func GetDEKIfUnlocked(boxID string) ([]byte, error)

GetDEKIfUnlocked 返回已解锁加密笔记本的 DEK(副本)。 非加密笔记本返回 (nil, nil)——filesys 据此原样读写,对普通笔记本透明。 加密但未解锁(DEK 不在内存)返回 (nil, error)——filesys 的加解密函数遇 error 后拒绝读写, 避免加密笔记本在未解锁状态下静默以明文落盘(深度防御,见 issue #18034)。

func GetDOMText

func GetDOMText(dom string) (ret string)

func GetDOMTextWithoutOCRAssets

func GetDOMTextWithoutOCRAssets(dom string) (ret string)

GetDOMTextWithoutOCRAssets 供发布读者使用,不返回资源的 OCR 文本,避免读取未发布资源的 OCR 缓存。

func GetDatabaseBlockVisibleViewIDs

func GetDatabaseBlockVisibleViewIDs(attrView *av.AttributeView, blockID string) ([]string, error)

GetDatabaseBlockVisibleViewIDs 读取指定数据库块的可见视图,并按数据库中的顺序返回。

func GetDecks

func GetDecks() (decks []*riff.Deck)

func GetDocBlocksOrders

func GetDocBlocksOrders(id string) (ret []string, err error)

func GetDocHistoryContent

func GetDocHistoryContent(historyPath, keyword string, highlight bool) (id, rootID, content string, isLargeDoc bool, err error)

func GetDocHistorySnapshots

func GetDocHistorySnapshots(ctx context.Context, id string, histories []*DocHistorySnapshotEntry) error

GetDocHistorySnapshots 按页匹配本地标记快照,仅在本次请求内复用文件摘要。 调用方须持有所有历史所属加密笔记本的请求租约,覆盖响应序列化。

func GetDocPaths

func GetDocPaths(boxID string, ids []string) (documents []*treenode.DocumentPath, missing []string, err error)

GetDocPaths 仅查询指定笔记本;缺失身份与索引、源格式错误分别返回。

func GetDocPathsWithIcons

func GetDocPathsWithIcons(boxID string, ids []string, includeIcons bool) (documents []*treenode.DocumentPath, missing []string, icons map[string]string, err error)

func GetFullHPathByID

func GetFullHPathByID(id string) (hPath string, err error)

func GetHPathByID

func GetHPathByID(id string) (hPath string, err error)

func GetHPathByPath

func GetHPathByPath(boxID, p string) (hPath string, err error)

func GetHPathsByPaths

func GetHPathsByPaths(paths []string) (hPaths []string, err error)

func GetHeadingChildrenDOM

func GetHeadingChildrenDOM(id string, removeFoldAttr bool) (ret string)

func GetHeadingChildrenIDs

func GetHeadingChildrenIDs(id string) (ret []string)

func GetHeadingNumbers

func GetHeadingNumbers(rootID, boxID string) (ret map[string]string, err error)

GetHeadingNumbers 返回文档标题块 ID 到显示编号的映射。

func GetIDsByHPath

func GetIDsByHPath(hpath, boxID string) ([]string, error)

GetIDsByHPath returns every clean exact match and rejects slash/empty-title collisions.

func GetImportAssetsDir

func GetImportAssetsDir(boxID, docDirLocalPath string) string

GetImportAssetsDir 返回导入资源的落盘目录。普通笔记本复用已有本地目录,否则回退到全局目录。

func GetInstalledBazaarPackageRatings

func GetInstalledBazaarPackageRatings(ctx context.Context, pkgType string,
	packageNames []string) (ratings map[string]*bazaar.PackageRating, eligiblePackageNames []string, err error)

GetInstalledBazaarPackageRatings 获取指定已安装包的公开评分。

func GetInstalledBazaarPackageRevision

func GetInstalledBazaarPackageRevision(pkgType, packageName string) (string, error)

GetInstalledBazaarPackageRevision 返回代码树摘要;目标不存在时返回 missing。

func GetInstalledBazaarPackageUserRatings

func GetInstalledBazaarPackageUserRatings(ctx context.Context, pkgType string,
	packageNames []string) (userRatings map[string]int, eligiblePackageNames []string, err error)

GetInstalledBazaarPackageUserRatings 获取指定已安装官方包的当前用户评分。

func GetInstalledPackageInfos

func GetInstalledPackageInfos(pkgType string) (installedPackageInfos []installedPackageInfo, basePath, baseURLPathPrefix string, err error)

GetInstalledPackageInfos 获取本地集市包信息,并返回路径相关字段供调用方复用

func GetInstalledPackageSize

func GetInstalledPackageSize(pkgType, packageName string) (size int64, hSize string, err error)

GetInstalledPackageSize 获取本地集市包的安装大小

func GetInstalledPackages

func GetInstalledPackages(pkgType, frontend, keyword string) (installedPackages []*bazaar.Package)

GetInstalledPackages 获取本地集市包列表

func GetLANSyncDiscoveryInfo

func GetLANSyncDiscoveryInfo() *lansync.DiscoveryInfo

func GetLocalStorage

func GetLocalStorage() (ret map[string]any)

func GetMobileExportName

func GetMobileExportName(exportPath string) string

GetMobileExportName 返回移动端保存对话框使用的文件名,不生成明文临时文件。

func GetNewSessionID

func GetNewSessionID() string

func GetOrderedListContinueStartInBox

func GetOrderedListContinueStartInBox(id, boxID string) (start int, found bool)

GetOrderedListContinueStartInBox 返回同一父级中最近前置有序列表的续编起始编号。

func GetOutlineStorage

func GetOutlineStorage(docID string) (ret map[string]any, err error)

func GetPathByID

func GetPathByID(id string) (path, boxID string, err error)

func GetPathPasswordByPublishAccess

func GetPathPasswordByPublishAccess(box string, blockPath string, publishAccess PublishAccess) (passwordID string, password string)

func GetPublishAccessSearchExclusion

func GetPublishAccessSearchExclusion(c *gin.Context) (denyAll bool, boxIDs, docIDs []string)

GetPublishAccessSearchExclusion 返回当前读者在全库搜索中不可见的笔记本 ID 和文档 ID 排除集合。 排除来源包括隐藏、禁止发布以及未通过密码验证的发布访问条目,保证搜索计数和分页不泄露这些条目。 denyAll 为 true 时当前读者不可见任何内容,调用方应直接返回空结果。

func GetQueryEmbedStatement

func GetQueryEmbedStatement(embedBlockID string) (stmt, boxID string, err error)

func GetRefUsed

func GetRefUsed() (ret map[string]int64)

GetRefUsed 返回目标块→最近引用时间戳映射,供块引排序使用。

func GetReleaseChangelog

func GetReleaseChangelog(ctx context.Context, version string) (string, error)

func GetRepoFile

func GetRepoFile(fileID string) (ret []byte, p string, err error)

func GetSyncCheckout

func GetSyncCheckout(appID, clientID string) apicontract.SyncCheckoutSnapshot

GetSyncCheckout 同步任务快照与结束版本,避免重连后继续使用过期的编辑阻断状态。

func GetSyncSourceState

func GetSyncSourceState() (ret apicontract.SyncSourceState, err error)

func GetTemplateHTTPFilePermission

func GetTemplateHTTPFilePermission(relativePath string) (bool, error)

func GetTokenClaims

func GetTokenClaims(token *jwt.Token) jwt.MapClaims

func GetUnfoldedParentID

func GetUnfoldedParentID(id string) (parentID string)

func GetViewState

func GetViewState(key string) (ret map[string]any, err error)

func GrantTemplateHTTPSource

func GrantTemplateHTTPSource(source *TemplateHTTPSource) error

func HTML2Tree

func HTML2Tree(htmlStr string, luteEngine *lute.Lute, boxID string) (tree *parse.Tree, withMath bool)

func HTML2TreeWithOptions

func HTML2TreeWithOptions(htmlStr string, luteEngine *lute.Lute, boxID string,
	options HTML2TreeOptions) (tree *parse.Tree, withMath bool)

func HTMLAssetIFrameSrc

func HTMLAssetIFrameSrc(assetPath string) string

HTMLAssetIFrameSrc 返回用于安全渲染 HTML 资源的 IFrame 地址。

func HandleAssetsChangeEvent

func HandleAssetsChangeEvent(assetAbsPath string)

func HandleAssetsRemoveEvent

func HandleAssetsRemoveEvent(assetAbsPath string)

func HandleSignal

func HandleSignal()

func HasEncryptedNotebookHistory

func HasEncryptedNotebookHistory() bool

HasEncryptedNotebookHistory 在扫描失败时按存在依赖处理,避免调用方因 I/O 或权限错误删除恢复材料。

func HasOCRFailure

func HasOCRFailure(path string) bool

HasOCRFailure 查询当前内核运行期间的识别失败;笔记本身份与 OCR 文本使用相同规范键。

func Heading2Doc

func Heading2Doc(srcHeadingID, targetBoxID, targetPath, previousPath string, toTop bool) (srcRootBlockID, newTargetPath string, err error)

func HideBoxConfSecret

func HideBoxConfSecret(c *conf.BoxConf)

HideBoxConfSecret 隐藏笔记本配置中的密钥材料。

func HideConfSecret

func HideConfSecret(c *AppConf)

HideConfSecret 隐藏设置中的秘密信息 REF: https://github.com/siyuan-note/siyuan/issues/11364

func HoldBoxReadLock

func HoldBoxReadLock(boxID string)

HoldBoxReadLock 获取 box 读锁,防止 LockBox 在持锁期间清除缓存/临时文件。 调用方完成解密输出后必须调 ReleaseBoxReadLock。

func HookDesktopUIProcJob

func HookDesktopUIProcJob()

func ImportData

func ImportData(zipPath string) (err error)

func ImportFromLocalPath

func ImportFromLocalPath(boxID, localPath string, toPath string) (err error)

func ImportFromLocalPathSkipRoot

func ImportFromLocalPathSkipRoot(boxID, localPath string, toPath string) (err error)

ImportFromLocalPathSkipRoot 导入本地路径,但不将来源根目录转换为文档。

func ImportNotebookArchive

func ImportNotebookArchive(archivePath, password string, keyData []byte) error

ImportNotebookArchive 在独立暂存区认证恢复材料,所有校验成功后才把密文放入未配置密钥的工作区。

func ImportNotebookCryptoBackup

func ImportNotebookCryptoBackup(data []byte, password string) error

ImportNotebookCryptoBackup 接收用户导入的密钥备份文件内容(JSON 字节), 校验为合法 NotebookCrypto 后写回 <DataDir>/.siyuan/data-crypto-backup.json 并装回本机 Conf。 用于新设备/重装后不依赖同步、手动恢复加密配置(详见设计文档 §4.1)。 安全:备份文件不含主密码(salt 不保密、verifier 是密文),导入只恢复配置,解锁仍需主密码。 防呆:本机已有完整且已启用的加密配置时拒绝导入,避免覆盖现有 salt/verifier 孤立现有 WrappedDEK。 ImportNotebookCryptoBackup 接收用户导入的密钥备份文件内容(JSON 字节)+ 主密码, 校验主密码能解开备份里的 verifier 后才写回配置。防止 crafted 备份设置弱 KDFParams 等攻击。 RecoveryRequired 状态允许导入,但候选 KEK 必须能解开所有现存笔记本和已删除笔记本历史。

func ImportOCRModels

func ImportOCRModels(ctx context.Context, files []*multipart.FileHeader) (string, error)

ImportOCRModels 使用固定目标文件名和内容摘要标识,不信任上传文件名或绝对路径。

func ImportRepoKey

func ImportRepoKey(base64Key string) (retKey string, err error)

func ImportSY

func ImportSY(zipPath, boxID, toPath string) (err error)

func ImportSYAuto

func ImportSYAuto(zipPath, boxID, toPath string) (createdBoxID string, notebook bool, err error)

func ImportSYNotebook

func ImportSYNotebook(zipPath string) (boxID string, err error)

func ImportSYNotebookBundle

func ImportSYNotebookBundle(zipPath string) (boxIDs []string, bundle bool, err error)

ImportSYNotebookBundle 导入批量笔记本包。普通 .sy.zip 返回 bundle=false,由原有导入流程继续处理。

func IncSync

func IncSync()

func IncSyncIfNeeded

func IncSyncIfNeeded(absPaths ...string)

IncSyncIfNeeded 在指定路径的变更会影响数据同步仓库时重新计划同步。

func IndexEmbedBlockJob

func IndexEmbedBlockJob()

IndexEmbedBlockJob 嵌入块支持搜索 https://github.com/siyuan-note/siyuan/issues/7112

func IndexRefs

func IndexRefs()

func IndexRepo

func IndexRepo(memo string) (id string, err error)

func InitAppearance

func InitAppearance()

func InitBoxes

func InitBoxes()

func InitCommunity

func InitCommunity()

func InitConf

func InitConf()

func InitJwtKey

func InitJwtKey()

func InitOCR

func InitOCR()

func InitPublishAccounts

func InitPublishAccounts()

func InitRepoKey

func InitRepoKey() (err error)

func InitRepoKeyFromPassphrase

func InitRepoKeyFromPassphrase(passphrase string) (err error)

func InsertAssetBytes

func InsertAssetBytes(id, fileName string, data []byte) (assetPath string, created bool, err error)

InsertAssetBytes 将内存中的资源直接写入目标文档资源目录,避免生成内容经过明文临时文件。

func InsertHTMLLocalAssets

func InsertHTMLLocalAssets(id string, assetAbsPaths []string) (succMap map[string]string,
	succFiles []AssetUploadSuccess, failedFiles []AssetUploadFailure, err error)

func InsertLocalAssets

func InsertLocalAssets(id string, assetAbsPaths []string, isUpload bool) (succMap map[string]string,
	succFiles []AssetUploadSuccess, failedFiles []AssetUploadFailure, err error)

func InstallBazaarPackage

func InstallBazaarPackage(pkgType, repoURL, repoHash, repoRef, packageName string, themeOptions *ThemeInstallOptions) error

InstallBazaarPackage 安装集市包,themeOptions 仅在 pkgType 为 "themes" 时生效

func InstallBazaarPackageContext

func InstallBazaarPackageContext(ctx context.Context, pkgType, repoURL, repoHash, repoRef, packageName string, themeOptions *ThemeInstallOptions) error

InstallBazaarPackageContext 在下载、解压和替换前响应请求取消,替换完成后仍执行运行时刷新。

func InvalidateTemplateHTTPDatabase

func InvalidateTemplateHTTPDatabase(owner, avID, fieldID string) error

func InvalidateTemplateHTTPFilePath

func InvalidateTemplateHTTPFilePath(filename string) error

func IsAIEditorStreamDone

func IsAIEditorStreamDone(err error) bool

func IsAccessAuthRequired

func IsAccessAuthRequired() bool

func IsAccessCodeSessionAuthenticated

func IsAccessCodeSessionAuthenticated(workspaceSession *util.WorkspaceSession) bool

func IsAdminRoleContext

func IsAdminRoleContext(c *gin.Context) bool

func IsBlockFolded

func IsBlockFolded(id string) (isFolded, isRoot bool)

func IsBlockRefCrossingBoundary

func IsBlockRefCrossingBoundary(srcBoxID, defBlockID string) bool

IsBlockRefCrossingBoundary 判断从 srcBoxID 引用 defBlockID 是否跨越加密边界。 加密笔记本禁止跨边界块引(双向):加密笔记本的块只能引用同一加密笔记本内的块,普通 box 的块不能引用加密笔记本的块。 供 transaction 落库时兜底校验,防止手工输入/拖拽/粘贴/API 直调绕过前端搜索分流。

func IsBoxDoc

func IsBoxDoc(boxID, id string) bool

func IsBoxDocEnabled

func IsBoxDocEnabled() bool

func IsBoxDocPath

func IsBoxDocPath(boxID, p string) bool

func IsBoxUnlocked

func IsBoxUnlocked(boxID string) bool

IsBoxUnlocked 返回该笔记本的 DEK 是否在内存(是否已解锁)。

func IsCloudAssetSourceChange

func IsCloudAssetSourceChange(err error) bool

func IsEncryptedAssetPath

func IsEncryptedAssetPath(absPath string) bool

IsEncryptedAssetPath 判断给定 asset 绝对路径是否属于加密笔记本。 供 server 层在缩略图等场景判断是否需跳过密文文件的处理。

func IsEncryptedBox

func IsEncryptedBox(boxID string) bool

IsEncryptedBox 判断给定 boxID 是否为加密笔记本。 配置缺失或损坏时依次检查运行时身份、独立备份和密文标识,任何检查错误都按加密笔记本处理。

func IsEncryptedBoxDeniedByPublishAccess

func IsEncryptedBoxDeniedByPublishAccess(boxID string) bool

IsEncryptedBoxDeniedByPublishAccess 判断笔记本是否应被发布门禁拒绝。

func IsEncryptedHistoryPath

func IsEncryptedHistoryPath(absPath string) bool

IsEncryptedHistoryPath 判断历史路径是否明确属于加密笔记本。

func IsEncryptedNotebookData

func IsEncryptedNotebookData(data []byte) bool

IsEncryptedNotebookData 判断数据是否以当前文档或资源密文标识开头。

func IsEncryptedOCRAsset

func IsEncryptedOCRAsset(path string) bool

IsEncryptedOCRAsset 保留笔记本查询参数并忽略链接片段,不依赖资源已下载或笔记本已解锁。

func IsEncryptedPublishAccessTarget

func IsEncryptedPublishAccessTarget(id string) bool

IsEncryptedPublishAccessTarget 判断发布访问配置目标是否属于加密笔记本,包括锁定笔记本中的文档。

func IsEncryptedPublishRuntimeTarget

func IsEncryptedPublishRuntimeTarget(id string) bool

IsEncryptedPublishRuntimeTarget 判断发布读取目标是否属于当前可解析的加密笔记本。

func IsHTMLAssetIFrameSrc

func IsHTMLAssetIFrameSrc(assetPath string) bool

IsHTMLAssetIFrameSrc 判断资源地址是否为 HTML 文件 IFrame 渲染地址。

func IsImageExecutionUnknown

func IsImageExecutionUnknown(err error) bool

IsImageExecutionUnknown 判断图片提供商调用是否已经开始,调用方不得自动重试这类错误。

func IsInvalidUserRefresh

func IsInvalidUserRefresh(err error) bool

func IsLocalHTMLAssetPath

func IsLocalHTMLAssetPath(assetPath string) bool

IsLocalHTMLAssetPath 判断资源地址是否为本地 HTML 文件。

func IsLocalRequest

func IsLocalRequest(c *gin.Context) bool

IsLocalRequest 判断请求是否由本机客户端直接发起或经内置 fixed-port 代理转发。

func IsManagedEncryptedExportPath

func IsManagedEncryptedExportPath(relativePath string) bool

IsManagedEncryptedExportPath 判断相对路径是否属于加密导出受控范围(<boxID>/<kind>/<file> 结构)。 只要路径首段是合法 boxID 格式即视为受控,不依赖 box 是否仍存在(笔记本删除后仍需按注册表拒绝, 避免因 IsEncryptedBox 返回 false 而 fail-open 暴露明文产物)。

func IsMoveOutlineHeading

func IsMoveOutlineHeading(transactions *[]*Transaction) bool

func IsOIDCSessionAuthenticated

func IsOIDCSessionAuthenticated(workspaceSession *util.WorkspaceSession) bool

func IsOIDCSessionVersionCurrent

func IsOIDCSessionVersionCurrent(version string) bool

func IsObsidianVaultTaskActive

func IsObsidianVaultTaskActive() bool

func IsPaidUser

func IsPaidUser() bool

func IsPetalsEnabled

func IsPetalsEnabled() bool

IsPetalsEnabled returns whether petals are enabled and trusted to be loaded

func IsPublishServiceToken

func IsPublishServiceToken(token *jwt.Token) bool

IsPublishServiceToken 检查 token 是否来自发布服务

func IsReadOnlyRole

func IsReadOnlyRole(role Role) bool

func IsReadOnlyRoleContext

func IsReadOnlyRoleContext(c *gin.Context) bool

func IsSameCryptoBoundary

func IsSameCryptoBoundary(srcBox, dstBox string) bool

IsSameCryptoBoundary 判断 srcBox 与 dstBox 是否处于同一加密边界(跨 box 操作是否安全)。 普通笔记本之间允许(都不加密);加密笔记本仅允许同一 box 内部操作——两个不同的加密笔记本各有独立 DEK, 之间互为"加密边界外",跨 box 移动/合并会用错 DEK 导致密文损坏。供 MoveDocs/Doc2Heading 等跨 box 操作校验。

func IsShorthandSaveBoxAvailable

func IsShorthandSaveBoxAvailable(boxID string) bool

func IsSubscriber

func IsSubscriber() bool

func IsSyncCheckoutApplying

func IsSyncCheckoutApplying() bool

func IsSyncingFile

func IsSyncingFile(rootID string) (ret bool)

func IsTemplateHTTPSourceCurrent

func IsTemplateHTTPSourceCurrent(source *TemplateHTTPSource) bool

func IsUserGuide

func IsUserGuide(boxID string) bool

func IsValidDocSortMode

func IsValidDocSortMode(sortMode int) bool

func IsValidPublishServiceToken

func IsValidPublishServiceToken(token *jwt.Token) bool

IsValidPublishServiceToken 检查 token 是否来自发布服务且有效

func IsValidRole

func IsValidRole(role Role, roles []Role) bool

func IsValidSearchBoxPath

func IsValidSearchBoxPath(box, docPath string) bool

IsValidSearchBoxPath 校验搜索入参中的笔记本 ID 与文档路径,阻止 SQL 元字符进入语句拼接。 box 必须是合法的节点 ID;docPath 为空表示仅限定笔记本范围;否则须为以 "/" 开头、 由节点 ID 段组成的文档路径(如 "/20210808180117-6v0mkxr.sy" 或子树目录 "/20210808180117-6v0mkxr")。

func IsWorkspaceSessionAuthenticated

func IsWorkspaceSessionAuthenticated(workspaceSession *util.WorkspaceSession) bool

func LANSyncActive

func LANSyncActive() bool

func ListAllEncryptedBoxIDs

func ListAllEncryptedBoxIDs() []string

ListAllEncryptedBoxIDs 返回所有可枚举的加密笔记本。扫描失败时记录错误并返回空列表; 涉及密钥覆盖或删除的调用方必须直接使用 listAllEncryptedBoxIDs 并处理错误。

func ListItem2Doc

func ListItem2Doc(srcListItemID, targetBoxID, targetPath, previousPath string, toTop bool) (srcRootBlockID, newTargetPath string, err error)

func LoadChatGPTAccountBindings

func LoadChatGPTAccountBindings(ai *conf.AI) error

LoadChatGPTAccountBindings 用当前设备的工作空间绑定替换配置携带的账户引用,不迁移旧引用。

func LoadFlashcards

func LoadFlashcards()

func LoadIcons

func LoadIcons()

func LoadPluginPublishData

func LoadPluginPublishData(name string) (map[string]json.RawMessage, error)

func LoadSnippets

func LoadSnippets() (ret []*conf.Snippet, err error)

func LoadThemes

func LoadThemes()

func LoadTreeByBlockID

func LoadTreeByBlockID(id string) (ret *parse.Tree, err error)

func LoadTreeByBlockIDInExactBox

func LoadTreeByBlockIDInExactBox(id, boxID string) (ret *parse.Tree, err error)

LoadTreeByBlockIDInExactBox 只在指定笔记本边界内加载块所在文档,boxID 为空时不遍历加密笔记本。

func LoadTreeByBlockIDWithReindex

func LoadTreeByBlockIDWithReindex(id string) (ret *parse.Tree, err error)

func LoadTreeByBlockIDWithReindexInBox

func LoadTreeByBlockIDWithReindexInBox(id, boxID string) (ret *parse.Tree, err error)

LoadTreeByBlockIDWithReindexInBox 与 LoadTreeByBlockIDWithReindex 一致,但按 boxID 路由 blocktree 查询。

func LoadUploadToken

func LoadUploadToken() (err error)

func LockBox

func LockBox(boxID string)

LockBox 清除指定笔记本的 DEK 并删除其加密 db 文件。Unmount 单个加密笔记本或手动锁定时调用。

func LockEncryptedNotebooksOnSystemLock

func LockEncryptedNotebooksOnSystemLock()

LockEncryptedNotebooksOnSystemLock 等待正在解锁的笔记本完成,再复用卸载流程保存内容并清除密钥。

func LockRequestAfterDecode

func LockRequestAfterDecode(c *gin.Context) error

LockRequestAfterDecode 接收剩余请求体后串行执行业务,避免排队请求占满 HTTP/2 连接接收窗口。 JSON 尾部数据沿用解码器的忽略语义;锁由外层中间件在响应和租约清理完成后释放。

func Login

func Login(userName, password, captcha string, cloudRegion int) (data *apicontract.AccountLoginData, code int, msg string)

Login 登录思源云端账号。code 沿用云端约定:0 成功,1 需要输入验证码,其他值为失败; 请求本身失败时使用 -1 并给出本地提示。data 为对应的账号载荷,失败时为 nil。

func Login2fa

func Login2fa(token, code string) *apicontract.Login2faEnvelope

Login2fa 提交双因素认证码,返回直接输出的响应信封。 云端结果的 code 会重映射:失败(-1)转为 1,以免与本地错误码混淆。

func LogoutUser

func LogoutUser()

func LookupAssetOriginalName

func LookupAssetOriginalName(boxID, diskName string) string

LookupAssetOriginalName 查询加密笔记本资源的原始文件名(供下载 Content-Disposition 等展示用)。 未找到时返回空串。

func LookupAssetOriginalNameLocked

func LookupAssetOriginalNameLocked(boxID, diskName string) string

LookupAssetOriginalNameLocked 在调用方已持有 box 读锁时查询原始资源名。

func MCPOAuthAvailable

func MCPOAuthAvailable() bool

func MCPOAuthService

func MCPOAuthService() (*mcpoauth.Service, error)

MCPOAuthService 的授权状态属于当前工作空间,管理员认证配置变化时撤销既有授权。

func ManageTemplateFiles

func ManageTemplateFiles(request TemplateFileRequest) (ret any, err error)

func ManageTemplateHTTPPermission

func ManageTemplateHTTPPermission(action, kind, path, avID, keyID, slot string) (bool, error)

ManageTemplateHTTPPermission 只从实际文件或字段解析来源,不接受客户端提供的授权 ID 或源码。

func MarkdownToMarkdownStrHTML

func MarkdownToMarkdownStrHTML(markdown string) string

func MarkdownToProtylePreviewHTML

func MarkdownToProtylePreviewHTML(markdown string) string

func MasterPasswordMigrationStatus

func MasterPasswordMigrationStatus() (pending bool, boxIDs []string)

MasterPasswordMigrationStatus 返回是否存在待完成的改密迁移及受影响的笔记本。

func MathDelimiterCompatibilityEnabled

func MathDelimiterCompatibilityEnabled() bool

MathDelimiterCompatibilityEnabled is scoped to external paste/import entry points. Stored documents and ordinary editor conversions continue to use the existing syntax.

func MergeConfJSON

func MergeConfJSON(base, patch []byte) ([]byte, error)

MergeConfJSON 按精确键名递归合并对象,数组和 null 整体替换,未知字段由入站契约决定是否接受。

func MergeConfSectionJSON

func MergeConfSectionJSON(current any, patch []byte) ([]byte, error)

MergeConfSectionJSON 基于当前配置段合并补丁,供模型更新和入站契约校验共用。

func MigrateAppearancePackages

func MigrateAppearancePackages() error

MigrateAppearancePackages 将第三方外观目录移入数据目录,已有目标优先,迁移成功后移除原目录。

func Mount

func Mount(boxID string) (alreadyMount bool, err error)

func MoveAttributeViewView

func MoveAttributeViewView(avID, blockID, viewID, previousViewID string) error

MoveAttributeViewView 将指定视图移到前置视图之后,空前置 ID 表示移到首位。

func MoveAttributeViewViewField

func MoveAttributeViewViewField(avID, blockID, viewID, keyID, previousKeyID string) error

MoveAttributeViewViewField 在载体所属数据库的指定视图内移动字段,并保留字段配置。

func MoveDocs

func MoveDocs(fromPaths []string, toBoxID, toPath string, callback any) (err error)

func MoveLocalShorthands

func MoveLocalShorthands(boxID string) (retIDs []string, err error)

func MutateAgentSnippet

func MutateAgentSnippet(action, id, revision string, value *AgentSnippetEdit) (*conf.Snippet, error)

MutateAgentSnippet 与已有全量保存共用锁,在校验版本后只修改指定片段,保留其他片段及顺序。 新片段默认禁用且不在发布服务中加载,更新不隐式改变类型或执行范围。

func MutateDocumentAddressingFiles

func MutateDocumentAddressingFiles(source, destination string, mutate func() error) error

MutateDocumentAddressingFiles 在移动、删除前记录完整源集合;目标路径按源的相对位置映射。

func NeedGenerateAssetsThumbnail

func NeedGenerateAssetsThumbnail(sourceImgPath string) bool

func NetAssets2LocalAssets

func NetAssets2LocalAssets(rootID string, onlyImg bool, originalURL string) (err error)

func NewAIProviderClient

func NewAIProviderClient(provider *conf.Provider, model string) *util.AIClient

NewAIProviderClient 按认证方式创建生成客户端,账户凭证不进入提供商配置。

func NewCalDAVHandler

func NewCalDAVHandler() http.Handler

NewCalDAVHandler 返回挂载在 /caldav 与 /.well-known/caldav 下的 CalDAV 处理器。

func NewCardDAVHandler

func NewCardDAVHandler() http.Handler

NewCardDAVHandler 返回挂载在 /carddav 与 /.well-known/carddav 下的 CardDAV 处理器。

func NewLute

func NewLute() (ret *lute.Lute)

func NormalizeAppConf

func NormalizeAppConf(c *AppConf)

NormalizeAppConf 对全部持久化配置段执行规范化,导入设置等整体写入路径使用。

func NotebookCryptoEnabled

func NotebookCryptoEnabled() bool

NotebookCryptoEnabled 返回加密笔记本功能是否处于可用的启用状态(线程安全)。

func NotebookCryptoMuLock

func NotebookCryptoMuLock()

NotebookCryptoMuLock 锁定 notebookCryptoMu,供 api 层读取一致的状态快照。

func NotebookCryptoMuUnlock

func NotebookCryptoMuUnlock()

NotebookCryptoMuUnlock 解锁 notebookCryptoMu。

func NotifyConfChanged

func NotifyConfChanged(namespace string)

NotifyConfChanged 统一发布配置提交通知,不在事件中携带配置或凭据。 客户端收到通知后按命名空间读取配置段,未知命名空间会让这次读取失败并向用户报错, 因此这里只记录日志而不广播。写入独立存储的端点不应走到这里。

func OCRAsset

func OCRAsset(ctx context.Context, path string) (string, []map[string]string, error)

OCRAsset 与自动任务共用内核识别和存储流程,失败时保留已有结果。

func OCRAssetsJob

func OCRAssetsJob()

func OCRModels

func OCRModels() []string

func OCRProviderAvailable

func OCRProviderAvailable(id string) bool

func OpenPluginPublishResource

func OpenPluginPublishResource(name, resource string) (*os.File, error)

func OpenPublishPackageFile

func OpenPublishPackageFile(c *gin.Context, requestPath string) (file *os.File, handled bool, err error)

OpenPublishPackageFile 在文件接口中处理公开文件和包资源,私有存储仍由默认拒绝策略保护。

func OpenRepoSnapshotFile

func OpenRepoSnapshotFile(fileID string) (title, content string, displayInText bool, updated int64, err error)

func ParseAddressPath

func ParseAddressPath(addressPath string) (addressBookPath string, addressID string, err error)

ParseAddressPath parses address path to address book path and address ID

func ParseCalendarObjectPath

func ParseCalendarObjectPath(objectPath string) (calendarPath string, objectID string, err error)

GetCardDavPathDepth parses

func ParseJWT

func ParseJWT(tokenString string) (token *jwt.Token, err error)

func ParseXAuthToken

func ParseXAuthToken(r *http.Request) *jwt.Token

func PatchViewState

func PatchViewState(key string, values map[string]any, removeKeys []string) (ret map[string]any, err error)

func PathCleanWithSlash

func PathCleanWithSlash(p string) string

PathCleanWithSlash 规范化 CalDAV/CardDAV 的 URL 路径;URL 路径只以 '/' 分隔,不能使用平台相关的 filepath。

func PathJoinWithSlash

func PathJoinWithSlash(elems ...string) string

PathJoinWithSlash joins the elements to a path with slash ('/') character

func PathsAffectSync

func PathsAffectSync(absPaths ...string) bool

PathsAffectSync 判断指定路径的变更是否会影响数据同步仓库。

func PdfListToCLinks(ctx *model.Context) (ret []model.LinkAnnotation, err error)

func PerformAttributeViewOperations

func PerformAttributeViewOperations(operations []*Operation) error

PerformAttributeViewOperations 使普通数据库 API 写入与编辑器共享自动化事务,保留 API 不生成撤销记录的约定。

func PerformBlockTransactions

func PerformBlockTransactions(transactions []*Transaction) error

PerformBlockTransactions 为外部批量块写入启用收集事件,并返回实际提交错误。

func PerformPreparedAttributeViewOperations

func PerformPreparedAttributeViewOperations(build func() ([]*Operation, error)) error

在事务串行区内读取字段和行身份并构造写入,避免校验后字段类型或绑定状态发生变化。

func PerformTransactionSync

func PerformTransactionSync(transaction *Transaction) (err error)

PerformTransactionSync 先执行已排队编辑,再同步执行事务并返回实际错误,同时发送事务错误通知。 主动跳过的操作保持成功语义,结构校验或提交失败仍返回错误。

func PerformTransactions

func PerformTransactions(transactions *[]*Transaction)

func PerformTxSync

func PerformTxSync(tx *Transaction) (err error)

PerformTxSync 同步执行单笔事务并返回错误,供需要获知落盘结果的调用方使用。 与异步入队的 PerformTransactions 不同,这里直接持有 flushLock 串行执行 performTx, 失败时返回原始错误(不转成推送消息),调用方可以保留待处理数据或回滚状态。

func PluginReloadPayload

func PluginReloadPayload(enabled, petalDisabled bool, revision uint64, changed bool) map[string]any

PluginReloadPayload 构造插件生命周期结果,响应与广播复用同一形态。

func PollPushQueue

func PollPushQueue()

func PrepareClipboardPasteAssets

func PrepareClipboardPasteAssets(boxID string, references []string) (result map[string]string, err error)

PrepareClipboardPasteAssets 在粘贴前复制普通附件并加密,全部完成后才返回替换链接。 生命周期租约覆盖整个批次,锁定等待写入或失败清理结束;源附件始终保持不变。

func PrepareEmbeddingSearch

func PrepareEmbeddingSearch()

PrepareEmbeddingSearch 仅检查表与配置并把 embeddingTableOk 置真,不启动后台索引循环。 供 CLI 一次性命令(如 search -m 4)使用:StartEmbeddingIndexer 是死循环,不能直接用于会立即退出的进程。

func PrepareEncryptedAssetForExternalOpen

func PrepareEncryptedAssetForExternalOpen(assetPath string) (string, error)

PrepareEncryptedAssetForExternalOpen 生成保留原始名称的受管明文副本,供外部程序打开或定位。 副本随笔记本锁定清理,外部程序的修改不会写回加密资源。

func PrepareNotebookArchive

func PrepareNotebookArchive(ids []string) (archiveID, downloadPath string, err error)

PrepareNotebookArchive 先保存可独立读取的完整归档,下载取消时不改变任何源文件。

func PreparePDFImage

func PreparePDFImage(ctx context.Context, source PDFImageSource, selection PDFImageSelection) (ret util.PreparedImage, err error)

func PreviewAttributeViewCollection

func PreviewAttributeViewCollection(avID, ruleID string, page int) (*apicontract.AVBlockCollectionPreview, error)

func PreviewAttributeViewTemplate

func PreviewAttributeViewTemplate(request apicontract.AVAutomationTemplatePreviewRequest) (*av.Value, error)

PreviewAttributeViewTemplate 使用独立快照和覆盖值,不执行写事务、不保存配置、不执行自动动作。

func PreviewCollectionRemoval

func PreviewCollectionRemoval(operations []*Operation, tagChanges []*apicontract.TagRemovalChange) (*apicontract.CollectionRemovalPreview, error)

func ProcessPDF

func ProcessPDF(id, p string, merge, removeAssets, watermark, exportAssets bool, mergeHeadingOptions ...MergeHeadingOptions) (err error)

func PublishVisibleDocPathFilter

func PublishVisibleDocPathFilter(boxID string, publishAccess PublishAccess) func(docPath string) bool

PublishVisibleDocPathFilter 返回发布读者可见文档路径的判定函数,口径与读者可见的发布视图一致: 隐藏、禁止发布以及加密笔记本中的文档都不计入读者统计。

func PurgeCloud

func PurgeCloud() (err error)

func PurgePublishAccess

func PurgePublishAccess()

func PurgeRepo

func PurgeRepo() (err error)

func PushCreate

func PushCreate(box *Box, p string, arg map[string]any)

func PushDocSortModeChanged

func PushDocSortModeChanged(scope, boxID, id, p string, sortMode *int)

PushDocSortModeChanged 广播会改变子文档有效排序方式的配置变更。

func PushPluginStorageDataChanged

func PushPluginStorageDataChanged(absPath, excludeApp string)

PushPluginStorageDataChanged 通知其他前端实例插件存储数据已变更。

func PushReloadAllEnabledPlugins

func PushReloadAllEnabledPlugins(enabled, petalDisabled bool, revision uint64, changed bool) map[string]any

PushReloadAllEnabledPlugins 向前端推送已启用插件的全局状态,并返回相同的权威状态供请求方应用。

func PushReloadPlugin

func PushReloadPlugin(uninstallPluginNameSet, unloadPluginNameSet, reloadPluginSet, dataChangePluginSet *hashset.Set,
	excludeApp, dataChangeReason string)

func PushReloadSnippet

func PushReloadSnippet(snippet *conf.Snpt)

func QueueAIMemoryConversation

func QueueAIMemoryConversation(sessionID, entryID string)

func QueueAIMemoryDatabaseSources

func QueueAIMemoryDatabaseSources(ids []string)

数据库文件变更只复核已有记忆引用的来源,不把整张表或所有笔记提交给模型。

func QueueAIMemorySources

func QueueAIMemorySources(ids []string)

QueueAIMemorySources 合并已提交修改,仅复核既有记忆;不从笔记变更新增或更新事实。

func ReadAssetBytesInBox

func ReadAssetBytesInBox(boxID, relativePath string) ([]byte, error)

ReadAssetBytesInBox 读取指定 box 内的资源文件字节。若 box 为加密笔记本则自动解密返回明文。 relativePath 形如 "assets/xxx.png",可带 ?box= 查询参数。

func ReadDocumentTitle

func ReadDocumentTitle(boxID, rootID string) (treenode.DocumentTitle, error)

ReadDocumentTitle 从同一笔记本的索引或已认证源属性取得摘要,不从可读路径提取末段。

func ReadTemplateFile

func ReadTemplateFile(p string) ([]byte, error)

ReadTemplateFile 在模板根目录内读取普通文件,禁止通过符号链接读取目录外的数据。

func RecentAIMemoryTasks

func RecentAIMemoryTasks() []apicontract.AIMemoryTaskData

最近任务只在本地管理员界面显示,不随模型工具结果外传,也不跨工作空间混用。

func Recover

func Recover(c *gin.Context)

func RecoverWorkspaceExit

func RecoverWorkspaceExit(pid int, startedAt int64, force bool) (int, string)

RecoverWorkspaceExit 仅接管指定批次且没有活动会话的桌面退出,允许用户确认后跳过同步,不触发安装更新。

func RefreshBacklink(id string)

func RefreshBoxDocFeature

func RefreshBoxDocFeature()

func RefreshCheckJob2H

func RefreshCheckJob2H()

func RefreshCheckJob6H

func RefreshCheckJob6H()

func RefreshHPathsJob

func RefreshHPathsJob()

RefreshHPathsJob 每次最多处理一个批次,普通编辑和索引刷新优先。

func RefreshLANSyncNetwork

func RefreshLANSyncNetwork()

RefreshLANSyncNetwork 在原生容器报告网络地址变化后刷新局域网同步服务。

func RefreshUser

func RefreshUser(token string) (ret *conf.User, err error)

func RegisterManagedEncryptedExport

func RegisterManagedEncryptedExport(boxID, kind, artifact string) string

RegisterManagedEncryptedExport 是 registerManagedEncryptedExport 的导出包装,供 api 层调用。

func ReindexAssetContent

func ReindexAssetContent()

func ReindexEmbedding

func ReindexEmbedding()

ReindexEmbedding 清空嵌入向量表并触发后台索引器重新计算所有块。异步执行:只入队任务后立即返回。

func ReindexFTS

func ReindexFTS()

func ReindexHistory

func ReindexHistory()

func ReindexMissingNormalBlock

func ReindexMissingNormalBlock(blockID string) error

ReindexMissingNormalBlock 在请求取得加密笔记本租约前,仅恢复普通笔记本中缺失的块索引。

func RejectNonCanonicalDAVPath

func RejectNonCanonicalDAVPath(next http.Handler) http.Handler

RejectNonCanonicalDAVPath 拒绝含 "."、".." 段、反斜杠或 NUL 的请求路径。 net/http 与 gin 都不清理请求路径,后端清理后可能跳到另一个 DAV 命名空间;Windows 上反斜杠也是路径分隔符。

func RejectNonCanonicalWebDAVPath

func RejectNonCanonicalWebDAVPath(next http.Handler) http.Handler

RejectNonCanonicalWebDAVPath 与 RejectNonCanonicalDAVPath 相同,但只在 Windows 上拒绝反斜杠:WebDAV 直接映射工作空间文件, 其他系统上反斜杠是文件名中的普通字符。

func ReleaseBoxReadLock

func ReleaseBoxReadLock(boxID string)

ReleaseBoxReadLock 释放 HoldBoxReadLock 获取的 box 读锁。

func ReleaseEncryptedBoxOperation

func ReleaseEncryptedBoxOperation(boxID string)

ReleaseEncryptedBoxOperation 释放响应级准入租约。

func ReleaseExportArtifactLease

func ReleaseExportArtifactLease(leaseID string)

ReleaseExportArtifactLease 释放导出产物租约;重复调用不会产生副作用。

func ReleaseMobileExportLease

func ReleaseMobileExportLease(leaseID string)

ReleaseMobileExportLease 释放移动端导出租约;重复调用不会产生副作用。

func RelinkAsset

func RelinkAsset(oldPath, newPath string, dryRun bool) (apicontract.AssetReferencesData, error)

func RelinkAssetWithContext

func RelinkAssetWithContext(ctx context.Context, oldPath, newPath string, dryRun bool) (apicontract.AssetReferencesData, error)

func ReloadAttrView

func ReloadAttrView(avID string)

ReloadAttrView 用于重新加载属性视图。

func ReloadFiletree

func ReloadFiletree()

func ReloadProtyle

func ReloadProtyle(rootID string)

func ReloadTag

func ReloadTag()

func RemoveAIEditorAction

func RemoveAIEditorAction(id string) (err error)

func RemoveAttributeViewBlock

func RemoveAttributeViewBlock(srcIDs []string, avID string) (err error)

func RemoveAttributeViewKey

func RemoveAttributeViewKey(avID, keyID string, removeRelationDest bool) (err error)

func RemoveAttributeViewView

func RemoveAttributeViewView(avID, blockID, viewID string) error

RemoveAttributeViewView 删除指定视图,保留至少一个视图并更新镜像数据库块。

func RemoveBookmark

func RemoveBookmark(bookmark string) (err error)

func RemoveBox

func RemoveBox(boxID string) (err error)

func RemoveCloudRepoTag

func RemoveCloudRepoTag(tag string) (err error)

func RemoveCloudShorthands

func RemoveCloudShorthands(ids []string) (err error)

func RemoveCloudSyncDir

func RemoveCloudSyncDir(name string) (err error)

func RemoveCriterion

func RemoveCriterion(name string) (err error)

func RemoveDeck

func RemoveDeck(deckID string) (err error)

func RemoveDoc

func RemoveDoc(boxID, p string) error

func RemoveDocs

func RemoveDocs(paths []string) error

func RemoveIndexes

func RemoveIndexes(paths []string)

func RemoveLANSyncPeer

func RemoveLANSyncPeer(instance string) bool

func RemoveLocalStorageVals

func RemoveLocalStorageVals(keys []string) (err error)

func RemoveOutlineStorage

func RemoveOutlineStorage(docID string) (err error)

func RemoveSnippet

func RemoveSnippet(id string) (ret *conf.Snippet, err error)

func RemoveTag

func RemoveTag(label string) (err error)

func RemoveTagSnapshot

func RemoveTagSnapshot(tag string) (err error)

func RemoveTemplate

func RemoveTemplate(p string) (err error)

RemoveTemplate 删除模板文件,路径必须限定在 <data>/templates/ 目录内,防止任意文件被删除

func RemoveUnusedAsset

func RemoveUnusedAsset(p string) (ret string, err error)

func RemoveUnusedAssets

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

func RemoveUnusedAttributeView

func RemoveUnusedAttributeView(id string) (err error)

func RemoveUnusedAttributeViews

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

func RemoveUnusedEncryptedBoxAssets

func RemoveUnusedEncryptedBoxAssets(ctx context.Context, boxID string, paths []string) (removed []string, err error)

RemoveUnusedEncryptedBoxAssets 重新扫描用户确认的候选,完整备份后删除,失败时恢复全部原文件。

func RemoveViewState

func RemoveViewState(key string) (err error)

func RenameAsset

func RenameAsset(oldPath, newName string) (newPath string, err error)

func RenameBookmark

func RenameBookmark(oldBookmark, newBookmark string) (err error)

func RenameBox

func RenameBox(boxID, name string) (err error)

func RenameDeck

func RenameDeck(deckID, name string) (err error)

func RenameDoc

func RenameDoc(boxID, p, title string) (err error)

func RenameTag

func RenameTag(oldLabel, newLabel string) (err error)

func RenderAttributeView

func RenderAttributeView(blockID, avID, viewID, query string, page, pageSize int, groupPaging map[string]any, createIfNotExist, ignoreRows bool) (viewable av.Viewable, attrView *av.AttributeView, err error)

func RenderDynamicIconContentTemplate

func RenderDynamicIconContentTemplate(c *gin.Context, content, id string) (ret string)

RenderDynamicIconContentTemplate 渲染动态图标中的模板内容。 调用方必须自行完成授权:只读角色会失去按块 ID 读取工作区数据的模板函数, 并且模板源码只能取自工作区中已保存的图标属性,避免绕过发布访问控制。

func RenderGoTemplate

func RenderGoTemplate(templateContent string) (ret string, err error)

func RenderGoTemplateAt

func RenderGoTemplateAt(templateContent string, now time.Time) (ret string, err error)

RenderGoTemplateAt 使用固定时间渲染 Go 模板,保证同一次业务操作中的多个模板结果一致。

func RenderGoTemplateAtInBox

func RenderGoTemplateAtInBox(templateContent string, now time.Time, boxID string) (ret string, err error)

func RenderGoTemplateInBox

func RenderGoTemplateInBox(templateContent, boxID string) (ret string, err error)

func RenderHistoryAttributeView

func RenderHistoryAttributeView(avID, viewID, carrierViewID, query string, page, pageSize int, groupPaging map[string]any, created string, calendarRanges ...*av.CalendarRange) (viewable av.Viewable, attrView *av.AttributeView, err error)

func RenderHistoryAttributeViewWithOptions

func RenderHistoryAttributeViewWithOptions(avID, viewID, carrierViewID, query string, page, pageSize int, groupPaging map[string]any, created string, options AttributeViewRenderOptions) (viewable av.Viewable, attrView *av.AttributeView, err error)

func RenderRepoSnapshotAttributeView

func RenderRepoSnapshotAttributeView(indexID, avID, viewID, carrierViewID string, calendarRanges ...*av.CalendarRange) (viewable av.Viewable, attrView *av.AttributeView, err error)

func RenderRepoSnapshotAttributeViewWithOptions

func RenderRepoSnapshotAttributeViewWithOptions(indexID, avID, viewID, carrierViewID string, options AttributeViewRenderOptions) (viewable av.Viewable, attrView *av.AttributeView, err error)

func RenderRepoSnapshotAttributeViewWithPagingOptions

func RenderRepoSnapshotAttributeViewWithPagingOptions(indexID, avID, viewID, carrierViewID, query string, page, pageSize int, groupPaging map[string]any, options AttributeViewRenderOptions) (viewable av.Viewable, attrView *av.AttributeView, err error)

func RenderTemplate

func RenderTemplate(p, id string, preview bool) (tree *parse.Tree, dom string, err error)

func ResetFlashcards

func ResetFlashcards(typ, id, deckID string, blockIDs []string) error

func ResetRepo

func ResetRepo() (err error)

func ResetSettings

func ResetSettings() error

ResetSettings 仅替换普通偏好。磁盘提交前不发布内存状态,敏感配置不经过前端往返。

func ResetVirtualBlockRefCache

func ResetVirtualBlockRefCache()

func ResolveAIProviderHeaders

func ResolveAIProviderHeaders(provider *conf.Provider) map[string]string

ResolveAIProviderHeaders 在创建请求客户端时解析密钥和变量,保留配置中的引用文本。 密钥只允许解析到其允许主机列表中的供应商地址,跨源重定向由请求传输层隔离。

func ResolveAssetPathWithMissingLeaf

func ResolveAssetPathWithMissingLeaf(absPath string) (string, error)

ResolveAssetPathWithMissingLeaf 校验尚未下载的路径,已存在的父目录仍须通过符号链接校验。

func ResolveBootAppearanceAsset

func ResolveBootAppearanceAsset(provider, appearanceID, relativePath string) (filePath, contentType string, err error)

ResolveBootAppearanceAsset 校验并解析当前启动页外观中的静态资源,不重复扫描已经在清单请求中校验的整个外观包。

func ResolveDataAssetPath

func ResolveDataAssetPath(assetPath string) (relativePath, absPath string, err error)

ResolveDataAssetPath 解析 data 相对资源路径,并确保目标位于全局或普通笔记本的资源目录中。

func ResolveDocCreateSaveLocation

func ResolveDocCreateSaveLocation(currentBoxID string) (boxID, pathTemplate string)

ResolveDocCreateSaveLocation 按笔记本配置和全局配置解析新建文档的存放位置。

func ResolveDocPath

func ResolveDocPath(boxID, startKind string, startID *string, segments []string) (*treenode.ResolvedDocumentPath, error)

ResolveDocPath 逐级精确匹配标题,不拆分标题内的字符,也不从同名候选中任取文档。

func ResolveDocTreeSortMode

func ResolveDocTreeSortMode(boxID, listPath string) (sortMode int, err error)

ResolveDocTreeSortMode 按当前父文档、最近祖先文档、笔记本和全局配置的顺序解析子文档排序方式。

func ResolveDocVersionBoxID

func ResolveDocVersionBoxID(ref *DocVersionRef) (string, error)

ResolveDocVersionBoxID 返回文档版本引用中明确记录的加密笔记本 ID。

func ResolveHistoryAttributeViewBoxID

func ResolveHistoryAttributeViewBoxID(avID, created string) (string, error)

ResolveHistoryAttributeViewBoxID 返回历史属性视图的唯一加密笔记本上下文。

func ResolveLegacyDocumentPath

func ResolveLegacyDocumentPath(boxID, hpath string, create bool) (*treenode.BlockTree, error)

ResolveLegacyDocumentPath requires one unambiguous, structurally clean target. Root paths retain their existing meaning. Callers acting on the result must still use the normal source-operation checks for moves, creates and reads.

func ResolveLivePhotoAssetPath

func ResolveLivePhotoAssetPath(assetPath string) (string, error)

ResolveLivePhotoAssetPath 沿用普通资源的真实路径校验,加密资源由带 box 的解析器验证边界。

func ResolveManagedEncryptedExport

func ResolveManagedEncryptedExport(relativePath string) (boxID, artifact string, ok bool)

ResolveManagedEncryptedExport 返回仍有效的加密导出产物,未登记、已撤销或过期的路径均不可下载。

func ResolveReplayDuplicateIds

func ResolveReplayDuplicateIds(tx *Transaction)

ResolveReplayDuplicateIds 在 undo/redo 重放事务前解决块 ID 冲突。 场景:剪切块 X 后粘贴到别处(保留原 ID),再撤销剪切会 insert X,而 X 已存在于粘贴处,产生重复 ID。 这里检查实际重放的 insert 操作;若其引入的 ID 在块树中已存在,且不会被前置 delete 清理, 则在当前重放操作的 ID、ParentID、PreviousID、NextID、BlockIDs 与 Data 内联 ID 中统一替换为新 ID。

func ResolveRepoFileBoxID

func ResolveRepoFileBoxID(fileID string) (boxID string, err error)

ResolveRepoFileBoxID 返回仓库文件路径中明确记录的加密笔记本 ID。

func ResolveRepoSnapshotAttributeViewBoxID

func ResolveRepoSnapshotAttributeViewBoxID(indexID, avID string) (string, error)

ResolveRepoSnapshotAttributeViewBoxID 返回快照属性视图的唯一加密笔记本上下文。

func ResolveTemplatePath

func ResolveTemplatePath(p string) (string, error)

ResolveTemplatePath 返回模板根目录内的绝对路径,接受绝对路径或相对模板根目录的路径。 此函数只校验路径边界,文件读写通过根目录句柄另行限制符号链接。

func ResolveUnusedDataAssetPath

func ResolveUnusedDataAssetPath(assetPath string) (relativePath, absPath string, err error)

ResolveUnusedDataAssetPath 解析可单独删除的资源路径,允许显式关闭 Android 保活通知。

func RespondTemplateHTTP

func RespondTemplateHTTP(id, confirmation, app, sessionID string, approved bool, permissionScope ...string) bool

RespondTemplateHTTP 只消费当前等待的一次回答;旧确认及重复回答无副作用。

func RetryFailedEmbedding

func RetryFailedEmbedding()

RetryFailedEmbedding 删除所有失败块的行,使其立即回到主循环重嵌。异步执行:只入队任务后立即返回。 与 ReindexEmbedding 的区别:只删 fail_count>0 的失败块(embedding 为空,无有效向量),已成功的向量不动。

func RevalidateAIMemorySources

func RevalidateAIMemorySources(ctx context.Context, changedIDs []string) error

func ReviewAttributeViewCollection

func ReviewAttributeViewCollection(avID string, page int, status string) (*apicontract.AVCollectionReview, error)

func ReviewFlashcard

func ReviewFlashcard(deckID, cardID string, rating riff.Rating, reviewedCardIDs []string) (err error)

func RevokeAllTemplateHTTPPermissions

func RevokeAllTemplateHTTPPermissions() error

func RevokeManagedEncryptedExportsForBox

func RevokeManagedEncryptedExportsForBox(boxID string)

RevokeManagedEncryptedExportsForBox 使指定笔记本的所有导出下载链接立即失效。

func RevokeTemplateHTTPHandoff

func RevokeTemplateHTTPHandoff(token, app, sessionID string)

RevokeTemplateHTTPHandoff 只允许原窗口撤销其预览凭证。

func RevokeTemplateHTTPSource

func RevokeTemplateHTTPSource(id string) error

func RollbackAssetsHistory

func RollbackAssetsHistory(historyPath string) (err error)

func RollbackAttributeViewHistory

func RollbackAttributeViewHistory(historyPath string) (err error)

func RollbackDocHistory

func RollbackDocHistory(historyPath string) (err error)

func RollbackNotebookHistory

func RollbackNotebookHistory(historyPath string) (err error)

func RollbackRepoSnapshotFile

func RollbackRepoSnapshotFile(fileID string) (err error)

func RunAttributeViewAutomation

func RunAttributeViewAutomation(ctx context.Context, avID, blockID, ruleID string, runtime *templatehttp.Execution) error

func RunManualAutomationRows

func RunManualAutomationRows(ctx context.Context, request apicontract.RunAttributeViewAutomationRequest, app, session string,
	runtime *templatehttp.Execution, committed func(*Transaction)) (*apicontract.AVAutomationRunResult, error)

func SaveMetaData

func SaveMetaData[T []*CalendarMetaData | []*AddressBookMetaData | map[string][]string](metaData T, metaDataFilePath string) error

func SavePluginPublishData

func SavePluginPublishData(name string, data map[string]json.RawMessage) error

func ScheduleAIMemoryOverview

func ScheduleAIMemoryOverview()

ScheduleAIMemoryOverview 合并显式管理的概览刷新;无独立模型配置时保留待更新状态。

func SearchAssetsByName

func SearchAssetsByName(keyword string, exts []string) (ret []*cache.Asset)

func SearchAssetsByNamePage

func SearchAssetsByNamePage(keyword string, exts []string, match *AssetSearchMatch, page, pageSize int, includeMetadata bool) (ret []*cache.Asset, err error)

SearchAssetsByNamePage 筛选资源,可合并图片元数据命中,并按稳定顺序返回指定页。

func SearchAttributeViewRelationKey

func SearchAttributeViewRelationKey(avID, keyword string) (ret []*av.Key)

func SearchAttributeViewRollupDestKeys

func SearchAttributeViewRollupDestKeys(avID, keyword string) (ret []*av.Key)

func SearchDocDisplayFields

func SearchDocDisplayFields(doc map[string]string) (typ, id, name string)

SearchDocDisplayFields 把 SearchDocs 返回的单条结果拆成展示用的类型、ID 与名称。 路径为 "/" 时该条结果表示笔记本根,类型为 NOTEBOOK;其余为 DOCUMENT,名称取文档路径去掉 .sy 后缀。

func SearchDocs

func SearchDocs(keyword string, flashcard bool, excludeIDs []string) (ret []map[string]string)

func SearchTags

func SearchTags(keyword string) (ret []string)

func SectionSpecByNamespace

func SectionSpecByNamespace(namespace string) (registeredSection, bool)

SectionSpecByNamespace 返回当前工作空间的注册项,不缓存可替换的 AppConf 地址。

func SetAccessCodeSession

func SetAccessCodeSession(workspaceSession *util.WorkspaceSession, accessAuthCode string)

SetAccessCodeSession 将会话绑定到指定的锁屏密码,会话只保存密码的 HMAC 摘要。

func SetAttrViewFilters

func SetAttrViewFilters(avID, blockID string, data []any) (err error)

SetAttrViewFilters 用新的过滤规则数组整体替换指定视图的过滤规则,并持久化。 data 为 JSON 反序列化前的 []any(通常是前端传来的过滤节点树)。

func SetAttrViewSorts

func SetAttrViewSorts(avID, blockID string, data []any) (err error)

SetAttrViewSorts 用新的排序规则数组整体替换指定视图的排序规则,并持久化。 data 为 JSON 反序列化前的 []any。

func SetAttributeViewBlockVisibleViews

func SetAttributeViewBlockVisibleViews(avID, blockID string, viewIDs []string) error

SetAttributeViewBlockVisibleViews 通过现有事务保存指定数据库块的可见视图集合。

func SetAttributeViewContextFilter

func SetAttributeViewContextFilter(blockID, avID, keyID string) (ret *av.AttributeViewContextFilter, err error)

SetAttributeViewContextFilter 设置物理数据库块独有的上下文筛选配置,keyID 为空时清除。

func SetAttributeViewGroup

func SetAttributeViewGroup(avID, blockID string, group *av.ViewGroup) (err error)

func SetAttributeViewKeyTemplate

func SetAttributeViewKeyTemplate(avID, keyID, templateContent string) (err error)

SetAttributeViewKeyTemplate 设置模板字段公式,复用字段模板保存和分组更新逻辑。

func SetAttributeViewViewFilters

func SetAttributeViewViewFilters(avID, blockID, viewID, revision string, filters []*av.ViewFilter) error

SetAttributeViewViewFilters 用完整规则树替换指定视图的筛选配置。

func SetAttributeViewViewGroup

func SetAttributeViewViewGroup(avID, blockID, viewID, revision string, group *av.ViewGroup) error

SetAttributeViewViewGroup 设置指定视图的分组配置,空字段清除分组。

func SetAttributeViewViewSorts

func SetAttributeViewViewSorts(avID, blockID, viewID, revision string, sorts []*av.ViewSort) error

SetAttributeViewViewSorts 用完整规则数组替换指定视图的排序配置。

func SetAutoLockMinutes

func SetAutoLockMinutes(minutes int)

SetAutoLockMinutes 设置加密笔记本自动锁定闲置分钟数。0 表示禁用。

func SetBazaarPackageRating

func SetBazaarPackageRating(ctx context.Context, pkgType, packageName string, userRating int) (rating *bazaar.PackageRating,
	ratingAvailable bool, retUserRating int, err error)

SetBazaarPackageRating 设置或取消已安装官方包的当前用户评分。

func SetBlockAttrs

func SetBlockAttrs(id string, nameValues map[string]string) (err error)

func SetBlockReminder

func SetBlockReminder(id, timed string) (err error)

func SetBoxIcon

func SetBoxIcon(boxID, icon string)

func SetCloudBlockReminder

func SetCloudBlockReminder(id, data string, timed int64) (err error)

func SetCloudReminder

func SetCloudReminder(id, content, timed string) (err error)

func SetCloudSyncDir

func SetCloudSyncDir(name string) error

func SetCriterion

func SetCriterion(criterion *Criterion) (err error)

func SetDatabaseBlockView

func SetDatabaseBlockView(blockID, avID, viewID string) (err error)

func SetDatabaseBlockVisibleViews

func SetDatabaseBlockVisibleViews(blockID, avID string, viewIDs []string) (err error)

func SetEncryptedNotebookFollowSystemLock

func SetEncryptedNotebookFollowSystemLock(enabled bool)

SetEncryptedNotebookFollowSystemLock 将锁屏策略保存在本机系统配置中,不参与密钥备份认证。

func SetFlashcardsDueTime

func SetFlashcardsDueTime(cardDues []*SetFlashcardDueTime) (err error)

func SetIcon

func SetIcon(icon string) error

func SetLocalStorage

func SetLocalStorage(val map[string]any) (err error)

func SetLocalStorageVals

func SetLocalStorageVals(keyVals map[string]any) (setKeyVals map[string]any, err error)

func SetOCRAssetText

func SetOCRAssetText(path, text string)

func SetOutlineStorage

func SetOutlineStorage(docID string, val map[string]any) (err error)

func SetPluginPublishDataGrant

func SetPluginPublishDataGrant(name string, fields []string, enabled bool) error

func SetPublishAccess

func SetPublishAccess(inputPublishAccess PublishAccess) (err error)

func SetPublishAuthCookie

func SetPublishAuthCookie(c *gin.Context, ID string, password string)

func SetRepoSnapshotMemo

func SetRepoSnapshotMemo(id, memo string) error

func SetSnippet

func SetSnippet(snippets []*conf.Snippet, expectedRevision ...string) (err error)

SetSnippet 的可选版本参数用于全量保存的并发校验;省略时保留历史接口行为。

func SetSyncAssetDownloadMode

func SetSyncAssetDownloadMode(mode int) error

func SetSyncEnable

func SetSyncEnable(b bool)

func SetSyncGenerateConflictDoc

func SetSyncGenerateConflictDoc(b bool)

func SetSyncInterval

func SetSyncInterval(interval int)

func SetSyncLAN

func SetSyncLAN(enabled bool, maxConcurrentReqs int)

func SetSyncMode

func SetSyncMode(mode int)

func SetSyncPerception

func SetSyncPerception(enabled bool)

func SetSyncProvider

func SetSyncProvider(provider int, completeAssets bool) (err error)

func SetSyncProviderLocal

func SetSyncProviderLocal(local *conf.Local) (err error)

func SetSyncProviderS3

func SetSyncProviderS3(s3 *conf.S3) (err error)

func SetSyncProviderWebDAV

func SetSyncProviderWebDAV(webdav *conf.WebDAV) (err error)

func SetTheme

func SetTheme(theme string, modes []int, appearanceMode string) (err error)

SetTheme 校验全部参数后一次性替换外观配置段,任一参数无效时保持原配置不变。

func SetUpdateChannel

func SetUpdateChannel(channel string) error

SetUpdateChannel 校验并保存应用级更新通道。

func SkipReviewFlashcard

func SkipReviewFlashcard(deckID, cardID string) (err error)

func SnapshotCreatedInRange

func SnapshotCreatedInRange(created, startTime, endTime int64) bool

func SnippetRevision

func SnippetRevision(snippet *conf.Snippet) string

SnippetRevision 覆盖完整片段,确认期间的内容和开关变化都使修改失效。

func SnippetsRevision

func SnippetsRevision(snippets []*conf.Snippet) string

SnippetsRevision 包含顺序和全部字段;缺失配置与空列表表示相同的初始状态。

func SortAttributeViewKey

func SortAttributeViewKey(avID, keyID, previousKeyID string) (err error)

func SortAttributeViewViewKey

func SortAttributeViewViewKey(avID, viewID, keyID, previousKeyID string) (err error)

SortAttributeViewViewKey 调整指定视图的字段顺序,空视图 ID 使用首个视图。

func StartEmbeddingIndexer

func StartEmbeddingIndexer()

func StartFreeTrial

func StartFreeTrial() (err error)

func StartLivePhotoPreview

func StartLivePhotoPreview(assetPath string, clientEncode bool) (livephoto.Session, error)

StartLivePhotoPreview 为在途任务取得独立租约,笔记本锁定先取消任务再排空租约。

func StartPushQueueConsumer

func StartPushQueueConsumer()

func StatJob

func StatJob()

func StoreAssetForBox

func StoreAssetForBox(boxID, assetDirPath, originalName string, data []byte) (diskName string, err error)

StoreAssetForBox 统一资产写入入口:根据 boxID 决定加密/明文写入,返回磁盘文件名(不含路径前缀)。 加密 box:生成脱敏名,把原始名称和内容写入单文件加密容器,再通过 filelock.WriteFile 落盘。 普通 box:util.AssetName 生成名 → filelock.WriteFile 明文写入 boxID 为空时按普通 box 处理(写入全局 assets)。

func SwapBlockRef

func SwapBlockRef(refID, defID string, includeChildren, originalToEmbed bool) (err error)

func SyncData

func SyncData(byHand bool) error

func SyncDataBeforeEnableEncryptedNotebook

func SyncDataBeforeEnableEncryptedNotebook() error

SyncDataBeforeEnableEncryptedNotebook 在启用加密笔记本前执行一次完整同步。 未启用数据同步时直接返回;已启用数据同步时,任何同步失败都会阻止继续创建新的密钥体系。

func SyncDataDownload

func SyncDataDownload(decisions ...SyncSourceDecision) (err error)

func SyncDataJob

func SyncDataJob()

func SyncDataUpload

func SyncDataUpload(decisions ...SyncSourceDecision) (err error)

func SystemOIDCConfig

func SystemOIDCConfig(value apicontract.SystemOIDC) *conf.OIDC

func SystemOIDCPayload

func SystemOIDCPayload(value *conf.OIDC) *apicontract.SystemOIDC

func TagSnapshot

func TagSnapshot(id, name string) (err error)

func TestSyncProviderLocal

func TestSyncProviderLocal(draft *conf.Local) (kind, msg string)

TestSyncProviderLocal 在候选端点中创建独占的临时目录并验证读写,始终清理,不修改配置。

func TestSyncProviderS3

func TestSyncProviderS3(s3 *conf.S3) (kind, msg string)

TestSyncProviderS3 用候选配置写入、列举并删除探针对象,确认读写与列举落在同一个对象键上。 只访问云端,不读取或保存用户配置;云端为空(首次配置)时同样适用,写入先于列举,不依赖任何已有对象。

func TestSyncProviderWebDAV

func TestSyncProviderWebDAV(draft *conf.WebDAV, cloudName string) (kind, msg string)

TestSyncProviderWebDAV 仅使用草稿配置,验证集合、目录创建和探针读写,不读取或保存同步配置。

func Timing

func Timing(c *gin.Context)

func TouchRefUsed

func TouchRefUsed(defBlockIDs []string)

TouchRefUsed 在用户真实插入引用时刷新目标块的最近引用时间。该时间独立于 refs 表的重建机制, 仅在事务处理(真实编辑)时写入,用于稳定块引"最近引用"排序。

func TouchUnlockedEncryptedBoxes

func TouchUnlockedEncryptedBoxes()

TouchUnlockedEncryptedBoxes 由真实用户交互或 headless 客户端的显式保活调用,刷新当前已解锁笔记本的闲置计时。

func TransferBlockRef

func TransferBlockRef(fromID, toID string, refIDs []string) (err error)

func TranslateAIMemoryOverview

TranslateAIMemoryOverview 不改变任何事实,仅为明确启用记忆的管理员生成当前界面语言的显示副本。

func TriggerOnboardingIfEmpty

func TriggerOnboardingIfEmpty()

TriggerOnboardingIfEmpty 在最后一个笔记本被删除后重置状态,并通知已连接的界面立即重新进入引导。

func UninstallPackage

func UninstallPackage(pkgType, packageName string) error

func UnlockAndMountBox

func UnlockAndMountBox(boxID, password string, boxEnc *conf.BoxEncryption) (alreadyMount bool, err error)

UnlockAndMountBox 在同一个笔记本转换锁内完成解锁和挂载,挂载失败时回滚本次新建的解锁状态。

func UnlockBox

func UnlockBox(boxID string, password string, boxEnc *conf.BoxEncryption) (err error)

UnlockBox 用主密码派生 KEK,解出该笔记本的 DEK 并缓存。KEK 用完即弃,不全局缓存。 每次调用都跑一次 Argon2id(约 1 秒),严格满足"每笔记本单独解锁"语义。

func Unmount

func Unmount(boxID string)

func UpdateAPIConf

func UpdateAPIConf(mutate func(*conf.API)) *conf.API

UpdateAPIConf 以快照方式更新 API 配置段。

func UpdateAppearanceConf

func UpdateAppearanceConf(mutate func(*conf.Appearance)) *conf.Appearance

UpdateAppearanceConf 以快照方式更新外观配置段。

func UpdateAttributeViewCell

func UpdateAttributeViewCell(tx *Transaction, avID, keyID, itemID string, valueData any) (val *av.Value, err error)

func UpdateAttributeViewKeyConfig

func UpdateAttributeViewKeyConfig(avID, keyID string, config map[string]any) (err error)

UpdateAttributeViewKeyConfig 每次修改一个字段配置,先校验参数,再复用界面操作维护关联数据。

func UpdateAttributeViewView

func UpdateAttributeViewView(avID, blockID, viewID string, update AttributeViewViewUpdate) error

UpdateAttributeViewView 通过现有事务修改指定视图的元数据。

func UpdateBazaarConf

func UpdateBazaarConf(mutate func(*conf.Bazaar)) *conf.Bazaar

UpdateBazaarConf 以快照方式更新集市配置段。

func UpdateBazaarPackage

func UpdateBazaarPackage(pkgType, packageName, frontend string) error

UpdateBazaarPackage 使用在线集市数据更新本地集市包

func UpdateBazaarPackageContext

func UpdateBazaarPackageContext(ctx context.Context, pkgType, packageName, frontend string) error

UpdateBazaarPackageContext 保留在线索引的更新限制,并传递取消信号到安装提交前。

func UpdateEditorConf

func UpdateEditorConf(mutate func(*conf.Editor)) *conf.Editor

UpdateEditorConf 以快照方式更新编辑器配置段。

func UpdateEmbedBlock

func UpdateEmbedBlock(id, content string) (err error)

func UpdateGraphConf

func UpdateGraphConf(mutate func(*conf.Graph) bool) *conf.Graph

UpdateGraphConf 以快照方式更新关系图配置段;mutate 返回 false 表示没有变化。

func UpdateOnboardingConf

func UpdateOnboardingConf(mutate func(*conf.Onboarding)) *conf.Onboarding

UpdateOnboardingConf 以快照方式更新首次使用引导状态。

func UpdatePinnedDocs

func UpdatePinnedDocs(ids []string, action, targetID string, after bool) error

根层顺序独立于源文档顺序,按相对位置更新以保留其他窗口新增的入口。

func UpdatePublishConf

func UpdatePublishConf(mutate func(*conf.Publish)) *conf.Publish

UpdatePublishConf 以快照方式更新发布服务配置段。

func UpdateRecentDocCloseTime

func UpdateRecentDocCloseTime(rootID string) (err error)

UpdateRecentDocCloseTime 更新文档关闭时间

func UpdateRecentDocOpenTime

func UpdateRecentDocOpenTime(rootID string) (err error)

UpdateRecentDocOpenTime 更新文档打开时间(只在第一次从文档树加载到页签时调用)

func UpdateRecentDocViewTime

func UpdateRecentDocViewTime(rootID string) (err error)

UpdateRecentDocViewTime 更新文档浏览时间

func UpdateRepoConf

func UpdateRepoConf(mutate func(*conf.Repo)) *conf.Repo

UpdateRepoConf 以快照方式更新数据仓库配置段。

func UpdateServerAddrs

func UpdateServerAddrs(serverAddrs []string) bool

UpdateServerAddrs 更新当前可用的本地服务器地址,返回地址是否发生变化。

func UpdateStatConf

func UpdateStatConf(mutate func(*conf.Stat)) *conf.Stat

UpdateStatConf 以快照方式更新统计配置段。

func UpdateSyncConf

func UpdateSyncConf(mutate func(*conf.Sync)) *conf.Sync

UpdateSyncConf 以快照方式更新同步配置段。

func UpdateSystemConf

func UpdateSystemConf(mutate func(*conf.System)) *conf.System

UpdateSystemConf 以快照方式更新系统配置段。

func UpdateTagConf

func UpdateTagConf(mutate func(*conf.Tag)) *conf.Tag

UpdateTagConf 以快照方式更新标签面板配置段。

func Upload

func Upload(c *gin.Context)

func UploadAssets2CloudByAssetsPathsWithApp

func UploadAssets2CloudByAssetsPathsWithApp(assetPaths []string, ignorePushMsg bool, app string) (count int, err error)

UploadAssets2CloudByAssetsPathsWithApp 在同一实例显示、更新和清除本次上传的提示。

func UploadAssets2CloudWithApp

func UploadAssets2CloudWithApp(id string, ignorePushMsg bool, app string) (count int, err error)

UploadAssets2CloudWithApp 将块资源上传提示限定到发起实例;空标识保留广播。

func UploadCloudSnapshot

func UploadCloudSnapshot(tag, id string) (err error)

func UpsertIndexes

func UpsertIndexes(paths []string)

func UseActivationcode

func UseActivationcode(code string) (err error)

func VacuumDataIndex

func VacuumDataIndex()

func ValidateBacklinkDatabaseFilter

func ValidateBacklinkDatabaseFilter(filter *BacklinkSourceFilter, boxID string) error

func ValidateCreateDoc

func ValidateCreateDoc(boxID, p, title string) error

ValidateCreateDoc 校验文档创建参数,不写入文件或索引。

func ValidateDocumentTitle

func ValidateDocumentTitle(format, text string) error

ValidateDocumentTitle 校验新协议的完整输入,不通过截断、修剪或字符替换悄悄改变标题。

func ValidateFlashcardBlockIDs

func ValidateFlashcardBlockIDs(blockIDs []string) error

ValidateFlashcardBlockIDs 只允许普通笔记本中可确认存在的块进入全局闪卡存储。

func ValidateFlashcardTransactions

func ValidateFlashcardTransactions(transactions []*Transaction) error

ValidateFlashcardTransactions 在事务入队前校验所有闪卡操作。

func ValidateImportFromLocalPath

func ValidateImportFromLocalPath(boxID, localPath, toPath string) error

ValidateImportFromLocalPath 校验 Markdown 导入来源和目标,不写入导入数据。

func ValidateNotebookDocumentTarget

func ValidateNotebookDocumentTarget(boxID string, target *conf.DocumentTarget) error

func ValidateOIDCConfiguration

func ValidateOIDCConfiguration(config *conf.OIDC) error

func ValidateOIDCConfigurationChange

func ValidateOIDCConfigurationChange(ctx context.Context, config *conf.OIDC, requireRemoteRedirect,
	hasAlternativeAuthentication, bypassAuthentication bool) error

func ValidateOIDCMobileConfiguration

func ValidateOIDCMobileConfiguration(config *conf.OIDC) error

func ValidateOIDCProviderConfiguration

func ValidateOIDCProviderConfiguration(ctx context.Context, config *conf.OIDC) error

func ValidateUnusedAttributeView

func ValidateUnusedAttributeView(id string) error

func WaitForTransactions

func WaitForTransactions(transactions []*Transaction)

WaitForTransactions 等待已提交批次的写入、撤销记录和清理完成,不等待后续事务到达。

func WatchAssets

func WatchAssets()

func WatchEmojis

func WatchEmojis()

func WatchThemes

func WatchThemes()

func WithEncryptedBoxOperationScope

func WithEncryptedBoxOperationScope(ctx context.Context) (context.Context, func())

WithEncryptedBoxOperationScope 创建覆盖整个外层响应过程的租约作用域。

func WithTransactionHistory

func WithTransactionHistory[T any](action func(execute func(*Transaction) error) T) T

WithTransactionHistory drains already queued edits before selecting a history entry. Selection, replay, stack finalization and its broadcast share the transaction execution lock. The callback must use execute instead of re-entering PerformTxSync.

func WrapNewDEK

func WrapNewDEK(boxID string, kek []byte) (*conf.BoxEncryption, []byte, error)

WrapNewDEK 用给定 KEK 生成随机 DEK 并包络,返回 BoxEncryption 元数据。 KEK 由调用方临时派生(不来自全局缓存),调用方负责使用后丢弃。 同时返回原始 DEK,供调用方在创建场景下直接开 db 缓存,省去再次 Argon2id 派生。

func WriteFileWithDocumentAddressing

func WriteFileWithDocumentAddressing(absPath string, data []byte) error

WriteFileWithDocumentAddressing 在文件锁内重新检查当前文档,再原样写入已验证的请求内容。 普通附件和插件文件保持原始文件写入语义;此函数不授予路径或加密笔记本访问权限。

Types

type AIEditorAction

type AIEditorAction struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Action string `json:"action"`
}

func GetAIEditorActions

func GetAIEditorActions() (ret []*AIEditorAction, err error)

func SaveAIEditorAction

func SaveAIEditorAction(action *AIEditorAction) (ret *AIEditorAction, err error)

type AIEditorChatStream

type AIEditorChatStream struct {
	// contains filtered or unexported fields
}

func NewAIEditorChatStream

func NewAIEditorChatStream(ctx context.Context, ids []string, input, action string, history []AIEditorMessage) (*AIEditorChatStream, error)

NewAIEditorChatStream 创建绑定到编辑器请求生命周期的模型流。

func (*AIEditorChatStream) Close

func (stream *AIEditorChatStream) Close()

func (*AIEditorChatStream) Recv

func (stream *AIEditorChatStream) Recv() (response openai.ChatCompletionStreamResponse, err error)

type AIEditorMessage

type AIEditorMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

type AVExportPublishFilter

type AVExportPublishFilter func(view av.Viewable, avID, blockID string) av.Viewable

AVExportPublishFilter 为导出路径提供发布访问过滤,nil 表示调用方已确认无需过滤(管理员导出)。

func NewAVExportPublishFilter

func NewAVExportPublishFilter(c *gin.Context) AVExportPublishFilter

NewAVExportPublishFilter 为发布读者构造导出用的属性视图过滤器,非读者角色返回 nil。

type Account

type Account struct {
	Username          string
	Password          string
	Token             string
	CredentialVersion string
}

func GetBasicAuthAccount

func GetBasicAuthAccount(username string) *Account

func GetBasicAuthAccountBySessionID

func GetBasicAuthAccountBySessionID(sessionID string) *Account

GetBasicAuthAccountBySessionID 返回会话对应的账户;会话不存在、已过期或凭据已变更时返回 nil。

type AccountsMap

type AccountsMap map[string]*Account // username -> account

type AddressBook

type AddressBook struct {
	Changed       bool
	DirectoryPath string
	MetaData      *AddressBookMetaData
	Addresses     sync.Map // id -> *AddressObject
}

type AddressBookMetaData

type AddressBookMetaData struct {
	Path                 string
	Name                 string
	Description          string
	MaxResourceSize      int64
	SupportedAddressData []AddressDataType
}

AddressBookMetaData 是 address-books.json 中一个通讯录的元数据。早期版本直接序列化 go-webdav 的 carddav.AddressBook,文件经数据同步在设备间共享,字段名和 JSON 结构必须与之保持一致。

type AddressDataType

type AddressDataType struct {
	ContentType string
	Version     string
}

AddressDataType 是通讯录支持的联系人媒体类型。

type AddressObject

type AddressObject struct {
	Changed  bool
	FilePath string
	BookPath string
	Data     *AddressObjectData
}

type AddressObjectData

type AddressObjectData struct {
	Path    string
	ModTime time.Time
	ETag    string
	// Content 是持久化文件的原始字节,GET 与完整的 address-data 原样返回,ETag 也由它计算
	Content []byte
	Card    vcard.Card
}

AddressObjectData 是联系人资源的当前表示。

type AgentSnippetEdit

type AgentSnippetEdit struct {
	Type    string  `json:"type"`
	Name    *string `json:"name"`
	Content *string `json:"content"`
	OldText *string `json:"oldText"`
	NewText *string `json:"newText"`
}

AgentSnippetEdit 用字段是否出现区分保留原值和写入空内容。

type Announcement

type Announcement struct {
	Id     string `json:"id"`
	Title  string `json:"title"`
	URL    string `json:"url"`
	Region int    `json:"region"`
}

type AppConf

type AppConf struct {
	LogLevel       string                       `json:"logLevel"`       // 日志级别:off, trace, debug, info, warn, error, fatal
	Appearance     ConfSection[conf.Appearance] `json:"appearance"`     // 外观
	Langs          []*conf.Lang                 `json:"langs"`          // 界面语言列表
	Lang           string                       `json:"lang"`           // 选择的界面语言,同 Appearance.Lang
	FileTree       ConfSection[conf.FileTree]   `json:"fileTree"`       // 文档面板
	Tag            ConfSection[conf.Tag]        `json:"tag"`            // 标签面板
	Editor         ConfSection[conf.Editor]     `json:"editor"`         // 编辑器配置
	Export         ConfSection[conf.Export]     `json:"export"`         // 导出配置
	Graph          ConfSection[conf.Graph]      `json:"graph"`          // 关系图配置
	UILayout       ConfSection[conf.UILayout]   `json:"uiLayout"`       // 界面布局,通过 SetUILayout 更新
	UserData       string                       `json:"userData"`       // 社区用户信息,对 User 加密存储
	User           *conf.User                   `json:"-"`              // 社区用户内存结构,不持久化。不要直接使用,使用 GetUser() 和 SetUser() 方法
	ReadOnly       bool                         `json:"readonly"`       // 是否是以只读模式运行
	ServerAddrs    []string                     `json:"serverAddrs"`    // 本地服务器地址列表
	AccessAuthCode string                       `json:"accessAuthCode"` // 锁屏密码
	OIDC           *conf.OIDC                   `json:"oidc"`           // OpenID Connect 登录
	System         ConfSection[conf.System]     `json:"system"`         // 系统配置
	Keymap         ConfSection[conf.Keymap]     `json:"keymap"`         // 快捷键配置
	Sync           ConfSection[conf.Sync]       `json:"sync"`           // 同步配置
	Search         ConfSection[conf.Search]     `json:"search"`         // 搜索配置
	Flashcard      ConfSection[conf.Flashcard]  `json:"flashcard"`      // 闪卡配置
	AI             ConfSection[conf.AI]         `json:"ai"`             // 人工智能配置
	OCR            ConfSection[conf.OCR]        `json:"ocr"`            // 本地图片文字识别
	Secrets        ConfSection[conf.Secrets]    `json:"secrets"`        // 全局密钥库
	Variables      ConfSection[conf.Variables]  `json:"variables"`      // 全局变量库
	Bazaar         ConfSection[conf.Bazaar]     `json:"bazaar"`         // 集市配置
	Stat           ConfSection[conf.Stat]       `json:"stat"`           // 统计
	Api            ConfSection[conf.API]        `json:"api"`            // API
	Repo           ConfSection[conf.Repo]       `json:"repo"`           // 数据仓库
	NotebookCrypto *conf.NotebookCrypto         `json:"notebookCrypto"` // 加密笔记本密钥管理
	Publish        ConfSection[conf.Publish]    `json:"publish"`        // 发布服务
	Onboarding     ConfSection[conf.Onboarding] `json:"onboarding"`     // 首次使用引导
	ShowChangelog  bool                         `json:"showChangelog"`  // 是否显示版本更新日志
	CloudRegion    int                          `json:"cloudRegion"`    // 云端区域,0:中国大陆,1:北美
	Snippet        ConfSection[conf.Snpt]       `json:"snippet"`        // 代码片段
	DataIndexState int                          `json:"dataIndexState"` // 数据索引状态,0:已索引,1:未索引
	CookieKey      string                       `json:"cookieKey"`      // 用于加密 Cookie 的密钥
	ConfVersion    int                          `json:"confVersion"`    // 配置格式版本,用于判定需要执行的迁移

	MCPOAuth string `json:"mcpOAuth"` // MCP OAuth 凭据密文

	Community *conf.Community `json:"community"` // 社区配置
	// contains filtered or unexported fields
}

AppConf 维护应用元数据,保存在 ~/.siyuan/conf.json。

var Conf *AppConf

func GetMaskedConf

func GetMaskedConf() (ret *AppConf, err error)

GetMaskedConf 获取脱敏后的 Conf

func NewAppConf

func NewAppConf() *AppConf

func (*AppConf) Box

func (conf *AppConf) Box(boxID string) *Box

func (*AppConf) BoxNames

func (conf *AppConf) BoxNames(boxIDs []string) (ret map[string]string)

func (*AppConf) Close

func (conf *AppConf) Close()

func (*AppConf) CompareAndSetOIDC

func (appConf *AppConf) CompareAndSetOIDC(expectedVersion string, config *conf.OIDC) (changed, swapped bool)

CompareAndSetOIDC 仅在当前配置版本仍与预期一致时写入 OIDC 配置。

func (*AppConf) GetBox

func (conf *AppConf) GetBox(boxID string) *Box

func (*AppConf) GetBoxes

func (conf *AppConf) GetBoxes() (ret []*Box)

func (*AppConf) GetClosedBoxes

func (conf *AppConf) GetClosedBoxes() (ret []*Box)

func (*AppConf) GetMCPOAuth

func (conf *AppConf) GetMCPOAuth() string

func (*AppConf) GetOCR

func (config *AppConf) GetOCR() conf.OCR

func (*AppConf) GetOIDC

func (appConf *AppConf) GetOIDC() *conf.OIDC

func (*AppConf) GetOpenedBoxes

func (conf *AppConf) GetOpenedBoxes() (ret []*Box)

func (*AppConf) GetUser

func (conf *AppConf) GetUser() *conf.User

func (*AppConf) Language

func (conf *AppConf) Language(num int) (ret string)

func (*AppConf) LoadAI

func (c *AppConf) LoadAI() *conf.AI

func (*AppConf) LoadApi

func (c *AppConf) LoadApi() *conf.API

func (*AppConf) LoadAppearance

func (c *AppConf) LoadAppearance() *conf.Appearance

段读取方法允许尚未初始化的配置,调用方在自己的有效性判断之后使用取得的快照。

func (*AppConf) LoadBazaar

func (c *AppConf) LoadBazaar() *conf.Bazaar

func (*AppConf) LoadEditor

func (c *AppConf) LoadEditor() *conf.Editor

func (*AppConf) LoadExport

func (c *AppConf) LoadExport() *conf.Export

func (*AppConf) LoadFileTree

func (c *AppConf) LoadFileTree() *conf.FileTree

func (*AppConf) LoadFlashcard

func (c *AppConf) LoadFlashcard() *conf.Flashcard

func (*AppConf) LoadGraph

func (c *AppConf) LoadGraph() *conf.Graph

func (*AppConf) LoadKeymap

func (c *AppConf) LoadKeymap() *conf.Keymap

func (*AppConf) LoadOCR

func (c *AppConf) LoadOCR() *conf.OCR

func (*AppConf) LoadOnboarding

func (c *AppConf) LoadOnboarding() *conf.Onboarding

func (*AppConf) LoadPublish

func (c *AppConf) LoadPublish() *conf.Publish

func (*AppConf) LoadRepo

func (c *AppConf) LoadRepo() *conf.Repo

func (*AppConf) LoadSearch

func (c *AppConf) LoadSearch() *conf.Search

func (*AppConf) LoadSecrets

func (c *AppConf) LoadSecrets() *conf.Secrets

func (*AppConf) LoadSnippet

func (c *AppConf) LoadSnippet() *conf.Snpt

func (*AppConf) LoadStat

func (c *AppConf) LoadStat() *conf.Stat

func (*AppConf) LoadSync

func (c *AppConf) LoadSync() *conf.Sync

func (*AppConf) LoadSystem

func (c *AppConf) LoadSystem() *conf.System

func (*AppConf) LoadTag

func (c *AppConf) LoadTag() *conf.Tag

func (*AppConf) LoadUILayout

func (c *AppConf) LoadUILayout() *conf.UILayout

func (*AppConf) LoadVariables

func (c *AppConf) LoadVariables() *conf.Variables

func (*AppConf) Save

func (conf *AppConf) Save()

func (*AppConf) SaveGraphQueryConf

func (appConf *AppConf) SaveGraphQueryConf(global *conf.GlobalGraph, local *conf.LocalGraph)

SaveGraphQueryConf 仅在查询携带的图配置变化时更新并保存,比较、赋值和序列化共用配置锁。

func (*AppConf) SetAI

func (conf *AppConf) SetAI(ctx context.Context, ai *conf.AI) error

func (*AppConf) SetMCPOAuth

func (conf *AppConf) SetMCPOAuth(value string)

func (*AppConf) SetOCR

func (config *AppConf) SetOCR(value conf.OCR) error

func (*AppConf) SetOIDC

func (appConf *AppConf) SetOIDC(config *conf.OIDC)

func (*AppConf) SetUILayout

func (conf *AppConf) SetUILayout(uiLayout *conf.UILayout)

func (*AppConf) SetUser

func (conf *AppConf) SetUser(user *conf.User)

type AssetContent

type AssetContent struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	Ext     string `json:"ext"`
	Path    string `json:"path"`
	Size    int64  `json:"size"`
	HSize   string `json:"hSize"`
	Updated int64  `json:"updated"`
	Content string `json:"content"`
}

func FilterAssetContentByPublishAccess

func FilterAssetContentByPublishAccess(c *gin.Context, publishAccess PublishAccess, assetContent []*AssetContent) (ret []*AssetContent)

func FullTextSearchAssetContent

func FullTextSearchAssetContent(query string, types map[string]bool, method, orderBy, page, pageSize int) (ret []*AssetContent, matchedAssetCount, pageCount int, err error)

FullTextSearchAssetContent 搜索资源文件内容。

method:0:关键字,1:查询语法,2:SQL,3:正则表达式 orderBy: 0:按相关度降序,1:按相关度升序,2:按更新时间升序,3:按更新时间降序

func GetAssetContent

func GetAssetContent(id, query string, queryMethod int) (ret *AssetContent)

func GetAssetContentByPath

func GetAssetContentByPath(path string) (ret *AssetContent)

GetAssetContentByPath 按资源文件路径获取已索引的完整内容。

path 为工作空间相对路径,形如 "assets/xxx.pdf"。返回 nil 表示该文件尚未被索引。 与 GetAssetContent(按索引记录 id)不同,此处直接返回 content 原文,不做高亮。

type AssetParseResult

type AssetParseResult struct {
	Path    string
	Size    int64
	Updated int64
	Content string
}

type AssetParser

type AssetParser interface {
	Parse(absPath string) *AssetParseResult
}

type AssetSearchMatch

type AssetSearchMatch struct {
	Field string
	Mode  string
	Value string
}

type AssetUploadFailure

type AssetUploadFailure struct {
	Index int    `json:"index"`
	Name  string `json:"name"`
	Error string `json:"error"`
}

AssetUploadFailure 记录单个输入文件的上传失败结果。

type AssetUploadRequest

type AssetUploadRequest struct {
	ID            *string
	AssetsDirPath *string
	Files         []*multipart.FileHeader
}

AssetUploadRequest 保留目标字段的缺省状态,并按输入顺序接收全部文件。

type AssetUploadResult

type AssetUploadResult struct {
	ErrFiles    []string             `json:"errFiles"`
	FailedFiles []AssetUploadFailure `json:"failedFiles"`
	SuccFiles   []AssetUploadSuccess `json:"succFiles"`
	SuccMap     map[string]string    `json:"succMap"`
}

func UploadAssets

func UploadAssets(request AssetUploadRequest) (result *AssetUploadResult, message string, err error)

UploadAssets 将附件写入目标资源目录,保留逐文件结果、加密写入和首条失败提示。

type AssetUploadSuccess

type AssetUploadSuccess struct {
	Index int    `json:"index"`
	Name  string `json:"name"`
	Path  string `json:"path"`
}

AssetUploadSuccess 记录单个输入文件的成功上传结果。

type AssetsSearcher

type AssetsSearcher struct {
	// contains filtered or unexported fields
}

func NewAssetsSearcher

func NewAssetsSearcher() *AssetsSearcher

func (*AssetsSearcher) FullIndex

func (searcher *AssetsSearcher) FullIndex() error

func (*AssetsSearcher) GetParser

func (searcher *AssetsSearcher) GetParser(ext string) AssetParser

type AttrView

type AttrView struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

type AttrViewCellUpdate

type AttrViewCellUpdate struct {
	KeyID string `json:"keyID"`
	RowID string `json:"rowID"`
	Data  any    `json:"data"`
}
type AttributeViewBacklink struct {
	AvID            string                           `json:"avID"`
	AvName          string                           `json:"avName"`
	BlockIDs        []string                         `json:"blockIDs"`
	DatabaseBlockID string                           `json:"databaseBlockID"`
	BoxID           string                           `json:"boxID"`
	DatabasePath    string                           `json:"databasePath"`
	ItemID          string                           `json:"itemID"`
	ValueID         string                           `json:"valueID"`
	Title           string                           `json:"title"`
	Icon            string                           `json:"icon"`
	BoundBlockID    string                           `json:"boundBlockID"`
	IsDetached      bool                             `json:"isDetached"`
	Relations       []*AttributeViewBacklinkRelation `json:"relations"`
}

type AttributeViewBacklinkRelation

type AttributeViewBacklinkRelation struct {
	KeyID        string `json:"keyID"`
	KeyName      string `json:"keyName"`
	TargetAvID   string `json:"targetAvID"`
	TargetItemID string `json:"targetItemID"`
}
type AttributeViewBacklinks struct {
	Total int                      `json:"total"`
	Items []*AttributeViewBacklink `json:"items"`
}

func FilterAttributeViewBacklinksByPublishAccess

func FilterAttributeViewBacklinksByPublishAccess(c *gin.Context, publishAccess PublishAccess, backlinks *AttributeViewBacklinks) (ret *AttributeViewBacklinks)
func GetAttributeViewBacklinks(nodeID, avID, itemID, valueID string) (ret *AttributeViewBacklinks)

func GetAttributeViewBacklinksByCarrier

func GetAttributeViewBacklinksByCarrier(itemID, valueID, blockID string, context *AttributeViewRelationContext) (*AttributeViewBacklinks, error)

type AttributeViewCreateKey

type AttributeViewCreateKey struct {
	Name string `json:"name"`
	Type string `json:"type"`
	Icon string `json:"icon,omitempty"`
}

AttributeViewCreateKey 描述创建数据库时需要按顺序初始化的字段。

type AttributeViewCreateResult

type AttributeViewCreateResult struct {
	BlockID       string
	AvID          string
	ViewID        string
	AttributeView *av.AttributeView
}

AttributeViewCreateResult 描述创建数据库后可供调用方继续操作的标识和数据。

func CreateAttributeViewDatabase

func CreateAttributeViewDatabase(parentID, previousID, nextID, name, primaryKeyName string, layout av.LayoutType,
	keySpecs []*AttributeViewCreateKey) (ret *AttributeViewCreateResult, err error)

CreateAttributeViewDatabase 创建数据库块和对应属性视图,并按照 keySpecs 的顺序初始化字段。

type AttributeViewData

type AttributeViewData struct {
	SubItems           *av.SubItemsConfig                          `json:"subItems,omitempty"`
	Spec               int                                         `json:"spec"`
	ID                 string                                      `json:"id"`
	Name               string                                      `json:"name"`
	CustomColors       []*av.AttributeViewCustomColor              `json:"customColors"`
	KeyValues          []*av.KeyValues                             `json:"keyValues"`
	KeyIDs             []string                                    `json:"keyIDs"`
	ViewID             string                                      `json:"viewID"`
	Views              []*av.View                                  `json:"views"`
	NewItemTemplates   []*av.NewItemTemplate                       `json:"newItemTemplates,omitempty"`
	DefaultTemplateID  string                                      `json:"defaultTemplateID,omitempty"`
	Automations        *av.AutomationConfig                        `json:"automations,omitempty"`
	CardCoverPositions map[string]map[string]*av.CardCoverPosition `json:"cardCoverPositions,omitempty"`
}

AttributeViewData 是面向外部接口的兼容数据,不参与数据库文件持久化。

func GetAttributeViewByCarrier

func GetAttributeViewByCarrier(blockID string, context *AttributeViewRelationContext) (*AttributeViewData, error)

func GetAttributeViewRelationDependencyMetadata

func GetAttributeViewRelationDependencyMetadata(targetID, blockID string, context *AttributeViewRelationContext, keyIDs []string) (*AttributeViewData, error)

func GetAttributeViewRelationFieldMetadata

func GetAttributeViewRelationFieldMetadata(targetID, blockID string, context *AttributeViewRelationContext) (*AttributeViewData, error)

字段配置没有来源条目,使用真实来源载体与字段目标校验,不放宽条目读取的成员检查。

func NewAttributeViewData

func NewAttributeViewData(attrView *av.AttributeView) (ret *AttributeViewData)

type AttributeViewFieldView

type AttributeViewFieldView struct {
	ID     string        `json:"id"`
	Icon   string        `json:"icon"`
	Name   string        `json:"name"`
	Type   av.LayoutType `json:"type"`
	Hidden bool          `json:"hidden"`
}

func GetAttributeViewFieldViews

func GetAttributeViewFieldViews(avID, keyID string) (ret []*AttributeViewFieldView, err error)

type AttributeViewGroupItemPosition

type AttributeViewGroupItemPosition struct {
	GroupID    string `json:"groupID"`
	PreviousID string `json:"previousID"`
}

type AttributeViewItemPosition

type AttributeViewItemPosition struct {
	ViewID     string                            `json:"viewID"`
	PreviousID string                            `json:"previousID"`
	Groups     []*AttributeViewGroupItemPosition `json:"groups"`
}

type AttributeViewKeys

type AttributeViewKeys struct {
	ID           string                         `json:"id"`
	Name         string                         `json:"name"`
	CustomColors []*av.AttributeViewCustomColor `json:"customColors"`
	Keys         []*av.Key                      `json:"keys"`
}

AttributeViewKeys 描述数据库字段及其类型专属配置。

func NewAttributeViewKeys

func NewAttributeViewKeys(attrView *av.AttributeView) (ret *AttributeViewKeys)

NewAttributeViewKeys 构造数据库字段结果。

type AttributeViewMetadata

type AttributeViewMetadata struct {
	ID           string                         `json:"id"`
	Name         string                         `json:"name"`
	CustomColors []*av.AttributeViewCustomColor `json:"customColors"`
	Keys         []*av.Key                      `json:"keys"`
	Views        []*av.ViewData                 `json:"views"`
}

AttributeViewMetadata 描述面向命令行和工具调用方的数据库元数据。

func NewAttributeViewMetadata

func NewAttributeViewMetadata(attrView *av.AttributeView) (ret *AttributeViewMetadata)

NewAttributeViewMetadata 构造不包含数据库条目值的元数据。

type AttributeViewRelationCellContext

type AttributeViewRelationCellContext struct {
	RelationContext AttributeViewRelationContext
	SourceItemIDs   []string
}

type AttributeViewRelationContext

type AttributeViewRelationContext struct {
	SourceAvID    string `json:"sourceAvID"`
	SourceItemID  string `json:"sourceItemID"`
	RelationKeyID string `json:"relationKeyID"`
	// contains filtered or unexported fields
}

func (*AttributeViewRelationContext) ResolveStorage

func (context *AttributeViewRelationContext) ResolveStorage(blockID string) error

func (*AttributeViewRelationContext) StorageContext

func (context *AttributeViewRelationContext) StorageContext() (string, bool)

type AttributeViewRelationItemCell

type AttributeViewRelationItemCell struct {
	ItemID         string
	RelatedItemIDs []string
}

AttributeViewRelationItemCell 保留前端批量编辑合并后的已有关系,新条目在事务内追加。

type AttributeViewRelationItemPreview

type AttributeViewRelationItemPreview struct {
	HasPrimaryKeyTemplate bool
	InputPrimaryKey       string
	TemplateID            string
	PrimaryKey            string
	CreatedAt             int64
	Error                 string
}

AttributeViewRelationItemPreview 固定本次模板解析时间,供关联面板预览并确认新条目名称。

func PreviewAttributeViewRelationCellItem

func PreviewAttributeViewRelationCellItem(avID, blockID, keyID, keyword string, context *AttributeViewRelationCellContext) *AttributeViewRelationItemPreview

func PreviewAttributeViewRelationItem

func PreviewAttributeViewRelationItem(avID, blockID, keyID, keyword string, contexts ...*AttributeViewRelationContext) *AttributeViewRelationItemPreview

PreviewAttributeViewRelationItem 仅解析目标数据库的默认模板,解析失败不阻断已有条目的选择。

type AttributeViewRelationItemsChange

type AttributeViewRelationItemsChange struct {
	AddItemIDs    []string `json:"addItemIDs"`
	RemoveItemIDs []string `json:"removeItemIDs"`
}

type AttributeViewRenderData

type AttributeViewRenderData struct {
	ID           string                         `json:"id"`
	Name         string                         `json:"name"`
	CustomColors []*av.AttributeViewCustomColor `json:"customColors"`
	ViewID       string                         `json:"viewID"`
	ViewType     av.LayoutType                  `json:"viewType"`
	Query        string                         `json:"query,omitempty"`
	Page         int                            `json:"page"`
	PageSize     int                            `json:"pageSize"`
	View         av.Viewable                    `json:"view"`
}

AttributeViewRenderData 描述经过指定视图筛选、排序、分组和分页后的数据库结果。

func NewAttributeViewRenderData

func NewAttributeViewRenderData(attrView *av.AttributeView, view av.Viewable, query string, page, pageSize int) (ret *AttributeViewRenderData)

NewAttributeViewRenderData 构造数据库渲染结果。

type AttributeViewRenderOptions

type AttributeViewRenderOptions struct {
	HTTPPreview      *sql.HTTPTemplatePreview
	RelationContext  *AttributeViewRelationContext
	TemporaryFilters []*av.ViewFilter
	TemplateHTTP     *templatehttp.Execution

	ItemStatuses  map[string]string
	Nested        *av.NestedRequest
	ScopeFilter   func(av.Viewable) av.Viewable
	ReadOnly      bool
	CalendarRange *av.CalendarRange
	TemporarySort *av.ViewSort
	// contains filtered or unexported fields
}

AttributeViewRenderOptions 仅影响本次渲染,不参与数据库持久化。

type AttributeViewRenderTarget

type AttributeViewRenderTarget struct {
	AncestorIDs []string `json:"ancestorIDs,omitempty"`
	Status      string   `json:"status"`
	ItemID      string   `json:"itemID"`
	GroupID     string   `json:"groupID,omitempty"`
	Index       int      `json:"index"`
	Offset      int      `json:"offset"`
	PageSize    int      `json:"pageSize"`
}

func RenderAttributeViewWithTarget

func RenderAttributeViewWithTarget(blockID, avID, viewID, query string, page, pageSize int, groupPaging map[string]any, initialLayout av.LayoutType, createIfNotExist, ignoreRows bool, targetItemID, targetGroupID string, calendarRanges ...*av.CalendarRange) (viewable av.Viewable, attrView *av.AttributeView, target *AttributeViewRenderTarget, err error)

func RenderAttributeViewWithTargetOptions

func RenderAttributeViewWithTargetOptions(blockID, avID, viewID, query string, page, pageSize int, groupPaging map[string]any, initialLayout av.LayoutType, createIfNotExist, ignoreRows bool, targetItemID, targetGroupID string, options AttributeViewRenderOptions) (viewable av.Viewable, attrView *av.AttributeView, target *AttributeViewRenderTarget, err error)

RenderAttributeViewWithTargetOptions 在分页前应用临时排序;临时排序和只读请求均不创建或保存数据库。

func RenderAttributeViewWithTargetReadOnly

func RenderAttributeViewWithTargetReadOnly(blockID, avID, viewID, query string, page, pageSize int, groupPaging map[string]any, initialLayout av.LayoutType, createIfNotExist, ignoreRows bool, targetItemID, targetGroupID string, calendarRanges ...*av.CalendarRange) (viewable av.Viewable, attrView *av.AttributeView, target *AttributeViewRenderTarget, err error)

RenderAttributeViewWithTargetReadOnly 仅在内存中渲染发布视图,不创建或保存数据库。

type AttributeViewRowOrder

type AttributeViewRowOrder = attributeViewRowOrder

AttributeViewRowOrder 和 AttributeViewRowOrderChange 用于传输层逐字段转换行排序预览。

type AttributeViewRowOrderChange

type AttributeViewRowOrderChange = attributeViewRowOrderChange

type AttributeViewRowSortPreview

type AttributeViewRowSortPreview struct {
	Conflict       bool         `json:"conflict"`
	DoOperations   []*Operation `json:"doOperations"`
	UndoOperations []*Operation `json:"undoOperations"`
}

func PrepareAttributeViewRowSort

func PrepareAttributeViewRowSort(request *AttributeViewRowSortRequest) (*AttributeViewRowSortPreview, error)

PrepareAttributeViewRowSort 只计算预览和撤销数据,不保存视图或改变字段值。

type AttributeViewRowSortRequest

type AttributeViewRowSortRequest struct {
	AvID       string   `json:"avID"`
	BlockID    string   `json:"blockID"`
	ViewID     string   `json:"viewID"`
	GroupID    string   `json:"groupID"`
	ItemIDs    []string `json:"itemIDs"`
	PreviousID string   `json:"previousID"`
	NextID     string   `json:"nextID"`
}

AttributeViewRowSortRequest 描述同一分组内的一次完整拖拽,落点可使用前项或后项定位。

type AttributeViewSearchTarget

type AttributeViewSearchTarget struct {
	AvID            string   `json:"avID"`
	DatabaseBlockID string   `json:"databaseBlockID"`
	NotebookID      string   `json:"notebookID"`
	ViewID          string   `json:"viewID,omitempty"`
	GroupID         string   `json:"groupID,omitempty"`
	ItemID          string   `json:"itemID"`
	ValueID         string   `json:"valueID"`
	MatchedValueID  string   `json:"matchedValueID"`
	MatchedKeyID    string   `json:"matchedKeyID"`
	Title           string   `json:"title"`
	BoundBlockID    string   `json:"boundBlockID"`
	IsDetached      bool     `json:"isDetached"`
	Keywords        []string `json:"keywords"`
}

func GetAttributeViewSearchTarget

func GetAttributeViewSearchTarget(blockID string, keywords []string) (ret *AttributeViewSearchTarget)

type AttributeViewViewUpdate

type AttributeViewViewUpdate struct {
	Name *string
	Icon *string
	Desc *string
}

AttributeViewViewUpdate 仅修改已提供的视图元数据,空字符串保留清空语义。

type AvSearchResult

type AvSearchResult struct {
	AvID       string            `json:"avID"`
	AvName     string            `json:"avName"`
	ViewName   string            `json:"viewName"`
	ViewID     string            `json:"viewID"`
	ViewLayout av.LayoutType     `json:"viewLayout"`
	BlockID    string            `json:"blockID"`
	HPath      string            `json:"hPath"`
	Matched    bool              `json:"matched,omitempty"`
	Children   []*AvSearchResult `json:"children,omitempty"`
}

func SearchAttributeView

func SearchAttributeView(keyword string, excludeAvIDs []string, currentAvID, currentBlockID string) []*AvSearchResult

func SearchAttributeViewWithOptions

func SearchAttributeViewWithOptions(options SearchAttributeViewOptions) (ret []*AvSearchResult)

type AvSearchTempResult

type AvSearchTempResult struct {
	AvID           string
	AvName         string
	AvUpdated      int64
	Score          float64
	Matched        bool
	SearchInfo     *av.AttributeViewSearchInfo
	MatchedViewIDs map[string]bool
}
type Backlink struct {
	Type                 string                         `json:"type,omitempty"`
	ReferenceBlockID     string                         `json:"referenceBlockID,omitempty"`
	AttributeViewTargets []*BacklinkAttributeViewTarget `json:"attributeViewTargets,omitempty"`
	ID                   string                         `json:"id"`
	DOM                  string                         `json:"dom"`
	BlockPaths           []*BlockPath                   `json:"blockPaths"`
	Expand               bool                           `json:"expand"`
	// contains filtered or unexported fields
}

func GetBacklinkDoc

func GetBacklinkDoc(defID, refTreeID, keyword string, containChildren, highlight bool, filters ...*BacklinkSourceFilter) (ret []*Backlink, keywords []string)

func GetBacklinkDocInBox

func GetBacklinkDocInBox(defID, refTreeID, keyword string, containChildren, highlight bool, boxID string, filters ...*BacklinkSourceFilter) (ret []*Backlink, keywords []string)

func GetBacklinkDocInBoxWithSort

func GetBacklinkDocInBoxWithSort(defID, refTreeID, keyword string, containChildren, highlight bool, boxID string, blockSort int, filters ...*BacklinkSourceFilter) (ret []*Backlink, keywords []string)

func GetBacklinkDocWithSort

func GetBacklinkDocWithSort(defID, refTreeID, keyword string, containChildren, highlight bool, blockSort int, filters ...*BacklinkSourceFilter) (ret []*Backlink, keywords []string)

func GetBackmentionDoc

func GetBackmentionDoc(defID, refTreeID, keyword string, containChildren, highlight bool, notifiers ...BackmentionNotifier) (ret []*Backlink, keywords []string)

func GetBackmentionDocInBox

func GetBackmentionDocInBox(defID, refTreeID, keyword string, containChildren, highlight bool, boxID string, notifiers ...BackmentionNotifier) (ret []*Backlink, keywords []string)

func GetGlobalBacklinkContexts

func GetGlobalBacklinkContexts(query GlobalBacklinkQuery, token string, ids []string, accessible func(string) bool) (items []*Backlink, expired bool, err error)

type BacklinkAttributeViewMatch

type BacklinkAttributeViewMatch struct {
	ItemID  string   `json:"itemID"`
	KeyID   string   `json:"keyID"`
	ValueID string   `json:"valueID"`
	Title   string   `json:"title"`
	KeyName string   `json:"keyName"`
	DefIDs  []string `json:"defIDs"`
}

type BacklinkAttributeViewTarget

type BacklinkAttributeViewTarget struct {
	BlockID string                        `json:"blockID"`
	Matches []*BacklinkAttributeViewMatch `json:"matches"`
}

type BacklinkDatabase

type BacklinkDatabase struct {
	ID   string
	Name string
	Keys []*av.Key
}

func GetBacklinkDatabases

func GetBacklinkDatabases(id, keyword, boxID string, containChildren bool, filter *BacklinkSourceFilter) ([]*BacklinkDatabase, error)

候选忽略当前数据库条件,保留其他来源限制,只返回确实绑定引用来源的数据库元数据。

type BacklinkDatabaseFilter

type BacklinkDatabaseFilter struct {
	AvID    string           `json:"avID"`
	Filters []*av.ViewFilter `json:"filters"`
}

type BacklinkRefDef

type BacklinkRefDef struct {
	ID   string `json:"id"`
	Text string `json:"text"`
	Path string `json:"path"`
}

func GetBacklinkRefDefs

func GetBacklinkRefDefs(id, keyword string, containChildren bool, boxID string, filter *BacklinkSourceFilter) (ret []*BacklinkRefDef, err error)

GetBacklinkRefDefs 返回应用引用排除前的候选,已选目标即使不再出现也保留。

type BacklinkSourceFilter

type BacklinkSourceFilter struct {
	DailyNote           string                  `json:"dailyNote"`
	ExcludedNotebookIDs []string                `json:"excludedNotebookIDs"`
	ExcludeSelf         bool                    `json:"excludeSelf"`
	ExcludedRefDefIDs   []string                `json:"excludedRefDefIDs"`
	Database            *BacklinkDatabaseFilter `json:"database,omitempty"`
}

func NormalizeBacklinkSourceFilter

func NormalizeBacklinkSourceFilter(filter *BacklinkSourceFilter) *BacklinkSourceFilter

type BackmentionNotifier

type BackmentionNotifier func(msg string, timeout int) string

BackmentionNotifier 向本次提及查询的发起端发送提示;显式传入 nil 时不发送。

type Backup

type Backup struct {
	Size    int64  `json:"size"`
	HSize   string `json:"hSize"`
	Updated string `json:"updated"`
	SaveDir string `json:"saveDir"` // 本地备份数据存放目录路径
}

type Block

type Block struct {
	Box      string            `json:"box"`
	Path     string            `json:"path"`
	HPath    string            `json:"hPath"`
	ID       string            `json:"id"`
	RootID   string            `json:"rootID"`
	ParentID string            `json:"parentID"`
	Name     string            `json:"name"`
	Alias    string            `json:"alias"`
	Memo     string            `json:"memo"`
	Tag      string            `json:"tag"`
	Content  string            `json:"content"`
	Number   string            `json:"number,omitempty"`
	FContent string            `json:"fcontent"`
	Markdown string            `json:"markdown"`
	Folded   bool              `json:"folded"`
	Type     string            `json:"type"`
	SubType  string            `json:"subType"`
	RefText  string            `json:"refText"`
	Defs     []*Block          `json:"-"`    // 当前块引用了这些块,避免序列化 JSON 时产生循环引用
	Refs     []*Block          `json:"refs"` // 当前块被这些块引用
	DefID    string            `json:"defID"`
	DefPath  string            `json:"defPath"`
	IAL      map[string]string `json:"ial"`
	Children []*Block          `json:"children"`
	Depth    int               `json:"depth"`
	Count    int               `json:"count"`
	RefCount int               `json:"refCount"`
	Sort     int               `json:"sort"`
	Created  string            `json:"created"`
	Updated  string            `json:"updated"`

	RiffCardID string    `json:"riffCardID"`
	RiffCard   *RiffCard `json:"riffCard"`
	// contains filtered or unexported fields
}

Block 描述了内容块。

func FilterBlocksByPublishAccess

func FilterBlocksByPublishAccess(c *gin.Context, publishAccess PublishAccess, blocks []*Block) (ret []*Block)

func FullTextSearchBlock

func FullTextSearchBlock(options BlockSearchOptions) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int, docMode bool)

FullTextSearchBlock 按同一组命名条件搜索内容块。 Method:0 为关键字,1 为查询语法,2 为 SQL,3 为正则表达式;GroupBy:0 不分组,1 按文档分组。 OrderBy:0 按块类型,1/2 按创建时间升/降序,3/4 按更新时间升/降序,5 按文档内内容顺序,6/7 按相关度升/降序。

func GetBlock

func GetBlock(id string, tree *parse.Tree) (ret *Block, err error)

func GetBlockInBox

func GetBlockInBox(id, boxID string) (ret *Block, err error)

GetBlockInBox 返回指定笔记本边界内的块。

func GetDeckFlashcards

func GetDeckFlashcards(deckID string, page, pageSize int) (blocks []*Block, total, pageCount int)

func GetFlashcardsByBlockIDs

func GetFlashcardsByBlockIDs(blockIDs []string) (ret []*Block)

func GetNotebookFlashcards

func GetNotebookFlashcards(boxID string, page, pageSize int) (blocks []*Block, total, pageCount int)

func GetTreeFlashcards

func GetTreeFlashcards(rootID string, page, pageSize int) (blocks []*Block, total, pageCount int)

func ListInvalidBlockRefs

func ListInvalidBlockRefs(page, pageSize int, excludeBoxIDs, excludeDocIDs []string) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int)

func RecentUpdatedBlocks

func RecentUpdatedBlocks() (ret []*Block)

func SearchExactRefDocTitle

func SearchExactRefDocTitle(id, rootID, title, boxID string) (blocks []*Block, newDoc bool, err error)

SearchExactRefDocTitle 在指定索引边界内解析完整文档标题,并读取目标文档后生成块引用。

func SearchRefBlock

func SearchRefBlock(id, rootID, keyword string, beforeLen int, isSquareBrackets, isDatabase bool) (ret []*Block, newDoc bool)

func SearchRefBlockInBox

func SearchRefBlockInBox(id, rootID, keyword string, beforeLen int, isSquareBrackets, isDatabase bool, boxID string) (ret []*Block, newDoc bool)

SearchRefBlockInBox 与 SearchRefBlock 一致,但按 boxID 路由到加密 db 或全局 db。 加密笔记本内搜索块引目标时传入 boxID,只搜该 box 自己的加密 db,避免跨加密边界引用。

func SemanticSearchBlock

func SemanticSearchBlock(query string, boxes, paths []string, types, subTypes map[string]bool, page, pageSize int, excludeBoxIDs, excludeDocIDs []string) (blocks []*Block, matchedBlockCount, matchedRootCount, pageCount int)

func (*Block) IsContainerBlock

func (block *Block) IsContainerBlock() bool

func (*Block) IsDoc

func (block *Block) IsDoc() bool

type BlockAttributeViewKeys

type BlockAttributeViewKeys struct {
	NotebookID    string                         `json:"notebookID,omitempty"`
	AvID          string                         `json:"avID"`
	AvName        string                         `json:"avName"`
	CustomColors  []*av.AttributeViewCustomColor `json:"customColors"`
	BlockIDs      []string                       `json:"blockIDs"`
	KeyValues     []*av.KeyValues                `json:"keyValues"`
	ItemPositions []*AttributeViewItemPosition   `json:"itemPositions"`
}

func FilterBlockAttributeViewKeysByPublishAccess

func FilterBlockAttributeViewKeysByPublishAccess(c *gin.Context, publishAccess PublishAccess, blockAttributeViewKeys []*BlockAttributeViewKeys) (ret []*BlockAttributeViewKeys)

func GetAttributeViewItemKeys

func GetAttributeViewItemKeys(avID, itemID, valueID string, executions ...*templatehttp.Execution) (ret []*BlockAttributeViewKeys)

func GetAttributeViewItemKeysWithContext

func GetAttributeViewItemKeysWithContext(avID, itemID, valueID, blockID string, context *AttributeViewRelationContext, related bool, executions ...*templatehttp.Execution) ([]*BlockAttributeViewKeys, error)

related 区分来源关系授权和原生详情的真实目标载体授权;两者均不接受客户端指定笔记本。

func GetBlockAttributeViewKeys

func GetBlockAttributeViewKeys(nodeID string, executions ...*templatehttp.Execution) (ret []*BlockAttributeViewKeys)

type BlockBreadcrumbChildren

type BlockBreadcrumbChildren struct {
	Items   []*BlockPath `json:"items"`
	HasMore bool         `json:"hasMore"`
}

func GetBlockBreadcrumbChildrenInBox

func GetBlockBreadcrumbChildrenInBox(id string, excludeTypes []string, offset, limit int, boxID string) (
	ret *BlockBreadcrumbChildren, err error)

type BlockInfo

type BlockInfo struct {
	ID           string            `json:"id"`
	RootID       string            `json:"rootID"`
	Name         string            `json:"name"`
	RefCount     int               `json:"refCount"`
	SubFileCount int               `json:"subFileCount"`
	RefIDs       []string          `json:"refIDs"`
	IAL          map[string]string `json:"ial"`
	Icon         string            `json:"icon"`
	AttrViews    []*AttrView       `json:"attrViews"`
}

func FilterBlockInfoByPublishAccess

func FilterBlockInfoByPublishAccess(c *gin.Context, publishAccess PublishAccess, info *BlockInfo) (ret *BlockInfo)

func GetDoc

func GetDoc(startID, endID, id string, index int, query string, queryTypes, querySubTypes map[string]bool, queryMethod, mode int, size int, isBacklink bool, originalRefBlockIDs map[string]string, highlight, includeDocInfo bool) (
	blockCount int, dom, parentID, parent2ID, rootID, typ string, eof, scroll bool, boxID, docPath string, isBacklinkExpand bool, keywords []string, headingNumbers map[string]string, docInfo *BlockInfo, err error)

func GetDocInBox

func GetDocInBox(startID, endID, id string, index int, query string, queryTypes, querySubTypes map[string]bool, queryMethod, mode int, size int, isBacklink bool, originalRefBlockIDs map[string]string, highlight, includeDocInfo bool, boxID string) (
	blockCount int, dom, parentID, parent2ID, rootID, typ string, eof, scroll bool, boxIDOut, docPath string, isBacklinkExpand bool, keywords []string, headingNumbers map[string]string, docInfo *BlockInfo, err error)

GetDocInBox 与 GetDoc 一致,但按 boxID 路由到加密 db 或全局 db。 加密笔记本打开文档时传入 boxID,blocktree/content 查询走加密 db;boxID 为空时 fall-through 全局 db。

func GetDocInfo

func GetDocInfo(blockID string) (ret *BlockInfo, err error)

func GetDocInfoInBox

func GetDocInfoInBox(blockID, boxID string) (ret *BlockInfo, err error)

GetDocInfoInBox 与 GetDocInfo 一致,但按 boxID 路由 blocktree/refs 查询到加密 db 或全局 db。

func GetDocsInfo

func GetDocsInfo(blockIDs []string, queryRefCount bool, queryAv bool) (rets []*BlockInfo)

type BlockPath

type BlockPath struct {
	ID            string       `json:"id"`
	Name          string       `json:"name"`
	DocumentTitle string       `json:"documentTitle,omitempty"`
	Type          string       `json:"type"`
	SubType       string       `json:"subType"`
	Children      []*BlockPath `json:"children"`
	HasChildren   bool         `json:"hasChildren,omitempty"`
}

func BuildBlockBreadcrumb

func BuildBlockBreadcrumb(id string, excludeTypes []string) (ret []*BlockPath, err error)

func BuildBlockBreadcrumbInBox

func BuildBlockBreadcrumbInBox(id string, excludeTypes []string, boxID string) (ret []*BlockPath, err error)

BuildBlockBreadcrumbInBox 与 BuildBlockBreadcrumb 一致,但按 boxID 路由 blocktree 查询到加密 db 或全局 db。

type BlockSearchOptions

type BlockSearchOptions struct {
	Context       context.Context
	Query         string
	Boxes         []string
	Paths         []string
	Types         map[string]bool
	SubTypes      map[string]bool
	Method        int
	OrderBy       int
	GroupBy       int
	Page          int
	PageSize      int
	BoxID         string
	SearchHPath   *bool
	ExcludeBoxIDs []string
	ExcludeDocIDs []string
}

BlockSearchOptions 汇总内容块搜索条件;未指定上下文时使用后台上下文,SearchHPath 缺省为 true。 BoxID 决定普通或加密笔记本的数据库路由,访问排除条件仍由调用方按请求权限提供。

type BlockTreeInfo

type BlockTreeInfo struct {
	HeadingChildren *bool  `json:"headingChildren,omitempty"`
	ID              string `json:"id"`
	Type            string `json:"type"`
	ParentID        string `json:"parentID"`
	ParentType      string `json:"parentType"`
	PreviousID      string `json:"previousID"`
	PreviousType    string `json:"previousType"`
	NextID          string `json:"nextID"`
	NextType        string `json:"nextType"`
}

type BlockUpdateInput

type BlockUpdateInput struct {
	ID       string
	Data     string
	DataType string
	LockType bool
}

BlockUpdateInput 描述一个外部块更新请求。

type Bookmark

type Bookmark struct {
	Name   BookmarkLabel `json:"name"`
	Blocks []*Block      `json:"blocks"`
	Type   string        `json:"type"` // "bookmark"
	Depth  int           `json:"depth"`
	Count  int           `json:"count"`
}

type BookmarkBlocks

type BookmarkBlocks []*Block

type BookmarkLabel

type BookmarkLabel string

type Bookmarks

type Bookmarks []*Bookmark

func BuildBookmark

func BuildBookmark() (ret *Bookmarks)

func (Bookmarks) Len

func (s Bookmarks) Len() int

func (Bookmarks) Less

func (s Bookmarks) Less(i, j int) bool

func (Bookmarks) Swap

func (s Bookmarks) Swap(i, j int)

type BootAppearance

type BootAppearance struct {
	Enabled         bool                      `json:"enabled"`
	Provider        string                    `json:"provider,omitempty"`
	Appearance      string                    `json:"appearance,omitempty"`
	DisplayName     string                    `json:"displayName,omitempty"`
	Frontends       []string                  `json:"frontends,omitempty"`
	BackgroundColor string                    `json:"backgroundColor,omitempty"`
	Style           string                    `json:"style,omitempty"`
	Layers          []*BootAppearanceLayer    `json:"layers,omitempty"`
	OfficialUI      *BootAppearanceOfficialUI `json:"officialUI,omitempty"`
}

BootAppearance 描述已经校验且可安全交给启动页渲染的外观。

func GetBootAppearance

func GetBootAppearance() *BootAppearance

GetBootAppearance 返回当前可用的启动页外观,任何异常和安全模式下均回退默认。

func GetBootAppearances

func GetBootAppearances() (ret []*BootAppearance)

GetBootAppearances 扫描所有已安装插件声明的启动页外观。

type BootAppearanceLayer

type BootAppearanceLayer struct {
	ID       string `json:"id"`
	Type     string `json:"type"`
	Src      string `json:"src"`
	Poster   string `json:"poster,omitempty"`
	Fit      string `json:"fit,omitempty"`
	Position string `json:"position,omitempty"`
}

BootAppearanceLayer 描述启动页外观中的一个图片或视频图层。

type BootAppearanceOfficialUI

type BootAppearanceOfficialUI struct {
	ShowDetails   bool   `json:"showDetails"`
	TextColor     string `json:"textColor,omitempty"`
	ProgressColor string `json:"progressColor,omitempty"`
	TrackColor    string `json:"trackColor,omitempty"`
}

BootAppearanceOfficialUI 描述官方启动页控件允许调整的有限外观字段。

type BootAppearanceSelection

type BootAppearanceSelection struct {
	SchemaVersion int    `json:"schemaVersion"`
	Provider      string `json:"provider"`
	Appearance    string `json:"appearance"`
}

BootAppearanceSelection 表示当前工作空间选择的启动页外观。

func GetBootAppearanceSelection

func GetBootAppearanceSelection() BootAppearanceSelection

GetBootAppearanceSelection 读取当前启动页外观选择,配置异常时返回默认选择。

func SetBootAppearance

func SetBootAppearance(provider, appearanceID string) (ret BootAppearanceSelection, err error)

SetBootAppearance 校验并原子持久化启动页外观选择,两项均为空表示恢复默认。

type Box

type Box struct {
	ID           string `json:"id"`
	Name         string `json:"name"`
	Icon         string `json:"icon"`
	Sort         int    `json:"sort"`
	SortMode     int    `json:"sortMode"`
	Closed       bool   `json:"closed"`
	SubFileCount int    `json:"subFileCount"`

	NewFlashcardCount int `json:"newFlashcardCount"`
	DueFlashcardCount int `json:"dueFlashcardCount"`
	FlashcardCount    int `json:"flashcardCount"`

	Encrypted bool              `json:"encrypted"` // 是否为加密笔记本
	Unlocked  bool              `json:"unlocked"`  // 加密笔记本是否已解锁(DEK 在内存),非加密笔记本恒为 false
	State     EncryptedBoxState `json:"state,omitempty"`
}

Box 笔记本。

func GetBoxByName

func GetBoxByName(name string) (ret *Box)

func GetFlashcardNotebooks

func GetFlashcardNotebooks() (ret []*Box)

func ListNotebooks

func ListNotebooks() (ret []*Box, err error)

func (*Box) Exist

func (box *Box) Exist(p string) bool

func (*Box) GetConf

func (box *Box) GetConf() (ret *conf.BoxConf)

func (*Box) GetInfo

func (box *Box) GetInfo() (ret *BoxInfo)

func (*Box) GetInfoForPublish

func (box *Box) GetInfoForPublish(publishAccess PublishAccess) (ret *BoxInfo)

GetInfoForPublish 返回发布访问控制下笔记本的聚合信息,只统计发布读者可见的文档。

func (*Box) Index

func (box *Box) Index()

func (*Box) ListFiles

func (box *Box) ListFiles(path string) (ret []*FileInfo)

func (*Box) Ls

func (box *Box) Ls(p string) (ret []*FileInfo, totals int, err error)

func (*Box) Mkdir

func (box *Box) Mkdir(path string) error

func (*Box) MkdirAll

func (box *Box) MkdirAll(path string) error

func (*Box) Move

func (box *Box) Move(oldPath, newPath string) error

func (*Box) Remove

func (box *Box) Remove(path string) error

func (*Box) SaveConf

func (box *Box) SaveConf(conf *conf.BoxConf) error

func (*Box) SaveConfAndSync

func (box *Box) SaveConfAndSync(conf *conf.BoxConf) error

SaveConfAndSync 保存用户修改的笔记本配置,并为已落盘的变更重新计划同步。

func (*Box) Stat

func (box *Box) Stat(p string) (ret *FileInfo)

func (*Box) Unindex

func (box *Box) Unindex()

func (*Box) UpdateHistoryGenerated

func (box *Box) UpdateHistoryGenerated()

type BoxInfo

type BoxInfo struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	DocCount int    `json:"docCount"`
	Size     uint64 `json:"size"`
	HSize    string `json:"hSize"`
	Mtime    int64  `json:"mtime"`
	CTime    int64  `json:"ctime"`
	HMtime   string `json:"hMtime"`
	HCtime   string `json:"hCtime"`
}

type CalDavPathDepth

type CalDavPathDepth int

func GetCalDavPathDepth

func GetCalDavPathDepth(urlPath string) CalDavPathDepth

type Calendar

type Calendar struct {
	Changed       bool
	DirectoryPath string
	MetaData      *CalendarMetaData
	Objects       sync.Map // id -> *CalendarObject
}

type CalendarMetaData

type CalendarMetaData struct {
	Path                  string
	Name                  string
	Description           string
	MaxResourceSize       int64
	SupportedComponentSet []string
}

CalendarMetaData 是 calendars.json 中一个日历的元数据。早期版本直接序列化 go-webdav 的 caldav.Calendar, 文件经数据同步在设备间共享,字段名和 JSON 结构必须与之保持一致。

type CalendarObject

type CalendarObject struct {
	Changed      bool
	FilePath     string
	CalendarPath string
	Data         *CalendarObjectData
}

type CalendarObjectData

type CalendarObjectData struct {
	Path    string
	ModTime time.Time
	ETag    string
	// Content 是持久化文件的原始字节,GET 与完整的 calendar-data 原样返回,ETag 也由它计算
	Content []byte
	Data    *ical.Calendar
}

CalendarObjectData 是日历对象资源的当前表示。

type Calendars

type Calendars struct {
	// contains filtered or unexported fields
}

func (*Calendars) CalendarProperties

func (c *Calendars) CalendarProperties(calendarPath string) []*dav.Node

CalendarProperties 返回日历死属性的副本。

func (*Calendars) CreateCalendar

func (c *Calendars) CreateCalendar(calendarMetaData *CalendarMetaData, properties []*dav.Node) (err error)

CreateCalendar 在 home set 下创建新日历并保存它的死属性;RFC 4918 §9.3 要求 MKCOL 不能作用于已存在的资源, RFC 4791 §5.3.1 要求失败时恢复原状态。

func (*Calendars) DeleteCalendar

func (c *Calendars) DeleteCalendar(calendarPath string, conditions *DAVConditions) (err error)

func (*Calendars) DeleteCalendarObject

func (c *Calendars) DeleteCalendarObject(objectPath string, conditions *DAVConditions) (err error)

func (*Calendars) DeleteObject

func (c *Calendars) DeleteObject(objectPath string, conditions *DAVConditions) (calendar *Calendar, calendarObject *CalendarObject, err error)

func (*Calendars) GetCalendar

func (c *Calendars) GetCalendar(calendarPath string) (calendar *CalendarMetaData, err error)

func (*Calendars) GetCalendarObject

func (c *Calendars) GetCalendarObject(objectPath string) (calendarObject *CalendarObjectData, err error)

func (*Calendars) GetObject

func (c *Calendars) GetObject(objectPath string) (calendar *Calendar, calendarObject *CalendarObject, err error)

func (*Calendars) ListCalendarObjects

func (c *Calendars) ListCalendarObjects(calendarPath string) (calendarObjects []*CalendarObjectData, err error)

ListCalendarObjects 返回日历中的全部对象,按路径排序。

func (*Calendars) ListCalendars

func (c *Calendars) ListCalendars() (calendars []CalendarMetaData, err error)

func (*Calendars) Load

func (c *Calendars) Load() error

func (*Calendars) PutCalendarObject

func (c *Calendars) PutCalendarObject(objectPath string, calendarData *ical.Calendar, conditions *DAVConditions) (calendarObject *CalendarObjectData, created bool, err error)

PutCalendarObject 写入日历对象;created 表示请求前该资源不存在(RFC 9110 §9.3.4 据此区分 201 与 204)。

func (*Calendars) UpdateCalendar

func (c *Calendars) UpdateCalendar(calendarPath string, update func(metaData *CalendarMetaData, properties *[]*dav.Node) error) error

UpdateCalendar 在持有锁时修改日历的元数据和死属性;update 返回错误时不做任何修改,保存失败时内存与磁盘都恢复原状。

type CardDavPathDepth

type CardDavPathDepth int

func GetCardDavPathDepth

func GetCardDavPathDepth(urlPath string) CardDavPathDepth

type ChildBlock

type ChildBlock struct {
	ID       string `json:"id"`
	Type     string `json:"type"`
	SubType  string `json:"subType,omitempty"`
	Content  string `json:"content,omitempty"`
	Markdown string `json:"markdown,omitempty"`
}

func GetChildBlocks

func GetChildBlocks(id string) (ret []*ChildBlock)

func GetChildBlocksInBox

func GetChildBlocksInBox(id, boxID string) (ret []*ChildBlock)

GetChildBlocksInBox 返回指定笔记本边界内的直接子块。

func GetTailChildBlocksInBox

func GetTailChildBlocksInBox(id string, n int, boxID string) (ret []*ChildBlock)

GetTailChildBlocksInBox 返回指定笔记本边界内末尾的子块。

type ClaimsKeyType

type ClaimsKeyType string

type CloudGPT

type CloudGPT struct {
}

type ConfSection

type ConfSection[T any] struct {
	// contains filtered or unexported fields
}

ConfSection 原子发布不可变配置段,复制容器时不会复制原子变量或写锁。

func NewConfSection

func NewConfSection[T any](value *T) ConfSection[T]

func (ConfSection[T]) Clone

func (section ConfSection[T]) Clone() ConfSection[T]

func (ConfSection[T]) Load

func (section ConfSection[T]) Load() *T

func (ConfSection[T]) MarshalJSON

func (section ConfSection[T]) MarshalJSON() ([]byte, error)

func (ConfSection[T]) SnapshotValue

func (section ConfSection[T]) SnapshotValue() any

SnapshotValue 供配置检查器遍历段内容,不暴露原子容器或互斥实现。

func (*ConfSection[T]) Store

func (section *ConfSection[T]) Store(value *T)

Store 在初始化阶段允许补建容器,发布配置后只原子替换段快照。

func (*ConfSection[T]) UnmarshalJSON

func (section *ConfSection[T]) UnmarshalJSON(data []byte) error

type Contacts

type Contacts struct {
	// contains filtered or unexported fields
}

func (*Contacts) AddressBookProperties

func (c *Contacts) AddressBookProperties(bookPath string) []*dav.Node

AddressBookProperties 返回通讯录死属性的副本。

func (*Contacts) CreateAddressBook

func (c *Contacts) CreateAddressBook(addressBookMetaData *AddressBookMetaData, properties []*dav.Node) (err error)

CreateAddressBook 在 home set 下创建新通讯录并保存它的死属性;RFC 4918 §9.3 要求 MKCOL 不能作用于已存在的资源, 失败时恢复原状态。

func (*Contacts) DeleteAddress

func (c *Contacts) DeleteAddress(addressPath string, conditions *DAVConditions) (addressBook *AddressBook, addressObject *AddressObject, err error)

func (*Contacts) DeleteAddressBook

func (c *Contacts) DeleteAddressBook(path string, conditions *DAVConditions) (err error)

func (*Contacts) DeleteAddressObject

func (c *Contacts) DeleteAddressObject(addressPath string, conditions *DAVConditions) (err error)

func (*Contacts) GetAddress

func (c *Contacts) GetAddress(addressPath string) (addressBook *AddressBook, addressObject *AddressObject, err error)

func (*Contacts) GetAddressBook

func (c *Contacts) GetAddressBook(path string) (addressBook *AddressBookMetaData, err error)

func (*Contacts) GetAddressObject

func (c *Contacts) GetAddressObject(addressPath string) (addressObject *AddressObjectData, err error)

func (*Contacts) ListAddressBooks

func (c *Contacts) ListAddressBooks() (addressBooks []AddressBookMetaData, err error)

func (*Contacts) ListAddressObjects

func (c *Contacts) ListAddressObjects(bookPath string) (addressObjects []*AddressObjectData, err error)

ListAddressObjects 返回通讯录中的全部联系人,按路径排序。

func (*Contacts) Load

func (c *Contacts) Load() error

func (*Contacts) PutAddressObject

func (c *Contacts) PutAddressObject(addressPath string, card vcard.Card, conditions *DAVConditions) (addressObject *AddressObjectData, created bool, err error)

PutAddressObject 写入联系人;created 表示请求前该资源不存在(RFC 9110 §9.3.4 据此区分 201 与 204)。

func (*Contacts) UpdateAddressBook

func (c *Contacts) UpdateAddressBook(bookPath string, update func(metaData *AddressBookMetaData, properties *[]*dav.Node) error) error

UpdateAddressBook 在持有锁时修改通讯录的元数据和死属性;update 返回错误时不做任何修改,保存失败时内存与磁盘都恢复原状。

type CreateAttributeViewItemDocsResult

type CreateAttributeViewItemDocsResult struct {
	ItemIDs        []string     `json:"itemIDs"`
	BlockIDs       []string     `json:"blockIDs"`
	SkippedItemIDs []string     `json:"skippedItemIDs,omitempty"`
	Warnings       []string     `json:"warnings,omitempty"`
	Transaction    *Transaction `json:"-"`
}

CreateAttributeViewItemDocsResult 描述将游离条目批量转换为文档后的结果。

func CreateAttributeViewItemDocs

func CreateAttributeViewItemDocs(avID, blockID, saveMode string, itemIDs []string, selections ...*DocumentSelection) (*CreateAttributeViewItemDocsResult, error)

CreateAttributeViewItemDocs 将指定条目中的游离条目批量创建为文档并绑定。

type CreateAttributeViewItemMarkdown

type CreateAttributeViewItemMarkdown struct {
	Title        string
	Markdown     string
	Tags         string
	WithMath     bool
	ClippingHref string
	ListDocTree  bool
}

CreateAttributeViewItemMarkdown 描述通过数据库条目模板创建文档时使用的 Markdown 内容。

type CreateAttributeViewItemResult

type CreateAttributeViewItemResult struct {
	ItemID          string   `json:"itemID"`
	BlockID         string   `json:"blockID"`
	Content         string   `json:"content"`
	IsDetached      bool     `json:"isDetached"`
	Warnings        []string `json:"warnings,omitempty"`
	OpenAfterCreate *bool    `json:"openAfterCreate,omitempty"`
	// 自动打开时使用当前分屏;false 或省略时向右分屏打开。
	OpenInCurrentTab bool         `json:"openInCurrentTab,omitempty"`
	Transaction      *Transaction `json:"-"`
}

CreateAttributeViewItemResult 描述按模板创建数据库条目的结果。

func CreateAttributeViewItem

func CreateAttributeViewItem(avID, blockID, viewID, templateID, previousID, groupID string, calendarDates ...*int64) (*CreateAttributeViewItemResult, error)

CreateAttributeViewItem 按指定模板创建一个数据库条目。templateID 为空时创建空白游离条目。

func CreateAttributeViewItemWithMarkdown

func CreateAttributeViewItemWithMarkdown(avID, blockID, viewID, templateID, previousID, groupID string,
	document *CreateAttributeViewItemMarkdown, selections ...*DocumentSelection) (*CreateAttributeViewItemResult, error)

CreateAttributeViewItemWithMarkdown 按指定的文档类型模板创建数据库条目,并使用传入的 Markdown 创建绑定文档。

func CreateAttributeViewItemWithSelection

func CreateAttributeViewItemWithSelection(avID, blockID, viewID, templateID, previousID, groupID string,
	calendarDate *int64, selection *DocumentSelection) (*CreateAttributeViewItemResult, error)

func CreateAttributeViewRelationCellItem

func CreateAttributeViewRelationCellItem(avID, blockID, keyID, keyword string, cells []*AttributeViewRelationItemCell,
	preview *AttributeViewRelationItemPreview, useInputName bool, context *AttributeViewRelationCellContext, selections ...*DocumentSelection) (*CreateAttributeViewItemResult, error)

func CreateAttributeViewRelationDetailItem

func CreateAttributeViewRelationDetailItem(avID, blockID, keyID, keyword string, cells []*AttributeViewRelationItemCell,
	preview *AttributeViewRelationItemPreview, useInputName bool, context *AttributeViewRelationContext, selections ...*DocumentSelection) (*CreateAttributeViewItemResult, error)

func CreateAttributeViewRelationItem

func CreateAttributeViewRelationItem(avID, blockID, keyID, keyword string, cells []*AttributeViewRelationItemCell,
	preview *AttributeViewRelationItemPreview, useInputName bool, selections ...*DocumentSelection) (*CreateAttributeViewItemResult, error)

文档沿用原生计划创建,数据库条目、来源单元格和双向关联通过同一可撤销事务写入。

type Criterion

type Criterion struct {
	Name string `json:"name"`
	// 排序方式:0 按块类型(默认),1 按创建时间升序,2 按创建时间降序,3 按更新时间升序,4 按更新时间降序,
	// 5 按内容顺序,6 按相关度升序,7 按相关度降序
	Sort         int                    `json:"sort"`
	Group        int                    `json:"group"`      // 0:不分组,1:按文档分组
	HasReplace   bool                   `json:"hasReplace"` // 是否有替换
	Method       int                    `json:"method"`     // 0:文本,1:查询语法,2:SQL,3:正则表达式,4:语义搜索
	HPath        string                 `json:"hPath"`
	IDPath       []string               `json:"idPath"`
	K            string                 `json:"k"`            // 搜索关键字
	R            string                 `json:"r"`            // 替换关键字
	Types        *CriterionTypes        `json:"types"`        // 类型过滤选项
	SubTypes     SearchSubTypes         `json:"subTypes"`     // 子类型过滤选项
	ReplaceTypes *CriterionReplaceTypes `json:"replaceTypes"` // 替换类型过滤选项
}

func FilterCriteriaByPublishAccess

func FilterCriteriaByPublishAccess(c *gin.Context, publishAccess PublishAccess, criteria []*Criterion) (ret []*Criterion)

func GetCriteria

func GetCriteria() (ret []*Criterion)

type CriterionReplaceTypes

type CriterionReplaceTypes struct {
	Text              bool `json:"text"`
	ImgText           bool `json:"imgText"`
	ImgTitle          bool `json:"imgTitle"`
	ImgSrc            bool `json:"imgSrc"`
	AText             bool `json:"aText"`
	ATitle            bool `json:"aTitle"`
	AHref             bool `json:"aHref"`
	Code              bool `json:"code"`
	Em                bool `json:"em"`
	Strong            bool `json:"strong"`
	InlineMath        bool `json:"inlineMath"`
	InlineMemo        bool `json:"inlineMemo"`
	BlockRef          bool `json:"blockRef"`
	FileAnnotationRef bool `json:"fileAnnotationRef"`
	Kbd               bool `json:"kbd"`
	Mark              bool `json:"mark"`
	S                 bool `json:"s"`
	Sub               bool `json:"sub"`
	Sup               bool `json:"sup"`
	Tag               bool `json:"tag"`
	U                 bool `json:"u"`
	DocTitle          bool `json:"docTitle"`
	CodeBlock         bool `json:"codeBlock"`
	MathBlock         bool `json:"mathBlock"`
	HtmlBlock         bool `json:"htmlBlock"`
}

type CriterionTypes

type CriterionTypes struct {
	Mindmap     *bool `json:"mindmap,omitempty"`
	MindmapItem *bool `json:"mindmapItem,omitempty"`
	CustomBlock *bool `json:"customBlock,omitempty"`

	MathBlock     bool `json:"mathBlock"`
	Table         bool `json:"table"`
	Blockquote    bool `json:"blockquote"`
	SuperBlock    bool `json:"superBlock"`
	Paragraph     bool `json:"paragraph"`
	Document      bool `json:"document"`
	Heading       bool `json:"heading"`
	List          bool `json:"list"`
	ListItem      bool `json:"listItem"`
	CodeBlock     bool `json:"codeBlock"`
	HtmlBlock     bool `json:"htmlBlock"`
	EmbedBlock    bool `json:"embedBlock"`
	DatabaseBlock bool `json:"databaseBlock"`
	AudioBlock    bool `json:"audioBlock"`
	VideoBlock    bool `json:"videoBlock"`
	IFrameBlock   bool `json:"iframeBlock"`
	WidgetBlock   bool `json:"widgetBlock"`
	Callout       bool `json:"callout"`
	Tabs          bool `json:"tabs"`
	TabItem       bool `json:"tabItem"`
}

type DAVConditions

type DAVConditions struct {
	IfMatch     string
	IfNoneMatch string
}

DAVConditions 是写请求携带的 If-Match / If-None-Match 前置条件。

type DailyNoteInfo

type DailyNoteInfo struct {
	ID      string
	HPath   string
	Title   string
	Existed bool
}

func GetDailyNoteInfo

func GetDailyNoteInfo(boxID string, date time.Time) (info *DailyNoteInfo, err error)

GetDailyNoteInfo 仅解析命名模板并读取已有文档,不创建文档或添加日记属性。

type DataImportPlan

type DataImportPlan struct {
	ID        string   `json:"id"`
	Conflicts []string `json:"conflicts"`
	Encrypted []string `json:"encrypted"`
}

func PrepareDataImport

func PrepareDataImport(zipPath string) (plan DataImportPlan, err error)

PrepareDataImport 先在独占访问下恢复未完成批次,再保存上传原件和预检结果,不安装上传内容。

type DiffFile

type DiffFile struct {
	FileID  string `json:"fileID"`
	IndexID string `json:"indexID"`
	Title   string `json:"title"`
	Path    string `json:"path"`
	HPath   string `json:"hPath,omitempty"`
	HSize   string `json:"hSize"`
	Updated int64  `json:"updated"`
}

func SearchRepoFile

func SearchRepoFile(keyword string, page int) (ret []*DiffFile, pageCount, totalCount int, err error)

type DiffIndex

type DiffIndex struct {
	ID      string `json:"id"`
	Created int64  `json:"created"`
}

type DocHeadingLevelResult

type DocHeadingLevelResult struct {
	Counts               [6]int       `json:"counts"`
	WithSubheadingCounts [6]int       `json:"withSubheadingCounts"`
	Title                string       `json:"title"`
	Transaction          *Transaction `json:"transaction"`
}

func GetDocHeadingLevelTransaction

func GetDocHeadingLevelTransaction(id, notebook string, source, target int, withSubheadings bool) (*DocHeadingLevelResult, error)

GetDocHeadingLevelTransaction 按完整文档中的原始标题级别收集目标,可连同子标题按相同级差转换。

type DocHistorySnapshot

type DocHistorySnapshot struct {
	ID      string
	FileID  string
	Tags    []string
	Memo    string
	Created int64
}

type DocHistorySnapshotEntry

type DocHistorySnapshotEntry struct {
	Created     string
	HistoryPath string
	Snapshots   []*DocHistorySnapshot
}

func ResolveDocHistorySnapshots

func ResolveDocHistorySnapshots(id string, created []string, op string) ([]*DocHistorySnapshotEntry, error)

ResolveDocHistorySnapshots 与文件历史预览使用相同的查询和首条记录。

type DocSaveAsTemplateInfo

type DocSaveAsTemplateInfo struct {
	Name        string `json:"name"`
	Directory   string `json:"directory"`
	HasDatabase bool   `json:"hasDatabase"`
}

func GetDocSaveAsTemplateInfo

func GetDocSaveAsTemplateInfo(id string) (ret *DocSaveAsTemplateInfo, err error)

type DocSortModeResult

type DocSortModeResult struct {
	Box               string `json:"box"`
	ID                string `json:"id"`
	Path              string `json:"path"`
	SortMode          *int   `json:"sortMode"`
	EffectiveSortMode int    `json:"effectiveSortMode"`
}

func SetDocSortMode

func SetDocSortMode(id string, sortMode *int) (ret *DocSortModeResult, err error)

SetDocSortMode 设置文档对子文档列表声明的排序方式,sortMode 为 nil 时恢复继承。

type DocTreeAccess

type DocTreeAccess struct {
	Published      bool
	Policy         PublishAccess
	RefBoxes       []string
	PolicyRevision string
}

DocTreeAccess 将目录可发现性和引用来源限制绑定到同一次请求的访问上下文。

type DocTreeLocation

type DocTreeLocation struct {
	ParentID, Path, ID, Revision string
	Index, Total, SortMode       int
}

func LocateDocTreeItem

func LocateDocTreeItem(ctx context.Context, notebook, id string, access DocTreeAccess) ([]DocTreeLocation, error)

type DocTreeRange

type DocTreeRange struct {
	Box, ParentID, Path, Revision  string
	Files                          []*File
	Total, Offset, Limit, SortMode int
	Stale                          bool
}

func ListDocTreeRange

func ListDocTreeRange(ctx context.Context, notebook, parentID string, offset, limit int, revision string, access DocTreeAccess) (*DocTreeRange, error)

type DocTreeReorderResult

type DocTreeReorderResult struct {
	Changed    bool   `json:"changed"`
	Conflict   bool   `json:"conflict"`
	Notebook   string `json:"notebook"`
	ParentPath string `json:"parentPath"`
}

func ReorderDocTree

func ReorderDocTree(sourceIDs []string, targetID, position string, preview, removeSorts bool) (ret *DocTreeReorderResult, err error)

ReorderDocTree 在移动前检查完整列表,确认冲突后仅设置目标列表的排序方式。

type DocVersionDiffContent

type DocVersionDiffContent struct {
	ID      string `json:"id"`
	RootID  string `json:"rootID"`
	Title   string `json:"title"`
	Content string `json:"content"`
}

type DocVersionDiffResult

type DocVersionDiffResult struct {
	Left          *DocVersionDiffContent  `json:"left"`
	Right         *DocVersionDiffContent  `json:"right"`
	Differences   []*DocVersionDifference `json:"differences"`
	Large         bool                    `json:"large"`
	Fallback      bool                    `json:"fallback"`
	Message       string                  `json:"message"`
	TitleModified bool                    `json:"titleModified"`
}

func DiffDocVersions

func DiffDocVersions(leftRef, rightRef *DocVersionRef) (ret *DocVersionDiffResult, err error)

DiffDocVersions 比较同一文档的两个版本,并返回带临时差异标记的只读块 DOM。

type DocVersionDifference

type DocVersionDifference struct {
	ID       string   `json:"id"`
	Statuses []string `json:"statuses"`
}

type DocVersionRef

type DocVersionRef struct {
	Type     string `json:"type"`
	ID       string `json:"id"`
	Path     string `json:"path"`
	Snapshot string `json:"snapshot"`
}

type DocumentAddressingError

type DocumentAddressingError struct {
	Reason         string
	Cause          error
	CleanIDs       []string
	UnsupportedIDs []string
}

func LegacyPathFailure

func LegacyPathFailure(err error) (*DocumentAddressingError, bool)

LegacyPathFailure exposes only addressing failures that the legacy HTTP result types can represent. Other source/authentication errors remain errors.

func (*DocumentAddressingError) Error

func (err *DocumentAddressingError) Error() string

func (*DocumentAddressingError) Unwrap

func (err *DocumentAddressingError) Unwrap() error

type DocumentAncestorAmbiguity

type DocumentAncestorAmbiguity struct {
	DocumentTitle       string
	DisplayPath         string
	Notebook            string
	Index               int
	Title               string
	ParentID            *string
	Candidates          []*treenode.DocumentPath
	CandidatesTruncated bool
	Time                time.Time
	TargetRevision      string
}

func (*DocumentAncestorAmbiguity) Error

func (err *DocumentAncestorAmbiguity) Error() string

func (*DocumentAncestorAmbiguity) Unwrap

func (err *DocumentAncestorAmbiguity) Unwrap() error

type DocumentAncestorChoice

type DocumentAncestorChoice struct {
	Index    int
	ID       string
	Revision string
}

type DocumentCreateFailure

type DocumentCreateFailure struct {
	Reason      string
	CommitState string
	ID          string
	Stage       string
	Completed   []string
	Cause       error
}

func (*DocumentCreateFailure) Error

func (err *DocumentCreateFailure) Error() string

func (*DocumentCreateFailure) Unwrap

func (err *DocumentCreateFailure) Unwrap() error

type DocumentCreatePlan

type DocumentCreatePlan struct {
	Notebook    string
	Title       string
	ExistingID  string
	DisplayPath string
	Steps       []DocumentCreateRequest
}

func PlanDocumentCreation

func PlanDocumentCreation(request DocumentPlanRequest) (*DocumentCreatePlan, error)

PlanDocumentCreation 预先验证整组标题并分配全部 ID,不创建源文件或目录。 各类模板均逐级验证显式选择,未选择的歧义返回候选;执行仍按单篇提交并保留已完成结果。

type DocumentCreateRequest

type DocumentCreateRequest struct {
	Notebook               string
	ParentID               *string
	ID                     string
	TitleFormat            string
	Title                  string
	Markdown               string
	ExpectedParentRevision *string
	ExpectedTarget         *DocumentTargetRevision
	NameConditions         []treenode.DocumentNameCondition
	Tags                   string
	WithMath               bool
	ClippingHref           string
	Sorts                  []string
	SortTargetID           string
	SortPosition           string
	DocCreateTemplatePath  string
	ListDocTree            bool
	Attributes             map[string]string
	TemplateTime           *time.Time
	// DOM 仅供已有块身份的内核业务使用,不能经 Markdown 重解析重分配 ID。
	DOM *string
	// contains filtered or unexported fields
}

type DocumentImageList

type DocumentImageList struct {
	DocumentID string             `json:"documentId"`
	Images     []ImageArtifactRef `json:"images"`
}

func ListDocumentImages

func ListDocumentImages(documentID string) (DocumentImageList, error)

ListDocumentImages 返回文档引用的本地图片,供智能体工具和编辑器功能复用。

type DocumentPlanRequest

type DocumentPlanRequest struct {
	Notebook                 string
	Purpose                  string
	ContextID                *string
	Title                    *string
	ID                       string
	Placement                string
	Reuse                    bool
	Now                      time.Time
	SkipContentTemplateCheck bool
	TargetRevision           string
	SelectionRevision        string
	AncestorChoices          []DocumentAncestorChoice
	// Target 供有独立保存配置的内核业务使用,不接受 HTTP 输入。
	Target *EffectiveDocumentTarget
}

type DocumentPreviewImage

type DocumentPreviewImage struct {
	Src      string
	Video    string
	Notebook string
}

func DocPreviewImages

func DocPreviewImages(rootID string) (ret []DocumentPreviewImage, err error)

type DocumentSelection

type DocumentSelection struct {
	Time            time.Time
	TargetRevision  string
	AncestorChoices []DocumentAncestorChoice
}

type DocumentStat

type DocumentStat struct {
	Stat          *util.BlockStatResult `json:"stat"`
	ContainsEmbed bool                  `json:"containsEmbed"`
	StatWithEmbed *util.BlockStatResult `json:"statWithEmbed,omitempty"`
	EmbedStat     *EmbedStat            `json:"embedStat,omitempty"`
}

DocumentStat 表示文档本身及包含嵌入块后的统计结果。

func GetDocumentStat

func GetDocumentStat(ctx context.Context, id, boxID string, includeEmbed bool, accessChecker EmbedBlockAccessChecker) (ret *DocumentStat)

GetDocumentStat 统计文档,并按需解析查询嵌入块。

type DocumentTargetRevision

type DocumentTargetRevision struct {
	Notebook string `json:"notebook"`
	Purpose  string `json:"purpose"`
	Revision string `json:"revision"`
}

type DocumentTitleData

type DocumentTitleData struct {
	ID, Notebook, Format, Text, BlockDOM, Revision string
	Empty                                          bool
	Source                                         *ast.DocumentTitle
}

func GetDocTitle

func GetDocTitle(id, boxID string) (*DocumentTitleData, error)

type DocxAssetParser

type DocxAssetParser struct {
}

func (*DocxAssetParser) Parse

func (parser *DocxAssetParser) Parse(absPath string) (ret *AssetParseResult)

type EffectiveDocumentTarget

type EffectiveDocumentTarget struct {
	Notebook              string
	Path                  string
	Structured            *conf.DocumentTarget
	DocCreateTemplatePath string
	Revision              string
	Rendered              bool
}

func GetDocCreateTarget

func GetDocCreateTarget(boxID, purpose string) (*EffectiveDocumentTarget, error)

GetDocCreateTarget 只解析继承,不渲染模板;版本仅覆盖参与继承的目标和正文模板字段。

type EmbedBlock

type EmbedBlock struct {
	Block               *Block       `json:"block"`
	BlockPaths          []*BlockPath `json:"blockPaths"`
	AllowChildOperation bool         `json:"allowChildOperation"`
}

func FilterEmbedBlocksByPublishAccess

func FilterEmbedBlocksByPublishAccess(c *gin.Context, publishAccess PublishAccess, embedBlocks []*EmbedBlock) (ret []*EmbedBlock)

func GetEmbedBlock

func GetEmbedBlock(embedBlockID string, includeIDs []string, headingMode int, breadcrumb bool) (ret []*EmbedBlock)

func GetEmbedBlockForPublish

func GetEmbedBlockForPublish(embedBlockID string, includeIDs []string, headingMode int, breadcrumb bool) (ret []*EmbedBlock)

func GetEmbedBlockInBox

func GetEmbedBlockInBox(embedBlockID string, includeIDs []string, headingMode int, breadcrumb bool, boxID string) (ret []*EmbedBlock)

func SearchEmbedBlockForPublish

func SearchEmbedBlockForPublish(embedBlockID, stmt string, excludeIDs []string, headingMode int, breadcrumb bool,
	boxID string) (ret []*EmbedBlock)

func SearchEmbedBlockInBox

func SearchEmbedBlockInBox(embedBlockID, stmt string, excludeIDs []string, headingMode int, breadcrumb bool, boxID string) (ret []*EmbedBlock)

SearchEmbedBlockInBox 与 SearchEmbedBlock 一致,但按 boxID 路由 SQL 到加密 content db。 加密笔记本的嵌入块查询走独立加密库(全局 siyuan.db 不含加密数据),boxID 为空时落回全局库。

type EmbedBlockAccessChecker

type EmbedBlockAccessChecker func(blockID string) bool

EmbedBlockAccessChecker 判断嵌入查询结果块是否允许返回。

type EmbedStat

type EmbedStat struct {
	Complete            bool `json:"complete"`
	QueryEmbedCount     int  `json:"queryEmbedCount"`
	JSEmbedCount        int  `json:"jsEmbedCount"`
	ResultCount         int  `json:"resultCount"`
	FailedQueryCount    int  `json:"failedQueryCount"`
	FailedResultCount   int  `json:"failedResultCount"`
	TruncatedQueryCount int  `json:"truncatedQueryCount"`
	CycleCount          int  `json:"cycleCount"`
	DepthLimitCount     int  `json:"depthLimitCount"`
}

EmbedStat 表示嵌入块解析的完整性和处理数量。

type EmbeddingStat

type EmbeddingStat struct {
	Total           int  `json:"total"`           // blocks 表总块数(分母)
	Indexed         int  `json:"indexed"`         // 有效向量数(length(embedding)>0)
	Pending         int  `json:"pending"`         // 待索引块数(blocks 中无对应 block_embeddings 行的)
	Failed          int  `json:"failed"`          // 失败块数(fail_count>0)
	IgnoredByLen    int  `json:"ignoredByLen"`    // 长度忽略(内容过短或过长,ignored_type=1)
	IgnoredByConfig int  `json:"ignoredByConfig"` // 配置忽略(被 .siyuan/embeddingignore 匹配,ignored_type=2)
	Enabled         bool `json:"enabled"`         // 是否已启用嵌入
}

EmbeddingStat 嵌入索引进度统计,供设置页展示。

func GetEmbeddingStat

func GetEmbeddingStat() (ret *EmbeddingStat)

GetEmbeddingStat 查询嵌入索引进度统计。表不存在或未启用时返回零值统计。

type EncryptedBoxState

type EncryptedBoxState string
const (
	EncryptedBoxStateLocked    EncryptedBoxState = "Locked"
	EncryptedBoxStateUnlocking EncryptedBoxState = "Unlocking"
	EncryptedBoxStateUnlocked  EncryptedBoxState = "Unlocked"
	EncryptedBoxStateLocking   EncryptedBoxState = "Locking"
	EncryptedBoxStateError     EncryptedBoxState = "Error"
)

func GetEncryptedBoxState

func GetEncryptedBoxState(boxID string) EncryptedBoxState

GetEncryptedBoxState 返回加密笔记本当前的显式生命周期状态。

type EpubAssetParser

type EpubAssetParser struct {
}

func (*EpubAssetParser) Parse

func (parser *EpubAssetParser) Parse(absPath string) (ret *AssetParseResult)

type ExportArtifactLease

type ExportArtifactLease struct {
	ID   string `json:"leaseID"`
	Path string `json:"path"`
	Name string `json:"name"`
	Size int64  `json:"size"`
}

func AcquireExportArtifactLease

func AcquireExportArtifactLease(exportPath string) (lease *ExportArtifactLease, err error)

AcquireExportArtifactLease 为导出产物取得覆盖整个复制过程的生命周期租约。

type ExportOptions

type ExportOptions struct {
	Render ExportRenderOptions `json:"-"`
	// 通用部分(PDF/Word/HTML/Markdown 均读取)
	AddTitle              *bool   `json:"addTitle"`              // 是否添加文档标题
	InlineMemo            *bool   `json:"inlineMemo"`            // 是否导出行级备注
	BlockRefMode          *int    `json:"blockRefMode"`          // 内容块引用导出模式
	BlockEmbedMode        *int    `json:"blockEmbedMode"`        // 内容块嵌入导出模式
	FileAnnotationRefMode *int    `json:"fileAnnotationRefMode"` // 文件标注引用导出模式
	BlockRefTextLeft      *string `json:"blockRefTextLeft"`      // 块引锚文本左侧符号
	BlockRefTextRight     *string `json:"blockRefTextRight"`     // 块引锚文本右侧符号
	TagOpenMarker         *string `json:"tagOpenMarker"`         // 标签开始标记符
	TagCloseMarker        *string `json:"tagCloseMarker"`        // 标签结束标记符
	// Markdown 专属部分
	HeadingNumber      *bool `json:"headingNumber"`      // false 省略本次 Markdown 的标题编号,nil 沿用导出设置,true 保留文档编号
	IncludeSubDocs     *bool `json:"includeSubDocs"`     // 是否包含子文档
	IncludeRelatedDocs *bool `json:"includeRelatedDocs"` // 是否包含关联文档
	MarkdownYFM        *bool `json:"markdownYFM"`        // 是否添加 YAML Front Matter
	RemoveAssetsID     *bool `json:"removeAssetsID"`     // 是否移除资源文件名中的 ID
}

ExportOptions 为单次导出提供的临时选项,缺省字段(nil)使用全局 Conf.Export 的值。 通用部分可被各导出格式复用,Markdown 专属部分仅 Markdown 导出使用。 用于「导出 Markdown 参数对话框」https://github.com/siyuan-note/siyuan/issues/17031

func ParseExportOptions

func ParseExportOptions(arg map[string]any) (opts *ExportOptions)

ParseExportOptions 从 JSON 请求参数中解析导出选项,未传入的字段保持 nil(沿用全局配置)#17031。

type ExportRenderOptions

type ExportRenderOptions struct {
	AssetsDestSpace2Underscore, FillCSSVar, AdjustHeadingLevel, ImgTag bool
	PreserveTaskMarkers                                                bool
	AVPublishFilter                                                    AVExportPublishFilter
	AccessCheckers                                                     []EmbedBlockAccessChecker
}

ExportRenderOptions 是导出入口的格式与访问上下文,不属于 HTTP 请求或持久化配置。

type File

type File struct {
	Path             string `json:"path"`
	Name             string `json:"name"` // 标题,即 ial["title"]
	TitleEmpty       bool   `json:"titleEmpty,omitempty"`
	TitleFormat      string `json:"titleFormat,omitempty"`
	TitleRevision    string `json:"titleRevision,omitempty"`
	SpecTooNew       bool   `json:"specTooNew,omitempty"` // 源版本高于当前版本,标题等属性仅来自占位读取
	Icon             string `json:"icon"`
	Name1            string `json:"name1"` // 命名,即 ial["name"]
	Alias            string `json:"alias"`
	Memo             string `json:"memo"`
	Bookmark         string `json:"bookmark"`
	ID               string `json:"id"`
	Count            int    `json:"count"`
	Size             uint64 `json:"size"`
	HSize            string `json:"hSize"`
	Mtime            int64  `json:"mtime"`
	CTime            int64  `json:"ctime"`
	HMtime           string `json:"hMtime"`
	HCtime           string `json:"hCtime"`
	Sort             int    `json:"sort"`
	SubFileCount     int    `json:"subFileCount"`
	ChildrenSortMode *int   `json:"childrenSortMode"`

	NewFlashcardCount int `json:"newFlashcardCount"`
	DueFlashcardCount int `json:"dueFlashcardCount"`
	FlashcardCount    int `json:"flashcardCount"`
}

func ListDocTree

func ListDocTree(boxID, listPath string, sortMode int, flashcard, showHidden bool, maxListCount int) (ret []*File, totals int, err error)

type FileInfo

type FileInfo struct {
	// contains filtered or unexported fields
}

type Flashcard

type Flashcard struct {
	DeckID     string                 `json:"deckID"`
	CardID     string                 `json:"cardID"`
	BlockID    string                 `json:"blockID"`
	Lapses     int                    `json:"lapses"`
	Reps       int                    `json:"reps"`
	State      riff.State             `json:"state"`
	LastReview int64                  `json:"lastReview"`
	NextDues   map[riff.Rating]string `json:"nextDues"`
}

func GetDueFlashcards

func GetDueFlashcards(deckID string, reviewedCardIDs []string) (ret []*Flashcard, unreviewedCount, unreviewedNewCardCount, unreviewedOldCardCount int, err error)

func GetNotebookDueFlashcards

func GetNotebookDueFlashcards(boxID string, reviewedCardIDs []string) (ret []*Flashcard, unreviewedCount, unreviewedNewCardCount, unreviewedOldCardCount int, err error)

func GetTreeDueFlashcards

func GetTreeDueFlashcards(rootID string, reviewedCardIDs []string) (ret []*Flashcard, unreviewedCount, unreviewedNewCardCount, unreviewedOldCardCount int, err error)

type GPT

type GPT interface {
	// contains filtered or unexported methods
}

type GenerateDocumentImageRequest

type GenerateDocumentImageRequest struct {
	DocumentID   string `json:"documentId"`
	Prompt       string `json:"prompt"`
	Size         string `json:"size"`
	Quality      string `json:"quality"`
	OutputFormat string `json:"outputFormat"`
}

type GenerateDocumentImageResult

type GenerateDocumentImageResult struct {
	Artifact      ImageArtifactRef `json:"artifact"`
	RevisedPrompt string           `json:"revisedPrompt,omitempty"`
}

func GenerateDocumentImage

func GenerateDocumentImage(ctx context.Context, request GenerateDocumentImageRequest) (GenerateDocumentImageResult, error)

GenerateDocumentImage 使用通用图片生成能力创建文档资源。

type GenerateImageRequest

type GenerateImageRequest struct {
	Prompt       string `json:"prompt"`
	Size         string `json:"size"`
	Quality      string `json:"quality"`
	OutputFormat string `json:"outputFormat"`
}

type GenerateImageResult

type GenerateImageResult struct {
	Data          []byte `json:"-"`
	MIMEType      string `json:"mimeType"`
	Extension     string `json:"extension"`
	RevisedPrompt string `json:"revisedPrompt,omitempty"`
}

func GenerateImage

func GenerateImage(ctx context.Context, request GenerateImageRequest) (GenerateImageResult, error)

GenerateImage 使用全局图片生成配置创建图片字节,可供文档资源、编辑器和其他图片入口复用。

type GlobalBacklinkItem

type GlobalBacklinkItem struct {
	ID, RootID, Box, HPath, Anchor string
	// contains filtered or unexported fields
}
func GetGlobalBacklinks(query GlobalBacklinkQuery, token string, offset int, anchorID string, accessible func(string) bool) (snapshotID string, items []*GlobalBacklinkItem, total, start int, expired bool, err error)

type GlobalBacklinkQuery

type GlobalBacklinkQuery struct {
	ID, Notebook, Keyword string
	Sort                  int
	ContainChildren       bool
	SourceFilter          *BacklinkSourceFilter
}

type GraphArrows

type GraphArrows struct {
	To *GraphArrowsTo `json:"to"`
}

type GraphArrowsTo

type GraphArrowsTo struct {
	Enabled bool `json:"enabled"`
}
type GraphLink struct {
	From   string       `json:"from"`
	To     string       `json:"to"`
	Ref    bool         `json:"ref"`
	Arrows *GraphArrows `json:"arrows"`
}

type GraphNode

type GraphNode struct {
	ID    string  `json:"id"`
	Box   string  `json:"box"`
	Path  string  `json:"path"`
	Size  float64 `json:"size"`
	Title string  `json:"title,omitempty"`
	Label string  `json:"label"`
	Type  string  `json:"type"`
	Refs  int     `json:"refs"`
	Defs  int     `json:"defs"`
}

type GroupState

type GroupState struct {
	ID              string
	LayoutID        string
	LayoutType      av.LayoutType
	Position        int
	Folded          bool
	Hidden          int
	Sort            int
	ItemIDs         []string
	SubItemsItemIDs []string
}

GroupState 用于临时记录每个分组视图的状态,以便后面重新生成分组后可以恢复这些状态。

type HTML2TreeOptions

type HTML2TreeOptions struct {
	SkipBase64Assets    bool
	SkipInlineSVGAssets bool
}

type History

type History struct {
	HCreated string         `json:"hCreated"`
	Items    []*HistoryItem `json:"items"`
}

func GetNotebookHistory

func GetNotebookHistory() (ret []*History, err error)

type HistoryItem

type HistoryItem struct {
	ID       string `json:"id"`
	Title    string `json:"title"`
	Path     string `json:"path"`
	Op       string `json:"op"`
	Notebook string `json:"notebook"` // 仅用于文档历史
}

func FullTextSearchHistoryItems

func FullTextSearchHistoryItems(created, query, box, op string, typ int) (ret []*HistoryItem)

func FullTextSearchHistoryItemsPage

func FullTextSearchHistoryItemsPage(created, query, box, op string, typ, page int) (ret []*HistoryItem, pageCount, totalCount int)

type ImageArtifactRef

type ImageArtifactRef struct {
	Kind       string `json:"kind"`
	Path       string `json:"path"`
	MIMEType   string `json:"mimeType,omitempty"`
	DocumentID string `json:"documentId,omitempty"`
}

type InlineStyle

type InlineStyle struct {
	ID     string            `json:"id"`
	Name   string            `json:"name"`
	Hidden bool              `json:"hidden,omitempty"`
	Light  *InlineStyleTheme `json:"light"`
	Dark   *InlineStyleTheme `json:"dark"`
}

type InlineStyleAV

type InlineStyleAV struct {
	Colors []*av.AttributeViewCustomColor `json:"colors"`
	Order  []string                       `json:"order"`
}

type InlineStyleBuiltin

type InlineStyleBuiltin struct {
	Colors []*InlineStyleBuiltinColor `json:"colors"`
	Styles []*InlineStyleBuiltinStyle `json:"styles"`
	Hidden *InlineStyleBuiltinHidden  `json:"hidden"`
}

type InlineStyleBuiltinColor

type InlineStyleBuiltinColor struct {
	Index int               `json:"index"`
	Light *InlineStyleTheme `json:"light"`
	Dark  *InlineStyleTheme `json:"dark"`
}

type InlineStyleBuiltinHidden

type InlineStyleBuiltinHidden struct {
	Color           []int    `json:"color"`
	BackgroundColor []int    `json:"backgroundColor"`
	Style1          []string `json:"style1"`
	AV              []int    `json:"av"`
}

type InlineStyleBuiltinStyle

type InlineStyleBuiltinStyle struct {
	ID    string            `json:"id"`
	Light *InlineStyleTheme `json:"light"`
	Dark  *InlineStyleTheme `json:"dark"`
}

type InlineStyleOrder

type InlineStyleOrder struct {
	Color           []string `json:"color"`
	BackgroundColor []string `json:"backgroundColor"`
	Style1          []string `json:"style1"`
}

type InlineStyleTheme

type InlineStyleTheme struct {
	Color           string `json:"color,omitempty"`
	BackgroundColor string `json:"backgroundColor,omitempty"`
}

type InlineStyles

type InlineStyles struct {
	Version int                 `json:"version"`
	Styles  []*InlineStyle      `json:"styles"`
	Builtin *InlineStyleBuiltin `json:"builtin"`
	Order   *InlineStyleOrder   `json:"order"`
	AV      *InlineStyleAV      `json:"av"`
}

func GetInlineStyles

func GetInlineStyles() (ret *InlineStyles, err error)

func SetInlineStyles

func SetInlineStyles(styles []*InlineStyle) (ret *InlineStyles, changed bool, err error)

func SetInlineStylesData

func SetInlineStylesData(styles *InlineStyles) (ret *InlineStyles, changed bool, err error)

SetInlineStylesData 全量保存行级样式和内置颜色配置。

func SetWorkspaceAVPalette

func SetWorkspaceAVPalette(update *WorkspaceAVPaletteUpdate) (ret *InlineStyles, changed bool, err error)

SetWorkspaceAVPalette 只更新数据库颜色配置,保留其他窗口可能同时修改的行级样式设置。

type Issue

type Issue struct {
	Field    string `json:"field"`
	Severity string `json:"severity"`
	Message  string `json:"message"`
}

Issue 描述配置字段诊断,error 阻断提交,warning 随成功结果返回。

func Apply

func Apply[C any](spec *SectionSpec[C], next C) ([]Issue, error)

Apply 在段写锁下完成规范化和诊断,再持配置锁发布并同步落盘。 反应在配置锁外执行,允许动作读取配置或更新领域状态。

func ApplyAppearanceSetting

func ApplyAppearanceSetting(value *conf.Appearance) ([]Issue, error)

ApplyAppearanceSetting 在同一段写锁内提交设置并刷新磁盘资源,内部偏好更新仍按资源字段变化触发反应。

func ApplyConfPatch

func ApplyConfPatch(namespace string, patch []byte) ([]Issue, error)

func ApplyConfSection

func ApplyConfSection(namespace string, value any) ([]Issue, error)

func ApplySyncSettingPatch

func ApplySyncSettingPatch(patch []byte) ([]Issue, error)

ApplySyncSettingPatch 在来源锁与段写锁内合并,先验证全部改动,再一次性发布配置。

type KernelPetal

type KernelPetal struct {
	JS           string `json:"js"`           // Kernel JS code
	Existed      bool   `json:"existed"`      // Whether kernel.js is exist
	Incompatible bool   `json:"incompatible"` // Whether incompatible
}

type LeftRightDiff

type LeftRightDiff struct {
	LeftIndex    *DiffIndex  `json:"leftIndex"`
	RightIndex   *DiffIndex  `json:"rightIndex"`
	AddsLeft     []*DiffFile `json:"addsLeft"`
	UpdatesLeft  []*DiffFile `json:"updatesLeft"`
	UpdatesRight []*DiffFile `json:"updatesRight"`
	RemovesRight []*DiffFile `json:"removesRight"`
}

func DiffRepoSnapshots

func DiffRepoSnapshots(left, right string) (ret *LeftRightDiff, err error)

type LocalBazaarInstallOptions

type LocalBazaarInstallOptions struct {
	ExpectedPackageHash       string
	ExpectedInstalledRevision string
	Context                   context.Context
	Recheck                   func() error
}

LocalBazaarInstallOptions 保留旧调用形式,官方受管制品由工具层要求同时绑定这两个摘要。

type LocalBazaarPackageInstallResult

type LocalBazaarPackageInstallResult struct {
	PackageType       string `json:"packageType"`
	PackageName       string `json:"packageName"`
	MinAppVersion     string `json:"minAppVersion,omitempty"`
	Updated           bool   `json:"updated"`
	PackageHash       string `json:"packageHash,omitempty"`
	InstalledRevision string `json:"installedRevision,omitempty"`
	PreviousRevision  string `json:"previousRevision,omitempty"`
}

LocalBazaarPackageInstallResult 描述本地集市包的识别和安装结果。

func InstallLocalBazaarPackage

func InstallLocalBazaarPackage(archivePath, frontend string, overwrite bool) (result *LocalBazaarPackageInstallResult, err error)

InstallLocalBazaarPackage 安装上传的本地集市包。

func InstallLocalBazaarPackageWithOptions

func InstallLocalBazaarPackageWithOptions(archivePath, frontend string, overwrite bool, options LocalBazaarInstallOptions) (result *LocalBazaarPackageInstallResult, err error)

type LocalBazaarPackagePreview

type LocalBazaarPackagePreview struct {
	PackageType       string `json:"packageType"`
	PackageName       string `json:"packageName"`
	Version           string `json:"version"`
	PackageHash       string `json:"packageHash"`
	InstalledRevision string `json:"installedRevision"`
	ConfiguredEnabled bool   `json:"configuredEnabled"`
}

func PreviewLocalBazaarPackage

func PreviewLocalBazaarPackage(archivePath, expectedPackageHash string) (*LocalBazaarPackagePreview, error)

PreviewLocalBazaarPackage 在确认前只读核验归档身份和目标状态,不创建项目、解压目录或配置文件。 启用标志仅是观测,不证明任何前端已卸载,也不缩小安装可能执行代码的授权范围。

type MergeHeadingOptions

type MergeHeadingOptions struct {
	DocHeadingMode     string
	ContentHeadingMode string
}

type MobileExportLease

type MobileExportLease = ExportArtifactLease

func AcquireMobileExportLease

func AcquireMobileExportLease(exportPath string) (lease *MobileExportLease, err error)

AcquireMobileExportLease 为移动端导出取得覆盖整个原生复制过程的生命周期租约。

type NewItemTemplatePreview

type NewItemTemplatePreview struct {
	PrimaryKey string   `json:"primaryKey"`
	BoxID      string   `json:"boxID,omitempty"`
	HPath      string   `json:"hPath,omitempty"`
	Warnings   []string `json:"warnings,omitempty"`
	// contains filtered or unexported fields
}

NewItemTemplatePreview 描述新增条目模板在当前数据库实例中的解析结果。

type NotebookArchiveCandidate

type NotebookArchiveCandidate struct {
	ID      string
	Current bool
}

func ListNotebookArchiveCandidates

func ListNotebookArchiveCandidates() ([]NotebookArchiveCandidate, error)

ListNotebookArchiveCandidates 同时列出现存密文和只有历史的笔记本,不要求解锁或派生密钥。

type NotebookCryptoState

type NotebookCryptoState string
const (
	NotebookCryptoStateDisabled         NotebookCryptoState = "Disabled"
	NotebookCryptoStateEnabled          NotebookCryptoState = "Enabled"
	NotebookCryptoStateRecoveryRequired NotebookCryptoState = "RecoveryRequired"
)

func NotebookCryptoLifecycleState

func NotebookCryptoLifecycleState(hasRecoveryDependency bool) NotebookCryptoState

NotebookCryptoLifecycleState 返回全局加密功能状态。

type OCRAIModel

type OCRAIModel struct {
	ID, Name, Provider string
}

func OCRAIModels

func OCRAIModels() (result []OCRAIModel)

OCRAIModels 返回可选模型的显示信息;保留配置中的顺序,不泄露连接凭据。

type ObsidianVaultAnalysis

type ObsidianVaultAnalysis struct {
	VaultName               string   `json:"vaultName"`
	VaultPath               string   `json:"vaultPath"`
	NotebookName            string   `json:"notebookName"`
	MarkdownCount           int      `json:"markdownCount"`
	SyntheticParentCount    int      `json:"syntheticParentCount"`
	NameAdjustmentCount     int      `json:"nameAdjustmentCount"`
	ImportableAssetCount    int      `json:"importableAssetCount"`
	ImportableAssetSize     int64    `json:"importableAssetSize"`
	UnreferencedFileCount   int      `json:"unreferencedFileCount"`
	WikiLinkCount           int      `json:"wikiLinkCount"`
	EmbedCount              int      `json:"embedCount"`
	BlockIDCount            int      `json:"blockIDCount"`
	FootnoteCount           int      `json:"footnoteCount"`
	CommentCount            int      `json:"commentCount"`
	MissingCount            int      `json:"missingCount"`
	AmbiguousCount          int      `json:"ambiguousCount"`
	UnsupportedCount        int      `json:"unsupportedCount"`
	SkippedHiddenCount      int      `json:"skippedHiddenCount"`
	SkippedLinkCount        int      `json:"skippedLinkCount"`
	SkippedSpecialCount     int      `json:"skippedSpecialCount"`
	SkippedNestedVaultCount int      `json:"skippedNestedVaultCount"`
	BlockingErrors          []string `json:"blockingErrors"`
	Warnings                []string `json:"warnings"`
}

type ObsidianVaultImportResult

type ObsidianVaultImportResult struct {
	NotebookID               string `json:"notebookID"`
	NotebookName             string `json:"notebookName"`
	MarkdownCount            int    `json:"markdownCount"`
	SyntheticParentCount     int    `json:"syntheticParentCount"`
	NameAdjustmentCount      int    `json:"nameAdjustmentCount"`
	ImportedAttachmentCount  int    `json:"importedAttachmentCount"`
	UnreferencedFileCount    int    `json:"unreferencedFileCount"`
	ConvertedLinkCount       int    `json:"convertedLinkCount"`
	ConvertedEmbedCount      int    `json:"convertedEmbedCount"`
	ConvertedFootnoteCount   int    `json:"convertedFootnoteCount"`
	PreservedCommentCount    int    `json:"preservedCommentCount"`
	PreservedUnresolvedCount int    `json:"preservedUnresolvedCount"`
	SkippedPathCount         int    `json:"skippedPathCount"`
	Incomplete               bool   `json:"incomplete"`
	FailedStage              string `json:"failedStage,omitempty"`
}

type ObsidianVaultTask

type ObsidianVaultTask struct {
	TaskID   string                     `json:"taskID"`
	State    string                     `json:"state"`
	Progress int                        `json:"progress"`
	Message  string                     `json:"message"`
	Error    string                     `json:"error,omitempty"`
	Detail   string                     `json:"detail,omitempty"`
	Analysis *ObsidianVaultAnalysis     `json:"analysis,omitempty"`
	Result   *ObsidianVaultImportResult `json:"result,omitempty"`
}

func CancelObsidianVaultTask

func CancelObsidianVaultTask(taskID string) (*ObsidianVaultTask, error)

func GetObsidianVaultTask

func GetObsidianVaultTask(taskID string) (*ObsidianVaultTask, error)

func StartObsidianVaultAnalysis

func StartObsidianVaultAnalysis(localPath string) (*ObsidianVaultTask, error)

func StartObsidianVaultImport

func StartObsidianVaultImport(taskID, notebookName string) (*ObsidianVaultTask, error)

type OnlineKernel

type OnlineKernel struct {
	ID       string `json:"id"`
	Hostname string `json:"hostname"`
	OS       string `json:"os"`
	Ver      string `json:"ver"`
}

func GetOnlineKernels

func GetOnlineKernels() (ret []*OnlineKernel)

type OpenAIGPT

type OpenAIGPT struct {
	// contains filtered or unexported fields
}

type Operation

type Operation struct {
	RelationContext *AttributeViewRelationContext `json:"relationContext,omitempty"`
	Action          string                        `json:"action"`
	Data            any                           `json:"data"`
	ID              string                        `json:"id"`
	RootID          string                        `json:"rootID"` // 思源内部暂时没有用到 https://github.com/siyuan-note/siyuan/issues/17179#issuecomment-4051604916
	ParentID        string                        `json:"parentID"`
	PreviousID      string                        `json:"previousID"`
	NextID          string                        `json:"nextID"`
	RetData         any                           `json:"retData"`
	BlockIDs        []string                      `json:"blockIDs"` // move/append 时为随折叠标题移动的顶层块,闪卡操作时为目标块
	BlockID         string                        `json:"blockID"`

	DeckID string      `json:"deckID"` // 用于添加/删除闪卡
	Tree   *parse.Tree `json:"-"`      // 仅用于内核事务重放,不发送到前端

	LockType bool `json:"-"` // 外部块更新是否禁止改变主类型

	AvID              string                `json:"avID"`                  // 属性视图 ID
	SrcIDs            []string              `json:"srcIDs"`                // 用于从属性视图中删除行
	Srcs              []map[string]any      `json:"srcs"`                  // 用于添加属性视图行(包括绑定块){id, content, isDetached}
	IsDetached        bool                  `json:"isDetached"`            // 用于标识是否未绑定块,仅存在于属性视图中
	Name              string                `json:"name"`                  // 属性视图列名
	Typ               string                `json:"type"`                  // 属性视图列类型
	Format            string                `json:"format"`                // 属性视图列格式化
	KeyID             string                `json:"keyID"`                 // 属性视图字段 ID
	RowID             string                `json:"rowID"`                 // 属性视图行 ID
	CellUpdates       []*AttrViewCellUpdate `json:"cellUpdates,omitempty"` // 属性视图单元格批量更新
	IsTwoWay          bool                  `json:"isTwoWay"`              // 属性视图关联列是否是双向关系
	BackRelationKeyID string                `json:"backRelationKeyID"`     // 属性视图关联列回链关联列的 ID
	RemoveDest        bool                  `json:"removeDest"`            // 属性视图删除关联目标
	Layout            av.LayoutType         `json:"layout"`                // 属性视图布局类型
	GroupID           string                `json:"groupID"`               // 属性视图分组视图 ID
	TargetGroupID     string                `json:"targetGroupID"`         // 属性视图目标分组视图 ID
	ViewID            string                `json:"viewID"`                // 属性视图视图 ID
	ViewIDs           []string              `json:"viewIDs,omitempty"`     // 数据库视图 ID 列表
	IgnoreDefaultFill bool                  `json:"ignoreDefaultFill"`     // 是否忽略默认填充

	Context map[string]any `json:"context"` // 上下文信息
	// contains filtered or unexported fields
}

func BuildBlockUpdateOperations

func BuildBlockUpdateOperations(inputs []BlockUpdateInput) (operations []*Operation, rootIDs []string, err error)

BuildBlockUpdateOperations 解析并校验所有块更新,全部通过后返回可执行的事务操作。

func (*Operation) IsAutomaticAttributeViewOperation

func (operation *Operation) IsAutomaticAttributeViewOperation() bool

IsAutomaticAttributeViewOperation 供块 API 保持仅返回原始块操作的响应格式。

func (*Operation) ResolveRelationDetailStorage

func (op *Operation) ResolveRelationDetailStorage() (boxID string, scoped bool, err error)

ResolveRelationDetailStorage 固定当前请求的真实来源边界,供 API 在解析数据库前取得相同笔记本租约。

type OutlineDoc

type OutlineDoc struct {
	DocID string         `json:"docID"`
	Data  map[string]any `json:"data"`
}

type PDFImageExtractResult

type PDFImageExtractResult struct {
	Page      int               `json:"page"`
	Object    int               `json:"object"`
	Artifact  *ImageArtifactRef `json:"artifact,omitempty"`
	SourceURL string            `json:"sourceURL,omitempty"`
	Error     string            `json:"error,omitempty"`
}

func ExtractPDFImages

func ExtractPDFImages(ctx context.Context, source PDFImageSource, revision, targetDocumentID string, selections []PDFImageSelection) (ret []PDFImageExtractResult, err error)

type PDFImageInfo

type PDFImageInfo struct {
	Page     int    `json:"page"`
	Object   int    `json:"object"`
	Width    int    `json:"width"`
	Height   int    `json:"height"`
	Encoding string `json:"encoding"`
}

type PDFImageList

type PDFImageList struct {
	Revision  string         `json:"revision"`
	PageCount int            `json:"pageCount"`
	Images    []PDFImageInfo `json:"images"`
	Total     int            `json:"total"`
	Offset    int            `json:"offset"`
	HasMore   bool           `json:"hasMore"`
}

func ListPDFImages

func ListPDFImages(ctx context.Context, source PDFImageSource, pages []int, offset, limit int, revision string) (ret PDFImageList, err error)

type PDFImageSelection

type PDFImageSelection struct {
	Revision string `json:"revision"`
	Page     int    `json:"page"`
	Object   int    `json:"object"`
}

PDFImageSelection 将对象编号绑定到认证读取后的 PDF 内容版本,避免文件替换后读取另一张图。

type PDFImageSource

type PDFImageSource struct {
	DocumentID string
	Path       string
}

type Path

type Path struct {
	ID         string   `json:"id"`                   // 块 ID
	Box        string   `json:"box"`                  // 块 Box
	Name       string   `json:"name"`                 // 当前路径
	NameIsHTML bool     `json:"nameIsHTML,omitempty"` // Name 是否为渲染后的 HTML,前端据此决定是否转义
	Number     string   `json:"number,omitempty"`     // 标题编号
	HPath      string   `json:"hPath"`                // 人类可读路径
	Type       string   `json:"type"`                 // "path"
	NodeType   string   `json:"nodeType"`             // 节点类型
	SubType    string   `json:"subType"`              // 节点子类型
	Blocks     []*Block `json:"blocks,omitempty"`     // 子块节点
	Children   []*Path  `json:"children,omitempty"`   // 子路径节点
	Depth      int      `json:"depth"`                // 层级深度
	Count      int      `json:"count"`                // 子块计数
	Folded     bool     `json:"folded"`               // 是否折叠

	Updated string `json:"updated"` // 更新时间
	Created string `json:"created"` // 创建时间
}

func FilterPathsByPublishAccess

func FilterPathsByPublishAccess(c *gin.Context, publishAccess PublishAccess, paths []*Path) (ret []*Path)

func GetBacklink2

func GetBacklink2(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool) (boxID string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int)

func GetBacklink2InBox

func GetBacklink2InBox(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool, boxID string) (boxIDOut string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int)

GetBacklink2InBox 与 GetBacklink2 一致,但按 boxID 路由到加密 db 或全局 db。

func GetBacklink2InBoxWithFilter

func GetBacklink2InBoxWithFilter(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool, boxID string, sourceFilter *BacklinkSourceFilter) (boxIDOut string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int)

func GetBacklink2InBoxWithOptions

func GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool, boxID string, sourceFilter *BacklinkSourceFilter, includeMentions, includeBacklinks bool, notifiers ...BackmentionNotifier) (boxIDOut string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int)

GetBacklink2InBoxWithOptions 按需查询反链文档分组与提及列表。

func GetBacklink2WithFilter

func GetBacklink2WithFilter(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool, sourceFilter *BacklinkSourceFilter) (boxID string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int)

func Outline

func Outline(rootID string, preview bool) (ret []*Path, err error)

func OutlineInBox

func OutlineInBox(rootID string, preview bool, boxID string) (ret []*Path, err error)

OutlineInBox 与 Outline 一致,但按 boxID 路由 blocktree 查询到加密 db 或全局 db。

type PdfAssetParser

type PdfAssetParser struct {
}

PdfAssetParser parser factory product

func (*PdfAssetParser) Parse

func (parser *PdfAssetParser) Parse(absPath string) (ret *AssetParseResult)

Parse will parse a PDF document using PDFium webassembly module using a worker pool

type Petal

type Petal struct {
	Name                  string `json:"name"`                     // Plugin name
	DisplayName           string `json:"displayName"`              // Plugin display name
	Version               string `json:"version"`                  // Plugin version
	Enabled               bool   `json:"enabled"`                  // Whether enabled
	Incompatible          bool   `json:"incompatible"`             // Whether incompatible
	DisabledInPublish     bool   `json:"disabledInPublish"`        // Whether disabled in publish mode
	UserDisabledInPublish bool   `json:"userDisabledInPublish"`    // 是否由用户在发布服务中禁用
	DisallowInstall       bool   `json:"disallowInstall"`          // Whether disallow install
	SettingsWindow        bool   `json:"settingsWindow,omitempty"` // 已验证设置窗口运行声明

	JS     string         `json:"js"`     // JS code
	CSS    string         `json:"css"`    // CSS code
	I18n   map[string]any `json:"i18n"`   // i18n text
	Kernel KernelPetal    `json:"kernel"` // Kernel plugin info
}

Petal represents a plugin's management status.

func GetPetalByName

func GetPetalByName(name string) (ret *Petal)

func LoadKernelPetals

func LoadKernelPetals() (ret []*Petal)

func LoadPetals

func LoadPetals(frontend string, isPublish bool, names []string) (ret []*Petal)

func LoadSettingsWindowPetals

func LoadSettingsWindowPetals(frontend string, isPublish bool, names []string) (ret []*Petal)

LoadSettingsWindowPetals 保留启用、信任、前端兼容和发布权限检查,只返回主动声明支持设置窗口的插件。

func SetPetalEnabled

func SetPetalEnabled(name string, enabled bool) (ret *Petal, err error)

func SetPetalPublishEnabled

func SetPetalPublishEnabled(name string, enabled bool) (ret *Petal, err error)

type PinnedDoc

type PinnedDoc struct {
	ID, Notebook, Name, Path, Icon string
	HSize, HMtime, HCtime          string
	Name1, Alias, Memo, Bookmark   string
	SubFileCount                   int
	Unavailable                    bool
	SpecTooNew                     bool
	ChildrenSortMode               *int
}

func GetPinnedDocs

func GetPinnedDocs() (ret []PinnedDoc, err error)

置顶只保存普通文档的标识,名称和子文档始终从源文档读取。

type PluginPublishDeclaration

type PluginPublishDeclaration struct {
	Resources []string `json:"resources"`
	Data      []string `json:"data"`
}

PluginPublishDeclaration 的资源为精确文件名或以 / 结尾的递归目录,数据为可公开的顶层标量字段。

type PluginPublishInfo

type PluginPublishInfo struct {
	Resources []string `json:"resources"`
	Fields    []string `json:"fields"`
	Granted   bool     `json:"granted"`
}

func GetPluginPublishInfo

func GetPluginPublishInfo(name string) (PluginPublishInfo, error)

type PptxAssetParser

type PptxAssetParser struct {
}

func (*PptxAssetParser) Parse

func (parser *PptxAssetParser) Parse(absPath string) (ret *AssetParseResult)

type PreparedDocumentImage

type PreparedDocumentImage struct {
	Artifact ImageArtifactRef   `json:"artifact"`
	Data     []byte             `json:"-"`
	MIMEType string             `json:"mimeType"`
	Prepared util.PreparedImage `json:"-"`
}

func PrepareAgentMessageImage

func PrepareAgentMessageImage(assetPath string) (PreparedDocumentImage, error)

PrepareAgentMessageImage 校验并读取智能体用户消息引用的全局资源图片。

func PrepareDocumentImage

func PrepareDocumentImage(documentID, assetPath string) (PreparedDocumentImage, error)

PrepareDocumentImage 校验并读取文档实际引用的本地资源图片,供当前模型直接接收图片输入。

type PublishAccess

type PublishAccess []*PublishAccessItem

func GetDisablePublishAccess

func GetDisablePublishAccess(inputPublishAccess PublishAccess) (outputPublishAccess PublishAccess)

func GetInvisiblePublishAccess

func GetInvisiblePublishAccess(inputPublishAccess PublishAccess) (outputPublishAccess PublishAccess)

func GetPublishAccess

func GetPublishAccess() (ret PublishAccess)

type PublishAccessItem

type PublishAccessItem struct {
	ID       string `json:"id"`
	Visible  bool   `json:"visible"`  // 是否发布可见
	Password string `json:"password"` // 密码,为空字符串时表示无密码
	Disable  bool   `json:"disable"`  // 是否禁止发布
}

type PublishAccessStatus

type PublishAccessStatus int
const (
	PublishAccessAllowed PublishAccessStatus = iota
	PublishAccessPasswordRequired
	PublishAccessDenied
)

func FilterContentByPublishAccessWithStatus

func FilterContentByPublishAccessWithStatus(c *gin.Context, publishAccess PublishAccess, box string, docPath string, content string, onlyIcon bool) (ret string, status PublishAccessStatus)

func GetBlockTreePublishAccessStatus

func GetBlockTreePublishAccessStatus(c *gin.Context, publishAccess PublishAccess, bt *treenode.BlockTree) PublishAccessStatus

type PublishSession

type PublishSession struct {
	Username          string
	CredentialVersion string
	LastActive        time.Time
}

PublishSession 发布服务会话,记录所属用户名、凭据版本与最近活跃时间。

type Reaction

type Reaction[C any] struct {
	Name    string
	Changed func(old, next C) bool
	Apply   func(old, next C)
}

type RecentDoc

type RecentDoc struct {
	RootID   string `json:"rootID"`
	Icon     string `json:"icon,omitempty"`
	Title    string `json:"title,omitempty"`
	ViewedAt int64  `json:"viewedAt,omitempty"` // 浏览时间字段
	ClosedAt int64  `json:"closedAt,omitempty"` // 关闭时间字段
	OpenAt   int64  `json:"openAt,omitempty"`   // 文档第一次从文档树加载到页签的时间
}

func FilterRecentDocsByPublishAccess

func FilterRecentDocsByPublishAccess(c *gin.Context, publishAccess PublishAccess, recentDocs []*RecentDoc) (ret []*RecentDoc)

func GetRecentDocs

func GetRecentDocs(sortBy string) (ret []*RecentDoc, err error)

type RefDefs

type RefDefs struct {
	RefID  string   `json:"refID"`
	DefIDs []string `json:"defIDs"`
}

func FilterRefDefsByPublishAccess

func FilterRefDefsByPublishAccess(c *gin.Context, publishAccess PublishAccess, refDefs []*RefDefs) (retRefDefs []*RefDefs, originalRefBlockIDs map[string]string)

func GetBlockRefsInBox

func GetBlockRefsInBox(defID, boxID string) (refDefs []*RefDefs, originalRefBlockIDs map[string]string)

GetBlockRefsInBox 获取指定笔记本内的块引用关系。空 box 不回退搜索加密笔记本。

type ReorderResult

type ReorderResult struct {
	Changed    bool   `json:"changed"`
	Notebook   string `json:"notebook,omitempty"`
	ParentPath string `json:"parentPath,omitempty"`
}

ReorderResult 描述相对排序操作的结果。

func ReorderDocs

func ReorderDocs(sourceIDs []string, targetID, position string) (ret *ReorderResult, err error)

ReorderDocs 将同级文档移动到目标文档之前或之后。

func ReorderNotebooks

func ReorderNotebooks(sourceIDs []string, targetID, position string) (ret *ReorderResult, err error)

ReorderNotebooks 将笔记本移动到目标笔记本之前或之后。

type RepoDocHistory

type RepoDocHistory struct {
	FileID    string                `json:"fileID"`
	IndexID   string                `json:"indexID"`
	Title     string                `json:"title"`
	HSize     string                `json:"hSize"`
	Updated   int64                 `json:"updated"`
	Snapshots []*DocHistorySnapshot `json:"snapshots"`
}

func GetRepoDocHistory

func GetRepoDocHistory(id string, page int) (ret []*RepoDocHistory, pageCount, totalCount int, err error)

type RichClipboardAsset

type RichClipboardAsset struct {
	Index int
	Path  string
	Box   string
}

type RichClipboardPrepared

type RichClipboardPrepared struct {
	Batch  string                       `json:"batch"`
	Groups []string                     `json:"groups"`
	Assets []RichClipboardPreparedAsset `json:"assets"`
}

func PrepareRichClipboardAssets

func PrepareRichClipboardAssets(assets []RichClipboardAsset) (ret *RichClipboardPrepared, err error)

type RichClipboardPreparedAsset

type RichClipboardPreparedAsset struct {
	Index int    `json:"index"`
	Path  string `json:"path"`
}

type RiffCard

type RiffCard struct {
	Due        time.Time  `json:"due"`
	Reps       uint64     `json:"reps"`
	Lapses     uint64     `json:"lapses"`
	State      fsrs.State `json:"state"`
	LastReview time.Time  `json:"lastReview"`
}

type Role

type Role uint
const (
	RoleAdministrator Role = iota // 管理员
	RoleEditor                    // 编辑者
	RoleReader                    // 读者
	RoleVisitor                   // 匿名访问者
)

func GetClaimRole

func GetClaimRole(claims jwt.MapClaims) Role

func GetGinContextRole

func GetGinContextRole(c *gin.Context) Role

GetGinContextRole 返回请求角色,无上下文或无角色时按最受限的匿名访问者处理。

type SearchAttributeViewOptions

type SearchAttributeViewOptions struct {
	Keyword            string
	ExcludeAvIDs       []string
	CurrentAvID        string
	CurrentBlockID     string
	IncludeViewMatches bool
}

type SearchSubTypes

type SearchSubTypes struct {
	Heading  map[string]bool `json:"heading"`
	List     map[string]bool `json:"list"`
	ListItem map[string]bool `json:"listItem"`
}

SearchSubTypes 保存各父类型的子类型选择,未知顶层字段由 JSON 解析器忽略。

type SectionSpec

type SectionSpec[C any] struct {
	Config    *AppConf
	Namespace string
	Load      func() C
	Store     func(C)
	Normalize func(C) C
	Validate  func(C) []Issue
	WriteLock *sync.Mutex
	Reactions []Reaction[C]
}

SectionSpec 集中描述配置段规范化、诊断和反应,写锁仅属于该配置段。

type SetFileTreeSortResult

type SetFileTreeSortResult struct {
	NotebookIDs []string `json:"notebookIDs"`
	DocIDs      []string `json:"docIDs"`
}

func SetFileTreeSort

func SetFileTreeSort(notebookSorts, docSorts []*SortItem) (ret *SetFileTreeSortResult, err error)

type SetFlashcardDueTime

type SetFlashcardDueTime struct {
	ID  string `json:"id"`  // 卡片 ID
	Due string `json:"due"` // 下次复习时间,格式为 YYYYMMDDHHmmss
}

type Snapshot

type Snapshot struct {
	*dejavu.Log
	Tags             []string     `json:"tags"`
	TypesCount       []*TypeCount `json:"typesCount"`
	RequiresDownload bool         `json:"requiresDownload"`
}

func GetRepoSnapshots

func GetRepoSnapshots(page int) (ret []*Snapshot, pageCount, totalCount int, err error)

func GetRepoSnapshotsByTime

func GetRepoSnapshotsByTime(page int, startTime, endTime int64) (ret []*Snapshot, pageCount, totalCount int, err error)

func GetTagSnapshots

func GetTagSnapshots() (ret []*Snapshot, err error)

func SearchRepoSnapshot

func SearchRepoSnapshot(id string, includeFiles bool) (ret []*Snapshot, pageCount, totalCount int, err error)

SearchRepoSnapshot 按完整 ID 或至少 7 位前缀读取本地快照,复用列表的元数据和下载状态计算。

type SortItem

type SortItem struct {
	ID   string `json:"id"`
	Sort int    `json:"sort"`
}

type Sync

type Sync struct {
	Size      int64  `json:"size"`
	HSize     string `json:"hSize"`
	Updated   string `json:"updated"`
	CloudName string `json:"cloudName"` // 云端同步数据存放目录名
	SaveDir   string `json:"saveDir"`   // 本地同步数据存放目录路径
}

func ListCloudSyncDir

func ListCloudSyncDir() (syncDirs []*Sync, hSize string, err error)

type SyncLANStatus

type SyncLANStatus struct {
	Enabled           bool `json:"enabled"`
	Active            bool `json:"active"`
	DiscoveredPeers   int  `json:"discoveredPeers"`
	ConnectedPeers    int  `json:"connectedPeers"`
	MaxConcurrentReqs int  `json:"maxConcurrentReqs"`
}

func GetSyncLANStatus

func GetSyncLANStatus() SyncLANStatus

type SyncSourceDecision

type SyncSourceDecision struct{ Source, LocalID, CloudID string }

SyncSourceDecision pins an explicit choice to the source and snapshots shown in the preview.

type Tag

type Tag struct {
	Name     string `json:"name"`
	Label    string `json:"label"`
	Children Tags   `json:"children"`
	Type     string `json:"type"` // "tag"
	Depth    int    `json:"depth"`
	Count    int    `json:"count"`
	// contains filtered or unexported fields
}

type TagBlocks

type TagBlocks []*Block

type Tags

type Tags []*Tag

func BuildTags

func BuildTags(ignoreMaxListHintArg bool, appID string, sortVal int) (ret *Tags)

func FilterTagsByPublishAccess

func FilterTagsByPublishAccess(c *gin.Context, publishAccess PublishAccess, tags *Tags) (ret *Tags)

type TemplateDatabaseMode

type TemplateDatabaseMode string
const (
	TemplateDatabaseModeCopy      TemplateDatabaseMode = "copy"
	TemplateDatabaseModeReference TemplateDatabaseMode = "reference"
)

type TemplateDocTreeNode

type TemplateDocTreeNode struct {
	ID       string                 `json:"id"`
	RootID   string                 `json:"-"`
	Title    string                 `json:"title"`
	ParentID string                 `json:"parentID"`
	HPath    string                 `json:"hPath"`
	Depth    int                    `json:"depth"`
	Template string                 `json:"-"`
	Define   string                 `json:"-"`
	Children []*TemplateDocTreeNode `json:"-"`
	// contains filtered or unexported fields
}

TemplateDocTreeNode 是模板声明的单个子文档,解析时先分配 ID,绑定父文档后再补全位置。

type TemplateDocTreePlanSummary

type TemplateDocTreePlanSummary struct {
	ID    string                 `json:"id"`
	Count int                    `json:"count"`
	Nodes []*TemplateDocTreeNode `json:"nodes"`
}

func PreviewTemplateSource

func PreviewTemplateSource(p, id, content string) (tree *parse.Tree, dom string, summary *TemplateDocTreePlanSummary, err error)

编辑器预览使用未保存的源码,文件路径仅用于解析同包子模板。

func RenderTemplateWithHTTP

func RenderTemplateWithHTTP(p, id string, mode TemplateRenderMode, content *string, execution *templatehttp.Execution) (tree *parse.Tree, dom string, summary *TemplateDocTreePlanSummary, err error)

RenderTemplateWithHTTP 在同一次函数调用中等待确认,关闭请求后丢弃渲染结果。

func RenderTemplateWithHTTPHandoff

func RenderTemplateWithHTTPHandoff(p, id string, mode TemplateRenderMode, content *string,
	execution *TemplateHTTPExecution, token string) (tree *parse.Tree, dom string,
	summary *TemplateDocTreePlanSummary, handoffToken string, err error)

RenderTemplateWithHTTPHandoff 只复用短期确认,插入仍重新请求外部数据。

func RenderTemplateWithMode

func RenderTemplateWithMode(p, id string, mode TemplateRenderMode) (tree *parse.Tree, dom string,
	summary *TemplateDocTreePlanSummary, err error)

type TemplateFileEntry

type TemplateFileEntry struct {
	Path           string `json:"path"`
	IsDir          bool   `json:"isDir"`
	IsPackage      bool   `json:"isPackage,omitempty"`
	HTTPPermission bool   `json:"httpPermission"`
}

type TemplateFileRequest

type TemplateFileRequest struct {
	Action   string `json:"action"`
	Path     string `json:"path"`
	Target   string `json:"target"`
	Content  string `json:"content"`
	Revision string `json:"revision"`
}

type TemplateHTTPExecution

type TemplateHTTPExecution struct {
	Runtime *templatehttp.Execution
	// contains filtered or unexported fields
}

TemplateHTTPExecution 将联网执行绑定到发起窗口,并校验实际模板来源的许可。

func StartTemplateHTTPExecution

func StartTemplateHTTPExecution(ctx context.Context, id, app, sessionID, scope string, boxIDs ...string) (*TemplateHTTPExecution, error)

func (*TemplateHTTPExecution) Close

func (execution *TemplateHTTPExecution) Close()

type TemplateHTTPPermission

type TemplateHTTPPermission struct {
	ID      string `json:"id"`
	Kind    string `json:"kind"`
	Label   string `json:"label"`
	Granted bool   `json:"granted"`
}

func ListTemplateHTTPPermissions

func ListTemplateHTTPPermissions() ([]TemplateHTTPPermission, error)

type TemplateHTTPSource

type TemplateHTTPSource struct {
	ID, Version, Kind, Label string
	Persistable              bool
	// contains filtered or unexported fields
}

TemplateHTTPSource 只由内核读取的源码生成,界面不能提交来源身份来创建许可。

func ReadTemplateHTTPFile

func ReadTemplateHTTPFile(filename string) ([]byte, *TemplateHTTPSource, error)

ReadTemplateHTTPFile 的身份、摘要和执行内容来自同一次受限文件读取。

func ResolveTemplateHTTPAutomationSource

func ResolveTemplateHTTPAutomationSource(owner, avID string, rule *av.AutomationRule) (*TemplateHTTPSource, error)

func ResolveTemplateHTTPDBSource

func ResolveTemplateHTTPDBSource(owner, avID, fieldID, slot, content string) (*TemplateHTTPSource, error)

ResolveTemplateHTTPDBSource 普通数据库属于全局存储,加密数据库使用真实笔记本 ID。

func ResolveTemplateHTTPInlineSource

func ResolveTemplateHTTPInlineSource(filename string, data []byte) (*TemplateHTTPSource, error)

ResolveTemplateHTTPInlineSource 只有与内核读取的当前磁盘内容一致时才能建立持久许可。

type TemplateRenderMode

type TemplateRenderMode string
const (
	TemplateRenderModeContent      TemplateRenderMode = "content"
	TemplateRenderModePreview      TemplateRenderMode = "preview"
	TemplateRenderModeEditorInsert TemplateRenderMode = "editorInsert"
)

type TemplateSearchResult

type TemplateSearchResult struct {
	Path         string `json:"path"`
	RelativePath string `json:"relativePath"`
	Content      string `json:"content"`
}

TemplateSearchResult 描述了模板搜索结果。

func SearchTemplate

func SearchTemplate(keyword string) (ret []*TemplateSearchResult)

type ThemeInstallOptions

type ThemeInstallOptions struct {
	Mode   int
	ModeOS bool
}

ThemeInstallOptions 描述新安装主题后需要应用的外观模式

type Transaction

type Transaction struct {
	CollectionRemovalSourceVersions map[string]string `json:"collectionRemovalSourceVersions,omitempty"`
	Timestamp                       int64             `json:"timestamp"`
	DoOperations                    []*Operation      `json:"doOperations"`
	UndoOperations                  []*Operation      `json:"undoOperations"`
	TemplateDocTreePlanID           string            `json:"templateDocTreePlanID,omitempty"`
	// contains filtered or unexported fields
}

func GetHeadingDeleteTransaction

func GetHeadingDeleteTransaction(id string) (transaction *Transaction, err error)

func GetHeadingFoldTransaction

func GetHeadingFoldTransaction(id, scope string) (transaction *Transaction, err error)

GetHeadingFoldTransaction 生成直接子标题或同级标题的批量折叠事务。

func GetHeadingInsertTransaction

func GetHeadingInsertTransaction(id string) (transaction *Transaction, err error)

func GetHeadingLevelBatchTransaction

func GetHeadingLevelBatchTransaction(ids []string, level int) (transaction *Transaction, err error)

func MigrateLegacyMindmaps

func MigrateLegacyMindmaps(id string) (tx *Transaction, visible map[string]string, err error)

MigrateLegacyMindmaps 在事务串行区内读取完整文档,迁移后返回调用方当前显示块的权威内容。

func PerformBlockOperation

func PerformBlockOperation(operation *Operation) (transactions []*Transaction, err error)

PerformBlockOperation 在事务串行区内校验并执行外部块操作,返回实际执行结果。

func PerformBlockUpdates

func PerformBlockUpdates(inputs []BlockUpdateInput) (transactions []*Transaction, rootIDs []string, err error)

PerformBlockUpdates 在事务串行区内准备并同步执行外部块更新。

func RemoveTagWithCollections

func RemoveTagWithCollections(request apicontract.RemoveTagWithCollectionsRequest) (*Transaction, error)

全局标签删除使用普通编辑事务,源标签和用户选择移出的字段共用撤销记录。

func RunAttributeViewHTTPAutomation

func RunAttributeViewHTTPAutomation(ctx context.Context, job *attributeViewHTTPAutomation, runtime *TemplateHTTPExecution) (*Transaction, error)

func (*Transaction) GetChangedRootIDs

func (tx *Transaction) GetChangedRootIDs() (ret []string)

func (*Transaction) GetMutatedRootIDs

func (tx *Transaction) GetMutatedRootIDs() (ret []string)

GetMutatedRootIDs 返回真正被写盘修改结构的树 rootID,不含 refreshDynamicRefTexts 刷新的引用树。 用于跨文档撤销判定:单文档编辑返回 1 个 rootID,跨文档移动返回多个,引用文本刷新不计入。

func (*Transaction) HTTPAutomationJobs

func (tx *Transaction) HTTPAutomationJobs() []*apicontract.AVHTTPAutomationJob

func (*Transaction) MarkFromAPI

func (tx *Transaction) MarkFromAPI()

MarkFromAPI 标记事务来自 /api/transactions HTTP 入口,供全局撤销日志捕获判别。

func (*Transaction) MarkReplay

func (tx *Transaction) MarkReplay()

MarkReplay 标记事务为 undo/redo 重放构造,重放不再进入撤销日志。

func (*Transaction) SetHTTPAutomationOwner

func (tx *Transaction) SetHTTPAutomationOwner(app, session string)

func (*Transaction) WaitForCommit

func (tx *Transaction) WaitForCommit()

type TxErr

type TxErr struct {
	// contains filtered or unexported fields
}

func (*TxErr) Code

func (e *TxErr) Code() int

Code 返回事务错误码。

func (*TxErr) Error

func (e *TxErr) Error() string

Error 实现 error 接口,供跨包(如 undo API)读取事务错误信息。

func (*TxErr) Unwrap

func (e *TxErr) Unwrap() error

type TxtAssetParser

type TxtAssetParser struct {
}

func (*TxtAssetParser) Parse

func (parser *TxtAssetParser) Parse(absPath string) (ret *AssetParseResult)

type TypeCount

type TypeCount struct {
	Type  string `json:"type"`
	Count int    `json:"count"`
}

type UndoEntry

type UndoEntry struct {
	// contains filtered or unexported fields
}

UndoEntry 是撤销栈中的一条记录。跨文档操作(MutatedRootIDs 含多个 rootID)的 entry 会以同一指针同时挂在这些 rootID 的栈上,撤销任一端时联动其他端移除引用。

func (*UndoEntry) DoOperationsForReplay

func (e *UndoEntry) DoOperationsForReplay() []*Operation

DoOperationsForReplay 返回正向操作副本,供 redo 重放构造事务。

func (*UndoEntry) MutatedRootIDs

func (e *UndoEntry) MutatedRootIDs() []string

MutatedRootIDs 返回该条目影响的 rootID 列表副本。

func (*UndoEntry) UndoOperationsForReplay

func (e *UndoEntry) UndoOperationsForReplay() []*Operation

UndoOperationsForReplay 返回逆向操作副本,供 undo 重放构造事务。

type UndoLog

type UndoLog struct {
	// contains filtered or unexported fields
}

UndoLog 是全局撤销日志,按 rootID 分栈,所有窗口/客户端共享同一权威。

func (*UndoLog) Clear

func (l *UndoLog) Clear(rootID string)

Clear 清理撤销日志。rootID 非空时清该文档栈并联动移除其他栈中相关条目;为空时清空全部。

func (*UndoLog) ClearAttributeView

func (l *UndoLog) ClearAttributeView(avID string)

ClearAttributeView 从各文档栈清理涉及指定数据库的整笔撤销、重做记录,保留无关记录。 非编辑器事务移除绑定条目后,旧记录不能再安全地重放单元格编辑或数据库快照。

func (*UndoLog) Peek

func (l *UndoLog) Peek(rootID string) *UndoEntry

Peek 返回 rootID 撤销栈顶(不弹出),栈空返回 nil。

func (*UndoLog) Record

func (l *UndoLog) Record(tx *Transaction)

Record 记录一笔已提交的编辑器事务。仅当事务来自 /api/transactions(fromAPI)、 携带非空 UndoOperations、且非 undo/redo 重放(isReplay)时记录。

func (*UndoLog) Redo

func (l *UndoLog) Redo(rootID string) *UndoEntry

Redo 弹出 rootID 重做栈顶,压回执行栈撤销栈。仅动执行栈,不做联动重挂。 不改 hasUndo(复现前端 redo 的不对称)。成功后调 RedoCommit;失败调 RedoRollback。

func (*UndoLog) RedoCommit

func (l *UndoLog) RedoCommit(entry *UndoEntry, rootID string)

RedoCommit 在重做成功执行后,联动把 entry 重新挂到其他关联栈顶。

func (*UndoLog) RedoRollback

func (l *UndoLog) RedoRollback(entry *UndoEntry, rootID string)

RedoRollback 在重做执行失败时回滚执行栈:把 entry 从撤销栈移回重做栈顶。 因 Redo 只动了执行栈,此回滚精确无误。

func (*UndoLog) State

func (l *UndoLog) State(rootID string) (canUndo, canRedo bool, peekMutatedRootIDs []string)

State 返回 rootID 的撤销/重做可用性及栈顶关联的 mutatedRootIDs。

func (*UndoLog) Undo

func (l *UndoLog) Undo(rootID string) *UndoEntry

Undo 弹出 rootID 撤销栈顶,压入执行栈重做栈,置 hasUndo。仅动执行栈,不做联动移除。 成功执行逆操作后调 UndoCommit 完成联动;失败调 UndoRollback 精确回滚(因只动了执行栈)。 返回弹出的 entry;栈空返回 nil。

func (*UndoLog) UndoCommit

func (l *UndoLog) UndoCommit(entry *UndoEntry, rootID string)

UndoCommit 在逆操作成功执行后,联动从其他关联栈移除该 entry(按 id 匹配)。

func (*UndoLog) UndoRollback

func (l *UndoLog) UndoRollback(entry *UndoEntry, rootID string)

UndoRollback 在逆操作执行失败时回滚执行栈:把 entry 从重做栈移回撤销栈顶,复位 hasUndo。 因 Undo 只动了执行栈,此回滚精确无误。

type UnusedItem

type UnusedItem struct {
	Item     string    `json:"item"`
	Name     string    `json:"name"`
	Path     string    `json:"path,omitempty"`
	BlockIDs []string  `json:"blockIDs,omitempty"`
	ModTime  time.Time `json:"-"`
	AbsPath  string    `json:"-"`
}

func MissingAssets

func MissingAssets() (ret []*UnusedItem, err error)

func UnusedAssets

func UnusedAssets(sorted bool) (ret []*UnusedItem, err error)

func UnusedAttributeViews

func UnusedAttributeViews(sorted bool) (ret []*UnusedItem, err error)

func UnusedEncryptedBoxAssets

func UnusedEncryptedBoxAssets(ctx context.Context, boxID string) (items []*UnusedItem, err error)

UnusedEncryptedBoxAssets 只扫描目标加密笔记本,明文解析结果不写入全局缓存。

type UpdatedPackage

type UpdatedPackage struct {
	Installed *bazaar.Package `json:"installed"`
	Available *bazaar.Package `json:"available"`
}

UpdatedPackage 描述本地已安装包及其在线可用更新

func GetUpdatedPackages

func GetUpdatedPackages(frontend string) (plugins, widgets, icons, themes, templates []*UpdatedPackage, err error)

GetUpdatedPackages 获取所有类型集市包的更新列表

  • frontend 仅用于插件和主题环境兼容性判断

type ValidationError

type ValidationError struct{ Issues []Issue }

func (*ValidationError) Error

func (err *ValidationError) Error() string

type ViewState

type ViewState struct {
	Updated int64          `json:"updatedAt"`
	Data    map[string]any `json:"data"`
	Order   []string       `json:"fieldOrder,omitempty"`
}

type WidgetSearchResult

type WidgetSearchResult struct {
	Name    string `json:"name"`
	Content string `json:"content"`
}

WidgetSearchResult 描述了挂件搜索结果。

func SearchWidget

func SearchWidget(keyword string) (ret []*WidgetSearchResult)

type WorkspaceAVBuiltinColorUpdate

type WorkspaceAVBuiltinColorUpdate struct {
	Index      int               `json:"index"`
	Customized bool              `json:"customized"`
	Light      *InlineStyleTheme `json:"light"`
	Dark       *InlineStyleTheme `json:"dark"`
	Hidden     bool              `json:"hidden"`
}

type WorkspaceAVPaletteUpdate

type WorkspaceAVPaletteUpdate struct {
	Colors        []*av.AttributeViewCustomColor   `json:"colors"`
	Order         []string                         `json:"order"`
	BuiltinColors []*WorkspaceAVBuiltinColorUpdate `json:"builtinColors"`
}

type XlsxAssetParser

type XlsxAssetParser struct {
}

func (*XlsxAssetParser) Parse

func (parser *XlsxAssetParser) Parse(absPath string) (ret *AssetParseResult)

Source Files

Directories

Path Synopsis
Package mcpoauth 实现仅用于内置 MCP 的授权码、刷新和撤销,持久化文件只保存凭证摘要。
Package mcpoauth 实现仅用于内置 MCP 的授权码、刷新和撤销,持久化文件只保存凭证摘要。

Jump to

Keyboard shortcuts

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