fix(download): stream book downloads instead of buffering in browser (#1718)
This commit is contained in:
@@ -219,6 +219,23 @@ public class SecurityConfig {
|
|||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@Order(8)
|
@Order(8)
|
||||||
|
public SecurityFilterChain bookDownloadSecurityChain(HttpSecurity http, QueryParameterJwtFilter queryParameterJwtFilter) throws Exception {
|
||||||
|
http
|
||||||
|
.securityMatcher("/api/v1/books/*/download", "/api/v1/books/*/download-all", "/api/v1/books/*/files/*/download")
|
||||||
|
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||||
|
.csrf(AbstractHttpConfigurer::disable)
|
||||||
|
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||||
|
.authorizeHttpRequests(auth -> auth
|
||||||
|
.anyRequest().permitAll()
|
||||||
|
)
|
||||||
|
.addFilterBefore(queryParameterJwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||||
|
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||||
|
.addFilterAfter(authenticationCheckFilter, UsernamePasswordAuthenticationFilter.class);
|
||||||
|
return http.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@Order(9)
|
||||||
public SecurityFilterChain wsSecurityChain(HttpSecurity http) throws Exception {
|
public SecurityFilterChain wsSecurityChain(HttpSecurity http) throws Exception {
|
||||||
http
|
http
|
||||||
.securityMatcher("/ws/**")
|
.securityMatcher("/ws/**")
|
||||||
@@ -238,7 +255,7 @@ public class SecurityConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@Order(9)
|
@Order(10)
|
||||||
public SecurityFilterChain jwtApiSecurityChain(HttpSecurity http) throws Exception {
|
public SecurityFilterChain jwtApiSecurityChain(HttpSecurity http) throws Exception {
|
||||||
var parser = new PathPatternParser();
|
var parser = new PathPatternParser();
|
||||||
final List<PathPattern> matchPatterns = Stream.of(
|
final List<PathPattern> matchPatterns = Stream.of(
|
||||||
@@ -289,7 +306,7 @@ public class SecurityConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@Order(10)
|
@Order(11)
|
||||||
public SecurityFilterChain staticResourcesSecurityChain(HttpSecurity http) throws Exception {
|
public SecurityFilterChain staticResourcesSecurityChain(HttpSecurity http) throws Exception {
|
||||||
http
|
http
|
||||||
.csrf(AbstractHttpConfigurer::disable)
|
.csrf(AbstractHttpConfigurer::disable)
|
||||||
|
|||||||
@@ -1,135 +1,85 @@
|
|||||||
import {HttpHeaders, provideHttpClient} from '@angular/common/http';
|
|
||||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
|
||||||
import {TestBed} from '@angular/core/testing';
|
import {TestBed} from '@angular/core/testing';
|
||||||
|
import {of, throwError} from 'rxjs';
|
||||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
|
||||||
import {FileDownloadService} from './file-download.service';
|
import {FileDownloadService} from './file-download.service';
|
||||||
|
import {AuthService} from './auth.service';
|
||||||
|
import {API_CONFIG} from '../../core/config/api-config';
|
||||||
|
|
||||||
describe('FileDownloadService', () => {
|
describe('FileDownloadService', () => {
|
||||||
|
const apiUrl = `${API_CONFIG.BASE_URL}/api/v1/books/1/download`;
|
||||||
let service: FileDownloadService;
|
let service: FileDownloadService;
|
||||||
let httpTestingController: HttpTestingController;
|
let ensureAccessToken: ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
|
ensureAccessToken = vi.fn().mockReturnValue(of('tok'));
|
||||||
|
|
||||||
TestBed.resetTestingModule();
|
TestBed.resetTestingModule();
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
provideHttpClient(),
|
|
||||||
provideHttpClientTesting(),
|
|
||||||
FileDownloadService,
|
FileDownloadService,
|
||||||
|
{provide: AuthService, useValue: {ensureAccessToken}},
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|
||||||
service = TestBed.inject(FileDownloadService);
|
service = TestBed.inject(FileDownloadService);
|
||||||
httpTestingController = TestBed.inject(HttpTestingController);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
httpTestingController.verify();
|
vi.restoreAllMocks();
|
||||||
TestBed.resetTestingModule();
|
TestBed.resetTestingModule();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('downloads a blob', () => {
|
function stubAnchor() {
|
||||||
const click = vi.fn();
|
const click = vi.fn();
|
||||||
const anchor = {href: '', download: '', click} as unknown as HTMLAnchorElement;
|
const anchor = {href: '', download: '', click} as unknown as HTMLAnchorElement;
|
||||||
const createElementSpy = vi.spyOn(document, 'createElement').mockReturnValue(anchor);
|
vi.spyOn(document, 'createElement').mockReturnValue(anchor);
|
||||||
const createObjectUrlSpy = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:download');
|
return {anchor, click};
|
||||||
const revokeObjectUrlSpy = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
|
}
|
||||||
|
|
||||||
service.downloadFile('/files/1', 'fallback.epub');
|
it('navigates to the download url with a fresh access token appended', () => {
|
||||||
|
const {anchor, click} = stubAnchor();
|
||||||
|
|
||||||
const request = httpTestingController.expectOne('/files/1');
|
service.downloadFile(apiUrl, 'book.epub');
|
||||||
expect(request.request.method).toBe('GET');
|
|
||||||
expect(request.request.responseType).toBe('blob');
|
|
||||||
request.flush(new Blob(['content']), {
|
|
||||||
headers: new HttpHeaders({
|
|
||||||
'Content-Disposition': "attachment; filename*=UTF-8''server%20name.epub",
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(createElementSpy).toHaveBeenCalledWith('a');
|
expect(ensureAccessToken).toHaveBeenCalledOnce();
|
||||||
expect(createObjectUrlSpy).toHaveBeenCalled();
|
expect(anchor.href).toBe(`${apiUrl}?token=tok`);
|
||||||
|
expect(anchor.download).toBe('book.epub');
|
||||||
expect(click).toHaveBeenCalledOnce();
|
expect(click).toHaveBeenCalledOnce();
|
||||||
expect(revokeObjectUrlSpy).toHaveBeenCalledWith('blob:download');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('downloads using the utf-8-only filename from the response header', () => {
|
it('uses & as the separator when the url already has a query string', () => {
|
||||||
const click = vi.fn();
|
const {anchor} = stubAnchor();
|
||||||
const anchor = {href: '', download: '', click} as unknown as HTMLAnchorElement;
|
|
||||||
vi.spyOn(document, 'createElement').mockReturnValue(anchor);
|
|
||||||
|
|
||||||
service.downloadFile('/files/1', 'fallback.epub');
|
service.downloadFile(`${apiUrl}?foo=bar`, 'book.epub');
|
||||||
|
|
||||||
const request = httpTestingController.expectOne('/files/1');
|
expect(anchor.href).toBe(`${apiUrl}?foo=bar&token=tok`);
|
||||||
request.flush(new Blob(['content']), {
|
|
||||||
headers: new HttpHeaders({
|
|
||||||
'Content-Disposition': "attachment; filename*=UTF-8''server%20name.epub",
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(anchor.download).toBe('server name.epub');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('downloads a blob using the ascii filename from the response header', () => {
|
it('url-encodes the token', () => {
|
||||||
const click = vi.fn();
|
ensureAccessToken.mockReturnValue(of('a b/c+d'));
|
||||||
const anchor = {href: '', download: '', click} as unknown as HTMLAnchorElement;
|
const {anchor} = stubAnchor();
|
||||||
vi.spyOn(document, 'createElement').mockReturnValue(anchor);
|
|
||||||
|
|
||||||
service.downloadFile('/files/1', 'fallback.epub');
|
service.downloadFile(apiUrl, 'book.epub');
|
||||||
|
|
||||||
const request = httpTestingController.expectOne('/files/1');
|
expect(anchor.href).toBe(`${apiUrl}?token=a%20b%2Fc%2Bd`);
|
||||||
request.flush(new Blob(['content']), {
|
|
||||||
headers: new HttpHeaders({
|
|
||||||
'Content-Disposition': "attachment; filename=\"server name.epub\"",
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(anchor.download).toBe('server name.epub');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('downloads a blob using the unquoted ascii filename from the response header', () => {
|
it('does not append the token to a non-API (cross-origin) url', () => {
|
||||||
const click = vi.fn();
|
const {anchor, click} = stubAnchor();
|
||||||
const anchor = {href: '', download: '', click} as unknown as HTMLAnchorElement;
|
|
||||||
vi.spyOn(document, 'createElement').mockReturnValue(anchor);
|
|
||||||
|
|
||||||
service.downloadFile('/files/1', 'fallback.epub');
|
service.downloadFile('https://example.com/evil', 'book.epub');
|
||||||
|
|
||||||
const request = httpTestingController.expectOne('/files/1');
|
expect(anchor.href).toBe('https://example.com/evil');
|
||||||
request.flush(new Blob(['content']), {
|
expect(click).toHaveBeenCalledOnce();
|
||||||
headers: new HttpHeaders({
|
|
||||||
'Content-Disposition': "attachment; filename=server_name.epub",
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(anchor.download).toBe('server_name.epub');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('downloads a blob using the both utf-8 and ascii from the response header', () => {
|
it('does not start a download when the token refresh fails', () => {
|
||||||
const click = vi.fn();
|
ensureAccessToken.mockReturnValue(throwError(() => new Error('refresh failed')));
|
||||||
const anchor = {href: '', download: '', click} as unknown as HTMLAnchorElement;
|
const createElement = vi.spyOn(document, 'createElement');
|
||||||
vi.spyOn(document, 'createElement').mockReturnValue(anchor);
|
|
||||||
|
|
||||||
service.downloadFile('/files/1', 'fallback.epub');
|
service.downloadFile(apiUrl, 'book.epub');
|
||||||
|
|
||||||
const request = httpTestingController.expectOne('/files/1');
|
expect(createElement).not.toHaveBeenCalled();
|
||||||
request.flush(new Blob(['content']), {
|
|
||||||
headers: new HttpHeaders({
|
|
||||||
'Content-Disposition': "attachment; filename=\"server name.epub\"; filename*=UTF-8''server%20name.epub",
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(anchor.download).toBe('server name.epub');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('falls back to the provided filename when the response has no content-disposition header', () => {
|
|
||||||
const click = vi.fn();
|
|
||||||
const anchor = {href: '', download: '', click} as unknown as HTMLAnchorElement;
|
|
||||||
vi.spyOn(document, 'createElement').mockReturnValue(anchor);
|
|
||||||
|
|
||||||
service.downloadFile('/files/2', 'fallback.epub');
|
|
||||||
|
|
||||||
const request = httpTestingController.expectOne('/files/2');
|
|
||||||
request.flush(new Blob(['content']));
|
|
||||||
|
|
||||||
expect(anchor.download).toBe('fallback.epub');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,41 +1,33 @@
|
|||||||
import {inject, Injectable} from '@angular/core';
|
import {inject, Injectable} from '@angular/core';
|
||||||
import {HttpClient} from '@angular/common/http';
|
import {DOCUMENT} from '@angular/common';
|
||||||
|
import {AuthService} from './auth.service';
|
||||||
|
import {API_CONFIG} from '../../core/config/api-config';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root'
|
providedIn: 'root'
|
||||||
})
|
})
|
||||||
export class FileDownloadService {
|
export class FileDownloadService {
|
||||||
private http = inject(HttpClient);
|
private readonly document = inject(DOCUMENT);
|
||||||
|
private authService = inject(AuthService);
|
||||||
|
|
||||||
downloadFile(url: string, filename: string): void {
|
downloadFile(url: string, filename: string): void {
|
||||||
this.http.get(url, {responseType: 'blob', observe: 'response'}).subscribe(response => {
|
this.authService.ensureAccessToken().subscribe({
|
||||||
const blob = response.body;
|
next: token => this.triggerDownload(url, filename, token),
|
||||||
if (!blob) return;
|
error: () => undefined
|
||||||
|
|
||||||
const resolvedFilename = this.extractFilename(response.headers.get('Content-Disposition')) ?? filename;
|
|
||||||
const objectUrl = URL.createObjectURL(blob);
|
|
||||||
const link = document.createElement('a');
|
|
||||||
link.href = objectUrl;
|
|
||||||
link.download = resolvedFilename;
|
|
||||||
link.click();
|
|
||||||
URL.revokeObjectURL(objectUrl);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private extractFilename(contentDisposition: string | null): string | null {
|
private triggerDownload(url: string, filename: string, token: string): void {
|
||||||
if (!contentDisposition) return null;
|
const link = this.document.createElement('a');
|
||||||
const utf8Match = contentDisposition.match(/filename\*=UTF-8''([\w%\-.]+)/i);
|
link.href = this.appendToken(url, token);
|
||||||
if (utf8Match) {
|
link.download = filename;
|
||||||
try {
|
link.click();
|
||||||
return decodeURIComponent(utf8Match[1]);
|
}
|
||||||
} catch {
|
|
||||||
// Do nothing in this case and fall back to the ascii filename.
|
private appendToken(url: string, token: string): string {
|
||||||
}
|
if (!url.startsWith(`${API_CONFIG.BASE_URL}/api/`)) {
|
||||||
|
return url;
|
||||||
}
|
}
|
||||||
const match = contentDisposition.match(/filename=(?:"([^"]+)"|([^"; ]+))/i)
|
return `${url}${url.includes('?') ? '&' : '?'}token=${encodeURIComponent(token)}`;
|
||||||
if (match) {
|
|
||||||
return match[1] ?? match[2];
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user