vault_import

package
v0.0.0-...-95891f2 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: AGPL-3.0 Imports: 33 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package vault_import turns a .zip of an Obsidian vault (or any folder of Markdown notes, including Notion and Trilium Markdown exports) into Chronicle pages.

Everything in the zip is attacker input, so the package is built in layers that never trust the one before it: archive.go admits entries (paths, sizes, ratios), vault.go reads notes and resolves links without writing anything (that is the preview), and runner.go is the only code that touches the campaign, through the narrow interfaces in ports.go. The package never imports another plugin; internal/app adapts the pages, media and page-file services to those interfaces.

Index

Constants

View Source
const (
	StateRunning = "running"
	StateDone    = "done"
	StateFailed  = "failed"
)

Job states.

View Source
const SettingsTabID = "import"

SettingsTabID is the Import tab's id on the campaign Settings page.

Variables

View Source
var DefaultLimits = Limits{
	MaxUploadBytes: 200 << 20,
	MaxEntries:     10000,
	MaxTotalBytes:  600 << 20,
	MaxFileBytes:   25 << 20,
	MaxNoteBytes:   2 << 20,
	MaxRatio:       200,
	MaxDepth:       24,
	MaxPathBytes:   1024,
}

DefaultLimits suit a large vault (a few thousand notes and their pictures) while keeping one request's worst case small enough to hold in a campaign's storage quota and the server's memory.

View Source
var ErrBusy = errors.New("an import is already running")

ErrBusy is returned when an import for the campaign is already running, or the server is at its limit.

Functions

func CleanEntryName

func CleanEntryName(raw string, lim Limits) (string, error)

CleanEntryName validates a name exactly as stored in the zip and returns it without a trailing slash. Backslashes, absolute paths, drive letters, "..", "." and empty segments, control characters and invalid UTF-8 are all refused: the importer never writes these names to disk, but a name that cannot be trusted also cannot be trusted to mean what a link says.

func DisplayName

func DisplayName(stem string) string

DisplayName is a file or folder name as a person would say it: without Notion's trailing id, without surrounding spaces.

func IsArchiveError

func IsArchiveError(err error) bool

IsArchiveError reports whether err is a refusal to show the owner as is.

func IsPictureName

func IsPictureName(name string) bool

IsPictureName reports whether a file name is a picture that can sit inside page text.

func Prepare

func Prepare(body string) string

Prepare rewrites the Obsidian-only syntax that has no Markdown meaning, so it does not show up as stray punctuation: %%comments%% vanish, ^block-ids vanish, and a "> [!note] Title" callout becomes a quote that opens with its title in bold. Code is left exactly as written.

func RegisterOwnerRoutes

func RegisterOwnerRoutes(cg *echo.Group, h *Handler, requireOwner echo.MiddlewareFunc)

RegisterOwnerRoutes mounts Settings > Import's routes on a /campaigns/:id group that already enforces sign-in and campaign access. Every route is owner-only: the import creates pages and uploads files under the owner's name. The two that take input or start work are also rate limited.

func RegisterRoutes

func RegisterRoutes(e *echo.Echo, h *Handler, authSvc auth.AuthService, campaignSvc campaigns.CampaignService)

RegisterRoutes mounts the import under /campaigns/:id behind sign-in, campaign access and the owner role. The group is built here so the sign-in requirement for the upload route lives next to the route.

func RequestLimit

func RequestLimit(l Limits) int64

RequestLimit is the largest request body the upload route accepts: the zip plus the multipart framing. The app applies it as a global middleware, ahead of the CSRF check, because that check parses the form (and so spools the body to disk) before the route's own limit could run.

func Rewrite

func Rewrite(body string, refs []Ref, f func(Ref) (string, bool)) string

Rewrite replaces each reference with what f returns for it; a reference f declines (ok=false) is left exactly as written. refs must be in order and not overlap, which ScanRefs guarantees.

Types

type Archive

type Archive struct {
	// Name is the vault's name: the zip's single top folder, else the file name.
	Name    string
	Entries []Entry
	// Ignored counts hidden and system files (".obsidian", ".git", ".DS_Store",
	// "__MACOSX") that are never imported and never worth listing.
	Ignored int
	Skipped []SkippedEntry
	// CaseClashes lists pairs of files whose names differ only by capitals or
	// by how an accent is encoded. Both are imported; link resolution is
	// deterministic about which a link means.
	CaseClashes [][2]string
	// contains filtered or unexported fields
}

Archive is a validated zip. Nothing in it has been extracted: entries are read one at a time, in memory, with a hard size ceiling.

func OpenArchive

func OpenArchive(zipPath, fallbackName string, lim Limits) (*Archive, error)

OpenArchive validates the zip at zipPath against lim. It refuses the whole archive for anything that looks hostile (unsafe paths, a repeated name, too many or too large files, a compression ratio no real notes have, a password), and skips, with a reason, what is merely unsupported (shortcuts, files over the per-file ceiling, unusual compression).

func (*Archive) Close

func (a *Archive) Close() error

Close releases the zip file.

func (*Archive) Read

func (a *Archive) Read(e Entry, max int64) ([]byte, error)

Read returns an entry's bytes, never more than max. The zip's declared size is not trusted: the reader is cut off at max+1 and a longer entry is an error.

type ArchiveError

type ArchiveError struct{ Msg string }

ArchiveError is a refusal whose text is safe and useful to show the owner. Anything else the archive code returns is an internal problem.

func (*ArchiveError) Error

func (e *ArchiveError) Error() string

type AttachCheck

type AttachCheck func(name string) bool

AttachCheck reports whether a file of this name can be attached to a page. The pages service decides; this package only asks.

type AuditLogger

type AuditLogger interface {
	LogCampaignEvent(ctx context.Context, campaignID, userID, action string, details map[string]any)
}

AuditLogger records that an import ran. Optional.

type Deps

type Deps struct {
	Pages    PageStore
	Pictures PictureStore
	Files    FileAttacher
	ToJSON   EditorJSON
	Audit    AuditLogger
	// Lifecycle ends running imports when the server shuts down.
	Lifecycle context.Context
	Limits    Limits
	TempDir   string
	Now       func() time.Time
}

Deps is everything the service needs from the rest of Chronicle.

type EditorJSON

type EditorJSON func(html string) (string, error)

EditorJSON converts sanitised HTML to the editor's document format.

type Entry

type Entry struct {
	Path string
	Kind EntryKind
	Size int64
	// contains filtered or unexported fields
}

Entry is one admitted file. Path is clean, relative to the vault root and always uses "/".

type EntryKind

type EntryKind int

EntryKind says what an admitted archive entry is for.

const (
	// KindNote is a Markdown note that becomes a page.
	KindNote EntryKind = iota
	// KindPicture is a picture that can be shown inside page text.
	KindPicture
	// KindFile is any other file; it can only be attached to a page.
	KindFile
)

type FileAttacher

type FileAttacher interface {
	// CanAttach reports whether a file of this name is a type pages accept.
	CanAttach(name string) bool
	AttachGMOnly(ctx context.Context, campaignID, pageID, userID, name string, data []byte) error
}

FileAttacher puts a file in a page's Files section, GM only.

type FrontMatter

type FrontMatter struct {
	Name        string   `yaml:"name"`
	Type        string   `yaml:"type"`
	Subcategory string   `yaml:"subcategory"`
	Visibility  string   `yaml:"visibility"`
	Tags        []string `yaml:"tags"`
	Description string   `yaml:"description"`
}

FrontMatter carries the keys Chronicle's AI-workspace import reads from a page's YAML header, under the same names. Obsidian properties that mean nothing to Chronicle (cssclasses, dates, aliases) are ignored without noise.

func SplitFrontMatter

func SplitFrontMatter(src string) (fm FrontMatter, body string, hadBlock bool, err error)

SplitFrontMatter separates a leading `---` YAML block from a note's body. It follows Obsidian: the block must start on the very first line, and ends at the next `---` (or `...`) line. A note without one, or with one that is not closed, is all body. err is set when a block was found but is not valid YAML; the body is still returned, header removed, so the text is never lost.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler serves Settings > Import. It binds the request and renders; the rules live in Service.

func NewHandler

func NewHandler(svc *Service) *Handler

NewHandler wires the handler to the import service.

func (*Handler) DropZone

func (h *Handler) DropZone(c *echo.Context) error

DropZone renders the upload step on its own, for "choose a different file" and "import another".

func (*Handler) Job

func (h *Handler) Job(c *echo.Context) error

Job answers a poll with the current progress, or the result once it ends. A job the server no longer knows (it restarted) gets a plain explanation and no further polling.

func (*Handler) Page

func (h *Handler) Page(c *echo.Context) error

Page sends the old Import page address to the Import part of Campaign settings' Data tab, so bookmarks and links written before the move still land on the import.

func (*Handler) Preview

func (h *Handler) Preview(c *echo.Context) error

Preview takes the uploaded zip and answers with what an import would do. Nothing is written to the campaign.

func (*Handler) SettingsTabFactory

func (h *Handler) SettingsTabFactory() func(*campaigns.CampaignContext) campaigns.SettingsTab

SettingsTabFactory returns the Settings > Import tab for the campaigns plugin's tab registry. It sits right after Data, is owner-only like every import route, and resumes the progress bar of a running import.

func (*Handler) Start

func (h *Handler) Start(c *echo.Context) error

Start begins the import of a previewed upload and answers with its progress.

type Job

type Job struct {
	ID         string
	CampaignID string
	UserID     string
	// contains filtered or unexported fields
}

Job is one running or finished import.

func (*Job) View

func (j *Job) View() JobView

View snapshots the job.

type JobView

type JobView struct {
	ID         string
	CampaignID string
	State      string
	Phase      string
	Done       int
	Total      int
	Percent    int
	// Label is the sentence over the progress bar.
	Label    string
	RootID   string
	RootName string
	// Partial is true on a failure that left an Imported folder behind.
	Partial bool
	Error   string
	Summary *Summary
	File    string
}

JobView is a consistent copy of a job's progress, safe to render and poll.

type Limits

type Limits struct {
	MaxUploadBytes int64 // the .zip file itself
	MaxEntries     int   // files and folders listed in the zip
	MaxTotalBytes  int64 // all files, uncompressed
	MaxFileBytes   int64 // one picture or file, uncompressed
	MaxNoteBytes   int64 // one Markdown note, uncompressed
	MaxRatio       int64 // uncompressed / compressed, for each entry over entryRatioFloor and for the archive as a whole
	MaxDepth       int   // folders deep
	MaxPathBytes   int
}

Limits bound what one uploaded archive may ask of the server. Every number is checked against what the zip declares AND against what is actually read, since a hostile archive controls its own headers.

type NewPage

type NewPage struct {
	Name     string
	KindID   int
	Label    string
	ParentID string // empty for the top level
}

NewPage describes a page to create. Every imported page is created GM only: there is deliberately no field to say otherwise.

type Note

type Note struct {
	Entry Entry
	Dir   string
	// Stem is the file name without extension and without Notion's id; links
	// find a note by it.
	Stem  string
	Title string
	FM    FrontMatter
	// BadFrontMatter is true when the file opened with a YAML block that could
	// not be read; the block is dropped and the text kept.
	BadFrontMatter bool
	// HadTags / HadVisibility record front matter keys Chronicle does not carry
	// over, so the preview can say so once instead of per page.
	HadTags       bool
	HadVisibility bool
}

Note is one Markdown file that becomes a page.

type OutlineLine

type OutlineLine struct {
	Depth int
	Name  string
	// Pages is how many pages sit anywhere beneath this one.
	Pages int
}

OutlineLine is one folder in the preview's page tree.

type Page

type Page struct {
	Name string
	// Note indexes Vault.Notes, or is -1 for a folder that has no note of its own.
	Note int
	// Parent indexes Vault.Pages, or is -1 for the top of the Imported folder.
	Parent int
}

Page is one page the import will create, in creation order (parents first).

type PageKind

type PageKind struct {
	ID      int
	Slug    string
	Enabled bool
}

PageKind is a page type a page can be created as.

type PageStore

type PageStore interface {
	Kinds(ctx context.Context, campaignID string) ([]PageKind, error)
	// NameTaken reports whether a live page already uses this name's address.
	NameTaken(ctx context.Context, campaignID, name string) (bool, error)
	// CreatePage creates a GM-only page and returns its id.
	CreatePage(ctx context.Context, campaignID, userID string, p NewPage) (string, error)
	// SetBody stores a page's text, as editor JSON plus the HTML shown to readers.
	SetBody(ctx context.Context, pageID, editorJSON, html string) error
	Rename(ctx context.Context, pageID, name string) error
}

PageStore is the part of the pages service the import writes through. The adapter in internal/app implements it over the entities service, so the normal rules (slug, version history, change events) apply.

type PictureStore

type PictureStore interface {
	StorePicture(ctx context.Context, campaignID, userID, name string, data []byte) (mediaID string, err error)
}

PictureStore stores a picture through the media service, with its type, size and quota checks, and returns the id the text refers to.

type Preview

type Preview struct {
	UploadID    string
	FileName    string
	VaultName   string
	Stats       Stats
	Total       int
	Outline     []OutlineLine
	OutlineMore int
	Skipped     []SkippedEntry
	SkippedMore int
}

Preview is what the owner sees before anything is written.

type Problem

type Problem struct {
	Where string
	What  string
}

Problem is one thing that did not import, in words for the owner.

type Ref

type Ref struct {
	Kind       RefKind
	Start, End int
	// Target is the note or file named, without #heading or ^block. For
	// Markdown links it is the URL-decoded path. Empty for a link to a heading
	// in the same note.
	Target   string
	Fragment string
	// Text is the alias, the link text or the picture's alt text.
	Text string
	// Hint is an embed's size ("300" or "300x200"); it is not alt text.
	Hint  string
	Title string
	// Remote is true for a Markdown reference that is not a path inside the
	// vault (a web address, mail link or bare #anchor). Such references are
	// left to the Markdown renderer, except that remote pictures become links.
	Remote bool
}

Ref is one link or picture found in a note's text. Start and End are byte offsets into the text that was scanned.

func ScanRefs

func ScanRefs(body string) []Ref

ScanRefs returns every reference in body outside code, in order.

Every step is linear in the length of body: a hostile note made of brackets must cost no more than a real one. Bracket partners and the next "]]" are found once per line in a single pass and looked up in O(1) afterwards.

type RefKind

type RefKind int

RefKind says which syntax a reference was written in.

const (
	// RefWiki is [[Note]], [[Note|alias]] or [[Note#Heading]].
	RefWiki RefKind = iota
	// RefEmbed is ![[Note]] or ![[picture.png|300]].
	RefEmbed
	// RefLink is [text](path).
	RefLink
	// RefImage is ![alt](path).
	RefImage
)

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service previews and runs imports. It holds uploads and job progress in memory: a restart forgets them, and a half-finished import is then marked by the folder it left behind (see runner.go), never by this state.

func NewService

func NewService(d Deps) *Service

NewService builds the service and clears any zips a previous run left in its temp folder.

func (*Service) ActiveJob

func (s *Service) ActiveJob(campaignID string) (JobView, bool)

ActiveJob returns the running import for a campaign, so a reloaded page can pick the progress bar back up.

func (*Service) Job

func (s *Service) Job(campaignID, jobID string) (JobView, bool)

Job returns the progress of a job that belongs to this campaign.

func (*Service) Limits

func (s *Service) Limits() Limits

Limits returns the limits in force, for the page to state them.

func (*Service) Preview

func (s *Service) Preview(ctx context.Context, campaignID, userID, zipPath, fileName string) (*Preview, error)

Preview checks and reads the zip at zipPath and reports what an import would do. Nothing is written to the campaign. On any error the file is removed.

func (*Service) SaveUpload

func (s *Service) SaveUpload(r io.Reader) (string, error)

SaveUpload copies an uploaded zip to a private temp file, refusing more than the upload limit, and returns its path. The caller hands the path to Preview.

func (*Service) Start

func (s *Service) Start(campaignID, userID, uploadID string) (*JobView, error)

Start begins importing a previewed upload in the background and returns the job to poll. The upload must belong to this campaign and this person.

type SkippedEntry

type SkippedEntry struct {
	Path   string
	Reason string
}

SkippedEntry is a file the archive held that was left out, with the reason.

type Stats

type Stats struct {
	Pages       int // notes
	FolderPages int // folders with no note of their own
	FolderNotes int // folders that reuse their own note as the folder page

	LinksToPages int // [[wiki]] and relative links that became page links
	LinksPlain   int // links to notes not in the zip, kept as plain text
	// UnresolvedNames lists some of the names behind LinksPlain, for the preview.
	UnresolvedNames []string

	Pictures        int // distinct pictures placed inside text
	PictureRefs     int
	MissingPictures int // pictures a note shows that are not in the zip
	Files           int // distinct other files that will be attached
	FileRefs        int // (page, file) attachments
	// SkippedFiles are files left out, with the reason.
	SkippedFiles []SkippedEntry

	BadFrontMatter int
	TagPages       int // pages whose tags are not carried over
	VisibilityKeys int // pages whose visibility key is ignored
	NameClashes    int // notes sharing a name with another note
	CaseClashes    int
	Ignored        int
}

Stats is everything the preview reports.

type Summary

type Summary struct {
	Pages          int // pages created, folders included
	PagesFailed    int // pages that could not be created
	TextsFailed    int // pages created but whose text could not be saved
	LinksMade      int
	LinksPlain     int
	Pictures       int
	PictureFails   int
	FilesAttached  int
	FilesSkipped   int
	Problems       []Problem
	MoreProblems   int
	VaultName      string
	SourceFileName string
}

Summary is the result of an import.

type Target

type Target struct {
	Kind  TargetKind
	Index int
}

Target is what a reference resolved to.

type TargetKind

type TargetKind int

TargetKind says what a reference points at.

const (
	// TargetNone is a reference to something that is not in the zip.
	TargetNone TargetKind = iota
	// TargetNote is another note (Index is into Vault.Notes).
	TargetNote
	// TargetFile is a picture or other file (Index is into Vault.Files).
	TargetFile
	// TargetSelf is a link to a heading in the same note.
	TargetSelf
)

type Vault

type Vault struct {
	Name  string
	Notes []*Note
	// Files are the pictures and other files, in path order.
	Files []Entry
	Pages []Page
	Stats Stats
	// contains filtered or unexported fields
}

Vault is the analysed archive: nothing in it has been written anywhere.

func Analyze

func Analyze(ctx context.Context, a *Archive, attachable AttachCheck) (*Vault, error)

Analyze reads every note once and works out the page tree, the links and the attachments, without writing anything. attachable is asked about each file that a note refers to but that cannot sit inside text.

func (*Vault) NotePage

func (v *Vault) NotePage(note int) int

NotePage returns the index in Pages of a note's page.

func (*Vault) Outline

func (v *Vault) Outline(limit int) (lines []OutlineLine, more int)

Outline lists the pages that have pages beneath them, indented by depth, so the preview can show the tree the folders will become. It stops at limit lines and reports how many were left out.

func (*Vault) Resolve

func (v *Vault) Resolve(src int, r Ref) Target

Resolve finds what a reference written in note src points at, the way Obsidian does: a bare name matches a file name anywhere in the vault, a name with folders matches the end of a path, and when several notes share a name the one in the same folder, then the shallowest, wins.

Jump to

Keyboard shortcuts

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