bookends

ref: master

pkg/bookends/bookends.go


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
// bookends
// Copyright (C) 2021   Honza Pokorny <honza@pokorny.ca>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

package bookends

import (
	"bytes"
	"errors"
	"fmt"
	"html/template"
	"io"
	"net/http"
	"net/url"
	"os"
	"path"
	"sort"
	"strconv"
	"strings"
	"time"

	"github.com/gorilla/feeds"
	"github.com/niklasfasching/go-org/org"
)

type Config struct {
	BookLogFilename    string
	CacheDir           string
	CoversDir          string
	OutputFilename     string
	AtomOutputFilename string
	TemplateFilename   string
}

type AtomConfig struct {
	Name        string
	Author      string
	Email       string
	Link        string
	Description string
}

type Book struct {
	Author   string
	Title    string
	ISBN     string
	DateRead time.Time
	Rating   int
	Review   template.HTML
	Tags     []string
}

func (b *Book) Link(config AtomConfig) string {
	return fmt.Sprintf("%s/feed/update/%s", config.Link, b.ISBN)
}

type BooksByDateRead []Book

func (r BooksByDateRead) Len() int      { return len(r) }
func (r BooksByDateRead) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
func (r BooksByDateRead) Less(i, j int) bool {
	return r[i].DateRead.After(r[j].DateRead)
}

func PathExists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}

func (b Book) CoverURL() (*url.URL, error) {
	// http: //covers.openlibrary.org/b/$key/$value-$size.jpg

	localPath := path.Join("covers", fmt.Sprintf("%s.jpg", b.ISBN))

	if PathExists(localPath) {
		return url.Parse(localPath)
	}

	s := fmt.Sprintf("https://covers.openlibrary.org/b/isbn/%s-M.jpg", b.ISBN)
	return url.Parse(s)

}

func (b Book) CacheCoverURL() (*url.URL, error) {
	localPath := path.Join("cache", fmt.Sprintf("%s.jpg", b.ISBN))
	return url.Parse(localPath)
}

func (b Book) DownloadCover(config Config) error {
	cachePath := path.Join(config.CacheDir, fmt.Sprintf("%s.jpg", b.ISBN))

	if PathExists(cachePath) {
		return nil
	}

	coversPath := path.Join(config.CoversDir, fmt.Sprintf("%s.jpg", b.ISBN))

	if PathExists(coversPath) {
		// Copy the file over
		err := copy(coversPath, cachePath)

		if err != nil {
			return err
		}

		return nil

	}

	coverUrl, err := b.CoverURL()

	if err != nil {
		return err
	}

	resp, err := http.Get(coverUrl.String())

	if err != nil {
		return err
	}

	if resp.StatusCode > 201 {
		return errors.New("non 200 response:" + b.Title)
	}

	destination, err := os.Create(cachePath)
	if err != nil {
		return err
	}
	defer destination.Close()
	_, err = io.Copy(destination, resp.Body)

	if err != nil {
		return err
	}
	return nil
}

func (b Book) AtomContent() string {
	if b.Review == "" {
		return fmt.Sprintf("%s by %s, rated with %d stars", b.Title, b.Author, b.Rating)
	}
	return fmt.Sprintf("%s by %s, rated with %d stars\n\n%s", b.Title, b.Author, b.Rating, string(b.Review))
}

func BuildHTML(config Config, books []Book) (string, error) {
	t, err := template.ParseFiles(config.TemplateFilename)

	if err != nil {
		return "", err
	}

	out := bytes.NewBuffer(nil)

	err = t.Execute(out, books)

	if err != nil {
		return "", err
	}

	return out.String(), nil
}

func WriteFile(filename string, contents string) error {
	f, err := os.Create(filename)
	defer f.Close()

	if err != nil {
		return err
	}

	_, err = f.WriteString(contents)

	if err != nil {
		return err
	}

	return nil

}

func BuildAtom(books []Book, config AtomConfig) (string, error) {
	now := time.Now()
	author := &feeds.Author{Name: config.Author, Email: config.Email}
	feed := &feeds.Feed{
		Title:       config.Name,
		Link:        &feeds.Link{Href: config.Link},
		Description: config.Description,
		Author:      author,
		Created:     now,
	}

	var items []*feeds.Item

	for _, book := range books {
		item := &feeds.Item{
			Title: book.Title,
			// NOTE: if feeds.Link.Href is empty, each item will appear new each time
			// the feed is updated
			Link:    &feeds.Link{Href: book.Link(config)},
			Content: book.AtomContent(),
			Author:  author,
			Created: book.DateRead,
		}

		items = append(items, item)
	}

	feed.Items = items
	return feed.ToAtom()
}

func Build(config Config) error {
	f, err := os.Open(config.BookLogFilename)

	if err != nil {
		return err
	}

	books, atomConfig, err := ParseOrgFile(f)

	if err != nil {
		return err
	}

	sort.Sort(BooksByDateRead(books))

	htmlOutput, err := BuildHTML(config, books)

	if err != nil {
		return err
	}

	err = WriteFile(config.OutputFilename, htmlOutput)

	if err != nil {
		return err
	}

	atom, err := BuildAtom(books, atomConfig)

	if err != nil {
		return err
	}

	err = WriteFile(config.AtomOutputFilename, atom)

	if err != nil {
		return err
	}

	return nil
}

func ParseAtomConfig(drawer org.PropertyDrawer) AtomConfig {
	name, _ := drawer.Get("ATOM_NAME")
	author, _ := drawer.Get("ATOM_AUTHOR")
	description, _ := drawer.Get("ATOM_DESCRIPTION")
	link, _ := drawer.Get("ATOM_LINK")

	return AtomConfig{
		Name:        name,
		Author:      author,
		Description: description,
		Link:        link,
	}
}

func ParseOrgFile(input io.Reader) ([]Book, AtomConfig, error) {
	books := []Book{}
	conf := org.New()
	d := conf.Parse(input, "")

	documentProperties := d.Nodes[0].(org.PropertyDrawer)
	atomConfig := ParseAtomConfig(documentProperties)

	for _, child := range d.Outline.Children {
		for _, sub := range child.Children {
			tags := []string{}
			for _, t := range sub.Headline.Tags {
				tags = append(tags, strings.ReplaceAll(t, "_", "-"))
			}
			book := Book{
				Title: sub.Headline.Title[0].String(),
				Tags:  tags,
			}

			rest := bytes.NewBufferString("")

			for _, c := range sub.Headline.Children {

				switch t := c.(type) {
				case org.PropertyDrawer:
					author, ok := t.Get("AUTHOR")

					if ok {
						book.Author = author
					}

					rating, ok := t.Get("RATING")
					if ok {
						ratingInt, err := strconv.ParseInt(rating, 10, 8)
						if err != nil {
							return books, atomConfig, err
						}
						book.Rating = int(ratingInt)
					}
					isbn, ok := t.Get("ISBN")
					if ok {
						book.ISBN = isbn
					}

				case org.Paragraph:

					s := t.String()

					if strings.HasPrefix(s, "CLOSED") {
						s = strings.TrimSpace(s)
						dt, err := time.Parse("CLOSED: [2006-01-02 Mon 15:04]", s)
						if err != nil {
							return books, atomConfig, err
						}
						book.DateRead = dt
						continue
					}

					fmt.Fprintln(rest, "")

					fmt.Fprint(rest, "<p>")

					for _, w := range t.Children {
						switch wt := w.(type) {
						case org.Text:
							fmt.Fprintln(rest, wt)
						case org.Emphasis:
							switch wt.Kind {
							case "*":
								fmt.Fprintf(rest, "<b>%s</b>", wt.Content[0].String())
							case "/":
								fmt.Fprintf(rest, "<em>%s</em>", wt.Content[0].String())
							case "=":
								fmt.Fprintf(rest, "<code>%s</code>", wt.Content[0].String())
							}
						case org.Timestamp:
							if wt.IsDate {
								fmt.Fprintln(rest, wt.Time.Format("January 2, 2006"))
							} else {
								fmt.Fprintln(rest, wt.Time.Format("January 2, 2006 at 15:04"))
							}
						case org.RegularLink:
							fmt.Fprintf(rest, `<a href="%s">%s</a>`, wt.URL, wt.Description[0])
						case org.LineBreak:
							continue
						default:
						}
					}
					fmt.Fprintln(rest, "</p>")
					fmt.Fprintln(rest, "")
				case org.Block:
					if t.Name == "QUOTE" {
						fmt.Fprintln(rest, "<blockquote>")
						for _, p := range t.Children {
							fmt.Fprintf(rest, "%s<br>", p)
						}
						fmt.Fprintln(rest, "</blockquote>")
					}
				case org.List:
					if t.Kind == "ordered" {
						fmt.Fprint(rest, "<ol>")
					} else {
						fmt.Fprint(rest, "<ul>")
					}
					for _, w := range t.Items {
						switch wt := w.(type) {
						case org.ListItem:
							fmt.Fprintf(rest, `<li>%s</li>`, wt.Children[0].String())
						default:
						}
					}
					if t.Kind == "ordered" {
						fmt.Fprint(rest, "</ol>")
					} else {
						fmt.Fprint(rest, "</ul>")
					}

				case org.LineBreak:
					fmt.Fprintln(rest, "")
				default:
				}
			}

			book.Review = template.HTML(rest.String())
			books = append(books, book)
		}

	}

	return books, atomConfig, nil

}

func copy(src, dst string) error {
	sourceFileStat, err := os.Stat(src)
	if err != nil {
		return err
	}

	if !sourceFileStat.Mode().IsRegular() {
		return fmt.Errorf("%s is not a regular file", src)
	}

	source, err := os.Open(src)
	if err != nil {
		return err
	}
	defer source.Close()

	destination, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer destination.Close()
	_, err = io.Copy(destination, source)
	return err
}

func CacheCovers(config Config) error {
	f, err := os.Open(config.BookLogFilename)

	if err != nil {
		return err
	}

	books, _, err := ParseOrgFile(f)

	if err != nil {
		return err
	}

	for _, book := range books {
		err = book.DownloadCover(config)
		if err != nil {
			return err
		}
	}

	return nil
}