UNPKG

react-native-scanbot-sdk

Version:

Scanbot Document and Barcode Scanner SDK React Native Plugin for Android and iOS

325 lines (310 loc) 9.73 kB
import { NativeModules, Platform } from 'react-native'; import { PartiallyConstructible } from '../utils/utils'; import { BufferImageLoadOptions, EncodeImageOptions, ImageInfo, ImageRefPoolSnapshot, PathImageLoadOptions, SaveImageOptions } from './ImageRefTypes'; const LINKING_ERROR = `The package 'react-native-scanbot-barcode-scanner-sdk' doesn't seem to be linked. Make sure: \n\n` + Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) + '- You rebuilt the app after installing the package\n' + '- You are not using Expo Go\n'; const ScanbotSDKImpl = NativeModules.RNScanbotSDK ? NativeModules.RNScanbotSDK : new Proxy({}, { get() { throw new Error(LINKING_ERROR); } }); class AutoReleasePool { static globalPull = null; static globalPullReferences = 0; poolObjects = []; releaseAll() { for (const obj of this.poolObjects) { if (!obj.isRetained()) { obj.release(); } } } addObject(obj) { this.poolObjects.push(obj); } } export async function autorelease(computation) { if (AutoReleasePool.globalPull === null) { AutoReleasePool.globalPull = new AutoReleasePool(); } AutoReleasePool.globalPullReferences++; const releasePoolRef = () => { AutoReleasePool.globalPullReferences--; if (AutoReleasePool.globalPullReferences === 0) { AutoReleasePool.globalPull.releaseAll(); AutoReleasePool.globalPull = null; } }; try { return await computation(); } finally { releasePoolRef(); } } export class AutoReleasable extends PartiallyConstructible { retained = false; constructor(uniqueId) { super(); if (uniqueId) { if (AutoReleasePool.globalPull === null) { const errorMessage = 'Initializing an object that contains a ScanbotImage instance as REFERENCE must be wrapped inside an autorelease pool. For example:' + '\n autorelease(()=>{' + '\n const barcodeItem = new BarcodeItem(source);' + '\n });'; throw new Error(errorMessage); } AutoReleasePool.globalPull.addObject(this); } } isRetained() { return this.retained; } retain() { this.retained = true; } } export class ImageRef extends AutoReleasable { released = false; get buffer() { return this._buffer; } constructor(uniqueId, buffer) { super(uniqueId); this.uniqueId = uniqueId; this._buffer = buffer; } static From(source) { if (source.buffer) { return new ImageRef(undefined, source.buffer); } else { return ImageRef.deserialize(source); } } static deserialize(serializedRef) { if (!serializedRef.uniqueId) { throw new Error('uniqueId must be present in serializedRef argument'); } // The promise is intentionally not awaited here ScanbotSDKImpl.imageRefDeserialize(serializedRef.uniqueId).catch(error => { console.error(`Error while deserializing ImageRef with uniqueId ${serializedRef.uniqueId}: ${error}`); }).then(success => { if (!success) { console.error(`Unsuccessful deserialization of ImageRef with uniqueId ${serializedRef.uniqueId}`); } }); return new ImageRef(serializedRef.uniqueId, undefined); } /** * Converts the Image Ref to Json representation */ async serialize(imageSerializationMode) { if (imageSerializationMode === 'BUFFER') { const encodedImage = await this.encodeImage(); if (encodedImage) { return { buffer: encodedImage }; } else { return null; } } else { this.throwErrorIfUniqueIdIsMissing(); this.throwErrorIfReleased(); // The promise is intentionally not awaited here ScanbotSDKImpl.imageRefSerialize(this.uniqueId).catch(error => { console.error(`Error while serializing ImageRef with uniqueId ${this.uniqueId}: ${error}`); }).then(success => { if (!success) { console.error(`Unsuccessful serialization of ImageRef with uniqueId ${this.uniqueId}`); } }); return { uniqueId: this.uniqueId }; } } /** * Creates ImageRef with uniqueId from the path to an image. */ static async fromImageFileUri(uri, options = new PathImageLoadOptions()) { try { const serializedImageRefUniqueId = await ScanbotSDKImpl.imageRefFromImageFileUri(uri, options); return ImageRef.deserialize({ uniqueId: serializedImageRefUniqueId }); } catch (error) { console.error(error); return null; } } /** * Creates ImageRef with uniqueId from base64 encoded buffer, e.g. from jpeg. */ static async fromEncodedBuffer(buffer, options = new BufferImageLoadOptions()) { try { const serializedImageRefUniqueId = await ScanbotSDKImpl.imageRefFromEncodedBuffer(buffer, options); return ImageRef.deserialize({ uniqueId: serializedImageRefUniqueId }); } catch (error) { console.error(error); return null; } } /** * Creates a deep copy of the image. * If uniqueId is not set or the image is already released, an exception will be thrown. */ async clone() { this.throwErrorIfUniqueIdIsMissing(); this.throwErrorIfReleased(); try { const serializedImageRefUniqueId = await ScanbotSDKImpl.imageRefClone(this.uniqueId); return ImageRef.deserialize({ uniqueId: serializedImageRefUniqueId }); } catch (error) { console.error(error); return null; } } /** * Compresses ImageRef and stores it either on disk or in memory according to global settings. * If uniqueId is not set or the image is already released, an exception will be thrown. */ async hibernate() { this.throwErrorIfUniqueIdIsMissing(); this.throwErrorIfReleased(); try { await ScanbotSDKImpl.imageRefHibernate(this.uniqueId); } catch (error) { console.error(error); } } /** * Releases native resources stored by the ref. * If two different ImageRef objects have the same uniqueId both of them become cleared. * If uniqueId is not set or the image is already released, an exception will be thrown. */ async clear() { this.throwErrorIfUniqueIdIsMissing(); this.throwErrorIfReleased(); try { await ScanbotSDKImpl.imageRefClear(this.uniqueId); } catch (error) { console.error(error); } } /** * Information about stored image as reference. * If uniqueId is not set or the image is already released, an exception will be thrown. */ async info() { this.throwErrorIfUniqueIdIsMissing(); this.throwErrorIfReleased(); try { const imageInfo = await ScanbotSDKImpl.imageRefInfo(this.uniqueId); return new ImageInfo(imageInfo); } catch (error) { console.error(error); return null; } } /** * Saves the stored image with the given options. * If uniqueId is not set or the image is already released, an exception will be thrown. */ async saveImage(path, options = new SaveImageOptions()) { this.throwErrorIfUniqueIdIsMissing(); this.throwErrorIfReleased(); try { return await ScanbotSDKImpl.imageRefSaveImage(this.uniqueId, path, options); } catch (error) { console.error(error); return false; } } /** * Encode image. */ async encodeInPlace() { if (this._buffer) { // NO-OP, ImageRef is already converted. } else { this.throwErrorIfUniqueIdIsMissing(); this.throwErrorIfReleased(); try { const imageAsBuffer = await ScanbotSDKImpl.imageRefEncodeImage(this.uniqueId, new EncodeImageOptions()); if (imageAsBuffer) { this._buffer = imageAsBuffer; } } catch (error) { console.error(error); } } } /** * Returns the stored image as base64. */ async encodeImage(options) { if (this._buffer) { if (options) { throw new Error('EncodeImageOptions are not available when image is already encoded to base64'); } return this._buffer; } else { this.throwErrorIfUniqueIdIsMissing(); this.throwErrorIfReleased(); try { return await ScanbotSDKImpl.imageRefEncodeImage(this.uniqueId, options ?? new EncodeImageOptions()); } catch (error) { console.error(error); return null; } } } /** * Releases strong reference to the image. * If uniqueId to the image is not set, an exception will be thrown. */ release() { this.throwErrorIfUniqueIdIsMissing(); if (!this.released) { // The promise is intentionally not awaited here ScanbotSDKImpl.imageRefRelease(this.uniqueId).catch(error => { console.error(`Error while releasing ImageRef with uniqueId ${this.uniqueId}: ${error}`); }); this.released = true; } } /** * Returns a snapshot of all alive ImageRefs. * The snapshot contains a list of ImageRefs with information such as in-memory size. */ static async makeSnapshot() { try { const snapshot = await ScanbotSDKImpl.makeSnapshot(); return new ImageRefPoolSnapshot(snapshot); } catch (error) { console.error(error); return null; } } /** * Releases all alive images despite any existing references. */ static releaseAll() { // The promise is intentionally not awaited here ScanbotSDKImpl.imageRefReleaseAll().catch(() => {}); } throwErrorIfUniqueIdIsMissing() { if (!this.uniqueId) { throw new Error('uniqueId is missing'); } } throwErrorIfReleased() { if (this.released) { throw new Error(`ImageRef with uniqueId ${this.uniqueId} has been released`); } } } //# sourceMappingURL=image.js.map