argos/dmp-frontend/src/app/core/services/file-transformer/file-transformer.service.ts

81 lines
2.8 KiB
TypeScript

import { Injectable } from '@angular/core';
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';
import { AuthService } from '../auth/auth.service';
import { RepositoryFileFormat } from '@app/core/model/file/file-format.model';
@Injectable()
export class FileTransformerService extends BaseService {
constructor(
private fileTransformerHttpService: FileTransformerHttpService,
private matomoService: MatomoService,
private fileUtils: FileUtils,
private authentication: AuthService,
) { super(); }
private _initialized: boolean = false;
private _loading: boolean = false;
private _availableFormats: RepositoryFileFormat[] = [];
get availableFormats(): RepositoryFileFormat[] {
if (!this.authentication.currentAccountIsAuthenticated()){
return;
}
// 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, repositoryId: string, format: string) {
this._loading = true;
this.fileTransformerHttpService.exportDmp(id, repositoryId, 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, repositoryId: string, format: string) {
this._loading = true;
this.fileTransformerHttpService.exportDescription(id, repositoryId, 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());
}
});
}
}