sf-i-uploader
Version:
Superflows Navigation Component
836 lines (833 loc) • 76.4 kB
JavaScript
/**
* @license
* Copyright 2022 Superflow.dev
* SPDX-License-Identifier: MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { LitElement, html, css } from 'lit';
import { customElement, query, property } from 'lit/decorators.js';
import Util from './util';
import Api from './api';
import pdfjs from '@bundled-es-modules/pdfjs-dist';
// pdfjs.GlobalWorkerOptions.workerSrc =
// '/node_modules/@bundled-es-modules/pdfjs-dist/build/pdf.worker.min.js';
// pdfjs.GlobalWorkerOptions.workerSrc =
// '/node_modules/@bundled-es-modules/pdfjs-dist/build/pdf.worker.min.js';
/*
Modes: View, Add, Edit, Delete, Admin
DB: partitionKey, rangeKey, values
*/
/**
* SfIUploader element.
* @fires renderComplete - When the list is populated
* @fires valueChanged - When the value is changed
* @property apiId - backend api id
* @property label - input label
* @property name - name of the input
* @property mode - mode of operation
* @property selectedId - id to preselect
* @property selectedValue - callback function
*/
let SfIUploader = class SfIUploader extends LitElement {
constructor() {
super();
// prepopulatedInputArr: string = "[{\"key\":\"2c39a366-1532-49a1-891e-bdcca8d5d215\",\"ext\": \"jpg\"},{\"key\": \"730e310f-5ae6-4641-a2af-eae3a535b6e9\",\"ext\": \"jpg\"}]";
// prepopulatedInputArr: string = "[{\"key\":\"45f25547-3dce-43e7-bf9e-585fe94a08eb\",\"ext\":\"jpg\"}]";
// prepopulatedInputArr: string = "[{\"key\":\"b70fead2-0068-4d9a-a210-5e2a0ff469ab\",\"ext\":\"pdf\"}]";
// prepopulatedInputArr: string = "[{\"key\":\"e59d2652-2dc8-4748-956a-3634553736bc\",\"ext\":\"pdf\"}]";
// prepopulatedInputArr: string = "[{\"key\":\"b70fead2-0068-4d9a-a210-5e2a0ff469ab\",\"ext\":\"pdf\"},{\"key\":\"430f0879-15c3-4fb5-a011-7616f9f696ee\",\"ext\":\"xlsx\"}]";
// prepopulatedInputArr: string = "[{\"filename\":\"logo.png\",\"key\":\"5e850fa4-19de-4ad0-bcd1-fe7e8d9335d5\",\"ext\":\"png\"}]";
// prepopulatedInputArr: string = "[{\"key\":\"3deb2dc2-dddc-4560-a5f2-d4a137429e59\",\"file\":{\"name\":\"3deb2dc2-dddc-4560-a5f2-d4a137429e59.pdf\",\"ext\":\"pdf\"},\"ext\":\"pdf\"},{\"key\":\"2050925c-db78-4a6c-ad75-cfa898fc64b2\",\"file\":{\"name\":\"2050925c-db78-4a6c-ad75-cfa898fc64b2.pdf\",\"ext\":\"pdf\"},\"ext\":\"pdf\"}]";
this.prepopulatedInputArr = "[]";
this.mode = "edit";
this.maximize = "no";
this.hidepreview = "no";
this.readOnly = false;
this.max = "1";
this.dataPassthrough = "{}";
this.callbackUrlHost = "eoma59bzxizzjlf.m.pipedream.net";
this.callbackUrlPath = "processresult";
this.displayDetail = "no";
this.getMax = () => {
try {
return parseInt(this.max);
}
catch (e) {
return 0;
}
};
this.projectId = "";
this.maxSize = 512000;
this.apiId = "qegqubqm14";
this.extract = "yes";
this.newButtonText = "New Upload";
this.allowedExtensions = "[\"jpg\", \"png\", \"pdf\"]";
this.extractableExtensions = "[\"jpg\", \"png\", \"pdf\"]";
this.extractJobId = "";
this.docType = "";
this.chunkSize = 102800;
this.allowDownload = "no";
this.getAllowedExtensions = () => {
return JSON.parse(this.allowedExtensions);
};
this.getExtractableExtensions = () => {
return JSON.parse(this.extractableExtensions);
};
// setAllowedExtensions = (arr: any) => {
// this.allowedExtensions = JSON.stringify(arr);
// }
this.selectedValues = () => {
const values = [];
for (var i = 0; i < this.inputArr.length; i++) {
if (this.inputArr[i]['key'] != null) {
if (this.inputArr[i]['arrWords'] != null) {
values.push({
arrWords: this.inputArr[i]['arrWords'],
arrWordsMeta: this.inputArr[i]['arrWordsMeta'],
jobId: this.inputArr[i]['jobId'],
filename: this.inputArr[i]['filename'],
key: this.inputArr[i]['key'],
ext: this.inputArr[i]['ext']
});
}
else if (this.inputArr[i]['jobId'] != null) {
values.push({
jobId: this.inputArr[i]['jobId'],
filename: this.inputArr[i]['filename'],
key: this.inputArr[i]['key'],
ext: this.inputArr[i]['ext']
});
}
else if (this.inputArr[i]['ext'] != null) {
values.push({
key: this.inputArr[i]['key'],
filename: this.inputArr[i]['filename'],
ext: this.inputArr[i]['ext']
});
}
else {
values.push({
key: this.inputArr[i]['key'],
filename: this.inputArr[i]['filename'],
ext: this.inputArr[i]['file'].name.split(".")[this.inputArr[i]['file'].name.split(".").length - 1]
});
}
}
}
return values;
};
this.selectedTexts = () => {
const values = [];
for (var i = 0; i < this.inputArr.length; i++) {
if (this.inputArr[i]['key'] != null) {
if (this.inputArr[i]['arrWords'] != null) {
values.push({
arrWords: this.inputArr[i]['arrWords'],
arrWordsMeta: this.inputArr[i]['arrWordsMeta'],
jobId: this.inputArr[i]['jobId'],
filename: this.inputArr[i]['filename'],
key: this.inputArr[i]['key'],
ext: this.inputArr[i]['ext']
});
}
else if (this.inputArr[i]['jobId'] != null) {
values.push({
jobId: this.inputArr[i]['jobId'],
filename: this.inputArr[i]['filename'],
key: this.inputArr[i]['key'],
ext: this.inputArr[i]['ext']
});
}
else if (this.inputArr[i]['ext'] != null) {
values.push({
key: this.inputArr[i]['key'],
filename: this.inputArr[i]['filename'],
ext: this.inputArr[i]['ext']
});
}
else {
values.push({
key: this.inputArr[i]['key'],
filename: this.inputArr[i]['filename'],
ext: this.inputArr[i]['file'].name.split(".")[this.inputArr[i]['file'].name.split(".").length - 1]
});
}
}
}
return values;
};
this.inputArr = [];
this.inputArrInterval = null;
this.uploadProgressInterval = null;
this.uploadProgress = { progress: 0 };
this.uploadProgressReceiver = null;
this.current = 0;
this.arrWords = [];
this.arrWordsMeta = {};
this.documentParsed = [""];
this.possibleMatches = [[]];
this.matchArr = [[]];
this.uploadValid = false;
this.flow = "";
// prepareXhr = async (data: any, url: string, loaderElement: any, authorization: any) => {
// if(loaderElement != null) {
// loaderElement.innerHTML = '<div class="lds-dual-ring"></div>';
// }
// return await Util.callApi(url, data, authorization);
// }
this.pageNum = 1;
this.pageRendering = false;
this.pageNumPending = null;
this.pdfDoc = null;
this.clearMessages = () => {
this._SfRowError.style.display = 'none';
this._SfRowErrorMessage.innerHTML = '';
this._SfRowSuccess.style.display = 'none';
this._SfRowSuccessMessage.innerHTML = '';
};
this.setError = (msg) => {
this._SfRowError.style.display = 'flex';
this._SfRowErrorMessage.innerHTML = msg;
this._SfRowSuccess.style.display = 'none';
this._SfRowSuccessMessage.innerHTML = '';
setTimeout(() => {
this.clearMessages();
}, 3000);
};
this.setSuccess = (msg) => {
this._SfRowError.style.display = 'none';
this._SfRowErrorMessage.innerHTML = '';
this._SfRowSuccess.style.display = 'flex';
this._SfRowSuccessMessage.innerHTML = msg;
};
this.uploadProgressUpdater = (element, value) => {
element.querySelector('.progress-number').innerHTML = value + '% Uploaded';
element.querySelector('.progress-bar-right').style.width = (100 - parseInt(value)) + '%';
element.querySelector('.progress-bar-left').style.width = value + '%';
};
this.renderMessageData = (message, verify, match) => {
this._SfMessageContainer.style.display = 'block';
var html = '';
html += '<div class="d-flex">';
html += '<div part="sf-upload-message">' + message + '</div>';
html += '</div>';
if (verify.length > 0) {
html += '<div class="d-flex">';
html += '<div part="sf-upload-submessage">It must contain following words</div>';
html += '</div>';
html += '<div class="d-flex">';
verify.forEach(verifyWord => {
html += '<div class="mr-10 upload-status" part="doctype-verify-badge">' + verifyWord + '</div>';
});
html += '</div>';
}
this._SfMessageContainer.innerHTML = html;
this.matchArr[0] = match;
};
this.renderPdfPage = (num, canvas, scale, ctx) => {
this.pageRendering = true;
// Using promise to fetch the page
let thisObj = this;
this.pdfDoc.getPage(num).then(function (page) {
var viewport = page.getViewport({ scale: scale });
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
var renderTask = page.render(renderContext);
// Wait for rendering to finish
renderTask.promise.then(function () {
thisObj.pageRendering = false;
if (thisObj.pageNumPending !== null) {
// New page rendering is pending
thisObj.renderPdfPage(thisObj.pageNumPending, canvas, scale, ctx);
thisObj.pageNumPending = null;
}
});
});
console.log("rendering page", this._SfDetailContainer.querySelector('#pdf-page-num'), num);
if (this._SfDetailContainer.querySelector('#pdf-page-num') != null) {
this._SfDetailContainer.querySelector('#pdf-page-num').innerHTML = num + "";
}
};
this.queueRenderPage = (num, canvas, scale, ctx) => {
if (this.pageRendering) {
this.pageNumPending = num;
}
else {
this.renderPdfPage(num, canvas, scale, ctx);
}
};
this.onPrevPage = (canvas, scale, ctx) => {
if (this.pageNum <= 1) {
return;
}
this.pageNum--;
this.queueRenderPage(this.pageNum, canvas, scale, ctx);
};
this.onNextPage = (canvas, scale, ctx) => {
if (this.pageNum >= this.pdfDoc.numPages) {
return;
}
this.pageNum++;
this.queueRenderPage(this.pageNum, canvas, scale, ctx);
};
this.expandPdfDetail = async (ext, data, fromMaximize = false) => {
var _a, _b, _c, _d;
console.log('rendering detail', ext, fromMaximize);
let detailHtml = '';
detailHtml += '<div class="d-flex justify-between align-center m-10" part="details-controls-container">';
if (this.allowDownload == "yes") {
detailHtml += '<button part="button-icon" id="download-pdf-button"><span class="material-icons">cloud_download</span></button>';
}
else {
detailHtml += '<button class="invisible" part="button-icon"><span class="material-icons">close</span></button>';
}
detailHtml += '<div id="pdf-controls-container" part="pdf-controls-container" class="d-flex justify-end align-center ml-10 mr-10">';
detailHtml += '<button id="pdf-prev" part="button-icon"><span class="material-icons">arrow_back</span></button>';
detailHtml += '<span class="m-5" part="pdf-pages">Page: <span id="pdf-page-num" part="pdf-page-num"></span> / <span id="pdf-page-count" part="pdf-page-count"></span></span>';
detailHtml += '<button id="pdf-next" part="button-icon"><span class="material-icons">arrow_forward</span></button>';
detailHtml += '</div>';
detailHtml += `<button id="button-detail-cancel" part="button-icon"><span class="material-icons">${(fromMaximize || this.displayDetail == "yes") ? 'call_received' : 'close'}</span></button>`;
detailHtml += '</div>';
detailHtml += '<canvas id="pdf-canvas" class="pdf-canvas mb-20", part="pdf-canvas"></canvas>';
this._SfDetailContainer.innerHTML = detailHtml;
this._SfDetailContainer.style.display = 'flex';
(_a = this._SfDetailContainer.querySelector('#download-pdf-button')) === null || _a === void 0 ? void 0 : _a.addEventListener('click', () => {
const a = document.createElement("a");
a.style.display = "none";
a.href = data;
a.download = "download_" + new Date().getTime() + "." + ext;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
(_b = this._SfDetailContainer.querySelector('#button-detail-cancel')) === null || _b === void 0 ? void 0 : _b.addEventListener('click', () => {
this._SfDetailContainer.innerHTML = '';
this._SfDetailContainer.style.display = 'none';
});
pdfjs.GlobalWorkerOptions.workerSrc = await this.loadWorkerURL("https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.6.172/pdf.worker.min.js");
const pdfjsLib = pdfjs;
var loadingTask = pdfjsLib.getDocument({ data: atob(data.replace("data:application/pdf;base64,", "")) });
var canvas = this._SfDetailContainer.querySelector('#pdf-canvas');
var ctx = canvas.getContext('2d');
var scale = 1.2;
let thisObj = this;
(_c = this._SfDetailContainer.querySelector('#pdf-prev')) === null || _c === void 0 ? void 0 : _c.addEventListener('click', () => {
thisObj.onPrevPage(canvas, scale, ctx);
});
(_d = this._SfDetailContainer.querySelector('#pdf-next')) === null || _d === void 0 ? void 0 : _d.addEventListener('click', () => {
thisObj.onNextPage(canvas, scale, ctx);
});
loadingTask.promise.then(function (pdf) {
console.log('PDF loaded', canvas);
thisObj.pdfDoc = pdf;
thisObj.pageNum = 1,
thisObj.pageRendering = false;
thisObj.pageNumPending = null;
thisObj._SfDetailContainer.querySelector('#pdf-page-count').innerHTML = pdf.numPages + "";
thisObj._SfDetailContainer.querySelector('#pdf-controls-container').style.display = (pdf.numPages == 1) ? "none" : "flex";
thisObj.renderPdfPage(thisObj.pageNum, canvas, scale, ctx);
}, function (reason) {
// PDF loading error
console.error(reason);
});
};
this.loadWorkerURL = async (url) => {
let cachedJSDfd = new pdfjs.PromiseCapability();
var xmlhttp;
xmlhttp = new XMLHttpRequest();
//the callback function to be callled when AJAX request comes back
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var workerJSBlob = new Blob([xmlhttp.responseText], {
type: "text/javascript"
});
cachedJSDfd.resolve(window.URL.createObjectURL(workerJSBlob));
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
return cachedJSDfd.promise;
};
this.renderMaximize = async (ext, data) => {
var _a, _b;
if (ext == "png" || ext == "jpg") {
if (this.displayDetail == "yes") {
this._SfDetailContainer.style.display = 'flex';
let flagSetHtml = true;
var html = '';
html += '<div class="d-flex justify-between m-10">';
html += '<button class="invisible" part="button-icon"><span class="material-icons">close</span></button>';
html += '<button id="button-detail-cancel" part="button-icon"><span class="material-icons">call_received</span></button>';
html += '</div>';
if (ext == "png" || ext == "jpg") {
html += '<div class="d-flex justify-center">';
html += '<img src="' + data + '" alt="picture" />';
html += '</div>';
}
else if (ext == "pdf") {
this.expandPdfDetail(ext, data, true);
flagSetHtml = false;
}
if (flagSetHtml) {
this._SfDetailContainer.innerHTML = html;
}
// console.log('rendering key data', html);
(_a = this._SfDetailContainer.querySelector('#button-detail-cancel')) === null || _a === void 0 ? void 0 : _a.addEventListener('click', () => {
this._SfDetailContainer.innerHTML = '';
this._SfDetailContainer.style.display = 'none';
});
}
else {
const contentType = ((_b = data.match(/[^:]\w+\/[\w-+\d.]+(?=;|,)/)) !== null && _b !== void 0 ? _b : [""])[0];
const byteCharacters = atob(data.substr(`data:${contentType};base64,`.length));
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += 1024) {
const slice = byteCharacters.slice(offset, offset + 1024);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, { type: contentType });
const blobUrl = URL.createObjectURL(blob);
window.open(blobUrl, '_blank');
}
}
};
this.renderDownload = async (ext, data) => {
const a = document.createElement("a");
a.style.display = "none";
a.href = data;
a.download = "download_" + new Date().getTime() + "." + ext;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
this.renderKeyData = async (ext, data, hidePreview = false) => {
var _a, _b, _c;
var html = '';
console.log("key Data", data, ext, this.mode);
if (this.mode == "view") {
if (ext == "png" || ext == "jpg") {
html += '<div class="d-flex justify-center align-center" part="image-container">';
if (!hidePreview) {
html += '<img src="' + data + '" alt="picture" part="image-component" class="mr-10"/>';
}
if (this.maximize == "yes") {
html += '<button id="button-open-in-new-tab" part="button-icon"><span class="material-icons">open_in_new</span></button>';
}
html += '</div>';
this._SfUploadContainer.innerHTML = html;
this._SfUploadContainer.style.display = 'flex';
if (this.maximize == "yes") {
this._SfUploadContainer.querySelector('#button-open-in-new-tab').addEventListener('click', () => {
var _a;
if (hidePreview) {
Api.getKeyData(this.inputArr[0]['key'], this.apiId, this._SfLoader, this.renderMaximize, (errMsg) => {
this.setError(errMsg);
setTimeout(() => {
this.clearMessages();
}, 3000);
}, this.projectId);
}
else {
console.log('opening in new tab');
const contentType = ((_a = data.match(/[^:]\w+\/[\w-+\d.]+(?=;|,)/)) !== null && _a !== void 0 ? _a : [""])[0];
const byteCharacters = atob(data.substr(`data:${contentType};base64,`.length));
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += 1024) {
const slice = byteCharacters.slice(offset, offset + 1024);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, { type: contentType });
const blobUrl = URL.createObjectURL(blob);
window.open(blobUrl, '_blank');
}
});
}
}
else if (ext == "pdf") {
html += '<div class="d-flex justify-center align-center" part="pdf-thumbnail-container">';
if (!hidePreview) {
html += '<canvas id="pdf-canvas-thumbnail" class="pdf-canvas-thumbnail", part="pdf-canvas-thumbnail"></canvas>';
}
if (this.maximize == "yes") {
html += '<button id="button-expand-pdf" part="button-icon"><span class="material-icons">open_in_new</span></button>';
}
html += '</div>';
this._SfUploadContainer.innerHTML = html;
console.log(html, this._SfUploadContainer, this._SfUploadContainer.innerHTML);
this._SfUploadContainer.style.display = 'flex';
if (this.maximize == "yes") {
this._SfUploadContainer.querySelector('#button-expand-pdf').addEventListener('click', () => {
if (hidePreview) {
Api.getKeyData(this.inputArr[0]['key'], this.apiId, this._SfLoader, this.expandPdfDetail, (errMsg) => {
this.setError(errMsg);
setTimeout(() => {
this.clearMessages();
}, 3000);
}, this.projectId);
}
else {
this.expandPdfDetail(ext, data);
}
});
}
if (!hidePreview) {
pdfjs.GlobalWorkerOptions.workerSrc = await this.loadWorkerURL("https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.6.172/pdf.worker.min.js");
const pdfjsLib = pdfjs;
// Using DocumentInitParameters object to load binary data.
var loadingTask = pdfjsLib.getDocument({ data: atob(data.replace("data:application/pdf;base64,", "")) });
var canvas = this._SfUploadContainer.querySelector('#pdf-canvas-thumbnail');
var ctx = canvas.getContext('2d');
var scale = 0.8;
let thisObj = this;
loadingTask.promise.then(function (pdf) {
console.log('PDF loaded');
thisObj.pdfDoc = pdf;
thisObj.pageNum = 1,
thisObj.pageRendering = false;
thisObj.pageNumPending = null;
// thisObj._SfUploadContainer.querySelector('#pdf-page-count').innerHTML = pdf.numPages + ""
// thisObj._SfUploadContainer.querySelector('#pdf-controls-container').style.display = (pdf.numPages == 1) ? "none" : "block"
thisObj.renderPdfPage(thisObj.pageNum, canvas, scale, ctx);
}, function (reason) {
// PDF loading error
console.error(reason);
});
}
}
else if (this.maximize == "yes") {
html += '<div class="d-flex justify-center align-center">';
html += '<button class="d-flex justify-center align-center" part="button-icon" id="download-button"><span>Download </span><span class="material-icons ml-10">cloud_download</span></button>';
html += '</div>';
this._SfUploadContainer.innerHTML = html;
this._SfUploadContainer.style.display = 'flex';
(_a = this._SfUploadContainer.querySelector('#download-button')) === null || _a === void 0 ? void 0 : _a.addEventListener('click', () => {
if (hidePreview) {
Api.getKeyData(this.inputArr[0]['key'], this.apiId, this._SfLoader, this.renderDownload, (errMsg) => {
this.setError(errMsg);
setTimeout(() => {
this.clearMessages();
}, 3000);
}, this.projectId);
}
else {
const a = document.createElement("a");
a.style.display = "none";
a.href = data;
a.download = "download_" + new Date().getTime() + "." + ext;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
});
}
}
else {
this._SfDetailContainer.style.display = 'flex';
let flagSetHtml = true;
html += '<div class="d-flex justify-between m-10">';
html += '<button class="invisible" part="button-icon"><span class="material-icons">close</span></button>';
html += '<button id="button-detail-cancel" part="button-icon"><span class="material-icons">close</span></button>';
html += '</div>';
if (ext == "png" || ext == "jpg") {
html += '<div class="d-flex justify-center">';
html += '<img src="' + data + '" alt="picture" />';
html += '</div>';
}
else if (ext == "pdf") {
this.expandPdfDetail(ext, data);
flagSetHtml = false;
}
else {
html += '<div class="d-flex justify-center align-center">';
html += '<div part="sf-uploader-download-message">File is ready for download!</div> ';
html += '<button part="button-icon" id="download-button"><span class="material-icons">cloud_download</span></button>';
html += '</div>';
}
if (flagSetHtml) {
this._SfDetailContainer.innerHTML = html;
}
// console.log('rendering key data', html);
(_b = this._SfDetailContainer.querySelector('#button-detail-cancel')) === null || _b === void 0 ? void 0 : _b.addEventListener('click', () => {
this._SfDetailContainer.innerHTML = '';
this._SfDetailContainer.style.display = 'none';
});
(_c = this._SfDetailContainer.querySelector('#download-button')) === null || _c === void 0 ? void 0 : _c.addEventListener('click', () => {
const a = document.createElement("a");
a.style.display = "none";
a.href = data;
a.download = "download_" + new Date().getTime() + "." + ext;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
}
};
this.chunkify = (base64String) => {
let regex = new RegExp(`.{1,${this.chunkSize}}`, 'g');
const chunks = base64String.match(regex);
return chunks;
};
this.executeExtract = async (jobId) => {
var resultExtractStatus;
do {
resultExtractStatus = await Api.getExtractStatus(jobId, this.apiId, this._SfLoader, this.setError, this.projectId);
console.log(resultExtractStatus);
await Util.sleep(5000);
} while (resultExtractStatus != null && resultExtractStatus.status == "IN_PROGRESS");
if (resultExtractStatus != null && resultExtractStatus.status == "SUCCEEDED") {
let index = 0;
for (let i = 0; i < this.inputArr.length; i++) {
if (this.inputArr[i]['jobId'] == jobId) {
index = i;
break;
}
}
this.arrWords = [];
this.arrWordsMeta = {};
this.documentParsed[index] = "";
this.arrWords = JSON.parse(resultExtractStatus.arrWords.S);
this.arrWordsMeta = JSON.parse(resultExtractStatus.arrWordsMeta.S);
this.documentParsed[index] = this.docType == "" ? "" : resultExtractStatus.documentParsed ? "yes" : "no";
this.possibleMatches[index] = this.docType == "" ? [] : resultExtractStatus.documentParsed ? resultExtractStatus.possibleMatches : [];
}
};
this.processExtract = async (key, fileIndex) => {
// this.extractState.state = 1;
const resultExtract = await Api.getExtract(key, fileIndex, this.dataPassthrough, this.apiId, this._SfLoader, (msg) => { this.setErrorMaliciousContent(msg, fileIndex); }, this.callbackUrlHost, this.callbackUrlPath, parseInt(fileIndex) == 0 ? this.docType : "", this.projectId);
if (resultExtract == null) {
return null;
}
const jobId = resultExtract.jobId;
return jobId;
};
this.setErrorMaliciousContent = (msg, fileIndex) => {
if (msg.toLowerCase().indexOf("malicious") >= 0) {
this.inputArr.splice(fileIndex, 1);
this.populateInputs();
}
this.setError(msg);
};
this.executeAndUpdateExtract = async (jobId, fileIndex) => {
await this.executeExtract(jobId);
let index = 0;
for (let i = 0; i < this.inputArr.length; i++) {
if (this.inputArr[i]['jobId'] == jobId) {
index = i;
break;
}
}
this.inputArr[fileIndex]["arrWords"] = this.arrWords;
this.inputArr[fileIndex]["arrWordsMeta"] = this.arrWordsMeta;
this.inputArr[fileIndex]["documentParsed"] = this.documentParsed[index];
const event2 = new CustomEvent('analysisCompleted', { detail: { meta: this.arrWordsMeta, words: this.arrWords }, bubbles: true, composed: true });
this.dispatchEvent(event2);
this.isUploadValid();
};
this.beginUploadJob = (fileIndex, file) => {
const event2 = new CustomEvent('uploadStarted', { detail: {}, bubbles: true, composed: true });
this.dispatchEvent(event2);
const fileName = file.name;
const ext = fileName.split(".")[file.name.split(".").length - 1].toLowerCase();
const key = Util.newUuidV4();
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
const run = async () => {
const chunks = this.chunkify(reader.result);
await Api.uploadMeta(key, fileName, ext, (chunks === null || chunks === void 0 ? void 0 : chunks.length) + "", this.apiId, this._SfLoader, this.setError, this.projectId);
for (var i = 0; i < chunks.length; i++) {
this.uploadProgressReceiver = this._SfUploadContainer.querySelector('#upload-row-' + fileIndex);
await Api.uploadBlock(key, i + "", chunks[i] + "", this.apiId, this._SfLoader, this.setError, this.projectId);
this.uploadProgress.progress = parseInt((((i + 1) * 100) / chunks.length) + "");
}
for (var i = 0; i < this.inputArr.length; i++) {
this.inputArr[i]["progress"] = false;
}
this.inputArr[fileIndex]["key"] = key;
this.inputArr[fileIndex]["ext"] = ext;
const keys = [];
for (i = 0; i < this.inputArr.length; i++) {
if (this.inputArr[i]['key'] != null && this.inputArr[i]['key'].length > 5) {
keys.push(this.inputArr[i]['key']);
}
}
const event = new CustomEvent('uploadCompleted', { detail: keys, bubbles: true, composed: true });
this.dispatchEvent(event);
if (this.extract.toLowerCase() == "yes" && this.getExtractableExtensions().indexOf(ext) >= 0) {
const jobId = await this.processExtract(key, fileIndex);
if (jobId == null) {
this.isUploadValid();
return;
}
this.inputArr[fileIndex]["jobId"] = jobId;
const event1 = new CustomEvent('analysisInProgress', { detail: jobId, bubbles: true, composed: true });
this.dispatchEvent(event1);
this.executeAndUpdateExtract(jobId, fileIndex);
}
this.isUploadValid();
};
run();
};
};
this.clearUploads = () => {
this.inputArr = [];
};
this.populateInputs = () => {
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
var htmlStr = '';
if (this.mode == "view") {
console.log("populating view input", this.inputArr, this.projectId);
if (this.inputArr.length > 0) {
if (this.hidepreview == "yes") {
this.renderKeyData(this.inputArr[0]['ext'], "", true);
}
else {
Api.getKeyData(this.inputArr[0]['key'], this.apiId, this._SfLoader, this.renderKeyData, (errMsg) => {
this.setError(errMsg);
setTimeout(() => {
this.clearMessages();
}, 3000);
}, this.projectId);
}
}
// for(var i = 0; i < this.inputArr.length; i++){
// if(this.inputArr[i].file == null) {
// //no file
// } else if (this.inputArr[i]["arrWords"] != null) {
// // file with analysis complete
// } else if (this.inputArr[i]["jobId"] != null) {
// //file with analysis not complete
// } else if (this.inputArr[i]["key"] != null) {
// // file with upload complete
// }
// }
}
else {
console.log('populating input', this.inputArr);
for (var i = 0; i < this.inputArr.length; i++) {
htmlStr += '<div part="input" id="upload-row-' + i + '">';
htmlStr += '<div class="d-flex align-center justify-between flex-wrap">';
if (this.inputArr[i].file == null) {
htmlStr += '<input id="file-' + i + '" type="file" />';
htmlStr += '<div class="d-flex align-center justify-between flex-wrap" part="upload-buttons-container">';
htmlStr += (this.docType == "" || i > 0 ? "" : '<div class="mr-10 upload-status" part="doctype-badge">' + this.docType + '</div>');
htmlStr += '<button id="button-delete-' + i + '" part="button-icon"><span class="material-icons">delete</span></button>';
htmlStr += '</div>';
}
else if (this.inputArr[i]["arrWords"] != null) {
const fileName = this.inputArr[i]['file'].name;
const ext = this.inputArr[i]['file'].name.split(".")[this.inputArr[i]['file'].name.split(".").length - 1];
htmlStr += '<div class="w-100 d-flex align-center justify-between">';
htmlStr += '<div class="mr-10"><sf-i-elastic-text text="' + fileName + '" minLength="20"></sf-i-elastic-text></div>';
htmlStr += '<div class="d-flex align-center" part="upload-buttons-container">';
// htmlStr += '<button id="button-delete-'+i+'" class="mr-10" part=""><span class="material-icons">delete</span></button>';
htmlStr += '<div class="mr-10 upload-status" part="upload-status">Analysis Complete</div>';
htmlStr += (this.docType == "" || i > 0 ? "" : '<div class="mr-10 upload-status" part="doctype-badge">' + this.docType + '</div>');
htmlStr += '<div part="ext-badge" class="ext-badge mr-10">' + ext + '</div>';
if (this.inputArr[i]["delete"]) {
htmlStr += '<button id="button-delete-file-cancel-' + i + '" part="button-icon" class="button-icon"><span class="material-icons">close</span></button>';
htmlStr += '<button id="button-delete-file-confirm-' + i + '" part="button-icon" class="button-icon"><span class="material-icons">delete</span><span class="material-icons">done</span></button>';
}
else {
htmlStr += '<button id="button-delete-file-' + i + '" part="button-icon" class="button-icon"><span class="material-icons">delete</span></button>';
htmlStr += '<button id="button-open-' + i + '" part="button-icon" class=""><span class="material-icons">open_in_new</span></button>';
}
htmlStr += '</div>';
htmlStr += '</div>';
htmlStr += '<div part="extracted-meta" class="d-flex align-center mt-10 w-100">';
if (this.inputArr[i]["arrWordsMeta"]['PAGE'] != null) {
htmlStr += '<div part="extracted-text-chip">' + this.inputArr[i]["arrWordsMeta"]['PAGE'] + ' Page(s)</div>';
}
else {
htmlStr += '<div part="extracted-text-chip">0 Page(s)</div>';
}
if (this.inputArr[i]["arrWordsMeta"]['LINE'] != null) {
htmlStr += '<div part="extracted-text-chip">' + this.inputArr[i]["arrWordsMeta"]['LINE'] + ' Line(s)</div>';
}
else {
htmlStr += '<div part="extracted-text-chip">0 Line(s)</div>';
}
if (this.inputArr[i]["arrWordsMeta"]['WORD'] != null) {
htmlStr += '<div part="extracted-text-chip">' + this.inputArr[i]["arrWordsMeta"]['WORD'] + ' Word(s)</div>';
}
else {
htmlStr += '<div part="extracted-text-chip">0 Word(s)</div>';
}
htmlStr += i == 0 ? this.documentParsed[i].length > 0 ? (this.documentParsed[i] == "yes" ? ('<div part="extracted-text-chip-parsed" class="d-flex align-center"><span>Document Check Successful</span> <span class="material-symbols-outlined parsing-result">verified</span></div>') : ('<div part="extracted-text-chip-failed" class="d-flex align-center"><span>Document Check Failed</span> <span class="material-symbols-outlined parsing-result">release_alert</span></div>')) : "" : "";
htmlStr += '</div>';
if (this.documentParsed[i] && this.matchArr[0].length > 0 && this.possibleMatches[i].length > 0) {
htmlStr += '<div class="mt-20 w-100">';
htmlStr += '<div part="matches-title">Possible Matches</div>';
htmlStr += '<div part="extracted-meta" class="d-flex align-center w-100">';
for (var j = 0; j < this.possibleMatches[i].length; j++) {
htmlStr += ('<div part="matches" class="mr-10">' + this.possibleMatches[i][j] + '</div>');
}
htmlStr += '</div>';
htmlStr += '</div>';
}
htmlStr += '<div class="mt-20 w-100">';
htmlStr += '<div part="extracted-title">Extracted Text</div>';
htmlStr += '<div part="extracted-text" class="d-flex align-center">';
htmlStr += '<sf-i-elastic-text text="' + this.inputArr[i]["arrWords"].join(' ') + '" minLength="100"></sf-i-elastic-text>';
htmlStr += '</div>';
htmlStr += '</div>';
}
else if (this.inputArr[i]["jobId"] != null) {
const fileName = this.inputArr[i]['file'].name;
const ext = this.inputArr[i]['file'].name.split(".")[this.inputArr[i]['file'].name.split(".").length - 1];
htmlStr += '<div class="mr-10"><sf-i-elastic-text text="' + fileName + '" minLength="20"></sf-i-elastic-text></div>';
htmlStr += '<div class="d-flex align-center" part="upload-buttons-container">';
htmlStr += '<div class="mr-10 upload-status" part="upload-status">Analyzing</div><div class="mr-10 analyzing-loader"></div>';
htmlStr += (this.docType == "" || i > 0 ? "" : '<div class="mr-10 upload-status" part="doctype-badge">' + this.docType + '</div>');
htmlStr += '<div part="ext-badge" class="ext-badge mr-10">' + ext + '</div>';
htmlStr += '</div>';
}
else if (this.inputArr[i]["key"] != null) {
const fileName = this.inputArr[i]['file'].name;
const ext = this.inputArr[i]['file'].name.split(".")[this.inputArr[i]['file'].name.split(".").length - 1];
htmlStr += '<div class="mr-10"><sf-i-elastic-text text="' + fileName + '" minLength="20"></sf-i-elastic-text></div>';
htmlStr += '<div class="d-flex align-center" part="upload-buttons-container">';
htmlStr += '<div class="progress-number mr-10 upload-status" part="upload-status"></div>';
htmlStr += '<div class="mr-10 upload-status" part="upload-status">Upload Complete</div>';
htmlStr += '<div part="ext-badge" class="ext-badge mr-10">' + ext + '</div>';
htmlStr += (this.docType == "" || i > 0 ? "" : '<div class="mr-10 upload-status" part="doctype-badge">' + this.docType + '</div>');
if (this.inputArr[i]["delete"]) {
htmlStr += '<button id="button-delete-file-cancel-' + i + '" part="button-icon" class="mr-10 button-icon"><span class="material-icons">close</span></button>';
htmlStr += '<button id="button-delete-file-confirm-' + i + '" part="button-icon" class="button-icon"><span class="material-icons">delete</span><span class="material-icons">done</span></button>';
}
else {
console.log('delete button', this.extract.toLowerCase(), this.getExtractableExtensions().indexOf(ext));
// if(this.extract.toLowerCase() != "yes" && this.getExtractableExtensions().indexOf(ext) < 0){
if (this.extract.toLowerCase() != "yes") {
htmlStr += '<button id="button-delete-file-' + i + '" part="button-icon" class="mr-10 button-icon"><span class="material-icons">delete</span></button>';
}
else if (this.getExtractableExtensions().indexOf(ext) < 0) {
htmlStr += '<button id="button-delete-file-' + i + '" part="button-icon" class="mr-10 button-icon"><span class="material-icons">delete</span></button>';
}
htmlStr += '<button id="button-open-' + i + '" part="button-icon" class=""><span class="material-icons">open_in_new</span></button>';
}
htmlStr += '</div>';
}
else {
const fileName = this.inputArr[i]['file'].name;
const ext = this.inputArr[i]['file'].name.split(".")[this.inputArr[i]['file'].name.split(".").length - 1];