UNPKG

ngx-academia-uniandes-library

Version:

This library is used for Academia-Uniandes system.

575 lines 30.4 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var file_info_model_1 = require("./file-info.model"); var forms_1 = require("@angular/forms"); var core_1 = require("@angular/core"); var ng2_file_upload_1 = require("ng2-file-upload"); var core_2 = require("@ngx-translate/core"); var platform_browser_1 = require("@angular/platform-browser"); var ng2_img_cropper_1 = require("ng2-img-cropper"); var common_1 = require("@angular/common"); var file_select_service_1 = require("../file-select/file-select/file-select.service"); var sweetalert2_1 = require("sweetalert2"); var FileInfoSelectComponent = /** @class */ (function (_super) { __extends(FileInfoSelectComponent, _super); function FileInfoSelectComponent(_formBuilder, cd, fileService, translate, sanitizer, document) { var _this = _super.call(this, {}) || this; _this._formBuilder = _formBuilder; _this.cd = cd; _this.fileService = fileService; _this.translate = translate; _this.sanitizer = sanitizer; _this.fileInfo = new file_info_model_1.FileInfoModel(); _this.fileSelectId = 0; _this.downloadFileList = []; _this.disableDownload = false; _this.disableUpload = false; _this.title = ""; _this.imageThumbnailHeight = 100; _this.otherParameters = []; _this.uploadServiceUrl = null; _this.downloadServiceUrl = null; _this.deleteServiceUrl = null; _this.downloadListServiceUrl = null; _this.maxFiles = 1; _this.cropperWidth = 500; _this.cropperHeight = 300; _this.cropperOutWidth = 500; _this.cropperOutHeight = 500; _this.extensionsList = []; _this.maxFileSize = 100000; _this.downloadOnly = false; _this.singleRequestUpload = false; //Events (All Syncronic for easier server url changing) _this.onFileUploadSuccess = new core_1.EventEmitter(false); _this.onFileUploadError = new core_1.EventEmitter(false); _this.onSingleRequestUploadSuccess = new core_1.EventEmitter(false); _this.onSingleRequestUploadError = new core_1.EventEmitter(false); _this.onFileDeleteSuccess = new core_1.EventEmitter(false); _this.onFileDeleteError = new core_1.EventEmitter(false); _this.onFileListUpdate = new core_1.EventEmitter(false); _this.uploaderState = 0; _this.isFileOvesized = false; _this.isFileQueueFull = false; _this.isFileInvalid = false; _this.cropperActive = false; _this.formFile = _this._formBuilder.group({ nameFileCtrl: ['', forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.maxLength(200)])], descriptionFileCtrl: ['', forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.maxLength(400)])], }); _this.cropperSettings = new ng2_img_cropper_1.CropperSettings(); _this.cropperSettings.width = _this.cropperOutWidth; _this.cropperSettings.height = _this.cropperOutHeight; _this.cropperSettings.croppedWidth = _this.cropperOutWidth; _this.cropperSettings.croppedHeight = _this.cropperOutHeight; _this.cropperSettings.canvasWidth = _this.cropperWidth; _this.cropperSettings.canvasHeight = _this.cropperHeight; _this.cropperSettings.noFileInput = true; _this.onAfterAddingFile = function (item) { if (_this.isFileAnImage(item)) { _this.setImageThmbFromFile(item); } if (!_this.isFileExtensionValid(item.file.name)) { _this.isFileInvalid = true; item.remove(); // Verify File Size } else if (item.file.size > _this.maxFileSize) { _this.isFileOvesized = true; item.remove(); //Verify File count } else if ((_this.queue.length + _this.downloadFileList.length) > _this.maxFiles) { _this.isFileQueueFull = true; item.remove(); } cd.detectChanges(); }; _this.onBeforeUploadItem = function (item) { cd.detectChanges(); }; _this.onCompleteAll = function () { _this.uploaderState = 1; cd.detectChanges(); }; _this.onCompleteItem = function (item) { cd.detectChanges(); }; _this.onSuccessItem = function (item, response) { _this.correctFileUpload(JSON.parse(response)); cd.detectChanges(); _this.switchUploadedToDownloaded(item); cd.detectChanges(); }; _this.onErrorItem = function (item, response) { _this.errorFileUpload(response); _this.uploaderState = 2; cd.detectChanges(); }; return _this; } Object.defineProperty(FileInfoSelectComponent.prototype, "getOtherParameters", { get: function () { return this.otherParameters; }, enumerable: true, configurable: true }); Object.defineProperty(FileInfoSelectComponent.prototype, "setOtherParameters", { set: function (value) { this.otherParameters = value; this.refreshUploaderOptions(); }, enumerable: true, configurable: true }); Object.defineProperty(FileInfoSelectComponent.prototype, "getUploadServiceUrl", { get: function () { return this.uploadServiceUrl; }, enumerable: true, configurable: true }); Object.defineProperty(FileInfoSelectComponent.prototype, "setUploadServiceUrl", { set: function (value) { this.uploadServiceUrl = value; this.refreshUploaderOptions(); }, enumerable: true, configurable: true }); Object.defineProperty(FileInfoSelectComponent.prototype, "getDownloadServiceUrl", { get: function () { return this.downloadServiceUrl; }, enumerable: true, configurable: true }); Object.defineProperty(FileInfoSelectComponent.prototype, "setDownloadServiceUrl", { set: function (value) { this.downloadServiceUrl = value; }, enumerable: true, configurable: true }); Object.defineProperty(FileInfoSelectComponent.prototype, "getDeleteServiceUrl", { get: function () { return this.deleteServiceUrl; }, enumerable: true, configurable: true }); Object.defineProperty(FileInfoSelectComponent.prototype, "setDeleteServiceUrl", { set: function (value) { this.deleteServiceUrl = value; }, enumerable: true, configurable: true }); Object.defineProperty(FileInfoSelectComponent.prototype, "getDownloadListServiceUrl", { get: function () { return this.downloadListServiceUrl; }, enumerable: true, configurable: true }); Object.defineProperty(FileInfoSelectComponent.prototype, "setDownloadListServiceUrl", { set: function (value) { this.downloadListServiceUrl = value; }, enumerable: true, configurable: true }); //========================= PRIVATE METHODS ========================= //========================= PRIVATE METHODS ========================= FileInfoSelectComponent.prototype.isFileAnImage = //========================= PRIVATE METHODS ========================= function (file) { var type = file.file.rawFile.type; if (type.toLowerCase().includes('image')) { return true; } return false; }; FileInfoSelectComponent.prototype.refreshUploaderOptions = function () { this.setOptions({ url: this.uploadServiceUrl, additionalParameter: this.otherParameters }); }; FileInfoSelectComponent.prototype.switchAllItemsToErrorSingleRequest = function (response) { this.queue.forEach(function (element) { element.isReady = false; element.isUploading = false; element.isUploaded = false; element.isSuccess = false; element.isCancel = false; element.isError = true; }); this.cd.detectChanges(); this.singleRequestUploadError(response); this.cd.detectChanges(); }; FileInfoSelectComponent.prototype.switchAllItemsToDownloadedSingleRequest = function (response) { this.queue = []; this.cd.detectChanges(); this.singleRequestUploadSuccess(response); this.cd.detectChanges(); this.getFileList(); }; FileInfoSelectComponent.prototype.switchUploadedToDownloaded = function (item) { item.remove(); this.getFileList(); }; FileInfoSelectComponent.prototype.getUploadProgress = function () { var uploaded = 0; this.queue.forEach(function (element) { if (element.isUploaded) { uploaded++; } }); return (uploaded / this.queue.length) * 100; }; FileInfoSelectComponent.prototype.openUploadDialog = function () { var event = new MouseEvent('click', { bubbles: false }); this.uplder.nativeElement.dispatchEvent(event); this.isFileOvesized = false; this.isFileQueueFull = false; this.isFileInvalid = false; }; FileInfoSelectComponent.prototype.isFileExtensionValid = function (filename) { var ext = filename.split('.').pop(); for (var i = 0; i < this.extensionsList.length; i++) { if (this.extensionsList[i].toLowerCase() === ext.toLowerCase()) { return true; } } return false; }; FileInfoSelectComponent.prototype.getExtensionsString = function () { var str = ""; var i = 0; this.extensionsList.forEach(function (element) { str += ((i == 0 ? "" : ", ") + element); i++; }); return str; }; //================== PUBLIC METHODS====================== //================== PUBLIC METHODS====================== FileInfoSelectComponent.prototype.correctFileUpload = //================== PUBLIC METHODS====================== function (data) { this.onFileUploadSuccess.emit(data); }; FileInfoSelectComponent.prototype.errorFileUpload = function (data) { this.onFileUploadError.emit(data); }; FileInfoSelectComponent.prototype.deleteFileSuccess = function (data) { this.onFileDeleteSuccess.emit(data); }; FileInfoSelectComponent.prototype.deleteFileError = function (data) { this.onFileDeleteError.emit(data); }; FileInfoSelectComponent.prototype.singleRequestUploadSuccess = function (data) { this.onSingleRequestUploadSuccess.emit({ data: data, fileInfo: this.fileInfo }); }; FileInfoSelectComponent.prototype.singleRequestUploadError = function (data) { this.onSingleRequestUploadError.emit(data); }; FileInfoSelectComponent.prototype.fileListUpdate = function (data) { this.onFileListUpdate.emit(data); }; FileInfoSelectComponent.prototype.resetFileStates = function () { this.queue.forEach(function (element) { element.isReady = true; element.isUploading = false; element.isUploaded = false; element.isSuccess = false; element.isCancel = false; element.isError = false; }); this.isFileOvesized = false; this.isFileQueueFull = false; this.isFileInvalid = false; }; FileInfoSelectComponent.prototype.removeAllPendingFiles = function () { this.queue = []; this.resetFileStates(); }; FileInfoSelectComponent.prototype.uploadFiles = function () { this.resetFileStates(); this.uploaderState = 0; if (this.singleRequestUpload) { this.uploadAllSingleRequest(); } else { this.uploadAll(); } }; FileInfoSelectComponent.prototype.ngOnInit = function () { this.setOptions({ url: this.uploadServiceUrl }); this.getFileList(); }; FileInfoSelectComponent.prototype.round = function (x, n) { return Math.round(x * Math.pow(10, n)) / Math.pow(10, n); }; //================= UPLOAD METHODS======================= //================= UPLOAD METHODS======================= FileInfoSelectComponent.prototype.uploadAllSingleRequest = //================= UPLOAD METHODS======================= function () { var _this = this; var xhr = new XMLHttpRequest(); var sendable = new FormData(); var fakeitem = null; this.onBuildItemForm(fakeitem, sendable); for (var _b = 0, _c = this.queue; _b < _c.length; _b++) { var item = _c[_b]; item.isReady = true; item.isUploading = true; item.isUploaded = false; item.isSuccess = false; item.isCancel = false; item.isError = false; item.progress = 0; if (typeof item._file.size !== 'number') { throw new TypeError('The file specified is no longer valid'); } sendable.append("files", item._file, item.file.name); } if (this.options.additionalParameter !== undefined) { Object.keys(this.options.additionalParameter).forEach(function (key) { sendable.append(key, _this.options.additionalParameter[key]); }); } xhr.onload = function (response) { var gist = (xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 ? 'Success' : 'Error'; if (gist == "Error") { _this.switchAllItemsToErrorSingleRequest(xhr.response); } else { _this.switchAllItemsToDownloadedSingleRequest(xhr.response); } }; xhr.onerror = function () { _this.onErrorItem(fakeitem, null, xhr.status, null); }; xhr.onabort = function () { _this.onErrorItem(fakeitem, null, xhr.status, null); }; xhr.open("POST", this.options.url, true); xhr.withCredentials = true; if (this.options.headers) { for (var _i = 0, _a = this.options.headers; _i < _a.length; _i++) { var header = _a[_i]; xhr.setRequestHeader(header.name, header.value); } } if (this.authToken) { xhr.setRequestHeader(this.authTokenHeader, this.authToken); } xhr.send(sendable); }; ; //=====================DOWNLOAD METHODS=========================== //=====================DOWNLOAD METHODS=========================== FileInfoSelectComponent.prototype.downloadFile = //=====================DOWNLOAD METHODS=========================== function (item) { var _this = this; if (this.downloadServiceUrl != null) { this.fileService.downloadFile(this.downloadServiceUrl, item).subscribe(function (success) { var a = document.createElement("a"); a.href = URL.createObjectURL(success); a.download = item.name; // start download a.click(); }, function (error) { sweetalert2_1.default({ type: 'error', title: _this.translate.instant('errorMessage'), text: _this.translate.instant("" + error.error) }); }); } }; //========================= DOWNLOAD LIST METHODS=================== //========================= DOWNLOAD LIST METHODS=================== FileInfoSelectComponent.prototype.getFileList = //========================= DOWNLOAD LIST METHODS=================== function () { var _this = this; if (this.downloadListServiceUrl != null) { this.downloadFileList = []; this.fileService.getDownloadFileList("" + this.downloadListServiceUrl).subscribe(function (success) { if (success != null) { if (success.files) { success.files.forEach(function (element) { _this.downloadFileList.push(element); }); } else { _this.downloadFileList.push(success); } } _this.fileListUpdate(success); _this.cd.detectChanges(); }, function (error) { sweetalert2_1.default({ type: 'error', title: _this.translate.instant('errorMessage'), text: _this.translate.instant(error.message) }); }); } }; //============================= DELETE METHODS ============================= //============================= DELETE METHODS ============================= FileInfoSelectComponent.prototype.deleteFile = //============================= DELETE METHODS ============================= function (item) { var _this = this; if (this.deleteServiceUrl != null) { var titleObs = this.translate.instant('areYouSure'); var textObs = this.translate.instant('noRevert'); var confirmButtonTextObs = this.translate.instant('yesDelete'); var declineButtonTextObs = this.translate.instant('cancel'); sweetalert2_1.default({ title: titleObs, text: textObs, type: 'warning', showCancelButton: true, confirmButtonText: confirmButtonTextObs, cancelButtonText: declineButtonTextObs }).then(function (result) { if (result.value) { _this.fileService.deleteFile(_this.deleteServiceUrl, item).subscribe(function (success) { _this.deleteFileSuccess(success); _this.cd.detectChanges(); _this.getFileList(); }, function (error) { _this.deleteFileError(error); sweetalert2_1.default({ type: 'error', title: _this.translate.instant('deleteErrorMessage'), text: _this.translate.instant(error.message) }); }); } }); } }; //================== IMAGE CROPPER =================== //================== IMAGE CROPPER =================== FileInfoSelectComponent.prototype.setImageThmbFromFile = //================== IMAGE CROPPER =================== function (item) { var _this = this; var idx = this.queue.indexOf(item); var nimage = new Image(); var file = item.file.rawFile; var myReader = new FileReader(); myReader.onloadend = function (loadEvent) { nimage.src = loadEvent.target.result; var imgThumb = document.getElementById("imgthfileselect" + _this.fileSelectId + "" + idx); imgThumb.setAttribute("src", nimage.src); }; myReader.readAsDataURL(file); }; FileInfoSelectComponent.prototype.cropImage = function () { var img = this.imgCropper.image; this.currentImage.file.rawFile = this.dataURLtoBlob(img.image); this.currentImage._file = this.dataURLtoBlob(img.image); this.setImageThmbFromFile(this.currentImage); this.cropperActive = false; }; FileInfoSelectComponent.prototype.openImageCropper = function (item) { var image = new Image(); var file = item.some; var reader = new FileReader(); var that = this; this.currentImage = item; reader.onloadend = function (loadEvent) { image.src = loadEvent.target.result; that.imgCropper.setImage(image); }; reader.readAsDataURL(file); this.cropperActive = true; }; //Tomado de https://stackoverflow.com/questions/28041840/convert-dataurl-to-file-using-javascript //Tomado de https://stackoverflow.com/questions/28041840/convert-dataurl-to-file-using-javascript FileInfoSelectComponent.prototype.dataURLtoBlob = //Tomado de https://stackoverflow.com/questions/28041840/convert-dataurl-to-file-using-javascript function (dataurl) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); }; FileInfoSelectComponent.prototype.closeImageCropper = function () { this.setImageThmbFromFile(this.currentImage); this.cropperActive = false; }; FileInfoSelectComponent.decorators = [ { type: core_1.Component, args: [{ selector: 'app-file-info-select', template: "\n <form class=\"form-container\" [formGroup]=\"formFile\">\n <div class=\"card\">\n <div class=\"card-body\">\n <div class=\"form-group\">\n <span class=\"red-text\">*</span>\n <label for=\"form-name\">{{'nameImage' | translate}}</label>\n <input type=\"text\" class=\"form-control\" [(ngModel)]=\"fileInfo.name\" id=\"form-name\" name=\"name\"\n placeholder=\"{{'nameImage' | translate}}\" formControlName=\"nameFileCtrl\" required>\n <p *ngIf=\"formFile.get('nameFileCtrl').hasError('maxlength') && \n formFile.get('nameFileCtrl').dirty\" class=\"validation-text\">\n {{ 'max200valuesValidation' | translate }}\n </p>\n </div>\n\n <div class=\"form-group\">\n <span class=\"red-text\">*</span>\n <label for=\"form-name\">\n {{'descriptionImage' | translate}}\n </label>\n <textarea rows=\"4\" class=\"form-control\" [(ngModel)]=\"fileInfo.description\" formControlName=\"descriptionFileCtrl\"\n placeholder=\"{{'descriptionImage' | translate }}\"></textarea>\n <p *ngIf=\"formFile.get('descriptionFileCtrl').hasError('maxlength') && \n formFile.get('descriptionFileCtrl').dirty\" class=\"validation-text\">\n {{ 'max400valuesValidation' | translate }}\n </p>\n </div>\n\n <div class=\"form-group\">\n <div class=\"cell-center-align\" *ngIf=\"!downloadOnly && queue.length == 0\">\n <input hidden type=\"file\" #uplder ng2FileSelect [uploader]=\"this\" multiple />\n <button type=\"button\" class=\"btn btn-primary btn-lg\" (click)=\"openUploadDialog()\">\n <i class=\"material-icons\">add</i>\n </button>\n </div>\n <div *ngIf=\"isFileOvesized || isFileQueueFull || isFileInvalid\" align=\"center\"\n class=\"alert alert-danger alert-borderless\" style=\"margin-top: 10px;\">\n <ul>\n <li *ngIf=\"isFileOvesized\">{{'maximumSizeExceeded' | translate}} </li>\n <li *ngIf=\"isFileQueueFull\">{{'queueFull' | translate}} </li>\n <li *ngIf=\"isFileInvalid\">{{'extensionInvalid' | translate}} </li>\n </ul>\n </div>\n </div>\n\n <div class=\"image-row-wrapper\">\n <ng-container *ngFor=\"let item of queue; let i = index\">\n <div *ngIf=\"isFileAnImage(item)\" class=\"file-row-img borders\">\n <div class=\"cell-center-align\">\n <img [id]=\"'imgthfileselect' + fileSelectId + '' + i\" src=\"\" class=\"imgThmb\"\n [height]=\"imageThumbnailHeight\" />\n </div>\n <div class=\"cell-center-align\">{{ item.file.name }}</div>\n <div class=\"cell-center-align\">{{ round(item.file.size / 1024, 1) }} KB</div>\n <div class=\"cell-center-align\">\n <span *ngIf=\"item.isCancel\">\n <i class=\"material-icons\">not_interested</i>\n </span>\n <span *ngIf=\"item.isError\">\n <i class=\"material-icons\" style=\"color: red;\">error</i>\n </span>\n <span *ngIf=\"!item.isSuccess && !item.isCancel && !item.isError && !item.isUploading\">\n <i class=\"material-icons\">hourglass_empty</i>\n </span>\n <div *ngIf=\"item.isUploading\" class=\"lds-fil\">\n <div></div>\n <div></div>\n <div></div>\n </div>\n </div>\n <div class=\"cell-center-align\">\n\n </div>\n <div class=\"cell-center-align\">\n <button type=\"button\" class=\"btn-default-transparent\" [disabled]=\"isUploading\" (click)=\"item.remove()\">\n <i class=\"material-icons\">clear</i>\n </button>\n </div>\n </div>\n </ng-container>\n </div>\n\n\n <div class=\"flex-container\" style=\"margin-top: 20px;\">\n <button type=\"button\" class=\"btn btn-primary btn-lg\" (click)=\"uploadFiles()\"\n [disabled]=\"!formFile.valid || !queue || queue.length == 0\">{{'uploadFileLab'|\n translate}}</button>\n </div>\n </div>\n\n </div>\n </form>\n ", styles: ["\n .red-text {\n color: red;\n }\n\n .validation-text {\n padding: 0;\n margin: 0;\n font-size: 12px;\n color: red;\n text-align: start;\n align-self: flex-start;\n }\n\n\n .image-row-wrapper {\n display: flex;\n flex-direction: column;\n gap: 16px;\n }\n\n .file-row-img {\n display: flex;\n flex-direction: row;\n align-items: center;\n gap: 16px;\n padding: 8px;\n border: 1px solid #ccc;\n border-radius: 6px;\n width: 100%;\n justify-content: space-between;\n }\n\n\n .flex-container {\n display: flex;\n justify-content: center;\n align-items: center;\n }\n "] },] }, ]; /** @nocollapse */ FileInfoSelectComponent.ctorParameters = function () { return [ { type: forms_1.FormBuilder, }, { type: core_1.ChangeDetectorRef, }, { type: file_select_service_1.FileSelectService, }, { type: core_2.TranslateService, }, { type: platform_browser_1.DomSanitizer, }, { type: undefined, decorators: [{ type: core_1.Inject, args: [common_1.DOCUMENT,] },] }, ]; }; FileInfoSelectComponent.propDecorators = { "fileSelectId": [{ type: core_1.Input },], "downloadFileList": [{ type: core_1.Input },], "disableDownload": [{ type: core_1.Input },], "disableUpload": [{ type: core_1.Input },], "title": [{ type: core_1.Input },], "imageThumbnailHeight": [{ type: core_1.Input },], "setOtherParameters": [{ type: core_1.Input, args: ['otherParameters',] },], "setUploadServiceUrl": [{ type: core_1.Input, args: ['uploadServiceUrl',] },], "setDownloadServiceUrl": [{ type: core_1.Input, args: ['downloadServiceUrl',] },], "setDeleteServiceUrl": [{ type: core_1.Input, args: ['deleteServiceUrl',] },], "setDownloadListServiceUrl": [{ type: core_1.Input, args: ['downloadListServiceUrl',] },], "maxFiles": [{ type: core_1.Input },], "cropperWidth": [{ type: core_1.Input },], "cropperHeight": [{ type: core_1.Input },], "cropperOutWidth": [{ type: core_1.Input },], "cropperOutHeight": [{ type: core_1.Input },], "extensionsList": [{ type: core_1.Input },], "maxFileSize": [{ type: core_1.Input },], "downloadOnly": [{ type: core_1.Input },], "singleRequestUpload": [{ type: core_1.Input },], "onFileUploadSuccess": [{ type: core_1.Output },], "onFileUploadError": [{ type: core_1.Output },], "onSingleRequestUploadSuccess": [{ type: core_1.Output },], "onSingleRequestUploadError": [{ type: core_1.Output },], "onFileDeleteSuccess": [{ type: core_1.Output },], "onFileDeleteError": [{ type: core_1.Output },], "onFileListUpdate": [{ type: core_1.Output },], "uplder": [{ type: core_1.ViewChild, args: ["uplder",] },], "imgCropper": [{ type: core_1.ViewChild, args: ['imgCropper',] },], }; return FileInfoSelectComponent; }(ng2_file_upload_1.FileUploader)); exports.FileInfoSelectComponent = FileInfoSelectComponent; //# sourceMappingURL=file-info-select.component.js.map