| 1 | package mapa |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "strings" |
| 7 | |
| 8 | "amadan.net/oficina/mapa/internal/mapa/notionmd" |
| 9 | "amadan.net/oficina/notion.git/notion" |
| 10 | ) |
| 11 | |
| 12 | // The image step (Notion import spec §12). During Write, before the |
| 13 | // page's transaction, each Notion-hosted image block on a page about to |
| 14 | // be written is reused, copied, or read again for a fresh signed URL, |
| 15 | // downloaded through the module's pinned file transport, and added to |
| 16 | // Mapa images as the runner (import_images_store.go). The page's commit |
| 17 | // then attaches what its body introduces (attachOwn on ImportCreate and |
| 18 | // ImportUpdate's edited revision). No network call and no store call |
| 19 | // happens inside a page transaction. notion_images remembers where each |
| 20 | // block's image went (import_images_place.go). |
| 21 | |
| 22 | // imageCap is the images spec's size cap (§3.4): 10 MiB. |
| 23 | const imageCap = 10 << 20 |
| 24 | |
| 25 | // ImageStore is where the run puts Notion's images: Mapa images, or a |
| 26 | // stand-in in tests. |
| 27 | type ImageStore interface { |
| 28 | // Ready refuses, before anything is downloaded, when images cannot |
| 29 | // be added at all: ErrNoImageStore's case (spec §12). |
| 30 | Ready(ctx context.Context) error |
| 31 | Add(ctx context.Context, who string, data []byte) (AddedImage, error) |
| 32 | Copy(ctx context.Context, who, publicID string) (AddedImage, error) |
| 33 | // Discard removes images a page's write did not attach, at once, |
| 34 | // when the write was kept, failed or found the page gone. |
| 35 | Discard(ctx context.Context, who string, added []AddedImage) error |
| 36 | // Held is whether an image still exists, attached to the page. |
| 37 | Held(ctx context.Context, publicID string, pageID int64) bool |
| 38 | Markdown(publicID, alt string) string |
| 39 | } |
| 40 | |
| 41 | // AddedImage is one pending image. |
| 42 | type AddedImage interface { |
| 43 | PublicID() string |
| 44 | Markdown(alt string) string |
| 45 | // Side is the image's longer side in pixels: an imported icon over |
| 46 | // MaxIconSide is refused (columns and icons spec §6.1). |
| 47 | Side() int |
| 48 | } |
| 49 | |
| 50 | // errNoImageStore is the images spec's ErrNoImageStore, whose sentence |
| 51 | // the refusal line carries. |
| 52 | var errNoImageStore = errors.New("images aren't set up in Mapa yet") |
| 53 | |
| 54 | // imageCounts is one page's images, for the report. |
| 55 | type imageCounts struct { |
| 56 | Imported int `json:"imported,omitempty"` |
| 57 | Links int `json:"links,omitempty"` |
| 58 | Failed map[string]int `json:"failed,omitempty"` |
| 59 | // Icon and Cover are the page's look (columns and icons spec |
| 60 | // §6.1): lookImported, or why not; "" when Notion has none. |
| 61 | Icon string `json:"icon,omitempty"` |
| 62 | Cover string `json:"cover,omitempty"` |
| 63 | } |
| 64 | |
| 65 | // pageImages is one page's prepared images: the line for each hosted |
| 66 | // image block, by block id, which the mapper writes in its place. |
| 67 | type pageImages struct { |
| 68 | lines map[string]string |
| 69 | added []AddedImage |
| 70 | counts imageCounts |
| 71 | // placed is where each hosted block's image went, for notion_images. |
| 72 | placed []placedImage |
| 73 | } |
| 74 | |
| 75 | func (prepared *pageImages) Image(blockID string) string { |
| 76 | return prepared.lines[blockID] |
| 77 | } |
| 78 | |
| 79 | // storedImages is a page's lines as the last import wrote them, with |
| 80 | // nothing fetched: for the fix-up pass after a Resume (Fable L6), and |
| 81 | // for a page decided before its images (kept, deleted). |
| 82 | func storedImages(entry *importEntry) *pageImages { |
| 83 | return &pageImages{lines: entry.place.ImageLines, |
| 84 | counts: imageCounts{Failed: map[string]int{}}} |
| 85 | } |
| 86 | |
| 87 | // prepareImages prepares a page's hosted images, in block order. |
| 88 | func (job *importJob) prepareImages(ctx context.Context, |
| 89 | entry *importEntry) (*pageImages, error) { |
| 90 | prepared := &pageImages{lines: map[string]string{}, |
| 91 | counts: imageCounts{Failed: map[string]int{}}} |
| 92 | var walk func([]notionmd.Block) error |
| 93 | walk = func(blocks []notionmd.Block) error { |
| 94 | for _, block := range blocks { |
| 95 | err := job.prepareImage(ctx, entry, block, prepared) |
| 96 | if err != nil { |
| 97 | return err |
| 98 | } |
| 99 | if err := walk(block.Children); err != nil { |
| 100 | return err |
| 101 | } |
| 102 | } |
| 103 | return nil |
| 104 | } |
| 105 | return prepared, walk(entry.staged.Blocks) |
| 106 | } |
| 107 | |
| 108 | func (job *importJob) prepareImage(ctx context.Context, entry *importEntry, |
| 109 | block notionmd.Block, prepared *pageImages) error { |
| 110 | if block.Type != "image" || block.File == nil { |
| 111 | return nil |
| 112 | } |
| 113 | if block.File.Type != notion.FileHosted { |
| 114 | prepared.counts.Links++ |
| 115 | return nil |
| 116 | } |
| 117 | if _, done := prepared.lines[block.ID]; done { |
| 118 | return nil // one block shown twice: one image (round 3, L2) |
| 119 | } |
| 120 | alt := plainRuns(block.Caption) |
| 121 | got, err := job.imageFor(ctx, entry, block, alt) |
| 122 | if err != nil { |
| 123 | return err |
| 124 | } |
| 125 | prepared.placed = append(prepared.placed, got.placed) |
| 126 | if got.reason != "" { |
| 127 | prepared.counts.Failed[got.reason]++ |
| 128 | prepared.lines[block.ID] = "(Image not imported: " + |
| 129 | imageName(block, alt) + ", " + got.reason + ")" |
| 130 | return nil |
| 131 | } |
| 132 | if got.added != nil { |
| 133 | prepared.added = append(prepared.added, got.added) |
| 134 | } |
| 135 | prepared.counts.Imported++ |
| 136 | prepared.lines[block.ID] = got.line |
| 137 | return nil |
| 138 | } |
| 139 | |
| 140 | // imageName is what a refusal line calls the image: the last segment of |
| 141 | // Notion's file URL, decoded, else the caption, on one line. |
| 142 | func imageName(block notionmd.Block, alt string) string { |
| 143 | return strings.NewReplacer("\r\n", " ", "\r", " ", "\n", " "). |
| 144 | Replace(firstOf(notion.FileName(block.File.URL), alt, "image")) |
| 145 | } |
| 146 | |
| 147 | // gotImage is one block's outcome. |
| 148 | type gotImage struct { |
| 149 | line, reason string |
| 150 | added AddedImage |
| 151 | placed placedImage |
| 152 | } |
| 153 | |
| 154 | // imageFor is a block's image: its last place reused where the block |
| 155 | // still shows the same file and the page still holds the image, a |
| 156 | // permanent refusal remembered, or a copy or a fresh download (spec |
| 157 | // §12). |
| 158 | // |
| 159 | // "The same file" is the file's key (notion.FileKey: its host and path, |
| 160 | // which hold the file's own id), never the block's last_edited_time: |
| 161 | // Notion rounds that to the minute (§25 note 17), so a file replaced |
| 162 | // within a minute of the last run would carry the time the run saw. |
| 163 | func (job *importJob) imageFor(ctx context.Context, entry *importEntry, |
| 164 | block notionmd.Block, alt string) (gotImage, error) { |
| 165 | placed := placedImage{block: block.ID, key: notion.FileKey(block.File.URL), |
| 166 | page: entry.staged.ID} |
| 167 | prior, found, err := job.priorPlace(ctx, entry.staged.ID, block.ID) |
| 168 | if err != nil { |
| 169 | return gotImage{}, err |
| 170 | } |
| 171 | if found && sameFile(prior.Key, placed.key) { |
| 172 | if prior.Reason != "" { |
| 173 | placed.reason, placed.permanent = prior.Reason, true |
| 174 | return gotImage{reason: prior.Reason, placed: placed}, nil |
| 175 | } |
| 176 | if entry.place.PageID != 0 && |
| 177 | job.images.Held(ctx, prior.PublicID, entry.place.PageID) { |
| 178 | placed.publicID = prior.PublicID |
| 179 | return gotImage{placed: placed, |
| 180 | line: job.images.Markdown(prior.PublicID, alt)}, nil |
| 181 | } |
| 182 | } |
| 183 | return job.freshImage(ctx, entry, block, alt, placed) |
| 184 | } |
| 185 | |
| 186 | // sameFile is whether two file keys name one file. A key that is empty |
| 187 | // (a row from before keys, or a URL that names no file) matches nothing, |
| 188 | // so the file is fetched again once rather than reused on a guess. |
| 189 | func sameFile(kept, now string) bool { |
| 190 | return kept != "" && kept == now |
| 191 | } |
| 192 | |
| 193 | // freshImage copies the block's image from another page that holds it, |
| 194 | // or downloads it and adds it. |
| 195 | func (job *importJob) freshImage(ctx context.Context, entry *importEntry, |
| 196 | block notionmd.Block, alt string, placed placedImage) (gotImage, |
| 197 | error) { |
| 198 | added, fetched, reason, err := job.addImage(ctx, entry, block) |
| 199 | if err != nil { |
| 200 | return gotImage{}, err |
| 201 | } |
| 202 | if fetched != "" { |
| 203 | // The file downloaded is the one kept: a file replaced since |
| 204 | // Survey read the block is keyed as the bytes are (Fable L1). |
| 205 | placed.key = fetched |
| 206 | } |
| 207 | if reason.text != "" { |
| 208 | placed.reason, placed.permanent = reason.text, reason.permanent |
| 209 | return gotImage{reason: reason.text, placed: placed}, nil |
| 210 | } |
| 211 | placed.publicID = added.PublicID() |
| 212 | return gotImage{added: added, line: added.Markdown(alt), |
| 213 | placed: placed}, nil |
| 214 | } |
| 215 | |
| 216 | // refusal is why an image was not added, and whether to try again. |
| 217 | type refusal struct { |
| 218 | text string |
| 219 | permanent bool |
| 220 | } |
| 221 | |
| 222 | // addImage copies or downloads one image and adds it, and answers the |
| 223 | // key of the file it downloaded, if it did. A refusal is a reason, not |
| 224 | // an error: the image becomes its line and the page is written. Only |
| 225 | // what stops the run (a lost lease, the token refused) is an error. |
| 226 | func (job *importJob) addImage(ctx context.Context, entry *importEntry, |
| 227 | block notionmd.Block) (AddedImage, string, refusal, error) { |
| 228 | id := block.ID |
| 229 | if job.imagesStopped == "" { |
| 230 | if err := job.images.Ready(ctx); err != nil { |
| 231 | job.imagesStopped = errNoImageStore.Error() |
| 232 | } |
| 233 | } |
| 234 | if job.imagesStopped != "" { |
| 235 | return nil, "", refusal{text: job.imagesStopped}, nil |
| 236 | } |
| 237 | // The lease is checked just before each of the store's own writes |
| 238 | // (§12): a copy, or an add after the download. |
| 239 | if err := job.store.bookkeep(ctx, job.lease, noChange); err != nil { |
| 240 | return nil, "", refusal{}, err |
| 241 | } |
| 242 | if added, ok := job.copyImage(ctx, entry, block); ok { |
| 243 | return added, "", refusal{}, nil |
| 244 | } |
| 245 | data, key, why, err := job.download(ctx, id) |
| 246 | if err != nil || why.text != "" { |
| 247 | return nil, key, why, err |
| 248 | } |
| 249 | if err := job.store.bookkeep(ctx, job.lease, noChange); err != nil { |
| 250 | return nil, "", refusal{}, err |
| 251 | } |
| 252 | added, err := job.images.Add(ctx, job.who, data) |
| 253 | return added, key, job.storeRefusal(err), nil |
| 254 | } |
| 255 | |
| 256 | // download reads the block again for a fresh signed URL and fetches it, |
| 257 | // and answers that file's key. |
| 258 | func (job *importJob) download(ctx context.Context, id string) ([]byte, |
| 259 | string, refusal, error) { |
| 260 | fresh, err := job.client.Block(ctx, id) |
| 261 | if err != nil || fresh.File == nil { |
| 262 | return nil, "", refusal{text: fetchReason(err)}, finalOnly(err) |
| 263 | } |
| 264 | key := notion.FileKey(fresh.File.URL) |
| 265 | data, err := job.files.Fetch(ctx, fresh.File.URL, imageCap) |
| 266 | if err != nil { |
| 267 | // Only size is permanent: a host the pin refuses may be one |
| 268 | // §19 step 4 has yet to add, so it is tried again (round 3, L5). |
| 269 | return nil, key, refusal{text: fetchReason(err), |
| 270 | permanent: notion.CodeOf(err) == notion.CodeTooLarge}, nil |
| 271 | } |
| 272 | return data, key, refusal{}, nil |
| 273 | } |
| 274 | |
| 275 | // storeRefusal is what Mapa images' answer means for the run: the first |
| 276 | // quota refusal, or no store at all, stops downloads for the rest of it |
| 277 | // (spec §12). |
| 278 | func (job *importJob) storeRefusal(err error) refusal { |
| 279 | switch { |
| 280 | case err == nil: |
| 281 | return refusal{} |
| 282 | case errors.Is(err, ErrImageQuota): |
| 283 | job.imagesStopped = quotaReason(err) |
| 284 | return refusal{text: job.imagesStopped} |
| 285 | case errors.Is(err, ErrNoImageStore): |
| 286 | job.imagesStopped = errNoImageStore.Error() |
| 287 | return refusal{text: job.imagesStopped} |
| 288 | case errors.Is(err, ErrImageType): |
| 289 | return refusal{text: "not a PNG, JPEG, GIF or WebP", permanent: true} |
| 290 | case errors.Is(err, ErrImageTooLarge): |
| 291 | return refusal{text: "over 10 MB", permanent: true} |
| 292 | case errors.Is(err, ErrImageDimensions): |
| 293 | return refusal{text: "too many pixels", permanent: true} |
| 294 | } |
| 295 | return refusal{text: "couldn't be stored"} |
| 296 | } |
| 297 | |
| 298 | // finalOnly passes on an error that stops the run, and drops the rest. |
| 299 | func finalOnly(err error) error { |
| 300 | if err != nil && notion.Final(err) { |
| 301 | return err |
| 302 | } |
| 303 | return nil |
| 304 | } |
| 305 | |
| 306 | // fetchReason is a download's refusal in words. |
| 307 | func fetchReason(err error) string { |
| 308 | if err == nil { |
| 309 | return "Notion gave no file" |
| 310 | } |
| 311 | switch notion.CodeOf(err) { |
| 312 | case notion.CodeTooLarge: |
| 313 | return "over 10 MB" |
| 314 | case notion.CodeForbiddenHost: |
| 315 | return "not from Notion's file store" |
| 316 | case notion.CodeFileExpired: |
| 317 | return "its link had expired" |
| 318 | } |
| 319 | return "couldn't be downloaded" |
| 320 | } |
| 321 | |