mirror of
https://github.com/kikootwo/ReadMeABook.git
synced 2026-06-03 04:40:09 +00:00
Add extensible notification providers + UI/API
Introduce a provider-based notification system and wire it through the API and admin UI. Added INotificationProvider + notification service implementation and providers (apprise, discord, ntfy, pushover), plus a GET /api/admin/notifications/providers endpoint to expose provider metadata. Refactored code to use provider type strings (removed enum coupling), updated masking/encryption calls, and simplified the test notification endpoint to accept backendId or type+config and call sendToBackend directly. UI: NotificationsTab now fetches provider metadata and renders provider cards and dynamic config forms (fields driven by provider metadata). Added config field rendering, improved backend cards, and edit/delete actions. APIs: New providers route, updated admin notification CRUD routes to validate provider types dynamically, updated test route schema. Added download-client categories POST API to fetch categories from clients and wired postImportCategory handling in download-client routes. Other notable changes: BookDate now fetches Claude models dynamically from Anthropic's Models API; added paginated model fetch helper. Added ALLOW_WEAK_PASSWORD flag exposure to auth providers and password change logic. Doc updates and various tests added/updated. File-organization doc clarifies EPERM fix using stream-based copy.
This commit is contained in:
@@ -30,8 +30,9 @@ vi.mock('@/lib/middleware/auth', () => ({
|
||||
requireAdmin: requireAdminMock,
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/services/notification.service', () => ({
|
||||
vi.mock('@/lib/services/notification', () => ({
|
||||
getNotificationService: () => notificationServiceMock,
|
||||
getRegisteredProviderTypes: () => ['discord', 'ntfy', 'pushover'],
|
||||
}));
|
||||
|
||||
describe('Admin notifications test route', () => {
|
||||
|
||||
@@ -35,8 +35,9 @@ vi.mock('@/lib/middleware/auth', () => ({
|
||||
requireAdmin: requireAdminMock,
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/services/notification.service', () => ({
|
||||
vi.mock('@/lib/services/notification', () => ({
|
||||
getNotificationService: () => notificationServiceMock,
|
||||
getRegisteredProviderTypes: () => ['discord', 'ntfy', 'pushover'],
|
||||
}));
|
||||
|
||||
describe('Admin notifications routes', () => {
|
||||
|
||||
@@ -13,6 +13,7 @@ const configServiceMock = vi.hoisted(() => ({
|
||||
}));
|
||||
const prowlarrMock = vi.hoisted(() => ({
|
||||
search: vi.fn(),
|
||||
searchWithVariations: vi.fn(),
|
||||
}));
|
||||
const rankTorrentsMock = vi.hoisted(() => vi.fn());
|
||||
const groupIndexersMock = vi.hoisted(() => vi.fn());
|
||||
@@ -68,7 +69,7 @@ describe('Audiobooks search torrents route', () => {
|
||||
.mockResolvedValueOnce(null);
|
||||
|
||||
groupIndexersMock.mockReturnValue({ groups: [{ categories: [1], indexerIds: [1] }], skippedIndexers: [] });
|
||||
prowlarrMock.search.mockResolvedValue([{ title: 'Result', size: 100, indexer: 'Indexer', indexerId: 1 }]);
|
||||
prowlarrMock.searchWithVariations.mockResolvedValue([{ title: 'Result', size: 100, indexer: 'Indexer', indexerId: 1 }]);
|
||||
rankTorrentsMock.mockReturnValue([
|
||||
{
|
||||
title: 'Result',
|
||||
|
||||
@@ -68,6 +68,32 @@ describe('Change password route', () => {
|
||||
expect(payload.error).toMatch(/at least 8 characters/i);
|
||||
});
|
||||
|
||||
it('allows short passwords when ALLOW_WEAK_PASSWORD is enabled', async () => {
|
||||
process.env.ALLOW_WEAK_PASSWORD = 'true';
|
||||
prismaMock.user.findUnique.mockResolvedValue({
|
||||
id: 'user-1',
|
||||
authProvider: 'local',
|
||||
authToken: 'enc-hash',
|
||||
plexId: 'local-user',
|
||||
plexUsername: 'user',
|
||||
});
|
||||
encryptionMock.decrypt.mockReturnValue('hash');
|
||||
bcryptMock.compare.mockResolvedValue(true);
|
||||
bcryptMock.hash.mockResolvedValue('new-hash');
|
||||
encryptionMock.encrypt.mockReturnValue('enc-new-hash');
|
||||
prismaMock.user.update.mockResolvedValue({});
|
||||
const { POST } = await import('@/app/api/auth/change-password/route');
|
||||
|
||||
const response = await POST(
|
||||
makeRequest({ currentPassword: 'oldpass', newPassword: 'ab', confirmPassword: 'ab' }) as any
|
||||
);
|
||||
const payload = await response.json();
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(payload.success).toBe(true);
|
||||
delete process.env.ALLOW_WEAK_PASSWORD;
|
||||
});
|
||||
|
||||
it('blocks non-local users', async () => {
|
||||
prismaMock.user.findUnique.mockResolvedValue({
|
||||
id: 'user-1',
|
||||
|
||||
@@ -149,6 +149,15 @@ describe('BookDate test connection route', () => {
|
||||
it('returns Claude models for unauthenticated requests', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({
|
||||
data: [
|
||||
{ id: 'claude-sonnet-4-5-20250929', display_name: 'Claude Sonnet 4.5', type: 'model', created_at: '2025-09-29T00:00:00Z' },
|
||||
{ id: 'claude-haiku-4-5-20251001', display_name: 'Claude Haiku 4.5', type: 'model', created_at: '2025-10-01T00:00:00Z' },
|
||||
],
|
||||
has_more: false,
|
||||
first_id: 'claude-sonnet-4-5-20250929',
|
||||
last_id: 'claude-haiku-4-5-20251001',
|
||||
}),
|
||||
text: vi.fn().mockResolvedValue('ok'),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
@@ -161,7 +170,142 @@ describe('BookDate test connection route', () => {
|
||||
|
||||
const payload = await response.json();
|
||||
expect(payload.success).toBe(true);
|
||||
expect(payload.models.length).toBe(4);
|
||||
expect(payload.models).toEqual([
|
||||
{ id: 'claude-sonnet-4-5-20250929', name: 'Claude Sonnet 4.5' },
|
||||
{ id: 'claude-haiku-4-5-20251001', name: 'Claude Haiku 4.5' },
|
||||
]);
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
expect.stringContaining('https://api.anthropic.com/v1/models'),
|
||||
expect.objectContaining({
|
||||
headers: expect.objectContaining({ 'x-api-key': 'key' }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('returns Claude models for authenticated requests', async () => {
|
||||
requireAuthMock.mockImplementation((_req: any, handler: any) => handler(_req));
|
||||
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({
|
||||
data: [
|
||||
{ id: 'claude-opus-4-20250514', display_name: 'Claude Opus 4', type: 'model', created_at: '2025-05-14T00:00:00Z' },
|
||||
],
|
||||
has_more: false,
|
||||
first_id: 'claude-opus-4-20250514',
|
||||
last_id: 'claude-opus-4-20250514',
|
||||
}),
|
||||
text: vi.fn().mockResolvedValue('ok'),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const { POST } = await import('@/app/api/bookdate/test-connection/route');
|
||||
const response = await POST({
|
||||
headers: { get: () => 'Bearer token' },
|
||||
json: vi.fn().mockResolvedValue({ provider: 'claude', apiKey: 'key' }),
|
||||
} as any);
|
||||
|
||||
const payload = await response.json();
|
||||
expect(payload.success).toBe(true);
|
||||
expect(payload.models).toEqual([
|
||||
{ id: 'claude-opus-4-20250514', name: 'Claude Opus 4' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns error for invalid Claude API key', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
text: vi.fn().mockResolvedValue('{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}'),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const { POST } = await import('@/app/api/bookdate/test-connection/route');
|
||||
const response = await POST({
|
||||
headers: { get: () => null },
|
||||
json: vi.fn().mockResolvedValue({ provider: 'claude', apiKey: 'bad-key' }),
|
||||
} as any);
|
||||
|
||||
const payload = await response.json();
|
||||
expect(response.status).toBe(400);
|
||||
expect(payload.error).toMatch(/Invalid Claude API key/i);
|
||||
});
|
||||
|
||||
it('paginates through Claude models when has_more is true', async () => {
|
||||
let callCount = 0;
|
||||
const fetchMock = vi.fn().mockImplementation(() => {
|
||||
callCount++;
|
||||
if (callCount === 1) {
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({
|
||||
data: [
|
||||
{ id: 'claude-sonnet-4-5-20250929', display_name: 'Claude Sonnet 4.5', type: 'model', created_at: '2025-09-29T00:00:00Z' },
|
||||
],
|
||||
has_more: true,
|
||||
first_id: 'claude-sonnet-4-5-20250929',
|
||||
last_id: 'claude-sonnet-4-5-20250929',
|
||||
}),
|
||||
text: vi.fn().mockResolvedValue('ok'),
|
||||
});
|
||||
}
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({
|
||||
data: [
|
||||
{ id: 'claude-haiku-4-5-20251001', display_name: 'Claude Haiku 4.5', type: 'model', created_at: '2025-10-01T00:00:00Z' },
|
||||
],
|
||||
has_more: false,
|
||||
first_id: 'claude-haiku-4-5-20251001',
|
||||
last_id: 'claude-haiku-4-5-20251001',
|
||||
}),
|
||||
text: vi.fn().mockResolvedValue('ok'),
|
||||
});
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const { POST } = await import('@/app/api/bookdate/test-connection/route');
|
||||
const response = await POST({
|
||||
headers: { get: () => null },
|
||||
json: vi.fn().mockResolvedValue({ provider: 'claude', apiKey: 'key' }),
|
||||
} as any);
|
||||
|
||||
const payload = await response.json();
|
||||
expect(payload.success).toBe(true);
|
||||
expect(payload.models).toEqual([
|
||||
{ id: 'claude-sonnet-4-5-20250929', name: 'Claude Sonnet 4.5' },
|
||||
{ id: 'claude-haiku-4-5-20251001', name: 'Claude Haiku 4.5' },
|
||||
]);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
// Second call should include after_id for pagination
|
||||
expect(fetchMock.mock.calls[1][0]).toContain('after_id=claude-sonnet-4-5-20250929');
|
||||
});
|
||||
|
||||
it('falls back to model id when display_name is missing', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({
|
||||
data: [
|
||||
{ id: 'claude-test-model', type: 'model', created_at: '2025-01-01T00:00:00Z' },
|
||||
],
|
||||
has_more: false,
|
||||
first_id: 'claude-test-model',
|
||||
last_id: 'claude-test-model',
|
||||
}),
|
||||
text: vi.fn().mockResolvedValue('ok'),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const { POST } = await import('@/app/api/bookdate/test-connection/route');
|
||||
const response = await POST({
|
||||
headers: { get: () => null },
|
||||
json: vi.fn().mockResolvedValue({ provider: 'claude', apiKey: 'key' }),
|
||||
} as any);
|
||||
|
||||
const payload = await response.json();
|
||||
expect(payload.success).toBe(true);
|
||||
expect(payload.models).toEqual([
|
||||
{ id: 'claude-test-model', name: 'claude-test-model' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns OpenAI error for unauthenticated requests with invalid key', async () => {
|
||||
|
||||
@@ -10,9 +10,11 @@ let authRequest: any;
|
||||
|
||||
const prismaMock = createPrismaMock();
|
||||
const requireAuthMock = vi.hoisted(() => vi.fn());
|
||||
const prowlarrMock = vi.hoisted(() => ({ search: vi.fn() }));
|
||||
const prowlarrMock = vi.hoisted(() => ({ search: vi.fn(), searchWithVariations: vi.fn() }));
|
||||
const rankTorrentsMock = vi.hoisted(() => vi.fn());
|
||||
const configServiceMock = vi.hoisted(() => ({ get: vi.fn() }));
|
||||
const groupIndexersMock = vi.hoisted(() => vi.fn());
|
||||
const groupDescriptionMock = vi.hoisted(() => vi.fn(() => 'Group'));
|
||||
const configState = vi.hoisted(() => ({
|
||||
values: new Map<string, string>(),
|
||||
}));
|
||||
@@ -23,6 +25,9 @@ const jobQueueMock = vi.hoisted(() => ({
|
||||
addSearchEbookJob: vi.fn(() => Promise.resolve()),
|
||||
}));
|
||||
const downloadEbookMock = vi.hoisted(() => vi.fn());
|
||||
const audibleServiceMock = vi.hoisted(() => ({
|
||||
getRuntime: vi.fn(),
|
||||
}));
|
||||
const fsMock = vi.hoisted(() => ({
|
||||
access: vi.fn(),
|
||||
}));
|
||||
@@ -44,6 +49,11 @@ vi.mock('@/lib/utils/ranking-algorithm', () => ({
|
||||
rankTorrents: rankTorrentsMock,
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/utils/indexer-grouping', () => ({
|
||||
groupIndexersByCategories: groupIndexersMock,
|
||||
getGroupDescription: groupDescriptionMock,
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/services/config.service', () => ({
|
||||
getConfigService: () => configServiceMock,
|
||||
}));
|
||||
@@ -56,6 +66,10 @@ vi.mock('@/lib/services/ebook-scraper', () => ({
|
||||
downloadEbook: downloadEbookMock,
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/integrations/audible.service', () => ({
|
||||
getAudibleService: () => audibleServiceMock,
|
||||
}));
|
||||
|
||||
vi.mock('fs/promises', () => ({ default: fsMock, ...fsMock, constants: { R_OK: 4 } }));
|
||||
|
||||
describe('Request action routes', () => {
|
||||
@@ -72,22 +86,24 @@ describe('Request action routes', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('performs interactive search and ranks results', async () => {
|
||||
it('performs interactive search and ranks results with runtime from ASIN', async () => {
|
||||
authRequest.json.mockResolvedValue({});
|
||||
prismaMock.request.findUnique.mockResolvedValueOnce({
|
||||
id: 'req-1',
|
||||
userId: 'user-1',
|
||||
audiobook: { title: 'Title', author: 'Author' },
|
||||
audiobook: { title: 'Title', author: 'Author', audibleAsin: 'B00ASIN123' },
|
||||
});
|
||||
prismaMock.user.findUnique.mockResolvedValueOnce({
|
||||
role: 'user',
|
||||
interactiveSearchAccess: null,
|
||||
});
|
||||
configServiceMock.get.mockResolvedValueOnce(JSON.stringify([{ id: 1, priority: 10 }]));
|
||||
configServiceMock.get.mockResolvedValueOnce(JSON.stringify([{ id: 1, priority: 10, categories: [3030] }]));
|
||||
configServiceMock.get.mockResolvedValueOnce(null);
|
||||
prowlarrMock.search.mockResolvedValueOnce([{ title: 'Result', size: 100 }]);
|
||||
groupIndexersMock.mockReturnValue({ groups: [{ categories: [3030], indexerIds: [1] }], skippedIndexers: [] });
|
||||
prowlarrMock.searchWithVariations.mockResolvedValueOnce([{ title: 'Result', size: 500 * 1024 * 1024 }]);
|
||||
audibleServiceMock.getRuntime.mockResolvedValueOnce(600);
|
||||
rankTorrentsMock.mockReturnValueOnce([
|
||||
{ title: 'Result', score: 50, breakdown: { matchScore: 50, formatScore: 0, seederScore: 0, notes: [] }, bonusPoints: 0, bonusModifiers: [], finalScore: 50 },
|
||||
{ title: 'Result', size: 500 * 1024 * 1024, score: 50, breakdown: { matchScore: 50, formatScore: 0, sizeScore: 12, seederScore: 0, notes: [] }, bonusPoints: 0, bonusModifiers: [], finalScore: 62 },
|
||||
]);
|
||||
|
||||
const { POST } = await import('@/app/api/requests/[id]/interactive-search/route');
|
||||
@@ -96,6 +112,77 @@ describe('Request action routes', () => {
|
||||
|
||||
expect(payload.success).toBe(true);
|
||||
expect(payload.results[0].rank).toBe(1);
|
||||
expect(audibleServiceMock.getRuntime).toHaveBeenCalledWith('B00ASIN123');
|
||||
expect(rankTorrentsMock).toHaveBeenCalledWith(
|
||||
expect.any(Array),
|
||||
expect.objectContaining({ title: 'Title', author: 'Author', durationMinutes: 600 }),
|
||||
expect.any(Object)
|
||||
);
|
||||
});
|
||||
|
||||
it('performs interactive search without runtime when no ASIN', async () => {
|
||||
authRequest.json.mockResolvedValue({});
|
||||
prismaMock.request.findUnique.mockResolvedValueOnce({
|
||||
id: 'req-1b',
|
||||
userId: 'user-1',
|
||||
audiobook: { title: 'Title', author: 'Author', audibleAsin: null },
|
||||
});
|
||||
prismaMock.user.findUnique.mockResolvedValueOnce({
|
||||
role: 'user',
|
||||
interactiveSearchAccess: null,
|
||||
});
|
||||
configServiceMock.get.mockResolvedValueOnce(JSON.stringify([{ id: 1, priority: 10, categories: [3030] }]));
|
||||
configServiceMock.get.mockResolvedValueOnce(null);
|
||||
groupIndexersMock.mockReturnValue({ groups: [{ categories: [3030], indexerIds: [1] }], skippedIndexers: [] });
|
||||
prowlarrMock.searchWithVariations.mockResolvedValueOnce([{ title: 'Result', size: 100 }]);
|
||||
rankTorrentsMock.mockReturnValueOnce([
|
||||
{ title: 'Result', size: 100, score: 50, breakdown: { matchScore: 50, formatScore: 0, sizeScore: 0, seederScore: 0, notes: [] }, bonusPoints: 0, bonusModifiers: [], finalScore: 50 },
|
||||
]);
|
||||
|
||||
const { POST } = await import('@/app/api/requests/[id]/interactive-search/route');
|
||||
const response = await POST({} as any, { params: Promise.resolve({ id: 'req-1b' }) });
|
||||
const payload = await response.json();
|
||||
|
||||
expect(payload.success).toBe(true);
|
||||
expect(audibleServiceMock.getRuntime).not.toHaveBeenCalled();
|
||||
expect(rankTorrentsMock).toHaveBeenCalledWith(
|
||||
expect.any(Array),
|
||||
expect.objectContaining({ title: 'Title', author: 'Author', durationMinutes: undefined }),
|
||||
expect.any(Object)
|
||||
);
|
||||
});
|
||||
|
||||
it('performs interactive search gracefully when runtime fetch fails', async () => {
|
||||
authRequest.json.mockResolvedValue({});
|
||||
prismaMock.request.findUnique.mockResolvedValueOnce({
|
||||
id: 'req-1c',
|
||||
userId: 'user-1',
|
||||
audiobook: { title: 'Title', author: 'Author', audibleAsin: 'B00FAIL' },
|
||||
});
|
||||
prismaMock.user.findUnique.mockResolvedValueOnce({
|
||||
role: 'user',
|
||||
interactiveSearchAccess: null,
|
||||
});
|
||||
configServiceMock.get.mockResolvedValueOnce(JSON.stringify([{ id: 1, priority: 10, categories: [3030] }]));
|
||||
configServiceMock.get.mockResolvedValueOnce(null);
|
||||
groupIndexersMock.mockReturnValue({ groups: [{ categories: [3030], indexerIds: [1] }], skippedIndexers: [] });
|
||||
prowlarrMock.searchWithVariations.mockResolvedValueOnce([{ title: 'Result', size: 100 }]);
|
||||
audibleServiceMock.getRuntime.mockRejectedValueOnce(new Error('Network error'));
|
||||
rankTorrentsMock.mockReturnValueOnce([
|
||||
{ title: 'Result', size: 100, score: 50, breakdown: { matchScore: 50, formatScore: 0, sizeScore: 0, seederScore: 0, notes: [] }, bonusPoints: 0, bonusModifiers: [], finalScore: 50 },
|
||||
]);
|
||||
|
||||
const { POST } = await import('@/app/api/requests/[id]/interactive-search/route');
|
||||
const response = await POST({} as any, { params: Promise.resolve({ id: 'req-1c' }) });
|
||||
const payload = await response.json();
|
||||
|
||||
expect(payload.success).toBe(true);
|
||||
expect(payload.results).toHaveLength(1);
|
||||
expect(rankTorrentsMock).toHaveBeenCalledWith(
|
||||
expect.any(Array),
|
||||
expect.objectContaining({ durationMinutes: undefined }),
|
||||
expect.any(Object)
|
||||
);
|
||||
});
|
||||
|
||||
it('triggers manual search job', async () => {
|
||||
|
||||
Reference in New Issue
Block a user