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
82 changes: 82 additions & 0 deletions plugins/motrix.scraper-hook/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import type { BeforeCreateHttpContext } from 'motrix:plugin-api'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

const api = vi.hoisted(() => ({
config: { get: vi.fn() },
hooks: { beforeCreate: vi.fn() },
http: { request: vi.fn() },
lifecycle: { onDeactivate: vi.fn() },
log: { info: vi.fn(), warn: vi.fn() },
}))
vi.mock('motrix:plugin-api', () => api)

describe('optional scraper budget', () => {
let run: (ctx: BeforeCreateHttpContext) => Promise<BeforeCreateHttpContext>
let ctx: BeforeCreateHttpContext
beforeEach(async () => {
vi.resetModules()
vi.resetAllMocks()
vi.useFakeTimers()
vi.setSystemTime(0)
api.config.get.mockResolvedValue(undefined)
await import('./index')
run = api.hooks.beforeCreate.mock.calls[0]![0]
ctx = {
type: 'http',
uris: ['https://example.test/page'],
headers: [{ name: 'Referer', value: 'https://example.test/' }],
update: vi.fn(),
} as unknown as BeforeCreateHttpContext
})
afterEach(() => vi.useRealTimers())

it('shares one three-second deadline across HEAD and GET', async () => {
api.http.request
.mockImplementationOnce(async () => {
vi.setSystemTime(2400)
return { headers: [{ name: 'Content-Type', value: 'text/html' }] }
})
.mockResolvedValueOnce({ body: '<html></html>', headers: [] })
expect(await run(ctx)).toBe(ctx)
expect(
api.http.request.mock.calls.map(([request]) => request.timeoutMs)
).toEqual([3000, 600])
expect(api.http.request.mock.calls[1]![0]).toMatchObject({
maxBodyBytes: 524288,
headers: ctx.headers,
})
})

it('does not start GET when HEAD has consumed the budget', async () => {
api.http.request.mockImplementationOnce(async () => {
vi.setSystemTime(3001)
return { headers: [{ name: 'Content-Type', value: 'text/html' }] }
})
expect(await run(ctx)).toBe(ctx)
expect(api.http.request).toHaveBeenCalledOnce()
})

it.each([
'plugin.http.timeout',
'plugin.http.network',
'plugin.http.response_too_large',
])('falls back for %s without a partial update', async (code) => {
api.http.request.mockRejectedValue(
Object.assign(new Error('unavailable'), { code })
)
expect(await run(ctx)).toBe(ctx)
expect(ctx.update).not.toHaveBeenCalled()
})

it.each([
'plugin.http.aborted',
'plugin.http.host_not_permitted',
'plugin.http.redirect_not_allowed',
'unknown',
])('propagates critical failure %s', async (code) => {
const error = Object.assign(new Error('denied'), { code })
api.http.request.mockRejectedValue(error)
await expect(run(ctx)).rejects.toBe(error)
expect(ctx.update).not.toHaveBeenCalled()
})
})
28 changes: 23 additions & 5 deletions plugins/motrix.scraper-hook/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ import {
import { findArchiveLink } from './scrapers'

const DEFAULT_MAX_BODY = 524288
const DISCOVERY_BUDGET_MS = 3_000
const OPTIONAL_NETWORK_ERRORS = new Set([
'plugin.http.timeout',
'plugin.http.network',
'plugin.http.response_too_large',
'plugin.http.too_many_redirects',
])

async function isEnabled(): Promise<boolean> {
const v = await config.get<boolean>('enabled')
Expand All @@ -26,33 +33,44 @@ hooks.beforeCreate(
if (!(await isEnabled())) return ctx
const url = ctx.uris[0]
if (!url) return ctx
const deadline = Date.now() + DISCOVERY_BUDGET_MS
const maxBody = await readMaxBody()
const remaining = () => Math.max(0, deadline - Date.now())
try {
const headBudget = remaining()
if (!headBudget) return ctx
const head = await http.request({
method: 'HEAD',
url,
responseType: 'text',
timeoutMs: 5_000,
headers: ctx.headers,
timeoutMs: headBudget,
})
const ctHeader = head.headers.find(
(h) => h.name.toLowerCase() === 'content-type'
)
const ct = ctHeader?.value ?? ''
if (!ct.includes('text/html')) return ctx
const maxBody = await readMaxBody()
const getBudget = remaining()
if (!getBudget) return ctx
const res = await http.request({
method: 'GET',
url,
responseType: 'text',
timeoutMs: 10_000,
headers: ctx.headers,
timeoutMs: getBudget,
maxBodyBytes: maxBody,
})
const archiveUrl = findArchiveLink(res.body as string, url)
if (archiveUrl) {
log.info('scraper rewrote URL', { from: url, to: archiveUrl })
log.info('scraper discovered a download target')
ctx.update({ uris: [archiveUrl] })
}
} catch (e) {
log.warn('scraper failed', { err: String(e) })
const code =
typeof e === 'object' && e !== null && 'code' in e ? String(e.code) : ''
if (!OPTIONAL_NETWORK_ERRORS.has(code)) throw e
log.warn('optional discovery unavailable', { code })
}
return ctx
}
Expand Down