| 1 | package notionmd |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "net/url" |
| 6 | "regexp" |
| 7 | "strings" |
| 8 | "unicode" |
| 9 | |
| 10 | "amadan.net/oficina/mapa/internal/mapa/markup" |
| 11 | ) |
| 12 | |
| 13 | // Links (§11.3) and mentions (§11.2). |
| 14 | |
| 15 | // The texts a link may become, settled through the copy review. |
| 16 | const ( |
| 17 | unsharedText = "(a Notion page not shared with the import)" |
| 18 | ) |
| 19 | |
| 20 | var trailingID = regexp.MustCompile(`[0-9a-f]{32}$`) |
| 21 | |
| 22 | // resolve asks the resolver, which may be absent in a test. |
| 23 | func (mapper *mapper) resolve(id string) (string, LinkState) { |
| 24 | if mapper.options.Resolve == nil { |
| 25 | return "", Unshared |
| 26 | } |
| 27 | title, state := mapper.options.Resolve.Page(id) |
| 28 | if state == Live && title == "" { |
| 29 | return "", Dead |
| 30 | } |
| 31 | return title, state |
| 32 | } |
| 33 | |
| 34 | // link is a text run's link: a [[link]] when it is a Notion page that |
| 35 | // was imported, else a web link if Mapa would make it one, else text. |
| 36 | func (mapper *mapper) link(label, address string) []part { |
| 37 | id, anchored, isNotion := notionID(address) |
| 38 | if !isNotion { |
| 39 | return mapper.webLink(label, address) |
| 40 | } |
| 41 | title, state := mapper.resolve(id) |
| 42 | switch state { |
| 43 | case Live: |
| 44 | if anchored { |
| 45 | mapper.loss(LossBlockAnchor) |
| 46 | } |
| 47 | return []part{mapper.wikiTo(id, title, label)} |
| 48 | case Dead: |
| 49 | mapper.loss(LossDeadLink) |
| 50 | return []part{lit(label)} |
| 51 | case Unshared: |
| 52 | mapper.result.Unresolved = append(mapper.result.Unresolved, id) |
| 53 | } |
| 54 | if strings.HasPrefix(strings.ToLower(address), "https://") { |
| 55 | mapper.result.NotionLinks++ |
| 56 | } |
| 57 | return mapper.webLink(label, address) |
| 58 | } |
| 59 | |
| 60 | // notionID is the page id a Notion address names: its path's last 32 |
| 61 | // hex digits, on notion.so, www.notion.so, a workspace's notion.site, |
| 62 | // or a bare path. anchored is a link to a block inside it. |
| 63 | func notionID(address string) (string, bool, bool) { |
| 64 | parsed, err := url.Parse(address) |
| 65 | if err != nil { |
| 66 | return "", false, false |
| 67 | } |
| 68 | host := strings.ToLower(parsed.Hostname()) |
| 69 | notion := host == "notion.so" || host == "www.notion.so" || |
| 70 | strings.HasSuffix(host, ".notion.site") || |
| 71 | (parsed.Scheme == "" && host == "" && |
| 72 | strings.HasPrefix(parsed.Path, "/")) |
| 73 | if !notion { |
| 74 | return "", false, false |
| 75 | } |
| 76 | segment := parsed.Path[strings.LastIndex(parsed.Path, "/")+1:] |
| 77 | segment = strings.ToLower(strings.ReplaceAll(segment, "-", "")) |
| 78 | found := trailingID.FindString(segment) |
| 79 | if found == "" { |
| 80 | return "", false, false |
| 81 | } |
| 82 | return dashed(found), parsed.Fragment != "", true |
| 83 | } |
| 84 | |
| 85 | // dashed is a 32-digit id in Notion's 8-4-4-4-12 form. |
| 86 | func dashed(compact string) string { |
| 87 | return compact[:8] + "-" + compact[8:12] + "-" + compact[12:16] + "-" + |
| 88 | compact[16:20] + "-" + compact[20:] |
| 89 | } |
| 90 | |
| 91 | // webLink is [label](address) when Mapa would make the address a link, |
| 92 | // with the address and label written inside the link syntax's limits; |
| 93 | // otherwise the label alone, counted. |
| 94 | func (mapper *mapper) webLink(label, address string) []part { |
| 95 | encoded := encodeAddress(address) |
| 96 | if !markup.SafeURL(encoded) { |
| 97 | mapper.loss(LossUnsafeLink) |
| 98 | return []part{lit(label)} |
| 99 | } |
| 100 | shown := cleanLabel(label) |
| 101 | if !markup.LinkAddress(encoded) { |
| 102 | // Past markup.MaxAddress a [label](address) is text, so the |
| 103 | // address is written bare after its label, and Mapa links it |
| 104 | // by itself (Fable round 3, M1). Never the fallback: the |
| 105 | // address is kept. |
| 106 | mapper.loss(LossLongLink) |
| 107 | if encodeAddress(label) == encoded { |
| 108 | // The label is the address as Notion gave it, before ( ) and |
| 109 | // spaces were encoded: not written twice (Fable round 5, |
| 110 | // M1a). A caption-less bookmark, embed or image is this. |
| 111 | shown = "" |
| 112 | } |
| 113 | return longLink(shown, encoded) |
| 114 | } |
| 115 | if shown == "" { |
| 116 | shown = cleanLabel(encoded) |
| 117 | } |
| 118 | return []part{{kind: web, text: shown, url: encoded}} |
| 119 | } |
| 120 | |
| 121 | // encodeAddress percent-encodes what would end a link's address: (, ) |
| 122 | // and whitespace. |
| 123 | func encodeAddress(address string) string { |
| 124 | var out strings.Builder |
| 125 | for _, char := range strings.TrimSpace(address) { |
| 126 | if char == '(' || char == ')' || unicode.IsSpace(char) { |
| 127 | for _, each := range []byte(string(char)) { |
| 128 | fmt.Fprintf(&out, "%%%02X", each) |
| 129 | } |
| 130 | continue |
| 131 | } |
| 132 | out.WriteRune(char) |
| 133 | } |
| 134 | return out.String() |
| 135 | } |
| 136 | |
| 137 | // cleanLabel is a label or shown text inside the syntax's limits: no [ |
| 138 | // ] | or line break, and no edge space a link would trim. |
| 139 | func cleanLabel(text string) string { |
| 140 | cleaned := strings.NewReplacer("[", "(", "]", ")", "|", "/", "\r\n", |
| 141 | " ", "\n", " ", "\r", " ").Replace(text) |
| 142 | return strings.TrimSpace(cleaned) |
| 143 | } |
| 144 | |
| 145 | // wikiTo is a [[link]] to a live page, with Notion's text shown when it |
| 146 | // differs from the page's Mapa title. |
| 147 | func (mapper *mapper) wikiTo(id, title, shown string) part { |
| 148 | mapper.result.Targets = append(mapper.result.Targets, id) |
| 149 | shown = cleanLabel(shown) |
| 150 | if shown == title { |
| 151 | shown = "" |
| 152 | } |
| 153 | return part{kind: wiki, target: title, text: shown} |
| 154 | } |
| 155 | |
| 156 | // mention maps a mention run. |
| 157 | func (mapper *mapper) mention(run Run) []part { |
| 158 | mention := run.Mention |
| 159 | switch mention.Type { |
| 160 | case "page", "database": |
| 161 | return mapper.pageMention(run) |
| 162 | case "date": |
| 163 | return mapper.date(*mention, run.Text) |
| 164 | case "user": |
| 165 | if mention.Name != "" { |
| 166 | return []part{lit("@" + mention.Name)} |
| 167 | } |
| 168 | case "link_preview", "link_mention": |
| 169 | address := firstOf(mention.URL, run.Href) |
| 170 | if address != "" { |
| 171 | return mapper.link(firstOf(run.Text, address), address) |
| 172 | } |
| 173 | } |
| 174 | return []part{lit(run.Text)} |
| 175 | } |
| 176 | |
| 177 | // pageMention is a page's or database's mention, by what it is to the |
| 178 | // import. |
| 179 | func (mapper *mapper) pageMention(run Run) []part { |
| 180 | id := run.Mention.ID |
| 181 | title, state := mapper.resolve(id) |
| 182 | switch state { |
| 183 | case Live: |
| 184 | return []part{mapper.wikiTo(id, title, run.Text)} |
| 185 | case Unshared: |
| 186 | mapper.loss(LossUnshared) |
| 187 | mapper.result.Unresolved = append(mapper.result.Unresolved, id) |
| 188 | return []part{lit(unsharedText)} |
| 189 | case Dead: |
| 190 | mapper.loss(LossDeadLink) |
| 191 | case Row: |
| 192 | mapper.loss(LossRowLink) |
| 193 | case Database: |
| 194 | mapper.loss(LossDatabase) |
| 195 | } |
| 196 | return []part{lit(run.Text)} |
| 197 | } |
| 198 | |
| 199 | // longLink is a link whose address is past markup.MaxAddress, which a |
| 200 | // [label](address) cannot hold: "label (address)", the address bare |
| 201 | // inside brackets. The ( lets Mapa's autolink start, and the ) ends it, |
| 202 | // so nothing after the address joins it (Fable round 4, M1). webLink |
| 203 | // clears a label that is the address itself, so it is not written |
| 204 | // twice. A mailto: address, which Mapa does not link bare, is text |
| 205 | // (§11.3). |
| 206 | func longLink(shown, address string) []part { |
| 207 | var out []part |
| 208 | if shown != "" { |
| 209 | out = append(out, lit(shown+" ")) |
| 210 | } |
| 211 | written := bareAddress(address) |
| 212 | if !strings.HasPrefix(written, "http") { |
| 213 | return append(out, lit("("+address+")")) |
| 214 | } |
| 215 | return append(out, fixed("("), part{kind: bare, url: written}, |
| 216 | fixed(")")) |
| 217 | } |
| 218 | |
| 219 | // bareAddress is an address as the autolink reads it whole: its scheme |
| 220 | // in lower case, as the autolink requires; [ ] < > ` and | percent- |
| 221 | // encoded, where the autolink would stop or the rest of Mapa read them; |
| 222 | // and a last character the autolink would drop (. , ; : ! ? ' ") |
| 223 | // encoded too, except a final ? that starts an empty query, which is |
| 224 | // dropped: %3F would name another address (Fable round 5, L2). |
| 225 | func bareAddress(address string) string { |
| 226 | if scheme, rest, ok := strings.Cut(address, "://"); ok { |
| 227 | address = strings.ToLower(scheme) + "://" + rest |
| 228 | } |
| 229 | if strings.HasSuffix(address, "?") && |
| 230 | strings.Index(address, "?") == len(address)-1 && |
| 231 | !strings.Contains(address, "#") { |
| 232 | address = strings.TrimSuffix(address, "?") |
| 233 | } |
| 234 | var out strings.Builder |
| 235 | for index, char := range address { |
| 236 | last := index == len(address)-1 |
| 237 | if strings.ContainsRune("[]<>`|", char) || |
| 238 | (last && strings.ContainsRune(".,;:!?'\"", char)) { |
| 239 | fmt.Fprintf(&out, "%%%02X", char) |
| 240 | continue |
| 241 | } |
| 242 | out.WriteRune(char) |
| 243 | } |
| 244 | return out.String() |
| 245 | } |
| 246 | |