import { Injectable } from '@angular/core'; import { FileFormat } from '@app/core/model/file/file-format.model'; import { BaseService } from '@common/base/base.service'; import { catchError, takeUntil } from 'rxjs/operators'; import { FileTransformerHttpService } from './file-transformer.http.service'; import { Guid } from '@common/types/guid'; import * as FileSaver from 'file-saver'; import { MatomoService } from '../matomo/matomo-service'; import { FileUtils } from '../utilities/file-utils.service'; @Injectable() export class FileTransformerService extends BaseService { constructor( private fileTransformerHttpService: FileTransformerHttpService, private matomoService: MatomoService, private fileUtils: FileUtils ) { super(); } private _initialized: boolean = false; private _loading: boolean = false; private _availableFormats: FileFormat[] = []; get availableFormats(): FileFormat[] { // console.log('availableFormats'); if (!this._initialized && !this._loading) this.init(); return this._availableFormats; } init() { this._loading = true; // console.log('init'); this.fileTransformerHttpService.getAvailableConfigurations().pipe(takeUntil(this._destroyed), catchError((error) => { this._loading = false; this._initialized = true; return []; })).subscribe(items => { this._availableFormats = items; this._loading = false; this._initialized = true; }); } exportDmp(id: Guid, format: string) { this._loading = true; this.fileTransformerHttpService.exportDmp(id, format).pipe(takeUntil(this._destroyed), catchError((error) => { this._loading = false; return null; })).subscribe(result => { if (result !== null) { const blob = new Blob([result.body], { type: 'application/octet-stream' }); const filename = this.fileUtils.getFilenameFromContentDispositionHeader(result.headers.get('Content-Disposition')); FileSaver.saveAs(blob, filename); this.matomoService.trackDownload('dmps', format, id.toString()); } }); } exportDescription(id: Guid, format: string) { this._loading = true; this.fileTransformerHttpService.exportDescription(id, format).pipe(takeUntil(this._destroyed), catchError((error) => { this._loading = false; return null; })).subscribe(result => { if (result !== null) { const blob = new Blob([result.body], { type: 'application/octet-stream' }); const filename = this.fileUtils.getFilenameFromContentDispositionHeader(result.headers.get('Content-Disposition')); FileSaver.saveAs(blob, filename); this.matomoService.trackDownload('descriptions', format, id.toString()); } }); } }