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 } from '@shared/core-utils/i18n'
9 import { ResultList, VideoCaption } from '@shared/models'
10 import { VideoCaptionEdit } from './video-caption-edit.model'
13 export class VideoCaptionService {
15 private authHttp: HttpClient,
16 private serverService: ServerService,
17 private restExtractor: RestExtractor
20 listCaptions (videoId: number | string): Observable<ResultList<VideoCaption>> {
21 return this.authHttp.get<ResultList<VideoCaption>>(VideoService.BASE_VIDEO_URL + videoId + '/captions')
23 switchMap(captionsResult => {
24 return this.serverService.getServerLocale()
25 .pipe(map(translations => ({ captionsResult, translations })))
27 map(({ captionsResult, translations }) => {
28 for (const c of captionsResult.data) {
29 c.language.label = peertubeTranslate(c.language.label, translations)
34 map(captionsResult => {
35 sortBy(captionsResult.data, 'language', 'label')
40 .pipe(catchError(res => this.restExtractor.handleError(res)))
43 removeCaption (videoId: number | string, language: string) {
44 return this.authHttp.delete(VideoService.BASE_VIDEO_URL + videoId + '/captions/' + language)
46 map(this.restExtractor.extractDataBool),
47 catchError(res => this.restExtractor.handleError(res))
51 addCaption (videoId: number | string, language: string, captionfile: File) {
52 const body = { captionfile }
53 const data = objectToFormData(body)
55 return this.authHttp.put(VideoService.BASE_VIDEO_URL + videoId + '/captions/' + language, data)
57 map(this.restExtractor.extractDataBool),
58 catchError(res => this.restExtractor.handleError(res))
62 updateCaptions (videoId: number | string, videoCaptions: VideoCaptionEdit[]) {
65 for (const videoCaption of videoCaptions) {
66 if (videoCaption.action === 'CREATE') {
67 obs = obs.pipe(switchMap(() => this.addCaption(videoId, videoCaption.language.id, videoCaption.captionfile)))
68 } else if (videoCaption.action === 'REMOVE') {
69 obs = obs.pipe(switchMap(() => this.removeCaption(videoId, videoCaption.language.id)))