]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+videos/+video-edit/shared/video-edit.component.ts
Add latency setting support
[github/Chocobozzz/PeerTube.git] / client / src / app / +videos / +video-edit / shared / video-edit.component.ts
1 import { forkJoin } from 'rxjs'
2 import { map } from 'rxjs/operators'
3 import { SelectChannelItem, SelectOptionsItem } from 'src/types/select-options-item.model'
4 import { ChangeDetectorRef, Component, EventEmitter, Input, NgZone, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
5 import { AbstractControl, FormArray, FormControl, FormGroup, Validators } from '@angular/forms'
6 import { HooksService, PluginService, ServerService } from '@app/core'
7 import { removeElementFromArray } from '@app/helpers'
8 import { BuildFormValidator } from '@app/shared/form-validators'
9 import {
10 VIDEO_CATEGORY_VALIDATOR,
11 VIDEO_CHANNEL_VALIDATOR,
12 VIDEO_DESCRIPTION_VALIDATOR,
13 VIDEO_LANGUAGE_VALIDATOR,
14 VIDEO_LICENCE_VALIDATOR,
15 VIDEO_NAME_VALIDATOR,
16 VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
17 VIDEO_PRIVACY_VALIDATOR,
18 VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
19 VIDEO_SUPPORT_VALIDATOR,
20 VIDEO_TAGS_ARRAY_VALIDATOR
21 } from '@app/shared/form-validators/video-validators'
22 import { FormReactiveValidationMessages, FormValidatorService } from '@app/shared/shared-forms'
23 import { InstanceService } from '@app/shared/shared-instance'
24 import { VideoCaptionEdit, VideoCaptionWithPathEdit, VideoEdit, VideoService } from '@app/shared/shared-main'
25 import { PluginInfo } from '@root-helpers/plugins-manager'
26 import {
27 HTMLServerConfig,
28 LiveVideo,
29 LiveVideoLatencyMode,
30 RegisterClientFormFieldOptions,
31 RegisterClientVideoFieldOptions,
32 VideoConstant,
33 VideoDetails,
34 VideoPrivacy
35 } from '@shared/models'
36 import { I18nPrimengCalendarService } from './i18n-primeng-calendar.service'
37 import { VideoCaptionAddModalComponent } from './video-caption-add-modal.component'
38 import { VideoCaptionEditModalComponent } from './video-caption-edit-modal/video-caption-edit-modal.component'
39 import { VideoEditType } from './video-edit.type'
40
41 type VideoLanguages = VideoConstant<string> & { group?: string }
42 type PluginField = {
43 pluginInfo: PluginInfo
44 commonOptions: RegisterClientFormFieldOptions
45 videoFormOptions: RegisterClientVideoFieldOptions
46 }
47
48 @Component({
49 selector: 'my-video-edit',
50 styleUrls: [ './video-edit.component.scss' ],
51 templateUrl: './video-edit.component.html'
52 })
53 export class VideoEditComponent implements OnInit, OnDestroy {
54 @Input() form: FormGroup
55 @Input() formErrors: { [ id: string ]: string } = {}
56 @Input() validationMessages: FormReactiveValidationMessages = {}
57
58 @Input() videoToUpdate: VideoDetails
59
60 @Input() userVideoChannels: SelectChannelItem[] = []
61 @Input() forbidScheduledPublication = true
62
63 @Input() videoCaptions: VideoCaptionWithPathEdit[] = []
64
65 @Input() waitTranscodingEnabled = true
66 @Input() type: VideoEditType
67 @Input() liveVideo: LiveVideo
68
69 @ViewChild('videoCaptionAddModal', { static: true }) videoCaptionAddModal: VideoCaptionAddModalComponent
70 @ViewChild('videoCaptionEditModal', { static: true }) editCaptionModal: VideoCaptionEditModalComponent
71
72 @Output() formBuilt = new EventEmitter<void>()
73 @Output() pluginFieldsAdded = new EventEmitter<void>()
74
75 // So that it can be accessed in the template
76 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
77
78 videoPrivacies: VideoConstant<VideoPrivacy>[] = []
79 videoCategories: VideoConstant<number>[] = []
80 videoLicences: VideoConstant<number>[] = []
81 videoLanguages: VideoLanguages[] = []
82 latencyModes: SelectOptionsItem[] = [
83 {
84 id: LiveVideoLatencyMode.SMALL_LATENCY,
85 label: $localize`Small latency`,
86 description: $localize`Reduce latency to ~15s disabling P2P`
87 },
88 {
89 id: LiveVideoLatencyMode.DEFAULT,
90 label: $localize`Default`,
91 description: $localize`Average latency of 30s`
92 },
93 {
94 id: LiveVideoLatencyMode.HIGH_LATENCY,
95 label: $localize`High latency`,
96 description: $localize`Average latency of 60s increasing P2P ratio`
97 }
98 ]
99
100 pluginDataFormGroup: FormGroup
101
102 schedulePublicationEnabled = false
103
104 calendarLocale: any = {}
105 minScheduledDate = new Date()
106 myYearRange = '1880:' + (new Date()).getFullYear()
107
108 calendarTimezone: string
109 calendarDateFormat: string
110
111 serverConfig: HTMLServerConfig
112
113 pluginFields: PluginField[] = []
114
115 private schedulerInterval: any
116 private firstPatchDone = false
117 private initialVideoCaptions: string[] = []
118
119 constructor (
120 private formValidatorService: FormValidatorService,
121 private videoService: VideoService,
122 private serverService: ServerService,
123 private pluginService: PluginService,
124 private instanceService: InstanceService,
125 private i18nPrimengCalendarService: I18nPrimengCalendarService,
126 private ngZone: NgZone,
127 private hooks: HooksService,
128 private cd: ChangeDetectorRef
129 ) {
130 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
131 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
132 }
133
134 updateForm () {
135 const defaultValues: any = {
136 nsfw: 'false',
137 commentsEnabled: this.serverConfig.defaults.publish.commentsEnabled,
138 downloadEnabled: this.serverConfig.defaults.publish.downloadEnabled,
139 waitTranscoding: 'true',
140 licence: this.serverConfig.defaults.publish.licence,
141 tags: []
142 }
143 const obj: { [ id: string ]: BuildFormValidator } = {
144 name: VIDEO_NAME_VALIDATOR,
145 privacy: VIDEO_PRIVACY_VALIDATOR,
146 channelId: VIDEO_CHANNEL_VALIDATOR,
147 nsfw: null,
148 commentsEnabled: null,
149 downloadEnabled: null,
150 waitTranscoding: null,
151 category: VIDEO_CATEGORY_VALIDATOR,
152 licence: VIDEO_LICENCE_VALIDATOR,
153 language: VIDEO_LANGUAGE_VALIDATOR,
154 description: VIDEO_DESCRIPTION_VALIDATOR,
155 tags: VIDEO_TAGS_ARRAY_VALIDATOR,
156 previewfile: null,
157 support: VIDEO_SUPPORT_VALIDATOR,
158 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
159 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
160 liveStreamKey: null,
161 permanentLive: null,
162 latencyMode: null,
163 saveReplay: null
164 }
165
166 this.formValidatorService.updateFormGroup(
167 this.form,
168 this.formErrors,
169 this.validationMessages,
170 obj,
171 defaultValues
172 )
173
174 this.form.addControl('captions', new FormArray([
175 new FormGroup({
176 language: new FormControl(),
177 captionfile: new FormControl()
178 })
179 ]))
180
181 this.trackChannelChange()
182 this.trackPrivacyChange()
183 this.trackLivePermanentFieldChange()
184
185 this.formBuilt.emit()
186 }
187
188 ngOnInit () {
189 this.serverConfig = this.serverService.getHTMLConfig()
190
191 this.updateForm()
192
193 this.pluginService.ensurePluginsAreLoaded('video-edit')
194 .then(() => this.updatePluginFields())
195
196 this.serverService.getVideoCategories()
197 .subscribe(res => this.videoCategories = res)
198
199 this.serverService.getVideoLicences()
200 .subscribe(res => this.videoLicences = res)
201
202 forkJoin([
203 this.instanceService.getAbout(),
204 this.serverService.getVideoLanguages()
205 ]).pipe(map(([ about, languages ]) => ({ about, languages })))
206 .subscribe(res => {
207 this.videoLanguages = res.languages
208 .map(l => {
209 if (l.id === 'zxx') return { ...l, group: $localize`Other`, groupOrder: 1 }
210
211 return res.about.instance.languages.includes(l.id)
212 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
213 : { ...l, group: $localize`All languages`, groupOrder: 2 }
214 })
215 .sort((a, b) => a.groupOrder - b.groupOrder)
216 })
217
218 this.serverService.getVideoPrivacies()
219 .subscribe(privacies => {
220 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies).videoPrivacies
221
222 // Can't schedule publication if private privacy is not available (could be deleted by a plugin)
223 const hasPrivatePrivacy = this.videoPrivacies.some(p => p.id === VideoPrivacy.PRIVATE)
224 if (this.forbidScheduledPublication || !hasPrivatePrivacy) return
225
226 this.videoPrivacies.push({
227 id: this.SPECIAL_SCHEDULED_PRIVACY,
228 label: $localize`Scheduled`,
229 description: $localize`Hide the video until a specific date`
230 })
231 })
232
233 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
234
235 this.ngZone.runOutsideAngular(() => {
236 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
237 })
238
239 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
240 }
241
242 ngOnDestroy () {
243 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
244 }
245
246 getExistingCaptions () {
247 return this.videoCaptions
248 .filter(c => c.action !== 'REMOVE')
249 .map(c => c.language.id)
250 }
251
252 onCaptionEdited (caption: VideoCaptionEdit) {
253 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
254
255 // Replace existing caption?
256 if (existingCaption) {
257 Object.assign(existingCaption, caption)
258 } else {
259 this.videoCaptions.push(
260 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
261 )
262 }
263
264 this.sortVideoCaptions()
265 }
266
267 deleteCaption (caption: VideoCaptionEdit) {
268 // Caption recovers his former state
269 if (caption.action && this.initialVideoCaptions.includes(caption.language.id)) {
270 caption.action = undefined
271 return
272 }
273
274 // This caption is not on the server, just remove it from our array
275 if (caption.action === 'CREATE' || caption.action === 'UPDATE') {
276 removeElementFromArray(this.videoCaptions, caption)
277 return
278 }
279
280 caption.action = 'REMOVE' as 'REMOVE'
281 }
282
283 openAddCaptionModal () {
284 this.videoCaptionAddModal.show()
285 }
286
287 isSaveReplayEnabled () {
288 return this.serverConfig.live.allowReplay
289 }
290
291 isPermanentLiveEnabled () {
292 return this.form.value['permanentLive'] === true
293 }
294
295 isLatencyModeEnabled () {
296 return this.serverConfig.live.latencySetting.enabled
297 }
298
299 isPluginFieldHidden (pluginField: PluginField) {
300 if (typeof pluginField.commonOptions.hidden !== 'function') return false
301
302 return pluginField.commonOptions.hidden({
303 formValues: this.form.value,
304 videoToUpdate: this.videoToUpdate,
305 liveVideo: this.liveVideo
306 })
307 }
308
309 getPluginsFields (tab: 'main' | 'plugin-settings') {
310 return this.pluginFields.filter(p => {
311 const wanted = p.videoFormOptions.tab ?? 'plugin-settings'
312
313 return wanted === tab
314 })
315 }
316
317 private sortVideoCaptions () {
318 this.videoCaptions.sort((v1, v2) => {
319 if (v1.language.label < v2.language.label) return -1
320 if (v1.language.label === v2.language.label) return 0
321
322 return 1
323 })
324 }
325
326 private async updatePluginFields () {
327 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
328
329 if (this.pluginFields.length === 0) return
330
331 const pluginObj: { [ id: string ]: BuildFormValidator } = {}
332 const pluginValidationMessages: FormReactiveValidationMessages = {}
333 const pluginFormErrors: any = {}
334 const pluginDefaults: any = {}
335
336 for (const setting of this.pluginFields) {
337 await this.pluginService.translateSetting(setting.pluginInfo.plugin.npmName, setting.commonOptions)
338
339 const validator = async (control: AbstractControl) => {
340 if (!setting.commonOptions.error) return null
341
342 const error = await setting.commonOptions.error({ formValues: this.form.value, value: control.value })
343
344 return error?.error ? { [setting.commonOptions.name]: error.text } : null
345 }
346
347 const name = setting.commonOptions.name
348
349 pluginObj[name] = {
350 ASYNC_VALIDATORS: [ validator ],
351 VALIDATORS: [],
352 MESSAGES: {}
353 }
354
355 pluginDefaults[name] = setting.commonOptions.default
356 }
357
358 this.pluginDataFormGroup = new FormGroup({})
359 this.formValidatorService.updateFormGroup(
360 this.pluginDataFormGroup,
361 pluginFormErrors,
362 pluginValidationMessages,
363 pluginObj,
364 pluginDefaults
365 )
366
367 this.form.addControl('pluginData', this.pluginDataFormGroup)
368 this.formErrors['pluginData'] = pluginFormErrors
369 this.validationMessages['pluginData'] = pluginValidationMessages
370
371 this.cd.detectChanges()
372 this.pluginFieldsAdded.emit()
373
374 // Plugins may need other control values to calculate potential errors
375 this.form.valueChanges.subscribe(() => this.formValidatorService.updateTreeValidity(this.pluginDataFormGroup))
376 }
377
378 private trackPrivacyChange () {
379 // We will update the schedule input and the wait transcoding checkbox validators
380 this.form.controls['privacy']
381 .valueChanges
382 .pipe(map(res => parseInt(res.toString(), 10)))
383 .subscribe(
384 newPrivacyId => {
385
386 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
387
388 // Value changed
389 const scheduleControl = this.form.get('schedulePublicationAt')
390 const waitTranscodingControl = this.form.get('waitTranscoding')
391
392 if (this.schedulePublicationEnabled) {
393 scheduleControl.setValidators([ Validators.required ])
394
395 waitTranscodingControl.disable()
396 waitTranscodingControl.setValue(false)
397 } else {
398 scheduleControl.clearValidators()
399
400 waitTranscodingControl.enable()
401
402 // Do not update the control value on first patch (values come from the server)
403 if (this.firstPatchDone === true) {
404 waitTranscodingControl.setValue(true)
405 }
406 }
407
408 scheduleControl.updateValueAndValidity()
409 waitTranscodingControl.updateValueAndValidity()
410
411 this.firstPatchDone = true
412
413 }
414 )
415 }
416
417 private trackChannelChange () {
418 // We will update the "support" field depending on the channel
419 this.form.controls['channelId']
420 .valueChanges
421 .pipe(map(res => parseInt(res.toString(), 10)))
422 .subscribe(
423 newChannelId => {
424 const oldChannelId = parseInt(this.form.value['channelId'], 10)
425
426 // Not initialized yet
427 if (isNaN(newChannelId)) return
428 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
429 if (!newChannel) return
430
431 // Wait support field update
432 setTimeout(() => {
433 const currentSupport = this.form.value['support']
434
435 // First time we set the channel?
436 if (isNaN(oldChannelId)) {
437 // Fill support if it's empty
438 if (!currentSupport) this.updateSupportField(newChannel.support)
439
440 return
441 }
442
443 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
444 if (!newChannel || !oldChannel) {
445 console.error('Cannot find new or old channel.')
446 return
447 }
448
449 // If the current support text is not the same than the old channel, the user updated it.
450 // We don't want the user to lose his text, so stop here
451 if (currentSupport && currentSupport !== oldChannel.support) return
452
453 // Update the support text with our new channel
454 this.updateSupportField(newChannel.support)
455 })
456 }
457 )
458 }
459
460 private trackLivePermanentFieldChange () {
461 // We will update the "support" field depending on the channel
462 this.form.controls['permanentLive']
463 .valueChanges
464 .subscribe(
465 permanentLive => {
466 const saveReplayControl = this.form.controls['saveReplay']
467
468 if (permanentLive === true) {
469 saveReplayControl.setValue(false)
470 saveReplayControl.disable()
471 } else {
472 saveReplayControl.enable()
473 }
474 }
475 )
476 }
477
478 private updateSupportField (support: string) {
479 return this.form.patchValue({ support: support || '' })
480 }
481 }