Skip to content

Commit

Permalink
feat: original file download (DEV-4401)
Browse files Browse the repository at this point in the history
  • Loading branch information
irmastnt committed Dec 2, 2024
1 parent 96c7a61 commit 8d379ca
Showing 1 changed file with 24 additions and 12 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { HttpClient } from '@angular/common/http';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {
ReadArchiveFileValue,
Expand Down Expand Up @@ -46,6 +46,11 @@ export class RepresentationService {
return this._http.get<FileInfo>(url);
}

getIngestFileUrl(projectShort: string, assetId: string): string {
const url = `${this._appConfigService.dspIngestConfig.url}/projects/${projectShort}/assets/${assetId}`;
return url;
}

getAttachedProject(parentResource: ReadResource): ReadProject | undefined {
const attachedProjects = this._store.selectSnapshot(ResourceSelectors.attachedProjects);
return this.getParentResourceAttachedProject(attachedProjects, parentResource);
Expand Down Expand Up @@ -79,32 +84,39 @@ export class RepresentationService {
throw new AppError('Project is not present');
}

this.getIiifFileInfo(fileValue.filename, attachedProject.shortcode)
.pipe(take(1))
.subscribe(response => {
this.downloadFile(fileValue.fileUrl, response.originalFilename, this.userCanView(fileValue));
});
const assetId = fileValue.filename.split('.')[0] || '';
const ingestFileUrl = this.getIngestFileUrl(attachedProject.shortcode, assetId);
this.downloadFile(ingestFileUrl, this.userCanView(fileValue));
}

private downloadFile(url: string, originalFileName?: string, userCanView = true) {
private downloadFile(url: string, userCanView = true) {
let headers = {};
const isLoggedIn = this._store.selectSnapshot(UserSelectors.isLoggedIn);
const withCredentials = isLoggedIn && userCanView;
if (withCredentials) {
const authToken = this._accessTokenService.getAccessToken();
headers = { Authorization: `Bearer ${authToken}` };
headers = {
Authorization: `Bearer ${authToken}`,
};
}

this._http
.get(url, {
.get(userCanView ? `${url}/original` : url, {
responseType: 'blob',
withCredentials,
headers,
observe: 'response',
})
.pipe(take(1))
.subscribe(res => {
.subscribe((res: HttpResponse<Blob>) => {
const contentDisposition = res.headers.get('content-disposition');
const fileNameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = fileNameRegex.exec(contentDisposition || '');
const fileName =
contentDisposition && matches != null && matches[1] ? matches[1].replace(/['"]/g, '') : url.split('/').pop()!;
const a = document.createElement('a');
a.href = window.URL.createObjectURL(res);
a.download = originalFileName || url.split('/').pop()!;
a.href = window.URL.createObjectURL(res.body!);
a.download = fileName;
a.click();
window.URL.revokeObjectURL(a.href);
});
Expand Down

0 comments on commit 8d379ca

Please sign in to comment.