Skip to content
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
7 changes: 6 additions & 1 deletion server/src/http/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,12 @@ export async function sendAssetPayload(
if (payload.etag) reply.header('etag', `"${payload.etag}"`);
if (payload.lastModified) reply.header('last-modified', new Date(payload.lastModified).toUTCString());
if (payload.filename) {
reply.header('content-disposition', `inline; filename*=UTF-8''${encodeURIComponent(payload.filename)}`);
const fallback = payload.filename.replace(/[^\x20-\x7e]|["%\\]/gu, '_');
const encoded = encodeURIComponent(payload.filename).replace(
/['()*]/g,
(character) => '%' + character.charCodeAt(0).toString(16).toUpperCase(),
);
reply.header('content-disposition', `inline; filename="${fallback}"; filename*=UTF-8''${encoded}`);
}

if (options.notModifiedOn && payload.lastModified && payload.lastModified <= options.notModifiedOn) {
Expand Down
24 changes: 15 additions & 9 deletions server/src/http/routes/opds.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
import { createReadStream } from 'node:fs';
import { realpath, stat } from 'node:fs/promises';
import { isAbsolute, relative } from 'node:path';
import { isAbsolute, posix, relative } from 'node:path';
import type { AppContext } from '../context.ts';
import { authenticate, currentUser } from '../auth.ts';
import { OpdsCredentials, xml } from '../../services/opds.ts';
Expand Down Expand Up @@ -86,9 +86,11 @@ export function registerOpdsRoutes(app: FastifyInstance, ctx: AppContext): void
.map((book) => {
const href = `${root()}/books/${encodeURIComponent(book.id)}`;
const file = new FilePublications(ctx.db, ctx.config).context(book.id);
const acquisitionUrl = `${href}/content/${encodeURIComponent(posix.basename(file.relPath))}`;
const mediaType = contentTypeFor(file.relPath).split(';', 1)[0];
return `<entry><id>urn:reader:book:${xml(book.id)}</id><title>${xml(book.title)}</title><updated>${new Date(book.updatedAt).toISOString()}</updated>
<author><name>${xml(book.author)}</name></author><summary type="text">${xml(book.description)}</summary>
${link('http://opds-spec.org/acquisition', href + '/content', contentTypeFor(file.relPath))}
${link('http://opds-spec.org/acquisition', acquisitionUrl, mediaType)}
${book.coverUrl ? link('http://opds-spec.org/image', href + '/cover', '') : ''}</entry>`;
})
.join('');
Expand All @@ -106,13 +108,17 @@ export function registerOpdsRoutes(app: FastifyInstance, ctx: AppContext): void
`<?xml version="1.0" encoding="utf-8"?><OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"><ShortName>Reader</ShortName><Description>搜索个人书架</Description><Url type="${feedType}" template="${xml(root() + '?search={searchTerms}')}"/><InputEncoding>UTF-8</InputEncoding></OpenSearchDescription>`,
),
);
app.get('/opds/books/:id/content', { onRequest: isolateBookResource, preHandler: access }, async (request, reply) => {
const book = ctx.shelf.get(currentUser(request).id, (request.params as { id: string }).id);
if (!formats.includes(book.format)) throw notFound('publication not available');
const files = new FilePublications(ctx.db, ctx.config);
await containedFile(files.context(book.id).absPath, [ctx.config.booksDir, ctx.config.dataDir]);
return sendAssetPayload(request, reply, await files.content(book.id, book.format));
});
app.get(
'/opds/books/:id/content/:filename?',
{ onRequest: isolateBookResource, preHandler: access },
async (request, reply) => {
const book = ctx.shelf.get(currentUser(request).id, (request.params as { id: string }).id);
if (!formats.includes(book.format)) throw notFound('publication not available');
const files = new FilePublications(ctx.db, ctx.config);
await containedFile(files.context(book.id).absPath, [ctx.config.booksDir, ctx.config.dataDir]);
return sendAssetPayload(request, reply, await files.content(book.id, book.format));
},
);
app.get('/opds/books/:id/cover', { onRequest: isolateBookResource, preHandler: access }, async (request, reply) => {
const book = ctx.shelf.get(currentUser(request).id, (request.params as { id: string }).id);
if (!formats.includes(book.format)) throw notFound('publication not available');
Expand Down
2 changes: 1 addition & 1 deletion server/src/indexer/formats/image-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const ZIP_IMAGE_TYPES: Record<string, string> = {
'.zip': 'application/zip',
'.cbz': 'application/vnd.comicbook+zip',
'.cbr': 'application/vnd.comicbook-rar',
'.txt': 'text/plain; charset=utf-8',
'.txt': 'text/plain',
'.md': 'text/markdown; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.html': 'text/html; charset=utf-8',
Expand Down
2 changes: 1 addition & 1 deletion server/src/indexer/formats/text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ export const textHandler = registerFileHandler({
const info = await stat(ctx.absPath);
return {
stream: createReadStream(ctx.absPath),
contentType: contentTypeFor(ctx.relPath, 'text/plain; charset=utf-8'),
contentType: contentTypeFor(ctx.relPath),
size: info.size,
seekable: true,
lastModified: info.mtimeMs,
Expand Down
32 changes: 29 additions & 3 deletions server/test/opds-server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,12 @@ test('OPDS credentials publish a scoped, paginated read-only feed and revoke eve
const session = await ctx.users.login('alice', 'password123', 'test');
const otherSession = await ctx.users.login('other', 'password123', 'test');
const bearer = { authorization: 'Bearer ' + session.accessToken };
const gbkFilename = '中文 书.txt';
const gbkBody = Buffer.from('d6d0cec4', 'hex');
for (let i = 0; i < 52; i++) {
const id = 'b' + String(i).padStart(3, '0');
const filename = i === 1 ? gbkFilename : id + '.txt';
const body = i === 1 ? gbkBody : Buffer.from('hello OPDS');
db.run(
'INSERT INTO books(id,content_hash,format,title,author,created_at,updated_at) VALUES(?,?,?,?,?,?,?)',
id,
Expand All @@ -60,13 +64,13 @@ test('OPDS credentials publish a scoped, paginated read-only feed and revoke eve
1,
1,
);
await writeFile(join(booksDir, id + '.txt'), 'hello OPDS');
await writeFile(join(booksDir, filename), body);
db.run(
'INSERT INTO book_files(id,book_id,rel_path,size,mtime_ms,first_seen,last_seen) VALUES(?,?,?,?,?,?,?)',
id,
id,
id + '.txt',
10,
filename,
body.byteLength,
1,
1,
1,
Expand Down Expand Up @@ -104,6 +108,27 @@ test('OPDS credentials publish a scoped, paginated read-only feed and revoke eve
assert.ok(feed.body.includes('&lt;&amp;&gt;'));
assert.ok(!feed.body.includes('test.txt'));
assert.equal(feed.headers['cache-control'], 'private, no-store');
const acquisition = parsed.entry.find((entry: any) => entry.id === 'urn:reader:book:b001').link;
assert.equal(acquisition['@_rel'], 'http://opds-spec.org/acquisition');
assert.equal(acquisition['@_type'], 'text/plain');
assert.equal(
acquisition['@_href'],
`https://reader.test/prefix/opds/books/b001/content/${encodeURIComponent(gbkFilename)}`,
);
const acquisitionPath = new URL(acquisition['@_href']).pathname.slice('/prefix'.length);
const download = await app.inject({ url: acquisitionPath, headers: basic });
assert.equal(download.statusCode, 200);
assert.deepEqual(download.rawPayload, gbkBody);
assert.equal(download.headers['content-type'], 'text/plain');
assert.equal(
download.headers['content-disposition'],
`inline; filename="__ _.txt"; filename*=UTF-8''${encodeURIComponent(gbkFilename)}`,
);
assert.equal((await app.inject(acquisitionPath)).statusCode, 401);
const rawAsset = await app.inject({ url: '/api/v1/books/b001/assets?ref=content', headers: bearer });
assert.equal(rawAsset.statusCode, 200);
assert.equal(rawAsset.headers['content-type'], 'text/plain');
assert.deepEqual(rawAsset.rawPayload, gbkBody);
const client = createOpdsProvider({
fetch: async (input, init) => {
const target = new URL(String(input));
Expand Down Expand Up @@ -180,6 +205,7 @@ test('OPDS credentials publish a scoped, paginated read-only feed and revoke eve
};
assert.ok(!(await app.inject({ url: '/opds', headers: otherBasic })).body.includes('<entry>'));
assert.equal((await app.inject({ url: '/opds/books/b000/content', headers: otherBasic })).statusCode, 404);
assert.equal((await app.inject({ url: acquisitionPath, headers: otherBasic })).statusCode, 404);
await app.inject({ method: 'DELETE', url: '/api/v1/opds/credentials/' + credential.id, headers: bearer });
for (const url of ['/opds', '/opds/books/b000/content', '/opds/books/b000/cover'])
assert.equal((await app.inject({ url, headers: basic })).statusCode, 401);
Expand Down
Loading