1 import { mapValues } from 'lodash-es'
2 import { firstValueFrom } from 'rxjs'
3 import { tap } from 'rxjs/operators'
4 import { Component, ElementRef, Inject, LOCALE_ID, ViewChild } from '@angular/core'
5 import { HooksService } from '@app/core'
6 import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'
7 import { logger } from '@root-helpers/logger'
8 import { videoRequiresAuth } from '@root-helpers/video'
9 import { objectKeysTyped, pick } from '@shared/core-utils'
10 import { VideoCaption, VideoFile, VideoPrivacy } from '@shared/models'
11 import { BytesPipe, NumberFormatterPipe, VideoDetails, VideoFileTokenService, VideoService } from '../shared-main'
13 type DownloadType = 'video' | 'subtitles'
14 type FileMetadata = { [key: string]: { label: string, value: string | number } }
17 selector: 'my-video-download',
18 templateUrl: './video-download.component.html',
19 styleUrls: [ './video-download.component.scss' ]
21 export class VideoDownloadComponent {
22 @ViewChild('modal', { static: true }) modal: ElementRef
24 downloadType: 'direct' | 'torrent' = 'direct'
26 resolutionId: number | string = -1
27 subtitleLanguageId: string
29 videoFileMetadataFormat: FileMetadata
30 videoFileMetadataVideoStream: FileMetadata | undefined
31 videoFileMetadataAudioStream: FileMetadata | undefined
33 isAdvancedCustomizationCollapsed = true
35 type: DownloadType = 'video'
37 videoFileToken: string
39 private activeModal: NgbModalRef
41 private bytesPipe: BytesPipe
42 private numbersPipe: NumberFormatterPipe
44 private video: VideoDetails
45 private videoCaptions: VideoCaption[]
48 @Inject(LOCALE_ID) private localeId: string,
49 private modalService: NgbModal,
50 private videoService: VideoService,
51 private videoFileTokenService: VideoFileTokenService,
52 private hooks: HooksService
54 this.bytesPipe = new BytesPipe()
55 this.numbersPipe = new NumberFormatterPipe(this.localeId)
59 return this.type === 'video'
61 : $localize`subtitles`
65 if (!this.video) return []
67 return this.video.getFiles()
71 if (!this.videoCaptions) return []
73 return this.videoCaptions
76 show (video: VideoDetails, videoCaptions?: VideoCaption[]) {
77 this.videoFileToken = undefined
80 this.videoCaptions = videoCaptions
82 this.activeModal = this.modalService.open(this.modal, { centered: true })
84 if (this.hasFiles()) {
85 this.onResolutionIdChange(this.getVideoFiles()[0].resolution.id)
88 if (this.hasCaptions()) {
89 this.subtitleLanguageId = this.videoCaptions[0].language.id
92 if (videoRequiresAuth(this.video)) {
93 this.videoFileTokenService.getVideoFileToken(this.video.uuid)
94 .subscribe(({ token }) => this.videoFileToken = token)
97 this.activeModal.shown.subscribe(() => {
98 this.hooks.runAction('action:modal.video-download.shown', 'common')
103 this.video = undefined
104 this.videoCaptions = undefined
108 window.location.assign(this.getLink())
110 this.activeModal.close()
114 return this.type === 'subtitles' && this.videoCaptions
115 ? this.getCaptionLink()
116 : this.getVideoFileLink()
119 async onResolutionIdChange (resolutionId: number) {
120 this.resolutionId = resolutionId
122 const videoFile = this.getVideoFile()
124 if (!videoFile.metadata) {
125 if (!videoFile.metadataUrl) return
127 await this.hydrateMetadataFromMetadataUrl(videoFile)
130 if (!videoFile.metadata) return
132 this.videoFileMetadataFormat = videoFile
133 ? this.getMetadataFormat(videoFile.metadata.format)
135 this.videoFileMetadataVideoStream = videoFile
136 ? this.getMetadataStream(videoFile.metadata.streams, 'video')
138 this.videoFileMetadataAudioStream = videoFile
139 ? this.getMetadataStream(videoFile.metadata.streams, 'audio')
143 onSubtitleIdChange (subtitleId: string) {
144 this.subtitleLanguageId = subtitleId
148 return this.getVideoFiles().length !== 0
152 const file = this.getVideoFiles()
153 .find(f => f.resolution.id === this.resolutionId)
156 logger.error(`Could not find file with resolution ${this.resolutionId}`)
163 getVideoFileLink () {
164 const file = this.getVideoFile()
167 const suffix = this.isConfidentialVideo()
168 ? '?videoFileToken=' + this.videoFileToken
171 switch (this.downloadType) {
173 return file.fileDownloadUrl + suffix
176 return file.torrentDownloadUrl + suffix
181 return this.getCaptions().length !== 0
185 const caption = this.getCaptions()
186 .find(c => c.language.id === this.subtitleLanguageId)
189 logger.error(`Cannot find caption ${this.subtitleLanguageId}`)
197 const caption = this.getCaption()
198 if (!caption) return ''
200 return window.location.origin + caption.captionPath
203 isConfidentialVideo () {
204 return this.video.privacy.id === VideoPrivacy.PRIVATE || this.video.privacy.id === VideoPrivacy.INTERNAL
207 switchToType (type: DownloadType) {
212 const file = this.getVideoFile()
213 if (!file) return undefined
218 private getMetadataFormat (format: any) {
219 const keyToTranslateFunction = {
220 encoder: (value: string) => ({ label: $localize`Encoder`, value }),
221 format_long_name: (value: string) => ({ label: $localize`Format name`, value }),
222 size: (value: number | string) => ({ label: $localize`Size`, value: this.bytesPipe.transform(+value, 2) }),
223 bit_rate: (value: number | string) => ({
224 label: $localize`Bitrate`,
225 value: `${this.numbersPipe.transform(+value)}bps`
230 const sanitizedFormat = Object.assign(format, format.tags)
231 delete sanitizedFormat.tags
234 pick(sanitizedFormat, objectKeysTyped(keyToTranslateFunction)),
235 (val: string, key: keyof typeof keyToTranslateFunction) => keyToTranslateFunction[key](val)
239 private getMetadataStream (streams: any[], type: 'video' | 'audio') {
240 const stream = streams.find(s => s.codec_type === type)
241 if (!stream) return undefined
243 let keyToTranslateFunction = {
244 codec_long_name: (value: string) => ({ label: $localize`Codec`, value }),
245 profile: (value: string) => ({ label: $localize`Profile`, value }),
246 bit_rate: (value: number | string) => ({
247 label: $localize`Bitrate`,
248 value: `${this.numbersPipe.transform(+value)}bps`
252 if (type === 'video') {
253 keyToTranslateFunction = Object.assign(keyToTranslateFunction, {
254 width: (value: string | number) => ({ label: $localize`Resolution`, value: `${value}x${stream.height}` }),
255 display_aspect_ratio: (value: string) => ({ label: $localize`Aspect ratio`, value }),
256 avg_frame_rate: (value: string) => ({ label: $localize`Average frame rate`, value }),
257 pix_fmt: (value: string) => ({ label: $localize`Pixel format`, value })
260 keyToTranslateFunction = Object.assign(keyToTranslateFunction, {
261 sample_rate: (value: string | number) => ({ label: $localize`Sample rate`, value }),
262 channel_layout: (value: string | number) => ({ label: $localize`Channel Layout`, value })
267 pick(stream, Object.keys(keyToTranslateFunction)),
268 (val: string, key: keyof typeof keyToTranslateFunction) => keyToTranslateFunction[key](val)
272 private hydrateMetadataFromMetadataUrl (file: VideoFile) {
273 const observable = this.videoService.getVideoFileMetadata(file.metadataUrl)
274 .pipe(tap(res => file.metadata = res))
276 return firstValueFrom(observable)