import { inject, Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import { API_CONFIG } from '../../../core/config/api-config'; import { AudiobookInfo, AudiobookProgress } from './audiobook.model'; import { AuthService } from '../../../shared/service/auth.service'; import { BookFileProgress } from '../../book/model/book.model'; import { QueryClient } from '@tanstack/angular-query-experimental'; import { patchBookFieldsInCache } from '../../book/service/book-query-cache'; @Injectable({ providedIn: 'root' }) export class AudiobookService { private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/audiobooks`; private readonly booksUrl = `${API_CONFIG.BASE_URL}/api/v1/books`; private http = inject(HttpClient); private authService = inject(AuthService); private queryClient = inject(QueryClient); getAudiobookInfo(bookId: number, bookType?: string): Observable { const params: Record = {}; if (bookType) { params['bookType'] = bookType; } return this.http.get(`${this.baseUrl}/${bookId}/info`, { params }); } getStreamUrl(bookId: number, trackIndex?: number): string { const token = this.authService.getInternalAccessToken(); let url = `${this.baseUrl}/${bookId}/stream?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`; if (trackIndex !== undefined && trackIndex !== null) { url += `&trackIndex=${trackIndex}`; } return url; } getTrackStreamUrl(bookId: number, trackIndex: number): string { const token = this.authService.getInternalAccessToken(); return `${this.baseUrl}/${bookId}/track/${trackIndex}/stream?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`; } getEmbeddedCoverUrl(bookId: number): string { const token = this.authService.getInternalAccessToken(); return `${this.baseUrl}/${bookId}/cover?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`; } saveProgress(bookId: number, progress: AudiobookProgress, bookFileId?: number): Observable { const body: {bookId: number; audiobookProgress: AudiobookProgress; fileProgress?: BookFileProgress} = { bookId, audiobookProgress: progress, }; if (bookFileId) { body.fileProgress = { bookFileId, positionData: progress.positionMs.toString(), positionHref: progress.trackIndex?.toString(), progressPercent: progress.percentage, }; } return this.http.post(`${this.booksUrl}/progress`, body).pipe( tap(() => { patchBookFieldsInCache(this.queryClient, [{bookId, fields: {audiobookProgress: progress}}]); }) ); } }