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