]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-video-miniature/video-download.component.ts
Bumped to version v5.2.1
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-video-miniature / video-download.component.ts
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'
12
13 type DownloadType = 'video' | 'subtitles'
14 type FileMetadata = { [key: string]: { label: string, value: string | number } }
15
16 @Component({
17 selector: 'my-video-download',
18 templateUrl: './video-download.component.html',
19 styleUrls: [ './video-download.component.scss' ]
20 })
21 export class VideoDownloadComponent {
22 @ViewChild('modal', { static: true }) modal: ElementRef
23
24 downloadType: 'direct' | 'torrent' = 'direct'
25
26 resolutionId: number | string = -1
27 subtitleLanguageId: string
28
29 videoFileMetadataFormat: FileMetadata
30 videoFileMetadataVideoStream: FileMetadata | undefined
31 videoFileMetadataAudioStream: FileMetadata | undefined
32
33 isAdvancedCustomizationCollapsed = true
34
35 type: DownloadType = 'video'
36
37 videoFileToken: string
38
39 private activeModal: NgbModalRef
40
41 private bytesPipe: BytesPipe
42 private numbersPipe: NumberFormatterPipe
43
44 private video: VideoDetails
45 private videoCaptions: VideoCaption[]
46
47 constructor (
48 @Inject(LOCALE_ID) private localeId: string,
49 private modalService: NgbModal,
50 private videoService: VideoService,
51 private videoFileTokenService: VideoFileTokenService,
52 private hooks: HooksService
53 ) {
54 this.bytesPipe = new BytesPipe()
55 this.numbersPipe = new NumberFormatterPipe(this.localeId)
56 }
57
58 get typeText () {
59 return this.type === 'video'
60 ? $localize`video`
61 : $localize`subtitles`
62 }
63
64 getVideoFiles () {
65 if (!this.video) return []
66
67 return this.video.getFiles()
68 }
69
70 getCaptions () {
71 if (!this.videoCaptions) return []
72
73 return this.videoCaptions
74 }
75
76 show (video: VideoDetails, videoCaptions?: VideoCaption[]) {
77 this.videoFileToken = undefined
78
79 this.video = video
80 this.videoCaptions = videoCaptions
81
82 this.activeModal = this.modalService.open(this.modal, { centered: true })
83
84 if (this.hasFiles()) {
85 this.onResolutionIdChange(this.getVideoFiles()[0].resolution.id)
86 }
87
88 if (this.hasCaptions()) {
89 this.subtitleLanguageId = this.videoCaptions[0].language.id
90 }
91
92 if (videoRequiresAuth(this.video)) {
93 this.videoFileTokenService.getVideoFileToken(this.video.uuid)
94 .subscribe(({ token }) => this.videoFileToken = token)
95 }
96
97 this.activeModal.shown.subscribe(() => {
98 this.hooks.runAction('action:modal.video-download.shown', 'common')
99 })
100 }
101
102 onClose () {
103 this.video = undefined
104 this.videoCaptions = undefined
105 }
106
107 download () {
108 window.location.assign(this.getLink())
109
110 this.activeModal.close()
111 }
112
113 getLink () {
114 return this.type === 'subtitles' && this.videoCaptions
115 ? this.getCaptionLink()
116 : this.getVideoFileLink()
117 }
118
119 async onResolutionIdChange (resolutionId: number) {
120 this.resolutionId = resolutionId
121
122 const videoFile = this.getVideoFile()
123
124 if (!videoFile.metadata) {
125 if (!videoFile.metadataUrl) return
126
127 await this.hydrateMetadataFromMetadataUrl(videoFile)
128 }
129
130 if (!videoFile.metadata) return
131
132 this.videoFileMetadataFormat = videoFile
133 ? this.getMetadataFormat(videoFile.metadata.format)
134 : undefined
135 this.videoFileMetadataVideoStream = videoFile
136 ? this.getMetadataStream(videoFile.metadata.streams, 'video')
137 : undefined
138 this.videoFileMetadataAudioStream = videoFile
139 ? this.getMetadataStream(videoFile.metadata.streams, 'audio')
140 : undefined
141 }
142
143 onSubtitleIdChange (subtitleId: string) {
144 this.subtitleLanguageId = subtitleId
145 }
146
147 hasFiles () {
148 return this.getVideoFiles().length !== 0
149 }
150
151 getVideoFile () {
152 const file = this.getVideoFiles()
153 .find(f => f.resolution.id === this.resolutionId)
154
155 if (!file) {
156 logger.error(`Could not find file with resolution ${this.resolutionId}`)
157 return undefined
158 }
159
160 return file
161 }
162
163 getVideoFileLink () {
164 const file = this.getVideoFile()
165 if (!file) return ''
166
167 const suffix = this.isConfidentialVideo()
168 ? '?videoFileToken=' + this.videoFileToken
169 : ''
170
171 switch (this.downloadType) {
172 case 'direct':
173 return file.fileDownloadUrl + suffix
174
175 case 'torrent':
176 return file.torrentDownloadUrl + suffix
177 }
178 }
179
180 hasCaptions () {
181 return this.getCaptions().length !== 0
182 }
183
184 getCaption () {
185 const caption = this.getCaptions()
186 .find(c => c.language.id === this.subtitleLanguageId)
187
188 if (!caption) {
189 logger.error(`Cannot find caption ${this.subtitleLanguageId}`)
190 return undefined
191 }
192
193 return caption
194 }
195
196 getCaptionLink () {
197 const caption = this.getCaption()
198 if (!caption) return ''
199
200 return window.location.origin + caption.captionPath
201 }
202
203 isConfidentialVideo () {
204 return this.video.privacy.id === VideoPrivacy.PRIVATE || this.video.privacy.id === VideoPrivacy.INTERNAL
205 }
206
207 switchToType (type: DownloadType) {
208 this.type = type
209 }
210
211 getFileMetadata () {
212 const file = this.getVideoFile()
213 if (!file) return undefined
214
215 return file.metadata
216 }
217
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`
226 })
227 }
228
229 // flattening format
230 const sanitizedFormat = Object.assign(format, format.tags)
231 delete sanitizedFormat.tags
232
233 return mapValues(
234 pick(sanitizedFormat, objectKeysTyped(keyToTranslateFunction)),
235 (val: string, key: keyof typeof keyToTranslateFunction) => keyToTranslateFunction[key](val)
236 )
237 }
238
239 private getMetadataStream (streams: any[], type: 'video' | 'audio') {
240 const stream = streams.find(s => s.codec_type === type)
241 if (!stream) return undefined
242
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`
249 })
250 }
251
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 })
258 })
259 } else {
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 })
263 })
264 }
265
266 return mapValues(
267 pick(stream, Object.keys(keyToTranslateFunction)),
268 (val: string, key: keyof typeof keyToTranslateFunction) => keyToTranslateFunction[key](val)
269 )
270 }
271
272 private hydrateMetadataFromMetadataUrl (file: VideoFile) {
273 const observable = this.videoService.getVideoFileMetadata(file.metadataUrl)
274 .pipe(tap(res => file.metadata = res))
275
276 return firstValueFrom(observable)
277 }
278 }