1 import { Observable, of } from 'rxjs'
2 import { catchError, map, switchMap } from 'rxjs/operators'
3 import { HttpClient } from '@angular/common/http'
4 import { Injectable } from '@angular/core'
5 import { RestExtractor, ServerService } from '@app/core'
6 import { objectToFormData, sortBy } from '@app/helpers'
7 import { VideoService } from '@app/shared/shared-main/video'
8 import { peertubeTranslate, ResultList, VideoCaption } from '@shared/models'
9 import { VideoCaptionEdit } from './video-caption-edit.model'
12 export class VideoCaptionService {
14 private authHttp: HttpClient,
15 private serverService: ServerService,
16 private restExtractor: RestExtractor
19 listCaptions (videoId: number | string): Observable<ResultList<VideoCaption>> {
20 return this.authHttp.get<ResultList<VideoCaption>>(VideoService.BASE_VIDEO_URL + videoId + '/captions')
22 switchMap(captionsResult => {
23 return this.serverService.getServerLocale()
24 .pipe(map(translations => ({ captionsResult, translations })))
26 map(({ captionsResult, translations }) => {
27 for (const c of captionsResult.data) {
28 c.language.label = peertubeTranslate(c.language.label, translations)
33 map(captionsResult => {
34 sortBy(captionsResult.data, 'language', 'label')
39 .pipe(catchError(res => this.restExtractor.handleError(res)))
42 removeCaption (videoId: number | string, language: string) {
43 return this.authHttp.delete(VideoService.BASE_VIDEO_URL + videoId + '/captions/' + language)
45 map(this.restExtractor.extractDataBool),
46 catchError(res => this.restExtractor.handleError(res))
50 addCaption (videoId: number | string, language: string, captionfile: File) {
51 const body = { captionfile }
52 const data = objectToFormData(body)
54 return this.authHttp.put(VideoService.BASE_VIDEO_URL + videoId + '/captions/' + language, data)
56 map(this.restExtractor.extractDataBool),
57 catchError(res => this.restExtractor.handleError(res))
61 updateCaptions (videoId: number | string, videoCaptions: VideoCaptionEdit[]) {
64 for (const videoCaption of videoCaptions) {
65 if (videoCaption.action === 'CREATE') {
66 obs = obs.pipe(switchMap(() => this.addCaption(videoId, videoCaption.language.id, videoCaption.captionfile)))
67 } else if (videoCaption.action === 'REMOVE') {
68 obs = obs.pipe(switchMap(() => this.removeCaption(videoId, videoCaption.language.id)))