metadata.go 6.69 KB
Newer Older
ale's avatar
ale committed
1 2 3 4 5
package liber

import (
	"errors"
	"fmt"
6
	"log"
ale's avatar
ale committed
7 8 9 10
	"path/filepath"
	"regexp"
	"strings"

11
	"github.com/meskio/epubgo"
ale's avatar
ale committed
12
	"git.autistici.org/ale/liber/third_party/gobipocket"
ale's avatar
ale committed
13 14
)

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// A metadata provider generates metadata from the local filesystem.
type MetadataProvider interface {
	Name() string
	Lookup(*FileStorage, string, string) (*Metadata, error)
	GetBookCover(*FileStorage, string) (string, error)
}

// A metadata refiner improves on existing metadata and may provide
// more than one result to choose from. It usually involves talking to
// a remote service.
type MetadataRefiner interface {
	Name() string
	Lookup(*Metadata) ([]*Metadata, error)
	GetBookCover(*Metadata) ([]byte, error)
}

ale's avatar
ale committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
type MetadataSource struct {
	Name string
	ID   string
}

type Metadata struct {
	Title       string
	Date        string
	Description string
	ISBN        []string
	Creator     []string
	Language    []string
	Publisher   []string
	Format      []string
	Keywords    []string
	Sources     []MetadataSource
}

ale's avatar
ale committed
49
// Sufficient returns true if the object contains enough information.
50
// If this check does not pass, the book won't be added to the database.
ale's avatar
ale committed
51 52 53 54
func (m *Metadata) Sufficient() bool {
	return m.Title != ""
}

55 56 57 58 59 60 61
// Complete returns true if we're satisfied with the quality of the
// information about this book. If this returns true, remote checks
// will be skipped.
func (m *Metadata) Complete() bool {
	return (m.Title != "" && len(m.Creator) > 0 && len(m.ISBN) > 0)
}

ale's avatar
ale committed
62 63 64 65 66 67 68
// Uniques returns the list of possible unique tokens for this book.
func (m *Metadata) Uniques() []string {
	var out []string
	for _, isbn := range m.ISBN {
		out = append(out, fmt.Sprintf("isbn:%s", isbn))
	}
	// Call it 'sig', but it's just title+author(s).
69
	sig := strings.ToLower(fmt.Sprintf("sig:%s|%s", m.Title, strings.Join(m.Creator, "|")))
ale's avatar
ale committed
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
	out = append(out, sig)
	return out
}

func listsOverlap(a, b []string) bool {
	for _, aa := range a {
		for _, bb := range b {
			if aa == bb {
				return true
			}
		}
	}
	return false
}

// Equals returns true if we think the two Metadata objects refer to
// the same book.
func (m *Metadata) Equals(other *Metadata) bool {
	// Compare ISBNs first, authors+title next.
	return (listsOverlap(m.ISBN, other.ISBN) ||
		(m.Title == other.Title && listsOverlap(m.Creator, other.Creator)))
}

// Merge with a more authoritative metadata source. Fields that are
// set in 'other' will take precedence over the ones in the receiver.
func (m *Metadata) Merge(other *Metadata) {
	if other.Title != "" {
		m.Title = other.Title
	}
	if other.Date != "" {
		m.Date = other.Date
	}
	if other.Description != "" {
		m.Description = other.Description
	}
	if other.Creator != nil {
		m.Creator = other.Creator
	}
	if other.ISBN != nil {
		m.ISBN = other.ISBN
	}
	if other.Publisher != nil {
		m.Publisher = other.Publisher
	}
	if other.Language != nil {
		m.Language = other.Language
	}
	if other.Format != nil {
		m.Format = other.Format
	}
	if other.Sources != nil {
		m.Sources = append(m.Sources, other.Sources...)
	}
}

var authorNameRx = regexp.MustCompile(`([\p{Lu}])[\p{Ll}]+ `)

func toYear(date string) string {
	if len(date) > 4 {
		return date[:4]
	}
	return date
}

func shortAuthorName(a string) string {
	return authorNameRx.ReplaceAllString(a, "$1. ")
}

func shortAuthorString(authors []string) string {
	var shortAuthors []string
	for _, a := range authors {
		shortAuthors = append(shortAuthors, shortAuthorName(a))
	}
	return strings.Join(shortAuthors, ", ")
}

func (m *Metadata) String() string {
	author := "unknown author"
	if len(m.Creator) > 0 {
		author = shortAuthorString(m.Creator)
	}
	if m.Date != "" {
ale's avatar
ale committed
152
		return fmt.Sprintf("%s, \"%s\", %s", author, m.Title, toYear(m.Date))
ale's avatar
ale committed
153
	}
ale's avatar
ale committed
154
	return fmt.Sprintf("%s, \"%s\"", author, m.Title)
ale's avatar
ale committed
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
}

func parseEpub(filename string) (*Metadata, error) {
	e, err := epubgo.Open(filename)
	if err != nil {
		return nil, err
	}
	defer e.Close()

	var m Metadata
	for _, field := range e.MetadataFields() {
		attr, err := e.MetadataAttr(field)
		if err != nil {
			continue
		}
		data, err := e.Metadata(field)
		if err != nil {
			continue
		}

		switch field {
		case "title":
			m.Title = data[0]
		case "date":
			// Just pick the first date available (year only).
			m.Date = toYear(data[0])
		case "creator":
			m.Creator = data
		case "language":
			m.Language = data
		case "publisher":
			m.Publisher = data
		case "identifier":
			for i, id := range data {
				if attr[i]["scheme"] == "ISBN" {
					m.ISBN = append(m.ISBN, id)
				}
			}
		}
	}

196 197 198 199 200 201 202 203
	// If we haven't found an ISBN, look for it in the book text.
	if len(m.ISBN) == 0 {
		if isbn := findISBNInEpub(e); len(isbn) > 0 {
			log.Printf("found ISBN in book text: %s", strings.Join(isbn, ", "))
			m.ISBN = isbn
		}
	}

ale's avatar
ale committed
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
	m.Sources = []MetadataSource{{
		Name: "epub",
		ID:   filename,
	}}

	return &m, nil
}

func parseMobi(filename string) (*Metadata, error) {
	e, err := mobipocket.Open(filename)
	if err != nil {
		return nil, err
	}

	var m Metadata
	for field, data := range e.Metadata {
		switch field {
		case "title":
			m.Title = data[0]
		case "pubdate":
			m.Date = toYear(data[0])
		case "description":
			m.Description = data[0]
		case "publisher":
			m.Publisher = data
		case "author":
			m.Creator = data
		case "isbn":
			m.ISBN = data
		}
	}

	m.Sources = []MetadataSource{{
		Name: "mobi",
		ID:   filename,
	}}

	return &m, nil
}

var alphanumRx = regexp.MustCompile(`[\pL\pN]+`)

func parseAnything(filename string) (*Metadata, error) {
	// Since there is no metadata available, try to match
	// something using just tokens from the file name.
	noext := strings.TrimSuffix(filepath.Base(filename), filepath.Ext(filename))
	return &Metadata{
		Keywords: alphanumRx.FindAllString(noext, -1),
	}, nil
}

255 256
type fileProvider struct{}

257 258 259 260 261 262 263 264 265
func (p *fileProvider) Lookup(storage *FileStorage, path, filetype string) (m *Metadata, err error) {
	// Catch panics from some of the underlying libraries (gmobi
	// in particular) and transform them into errors.
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("panic(): %v", r.(error))
		}
	}()

266 267
	path = storage.Abs(path)
	switch filetype {
ale's avatar
ale committed
268
	case ".epub":
269
		m, err = parseEpub(path)
ale's avatar
ale committed
270
	case ".mobi":
271
		m, err = parseMobi(path)
ale's avatar
ale committed
272
	case ".pdf":
273
		m, err = parseAnything(path)
ale's avatar
ale committed
274
	default:
275
		err = errors.New("unsupported file format")
ale's avatar
ale committed
276 277
	}

278
	return
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
}

func (p *fileProvider) GetBookCover(storage *FileStorage, path string) (string, error) {
	coverPath := path + ".cover.png"
	if storage.Exists(coverPath) {
		return coverPath, nil
	}
	return "", nil
}

func (p *fileProvider) Name() string {
	return "file"
}

func GetFileType(path string) (string, error) {
	filetype := strings.ToLower(filepath.Ext(path))
	if filetype != ".epub" && filetype != ".mobi" && filetype != ".pdf" {
		return "", errors.New("unsupported file format")
	}
	return filetype, nil
ale's avatar
ale committed
299
}