1 import { mapValues, pick } 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 { VideoCaption, VideoFile, VideoPrivacy } from '@shared/models'
10 import { BytesPipe, NumberFormatterPipe, VideoDetails, VideoFileTokenService, VideoService } from '../shared-main'
12 type DownloadType = 'video' | 'subtitles'
13 type FileMetadata = { [key: string]: { label: string, value: string } }
16 selector: 'my-video-download',
17 templateUrl: './video-download.component.html',
18 styleUrls: [ './video-download.component.scss' ]
20 export class VideoDownloadComponent {
21 @ViewChild('modal', { static: true }) modal: ElementRef
23 downloadType: 'direct' | 'torrent' = 'direct'
25 resolutionId: number | string = -1
26 subtitleLanguageId: string
28 videoFileMetadataFormat: FileMetadata
29 videoFileMetadataVideoStream: FileMetadata | undefined
30 videoFileMetadataAudioStream: FileMetadata | undefined
32 isAdvancedCustomizationCollapsed = true
34 type: DownloadType = 'video'
36 videoFileToken: string
38 private activeModal: NgbModalRef
40 private bytesPipe: BytesPipe
41 private numbersPipe: NumberFormatterPipe
43 private video: VideoDetails
44 private videoCaptions: VideoCaption[]
47 @Inject(LOCALE_ID) private localeId: string,
48 private modalService: NgbModal,
49 private videoService: VideoService,
50 private videoFileTokenService: VideoFileTokenService,
51 private hooks: HooksService
53 this.bytesPipe = new BytesPipe()
54 this.numbersPipe = new NumberFormatterPipe(this.localeId)
58 return this.type === 'video'
60 : $localize`subtitles`
64 if (!this.video) return []
66 return this.video.getFiles()
70 if (!this.videoCaptions) return []
72 return this.videoCaptions
75 show (video: VideoDetails, videoCaptions?: VideoCaption[]) {
76 this.videoFileToken = undefined
79 this.videoCaptions = videoCaptions
81 this.activeModal = this.modalService.open(this.modal, { centered: true })
83 if (this.hasFiles()) {
84 this.onResolutionIdChange(this.getVideoFiles()[0].resolution.id)
87 if (this.hasCaptions()) {
88 this.subtitleLanguageId = this.videoCaptions[0].language.id
91 if (videoRequiresAuth(this.video)) {
92 this.videoFileTokenService.getVideoFileToken(this.video.uuid)
93 .subscribe(({ token }) => this.videoFileToken = token)
96 this.activeModal.shown.subscribe(() => {
97 this.hooks.runAction('action:modal.video-download.shown', 'common')
102 this.video = undefined
103 this.videoCaptions = undefined
107 window.location.assign(this.getLink())
109 this.activeModal.close()
113 return this.type === 'subtitles' && this.videoCaptions
114 ? this.getCaptionLink()
115 : this.getVideoFileLink()
118 async onResolutionIdChange (resolutionId: number) {
119 this.resolutionId = resolutionId
121 const videoFile = this.getVideoFile()
123 if (!videoFile.metadata) {
124 if (!videoFile.metadataUrl) return
126 await this.hydrateMetadataFromMetadataUrl(videoFile)
129 if (!videoFile.metadata) return
131 this.videoFileMetadataFormat = videoFile
132 ? this.getMetadataFormat(videoFile.metadata.format)
134 this.videoFileMetadataVideoStream = videoFile
135 ? this.getMetadataStream(videoFile.metadata.streams, 'video')
137 this.videoFileMetadataAudioStream = videoFile
138 ? this.getMetadataStream(videoFile.metadata.streams, 'audio')
142 onSubtitleIdChange (subtitleId: string) {
143 this.subtitleLanguageId = subtitleId
147 return this.getVideoFiles().length !== 0
151 const file = this.getVideoFiles()
152 .find(f => f.resolution.id === this.resolutionId)
155 logger.error(`Could not find file with resolution ${this.resolutionId}`)
162 getVideoFileLink () {
163 const file = this.getVideoFile()
166 const suffix = this.isConfidentialVideo()
167 ? '?videoFileToken=' + this.videoFileToken
170 switch (this.downloadType) {
172 return file.fileDownloadUrl + suffix
175 return file.torrentDownloadUrl + suffix
180 return this.getCaptions().length !== 0
184 const caption = this.getCaptions()
185 .find(c => c.language.id === this.subtitleLanguageId)
188 logger.error(`Cannot find caption ${this.subtitleLanguageId}`)
196 const caption = this.getCaption()
197 if (!caption) return ''
199 return window.location.origin + caption.captionPath
202 isConfidentialVideo () {
203 return this.video.privacy.id === VideoPrivacy.PRIVATE || this.video.privacy.id === VideoPrivacy.INTERNAL
206 switchToType (type: DownloadType) {
211 const file = this.getVideoFile()
212 if (!file) return undefined
217 private getMetadataFormat (format: any) {
218 const keyToTranslateFunction = {
219 encoder: (value: string) => ({ label: $localize`Encoder`, value }),
220 format_long_name: (value: string) => ({ label: $localize`Format name`, value }),
221 size: (value: number) => ({ label: $localize`Size`, value: this.bytesPipe.transform(value, 2) }),
222 bit_rate: (value: number) => ({
223 label: $localize`Bitrate`,
224 value: `${this.numbersPipe.transform(value)}bps`
229 const sanitizedFormat = Object.assign(format, format.tags)
230 delete sanitizedFormat.tags
233 pick(sanitizedFormat, Object.keys(keyToTranslateFunction)),
234 (val, key) => keyToTranslateFunction[key](val)
238 private getMetadataStream (streams: any[], type: 'video' | 'audio') {
239 const stream = streams.find(s => s.codec_type === type)
240 if (!stream) return undefined
242 let keyToTranslateFunction = {
243 codec_long_name: (value: string) => ({ label: $localize`Codec`, value }),
244 profile: (value: string) => ({ label: $localize`Profile`, value }),
245 bit_rate: (value: number) => ({
246 label: $localize`Bitrate`,
247 value: `${this.numbersPipe.transform(value)}bps`
251 if (type === 'video') {
252 keyToTranslateFunction = Object.assign(keyToTranslateFunction, {
253 width: (value: number) => ({ label: $localize`Resolution`, value: `${value}x${stream.height}` }),
254 display_aspect_ratio: (value: string) => ({ label: $localize`Aspect ratio`, value }),
255 avg_frame_rate: (value: string) => ({ label: $localize`Average frame rate`, value }),
256 pix_fmt: (value: string) => ({ label: $localize`Pixel format`, value })
259 keyToTranslateFunction = Object.assign(keyToTranslateFunction, {
260 sample_rate: (value: number) => ({ label: $localize`Sample rate`, value }),
261 channel_layout: (value: number) => ({ label: $localize`Channel Layout`, value })
266 pick(stream, Object.keys(keyToTranslateFunction)),
267 (val, key) => keyToTranslateFunction[key](val)
271 private hydrateMetadataFromMetadataUrl (file: VideoFile) {
272 const observable = this.videoService.getVideoFileMetadata(file.metadataUrl)
273 .pipe(tap(res => file.metadata = res))
275 return firstValueFrom(observable)