]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+videos/+video-edit/shared/video-edit.component.ts
Handle input error in markdown textarea
[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
184 this.formBuilt.emit()
185 }
186
187 ngOnInit () {
188 this.serverConfig = this.serverService.getHTMLConfig()
189
190 this.updateForm()
191
192 this.pluginService.ensurePluginsAreLoaded('video-edit')
193 .then(() => this.updatePluginFields())
194
195 this.serverService.getVideoCategories()
196 .subscribe(res => this.videoCategories = res)
197
198 this.serverService.getVideoLicences()
199 .subscribe(res => this.videoLicences = res)
200
201 forkJoin([
202 this.instanceService.getAbout(),
203 this.serverService.getVideoLanguages()
204 ]).pipe(map(([ about, languages ]) => ({ about, languages })))
205 .subscribe(res => {
206 this.videoLanguages = res.languages
207 .map(l => {
208 if (l.id === 'zxx') return { ...l, group: $localize`Other`, groupOrder: 1 }
209
210 return res.about.instance.languages.includes(l.id)
211 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
212 : { ...l, group: $localize`All languages`, groupOrder: 2 }
213 })
214 .sort((a, b) => a.groupOrder - b.groupOrder)
215 })
216
217 this.serverService.getVideoPrivacies()
218 .subscribe(privacies => {
219 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies).videoPrivacies
220
221 // Can't schedule publication if private privacy is not available (could be deleted by a plugin)
222 const hasPrivatePrivacy = this.videoPrivacies.some(p => p.id === VideoPrivacy.PRIVATE)
223 if (this.forbidScheduledPublication || !hasPrivatePrivacy) return
224
225 this.videoPrivacies.push({
226 id: this.SPECIAL_SCHEDULED_PRIVACY,
227 label: $localize`Scheduled`,
228 description: $localize`Hide the video until a specific date`
229 })
230 })
231
232 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
233
234 this.ngZone.runOutsideAngular(() => {
235 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
236 })
237
238 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
239 }
240
241 ngOnDestroy () {
242 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
243 }
244
245 getExistingCaptions () {
246 return this.videoCaptions
247 .filter(c => c.action !== 'REMOVE')
248 .map(c => c.language.id)
249 }
250
251 onCaptionEdited (caption: VideoCaptionEdit) {
252 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
253
254 // Replace existing caption?
255 if (existingCaption) {
256 Object.assign(existingCaption, caption)
257 } else {
258 this.videoCaptions.push(
259 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
260 )
261 }
262
263 this.sortVideoCaptions()
264 }
265
266 deleteCaption (caption: VideoCaptionEdit) {
267 // Caption recovers his former state
268 if (caption.action && this.initialVideoCaptions.includes(caption.language.id)) {
269 caption.action = undefined
270 return
271 }
272
273 // This caption is not on the server, just remove it from our array
274 if (caption.action === 'CREATE' || caption.action === 'UPDATE') {
275 removeElementFromArray(this.videoCaptions, caption)
276 return
277 }
278
279 caption.action = 'REMOVE' as 'REMOVE'
280 }
281
282 openAddCaptionModal () {
283 this.videoCaptionAddModal.show()
284 }
285
286 isSaveReplayEnabled () {
287 return this.serverConfig.live.allowReplay
288 }
289
290 isPermanentLiveEnabled () {
291 return this.form.value['permanentLive'] === true
292 }
293
294 isLatencyModeEnabled () {
295 return this.serverConfig.live.latencySetting.enabled
296 }
297
298 isPluginFieldHidden (pluginField: PluginField) {
299 if (typeof pluginField.commonOptions.hidden !== 'function') return false
300
301 return pluginField.commonOptions.hidden({
302 formValues: this.form.value,
303 videoToUpdate: this.videoToUpdate,
304 liveVideo: this.liveVideo
305 })
306 }
307
308 getPluginsFields (tab: 'main' | 'plugin-settings') {
309 return this.pluginFields.filter(p => {
310 const wanted = p.videoFormOptions.tab ?? 'plugin-settings'
311
312 return wanted === tab
313 })
314 }
315
316 private sortVideoCaptions () {
317 this.videoCaptions.sort((v1, v2) => {
318 if (v1.language.label < v2.language.label) return -1
319 if (v1.language.label === v2.language.label) return 0
320
321 return 1
322 })
323 }
324
325 private async updatePluginFields () {
326 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
327
328 if (this.pluginFields.length === 0) return
329
330 const pluginObj: { [ id: string ]: BuildFormValidator } = {}
331 const pluginValidationMessages: FormReactiveValidationMessages = {}
332 const pluginFormErrors: any = {}
333 const pluginDefaults: any = {}
334
335 for (const setting of this.pluginFields) {
336 await this.pluginService.translateSetting(setting.pluginInfo.plugin.npmName, setting.commonOptions)
337
338 const validator = async (control: AbstractControl) => {
339 if (!setting.commonOptions.error) return null
340
341 const error = await setting.commonOptions.error({ formValues: this.form.value, value: control.value })
342
343 return error?.error ? { [setting.commonOptions.name]: error.text } : null
344 }
345
346 const name = setting.commonOptions.name
347
348 pluginObj[name] = {
349 ASYNC_VALIDATORS: [ validator ],
350 VALIDATORS: [],
351 MESSAGES: {}
352 }
353
354 pluginDefaults[name] = setting.commonOptions.default
355 }
356
357 this.pluginDataFormGroup = new FormGroup({})
358 this.formValidatorService.updateFormGroup(
359 this.pluginDataFormGroup,
360 pluginFormErrors,
361 pluginValidationMessages,
362 pluginObj,
363 pluginDefaults
364 )
365
366 this.form.addControl('pluginData', this.pluginDataFormGroup)
367 this.formErrors['pluginData'] = pluginFormErrors
368 this.validationMessages['pluginData'] = pluginValidationMessages
369
370 this.cd.detectChanges()
371 this.pluginFieldsAdded.emit()
372
373 // Plugins may need other control values to calculate potential errors
374 this.form.valueChanges.subscribe(() => this.formValidatorService.updateTreeValidity(this.pluginDataFormGroup))
375 }
376
377 private trackPrivacyChange () {
378 // We will update the schedule input and the wait transcoding checkbox validators
379 this.form.controls['privacy']
380 .valueChanges
381 .pipe(map(res => parseInt(res.toString(), 10)))
382 .subscribe(
383 newPrivacyId => {
384
385 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
386
387 // Value changed
388 const scheduleControl = this.form.get('schedulePublicationAt')
389 const waitTranscodingControl = this.form.get('waitTranscoding')
390
391 if (this.schedulePublicationEnabled) {
392 scheduleControl.setValidators([ Validators.required ])
393
394 waitTranscodingControl.disable()
395 waitTranscodingControl.setValue(false)
396 } else {
397 scheduleControl.clearValidators()
398
399 waitTranscodingControl.enable()
400
401 // Do not update the control value on first patch (values come from the server)
402 if (this.firstPatchDone === true) {
403 waitTranscodingControl.setValue(true)
404 }
405 }
406
407 scheduleControl.updateValueAndValidity()
408 waitTranscodingControl.updateValueAndValidity()
409
410 this.firstPatchDone = true
411
412 }
413 )
414 }
415
416 private trackChannelChange () {
417 // We will update the "support" field depending on the channel
418 this.form.controls['channelId']
419 .valueChanges
420 .pipe(map(res => parseInt(res.toString(), 10)))
421 .subscribe(
422 newChannelId => {
423 const oldChannelId = parseInt(this.form.value['channelId'], 10)
424
425 // Not initialized yet
426 if (isNaN(newChannelId)) return
427 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
428 if (!newChannel) return
429
430 // Wait support field update
431 setTimeout(() => {
432 const currentSupport = this.form.value['support']
433
434 // First time we set the channel?
435 if (isNaN(oldChannelId)) {
436 // Fill support if it's empty
437 if (!currentSupport) this.updateSupportField(newChannel.support)
438
439 return
440 }
441
442 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
443 if (!newChannel || !oldChannel) {
444 console.error('Cannot find new or old channel.')
445 return
446 }
447
448 // If the current support text is not the same than the old channel, the user updated it.
449 // We don't want the user to lose his text, so stop here
450 if (currentSupport && currentSupport !== oldChannel.support) return
451
452 // Update the support text with our new channel
453 this.updateSupportField(newChannel.support)
454 })
455 }
456 )
457 }
458
459 private updateSupportField (support: string) {
460 return this.form.patchValue({ support: support || '' })
461 }
462 }