// SPDX-License-Identifier: AGPL-3.0-or-later package directory import ( "context" "encoding/json" "fmt" "log/slog" "sort" "strconv" "strings" "time" "docwell/server/internal/access" "docwell/server/internal/convert" ) // importMeta gives imported pages the tags and properties their files name // (Obsidian front matter, #tags, a Readwise book's author): tags and // properties are found by name, case aside, or made. A value that does not // fit an existing property's type is left out; nothing here fails an import. type importMeta struct { s *Service c access.Caller ws string loaded bool tags map[string]string // lower-case name -> tag id props map[string]*propertyRecord // lower-case name -> property } func (s *Service) newImportMeta(c access.Caller, wsID string) *importMeta { return &importMeta{s: s, c: c, ws: wsID} } func (m *importMeta) load(ctx context.Context) { if m.loaded { return } m.loaded = true m.tags, m.props = map[string]string{}, map[string]*propertyRecord{} if rows, err := m.s.workspaceTags(ctx, m.ws); err == nil { for _, r := range rows { m.tags[strings.ToLower(r.Name)] = r.ID } } if rows, err := m.s.workspaceProperties(ctx, m.ws); err == nil { for i := range rows { m.props[strings.ToLower(rows[i].Name)] = &rows[i] } } } // apply sets the page's tags and property values. func (m *importMeta) apply(ctx context.Context, pageID string, p convert.NotionPage) { if len(p.Tags) == 0 && len(p.Props) == 0 { return } m.load(ctx) in := UpdatePageInput{} var tagIDs []string for _, name := range p.Tags { if id := m.tag(ctx, name); id != "" && len(tagIDs) < maxTagsPerPage { tagIDs = append(tagIDs, id) } } if len(tagIDs) > 0 { in.Tags = &tagIDs } keys := make([]string, 0, len(p.Props)) for k := range p.Props { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { def := m.property(ctx, k, p.Props[k]) if def == nil { continue } if v, ok := m.value(ctx, def, p.Props[k]); ok { if in.Properties == nil { in.Properties = map[string]json.RawMessage{} } in.Properties[def.ID] = v } } if in.Tags == nil && in.Properties == nil { return } if _, err := m.s.UpdatePage(ctx, m.c, pageID, in); err != nil { slog.Warn("import: tags and properties not set", "page", pageID, "err", err) } } func (m *importMeta) tag(ctx context.Context, name string) string { name = strings.TrimSpace(name) if r := []rune(name); len(r) > 60 { name = string(r[:60]) } if name == "" { return "" } if id, ok := m.tags[strings.ToLower(name)]; ok { return id } t, err := m.s.CreateTag(ctx, m.c, m.ws, TagInput{Name: &name}) if err != nil { m.tags[strings.ToLower(name)] = "" // Guests cannot make tags; do not try again. return "" } m.tags[strings.ToLower(name)] = t.ID return t.ID } // property finds the property named name, or makes one of the type the // value suggests. func (m *importMeta) property(ctx context.Context, name string, v any) *propertyRecord { name = strings.TrimSpace(name) if r := []rune(name); len(r) > maxPropertyName { name = string(r[:maxPropertyName]) } if name == "" { return nil } if def, ok := m.props[strings.ToLower(name)]; ok { return def } typ := guessPropertyType(v) created, err := m.s.CreateProperty(ctx, m.c, m.ws, PropertyInput{Name: &name, Type: &typ}) if err != nil { m.props[strings.ToLower(name)] = nil return nil } rec := propertyRecord(created) m.props[strings.ToLower(name)] = &rec return &rec } func guessPropertyType(v any) string { switch x := v.(type) { case bool: return PropCheckbox case float64: return PropNumber case []string: return PropMultiSelect case string: if _, err := time.Parse(time.DateOnly, x); err == nil { return PropDate } if (strings.HasPrefix(x, "https://") || strings.HasPrefix(x, "http://")) && validLink(x) { return PropLink } } return PropText } // value is v as the property's type stores it. func (m *importMeta) value(ctx context.Context, def *propertyRecord, v any) (json.RawMessage, bool) { enc := func(x any) (json.RawMessage, bool) { b, err := json.Marshal(x) if err != nil { return nil, false } if _, err := cleanValue(*def, b); err != nil { return nil, false } return b, true } text := func() string { switch x := v.(type) { case []string: return strings.Join(x, ", ") case float64: return strconv.FormatFloat(x, 'f', -1, 64) } return fmt.Sprint(v) } switch def.Type { case PropText, PropLink, PropDate: s := text() if len(s) > maxTextValue { s = s[:maxTextValue] } return enc(s) case PropNumber: switch x := v.(type) { case float64: return enc(x) case string: if f, err := strconv.ParseFloat(strings.ReplaceAll(x, ",", "."), 64); err == nil { return enc(f) } } case PropCheckbox: switch x := v.(type) { case bool: return enc(x) case string: switch strings.ToLower(x) { case "true", "yes", "x", "1": return enc(true) case "false", "no", "0": return enc(false) } } case PropSelect, PropMultiSelect: var names []string switch x := v.(type) { case []string: names = x default: names = []string{text()} } if def.Type == PropSelect && len(names) > 1 { names = names[:1] } ids := m.options(ctx, def, names) if len(ids) == 0 { return nil, false } if def.Type == PropSelect { return enc(ids[0]) } return enc(ids) } return nil, false } // options returns the ids of the named choices, adding the missing ones. func (m *importMeta) options(ctx context.Context, def *propertyRecord, names []string) []string { var ids []string var added bool opts := append([]PropertyOption(nil), def.Options...) for _, name := range names { name = strings.TrimSpace(name) if r := []rune(name); len(r) > 60 { name = string(r[:60]) } if name == "" { continue } found := "" for _, o := range opts { if strings.EqualFold(o.Name, name) { found = o.ID } } if found == "" { if len(opts) >= maxOptions { continue } found = newOptionID() opts = append(opts, PropertyOption{ID: found, Name: name, Color: labelColors[2+len(opts)%(len(labelColors)-2)]}) added = true } ids = append(ids, found) } if added { updated, err := m.s.UpdateProperty(ctx, m.c, def.ID, PropertyInput{Options: &opts}) if err != nil { return nil } def.Options = updated.Options } return ids }