Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add more metadata in POST to /api/v1/books #34

Merged
merged 5 commits into from
May 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ ebooks/**
*.log
hidden
secrets/*.env
envs/*.env
envs/*.env
.vscode/
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
13
8 changes: 8 additions & 0 deletions lib/app-errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ class AppErrors {

return Object.keys(patterns).find((key) => RegExp(patterns[key]).test(error.message));
}

static invalidBookKey(keyName) {
return {
status: '400',
message: `Request contained an invalid property '${keyName}'`,
};
}
}

AppErrors.api = {
Expand All @@ -52,6 +59,7 @@ AppErrors.api = {
message: 'Request exceeds size limit. Try less items.',
},
NO_SECTIONS_SPECIFIED: { status: '400', message: 'No sections provided.' },
COVER_PATH_INVALID: { status: '400', message: 'coverPath must be http or https' },
NOT_FOUND: { status: '404', message: 'Not found.' },
MALFORMED_REQUEST: {
status: '400',
Expand Down
74 changes: 66 additions & 8 deletions lib/book.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
'use strict';


const fs = require('fs');

const shortid = require('shortid');
const sanitizeHtml = require('sanitize-html');

const Url = require('url');
const { VALID_BOOK_METADATA_KEYS } = require('./constants');
const AppErrors = require('./app-errors');
const Config = require('./config');
const Utilities = require('./utilities');
Expand Down Expand Up @@ -40,6 +42,16 @@ class Book {
return !!((section.title && section.content) || section.url);
}

static isValidMetadataKey(key) {
return VALID_BOOK_METADATA_KEYS.includes(key);
}

static assertIsValidMetadataKey(key) {
if (!Book.isValidMetadataKey(key)) {
throw AppErrors.invalidBookKey(key);
}
}

static fallbackTitle(section) {
let fallbackTitle;
const titleMatches = section.html.match(/<title>(.*?)<\/title>/i);
Expand Down Expand Up @@ -99,6 +111,33 @@ class Book {
return tableOfContents.join('\n');
}

/**
* A book
* @typedef {Object} Book
* @property {string} author - the authof of the book (default: EpubPress)
* @property {string} coverPath - (optional) http(s) link to an
* image for the cover of the book (816x1056)
* @property {string} description - description of book
* (default: 'Built using https://epub.press')
* @property {string} genre - the genre of the book (default: Unknown)
* @property {string} language - the languages of the book (default: en)
* @property {string} title - title of book
* @property {number} published - publish Date (default: today)
* @property {string} publisher - publisher (deafult: https://epub.press)
* @property {Object[]} sections - collection of sections for the book.
* A section include a title and (html) content OR a url. Mutually exclusive with urls
* @property {string} series - the series - used in Calibre (default: '')
* @property {number} sequence - the sequence - used in Calibre (default: '')
* @property {string} tags - (optional) a CSV list of strings that become
* tags/subject for the book (default: empty)
* @property {string[]} urls - collection of sites to transform and add as sections
* to the book. Mutually exclusive with section
*/

/**
* Create a book from json
* @param {Book} book - The {@link Book} to be created
*/
static fromJSON(json) {
let reqBody = json;
if (typeof reqBody === 'string') {
Expand All @@ -110,14 +149,7 @@ class Book {
sections = attrs.urls.map((url) => ({ url, html: null }));
}

return new Book(
{
title: attrs.title,
description: attrs.description,
author: attrs.author,
},
sections
);
return new Book(attrs, sections);
}

constructor(metadata, sections) {
Expand All @@ -128,13 +160,28 @@ class Book {
this._metadata = { id, title: `EpubPress - ${date}`, ...Book.DEFAULT_METADATA };
Object.keys(metadata || {}).forEach((metaKey) => {
if (metadata[metaKey]) {
// these properties can come in with metadata, but are not the same
// metadata that is passed to nodepub
if (metaKey !== 'sections' && metaKey !== 'urls') {
Book.assertIsValidMetadataKey(metaKey);
}
this._metadata[metaKey] = Book.replaceCharacters(sanitizeHtml(metadata[metaKey]));
}
});

const coverPath = this.getCoverPath();

if (coverPath !== Book.DEFAULT_COVER_PATH && !coverPath.startsWith('http')) {
throw AppErrors.api.COVER_PATH_INVALID;
}

this._sections = sections || [];
}

/**
* @returns metadata used to generate the book in the ebpub library, nodepub
* @see https://github.com/kcartlidge/nodepub#creating-your-content for details
*/
getMetadata() {
return this._metadata;
}
Expand All @@ -151,10 +198,17 @@ class Book {
return `${this.getPath()}.mobi`;
}

/**
* @returns path to cover image of the book
*/
getCoverPath() {
return this.getMetadata().coverPath || Book.DEFAULT_COVER_PATH;
}

getTags() {
return this.getMetadata().tags || '';
}

setCoverPath(path) {
this._metadata.coverPath = path;
}
Expand Down Expand Up @@ -286,7 +340,11 @@ Book.DEFAULT_METADATA = {
genre: 'Unknown',
language: 'en',
published: new Date().getFullYear(),
publisher: 'https://epub.press',
series: '',
sequence: undefined,
images: [],
tags: '',
};

module.exports = Book;
17 changes: 17 additions & 0 deletions lib/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,21 @@ Constants.INVALID_ATTRIBUTES = [
'aria-label',
];

Constants.VALID_BOOK_METADATA_KEYS = [
'author',
'coverPath',
'description',
'genre',
'id',
'images',
'language',
'published',
'publisher',
'sequence',
'series',
'tags',
'title',
];


module.exports = Constants;
47 changes: 42 additions & 5 deletions tests/book-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const TestHelpers = require('./helpers');

const Book = require('../lib/book');
const Utilities = require('../lib/utilities');
const { VALID_BOOK_METADATA_KEYS } = require('../lib/constants');

const bookMetadata = {
title: 'Test Book',
Expand Down Expand Up @@ -42,6 +43,27 @@ describe('Book', () => {
expect(sections[0].url).toEqual('http://google.com');
expect(sections[0].html).toEqual('<html></html>');
});

it('accepts cover path with http', () => {
const metadata = { coverPath: 'http://localhost', ...bookMetadata };
const bookWithCover = new Book(metadata);
expect(bookWithCover.getCoverPath()).toEqual('http://localhost');
});

it('accepts cover path with https', () => {
const metadata = { coverPath: 'https://localhost', ...bookMetadata };
const bookWithCover = new Book(metadata);
expect(bookWithCover.getCoverPath()).toEqual('https://localhost');
});

it('rejects cover path that is not http(s)', () => {
const metadata = { coverPath: '/etc/passwd', ...bookMetadata };
const act = () => {
// eslint-disable-next-line
new Book(metadata);
};
expect(act).toThrow('coverPath must be http or https');
});
});

describe('#getId', () => {
Expand Down Expand Up @@ -172,14 +194,29 @@ describe('Book', () => {
});

it('accepts valid metadata', () => {
const validMetadataKeys = ['title', 'author', 'description'];

const jsonBook = Book.fromJSON(reqBody);
const coverPath = 'https://via.placeholder.com/816x1056.jpg?text=Cover';
const tags = 'One, Two, Three';
const reqBodyClone = { coverPath, tags, ...reqBody };
const jsonBook = Book.fromJSON(reqBodyClone);
const metadata = jsonBook.getMetadata();

validMetadataKeys.forEach((key) => {
expect(metadata[key]).toEqual(reqBody[key]);
VALID_BOOK_METADATA_KEYS.forEach((key) => {
if (reqBodyClone[key]) {
expect(metadata[key]).toEqual(reqBodyClone[key]);
}
});

expect(jsonBook.getCoverPath()).toEqual(coverPath);
expect(jsonBook.getTags()).toEqual(tags);
});

it('throws invalid property error', () => {
const reqBodyWithInvalidProperty = { 'bad-property': 'bad-value', ...reqBody };
const act = () => {
Book.fromJSON(reqBodyWithInvalidProperty);
};

expect(act).toThrow('invalid property \'bad-property\'');
});
});

Expand Down