diff --git a/src/lib/RepStatus.js b/src/lib/RepStatus.js index 39809738c..919d3897f 100644 --- a/src/lib/RepStatus.js +++ b/src/lib/RepStatus.js @@ -37,6 +37,25 @@ class RepStatus extends EventEmitter { return code; } + /** + * Reads the status state out of a representation info response, tolerating a malformed payload + * + * @private + * @param {Object} info - representation info response + * @return {string|undefined} status state, or undefined when the payload has none + */ + static getStateFromInfo(info) { + if (!info) { + return undefined; + } + + if (typeof info.status === 'object') { + return info.status ? info.status.state : undefined; + } + + return info.temp_status ? info.temp_status.state : undefined; + } + /** * [constructor] * @@ -48,15 +67,32 @@ class RepStatus extends EventEmitter { * @param {string} options.sharedLinkPassword - Shared link password * @param {string} options.fileId - File ID * @param {Object} [options.logger] - Optional logger instance + * @param {boolean} [options.enableConvertTimer] - Whether to time the conversion for the load metrics + * @param {Object} [options.backoff] - Multiplies the pending poll interval by factor (default 2) up to + * maxIntervalMs and rejects once polling would run past maxWaitMs. Polls every STATUS_UPDATE_INTERVAL_MS + * indefinitely without it. * @return {RepStatus} RepStatus instance */ - constructor({ api, representation, token, sharedLink, sharedLinkPassword, logger, fileId }) { + constructor({ + api, + representation, + token, + sharedLink, + sharedLinkPassword, + logger, + fileId, + enableConvertTimer = true, + backoff = null, + }) { super(); this.api = api; this.representation = representation; this.logger = logger; this.fileId = fileId; + this.enableConvertTimer = enableConvertTimer; + this.backoff = backoff; + this.pollIntervalMs = STATUS_UPDATE_INTERVAL_MS; // Some representations (e.g. ORIGINAL) may not have an info url const repInfo = this.representation.info; @@ -75,6 +111,7 @@ class RepStatus extends EventEmitter { * @return {void} */ destroy() { + this.destroyed = true; clearTimeout(this.statusTimeout); } @@ -85,27 +122,41 @@ class RepStatus extends EventEmitter { * @return {Promise} Promise to update status */ updateStatus() { - if (!this.infoUrl) { + if (!this.infoUrl || this.destroyed) { return Promise.resolve(); } - const tag = Timer.createTag(this.fileId, LOAD_METRIC.convertTime); - Timer.start(tag); + if (this.enableConvertTimer) { + Timer.start(Timer.createTag(this.fileId, LOAD_METRIC.convertTime)); + } const options = this.headers ? { headers: this.headers } : {}; return this.api.get(this.infoUrl, options).then( info => { + if (this.destroyed) { + return; + } + clearTimeout(this.statusTimeout); + const state = RepStatus.getStateFromInfo(info); + if (!state) { + this.reject( + new PreviewError(ERROR_CODE.CONVERSION_GENERIC, __('error_refresh'), { + representation: this.representation, + }), + ); + return; + } + if (info.metadata) { this.representation.metadata = info.metadata; } - const status = typeof info.status === 'object' ? info.status.state : info.temp_status.state; if (typeof this.representation.status === 'object') { - this.representation.status.state = status; + this.representation.status.state = state; } else { - this.representation.temp_status.state = status; + this.representation.temp_status.state = state; } this.handleResponse(); @@ -113,6 +164,10 @@ class RepStatus extends EventEmitter { // Reject instead of hanging if the info request itself fails (e.g. the representation // endpoint returns a 4xx/5xx), so the viewer can surface an error rather than spin forever. () => { + if (this.destroyed) { + return; + } + clearTimeout(this.statusTimeout); const error = new PreviewError(ERROR_CODE.CONVERSION_GENERIC, __('error_refresh'), { representation: this.representation, @@ -167,7 +222,9 @@ class RepStatus extends EventEmitter { case STATUS_SUCCESS: case STATUS_VIEWABLE: - Timer.stop(convertTag); + if (this.enableConvertTimer) { + Timer.stop(convertTag); + } this.resolve(); break; @@ -180,15 +237,7 @@ class RepStatus extends EventEmitter { this.emit('conversionpending'); - // Check status again after delay or - // If status is none, request immediately since conversion - // won't kick off until representation is requested - this.statusTimeout = setTimeout( - () => { - this.updateStatus(); - }, - status === STATUS_NONE ? 0 : STATUS_UPDATE_INTERVAL_MS, - ); + this.scheduleNextPoll(status); break; default: @@ -196,6 +245,40 @@ class RepStatus extends EventEmitter { } } + /** + * Schedules the next status check. A 'none' status is checked immediately, since the conversion won't + * kick off until the representation is requested. + * + * @private + * @param {string} status - Current representation status + * @return {void} + */ + scheduleNextPoll(status) { + const delay = status === STATUS_NONE ? 0 : this.pollIntervalMs; + + if (this.backoff) { + const { factor = 2, maxIntervalMs, maxWaitMs } = this.backoff; + + this.pollStartTime = this.pollStartTime ?? Date.now(); + if (Date.now() - this.pollStartTime + delay > maxWaitMs) { + this.reject( + new PreviewError(ERROR_CODE.CONVERSION_TRY_AGAIN_LATER, __('error_try_again_later'), { + representation: this.representation, + }), + ); + return; + } + + if (status !== STATUS_NONE) { + this.pollIntervalMs = Math.min(Math.round(delay * factor), maxIntervalMs); + } + } + + this.statusTimeout = setTimeout(() => { + this.updateStatus(); + }, delay); + } + /** * Promises to return the status of a representation asset * diff --git a/src/lib/__tests__/RepStatus-test.js b/src/lib/__tests__/RepStatus-test.js index b4955481a..0e52d63b6 100644 --- a/src/lib/__tests__/RepStatus-test.js +++ b/src/lib/__tests__/RepStatus-test.js @@ -2,7 +2,7 @@ import * as util from '../util'; import Api from '../api'; import RepStatus from '../RepStatus'; -import { LOAD_METRIC } from '../events'; +import { ERROR_CODE, LOAD_METRIC } from '../events'; import Timer from '../Timer'; import { STATUS_SUCCESS } from '../constants'; @@ -73,6 +73,32 @@ describe('lib/RepStatus', () => { }); }); + describe('getStateFromInfo()', () => { + test('should return undefined when there is no info', () => { + expect(RepStatus.getStateFromInfo(undefined)).toBeUndefined(); + }); + + test('should return the state from the status object', () => { + expect(RepStatus.getStateFromInfo({ status: { state: 'success' } })).toBe('success'); + }); + + test('should return undefined when the status object has no state', () => { + expect(RepStatus.getStateFromInfo({ status: {} })).toBeUndefined(); + }); + + test('should return undefined when the status object is null', () => { + expect(RepStatus.getStateFromInfo({ status: null })).toBeUndefined(); + }); + + test('should fall back to temp_status when status is not an object', () => { + expect(RepStatus.getStateFromInfo({ temp_status: { state: 'pending' } })).toBe('pending'); + }); + + test('should return undefined when neither status nor temp_status carry a state', () => { + expect(RepStatus.getStateFromInfo({})).toBeUndefined(); + }); + }); + describe('constructor()', () => { const infoUrl = 'someUrl'; @@ -92,6 +118,18 @@ describe('lib/RepStatus', () => { expect(typeof repStatus.logger).toBe('object'); expect(repStatus.infoUrl).toBe(infoUrl); expect(repStatus.promise).toBeInstanceOf(Promise); + expect(repStatus.enableConvertTimer).toBe(true); + }); + + test('should disable the convert timer when told to', () => { + repStatus = new RepStatus({ + api: {}, + representation: rep, + logger: {}, + enableConvertTimer: false, + }); + + expect(repStatus.enableConvertTimer).toBe(false); }); test('should use appendAuthParamsV2 and set Authorization headers', () => { @@ -120,6 +158,11 @@ describe('lib/RepStatus', () => { sandbox.mock(window).expects('clearTimeout'); repStatus.destroy(); }); + + test('should mark the instance destroyed', () => { + repStatus.destroy(); + expect(repStatus.destroyed).toBe(true); + }); }); describe('updateStatus()', () => { @@ -171,6 +214,14 @@ describe('lib/RepStatus', () => { expect(repStatus.api.get).not.toBeCalled(); }); + test('should return a resolved promise without fetching if destroyed', () => { + jest.spyOn(repStatus.api, 'get'); + + repStatus.destroyed = true; + expect(repStatus.updateStatus()).toBeInstanceOf(Promise); + expect(repStatus.api.get).not.toBeCalled(); + }); + test('should start a convert time Timer', () => { jest.spyOn(repStatus.api, 'get').mockResolvedValue({ info: {}, @@ -186,6 +237,42 @@ describe('lib/RepStatus', () => { }); }); + test('should not start a convert time Timer when the timer is disabled', () => { + repStatus.enableConvertTimer = false; + jest.spyOn(repStatus.api, 'get').mockResolvedValue({ + info: {}, + status: { + state, + }, + }); + jest.spyOn(Timer, 'start'); + + return repStatus.updateStatus().then(() => { + expect(Timer.start).not.toBeCalled(); + }); + }); + + test('should not process a response that arrives after it is destroyed', () => { + jest.spyOn(repStatus.api, 'get').mockImplementation(() => { + repStatus.destroyed = true; + return Promise.resolve({ info: {}, status: { state } }); + }); + + return repStatus.updateStatus().then(() => { + expect(repStatus.handleResponse).not.toBeCalled(); + }); + }); + + test('should reject when the info response has no status state', () => { + jest.spyOn(repStatus.api, 'get').mockResolvedValue({ info: {} }); + jest.spyOn(repStatus, 'reject').mockImplementation(); + + return repStatus.updateStatus().then(() => { + expect(repStatus.reject).toBeCalled(); + expect(repStatus.handleResponse).not.toBeCalled(); + }); + }); + test('should reject the status promise when the info request fails instead of hanging', () => { jest.spyOn(repStatus.api, 'get').mockRejectedValue(new Error('Not Found')); jest.spyOn(repStatus, 'reject').mockImplementation(); @@ -195,6 +282,18 @@ describe('lib/RepStatus', () => { expect(repStatus.handleResponse).not.toBeCalled(); }); }); + + test('should not reject a failed info request after it is destroyed', () => { + jest.spyOn(repStatus.api, 'get').mockImplementation(() => { + repStatus.destroyed = true; + return Promise.reject(new Error('Not Found')); + }); + jest.spyOn(repStatus, 'reject').mockImplementation(); + + return repStatus.updateStatus().then(() => { + expect(repStatus.reject).not.toBeCalled(); + }); + }); }); describe('handleResponse()', () => { @@ -350,6 +449,78 @@ describe('lib/RepStatus', () => { clock.restore(); }); + describe('polling backoff', () => { + const getPollDelays = setTimeoutStub => setTimeoutStub.mock.calls.map(([, delay]) => delay); + let stubs; + + beforeEach(() => { + stubs = {}; + repStatus.logger = false; + stubs.setTimeout = jest.spyOn(global, 'setTimeout').mockImplementation(() => 1); + stubs.now = jest.spyOn(Date, 'now').mockReturnValue(0); + }); + + test('should poll a pending status at a fixed interval without a backoff', () => { + repStatus.representation.status.state = 'pending'; + + repStatus.handleResponse(); + repStatus.handleResponse(); + repStatus.handleResponse(); + + expect(getPollDelays(stubs.setTimeout)).toEqual([2000, 2000, 2000]); + }); + + test('should grow the pending poll interval by the backoff factor up to the maximum', () => { + repStatus.backoff = { factor: 1.5, maxIntervalMs: 10000, maxWaitMs: 600000 }; + repStatus.representation.status.state = 'pending'; + + for (let i = 0; i < 6; i += 1) { + repStatus.handleResponse(); + } + + expect(getPollDelays(stubs.setTimeout)).toEqual([2000, 3000, 4500, 6750, 10000, 10000]); + }); + + test('should double the pending poll interval when the backoff has no factor', () => { + repStatus.backoff = { maxIntervalMs: 30000, maxWaitMs: 600000 }; + repStatus.representation.status.state = 'pending'; + + for (let i = 0; i < 6; i += 1) { + repStatus.handleResponse(); + } + + expect(getPollDelays(stubs.setTimeout)).toEqual([2000, 4000, 8000, 16000, 30000, 30000]); + }); + + test('should poll a none status immediately without growing the backoff interval', () => { + repStatus.backoff = { maxIntervalMs: 30000, maxWaitMs: 600000 }; + + repStatus.representation.status.state = 'none'; + repStatus.handleResponse(); + repStatus.representation.status.state = 'pending'; + repStatus.handleResponse(); + + expect(getPollDelays(stubs.setTimeout)).toEqual([0, 2000]); + }); + + test('should stop polling and reject once the next poll would pass the hard limit', () => { + repStatus.backoff = { maxIntervalMs: 30000, maxWaitMs: 60000 }; + repStatus.representation.status.state = 'pending'; + const rejectStub = jest.spyOn(repStatus, 'reject').mockImplementation(); + + repStatus.handleResponse(); + expect(rejectStub).not.toBeCalled(); + + stubs.now.mockReturnValue(58000); + repStatus.handleResponse(); + + expect(getPollDelays(stubs.setTimeout)).toEqual([2000]); + expect(rejectStub).toBeCalledWith( + expect.objectContaining({ code: ERROR_CODE.CONVERSION_TRY_AGAIN_LATER }), + ); + }); + }); + test('should stop a convert time Timer on success converting', () => { repStatus.representation.status.state = STATUS_SUCCESS; const tag = Timer.createTag(fileId, LOAD_METRIC.convertTime); @@ -359,6 +530,17 @@ describe('lib/RepStatus', () => { // Elapsed will not exist if stop isn't called expect(Timer.get(tag).elapsed).toBeDefined(); }); + + test('should not stop a convert time Timer on success when the timer is disabled', () => { + repStatus.enableConvertTimer = false; + repStatus.representation.status.state = STATUS_SUCCESS; + const tag = Timer.createTag(fileId, LOAD_METRIC.convertTime); + Timer.start(tag); + repStatus.handleResponse(); + + // Elapsed will exist only if stop is called + expect(Timer.get(tag).elapsed).toBeUndefined(); + }); }); describe('getPromise()', () => { diff --git a/src/lib/viewers/BaseViewer.js b/src/lib/viewers/BaseViewer.js index a6b80ebb8..4062018af 100644 --- a/src/lib/viewers/BaseViewer.js +++ b/src/lib/viewers/BaseViewer.js @@ -951,9 +951,11 @@ class BaseViewer extends EventEmitter { * Instantiates and returns RepStatus * * @param {Object} [representation] - Optional representation + * @param {Object} [options] - Optional RepStatus options + * @param {Object} [options.backoff] - Poll backoff, see RepStatus * @return {RepStatus} Instance of RepStatus */ - getRepStatus(representation) { + getRepStatus(representation, { backoff } = {}) { const { token, sharedLink, sharedLinkPassword, logger, file } = this.options; const repStatus = new RepStatus({ api: this.api, @@ -963,6 +965,8 @@ class BaseViewer extends EventEmitter { sharedLinkPassword, fileId: file.id, logger: representation ? null : logger, // Do not log to main preview status if rep is passed in + enableConvertTimer: !representation || representation === this.options.representation, + backoff, }); // Don't time out while conversion is pending diff --git a/src/lib/viewers/__tests__/BaseViewer-test.js b/src/lib/viewers/__tests__/BaseViewer-test.js index 4a3bafc04..bb132a379 100644 --- a/src/lib/viewers/__tests__/BaseViewer-test.js +++ b/src/lib/viewers/__tests__/BaseViewer-test.js @@ -1116,6 +1116,32 @@ describe('lib/viewers/BaseViewer', () => { expect(repStatus.representation).toBe(representation); }); + test('should enable the convert timer for the main representation', () => { + const repStatus = base.getRepStatus(); + expect(repStatus.enableConvertTimer).toBe(true); + }); + + test('should disable the convert timer for a passed in secondary representation', () => { + const repStatus = base.getRepStatus({ info: { url: 'someOtherUrl' } }); + expect(repStatus.enableConvertTimer).toBe(false); + }); + + test('should enable the convert timer when the main representation is passed in', () => { + const repStatus = base.getRepStatus(base.options.representation); + expect(repStatus.enableConvertTimer).toBe(true); + }); + + test('should poll without a backoff by default', () => { + const repStatus = base.getRepStatus({ info: { url: 'someOtherUrl' } }); + expect(repStatus.backoff).toBeNull(); + }); + + test('should pass the poll backoff through to the rep status', () => { + const backoff = { maxIntervalMs: 30000, maxWaitMs: 600000 }; + const repStatus = base.getRepStatus({ info: { url: 'someOtherUrl' } }, { backoff }); + expect(repStatus.backoff).toBe(backoff); + }); + test('should emit conversionpending once when the main representation is pending', () => { jest.spyOn(base, 'emit'); const repStatus = base.getRepStatus(); diff --git a/src/lib/viewers/doc/DocBaseViewer.js b/src/lib/viewers/doc/DocBaseViewer.js index f6fa225a8..33d4c4038 100644 --- a/src/lib/viewers/doc/DocBaseViewer.js +++ b/src/lib/viewers/doc/DocBaseViewer.js @@ -10,6 +10,7 @@ import DocFindBar from './DocFindBar'; import { DocFindBarV2Root } from './DocFindBarV2'; import GalleryController from '../gallery/GalleryController'; import { GALLERY_MAX_SCALE, GALLERY_MIN_SCALE } from '../gallery/constants'; +import getOcrFallbackRepresentation from './getOcrFallbackRepresentation'; import { isNpmBuild } from '../../isNpmBuild'; import limitMarkedContentNesting from './limitMarkedContentNesting'; import PageTracker from '../../PageTracker'; @@ -37,12 +38,11 @@ import { CLASS_IS_SCROLLABLE, DISCOVERABILITY_ATTRIBUTE, DOCUMENT_FTUX_CURSOR_SEEN_KEY, - ORIGINAL_REP_NAME, PERMISSION_DOWNLOAD, PRELOAD_REP_NAME, PRELOAD_PAGED_REP_NAME, - STATUS_ERROR, - STATUS_SUCCESS, + STATUS_NONE, + STATUS_PENDING, } from '../../constants'; import { createAssetUrlCreator, @@ -123,6 +123,7 @@ const MAX_OPERATIONS = 320000; // Block PDFs with more than 320,000 drawing oper const MAX_OPERATION_PAGES = 5; // Check only the first 5 pages const MAX_OPERATIONS_ERROR_MESSAGE = 'Too many drawing operations'; const EXTENSIONS_WITH_OPERATION_LIMIT = ['dwg', 'numbers', 'xlsx']; +const OCR_PDF_POLL_BACKOFF = { factor: 1.5, maxIntervalMs: 10000, maxWaitMs: 10 * 60 * 1000 }; /** Resolves true when the first maxPages pages exceed operationLimit drawing operations. */ export function checkPdfOperationLimit(doc, maxPages = MAX_OPERATION_PAGES, operationLimit = MAX_OPERATIONS) { @@ -349,6 +350,15 @@ class DocBaseViewer extends BaseViewer { } } + if (this.ocrSwapLoadingTask) { + try { + this.ocrSwapLoadingTask.destroy(); + } catch (e) { + // Ignore these errors + } + this.ocrSwapLoadingTask = null; + } + // Clean up and detach the PDF.js document so retained viewer instances // do not keep page views and document resources alive. if (this.pdfViewer) { @@ -805,19 +815,177 @@ class DocBaseViewer extends BaseViewer { return null; } - const pdfRep = getRepresentation(file, 'pdf'); - if (pdfRep && RepStatus.getStatus(pdfRep) === STATUS_SUCCESS) { - return pdfRep; + return getOcrFallbackRepresentation(file); + } + + /** + * Warms the on-demand 'ocr_pdf' rep in the background and swaps it in once it is ready. + * + * @return {void} + */ + requestOcrPdfConversion() { + if (this.isDestroyed() || getProp(this.options, 'viewer.REP') !== 'ocr_pdf') { + return; } - // pdf.js can only render the original bytes directly when the file itself is a PDF. For other - // document types the original is e.g. a raw .docx, so keep awaiting the on-demand 'pdf' conversion - // (unless it has already errored) rather than handing an unrenderable original to pdf.js. - if (file.extension === 'pdf') { - return getRepresentation(file, ORIGINAL_REP_NAME); + const { file, representation } = this.options; + if (representation && representation.representation === 'ocr_pdf') { + return; + } + + if (!file || !file.representations) { + return; + } + + const ocrPdfRep = getRepresentation(file, 'ocr_pdf'); + if (!ocrPdfRep) { + return; + } + + const status = RepStatus.getStatus(ocrPdfRep); + if (status !== STATUS_NONE && status !== STATUS_PENDING) { + return; } - return pdfRep && RepStatus.getStatus(pdfRep) !== STATUS_ERROR ? pdfRep : null; + const ocrPdfRepStatus = this.getRepStatus(ocrPdfRep, { backoff: OCR_PDF_POLL_BACKOFF }); + ocrPdfRepStatus.removeListener('conversionpending', this.resetLoadTimeout); + ocrPdfRepStatus + .getPromise() + .then(() => this.swapToOcrPdf(ocrPdfRep)) + .catch(err => { + if (!this.isDestroyed()) { + console.warn('ocr_pdf conversion did not complete, keeping the fallback representation', err); // eslint-disable-line no-console + } + }); + } + + /** + * Swaps the live pdf.js document for the 'ocr_pdf' rep in place, preserving page, zoom and rotation. + * + * @param {Object} ocrPdfRep - The ready 'ocr_pdf' representation + * @return {void} + */ + swapToOcrPdf(ocrPdfRep) { + if (this.isDestroyed() || !this.pdfViewer || !this.pdfEventBus) { + return; + } + + const { file, representation } = this.options; + if (!representation || representation.representation === 'ocr_pdf') { + return; + } + + const pdfUrl = this.createContentUrlV2(ocrPdfRep.content.url_template); + + const swapLoadingTask = this.pdfjsLib.getDocument(this.getPdfDocConfig(pdfUrl)); + this.ocrSwapLoadingTask = swapLoadingTask; + + swapLoadingTask.promise + .then(doc => doc.getPage(1).then(() => doc)) + .then(doc => { + if (EXTENSIONS_WITH_OPERATION_LIMIT.includes(file.extension)) { + return checkPdfOperationLimit(doc).then(hasTooManyOperations => { + if (hasTooManyOperations) { + throw new Error(MAX_OPERATIONS_ERROR_MESSAGE); + } + return doc; + }); + } + return doc; + }) + .then(doc => { + if (this.isDestroyed()) { + swapLoadingTask.destroy(); + return; + } + + limitMarkedContentNesting(doc); + + const fallbackState = { + doc: this.doc, + pdfLoadingTask: this.pdfLoadingTask, + pdfUrl: this.pdfUrl, + representation: this.options.representation, + }; + + this.pendingSwapViewState = { + page: this.pdfViewer.currentPageNumber, + scale: this.pdfViewer.currentScaleValue, + rotation: this.rotationAngle, + location: this.pdfViewer._location, + }; + + try { + this.options.representation = ocrPdfRep; + this.pdfUrl = pdfUrl; + this.pdfLoadingTask = swapLoadingTask; + this.pdfLinkService.setDocument(doc, pdfUrl); + this.pdfViewer.setDocument(doc); + } catch (err) { + this.restoreFallbackDocument(fallbackState); + throw err; + } + + this.doc = doc; + + if (fallbackState.pdfLoadingTask) { + try { + fallbackState.pdfLoadingTask.destroy(); + } catch (e) { + // Ignore these errors + } + } + }) + .catch(err => { + swapLoadingTask.destroy(); + if (!this.isDestroyed()) { + console.warn('ocr_pdf failed to load, keeping the fallback representation', err); // eslint-disable-line no-console + } + }) + .finally(() => { + this.ocrSwapLoadingTask = null; + }); + } + + /** + * Puts the fallback document back after attaching the 'ocr_pdf' document failed part way. Keeps the + * captured view state so the re-attached fallback opens where the user was. + * + * @param {Object} fallbackState - The document, loading task, url and representation before the swap + * @return {void} + */ + restoreFallbackDocument({ doc, pdfLoadingTask, pdfUrl, representation }) { + this.options.representation = representation; + this.pdfUrl = pdfUrl; + this.pdfLoadingTask = pdfLoadingTask; + + try { + this.pdfLinkService.setDocument(doc, pdfUrl); + this.pdfViewer.setDocument(doc); + } catch (e) { + this.pendingSwapViewState = null; + } + } + + /** + * Restores the view captured before the 'ocr_pdf' swap once pdf.js has re-initialized the pages. + * + * @param {Object} viewState - The page, scale, rotation and pdf.js location captured before the swap + * @return {void} + */ + restoreSwapViewState({ page, scale, rotation, location }) { + this.rotationAngle = rotation; + this.pdfViewer.pagesRotation = rotation; + this.pdfViewer.currentScaleValue = scale; + this.setPage(page); + if (location) { + this.pdfViewer.scrollPageIntoView({ + pageNumber: location.pageNumber, + destArray: [null, { name: 'XYZ' }, location.left, location.top, null], + allowNegativeOffset: true, + }); + } + this.setupPageIds(); } handleFindBarClose() { @@ -1192,54 +1360,9 @@ class DocBaseViewer extends BaseViewer { this.pdfViewer = this.initPdfViewer(); this.pdfLinkService.setViewer(this.pdfViewer); - const { file, location } = this.options; - const { size, watermark_info: watermarkInfo } = file; - const assetUrlCreator = createAssetUrlCreator(location); - - // Do not disable create object URL in IE11 or iOS Chrome - pdf.js issues #3977 and #8081 are - // not applicable to Box's use case and disabling causes performance issues - const disableCreateObjectURL = false; - - // Disable font faces on IOS 10.3.X - const disableFontFace = Browser.hasFontIssue() || this.getViewerOption('disableFontFace'); - - // Disable range requests for files smaller than minimum range request size - const isRangeSupported = size >= (this.getViewerOption('rangeMinSize') || RANGE_REQUEST_MINIMUM_SIZE); - const isWatermarked = watermarkInfo && watermarkInfo.is_watermarked; - const disableRange = isWatermarked || !isRangeSupported; - - // Use larger chunk sizes because we assume that en-US users have better connections to Box's servers - const rangeChunkSizeDefault = location.locale === 'en-US' ? RANGE_CHUNK_SIZE_US : RANGE_CHUNK_SIZE_NON_US; - const rangeChunkSize = this.getViewerOption('rangeChunkSize') || rangeChunkSizeDefault; - - // Disable streaming by default unless it is explicitly enabled via options - const disableStream = this.getViewerOption('disableStream') !== false; - - // Load PDF from representation URL and set as document for pdf.js. Cache task for destruction - const useNpmPdfjs = this.featureEnabled('useNpmPdfjs'); - const cMapUrl = useNpmPdfjs ? assetUrlCreator('cmaps/') : assetUrlCreator(CMAP); - const pdfDocConfig = { - cMapPacked: true, - cMapUrl, - disableCreateObjectURL, - disableFontFace, - disableRange, - disableStream, - rangeChunkSize, - url: pdfUrl, - }; - - if (useNpmPdfjs) { - pdfDocConfig.iccUrl = assetUrlCreator('iccs/'); - pdfDocConfig.standardFontDataUrl = assetUrlCreator('standard_fonts/'); - pdfDocConfig.wasmUrl = assetUrlCreator('wasm/'); - } else { - pdfDocConfig.isEvalSupported = false; - } - - pdfDocConfig.httpHeaders = this.appendAuthHeader(); + const { file } = this.options; - this.pdfLoadingTask = this.pdfjsLib.getDocument(pdfDocConfig); + this.pdfLoadingTask = this.pdfjsLib.getDocument(this.getPdfDocConfig(pdfUrl)); if (this.pageTracker) { this.addListener('preview_event_report', this.handlePreviewEventReport); @@ -1319,6 +1442,63 @@ class DocBaseViewer extends BaseViewer { }); } + /** + * Builds the pdf.js getDocument config for a representation content url. + * + * @protected + * @param {string} pdfUrl - content url of the representation to load + * @return {Object} pdf.js document config + */ + getPdfDocConfig(pdfUrl) { + const { file, location } = this.options; + const { size, watermark_info: watermarkInfo } = file; + const assetUrlCreator = createAssetUrlCreator(location); + + // Do not disable create object URL in IE11 or iOS Chrome - pdf.js issues #3977 and #8081 are + // not applicable to Box's use case and disabling causes performance issues + const disableCreateObjectURL = false; + + // Disable font faces on IOS 10.3.X + const disableFontFace = Browser.hasFontIssue() || this.getViewerOption('disableFontFace'); + + // Disable range requests for files smaller than minimum range request size + const isRangeSupported = size >= (this.getViewerOption('rangeMinSize') || RANGE_REQUEST_MINIMUM_SIZE); + const isWatermarked = watermarkInfo && watermarkInfo.is_watermarked; + const disableRange = isWatermarked || !isRangeSupported; + + // Use larger chunk sizes because we assume that en-US users have better connections to Box's servers + const rangeChunkSizeDefault = location.locale === 'en-US' ? RANGE_CHUNK_SIZE_US : RANGE_CHUNK_SIZE_NON_US; + const rangeChunkSize = this.getViewerOption('rangeChunkSize') || rangeChunkSizeDefault; + + // Disable streaming by default unless it is explicitly enabled via options + const disableStream = this.getViewerOption('disableStream') !== false; + + const useNpmPdfjs = this.featureEnabled('useNpmPdfjs'); + const cMapUrl = useNpmPdfjs ? assetUrlCreator('cmaps/') : assetUrlCreator(CMAP); + const pdfDocConfig = { + cMapPacked: true, + cMapUrl, + disableCreateObjectURL, + disableFontFace, + disableRange, + disableStream, + rangeChunkSize, + url: pdfUrl, + }; + + if (useNpmPdfjs) { + pdfDocConfig.iccUrl = assetUrlCreator('iccs/'); + pdfDocConfig.standardFontDataUrl = assetUrlCreator('standard_fonts/'); + pdfDocConfig.wasmUrl = assetUrlCreator('wasm/'); + } else { + pdfDocConfig.isEvalSupported = false; + } + + pdfDocConfig.httpHeaders = this.appendAuthHeader(); + + return pdfDocConfig; + } + /** * Initialize the pdf.js viewer. * @@ -1667,6 +1847,11 @@ class DocBaseViewer extends BaseViewer { * @return {void} */ loadUI() { + if (this.controls) { + this.renderUI(); + return; + } + this.controls = new ControlsRoot({ containerEl: this.containerEl, fileExtension: this.options.file.extension, @@ -1810,6 +1995,13 @@ class DocBaseViewer extends BaseViewer { * @return {void} */ pagesinitHandler() { + if (this.pendingSwapViewState) { + const viewState = this.pendingSwapViewState; + this.pendingSwapViewState = null; + this.restoreSwapViewState(viewState); + return; + } + this.pdfViewer.currentScaleValue = 'auto'; this.loadUI(); @@ -1841,6 +2033,8 @@ class DocBaseViewer extends BaseViewer { // Add page IDs to each page after page structure is available this.setupPageIds(); + + this.requestOcrPdfConversion(); } } diff --git a/src/lib/viewers/doc/DocLoader.js b/src/lib/viewers/doc/DocLoader.js index 6513ad01b..0dd95f37a 100644 --- a/src/lib/viewers/doc/DocLoader.js +++ b/src/lib/viewers/doc/DocLoader.js @@ -5,9 +5,15 @@ import DocumentViewer from './DocumentViewer'; import PresentationViewer from './PresentationViewer'; import SinglePageViewer from './SinglePageViewer'; import RepStatus from '../../RepStatus'; -import { ORIGINAL_REP_NAME, STATUS_ERROR, STATUS_SUCCESS } from '../../constants'; +import getOcrFallbackRepresentation from './getOcrFallbackRepresentation'; +import { ORIGINAL_REP_NAME, STATUS_ERROR, STATUS_SUCCESS, STATUS_VIEWABLE } from '../../constants'; import { DOCUMENT_EXTENSIONS } from '../../extensions'; +const isRepReady = rep => { + const status = RepStatus.getStatus(rep); + return status === STATUS_SUCCESS || status === STATUS_VIEWABLE; +}; + // Order of the viewers matters. For example, a PDF file can be previewed by using the preferred optimized 'pdf' rep // or the original as a fallback. Additionally, we include multiple entries for the presentation viewer so that it can be // used by other docoument types if the document viewer is disabled. @@ -94,26 +100,16 @@ class DocLoader extends AssetLoader { */ determineRepresentation(file, viewer) { let rep = super.determineRepresentation(file, viewer); - let status = RepStatus.getStatus(rep); - if (rep.representation === 'ocr_pdf' && status === STATUS_ERROR) { - rep = getRepresentation(file, 'pdf') || rep; - status = RepStatus.getStatus(rep); + if (rep.representation === 'ocr_pdf' && !isRepReady(rep)) { + rep = getOcrFallbackRepresentation(file) || rep; } - // The searchable 'ocr_pdf' rep is generated on demand: requesting its info url is what kicks - // off the conversion, and RepStatus polls none/pending until it is ready. Keep it while it is - // still converting so that polling can trigger and await the conversion, rather than falling - // straight through to the non-searchable original below. Once it has errored, the block above - // has already tried 'pdf', so we allow the original fallback as usual. - const isOcrPdfConverting = rep.representation === 'ocr_pdf' && status !== STATUS_ERROR; + if (rep.representation === 'ocr_pdf' && RepStatus.getStatus(rep) === STATUS_ERROR) { + rep = getRepresentation(file, 'pdf') || rep; + } - if ( - file.extension === 'pdf' && - rep.representation !== ORIGINAL_REP_NAME && - status !== STATUS_SUCCESS && - !isOcrPdfConverting - ) { + if (file.extension === 'pdf' && rep.representation !== ORIGINAL_REP_NAME && !isRepReady(rep)) { rep = getRepresentation(file, ORIGINAL_REP_NAME) || rep; } diff --git a/src/lib/viewers/doc/__tests__/DocBaseViewer-test.js b/src/lib/viewers/doc/__tests__/DocBaseViewer-test.js index 56ca5f9bf..5326e2dd4 100644 --- a/src/lib/viewers/doc/__tests__/DocBaseViewer-test.js +++ b/src/lib/viewers/doc/__tests__/DocBaseViewer-test.js @@ -452,6 +452,18 @@ describe('src/lib/viewers/doc/DocBaseViewer', () => { expect(docBase.pdfLoadingTask.destroy).toBeCalled(); }); + test('should cancel a pending ocr_pdf swap loading task', () => { + docBase.ocrSwapLoadingTask = { + destroy: jest.fn(), + }; + const { ocrSwapLoadingTask } = docBase; + + docBase.destroy(); + + expect(ocrSwapLoadingTask.destroy).toBeCalled(); + expect(docBase.ocrSwapLoadingTask).toBeNull(); + }); + test('should clean up the viewer', () => { docBase.pdfViewer = { cleanup: jest.fn(), @@ -1331,7 +1343,10 @@ describe('src/lib/viewers/doc/DocBaseViewer', () => { test('should fall back to the original rep when no pdf rep exists', () => { const originalRep = { representation: 'ORIGINAL', status: { state: 'success' } }; docBase.options.representation = { representation: 'ocr_pdf' }; - docBase.options.file = makeFile([{ representation: 'ocr_pdf', status: { state: 'none' } }, originalRep]); + docBase.options.file = makeFile([ + { representation: 'ocr_pdf', status: { state: 'none' } }, + originalRep, + ]); expect(docBase.getRepFallback()).toBe(originalRep); }); @@ -1462,6 +1477,509 @@ describe('src/lib/viewers/doc/DocBaseViewer', () => { }); }); + describe('requestOcrPdfConversion()', () => { + const flush = () => + new Promise(resolve => { + setTimeout(resolve, 0); + }); + const makeFile = entries => ({ id: '0', extension: 'docx', representations: { entries } }); + + beforeEach(() => { + docBase.options.representation = { representation: 'pdf' }; + docBase.options.viewer = { NAME: 'Document', REP: 'ocr_pdf' }; + stubs.consoleWarn = jest.spyOn(console, 'warn').mockImplementation(); + }); + + test('should do nothing when destroyed', () => { + jest.spyOn(docBase, 'isDestroyed').mockReturnValue(true); + const getRepStatusStub = jest.spyOn(docBase, 'getRepStatus'); + + docBase.requestOcrPdfConversion(); + + expect(getRepStatusStub).not.toBeCalled(); + }); + + test.each([ + ['Presentation', 'pdf'], + ['AutoCAD', 'pdf'], + ['SinglePage', 'pdf'], + ['Document', 'pdf'], + ])('should do nothing for a viewer that was not chosen for ocr_pdf (%s, %s)', (NAME, REP) => { + docBase.options.viewer = { NAME, REP }; + docBase.options.file = makeFile([{ representation: 'ocr_pdf', status: { state: 'none' } }]); + const getRepStatusStub = jest.spyOn(docBase, 'getRepStatus'); + + docBase.requestOcrPdfConversion(); + + expect(getRepStatusStub).not.toBeCalled(); + }); + + test('should do nothing when the current representation is ocr_pdf', () => { + docBase.options.representation = { representation: 'ocr_pdf' }; + docBase.options.file = makeFile([{ representation: 'ocr_pdf', status: { state: 'none' } }]); + const getRepStatusStub = jest.spyOn(docBase, 'getRepStatus'); + + docBase.requestOcrPdfConversion(); + + expect(getRepStatusStub).not.toBeCalled(); + }); + + test('should do nothing when the file has no ocr_pdf rep', () => { + docBase.options.file = makeFile([{ representation: 'pdf', status: { state: 'success' } }]); + const getRepStatusStub = jest.spyOn(docBase, 'getRepStatus'); + + docBase.requestOcrPdfConversion(); + + expect(getRepStatusStub).not.toBeCalled(); + }); + + test.each(['success', 'viewable', 'error'])( + 'should do nothing when the ocr_pdf rep is already resolved (%s)', + state => { + docBase.options.file = makeFile([{ representation: 'ocr_pdf', status: { state } }]); + const getRepStatusStub = jest.spyOn(docBase, 'getRepStatus'); + + docBase.requestOcrPdfConversion(); + + expect(getRepStatusStub).not.toBeCalled(); + }, + ); + + test.each(['none', 'pending'])( + 'should warm the ocr_pdf rep and swap it in once ready (%s)', + async state => { + const ocrPdfRep = { representation: 'ocr_pdf', status: { state } }; + docBase.options.file = makeFile([ocrPdfRep]); + const repStatus = { + getPromise: jest.fn().mockResolvedValue(), + removeListener: jest.fn(), + }; + jest.spyOn(docBase, 'getRepStatus').mockReturnValue(repStatus); + const swapStub = jest.spyOn(docBase, 'swapToOcrPdf').mockImplementation(); + + docBase.requestOcrPdfConversion(); + await flush(); + + expect(docBase.getRepStatus).toBeCalledWith(ocrPdfRep, { + backoff: { factor: 1.5, maxIntervalMs: 10000, maxWaitMs: 600000 }, + }); + expect(repStatus.removeListener).toBeCalledWith('conversionpending', docBase.resetLoadTimeout); + expect(swapStub).toBeCalledWith(ocrPdfRep); + }, + ); + + test('should not swap when the conversion fails', async () => { + const ocrPdfRep = { representation: 'ocr_pdf', status: { state: 'pending' } }; + docBase.options.file = makeFile([ocrPdfRep]); + const repStatus = { + getPromise: jest.fn().mockRejectedValue(new Error('conversion failed')), + removeListener: jest.fn(), + }; + jest.spyOn(docBase, 'getRepStatus').mockReturnValue(repStatus); + const swapStub = jest.spyOn(docBase, 'swapToOcrPdf').mockImplementation(); + + docBase.requestOcrPdfConversion(); + await flush(); + + expect(swapStub).not.toBeCalled(); + expect(stubs.consoleWarn).toBeCalledWith(expect.stringContaining('ocr_pdf'), expect.any(Error)); + }); + + test('should not warn when the conversion fails after the viewer is destroyed', async () => { + docBase.options.file = makeFile([{ representation: 'ocr_pdf', status: { state: 'pending' } }]); + let rejectConversion; + const repStatus = { + getPromise: jest.fn( + () => + new Promise((resolve, reject) => { + rejectConversion = reject; + }), + ), + removeListener: jest.fn(), + }; + jest.spyOn(docBase, 'getRepStatus').mockReturnValue(repStatus); + + docBase.requestOcrPdfConversion(); + jest.spyOn(docBase, 'isDestroyed').mockReturnValue(true); + rejectConversion(new Error('conversion failed')); + await flush(); + + expect(stubs.consoleWarn).not.toBeCalled(); + }); + }); + + describe('swapToOcrPdf()', () => { + const flush = () => + new Promise(resolve => { + setTimeout(resolve, 0); + }); + let ocrPdfRep; + let swapLoadingTask; + let resolveDoc; + let rejectDoc; + + beforeEach(() => { + ocrPdfRep = { representation: 'ocr_pdf', content: { url_template: 'ocr-template' } }; + docBase.options.representation = { representation: 'pdf' }; + docBase.rotationAngle = 90; + docBase.pdfEventBus = { off: jest.fn(), on: jest.fn() }; + docBase.pdfViewer = { + currentPageNumber: 3, + currentScaleValue: '1.5', + scrollPageIntoView: jest.fn(), + setDocument: jest.fn(), + }; + docBase.pdfLinkService = { setDocument: jest.fn() }; + docBase.pdfUrl = 'previous-url'; + docBase.pdfLoadingTask = { destroy: jest.fn() }; + swapLoadingTask = { + destroy: jest.fn(), + promise: new Promise((resolve, reject) => { + resolveDoc = resolve; + rejectDoc = reject; + }), + }; + docBase.pdfjsLib = { getDocument: jest.fn(() => swapLoadingTask) }; + jest.spyOn(docBase, 'createContentUrlV2').mockReturnValue('ocr-url'); + jest.spyOn(docBase, 'getPdfDocConfig').mockReturnValue({ url: 'ocr-url' }); + jest.spyOn(docBase, 'setPage').mockImplementation(); + jest.spyOn(docBase, 'setupPageIds').mockImplementation(); + stubs.consoleWarn = jest.spyOn(console, 'warn').mockImplementation(); + }); + + test('should do nothing when there is no pdfViewer', () => { + docBase.pdfViewer = null; + + docBase.swapToOcrPdf(ocrPdfRep); + + expect(docBase.pdfjsLib.getDocument).not.toBeCalled(); + }); + + test('should do nothing when the current representation is already ocr_pdf', () => { + docBase.options.representation = { representation: 'ocr_pdf' }; + + docBase.swapToOcrPdf(ocrPdfRep); + + expect(docBase.pdfjsLib.getDocument).not.toBeCalled(); + }); + + test('should attach the ocr_pdf document to the live viewer', async () => { + const doc = { getPage: jest.fn().mockResolvedValue({}) }; + + docBase.swapToOcrPdf(ocrPdfRep); + resolveDoc(doc); + await flush(); + + expect(docBase.options.representation).toBe(ocrPdfRep); + expect(docBase.pdfUrl).toBe('ocr-url'); + expect(docBase.pdfLinkService.setDocument).toBeCalledWith(doc, 'ocr-url'); + expect(docBase.pdfViewer.setDocument).toBeCalledWith(doc); + expect(docBase.doc).toBe(doc); + expect(docBase.pdfLoadingTask).toBe(swapLoadingTask); + expect(docBase.pendingSwapViewState).toEqual({ + page: 3, + scale: '1.5', + rotation: 90, + location: undefined, + }); + }); + + test('should destroy the previous loading task after the swap', async () => { + const doc = { getPage: jest.fn().mockResolvedValue({}) }; + const previousTask = docBase.pdfLoadingTask; + + docBase.swapToOcrPdf(ocrPdfRep); + resolveDoc(doc); + await flush(); + + expect(previousTask.destroy).toBeCalled(); + }); + + test('should restore page, scale and rotation when pages re-init', async () => { + const doc = { getPage: jest.fn().mockResolvedValue({}) }; + + docBase.swapToOcrPdf(ocrPdfRep); + resolveDoc(doc); + await flush(); + + // pdf.js resets scale on pagesinit; the restore handler puts it back + docBase.pdfViewer.currentScaleValue = 'auto'; + docBase.rotationAngle = 0; + docBase.pagesinitHandler(); + + expect(docBase.pendingSwapViewState).toBeNull(); + expect(docBase.rotationAngle).toBe(90); + expect(docBase.pdfViewer.pagesRotation).toBe(90); + expect(docBase.pdfViewer.currentScaleValue).toBe('1.5'); + expect(docBase.setPage).toBeCalledWith(3); + expect(docBase.setupPageIds).toBeCalled(); + }); + + test('should not re-run the first-load page setup when the swapped pages re-init', async () => { + const loadUIStub = jest.spyOn(docBase, 'loadUI').mockImplementation(); + const requestOcrPdfConversionStub = jest.spyOn(docBase, 'requestOcrPdfConversion').mockImplementation(); + const emitStub = jest.spyOn(docBase, 'emit').mockImplementation(); + docBase.loaded = true; + docBase.startPageNum = 1; + + docBase.swapToOcrPdf(ocrPdfRep); + resolveDoc({ getPage: jest.fn().mockResolvedValue({}) }); + await flush(); + + docBase.pagesinitHandler(); + + expect(loadUIStub).not.toBeCalled(); + expect(requestOcrPdfConversionStub).not.toBeCalled(); + expect(emitStub).not.toBeCalled(); + expect(docBase.setPage).toBeCalledTimes(1); + expect(docBase.setPage).toBeCalledWith(3); + }); + + test('should run the regular page setup on a pagesinit after the swap has been restored', async () => { + const loadUIStub = jest.spyOn(docBase, 'loadUI').mockImplementation(); + docBase.loaded = true; + + docBase.swapToOcrPdf(ocrPdfRep); + resolveDoc({ getPage: jest.fn().mockResolvedValue({}) }); + await flush(); + + docBase.pagesinitHandler(); + expect(loadUIStub).not.toBeCalled(); + + docBase.pagesinitHandler(); + expect(loadUIStub).toBeCalledTimes(1); + }); + + test('should restore the exact scroll offset within the page when pages re-init', async () => { + docBase.pdfViewer._location = { pageNumber: 2, left: 12.5, top: 640.25 }; + + docBase.swapToOcrPdf(ocrPdfRep); + resolveDoc({ getPage: jest.fn().mockResolvedValue({}) }); + await flush(); + + docBase.pdfViewer._location = { pageNumber: 1, left: 0, top: 792 }; + docBase.pagesinitHandler(); + + expect(docBase.setPage).toBeCalledWith(3); + expect(docBase.pdfViewer.scrollPageIntoView).toBeCalledWith({ + pageNumber: 2, + destArray: [null, { name: 'XYZ' }, 12.5, 640.25, null], + allowNegativeOffset: true, + }); + expect(docBase.setPage.mock.invocationCallOrder[0]).toBeLessThan( + docBase.pdfViewer.scrollPageIntoView.mock.invocationCallOrder[0], + ); + }); + + test('should only restore the page when pdf.js has no scroll location yet', async () => { + docBase.swapToOcrPdf(ocrPdfRep); + resolveDoc({ getPage: jest.fn().mockResolvedValue({}) }); + await flush(); + + docBase.pagesinitHandler(); + + expect(docBase.setPage).toBeCalledWith(3); + expect(docBase.pdfViewer.scrollPageIntoView).not.toBeCalled(); + }); + + test('should revert to the previous representation when the swap fails', async () => { + const previousRep = docBase.options.representation; + const previousTask = docBase.pdfLoadingTask; + + docBase.swapToOcrPdf(ocrPdfRep); + rejectDoc(new Error('load failed')); + await flush(); + + expect(docBase.options.representation).toBe(previousRep); + expect(docBase.pdfUrl).toBe('previous-url'); + expect(docBase.pdfLoadingTask).toBe(previousTask); + expect(swapLoadingTask.destroy).toBeCalled(); + expect(docBase.pdfViewer.setDocument).not.toBeCalled(); + expect(stubs.consoleWarn).toBeCalledWith(expect.stringContaining('ocr_pdf'), expect.any(Error)); + }); + + test('should keep the fallback when the first ocr_pdf page fails to load', async () => { + const previousRep = docBase.options.representation; + const previousTask = docBase.pdfLoadingTask; + const doc = { getPage: jest.fn().mockRejectedValue(new Error('page failed')) }; + + docBase.swapToOcrPdf(ocrPdfRep); + resolveDoc(doc); + await flush(); + + expect(doc.getPage).toBeCalledWith(1); + expect(docBase.pdfViewer.setDocument).not.toBeCalled(); + expect(docBase.pdfLinkService.setDocument).not.toBeCalled(); + expect(docBase.options.representation).toBe(previousRep); + expect(docBase.pdfUrl).toBe('previous-url'); + expect(docBase.pdfLoadingTask).toBe(previousTask); + expect(previousTask.destroy).not.toBeCalled(); + expect(swapLoadingTask.destroy).toBeCalled(); + expect(stubs.consoleWarn).toBeCalledWith(expect.stringContaining('ocr_pdf'), expect.any(Error)); + }); + + test('should load the first ocr_pdf page before attaching the document', async () => { + const getPage = jest.fn().mockResolvedValue({}); + + docBase.swapToOcrPdf(ocrPdfRep); + resolveDoc({ getPage }); + await flush(); + + expect(getPage).toBeCalledWith(1); + expect(getPage.mock.invocationCallOrder[0]).toBeLessThan( + docBase.pdfViewer.setDocument.mock.invocationCallOrder[0], + ); + }); + + test('should not warn when the swap is cancelled because the viewer was destroyed', async () => { + docBase.swapToOcrPdf(ocrPdfRep); + jest.spyOn(docBase, 'isDestroyed').mockReturnValue(true); + rejectDoc(new Error('Loading aborted')); + await flush(); + + expect(swapLoadingTask.destroy).toBeCalled(); + expect(stubs.consoleWarn).not.toBeCalled(); + }); + + test('should put the fallback document back when attaching the ocr_pdf document throws', async () => { + const fallbackDoc = { getPage: jest.fn().mockResolvedValue({}) }; + const doc = { getPage: jest.fn().mockResolvedValue({}) }; + const previousRep = docBase.options.representation; + const previousTask = docBase.pdfLoadingTask; + docBase.doc = fallbackDoc; + docBase.pdfViewer.setDocument.mockImplementationOnce(() => { + throw new Error('attach failed'); + }); + + docBase.swapToOcrPdf(ocrPdfRep); + resolveDoc(doc); + await flush(); + + expect(docBase.options.representation).toBe(previousRep); + expect(docBase.pdfUrl).toBe('previous-url'); + expect(docBase.pdfLoadingTask).toBe(previousTask); + expect(docBase.doc).toBe(fallbackDoc); + expect(docBase.pdfLinkService.setDocument).toHaveBeenLastCalledWith(fallbackDoc, 'previous-url'); + expect(docBase.pdfViewer.setDocument).toHaveBeenLastCalledWith(fallbackDoc); + expect(docBase.pendingSwapViewState).toEqual(expect.objectContaining({ page: 3, scale: '1.5' })); + expect(previousTask.destroy).not.toBeCalled(); + expect(swapLoadingTask.destroy).toBeCalled(); + expect(docBase.ocrSwapLoadingTask).toBeNull(); + expect(stubs.consoleWarn).toBeCalledWith(expect.stringContaining('ocr_pdf'), expect.any(Error)); + }); + + test('should drop the captured view state when the fallback document cannot be re-attached', async () => { + docBase.doc = { getPage: jest.fn().mockResolvedValue({}) }; + docBase.pdfViewer.setDocument.mockImplementation(() => { + throw new Error('attach failed'); + }); + + docBase.swapToOcrPdf(ocrPdfRep); + resolveDoc({ getPage: jest.fn().mockResolvedValue({}) }); + await flush(); + + expect(docBase.pendingSwapViewState).toBeNull(); + expect(docBase.options.representation).toEqual({ representation: 'pdf' }); + expect(swapLoadingTask.destroy).toBeCalled(); + }); + + test('should discard the loaded document if destroyed mid-load', async () => { + const doc = { getPage: jest.fn().mockResolvedValue({}) }; + + docBase.swapToOcrPdf(ocrPdfRep); + jest.spyOn(docBase, 'isDestroyed').mockReturnValue(true); + resolveDoc(doc); + await flush(); + + expect(swapLoadingTask.destroy).toBeCalled(); + expect(docBase.pdfViewer.setDocument).not.toBeCalled(); + }); + + test('should keep the fallback representation active while the ocr_pdf loads', () => { + const previousRep = docBase.options.representation; + + docBase.swapToOcrPdf(ocrPdfRep); + + expect(docBase.options.representation).toBe(previousRep); + expect(docBase.pdfUrl).toBe('previous-url'); + expect(docBase.ocrSwapLoadingTask).toBe(swapLoadingTask); + }); + + test('should capture the view state when the document attaches, not when the swap starts', async () => { + const doc = { getPage: jest.fn().mockResolvedValue({}) }; + + docBase.swapToOcrPdf(ocrPdfRep); + + docBase.pdfViewer.currentPageNumber = 7; + docBase.pdfViewer.currentScaleValue = '2'; + docBase.rotationAngle = 180; + + resolveDoc(doc); + await flush(); + + docBase.pagesinitHandler(); + + expect(docBase.rotationAngle).toBe(180); + expect(docBase.pdfViewer.pagesRotation).toBe(180); + expect(docBase.pdfViewer.currentScaleValue).toBe('2'); + expect(docBase.setPage).toBeCalledWith(7); + }); + + test('should clear the pending swap task on success', async () => { + docBase.swapToOcrPdf(ocrPdfRep); + resolveDoc({ getPage: jest.fn().mockResolvedValue({}) }); + await flush(); + + expect(docBase.ocrSwapLoadingTask).toBeNull(); + }); + + test('should clear the pending swap task on failure', async () => { + docBase.swapToOcrPdf(ocrPdfRep); + rejectDoc(new Error('load failed')); + await flush(); + + expect(docBase.ocrSwapLoadingTask).toBeNull(); + }); + + test('should keep the fallback and not swap when the ocr_pdf exceeds the operation limit', async () => { + docBase.options.file = { id: '0', extension: 'xlsx' }; + const previousRep = docBase.options.representation; + const doc = { + numPages: 1, + getPage: jest.fn().mockResolvedValue({ + getOperatorList: jest.fn().mockResolvedValue({ fnArray: new Array(320001) }), + }), + }; + + docBase.swapToOcrPdf(ocrPdfRep); + resolveDoc(doc); + await flush(); + + expect(docBase.pdfViewer.setDocument).not.toBeCalled(); + expect(docBase.options.representation).toBe(previousRep); + expect(docBase.pdfUrl).toBe('previous-url'); + expect(swapLoadingTask.destroy).toBeCalled(); + expect(docBase.ocrSwapLoadingTask).toBeNull(); + }); + + test('should swap in an ocr_pdf within the operation limit for a limited extension', async () => { + docBase.options.file = { id: '0', extension: 'xlsx' }; + const doc = { + numPages: 1, + getPage: jest.fn().mockResolvedValue({ + getOperatorList: jest.fn().mockResolvedValue({ fnArray: new Array(10) }), + }), + }; + + docBase.swapToOcrPdf(ocrPdfRep); + resolveDoc(doc); + await flush(); + + expect(docBase.pdfViewer.setDocument).toBeCalledWith(doc); + expect(docBase.options.representation).toBe(ocrPdfRep); + }); + }); + describe('initFind()', () => { beforeEach(() => { docBase.pdfEventBus = { @@ -2965,6 +3483,44 @@ describe('src/lib/viewers/doc/DocBaseViewer', () => { }); }); + describe('getPdfDocConfig()', () => { + beforeEach(() => { + docBase.options.file = { size: 1000000, watermark_info: {} }; + docBase.options.location = { locale: 'en-US' }; + jest.spyOn(docBase, 'getViewerOption').mockImplementation(); + jest.spyOn(docBase, 'appendAuthHeader').mockReturnValue({ Authorization: 'Bearer token' }); + }); + + test('should build a config carrying the url and auth headers', () => { + const config = docBase.getPdfDocConfig('pdf-url'); + + expect(config.url).toBe('pdf-url'); + expect(config.httpHeaders).toEqual({ Authorization: 'Bearer token' }); + }); + + test('should disable range requests for watermarked files', () => { + docBase.options.file.watermark_info = { is_watermarked: true }; + + expect(docBase.getPdfDocConfig('pdf-url').disableRange).toBe(true); + }); + + test('should add npm-specific asset urls when useNpmPdfjs is enabled', () => { + jest.spyOn(docBase, 'featureEnabled').mockImplementation(flag => flag === 'useNpmPdfjs'); + + const config = docBase.getPdfDocConfig('pdf-url'); + + expect(config.wasmUrl).toBeDefined(); + expect(config.standardFontDataUrl).toBeDefined(); + expect(config.isEvalSupported).toBeUndefined(); + }); + + test('should disable eval for the legacy build', () => { + jest.spyOn(docBase, 'featureEnabled').mockReturnValue(false); + + expect(docBase.getPdfDocConfig('pdf-url').isEvalSupported).toBe(false); + }); + }); + describe('resize()', () => { const resizeFunc = BaseViewer.prototype.resize; @@ -3348,6 +3904,21 @@ describe('src/lib/viewers/doc/DocBaseViewer', () => { expect(docBase.renderUI).toBeCalled(); }); + test('should re-render without recreating the controls when already loaded', () => { + jest.spyOn(docBase, 'renderUI').mockImplementation(); + const subscribeSpy = jest.spyOn(docBase.annotationControlsFSM, 'subscribe'); + + docBase.loadUI(); + const { controls } = docBase; + subscribeSpy.mockClear(); + + docBase.loadUI(); + + expect(docBase.controls).toBe(controls); + expect(subscribeSpy).not.toBeCalled(); + expect(docBase.renderUI).toBeCalledTimes(2); + }); + test.each` features | isBlueprintEnabled ${{ blueprintMigrationControlsBar: { enabled: true } }} | ${true} @@ -3869,6 +4440,21 @@ describe('src/lib/viewers/doc/DocBaseViewer', () => { stubs.getCachedPage = jest.spyOn(docBase, 'getCachedPage').mockImplementation(); stubs.emit = jest.spyOn(docBase, 'emit').mockImplementation(); stubs.setupPages = jest.spyOn(docBase, 'setupPageIds').mockImplementation(); + stubs.requestOcrPdfConversion = jest.spyOn(docBase, 'requestOcrPdfConversion').mockImplementation(); + }); + + test('should request the ocr_pdf conversion on first load only', () => { + docBase.pdfViewer = { + currentScale: 'unknown', + pagesCount: 3, + }; + docBase.loaded = false; + + docBase.pagesinitHandler(); + expect(stubs.requestOcrPdfConversion).toBeCalledTimes(1); + + docBase.pagesinitHandler(); + expect(stubs.requestOcrPdfConversion).toBeCalledTimes(1); }); test('should load UI, check the pagination buttons, set the page, and make document scrollable', () => { diff --git a/src/lib/viewers/doc/__tests__/DocLoader-test.js b/src/lib/viewers/doc/__tests__/DocLoader-test.js index de1d71a66..d67754105 100644 --- a/src/lib/viewers/doc/__tests__/DocLoader-test.js +++ b/src/lib/viewers/doc/__tests__/DocLoader-test.js @@ -86,8 +86,28 @@ describe('lib/viewers/doc/DocLoader', () => { expect(determinedRep.representation).toBe('pdf'); }); - test.each(['pending', 'none', 'viewable'])( - 'should keep the ocr_pdf rep when its conversion is still in progress (%s)', + test('should surface the failed pdf rep when both the ocr_pdf and pdf reps have failed', () => { + const pdfRep = { representation: 'pdf', status: { state: 'error', code: 'error_password_protected' } }; + file.representations.entries = [{ representation: 'ocr_pdf', status: { state: 'error' } }, pdfRep]; + viewer.REP = 'ocr_pdf'; + + const determinedRep = DocLoader.determineRepresentation(file, viewer); + expect(determinedRep).toBe(pdfRep); + }); + + test('should keep the converting ocr_pdf rep when the pdf rep has failed', () => { + file.representations.entries = [ + { representation: 'ocr_pdf', status: { state: 'pending' } }, + { representation: 'pdf', status: { state: 'error' } }, + ]; + viewer.REP = 'ocr_pdf'; + + const determinedRep = DocLoader.determineRepresentation(file, viewer); + expect(determinedRep.representation).toBe('ocr_pdf'); + }); + + test.each(['pending', 'none'])( + 'should use the ready pdf rep while the ocr_pdf rep is still converting (%s)', state => { file.representations.entries.unshift({ representation: 'ocr_pdf', @@ -96,10 +116,21 @@ describe('lib/viewers/doc/DocLoader', () => { viewer.REP = 'ocr_pdf'; const determinedRep = DocLoader.determineRepresentation(file, viewer); - expect(determinedRep.representation).toBe('ocr_pdf'); + expect(determinedRep.representation).toBe('pdf'); }, ); + test('should keep the ocr_pdf rep when it is viewable', () => { + file.representations.entries.unshift({ + representation: 'ocr_pdf', + status: { state: 'viewable' }, + }); + viewer.REP = 'ocr_pdf'; + + const determinedRep = DocLoader.determineRepresentation(file, viewer); + expect(determinedRep.representation).toBe('ocr_pdf'); + }); + test('should fall back to the original rep when a born-digital pdf only has a failed ocr_pdf rep', () => { file.extension = 'pdf'; file.representations.entries = [ @@ -114,7 +145,7 @@ describe('lib/viewers/doc/DocLoader', () => { }); test.each(['none', 'pending'])( - 'should keep the ocr_pdf rep for a pdf file while it converts on demand (%s)', + 'should use the original rep for a pdf file while the ocr_pdf rep converts on demand (%s)', state => { file.extension = 'pdf'; file.representations.entries = [ @@ -125,10 +156,24 @@ describe('lib/viewers/doc/DocLoader', () => { viewer.EXT = ['pdf']; const determinedRep = DocLoader.determineRepresentation(file, viewer); - expect(determinedRep.representation).toBe('ocr_pdf'); + expect(determinedRep.representation).toBe('ORIGINAL'); }, ); + test('should use the ready pdf rep for a pdf file while the ocr_pdf rep converts on demand', () => { + file.extension = 'pdf'; + file.representations.entries = [ + { representation: 'ocr_pdf', status: { state: 'pending' } }, + { representation: 'pdf', status: { state: 'success' } }, + { representation: 'ORIGINAL', status: { state: 'success' } }, + ]; + viewer.REP = 'ocr_pdf'; + viewer.EXT = ['pdf']; + + const determinedRep = DocLoader.determineRepresentation(file, viewer); + expect(determinedRep.representation).toBe('pdf'); + }); + test('should fall back from a failed ocr_pdf through pdf to the original rep for pdf files', () => { file.extension = 'pdf'; file.representations.entries = [ diff --git a/src/lib/viewers/doc/__tests__/PresentationViewer-test.js b/src/lib/viewers/doc/__tests__/PresentationViewer-test.js index eea2403a9..6553bfa03 100644 --- a/src/lib/viewers/doc/__tests__/PresentationViewer-test.js +++ b/src/lib/viewers/doc/__tests__/PresentationViewer-test.js @@ -47,6 +47,7 @@ describe('lib/viewers/doc/PresentationViewer', () => { presentation.controls = { add: jest.fn(), + render: jest.fn(), }; createRoot.mockReturnValue({ diff --git a/src/lib/viewers/doc/__tests__/getOcrFallbackRepresentation-test.js b/src/lib/viewers/doc/__tests__/getOcrFallbackRepresentation-test.js new file mode 100644 index 000000000..13cdbe2cb --- /dev/null +++ b/src/lib/viewers/doc/__tests__/getOcrFallbackRepresentation-test.js @@ -0,0 +1,68 @@ +import getOcrFallbackRepresentation from '../getOcrFallbackRepresentation'; + +describe('lib/viewers/doc/getOcrFallbackRepresentation', () => { + const makeFile = (extension, entries) => ({ + extension, + representations: { entries }, + }); + + test('should return the pdf rep when it is successful', () => { + const file = makeFile('docx', [ + { representation: 'pdf', status: { state: 'success' } }, + { representation: 'ORIGINAL', status: { state: 'success' } }, + ]); + + expect(getOcrFallbackRepresentation(file).representation).toBe('pdf'); + }); + + test.each(['pending', 'none'])('should return the converting pdf rep for a non-pdf file (%s)', state => { + const file = makeFile('docx', [{ representation: 'pdf', status: { state } }]); + + expect(getOcrFallbackRepresentation(file).representation).toBe('pdf'); + }); + + test('should return null for a non-pdf file when the pdf rep has failed', () => { + const file = makeFile('docx', [{ representation: 'pdf', status: { state: 'error' } }]); + + expect(getOcrFallbackRepresentation(file)).toBeNull(); + }); + + test('should return null for a non-pdf file that has no pdf rep', () => { + const file = makeFile('docx', [{ representation: 'ORIGINAL', status: { state: 'success' } }]); + + expect(getOcrFallbackRepresentation(file)).toBeNull(); + }); + + test('should prefer the ready pdf rep for a pdf file', () => { + const file = makeFile('pdf', [ + { representation: 'pdf', status: { state: 'success' } }, + { representation: 'ORIGINAL', status: { state: 'success' } }, + ]); + + expect(getOcrFallbackRepresentation(file).representation).toBe('pdf'); + }); + + test('should fall back to the original rep for a pdf file when the pdf rep is not ready', () => { + const file = makeFile('pdf', [ + { representation: 'pdf', status: { state: 'pending' } }, + { representation: 'ORIGINAL', status: { state: 'success' } }, + ]); + + expect(getOcrFallbackRepresentation(file).representation).toBe('ORIGINAL'); + }); + + test('should fall back to the original rep for a pdf file when the pdf rep has failed', () => { + const file = makeFile('pdf', [ + { representation: 'pdf', status: { state: 'error' } }, + { representation: 'ORIGINAL', status: { state: 'success' } }, + ]); + + expect(getOcrFallbackRepresentation(file).representation).toBe('ORIGINAL'); + }); + + test('should return null for a pdf file that only has a failed ocr_pdf rep', () => { + const file = makeFile('pdf', [{ representation: 'ocr_pdf', status: { state: 'error' } }]); + + expect(getOcrFallbackRepresentation(file)).toBeNull(); + }); +}); diff --git a/src/lib/viewers/doc/getOcrFallbackRepresentation.js b/src/lib/viewers/doc/getOcrFallbackRepresentation.js new file mode 100644 index 000000000..1ddd68fdf --- /dev/null +++ b/src/lib/viewers/doc/getOcrFallbackRepresentation.js @@ -0,0 +1,17 @@ +import { getRepresentation } from '../../file'; +import RepStatus from '../../RepStatus'; +import { ORIGINAL_REP_NAME, STATUS_ERROR, STATUS_SUCCESS } from '../../constants'; + +export default function getOcrFallbackRepresentation(file) { + const pdfRep = getRepresentation(file, 'pdf'); + + if (pdfRep && RepStatus.getStatus(pdfRep) === STATUS_SUCCESS) { + return pdfRep; + } + + if (file.extension === 'pdf') { + return getRepresentation(file, ORIGINAL_REP_NAME) || null; + } + + return pdfRep && RepStatus.getStatus(pdfRep) !== STATUS_ERROR ? pdfRep : null; +}